.net资料如何高效应用于长尾关键词优化策略?
- 内容介绍
- 文章标签
- 相关推荐
本文共计4244个文字,预计阅读时间需要17分钟。
EFSqlBulkCopy 批量入库,使用 StringConnection 连接字符串:
csharpstring connection=ConfigurationManager.ConnectionStrings[DbConn].ConnectionString;using (System.Data.SqlClient.SqlConnection sqlConnection=new System.Data.SqlClient.SqlConnection(connection)){ using (System.Data.SqlClient.SqlBulkCopy bulkCopy=new System.Data.SqlClient.SqlBulkCopy(sqlConnection)) { // 设置源和目标 bulkCopy.DestinationTableName=TargetTable; // 执行批量插入 bulkCopy.WriteToServer(YourDataTable); }}
EFSqlBulkCopy批量入库
stringconnection=ConfigurationManager.ConnectionStrings["DbConn"].ConnectionString;
using System.Data.SqlClient;
using System.Data;
using System.ComponentModel;
publicstaticvoidBulkInsert<T>(stringconnection,stringtableName,IList<T>list)
{
using(varbulkCopy=newSqlBulkCopy(connection))
{
bulkCopy.BatchSize=list.Count;
bulkCopy.DestinationTableName=tableName;
vartable=newDataTable();
varprops=TypeDescriptor.GetProperties(typeof(T))
.Cast<PropertyDescriptor>()
.Where(propertyInfo=>propertyInfo.PropertyType.Namespace.Equals("System"))
.ToArray();
foreach(varpropertyInfoinprops)
{
bulkCopy.ColumnMappings.Add(propertyInfo.Name,propertyInfo.Name);
table.Columns.Add(propertyInfo.Name,Nullable.GetUnderlyingType(propertyInfo.PropertyType)??propertyInfo.PropertyType);
}
varvalues=newobject[props.Length];
foreach(variteminlist)
{
for(vari=0;i<values.Length;i++)
{
values[i]=props[i].GetValue(item);
}
table.Rows.Add(values);
}
bulkCopy.WriteToServer(table);
}
}
varimports=newList<sendapientity>();
foreach(JTokenphoneinphones)
{
SendEntitysendphone=JsonConvert.DeserializeObject<SendEntity>(phone.ToString());
stringtphone=sendphone.phone;intsendid=Convert.ToInt32(sendphone.id);
sendapientitys=newsendapientity();
s.UserId=userid;
s.PartnersCode=partnerscode;
s.SendId=sendid;
s.Phone=tphone;
s.Message=msg;
s.SentTime=sendtime;
s.CreateTime=DateTime.Now;
s.BatchId=batchid;
s.Count=count;
imports.Add(s);
}
using(SMMMContextdb=newSMMMContext())
{
BulkInsert(db.Database.Connection.ConnectionString,"Send_Api",imports);
}
publicclasssendapientity
{
publicintUserId{get;set;}
publicstringPartnersCode{get;set;}
publicintSendId{get;set;}
publicstringPhone{get;set;}
publicstringMessage{get;set;}
publicstringSentTime{get;set;}
publicDateTimeCreateTime{get;set;}
publiclongBatchId{get;set;}
publicintCount{get;set;}
}
在JavaScript中推荐的做法是用encodeURI对URI的网址部分编码,用encodeURIComponent对URI中传递的参数进行编码。
在C#中推荐的做法是用Uri.EscapeUriString对URI的网址部分编码,用Uri.EscapeDataString对URI中传递的参数进行编码。
publicstaticintToInt32(doublevalue)
{
if(value>=0.0)
{
if(value<2147483647.5)
{
intnum=(int)value;
doublenum2=value-num;
if((num2>0.5)||((num2==0.5)&&((num&1)!=0)))
{
num++;
}
returnnum;
}
}
elseif(value>=-2147483648.5)
{
intnum3=(int)value;
doublenum4=value-num3;
if((num4<-0.5)||((num4==-0.5)&&((num3&1)!=0)))
{
num3--;
}
returnnum3;
}
thrownewOverflowException(Environment.GetResourceString("Overflow_Int32"));
}
publicenumCommentType{不推荐=0,一般=3,良=4,优=5}
///<summary>
///绑定评分类型
///</summary>
///<paramname="RBL"></param>
protectedstaticvoidBindRadioButtonList(RadioButtonListRBL)
{
RBL.Items.Clear();
Typetyp=typeof(CommentType);
foreach(intiinEnum.GetValues(typ))
{
RBL.Items.Add(newListItem(Enum.GetName(typ,i),Enum.Format(typ,Enum.Parse(typ,Enum.GetName(typ,i)),"d")));
RBL.SelectedValue=i.ToString();
}
}
///<summary>
///获取类型名称
///</summary>
///<paramname="typeid"></param>
///<returns></returns>
protectedstaticstringBindRating(stringtypeid)
{
stringtypename="";
Typetyp=typeof(CommentType);
foreach(intiinEnum.GetValues(typ))
{
if(typeid==Enum.Format(typ,Enum.Parse(typ,Enum.GetName(typ,i)),"d"))
{
typename=Enum.GetName(typ,i);
}
}
returntypename;
}
//.NET正确获取当前URL
HttpContext.Current.Request.Url.ToString()不可靠
HttpContext.Current.Request.Url.PathAndQuery正确
///newList<int>(ht.Keys),用到了List的构造拷贝函数
///在遍历数据结构的时候,是不可以修改原数据结构的。不然就会抛出错误。
foreach(stringkeyinnewList<string>(_IpAdresses.Keys))
{
_IpAdresses[key]--;
if(_IpAdresses[key]==0)
_IpAdresses.Remove(key);
}
c# 四舍五入 保留几位小数点
protectedstringgetProductPrice(intid)
{
CustomerProInfocp=ahlan.getCustomerProInfoByID(id);
doublex=double.Parse((cp.Product.sprice*cp.proValue/10).ToString());//两个double相乘结果是double?,所以要强制在转换一次
returnChinaRound(x,2).ToString();
}
//value你要转换的double数据,decimals要保留的小数点
doubleChinaRound(doublevalue,intdecimals)
{
if(value<0)
{
returnMath.Round(value+5/Math.Pow(10,decimals+1),decimals,MidpointRounding.AwayFromZero);
}
else
{
returnMath.Round(value,decimals,MidpointRounding.AwayFromZero);
}
}
//判断用户是手机还是pc访问
publicclassIsPhoneAttribute:ActionFilterAttribute
{
publicoverridevoidOnActionExecuting(ActionExecutingContextfilterContext)
{
stringu=filterContext.HttpContext.Request.ServerVariables["HTTP_USER_AGENT"];
Regexb=newRegex(@"android.+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge|maemo|midp|mmp|netfront|operam(ob|in)i|palm(os)?|phone|p(ixi|re)\/|plucker|pocket|psp|symbian|treo|up\.(browser|link)|vodafone|wap|windows(ce|phone)|xda|xiino",RegexOptions.IgnoreCase|RegexOptions.Multiline);
Regexv=newRegex(@"1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|awa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r|s)|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp(i|ip)|hs\-c|ht(c(\-||_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac(|\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt(|\/)|klon|kpt|kwc\-|kyo(c|k)|le(no|xi)|lg(g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(di|rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-||o|v)|zz)|mt(50|p1|v)|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v)|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-|)|webc|whit|wi(g|nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-",RegexOptions.IgnoreCase|RegexOptions.Multiline);
if(!(b.IsMatch(u)||v.IsMatch(u.Substring(0,4))))
{
filterContext.Controller.ViewData["ErrorMessage"]="对不起,请用手机访问!";
filterContext.Result=newViewResult()
{
ViewName="ErrorInfo",
ViewData=filterContext.Controller.ViewData,
};
}
}
}
发送短信接口
publicstaticboolSendMobileMsg(stringmsgContent,List<string>destListPhones)
{
try
{
boolresult=false;
stringstrPhones=string.Join(";",destListPhones.ToArray());
strPhones+=";";
varencoding=System.Text.Encoding.GetEncoding("GB2312");
stringpostData=string.Format("uid=用户名&pwd=密码&mobile={0};&msg={1}&dtime=",strPhones,msgContent);
byte[]data=encoding.GetBytes(postData);
//定义WebRequest
HttpWebRequestmyRequest=
(HttpWebRequest)WebRequest.Create("www.smsadmin.cn/smsmarketing/wwwroot/api/post_send/");
myRequest.Method="POST";
myRequest.ContentType="application/x-www-form-urlencoded";
myRequest.ContentLength=data.Length;
StreamnewStream=myRequest.GetRequestStream();
//发送数据
newStream.Write(data,0,data.Length);
newStream.Close();
//得到Response
HttpWebResponsemyResponse=(HttpWebResponse)myRequest.GetResponse();
StreamReaderreader=newStreamReader(myResponse.GetResponseStream(),Encoding.Default);
stringcontent=reader.ReadToEnd();
if(content.Substring(0,1)=="0")
result=true;
else
{
if(content.Substring(0,1)=="2")//余额不足
{
//"手机短信余额不足";
//TODO
}
else
{
//短信发送失败的其他原因,请参看官方API
}
result=false;
}
returnresult;
}
catch
{
returnfalse;
}
}
很“干净”的调用,没有WebService也没有COM。
唯一要注意的就是编码用GB2312否则您收到短信的中文部分都是乱码,另外第10行的用户名和密码被硬编码了,应写在配置文件内。
使用正则替换文章屏蔽词
privatestaticreadonlyRegexreg_b=newRegex(@"\B",RegexOptions.Compiled);
privatestaticreadonlyRegexreg_en=newRegex(@"[a-zA-Z]+",RegexOptions.Compiled);
privatestaticreadonlyRegexreg_num=newRegex(@"^[\-\.\s\d]+$",RegexOptions.Compiled);
privatestaticRegexreg_word=null;//组合所有屏蔽词的正则
privatestaticRegexGetRegex()
{
if(reg_word==null)
{
reg_word=newRegex(GetPattern(),RegexOptions.Compiled|RegexOptions.IgnoreCase);
}
returnreg_word;
}
///<summary>
///检查输入内容是否包含脏词(包含返回true)
///</summary>
publicstaticboolHasBlockWords(stringraw)
{
returnGetRegex().Match(raw).Success;
}
///<summary>
///脏词替换成*号
///</summary>
publicstaticstringWordsFilter(stringraw)
{
returnGetRegex().Replace(raw,"***");
}
///<summary>
///获取内容中含有的脏词
///</summary>
publicstaticIEnumerable<string>GetBlockWords(stringraw)
{
foreach(Matchmatinreg_word.Matches(raw))
{
yieldreturn(mat.Value);
}
}
privatestaticstringGetPattern()
{
StringBuilderpatt=newStringBuilder();
strings;
foreach(stringwordinGetBlockWords())
{
if(word.Length==0)continue;
if(word.Length==1)
{
patt.AppendFormat("|({0})",word);
}
elseif(reg_num.IsMatch(word))
{
patt.AppendFormat("|({0})",word);
}
elseif(reg_en.IsMatch(word))
{
s=reg_b.Replace(word,@"(?:[^a-zA-Z]{0,3})");
patt.AppendFormat("|({0})",s);
}
else
{
s=reg_b.Replace(word,@"(?:[^\u4e00-\u9fa5]{0,3})");
patt.AppendFormat("|({0})",s);
}
}
if(patt.Length>0)
{
patt.Remove(0,1);
}
returnpatt.ToString();
}
///<summary>
///获取所有脏词
///</summary>
publicstaticstring[]GetBlockWords()
{
returnnewstring[]{"国民党","fuck","110"};//这里应该从数据库获取
}
这个程序可替换以下内容:
国民党
国-民-党
国o民o党
fuck
f.u.c.k
110(110的变形写法不被替换)
//intdouble转换
intgoodper;
intbadper;
intgoodposts=Convert.ToInt32(dr["goodpost"]);
intbadposts=Convert.ToInt32(dr["badpost"]);
if(goodposts+badposts==0)
{
goodper=badper=0;
}
else
{
intalls=goodposts+badposts;
goodper=Convert.ToInt32((double)goodposts/alls*100);
badper=100-goodper;
}
如:
Convert.ToInt32(4/5*100)=0
Convert.ToInt32(4.0/5*100)=80
//中英文字符串截取方法
publicstaticstringIntercept(stringinput,intp)
{
Encodingencode=Encoding.GetEncoding("gb2312");
byte[]byteArr=encode.GetBytes(input);
if(byteArr.Length<=p)returninput;
intm=0,n=0;
foreach(bytebinbyteArr)
{
if(n>=p)break;
if(b>127)m++;//重要一步:对前p个字节中的值大于127的字符进行统计
n++;
}
if(m%2!=0)n=p+1;//如果非偶:则说明末尾为双字节字符,截取位数加1
returnencode.GetString(byteArr,0,n);
}
Console.WriteLine(Intercept("ABC中国人",7));
Console.WriteLine(Intercept("ABCD中国人",7));
Console.WriteLine(Intercept("ABC中D国人",7));
/*
测试代码的结果:
ABC中国
ABCD中国
ABC中D国
*/
//kigg发表于某天某时某分前
publicstaticstringAgo(thisDateTimetarget)
{
StringBuilderresult=newStringBuilder();
TimeSpandiff=(DateTime.Now-target.ToLocalTime());
if(diff.Days>0)
{
result.AppendFormat("{0}days",diff.Days);
}
if(diff.Hours>0)
{
if(result.Length>0)
{
result.Append(",");
}
result.AppendFormat("{0}hours",diff.Hours);
}
if(diff.Minutes>0)
{
if(result.Length>0)
{
result.Append(",");
}
result.AppendFormat("{0}minutes",diff.Minutes);
}
if(result.Length==0)
{
result.Append("fewmoments");
}
returnresult.ToString();
}
}
<%#GetOutTime(Eval("发布时间"))%>
///<summary>
///
///</summary>
///<paramname="dtime">发布时间</param>
///<returns></returns>
publicstaticstringGetOutTime(DateTimedtime)
{
DateTimedt=DateTime.Now;
TimeSpants=((TimeSpan)(dt-dtime));
intdays=ts.Days;
inthours=ts.Hours;
intminutes=ts.Minutes;
intmilliseconds=ts.Milliseconds;
if(days>0)returnstring.Format("发布于{0}天前",days);
if(hours>0)returnstring.Format("发布于{0}小时前",hours);
if(minutes>0)returnstring.Format("发布于{0}分钟前",minutes);
returnstring.Format("发布于{0}秒前",milliseconds);
}
publicstaticstringToPrettyDate(thisDateTime date)
{
var timeSince=DateTime.Now.Subtract(date);
if(timeSince.TotalMilliseconds<1)return"not yet";
if(timeSince.TotalMinutes<1)return"just now";
if(timeSince.TotalMinutes<2)return"1 minute ago";
if(timeSince.TotalMinutes<60)returnstring.Format("{0} minutes ago", timeSince.Minutes);
if(timeSince.TotalMinutes<120)return"1 hour ago";
if(timeSince.TotalHours<24)returnstring.Format("{0} hours ago", timeSince.Hours);
if(timeSince.TotalDays==1)return"yesterday";
if(timeSince.TotalDays<7)returnstring.Format("{0} day(s) ago", timeSince.Days);
if(timeSince.TotalDays<14)return"last week";
if(timeSince.TotalDays<21)return"2 weeks ago";
if(timeSince.TotalDays<28)return"3 weeks ago";
if(timeSince.TotalDays<60)return"last month";
if(timeSince.TotalDays<365)returnstring.Format("{0} months ago", Math.Round(timeSince.TotalDays/30));
if(timeSince.TotalDays<730)return"last year";
returnstring.Format("{0} years ago", Math.Round(timeSince.TotalDays/365));
}
DateTimedt=DateTime.Now;
Gengerateg=newGengerate();
g.GengerateHtml();
DateTimedt2=DateTime.Now;
TimeSpants=dt2.Subtract(dt);
stringstrTs=ts.TotalSeconds.ToString();
ltGengerate.Text="生成成功,生成用时"+strTs+"秒!";
//ddl点击赋值:
if(DropDownList1.selectedindex>-1)
{
DropDownList1.Items[DropDownList1.SelectedIndex].Text=TextBox1.Text;
}
//设置ddl的enabled属性:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="id"
OnRowDataBound="GridView1_RowDataBound" >
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow) //一定要
{
DropDownList ddl = (DropDownList)e.Row.FindControl("DropDownList1");
if (ddl != null)
{
if (ddl.SelectedValue == "1")
{
ddl.Enabled = false;
}
}
}
}
string strPath = Server.MapPath("~/roomindex");
/// <summary>
/// 用递归方法删除文件夹目录及文件
/// </summary>
/// <param name="dir">带文件夹名的路径</param>
public void DeleteFolder(string dir)
{
if (Directory.Exists(dir)) //如果存在这个文件夹删除之
{
foreach (string d in Directory.GetFileSystemEntries(dir))
{
if (File.Exists(d))
File.Delete(d); //直接删除其中的文件
else
DeleteFolder(d); //递归删除子文件夹
}
Directory.Delete(dir, true); //删除已空文件夹
}
}
确保您具有足够的权限 对路径 的访问被拒绝
删除权限设置:
在web.config中的<system.web>下加入<identity impersonate="true"/>
//根据用户选择的值设置Cookie的保存时间
if(this.RadioButtonList1.SelectedValue.ToString()=="1")//一天
{
this.Response.Cookies["UserName"].Expires=DateTime.Now.AddDays(1);
this.Response.Cookies["Password"].Expires=DateTime.Now.AddDays(1);
}
if(RadioButtonList1.SelectedValue.ToString()=="2")//一个月
{
this.Response.Cookies["UserName"].Expires=DateTime.Now.AddMonths(1);
this.Response.Cookies["Password"].Expires=DateTime.Now.AddMonths(1);
}
if(RadioButtonList1.SelectedValue.ToString()=="3")//半年
{
this.Response.Cookies["UserName"].Expires=DateTime.Now.AddYears(1/2);
this.Response.Cookies["Password"].Expires=DateTime.Now.AddYears(1/2);
}
if(RadioButtonList1.SelectedValue.ToString()=="4")//一年
{
this.Response.Cookies["UserName"].Expires=DateTime.Now.AddYears(1);
this.Response.Cookies["Password"].Expires=DateTime.Now.AddYears(1);
}
//将用户输入的用户名和密码保存到Cookie中
this.Response.Cookies["UserName"].Value=this.tname.Text;
this.Response.Cookies["Password"].Value=this.tpass.Text;
//跳转到getcookie.aspx页面中显示Cookie中的值
Response.Write("用户登录成功!并将用户登录的用户名和密码保存到Cookie中。");
}
else
{
Response.Redirect("Login.aspx");
}
}
//Attribute:
Response.Write("浏览器的信息为:<br>");
Response.Write("(1)浏览器="+Request.Browser.Browser+"<br>");
Response.Write("(2)型态="+Request.Browser.Type+"<br>");
Response.Write("(3)名称="+Request.Browser.Browser+"<br>");
Response.Write("(4)版本="+Request.Browser.Version+"<br>");
Response.Write("(5)使用平台="+Request.Browser.Platform+"<br>");
Response.Write("(6)是否为测试版="+Request.Browser.Beta+"<br>");
Response.Write("(7)是否为位的环境="+Request.Browser.Win16+"<br>");
Response.Write("(8)是否为位的环境="+Request.Browser.Win32+"<br>");
Response.Write("(9)是否支持框架(Frame)="+Request.Browser.Frames+"<br>");
Response.Write("(10)是否支持表格(Table)="+Request.Browser.Tables+"<br>");
Response.Write("(11)是否支持Cookies="+Request.Browser.Cookies+"<br>");
Response.Write("(12)是否支持ActiveXControls="+Request.Browser.ActiveXControls+"<br>");
stringbb=System.Environment.CurrentDirectory.ToString();
Response.Write(bb);
stringa=Request.Url.ToString();
stringb=Request.Path.ToString();
stringc=Request.PhysicalPath.ToString();
Response.Write("URL地址:"+a+"<br>虚拟路径:"+b+"<br>物理路径:"+c);
stringHostName=Server.MachineName.ToString();
Response.Write("电脑的名称为:"+HostName)
stringpath=Server.MapPath("~").ToString();
Response.Write("物理路径为:"+path);
//结果:
//物理路径为:C:\DocumentsandSettings\itd0300166.PLSH166\桌面\曾祥展\ASP.NET2.0+SQLServer2005全程指南\Study_NET\chap05\Server
stringEncode=Server.HtmlDecode("<b>HTML代码中的内容</b>");
stringDecode=Server.HtmlEncode("<b>HTML代码中的内容</b>");
Response.Write(Encode+"<br>"+Decode);
结果:
HTML代码中的内容
<b>HTML代码中的内容</b>
javascript:void(0)
/
////gridview导出excel
publicoverridevoidVerifyRenderingInServerForm(Controlcontrol)
{
//ConfirmsthatanHtmlFormcontrolisrenderedfor
}
protectedvoidButton3_Click(objectsender,EventArgse)
{
Response.Clear();
Response.Buffer=false;
Response.Charset="GB2312";
Response.AppendHeader("Content-Disposition","attachment;filename=score.xls");
Response.ContentEncoding=System.Text.Encoding.GetEncoding("GB2312");
Response.ContentType="application/ms-excel";
Response.Write("<metawww.558idc.com/ne.html 复制请保留原URL】
本文共计4244个文字,预计阅读时间需要17分钟。
EFSqlBulkCopy 批量入库,使用 StringConnection 连接字符串:
csharpstring connection=ConfigurationManager.ConnectionStrings[DbConn].ConnectionString;using (System.Data.SqlClient.SqlConnection sqlConnection=new System.Data.SqlClient.SqlConnection(connection)){ using (System.Data.SqlClient.SqlBulkCopy bulkCopy=new System.Data.SqlClient.SqlBulkCopy(sqlConnection)) { // 设置源和目标 bulkCopy.DestinationTableName=TargetTable; // 执行批量插入 bulkCopy.WriteToServer(YourDataTable); }}
EFSqlBulkCopy批量入库
stringconnection=ConfigurationManager.ConnectionStrings["DbConn"].ConnectionString;
using System.Data.SqlClient;
using System.Data;
using System.ComponentModel;
publicstaticvoidBulkInsert<T>(stringconnection,stringtableName,IList<T>list)
{
using(varbulkCopy=newSqlBulkCopy(connection))
{
bulkCopy.BatchSize=list.Count;
bulkCopy.DestinationTableName=tableName;
vartable=newDataTable();
varprops=TypeDescriptor.GetProperties(typeof(T))
.Cast<PropertyDescriptor>()
.Where(propertyInfo=>propertyInfo.PropertyType.Namespace.Equals("System"))
.ToArray();
foreach(varpropertyInfoinprops)
{
bulkCopy.ColumnMappings.Add(propertyInfo.Name,propertyInfo.Name);
table.Columns.Add(propertyInfo.Name,Nullable.GetUnderlyingType(propertyInfo.PropertyType)??propertyInfo.PropertyType);
}
varvalues=newobject[props.Length];
foreach(variteminlist)
{
for(vari=0;i<values.Length;i++)
{
values[i]=props[i].GetValue(item);
}
table.Rows.Add(values);
}
bulkCopy.WriteToServer(table);
}
}
varimports=newList<sendapientity>();
foreach(JTokenphoneinphones)
{
SendEntitysendphone=JsonConvert.DeserializeObject<SendEntity>(phone.ToString());
stringtphone=sendphone.phone;intsendid=Convert.ToInt32(sendphone.id);
sendapientitys=newsendapientity();
s.UserId=userid;
s.PartnersCode=partnerscode;
s.SendId=sendid;
s.Phone=tphone;
s.Message=msg;
s.SentTime=sendtime;
s.CreateTime=DateTime.Now;
s.BatchId=batchid;
s.Count=count;
imports.Add(s);
}
using(SMMMContextdb=newSMMMContext())
{
BulkInsert(db.Database.Connection.ConnectionString,"Send_Api",imports);
}
publicclasssendapientity
{
publicintUserId{get;set;}
publicstringPartnersCode{get;set;}
publicintSendId{get;set;}
publicstringPhone{get;set;}
publicstringMessage{get;set;}
publicstringSentTime{get;set;}
publicDateTimeCreateTime{get;set;}
publiclongBatchId{get;set;}
publicintCount{get;set;}
}
在JavaScript中推荐的做法是用encodeURI对URI的网址部分编码,用encodeURIComponent对URI中传递的参数进行编码。
在C#中推荐的做法是用Uri.EscapeUriString对URI的网址部分编码,用Uri.EscapeDataString对URI中传递的参数进行编码。
publicstaticintToInt32(doublevalue)
{
if(value>=0.0)
{
if(value<2147483647.5)
{
intnum=(int)value;
doublenum2=value-num;
if((num2>0.5)||((num2==0.5)&&((num&1)!=0)))
{
num++;
}
returnnum;
}
}
elseif(value>=-2147483648.5)
{
intnum3=(int)value;
doublenum4=value-num3;
if((num4<-0.5)||((num4==-0.5)&&((num3&1)!=0)))
{
num3--;
}
returnnum3;
}
thrownewOverflowException(Environment.GetResourceString("Overflow_Int32"));
}
publicenumCommentType{不推荐=0,一般=3,良=4,优=5}
///<summary>
///绑定评分类型
///</summary>
///<paramname="RBL"></param>
protectedstaticvoidBindRadioButtonList(RadioButtonListRBL)
{
RBL.Items.Clear();
Typetyp=typeof(CommentType);
foreach(intiinEnum.GetValues(typ))
{
RBL.Items.Add(newListItem(Enum.GetName(typ,i),Enum.Format(typ,Enum.Parse(typ,Enum.GetName(typ,i)),"d")));
RBL.SelectedValue=i.ToString();
}
}
///<summary>
///获取类型名称
///</summary>
///<paramname="typeid"></param>
///<returns></returns>
protectedstaticstringBindRating(stringtypeid)
{
stringtypename="";
Typetyp=typeof(CommentType);
foreach(intiinEnum.GetValues(typ))
{
if(typeid==Enum.Format(typ,Enum.Parse(typ,Enum.GetName(typ,i)),"d"))
{
typename=Enum.GetName(typ,i);
}
}
returntypename;
}
//.NET正确获取当前URL
HttpContext.Current.Request.Url.ToString()不可靠
HttpContext.Current.Request.Url.PathAndQuery正确
///newList<int>(ht.Keys),用到了List的构造拷贝函数
///在遍历数据结构的时候,是不可以修改原数据结构的。不然就会抛出错误。
foreach(stringkeyinnewList<string>(_IpAdresses.Keys))
{
_IpAdresses[key]--;
if(_IpAdresses[key]==0)
_IpAdresses.Remove(key);
}
c# 四舍五入 保留几位小数点
protectedstringgetProductPrice(intid)
{
CustomerProInfocp=ahlan.getCustomerProInfoByID(id);
doublex=double.Parse((cp.Product.sprice*cp.proValue/10).ToString());//两个double相乘结果是double?,所以要强制在转换一次
returnChinaRound(x,2).ToString();
}
//value你要转换的double数据,decimals要保留的小数点
doubleChinaRound(doublevalue,intdecimals)
{
if(value<0)
{
returnMath.Round(value+5/Math.Pow(10,decimals+1),decimals,MidpointRounding.AwayFromZero);
}
else
{
returnMath.Round(value,decimals,MidpointRounding.AwayFromZero);
}
}
//判断用户是手机还是pc访问
publicclassIsPhoneAttribute:ActionFilterAttribute
{
publicoverridevoidOnActionExecuting(ActionExecutingContextfilterContext)
{
stringu=filterContext.HttpContext.Request.ServerVariables["HTTP_USER_AGENT"];
Regexb=newRegex(@"android.+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge|maemo|midp|mmp|netfront|operam(ob|in)i|palm(os)?|phone|p(ixi|re)\/|plucker|pocket|psp|symbian|treo|up\.(browser|link)|vodafone|wap|windows(ce|phone)|xda|xiino",RegexOptions.IgnoreCase|RegexOptions.Multiline);
Regexv=newRegex(@"1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|awa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r|s)|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp(i|ip)|hs\-c|ht(c(\-||_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac(|\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt(|\/)|klon|kpt|kwc\-|kyo(c|k)|le(no|xi)|lg(g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(di|rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-||o|v)|zz)|mt(50|p1|v)|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v)|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-|)|webc|whit|wi(g|nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-",RegexOptions.IgnoreCase|RegexOptions.Multiline);
if(!(b.IsMatch(u)||v.IsMatch(u.Substring(0,4))))
{
filterContext.Controller.ViewData["ErrorMessage"]="对不起,请用手机访问!";
filterContext.Result=newViewResult()
{
ViewName="ErrorInfo",
ViewData=filterContext.Controller.ViewData,
};
}
}
}
发送短信接口
publicstaticboolSendMobileMsg(stringmsgContent,List<string>destListPhones)
{
try
{
boolresult=false;
stringstrPhones=string.Join(";",destListPhones.ToArray());
strPhones+=";";
varencoding=System.Text.Encoding.GetEncoding("GB2312");
stringpostData=string.Format("uid=用户名&pwd=密码&mobile={0};&msg={1}&dtime=",strPhones,msgContent);
byte[]data=encoding.GetBytes(postData);
//定义WebRequest
HttpWebRequestmyRequest=
(HttpWebRequest)WebRequest.Create("www.smsadmin.cn/smsmarketing/wwwroot/api/post_send/");
myRequest.Method="POST";
myRequest.ContentType="application/x-www-form-urlencoded";
myRequest.ContentLength=data.Length;
StreamnewStream=myRequest.GetRequestStream();
//发送数据
newStream.Write(data,0,data.Length);
newStream.Close();
//得到Response
HttpWebResponsemyResponse=(HttpWebResponse)myRequest.GetResponse();
StreamReaderreader=newStreamReader(myResponse.GetResponseStream(),Encoding.Default);
stringcontent=reader.ReadToEnd();
if(content.Substring(0,1)=="0")
result=true;
else
{
if(content.Substring(0,1)=="2")//余额不足
{
//"手机短信余额不足";
//TODO
}
else
{
//短信发送失败的其他原因,请参看官方API
}
result=false;
}
returnresult;
}
catch
{
returnfalse;
}
}
很“干净”的调用,没有WebService也没有COM。
唯一要注意的就是编码用GB2312否则您收到短信的中文部分都是乱码,另外第10行的用户名和密码被硬编码了,应写在配置文件内。
使用正则替换文章屏蔽词
privatestaticreadonlyRegexreg_b=newRegex(@"\B",RegexOptions.Compiled);
privatestaticreadonlyRegexreg_en=newRegex(@"[a-zA-Z]+",RegexOptions.Compiled);
privatestaticreadonlyRegexreg_num=newRegex(@"^[\-\.\s\d]+$",RegexOptions.Compiled);
privatestaticRegexreg_word=null;//组合所有屏蔽词的正则
privatestaticRegexGetRegex()
{
if(reg_word==null)
{
reg_word=newRegex(GetPattern(),RegexOptions.Compiled|RegexOptions.IgnoreCase);
}
returnreg_word;
}
///<summary>
///检查输入内容是否包含脏词(包含返回true)
///</summary>
publicstaticboolHasBlockWords(stringraw)
{
returnGetRegex().Match(raw).Success;
}
///<summary>
///脏词替换成*号
///</summary>
publicstaticstringWordsFilter(stringraw)
{
returnGetRegex().Replace(raw,"***");
}
///<summary>
///获取内容中含有的脏词
///</summary>
publicstaticIEnumerable<string>GetBlockWords(stringraw)
{
foreach(Matchmatinreg_word.Matches(raw))
{
yieldreturn(mat.Value);
}
}
privatestaticstringGetPattern()
{
StringBuilderpatt=newStringBuilder();
strings;
foreach(stringwordinGetBlockWords())
{
if(word.Length==0)continue;
if(word.Length==1)
{
patt.AppendFormat("|({0})",word);
}
elseif(reg_num.IsMatch(word))
{
patt.AppendFormat("|({0})",word);
}
elseif(reg_en.IsMatch(word))
{
s=reg_b.Replace(word,@"(?:[^a-zA-Z]{0,3})");
patt.AppendFormat("|({0})",s);
}
else
{
s=reg_b.Replace(word,@"(?:[^\u4e00-\u9fa5]{0,3})");
patt.AppendFormat("|({0})",s);
}
}
if(patt.Length>0)
{
patt.Remove(0,1);
}
returnpatt.ToString();
}
///<summary>
///获取所有脏词
///</summary>
publicstaticstring[]GetBlockWords()
{
returnnewstring[]{"国民党","fuck","110"};//这里应该从数据库获取
}
这个程序可替换以下内容:
国民党
国-民-党
国o民o党
fuck
f.u.c.k
110(110的变形写法不被替换)
//intdouble转换
intgoodper;
intbadper;
intgoodposts=Convert.ToInt32(dr["goodpost"]);
intbadposts=Convert.ToInt32(dr["badpost"]);
if(goodposts+badposts==0)
{
goodper=badper=0;
}
else
{
intalls=goodposts+badposts;
goodper=Convert.ToInt32((double)goodposts/alls*100);
badper=100-goodper;
}
如:
Convert.ToInt32(4/5*100)=0
Convert.ToInt32(4.0/5*100)=80
//中英文字符串截取方法
publicstaticstringIntercept(stringinput,intp)
{
Encodingencode=Encoding.GetEncoding("gb2312");
byte[]byteArr=encode.GetBytes(input);
if(byteArr.Length<=p)returninput;
intm=0,n=0;
foreach(bytebinbyteArr)
{
if(n>=p)break;
if(b>127)m++;//重要一步:对前p个字节中的值大于127的字符进行统计
n++;
}
if(m%2!=0)n=p+1;//如果非偶:则说明末尾为双字节字符,截取位数加1
returnencode.GetString(byteArr,0,n);
}
Console.WriteLine(Intercept("ABC中国人",7));
Console.WriteLine(Intercept("ABCD中国人",7));
Console.WriteLine(Intercept("ABC中D国人",7));
/*
测试代码的结果:
ABC中国
ABCD中国
ABC中D国
*/
//kigg发表于某天某时某分前
publicstaticstringAgo(thisDateTimetarget)
{
StringBuilderresult=newStringBuilder();
TimeSpandiff=(DateTime.Now-target.ToLocalTime());
if(diff.Days>0)
{
result.AppendFormat("{0}days",diff.Days);
}
if(diff.Hours>0)
{
if(result.Length>0)
{
result.Append(",");
}
result.AppendFormat("{0}hours",diff.Hours);
}
if(diff.Minutes>0)
{
if(result.Length>0)
{
result.Append(",");
}
result.AppendFormat("{0}minutes",diff.Minutes);
}
if(result.Length==0)
{
result.Append("fewmoments");
}
returnresult.ToString();
}
}
<%#GetOutTime(Eval("发布时间"))%>
///<summary>
///
///</summary>
///<paramname="dtime">发布时间</param>
///<returns></returns>
publicstaticstringGetOutTime(DateTimedtime)
{
DateTimedt=DateTime.Now;
TimeSpants=((TimeSpan)(dt-dtime));
intdays=ts.Days;
inthours=ts.Hours;
intminutes=ts.Minutes;
intmilliseconds=ts.Milliseconds;
if(days>0)returnstring.Format("发布于{0}天前",days);
if(hours>0)returnstring.Format("发布于{0}小时前",hours);
if(minutes>0)returnstring.Format("发布于{0}分钟前",minutes);
returnstring.Format("发布于{0}秒前",milliseconds);
}
publicstaticstringToPrettyDate(thisDateTime date)
{
var timeSince=DateTime.Now.Subtract(date);
if(timeSince.TotalMilliseconds<1)return"not yet";
if(timeSince.TotalMinutes<1)return"just now";
if(timeSince.TotalMinutes<2)return"1 minute ago";
if(timeSince.TotalMinutes<60)returnstring.Format("{0} minutes ago", timeSince.Minutes);
if(timeSince.TotalMinutes<120)return"1 hour ago";
if(timeSince.TotalHours<24)returnstring.Format("{0} hours ago", timeSince.Hours);
if(timeSince.TotalDays==1)return"yesterday";
if(timeSince.TotalDays<7)returnstring.Format("{0} day(s) ago", timeSince.Days);
if(timeSince.TotalDays<14)return"last week";
if(timeSince.TotalDays<21)return"2 weeks ago";
if(timeSince.TotalDays<28)return"3 weeks ago";
if(timeSince.TotalDays<60)return"last month";
if(timeSince.TotalDays<365)returnstring.Format("{0} months ago", Math.Round(timeSince.TotalDays/30));
if(timeSince.TotalDays<730)return"last year";
returnstring.Format("{0} years ago", Math.Round(timeSince.TotalDays/365));
}
DateTimedt=DateTime.Now;
Gengerateg=newGengerate();
g.GengerateHtml();
DateTimedt2=DateTime.Now;
TimeSpants=dt2.Subtract(dt);
stringstrTs=ts.TotalSeconds.ToString();
ltGengerate.Text="生成成功,生成用时"+strTs+"秒!";
//ddl点击赋值:
if(DropDownList1.selectedindex>-1)
{
DropDownList1.Items[DropDownList1.SelectedIndex].Text=TextBox1.Text;
}
//设置ddl的enabled属性:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="id"
OnRowDataBound="GridView1_RowDataBound" >
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow) //一定要
{
DropDownList ddl = (DropDownList)e.Row.FindControl("DropDownList1");
if (ddl != null)
{
if (ddl.SelectedValue == "1")
{
ddl.Enabled = false;
}
}
}
}
string strPath = Server.MapPath("~/roomindex");
/// <summary>
/// 用递归方法删除文件夹目录及文件
/// </summary>
/// <param name="dir">带文件夹名的路径</param>
public void DeleteFolder(string dir)
{
if (Directory.Exists(dir)) //如果存在这个文件夹删除之
{
foreach (string d in Directory.GetFileSystemEntries(dir))
{
if (File.Exists(d))
File.Delete(d); //直接删除其中的文件
else
DeleteFolder(d); //递归删除子文件夹
}
Directory.Delete(dir, true); //删除已空文件夹
}
}
确保您具有足够的权限 对路径 的访问被拒绝
删除权限设置:
在web.config中的<system.web>下加入<identity impersonate="true"/>
//根据用户选择的值设置Cookie的保存时间
if(this.RadioButtonList1.SelectedValue.ToString()=="1")//一天
{
this.Response.Cookies["UserName"].Expires=DateTime.Now.AddDays(1);
this.Response.Cookies["Password"].Expires=DateTime.Now.AddDays(1);
}
if(RadioButtonList1.SelectedValue.ToString()=="2")//一个月
{
this.Response.Cookies["UserName"].Expires=DateTime.Now.AddMonths(1);
this.Response.Cookies["Password"].Expires=DateTime.Now.AddMonths(1);
}
if(RadioButtonList1.SelectedValue.ToString()=="3")//半年
{
this.Response.Cookies["UserName"].Expires=DateTime.Now.AddYears(1/2);
this.Response.Cookies["Password"].Expires=DateTime.Now.AddYears(1/2);
}
if(RadioButtonList1.SelectedValue.ToString()=="4")//一年
{
this.Response.Cookies["UserName"].Expires=DateTime.Now.AddYears(1);
this.Response.Cookies["Password"].Expires=DateTime.Now.AddYears(1);
}
//将用户输入的用户名和密码保存到Cookie中
this.Response.Cookies["UserName"].Value=this.tname.Text;
this.Response.Cookies["Password"].Value=this.tpass.Text;
//跳转到getcookie.aspx页面中显示Cookie中的值
Response.Write("用户登录成功!并将用户登录的用户名和密码保存到Cookie中。");
}
else
{
Response.Redirect("Login.aspx");
}
}
//Attribute:
Response.Write("浏览器的信息为:<br>");
Response.Write("(1)浏览器="+Request.Browser.Browser+"<br>");
Response.Write("(2)型态="+Request.Browser.Type+"<br>");
Response.Write("(3)名称="+Request.Browser.Browser+"<br>");
Response.Write("(4)版本="+Request.Browser.Version+"<br>");
Response.Write("(5)使用平台="+Request.Browser.Platform+"<br>");
Response.Write("(6)是否为测试版="+Request.Browser.Beta+"<br>");
Response.Write("(7)是否为位的环境="+Request.Browser.Win16+"<br>");
Response.Write("(8)是否为位的环境="+Request.Browser.Win32+"<br>");
Response.Write("(9)是否支持框架(Frame)="+Request.Browser.Frames+"<br>");
Response.Write("(10)是否支持表格(Table)="+Request.Browser.Tables+"<br>");
Response.Write("(11)是否支持Cookies="+Request.Browser.Cookies+"<br>");
Response.Write("(12)是否支持ActiveXControls="+Request.Browser.ActiveXControls+"<br>");
stringbb=System.Environment.CurrentDirectory.ToString();
Response.Write(bb);
stringa=Request.Url.ToString();
stringb=Request.Path.ToString();
stringc=Request.PhysicalPath.ToString();
Response.Write("URL地址:"+a+"<br>虚拟路径:"+b+"<br>物理路径:"+c);
stringHostName=Server.MachineName.ToString();
Response.Write("电脑的名称为:"+HostName)
stringpath=Server.MapPath("~").ToString();
Response.Write("物理路径为:"+path);
//结果:
//物理路径为:C:\DocumentsandSettings\itd0300166.PLSH166\桌面\曾祥展\ASP.NET2.0+SQLServer2005全程指南\Study_NET\chap05\Server
stringEncode=Server.HtmlDecode("<b>HTML代码中的内容</b>");
stringDecode=Server.HtmlEncode("<b>HTML代码中的内容</b>");
Response.Write(Encode+"<br>"+Decode);
结果:
HTML代码中的内容
<b>HTML代码中的内容</b>
javascript:void(0)
/
////gridview导出excel
publicoverridevoidVerifyRenderingInServerForm(Controlcontrol)
{
//ConfirmsthatanHtmlFormcontrolisrenderedfor
}
protectedvoidButton3_Click(objectsender,EventArgse)
{
Response.Clear();
Response.Buffer=false;
Response.Charset="GB2312";
Response.AppendHeader("Content-Disposition","attachment;filename=score.xls");
Response.ContentEncoding=System.Text.Encoding.GetEncoding("GB2312");
Response.ContentType="application/ms-excel";
Response.Write("<metawww.558idc.com/ne.html 复制请保留原URL】

