How to initialize in an ASP.net application

Source: Internet
Author: User
Tags static class

Each program needs to initialize the process to read the configuration or set up some running environment (variables), for the ASP.net program, where to perform the initialization task?

I think most people should know the process of initializing in Global.asax, but there are some details that we need to focus on.

Use cases for this article

In the example code for this blog, Appinitializer contains the initialization implementation code for the site:

 
 
  1. public static Class Appinitializer
  2. {
  3. public static connectionstringsettings mynorthwindconnectionsetting {get; private set;}
  4. public static void Init ()
  5. {
  6. Reads the connection string.
  7. Loadconnectionstring ();
  8. Set up SQL Server cache dependency notification.
  9. Setsqldependency ();
  10. Other initialization operations.
  11. Othersinit ();
  12. }
  13. static void Loadconnectionstring ()
  14. {
  15. connectionstringsettings setting = configurationmanager.connectionstrings["MyNorthwind"];
  16. if (setting = null)
  17. throw new ConfigurationException ("The MyNorthwind connection string is not configured.) ");
  18. if (string. IsNullOrEmpty (setting. ConnectionString))
  19. throw new ConfigurationException ("There is no content specified for the MyNorthwind connection string. ");
  20. if (string. IsNullOrEmpty (setting. ProviderName))
  21. throw new ConfigurationException ("No providername specified for the MyNorthwind connection string. ");
  22. Saves the read-to connection string for use by the program.
  23. mynorthwindconnectionsetting = setting;
  24. }
  25. static void Setsqldependency ()
  26. {
  27. To determine if SQL Server version is more than 2005 version,
  28. The check code to open Service Broker is not listed.
  29. Sqldependency.start (mynorthwindconnectionsetting.connectionstring);
  30. }
  31. static void Othersinit ()
  32. {
  33. Other initialization operations.
  34. For example:
  35. 1. Load the necessary cached data.
  36. 2. Check the upload directory does not exist.
  37. 3. ...................
  38. }
  39. }

The intent of this code is clear, make sure that the database connection string is correctly configured, otherwise it will be reported in the form of an exception.

The sample program also has a page, default.aspx

 
 
  1. <body>
  2. <form id= "Form1" runat= "Server" >
  3. <div>
  4. </div>
  5. <p style= "line-height:150%;" >
  6. UserName: <asp:textbox id= "txtUserName" runat= "Server" width= "200px" text= "Fish Li" ></asp:textbox><br />
  7. Password: <asp:textbox id= "Txtpassword" runat= "Server" width= "200px" textmode= "Password" ></asp:TextBox> <br/>
  8. <asp:button id= "Btnlogin" runat= "server" text= "login" onclick= "Btnlogin_click"/>
  9. </p>
  10. </form>
  11. </body>

is actually a login page, the background code is:

 
 
  1. protected void Btnlogin_click (object sender, EventArgs e)
  2. {
  3. bool OK = false;
  4. using (SqlConnection connection
  5. = new SqlConnection (AppInitializer.MyNorthwindConnectionSetting.ConnectionString)) {
  6. Connection. Open ();
  7. Other database operations.
  8. OK = true;
  9. }
  10. if (OK)
  11. Response.Redirect ("default2.aspx");
  12. }

Global.asax Strange things you didn't think of!

Maybe some people would write their initialization code like this:

 
  
  
  1. void Application_Start (object sender, EventArgs e)
  2. {
  3. Code that runs when the application starts
  4. try {
  5. Appinitializer.init ();
  6. }
  7. catch (Exception ex) {
  8. Logexception (ex);
  9. // .....................
  10. }
  11. }

What's wrong with this code?

The clue to the question is: Why do you want to add a Try....catch statement because you know that an exception might occur?

If there is a real anomaly happening, will the subsequent request be followed by a variety of imaginary errors?

Obviously there is no exception to be eaten here, or the subsequent requests are certainly problematic because the settings they rely on are not properly initialized.

Well, then I'll get rid of the Try.....catch statement, so it's always OK:

 
  
  
  1. void Application_Start (object sender, EventArgs e)
  2. {
  3. Code that runs when the application starts
  4. Appinitializer.init ();
  5. }

It looks like a real operation.

Oh, I'm sorry, I forgot. Configure the connection string, this exception hint is too much force.

Do you want to add the connection string now?

Don't worry, imagine what it would be like if this site were a real online site.
There are two kinds of answers:

1. Another user has also initiated a request.

2. When the current user sees the error page, the current page is refreshed again.

Now I use Opera to play a second browsing user, or to open the same Web site.

It's so weird that the second user can actually open the page, OK, let him log in and try.

As a result, the second user sees an error condition that is completely different from the first user.

If the first user refreshes his browser at this time, the discovery page can be displayed again, but when you log on, you will see the same exception information as the second user.

This sample code is simply too simple, I think the maintenance personnel according to NullReferenceException this clue to go down, soon can find the answer. If the initialization code is more complex, such as the exception in Setsqldependency (), then the program will still work, but we expect the cache dependency may be ineffective, and ultimately can produce performance problems, the difficulty of troubleshooting will be much.

Remember to do the project, I have encountered this situation, then feel very strange, why refresh the Yellow pages, but the wrong behind is very frustrating people, and finally let me sum up this lesson. So I suggest: if there is an exception in the initialization phase, simply do not let the program continue to run, each request will directly display the Yellow pages, until troubleshooting.

How do I guarantee that initialization exceptions are always displayed?

When an exception is initialized, how do you ensure that the initialization exception is always displayed?

method is not difficult, we need to modify the code:

 
 
  1. private static Exception s_initexception;
  2. void Application_Start (object sender, EventArgs e)
  3. {
  4. try {
  5. Appinitializer.init ();
  6. }
  7. catch (Exception ex) {
  8. Note the initialization exception.
  9. S_initexception = ex;
  10. }
  11. }
  12. protected void Application_BeginRequest (object sender, EventArgs e)
  13. {
  14. If there is an initialization exception, throw it out.
  15. Until the developer discovers the exception, and the exception is resolved.
  16. if (s_initexception!= null)
  17. Throw s_initexception;
  18. }

Now no matter how many users are accessing it, or how many times the first visitor refreshes the browser, you will see the same exception message:

Description: This problem with Global.asax does not exist in the integrated mode of IIS7 above version.

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.