jump to navigation

Create an Asp.Net web user control with C# October 28, 2009

Posted by fofo in C#, Visual Studio 2005, Visual Studio 2008, asp.net.
Tags: , ,
1 comment so far

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 devlopment 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 theSystem.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 IDproperty 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 IDproperty 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 Textproperty 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 thatheadingLabel 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 theHeader=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 IDproperty 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 itConfirmed 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 theDefault.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  fromShippingAdress_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.

Add to FacebookAdd to NewsvineAdd to DiggAdd to Del.icio.usAdd to StumbleuponAdd to RedditAdd to BlinklistAdd to TwitterAdd to TechnoratiAdd to Furl

Creating an ASP.NET Dynamic Data Web Site with VB.Net October 13, 2009

Posted by fofo in VB 2008, VB 9.0, Visual Studio 2008, Visual Studio 2010.
Tags: , , , ,
1 comment so far

I wanted to do a post on ASP.NET Dynamic Data for a long time. I had a seminar the other day and I was asked if I could blog on this technology, so here I am.

First things first. ASP.NET Dynamic data shipped (August 2008) with .NET 3.5 SP1 and Visual Studio 2008 SP1.Before that it was a part of the “ASP.NET 3.5 Extensions” package that was shipped back in 2007.

So why  is this an exciting feature? We can quickly build data centric web-sites that work against a LINQ to SQL (or a LINQ to Entities) object model without having to build any of the pages manually!!!!!Scaffolding is an important concept in ASP.NET dynamic data terminology so let’s give it a formal definition.

Scaffolding is a mechanism that takes the power and functionality of the existing asp.net page framework  and enhances it by dynamically displaying pages based on the data model without a physical page to actually exist.

There are many advantages when using the scaffolding mechanism. Some of them are

  • We have to write very little or no code to create a data-driven Web application. This means quick development time,less bugs and code easier to maintain.
  • In all pages we have all the CRUD operations available with no effort
  • Paging,sorting,filtering functionalities are also included-generated
  • Built-in validation which follows the db schema

The scaffolding mechanism uses templates so we can view the data. When you create you asp.net dynamic data website you will see the PageTemplates folder.These are the default templates scaffolding uses to show us the data. Obviously you can change these templates according to your project needs.

I will try to demonstrate all the concepts related with an asp.net dynamic data web site in the following, walktrhough-demo.

In order to follow along you need a VS 2008 SP1 or Visual web developer 2008 SP1 and .Net 3.5 SP1. 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 will use VB.Net as the development language.

1) Launch VS 2008 and create a new website

2) From the available templates, select Dynamic Data Web Site

3) Choose VB as the development language, as Location your File System and then save your website giving it an appropriate name, e.g Dynamic Data

4) Now you will have in your Solution Explorer all the files created for us. I urge you to have a look at the DynamicData folder and the .aspx pages and templates beneath it.Look closely inside the PageTemplates folder.

5) Also have a look at the FieldTemplates folder. Scaffolding uses Field templates to  create default rendering for displaying and editing data.One can customize the default field templates or create new ones from scratch.Notice that field templates are web user controls.

6) Obviously for this example we will need a database. I will use the Northwind database. This is a well known database and many people are familiar with its schema.You can download the Northwinds database from this link. When you finish downloading just drag and drop the .mdf and .ldf files in the App_Data special folder.

7) We will use LINQ to SQL(one can use Linq to Entities as well) in order to generate our object model. Select your project from the Solution Explorer and select Add -> New item -> LINQ to SQL Classes, change the name to Northwind.dbml and click Add.

8) Go to you Server Explorer – Database Explorer and from the Northwind database drag and drop some tables onto the designer(Categories,Orders,Products,Customers)

9) Now we have our object data model that relates to the underlying db schema thanks to LINQtoSQL. You will have the main class which is NorthwindDataContext.

10) If we try to run our application we will receive an exception. We must do something else first. We need to open the Global.asax file in the Solution Explorer.

In this file you will see commented lines of code and simple comments. Make sure you uncomment this line

DefaultModel.RegisterContext(GetType(YourDataContextType), New ContextConfiguration() With {.ScaffoldAllTables = False})

and replace the YourDataContextType with this NorthwindDataContext and also set .ScaffoldAllTables = True (which is the not wisest thing to do, in a real world scenario)

11) Run you application. If you have followed all the steps so far, you will see your application up and running. Have a look at the picture below

scaff

12 ) Click on the Categories table. Notice that you can

  1. Edit a category
  2. Delete a category
  3. Insert a new category
  4. View Products per category
  5. You can sort by CategoryName

13) Click on the Customers table. You will see that we have Paging enabled and choose how many records per page we want displayed.

14) Click on the Orders table and see that we have built-in filtering features with zero effort.

15) Click on the Products table. Click to edit the product. Delete the product name and click Update. You will see a validation error message and the update will fail(as we would want to)

Amazing, truly amazing!!!

16) Have a look at the urls in the browser window. For example if you click the Categories table, you will see something like that.

http://localhost:6754/Categories/List.aspx

You might wonder from where this URL takes its name?

Open your Global.asax file again and note the

routes.Add(New DynamicDataRoute(“{table}/{action}.aspx”)

You know something….. Routing is not just an MVC thing…

If you close the browser window and return to the Solution Explorer, under the DynamicData folder you will see no .aspx pages code generated e.g a Products page or a Customers page. What you must understand is that we are talking about dynamic templating and the display is based on the various templates (which are easily customisable) and the data retrieved from the data model.

That is all.More to follow on Dynamic Data in future posts. Hope it helps.

Add to FacebookAdd to NewsvineAdd to DiggAdd to Del.icio.usAdd to StumbleuponAdd to RedditAdd to BlinklistAdd to TwitterAdd to TechnoratiAdd to Furl

ASP.NET 4.0,SEO and meta tags September 27, 2009

Posted by fofo in ASP.NET 4.0, Visual Studio 2010.
Tags: ,
add a comment

I am thinking to create a new series of posts regarding ASP.NET and SEO (Search Engine Optimisation). I am going to start with this post , talking about some new features that make our asp.net apps more SEO friendly. At the end of the day, there is no point having a great application and somehow “scare” the search engines away. This is going to be a short post so let’s quickly have a look at meta keywords and ASP.NET 4.0.

Meta keywords and description are important elements of a page and make it search engine friendly. ASP.Net 4.0 added 2 new properties on the Page object to let us define the Meta Keywords and Description.

Create a simple asp.net application using Visual Studio 2010. In the Default.aspx.cs code behind file type

Page.MetaKeywords = “asp.net,vb,c#,css,html,”;

Page.MetaDescription = “This is my blog that focuses on ASP.NET.”;

Alternatively we can add those two meta tags in the Page directive

<%@ Page Language=”C#” MetaKeywords=”asp.net,vb,c#,css,html” MetaDescription=”This is my blog that focuses on ASP.NET.” AutoEventWireup=”true”  CodeFile=”Default.aspx.cs” Inherits=”_Default” %>

Run your application. Go to View->Source and see the meta tags

</title><meta name=”description” content=”This is my blog that focuses on ASP.NET.” /><meta name=”keywords” content=”asp.net,vb,c#,css,html” /></head>

Hope it helps!!!

Add to FacebookAdd to NewsvineAdd to DiggAdd to Del.icio.usAdd to StumbleuponAdd to RedditAdd to BlinklistAdd to TwitterAdd to TechnoratiAdd to Furl

ASP.NET 4.0 Entity DataSource and GridView September 27, 2009

Posted by fofo in ASP.NET 4.0, Visual Studio 2010, c# 4.0.
Tags: , , , ,
add a comment

Recently I had the time to examine thoroughly my blog stats. From that it was evident people liked a lot the posts regarding the new features in .Net 4.0. So in this post I am going to discuss the new Entity DataSource web server control which is  similar to the LINQ to SQL DataSource, except it allows you to use your Entity Framework data object model instead. I will also demonstrates the new features of the GridView control. I have talked about EF and how to build an application with EF and C# in one of my previous posts. In this post I will talk more about the Entity Datasource object and enhancements made in the GridView control.

I will create a sample website as always so it is easier for you to understand.In order to follow along you must have installed in your PC VS 2010 and the .NET 4.0 framework.Obviously we are going to need a data store for our application. I will use the AdventureWorksLt which you can download from this site .

1) Launch Visual Studio 2010 and create a new web site.

2) Choose Asp.Net application from the available templates and C# as the development language

3) You now have your files in the Solution Explorer window.

4) Choose the default.aspx page and go to your Toolbox and under the Data Controls drag and drop an Entity Datasource control on the page.

5) Now you need an Entity Data model that the Entity Datasource can bind to. In the Solution Explorer add (right-click) a new special folder , App_Code

6) Select the App_Code and add a new item(right-click) , ADO.NET Entity Data Model.Leave the default name.

7) In the next window select “Generate from database” and click Necxt.

8) In the next window of the Entity model wizard create a new connection to you database (AdventureWorksLT)or select an existing connection that points to the same db.

9) Save the entity connection settings in the web.config file

10) Click Next on the wizard window. From all the available db objects we want to include in our model only tables and more specifically only the Products table.

11) Select the table and click Finish. So now we have a Product Entity with all the mappings to the database.

12) Select the Entity Datasource control and click the arrow on the right-top corner and select Configure Data Source.

13) Select in the Named Connection option of the wizard and select the AdventureWorkLTEntities and click Next

14) In the EntitySetName select Product and from the available Entity values select ProductID,Name,ListPrice,Size,Weightand and click Finish.

15) Drag and drop on the default.aspx page a Gridview control (control in your Toolbox data controls area).Give it some formatting from the AutoFormat options

16) Set the datasource of the Gridview control to the Entity datasource.

17) Enable Sorting,Paging and Selection for the Gridview control

18) Run your application by hitting F5 from your keyboard. If everything is ok you will be able to see a list of products in your page.

The imporevement in the GridView control is about selecting rows.If you selected an item in GridView(the third one for example) and then browsed through the pages the third item in every page will also be selected. That was not always what we wanted. The GridView control did that based on an index it had and used to find the third item on that page.

We can overcome that by enabling the EnablePersistenSelection property and setting it to True.

Then we need to select the DataKeynames property and set it to ProductID.

19) Now if run our application again and select a product in the first page(6th product), and browse through the pages the product in position 6(index 6) is not selected anymore.Now the selection is made over the underlying primary key and not the index in the view of the GridViewControl

Hope it helps!!!

If you need the source code just email me or just comment on this post.

Add to FacebookAdd to NewsvineAdd to DiggAdd to Del.icio.usAdd to StumbleuponAdd to RedditAdd to BlinklistAdd to TwitterAdd to TechnoratiAdd to Furl

Using the ASP.Net Calendar Control September 21, 2009

Posted by fofo in C#, Visual Studio 2005, Visual Studio 2008, asp.net.
Tags: , , , ,
1 comment so far

I have been using my blog to talk primarily about new things and enhancements in the .Net Framework. I have been talking about C# new features,VB new features, LINQ,Entity framework and the new Visual Studio 2010. The other day during a seminar I was asked about a very important ASP.NET 2.0 web server control, the calendar control. So I thought to write a post and look into this very useful control, presenting its basic functionality but also looking into the more advanced functionality it has.

So what is the calendar control.

A simple but powerful definition could be:

It allows the users to select a date or a range of dates withing an application

I will be using VS 2008 and C# to create a simple asp.net application.

1) Launch Visual Studio 2005 or 2008.

2) Create a new website and name it with a meaningful name, e.g CalendarSite

3) Drag and drop a Calendar control from the toolbox into the default.aspx page.Leave the default name

4) Let’s examine some of the most used properties.

SelectedDate: By setting this property to a value, you have this value-date selected in the calendar control. Set the value to a date and run your application

VisibleDate:Whenever we want to use a different month or year, when the control initially loads, we can set the VisibleDate property to a date

If you want to select any particular day just click on the hyperlink on the bottom of each day.

5) But what if we wanted to select all of the days of a particular week or all the days of a particulat month.

Then we need to look into another useful property of the Calendar control, the SelectionMode. For selecting all the days of the week, you can set its value to DayWeek.

For selecting all the days in a month, you can set its value to DayWeekMonth.

Run your application and you will see more selectors (arrows) in the calendar control. By clicking on them you will be able to select a whole week or month.

Some other very important properties are:

  • DayNameFormat , which allow us to change the number of letters the header day text contains
  • FirstDayOfWeek, which allow us to set the first day of the week to Monday if we want to

We have so many options to style the control by setting the values of properties like BorderColor,BordeWidth,BorderStyle,BackColor to the values we want. We can also set the values of various font properties. We can always use the smart tag(little arrow on the top right hand corner) to use one of the many predefined formatting styles for our calendar control.

Now that I have covered some of the basic stuff, I would like to mention

  • Calendar click events
  • Control Calendar cell’s rendering

6) Every time the user selects a date in you calendar control, you capture this selection by the SelectionChanged event.

Add a literal control to the default.aspx page. Name it SelectedDatesLiteral

Just double click on a day in the calendar control. In the event handling routine, type the following

foreach (DateTime selectedDate in Calendar1.SelectedDates)
{
SelectedDatesLiteral.Text = string.Format(“You selected: {0:d}<br/>{1}”, selectedDate, SelectedDatesLiteral.Text);
}

Here, I just loop through the selected dates and append their values to a literal control.Run your application and see for yourself.

7) If we want to add content in a day in the calendar, we must use  the DayRender event. This event is invoked once for every day in the calendar. The table cell and the date are passed to the event handler and can be used to render custom content or look up data in a database etc. We will pull event data from an xml file.Add an xml file to your project and call it events.xml. Place this file in the App_Data special folder. The contents of this file could be something like this

<?xml version=”1.0″ encoding=”utf-8″ ?>
<Events>
<Event Month=”1″ Day=”1″>Happy New Year.</Event>
<Event Month=”2″ Day=”29″>Happy leap day.</Event>
<Event Month=”12″ Day=”25″><![CDATA[Merry Christmas.]]></Event>
<Event Month=”12″ Day=”7″><![CDATA[Bob's Birthday!]]></Event>
<Event Month=”12″ Day=”28″><![CDATA[16th anniverary]]></Event>
</Events>

Add a XMLDataSource control in to your default.aspx page and configure it so it reads the contents of your xml file.

Then in the DayRender Event type the following

protected void Calendar1_DayRender(object sender, DayRenderEventArgs e)
{
string xpath = string.Format(“//Event[@Month={0} and @Day={1}]/text()”, e.Day.Date.Month, e.Day.Date.Day);
XmlDocument doc = XmlDataSource1.GetXmlDocument();

StringBuilder content = new StringBuilder(e.Day.DayNumberText);
foreach (XmlNode node in doc.SelectNodes(xpath))
{
content.Append(“<br/>”);
content.Append(node.Value);
}

e.Cell.Text = content.ToString();
}

Make sure you have added these namespaces in the Default.aspx.cs file

using System.Xml;
using System.Text;

I am using an XPath to filter out only the nodes in our xml document that have content.

Then I am opening the xml document and then I am building a string with values that will be displayed in the calendar cell for the current day.

Then I loop through all the items that were returned back from the XML document and append those values together in order to create a string of all of events that happend in this specific day.

Run your application and see the content that is passed from the xml file to the specific dates, e.g Christmas day.

If you need the full code, just email me.

Hope it helps!!!

Add to FacebookAdd to NewsvineAdd to DiggAdd to Del.icio.usAdd to StumbleuponAdd to RedditAdd to BlinklistAdd to TwitterAdd to TechnoratiAdd to Furl