Monday, June 28, 2010

Sharepoint WORKFLOW

The majority of workflows involve a person in the process at some point. SharePoint is ideal for this. There are other types, such as ‘system’ workflows which pass messages between disparate systems, and there are specific tools to manage these, such as Microsoft BizTalk Server.
If you have purchased the enterprise SharePoint product Microsoft Office SharePoint Server (MOSS) 2007 then you will have seen that there are several workflows included , such as ‘Approval’, ‘Collect Feedback’, ‘Collect Signatures’ . However, at some point you are going to have to create and customise your own workflow. Fortunately, Microsoft has now provided you with Microsoft Office SharePoint Designer, which is a free product and makes this task simple and productive. To follow through the examples in this article you will need to download a copy of SharePoint Designer from Microsoft’s website.
You can customise SharePoint sites with SharePoint Designer. This is a tool for designing and developing custom workflows that then allows you to and attach these to your lists and libraries. This is done with a very simple wizard-like interface. Once you understand the concepts of creating workflow in this manner you will be surprised by what can be achieved without the need to turn to custom code and Visual Studio.
The easiest way of introducing workflow in SharePoint is to show you a simple example that makes small calculations and changes. This is slightly artificial because SharePoint also provides us with EventReceivers which are much better for small changes based upon an add/edit/delete within a list. The example used in this article would actually lend itself to an EventReceiver rather than a workflow, but serves to show the principles. To get things up and running quickly, I am going to add a custom workflow to the example begun in the first article in this series.
Planning a workflow
We are going to develop a simple workflow to manage the stock of our products and to alert a stock controller that we need more inventory when it runs short. In order to do this I have added a new column to the Products list called Inventory and set it to 500 for all our products.

Before we can begin designing this workflow, we must plan out exactly what it will do. The easiest way to do this is to draw out a flowchart-type diagram representing the process. Now you could go to town on this and use Microsoft Visio or some other drawing tool, but a simple hand drawn sketch is just as good, as long as you have an accurate idea of what your workflow needs to do. Below is a sketch of our workflow (please excuse my handwriting).

Once you have planned out your process then you need to design this in SharePoint Designer.
Creating a basic workflow
We need to attach our workflow to the Orders list so that the inventory is updated every time a new order is made.
To create a new custom workflow:
• Open SharePoint Designer.
• Select File > Open Site
• In the Site name: text box enter the full URL to your site.
• Click Open
• Select File > New > Workflow
At this point SharePoint Designer needs to retrieve some information from your site so this may take a few seconds.
You are now presented with the workflow designer. This is the main interface that you will use to create and modify your workflows. It is designed to work in stages.
• In the workflow designer type a name in the box labelled ‘Give a name to this workflow:’
• Select the Orders list from the drop down menu labelled ‘What SharePoint list should this workflow be attached to?’
• Within the options labelled ‘Select workflow start options for items in Orders:’ ensure that the checkbox labelled ‘Automatically start this workflow when a new item is created’ is checked, but none of the others.

• Click Next
You are now in a position to create a series of steps for this workflow. Each step consists of a number of lists of actions which can be executed depending upon a condition. Conditions can be selected from the list shown below. If none are specified then the actions listed will be executed regardless.

In your example you simply want to update the Inventory column for every new order so there is no condition to meet. However this is a powerful area of workflow and its worth exploring some of these different conditions.
• In the ‘Step Name’ box enter a name that indicates what this step will do. I have used ‘Update Inventory’
• Under Actions select ‘More Actions…’
• You should now see the workflow actions dialog. This will allow you to choose from a range of possible actions to perform within this workflow. If you select All Actions from the Select a Category drop down menu then you should see all available workflow actions.

• As per our workflow diagram we need to get the quantity field from our order into a variable. This is done using the ‘Set Workflow Variable’ action. So select this from the Choose an Action list, and click Add.
• You will notice that our action is represented by a sentence within the actions of this workflow step. This sentence contains links which enable you to configure the variables assigned to the action.

• Click on ‘workflow variable’ and select Create a new variable.

• In the Name box type ‘OrderQuantity’ and select Number from the Type drop down menu.
• Click OK
• In the actions list select the value link within our action.

• Now select the fx button in order to lookup a value.

• Leave Source set to Current Item
• Select Quantity in the Field drop down menu.
• You need to perform a calculation based on this, so click on Actions and select ‘Do Calculation’ you may need to select the More Actions option to find this action.
• There are three properties to set on this action so click the first ‘value’ and select the fx button.
• You need to look up the inventory of the purchased product from the Products list, so select Product in the Source drop down menu.

• Select Inventory in the Field drop down menu.
We have two additional options in this dialog now to allow us to identify the item in the products list that we want to get this value for. This type of operation is common within workflows in SharePoint so you should take some time to understand what is happening here.
Under ‘Find the List Item’ you need to choose a field and value which uniquely identify the product in question. Ideally this would be something like the ID column. However we do not have a method to retrieve the ID of the list item we are interested in, we only have the lookup column on our existing item and that contains the Product Name. However the product name should also be unique so we will use this.
• In the Field drop down menu under ‘Find the List Item’ select Products:ProductName

• Next to the Value box select the fx button to perform a lookup.
• Leave Source as Current Item, but in the Field drop down menu select Product
• Click OK to close the Define Workflow Lookup dialog.
• You will get a notification from SharePoint Designer. This is telling you that your lookup is not guaranteed to return a unique value (because you could enter the same Product Name twice); however in our situation this is acceptable so you can click Yes to continue.

• Click on the ‘plus’ within the action description and select minus.

• Click on the remaining ‘value’ within the action description and select the fx button.
• In the Source drop down menu on the Define Workflow Lookup dialog select Workflow Data.
• In the Field drop down menu select Variable: OrderQuantity

We now have a variable called Calc which contains the updated inventory count for our product. So the remaining part of our workflow is to update the Products list with the new inventory count.
• Under the actions drop down menu select Update List Item.
• Click on ‘this list’ in the action description.
• In the Update List Item dialog select Products from the List drop down menu.

• Click on Add to select a field on this list to update.
• Select Inventory under Set this field
• Click on the fx button to lookup the value.
• In the Source drop down menu on the Define Workflow Lookup dialog select Workflow Data.
• In the Field drop down menu select Variable: calc
• Click OK

• Click OK in the Value Assignment dialog
• You need to use exactly the same settings as you did previously to identify the list item within the Products list.

• Click on OK and click Yes on the warning dialog.
• Finally click Finish on the Workflow Designer dialog.
This workflow is now complete and SharePoint Designer will have attached this to the Orders list for you. If you now go and create an Order for a new Product you will see that the Inventory field on your associated Product list item is updated accordingly.
The purpose of this simple workflow has been to introduce you to the power within workflows and how they can quickly and easily simplify some of the more mundane tasks within your business processes. Now try creating a new workflow to ensure that the Total field for your order is calculated for you based on the Price field of the Products list. This uses the same skills you will have learned from this article and it will help to ‘cement’ this technique in your memory.
Next time I will be looking at how developers can create custom workflows within Visual Studio 2008 and harness the full power of Windows Workflow Foundation.



























Introduction
Workflows are now an integral part for any project. You can build a SharePoint work flow using the available templates, SharePoint designer and Visual Studio 2005 / 2008. This tutorial will mainly concentrate on workflow creation using SharepPoint designer. We will walk through the basic 8 steps needed to create workflows using SharePoint designer.

I have published some videos on SharePoint, WCF, WPF, WWF, design patterns, UML, FPA, Enterprise blocks, etc. You can watch the videos here. You can download my 400 .NET FAQ EBook from here.
8 Steps to Create Workflow using SharePoint Designer
SharePoint designer helps us to create workflows and attach the workflows to a content type like list, document, etc. In other words, SharePoint designer creates workflows and publishes the workflow on the SharePoint server site.

To understand it better, we will build a simple workflow of completed and incomplete tasks. We will create two lists, one is the incomplete tasks and the other the completed tasks. The workflow will flow something like this:
• User will create a task and enter the status of the task.
• If the task is incomplete, nothing will happen.
• Once the task is marked as complete, the task will be copied from incomplete task list to completed task list.
• The task will be deleted from the incomplete task list.

So let’s understand the eight important steps we will need to create the above workflow using SharePoint designer.
Step 1
Create a team site using the SharePoint team site template.
Step 2
Create two task lists, one is incomplete task list and the other completed task list.
To create task list, click on site action -> Create: Add a new library list -> create a task.
Step 3
Start the SharePoint designer.

Step 4
Open the site in your SharePoint designer using click on file -> open site.

Step 5
Go to workflows by clicking on file -> new -> SharePoint content and click ok as shown in the below figure:

Step 6
This is an important step. In this step, we define two important things. The first is this workflow will be attached to which list. Currently we have attached the workflow to incomplete tasks list. Second we need to define the events on which the workflow should be activated. For the current scenario, we have considered two events; one when the item is created and the second when the item is updated.

Step 7
This is one more crucial step where we need to define on what condition the workflow will execute and what action should take place if the condition is true. So when a task status is completed, two actions will take place. First the task will be copied from the incomplete task list to the completed task list. Second the task is deleted from the incomplete task list.

Once you click finish, you can see the workflow created in the SharePoint designer. This workflow is also published to the SharePoint server,

You can see if the workflow is associated with the incomplete task list. Go to incomplete tasks -> Settings -> List settings -> Workflow settings. You can see that the workflow is attached to the incomplete task list.

Step 8
Ok, now it’s time to see the workflow in action. So go to incomplete task list and create a task with status completed.

Once you click ok, you see the task for some seconds in the incomplete tasks list and then the task is copied to the completed task list and deleted from the incomplete task list.

Previous SharePoint QuickStart FAQ


















This article will show us how to use the Datalist in a webpart and embedding CSS file and classes in the webpart.

First we are creating the webpart. For that follow the below steps
1. Create a webpart solution
2. Create a child controls and add the related code in webpart cs file like below

DataList dlNews;
Label lblNewsTitle;
protected override void CreateChildControls()
{
// Create and add the controls that compose the
// user interface of the Web Part.
Controls.Clear();
dlNews = new DataList();
//CSS link calling as object
Microsoft.SharePoint.WebControls.CssLink cssLink = new Microsoft.SharePoint.WebControls.CssLink();
cssLink.DefaultUrl = "/_layouts/1033/styles/News.css";
this.Page.Header.Controls.Add(cssLink);
// Create the Datatable
DataTable dtItem = new DataTable();
// send the Data items from this datatable
//News Datalist view
fillResultsDatalist(dtItem);

}
private void fillResultsDatalist(DataTable dtItem)
{
// Create an instance of the DataGrid and set its
// DataSource property to the supplied DataSet.
dlNews = new DataList();
dlNews.DataSource = dtItem;
dlNews.CellPadding = 0;
dlNews.CellSpacing = 0;
dlNews.BorderWidth = 0;
dlNews.RepeatDirection = RepeatDirection.Vertical;
// Calling the Itemplete for data list bound columns
dlNews.ItemTemplate = new DatalistLabelColumn();
// Bind the data to the DataGrid.
dlNews.DataBind();
//Add the DataGrid to the controls.
Controls.Add(dlNews);
}

3. Add/Create the the ITemplate class
///
/// Intialize the Container controls
///

///
public void InstantiateIn(Control container)
{
Label lblNewsTitle = new Label();
lblNewsTitle.DataBinding += new EventHandler(this.BindLabelColumn);
container.Controls.Add(lblNewsTitle);
Label lblNewsText = new Label();
lblNewsText.DataBinding += new EventHandler(this.BindLabelColumn1);
container.Controls.Add(lblNewsText);
LinkButton lnkButton = new LinkButton();
lnkButton.DataBinding += new EventHandler(this.BindLabelColumn2);
container.Controls.Add(lnkButton);
}
///
/// BindLabelColumn for Title of the News
///

///
///
public void BindLabelColumn(object sender, EventArgs e)
{
Label lblTitle = (Label)sender;
DataListItem container = (DataListItem)lblTitle.NamingContainer;
String strVals = Convert.ToString(DataBinder.Eval(((DataListItem)container).DataItem, "Titre"));
lblTitle.Text = "
> " + strVals + "
";
}
///
/// BindLabelColumn1 for news Description label
///

///
///
public void BindLabelColumn1(object sender, EventArgs e)
{
Label lblText = (Label)sender;
DataListItem container = (DataListItem)lblText.NamingContainer;
String strVals = Convert.ToString(DataBinder.Eval(((DataListItem)container).DataItem, "Text"));
strVals = Regex.Replace(strVals, @"<(.\n)*?>", string.Empty);
strVals = RetComments(strVals);
lblText.Text = "
" + strVals + "
";
}
///
/// BindLabelColumn2 for Link button
///

///
///
public void BindLabelColumn2(object sender, EventArgs e)
{
LinkButton lnkButton = (LinkButton)sender;
DataListItem container = (DataListItem)lnkButton.NamingContainer;
String strVals = Convert.ToString(DataBinder.Eval(((DataListItem)container).DataItem, "Link"));
lnkButton.Text = @"
";
lnkButton.PostBackUrl = strVals;
}
///
/// Substring the text upto 60 characters
///

///
///
public string RetComments(string strCompanyName)
{
string sComments = string.Empty;
if (strCompanyName.Length > 50)
{
sComments = strCompanyName.Substring(0, 50).Trim() + "...";
}
else if (strCompanyName.Length == 0)
{
sComments = "--";
}
else
{
sComments = strCompanyName;
}
return sComments;
}

4. Create the CSS page News.css.

.HomeNewsTitle,.HomeNewsSubTitle,.HomeNewsLink,.HomeSeperator,.HomeNewsTitle2,.HomeNewsLink1,.HomeNewsLink2{
font-family: Trebuchet MS;
position: relative;
float: left;
left: 0px;
width: 172px;
}
.HomeNewsTitle,.HomeNewsTitle2{
color: #0099cc;
font-size: 13px;
}
.HomeNewsTitle2{
top:4px;
}
.HomeNewsSubTitle{
color: #333333;
font-size: 12px;
line-height:15px;
}
.HomeNewsLink,.HomeNewsLink1,.HomeNewsLink2{
color: #0099cc;
font-size: 11px;
text-decoration:underline;
text-align:right;
padding-bottom:1px;
}
.HomeNewsLink1{
padding-bottom:10px;
}
.HomeNewsLink2{
bottom:5px;
}

5. Add/Place the CSS file in to below folder
C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\LAYOUTS\1033\STYLES
6. you have to call the Default URL of the CSS file path like "/_layouts/1033/styles/News.css";
Now you can able to use embedded CSS classes and datalist in webpart.

I hope this will be useful for sharepoint developers.


Difference between Server.Transfer and Response.Redirect?

What is the difference between Server.Transfer and Response.Redirect?
Response.Redirect involves a roundtrip to the server whereas Server.Transfer conserves server resources by avoiding the roundtrip. It just changes the focus of the webserver to a different page and transfers the page processing to a different page.
Response.Redirect can be used for both .aspx and html pages whereas Server.Transfer can be used only for .aspx pages.
Response.Redirect can be used to redirect a user to an external websites. Server.Transfer can be used only on sites running on the same server. You cannot use Server.Transfer to redirect the user to a page running on a different server.
Response.Redirect changes the url in the browser. So they can be bookmarked. Whereas Server.Transfer retains the original url in the browser. It just replaces the contents of the previous page with the new one.

MVC

MVC
ASP.NET MVC
This is the C# tutorial (Switch to the Visual Basic tutorial)
Stephen Walther builds an entire database-driven ASP.NET MVC application from start to finish. This tutorial is a great introduction for people who are new to the ASP.NET MVC Framework and who want to get a sense of the process of building an ASP.NET MVC application.
Download the code for this tutorial
« Previous Tutorial | Next Tutorial »
Create a Movie Database Application in 15 Minutes with ASP.NET MVC (C#)
The purpose of this tutorial is to give you a sense of "what it is like" to build an ASP.NET MVC application. In this tutorial, I blast through building an entire ASP.NET MVC application from start to finish. I show you how to build a simple database-driven application that illustrates how you can list, create, and edit database records.
To simplify the process of building our application, we'll take advantage of the scaffolding features of Visual Studio 2008. We'll let Visual Studio generate the initial code and content for our controllers, models, and views.
If you have worked with Active Server Pages or ASP.NET, then you should find ASP.NET MVC very familiar. ASP.NET MVC views are very much like the pages in an Active Server Pages application. And, just like a traditional ASP.NET Web Forms application, ASP.NET MVC provides you with full access to the rich set of languages and classes provided by the .NET framework.
My hope is that this tutorial will give you a sense of how the experience of building an ASP.NET MVC application is both similar and different than the experience of building an Active Server Pages or ASP.NET Web Forms application.
Overview of the Movie Database Application
Because our goal is to keep things simple, we'll build a very simple Movie Database application. Our simple Movie Database application will allow us to do three things:
1. List a set of movie database records
2. Create a new movie database record
3. Edit an existing movie database record
Again, because we want to keep things simple, we'll take advantage of the minimum number of features of the ASP.NET MVC framework needed to build our application. For example, we won't be taking advantage of Test-Driven Development.
In order to create our application, we need to complete each of the following steps:
1. Create the ASP.NET MVC Web Application Project
2. Create the database
3. Create the database model
4. Create the ASP.NET MVC controller
5. Create the ASP.NET MVC views
Preliminaries
You'll need either Visual Studio 2008 or Visual Web Developer 2008 Express to build an ASP.NET MVC application. You also need to download the ASP.NET MVC framework.
If you don't own Visual Studio 2008, then you can download a 90 day trial version of Visual Studio 2008 from this website:
http://msdn.microsoft.com/en-us/vs2008/products/cc268305.aspx
Alternatively, you can create ASP.NET MVC applications with Visual Web Developer Express 2008. If you decide to use Visual Web Developer Express then you must have Service Pack 1 installed. You can download Visual Web Developer 2008 Express with Service Pack 1 from this website:
http://www.microsoft.com/downloads/details.aspx?FamilyId=BDB6391C-05CA-4036-9154-6DF4F6DEBD14&displaylang=en
After you install either Visual Studio 2008 or Visual Web Developer 2008, you need to install the ASP.NET MVC framework. You can download the ASP.NET MVC framework from the following website:
http://www.asp.net/mvc/
Instead of downloading the ASP.NET framework and the ASP.NET MVC framework individually, you can take advantage of the Web Platform Installer. The Web Platform Installer is an application that enables you to easily manage the installed applications are your computer:
http://www.microsoft.com/web/gallery/Install.aspx
Creating an ASP.NET MVC Web Application Project
Let's start by creating a new ASP.NET MVC Web Application project in Visual Studio 2008. Select the menu option File, New Project and you will see the New Project dialog box in Figure 1. Select C# as the programming language and select the ASP.NET MVC Web Application project template. Give your project the name MovieApp and click the OK button.

Figure 01: The New Project dialog box (Click to view full-size image)
Make sure that you select .NET Framework 3.5 from the dropdown list at the top of the New Project dialog or the ASP.NET MVC Web Application project template won't appear.
Whenever you create a new MVC Web Application project, Visual Studio prompts you to create a separate unit test project. The dialog in Figure 2 appears. Because we won't be creating tests in this tutorial because of time constraints (and, yes, we should feel a little guilty about this) select the No option and click the OK button.
Visual Web Developer does not support test projects.

Figure 02: The Create Unit Test Project dialog (Click to view full-size image)
An ASP.NET MVC application has a standard set of folders: a Models, Views, and Controllers folder. You can see this standard set of folders in the Solution Explorer window. We'll need to add files to each of the Models, Views, and Controllers folders in order to build our Movie Database application.
When you create a new MVC application with Visual Studio, you get a sample application. Because we want to start from scratch, we need to delete the content for this sample application. You need to delete the following file and the following folder:
• Controllers\HomeController.cs
• Views\Home
Creating the Database
We need to create a database to hold our movie database records. Luckily, Visual Studio includes a free database named SQL Server Express. Follow these steps to create the database:
1. Right-click the App_Data folder in the Solution Explorer window and select the menu option Add, New Item.
2. Select the Data category and select the SQL Server Database template (see Figure 3).
3. Name your new database MoviesDB.mdf and click the Add button.
After you create your database, you can connect to the database by double-clicking the MoviesDB.mdf file located in the App_Data folder. Double-clicking the MoviesDB.mdf file opens the Server Explorer window.
The Server Explorer window is named the Database Explorer window in the case of Visual Web Developer.

Figure 03: Creating a Microsoft SQL Server Database (Click to view full-size image)
Next, we need to create a new database table. From within the Sever Explorer window, right-click the Tables folder and select the menu option Add New Table. Selecting this menu option opens the database table designer. Create the following database columns:
Column Name Data Type Allow Nulls
Id Int False
Title Nvarchar(100) False
Director Nvarchar(100) False
DateReleased DateTime False
The first column, the Id column, has two special properties. First, you need to mark the Id column as the primary key column. After selecting the Id column, click the Set Primary Key button (it is the icon that looks like a key). Second, you need to mark the Id column as an Identity column. In the Column Properties window, scroll down to the Identity Specification section and expand it. Change the Is Identity property to the value Yes. When you are finished, the table should look like Figure 4.

Figure 04: The Movies database table (Click to view full-size image)
The final step is to save the new table. Click the Save button (the icon of the floppy) and give the new table the name Movies.
After you finish creating the table, add some movie records to the table. Right-click the Movies table in the Server Explorer window and select the menu option Show Table Data. Enter a list of your favorite movies (see Figure 5).

Figure 05: Entering movie records (Click to view full-size image)
Creating the Model
We next need to create a set of classes to represent our database. We need to create a database model. We'll take advantage of the Microsoft Entity Framework to generate the classes for our database model automatically.
The ASP.NET MVC framework is not tied to the Microsoft Entity Framework. You can create your database model classes by taking advantage of a variety of Object Relational Mapping (OR/M) tools including LINQ to SQL, Subsonic, and NHibernate.
Follow these steps to launch the Entity Data Model Wizard:
1. Right-click the Models folder in the Solution Explorer window and the select the menu option Add, New Item.
2. Select the Data category and select the ADO.NET Entity Data Model template.
3. Give your data model the name MoviesDBModel.edmx and click the Add button.
After you click the Add button, the Entity Data Model Wizard appears (see Figure 6). Follow these steps to complete the wizard:
1. In the Choose Model Contents step, select the Generate from database option.
2. In the Choose Your Data Connection step, use the MoviesDB.mdf data connection and the name MoviesDBEntities for the connection settings. Click the Next button.
3. In the Choose Your Database Objects step, expand the Tables node, select the Movies table. Enter the namespace MovieApp.Models and click the Finish button.


Figure 06: Generating a database model with the Entity Data Model Wizard (Click to view full-size image)
After you complete the Entity Data Model Wizard, the Entity Data Model Designer opens. The Designer should display the Movies database table (see Figure 7).

Figure 07: The Entity Data Model Designer (Click to view full-size image)
We need to make one change before we continue. The Entity Data Wizard generates a model class named Movies that represents the Movies database table. Because we'll use the Movies class to represent a particular movie, we need to modify the name of the class to be Movie instead of Movies (singular rather than plural).
Double-click the name of the class on the designer surface and change the name of the class from Movies to Movie. After making this change, click the Save button (the icon of the floppy disk) to generate the Movie class.
Creating the ASP.NET MVC Controller
The next step is to create the ASP.NET MVC controller. A controller is responsible for controlling how a user interacts with an ASP.NET MVC application.
Follow these steps:
1. In the Solution Explorer window, right-click the Controllers folder and select the menu option Add, Controller.
2. In the Add Controller dialog, enter the name HomeController and check the checkbox labeled Add action methods for Create, Update, and Details scenarios (see Figure 8).
3. Click the Add button to add the new controller to your project.
After you complete these steps, the controller in Listing 1 is created. Notice that it contains methods named Index, Details, Create, and Edit. In the following sections, we'll add the necessary code to get these methods to work.

Figure 08: Adding a new ASP.NET MVC Controller (Click to view full-size image)
Listing 1 – Controllers\HomeController.cs
using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Mvc;

using System.Web.Mvc.Ajax;

namespace MovieApp.Controllers

{

public class HomeController : Controller

{

//

// GET: /Home/

public ActionResult Index()

{

return View();

}

//

// GET: /Home/Details/5

public ActionResult Details(int id)

{

return View();

}

//

// GET: /Home/Create

public ActionResult Create()

{

return View();

}

//

// POST: /Home/Create

[AcceptVerbs(HttpVerbs.Post)]

public ActionResult Create(FormCollection collection)

{

try

{

// TODO: Add insert logic here

return RedirectToAction("Index");

}

catch

{

return View();

}

}

//

// GET: /Home/Edit/5

public ActionResult Edit(int id)

{

return View();

}

//

// POST: /Home/Edit/5

[AcceptVerbs(HttpVerbs.Post)]

public ActionResult Edit(int id, FormCollection collection)

{

try

{

// TODO: Add update logic here

return RedirectToAction("Index");

}

catch

{

return View();

}

}

}

}
Listing Database Records
The Index() method of the Home controller is the default method for an ASP.NET MVC application. When you run an ASP.NET MVC application, the Index() method is the first controller method that is called.
We'll use the Index() method to display the list of records from the Movies database table. We'll take advantage of the database model classes that we created earlier to retrieve the movie database records with the Index() method.
I've modified the HomeController class in Listing 2 so that it contains a new private field named _db. The MoviesDBEntities class represents our database model and we'll use this class to communicate with our database.
I've also modified the Index() method in Listing 2. The Index() method uses the MoviesDBEntities class to retrieve all of the movie records from the Movies database table. The expression _db.MovieSet.ToList() returns a list of all of the movie records from the Movies database table.
The list of movies is passed to the view. Anything that gets passed to the View() method gets passed to the view as view data.
Listing 2 – Controllers/HomeController.cs (modified Index method)
using System.Linq;

using System.Web.Mvc;

using MovieApp.Models;

namespace MovieApp.Controllers

{

public class HomeController : Controller

{

private MoviesDBEntities _db = new MoviesDBEntities();

public ActionResult Index()

{

return View(_db.MovieSet.ToList());

}

}

}
The Index() method returns a view named Index. We need to create this view to display the list of movie database records. Follow these steps:
You should build your project (select the menu option Build, Build Solution) before opening the Add View dialog or no classes will appear in the View data class dropdown list.
1. Right-click the Index() method in the code editor and select the menu option Add View (see Figure 9).
2. In the Add View dialog, verify that the checkbox labeled Create a strongly-typed view is checked.
3. From the View content dropdown list, select the value List.
4. From the View data class dropdown list, select the value MovieApp.Models.Movie.
5. Click the Add button to create the new view (see Figure 10).
After you complete these steps, a new view named Index.aspx is added to the Views\Home folder. The contents of the Index view are included in Listing 3.

Figure 09: Adding a view from a controller action (Click to view full-size image)

Figure 10: Creating a new view with the Add View dialog (Click to view full-size image)


The Index view displays all of the movie records from the Movies database table within an HTML table. The view contains a foreach loop that iterates through each movie represented by the ViewData.Model property. If you run your application by hitting the F5 key, then you'll see the web page in Figure 11.

Figure 11: The Index view (Click to view full-size image)
Creating New Database Records
The Index view that we created in the previous section includes a link for creating new database records. Let's go ahead and implement the logic and create the view necessary for creating new movie database records.
The Home controller contains two methods named Create(). The first Create() method has no parameters. This overload of the Create() method is used to display the HTML form for creating a new movie database record.
The second Create() method has a FormCollection parameter. This overload of the Create() method is called when the HTML form for creating a new movie is posted to the server. Notice that this second Create() method has an AcceptVerbs attribute that prevents the method from being called unless an HTTP POST operation is performed.
This second Create() method has been modified in the updated HomeController class in Listing 4. The new version of the Create() method accepts a Movie parameter and contains the logic for inserting a new movie into the Movies database table.
Notice the Bind attribute. Because we don't want to update the Movie Id property from HTML form, we need to explicitly exclude this property.
Listing 4 – Controllers\HomeController.cs (modified Create method)
//

// GET: /Home/Create

public ActionResult Create()

{

return View();

}

//

// POST: /Home/Create

[AcceptVerbs(HttpVerbs.Post)]

public ActionResult Create([Bind(Exclude="Id")] Movie movieToCreate)

{

if (!ModelState.IsValid)

return View();

_db.AddToMovieSet(movieToCreate);

_db.SaveChanges();

return RedirectToAction("Index");

}
Visual Studio makes it easy to create the form for creating a new movie database record (see Figure 12). Follow these steps:
1. Right-click the Create() method in the code editor and select the menu option Add View.
2. Verify that the checkbox labeled Create a strongly-typed view is checked.
3. From the View content dropdown list, select the value Create.
4. From the View data class dropdown list, select the value MovieApp.Models.Movie.
5. Click the Add button to create the new view.


Figure 12: Adding the Create view (Click to view full-size image)
Visual Studio generates the view in Listing 5 automatically. This view contains an HTML form that includes fields that correspond to each of the properties of the Movie class.
Listing 5 – Views\Home\Create.aspx
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %>



Create





Create



<%= Html.ValidationSummary("Create was unsuccessful. Please correct the errors and try again.") %>

<% using (Html.BeginForm()) {%>



Fields





<%= Html.TextBox("Id") %>

<%= Html.ValidationMessage("Id", "*") %>







<%= Html.TextBox("Title") %>

<%= Html.ValidationMessage("Title", "*") %>







<%= Html.TextBox("Director") %>

<%= Html.ValidationMessage("Director", "*") %>







<%= Html.TextBox("DateReleased") %>

<%= Html.ValidationMessage("DateReleased", "*") %>











<% } %>



<%=Html.ActionLink("Back to List", "Index") %>




The HTML form generated by the Add View dialog generates an Id form field. Because the Id column is an Identity column, we don't need this form field and you can safely remove it.
After you add the Create view, you can add new Movie records to the database. Run your application by pressing the F5 key and click the Create New link to see the form in Figure 13. If you complete and submit the form, a new movie database record is created.
Notice that you get form validation automatically. If you neglect to enter a release date for a movie, or you enter an invalid release date, then the form is redisplayed and the release date field is highlighted.

Figure 13: Creating a new movie database record (Click to view full-size image)
Editing Existing Database Records
In the previous sections, we discussed how you can list and create new database records. In this final section, we discuss how you can edit existing database records.
First, we need to generate the Edit form. This step is easy since Visual Studio will generate the Edit form for us automatically. Open the HomeController.cs class in the Visual Studio code editor and follow these steps:
1. Right-click the Edit() method in the code editor and select the menu option Add View (see Figure 14).
2. Check the checkbox labeled Create a strongly-typed view.
3. From the View content dropdown list, select the value Edit.
4. From the View data class dropdown list, select the value MovieApp.Models.Movie.
5. Click the Add button to create the new view.
Completing these steps adds a new view named Edit.aspx to the Views\Home folder. This view contains an HTML form for editing a movie record.

Figure 14: Adding the Edit view (Click to view full-size image)
The Edit view contains an HTML form field that corresponds to the Movie Id property. Because you don't want people editing the value of the Id property, you should remove this form field.
Finally, we need to modify the Home controller so that it supports editing a database record. The updated HomeController class is contained in Listing 6.
Listing 6 – Controllers\HomeController.cs (Edit methods)
//

// GET: /Home/Edit/5

public ActionResult Edit(int id)

{

var movieToEdit = (from m in _db.MovieSet

where m.Id == id

select m).First();

return View(movieToEdit);

}

//

// POST: /Home/Edit/5

[AcceptVerbs(HttpVerbs.Post)]

public ActionResult Edit(Movie movieToEdit)

{

var originalMovie = (from m in _db.MovieSet

where m.Id == movieToEdit.Id

select m).First();

if (!ModelState.IsValid)

return View(originalMovie);

_db.ApplyPropertyChanges(originalMovie.EntityKey.EntitySetName, movieToEdit);

_db.SaveChanges();

return RedirectToAction("Index");

}
In Listing 6, I've added additional logic to both overloads of the Edit() method. The first Edit() method returns the movie database record that corresponds to the Id parameter passed to the method. The second overload performs the updates to a movie record in the database.
Notice that you must retrieve the original movie, and then call ApplyPropertyChanges(), to update the existing movie in the database.
Summary
The purpose of this tutorial was to give you a sense of the experience of building an ASP.NET MVC application. I hope that you discovered that building an ASP.NET MVC web application is very similar to the experience of building an Active Server Pages or ASP.NET application.
In this tutorial, we examined only the most basic features of the ASP.NET MVC framework. In future tutorials, we dive deeper into topics such as controllers, controller actions, views, view data, and HTML helpers.

Shadow Fields, Override Virtual Methods

Shadow Fields, Override Virtual Methods
Well, I am going to finish this "nuts and bolts" chapter before I flame out! I promised that I would discuss overriding, so I am going to make good on this promise. In general when you extend a class, you shadow fields with the same name in the base class and override virtual methods with the same name and parameter list in the base class. Overriding makes the base class method invisible. Shadowing a field, only hides the field from view. You can still explicitly touch the hidden shadowed field if you wish. You cannot touch an invisible overridden method. To demonstrate the difference between shadowing and overriding I resort, as usual, to twisted code!
First, you can create a sample base class with a public read only field "toastTime" and a virtual method "MakeToast()":
class Base
{
public readonly int toastTime= 60;
public virtual void MakeToast()
{
System.Console.WriteLine("MakeToastInSeconds: " + toastTime.ToString());
}
}
Declaring the only method virtual explicitly allows a designer to override the MakeToast() method in a subclass. (Contrast this to the approach in Java in which all methods are virtual by default.) This is important, since you are explicitly allowing a subclass to completely rewrite the implementation of the MakeToast() method and in doing so make it totally invisible!
Shadow Fields, Override Methods in the Base Class
Now you can extend or subclass the class Base:
///
/// Summary description for SubClass
///

class SubClass : Base
{
public readonly new int toastTime= 1;
public override void MakeToast()
{
System.Console.WriteLine("MakeToastInMinutes:" + toastTime.ToString());
}
}
Note: You must explicitly tell the compiler that you are overriding the virtual base class method MakeToast() with the key word override and that you are hiding the base field with the key word new. (You cannot override a field in a base class.)
Overriding the method MakeToast makes the base class method with the same name and signature invisible to the caller of the class. This is in contrast to the base class field toastTime. The base class field toastTime is shadowed, but still potentially visible to the caller. You have shadowed a base class field and overridden a base class method.
You can demonstrate the behavior of shadowed fields with the following test code:
SubClass sc= new SubClass();
System.Console.WriteLine(sc.toastTime.ToString()); // --> 1
Base super= (Base)sc;
System.Console.WriteLine(super.toastTime.ToString()); // --> 60
In the above code snippet, the type of the reference variable determines which value of toastTime can be touched with the reference variable. Touching the field with a reference of type SubClass tells the compiler that you want to touch the the toastTime field of class SubClass. Casting the reference variable to the base type, tells the compiler that you want to touch the toastTime field of the type Base. Both fields are potentially visible to the caller. The base class field is shadowed, but still touchable.
You can demonstrate the behavior of an overridden method with the following test code. This code demonstrates that the overridden base class method MakeToast is invisible. You cannot touch the overridden method even if you cast the reference to the base type.
SubClass sc= new SubClass();
sc.MakeToast(); // --> MakeToastInMinutes: 1
Base super= (Base)sc;
super.MakeToast(); // --> MakeToastInMinutes: 1
Despite the cast, only the derived (specialized) class method is visible. If you think about it, this behavior is absolutely essential to polymorphism. Overriding insures that the "proper" implementation of a polymorphic method is called at runtime. You can demonstrate the proper polymorphic behavior with a little sample code. Here is yet another version of the Drawable class, now with a default implementation of DrawYourself.
class Drawable
{
public virtual void DrawYourself()
{
System.Console.WriteLine("Drawable");
}
}
class Square : Drawable
{
public override void DrawYourself()
{
System.Console.WriteLine("Square");
}
}
class Circle : Drawable
{
public override void DrawYourself()
{
System.Console.WriteLine("Circle");
}
}
Here is the sample code that demonstrates that the "proper" implementation is called at runtime.
Drawable draw= new Drawable();
draw.DrawYourself(); //--> Drawable
draw= new Square();
draw.DrawYourself(); //--> Square
draw= new Circle();
draw.DrawYourself(); //--> Circle
Overriding insures that the proper super class implementation is always called at runtime. The magic of polymorphism is secure.
You Can Hide a Method
For completeness sake, I will mention that you can hide a virtual method using the key word new instead of the key word override. Go ahead. Edit the previous code sample and replace the key word override with the key word new.
This is the new behavior that breaks polymorphism:
Drawable draw= new Drawable();
draw.DrawYourself(); //--> Drawable
draw= new Square();
draw.DrawYourself(); //--> Drawable
draw= new Circle();
draw.DrawYourself(); //--> Drawable

STATIC MEMBER …………….

STATIC MEMBER …………….
A C# class can contain both static and non-static members. When we declare a member with the help of the keyword static, it becomes a static member. A static member belongs to the class rather than to the objects of the class. Hence static members are also known as class members and non-static members are known as instance members.

In C#, data fields, member functions, properties and events can be declared either as static or non-static. Remember that indexers in C# can't declared as static.

Static Fields

Static fields can be declared as follows by using the keyword static.

class My Class
{
public static int x;
public static int y = 20;
}

When we declare a static field inside a class, it can be initialized with a value as shown above. All un-initialized static fields automatically get initialized to their default values when the class is loaded first time.
For example


// C#:static & non-static
// Author: rajeshvs@msn.com
using System;
class MyClass
{
public static int x = 20;
public static int y;
public static int z = 25;
public MyClass(int i)
{
x = i;
y = i;
z = i;
}
}
class MyClient
{
public static void Main()
{
Console.WriteLine("{0},{1},{2}",MyClass.x,MyClass.y,MyClass.z);
MyClass mc = new MyClass(25);

Console.WriteLine("{0},{1},{2}",MyClass.x,MyClass.y,MyClass.z);
}
}

The C# provides a special type of constructor known as static constructor to initialize the static data members when the class is loaded at first. Remember that, just like any other static member functions, static constructors can't access non-static data members directly.
The name of a static constructor must be the name of the class and even they don't have any return type. The keyword static is used to differentiate the static constructor from the normal constructors. The static constructor can't take any arguments. That means there is only one form of static constructor, without any arguments. In other way it is not possible to overload a static constructor.

We can't use any access modifiers along with a static constructor.

// C# static constructor
// Author: rajeshvs@msn.com
using System;
class MyClass
{
public static int x;
public static int y;
static MyClass ()
{
x = 100;
Y = 200;
}
}
class MyClient
{
public static void Main()
{
Console.WriteLine("{0},{1},{2}",MyClass.x,MyClass.y);
}
}

Note that static constructor is called when the class is loaded at the first time. However we can't predict the exact time and order of static constructor execution. They are called before an instance of the class is created, before a static member is called and before the static constructor of the derived class is called.
Static Member Functions

Inside a C# class, member functions can also be declared as static. But a static member function can access only other static members. They can access non-static members only through an instance of the class.

We can invoke a static member only through the name of the class. In C#, static members can't invoked through an object of the class as like in C++ or JAVA.

// C#:static & non-static
// Author: rajeshvs@msn.com

using System;
class MyClass
{
private static int x = 20;
private static int y = 40;
public static void Method()
{
Console.WriteLine("{0},{1}",x,y);
}
}
class MyClient
{
public static void Main()
{
MyClass.Method();

}
}

Static Properties

The properties also in C# can be declared as static. The static properties are accessing using the class name. A concrete example is shown below.

// C#:static & non-static
// Author: rajeshvs@msn.com

using System;
class MyClass
{
public static int X
{
get
{
Console.Write("GET");
return 10;
}
set
{
Console.Write("SET");
}
}

}
class MyClient
{
public static void Main()
{
MyClass.X = 20; // calls setter displays SET
int val = MyClass.X;// calls getter displays GET
}
}

Static Indexers
In C# there is no concept of static indexers, even though static properties are there.

Static Members & Inheritance

A derived class can inherit a static member. The example is shown below.

// C#:static
// Author: rajeshvs@msn.com
using System;
class MyBase
{
public static int x = 25;
public static void Method()
{
Console.WriteLine("Base static method");
}

}
class MyClass : MyBase
{
}
class MyClient
{
public static void Main()
{
MyClass.Method(); // Displays 'Base static method'
Console.WriteLine(MyClass.x);// Displays 25
}
}

But a static member in C# can't be marked as override, virtual or abstract. However it is possible to hide a base class static method in a derived class by using the keyword new.
An example is shown below.

// C#:static & non-static
// Author: rajeshvs@msn.com

using System;
class MyBase
{
public static int x = 25;
public static void Method()
{
Console.WriteLine("Base static method");
}

}
class MyClass : MyBase
{
public new static int x = 50;
public new static void Method()
{
Console.WriteLine("Derived static method");
}
}
class MyClient
{
public static void Main()
{
MyClass.Method(); // Displays 'Derived static method'
Console.WriteLine(MyClass.x);// Displays 50
}
}

Finally remember that it is not possible to use this to reference static methods.

>> Static variables inside a class method (not in a class) shared among all instances of the class?
>>Even if you have a bunch of instances of this class, you only will have one copy of your static variable shared by all the instances

any variable marked as a static is considered a variable owned by the class. Even if you have a bunch of instances of this class, you only will have one copy of your static variable shared by all the instances.

This is the main difference with instance variables where each instance of your class have his own variables.

Example, if you have a class like this:

public class SoldCar{
public String model; //instance variable - each soldCar have its model
public int cost; //instance variable - each soldCar have its cost
public static int count; //class variable - all soldCars share this count

public SoldCar(){
count ++;
}

public static void main(String[] args){
SoldCar ferrari = new SoldCar();
ferrari.model = "fiorano";
ferrari .cost = 999999;

SoldCar beetle = new SoldCar();
beetle.model = "new beetle";
beetle.cost = 2222;

System.out.println( ferrari.model + "," + ferrari.count );
System.out.println( beetle.model + "," + beetle.count );
}

}

The output of this program is :
fiorano,2
new beetle,2


You can declare a static local variable in a class, that is, inside a procedure in that class. However, you cannot declare a static local variable in a structure.


We use static class when we have to separate data and behavior that will be independent of any object identity. The data and functions do not change regardless of what happens to the object.
A static class can only contain static members. We cannot create an instance of a static class. Static class is always sealed and they cannot contain instance constructor. Hence we can also say that creating a static class is nearly same as creating a class with only static members and a private constructor (private constructor prevents the class from being instantiated).
The advantage of using the static class is that compiler can check that no instance of the class is accidentally added. The complier will not allow any instance class of a static class. We also cannot inherit a static class since it is sealed. Static class do not have constructor, but can still declare static constructor to set up the initial values.
Static class also makes the implementation simpler and faster since we do not have make and instance of the class to call its method. An example of good use of static class would be a class like math, which does all the mathematic function, or a currency converter class to convert currency class for converting the currency.

STATIC MEMBER C#

STATIC MEMBER C#
C# – Static Members
April 10th, 2006 in C# Language by admin
2


A C# class can contain both static and non-static members. When we declare a member with the help of the keyword static, it becomes a static member. A static member belongs to the class rather than to the objects of the class. Hence static members are also known as class members and non-static members are known as instance members.
In C#, data fields, member functions, properties and events can be declared either as static or non-static. Remember that indexers in C# can't declared as static.
Static Fields
Static fields can be declared as follows by using the keyword static.
class MyClass
{
public static int x;
public static int y = 20;
}

When we declare a static field inside a class, it can be initialized with a value as shown above. All un-initialized static fields automatically get initialized to their default values when the class is loaded first time.
For example

// C#:static & non-static
// Author: rajeshvs@msn.com
using System;
class MyClass
{
public static int x = 20;
public static int y;
public static int z = 25;
public MyClass(int i)
{
x = i;
y = i;
z = i;
}
}
class MyClient
{
public static void Main()
{
Console.WriteLine("{0},{1},{2}",MyClass.x,MyClass.y,MyClass.z);
MyClass mc = new MyClass(25);
Console.WriteLine("{0},{1},{2}",MyClass.x,MyClass.y,MyClass.z);
}
}

The C# provides a special type of constructor known as static constructor to initialize the static data members when the class is loaded at first. Remember that, just like any other static member functions, static constructors can't access non-static data members directly.
The name of a static constructor must be the name of the class and even they don't have any return type. The keyword static is used to differentiate the static constructor from the normal constructors. The static constructor can't take any arguments. That means there is only one form of static constructor, without any arguments. In other way it is not possible to overload a static constructor.
We can't use any access modifiers along with a static constructor.
// C# static constructor
// Author: rajeshvs@msn.com
using System;
class MyClass
{
public static int x;
public static int y;
static MyClass ()
{
x = 100;
Y = 200;
}
}
class MyClient
{
public static void Main()
{
Console.WriteLine("{0},{1},{2}",MyClass.x,MyClass.y);
}
}

Note that static constructor is called when the class is loaded at the first time. However we can't predict the exact time and order of static constructor execution. They are called before an instance of the class is created, before a static member is called and before the static constructor of the derived class is called.
Static Member Functions
Inside a C# class, member functions can also be declared as static. But a static member function can access only other static members. They can access non-static members only through an instance of the class.
We can invoke a static member only through the name of the class. In C#, static members can't invoked through an object of the class as like in C++ or JAVA.
// C#:static & non-static
// Author: rajeshvs@msn.com
using System;
class MyClass
{
private static int x = 20;
private static int y = 40;
public static void Method()
{
Console.WriteLine("{0},{1}",x,y);
}
}
class MyClient
{
public static void Main()
{
MyClass.Method();
}
}

Static Properties
The properties also in C# can be declared as static. The static properties are accessing using the class name. A concrete example is shown below.
// C#:static & non-static
// Author: rajeshvs@msn.com
using System;
class MyClass
{
public static int X
{
get
{
Console.Write("GET");
return 10;
}
set
{
Console.Write("SET");
}
}
}
class MyClient
{
public static void Main()
{
MyClass.X = 20; // calls setter displays SET
int val = MyClass.X;// calls getter displays GET
}
}

Static Indexers
In C# there is no concept of static indexers, even though static properties are there.
Static Members & Inheritance
A derived class can inherit a static member. The example is shown below.
// C#:static
// Author: rajeshvs@msn.com
using System;
class MyBase
{
public static int x = 25;
public static void Method()
{
Console.WriteLine("Base static method");
}
}
class MyClass : MyBase
{
}
class MyClient
{
public static void Main()
{
MyClass.Method(); // Displays 'Base static method'
Console.WriteLine(MyClass.x);// Displays 25
}
}

But a static member in C# can't be marked as override, virtual or abstract. However it is possible to hide a base class static method in a derived class by using the keyword new.
An example is shown below.
// C#:static & non-static
// Author: rajeshvs@msn.com
using System;
class MyBase
{
public static int x = 25;
public static void Method()
{
Console.WriteLine("Base static method");
}
}
class MyClass : MyBase
{
public new static int x = 50;
public new static void Method()
{
Console.WriteLine("Derived static method");
}
}
class MyClient
{
public static void Main()
{
MyClass.Method(); // Displays 'Derived static method'
Console.WriteLine(MyClass.x);// Displays 50
}
}

Finally remember that it is not possible to use this to reference static methods.
The main features of a static class are:
• They only contain static members.
• They cannot be instantiated.
• They are sealed.
• They cannot contain Instance Constructors (C# Programming Guide).
------------------------------------------------------------------------------------------------------------------------

ASP.NET USER CONTROLL AND CUSTOME CONTROLL DEVELOPMENT

IN ASP.NET USER CONTROLL AND CUSTOME CONTROLL DEVELOPMENT

User Controls
The composition of a user control is very simple and requires a smaller skill set than that required by custom control developers
. User controls preserve the use of ASP.NET mark-up coupled with the code behind model (although inline code is an option).
One of the great things about user controls is that they allow a quick conversion from something like an existing ASP.NET page to a user control - and as a result they have many similarities. Some of the similarities include the use of existing server controls that ASP.NET offers, as well as the event model that you are familiar with as ASP.NET developers. User controls provide a quick and easy way to introduce modularity into an ASP.NET web application.
User controls - unlike ASP.NET pages that have the file extension .aspx - have the extension .ascx. User controls files cannot be requested via a browser; they can only be used via the containing ASP.NET page. Web servers like IIS and Cassini prohibit browsing to files with the .ascx file extension.
Like ASP.NET pages - in the context of a file based web site - compilation of a user control is done upon first request.
So why after this glowing review should we even care about custom control development in ASP.NET? Custom controls allow us a more atomic control on authoring, as well as the ability to ship our controls as a dynamic link library (.dll) which can be pre-compiled as well as integrating nicely with the Visual Studio IDE.
If you are building controls specifically for a certain web application, then user controls will probably be all you need. However, if your desire is to build redistributable controls that integrate well with the Visual Studio IDE, then custom controls are the best choice.
User Control example
Even if the main purpose of this article is covering custom controls, I would like to start with a walkthrough about the creation of a simple user control.
In the following example, I have identified a component that will appear many times within my hypothetical web site. The user control that we will create simply consists of a GridView and a SqlDataSource that queries for all the ContactName's and CompanyName's from the Northwind Customers table.
When creating user controls I like to create a new folder within my web site entitled... yes you guessed it, UserControls; and drop all my user controls into that folder. However, this isn't a requirement.
Step 1: Adding a user control to the web site
Adding a user control to your solution is real simple. You just have to right click your solution and click Add New Item; then from the dialog window click Web User Control and name the control MyUserControl.ascx.
Figure 1: Adding a Web User Control

Step 2: Adding the ASP.NET controls to MyUserControl.ascx
As mentioned earlier this user control will merely consist of a GridView and a SqlDataSource ASP.NET server controls.
Before we go ahead and add our controls to the user control, notice that the Page directive is not used for our user control, and that it has been replaced with the Control directive.
Listing 1: Control directive
view sourceprint?
1.<%@ Control Language="C#"
2. AutoEventWireup="true" CodeFile="MyUserControl.ascx.cs"
3. Inherits="UserControls_MyUserControl" %>
As well as the Control directive also note that our code behind derives from the System.Web.UI.UserControl class and not from System.Web.UI.Page.
Listing 2: Deriving from the UserControl class
view sourceprint?
1.public partial class UserControls_MyUserControl : System.Web.UI.UserControl
There is only one similarity between the System.Web.UI.UserControl and System.Web.UI.Page types: they both derive from TemplateControl.
Let's go ahead and add the required server controls to our user control.
Listing 3: Adding a GridView and SqlDataSource server control to our user control
view sourceprint?
Listing 1-1 shows the final version of MyUserControl.ascx.
Step 3: Adding our user control to a Web Form
There are a few ways in which we can do this. We can either use the Register directive, or we can go ahead and register our user control in the web.config.
Using the Register directive is really simple and allows all web forms with the appropriate Register directive to go ahead and use our user control. Setting up the Register directive is easy. We need to provide a TagPrefix, TagName and Src for the user control – all of which are attributes of the Register directive.
Listing 4: Setting up the Register directive
view sourceprint?
1.<%@ Register TagPrefix="gb" TagName="Customers"
2. src="~/UserControls/MyUserControl.ascx" %>
As well as using the Register directive, as of ASP.NET 2.0, we can go ahead and register our user control within the controls element of the pages element.
Listing 5: Registering our use control in the web.config
view sourceprint?
When registering our user control in the web.config file, all pages within the web site can now use the user control omitting the Register directive.
Step 4: Using our simple user control within a Web Form
This is really simple. Either setup the Register directive on your Web Form or register your user control within the web.config as shown in step 3. With that done, you will be able to use your control as shown in the following listing.
Listing 6: Using our user control within a Web Form
view sourceprint?

There are a few things to remember about user controls. The first is that you shouldn't include a server form element, which is a form control with the runat="server" attribute. However, you can use a standard form element. Also, you should not include any HTML elements that are already contained in the Web Form, like body, head and so on. If you require either, a MasterPage might be better suited for your needs.
Figure 2: Our simple user control in action

Custom Controls
The power of custom controls is staggering. You can create highly complex controls and then bundle them up and ship them as compiled managed .dlls. As I mentioned before, custom controls can provide a richer interface between the developer and the control, via the Visual Studio IDE. This is achieved using attributes to decorate various parts of a custom controls internals.
When creating a custom control, we derive our control class from one of two base types:
• System.Web.UI.Control
• System.Web.UI.WebControl
Control
Deriving from the Control class allows our control to take advantage of the rendering methods provided by the Control class, as well as the use of ViewState.
WebControl
The WebControl class derives from the Control class. However, if we derive our custom control from WebControl, we get free support for many visual aspects of our control, like font size, CSS classes, background colour and so on.
Which class should I derive from?
When you are creating a custom control that requires little or no UI, then you should derive from the Control class. If your control does require the need for extensive UI support, then you should derive from WebControl.
Creating a simple custom control
In this first part of the series we will create a trivial Label-like control that simply allows the user to define the text of a server control. This control will derive from the Control class.
Step 1: Creating a new Web Control Library project
Right click on your web site solution and click on the Add New Project. From the dialog window, choose the Web Control Library project template. You can name this project whatever you want.
Figure 3: Creating a new Web Control Library project

Step 2: Deriving from the Control class
Go ahead and add a new class to your Web Control Library called SimpleLabel, and derive SimpleLabel from the System.Web.UI.Control class.
Listing 7: Deriving from Control
view sourceprint?
01.using System;
02.using System.Web.UI;
03.
04.namespace Org.GBarnett.Dns.WebControls
05.{
06. public class SimpleLabel : Control
07. {
08. }
09.}
Step 3: Adding some functionality to our control
In this step we will override the Render method defined in the Control class, and also add a Text property to the class so that our user can define the text of our label.
First, we will add the Text property to our class and store the value in ViewState so the control can maintain state over post back.
Note: ViewState will be described in detail in the next part of this series.
Listing 8: Text property
view sourceprint?
01.public string Text
02.{
03. get
04. {
05. string s = ViewState["Text"] as string;
06. return (s == null) ? string.Empty : s;
07. }
08. set
09. {
10. ViewState["Text"] = value;
11. }
12.}
Now we will go ahead and override the Render method of our control.
Listing 9: Overriding the Render method
view sourceprint?
1.protected override void Render(HtmlTextWriter writer)
2.{
3. writer.RenderBeginTag(HtmlTextWriterTag.Span);
4. writer.Write(Text);
5. writer.RenderEndTag();
6.}
In the previous listing, we start off by writing an opening tag, then writing out the user defined text and then finally closing that opening tag.
Note: We will discuss the control lifecycle in the next part along with rendering.
Listing 10: Our final control
view sourceprint?
01.using System;
02.using System.Web.UI;
03.
04.namespace Org.GBarnett.Dns.WebControls
05.{
06. public class SimpleLabel : Control
07. {
08.
09. public string Text
10. {
11. get
12. {
13. string s = ViewState["Text"] as string;
14. return (s == null) ? string.Empty : s;
15. }
16. set
17. {
18. ViewState["Text"] = value;
19. }
20. }
21.
22. protected override void Render(HtmlTextWriter writer)
23. {
24. writer.RenderBeginTag(HtmlTextWriterTag.Span);
25. writer.Write(Text);
26. writer.RenderEndTag();
27. }
28. }
29.}
Please go ahead now and build the project.
Step 4: Using the SimpleLabel custom control within an ASP.NET project
You have two choices here: Either install the resulting .dll into the global assembly cache (GAC) or drop the .dll into the bin folder of your web application. We will do the latter.
Right click on your web site solution and click Add Reference, a dialog window will appear. Click on the Browse tab and then browse to the resulting .dll created from the web control library project.
Figure 4: Referencing our web control library project

With the .dll reference you can either use the Control directive to register your custom controls, or you can use the web.config file to do so. I will use the web.config to register my control. If you want to use the Control directive please check the beginning of this article.
Listing 11: Registering the web control library
view sourceprint?
1.
2.
3. 4. namespace="Org.GBarnett.Dns.WebControls"/>
5.

6.

With our control library registered we can now go ahead and use it!
Listing 12: Using our control within a Web Form
view sourceprint?
Figure 5: Our custom control in all of its glory

If you view the source of the resulting HTML then you will see that Granville is a child of the element, which is how we defined our control in the Render method.






Adding custom control to toolbox.
Step 1 – Switch over to the web project in which you want to use the control.
Step 2 – In toolbox add your own tab or click on general tab.
Step 3 – Right click in the selected tab area and click Chose Items.

Step 4 – This will open Choose Toolbox Item screen. Click on Browse button and specify the path of dll you created in your myControlLib project.


Step 5 – Click Ok and you’re done. Your Custom control will be added to the toolbox as shown below.


















Difference between User Control and custom control:

User control
1) Reusability web page
2) We can’t add to toolbox
3) Just drag and drop from solution explorer to page (aspx)
4) U can register user control to. Aspx page by Register tag
5) A separate copy of the control is required in each application
6) Good for static layout
7) Easier to create
8)Not complied into DLL
9) Here page (user page) can be converted as control then
We can use as control in aspx

Custom controls
1) Reusability of control (or extend functionalities of existing control)
2) We can add toolbox
3) Just drag and drop from toolbox
4) U can register user control to. Aspx page by Register tag
5) A single copy of the control is required in each application
6) Good for dynamics layout
7) Hard to create
8) Compiled in to dll

VIEW STATE-C#

VIEW STATE-C#
ViewState is the mechanism that allows state values to be preserved across page postbacks.
Because of the stateless nature of web pages, regular page member variables will not maintain their values across postbacks. When we need a page variable to maintain its value across page post backs, we can use ViewState to store that value. Values stored in ViewState will be serialized and sent to the client browser as the value of a hidden form input. When you view the page source (in your browser) of a page the uses ViewState, you may see this hidden viewstate input which will look something like this:

This single hidden field contains all the viewstate values for all the page controls. This is an important aspect of viewstate that you need to consider.
Because viewstate is (by default) sent to the client browser and then returned to the server in the form of a hidden input control on your page, storing a significant amount of data in viewstate can increase your page size and can affect your page performance.
To disable ViewState for a control, you can set the EnableViewState property to false. When ViewState is disabled for any control, it will also automatically be disabled for all child controls of that control.
Example:

This does not mean that you should avoid viewstate. You should however, always be aware of what you are storing there and how it affects your overall page size.
Some people hate ViewState, others love it. Either way, you have control over your ViewState, so take control!
Example
One simple way to store small values in viewstate is to use a property instead of a member variable. This property can use viewstate to store its value rather than a member variable that would lose the value over a postback. For example, storing an Integer in viewstate can be accomplished like this:
VB
Public Property SomeInteger() As Integer
Get
Dim o As Object = ViewState("SomeInteger")
If Not o Is Nothing Then Return DirectCast(o, Integer)
Return 0 'a default
End Get
Set(ByVal value As Integer)
ViewState("SomeInteger") = value
End Set
End Property
C#
public int SomeInteger {
get {
object o = ViewState["SomeInteger"];
if (o != null) return (int)o;
return 0;
//a default
}
set { ViewState["SomeInteger"] = value; }
}

This step-by-step article describes how to control the caching of Web pages and data objects in ASP.NET. When you cache Web pages, you avoid re-creating information when you make a later request. Caching is an important technique for building high performance and scalable server applications. When you make the first request for the page, you can store data objects, pages, or part of the page to the memory. You can store these items on a Web server, on a proxy server, or on the browser.



Back to the top
MORE INFORMATION
ASP.NET provides easier methods to control caching. You can use the @ OutputCache directive to control page output caching in ASP.NET. Use the HttpCachePolicy class to store arbitrary objects, such as datasets, to server memory. You can store the cache in applications such as the client browser, the proxy server, and Microsoft Internet Information Services (IIS). By using the Cache-Control HTTP Header, you can control caching.

For more information about ASP.NET output caching, click the following article number to view the article in the Microsoft Knowledge Base:
308375 How to control page output caching in ASP.NET by using Visual C# .NET


Back to the top
Cache ASP.NET pages

You can use the @ OutputCache directive to cache, or you can cache programmatically through code by using Visual Basic .NET or Visual C# .NET. The @ OutputCache directive contains a Location attribute. This attribute determines the location for cached item. You can specify the following locations:
• Any - This stores the output cache in the client's browser, on the proxy server (or any other server) that participates in the request, or on the server where the request is processed. By default, Any is selected.
• Client - This stores output cache in the client's browser.
• Downstream - This stores the output cache in any cache-capable devices (other than the origin server) that participate in the request.
• Server - This stores the output cache on the Web server.
• None - This turns off the output cache.

The following are code samples for the @ OutputCache directive and equivalent programmatic code.
• To store the output cache for a specified duration

Declarative Approach:
<%@ OutputCache Duration="60" VaryByParam="None" %>

Programmatic Approach:
Response.Cache.SetExpires(DateTime.Now.AddSeconds(60));
Response.Cache.SetCacheability(HttpCacheability.Public);
• To store the output cache on the browser client where the request originated

Declarative Approach:
<%@ OutputCache Duration="60" Location="Client" VaryByParam="None" %>

Programmatic Approach:
Response.Cache.SetExpires(DateTime.Now.AddSeconds(60));
Response.Cache.SetCacheability(HttpCacheability.Private);
• To store the output cache on any HTTP 1.1 cache-capable devices including the proxy servers and the client that made request

Declarative Approach:
<%@ OutputCache Duration="60" Location="Downstream" VaryByParam="None" %>

Programmatic Approach:
Response.Cache.SetExpires(DateTime.Now.AddSeconds(60));
Response.Cache.SetCacheability(HttpCacheability.Public);
Response.Cache.SetNoServerCaching();
• To store the output cache on the Web server

Declarative Approach:
<%@ OutputCache Duration="60" Location="Server" VaryByParam="None" %>

Programmatic Approach:
TimeSpan freshness = new TimeSpan(0,0,0,60);
DateTime now = DateTime.Now;
Response.Cache.SetExpires(now.Add(freshness));
Response.Cache.SetMaxAge(freshness);
Response.Cache.SetCacheability(HttpCacheability.Server);
Response.Cache.SetValidUntilExpires(true);
• To cache the output for each HTTP request that arrives with a different City:

Declarative Approach:
<%@ OutputCache duration="60" varybyparam="City" %>

Programmatic Approach:
Response.Cache.SetExpires(DateTime.Now.AddSeconds(60));
Response.Cache.SetCacheability(HttpCacheability.Public);
Response.Cache.VaryByParams["City"] = true;
For the VaryByCustom attribute, the VaryByHeader attribute, and the VaryByParam attribute in the @ OutputCache directive, the HttpCachePolicy class provides the VaryByHeaders property and the VaryByParams property, and the SetVaryByCustom method.


Back to the top
Turn off client and proxy caching
To turn off the output cache for an ASP.NET Web page at the client location and at the proxy location, set the Location attribute value to none, and then set the VaryByParam value to none in the @ OutputCache directive. Use the following code samples to turn off client and proxy caching.
• Declarative Approach:
<%@ OutputCache Location="None" VaryByParam="None" %>
• Programmatic Approach:
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Back to the top
Cache arbitrary objects in server memory
ASP.NET includes a powerful, easy-to-use caching mechanism that you can use to store objects that require a lot of server resources to create in memory. The Cache class implements this method. Instances are private to each application and the lifetime is tied to the corresponding application. To cache the arbitrary objects in ASP.Net by using the Cache class, follow these steps:
1. Create a new ASP.NET Web Application by using Visual C# .NET.
2. By default, WebForm1.aspx is created.
3. In HTML view of WebForm1.aspx, replace the existing code with the following sample code:
4. <%@ Import Namespace="System.Data" %>
5. <%@ Import Namespace="System.Data.SqlClient" %>
6.
7. Note Replace the values for ServerName, UID, and PWD in the sample code for the SqlConnection object with your SQL Server Name, User ID, and Password.
68. On the Debug menu, click Start to run the application.

Note When you restart the application, the Cached object is re-created.
Introduction
Before I start this article, let me ask you something. Is it possible to access the ViewState variable of one page on another page? I don't know what your answer is. Well, frankly speaking, my answer was also "NO" before writing this article as it is said that ViewState is page specific.
Background
ViewState is a very misunderstood animal. It is said that ViewState is Page specific; that means, it is available only on the same page on which it was created. Once you redirect to another page, the previous page's viewstate is no longer accessible. But that is not true.
Using the Code
Yes, we can access the viewstate variables across pages. This is only possible if Cross Page Posting or Server.transfer is used to redirect the user to other page. If Response.redirect is used, then ViewState cannot be accessed across pages.
Before you continue reading this article, please read these articles on Cross Page Posting and Server.transfer.
Ok, so all set now... I will demonstrate this using the demo created by me. You can download the demo from the link at the top of this article.
I have created two *.aspx pages named:
1. ViewStateContainer.aspx: This page sets the ViewState variable and transfers the user to another page using Server.transfer.
2. AccessViewState.aspx: This page accesses the ViewState variable of ViewStateContainer.aspx page.
This is the code of ViewStateContainer.aspx page:
Collapse Copy Code
public partial class ViewStateContainer : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
ViewState["Page1"] = "Page1 ViewState";
Server.Transfer("AccessViewState.aspx");
}

public StateBag ReturnViewState()
{
return ViewState;
}
}
As you can see, I have set a ViewState variable in Page Load and transfer the user to AccessViewState.aspx page using the Server.transfer() method.
This page also contains a method ReturnViewState() which actually returns the ViewState of this page to the calling function. The return type of the method is StateBag class.
StateBag class: This class is the primary storage mechanism for all HTML and Web server controls. It stores attribute/value pairs as strings associated with the control. It tracks changes to these attributes only after the OnInit method is executed for a page request, and saves the changes to the page's or control's viewstate.
Now let's take look at AccessViewState.aspx Page code:
Collapse Copy Code
public partial class AccessViewState : System.Web.UI.Page
{
private StateBag PreviousPageViewState
{
get
{
StateBag returnValue = null;
if (PreviousPage != null)
{
Object objPreviousPage = (Object)PreviousPage;
MethodInfo objMethod = objPreviousPage.GetType().GetMethod
("ReturnViewState");
return (StateBag)objMethod.Invoke(objPreviousPage, null);
}
return returnValue;
}
}

protected void Page_Load(object sender, EventArgs e)
{
if (PreviousPage != null)
{
if (PreviousPageViewState != null)
{
Label1.Text = PreviousPageViewState["Page1"].ToString();
}
}
}
}
Whenever we use Server.transfer or Cross Page Posting, We can get the previous page object via PreviousPage property. Using Previous Page, we can find the controls of the previous page. For example, one can access Label control placed in ViewStateContainer Page in current Page.
Looking at the code, I have created a PreviousPageViewState property in this page, which returns the previous page's ViewState. It first checks whether PreviousPage is null or not, if it's not null, then it creates an object of the previous page. Now using Reflection, we can invoke the method of the previous class. Using MethodInfo class, I have invoked the ReturnViewState() method of ViewStateContainer Page.
In Page_Load event, I am able to access the ViewState variable of ViewStateContainer Page. You can access all the viewstate variables set in ViewStateContainer Page.
Enjoy.

Sealed Classes

What Is Sealed Class ?
Sealed classes are used to restrict the inheritance feature of object oriented programming. Once a class is defined as sealed class, this class cannot be inherited.
In C#, the sealed modifier is used to define a class as sealed. In Visual Basic .NET, NotInheritable keyword serves the purpose of sealed. If a class is derived from a sealed class, compiler throws an error.

If you have ever noticed, structs are sealed. You cannot derive a class from a struct.
The following class definition defines a sealed class in C#:

// Sealed class
sealed class SealedClass
{

}

In the following code, I create a sealed class SealedClass and use it from Class1. If you run this code, it will work fine. But if you try to derive a class from sealed class, you will get an error.

using System;
class Class1
{
static void Main(string[] args)
{
SealedClass sealedCls = new SealedClass();
int total = sealedCls.Add(4, 5);
Console.WriteLine("Total = " + total.ToString());
}
}
// Sealed class
sealed class SealedClass
{
public int Add(int x, int y)
{
return x + y;
}
}



Why Sealed Classes?
We just saw how to create and use a sealed class. The main purpose of a sealed class to take away the inheritance feature from the user so they cannot derive a class from a sealed class. One of the best usage of sealed classes is when you have a class with static members. For example, the Pens and Brushes classes of the System.Drawing namespace.
The Pens class represent the pens for standard colors. This class has only static members. For example, Pens.Blue represents a pen with blue color. Similarly, the Brushes class represents standard brushes. The Brushes.Blue represents a brush with blue color.
So when you're designing your application, you may keep in mind that you have sealed classes to seal user's boundaries.
In the next article of this series, I will discuss some usage of abstract classes.

Note: At the time of writing this article, C# language did not have static classes. Now C# has static classes.

Working with ASP.NET Master Pages

Working with ASP.NET Master Pages Programmatically
You can perform a number of common tasks programmatically with master pages, including the following:
• Accessing members that are defined on the master page, which can consist of public properties and methods or controls.
• Attaching master pages to a content page dynamically.
Accessing Members on the Master Page
To provide access to members of the master page, the Page class exposes a Master property. To access members of a specific master page from a content page, you can create a strongly typed reference to the master page by creating a @ MasterType directive. The directive allows you to point to a specific master page. When the page creates its Master property, the property is typed to the referenced master page.
For example, you might have a master page named MasterPage.master that is the class name MasterPage_master. You might create @ Page and @ MasterType directives that look like the following:
<%@ Page masterPageFile="~/MasterPage.master"%>
<%@ MasterType virtualPath="~/MasterPage.master"%>
When you use a @ MasterType directive, such as the one in the example, you can reference members on the master page as in the following example:
VB
C#
C++
F#
JScript
Copy
CompanyName.Text = Master.CompanyName;
The Master property of the page is already typed to MasterPage_master.
Getting the Values of Controls on the Master Page
At run time, the master page is merged with the content page, so the controls on the master page are accessible to content page code. (If the master page contains controls in a ContentPlaceHolder control, those controls are not accessible if overridden by a Content control from the content page.) The controls are not directly accessible as master-page members because they are protected. However, you can use the FindControl method to locate specific controls on the master page. If the control that you want to access is inside a ContentPlaceHolder control on the master page, you must first get a reference to the ContentPlaceHolder control, and then call its FindControl method to get a reference to the control.
The following example shows how you can get a reference to controls on the master page. One of the controls being referenced is in a ContentPlaceHolder control and the other is not.
VB
C#
C++
F#
JScript
Copy
// Gets a reference to a TextBox control inside a ContentPlaceHolder
ContentPlaceHolder mpContentPlaceHolder;
TextBox mpTextBox;
mpContentPlaceHolder =
(ContentPlaceHolder)Master.FindControl("ContentPlaceHolder1");
if(mpContentPlaceHolder != null)
{
mpTextBox = (TextBox) mpContentPlaceHolder.FindControl("TextBox1");
if(mpTextBox != null)
{
mpTextBox.Text = "TextBox found!";
}
}

// Gets a reference to a Label control that is not in a
// ContentPlaceHolder control
Label mpLabel = (Label) Master.FindControl("masterPageLabel");
if(mpLabel != null)
{
Label1.Text = "Master page label = " + mpLabel.Text;
}

You can access the contents of the master page's ContentPlaceHolder controls by using the FindControl method, as shown above. If the ContentPlaceHolder control has been merged with content from a Content control, the ContentPlaceHolder control will not contain its default content. Instead, it will contain the text and controls that are defined in the content page.
Attaching Master Pages Dynamically
In addition to specifying a master page declaratively (in the @ Page directive or in the configuration file), you can attach a master page dynamically to a content page. Because the master page and content page are merged during the initialization stage of page processing, a master page must be assigned before then. Typically, you assign a master page dynamically during the PreInit stage, as in the following example:
VB
C#
C++
F#
JScript
Copy
void Page_PreInit(Object sender, EventArgs e)
{
this.MasterPageFile = "~/NewMaster.master";
}
Strong Typing for Dynamic Master Pages
If the content page assigns a strong type to the master page by using a @ MasterType directive, the type must apply to any master page that you assign dynamically. If you intend to select a master page dynamically, it is recommended that you create a base class from which your master pages derive. The base master-page class can then define the properties and methods that the master pages have in common. In the content page, when you assign a strong type to the master page by using a @ MasterType directive, you can assign it to the base class instead of to an individual master page.
The following examples show how to create a base master-page type that can be used by multiple master pages. The examples consist of a base type that is derived from the MasterPage control, two master pages that inherit from the base type, and a content page that allows users to select a master page dynamically by using a query string (?color=green). The base master type defines a property named MyTitle. One of the master pages overrides the MyTitle property, and the other one does not. The content page displays the MyTitle property as the page's title. The title of the page will therefore vary depending on which master page has been selected.
This is the base master-page type. It belongs in the App_Code directory.
VB
C#
C++
F#
JScript
Copy
using System;
using System.Data;
using System.Configuration;
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 class BaseMaster : System.Web.UI.MasterPage
{
public virtual String MyTitle
{
get { return "BaseMaster Title"; }
}
}
This is the first master page, which displays a blue background. Notice that the Inherits attribute in the @ Master directive references the base type.
VB
C#
C++
F#
JScript
Copy
<%@ Master Language="C#" Inherits="BaseMaster"
ClassName="MasterBlue" %>
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">


This is the second master page. It is the same as the first master page, except that it displays a green background, and it overrides the MyTitle property that is defined in the base type.
VB
C#
C++
F#
JScript
Copy
<%@ Master Language="C#" Inherits="BaseMaster"
ClassName="MasterGreen" %>
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">



This is the content page, which allows users to select a master page based on a query string provided with the request. The @ MasterType directive, which assigns a strong type to the page's Master property, references the base type.
VB
C#
C++
F#
JScript
Copy
<%@ Page Language="C#" Title="Content Page" MasterPageFile="~/MasterBlue.master"%>
<%@ MasterType TypeName="BaseMaster" %>


Runat="Server">
Content from Content page.