Sunday 9 December 2012

Introduction about ASP.Net Application and Pages

Goals:
  • Present main concepts of the ASP.NET applications.
  • Introduce web pages and their events.
Steps:
  1. Create a new project - Visual C# / Web / ASP.NET Web Application.
    There is also possibility to create a 'Web Site' (menu File / New / Web Site), but the 'Web Application' should be preferred. The Web Site has no project file. The lack of a project file can make the application's configuration much harder (sometimes even impossible)
  2. Take a look into the generated project.
    • The AssemblyInfo.cs file, as usually in .NET C# projects, contains definition of the project assembly's properties.
    • The App_Data item is a folder, where all data files used by the project should be kept, e.g. text, xml, or database files. This folder is configured in a special way by default - the user account that is used to run the application (for example, the local ASP.NET account) has permissions to read, write, and create files in this folder.
    • The Default item is a web page (aka 'web form'). There are 3 files generated as parts of this item:
      • Default.aspx contains the design of a web page. All the HTML and ASP.NET tags are placed here (unless some of they are generated dynamically in the source code). There are 2 different views for editing this file: 'Design' and 'Source'. In the Design mode all the design can be visually modified, and in the Source mode you can manually modify all tags. There is also the 'Split' mode which allows to use the Design and Source modes simultaneously.
        The visual designer of ASP.NET pages built in Visual Studio (i.e. the Design mode) is a quite comfortable and powerful visual editor for HTML files, in fact.
      • Default.aspx.cs is so called code-behind file, it contains C# source code for the page. Usually, the code file contains methods responding for the page's or its controls events and some helpful methods.
      • Default.aspx.designer.cs contains C# code generated by the Visual Studio in response for modification of the .aspx file. In example, after adding a control to the .aspx file, a member of the page's class representing this control will be automatically added to this file.
    • The Web.config file is a configuration file of the web application. There are many web-related configuration options allowed to be placed here. This file serves also as a normal configuration file for the .NET project, just like .exe.config files for Windows Forms or console projects.
  3. Add text to the Default page:
  4. Run the project (Ctrl+F5 or menu Debug / Start Without Debugging). Note the following actions:
    • Visual Studio compiles the project.
    • The ASP.NET Development Server is started in the system:
    • The default Internet browser starts and opens the address: http://localhost:49691 (the port number can vary):
    • Take a look into source code of the generated page (use the 'View Source Code' option in the browser):
      <!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><title>
      
      </title></head>
      <body>
          <form name="form1" method="post" action="Default.aspx" id="form1">
      <div>
      <input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwULLTE2MTY2ODcyMjlkZO/ZMzP2K7pbdL0x/efEBPI9tp28" />
      </div>
      
          <div>
          
              Welcome on the Default page.</div>
      
          </form>
      </body>
      </html>
      Compare this code with source code of the Default.aspx file in Visual Studio and note some differences - ASP.NET automatically generates the output HTML code based on the source ASP.NET code. For most complicated pages using some ASP.NET controls there will be more differences.
  5. Modify in Visual Studio the text displayed on the page and save the file. Do not compile the project, just refresh the page in the browser. Note that the text has changed. ASP.NET automatically checks for changes in source code files and, when there is such need, recompiles the project.
  6. Add a new Web Form to the project (right click on the project in the Solution Explorer window: Add / New Item / Web Form). Name it Info.aspx:
    • Add the following code to the Page_Load method in the Info.aspx.cs file:
      Response.Write(string.Format("ApplicationPath: {0}<br>", Request.ApplicationPath));
      Response.Write(
      string.Format("CurrentExecutionFilePath: {0}<br>", Request.CurrentExecutionFilePath));
      Response.Write(
      string.Format("FilePath: {0}<br>", Request.FilePath));
      Response.Write(
      string.Format("Path: {0}<br>", Request.Path));
      Response.Write(
      string.Format("PhysicalApplicationPath: {0}<br>", Request.PhysicalApplicationPath));
      Response.Write(
      string.Format("ApplicationPath: {0}<br>", Request.ApplicationPath));
      Response.Write(
      "<br><br>");
      Response.Write(
      string.Format("Physical ~ is {0}<br>", Server.MapPath("~")));
      • The Page_Load method is automatically attached to the Load event of the page. The AutoEventWireup property of the Page declaration starting the Info.aspx file is responsible for this.
      • The Response object used in the C# code is a property of the current page. (All the code in the .aspx.cs file is a part of the page's class, so all its properties are directly available.) The Write method allows to directly generate the output HTML code. (This is very powerful possibility but should not be overused in conjunction with using ASP.NET controls.)
      • The Request is also a property of the current page. It represents the request coming from the user's browser. It makes available some very useful properties, in example these used in the above code.
      • The '~' character in logical paths always represents the main folder of the application. It is used in logical web paths, not in physical disk ones.
      • To convert logical web path to physical disk path, the MapPath method of the HttpServerUtility class can be used. An object of this class is available as the Server property of the current page.
    • Run the application (Ctrl+F5):
    • Make the Default.aspx page the starting one (right click on the page in the Solution Explorer window: Set as Start Page).
  7. Add to the Default.aspx page options that will allow to move to the Info.aspx page (currently, the only option is manual modification of the address displayed in the browser). There are a few ways to do it:
    • The 1st way is to add a simple HTML hyperlink to the Default.aspx file:

      Note, a relative path (i.e. no path - both files are in the same directory) was used. It is always a good idea to avoid hard-coding absolute paths).
    • The 2nd way is to use ASP.NET control that works like an HTML hyperlink. Drop to the Default.aspx design a Hyperlink control dragged from the Standard group from the Toolbox window.
    • The 3rd way is to force the user's browser to ask for another page. This can be done only in response for a request from the browser. To get a request, a button will be used.
      • Drop on the Default.aspx design a Button control (from the Toolbox):
      • Double click the button to generate a handler for its Click event. Add the following code to the handler:
        protected void Button1_Click(object sender, EventArgs e)
        {
            Response.Redirect(
        "Info.aspx");
        }
      • Note that in this way one additional transmission from the server to the client and back is required, so, in most cases, such solution makes sense only when redirection is done to another application or server. Such redirections within a single web application are extremely inefficient.
    • Another way is transferring requests within a single web application. This can be using the Transfer method of the HttpServerUtility class.
      • Add a button like in the previous solution:
      • Add the following code in the Click event handler:
        protected void Button2_Click(object sender, EventArgs e)
        {
            Server.Transfer(
        "Info.aspx");
        }
      • This solution is definitely more efficient than the previous one (no additional round trip of a request/response pair is necessary), but there are some drawbacks
        • The user will see in the browser the address of the Default.aspx page, but the content of the Info.aspx file:
        • The Transfer method throws ThreadAbortException to abort processing of the original request (for the Default.aspx page, in this example).
    • Yet another way is using so-called cross-page posting. Normally, all controls post back to the same page (that's why the C# code for responding for Click event for the above buttons was located on the Default.aspx page). Cross-page posting consists in specifying another page as a target for, in example, clicking a button.
      • Add a button to the Default.aspx page and set its PostBackUrl property to Info.aspx:
  8. Test some of web pages' events:
    • Add a new Web Form to the project.
    • Add the following code to the .aspx.cs file:
      Button dynamicButton;
      protected override void OnInit(EventArgs e)
      {
          Response.Write(
      "=== Init event ===<br>");
          
      base.OnInit(e);

          dynamicButton =
      new Button();
          dynamicButton.Text =
      "Dynamic button";
          dynamicButton.Click +=
      new EventHandler(DynamicButton_Click);
          Form.Controls.Add(dynamicButton);
      }
      void DynamicButton_Click(object sender, EventArgs e)
      {
          Response.Write(
      "=== DynamicButton_Click event ===<br>");
      }
      protected override void OnLoad(EventArgs e)
      {
          Response.Write(
      "=== Load event ===<br>");
          
      base.OnLoad(e);
      }
      protected override void OnPreRender(EventArgs e)
      {
          Response.Write(
      "=== PreRender event ===<br>");
          
      base.OnPreRender(e);

          dynamicButton.OnClientClick =
      "alert('Hello from Dynamic Button')";
      }
    • Run the application and test how it works:
    • In this code instead of the Page_Load method, the OnLoad overridden method was used. In both cases the result is the same - code from these methods is executed during the Load event. The OnLoad method should be preferred, because the Page_Load method is based on the mechanism of 'wiring' automatically methods to events by their names, which is slower than direct overriding methods.
    • Only controls added to the page's Form property (or contained within the <form> tag) will be rendered to the output HTML code. This is the reason of calling the Form.Controls.Add method.
    • The OnClientClick property of a button can contain JavaScript code to be executed in the user's browser.
  9. The source code of the web application can be debugged. It concerns both the C# and JavaScript code. The support for debugging is not limited to the Internet Explorer browser.
    To debug the application just press F5 button in Visual Studio. If it is the first try of debugging, a message appears:

    Note that (as mentioned in the message) enabling debugging should be disabled before deploying the application to the production server.
  10. Apart from the page's and its controls' events, there are also application's events available. There are only a few of application's events, but some of them can be extremely useful.
    • Add to the project the Global Application Class:
    • Add to the Application_Start method in the Global.asax file the following line:
      Application["StartTime"] = DateTime.Now;
      This line allows to store time of the beginning of the application in the dictionary of values shared by all pages of the application.
    • Add to the Page_Load method of the Info.aspx page the following line:
      Response.Write(string.Format("Application[\"StartTime\"]: {0}<br>", Application["StartTime"]));
    • Run the application, refresh the Info.aspx page many times and note that the value of 'StartTime' does not change. Rebuild the application, refresh the Info.aspx in the browser and note a new value. It proves that rebuilding the source code causes restart of the application.
[Source code]

No comments :