Web.Config
1 |
<globalization responseEncoding="gb2312"/> |
CS文件
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 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 |
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Net; using System.Text; using System.IO; using System.Xml; using System.Collections; using System.Diagnostics; namespace WebPortal { public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void Button1_Click(object sender, EventArgs e) { CoreProxy.Class1 c = new CoreProxy.Class1(); c.test1(); } protected void Button2_Click(object sender, EventArgs e) { webquerst1(); } public void webquers2() { string html = null; string url = "http://china.alibaba.com/keyword/promotion.htm?catId=14"; WebRequest req = WebRequest.Create(url); req.Method = "POST"; WebResponse res = req.GetResponse(); Stream receiveStream = res.GetResponseStream(); Encoding encode = Encoding.GetEncoding("gb2312"); StreamReader sr = new StreamReader(receiveStream, encode); char[] readbuffer = new char[256]; int n = sr.Read(readbuffer, 0, 256); while (n > 0) { string str = new string(readbuffer, 0, n); html += str; n = sr.Read(readbuffer, 0, 256); } System.Console.Write(html); } //成功!,利用WebRequest 一次Post提交XML内容 public void webquerst1() { WebRequest request = WebRequest.Create("http://192.168.1.244/WebPortal/PortalHandler.ashx"); // Set the Method property of the request to POST. request.Method = "POST"; // Create POST data and convert it to a byte array. System.Xml.XmlDocument xmlpostdata = new System.Xml.XmlDocument(); xmlpostdata.Load(Server.MapPath("XML/20097.xml")); string postData = HttpUtility.HtmlEncode(xmlpostdata.InnerXml); //普通字符串内容 //string postData = "你好,1232355 abdcde"; byte[] byteArray = Encoding.UTF8.GetBytes(postData); // Set the ContentType property of the WebRequest. request.ContentType = "application/x-www-form-urlencoded"; // Set the ContentLength property of the WebRequest. request.ContentLength = byteArray.Length; // Get the request stream. Stream dataStream = request.GetRequestStream(); // Write the data to the request stream. dataStream.Write(byteArray, 0, byteArray.Length); // Close the Stream object. dataStream.Close(); // Get the response. WebResponse response = request.GetResponse(); // Display the status. //Console.WriteLine(((HttpWebResponse)response).StatusDescription); // Get the stream containing content returned by the server. dataStream = response.GetResponseStream(); // Open the stream using a StreamReader for easy access. StreamReader reader = new StreamReader(dataStream); // Read the content. string responseFromServer = reader.ReadToEnd(); // Display the content. //Console.WriteLine(responseFromServer); // Clean up the streams. reader.Close(); dataStream.Close(); response.Close(); } protected void Button3_Click(object sender, EventArgs e) { WebClientPost(); } //重点!! 成功 利用Webclient Post 按字段的方式提交每个字段的内容给服务器端 public void WebClientPost() { System.Xml.XmlDocument xmlpostdata = new System.Xml.XmlDocument(); xmlpostdata.Load(Server.MapPath("XML/OrderClient.xml")); string OrderClient = HttpUtility.HtmlEncode(xmlpostdata.InnerXml); xmlpostdata.Load(Server.MapPath("XML/Order.xml")); string Order = HttpUtility.HtmlEncode(xmlpostdata.InnerXml); xmlpostdata.Load(Server.MapPath("XML/TargetOut.xml")); string TargetOut = HttpUtility.HtmlEncode(xmlpostdata.InnerXml); xmlpostdata.Load(Server.MapPath("XML/ArrayOfOrderDetail.xml")); string ArrayOfOrderDetail = HttpUtility.HtmlEncode(xmlpostdata.InnerXml); System.Net.WebClient WebClientObj = new System.Net.WebClient(); System.Collections.Specialized.NameValueCollection PostVars = new System.Collections.Specialized.NameValueCollection(); //添加值域 PostVars.Add("OrderClient", OrderClient); PostVars.Add("Order", Order); PostVars.Add("TargetOut", TargetOut); PostVars.Add("ArrayOfOrderDetail", ArrayOfOrderDetail); try { byte[] byRemoteInfo = WebClientObj.UploadValues("http://192.168.1.244/WebPortal/PlaceOrder.ashx", "POST", PostVars); //下面都没用啦,就上面一句话就可以了 string sRemoteInfo = System.Text.Encoding.Default.GetString(byRemoteInfo); //这是获取返回信息 Debug.WriteLine(sRemoteInfo); } catch { } } //未测试,使用WebClient 一次性提交POst public static string SendPostRequest(string url, string postString) { byte[] postData = Encoding.UTF8.GetBytes(postString); WebClient client = new WebClient(); client.Headers.Add("Content-Type", "application/x-www-form-urlencoded"); client.Headers.Add("ContentLength", postData.Length.ToString()); byte[] responseData = client.UploadData(url, "POST", postData); return Encoding.Default.GetString(responseData); } /// <summary> /// 这个是用WEbRequest 提交到WEbService 的例子 /// </summary> /// <param name="URL"></param> /// <param name="MethodName"></param> /// <param name="Pars"></param> /// <returns></returns> public static XmlDocument QueryPostWebService(String URL, String MethodName, Hashtable Pars) { HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(URL); request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; SetWebRequest(request); byte[] data = EncodePars(Pars); WriteRequestData(request, data); return ReadXmlResponse(request.GetResponse()); } private static void SetWebRequest(HttpWebRequest request) { request.Credentials = CredentialCache.DefaultCredentials; request.Timeout = 10000; } private static void WriteRequestData(HttpWebRequest request, byte[] data) { request.ContentLength = data.Length; Stream writer = request.GetRequestStream(); writer.Write(data, 0, data.Length); writer.Close(); } private static byte[] EncodePars(Hashtable Pars) { return Encoding.UTF8.GetBytes(ParsToString(Pars)); } private static String ParsToString(Hashtable Pars) { StringBuilder sb = new StringBuilder(); foreach (string k in Pars.Keys) { if (sb.Length > 0) { sb.Append("&"); } sb.Append(HttpUtility.UrlEncode(k) + "=" + HttpUtility.UrlEncode(Pars[k].ToString())); } return sb.ToString(); } private static XmlDocument ReadXmlResponse(WebResponse response) { StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8); String retXml = sr.ReadToEnd(); sr.Close(); XmlDocument doc = new XmlDocument(); doc.LoadXml(retXml); return doc; } private static void AddDelaration(XmlDocument doc) { XmlDeclaration decl = doc.CreateXmlDeclaration("1.0", "utf-8", null); doc.InsertBefore(decl, doc.DocumentElement); } protected void Button4_Click(object sender, EventArgs e) { } } } |
ashx
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 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 |
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Services; using System.Diagnostics; using System.IO; using System.Xml; namespace WebPortal { /// <summary> /// $codebehindclassname$ 的摘要说明 /// </summary> [WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] public class PortalHandler : IHttpHandler { public void ProcessRequest(HttpContext context) { string testGet = context.Request["testGet"]; string testPost = context.Request["testPost"]; Debug.WriteLine(testGet); Debug.WriteLine(testPost); //一次性提交的方式 //获得内容长度 int len = context.Request.ContentLength; //获得所有内容流 StreamReader reader = new StreamReader(context.Request.InputStream); //读取内容 string responseFromServer = reader.ReadToEnd(); //字段提交Post方式 string a1 = context.Request["A1"]; string a2 = context.Request["A2"]; string a3 = context.Request["A3"]; //解析Html编码 string re = HttpUtility.HtmlDecode(a1); XmlDocument xd = new XmlDocument(); //加载XML xd.LoadXml(re); context.Response.ContentType = "text/plain"; context.Response.Write(testGet); } public bool IsReusable { get { return false; } } } } |
转自:http://www.cnblogs.com/goody9807/archive/2011/10/08/2202265.html
View Detailsusing System; using System.IO; using System.Net; using System.Text; using System.Web; namespace HP.Common { /// <summary> /// 信息 /// </summary> public class InfoCollect { /// <summary> /// 获取内网页面内容 /// </summary> /// <param name="url"></param> /// <returns></returns> public static string GetPageByInner(string url) { return GetPage("http://" + HttpContext.Current.Request.ServerVariables["SERVER_NAME"] + (HttpContext.Current.Request.ServerVariables["SERVER_PORT"] == "80" ? "" : ":" + HttpContext.Current.Request.ServerVariables["SERVER_PORT"]) + url); } /// <summary> /// 获取公网url内容(GET) /// </summary> /// <param name="url"></param> /// <returns></returns> public static string GetPage(string url) { return GetPage(url, "GET", null); } /// <summary> /// 获取公网url内容(Post方法) /// </summary> /// <param name="url"></param> […]
View Details任何程序都离不开对异常的处理,良好的异常处理方式可加快寻找出异常的根源,同时也需要避免暴露敏感信息到异常中。WCF这种典型的服务端和客户端交互的程序,服务端的异常更需要适当的处理。下面以一个简单的服务为例,说明WCF中处理异常的方式。 WCF服务定义如下,很明显方法Divide在divisor为0的时候将会抛出异常 View Code 客户端调用如下: using (var client = new CalculateServiceClient()) { try { Console.WriteLine(client.Divide(20, 0)); } catch (FaultException ex) { Console.WriteLine(ex.Reason); } } 首先需要知道的是,WCF的异常信息默认是以FaultException的形式返回到客户端,FaultException的关键属性Reason是对客户端反馈的最重要信息之一。以上客户端代码调用之后,默认的FaultException返回的Message信息如下: 由于内部错误,服务器无法处理该请求。有关该错误的详细信息,请打开服务器上的 IncludeExceptionDetailInFaults (从 ServiceBehaviorAttribute 或从 <serviceDebug> 配置行为)以便将异常信息发送回客户端,或在打开每个 Microsoft .NET Framework 3.0 SDK 文档的跟踪的同时检查服务器跟踪日志。 根据异常的提示,意思说如果要在客户端看到详细的Exception信息,那么请将ServiceBehavior对应的IncludeExceptionDetailInFaults属性设置为True,通常在配置中表现为如下设置: View Code 通过以上设置之后,客户端输出的内容为“尝试除以零”,这个提示信息跟原始的异常信息是一致,即返回的FaultException中的Reason包含原始异常的Message的值,但是这样处理之后服务端所报出的异常信息直接传到了客户端,比如一些保密信息也可能输出到了客户端,因此对于异常信息必须进行一个封装。最直接的形式莫过于在服务端就把异常给捕获了,并重新throw一个FaultException 服务端的代码改进如下,经过以下改进,那么客户端得到的信息仅仅是"操作失败",同时服务端也记录了异常信息(这时IncludeExceptionDetailInFaults是设置为False的)。 View Code 当然这是FaultException的默认用法,FaultException还支持强类型的异常错误信息,返回更加丰富和精确的错误提示。假设定义如下通用的一个FaultContract类型,将出错时的用户名和线程名字记录到异常信息中,因为异常信息也是通过SOAP格式传输的,因此跟定义其他DataContract的方式一样。 CommonFaultContract 那么服务方法的接口需要增加如下标记,如果不这样标记,那么客户端得到的异常类型依然是FaultException,而不是强类型的异常信息。 [FaultContract(typeof(CommonFaultContract))] int Divide(int dividend, int divisor) 实现方法中抛出异常的部分代码改成如下: 异常处理 这时候重新生成客户端的代理类,然后更新客户端的代码如下,红色部分即获取强类型的异常错误信息。 View Code 当然在具体应用中还需要根据需求,返回不同的信息,构建不同的FaultContract。 以上服务端捕获的异常方法,适用于方法比较少的情况,如果有十多个方法,一个个去写try catch然后做标记等,那么工作量会很大,而且代码也不利于重用。尝试寻找像MVC Controller那样的统一处理Exception的方式,将异常处理都放在基类中,那么只要继承与这个基类的方法都不需要去写try catch去捕获异常。但WCF中似乎没有这样的机制,放弃了这种做法。 最近在研究Enterprise Lib中对WCF的支持时,发现Exception Block中还特地有针对WCF程序异常处理的解决方案,而且满足以上说道的需求,即可记录异常,又可对异常信息进行封装。更重要的时,自动处理运行时的异常信息,不需要挨个方法的去写Try catch。秉承企业库的优秀传统,大部分工作还是通过配置就可以完成了,非常好的解决方案。下面介绍具体的使用步骤。 步骤一: 引用以下dll Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.dll Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.WCF.dll Microsoft.Practices.EnterpriseLibrary.Common.dll Microsoft.Practices.ObjectBuilder2.dll 步骤2: 在具体的实现类中,增加如下属性标记,其中WcfException为企业库中Exception Block中的一个异常处理策略,具体如何配置异常处理策略,请参考企业库的帮助文档。 [ExceptionShielding("WcfException")] public class CalculateService : ICalculateService 那么只要增加了[ExceptionShielding("WcfException")]这个属性标记之后,所有运行时的异常都将交给策略名为WcfException的异常处理block来处理,在这里就可以执行一些异常记录以及异常封装的操作。 步骤3: 将异常信息封装为FaultException,这个动作也是通过配置来完成。在Exception节点中添加一个Fault Contract Exception Handler。 Fault Contract Exception Handler需要设置以下两个属性值 exceptionMessage:所有异常封装后的错误信息 faultContractType:即返回异常的faltContract类型,这个类型必须指定一个,哪怕方法中没有用到也要,如果方法中有用到,那么客户端那边就能得到强类型FaultException,否则就是普通的FaultException。这里指定为之前定义的CommonFaultContract。 对于faultContract类型的值,还可以通过PropertyMappings来自定义需要从原始异常信息中映射到faultContract的属性中,这个属性可选。 […]
View Details使用WCF传输大数据时,我们都会碰到如题中出现的错误信息,出现这个问题是因为WCF本身的安全机制导致的,限制了客户端与服务器资源传输大小,那我们如何还解决这个问题呢? 针对这个问题,我们要分发送、接受两个方面来解决。 发送大数据:在WCF服务端解决 NetTcpBinding binding = new NetTcpBinding(); binding.MaxReceivedMessageSize= 2147483647(更改这个数字) ; 接受大数据:在WCF客户端解决 NetTcpBinding binding = new NetTcpBinding(); binding.ReaderQuotas = new XmlDictionaryReaderQuotas() { MaxStringContentLength = 2147483647(更改这个数字) }; 我们即可以使用如上述通过代码配置,我们同样也可以使用配置文件进行配置(在binding节中)。
1 2 3 4 5 6 7 |
public static System.ServiceModel.BasicHttpBinding Binding() { //读取 XML 数据时,超出最大字符串内容长度配额 (8192)。 System.ServiceModel.BasicHttpBinding bing = new System.ServiceModel.BasicHttpBinding(); bing.ReaderQuotas = new System.Xml.XmlDictionaryReaderQuotas() { MaxStringContentLength = 2147483647 }; //(更改这个数字) return bing; } |
1 2 3 |
public static API.iClient api = new API.iClient(Binding(), new System.ServiceModel.EndpointAddress("http://192.168.1.11:4417/WebService.svc")); 转自:<a href="http://www.cnblogs.com/Fooo/archive/2012/12/06/2805362.html">http://www.cnblogs.com/Fooo/archive/2012/12/06/2805362.html</a> |
WEB站点在调用我们WCF服务的时候,只要传入的参数过长,就报如下错误: [csharp] view plaincopy 格式化程序尝试对消息反序列化时引发异常: 尝试对参数 http://tempuri.org/ 进行反序列化时出错: formDataXml。InnerException 消息是“反序列化对象 属于类型 System.String 时出现错误。读取 XML 数据时,超出最大字符串内容长度配额 (8192)。通过更改在创建 XML 读取器时所使用的 XmlDictionaryReaderQuotas 对象的 MaxStringContentLength 属性,可增加此配额。 第 137 行,位置为 76。”。有关详细信息,请参阅 InnerException。 网上一搜索,答案基本得到解决,可我的问题就是不能解决(主要是细节打败了我),按照网上的文章进行服务器端修改配置如下: [html] view plaincopy <binding name="HttpBinding" <span style="color:#ff0000"><strong>maxReceivedMessageSize</strong></span>="2097152"> <readerQuotas maxDepth="32" <span style="color:#ff0000"><strong>maxStringContentLength</strong></span>="2097152" maxArrayLength="2097152" maxBytesPerRead="2097152" maxNameTableCharCount="2097152" /> <security mode="None"></security> </binding> 其实这里主要的配置是两个:maxReceivedMessageSize、maxStringContentLength; 网上提到还需要配置客户端,其实如果是报上面错误就不要管客户端了,因为如果是客户端调用WCF报错,就不是读取XML数据超时,而是明确的错误提示,如下: [csharp] view plaincopy 已超过传入消息(1024)的最大消息大小配额。若要增加配额,请使用相应绑定元素上的 MaxReceivedMessageSize 属性。 所以这篇文章提到的错误基本与客户端无关。 一般情况下,安装上面的修改就可以解决问题了,但是我的WCF还是报错,没办法,只能继续找,无意间发现服务器端WCF配置有点异常,不用登录验证的WCF接口有用到bindingConfiguration,但是需要验证的WCF接口就没有配置该属性,如下代码: [html] view plaincopy <bindings> <wsHttpBinding> <span style="color:#ff0000"><binding name="HttpBinding" maxReceivedMessageSize="2097152"> <readerQuotas maxDepth="32" maxStringContentLength="2097152" maxArrayLength="2097152" maxBytesPerRead="2097152" maxNameTableCharCount="2097152" /> <security mode="None"></security> </binding></span><span style="background-color:#f0f0f0"><binding name="HttpBinding" maxReceivedMessageSize="2097152"> <readerQuotas maxDepth="32" maxStringContentLength="2097152" maxArrayLength="2097152" maxBytesPerRead="2097152" maxNameTableCharCount="2097152" /> <security mode="None"></security> </binding></span> </wsHttpBinding> </bindings> <serviceHostingEnvironment aspNetCompatibilityEnabled="true" /> <services> <service name="Achievo.MMIP.WMP.WebService.WMPProcService" behaviorConfiguration="wmpWcfBehavior"> <span style="color:#ff0000"><strong><endpoint address="" binding="wsHttpBinding" contract="Achievo.MMIP.WMP.WebServiceIService.WMPServiceProcIService"></strong> </span> <identity> <dns value="localhost" /> </identity> </endpoint> <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" /> </service> <service name="Achievo.MMIP.WMP.WebService.WMPGetFormDataService" behaviorConfiguration="wmpWcfFormDataBehavior"> <span style="color:#ff0000"><strong><endpoint address="" binding="wsHttpBinding" bindingConfiguration="HttpBinding" contract="Achievo.MMIP.WMP.WebServiceIService.IWMPGetFormDataIService"></strong> </span> <identity> <dns value="localhost" /> </identity> </endpoint> <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" /> </service> </services> 注意红色部分的配置,大伙可以对比一下,就发现其中一个缺少bindingConfiguration配置;如果这个时候,把缺少的部分补上,和另外一个配置一样,WCF就会出错,这里我的初步判断是:name="Achievo.MMIP.WMP.WebService.WMPProcService"是必须要验证登录才能访问,所以不能绑定上面的匿名访问的配置,简单说就是规定是验证就不能在配置为匿名;所以把配置修改为如下: [html] view plaincopy <bindings> <wsHttpBinding> <span style="color:#ff0000"><strong><binding name="HttpBinding" maxReceivedMessageSize="2097152"> <readerQuotas maxDepth="32" maxStringContentLength="2097152" maxArrayLength="2097152" maxBytesPerRead="2097152" maxNameTableCharCount="2097152" /> <security mode="None"></security> </binding> <binding name="HttpBinding1" maxReceivedMessageSize="2097152"> <readerQuotas maxDepth="32" maxStringContentLength="2097152"/> </binding></strong></span> </wsHttpBinding> </bindings> <serviceHostingEnvironment aspNetCompatibilityEnabled="true" /> <services> <service name="Achievo.MMIP.WMP.WebService.WMPProcService" behaviorConfiguration="wmpWcfBehavior"> <strong><span style="color:#ff0000"><endpoint address="" binding="wsHttpBinding" <span style="font-size:18px">bindingConfiguration="HttpBinding1"</span> contract="Achievo.MMIP.WMP.WebServiceIService.WMPServiceProcIService"></span></strong> <identity> <dns value="localhost" /> </identity> </endpoint> <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" /> </service> <service name="Achievo.MMIP.WMP.WebService.WMPGetFormDataService" behaviorConfiguration="wmpWcfFormDataBehavior"> <strong><span style="color:#ff0000"><endpoint address="" binding="wsHttpBinding" bindingConfiguration="HttpBinding" contract="Achievo.MMIP.WMP.WebServiceIService.IWMPGetFormDataIService"></span></strong> <identity> <dns value="localhost" /> </identity> </endpoint> <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" /> </service> </services> 在验证,OK,通过。 转自:http://blog.csdn.net/yang_5/article/details/11775819
View Detailsusing System; using System.IO; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Binary; using System.Runtime.Serialization.Formatters.Soap; using System.Xml.Serialization; using HP.Common; namespace HP.UI.Web { public partial class Test : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { //原始对象 var obj = new Person { Sno = "200719", Name = "yuananyun", Sex="man", Age=22 }; Response.Write("原始信息:" + obj.DisplayInfo() + "<br /><br />"); //序列化 IFormatter formatter = new BinaryFormatter(); //二进制 //IFormatter formatter = new SoapFormatter(); //SOAP //var formatter = new XmlSerializer(typeof(Person)); //XML var stream = new MemoryStream(); formatter.Serialize(stream, obj); var bs = stream.ToArray(); var s = System.Text.Encoding.Default.GetString(bs); stream.Close(); Response.Write("序列化:" + s + "<br /><br />"); […]
View Details这是为C#开发者准备的通用性代码审查清单,可以当做开发过程中的参考。这是为了确保在编码过程中,大部分通用编码指导原则都能注意到。对于新手和缺乏经验(0到3年工作经验)的开发者,参考这份清单编码会很帮助。 清单 1. 确保没有任何警告(warnings)。 2.如果先执行Code Analysis(启用所有Microsoft Rules)再消除所有警告就更好了。 3. 去掉所有没有用到的usings。编码过程中去掉多余代码是个好习惯。(参考:msdn) 4. 在合理的地方检查对象是否为’null’,避免运行的时候出现Null Reference Exception。 5. 始终遵循命名规范。一般而言变量参数使用驼峰命名法,方法名和类名使用Pascal命名法。(参考:msdn) 6. 请确保你了解SOLID原则。 根据维基百科定义:在程序设计领域,SOLID (单一功能、开闭原则、里氏替换、接口隔离以及依赖反转) 是由罗伯特·C·马丁在21世纪早期引入的记忆术首字母缩略字,指代了面向对象编程和面向对象设计的五个基本原则。当这些原则被一起应用时,它们使得一个 程序员开发一个容易进行软件维护和扩展的系统变得更加可能。SOLID所包含的原则是通过引发编程者进行软件源代码的代码重构进行软件的代码异味清扫,从而使得软件清晰可读以及可扩展时可以应用的指南。SOLID被典型的应用在测试驱动开发上,并且是敏捷开发以及自适应软件开发的基本原则的重要组成部分。参考:wiki/SOLID_(面向对象设计) 7. 代码可重用性:如果一块代码已经被使用超过一次,或者你希望将来使用它,请提取成一个方法。将重复的工作做成通用的方法放在相关的类中,这样一旦你完成别人就可以使用了。将常用功能开发成用户控件,这样可以跨项目重用它们。(参考:① 、 ②) 8. 代码一致性:比方说,Int32写成int,String写成string,应该在代码里保持统一形式。不能一会二写成int一会儿写成Int32。 9. 代码可读性:代码应该是可维护的,便于其他开发者理解。(参考:msdn) 10. 释放非托管资源,比如文件I/O,网络资源等。一旦使用结束就应该释放它们。如果你想一旦超出使用范围就自动释放对象,可以使用usings将非托管代码括起来。参考:msdn 11. 合理实现异常处理(try/catch和finally块)和异常记录。参考:msdn 12. 确保代码中方法的行数不要过多,不超过30到40行。 13. 及时用代码管理工具check-in/check-out代码。(比如TFS) 参考:codeproject.com 14. 相互审查代码:和你的同事交换代码,实现内部审查。 15. 单元测试:编写开发测试用例完成单元测试,确保代码被送到QA以前,基本测试完成。参考:msdn 16. 尽量避免for/foreach循环嵌套和if条件嵌套。 17. 如果代码只会使用一次,请使用匿名类型。参考:msdn 18. 尽量使用LINQ查询和Lambda表达式,增加可读性。参考:msdn 19. 合理使用var、object和dynamic关键字。由于很多开发者会感到困惑或者知道的很少,会觉得它们有些相似,故而交换使用,这是要避免的。参考:blogs.msdn 20. 使用访问限定符(private, public, protected, internal, protected internal)限定每个方法、类或变量的需要范围。比方说如果一个类只会在程序集内使用,那么定义成internal就足够了。参考:msdn 21. 在需要保持解耦的地方使用接口,有些设计模式的出现也是由于接口的使用。参考:msdn 22. 按照用法和需要将类定义为sealed、static或abstract。参考:msdn 23. 如果需要多次串联,请使用Stringbuilder代替string,这可以节省堆内存。 24. 检查是否有不可能执行的代码,如果有,请修改。 25. 在每个方法前注释,说明它的用法、输入类型和返回值类型信息。 26. 使用类似Silverlight Spy的工具,检查和操控Silverlight应用在运行时对XMAL的渲染,以此来改善效率。这可以在设计执行XAML时,节省大量退回和来回修改的时间。 27. 使用filddler工具通过检查HTTP/网络流量和带宽,来跟踪web应用和服务的性能。 28. 如果你想确认Visual Studio以外的方法,请使用WCFTestClient.exe工具,或者装载它的进程到Visual Studio来进行调试。 29. 在任何合理的地方使用constants和readonly。参考:/msdn、msdn 30. 尽量避免强制转换和类型转换,因为会造成性能损失。参考:msdn 31. 对于你想提供自定义信息的类,请重载ToString(来自Object类)。参考:msdn 32. 避免直接从其他代码中ctrl+c/ctrl+v。一直建议还是自己用手敲,即使你已经找到相关代码。这样可以锻炼自己写代码能力,还能正确理解那段代码的用法。最终你永远都不会忘记那段代码。 33. 保持阅读书籍和文章的良好习惯,遵循大神们的实践指导。(比如微软专家和一些著名的专家,Martin Fowler, Kent Beck, Jeffrey Ritcher, Ward […]
View Details以SQL SERVER2000自带数据库Northwind中Customers表示例. 前台aspx代以码: <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Repeater.aspx.cs" Inherits="Repeater" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title>Repeater控件使用</title> <script language="javascript" type="text/javascript"> function Check(parentChk,ChildId) { var oElements = document.getElementsByTagName("INPUT"); var bIsChecked = parentChk.checked; for(i=0; i<oElements.length;i++) { if( IsCheckBox(oElements[i]) && IsMatch(oElements[i].id, ChildId)) { oElements[i].checked = bIsChecked; } } } function IsMatch(id, ChildId) { var sPattern =’^Repeater1.*’+ChildId+’$'; var oRegExp = new RegExp(sPattern); if(oRegExp.exec(id)) return true; else return false; } function IsCheckBox(chk) { if(chk.type == 'checkbox') return true; else return false; } </script> </head> <body> <form id="form1" runat="server"> <div style="margin-bottom:20px;text-align:center; width:1006px;">Repeater控件使用</div> <asp:Repeater ID="Repeater1" runat="server"> <%--SeparatorTemplate描述一个介于每条记录之间的分隔符--%> <%--<SeparatorTemplate> <tr> <td colspan="5"><hr /></td> </tr> </SeparatorTemplate>--%> <HeaderTemplate> <table border="1" cellpadding="0" cellspacing="0" style="width:1006px;border-collapse:collapse; text-align:center;"> <tr> <td style="background-color:#cccccc; font-weight:bold; height:25px;"><input id="chkAll" name="chkAll" runat="server" type="checkbox" onclick="Check(this,’chkItem')" title="全选" />全</td> <td style="background-color:#cccccc; font-weight:bold; height:25px;">View</td> <td style="background-color:#cccccc; font-weight:bold; height:25px;">CustomerID</td> <td style="background-color:#cccccc; font-weight:bold;">CompanyName</td> <td style="background-color:#cccccc; font-weight:bold;">ContactName</td> <td style="background-color:#cccccc; font-weight:bold;">ContactTitle</td> <td style="background-color:#cccccc; font-weight:bold;">Address</td> </tr> </HeaderTemplate> <ItemTemplate> <tr> <td><asp:CheckBox ID="chkItem" runat="server" /></td> <td><a href='<%# "View.aspx?id="+DataBinder.Eval(Container.DataItem, "CustomerID") %>' target="_blank">View</a></td> <td><asp:Label ID="lblID" Text='<%# DataBinder.Eval(Container.DataItem, "CustomerID")%>' runat="server"></asp:Label></td> <td><%# DataBinder.Eval(Container.DataItem, "CompanyName")%></td> <td><%# DataBinder.Eval(Container.DataItem, "ContactName")%></td> <td><%# DataBinder.Eval(Container.DataItem, "ContactTitle")%></td> <td><%# DataBinder.Eval(Container.DataItem, "Address")%></td> </tr> </ItemTemplate> <%--AlternatingItemTemplate描述交替输出行的另一种外观--%> <AlternatingItemTemplate> <tr bgcolor="#e8e8e8"> <td><asp:CheckBox ID="chkItem" runat="server" /></td> <td><a href='<%# "View.aspx?id="+DataBinder.Eval(Container.DataItem, "CustomerID") %>' target="_blank">View</a></td> <td><asp:Label ID="lblID" Text='<%# DataBinder.Eval(Container.DataItem, "CustomerID")%>' runat="server"></asp:Label></td> <td><%# DataBinder.Eval(Container.DataItem, "CompanyName")%></td> <td><%# DataBinder.Eval(Container.DataItem, "ContactName")%></td> <td><%# DataBinder.Eval(Container.DataItem, "ContactTitle")%></td> <td><%# DataBinder.Eval(Container.DataItem, "Address")%></td> </tr> </AlternatingItemTemplate> <FooterTemplate> </table> </FooterTemplate> </asp:Repeater> <div style="background-color:#dedede; width:1006px;"> […]
View Details最近在做Silverlight,Windows Phone应用移植到Windows 8平台,在IIS8中测试一些传统WCF服务应用,发现IIS8不支持WCF服务svc请求,后来发现IIS8缺少对WCF服务的Managed Handler,按照以下步骤添加后,IIS8即支持WCF服务。 1. 首先添加MIME类型 扩展名“.svc”,MIME类型 “application/octet-stream” 2. 然后在“Handler Mappings”中添加Managed Handler, Request path: *.svc Type: System.ServiceModel.Activation.HttpHandler Name: svc-Integrated 完成后,IIS8即可支持WCF服务svc请求。 转自:http://www.cnblogs.com/jv9/archive/2012/11/13/2767396.html
View Details下载:Newtonsoft.Json.dll 安装: 1.解压下载文件,得到Newtonsoft.Json.dll 2.在项目中添加引用..
View Details