.net 常用方法

   #region 获取mvc 模型绑定的错误

        /// <summary>
        /// 获得某个属性的错误ModelState错误信息
        /// </summary>
        /// <param name="modelState"></param>
        /// <param name="attribute"></param>
        /// <returns></returns>
        public static string GetModeStateErrorByAttribute(ModelStateDictionary modelState, string attribute)
        {
            string errorMessage = string.Empty;
            var allError = modelState[attribute];
            if (allError != null)
            {
                foreach (var item in allError.Errors)
                {
                    errorMessage += item.ErrorMessage;
                }
            }

            return errorMessage;
        }

        /// <summary>
        /// 得到所有属性的错误信息
        /// </summary>
        /// <param name="modelState"></param>
        /// <returns></returns>
        public static string GetModeStateErrorByAttribute(ModelStateDictionary modelState)
        {
            string errorMessage = string.Empty;

            foreach (var item in modelState.Keys)
            {
                errorMessage += GetModeStateErrorByAttribute(modelState, item);
            }
            return errorMessage;
        }

        #endregion 获取mvc 模型绑定的错误

        #region GET POST 数据方法

        private static string PostHttpWebRequest(string data, string url)
        {
            string result = null;
            try
            {
                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
                byte[] requestBytes = System.Text.Encoding.UTF8.GetBytes(data);
                req.Method = "POST";
                req.ContentType = "application/x-www-form-urlencoded";
                req.ContentLength = requestBytes.Length;
                Stream requestStream = req.GetRequestStream();
                requestStream.Write(requestBytes, 0, requestBytes.Length);
                requestStream.Close();
                HttpWebResponse res = (HttpWebResponse)req.GetResponse();
                StreamReader sr = new StreamReader(res.GetResponseStream());
                result = sr.ReadToEnd();
                sr.Close();
                res.Close();
            }
            catch (Exception ex)
            {
                throw;
            }
            return result;
        }

        private static string PostWebRequestAndCookie(string postData, string url)
        {
            Encoding encoding = Encoding.GetEncoding("utf-8");
            byte[] bytesToPost = encoding.GetBytes(postData);
            CookieContainer cookieCon = new CookieContainer();
            cookieCon.Add(new Cookie { Name = "zhud", Value = "true", Domain = "tiny1.yaolan.com" });
            HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(url);
            httpRequest.CookieContainer = cookieCon;
            httpRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.2; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";
            httpRequest.ContentType = "application/x-www-form-urlencoded";
            httpRequest.Method = "POST";
            httpRequest.ContentLength = bytesToPost.Length;
            Stream requestStream = httpRequest.GetRequestStream();
            requestStream.Write(bytesToPost, 0, bytesToPost.Length);
            requestStream.Close();
            Stream responseStream = httpRequest.GetResponse().GetResponseStream();
            string stringResponse = string.Empty;
            StreamReader responseReader = new StreamReader(responseStream, Encoding.UTF8);
            stringResponse = responseReader.ReadToEnd();
            responseStream.Close();
            return stringResponse;
        }

        public static string PostWebRequest(string data, string url)
        {
            string result = null;
            try
            {
                WebRequest request = WebRequest.Create(url);
                request.Method = "POST";
                byte[] byteArray = Encoding.UTF8.GetBytes(data);
                request.ContentType = "application/x-www-form-urlencoded";
                request.ContentLength = byteArray.Length;
                Stream dataStream = request.GetRequestStream();
                dataStream.Write(byteArray, 0, byteArray.Length);
                dataStream.Close();
                WebResponse response = request.GetResponse();
                dataStream = response.GetResponseStream();
                StreamReader reader = new StreamReader(dataStream);
                result = reader.ReadToEnd();
                reader.Close();
                response.Close();
            }
            catch (Exception ex)
            {
                throw;
            }
            return result;
        }

        public static string GetWebRequest(string url)
        {
            string result = null;
            try
            {
                WebRequest webRequest = WebRequest.Create(url);
                //  webRequest.Headers.Add("Cookie", Request.Headers["Cookie"]);
                WebResponse webResponse = webRequest.GetResponse();
                Stream stream = webResponse.GetResponseStream();
                StreamReader sr = new StreamReader(stream, Encoding.GetEncoding("UTF-8"));
                result = sr.ReadToEnd();
                webResponse.Close();
                stream.Close();
            }
            catch (Exception ex)
            {
                throw;
            }
            return result;
        }

        public static string PostWebClient(NameValueCollection data, string url)
        {
            string result = null;
            try
            {
                System.Net.WebClient webClient = new System.Net.WebClient();
                byte[] byRemoteInfo = webClient.UploadValues(url, "POST", data);
                result = System.Text.Encoding.UTF8.GetString(byRemoteInfo);
            }
            catch (Exception ex)
            {
                throw;
            }

            return result;
        }

        public static string GetWebClint(string url)
        {
            string result = null;
            try
            {
                System.Net.WebClient webClient = new System.Net.WebClient();
                result = webClient.DownloadString(url);
            }
            catch (Exception ex)
            {
                throw;
            }
            return result;
        }

        #endregion GET POST 数据方法

        public static string UserHostAddress
        {
            get
            {
                return HttpContext.Current.Request.UserHostAddress;
            }
        }

        /// <summary>
        /// ip是否有效
        /// </summary>
        /// <returns></returns>
        public static bool IPIsValid
        {
            get
            {
                bool ipIsValid = false;
                foreach (var item in IPLimitList)
                {
                    if (HttpContext.Current.Request.UserHostAddress.Contains(item.Replace("*", string.Empty)))
                    {
                        ipIsValid = true;
                        break;
                    }
                }

                return ipIsValid;
            }
        }

        public static DateTime WeekStartTime
        {
            get
            {
                DateTime dt = DateTime.Now;
                int dayOfWeek = -1 * (int)dt.DayOfWeek;
                DateTime weekStartTime = dt.AddDays(dayOfWeek + 1);
                if (dayOfWeek == 0)
                {
                    weekStartTime = weekStartTime.AddDays(-7);
                }

                return weekStartTime.Date;
            }
        }

        public static DateTime WeekEndTime
        {
            get
            {
                return WeekStartTime.AddDays(7);
            }
        }

        /// <summary>
        /// xml序列化
        /// </summary>
        /// <param name="type"></param>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string XmlSerializer<T>(T obj)
        {
            System.IO.StringWriter stringWriter = new System.IO.StringWriter();
            try
            {
                System.Xml.Serialization.XmlSerializer xmlSerializer = new System.Xml.Serialization.XmlSerializer(typeof(T));
                xmlSerializer.Serialize(stringWriter, obj);
            }
            catch (Exception ex)
            {
                throw;
            }

            return stringWriter.ToString();
        }

        /// <summary>
        /// xml反序列化
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="xml"></param>
        /// <returns></returns>
        public static T XmlDeserialize<T>(string xml)
        {
            System.IO.StringReader stringReader = new System.IO.StringReader(xml);
            System.Xml.Serialization.XmlSerializer xmlSerializer = new System.Xml.Serialization.XmlSerializer(typeof(T));
            return (T)xmlSerializer.Deserialize(stringReader);
        }

        public static List<object> GetEnumItems(Type enumType)
        {
            var objList = new List<object>();
            foreach (var item in Enum.GetValues(enumType))
            {
                objList.Add(new { Text=item.ToString(),Value=(int)item});
            }
            return objList;

        }
        /// <summary>
        /// 将对象转化为Json字符串
        /// </summary>
        /// <typeparam name="T">源类型</typeparam>
        /// <param name="obj">源类型实例</param>
        /// <returns>Json字符串</returns>
        public static string ObjToJson<T>(T obj)
        {
            DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(obj.GetType());
            using (MemoryStream ms = new MemoryStream())
            {
                jsonSerializer.WriteObject(ms, obj);
                return Encoding.UTF8.GetString(ms.ToArray());
            }
        }

        /// <summary>
        /// 将Json字符串转化为对象
        /// </summary>
        /// <typeparam name="T">目标类型</typeparam>
        /// <param name="strJson">Json字符串</param>
        /// <returns>目标类型的一个实例</returns>
        public static T JsonToObj<T>(string strJson)
        {
            // T obj = Activator.CreateInstance<T>();
            using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(strJson)))
            {
                DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(T));
                return (T)jsonSerializer.ReadObject(ms);
            }
        }

        public static T ChangeType<T>(object value)
        {
            return (T)Convert.ChangeType(value, typeof(T));
        }

        /// <summary>
        /// 将毫秒数(从1970/1/1 到现在所经历的毫秒数)转化为本地时区的时间
        /// </summary>
        /// <param name="ltime"></param>
        /// <returns></returns>
        public static DateTime GetTimeFromInt(long ltime)
        {
            long Eticks = (long)(ltime * 10000) + new DateTime(1970, 1, 1).Ticks;
            DateTime dt = new DateTime(Eticks).ToLocalTime();
            return dt;
        }

        /// <summary>
        ///  将时间变成毫秒数(从1970/1/1 到现在所经历的毫秒数)
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        public static long GetIntFromTime(DateTime dt)
        {
            DateTime dtNew = DateTime.Now.ToUniversalTime();
            long Sticks = (dtNew.Ticks - new DateTime(1970, 1, 1).Ticks) / 10000;
            return Sticks;
        }

        public static string GetMD5(string input)
        {
            //System.Security.Cryptography.MD5CryptoServiceProvider MD5CSP = new System.Security.Cryptography.MD5CryptoServiceProvider();
            //byte[] inputByte = System.Text.Encoding.Unicode.GetBytes(input);
            //byte[] md5Byte = MD5CSP.ComputeHash(inputByte);
            //md5Result = System.Text.Encoding.Unicode.GetString(md5Byte);

            return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(input, "SHA1").ToLower();
        }

.net 常用方法

时间: 2024-10-11 06:32:19

.net 常用方法的相关文章

从头认识java-15.2 Collection的常用方法

这一章节我们来介绍一下Collection的常用方法. 我们下面以ArrayList为例. package com.ray.ch14; import java.util.ArrayList; import java.util.Iterator; public class Test { public static void main(String[] args) { ArrayList<Integer> rtnList = new ArrayList<Integer>(); rtnL

java中String的常用方法

java中String的常用方法1.length() 字符串的长度 例:char chars[]={'a','b'.'c'}; String s=new String(chars); int len=s.length(); 2.charAt() 截取一个字符 例:char ch; ch="abc".charAt(1); 返回'b' 3. getChars() 截取多个字符 void getChars(int sourceStart,int sourceEnd,char target[]

查看Oracle执行计划的几种常用方法-系列1

SQL的执行计划实际代表了目标SQL在Oracle数据库内部的具体执行步骤,作为调优,只有知道了优化器选择的执行计划是否为当前情形下最优的执行计划,才能够知道下一步往什么方向. 执行计划的定义:执行目标SQL的所有步骤的组合. 我们首先列出查看执行计划的一些常用方法: 1. explain plan命令 PL/SQL Developer中通过快捷键F5就可以查看目标SQL的执行计划了.但其实按下F5后,实际后台调用的就是explain plan命令,相当于封装了该命令. explain plan

检查主板故障的常用方法

主板故障往往表现为系统启动失败.屏幕无显示等难以直观判断的故障现象.下面列举的维修方法各有优势和局限性,往往结合使用. 1.清洁法 可用毛刷轻轻刷去主板上的灰尘,另外,主板上一些插卡.芯片采用插脚形式,常会因为引脚氧化而接触不良.可用橡皮擦去表面氧化层,重新插接. 2.观察法 反复查看待修的板子,看各插头.插座是否歪斜,电阻.电容引脚是否相碰,表面是否烧焦,芯片表面是否开裂,主板上的铜箔是否烧断.还要查看是否有异物掉进主板的元器件之间.遇到有疑问的地方,可以借助万用表量一下.触摸一些芯片的表面,

Rhythmk 一步一步学 JAVA (20) JAVA enum常用方法

JAVA 枚举定义常用方法: 1.static Enum valueOf(Class enum,String name) 返回指定name的枚举类型 2.Static Enum values[] 返回枚举常量集合 ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50

Javascript - ExtJs - 常用方法和属性

常用方法和属性(Common methods and attributes) 获取 get(x) x是元素的ID || dom元素对象 || ExtElement对象 将参数所指转化为ExtElement对象并返回它(非Dom元素对象,而是对Dom元素的封装),此方法等同于new Ext.Element(x) . Ext.select(x) x是选择器 返回一个CompositeElement对象,表示ExtElment对象的集合.但返回的这个对象实际上并非数组,不能通过数组索引访问它包含的数据

Request常用方法

一.HttpServletRequest介绍 HttpServletRequest对象代表客户端的请求,当客户端通过HTTP协议访问服务器时,HTTP请求头中的所有信息都封装在这个对象中,通过这个对象提供的方法,可以获得客户端请求的所有信息. 二.Request常用方法 2.1.获得客户机信息 getRequestURL方法返回客户端发出请求时的完整URL.  getRequestURI方法返回请求行中的资源名部分.  getQueryString 方法返回请求行中的参数部分.  getPath

window对象的常用属性,常用方法

window对象的常用属性: window.self 返回当前窗口的引用 window.parent   返回当前窗体的父窗体对象 window.top 返回当前窗体最顶层的父窗体的引用 window.outerwidth       返回当前窗口的外部宽 window.outerheight  返回当前窗口的外部高 window.innerwidth       返回当前窗口的可显示区域宽 window.innerheight  返回当前窗口的可显示区域高 提示:通过直接在Chrome控制台中

Java实战之02Hibernate-03Session中的常用方法

九.Session中的常用方法 1.save方法 都是临时态————>持久态 2.persist方法 作用: 持久化临时态对象. 与save方法的区别: 开始了事务:persist和save没有区别. 不开启事务: persist:什么都不会做. save: hibernate3:计划保存数据,因为没有开启事务,自动回滚. hibernate5:提供一个内置事务执行保存操作. 1 /* 2 * save方法和persist方法 3 * 共同点: 4 * 都是把临时态对象转成持久态 5 * 区别:

07python之字符串的常用方法

字符串作为python中常用的数据类型,掌握字符串的常用方法十分必要. 常用知识点: 1.字符串的3种格式化方法 2.字符串的strip()方法 3.字符串的join()方法 4.字符串可以切片 1.字符串的格式化有三种方式. 1)使用+拼接模式 2)使用占为符方式  %s 字符串占为符,%d数字占为符 3)使用字符串类的格式化方法,即 str.format() 优缺点: 1)此等方式开辟内存空间较大,不好,弃用 2)此等方式方便,可用 3)字符串格式化方法也挺好,可用. 总结:建议使用第二种,