.net 资料
?EF?SqlBulkCopy?批量入庫
string?connection=ConfigurationManager.ConnectionStrings["DbConn"].ConnectionString;
using System.Data.SqlClient;
using System.Data;
using System.ComponentModel;
{
????using?(var?bulkCopy?=?new?SqlBulkCopy(connection))
????{
????????bulkCopy.BatchSize?=?list.Count;
????????bulkCopy.DestinationTableName?=?tableName;
????????var?table?=?new?DataTable();
????????var?props?=?TypeDescriptor.GetProperties(typeof(T))
???????????.Cast<PropertyDescriptor>()
???????????.Where(propertyInfo?=>?propertyInfo.PropertyType.Namespace.Equals("System"))
???????????.ToArray();
????????foreach?(var?propertyInfo?in?props)
????????{
????????????bulkCopy.ColumnMappings.Add(propertyInfo.Name,?propertyInfo.Name);
????????????table.Columns.Add(propertyInfo.Name,?Nullable.GetUnderlyingType(propertyInfo.PropertyType)????propertyInfo.PropertyType);
????????}
????????var?values?=?new?object[props.Length];
????????foreach?(var?item?in?list)
????????{
????????????for?(var?i?=?0;?i?<?values.Length;?i++)
????????????{
????????????????values[i]?=?props[i].GetValue(item);
????????????}
????????????table.Rows.Add(values);
????????}
????????bulkCopy.WriteToServer(table);
????}
}
var?imports?=?new?List<sendapientity>();
foreach?(JToken?phone?in?phones)
{
????SendEntity?sendphone?=?JsonConvert.DeserializeObject<SendEntity>(phone.ToString());
????string?tphone?=?sendphone.phone;?int?sendid?=?Convert.ToInt32(sendphone.id);
????sendapientity?s?=?new?sendapientity();
????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?(SMMMContext?db?=?new?SMMMContext())
?{
?????BulkInsert(db.Database.Connection.ConnectionString,?"Send_Api",?imports);
?}
?public?class?sendapientity
?{
?????public?int?UserId?{?get;?set;?}
?????public?string?PartnersCode?{?get;?set;?}
?????public?int?SendId?{?get;?set;?}
?????public?string?Phone?{?get;?set;?}
?????public?string?Message?{?get;?set;?}
?????public?string?SentTime?{?get;?set;?}
?????public?DateTime?CreateTime?{?get;?set;?}
?????public?long?BatchId?{?get;?set;?}
?????public?int?Count?{?get;?set;?}
?}
?
?
在JavaScript中推薦的做法是用encodeURI對URI的網址部分編碼,用encodeURIComponent對URI中傳遞的參數進行編碼。
在C#中推薦的做法是用Uri.EscapeUriString對URI的網址部分編碼,用Uri.EscapeDataString對URI中傳遞的參數進行編碼。
?
public?static?int?ToInt32(double?value){
????if?(value?>=?0.0)
????{
????????if?(value?<?2147483647.5)
????????{
????????????int?num?=?(int)value;
????????????double?num2?=?value?-?num;
????????????if?((num2?>?0.5)?||?((num2?==?0.5)?&&?((num?&?1)?!=?0)))
????????????{
????????????????num++;
????????????}
????????????return?num;
????????}
????}
????else?if?(value?>=?-2147483648.5)
????{
????????int?num3?=?(int)value;
????????double?num4?=?value?-?num3;
????????if?((num4?<?-0.5)?||?((num4?==?-0.5)?&&?((num3?&?1)?!=?0)))
????????{
????????????num3--;
????????}
????????return?num3;
????}
????throw?new?OverflowException(Environment.GetResourceString("Overflow_Int32"));
}
?
public?enum?CommentType?{?不推薦=0,?一般=3,?良=4,?優=5?}??///?<summary>
????????///?綁定評分類型
????????///?</summary>
????????///?<param?name="RBL"></param>
????????protected?static?void?BindRadioButtonList(RadioButtonList?RBL)
????????{
????????????RBL.Items.Clear();
????????????Type?typ?=?typeof(CommentType);
????????????foreach?(int?i?in?Enum.GetValues(typ))
????????????{
????????????????RBL.Items.Add(new?ListItem(Enum.GetName(typ,?i),?Enum.Format(typ,?Enum.Parse(typ,?Enum.GetName(typ,?i)),?"d")));
????????????????RBL.SelectedValue?=?i.ToString();
????????????}
????????}
?///?<summary>
????????///?獲取類型名稱
????????///?</summary>
????????///?<param?name="typeid"></param>
????????///?<returns></returns>
????????protected?static?string?BindRating(string?typeid)
????????{
????????????string?typename?=?"";
????????????Type?typ?=?typeof(CommentType);
????????????foreach?(int?i?in?Enum.GetValues(typ))
????????????{
????????????????if?(typeid?==?Enum.Format(typ,?Enum.Parse(typ,?Enum.GetName(typ,?i)),?"d"))
????????????????{
????????????????????typename?=?Enum.GetName(typ,?i);
????????????????}
????????????}
????????????return?typename;
????????}
?
//.NET?正確獲取當前URLHttpContext.Current.Request.Url.ToString()????不可靠
HttpContext.Current.Request.Url.PathAndQuery??正確?
///?new?List<int>(ht.Keys),用到了?List?的構造拷貝函數
///?在遍歷數據結構的時候,是不可以修改原數據結構的。不然就會拋出錯誤。
foreach?(string?key?in?new?List<string>(_IpAdresses.Keys))
????{
????????_IpAdresses[key]--;
????????if?(_IpAdresses[key]?==?0)
????????????_IpAdresses.Remove(key);
????}
c# 四舍五入 保留幾位小數點
????protected?string?getProductPrice(int?id)????{
????????CustomerProInfo?cp?=?ahlan.getCustomerProInfoByID(id);
????????double?x?=?double.Parse((cp.Product.sprice?*?cp.proValue?/?10).ToString());?//兩個double相乘結果是double?,所以要強制在轉換一次
????????return?ChinaRound(x,2).ToString();
????}
????//value你要轉換的double數據,decimals要保留的小數點
????double?ChinaRound(double?value,?int?decimals)
????{
????????if?(value?<?0)
????????{
????????????return?Math.Round(value?+?5?/?Math.Pow(10,?decimals?+?1),?decimals,?MidpointRounding.AwayFromZero);
????????}
????????else
????????{
????????????return?Math.Round(value,?decimals,?MidpointRounding.AwayFromZero);
????????}
????}
?
//判斷用戶是手機還是pc訪問public?class?IsPhoneAttribute?:?ActionFilterAttribute
?????{
?????????public?override?void?OnActionExecuting(ActionExecutingContext?filterContext)
?????????{
?????????????string?u?=?filterContext.HttpContext.Request.ServerVariables["HTTP_USER_AGENT"];
?????????????Regex?b?=?new?Regex(@"android.+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge?|maemo|midp|mmp|netfront|opera?m(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);
?????????????Regex?v?=?new?Regex(@"1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a?wa|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(\-|_)|g1?u|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?=?new?ViewResult()
?????????????????{
?????????????????????ViewName?=?"ErrorInfo",
?????????????????????ViewData?=?filterContext.Controller.ViewData,
?????????????????};
?????????????}
?
?????????}
?????}
?
?發送短信接口?
public?static?bool?SendMobileMsg(string?msgContent,?List<string>?destListPhones)?????????{
?????????????try
?????????????{
?????????????????bool?result?=?false;
?????????????????string?strPhones?=?string.Join(";",?destListPhones.ToArray());
?????????????????strPhones?+=?";";
?????????????????var?encoding?=?System.Text.Encoding.GetEncoding("GB2312");
?
?????????????????string?postData?=?string.Format("uid=用戶名&pwd=密碼&mobile={0};&msg={1}&dtime=",?strPhones,?msgContent);
?
?????????????????byte[]?data?=?encoding.GetBytes(postData);
?
?????????????????//?定義?WebRequest
??????????????????HttpWebRequest?myRequest?=
?????????????????(HttpWebRequest)WebRequest.Create("http://www.smsadmin.cn/smsmarketing/wwwroot/api/post_send/");
?
?????????????????myRequest.Method?=?"POST";
?????????????????myRequest.ContentType?=?"application/x-www-form-urlencoded";
?????????????????myRequest.ContentLength?=?data.Length;
?
?????????????????Stream?newStream?=?myRequest.GetRequestStream();
?
?????????????????//發送數據
??????????????????newStream.Write(data,?0,?data.Length);
?????????????????newStream.Close();
?
?????????????????//?得到?Response
?????????????????HttpWebResponse?myResponse?=?(HttpWebResponse)myRequest.GetResponse();
?????????????????StreamReader?reader?=?new?StreamReader(myResponse.GetResponseStream(),?Encoding.Default);
?????????????????string?content?=?reader.ReadToEnd();
?
?????????????????if?(content.Substring(0,?1)?==?"0")
?????????????????????result?=?true;
?????????????????else
?????????????????{
?????????????????????if?(content.Substring(0,?1)?==?"2")?//余額不足
?????????????????????{
???????????????????????//"手機短信余額不足";
???????????????????????//TODO
?????????????????????}
?????????????????????else
?????????????????????{
???????????????????????//短信發送失敗的其他原因,請參看官方API
?????????????????????}
?????????????????????result?=?false;
?????????????????}
?
?????????????????return?result;
?????????????}
?????????????catch
?????????????{
?????????????????return?false;
?????????????}
?????????
?????????}
?
?
很“干凈”的調用,沒有WebService也沒有COM。
唯一要注意的就是編碼用?GB2312?否則您收到短信的中文部分都是亂碼,另外第10行的用戶名和密碼被硬編碼了,應寫在配置文件內。
?
使用正則替換文章屏蔽詞
private?static?readonly?Regex?reg_b?=?new?Regex(@"\B",?RegexOptions.Compiled);private?static?readonly?Regex?reg_en?=?new?Regex(@"[a-zA-Z]+",?RegexOptions.Compiled);
private?static?readonly?Regex?reg_num?=?new?Regex(@"^[\-\.\s\d]+$",?RegexOptions.Compiled);
private?static?Regex?reg_word?=?null;?//組合所有屏蔽詞的正則
private?static?Regex?GetRegex()
{
????if?(reg_word?==?null)
????{
????????reg_word?=?new?Regex(GetPattern(),?RegexOptions.Compiled?|?RegexOptions.IgnoreCase);
????}
????return?reg_word;
}
///?<summary>
///?檢查輸入內容是否包含臟詞(包含返回true)
///?</summary>
public?static?bool?HasBlockWords(string?raw)
{
????return?GetRegex().Match(raw).Success;
}
///?<summary>
///?臟詞替換成*號
///?</summary>
public?static?string?WordsFilter(string?raw)
{
????return?GetRegex().Replace(raw,?"***");
}
///?<summary>
///?獲取內容中含有的臟詞
///?</summary>
public?static?IEnumerable<string>?GetBlockWords(string?raw)
{
????foreach?(Match?mat?in?reg_word.Matches(raw))
????{
????????yield?return?(mat.Value);
????}
}
private?static?string?GetPattern()
{
????StringBuilder?patt?=?new?StringBuilder();
????string?s;
????foreach?(string?word?in?GetBlockWords())
????{
????????if?(word.Length?==?0)?continue;
????????if?(word.Length?==?1)
????????{
????????????patt.AppendFormat("|({0})",?word);
????????}
????????else?if?(reg_num.IsMatch(word))
????????{
????????????patt.AppendFormat("|({0})",?word);
????????}
????????else?if?(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);
????}
????return?patt.ToString();
}
///?<summary>
///?獲取所有臟詞
///?</summary>
public?static?string[]?GetBlockWords()
{
????return?new?string[]{"國民黨","fuck","110"};//這里應該從數據庫獲取
}
?
?
這個程序可替換以下內容:
國民黨
國-民-黨
國o民o黨
fuck
f.u.c.k
110(110的變形寫法不被替換)
??
//int?double?轉換
int?goodper;
int?badper;
int?goodposts?=?Convert.ToInt32(dr["goodpost"]);
int?badposts?=?Convert.ToInt32(dr["badpost"]);
if?(goodposts?+?badposts?==?0)
{
????goodper?=?badper?=?0;
}
else
{
????int?alls?=?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
//中英文字符串截取方法?
public?static?string?Intercept(string?input,?int?p)
????????{
????????????Encoding?encode?=?Encoding.GetEncoding("gb2312");
????????????byte[]?byteArr?=?encode.GetBytes(input);
????????????if?(byteArr.Length?<=?p)?return?input;
????????????int?m?=?0,?n?=?0;
????????????foreach?(byte?b?in?byteArr)
????????????{
????????????????if?(n?>=?p)?break;
????????????????if?(b?>?127)?m++;?//重要一步:對前p個字節中的值大于127的字符進行統計
????????????????n++;
????????????}
????????????if?(m?%?2?!=?0)?n?=?p?+?1;?//如果非偶:則說明末尾為雙字節字符,截取位數加1
????????????return?encode.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?發表于某天某時某分前?
????public?static?string?Ago(this?DateTime?target)
????{
????????StringBuilder?result?=?new?StringBuilder();
????????TimeSpan?diff?=?(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("few?moments");
????????}
????????return?result.ToString();
????}
}
<%#?GetOutTime(Eval("發布時間"))?%>
?
????///?<summary>
????///?
????///?</summary>
????///?<param?name="dtime">發布時間</param>
????///?<returns></returns>
????public?static?string?GetOutTime(DateTime?dtime)
????{
????????DateTime?dt?=?DateTime.Now;
????????TimeSpan?ts?=?((TimeSpan)(dt?-?dtime));
????????
????????int?days?=?ts.Days;
????????int?hours?=?ts.Hours;
????????int?minutes?=?ts.Minutes;
????????int?milliseconds?=?ts.Milliseconds;
????????if?(days?>?0)?return?string.Format("發布于{0}天前",?days);
????????if?(hours?>?0)?return?string.Format("發布于{0}小時前",?hours);
????????if?(minutes?>?0)?return?string.Format("發布于{0}分鐘前",?minutes);
????????return?string.Format("發布于{0}秒前",?milliseconds);
????}
public?static?string?ToPrettyDate(this?DateTime 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)?return?string.Format("{0} minutes ago", timeSince.Minutes);
? ? ? ? ? ??if?(timeSince.TotalMinutes?<?120)?return?"1 hour ago";
? ? ? ? ? ??if?(timeSince.TotalHours?<?24)?return?string.Format("{0} hours ago", timeSince.Hours);
? ? ? ? ? ??if?(timeSince.TotalDays?==?1)?return?"yesterday";
? ? ? ? ? ??if?(timeSince.TotalDays?<?7)?return?string.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)?return?string.Format("{0} months ago", Math.Round(timeSince.TotalDays?/?30));
? ? ? ? ? ??if?(timeSince.TotalDays?<?730)?return?"last year";
? ? ? ? ? ??return?string.Format("{0} years ago", Math.Round(timeSince.TotalDays?/?365));
? ? ? ??}
????????????DateTime?dt?=?DateTime.Now;
????????????Gengerate?g?=?new?Gengerate();
????????????g.GengerateHtml();
????????????DateTime?dt2?=?DateTime.Now;
????????????TimeSpan?ts?=?dt2.Subtract(dt);
????????????string?strTs?=?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)是否支持ActiveX?Controls="?+Request.Browser.ActiveXControls?+?"<br>");
string?bb?=?System.Environment.CurrentDirectory.ToString();
Response.Write(bb);
string?a?=?Request.Url.ToString();
string?b?=?Request.Path.ToString();
string?c?=?Request.PhysicalPath.ToString();
Response.Write("URL地址:"?+?a?+?"<br>虛擬路徑:"?+?b?+?"<br>物理路徑:"?+?c);
string?HostName=Server.MachineName.ToString();
Response.Write("電腦的名稱為:"+HostName)
string?path?=?Server.MapPath("~").ToString();
Response.Write("物理路徑為:"+path);
//結果:
//物理路徑為:C:\Documents?and?Settings\itd0300166.PLSH166\桌面\曾祥展\ASP.NET?2.0+SQL?Server?2005全程指南\Study_NET\chap05\Server
string?Encode?=?Server.HtmlDecode("<b>HTML代碼中的內容</b>");
string?Decode?=?Server.HtmlEncode("<b>HTML代碼中的內容</b>");
Response.Write(Encode+"<br>"+Decode);
結果:
HTML代碼中的內容
<b>HTML代碼中的內容</b>
http://www.cnblogs.com/hun_dan/archive/2011/03/01/1968298.html
/
////gridview導出excel
public?override?void?VerifyRenderingInServerForm(Control?control)
{
//?Confirms?that?an?HtmlForm?control?is?rendered?for
}
protected?void?Button3_Click(object?sender,?EventArgs?e)
{
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("<meta?http-equiv=Content-Type?content=\"text/html;?charset=GB2312\">");
this.EnableViewState?=?false;
System.Globalization.CultureInfo?str?=?new?System.Globalization.CultureInfo("ZH-CN",?true);
System.IO.StringWriter?oStringWriter?=?new?System.IO.StringWriter(str);
HtmlTextWriter?oHtmlTextWriter?=?new?HtmlTextWriter(oStringWriter);
GridView1.RenderControl(oHtmlTextWriter);
Response.Write(oStringWriter.ToString());
Response.End();
}
<script?language="javascript"?type="text/javascript">
//先獲取所有的Checkbox
var?chkList?=?document.getElementsByName("CheckBox1");
window.onload?=?function()
{
//為所有checkbox添加onclick事件處理,以自動更新“已選擇的項”
for(var?i=0;?i<chkList.length;?i++)
{
chkList[i].onclick?=?chkClick;
}
}
//checkbox的onclick事件,用于更新“已選擇的項”
function?chkClick()
{
var?checkedList?=?"";
//獲取所有被選中的項
for(var?i=0;?i<chkList.length;?i++){
if(chkList[i].checked)
checkedList?+=?chkList[i].value?+?",";
}
//把選中項的列表顯示到“已選擇的項”中,substring在這里是為了去除最后一個逗號
document.getElementById("HiddenField1").value?=?checkedList.substring(0,checkedList.length-1);
}
</script>
string?type?=?HiddenField1.Value;
string[]?keyValue?=?type.Split(',');
foreach?(string?str?in?keyValue)
{
//判定是否選中任何一門
string?sql1?=?"select?*?from?xk?where?課程編號='"?+?str?+?"'?";
//遍歷?Panel1下的下拉框
foreach?(System.Web.UI.Control?ddl?in?Panel1.Controls)
{
if?(ddl?is?DropDownList)
{
DropDownList?d?=?(DropDownList)ddl;
str?=?str?+?d.SelectedValue.ToString()?+?",";
}
}
int?j?=?0;
string[]?words?=?sqlpj.Split(',');
//TextBox1.Text?=?sqlpj.Substring(sqlpj.IndexOf(words[20]),?sqlpj.Length-?sqlpj.IndexOf(words[20]));
TextBox1.Text?=?sqlpj.Remove(0,sqlpj.IndexOf(words[20]));
foreach?(System.Web.UI.Control?ddl?in?Panel1.Controls)
{
if?(?ddl?is?DropDownList)
{
DropDownList?d?=?(DropDownList)ddl;
d.Text?=?words[j];
j++;
}
}
//第二種方法
string[]?sqlleft?=?new?string[20];
string?sqlrigth?=?sqlpj;
for?(int?i?=?0;?i?<?20;?i++)
{
int?dex?=?sqlpj.IndexOf(',');
sqlleft[i]?=?sqlrigth.Substring(0,?dex);
sqlrigth?=?sqlrigth.Substring(dex?+?1);
}
TextBox1.Text?=?sqlrigth;
int?j?=?0;
foreach?(System.Web.UI.Control?ddl?in?Panel1.Controls)
{
if?(ddl?is?DropDownList)
{
DropDownList?d?=?(DropDownList)ddl;
d.Text?=?sqlleft[j];
j++;
}
}
<asp:HyperLinkField?DataNavigateUrlFields="任課老師"
DataNavigateUrlFormatString="Stu_pjtea.aspx?任課老師={0}"?HeaderText="進入評教"
NavigateUrl="Stu_pjtea.aspx"?Text="<font?color=red?>進入</font>"?/>
string?teaname?=?Request.QueryString["任課老師"].ToString();
?
?
//從1,50隨機20個不重復數
??public?int[]?GetRandomUnrepeatArray(int?minValue,?int?maxValue,?int?count)
??{
??????Random?rnd?=?new?Random();
??????int?length?=?maxValue?-?minValue?+?1;
??????byte[]?keys?=?new?byte[length];
??????rnd.NextBytes(keys);
??????int[]?items?=?new?int[length];
??????for?(int?i?=?0;?i?<?length;?i++)
??????{
??????????items[i]?=?i?+?minValue;
??????}
??????Array.Sort(keys,?items);
??????int[]?result?=?new?int[count];
??????Array.Copy(items,?result,?count);
??????return?result;
??}
調用:
int[]?a=?GetRandomUnrepeatArray(1,100,20);
???????for?(int?i?=?0;?i?<?a.Length;?i++)
???????{
???????????Response.Write(a[i].ToString()+",");
???????}
//結果:27,34,44,19,30,67,58,18,26,57,62,16,8,91,100,31,56,85,88,29
?
///?<summary>?????
///?從1到33中任意選取不重復的6個隨機數?????
///?</summary>?????
///?<returns></returns>?????
public?List<int>?GenerateNumber()?????
{?????
????//用于存放1到33這33個數?????.????List<int>?container?=?new?List<int>(33);?????
????//用于保存返回結果?????
????List<int>?result?=?new?List<int>(6);?????
????Random?random?=?new?Random();?????
????for?(int?i?=?1;?i?<=?33;?i++)?????
????{?????
????????container.Add(i);?????
????}?????
????int?index?=?0;?????
????int?value?=?0;?????
????for?(int?i?=?1;?i?<=?6;?i++)?????
????{?????
????????//從[0,container.Count)中取一個隨機值,保證這個值不會超過container的元素個數?????
????????index?=?random.Next(0,?container.Count);?????
????????//以隨機生成的值作為索引取container中的值?????
????????value?=?container[index];?????
????????//將隨機取得值的放到結果集合中?????
????????result.Add(value);?????
????????//從容器集合中刪除這個值,這樣會導致container.Count發生變化?????
????????container.RemoveAt(index);?????
????????//注意這一句與上面一句能達到同樣效果,但是沒有上面一句快?????
????????//container.Remove(value);?????
????}????
????//result.Sort();排序?????
????return?result;?????
}?
public?int[]?GenerateNumber()?????
{?????
????//用于存放1到33這33個數?????
????int[]?container?=?new?int[33];?????
????//用于保存返回結果?????
????int[]?result?=?new?int[6];?????
????Random?random?=?new?Random();?????
????for?(int?i?=?1;?i?<=?33;?i++)?????
????{?????
????????container[i?-?1]?=?i;?????
????}????
????int?index?=?0;?????
????int?value?=?0;?????
????for?(int?i?=?0;?i?<?6;?i++)????
????{?????
????????//從[1,container.Count?+?1)中取一個隨機值,保證這個值不會超過container的元素個數?????
????????index?=?random.Next(1,?container.Length-1-i);?????
????????//以隨機生成的值作為索引取container中的值?????
????????value?=?container[index];?????
????????//將隨機取得值的放到結果集合中?????
????????result[i]=value;????
????????//將剛剛使用到的從容器集合中移到末尾去?????
????????container[index]?=?container[container.Length?-?i-1];?????
????????//將隊列對應的值移到隊列中?????
???????container[container.Length?-?i-1]?=?value;?????
????}?????
????//result.Sort();排序????
????return?result;????
}?
?
??Random?r?=?new?Random(Guid.NewGuid().GetHashCode()); 隨機不重復
?
// Select/Deselect checkboxes based on header checkbox function SelectheaderCheckboxes(headerchk) { // debugger var gvcheck = document.getElementById('rptList'); var i; //Condition to check header checkbox selected or not if that is true checked all checkboxes var checkedList = ""; if (headerchk.checked) { for (i = 0; i < gvcheck.rows.length; i++) { var inputs = gvcheck.rows[i].getElementsByTagName('input'); inputs[0].checked = true; var s=$($(inputs)).next().html(); if (s!==null) { checkedList += s + ","; } document.getElementById("hidvalue").value = checkedList.substring(0, checkedList.length - 1); } } //if condition fails uncheck all checkboxes in gridview else { for (i = 0; i < gvcheck.rows.length; i++) { var inputs = gvcheck.rows[i].getElementsByTagName('input'); inputs[0].checked = false; } document.getElementById("hidvalue").value = ""; } } //function to check header checkbox based on child checkboxes condition function Selectchildcheckboxes(header) { var ck = header; var count = 0; var gvcheck = document.getElementById('rptList'); var headerchk = document.getElementById(header); var rowcount = gvcheck.rows.length; var checkedList = ''; //By using this for loop we will count how many checkboxes has checked for (i = 1; i < gvcheck.rows.length; i++) { var inputs = gvcheck.rows[i].getElementsByTagName('input'); if (inputs[0].checked) { count++; var s = $($(inputs)).next().html(); if (s !== null) { checkedList += s + ","; } } document.getElementById("hidvalue").value = checkedList.substring(0, checkedList.length - 1); } //Condition to check all the checkboxes selected or not if (count == rowcount - 1) { headerchk.checked = true; } else { headerchk.checked = false; } } //先獲取所有的Checkbox var chkList = $('#rptList').find(".chkChild input"); window.onload = function () { //為所有checkbox添加onclick事件處理,以自動更新“已選擇的項” for (var i = 0; i < chkList.length; i++) { chkList[i].onclick = chkClick; } } //checkbox的onclick事件,用于更新“已選擇的項” function chkClick() { var checkedList = ""; //獲取所有被選中的項 for (var i = 0; i < chkList.length; i++) { if (chkList[i].checked) // checkedList += chkList[i].value + ","; checkedList += $($(chkList[i])).next().html() + ","; } //把選中項的列表顯示到“已選擇的項”中,substring在這里是為了去除最后一個逗號 document.getElementById("hidvalue").value = checkedList.substring(0, checkedList.length - 1); }?
?
/// <summary>/// 隨機排列數組元素 打亂順序 調用 string[] newlist = Shuffle(arr);/// </summary>/// <typeparam name="T"></typeparam>/// <param name="Source"></param>public static T[] Shuffle<T>(T[] Source){if (Source == null) return null;int len = Source.Length;//用變數記會快一點點點Random rd = new Random();int r;//記下隨機產生的號碼T tmp;//暫存用for (int i = 0; i < len - 1; i++){r = rd.Next(i, len);//取亂數,範圍從自己到最後,決定要和哪個位置交換,因此也不用跑最後一圈了if (i == r) continue;tmp = Source[i];Source[i] = Source[r];Source[r] = tmp;}return Source;}? ? 本文轉自曾祥展博客園博客,原文鏈接:http://www.cnblogs.com/zengxiangzhan/archive/2009/10/31/1593642.html,如需轉載請自行聯系原作者
總結
- 上一篇: NFS共享安装部署
- 下一篇: 201671010128 2017-11