Krzysztof Mossakowski
For Students
  • Generate Web Site Starter Kit project using Visual Studio (it is a sample application with quite rich functionality)
    • menu File / New / Web Site
    • Choose 'Personal Web Site Starter Kit' to see sample Web application created using ASP.NET
    • Note the 'Location' option on the 'New Web Site' window
      • File System - the Web application will be created in a folder on your local or a remote computer. The built-in Visual Studio Web server will be used to serve the application (unless the IIS is configured).
      • HTTP - the files are stored under the Web application root (typically, Inetpub/wwwroot). IIS (Internet Information Services) will be used as a Web server (it must be installed in the system).
      • FTP - the FTP protocol will be used to store source files.
    • Take a look at files generated by Visual Studio
      • .aspx files
        • Double click the .aspx file in the 'Solution Explorer' window to see the source (HTML code + server controls).
        • Click the 'Design' button to see the Design view . Note all possibilities of visual edition of aspx files (e.g properties, events, the 'Tasks' window, etc.).
        • Right click on the file in the 'Solution Explorer' window and choose 'View Code' to see the source code for the page, written in C# (according to rules of so-called Code-Behind model), or expand the '+' sign in the tree presented in the window.
      • Normal folders
        • Normal folders can be created in the 'Solution Explorer' and are represented as folders on the disk.
        • They allow to use special credentials for some parts of the application, e.g. the content in the 'Admin' folder is available only for members of 'Administrators' group (try to find appropriate setting in the web.config file).
      • Special folders (with the 'App_' prefix)
        • 'App_Code' - a place for source code for utility classes and business objects that should be compiled as a part of your application.
        • 'App_Data' - a place for data files (XML files, MS Access databases, SQL Server database files, etc.).
        • 'App_Themes' - contains a collection of files (.skin and .css files, as well as image files and generic resources) that define the appearance of ASP.NET Web pages and controls.
      • .css files
        • Double click the file to see its source code.
        • Right click on a defined element and choose 'Build Style' option - note very functional editor of CSS styles (built-in feature of Visual Studio).
        • New CSS elements can be added using the 'Add Style Rule' option.
      • Default.master - it is a master page
        • A single master page defines the look and feel and standard behavior that you want for all of the pages (or a group of pages) in your application.
        • Elements of the master page can be edited as elements of normal pages, but changes will be visible on all pages which use this master page (i.e. all pages which have 'MasterPageFile="~/Default.master"' phrase in the @Page directive).
      • Global.asax - it is the file in which code executed for application's events should be placed.
        • In the sample project one event, Application_Start, is handled.
      • Handler.ashx - a generic handler file that contains code that implements the IHttpHandler interface to handle all incoming requests.
      • web.config - the configuration file
        • Web.config files can appear in multiple directories in ASP.NET applications.
      • web.sitemap - a file with the content of the Web site.
        • It is used by the site navigation system to create navigation menus or trees.
        • In the sample project this file is used by the SiteMapPath control placed on the master page.
    • Compile and run the project.
      • Please note that 'ASP.NET Development Server' runs and is visible as an icon in the tray area. It allows to run ASP.NET Web projects on systems where IIS (Internet Information Services) is not installed.
      • The default browser is run and the start page of the project is displayed (you can change the start page in the 'Solution Explorer' window using right mouse click and choosing the 'Set As Start Page' option).
      • Take a look at the source of the page displayed in the browser, compare it with the source code visible in Visual Studio. Note, that all server controls (with <asp: prefix) has been rendered as standard elements of HTML.


  • Create a simple calculator
    • Create a new Web site (menu File / New / Web Site - ASP.NET Web Site).
    • Add necessary controls (using the Design view of the page) and set their properties.
      • The DropDownList (called ComboBox in Windows applications) can be filled in the Visual Designer.
      • Visual Designer uses flow layout by default (i.e. controls are positioned from the left to the right, according to the width of the browser window). To position controls absolutely, use CSS styles.
      • Add code for the event of pushing '=' button, e.g.:
        resultTextBox.Text = "";
        double left, right;
        if (!double.TryParse(leftTextBox.Text, out left)) {
            statusLabel.Text = "The first number is incorrect.";
        } else if (!double.TryParse(rightTextBox.Text, out right)) {
            statusLabel.Text = "The second number is incorrect.";
        } else if (operatorDropDownList.SelectedValue == "/" && 
            right < 1e-307 && right > -1e-307) 
        {
            statusLabel.Text = "Divide by 0";
        } else {
            double result = 0;
            switch (operatorDropDownList.SelectedValue) {
                case "+":
                    result = left + right;
                    break;
                case "-":
                    result = left - right;
                    break;
                case "*":
                    result = left * right;
                    break;
                case "/":
                    result = left / right;
                    break;
            }
            resultTextBox.Text = result.ToString();
            statusLabel.Text = "";
        }    
        
      • Run the project.
    • Change the look of the page by using a .css file
      • Add new 'Style Sheet' item to the project.
      • Define background color and a class that will be used by the label to change its font and color.
      • Drag the .css file from the 'Solution Explorer' window and drop it on the target form (or manually add the following line in the <head> section)
        <link href="StyleSheet.css" rel="stylesheet" type="text/css" />
        
      • Set the 'CssClass' property of the statusLabel control to the name of the class created in the .css file.
      • Do not recompile the page, just save it and refresh in the browser. The request from the browser automatically forces the page to recompile if the source code was changed.
    • Note that there are special validation controls (similar to those from Windows Forms) which can be used instead of manual changing a text of a Label control. Validation controls can be found in the 'Validation' group in the Toolbox window.
    • Understanding the postback mechanism
      • Remove items added to the DropDownList control using Visual Designer - open the page in the Source view and remove the following code:
        <asp:ListItem>+</asp:ListItem>
        <asp:ListItem>-</asp:ListItem>
        <asp:ListItem>*</asp:ListItem>
        <asp:ListItem>/</asp:ListItem>
        
      • Add the following code to the Page_Load method (in the Default.aspx.cs file):
        operatorDropDownList.Items.Add("+");
        operatorDropDownList.Items.Add("-");
        operatorDropDownList.Items.Add("/");
        operatorDropDownList.Items.Add("*");
        
      • Compile the project and run (or just refresh the page in the browser). Note, that after making two calculations, there are 8 operators in the list - each calculation adds new 4 operators. To add operators only during the initial loading of the page, change the code to the following:
        if (!IsPostBack) {
            operatorDropDownList.Items.Add("+");
            operatorDropDownList.Items.Add("-");
            operatorDropDownList.Items.Add("/");
            operatorDropDownList.Items.Add("*");
        }    
        
        • The IsPostBack property gets a value indicating whether the page is being loaded in response to a client postback, or if it is being loaded and accessed for the first time.
    • Using themes (a new feature of ASP.NET 2.0).
      • Add the App_Themes folder to the project (right click on the 'Solution Explorer' window, 'Add ASP.NET Folder' / Theme).
      • Rename the new theme to 'RedTheme'.
      • Add a skin file to the theme (right click on the theme in the 'Solution Explorer' window, 'Add New Item', 'Skin File').
      • In the .skin file, add a normal control definition by using declarative syntax, but include only the properties that you want to set for the theme. The easiest way is to modify the look of a control on a normal page, copy generated code, and remove all properties which are not necessary.
      • <asp:TextBox runat="server" BackColor="#FFC0C0" BorderColor="Red" />
        <asp:DropDownList runat="server" BackColor="#FFC0C0" ForeColor="Red" />
        <asp:Button runat="server" BackColor="#FFC0C0" BorderColor="Red" ForeColor="Red" />
        
      • Add the CSS file to the theme (right click on the theme, 'Add New Item', 'Style Sheet') and modify the background color.
      • A theme can be applied to all pages of the Web application by change settings in the web.config file,
        <configuration>
            <system.web>
                <pages theme="RedTheme" />
            </system.web>
        </configuration>
        
        or to individual pages by settings the 'Theme' attribute of the @Page directive
        <%@ Page Theme="RedTheme" %>
        

      • Create a new theme, analogous to the first one, but green (the easiest way is to copy and paste a theme in the 'Solution Explorer' window), name it 'GreenTheme'.
        • Modify color values to make green colors.
      • The theme used by the page can be changed programmatically in the PreInit event:
        • Add two hyperlinks to allow the user to change a theme. Set NavigateUrl properties of these hyperlink to
          ~/Default.aspx?theme=green
          
          and
          ~/Default.aspx?theme=red
          
          respectively. (Note the '~' sign as a path to the current Web project.)
        • Add a handler for the PreInit event. It is enough to paste the following code to the Default.aspx.cs file.
          protected void Page_PreInit(object sender, EventArgs e)
          {
              switch (Request.QueryString["theme"]) {
                  case "red":
                      Page.Theme = "RedTheme";
                      break;
                  case "green":
                      Page.Theme = "GreenTheme";
                      break; 
              }
          }
          



  • Using Master Pages and Site Navigation
    • Create a new project (ASP.NET Web Site).
    • Add a master page to the project (menu Website / Add New Item / Master Page).
    • Edit the master page to make the following view (make sure that both images are hyperlinks):
      • Both the Design view and Source view can be used - HTML code can be edited directly.
      • Add images to the project - it allows to point them as values of controls' properties.
      • Here is sample solution:
         <form id="form1" runat="server">
          <div>
              <asp:Panel ID="Panel1" runat="server" BackColor="Maroon" Width="100%">
              <table width="100%">
                  <tr>
                     <td>
                       <a href="http://www.mini.pw.edu.pl">
                         <asp:Image ID="Image1" runat="server" ImageUrl="~/mini_logo.gif" />
                       </a>
                     </td> 
                     <td style="width: 90%">
                       <div style="text-align: center">
                         <asp:Label ID="Label1" runat="server" Font-Bold="True" Font-Names="tahoma" ForeColor="White"
                             Text="My Great Web Site"></asp:Label>
                       </div>
                    </td> 
                     <td>
                       <a href="http://www.pw.edu.pl">
                         <asp:Image ID="Image2" runat="server" ImageUrl="~/pw_logo.gif" />
                       </a>
                     </td> 
                  </tr>
              </table>
              </asp:Panel>
              <asp:contentplaceholder id="ContentPlaceHolder1" runat="server">
              </asp:contentplaceholder>
              <asp:Panel ID="Panel2" runat="server" BackColor="Maroon" Width="100%">
              <table width="100%">
                  <tr>
                     <td style="width: 100%">
                       <div style="text-align: center">
                         <asp:Label ID="Label2" runat="server" Font-Bold="True" Font-Names="tahoma" ForeColor="White"
                             Text="Copyright © 2006"></asp:Label>
                       </div>
                    </td> 
                  </tr>
              </table>
              </asp:Panel>
          </div>
          </form>
        
    • Modify the default.aspx page to use the master page.
      • Set the MasterPageFile property.
      • Switch to the Design mode and click the 'Content - Content1 (Master)' control.
      • Right click the Content control and choose the 'Create Custom Content' option.
      • You are able to write content of the page now. Write something or add any control to see how it works.
      • Try to compile the page. You will see 'Only Content controls are allowed directly in a content page that contains Content controls'. Modify the content according to this explanation, e.g.:
        <%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" 
            Inherits="_Default" MasterPageFile="~/MasterPage.master" %>
        <asp:Content ID="Content1" runat="server" ContentPlaceHolderID="ContentPlaceHolder1">
            <asp:Label ID="Label1" runat="server" Text="The beginning of the greatest Web site."></asp:Label>
        </asp:Content>
        
      • In the Design view of your page you should see both the content and elements of the master page (grayed).
      • Compile your project and run it in the browser.
    • Add new pages to the project, make sure to check the 'Select master page' option in the 'Add New Item' window':
      • about.aspx, president.aspx, vicepresident.aspx, keyaccountmanager.aspx, callcenter.aspx, clients.aspx
      • Add content to these pages.
      • Make the Web site navigable:
        • Add a Site Map to the project ('Add New Item' - Site Map).
        • Modify the Site Map to adapt to site's content:
          <?xml version="1.0" encoding="utf-8" ?>
          <siteMap xmlns="http://schemas.microsoft.com/AspNet/SiteMap-File-1.0" >
              <siteMapNode url="default.aspx" title="Home"  description="The beginning">
                  <siteMapNode url="about.aspx" title="About us"  description="Short information about the company">
                      <siteMapNode url="president.aspx" title="The President"  description="Our great president" />
                      <siteMapNode url="vicepresident.aspx" title="The Vice-President"  description="Very clever vice-president" />
                      <siteMapNode url="keyaccountmanager.aspx" title="Key Account Managers"  description="Key account managers" />
                      <siteMapNode url="callcenter.aspx" title="Call Center"  description="Call Center Department" />
                  </siteMapNode>
                  <siteMapNode url="clients.aspx" title="Clients"  description="Our clients" />
              </siteMapNode>
          </siteMap>
          
        • Add navigational controls to the master page:
          • Add the SiteMapPath Control (from the Navigation group on the Toolbox). It should start working automatically, taking all necessary data from the Web.sitemap file.
          • Add the SiteMapDataSource control (from the Data group on the Toolbox).
          • Add the TreeView control (from the Navigation group). Set the DataSourceID property to SiteMapDataSource1 (note, that you can see your site map in the Design view).
          • Compile and run the project. Your users have two possibilities to navigate on your great Web site.


  • State management
    • Create a new Web site.
    • Enable tracing on the Default.aspx page by adding Trace="true" parameter for the @Page directive:
      <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" 
          Inherits="_Default" Trace="true"%>
      
    • Compile and run the page in a browser (note rich information about internal data of the application, session, and page).
    • Add controls to the page which allow to add and remove application, session and cookie variables.
      • Make sure that all 3 radio buttons have the same (not empty) value of the GroupName property.
      • Add code for events of pushing buttons (just double-click the button to generate the method in the Default.aspx.cs file.
        protected void addButton_Click(object sender, EventArgs e)
        {
            if (applicationRadioButton.Checked) {
                Application[keyTextBox.Text] = valueTextBox.Text;
            } else if (sessionRadioButton.Checked) {
                Session[keyTextBox.Text] = valueTextBox.Text;
            } else if (cookieRadioButton.Checked) {
                HttpCookie cookie = new HttpCookie(keyTextBox.Text, valueTextBox.Text);
                Response.Cookies.Add(cookie);
            }
        }
        
        protected void removeButton_Click(object sender, EventArgs e)
        {
            
            if (applicationRadioButton.Checked) {
                Application.Remove(keyTextBox.Text);
            } else if (sessionRadioButton.Checked) {
                Session.Remove(keyTextBox.Text);
            } else if (cookieRadioButton.Checked) {
                Response.Cookies.Remove(keyTextBox.Text);
            }
        }
        
    • Add and remove variables, observe values displayed in the trace area, and try to understand the idea of application, session, and cookie variables.
      • All three containers of custom variables are dictionaries, you provide a name of the key and a value for this key.
      • All application variable are shared between all users currently using the application. It means, that if you run your page in two different browsers (also on different systems), all variables will be accessible (visible and available for modification) for both users.
      • Session variables are limited to the session of a user. Sessions are identified by a unique session identifier (SessionID). The session state can be configured in the sessionState node of the web.config file.
      • Cookies allow to store user-specific information on the client side. For example, when a user visits your site, you can use cookies to store user preferences or other information. When the user visits your Web site another time, the application can retrieve the information it stored earlier. You can track cookies (also remove them and block them) in your browser's options.