Tips on asp.net Development

Source: Internet
Author: User

The following are some of the problems found during actual development or reading. Some even have the code written by developers for many years and are also common mistakes made by many people. You can see if you have been lying down and shot. First, perform non-null judgment on integer variables. // A is int type (not int ?) If (! = Null) {// operation} personal comment: meaningless judgment, value type can never be null. Second, use static to keep the page sending and copying code static int id; protected void Page_Load (object sender, EventArgs e) {if (Request. QueryString ["ID"]! = Null & Request. QueryString ["ID"]. ToString ()! = "") {Id = Convert. ToInt32 (Request. QueryString ["ID"]. ToString () ;}} copy the code to your personal comment: this is not an explanation and I don't know what to say. However, we have encountered this problem recently, and it is not a small project. WebForm has no server control development. Third, when the data control is bound programmatically, when the data source is DataSet, the system determines null and does not interpret the number of Tables in the DataSet. DataSet ds = bll. GetList (); if (ds! = Null) {Repeater1.DataSource = ds; Repeater1.DataBind ();} personal comment: When bll. when the DataSet returned by GetList () is non-null but does not contain a data table, an HttpException (IListSource does not contain any data source) is reported when the DataBind () method is executed ). The correct syntax should be to copy the code DataSet ds = bll. GetList (); if (ds! = Null & ds. Tables. Count> 0) {Repeater1.DataSource = ds; Repeater1.DataBind () ;}// or DataSet ds = bll. GetList ()?? New DataSet (); if (ds. tables. count> 0) {Repeater1.DataSource = ds; Repeater1.DataBind ();} copy the fourth code. If the data source is able or List when the data control is bound programmatically, null is determined. DataTable dt = bll. GetList (); if (dt! = Null) {Repeater1.DataSource = dt; Repeater1.DataBind ();} personal comment: meaningless judgment. The following statement is correct, even if dt = null DataTable dt = bll. getList (); Repeater1.DataSource = dt; Repeater1.DataBind (); Fifth Model m = new Model (); m = bll. getModel (id); m. name; personal comment: I think that as long as the declaration is not null, no non-null judgment is required later. What if the model returned by the BLL layer in step 2 is null? Sixth, write the code Label lblPMID = (Label) e. Item. FindControl ("lblPMID"); if (lblPMID. Text! = "") {// Operation} personal comment: inefficient and meaningless judgment. It is likely that NullReferenceException (the instance where the object is not referenced) is abnormal. Label lblPMID = e. Item. FindControl ("lblPMID") as Label; if (lblPMID! = Null & lblPMID. Text! = "") // Determines whether to determine the lblPMID Based on the usage. text is "" or blank {// operation} seventh copy code string txtName = Request ["txtName"] = null? "": Request ["txtName"]. ToString (); string strWhere + = "and ID =" + userId + ""; // userId is intif (txtName! = "") {StrWhere + = "and NAME = '" + txtName + "'";} strWhere + = "order by id desc "; // projects use parameterized queries. Here are some advanced query conditions exposed to the Web layer. Personal comments on copying code: 1. Value Type and String concatenation are implicitly boxed; 2. SQL injection is dangerous. The correct method is userId. ToString () and filters out special characters in txtName to limit the length of the string. Note: filtering strings when splicing SQL statements does not completely prevent SQL injection. However, in most cases, splicing SQL statements in advanced queries is the simplest and most convenient, at this time, filter should not only filter some specified special characters, such as single quotes, equal signs, greater than/less than/equal to, spaces, parentheses and other dangerous characters. All characters except Chinese characters, English letters, and numbers should be filtered out (depending on the situation ). The length of the string is strictly limited. Generally, the keyword entered during query is not too long. If the user inputs a space, it is split into multiple conditions. This will minimize the chance of SQL injection. Finally, I would like to share with you a few small experiences. Although some of them are just syntactic sugar, they can help us write or read code more efficiently. I. It is very troublesome to use the null value of the reference type, because when the type is null, the vertex operator (.) will report an exception, so it is often necessary to make a non-null judgment. Can be used ?? The null merge operator reduces the amount of code. For example, copy the code // write an int ID; if (Request. Form ["ID"]! = Null & Request. Form ["ID"]. ToString ()! = "") {ID = Convert. toInt32 (Request. form ["ID"]. toString ();} // write the second int id; if (int. tryParse (Request. form ["ID"]? "", Out id) {}// method 1 string userName2 = string. Empty; if (Session ["userName"]! = Null) {userName2 = Session ["userName"]. ToString () ;}// method 2 string userName1 = Session ["userName"] = null? "": Session ["userName"]. ToString (); // method 3 string userName = (Session ["userName"]? ""). ToString (); copy code 2. Put all sessions or cookies in the Web project to a class for management. The most important purpose is to manage the index names in the Session independently, that is, do not enter the Session name for all pages except this class. It is possible that the language is not straightforward enough to directly use the code. Many people see this, including some common helper libraries on the Internet. View Code I want to know, what is the practical significance of this? HttpContext. Current does not perform the null check. SessionHelper is everywhere in the project. setSession ("name"), SessionHelper. as a result, the compiler cannot find the code referenced by GetSession ("name"). When many pages use this session, it will be a disaster to change the session name or delete the session. If the code is too large, there may be conflicts between multiple sessions, and the name is wrong, resulting in session loss. To overcome the preceding problems, you should write the View Code in the Session of the Web Project. when the project is used, the Session SessionManager will be added after successful logon. addUserLoginMark (the currently logged-on user object); SessionManager is determined during logon check on the page. getUserLogin (); returns whether it is null. Log out of SessionManager. RemoveUserLoginMark. In this way, you only need to call the API. You do not have to worry about what the Session name is. It is more convenient to delete or change the Session name. Of course, Session name duplication does not occur, then you are truly talented ). Of course, writing in this way does not have any disadvantages. Compared with the previous one, this method may not be able to be written once and used everywhere. You need to flexibly modify the corresponding code according to the current project, but the benefits are obvious. This method also applies to Cache and Cookie. 3. It is best not to use Request [] instead of Request. Form [] and Request. QueryString []. If the page has many requests. form [], Request. queryString [] and Session [] are recommended to retrieve all values from Page_Load and store them in variables, and convert them to the desired type. Full Request. form [], Request. the QueryString [] and Session [] compilers cannot check strings in [], which is prone to errors and affects reading, the same parameter may also need to be converted multiple times (this one is particularly useful for WebFrom serverless control development ). 4. Use as to replace the conversion between reference types (see the sixth one above ). We all know this, but we still find that many people are using forced conversion, including some excellent open-source projects. 5. RegisterClientScriptBlock, rule, RegisterStartupScript, RegisterOnSubmitStatement, RegisterClientScriptResource, and other methods require the front-end page to have form server Control (<form runat = "server"> </form> ). This means that when developing a WebForm without a server control, these items are useless (the same Page. IsPostBack should be careful ). 6. Microsoft does not recommend using Response. Write () to output JS directly in the background, and some browsers will indeed cause page deformation. However, it is found that many people are using it, including some excellent open-source projects. I am currently using <% = strMsg %> at the front end to receive messages sent from the backend. I don't know how to use it. 7. Finally, I will share with you a small piece of code written by myself, and add the EmptyDataTemplate template for the Repeater control (before the EmptyDataTemplate is in FooterTemplate ).

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.