Feb 10, 2010

Building ASP.NET UserControls

Introduction

If you are Classic ASP programmer or PHP programmer, you probably use SSI include files quite a lot on your web applications and you probably also know that this has worked quite reasonably well for all of you. But the major disadvantages would be maintaining the code once your web projects has grow bigger. Major problem would be to keep up with the HTML opening and closing tags. Its quite hard to debug the code if you are adding some HTML files in your include files and then later on you find that it produce funny result on certain page. There are no visual GUI or IDE that can help you to see the design view. The only way to debug is by viewing the page in the browser. This has taken quite a lot of developer time. The code was also very messy and also you might need to include all your include files in correct order and lots of developer normally will do copy and paste for all their page.

Luckily in ASP.NET technology, this problem has been solved with the introduction of UserControl. UserControl is basically use the same technology like the SSI includes except that it is a self contained objects where you can set the properties,attributes and methods. UserControl also can be designed using Visual Studio design view which allow you to see the layout of your page nicely.

Main

In this article, I will be presenting some simple example of my existing projects that use UserControls.
We will be doing some Header and Footer UserControls that expose some properties and attributes.
Now, let's start writing some code for creating UserControl.

Open Visual Studio 2005, Add New Web Site and Choose to add New UserControl. First one should be named as Header.ascx and second one as Footer.ascx.

If you look at the HTML source for the user control, you see several interesting differences from a standard ASP.NET Web Page
<%@ CONTROL LANGUAGE="C#" AUTOEVENTWIREUP="true" CODEFILE="Header.ascx.cs" I

INHERITS="UserControl_Header" %>
First,notice that the source uses @Control directive rather than @Page directive which a standard Web page would use. Second, notice that unlike a standard ASP.NET Web Page,no other HTML tags such as body,or DIV exists on the control. The web page containing the user control provides the basic HTML tags such as and
tags.In fact if you try to add server side form tags to the user control,ASP.NET will returns an error when the page is served to the clients.

Now, add this code into your Header.ascx
<%@ CONTROL LANGUAGE="C#" AUTOEVENTWIREUP="true" CODEFILE="Header.ascx.cs" INHERITS="Header" %>

<TABLE BORDER="0" WIDTH="100%">

   <TR>

       <TD>

           I am header User Control.TD>

       <TD>

           Today Date is <%=Date %>

       TD>

       <TD>

           Our Phone Number is <%=PhoneNumber %>

       TD>

   TR>

   <TR>

       <TD COLSPAN="3" BGCOLOR=<%=BgColor %>>

           <ASP:MENU ID="Menu1" RUNAT="server" ORIENTATION="Horizontal" WIDTH="100%" BACKCOLOR="#B5C7DE"

                DYNAMICHORIZONTALOFFSET="2" FONT-NAMES="Verdana" FONT-SIZE="0.8em" FORECOLOR="#284E98"

                STATICSUBMENUINDENT="10px">

               <ITEMS>

                   <ASP:MENUITEM TEXT="Home" VALUE="New Item">ASP:MENUITEM>

                   <ASP:MENUITEM TEXT="Our Products" VALUE="New Item">ASP:MENUITEM>

                   <ASP:MENUITEM TEXT="Our Features" VALUE="New Item">ASP:MENUITEM>

                   <ASP:MENUITEM TEXT="About Us" VALUE="New Item">ASP:MENUITEM>

                   <ASP:MENUITEM TEXT="Contact Us" VALUE="New Item">ASP:MENUITEM>

                   <ASP:MENUITEM TEXT="Why Choose Us" VALUE="New Item">ASP:MENUITEM>

               ITEMS>

               <STATICMENUITEMSTYLE HORIZONTALPADDING="5px" VERTICALPADDING="2px" />

               <DYNAMICHOVERSTYLE BACKCOLOR="#284E98" FORECOLOR="White" />

               <DYNAMICMENUSTYLE BACKCOLOR="#B5C7DE" />

               <STATICSELECTEDSTYLE BACKCOLOR="#507CD1" />

               <DYNAMICSELECTEDSTYLE BACKCOLOR="#507CD1" />

               <DYNAMICMENUITEMSTYLE HORIZONTALPADDING="5px" VERTICALPADDING="2px" />

               <STATICHOVERSTYLE BACKCOLOR="#284E98" FORECOLOR="White" />

           ASP:MENU>

       TD>

   TR>

TABLE>





From the code above, you notice that we use lots of server side tags <%=%> in the ascx file. The reason is because all that values is taken from the usercontrol properties and we can set the properties from the hosted user control page. The idea was be able to set and get the properties from the page.
In this example, we can set the background color of the user page, set the title and set the Date.

Now, add this code into Header.ascx.cs
using System;

using System.Data;

using System.Configuration;

using System.Collections;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Web.UI.HtmlControls;



public partial class Header : System.Web.UI.UserControl

{

   private string sTitle = "Welcome to My Company";

   private string sPhoneNumber = "12345667";

   private string sDate = "12/12/2007";

   private string sBgColor = "white";

   protected void Page_Load(object sender, EventArgs e)

   {



   }

   public string BgColor

   {

       get

       {

           return sBgColor;

       }

       set

       {

           sBgColor= value;

       }

   }

   public string Title

   {

       get

       {

           return sTitle;

       }

       set

       {

           sTitle = value;

       }

   }

   public string PhoneNumber

   {

       get

       {

           return sPhoneNumber;

       }

       set

       {

           sPhoneNumber = value;

       }

   }

   public string Date

   {

       get

       {

           return sDate;

       }

       set

       {

           sDate = value;

       }

   }



}
From the code above, you can see that we provide public get and set methods for all the properties that we use in Header.ascx file. We also provide default properties values for that incase if the UserControl does not override the property value.

Adding UserControl into Page

To add User Controls to the form, you can do it in two ways.
First, would be easy ways, but you need to have Visual Studio.
Open your Visual Studio in design View, and then drag the Header.ascx from SolutionExplorer into your Page. Once you do that, you can see that Visual Studio does all the necessary code for you.

Second way, would be manually code the UserControl in your page.
Add the Register directives as below
<%@ REGISTER src="Header.ascx" TAGNAME="Header" TAGPREFIX="uc1" %>
You can named the TagName and TagPrefix as you like. After that add the UserControl to the location you want on your page. The tag for user control should be like this
<UC1:HEADERS ID="Header1" RUNAT="server" TITLE="Hello Here" BGCOLOR="red"

PHONENUMBER="123455" />
Notice that in the UserControl above, we can define all the properties that we have previously provide public set methods.

You can also set and get the UserControl properties in code behind.
To get and set the UserControl properties, you can use code like this in your code behind
e.g Header1.Title = "Yes";
or Response.Write(Header1.Title);

UserControls is infact an object in your Page. You can add as many usercontrol on your page, or on multiple page. Each individual UserControl you add can have different set of properties and methods you can call.

Conclusion

ASP.NET UserControl is the new way of encapsulate all your code reuse in your web applications. Old way of doing this would be via SSI includes which can be very messy and very hard to maintain if your site grow. ASP.NET UserControl is infact the simplest form of ASP.NET control encapsulation. Because they are the simplest, they are also the easiest to create and use. Essentially user control is a grouping of existing server controls into a single container control. This enables you to group all your reusable part of webpage into UserControl. The basic example would be Login Controls, News Controls, Header Controls and etc.

If However you want to create your own controls from scratch that has the features like ASP.NET Web Server controls (Label,Button,TextBox), then you need to create the controls as Custom Controls. Custom controls is not discussed in this article.

Get current page name

This function can be used to retrieve the current page:s name, i.e default.aspx, hello.aspx or whatever.


public string GetCurrentPageName()
{
string sPath = System.Web.HttpContext.Current.Request.Url.AbsolutePath;
System.IO.FileInfo oInfo = new System.IO.FileInfo(sPath);
string sRet = oInfo.Name;
return sRet;
}


By going through System.Web.HttpContext.Current object we are able to have this function in a generic dll or class - and not in each and every page needing to call it.

Nov 20, 2009

Register IIS

Sounds like a permissions issue.

Can you try running %windir%\microsoft.net\framework\v2.0.50727\aspnet_regiis -i -enable

That should reset the permissions and reregister ASP.Net on your server.

Oct 5, 2009

Finding Blank Lines using regular expressions

Finding Blank Lines using regular expressions

In this regular expression we are going to find out blank lines. Means we are going to search lines containing only spaces (or Whitespace) and end of line.
Regular Expression Pattern

^\s*$
A description of the regular expression:

Beginning of line or string
Whitespace, any number of repetitions
End of line or string
How It Works

This regular expression will check for blank lines contains only spaces (Whitespace). Here we are going to search Beginning of line followed by Whitespace, any number of repetitions and End of line or string.

Finding Blank Lines using regular expressions



ASP.NET

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>



Finding Blank Lines using regular expressions


Valid Format: enter some spaces (or Whitespace)











C#.NET

//use System.Text.RegularExpressions befour using this function
public bool vldRegex(string strInput)
{
//create Regular Expression Match pattern object
Regex myRegex = new Regex("^\\s*$");
//boolean variable to hold the status
bool isValid = false;
if (string.IsNullOrEmpty(strInput))
{
isValid = false;
}
else
{
isValid = myRegex.IsMatch(strInput);
}
//return the results
return isValid;
}



VB.NET

‘Imports System.Text.RegularExpressions befour using this function
Public Function vldRegex(ByVal strInput As String) As Boolean
‘create Regular Expression Match pattern object
Dim myRegex As New Regex("^\s*$")
‘boolean variable to hold the status
Dim isValid As Boolean = False
If strInput = "" Then
isValid = False
Else
isValid = myRegex.IsMatch(strInput)
End If
‘return the results
Return isValid
End Function

Sep 30, 2009

Some important LINKS

Update for .NET 3.5 SP1 (Important if working with Dynamic Data)

http://support.microsoft.com/kb/959209

ASP.NET Compilation Enhancement Fix

http://code.msdn.microsoft.com/KB967535/Release/ProjectReleases.aspx?ReleaseId=2328 (for Windows Vista and Windows Server 2008)https://connect.microsoft.com/VisualStudio/Downloads/DownloadDetails.aspx?DownloadID=18157 (for Windows XP and Windows Server 2003)

Microsoft .NET RIA Services May 2009 Preview

http://www.microsoft.com/downloads/details.aspx?FamilyID=76bb3a07-3846-4564-b0c3-27972bcaabce&displaylang=en

ASP.NET 4.0 in VS 2010 Doc

http://www.asp.net/learn/whitepapers/aspnet40

Some of them are a little old but thought worth putting them up.

Cheers !!!

Sep 18, 2009

Creating multiple websites on a single IP ...

Suppose, I have a couple of websites hosted on a dedicated server (Windows 2003 with IIs 6.0) and the issue is that with one IP address (in other words - Static/Dedicated IP address), I was able to reach only one of the websites.

There are three options to host multiple websites in IIS :

1. Create websites, each assigned an IP - The downside of this option is that you will have limited IPs with you !!
2. Create websites, each listening on different port numbers.For example, http://mysite1.com and http://mysite2.com:8888 - The downside of this approach is that users have to remember the port number of the site that they are interested in!!
3. Using Host-Headers - This option is the "best" that solves the problem at hand.

Let me elaborate a bit on option #3 here:

1. Create multiple websites in IIS
2. Right click on a website, choose "Properties".
3. On the tab page named "Website" click "Advanced ..." and here you can add a host header (say, mysite2.com) and let all the websites have the IP as "All Unassigned" and the port 80.

Having done this, update the DNS records for mysite1.com and mysite2.com to point to the IP running your webserver and try accessing mysite1.com and mysite2.com, it works :-)

For more details, please visit http://www.iisanswers.com/Top10FAQ/t10-hostheaders.htm

Sep 17, 2009

Set Height Width Color of Rad Confirm Window in Radgrid Button Column

style type="text/css">
.RadWindow .rwWindowContent .radconfirm,
{
color:White !important;
}
.RadWindow .windowpopup.radconfirm
{
height: 150px !important;
width: 300px !important;
}
style