November 28, 2010

In many web applications we want to load a control based on what is selected in another control. For example, loading a ListBox control or a DropDownList control based on what is selected in another ListBox or DropDownList control. The situation is not limited to only these controls but could also use RadioButtonList, CheckBoxList controls, etc.

In this example,  I have created a page that populates ListBox control with States value based on what Country is selected in another ListBox. I have added 2 ListBox controls – for State and Country, a Button and a Label control to the page. From code-behind page, I have created a DataTable that holds the country and corresponding state values. When an item is selected from Country ListBox, the State ListBox is populated. The AutoPostBack property for Country ListBox is set to true and SelectedIndexChanged event is implemented.

When the Button is clicked, the Label control’s Text property is populated to display the state and country that has been selected from the ListBox controls. The code for the aspx page and code-behind is below.

aspx page
  1. <%@ Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="LoadListboxFromDatatable.aspx.cs" Inherits="WebApplication1.LoadListboxFromDatatable" %>
  2. <asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
  3. </asp:Content>
  4. <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
  5.  
  6.     <asp:ListBox ID="ListBoxCountry" runat="server" AutoPostBack="True"
  7.         onselectedindexchanged="ListBoxCountry_SelectedIndexChanged">
  8.         <asp:ListItem>Select:</asp:ListItem>
  9.         <asp:ListItem>Australia</asp:ListItem>
  10.         <asp:ListItem>US</asp:ListItem>
  11.         <asp:ListItem>India</asp:ListItem>
  12.     </asp:ListBox>
  13.     <asp:ListBox ID="ListBoxState" runat="server"></asp:ListBox>
  14.     <br />
  15.     <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Show" />
  16.     <asp:Label ID="LStatus" runat="server"></asp:Label>
  17.  
  18. </asp:Content>

 

Code-behind
  1. using System;
  2. using System.Data;
  3.  
  4. namespace WebApplication1
  5. {
  6.     public partial class LoadListboxFromDatatable : System.Web.UI.Page
  7.     {
  8.         protected void Page_Load(object sender, EventArgs e)
  9.         {
  10.  
  11.         }
  12.  
  13.         protected void ListBoxCountry_SelectedIndexChanged(object sender, EventArgs e)
  14.         {
  15.             string country = ListBoxCountry.SelectedValue;
  16.             ListBoxState.Items.Clear();
  17.  
  18.             foreach (DataRow rows in GetStates().Rows)
  19.             {
  20.                 if (rows[0].ToString() == country)
  21.                     ListBoxState.Items.Add(rows[1].ToString());
  22.             }
  23.         }
  24.  
  25.         private DataTable GetStates()
  26.         {
  27.             DataTable dt = new DataTable();
  28.             dt.Columns.Add("Country", typeof(string));
  29.             dt.Columns.Add("State", typeof(string));
  30.  
  31.             dt.Rows.Add(new object[] { "US", "Los Angeles" });
  32.             dt.Rows.Add(new object[] { "US", "Virginia" });
  33.             dt.Rows.Add(new object[] { "US", "Ohio" });
  34.             dt.Rows.Add(new object[] { "Australia", "NSW" });
  35.             dt.Rows.Add(new object[] { "Australia", "Victoria" });
  36.             dt.Rows.Add(new object[] { "Australia", "Tasmania" });
  37.             dt.Rows.Add(new object[] { "India", "Maharastra" });
  38.             dt.Rows.Add(new object[] { "India", "West Bengal" });
  39.             dt.Rows.Add(new object[] { "India", "Assam" });
  40.  
  41.             return dt;
  42.         }
  43.  
  44.         protected void Button1_Click(object sender, EventArgs e)
  45.         {
  46.             LStatus.Text = "Country: " + ListBoxCountry.SelectedValue + "; State: " + ListBoxState.SelectedValue;
  47.         }
  48.     }
  49. }

November 21, 2010

The asp.net FileUpload control allows a user to browse and upload files to the web server. From developers perspective, it is as simple as dragging and dropping the FileUpload control to the aspx page. An extra control, like a Button control, or some other control is needed, to actually save the file.

aspx page
  1. <asp:FileUpload ID="FileUpload1" runat="server" />
  2. <asp:Button ID="B1" runat="server" Text="Save" OnClick="B1_Click" />

By default, the FileUpload control allows a maximum of 4MB file to be uploaded and the execution timeout is 110 seconds. These properties can be changed from within the web.config file’s httpRuntime section. The maxRequestLength property determines the maximum file size that can be uploaded. The executionTimeout property determines the maximum time for execution.

web.config file
  1. <httpRuntime maxRequestLength="8192" executionTimeout="220"/>

From code behind, the mime type, size of the file, file name and the extension of the file can be obtained. The maximum file size that can be uploaded can be obtained and modified using the System.Web.Configuration.HttpRuntimeSection class.

Files can be alternatively saved using the System.IO.HttpFileCollection class. This collection class can be populated using the Request.Files property. The collection contains HttpPostedFile class which contains a reference to the class.

Code behind
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5. using System.Web.UI;
  6. using System.Web.UI.WebControls;
  7. using System.IO;
  8. using System.Configuration;
  9. using System.Web.Configuration;
  10.  
  11. namespace WebApplication1
  12. {
  13.     public partial class WebControls : System.Web.UI.Page
  14.     {
  15.         protected void Page_Load(object sender, EventArgs e)
  16.         {
  17.         }
  18.  
  19.         //Using FileUpload control to upload and save files
  20.         protected void B1_Click(object sender, EventArgs e)
  21.         {
  22.             if (FileUpload1.HasFile && FileUpload1.PostedFile.ContentLength > 0)
  23.             {
  24.                 //mime type of the uploaded file
  25.                 string mimeType = FileUpload1.PostedFile.ContentType;
  26.  
  27.                 //size of the uploaded file
  28.                 int size = FileUpload1.PostedFile.ContentLength; // bytes
  29.  
  30.                 //extension of the uploaded file
  31.                 string extension = System.IO.Path.GetExtension(FileUpload1.FileName);
  32.                 
  33.                 //save file
  34.                 string path = Server.MapPath("path");                
  35.                 FileUpload1.SaveAs(path + FileUpload1.FileName);
  36.                 
  37.             }
  38.             //maximum file size allowed
  39.             HttpRuntimeSection rt = new HttpRuntimeSection();
  40.             rt.MaxRequestLength = rt.MaxRequestLength * 2;
  41.             int length = rt.MaxRequestLength;
  42.        
  43.             //execution timeout
  44.             TimeSpan ts = rt.ExecutionTimeout;
  45.             double secomds = ts.TotalSeconds;
  46.  
  47.         }
  48.  
  49.         //Using Request.Files to save files
  50.         private void AltSaveFile()
  51.         {
  52.             HttpFileCollection coll = Request.Files;
  53.             for (int i = 0; i < coll.Count; i++)
  54.             {
  55.                 HttpPostedFile file = coll[i];
  56.  
  57.                 if (file.ContentLength > 0)
  58.                     ;//do something
  59.             }
  60.         }
  61.     }
  62. }

November 20, 2010

The Validation Summary control in asp.net displays error messages when the button is clicked. The other validation controls, like Required Field Valuators or Compare Valuators controls displays error messages when the controls it’s validating loses focus or changes. There is no built in control that displays a summary of all validation errors in a separate controls.

In this blog post, I will create a asp.net page, add couple of controls – Textbox and DropDownList and add validation controls for these. I will also add custom javascript that checks the validation controls are displaying error messages and populates the custom validation control accordingly.

From the javascript, I have checked whether the validation controls are showing any messages and populated the validation summary section. Also, OnBlur event of Textbox and onchange event of Dropdownlist is used to check for the errors.

Code Snippet
  1. <%@ Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Validation.aspx.cs" Inherits="WebApplication1.Validation" %>
  2. <asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
  3. <script type="text/javascript">
  4.     function ShowError() {
  5.         var msg = document.getElementById("spanError");
  6.         var reqV = document.getElementById('<%= RequiredFieldValidator1.ClientID %>');
  7.         var comV = document.getElementById('<%= CompareValidator1.ClientID %>');
  8.  
  9.         msg.innerHTML = "";
  10.  
  11.         if (reqV.style.visibility == "visible")
  12.             msg.innerHTML += "Textbox1 is required" + "<br/>";
  13.  
  14.         if (comV.style.visibility == "visible")
  15.             msg.innerHTML += "Drop down list is required";
  16.                          
  17.     }
  18.  
  19. </script>
  20. </asp:Content>
  21. <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
  22.  
  23.  
  24.     <asp:TextBox ID="TextBox1" runat="server" onblur="ShowError()"></asp:TextBox>
  25.     <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
  26.         ControlToValidate="TextBox1" ErrorMessage="*"></asp:RequiredFieldValidator>
  27.     <br />
  28.     <asp:DropDownList ID="DropDownList1" runat="server" onchange="ShowError()">
  29.         <asp:ListItem>Select:</asp:ListItem>
  30.         <asp:ListItem>1</asp:ListItem>
  31.     </asp:DropDownList>
  32.     <asp:CompareValidator ID="CompareValidator1" runat="server"
  33.         ControlToValidate="DropDownList1" ErrorMessage="*"
  34.         Operator="NotEqual" ValueToCompare="Select:"></asp:CompareValidator>
  35.     <br />
  36.     <asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="ShowError()" />
  37.  
  38.     <div>Validation Summary:<br />
  39.     <span id="spanError"></span>
  40.     </div>
  41.  
  42. </asp:Content>

November 15, 2010

Http handlers in asp.net implement the System.Web.IHTTPHandler interface and provides low level Request and Response API to respond to the incoming Http requests. Using this method, we can setup a different file extension instead of .aspx to handle the request.

In this example, I will create a simple handler and use .example as the extension to call the page. First, I will add a class that implements the IHTTPHandler class as below.

Code Snippet
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5. using System.Text;
  6.  
  7. namespace WebApplication1
  8. {
  9.     public class CustomHandler : IHttpHandler
  10.     {
  11.         public bool IsReusable
  12.         {
  13.             get { return false; }
  14.         }
  15.  
  16.         public void ProcessRequest(HttpContext context)
  17.         {
  18.             HttpRequest request = context.Request;
  19.             HttpResponse response = context.Response;
  20.             response.Write(Html());
  21.         }
  22.  
  23.         public string Html()
  24.         {
  25.             StringBuilder sb = new StringBuilder();
  26.             sb.Append("<html><head><title>Custom Handler</title></head>");
  27.             sb.Append("<body>Test page to demonstrate custom handler</body></html>");
  28.             return sb.ToString();        
  29.         }
  30.     }
  31. }

 

The IsReusable() and ProcessRequest(HttpContext context) methods need to be implemented as part of implementing the interface. The HttpContext class contains reference to the Request and Response objects. To send custom html as the response, another method Html() is written that return some html content as string.

To be able to use this code and use .example as the file extension, the <system.web> section of web.config file needs to be updated. The code is shown below.

Code Snippet
  1. <httpHandlers>
  2.   <add verb="*" path="*.example" type="WebApplication1.CustomHandler"/>
  3. </httpHandlers>

When any page with file name, for example, example.example is called on the browser, custom html is returned as defined in  ProcessRequest method in CustomHandler class.

November 14, 2010

Using asp.net AdRotator control

The asp.net AdRotator control is used to dynamically display advertisements on the web page. Advertisements are basically images that can be clicked and changes when page is refreshed. The AdRotator control requires an xml file to be used as the data source. The following properties can be specified for the control.

  • ImageUrl – Source URL of the image.
  • NavigateUrl – URL to which the page will be redirected once the image is clicked.
  • AlternateText – The text that will be used as the alt attribute for the image.
  • Impressions – A number that determines the number of times that the image will be displayed.
  • Keyword – The category for the advertisements.
  • Height – Height of the image.
  • Width – Width of the image.

The following is a sample code that is used to display the ads dynamically.

On .aspx page,

Code Snippet
  1. <asp:AdRotator ID="AdRotator1" runat="server" DataSourceID="XmlDataSource1" />
  2. <asp:XmlDataSource ID="XmlDataSource1" runat="server" DataFile="~/Ads.xml">
  3. </asp:XmlDataSource>

Sample code for the xml is below.

Code Snippet
  1. <?xml version="1.0" encoding="utf-8" ?>
  2. <Advertisements>
  3.   <Ad>
  4.     <ImageUrl>images/ad1.png</ImageUrl>
  5.     <NavigateUrl>Default.aspx</NavigateUrl>
  6.     <AlternateText>Ad1</AlternateText>
  7.     <Impressions>60</Impressions>
  8.     <Keyword>Ad1 Ad1</Keyword>
  9.   </Ad>
  10.   <Ad>
  11.     <ImageUrl>images/ad2.png</ImageUrl>
  12.     <NavigateUrl>Default2.aspx</NavigateUrl>
  13.     <AlternateText>Ad2</AlternateText>
  14.     <Impressions>40</Impressions>
  15.     <Keyword>Ad2 Ad2</Keyword>
  16.   </Ad>
  17. </Advertisements>

November 9, 2010

Monitor file system in .NET using C#

The System.IO.FileSystemWatcher class can be used to monitor a particular path/directory for any modification to the files. The modification includes creation, deletion, renaming, file name changes and file size changes in the particular directory or to any sub-directory. The EnableRaisingEvents property of FileSystemWatcher  class must be set to true.

The  properties of the file that needs to be monitored can be set by using the NotifyFilter class. The IncludeSubdirectories property needs to be set to true if sub-directories needs to be monitored.

The Changed, Created and Deleted events can be handled by the FileSystemEventHandler and the Renamed event can be handled by the RenamedEventHandler. It is a good idea to decide want what to monitor as otherwise the log file will keep growing.

In this particular example, I will monitor the App_Data folder in a web application and write the logs in a text file. The code is written in Global.asax file.

Code Snippet
  1. void Application_Start(object sender, EventArgs e)
  2. {
  3.     // Code that runs on application startup
  4.     string path = Server.MapPath("App_Data");
  5.     FileSystemWatcher fs = new FileSystemWatcher(path);
  6.  
  7.     fs.EnableRaisingEvents = true; // must be set to true
  8.     fs.IncludeSubdirectories = true;
  9.     //fs.NotifyFilter = NotifyFilters.FileName | NotifyFilters.Size;
  10.  
  11.     fs.Changed += new FileSystemEventHandler(fs_Changed);
  12.     fs.Renamed += new RenamedEventHandler(fs_Renamed);
  13.     fs.Created += new FileSystemEventHandler(fs_Changed);
  14.     fs.Deleted += new FileSystemEventHandler(fs_Changed);
  15.  
  16.     Application.Add("watcher", fs);            
  17. }
  18.  
  19. public static void fs_Renamed(object sender, RenamedEventArgs e)
  20. {
  21.     string path = @"C:\Users\username\Desktop\lognet.txt";
  22.     File.AppendAllText(path, e.Name + "-" + e.ChangeType);
  23. }
  24.  
  25. public void fs_Changed(object sender, FileSystemEventArgs e)
  26. {
  27.     string path = @"C:\Users\username\Desktop\lognet.txt";
  28.     File.AppendAllText(path, e.Name + " - " + e.ChangeType);
  29. }
Reference: Shahed Kazi at AspNetify.com