【知识碎片】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=mimaxxx;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>
读取:
string connString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString.ToString();
记得添加引用 using System.Configuration;
46、asp.net MVC 导出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("内容:" + item.Content.ToString() + "\n"); sb.Append("--------------------------------------------------\n\n"); } Response.Write(sb); Response.Flush(); Response.End(); return new EmptyResult(); }
//导出数据 function ExpData() { window.location.href = "/LogManager/ExpData"; //MySuccess("导出成功!"); };
44、动态解析二级域名
1、DomainRoute插件
2、global里URL重写
--------------------------------------------------------------------------------------------------------------------------
30、错误页面配置
mode 值
On 指定启用自定义错误。如果没有指定 defaultRedirect,用户将看到一般性错误。
Off 指定禁用自定义错误。这允许显示详细的错误。
RemoteOnly 指定仅向远程客户端端显示自定义错误,并向本地主机显示 ASP.NET 错误。这是默认值。
<configuration> <system.web> <customErrors mode="On" defaultRedirect="MyErrorPage.html"><!--默认错误页面--> <error statusCode="403" redirect="NoAccess.htm" /><!--个别错误指定错误页面--> <error statusCode="404" redirect="FileNotFound.html" /> </customErrors> </system.web> </configuration>
ps:iis中有一错误页面 选项 也需要配置一下
34、进程
//获取所有的进程的信息 //Process[] ps=Process.GetProcesses(); //foreach (Process p in ps) //{ // //p.Kill(); // Console.WriteLine(p.ProcessName); //} //获取当前进程 //Process p= Process.GetCurrentProcess();//获取当前的进程 //Console.WriteLine(p.ProcessName); //启动别的进程 //Process.Start("notepad.exe"); //flv. ffmpeg.exe//很好的视频转换工具 //视频转码解决方案,用户传到服务器,通过进行启动第三方软件(如:ffmpeg.exe)进行转换
35、线程
/// <summary> /// 将计算的任务交给另外一个线程来执行,UI线程还是负责与用户进行打交道。默认情况线程所执行的任务完成了,该线程也就终止了。 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> //bool isStop = true;//推荐使用这种方式结束线程,不是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();//强制终止线程。尽量不要该方法 // thread.Join(1000);//主线程会阻塞(睡眠、等待1000毫秒)等待 thread.Start();//将该线程标记可运行状态。 } private void StartCacul() { // while (isStop)//推荐使用这种方式结束线程,不是thread.Abort() //{ int a = 0; for (int i = 0; i < 999999999; i++) { a = i; } // MessageBox.Show(a.ToString()); this.txtNum.Text = a.ToString(); //} }
/// <summary> /// 后台线程:当窗体关闭该线程也就结束了。 /// </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(); }
线程池:
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); } } } }
36、redis队列
大致应该是两个redis的方法
EnqueueItemOnList 将一个元素存入指定ListId的List<T>的头部
DequeueItemFromList 将指定ListId的List<T>末尾的那个元素出列,返回出列元素
应用:
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客户端实例 public static IRedisClient redisClient = redisClientManager.GetClient(); public override void OnException(ExceptionContext filterContext) { //将异常信息入队 redisClient.EnqueueItemOnList("ExceptionLog", filterContext.Exception.ToString()); //跳转到自定义错误页 filterContext.HttpContext.Response.Redirect("~/Common/CommonError.html"); base.OnException(filterContext); } }
http://www.cnblogs.com/edisonchou/p/3825682.html
ps:log4net 早期版本不支持多线程 log4net 1.2.11版本以上支持
38、lenght
循环的时候 尽量放在外面 否者每次循环都计算一次 不能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> /// 根据当前登录的IP的省份和城市,返回要跳转的城市 /// </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); //获取根节点 XmlNode root = xd.DocumentElement; //获取节点列表 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; } } } }
<?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>
43、list取随机
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"); //随机一个 var s = liststr.OrderBy(_ => Guid.NewGuid()).First(); //随机两个 var ss = liststr.OrderBy(_ => Guid.NewGuid()).Take(2); //乱序 var sss = liststr.OrderBy(o => rd.Next(0, liststr.Count())).ToList();
2、C#读取web.config文件信息
web.config
<?xml version="1.0"?> <!-- 有关如何配置 ASP.NET 应用程序的详细信息,请访问 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#设置
System.Web.Configuration.WebConfigurationManager.AppSettings.Set("name", "name2");