118kjcom开奖现场常见.NET效用代码汇总,常见.NET功

作者:118kjcom开奖现场

常见.NET效能代码汇总

常见.NET效用代码汇总

23,获取和设置分级缓存

得到缓存:首先从地面缓存获取,若无,再去读取遍布式缓存
写缓存:同临时候写本地缓存和布满式缓存

  private static T GetGradeCache<T>(string key) where T:struct         {            MemoryCacheManager localCache = MemoryCacheManager.Instance;            if (!localCache.IsSet            {                //本地不存在此缓存               T  remoteValue = MemCacheManager.Instance.Get<T>;               if (!ValueType.Equals(remoteValue, default               {                     //如果远程有                   localCache.Set(key, remoteValue, 1);                }               else               {                   localCache.SetFromSeconds(key, default, 10);                }               return remoteValue;            }            T value = localCache.Get<T>;            return value;        }        private static void SetGradeCache<T>(string key,T Value,int time) where T : struct         {            MemoryCacheManager localCache = MemoryCacheManager.Instance;            localCache.Remove;            localCache.Set(key, Value, time);            MemCacheManager.Instance.Remove;            MemCacheManager.Instance.Set(key, Value, time);         }

23,获取和装置分级缓存

获取缓存:首先从地方缓存获取,若无,再去读取遍布式缓存
写缓存:同偶尔间写本地缓存和布满式缓存

  private static T GetGradeCache<T>(string key) where T:struct 
        {
            MemoryCacheManager localCache = MemoryCacheManager.Instance;
            if (!localCache.IsSet(key))
            {
                //本地不存在此缓存
               T  remoteValue = MemCacheManager.Instance.Get<T>(key);
               if (!ValueType.Equals(remoteValue, default(T)))
               { 
                    //如果远程有
                   localCache.Set(key, remoteValue, 1); 
               }
               else
               {
                   localCache.SetFromSeconds(key, default(T), 10); 
               }
               return remoteValue;
            }
            T value = localCache.Get<T>(key);
            return value;
        }

        private static void SetGradeCache<T>(string key,T Value,int time) where T : struct 
        {
            MemoryCacheManager localCache = MemoryCacheManager.Instance;
            localCache.Remove(key);
            localCache.Set(key, Value, time);
            MemCacheManager.Instance.Remove(key);
            MemCacheManager.Instance.Set(key, Value, time); 
        }

24,求相对目录的相对路线

有的时候,我们要求求绝对于近年来根目录的相对目录,比如将日志文件存款和储蓄在站点目录之外,我们得以利用 ../logs/ 的法子:

 string vfileName = string.Format("../logs/{0}_{1}_{2}.log", logFileName, System.Environment.MachineName, DateTime.Now.ToString("yyyyMMdd"));            string rootPath = HttpContext.Current.Server.MapPath("/");            string targetPath = System.IO.Path.Combine(rootPath, vfileName);            string fileName = System.IO.Path.GetFullPath(targetPath);            string fileDir = System.IO.Path.GetDirectoryName;            if (!System.IO.Directory.Exists                System.IO.Directory.CreateDirectory;

其一代码会在站点目录之外的日志目录,创立一个代机器名称的依据日期区分的日记文件。

24,求相对目录的相对路线

118kjcom开奖现场,有的时候,大家需须要相对于当下根目录的周旋目录,举例将日志文件存款和储蓄在站点目录之外,大家得以选拔../logs/ 的点子:

 string vfileName = string.Format("../logs/{0}_{1}_{2}.log", logFileName, System.Environment.MachineName, DateTime.Now.ToString("yyyyMMdd"));
            string rootPath = HttpContext.Current.Server.MapPath("/");
            string targetPath = System.IO.Path.Combine(rootPath, vfileName);
            string fileName = System.IO.Path.GetFullPath(targetPath);
            string fileDir = System.IO.Path.GetDirectoryName(fileName);
            if (!System.IO.Directory.Exists(fileDir))
                System.IO.Directory.CreateDirectory(fileDir);

以此代码会在站点目录之外的日记目录,建设构造一个代机器名称的遵照日期区分的日志文件。

25,数十次品尝写日记文件形式

日记文件大概会油然则生的写入,此时说不定会唤醒“文件被别的三个进度占用”,因而得以频仍尝试写入。上面包车型大巴方法会递归的张开文件写入尝试,借使尝试次数用完才会最终报错。

  /// <summary>        /// 保存日志文件        /// </summary>        /// <param name="logFileName">不带扩展名文件名</param>        /// <param name="logText">日志内容</param>        /// <param name="tryCount">如果出错的尝试次数,建议不大于100,如果是0则不尝试</param>        public static void SaveLog(string logFileName, string logText, int tryCount)        {            string vfileName = string.Format("..\logs\{0}_{1}_{2}.log", logFileName, System.Environment.MachineName, DateTime.Now.ToString("yyyyMMdd"));            string rootPath = System.AppDomain.CurrentDomain.BaseDirectory;            string targetPath = System.IO.Path.Combine(rootPath, vfileName);            string fileName = System.IO.Path.GetFullPath(targetPath);            string fileDir = System.IO.Path.GetDirectoryName;            if (!System.IO.Directory.Exists                System.IO.Directory.CreateDirectory;                        try            {                System.IO.File.AppendAllText(fileName, logText);                tryCount = 0;            }            catch (Exception ex)            {                if (tryCount > 0)                {                    System.Threading.Thread.Sleep(1000);                    logText = logText + "rnSaveLog,try again times =" + tryCount + " ,Error:" + ex.Message;                    tryCount--;                    SaveLog(logFileName, logText, tryCount);                }                else                {                    throw new Exception("Save log file Error,try count more times!");                }            }        }

25,多次品尝写日记文件措施

日志文件恐怕会并发的写入,此时说不定会提醒“文件被其余叁个历程占用”,因而能够每每品尝写入。上面包车型客车方法会递归的扩充文件写入尝试,假使尝试次数用完才会最终报错。

  /// <summary>
        /// 保存日志文件
        /// </summary>
        /// <param name="logFileName">不带扩展名文件名</param>
        /// <param name="logText">日志内容</param>
        /// <param name="tryCount">如果出错的尝试次数,建议不大于100,如果是0则不尝试</param>
        public static void SaveLog(string logFileName, string logText, int tryCount)
        {
            string vfileName = string.Format("..\logs\{0}_{1}_{2}.log", logFileName, System.Environment.MachineName, DateTime.Now.ToString("yyyyMMdd"));
            string rootPath = System.AppDomain.CurrentDomain.BaseDirectory;
            string targetPath = System.IO.Path.Combine(rootPath, vfileName);
            string fileName = System.IO.Path.GetFullPath(targetPath);
            string fileDir = System.IO.Path.GetDirectoryName(fileName);
            if (!System.IO.Directory.Exists(fileDir))
                System.IO.Directory.CreateDirectory(fileDir);

            try
            {
                System.IO.File.AppendAllText(fileName, logText);
                tryCount = 0;
            }
            catch (Exception ex)
            {
                if (tryCount > 0)
                {
                    System.Threading.Thread.Sleep(1000);
                    logText = logText + "rnSaveLog,try again times =" + tryCount + " ,Error:" + ex.Message;
                    tryCount--;
                    SaveLog(logFileName, logText, tryCount);
                }
                else
                {
                    throw new Exception("Save log file Error,try count more times!");
                }
            }
        }

26,ASP.NET获取顾客端的IP地址

      string GetRemoteIP()        {            string result = HttpContext.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];            if (null == result || result == String.Empty)            {                result = HttpContext.Request.ServerVariables["REMOTE_ADDR"];            }            if (null == result || result == String.Empty)            {                result = HttpContext.Request.UserHostAddress;            }            return result;

 26,ASP.NET获取顾客端的IP地址

      string GetRemoteIP()
        {
            string result = HttpContext.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
            if (null == result || result == String.Empty)
            {
                result = HttpContext.Request.ServerVariables["REMOTE_ADDR"];
            }


            if (null == result || result == String.Empty)
            {
                result = HttpContext.Request.UserHostAddress;
            }
            return result;

27,ASP.NET MVC 在Action里面获得央浼的UENVISIONL

能够分为3种方法,
1)ASP.NET MVC 在调节器的默许Action里面获取央求其余Action的不二等秘书技
比如在私下认可的 Index Action里面得到路线,如下:

string sso_url= "http://" + Request.Url.Authority + Request.Url.AbsolutePath + "/SSO?id=" + userid;

2)在别的Action里面获取当前调节器的路线

string ctrName = RouteData.Values["controller"].ToString(); string redirectUrl = "http://" + Request.Url.Authority + "/" + ctrName + "/SSO?id=" + userid;

3)直接拿走当前Action伏乞的路子

string url=Request.Url.ToString();

27,ASP.NET MVC 在Action里面获得央求的U奥迪Q7L

能够分为3种方法,
1)ASP.NET MVC 在调控器的默许Action里面获取央浼别的Action的路子
比方说在暗中同意的 Index Action里面获得路线,如下:

string sso_url= "http://" + Request.Url.Authority + Request.Url.AbsolutePath + "/SSO?id=" + userid;

 2)在其余Action里面获取当前调整器的路线 

string ctrName = RouteData.Values["controller"].ToString();
 string redirectUrl = "http://" + Request.Url.Authority + "/" + ctrName + "/SSO?id=" + userid;

 3)直接拿走当前Action央浼的门路

string url=Request.Url.ToString();

 

28,ASP.NET MVC Action重返能够在浏览器直接查看的纯文本音信

亟待钦定Context的contentType 为“text/plain”,代码如下:

 public ActionResult SendMessage() {   string txt="你好!";   return Content(text, "text/plain", System.Text.Encoding.UTF8);  }

28,ASP.NET MVC Action重临能够在浏览器间接查看的纯文本消息

内需钦定Context的contentType 为“text/plain”,代码如下:

 public ActionResult SendMessage()
 {
   string txt="你好!";
   return Content(text, "text/plain", System.Text.Encoding.UTF8);
  }

29,使用Linq2XML读写XML

此地关键使用XDocument,XElement对象来操作XML内容,如下代码:

    public static class XDocumentExtentsion    {        //生成XML的申明部分        public static string ToStringWithDeclaration(this XDocument doc, SaveOptions options = SaveOptions.DisableFormatting)        {            return doc.Declaration.ToString() + doc.ToString;        }    }        public string CreateMsgResult(string loginUserId,string corpid, string msg,string ts)        {            var xDoc = new XDocument(                new XDeclaration("1.0", "UTF-8", null),                  new XElement("result",                    new XElement("corpid", corpid),                    new XElement("userid", loginUserId),                    new XElement("ts", ts),                    new XElement("sendmsg", msg)                ));            return xDoc.ToStringWithDeclaration();        }        public ResponseMessage ParseXMLString(string xml)        {            var xDoc = XDocument.Parse;            if (xDoc == null) return null;            var root = xDoc.Element("result");            if(root==null)                throw new Exception ("not found the 'result' root node,input XMLrn"+xml);            ResponseMessage result =             new ResponseMessage()             {                 ErrorCode  = root.Element("rescode").Value,                 ErrorMessage  = root.Element("resmsg").Value,                 RedirectUrl  = root.Element("redirect_url") == null ? "" : root.Element("redirect_url").Value             };                      return result;        }

 29,使用Linq2XML读写XML

这里关键行使XDocument,XElement对象来操作XML内容,如下代码:

    public static class XDocumentExtentsion
    {
        //生成XML的申明部分
        public static string ToStringWithDeclaration(this XDocument doc, SaveOptions options = SaveOptions.DisableFormatting)
        {
            return doc.Declaration.ToString() + doc.ToString(options);
        }
    }

        public string CreateMsgResult(string loginUserId,string corpid, string msg,string ts)
        {
            var xDoc = new XDocument(
                new XDeclaration("1.0", "UTF-8", null),  
                new XElement("result",
                    new XElement("corpid", corpid),
                    new XElement("userid", loginUserId),
                    new XElement("ts", ts),
                    new XElement("sendmsg", msg)
                ));
            return xDoc.ToStringWithDeclaration();
        }

        public ResponseMessage ParseXMLString(string xml)
        {
            var xDoc = XDocument.Parse(xml);
            if (xDoc == null) return null;
            var root = xDoc.Element("result");
            if(root==null)
                throw new Exception ("not found the 'result' root node,input XMLrn"+xml);
            ResponseMessage result =
             new ResponseMessage()
             {
                 ErrorCode  = root.Element("rescode").Value,
                 ErrorMessage  = root.Element("resmsg").Value,
                 RedirectUrl  = root.Element("redirect_url") == null ? "" : root.Element("redirect_url").Value
             };

            return result;
        }

30,访问Web内容的自定义代码

采纳 HttpWebRequest和HttpWebResponse 对象完毕Web访问,假如是.NET 4.5,建议直接动用 HttpClient对象:

        /// <summary>        /// 获取请求结果        /// </summary>        /// <param name="requestUrl">请求地址</param>        /// <param name="timeout">超时时间</param>        /// <param name="requestXML">请求xml内容</param>        /// <param name="isPost">是否post提交</param>        /// <param name="encoding">编码格式 例如:utf-8</param>        /// <param name="errorMsg">抛出的错误信息</param>        /// <returns>返回请求结果</returns>        public static string HttpWebRequest(string requestUrl, int timeout, string requestXML, bool isPost, string encoding, out string errorMsg, string contentType = "application/x-www-form-urlencoded")        {            errorMsg = string.Empty;            string result = string.Empty;            try            {                byte[] bytes = System.Text.Encoding.GetEncoding.GetBytes(requestXML);                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestUrl);                request.Referer = requestUrl;                request.Method = isPost ? "POST" : "GET";                request.Timeout = timeout * 1000;                if                 {                    request.ContentType = contentType;// "application/x-www-form-urlencoded";                    request.ContentLength = bytes.Length;                    using (Stream requestStream = request.GetRequestStream                    {                        requestStream.Write(bytes, 0, bytes.Length);                        requestStream.Close();                    }                }                                HttpWebResponse response = (HttpWebResponse)request.GetResponse();                Stream responseStream = response.GetResponseStream();                if (responseStream != null)                {                    StreamReader reader = new StreamReader(responseStream, System.Text.Encoding.GetEncoding);                    result = reader.ReadToEnd();                    reader.Close();                    responseStream.Close();                    request.Abort();                    response.Close();                    return result.Trim();                }            }            catch (Exception ex)            {                errorMsg =string.Format("Error Message:{0},Request Url:{1},StackTrace:{2}", ex.Message ,requestUrl , ex.StackTrace);            }            return result;        }

 30,访谈Web内容的自定义代码

动用 HttpWebRequest和HttpWebResponse 对象完毕Web访问,固然是.NET 4.5,建议直接动用 HttpClient对象:

        /// <summary>
        /// 获取请求结果
        /// </summary>
        /// <param name="requestUrl">请求地址</param>
        /// <param name="timeout">超时时间(秒)</param>
        /// <param name="requestXML">请求xml内容</param>
        /// <param name="isPost">是否post提交</param>
        /// <param name="encoding">编码格式 例如:utf-8</param>
        /// <param name="errorMsg">抛出的错误信息</param>
        /// <returns>返回请求结果</returns>
        public static string HttpWebRequest(string requestUrl, int timeout, string requestXML, bool isPost, string encoding, out string errorMsg, string contentType = "application/x-www-form-urlencoded")
        {
            errorMsg = string.Empty;
            string result = string.Empty;
            try
            {
                byte[] bytes = System.Text.Encoding.GetEncoding(encoding).GetBytes(requestXML);
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestUrl);
                request.Referer = requestUrl;
                request.Method = isPost ? "POST" : "GET";
                request.Timeout = timeout * 1000;
                if (isPost)
                {
                    request.ContentType = contentType;// "application/x-www-form-urlencoded";
                    request.ContentLength = bytes.Length;
                    using (Stream requestStream = request.GetRequestStream())
                    {
                        requestStream.Write(bytes, 0, bytes.Length);
                        requestStream.Close();
                    }
                }

                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream responseStream = response.GetResponseStream();
                if (responseStream != null)
                {
                    StreamReader reader = new StreamReader(responseStream, System.Text.Encoding.GetEncoding(encoding));
                    result = reader.ReadToEnd();
                    reader.Close();
                    responseStream.Close();
                    request.Abort();
                    response.Close();
                    return result.Trim();
                }
            }
            catch (Exception ex)
            {
                errorMsg =string.Format("Error Message:{0},Request Url:{1},StackTrace:{2}", ex.Message ,requestUrl , ex.StackTrace);
            }

            return result;
        }

31,自定义浏览器合同,完毕web程序调用本地程序

(转自
近年项目遭逢那样个难点。客户供给用web页面,点击一个链接,调用本地的叁个主次。

参照了弹指间qq的方法。
tencent://Message/?Uin=000000&websiteName=qzone.qq.com&Menu=yes

在注册表里面增多下面,就能够兑现,详细内容见原来的书文

 31,自定义浏览器协议(伪左券),完毕web程序调用本地程序

(转自 )
近来项目碰着那样个难题。客户供给用web页面,点击贰个链接,调用本地的二个前后相继。

参照了一晃qq的点子。
tencent://Message/?Uin=000000&websiteName=qzone.qq.com&Menu=yes

在注册表里面加多上面,就会促成,详细内容见最先的文章

 

32,线程安全的向集结添英镑素

有的时候候,向一个List对象调用Add 方法,会出现“索引赶过了数组界限”那样的主题材料,此时得以思虑采取线程安全的聚集,但对此专门的学业上设定了集聚的最大值的动静下,用线程安全集合就有一些重了,成效不高,此时能够通过 Interlocked.CompareExchange 来完毕,具体代码如下:

private int length=0;private int maxLength=50;private int[] Arr=new int[maxLength];//使用循环数组,安全的添加元素void Add(int value){  int p= Interlocked.CompareExchange(ref length,0,maxLength);  if(p==length)   {      //说明length变量并且没有达到最大值,并安全的返回length当时的值      Arr[p]=value;  }  else  {      //数组元素已经达到上限,需要触发另外的操作,比如将数组全部输出      // To Do      //之后,再将当前位置的元素写入      //此时,length可能是0,也可能是其它值      Arr[length]=value;  }  Interlocked.Increment(ref length);}

32,线程安全的向集结添台币素

不经常,向三个List对象调用Add 方法,会现出“索引超越了数组界限”那样的主题材料,此时得以思索选取线程安全的成团,但对于职业上设定了集聚的最大值的气象下,用线程安全会集就有一点重了,效用不高,此时能够透过 Interlocked.CompareExchange 来实现,具体代码如下:

private int length=0;
private int maxLength=50;
private int[] Arr=new int[maxLength];

//使用循环数组,安全的添加元素
void Add(int value){
  int p= Interlocked.CompareExchange(ref length,0,maxLength);
  if(p==length) 
  {
      //说明length变量并且没有达到最大值,并安全的返回length当时的值
      Arr[p]=value;
  }
  else
  {
      //数组元素已经达到上限,需要触发另外的操作,比如将数组全部输出
      // To Do
      //之后,再将当前位置的元素写入
      //此时,length可能是0,也可能是其它值
      Arr[length]=value;
  }
  Interlocked.Increment(ref length);
}

 

33,WPF绑定异步更新的数额集结

最近做多个WPF项目,后端API推送过来的数目要翻新WPF分界面包车型地铁数码,发现有个别数据尚未跟后端数据状态一样。日常情状下,WPF绑定的Model数据集结都以一连于ObservableCollection 的,可是在当前处境下会有标题,那是能够打包贰个异步的多寡集结:

public class AsyncObservableCollection<T> : ObservableCollection<T>{    //获取当前线程的SynchronizationContext对象    private SynchronizationContext _synchronizationContext = SynchronizationContext.Current;    public AsyncObservableCollection() { }    public AsyncObservableCollection(IEnumerable<T> list) : base { }    protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)    {                  if (SynchronizationContext.Current == _synchronizationContext)        {            //如果操作发生在同一个线程中,不需要进行跨线程执行                     RaiseCollectionChanged;        }        else        {            //如果不是发生在同一个线程中            //准确说来,这里是在一个非UI线程中,需要进行UI的更新所进行的操作                     _synchronizationContext.Post(RaiseCollectionChanged, e);        }    }    private void RaiseCollectionChanged(object param)    {        // 执行                 base.OnCollectionChanged((NotifyCollectionChangedEventArgs)param);    }    protected override void OnPropertyChanged(PropertyChangedEventArgs e)    {        if (SynchronizationContext.Current == _synchronizationContext)        {            // Execute the PropertyChanged event on the current thread                         RaisePropertyChanged;        }        else        {            // Post the PropertyChanged event on the creator thread                         _synchronizationContext.Post(RaisePropertyChanged, e);        }    }    private void RaisePropertyChanged(object param)    {        // We are in the creator thread, call the base implementation directly                 base.OnPropertyChanged((PropertyChangedEventArgs)param);    }}

越多新闻,请参见:

WPF十六线程UI更新——三种艺术

绑定到异步的ObservableCollection

 33,WPF绑定异步更新的数目集合

多年来做一个WPF项目,后端API推送过来的数据要改进WPF分界面包车型地铁数据,开掘有一点数据未有跟后端数据状态一样。经常状态下,WPF绑定的Model数据集合都以连续于ObservableCollection 的,不过在当前情状下会有标题,那是足以打包多个异步的数额集合:

public class AsyncObservableCollection<T> : ObservableCollection<T>
{
    //获取当前线程的SynchronizationContext对象
    private SynchronizationContext _synchronizationContext = SynchronizationContext.Current;
    public AsyncObservableCollection() { }
    public AsyncObservableCollection(IEnumerable<T> list) : base(list) { }
    protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
    {

        if (SynchronizationContext.Current == _synchronizationContext)
        {
            //如果操作发生在同一个线程中,不需要进行跨线程执行         
            RaiseCollectionChanged(e);
        }
        else
        {
            //如果不是发生在同一个线程中
            //准确说来,这里是在一个非UI线程中,需要进行UI的更新所进行的操作         
            _synchronizationContext.Post(RaiseCollectionChanged, e);
        }
    }
    private void RaiseCollectionChanged(object param)
    {
        // 执行         
        base.OnCollectionChanged((NotifyCollectionChangedEventArgs)param);
    }
    protected override void OnPropertyChanged(PropertyChangedEventArgs e)
    {
        if (SynchronizationContext.Current == _synchronizationContext)
        {
            // Execute the PropertyChanged event on the current thread             
            RaisePropertyChanged(e);
        }
        else
        {
            // Post the PropertyChanged event on the creator thread             
            _synchronizationContext.Post(RaisePropertyChanged, e);
        }
    }
    private void RaisePropertyChanged(object param)
    {
        // We are in the creator thread, call the base implementation directly         
        base.OnPropertyChanged((PropertyChangedEventArgs)param);
    }
}

更加的多音信,请参谋:

WPF四线程UI更新——三种办法

绑定到异步的ObservableCollection

 

本文由118kjcom最快开奖现场发布,转载请注明来源

关键词: