Nikolaos Kantzelis ASP.Net Blog

This blog will focus on ASP.NET Framework

Sponsors

About Me

Great Blogs

October 2009 - Posts

ASP.NET 4.0 and ClientID Mode

In this post I will be talking about a new enhancement in ASP.NET 4.0.It is now possible to set the name of your controls ClientID attribute, thanks to the ClientIDMode property. Developers requested a better way of setting names of the web server controls and with the new version of ASP.NET 4.0, this is now a reality.

We can demonstrate this with a new project.I will be using C# and VS 2010.

1) Launch Visual Studio 2010

2) Create a new website, select ASP.NET Web site from the available templates. Save your website by giving it an appropriate name. e.g Clientid

3) Create a master page and add it to the page.Leave the default name.

4) Create a new web user control.Leave the default name.

5) In the WebUserControl.ascx add two web server controls,a label control and a textbox control

6) Add the web user control to the asp.net page by typing in the directives section(top of the page)

<%@ Register src=”WebUserControl.ascx” tagname=”WebUserControl1″
tagprefix=”uc1″ %>

7) Run your application. When the default.aspx page is render by the browser, go to View->Source and you will see something like this:

<div>

<span id=”WebUserControl11_Label1″>what is your name?</span>
<input name=”WebUserControl11$TextBox1″ type=”text” id=”WebUserControl11_TextBox1″ />

</div>

This is how the controls take their name. The first part is the name of the parent control and the second part is the name of the control itself. If you have many nested elements you end up with messy control names.If you wanted to access these controls in external Javascript files, you had no other alternative but to use these names.

8) Switch to the WebUserControl.ascx file in VS 2010, and change the ids of the label and textbox control. For example

<asp:Label ID=”namelabel”
<asp:TextBox ID=”txtlabel”

9) Then we set the ClientIDMode to static for both controls. Save your work and run the application

10) When the default.aspx page is render by the browser, go to View->Source and you will see something like this:

<span id=”namelabel”>what is your name?</span>
<input name=”WebUserControl11$txtlabel” type=”text” id=”txtlabel” />

It is evident that now we have the ID values that we want , and it much easier and handy to use.

The other values for the ClientIDMode are:

  • Legacy: This is equivalent to the ClientID property behavior for earlier versions of ASP.NET. This is also the default value.
  • Predictable:This is used in data controls that use repeating templates. It uses ID attributes of the parent control’s naming containers, but generated IDs do not have names that contain strings like “ctlxxx”.
  • Inherit: This specifies that a control’s ID generation is the same as its parent.


Stored procedures with Linq to Sql in an ASP.Net application
 
In this post, I am going to show with an example how to use LINQ and stored procedures to insert,update and delete records from a particular table.

I will use visual studio 2008 to create an asp.net application (c# version) that demonstrates how to use stored procs with LINQ.

If you want to see how LINQ treats stored procedures, have a look here

I am going to use the Pubs datatabase and in particular the Authors table.

I am pretty sure, because I have used the Pubs database in almost all my examples that you have installed it and attached it in your local instance of Sql Server.

You can use Visual Studio 2008 express edition and Sql Server express edition for this example.

We often need to use stored procs to talk with our database because there have many benefits,like

  •     They allow modular programming.
  •     They allow faster execution.
  •     They can reduce network traffic.
  •     They can be used as a security mechanism.


First we need to create the 3 stored procedures that will insert,update and delete records from the Authors table

This is not a post on how to create stored procedures, so i am just going to paste here the complete stored procs.

   
      DeleteAuthor

USE [pubs]
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[DeleteAuthor]

@AuthorID nvarchar(20)

AS
BEGIN

DELETE FROM authors
WHERE au_id = @AuthorID

END
GO


   
      UpdateAuthor

USE [pubs]
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[UpdateAuthor]

@authorID varchar(11),
@lname nvarchar(50),
@fname nvarchar(50),
@phone char(12),
@address nvarchar(40),
@city nvarchar(40),
@state char(2),
@zip char(5),
@contract bit

AS
BEGIN

UPDATE authors
SET

au_lname=@lname,
au_fname=@fname,
phone=@phone,
address=@address,
city=@city,
state=@state,
zip=@zip,
contract=@contract
WHERE au_id  = @authorID

END
GO


   
      InsertAuthor

USE [pubs]
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[InsertAuthor]
@id varchar(11),
@lName nvarchar(50),
@fname nvarchar(50),
@phone char(12),
@address nvarchar(40),
@city nvarchar(40),
@state char(2),
@zip char(5),
@contract bit

AS
BEGIN

INSERT INTO pubs.dbo.authors(
au_id,
au_lname,
au_fname,
phone,
address,
city,
state,
zip,
contract)
VALUES (
@id,
@lname,
@fname,
@phone,
@address,
@city,
@state,
@zip,
@contract)

END


GO

1) Launch Visual Studio 2008

2) Create an ASP.net web application. Use C# a your language of development

3) Name your project – solution as you want.

4) Open the Server Explorer and connect to the Pubs database.

5) Add a new item in your project, a Linq to SQL classes, a .dbml file. name it authors.dbml

6) Drag and drop from the Server explorer window the authors table into the designer area (on the .dbml file)

7) Right-Click on the designer area and show the “Show methods Pane”

8) Drag and drop the stored procedures from the Server explorer to the designer area

9) Select the author entity from the deisgner area and select the Properties window. In theDefault methods we need to assign the correct stored procs and not to leave the default option which is “use Runtime”. So please assign the different methods to their respective stored procs. Have a look at the picture below



10) We will use these stored procs that are methods now as far as LINQ is concerned to update,insert and delete records from the database.

11) Add a button in the Default.aspx file. Name it “Update”.Double click on this button. In the event handling routine type:

using (authorsDataContext authdata = new authorsDataContext())
{
var author = (from a in authdata.authors
where a.au_id == “238-95-7766″
select a).Single();
Response.Write(author.au_fname);
author.au_fname = “nikolaos”;
authdata.SubmitChanges();
}

12) Add another button in the default.aspx page. Name it “After Update”.In this routine we try to see the updated value in the database.Double click on this button. In the event handling routine type:


using (authorsDataContext authdata = new authorsDataContext())
{
var author = (from a in authdata.authors
where a.au_id == “238-95-7766″
select a).Single();
Response.Write(author.au_fname);

}
12) Add another button in the default.aspx page and name it “Insert”.Double click on this button. In the event handling routine type:


using (authorsDataContext authdata = new authorsDataContext())
{

authdata.InsertAuthor(”216-49-8915″, “Jones”, “Michael”, “432423424″, “james street 123″, “New york”, “NY”, “94618″, true);
authdata.SubmitChanges();
}


13) Add another button in the default.aspx page and name it “Delete”. Double click on this button. In the event handling routine type:


using (authorsDataContext authdata = new authorsDataContext())
{
var author = (from a in authdata.authors
where a.au_id == “216-49-8915″
select a).Single();
authdata.DeleteAuthor(author.au_id);
authdata.SubmitChanges();
}


if you named you .dbml file “authors”, then there is a file “authors.designer.cs”. Inside there you will find this code


private void Insertauthor(author obj)
{
this.InsertAuthor(default(string), default(string), default(string), obj.phone, obj.address, obj.city, obj.state, obj.zip, ((System.Nullable<bool>)(obj.contract)));
}
private void Updateauthor(author obj)
{
this.UpdateAuthor(obj.au_id, obj.au_lname, obj.au_fname, obj.phone, obj.address, obj.city, obj.state, obj.zip, ((System.Nullable<bool>)(obj.contract)));
}
private void Deleteauthor(author obj)
{
this.DeleteAuthor(default(string));
}


The methods above, are our stored procedures , which are called whenever we insert,update,delete

Hope it helps!!!

If you need the source code just email me.

Five common mistakes in the web.config file

In this post I wοuld like to talk about mistakes in web.config file in ASP.Net applications.
I would like to mention the five of the most common mistakes developers make when they manipulate the web.config file.

1. Custom Errors Disabled

When you disable custom errors as shown below, ASP.NET provides a detailed error message to clients by default.

Wrong configuration:

<configuration>

<system.web>

<customErrors mode="Off">

Right configuration:

<configuration>

<system.web>

<customErrors mode="RemoteOnly">

The more information a hacker can gather about a Web site, the more likely it is that he will be able to successfully attack it. An error message can be of vital significance to an attacker. A default ASP.NET error message lists the specific versions of ASP.NET and the .NET framework which are being used by the Web server, as well as the type of exception that was thrown. Just knowing which Web-based applications are used (in this case ASP.NET) compromises application security by telling the attacker that the server is running a relatively recent version of Microsoft Windows and that Microsoft Internet Information Server (IIS) 6.0 or later is being used as the Web server.

You can build up application security to prevent such information leakage by modifying the mode attribute of the <customErrors> element to "On" or "RemoteOnly." This setting instructs Web-based applications to display a nondescript, generic error message when an unhandled exception is generated. Another way to circumvent this application security issue is to redirect the user to a new page when errors occur by setting the "defaultRedirect" attribute of the <customErrors> element. This approach can provide even better application security because the default generic error page still gives away too much information about the system (namely, that it's using a Web.config file, which reveals that the server is running ASP.NET).

2. Leaving Tracing Enabled in Web-Based Applications

The trace feature of ASP.NET is one of the most useful tools that you can use to ensure application security by debugging and profiling your Web-based applications. Unfortunately, it is also one of the most useful tools that a hacker can use to attack your Web-based applications if it is left enabled in a production environment.

Wrong configuration:

<configuration>

<system.web>

<trace enabled="true" localOnly="false">

Right configuration:

<configuration>

<system.web>

<trace enabled="false" localOnly="true">

When the <trace> element is enabled for remote users of Web-based applications (localOnly="false"), any user can get detailed list of recent requests to the application simply by browsing to the page "trace.axd." A trace log presents a wealth of information: the .NET and ASP.NET versions that the server is running; a complete trace of all the page methods that the request caused, including their times of execution; the session state and application state keys; the request and response cookies; the complete set of request headers, form variables, and QueryString variables; and finally the complete set of server variables.

A hacker looking for a way around application security would obviously find the form variable histories useful because these might include email addresses that could be harvested and sold to spammers, IDs and passwords that could be used to impersonate the user, or credit card and bank account numbers. Even the most innocent-looking piece of data in the trace collection can be dangerous in the wrong hands. For example, the "APPL_PHYSICAL_PATH" server variable, which contains the physical path of Web-based applications on the server, could help an attacker perform directory traversal attacks against the system.

The best way to prevent a hacker from obtaining trace data from Web-based applications is to disable the trace viewer completely by setting the "enabled" attribute of the <trace> element to "false." If you have to have the trace viewer enabled, either to debug or to profile your application, then be sure to set the "localOnly" attribute of the <trace> element to "true." That allows users to access the trace viewer only from the Web server and disables viewing it from any remote machine, increasing your application security.

3. Debugging Enabled

You should never deploy an ASP.Net application in debug mode. Visual Studio 2005/2010 will even automatically modify the Web.config file to allow debugging when you start to debug your application. And, since deploying ASP.NET applications is as simple as copying the files from the development folder into the deployment folder, it's easy to see how development configuration settings can accidentally make it into production, compromising application security.

Wrong configuration:

<configuration>

<system.web>

<compilation debug="true">

Right configuration:

<configuration>

<system.web>

<compilation debug="false">

Leaving debugging enabled is dangerous because you are providing inside information to end users who shouldn't have access to it, and who may use it to attack your Web-based applications. For example, if you have enabled debugging and disabled custom errors in your application, then any error message displayed to an end user of your Web-based applications will include not only the server information, a detailed exception message, and a stack trace, but also the actual source code of the page where the error occurred.

Unfortunately, this configuration setting isn't the only way that source code might be displayed to the user. Here's a story that illustrates why developers shouldn't concentrate solely on one type of configuration setting to improve application security. In early versions of Microsoft's ASP.NET AJAX framework, some controls would return a stack trace with source code to the client browser whenever exceptions occurred. This behavior happened whenever debugging was enabled, regardless of the custom error setting in the configuration. So, even if you properly configured your Web-based applications to display non-descriptive messages when errors occurred, you could still have unexpectedly revealed your source code to your end users if you forgot to disable debugging.

If you want to disable debugging, set the value of the "debug" attribute of the <compilation> element to "false."

4. Cookies Accessible through Client-Side Script

In Internet Explorer 6.0, Microsoft introduced a new cookie property called "HttpOnly". While you can set the property programmatically on a per-cookie basis, you also can set it globally in the site configuration.

Wrong configuration:

<configuration>

<system.web>

<httpCookies httpOnlyCookies="false">

Right configuration:

<configuration>

<system.web>

<httpCookies httpOnlyCookies="true">

Any cookie marked with this property will be accessible only from server-side code, and not to any client-side scripting code like JavaScript or VBScript. This shielding of cookies from the client helps to protect Web-based applications from Cross-Site Scripting attacks. A hacker initiates a Cross-Site Scripting (also called CSS or XSS) attack by attempting to insert his own script code into the Web page to get around any application security in place. Any page that accepts input from a user and echoes that input back is potentially vulnerable. For example, a login page that prompts for a user name and password and then displays "Welcome back, <username>" on a successful login may be susceptible to an XSS attack.

As mentioned earlier, it is possible to enable "HttpOnly" programmatically on any individual cookie by setting the "HttpOnly" property of the "HttpCookie" object to "true." However, it is easier and more reliable to configure the application to automatically enable "HttpOnly" for all cookies. To do this, set the "httpOnlyCookies" attribute of the <httpCookies> element to "true."

5. Cookieless Session State Enabled

In the initial 1.0 release of ASP.NET, you had no choice about how to transmit the session token between requests when your Web application needed to maintain session state: it was always stored in a cookie. Unfortunately, this meant that users who would not accept cookies could not use your application. So, in ASP.NET 1.1, Microsoft added support for cookieless session tokens via use of the "cookieless" setting.

Right configuration:

<configuration>

<system.web>

<sessionState cookieless="UseUri">

Secure configuration:

<configuration>

<system.web>

<sessionState cookieless="UseCookies">

Web applications configured to use cookieless session state now stored the session token in the page URLs rather than a cookie. For example, the page URL might change from

http://myserver/MyApplication/default.aspx to http://myserver/MyApplication/(123456789ABCDEFG)/default.aspx. In this case, "123456789ABCDEFG" represents the current user's session token. A different user browsing the site at the same time would receive a completely different session token, resulting in a different URL, such as http://myserver/MyApplication/(ZYXWVU987654321)/default.aspx.

While adding support for cookieless session state did improve the usability of ASP.NET Web applications for users who would not accept cookies, it also had the side effect of making those applications much more vulnerable to session hijacking attacks. Session hijacking is basically a form of identity theft wherein a hacker impersonates a legitimate user by stealing his session token. When the session token is transmitted in a cookie, and the request is made on a secure channel (that is, it uses SSL), the token is secure. However, when the session token is included as part of the URL, it is much easier for a hacker to find and steal it. By using a network monitoring tool (also known as a "sniffer") or by obtaining a recent request log, hijacking the user's session becomes a simple matter of browsing to the URL containing the stolen unique session token. The Web application has no way of knowing that this new request with session token "123456789ABCDEFG" is not coming from the original, legitimate user. It happily loads the corresponding session state and returns the response back to the hacker, who has now effectively impersonated the user.

The most effective way to prevent these session hijacking attacks is to force your Web application to use cookies to store the session token. This is accomplished by setting the "cookieless" attribute of the <sessionState> element to "UseCookies" or "false." But what about the users who do not accept cookies? Do you have to choose between making your application available to all users versus ensuring that it operates securely for all users? A compromise between the two is possible in ASP.NET 2.0. By setting the "cookieless" attribute to "AutoDetect", the application will store the session token in a cookie for users who accept them and in the URL for those who won't.

Hope it helps...

How to build a simple ASP.Net application with C# and Entity Framework

In this post I will show you a step by step example on how to build an ASP.NET application with C# and Entity Framework. First let’s try to define what EF is and why it is going to help us to create easily data-centric applications.Entity Framework is an object-relational mapping (ORM) framework for the .NET Framework.EF addresses the problem of Object-relational impedance mismatch. I will not be talking about that mismatch because it is well documented in many sites on the Internet. Through that framework we can program against a conceptual application model instead of programming directly against a relational schema-model. By doing so we can decrease the amount of code we do write to access a data storage and thus decrease maintenance time.

ADO.NET Entity Framework (EF) is included with .NET Framework 3.5 Service Pack 1 and Visual Studio 2008 Service Pack 1

So you must donwload and have this software installed if you want to follow along.

It is not going to be a very difficult example. I will just bring data from a entity model to a gridview control and then give the user a way to filter that data.

There are many new enhancements regarding EF in VS 2010 and .Net .4.0 framework. I will not be talking about that since these enhancements are brand new and I am currently looking into them. I will just mention model-first development. This feature allows you to create your entity data model from scratch and then generate a database from it!!! We will do the opposite in this example.

Obviously for this example we will need a database. I will use the Pubs database. This is a well known database and many people are familiar with its schema.You can download the Pubs database from this link. If you need some help on how to install the database have a look here .

I have installed SQL Server 2008 Standard edition in my PC. SQL Server 2008/2005 Express editions will work just fine.You can download SQL Server 2008 Express edition from this link. I have attached the Pubs database in my local instance of the SQL Server.

Let’s start out project.

1) Launch Visual studio 2008

2) Create a new Project and from the available templates choose “ASP.Net web application”

3) Choose C# as your language of development and save your project in your hard drive with a name e.g “EFWebApplication” and click “OK”.

4) Click on the Solutions Explorer and open the Default.aspx page.

5) From the Toolbox drag and drop on the page , a Gridview control, a Textbox control and Button control. Leave the default names.

6) From the Toolbox drag and drop a EntityDatasource control on the page.

7) Choose the data source of the gridview control to be the EntityDatasource1 object.

8) Now we are ready to create our entity model. Right – click on your project from the Solutions Explorer window and Add a new Item. From the availble templates choose ADO.NET Entity data model. Give it the name Pubs.edmx and click the Add button.

9) In the Entity data model wizard window choose Generate from database and click Next .

10) Click New Connection, choose the Server name and from the databases your Pubs database is attached and then connect to the Pubs database and test your connection and click OK

11) If you notice you will see that there is something called Entity connection string and looks like this

 

metadata=res://*/Pubs.csdl|res://*/Pubs.ssdl|res://*/Pubs.msl;

provider=System.Data.SqlClient;provider connection string=”Data Source=FOFO-PC;

Initial Catalog=pubs;Integrated Security=True”

The connection string used by the Entity Framework contains not only the database connection string, but a metadata parameter with pointers to three mapping files separated by a pipe character.These mapping files will be generated when we finish this wizard.

12) Click Next on your wizard window and from the databases objects available choose Tables and more specifically the Titles, Authors and TitleAuthor tables. Leave the Model namespace as pubsModel and click Finish.

13) Our new Pubs.edmx file called is created and all the entities are generated which are basically classes derived from the data model . Have a look at the picture below to see the Entity model in the Designer window. You can zoom in and zoom out using the appropriate buttons.

 


 

14) Have a look at the Mapping details of each entity type (Authors, Titles,  TitleAuthor). You can change if you want the property names for a particular entity type. For example you can change au_lname to lastname of the Authors entity type. You can also change the names of the entity types and singularise them in a way so they resemble more like a class name. Change Authors to Author and Titles to Title from the Designer.

15) Go to your default.aspx page and click on the EntityDatasource object and hit the option Configure Data Source. In the window that appears choose Named Connection and select the PubsEntities that will apear in the drop-down and hit the Next button.

 

 16) In the next step from the EntitySetName select authors. Select all fields and and enable automatic inserts,updates,deletes and hit the Finish button.

 

17) In your gridview control enable paging,sorting,editing,deleting and selection.

 


 

18) Build and run your application and see the records in your web page. Try to sort,edit, delete records. Well done!!!!

19) Let’s give the ability to the user to apply a filter to the data by typing something to the textbox and return only the relevant data.Choose your EntityDatasource object and from the Properties window select  Where. Click on the “…” to launch the Expression editor window.

20) We will create an expression to use it as a filter(e.g filter the records by city name). The expression could be something like this

it.city=@city OR @city IS NULL

This expression above is written in Entity SQL which is T-SQL like syntax.

Click the Add Parameter button and under name write “city” and the value will be a control, so from the Parameter Source select Control and from the ControlID your textbox control (e.g TextBox1)

Go to show advanced properties and in the “Type” field choose String.  Your settings should be like this:

 


 

21) Hit the OK button to close the Expression Editor window. Hit F5 to run your application. In the textbox type

“Oakland” and hit the button control. See the filtered results. That is all!!!! We did that without writing a single line of code.

If you need the source code for this example, just leave a comment and I will email it to you as soon as possible.

 

Viewstate management in ASP.Net 4.0

In ASP.NET 4.0 we have some very interesting new enhancements and new features.

I will try to talk about all of them in separate posts.

In this post I will talk about Viewstate management in ASP.NET 4.0.

Let’s have a look first what really Viewstate is and what it really does.Unless you move to a new paradigm for building web applications like ASP.NET MVC you must have a good knowledge of Viewstate.

Viewstate represents the state of the page when it was last processed on the server. We use it to retain values across two successive requests for the same page. It is a hidden field added to the page and is restored on the server before the page request is processed. The Viewstate information travels back and forth with the page itself, but contains no visual elements that need to be rendered. So you must be thinking that this is fantastic news for the web developer. But (there is always a but), the extra information in the Viewstate adds to the size of the page and the information that travels down the wire. I have seen web pages that have an additional 20Kbytes of Viewstate information.

Every .aspx page derives from the Page class or Page control and extends it. The default value for the EnableViewState property for the page is True. Through that property we can get or set(enable-disable)  the view state of the control. However, EnableViewState property is ignored for child controls. So if we have EnableViewState=True for the page, which is True by default, all the child elements on that page will have EnableViewState=True for their viewstate property. So if we type this  txtname.EnableViewState = false , this will have no effect, since the textbox is the child of the .aspx page we are designing.

There is a mistake here. The opposite is actually true.If we disable ViewState on page level, you cannot enable it on child controls. if you go to the web.config and type

<pages enableViewState="false">

then if you try to enable it on child controls is impossible.

So to be absolutely clear, in asp.net 1.1,2.0.3.5 if you have ViewState enabled on page level , you can have it disabled for some controls you choose.

But if you disable it on page level(or application level) you cannot enable it for individual controls.

See an example below(in the comments section written by Richard).

Credit and kudos to Richard  for pointing that out and correct me. Thanks Richard!!!!!

In ASP.NET 4.0 we have the ViewState property. There are 3 values for this property:enabled, disabled, inherit .

We can use this property to enable Viewstate for an individual control even if Viewstate is disabled for the page. We can disable the Viewstate for a control even if it is enabled on a page level.

How to create,use and manipulate a web user control

User controls are reusable controls that can be defined once and used whenever we need them, in any of the .aspx pages of our application. We do have skins,themes and css to give a standard look to our website. User controls help to achieve that as well because since we define them once and use many times, thus making sure we do not have same controls on pages looking differently. When we make changes to a user control all these changes will be reflected to all instances of the control.

I will try to highlight the following in this post

 

  1. What is a user control and why we need it
  2. How to add Content to a User Control
  3. How to add a User Control to a Web Page
  4. How to define properties in a User Control
  5. How to handle events in a User Control
  6. How to raise events in a User Control
  7. How to access the contents of a User Control

 

We will have to create a simple user control step by step.Imagine you have many pages in your asp.net website. Let's say that you are developing a fully functional e-commerce site. You will find that you need to collect user data, e.g address information (shipping address info,billing address info,registration customer address info). In this example we will use a user control to collect customer address data.

 

We just need Visual Studio 2005/2008 or VS 2010.

1) Launch Visual Studio and create a new asp.net website

2)  Save this website in you local file system and give it a name. Choose C# as your development language for this website

3)  Add new folder to your website and name it UserControl

4) Right-click on this folder and add a new item. From all the items available select a Web User control. Also choose C# as the development language and tick the option Place code in a seperate file.Name the control Address.ascx

5) Switch to the Source view of the Address.ascx control.Have a look at the first line.

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="Address.ascx.cs" Inherits="UserControls_Items_Address" %>

Notice that even though this directive looks a lot like a page directive it starts with  @ Control

6)  Open the Address.ascx.cs file.Your newly create class does not inherit from the System.Web.UI.Page but from

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

The classes System.Web.UI.Page and System.Web.UI.UserControl have lots in common since they both inherit from another class,TemplateControl class

For more information click here

7)  Let's work on our new user control. Insert a table in your "Address.ascx" page. This table should have 4 rows and 2 columns.

8)  Add 4 label web server controls on the first 4 rows of the first column. Set their ID property as you like(AddressLabel1,AddressLabel2,AddressLabel3,PostCodeLabel). Set their text property like  this

  • Address1
  • Address2
  • Address3
  • PostCode

9) Add 4 textbox web server controls on the 4 rows of the second column.Set their ID property like this

txtaddr1,txtaddr2,txtaddr3,txtpostcode

10)  In order to add this newly created web user control to the Default.aspx page just drag and drop it from the Solution Explorer onto the .aspx page

11) Look in the source view of the Default.aspx page and notice this line

<%@ Register src="UserControl/Address.ascx" tagname="Address" tagprefix="uc1" %>

This is how the user control is registered with the .aspx page. You will also see this

<uc1:Address ID="Address1" runat="server" />

Change the ID property to Shipping_Address

 12) We can add new server controls to our user control. If we wanted to have a label control as a header we must select the Address.ascx and just above the table to insert a new label.Name this label headingLabel.

One can set the Text property of this new header label control and make it apparent to the end use that we talk about Shipping Address. But as I mentioned before we need to use this user control in many places in our website. So we do not want to have a fixed Text property but one we can set its value accordingly.

Select the Default.aspx page and in the

 <uc1:Address ID="Shipping_Address"  runat="server"/> section you will see that headingLabel is not exposed as a property. It cannot be accessed from our page.

 

So we must add a new public property on this UserControl_Address class.This is the same with every other normal class.

So in the Address.ascx.cs file type

 

 public string Header
    {
        set { headingLabel.Text = value; }
    }

 

13) Now you can go back to the Default.aspx page (Source View) and add the Header=Shipping Address <uc1:Address ID="Shipping_Address"  runat="server" Header="Shipping Address">

14) It is very easy to handle events in a user control.Add a button to the user control. This means that you go to the Address.ascx file and drop a button under the table. Set the ID property to be txtNext and the Text property to be Next. Add another .aspx page to your website and call it Checkout.aspx. Double click on the button and you have the empty event handling routine.

Type the following

 protected void Button1_Click(object sender, EventArgs e)
    {
        Response.Redirect("~/Checkout.aspx");
    }

 You see how easy it is to handle events in a user control.

 14 ) Let's see now, how we can create an event in the user control. First we need to define an event.

When we define an event we must define the signature of the event handler method. We do that by choosing a delegate type.We also must give a name to our event. We will call it Confirmed event.


Select the Address.ascx.cs  and type

public event EndEventHandler Confirmed

So we know now that our user control class will raise an event and we must write some code to actually cause this event to be raised.

So in our Button_Click event handler, we type

if (Confirmed!=null) Confirmed(this, new EventArgs());

When the user clicks the button, the Confirmed event will be raised.

Select the Default.aspx page and in the Source View locate the

<uc1:Address ID="Shipping_Address"  runat="server" Header="Shipping Address"/>

and change it to 

<uc1:Address ID="Shipping_Address" onConfirmed="ShippingAdress_Confirmed"  runat="server" Header="Shipping Address"/>

We just added the event handler in the user control.We do that by entering the name of the event and the name of the event handling routine we will add shortly.

In order to add the ShippingAdress_Confirmed event handling routine we go back to the Default.aspx.cs file and type

protected void ShippingAdress_Confirmed(object sender, EventArgs e)
    {
      
       
    

    }

Inside this routine add this line of code:

Response.Write("The event has been handled");

Run the application and you will see the event raised and handled (the text "The event has been handled" will be printed in the Default.aspx page)

For more information on events have a look here .

15) Let's assume that we need 2 instances of our user contol in the Default.aspx page (e.g one for shipping address and one for billing address).Select the Default.aspx and add a new user control. Go to the Source View and add a Header property e.g Billing Address. Also set the ID property to "Billing_Address". You should have something like this

 <uc1:Address ID="Billing_Address" runat="server" Header="Billing Address" />.

Run the application and see the 2 user controls.

We need to copy all the fields entered in our Shipping address to the Billing address fields.

So we must access the text properties of the Shipping_Address user control and copy them to the Billing_Address user control.

You will see that it is impossible to access these textbox values directly  from ShippingAdress_Confirmed event handler in the Default.aspx.cs class, because these text properties are protected and thus invisible to the event handling routine.

So we need to create some public properties in our user control class.

Select the Address.asx.cs file and type

 

 public string Address1
    {
        get {return txtaddr1.Text; }
        set {txtaddr1.Text=value;}
    }
    public string Address2
    {
        get { return txtaddr2.Text; }
        set { txtaddr2.Text = value; }
    }
    public string Address3
    {
        get { return txtaddr3.Text; }
        set { txtaddr3.Text = value; }
    }
    public string PostCode
    {
        get { return txtpostcode.Text; }
        set { txtpostcode.Text = value; }
    }

 16) Select the Default.aspx.cs file and inside the ShippingAddress_Confirmed event handling routine, comment out the ( Response.Write("The event has been handled");) and type

 
        Billing_Address.Address1 = Shipping_Address.Address1;
        Billing_Address.Address2 = Shipping_Address.Address2;
        Billing_Address.Address3 = Shipping_Address.Address3;
        Billing_Address.PostCode = Shipping_Address.PostCode;

Run your application. Type some address data into the first user control and then click the button.You will see the entered data copied in the second user control.

Hope it helps. If you need the source code just email me.

More Posts