Apr 25 2006

Define Custom Events in UserControls

Category: ASP.NET 1.x | ASP.NET 2.0 - GeneralBil@l @ 17:55

A very common question on the ASP.NET forums is:

How to define an event in a UserControl, and process this event in the Page holding this UserControl?

The answer is simple, follow this post, and you will be able to define your own events very easily.

We have the following UserControl file together with the Code Behind as follows:

<%@ Control Language="c#" AutoEventWireup="false" Codebehind="EventUserControl.ascx.cs" Inherits="UserControls.EventUserControl" TargetSchema="http://schemas.microsoft.com/intellisense/ie5"%>
<P>Choose a Country:&nbsp;&nbsp;
 <asp:DropDownList id="ddlCountry" runat="server">
  <asp:ListItem Value="Australia">Australia</asp:ListItem>
  <asp:ListItem Value="Canada">Canada</asp:ListItem>
  <asp:ListItem Value="Kuwait">Kuwait</asp:ListItem>
  <asp:ListItem Value="Lebanon">Lebanon</asp:ListItem>
  <asp:ListItem Value="Saudi Arabia">Saudi Arabia</asp:ListItem>
  <asp:ListItem Value="USA">USA</asp:ListItem>
 </asp:DropDownList></P>
<P>
 <asp:Button id="btnSubmit" runat="server" Text="Select"></asp:Button></P>

The code behind has been enriched with many comments to make your life easy while reading the code:

namespace UserControls
{
 #region Imports
 using System;
 using System.Data;
 using System.Drawing;
 using System.Web;
 using System.Web.UI.WebControls;
 using System.Web.UI.HtmlControls;
 #endregion

 #region Class Declaration
 public class EventUserControl : System.Web.UI.UserControl
 {
  #region Controls
  protected System.Web.UI.WebControls.DropDownList ddlCountry;
  protected System.Web.UI.WebControls.Button btnSubmit;
  #endregion
 
  #region Delegate Declaration
  // Step 2
  // Define the handler that will handle the event fired by the Button
  // It takes two arguments, the sender and a parameter of type ButtonEventArgs.
  // The ButtonEventArgs will hold the country that was selected
  // So the event handler in the ASPX page, should have the same signature
  // as that of the handler, of the event fired by the UserControl
  public delegate void ButtonClickedHandler (object Sender, ButtonEventArgs e);
  #endregion

  #region Event Definition
  // Step 3
  // Define an instance of the event handler,
  // this instance shall be filled with the event handler
  // that will be defined in the ASPX page
  public event ButtonClickedHandler ButtonClicked;
  #endregion

  #region OnEvent Event
  // Step 4
  // You always need the "On" method that will check if
  // the above event has been registered with an event handler or not
  // if it has been registered, then it will fire that event in the ASPX page
  // the page that is holding the UserControl
  public virtual void OnButtonClicked(ButtonEventArgs e)
  {
   if (ButtonClicked != null)
   {
    ButtonClicked(this,e);
   }
  }
  #endregion

  #region Control Events
  private void Page_Load(object sender, System.EventArgs e)
  {
   
  }
  private void btnSubmit_Click(object sender, System.EventArgs e)
  {
   string ddlSelectedValue = this.ddlCountry.SelectedItem.Text;

   // Step 5
   // Get a new instance of ButtonClickedArgs, fill it with the
   // Country that has been selected
   ButtonEventArgs objBCA = new ButtonEventArgs();
   objBCA.CountrySelected = ddlSelectedValue;

   // Call the method that will fire the event in ASPX page
   OnButtonClicked(objBCA);

  }
  #endregion

  #region Web Form Designer generated code
  override protected void OnInit(EventArgs e)
  {
   InitializeComponent();
   base.OnInit(e);
  }

  private void InitializeComponent()
  {
   this.btnSubmit.Click += new System.EventHandler(this.btnSubmit_Click);
   this.Load += new System.EventHandler(this.Page_Load);
  }
  #endregion
 }
 #endregion

 #region ButtonEventArgs Definition
 // Step 1
 // An object can extend the EventArgs object
 // and adds its own fields to it
 // to be able lto gather more data
 // about the event fired
 public class ButtonEventArgs : EventArgs
 {
  #region Private Fields
  private string m_CountrySelected;
  #endregion

  #region Public Properties
  public string CountrySelected
  {
   get {return this.m_CountrySelected;}
   set {this.m_CountrySelected = value;}
  }
  #endregion

  #region Constructors
  public ButtonEventArgs()
  {}

  public ButtonEventArgs(string p_CountrySelected)
  {
   this.m_CountrySelected = p_CountrySelected;
  }
  #endregion
 }
 #endregion

}

Then, the ASPX page that will hold the UserControl is defined below, through both the Code-Behind and ASPX page:

<%@ Page language="c#" Codebehind="TestEventUserControl.aspx.cs" AutoEventWireup="false" Inherits="UserControls.TestEventUserControl" %>
<%@ Register TagPrefix="uc1" TagName="EventUserControl" Src="EventUserControl.ascx" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
 <HEAD>
 </HEAD>
 <body MS_POSITIONING="GridLayout">
  <form id="Form1" method="post" runat="server">
   <uc1:EventUserControl id="EventUserControl1" runat="server"></uc1:EventUserControl>
  </form>
 </body>
</HTML>

The code behind is as follows:

#region Imports
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
#endregion

namespace UserControls
{
 public class TestEventUserControl : System.Web.UI.Page
 {
  #region Define UserControl
  // Step 1
  // Define an instance of the UserControl
  // to be able to add an event handler
  protected EventUserControl EventUserControl1;
  #endregion

  private void Page_Load(object sender, System.EventArgs e)
  {
   
  }
  
  // Step 3
  // The event handler, whose signature is the same as the ButtonClickEventHandler
  // that will be used to handle the event fired by the UserControl
  private void EventUserControl_Fired(object Sender, ButtonEventArgs e)
  {
   Response.Write("You have choosen: " + e.CountrySelected);
  }

  #region Web Form Designer generated code
  override protected void OnInit(EventArgs e)
  {
   InitializeComponent();
   base.OnInit(e);
  }
  
  private void InitializeComponent()
  {   
   this.Load += new System.EventHandler(this.Page_Load);

   // Step 2
   // Registering the ButtonClick event with the event handler on the ASPX page
   this.EventUserControl1.ButtonClicked += new UserControls.EventUserControl.ButtonClickedHandler(EventUserControl_Fired);
  }
  #endregion
 }
}

Now, you can create a new Web Application, make sure to name the Application UserControls, create a user control called EventUserControl.ascx and a page called TestEventUserControl.aspx. Those names are just named so that you can run the above code without any changes, however, feel free to change them to whatever names you want.

Hope I was able to make it easy on you, on how to define events inside UserControl and handle them in the ASPX page that is holding the UserControl.

HTH,

Regards

 

Tags: ,

Apr 13 2006

Define a Custom Event inside UserControls

Category: ASP.NET 1.x | ASP.NET 2.0 - GeneralBil@l @ 08:51

If you are working with either a new custom server control or a normal web user control, this is the proper way of adding an event that can be handled by the parent control of the child control you are develping:

Add the following to the control (Server Control / Web User Control ) being developed:

#region Event Handler 
private static readonly object EventBubbleRaised = new object(); 
public event EventHandler BubbleRaise 
{ 
       add 
      { 
                Events.AddHandler(EventBubbleRaised, value); 
       } 
       remove 
      { 
               Events.RemoveHandler(EventBubbleRaised, value); 
      } 
} 
protected virtual void OnBubbleClick(EventArgs e) 
{
              EventHandler BubbleRaised = (EventHandler)Events[EventBubbleRaised]; 
              if (BubbleRaised != null) 
                      BubbleRaised(this, e); 
} 
#endregion

In the parent page / control, you add this in the Init method:

BubbleControl.BubbleRaise += new EventHandler(ControlName_BubbleRaise);


Then you define you our handler:

private void ControlName_BubbleRaise(object sender, EventArgs e) 
{ 
                Response.Write(sender.GetType().ToString()); 
}

                

That was a simple example, but at least you know now the steps.

Regards

Tags: ,

Mar 29 2006

DateTime Formatting in ASP.NET 2.0

Category: ASP.NET 1.x | ASP.NET 2.0 - GeneralBil@l @ 09:33

This is a nice summarized sample code on how to format DateTime instances:

// This code example demonstrates the String.Format() method.
// Formatting for this example uses the "en-US" culture.

using System;
class Sample 
{
    enum Color {Yellow = 1, Blue, Green};
    static DateTime thisDate = DateTime.Now;

    public static void Main() 
    {
// Store the output of the String.Format method in a string.
    string s = "";

    Console.Clear();

// Format a negative integer or floating-point number in various ways.
    Console.WriteLine("Standard Numeric Format Specifiers");
    s = String.Format(
        "(C) Currency: . . . . . . . . {0:C}\n" +
        "(D) Decimal:. . . . . . . . . {0:D}\n" +
        "(E) Scientific: . . . . . . . {1:E}\n" +
        "(F) Fixed point:. . . . . . . {1:F}\n" +
        "(G) General:. . . . . . . . . {0:G}\n" +
        "    (default):. . . . . . . . {0} (default = 'G')\n" +
        "(N) Number: . . . . . . . . . {0:N}\n" +
        "(P) Percent:. . . . . . . . . {1:P}\n" +
        "(R) Round-trip: . . . . . . . {1:R}\n" +
        "(X) Hexadecimal:. . . . . . . {0:X}\n",
        -123, -123.45f); 
    Console.WriteLine(s);

// Format the current date in various ways.
    Console.WriteLine("Standard DateTime Format Specifiers");
    s = String.Format(
        "(d) Short date: . . . . . . . {0:d}\n" +
        "(D) Long date:. . . . . . . . {0:D}\n" +
        "(t) Short time: . . . . . . . {0:t}\n" +
        "(T) Long time:. . . . . . . . {0:T}\n" +
        "(f) Full date/short time: . . {0:f}\n" +
        "(F) Full date/long time:. . . {0:F}\n" +
        "(g) General date/short time:. {0:g}\n" +
        "(G) General date/long time: . {0:G}\n" +
        "    (default):. . . . . . . . {0} (default = 'G')\n" +
        "(M) Month:. . . . . . . . . . {0:M}\n" +
        "(R) RFC1123:. . . . . . . . . {0:R}\n" +
        "(s) Sortable: . . . . . . . . {0:s}\n" +
        "(u) Universal sortable: . . . {0:u} (invariant)\n" +
        "(U) Universal sortable: . . . {0:U}\n" +
        "(Y) Year: . . . . . . . . . . {0:Y}\n", 
        thisDate);
    Console.WriteLine(s);

// Format a Color enumeration value in various ways.
    Console.WriteLine("Standard Enumeration Format Specifiers");
    s = String.Format(
        "(G) General:. . . . . . . . . {0:G}\n" +
        "    (default):. . . . . . . . {0} (default = 'G')\n" +
        "(F) Flags:. . . . . . . . . . {0:F} (flags or integer)\n" +
        "(D) Decimal number: . . . . . {0:D}\n" +
        "(X) Hexadecimal:. . . . . . . {0:X}\n", 
        Color.Green);       
    Console.WriteLine(s);
    }
}
/*
This code example produces the following results:

Standard Numeric Format Specifiers
(C) Currency: . . . . . . . . ($123.00)
(D) Decimal:. . . . . . . . . -123
(E) Scientific: . . . . . . . -1.234500E+002
(F) Fixed point:. . . . . . . -123.45
(G) General:. . . . . . . . . -123
    (default):. . . . . . . . -123 (default = 'G')
(N) Number: . . . . . . . . . -123.00
(P) Percent:. . . . . . . . . -12,345.00 %
(R) Round-trip: . . . . . . . -123.45
(X) Hexadecimal:. . . . . . . FFFFFF85

Standard DateTime Format Specifiers
(d) Short date: . . . . . . . 6/26/2004
(D) Long date:. . . . . . . . Saturday, June 26, 2004
(t) Short time: . . . . . . . 8:11 PM
(T) Long time:. . . . . . . . 8:11:04 PM
(f) Full date/short time: . . Saturday, June 26, 2004 8:11 PM
(F) Full date/long time:. . . Saturday, June 26, 2004 8:11:04 PM
(g) General date/short time:. 6/26/2004 8:11 PM
(G) General date/long time: . 6/26/2004 8:11:04 PM
    (default):. . . . . . . . 6/26/2004 8:11:04 PM (default = 'G')
(M) Month:. . . . . . . . . . June 26
(R) RFC1123:. . . . . . . . . Sat, 26 Jun 2004 20:11:04 GMT
(s) Sortable: . . . . . . . . 2004-06-26T20:11:04
(u) Universal sortable: . . . 2004-06-26 20:11:04Z (invariant)
(U) Universal sortable: . . . Sunday, June 27, 2004 3:11:04 AM
(Y) Year: . . . . . . . . . . June, 2004

Standard Enumeration Format Specifiers
(G) General:. . . . . . . . . Green
    (default):. . . . . . . . Green (default = 'G')
(F) Flags:. . . . . . . . . . Green (flags or integer)
(D) Decimal number: . . . . . 3
(X) Hexadecimal:. . . . . . . 00000003

*/


This samlpe code is taken from:

http://msdn2.microsoft.com/library/system.string.format.aspx

Tags: ,

Mar 19 2006

CurrentCulture &amp; CurrentUICulture

Category: ASP.NET 1.x | ASP.NET 2.0 - GeneralBil@l @ 13:10

There has been always a popular question on the ASP.NET forums about the difference between CurrentCulture and CurrentUICulture. I wanted to distinguish things in this post and make it clear once and for all.

  1. CurrentCulture and CurrentUICulture are both of type CultureInfo which is part of the  System.Globalization.
  2. CurrentCulture and CurrentUICulture are boh properties of the current thread represented as: System.Threading.Thread.CurrentThread.CurrentCulture and System.Threading.Thread.CurrentThread.CurrentUICulture
  3. CurrentCulture is used mainly to format the Dates, Currencies, etc ... For that reason it should be set specific. For instance, you need to set the CurrentCulture as:

    System.Threading.Thread.CurrentThread.CurrentCulture= new CultureInfo("ar-LB");

    We have set current culture to be a specific culture and mainly, Arabic - Lebanese. So make sure always to be specific in specifying the
    CurrentCulture
  4. CurrentUICulture is mainly used for language/text translations. So the ResourceManager is based upon the CurrentUICulture. It doesn't matter whether the culture set here is specific or neutral. For instance, either ar or ar-lb works fine with the CurrentUICulture:

    System.Threading.Thread.CurrentThread.CurrentCulture= new CultureInfo("ar"); // ar-lb

    Both work fine in this case.
  5. ASP.NET controls (Calendar for example) with built-in localization cannot use a neutral culture. When you want to make use of the built-in localization of ASP.NET Controls, make sure to specify a specific culture in the CurrentCulture.

Hope this post helps you clarify the differences between CurrentCulture and CurrentUICulture.

Regards 

Tags: ,

Mar 10 2006

Server.MapPath Analysis

Category: ASP.NET 1.x | ASP.NET 2.0 - GeneralBil@l @ 08:36

While working with the HttpContext.Current.Server.MapPath(), I discovered something which is that, the MapPath method starts seeking a path Starting from the current directory you are in and not directly from the root directory.

Hope this hint helps,

Regards

 

Tags: ,

Mar 9 2006

HttpHandlers, HttpModules, and the FormsAuthentication

Category: ASP.NET 1.x | ASP.NET 2.0 - GeneralBil@l @ 16:33

I have been working on a Global Error Logging & Handling solution for a web application that is part of a huge system we have been developing in my company.

I used an HttpModule to get attached to the Application_Error event, where I instantiate my own error handler classes and process the error. The processing is done though sending an email to the admin, saving to datatabase, and optionally saving to a text file. After the error handling is finished, I redirect users to "ApplicationName.er".

The "ApplicationName.er", has a weird extension right? I have added this extension to the IIS, so that it will send such requests to my web application. In my web application, I built an HttpHandler, that handles such request or pages with the .er extensions. In the ProcessRequest method of the HttpHandler, I was sending a WebRequest to a template page, that has the text to display when we are faced with an exception in our application. All that was going fine. (I could have also used an HttpHandlerFactory instead).

The problem seemed to be as follows: The whole application is set to be "denied by ?", which means only authenticated users are allowed to visit my web appication pages. The problem with my application was that, in the HttpModule, I was redirecting to ApplicationName.er, since this file doesn't physically exist and I cannot add a <location> tag for this page since, it is not a .NET page and so the location tag won't have any effect on it, for all the above reasons, my application was not running as expected.

Solution? Well, it was an easy yet effective solution, I created a new folder named Include, it is an empty folder. I add a location tag for this folder to be accessible by all users <allow user="*" />. I made the HttpModule redirect to ~/Include/ApplicationName.er  and that's it worked perfect.

Hope that helps you,

Regards

Tags: ,

Mar 5 2006

Using Method inside a DataGrid or GridView TemplateField

Category: ASP.NET 1.x | ASP.NET 2.0 - GeneralBil@l @ 09:55

Sometimes there is a need to do some action on a field returned from the database and displayed inside a TemplateField inside the DataGrid or GridView columns.

For example, you might have an email address inside your database and you want to set the HREF of the a tag as a link with the "mailto:" appended at the beginning of the field.

I usually use a small helper method, that takes as input the field coming from the databasee and formats for me the display I want. In the example below, I am displaying the full name of the customer or client, as a link to his/her email address.

GridView Example:

<asp:TemplateField HeaderText="Name">
    <ItemTemplate>
        <a href='<%# FormatUrl(Eval("email1").ToString())%>'><%# Eval("fname") %>,&nbsp;<%# Eval("lname") %></a>
    </ItemTemplate>
</asp:TemplateField>

As you can see, I am calling a method called FormatUrl with an input the email field we're getting from the database.

DataGrid Example:

<asp:TemplateColumn HeaderText="Name">
    <ItemTemplate>
        <a href='<%# FormatUrl(Eval("email1").ToString())%>'><%# Eval("fname") %>,&nbsp;<%# Eval("lname") %></a>
    </ItemTemplate>
</asp:TemplateColumn>

Now the FormatUrl method is as simple as the following:

public string FormatUrl(string email)
{
    return "mailto:" + email;
}

                

The idea is so simple, we are just calling a heler method, giving it the needed fields to return a formatted string as we want.

Hope this helps,

Regards

Tags: ,

Mar 4 2006

Difference between NULL and DBNull

I have always misunderstood the difference between NULL and DBNULL until recently while I was working on ASP.NET web application, and was talking to a Webservice and I found an exception coming from one of the web methods inside the Webservice which is using the SqlCommand.ExecuteScalar() method.

What happens when the ExecuteScalar() method is used? Usually, the ExecuteScalar() method returns the First Column of the First Row returned by the database stored procedure or SQL query.

Suppose for example you are searching for the CustomerPhone of the customer named "Bilal Haidar", and that customer didn't have any record in the database, so a query such as:

public string Get_Customer_ID(string UserName)
{
   // Prepare database connection
   SqlConnection conn = new SqlConnection("...");
   // Prepare command to execute
   SqlCommand cmd = new SqlCommand("SELECT CustomerPhone FROM Custoers WHERE CustomerName = 'Bilal Haidar'", conn);

   // Execute the command and store result in an object
   object objResult = cmd.ExecuteScalar();






if (objResult == null) return "Customer not found in our database";
if (objResult == System.DBNull.Value) return "Customer found but his/her phone number is null"; return (string) objResult; }

So now here how it goes. The query will search for the Customer Phone. We are returning the result and storing it in the objResult object.

If the result object is null, then there is no record in the database with the username specified.

If the result value is not null, we need to check if the Cutomer Phone field has a value or not, how do you do so? Using the DBNull.Value would check for you if the field returned is null or not.

So, comparing the ExecuteScalar() to null means, we are checking if there is a record returned, and checking if value of the first column of the first row is null or not, means we need to check against DBNul..Value

Hope you have now a better understanding of the difference between NULL and DBNull

Regards

Tags: , , , ,

Mar 4 2006

ASP.NET and DNN Website deploy

When you developer an ASP.NET web application or a DotNetNuke application, you will be having all types of file extensions:

  • .csproj
  • .cs
  • .vb
  • .su
  • .sln
  • etc ...

So, imagine you are developing a huge web application or even a DotNetNuke website and now it is time to deploy your application. Are you going to go through each single folder in your web application, remove all un needed files and leave the aspx, ascx, css, etc .. files for deployment? Maybe that can be done for small applications, but not for DoetNetNuke applications nor for huge ASP.NET web applications.

The solution found here is called DNNDeploy which you can read more about it here:

ASP.NET Deployment App

This tool goes through all your files in the application, allows you to choose what file extensions to keep and generates a web site ready for deployment.

I am sure this helps us a lot.

Regards

Tags: , ,

Feb 23 2006

Security Training Modules

Category: ASP.NET 1.x | ASP.NET 2.0 - GeneralBil@l @ 15:07

There is a very nice module on Security Patterns in ASP.NET (1.x/2.0).

You can check it at: Security Training Modules

Hope that helps,

Regards

Tags: ,