【知识碎片】Asp.Net 篇
?
51、app.config 連接字符串
<?xml version="1.0" encoding="utf-8"?> <configuration><startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" /></startup><appSettings><add key="dmsFolder" value="C:\local.dfs.com\Data\DMS\" /></appSettings><connectionStrings><!--<add name="dfs" connectionString="user id=ProferoTest;password=Pr0f3r0;Data Source=127.0.0.1;Database=databesename" />--><!--<add name="ConnectionString" connectionString="Data Source=.;Initial Catalog=ExpUsers;Persist Security Info=True;User ID=sa;password=mima;" providerName="System.Data.SqlClient" />--><add name="ConnectionString" connectionString=" Data Source=.;Initial Catalog=UserExp2;Persist Security Info=True;User ID=sa;password=mima;" providerName="System.Data.SqlClient" /></connectionStrings> </configuration> View Code讀取:
string connString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString.ToString();記得添加引用?using System.Configuration;
50、常用設(shè)計模式
savechange 設(shè)計模式:工作單元模式 :一個業(yè)務(wù)對多張表的操作,只連一次數(shù)據(jù)庫,完成條記錄的更新
簡單工廠:返回父類或者接口的多種形態(tài)
抽象工廠:通過反射創(chuàng)建
單例:類似靜態(tài)類 ?可以繼承 ?擴(kuò)展 ?延遲加載.....保證程序只new一次 ? 比如隊(duì)列 就可以放在單列里面
49、.net ?常用 ORM框架
對象關(guān)系映射(英語:Object Relational Mapping,簡稱ORM,或O/RM,或O/R mapping),是一種程序技術(shù),用于實(shí)現(xiàn)面向?qū)ο缶幊陶Z言里不同類型系統(tǒng)的數(shù)據(jù)之間的轉(zhuǎn)換。從效果上說,它其實(shí)是創(chuàng)建了一個可在編程語言里使用的“虛擬對象數(shù)據(jù)庫”。?
EF:Entity Framework
NHibernate
Linq
Dapper
PetaPoco
轉(zhuǎn)自:http://zhan.renren.com/h5/entry/3602888498046723643
48、二維碼生成
后臺代碼:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Web;namespace JTZK_Handle {public class HandleEr{public static string GetEr(){string html = @"<div style=""text-align: center;border: solid 1px #cacaca; margin-top:20px""><p style=""border-bottom: solid 1px #cacaca; line-height: 40px;""><img align=""middle"" src=""/images/weixinico.png"" /> 微信掃一掃,分享到朋友圈</p><p style=""margin-bottom: 20px; margin-top: 20px;""><img src=""http://s.jiathis.com/qrcode.php?url={0}"" width=""140"" height=""130"" /></p> </div>";return string.Format(html, HttpContext.Current.Request.Url.ToString());}} } View Code前臺代碼:
<%=JTZK_Handle.HandleEr.GetEr() %>?
?
47、.net 中const 與readonly的區(qū)別???
const和readonly都是只讀的。
但是const修飾的變量必須在聲明時賦值。
readonly修飾的變量可以在聲明時或者構(gòu)造函數(shù)里賦值。
private const double pi=3.14;
class A { private readonly int a; public A(int v) { a=v; } }
46、asp.net MVC 導(dǎo)出txt文件
public ActionResult ExpData(){StringBuilder sb = new StringBuilder();string timeNow = DateTime.Now.ToString();Response.Clear();Response.Buffer = false;//通知瀏覽器 下載文件而不是打開Response.ContentType = "application/octet-stream";Response.AppendHeader("content-disposition", "attachment;filename=" + timeNow + ".txt;");var operLogList = operLogBLL.LoadEntities(o=>o.IsValid==1);foreach (var item in operLogList){sb.Append("時間:" + item.CreateTime.ToString() + "\n");sb.Append("類別:" + item.Category.ToString() + "\n");sb.Append("域:" + item.DomainID.ToString() + "\n");sb.Append("用戶名:" + item.AccountName.ToString() + "\n");sb.Append("內(nèi)容:" + item.Content.ToString() + "\n");sb.Append("--------------------------------------------------\n\n");}Response.Write(sb);Response.Flush();Response.End();return new EmptyResult();} View Code //導(dǎo)出數(shù)據(jù) function ExpData() {window.location.href = "/LogManager/ExpData";//MySuccess("導(dǎo)出成功!");};?
45、評論插件
國外成功的案例是國內(nèi)互聯(lián)網(wǎng)創(chuàng)業(yè)者的風(fēng)向標(biāo)。在Disqus??http://disqus.com?獲得巨大成功。在沒美國很多網(wǎng)站都用此評論系統(tǒng)
社交評論插件的國內(nèi)模仿者我見到的幾家就是:
1、多說(http://www.duoshuo.com/?)
2、評論啦(http://www.pinglun.la/)
3、友言(http://uyan.cc/)
4、貝米(http://baye.me/)
?
44、動態(tài)解析二級域名
剛開始在網(wǎng)上找 ?看到了DomainRoute這個插件?
按照教程弄了,確實(shí)好使 也能跑起來
可是之前的好多路由配置再改成這樣的,不好改,而且這個這個沒有控制器 和方法名的限制參數(shù)
而且這個插件和url轉(zhuǎn)小寫的插件不能一起用
最后還是打算自己在global里URL重寫吧
--------------------------------------------------------------------------------------------------------------------------
請求報文 ?接收報文
http協(xié)議 ?返回的請求狀態(tài)碼
post請求 ?get請求
get請求接收 context.Request.QueryString["catalog"]
post請求接收 context.Request.Form["catalog"]
Response.Redirect重定向
context.Response.Redirect("UserInfoList.ashx");?文件上傳 可以用文件流的MD5 或者GUID做標(biāo)識,時間不能唯一不建議
webform調(diào)用后臺 變量方法
<strong>1.在前臺html控件調(diào)用c#后臺變量。</strong> 在后臺的類代碼里定義一個字符串。如 public partial class Index : System.Web.UI.Page {public string msg = ""; } 然后可以寫方法改變此字符串的值。 前臺調(diào)用也很簡單: <input id="Text1" type="text" value="<%=msg%>"/> <strong>2.在前臺html調(diào)用c#后臺方法</strong> 后臺有一個方法: public string test() {return "message"; } 前臺代碼: <input id="Text2" type="text" value="<%=test()%>"/> <strong>3.在前臺js里調(diào)用c#后臺變量</strong> 后臺代碼: public partial class Index : System.Web.UI.Page {public string msg = ""; } 前臺代碼:<script>alert("<%=msg%>");</script> <strong>4.在前臺js里調(diào)用c#后臺變量</strong> 后臺有一個方法: public string test() {return "message"; } 前臺代碼: <script>alert("<%=test() %>");</script> <strong>5,前臺js里調(diào)用后臺帶參數(shù)的方法</strong> public string test(string a) {return a+",我是參數(shù)傳進(jìn)來的"; } <script>alert("<%=test("021") %>");</script> <strong>6,前臺js里調(diào)用后臺帶參數(shù)的方法</strong>//商品信息 function getProInfo(t) {var result = "";result = MallPowerSite.order.ChangeOrderEdit.GetProductInfo(t).value;//后臺的方法,注意這里不用雙引號return result; } View Code值得注意的是,要在js中調(diào)用C#的變量和函數(shù)返回的結(jié)果,js代碼必須寫在頁面的<script>...</script>中,而不能寫在獨(dú)立的*.js文件中,這樣會js會將*.js的C#代碼作為字符串處理,而不是變量或者方法。
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="UserInfoList.aspx.cs" Inherits="CZBK.ItcastProject.WebApp._2015_5_29.UserInfoList" %> <!DOCTYPE html> <%@ Import Namespace="CZBK.ItcastProject.Model" %> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/><title></title><script type="text/javascript">window.onload = function () {var datas = document.getElementsByClassName("deletes");var dataLength = datas.length;for (var i = 0; i < dataLength; i++) {datas[i].onclick = function () {if (!confirm("確定要刪除嗎?")) {return false;}}}};</script><link href="../Css/tableStyle.css" rel="stylesheet" /> </head> <body><form id="form1" runat="server"><div><a href="AddUserInfo.aspx">添加用戶</a><table> <tr><th>編號</th><th>用戶名</th><th>密碼</th><th>郵箱</th><th>時間</th><th>刪除</th><th>詳細(xì)</th><th>編輯</th></tr><%-- <%=StrHtml%>--%><% foreach(UserInfo userInfo in UserList){%><tr><td><%=userInfo.Id %></td><td><%=userInfo.UserName %></td><td><%=userInfo.UserPass %></td><td><%=userInfo.Email %></td><td><%=userInfo.RegTime.ToShortDateString() %></td><td><a href="Delete.ashx?id=<%=userInfo.Id %>" class="deletes">刪除</a></td><td>詳細(xì)</td><td><a href="EditUser.aspx?id=<%=userInfo.Id %>">編輯</a> </td></tr><%} %></table><hr /></div></form> </body> </html> View Code?
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Fdcxm_Mx.aspx.cs" Inherits="WebApplication.Fdc.Fdcxm_Mx" %><html xmlns="http://www.w3.org/1999/xhtml"> <head id="Head1" runat="server"><title></title><link href="/Css/FDC.css" type="text/css" rel="stylesheet" /> </head> <body><table border="0" cellspacing="1"><tr><td colspan="6" align="center" valign="middle" class="title_0"><%=this.XmFdcInfo.XmName%></td></tr></table><table border="0" cellspacing="1"><tr><td align="center" valign="middle" class="title_1">稅款屬期</td><td align="center" valign="middle" class="title_1">項(xiàng)目固定信息數(shù)據(jù)申報表</td><td align="center" valign="middle" class="title_1">項(xiàng)目按月信息數(shù)據(jù)申報表</td><td align="center" valign="middle" class="title_1">施工企業(yè)報送數(shù)據(jù)申報表</td></tr><tbody id="tab"><tr><td align="center" valign="middle"><%=Convert.ToDateTime(this.YYS_SKSQ).ToString("yyyy-MM")%></td><td align="center" valign="middle"><a href="#" onclick="top.frames['MainFrame'].WinClose1('/Fdc/Jcxx.aspx?YYS_SKSQ=<%=this.YYS_SKSQ %>&XM_CODE=<%=this.XmFdcInfo.XmCode%>', '<%=this.XmFdcInfo.XmName%>房地產(chǎn)固定信息');"><%if (this.GDSB_SH_JG == "審核未通過" || this.GDSB_SH_JG == ""){ %>數(shù)據(jù)申報<%} %><%else{ %>數(shù)據(jù)修改<%} %></a></td><td align="center" valign="middle"><%if (this.GDSB_SH_JG == "審核已通過"){ %><a href="#" onclick="top.frames['MainFrame'].WinClose1('/Fdc/AysbMx.aspx?YYS_SKSQ=<%=this.YYS_SKSQ %>&XM_CODE=<%=this.XmFdcInfo.XmCode%>', '<%=this.XmFdcInfo.XmName%>按月數(shù)據(jù)申報信息');"><%if (this.AYSB_SH_JG == "審核未通過" || this.AYSB_SH_JG == ""){ %>數(shù)據(jù)申報<%} %><%else{ %>數(shù)據(jù)修改<%} %></a><%}else{ %>數(shù)據(jù)申報<%} %></td><td align="center" valign="middle"><%if (AYSB_SH_JG == "審核已通過" && this.GDSB_SH_JG == "審核已通過" && this.XmFdcInfo.XmZt != "尾盤"){ %><a href="#" onclick="top.frames['MainFrame'].WinClose1('/Fdc/SGDW.aspx?YYS_SKSQ=<%=this.YYS_SKSQ %>&XM_CODE=<%=this.XmFdcInfo.XmCode%>', '<%=this.XmFdcInfo.XmName%>報送施工企業(yè)信息');"><%if (this.SGDW_SH_JG == "審核未通過" || this.SGDW_SH_JG == ""){ %>數(shù)據(jù)申報<%} %><%else{ %>數(shù)據(jù)修改<%} %></a><%}else{ %>數(shù)據(jù)申報<%} %></td></tr><tr><td align="center" valign="middle" class="title_1">歷史數(shù)據(jù)</td><td align="center" valign="middle" class="title_1">項(xiàng)目固定信息數(shù)據(jù)申報表</td><td align="center" valign="middle" class="title_1">項(xiàng)目按月信息數(shù)據(jù)申報表</td><td align="center" valign="middle" class="title_1">施工企業(yè)報送數(shù)據(jù)申報表</td></tr><%=this.Output%></tbody></table><script type="text/javascript" language="JavaScript">function a() {alert("項(xiàng)目固定信息數(shù)據(jù)申報表,錯誤,請修改!");TopView();}function TopView(){top.ymPrompt.close();top.ymPrompt.win({ message: '<div style="width:900px;height:550px;overflow-x: scroll;overflow-y: scroll;"><iframe id="MenuFrame" src="Fdc/AysbMx.aspx" height="100%" width="100%" frameborder="0" ></iframe></div>', width: 905, height: 580, title: "項(xiàng)目固定信息數(shù)據(jù)申報表", iframe: false, closeBtn: true, dragOut: false }); }<!-- var Ptr=document.getElementById("tab").getElementsByTagName("tr"); function $() {for (i=1;i<Ptr.length+1;i++) { Ptr[i-1].className = (i%2>0)?"t1":"t2"; } } window.onload=$; for(var i=0;i<Ptr.length;i++) {Ptr[i].onmouseover=function(){this.tmpClass=this.className;this.className = "t3";};Ptr[i].onmouseout=function(){this.className=this.tmpClass;}; } //--></script> </body> </html> View Code?什么時候用aspx ?是時候用ashx(一般處理程序)
建議:
如果有復(fù)雜的界面布局用aspx
如果沒有布局例如刪除,用ashx,或者返回json數(shù)據(jù)
15、
如果往本頁即post又get請求,可以在form里放一個隱藏域(input)
如果有?runat="server" 就自動添加隱藏域,判斷的時候 直接判斷if(isPostBack)就可以了
<body><form id="form1" runat="server"><div>用戶名:<input type="text" name="txtName" /><br />密碼:<input type="password" name="txtPwd" /><br />郵箱:<input type="text" name="txtMail" /><br /><%-- <input type="hidden" name="isPostBack" value="aaa" />--%><input type="submit" value="添加用戶" /></div></form> </body> View Code?16、分頁
sql中的over函數(shù)和row_numbert()函數(shù)配合使用,可生成行號。可對某一列的值進(jìn)行排序,對于相同值的數(shù)據(jù)行進(jìn)行分組排序。
執(zhí)行語句:
select row_number() over(order by AID DESC) as rowid,* from bbdao
/// <summary>/// 根據(jù)指定的范圍,獲取指定的數(shù)據(jù)/// </summary>/// <param name="start"></param>/// <param name="end"></param>/// <returns></returns>public List<UserInfo> GetPageList(int start,int end){string sql = "select * from(select *,row_number()over(order by id) as num from UserInfo) as t where t.num>=@start and t.num<=@end";SqlParameter[] pars = { new SqlParameter("@start",SqlDbType.Int),new SqlParameter("@end",SqlDbType.Int)};pars[0].Value = start;pars[1].Value = end;DataTable da=SqlHelper.GetDataTable(sql, CommandType.Text, pars);List<UserInfo> list = null;if (da.Rows.Count > 0){list = new List<UserInfo>();UserInfo userInfo = null;foreach (DataRow row in da.Rows){userInfo = new UserInfo();LoadEntity(userInfo, row);list.Add(userInfo);}}return list;}/// <summary>/// 獲取總的記錄數(shù)/// </summary>/// <returns></returns>public int GetRecordCount(){string sql = "select count(*) from UserInfo";return Convert.ToInt32(SqlHelper.ExecuteScalar(sql,CommandType.Text));}private void LoadEntity(UserInfo userInfo, DataRow row){userInfo.UserName = row["UserName"] != DBNull.Value ? row["UserName"].ToString() : string.Empty;userInfo.UserPass = row["UserPass"] != DBNull.Value ? row["UserPass"].ToString() : string.Empty;userInfo.Email = row["Email"] != DBNull.Value ? row["Email"].ToString() : string.Empty;userInfo.Id = Convert.ToInt32(row["ID"]);userInfo.RegTime = Convert.ToDateTime(row["RegTime"]);} View Codebll
/// <summary>/// 計算獲取數(shù)據(jù)的訪問,完成分頁/// </summary>/// <param name="pageIndex">當(dāng)前頁碼</param>/// <param name="pageSize">每頁顯示的記錄數(shù)據(jù)</param>/// <returns></returns>public List<UserInfo> GetPageList(int pageIndex,int pageSize){int start=(pageIndex-1)*pageSize+1;int end = pageIndex * pageSize;return UserInfoDal.GetPageList(start, end);}/// <summary>/// 獲取總的頁數(shù)/// </summary>/// <param name="pageSize">每頁顯示的記錄數(shù)</param>/// <returns></returns>public int GetPageCount(int pageSize){int recoredCount = UserInfoDal.GetRecordCount();//獲取總的記錄數(shù).int pageCount =Convert.ToInt32(Math.Ceiling((double)recoredCount / pageSize));return pageCount;} View Codeaspx
using CZBK.ItcastProject.Model; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Web; using System.Web.UI; using System.Web.UI.WebControls;namespace CZBK.ItcastProject.WebApp._2015_5_30 {public partial class NewList : System.Web.UI.Page{public string StrHtml { get; set; }public int PageIndex { get; set; }public int PageCount { get; set; }protected void Page_Load(object sender, EventArgs e){int pageSize=5;int pageIndex;if(!int.TryParse(Request.QueryString["pageIndex"],out pageIndex)){pageIndex=1;}BLL.UserInfoService UserInfoService = new BLL.UserInfoService();int pagecount = UserInfoService.GetPageCount(pageSize);//獲取總頁數(shù)PageCount = pagecount;//對當(dāng)前頁碼值范圍進(jìn)行判斷pageIndex = pageIndex < 1 ? 1 : pageIndex;pageIndex = pageIndex > pagecount ? pagecount : pageIndex;PageIndex = pageIndex;List<UserInfo>list= UserInfoService.GetPageList(pageIndex,pageSize);//獲取分頁數(shù)據(jù)StringBuilder sb = new StringBuilder();foreach (UserInfo userInfo in list){sb.AppendFormat("<li><span>{0}</span><a href='#' target='_blank'>{1}</a></li>",userInfo.RegTime.ToShortDateString(),userInfo.UserName);}StrHtml = sb.ToString();}} } View CodepagebarHelper
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks;namespace Common {public class PageBarHelper{public static string GetPagaBar(int pageIndex, int pageCount){if (pageCount == 1){return string.Empty;}int start = pageIndex - 5;//計算起始位置.要求頁面上顯示10個數(shù)字頁碼.if (start < 1){start = 1;}int end = start + 9;//計算終止位置.if (end > pageCount){end = pageCount;//重新計算一下Start值.start = end - 9 < 1 ? 1 : end - 9;}StringBuilder sb = new StringBuilder();if (pageIndex > 1){sb.AppendFormat("<a href='?pageIndex={0}' class='myPageBar'>上一頁</a>", pageIndex - 1);}for (int i = start; i <= end; i++){if (i == pageIndex){sb.Append(i);}else{sb.AppendFormat("<a href='?pageIndex={0}' class='myPageBar'>{0}</a>",i);}}if (pageIndex < pageCount){sb.AppendFormat("<a href='?pageIndex={0}' class='myPageBar'>下一頁</a>", pageIndex + 1);}return sb.ToString();}} } View Code <%=Common.PageBarHelper.GetPagaBar(PageIndex,PageCount)%>?
?17、http協(xié)議?request?response?server成員
http協(xié)議 超文本傳輸協(xié)議 包括請求響應(yīng)報文? 請求報文包括請求頭 請求內(nèi)容
request 成員
Files 接受文件 Request.Files["FileName"]
UrlReferrer 請求的來源
Url 請求的網(wǎng)址
UserHostAddress 訪問者IP
Cookie 瀏覽器Cookie
MapPath 虛擬路徑轉(zhuǎn)物理路徑 ../2016/hello.aspx -->E:\web\2016\hello.aspx
?
response 成員
Flush() 將緩沖區(qū)中的數(shù)據(jù)發(fā)送給用戶
Clear() 清空緩沖區(qū)
ContentEncoding 輸出流的編碼
ContentType 輸出流的內(nèi)容類型 HTML(text/html) ?普通文本(text/plain) ?jpeg (image/JPEG)?
server成員
Server.Transfer("Child.aspx")?
Server.Execute("Child.aspx");
這兩個是一樣的 都是在后臺訪問其他的頁面 達(dá)到ifram的效果
與Response.Redirect的區(qū)別。Transfer:服務(wù)端跳轉(zhuǎn),不會向?yàn)g覽器返回任何內(nèi)容,所以地址欄中的URL地址不變。
Server.HtmlEncode("<font color='red'></font>")
?
18、XSS跨站攻擊
比如評論的時候,沒有編碼,別人寫了JavaScript代碼,直接可以跳轉(zhuǎn)到別的網(wǎng)站
注釋
服務(wù)器注釋 不會顯示到HTML <%--這是注釋內(nèi)容--%>
顯示到HTML里 <!--這是注釋內(nèi)容-->
?
19、viewstate
當(dāng)我們在寫一個asp.net表單時, 一旦標(biāo)明了 form runat=server ,那么,asp.net就會自動在輸出時給頁面添加一個隱藏域
<input?type="hidden"?name="__VIEWSTATE"?value=""> MVC中沒有 viewstate賦值 using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls;namespace CZBK.ItcastProject.WebApp._2015_5_30 {public partial class ViewStateDemo : System.Web.UI.Page{public int Count { get; set; }protected void Page_Load(object sender, EventArgs e){int count = 0;if (ViewState["count"] != null){count = Convert.ToInt32(ViewState["count"]);count++;Count = count;}ViewState["count"] = Count;//當(dāng)我們把數(shù)據(jù)給了ViewState對象以后,該對象會將數(shù)據(jù)進(jìn)行編碼,然后存到__VIEWSTATE隱藏域中,然后返回給瀏覽器。//當(dāng)用戶通過瀏覽器單擊“提交”按鈕,會向服務(wù)端發(fā)送一個POST請求那么__VIEWSTATE隱藏域的值也會提交到服務(wù)端,那么服務(wù)端自動接收__VIEWSTATE隱藏域的值,并且再反編碼,重新賦值給ViewState對象。 }} } View Code <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ViewStateDemo.aspx.cs" Inherits="CZBK.ItcastProject.WebApp._2015_5_30.ViewStateDemo" %><!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/><title></title> </head> <body><form id="form1" runat="server"><div><span><%=Count%></span><input type="submit" value="計算" /></div></form> </body> </html> View Code?
20、cookie
存在瀏覽器中 ?指定時間:存在硬盤中,關(guān)閉瀏覽器也會存在,不指定時間存在瀏覽器內(nèi)存中,關(guān)閉就沒了?
21、session
瀏覽器關(guān)閉就不見了 ?因?yàn)镮D是一cookie的形式存在瀏覽器之前傳送,沒有指定過期時間,存在瀏覽器內(nèi)存中
22、page_init()?
和page_Load()一樣都是自動執(zhí)行,不過這個在page_Load之前執(zhí)行
統(tǒng)一的驗(yàn)證:寫一個pagebase繼承system.web.UI.page ?然后在Page_Init()方法里寫驗(yàn)證
23、自動登錄實(shí)現(xiàn)原理
如果勾選了自動登錄,把用戶名和密碼存在cookie中 記得加密,下次登錄的時候直接進(jìn)入get請求,給session賦值
http://www.liaoxuefeng.com/article/00146129217054923f7784c57134669986a8875c10e135e000 using CZBK.ItcastProject.Model; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls;namespace CZBK.ItcastProject.WebApp._2015_5_31 {public partial class UserLogin : System.Web.UI.Page{public string Msg { get; set; }public string UserName { get; set; }protected void Page_Load(object sender, EventArgs e){if (IsPostBack){//string userName = Request.Form["txtName"];//UserName = userName;if (CheckValidateCode())//先判斷驗(yàn)證碼是否正確. {CheckUserInfo();}else{//驗(yàn)證碼錯誤Msg = "驗(yàn)證碼錯誤!!";}}else{//判斷Cookie中的值。自動登錄 CheckCookieInfo();}}#region 判斷用戶名密碼是否正確protected void CheckUserInfo(){//獲取用戶輸入的用戶名和密碼.string userName = Request.Form["txtName"];UserName = userName;string userPwd = Request.Form["txtPwd"];//校驗(yàn)用戶名密碼.BLL.UserInfoService UserInfoService = new BLL.UserInfoService();string msg = string.Empty;UserInfo userInfo = null;//判斷用戶名與密碼if (UserInfoService.ValidateUserInfo(userName, userPwd, out msg, out userInfo)){//判斷用戶是否選擇了“自動登錄”if (!string.IsNullOrEmpty(Request.Form["autoLogin"]))//頁面上如果有多個復(fù)選框時,只能將選中復(fù)選框的的值提交到服務(wù)端。 {HttpCookie cookie1 = new HttpCookie("cp1",userName);HttpCookie cookie2 = new HttpCookie("cp2", Common.WebCommon.GetMd5String(Common.WebCommon.GetMd5String(userPwd)));cookie1.Expires = DateTime.Now.AddDays(7);cookie2.Expires = DateTime.Now.AddDays(7);Response.Cookies.Add(cookie1);Response.Cookies.Add(cookie2);}Session["userInfo"] = userInfo;Response.Redirect("UserInfoList.aspx");}else{Msg = msg;}}#endregion#region 校驗(yàn)Cookie信息.protected void CheckCookieInfo(){if (Request.Cookies["cp1"] != null && Request.Cookies["cp2"] != null){string userName = Request.Cookies["cp1"].Value;string userPwd = Request.Cookies["cp2"].Value;//校驗(yàn)BLL.UserInfoService UserInfoService = new BLL.UserInfoService();UserInfo userInfo=UserInfoService.GetUserInfo(userName);if (userInfo != null){//注意:在添加用戶或注冊用戶時一定要將用戶輸入的密碼加密以后在存儲到數(shù)據(jù)庫中。if (userPwd == Common.WebCommon.GetMd5String(Common.WebCommon.GetMd5String(userInfo.UserPass))){Session["userInfo"] = userInfo;Response.Redirect("UserInfoList.aspx");}}Response.Cookies["cp1"].Expires = DateTime.Now.AddDays(-1);Response.Cookies["cp2"].Expires = DateTime.Now.AddDays(-1);}}#endregion#region 判斷驗(yàn)證碼是否正確protected bool CheckValidateCode(){bool isSucess = false;if (Session["validateCode"] != null)//在使用Session時一定要校驗(yàn)是否為空 {string txtCode = Request.Form["txtCode"];//獲取用戶輸入的驗(yàn)證碼。string sysCode = Session["validateCode"].ToString();if (sysCode.Equals(txtCode, StringComparison.InvariantCultureIgnoreCase)){isSucess = true;Session["validateCode"] = null;}}return isSucess;}#endregion} } View Code?24、request[""] 自動識別post get
POST GET:context.request["name"] ?post:context.request.form["name"] ?get:context.request.Querystring["name"] ?
?25、手寫異步請求
<script type="text/javascript">$(function () {$("#btnGetDate").click(function () {//開始通過AJAX向服務(wù)器發(fā)送請求.var xhr;if (XMLHttpRequest) {//表示用戶使用的高版本IE,谷歌,狐火等瀏覽器xhr = new XMLHttpRequest();} else {// 低IExhr=new ActiveXObject("Microsoft.XMLHTTP");}xhr.open("get", "GetDate.ashx?name=zhangsan&age=12", true);xhr.send();//開始發(fā)送//回調(diào)函數(shù):當(dāng)服務(wù)器將數(shù)據(jù)返回給瀏覽器后,自動調(diào)用該方法。xhr.onreadystatechange = function () {if (xhr.readyState == 4) {//表示服務(wù)端已經(jīng)將數(shù)據(jù)完整返回,并且瀏覽器全部接受完畢。if (xhr.status == 200) {//判斷響應(yīng)狀態(tài)碼是否為200. alert(xhr.responseText);}}}});});</script> View Code <script src="../Js/jquery-1.7.1.js"></script><script type="text/javascript">$(function () {$("#btnPost").click(function () {var xhr;if (XMLHttpRequest) {xhr = new XMLHttpRequest();} else {xhr = new ActiveXObject("Microsoft.XMLHTTP");}xhr.open("post", "GetDate.ashx", true);xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");xhr.send("name=zhangsan&pwd=123");xhr.onreadystatechange = function () {if (xhr.readyState == 4) {if (xhr.status == 200) {alert(xhr.responseText);}}}});});</script> View Code26、統(tǒng)一布局
webform:ifram 母版頁 (或者用第三方框架如fineUI) VTemplate模板 ?MVC:razor視圖?
27、緩存cache
和session的區(qū)別
每個用戶都有自己單獨(dú)的session
但是cache的數(shù)據(jù)是大家共享的
?
相同:都放在服務(wù)器內(nèi)存中
using CZBK.ItcastProject.Model; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Caching; using System.Web.UI; using System.Web.UI.WebControls;namespace CZBK.ItcastProject.WebApp._2015_6_6 {public partial class CacheDemo : System.Web.UI.Page{protected void Page_Load(object sender, EventArgs e){//判斷緩存中是否有數(shù)據(jù).if (Cache["userInfoList"] == null){BLL.UserInfoService UserInfoService = new BLL.UserInfoService();List<UserInfo> list = UserInfoService.GetList();//將數(shù)據(jù)放到緩存中。// Cache["userInfoList"] = list;//第二種賦值方式Cache.Insert("userInfoList", list);//賦值的重載方法 可以指定緩存時間//不推薦用這么多參數(shù)的重載,這里只是介紹一下,緩存依賴性什么的完全沒必要,在數(shù)據(jù)庫插入的時候做一下操作就可以了 Cache.Insert("userInfoList", list, null, DateTime.Now.AddSeconds(5), TimeSpan.Zero, System.Web.Caching.CacheItemPriority.Normal, RemoveCache);Response.Write("數(shù)據(jù)來自數(shù)據(jù)庫");//Cache.Remove("userInfoList");//移除緩存 }else{List<UserInfo> list = (List<UserInfo>)Cache["userInfoList"];Response.Write("數(shù)據(jù)來自緩存");}}protected void RemoveCache(string key, object value, CacheItemRemovedReason reason){if (reason == CacheItemRemovedReason.Expired){//緩存移除的原因?qū)懙饺罩局小?/span> }}} } View Code文件緩存依賴項(xiàng)
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Web; using System.Web.Caching; using System.Web.UI; using System.Web.UI.WebControls;namespace CZBK.ItcastProject.WebApp._2015_6_6 {public partial class FileCacheDep : System.Web.UI.Page{protected void Page_Load(object sender, EventArgs e){string filePath = Request.MapPath("File.txt");if (Cache["fileContent"] == null){//文件緩存依賴.CacheDependency cDep = new CacheDependency(filePath);string fileContent = File.ReadAllText(filePath);Cache.Insert("fileContent", fileContent, cDep);Response.Write("數(shù)據(jù)來自文件");}else{Response.Write("數(shù)據(jù)來自緩存:"+Cache["fileContent"].ToString());}}} } View Code?http://www.cnblogs.com/xiaoshi657/p/5570705.html
?28、頁面緩存
webform
在頁面加<%@ OutputCache Duration="5" VaryByParam="*"%> 就可以了,如果有參數(shù)VaryByParam="id" 兩個參數(shù)VaryByParam="id;type" ?所有參數(shù)VaryByParam="*"
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ShOWDetail.aspx.cs" Inherits="CZBK.ItcastProject.WebApp._2015_6_6.ShOWDetail" %> <%@ OutputCache Duration="5" VaryByParam="*"%> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/><title></title> </head> <body><form id="form1" runat="server"><div><asp:DetailsView ID="DetailsView1" runat="server" Height="50px" Width="125px"></asp:DetailsView></div></form> </body> </html> View Code?MVC
在MVC中要如果要啟用頁面緩存,在頁面對應(yīng)的Action前面加上一個OutputCache屬性即可。
[HandleError] public class HomeController : Controller { [OutputCache(Duration = 5, VaryByParam = "none")] public ActionResult Index() { return View(); } } View Code?
http://www.cnblogs.com/iamlilinfeng/p/4419362.html#t5
29、session分布式存儲方案
其他機(jī)器:session狀態(tài)服務(wù)器,單獨(dú)一臺機(jī)器,專門記錄所有機(jī)器的session狀態(tài)
數(shù)據(jù)庫
上面兩個性能太低,微軟給的解決方案,不推薦用。建議用memcache,redis
30、錯誤頁面配置
mode 值
?On 指定啟用自定義錯誤。如果沒有指定 defaultRedirect,用戶將看到一般性錯誤。
Off 指定禁用自定義錯誤。這允許顯示詳細(xì)的錯誤。
?RemoteOnly 指定僅向遠(yuǎn)程客戶端端顯示自定義錯誤,并向本地主機(jī)顯示 ASP.NET 錯誤。這是默認(rèn)值。
?ps:iis中有一錯誤頁面 選項(xiàng) 也需要配置一下
31、隊(duì)列寫在內(nèi)存中
new線程 ?比去線程池中取線程效率低很多
線程池的線程是自動創(chuàng)建的,我們控制不了,如果想控制線程就要自己new了
?全部代碼
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms;namespace WindowsFormsApplication1 {public partial class Form1 : Form{private static readonly object obj = new object();public Form1(){InitializeComponent();TextBox.CheckForIllegalCrossThreadCalls = false;}/// <summary>/// 單線程:當(dāng)程序執(zhí)行時,有一個線程負(fù)責(zé)執(zhí)行該代碼,沒有辦法與用戶進(jìn)行其它的交互,所以窗體界面卡死了。(與窗體界面交互的線程叫UI線程。)/// </summary>/// <param name="sender"></param>/// <param name="e"></param>private void button1_Click(object sender, EventArgs e){int a = 0;for (int i = 0; i < 999999999; i++){a = i;}MessageBox.Show(a.ToString());}/// <summary>/// 將計算的任務(wù)交給另外一個線程來執(zhí)行,UI線程還是負(fù)責(zé)與用戶進(jìn)行打交道。默認(rèn)情況線程所執(zhí)行的任務(wù)完成了,該線程也就終止了。/// </summary>/// <param name="sender"></param>/// <param name="e"></param>//bool isStop = true;//推薦使用這種方式結(jié)束線程,不是thread.Abort()private void button2_Click(object sender, EventArgs e){ThreadStart threadStart=new ThreadStart(StartCacul);Thread thread = new Thread(threadStart);// thread.Priority = ThreadPriority.Normal;//建議.// thread.Name = "shit";//thread.Abort();//強(qiáng)制終止線程。盡量不要該方法// thread.Join(1000);//主線程會阻塞(睡眠、等待1000毫秒)等待 thread.Start();//將該線程標(biāo)記可運(yùn)行狀態(tài)。 }private void StartCacul(){// while (isStop)//推薦使用這種方式結(jié)束線程,不是thread.Abort()//{int a = 0;for (int i = 0; i < 999999999; i++){a = i;}// MessageBox.Show(a.ToString());this.txtNum.Text = a.ToString();//} }/// <summary>/// 后臺線程:當(dāng)窗體關(guān)閉該線程也就結(jié)束了。/// </summary>/// <param name="sender"></param>/// <param name="e"></param>private void button3_Click(object sender, EventArgs e){Thread thread1 = new Thread(StartCacul);thread1.IsBackground = true;thread1.Start();}/// <summary>/// 委托調(diào)用帶參數(shù)的方法/// </summary>/// <param name="sender"></param>/// <param name="e"></param>private void button4_Click(object sender, EventArgs e){List<int> list = new List<int>() {1,2,3,4,5 };ParameterizedThreadStart paramThread = newParameterizedThreadStart(ShowList);Thread thread2 = new Thread(paramThread);thread2.IsBackground = true;thread2.Start(list);//傳遞參數(shù) }private void ShowList(object obj){List<int> list = (List<int>)obj;foreach (int i in list){MessageBox.Show(i.ToString());}}/// <summary>/// 解決跨線程訪問。/// </summary>/// <param name="sender"></param>/// <param name="e"></param>private void button5_Click(object sender, EventArgs e){Thread thread3 = new Thread(ShowStartCacul);thread3.IsBackground = true;thread3.Start();}private void ShowStartCacul(){int a = 0;for (int i = 0; i < 999999999; i++){a = i;}if (this.txtNum.InvokeRequired)//解決跨線程訪問。如果該條件成立表示跨線程訪問. {//Invoke:找到最終創(chuàng)建文本框的線程,然后有該線程為文本框賦值。this.txtNum.Invoke(new Action<TextBox, string>(SetValue), this.txtNum, a.ToString());}}private void SetValue(TextBox txt,string value){txt.Text = value;}/// <summary>/// 線程同步:當(dāng)多個線程同時在操作同一個資源時,會出現(xiàn)并發(fā)問題(例如操作文件)。這是可以加鎖。/// </summary>/// <param name="sender"></param>/// <param name="e"></param>private void button6_Click(object sender, EventArgs e){Thread t1 = new Thread(SetTextValue);t1.IsBackground = true;t1.Start();Thread t2 = new Thread(SetTextValue);t2.IsBackground = true;t2.Start();}private void SetTextValue(){lock (obj){//執(zhí)行操作。寫文件。for (int i = 0; i <=2000; i++){int a = Convert.ToInt32(this.txtNum.Text);a++;this.txtNum.Text = a.ToString();}}}} } View Code?
32、HttpModule ?
創(chuàng)建httpapplacation之后 會遍歷所有的httpmodule ?包括web.config中配置的
https://www.cnblogs.com/xiaoshi657/p/6529777.html
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Web;namespace CZBK.ItcastProject.Common {//過濾器。public class CheckSessionModule:IHttpModule{public void Dispose(){throw new NotImplementedException();}public void Init(HttpApplication context){//URL重寫。// context.AcquireRequestState+=context_AcquireRequestState; }public void context_AcquireRequestState(object sender, EventArgs e){//判斷Session是否有值.HttpApplication application = (HttpApplication)sender;HttpContext context = application.Context;string url = context.Request.Url.ToString();//獲取用戶請求的URL地址.if (url.Contains("AdminManger"))//網(wǎng)站程序所有的后臺頁面都放在該文件夾中。 {if (context.Session["userInfo"] == null){context.Response.Redirect("/2015-02-27/Login.aspx");}}}} } View Code33、Global
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Security; using System.Web.SessionState;namespace CZBK.ItcastProject.WebApp {public class Global : System.Web.HttpApplication{/// <summary>/// 整個WEB應(yīng)用程序的入口。相當(dāng)于Main函數(shù).該方法只執(zhí)行一次,當(dāng)WEB應(yīng)用程序第一次啟動時,執(zhí)行該方法,后續(xù)請求其它頁面該方法不在執(zhí)行。該方法中一般完成對整個網(wǎng)站的初始化。/// </summary>/// <param name="sender"></param>/// <param name="e"></param>protected void Application_Start(object sender, EventArgs e){//這個只執(zhí)行一次,其他的是用戶請求一次執(zhí)行一次,這個和用戶請求無關(guān),只有服務(wù)器上網(wǎng)站啟動的時候,初始化啟動 }/// <summary>/// 開啟會話的時候執(zhí)行該方法。/// </summary>/// <param name="sender"></param>/// <param name="e"></param>protected void Session_Start(object sender, EventArgs e){//統(tǒng)計訪問人數(shù).//訪問人數(shù)+1.//Application:服務(wù)端狀態(tài)保持機(jī)制,并且放在該對象中的數(shù)據(jù)大家共享的。使用該對象時必須加鎖。 Application.Lock();if (Application["count"] != null){int count = Convert.ToInt32(Application["count"]);count++;Application["count"] = count;//向永久保存訪客人數(shù)必須將該數(shù)據(jù)存儲到文件或數(shù)據(jù)庫中。 }else{Application["count"] = 1;}Application.UnLock();}protected void Application_BeginRequest(object sender, EventArgs e){}protected void Application_AuthenticateRequest(object sender, EventArgs e){}/// <summary>/// 注意的方法。該方法會捕獲程序中(所有)沒有處理的異常。并且將捕獲的異常信息寫到日志中。/// </summary>/// <param name="sender"></param>/// <param name="e"></param>protected void Application_Error(object sender, EventArgs e){HttpContext.Current.Server.GetLastError();//捕獲異常信息.//將捕獲的異常信息寫到日志中。 }/// <summary>/// 會話結(jié)束的時候執(zhí)行該方法。/// </summary>/// <param name="sender"></param>/// <param name="e"></param>protected void Session_End(object sender, EventArgs e){//不是實(shí)時的,和session的默認(rèn)有效期是20分鐘有關(guān) }/// <summary>/// 整個應(yīng)用程序結(jié)束的時候執(zhí)行。/// </summary>/// <param name="sender"></param>/// <param name="e"></param>protected void Application_End(object sender, EventArgs e){}} } View Code?34、進(jìn)程
//獲取所有的進(jìn)程的信息//Process[] ps=Process.GetProcesses();//foreach (Process p in ps)//{// //p.Kill();// Console.WriteLine(p.ProcessName);//}//獲取當(dāng)前進(jìn)程//Process p= Process.GetCurrentProcess();//獲取當(dāng)前的進(jìn)程//Console.WriteLine(p.ProcessName);//啟動別的進(jìn)程//Process.Start("notepad.exe");//flv. ffmpeg.exe//很好的視頻轉(zhuǎn)換工具//視頻轉(zhuǎn)碼解決方案,用戶傳到服務(wù)器,通過進(jìn)行啟動第三方軟件(如:ffmpeg.exe)進(jìn)行轉(zhuǎn)換 View Code?35、線程
/// <summary>/// 將計算的任務(wù)交給另外一個線程來執(zhí)行,UI線程還是負(fù)責(zé)與用戶進(jìn)行打交道。默認(rèn)情況線程所執(zhí)行的任務(wù)完成了,該線程也就終止了。/// </summary>/// <param name="sender"></param>/// <param name="e"></param>//bool isStop = true;//推薦使用這種方式結(jié)束線程,不是thread.Abort()private void button2_Click(object sender, EventArgs e){ThreadStart threadStart=new ThreadStart(StartCacul);Thread thread = new Thread(threadStart);// thread.Priority = ThreadPriority.Normal;//建議.// thread.Name = "shit";//thread.Abort();//強(qiáng)制終止線程。盡量不要該方法// thread.Join(1000);//主線程會阻塞(睡眠、等待1000毫秒)等待 thread.Start();//將該線程標(biāo)記可運(yùn)行狀態(tài)。 }private void StartCacul(){// while (isStop)//推薦使用這種方式結(jié)束線程,不是thread.Abort()//{int a = 0;for (int i = 0; i < 999999999; i++){a = i;}// MessageBox.Show(a.ToString());this.txtNum.Text = a.ToString();//} } View Code?
/// <summary>/// 后臺線程:當(dāng)窗體關(guān)閉該線程也就結(jié)束了。/// </summary>/// <param name="sender"></param>/// <param name="e"></param>private void button3_Click(object sender, EventArgs e){Thread thread1 = new Thread(StartCacul);thread1.IsBackground = true;//這個值表示窗體關(guān)閉,線程就關(guān)閉 thread1.Start();} View Code?線程池:
using System; using System.Threading;namespace ThreadDemo {class program{static void Main(){int nWorkThreads;int nCompletionPortThreads;ThreadPool.GetMaxThreads(out nWorkThreads, out nCompletionPortThreads);Console.WriteLine("Max worker threads: {0}, I/O completion threads: {1}",nWorkThreads, nCompletionProtThreads);for(int i = 0; i < 5; i++){ThreadPool.QueueUserWorkItem(JobForAThread);}Thread.Sleep(3000);}static void JobForAThread(object state){for(int i = 0; i < 3; i++){Console.WriteLine("loop {0}, running inside pooled thread {1}", i, Thread.CurrentThread.ManagedThreadId);Thread.Sleep(50);}}} } View Code?
36、redis隊(duì)列
剛剛百度了一下redis的隊(duì)列,大致應(yīng)該是兩個redis的方法
EnqueueItemOnList 將一個元素存入指定ListId的List<T>的頭部
DequeueItemFromList 將指定ListId的List<T>末尾的那個元素出列,返回出列元素
應(yīng)用:
public class MyExceptionFilterAttribute : HandleErrorAttribute{//版本2:使用Redis的客戶端管理器(對象池)public static IRedisClientsManager redisClientManager = new PooledRedisClientManager(new string[] {//如果是Redis集群則配置多個{IP地址:端口號}即可//例如: "10.0.0.1:6379","10.0.0.2:6379","10.0.0.3:6379""127.0.0.1:6379"});//從池中獲取Redis客戶端實(shí)例public static IRedisClient redisClient = redisClientManager.GetClient();public override void OnException(ExceptionContext filterContext){//將異常信息入隊(duì)redisClient.EnqueueItemOnList("ExceptionLog", filterContext.Exception.ToString());//跳轉(zhuǎn)到自定義錯誤頁filterContext.HttpContext.Response.Redirect("~/Common/CommonError.html");base.OnException(filterContext);}} View Codehttp://www.cnblogs.com/edisonchou/p/3825682.html
ps:log4net 早期版本不支持多線程?log4net 1.2.11版本以上支持
37、application19事件
38、lenght
循環(huán)的時候 盡量放在外面 ?否者每次循環(huán)都計算一次 ?不能for(int i=0,i<a.lenght,i++){}
39、反編譯軟件 reflector??IL Spy
40、判斷字符串中是否存在某段字符
indexOf?Contains
41、去掉最后一個逗號
RegionsStr = RegionsStr.Remove(RegionsStr.LastIndexOf(","), 1); //去掉最后一個逗號42、讀取xml
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Web; using System.Xml; using WebCenter.Model;namespace WebCenter.Service {/// <summary>/// Index 的摘要說明/// </summary>public class Index : IHttpHandler{protected readonly string CityIpConfigXMLPath = System.Web.HttpContext.Current.Server.MapPath("/config/CityIpConfigXML.xml");public void ProcessRequest(HttpContext context){string _province = context.Request.QueryString["_province"];string _city = context.Request.QueryString["_city"];City city = GetSkipCity(_province, _city);context.Response.ContentType = "text/plain";context.Response.Write("{status:'200',data:" + JsonConvert.SerializeObject(city) + "}");}/// <summary>/// 根據(jù)當(dāng)前登錄的IP的省份和城市,返回要跳轉(zhuǎn)的城市/// </summary>/// <param name="ProvinceName">省份</param>/// <param name="CityName">城市</param>/// <returns></returns>public City GetSkipCity(string ProvinceName, string CityName){City citymodel=null;string SkipCityName = string.Empty;XmlDocument xd = new XmlDocument();xd.Load(CityIpConfigXMLPath);//獲取根節(jié)點(diǎn)XmlNode root = xd.DocumentElement;//獲取節(jié)點(diǎn)列表XmlNodeList ProvinceList = root.ChildNodes;foreach (XmlNode Province in ProvinceList){if (ProvinceName == Province.Attributes["ProvinceName"].Value.ToString()){foreach (XmlNode city in Province){if (CityName == city.Attributes["CityName"].Value.ToString()){citymodel = new City();citymodel.CityCode = city.Attributes["CityCode"].Value.ToString();citymodel.CityName = city.Attributes["SkipCity"].Value.ToString();citymodel.CityID = city.Attributes["CityValue"].Value.ToString();citymodel.CitySkipUrl = city.Attributes["CitySkipUrl"].Value.ToString();return citymodel;}}if (citymodel==null){foreach (XmlNode province in Province){if (province.Attributes["CityName"].Value.ToString() == "其他"){citymodel = new City();citymodel.CityCode = province.Attributes["CityCode"].Value.ToString();citymodel.CityName = province.Attributes["SkipCity"].Value.ToString();citymodel.CityID = province.Attributes["CityValue"].Value.ToString();citymodel.CitySkipUrl = province.Attributes["CitySkipUrl"].Value.ToString();return citymodel;}}}}}if (citymodel==null){foreach (XmlNode province in ProvinceList){if (province.Attributes["ProvinceName"].Value.ToString() == "其他"){citymodel = new City();citymodel.CityName = province.Attributes["SkipDafualt"].Value.ToString();citymodel.CitySkipUrl = province.Attributes["CitySkipUrl"].Value.ToString();return citymodel;}}}return citymodel;}public bool IsReusable{get{return false;}}} } View Code <?xml version="1.0" encoding="utf-8" ?> <CityIpConfig><ProvinceIp ProvinceName="北京"><CityIp CityName="北京" SkipCity="北京" CityCode="" CityValue="" CitySkipUrl="http://webbj.imtfc.com/Index.html" ></CityIp></ProvinceIp><ProvinceIp ProvinceName="福建"><CityIp CityName="廈門" SkipCity="廈門" CityCode="XM" CityValue="4" CitySkipUrl="http://webcenter.imtfc.com/WebConstruction.html" >"</CityIp><CityIp CityName="福州" SkipCity="福州" CityCode="FZ" CityValue="3" CitySkipUrl="http://webcenter.imtfc.com/WebConstruction.html" ></CityIp><CityIp CityName="龍巖" SkipCity="廈門" CityCode="XM" CityValue="4" CitySkipUrl="http://webcenter.imtfc.com/WebConstruction.html" ></CityIp><CityIp CityName="泉州" SkipCity="廈門" CityCode="XM" CityValue="4" CitySkipUrl="http://webcenter.imtfc.com/WebConstruction.html" ></CityIp><CityIp CityName="其他" SkipCity="福州" CityCode="FZ" CityValue="3" CitySkipUrl="http://webcenter.imtfc.com/WebConstruction.html" ></CityIp></ProvinceIp><ProvinceIp ProvinceName="其他" SkipDafualt="北京" CitySkipUrl="http://webbj.imtfc.com/Index.html"></ProvinceIp> </CityIpConfig> View Code?
43、list取隨機(jī)
Random rd = new Random();List<string> liststr = new List<string>();liststr.Add("aaa");liststr.Add("bbb");liststr.Add("ccc");liststr.Add("111");liststr.Add("222");liststr.Add("333");//隨機(jī)一個var s = liststr.OrderBy(_ => Guid.NewGuid()).First();//隨機(jī)兩個var ss = liststr.OrderBy(_ => Guid.NewGuid()).Take(2);//亂序var sss = liststr.OrderBy(o => rd.Next(0, liststr.Count())).ToList(); View Code?
?
?
?
2、C#讀取web.config文件信息
web.config
<?xml version="1.0"?> <!--有關(guān)如何配置 ASP.NET 應(yīng)用程序的詳細(xì)信息,請?jiān)L問http://go.microsoft.com/fwlink/?LinkId=169433--> <configuration><appSettings><add key="name" value="name1"/></appSettings> </configuration>C#讀取
string name = System.Web.Configuration.WebConfigurationManager.AppSettings["name"];System.Configuration.ConfigurationManager.AppSettings["SqlConnectionStr"];?
C#設(shè)置
System.Web.Configuration.WebConfigurationManager.AppSettings.Set("name", "name2");1、常用技術(shù)、框架?
首先C#基礎(chǔ)應(yīng)該熟悉,不要把暫時用不到而卻常用的東西忘掉。
數(shù)據(jù)庫
應(yīng)該掌握oracle,畢竟工作這么多年一直用的oracle
MSSQL、SQLServer了解即可,畢竟SQL相似度很高。
C#開發(fā)框架:
MVC ?EF ?三層
第三方組件
Log4net ?日志
json.net ?json轉(zhuǎn)換
Npoi ? ? office處理
前臺web框架
easyUI ? js前端框架
bootstrap ?很好的
LigerUI
extjs
?
控件、技術(shù)
ECharts 圖標(biāo) 大文件上傳
有時間可以了解一下安卓開發(fā),U3D開發(fā)。
先整理這些,以后想起來什么再寫
Lucene.Net+盤古分詞?
?
高清楚 WEBAPI
?
T4 ?代碼生成器 ? ? powerde.. ?Npoi ? Log4
?
轉(zhuǎn)載于:https://www.cnblogs.com/xiaoshi657/p/5526345.html
總結(jié)
以上是生活随笔為你收集整理的【知识碎片】Asp.Net 篇的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Eclipse启动报错Java was
- 下一篇: mysql查看数据库命令