Archive

Archive for December, 2006

Custom Paging Solution

December 31, 2006 Leave a comment

ALTER PROCEDURE [dbo].[tbh_Articles_GetPublishedArticles]

(

@CurrentDate

datetime,

@PageIndex

int,

@PageSize

int

)

AS

SET

NOCOUNT ON

SELECT * FROM

(

SELECT tbh_Articles.ArticleID, tbh_Articles.AddedDate, tbh_Articles.AddedBy, tbh_Articles.CategoryID, tbh_Articles.Title, tbh_Articles.Abstract, tbh_Articles.Body,

tbh_Articles

.Country, tbh_Articles.State, tbh_Articles.City, tbh_Articles.ReleaseDate, tbh_Articles.ExpireDate, tbh_Articles.Approved,

tbh_Articles

.Listed, tbh_Articles.CommentsEnabled, tbh_Articles.OnlyForMembers, tbh_Articles.ViewCount, tbh_Articles.Votes, tbh_Articles.TotalRating,

tbh_Categories

.Title AS CategoryTitle,

ROW_NUMBER

() OVER (ORDER BY ReleaseDate DESC) AS RowNum

FROM tbh_Articles INNER JOIN

tbh_Categories

ON tbh_Articles.CategoryID = tbh_Categories.CategoryID

WHERE Approved = 1 AND Listed = 1 AND

ReleaseDate

<= @CurrentDate AND ExpireDate > @CurrentDate

)

Articles

WHERE Articles.RowNum BETWEEN (@PageIndex*@PageSize+1) AND ((@PageIndex+1)*@PageSize)

ORDER BY ReleaseDate DESC

Categories: .NET

Integrating Customized Roles, Membership

December 30, 2006 Leave a comment
There is a lot of material on ASP.NET 2.0 Membership Provider, some about Roles, and even less on Profile providers. My goal in this short piece is to provide an example of how to pull them all together. We’ll use the Membership Provider for authentication, a Role provider for Authorization, and we’ll add a custom Profile example to show how custom user Profile data can be stored on a per-user basis, even for anonymous users, and then automatically migrated to their full User profile when they "sign up" on the site.

To do this, I’ll use a previously "fleshed out" framework from this article, "Dynamic Display of Uploaded Content in Master Pages" as the basis for the "pseudo site". You can set this up with any SQL Server database you want, including either a new or existing one. Plus, I’ll include a SQL Script that will show you how to install Membership, Role and Profile required database information on a hosted site, and even an ASP.NET "SetUpSite.Aspx" page that does it programmatically. Finally, I’ll include some nice "Admin" pages, courtesy of Peter Kellner, to allow Administrators to work with users and roles online, and point you to some additional resources that have become available.

 

In short, you’ll have some basic example code and controls to do just about anything you would expect to need to perform in ASP.NET 2.0 for a site, using all three providers – Membership, Role, and Profile. So, let’s get started.

The first thing we want to do before we even open the sample solution is to enable our database for the providers. There are actually three separate ways you can do this:

1) Run ASPNET_REGSQL and follow the prompts. Of course, this requires that you have command-prompt access to the machine on which your site will be deployed.

2) Run ASP.NET_REGSQL on your own sample database locally, and EXPORT all the sql script necessary to create the tables, views and stored procedures on a remote site. Again, this assumes you have the ability to access a remote hosted site’s SQL Server online and execute a rather large SQL Script on it. A sample script is included in the "SQL" Folder in the download.

3) Do it programmatically: Make a "Setup.aspx" page that uses the System.Web.Management utility method:

Management.SqlServices.Install("server", "USERNAME", "PASSWORD", "databasename", SqlFeatures.All)

This does everything that ASPNET_REGSQL does. You’d think they would make it more obvious that you can do this, given the large number of sites that are hosted by commercial shared hosting companies, but no, they decided to push ASPNET_REGSQL as if everybody everywhere automatically has access to it. Go figure. There is a sample page "SetUpASPNetDatabase.aspx" in the sample solution where you can simply fill in the above parameters in a form, and press a button to set up your database.

So, now we have our database (either SQL Server 2000 / MSDE or SQL Server 2005 / SQLExpress) set up for Membership, Roles and Profiles. The rest is just figuring out what code and what controls to use to make everything work. Fortunately, ASP.NET 2.0 provides a group of controls that handle most of these tasks out of the box and can also be highly customized beyond their default behaviors.

The easiest way to review this process is to go through it in stages with the sample application open in Visual Studio.NET 2005. So, unzip the sample into your favorite folder, and double-click on the "ArticleMaster.sln" solution file to bring it all up. This is configured as a File-based Web Site solution, so no IIS settings are required.

The sample database for this exercise is "Articles" so go ahead and create a new database of that name now, and then run the "TablesSprocAndData.sql" Sql script in the "SQL" subfolder against it. This creates the table and stored procs that were used in the original article referenced above, so that we don’t need to "reinvent the wheel". Next, if you haven’t set up your new database for Membership, Roles and Profiles, you can either execute the stock "ASPNETREGSQLFULL.sql" script that I have prepared as in "2" above, or you can "View In Browser" on the SetupASPNETDatabase.aspx page in the solution to see how the option "3" works. Fill in Server, Username, password and database names, and press the "Set Up Database" button, and the SqlServices.Install Method will be run. Finally, make sure the connection strings in the web.config actually work for your specific environment, otherwise you won’t get very far.

At this point, all your infrastructure for the sample is set up, and we are ready to look at some code. If you look at the Default.aspx page, it has a Repeater as in the original article, to display content, and sports a LoginStatus control pointing to "~/Login.aspx" as its login/ logout page action. Now let’s move to the Login.aspx page.

You can see that Login.aspx has only a Login Control. The property settings on this control are where we can take advantage of our Membership Provider automatically. In this case, our MembershipProvider is set to "DefaultMembershipProvider", and whatever we have in our web.config for that takes over. In my codebehind for this control, I have only the following:

 protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
    {
        string userName = Login1.UserName.ToString();
        string password = Login1.Password.ToString();
        if (Membership.ValidateUser(userName, password))
        {
            if (Request.QueryString["ReturnUrl"] != null)
            {           
                FormsAuthentication.RedirectFromLoginPage(userName,true);
            }
            else
            {
                FormsAuthentication.SetAuthCookie(userName, true);
                Response.Redirect("~/Default.aspx");
            }
        }
        else
        {
         lblResults.Visible = true;
       lblResults.Text = "Unsuccessful login. Please re-enter your information and try again.";
         if ((Membership.GetUser(userName) != null) && 
(Membership.GetUser(userName).IsLockedOut == true)) lblResults.Text += " Your account has been locked out."; } }

So, I am using the Login Control to use the Membership Provider’s "ValidateUser" method, with Forms Authentication, which is already set up in the web.config.

Obviously, if you aren’t a "member" yet, you’ll want to click the "Create Account" link on the Login Control, and this will take you to the "Admin.aspx" page, where we have a CreateUserWizard, a ChangePassword, and a PasswordRecovery control. All the settings on these are highly configurable; in most cases you will not need to write any code to use them. In my CreateUserWizard Control, I am using the following codebehind:

 protected void CreateUserWizard1_CreatedUser(object sender, EventArgs e)
	{
		if(!Roles.RoleExists("user")) Roles.CreateRole("user");
		string username = this.CreateUserWizard1.UserName;
		Roles.AddUserToRole(username, "user");		
	}    

If the User Role doesn’t exist yet (first time the app is ever used) we create one, and then we Add this user to the "user" role. Done! The rest of the CreateUserWizard process doesn’t require any custom code – its automatic, based on the property settings of the control. You can check for and add additional roles here if you like.

Now let’s take a look at some Profile Features. Start the application, but do not log in or create an account. Go to the Profile page, and fill in your Profile data. Then, press the Get Profile Values button to see that your Profile data has been saved as an anonymous user. You can close your browser, and come back again, and see that we are indeed holding Profile data for you, even as an anonymous user. Now, create a new account for yourself and log in. Then, go to the Profile page again, and you will see that we have migrated your anonymous data to your new "real member" Profile. This is done in the new "OnMigrateAnonymous" event which fires in Global.asax:

 public void Profile_OnMigrateAnonymous(Object sender, ProfileMigrateEventArgs args)
    {
        ProfileCommon anonymousProfile;
        anonymousProfile =Profile.GetProfile(args.AnonymousID);
        if (Profile.LastActivityDate == DateTime.MinValue)
        {
            Profile.UserDetails.Address = anonymousProfile.UserDetails.Address;
            Profile.UserDetails.City = anonymousProfile.UserDetails.City;
           
            Profile.UserDetails.State = anonymousProfile.UserDetails.State;
            Profile.UserDetails.Zip = anonymousProfile.UserDetails.Zip;
            Profile.UserDetails.Email = anonymousProfile.UserDetails.Email;
            Profile.UserDetails.Phone = anonymousProfile.UserDetails.Phone;
            Profile.UserDetails.GetNewsletter = anonymousProfile.UserDetails.GetNewsletter;
            Profile.Save();
        }        
        // delete the anonymous user data, user is no longer anonymous
        ProfileManager.DeleteProfile(anonymousProfile.UserName);
        //delete the anonymous cookie so this event no longer fires for a logged-in user:
        AnonymousIdentificationModule.ClearAnonymousIdentifier();
    }	  	  
	  

Now, let’s take a look at the web.config setup for all this, and how it works:

p.MsoNormal, li.MsoNormal, div.MsoNormal
{margin-right:0in;margin-bottom:10.0pt;margin-left:0in;line-height:115%;font-size:11.0pt;font-family:’Calibri","sans-serif’;}
.MsoPapDefault
{margin-bottom:10.0pt;line-height:115%;}
@page Section1
{size:8.5in 11.0in;margin:1.0in 1.0in 1.0in 1.0in;}
div.Section1
{page:Section1;}

<?xml version="1.0"?>
<configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0"> 
<
connectionStrings>
   <remove name="LocalSqlServer" />
  <add name="LocalSqlServer" connectionString="server=localhost;database=Articles;uid=sa;pwd="
    
providerName="System.Data.SqlClient" />
  </connectionStrings>
 <appSettings>
    <add key="articleFolder" value="Articles" />
  <add key="connectionString" value="server=localhost;database=Articles;uid=sa;pwd="/>
 </appSettings >
   <system.web>
 <anonymousIdentification enabled="true"/>
 <!– profile–>
<profile>
 <properties>
 <group name ="UserDetails">
   <add name="State"  type="System.String" allowAnonymous="true" />
   <add name="Email" type="System.String" allowAnonymous="true" />
   <add name="Address" type="System.String" allowAnonymous="true" />
   <add name="City" type="System.String" allowAnonymous="true" />
   <add name="Zip"  type="System.String" allowAnonymous="true" />
   <add name="Phone"  type="System.String" allowAnonymous="true" />
   <add name="GetNewsletter" type="System.Boolean" allowAnonymous="true" />
 </group>  
 </properties>
</profile>

<!– membership provider –>
 <roleManager enabled="true" cacheRolesInCookie="true" createPersistentCookie="true" >
    <providers>
       <add applicationName="/" connectionStringName="LocalSqlServer" name="DefaultRoleProvider" type="System.Web.Security.SqlRoleProvider" />
    </providers>
 </roleManager>
 <membership>
    <providers>

       <add connectionStringName="LocalSqlServer" enablePasswordRetrieval="true" enablePasswordReset="true" requiresQuestionAndAnswer="false" applicationName="/" requiresUniqueEmail="true" passwordFormat="Clear" minRequiredPasswordLength="3" minRequiredNonalphanumericCharacters="0" passwordStrengthRegularExpression="" name="DefaultMembershipProvider" type="System.Web.Security.SqlMembershipProvider" />
    </providers>
 </membership
         <compilation debug="true">       
 </compilation>
 <authentication mode="Forms">
   <forms name=".SITE1"
                 loginUrl="Login.aspx"
                 protection="All"
                 timeout="30"
                 path="/"
                 requireSSL="false"
                 slidingExpiration="true"
                 defaultUrl="Default.aspx"
enableCrossAppRedirects="true"/>
 </authentication>
 </system.web
 <location path="SamplePages">
 <system.web>
   <authorization>     
     <allow roles="Administrator" />  
     <deny users="*"/>
   </authorization>
 </system.web>
 </location>
</configuration>

In the beginning, I start with the ConnectionStrings section, removing the Default LocalSqlServer Provider (which defaults to SQLExpress) so that I can add back in my own, specifying the connection string and database.

The appSettings section is just a holdover for backwards – compatibility with the original app.

Next, I specify that anonymousIdentification is enabled. This is what lets us store Profile Data for the anonymous users, and migrate it to their permanent Profile when they join the site. Then, I have my profile section where I actually set up the profile items I want to store. If you look in the APP_CODE folder of the solution, you’ll see the CustomProfile.cs class I’ve created and how easy it is to override the ProfileBase class. In particular, notice that I’ve decorated each item with the [System.Web.Profile.SettingsAllowAnonymous(true)] attribute.

Next, I specify the Membership Provider, and it this case I am using the DefaultProvider. Next, the Role provider. Finally I have my Forms Authentication setup. The last entry is a location path block to allow only Administrators access to the SamplePages folder. Originally I was going to write up a page to manage Members and Roles, but then I found Peter Kellner’s nice workup and sample on this, so in the interest of my credo "Don’t reinvent the wheel", I’ve included those pages in the app. You can, of course, comment that section out temporarily to allow you access so you can make yourself an Administrator after you log into your own site! There is another one in the SamplePages folder, just in case.

By the way, for those Master Mechanics who are interested in getting their hands greasy, Scott Guthrie recently announced the download of the sample Provider Toolkit: "The ASP.NET Provider Toolkit provides a full source code implementation for how you can build a set of ASP.NET 2.0 providers for the new Membership, Role Managmenet, Health Monitoring and Personalization features." If you would like to see an implementation I did for the SQLite database, check out this article.

Finally, in the interest of not getting flamed unnecessarily, be advised that this is not a website — it is just a sample application that was designed solely to illustrate how to pull together the various providers and make them work together. As such, I wouldn’t recommend using the solution as the basis for a real web site, but rather, as a test bed to play around with and get used to how the various parts work.

I hope this effort at bringing together examples of how the Membership, Roles and Profile providers work, in a single article, has been useful to you.

Categories: Uncategorized

Multiple .Config files

December 30, 2006 Leave a comment

Include Multiple .Config Files in ASP.NET Web Application

Introduction

Microsoft ASP.Net provides a configuration system that can be used to keep our applications flexible at run-time. In this article, I will focus on using multiple configuration files. This is a rare technique and is unknown to many developers. The usage of multiple configuration file makes the application more secure and manageable.

 

Prerequisites

This tutorial assumes that you own a copy of Visual Studio 2005 or Visual Web Developer Express. It also assumes that you are familiar with ASP.Net 2.0 basics and have worked with web.config before.

 

Working with Web.Config

Web.config exposes an <appSettings> element that can be used as a place to store application settings like connection strings, file paths, etc. Using the web.config is an ideal method of creating a robust application that can quickly adapt to changes in its environment. For instance, if the connection string is stored in web.config and is being called from the web-pages from there, then changes in the connection string will have to be made in web.config only. Otherwise, the user would have to go to each page individually and update the connection string.

Let us look at a basic web.config which holds our connection string.

 

<?xml version="1.0"?>

<configuration>

    <appSettings/>

    <connectionStrings/>

    <system.web>

        <compilation debug="false" strict="false" explicit="true" />

    </system.web>

    <appSettings>

      <add key="myConnInfo" value="server=_;database=_;user=_;pass=_;" />

    </appSettings>

</configuration>

 

To read the connection setting from the Config file, you have to use a single line of code:

 

System.Configuration.ConfigurationManager.AppSettings("ConnectionInfo")

 

Multiple Config Files

The appSettings element can contain a file attribute that points to an external file. I will change my web.config file to look like the following:

 

<?xml version="1.0"?>

<configuration>

    <appSettings/>

    <connectionStrings/>

    <system.web>

        <compilation debug="false" strict="false" explicit="true" />

    </system.web>

    <appSettings file="externalSettings.config"/>

</configuration>

Categories: .NET

Regular Expressions

December 11, 2006 Leave a comment

Table 1. Common Regular Expressions

Field Expression Format Samples Description
Name ^[a-zA-Z”-‘s]{1,40}$ John Doe
O’Dell
Validates a name. Allows up to 40 uppercase and lowercase characters and a few special characters that are common to some names. You can modify this list.
Social Security Number ^d{3}-d{2}-d{4}$ 111-11-1111 Validates the format, type, and length of the supplied input field. The input must consist of 3 numeric characters followed by a dash, then 2 numeric characters followed by a dash, and then 4 numeric characters.
Phone Number ^[01]?[- .]?(([2-9]d{2})|[2-9]d{2})[- .]?d{3}[- .]?d{4}$ (425) 555-0123
425-555-0123
425 555 0123
1-425-555-0123
Validates a U.S. phone number. It must consist of 3 numeric characters, optionally enclosed in parentheses, followed by a set of 3 numeric characters and then a set of 4 numeric characters.
E-mail ^([0-9a-zA-Z]([-.w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-w]*[0-9a-zA-Z].)+[a-zA-Z]{2,9})$ someone@example.com Validates an e-mail address.
URL ^(ht|f)tp(s?)://[0-9a-zA-Z]([-.w]*[0-9a-zA-Z])*(:(0-9)*)*(/?)([a-zA-Z0-9-.?,’/\+&amp;%$#_]*)?$ http://www.microsoft.com Validates a URL
ZIP Code ^(d{5}-d{4}|d{5}|d{9})$|^([a-zA-Z]d[a-zA-Z] d[a-zA-Z]d)$ 12345 Validates a U.S. ZIP Code. The code must consist of 5 or 9 numeric characters.
Password (?!^[0-9]*$)(?!^[a-zA-Z]*$)^([a-zA-Z0-9]{8,10})$   Validates a strong password. It must be between 8 and 10 characters, contain at least one digit and one alphabetic character, and must not contain special characters.
Non- negative integer ^d+$ 0
986
Validates that the field contains an integer greater than zero.
Currency (non- negative) ^d+(.dd)?$ 1.00 Validates a positive currency amount. If there is a decimal point, it requires 2 numeric characters after the decimal point. For example, 3.00 is valid but 3.1 is not.
Currency (positive or negative) ^(-)?d+(.dd)?$ 1.20 Validates for a positive or negative currency amount. If there is a decimal point, it requires 2 numeric characters after the decimal point.

 

Categories: .NET

Add to car button from within Gridview

December 8, 2006 Leave a comment

"Add to cart" button. it’s a image button.
and you want it pass the RowID to the code.

(with the row id of the GridView, we can easily get the data ID value. product ID in this case)

here’s how to do it.

CommandArgument="<%# Container.DataItemIndex %>"
and with commandName "Vote"

<

ItemTemplate>

<asp:ImageButton ID="btnOK" runat="server"
ImageUrl="~/Images/submyscore.jpg"
CommandArgument="<%# Container.DataItemIndex %>"
CommandName="Vote" />

Code behind:

 

protected

void FilmList_RowCommand(object sender, GridViewCommandEventArgs e)
{

if

(e.CommandName == "Vote")

{

// Convert the row index stored in the CommandArgument

// property to an Integer.

int index = Convert.ToInt32(e.CommandArgument); // This is the Gridview Row Index!

int filmid = (int)FilmList.DataKeys[index]["FilmID"]; //The value of FilmID;

// Retrieve the row that contains the button clicked

// by the user from the Rows collection.

GridViewRow row = FilmList.Rows[index];

Label lbl = (Label)row.FindControl("Label1");

lbl.Text =

"Dected row index!: " + index.ToString() + " and FilmID is:" + filmid.ToString() ;

 

//PlaceHolder ph = (PlaceHolder)row.FindControl("PlaceHolder1");

Control uc = (Control)row.FindControl("uc1");

RadioButtonList rdi = (RadioButtonList)uc.FindControl("rdiOverall");

lbl.Text =

"hello" +rdi.SelectedValue;

}

}

 

Categories: Uncategorized

ASP.NET Page Life Cycle Overview

December 8, 2006 Leave a comment
ASP.NET Page Life Cycle Overview 

When an ASP.NET page runs, the page goes through a life cycle in which it performs a series of processing steps. These include initialization, instantiating controls, restoring and maintaining state, running event handler code, and rendering. It is important for you to understand the page life cycle so that you can write code at the appropriate life-cycle stage for the effect you intend. Additionally, if you develop custom controls, you must be familiar with the page life cycle in order to correctly initialize controls, populate control properties with view-state data, and run any control behavior code. (The life cycle of a control is based on the page life cycle, but the page raises more events for a control than are available for an ASP.NET page alone.)

General Page Life-cycle Stages

In general terms, the page goes through the stages outlined in the following table. In addition to the page life-cycle stages, there are application stages that occur before and after a request but are not specific to a page. For more information, see ASP.NET Application Life Cycle Overview.

Stage Description

Page request

The page request occurs before the page life cycle begins. When the page is requested by a user, ASP.NET determines whether the page needs to be parsed and compiled (therefore beginning the life of a page), or whether a cached version of the page can be sent in response without running the page.

Start

In the start step, page properties such as Request and Response are set. At this stage, the page also determines whether the request is a postback or a new request and sets the IsPostBack property. Additionally, during the start step, the page’s UICulture property is set.

Page initialization

During page initialization, controls on the page are available and each control’s UniqueID property is set. Any themes are also applied to the page. If the current request is a postback, the postback data has not yet been loaded and control property values have not been restored to the values from view state.

Load

During load, if the current request is a postback, control properties are loaded with information recovered from view state and control state.

Validation

During validation, the Validate method of all validator controls is called, which sets the IsValid property of individual validator controls and of the page.

Postback event handling

If the request is a postback, any event handlers are called.

Rendering

Before rendering, view state is saved for the page and all controls. During the rendering phase, the page calls the Render method for each control, providing a text writer that writes its output to the OutputStream of the page’s Response property.

Unload

Unload is called after the page has been fully rendered, sent to the client, and is ready to be discarded. At this point, page properties such as Response and Request are unloaded and any cleanup is performed.

Life-cycle Events

Within each stage of the life cycle of a page, the page raises events that you can handle to run your own code. For control events, you bind the event handler to the event, either declaratively using attributes such as onclick, or in code.

Pages also support automatic event wire-up, meaning that ASP.NET looks for methods with particular names and automatically runs those methods when certain events are raised. If the AutoEventWireup attribute of the @ Page directive is set to true (or if it is not defined, since by default it is true), page events are automatically bound to methods that use the naming convention of Page_event, such as Page_Load and Page_Init. For more information on automatic event wire-up, see ASP.NET Web Server Control Event Model.

The following table lists the page life-cycle events that you will use most frequently. There are more events than those listed; however, they are not used for most page processing scenarios. Instead, they are primarily used by server controls on the ASP.NET Web page to initialize and render themselves. If you want to write your own ASP.NET server controls, you need to understand more about these stages. For information about creating custom controls, see Developing Custom ASP.NET Server Controls.

Page Event Typical Use

PreInit

Use this event for the following:

  • Check the IsPostBack property to determine whether this is the first time the page is being processed.

  • Create or re-create dynamic controls.

  • Set a master page dynamically.

  • Set the Theme property dynamically.

  • Read or set profile property values.

    NoteNote

    If the request is a postback, the values of the controls have not yet been restored from view state. If you set a control property at this stage, its value might be overwritten in the next event.

Init

Raised after all controls have been initialized and any skin settings have been applied. Use this event to read or initialize control properties.

InitComplete

Raised by the Page object. Use this event for processing tasks that require all initialization be complete.

PreLoad

Use this event if you need to perform processing on your page or control before the Load event.

After the Page raises this event, it loads view state for itself and all controls, and then processes any postback data included with the Request instance.

Load

The Page calls the OnLoad event method on the Page, then recursively does the same for each child control, which does the same for each of its child controls until the page and all controls are loaded.

Use the OnLoad event method to set properties in controls and establish database connections.

Control events

Use these events to handle specific control events, such as a Button control’s Click event or a TextBox control’s TextChanged event.

NoteNote

In a postback request, if the page contains validator controls, check the IsValid property of the Page and of individual validation controls before performing any processing.

LoadComplete

Use this event for tasks that require that all other controls on the page be loaded.

PreRender

Before this event occurs:

The PreRender event occurs for each control on the page. Use the event to make final changes to the contents of the page or its controls.

SaveStateComplete

Before this event occurs, ViewState has been saved for the page and for all controls. Any changes to the page or controls at this point will be ignored.

Use this event perform tasks that require view state to be saved, but that do not make any changes to controls.

Render

This is not an event; instead, at this stage of processing, the Page object calls this method on each control. All ASP.NET Web server controls have a Render method that writes out the control’s markup that is sent to the browser.

If you create a custom control, you typically override this method to output the control’s markup. However, if your custom control incorporates only standard ASP.NET Web server controls and no custom markup, you do not need to override the Render method. For more information, see Developing Custom ASP.NET Server Controls.

A user control (an .ascx file) automatically incorporates rendering, so you do not need to explicitly render the control in code.

Unload

This event occurs for each control and then for the page. In controls, use this event to do final cleanup for specific controls, such as closing control-specific database connections.

For the page itself, use this event to do final cleanup work, such as closing open files and database connections, or finishing up logging or other request-specific tasks.

NoteNote

During the unload stage, the page and its controls have been rendered, so you cannot make further changes to the response stream. If you attempt to call a method such as the Response.Write method, the page will throw an exception.

Additional Page Life Cycle Considerations

Individual ASP.NET server controls have their own life cycle that is similar to the page life cycle. For example, a control’s Init and Load events occur during the corresponding page events.

Although both Init and Load recursively occur on each control, they happen in reverse order. The Init event (and also the Unload event) for each child control occur before the corresponding event is raised for its container (bottom-up). However the Load event for a container occurs before the Load events for its child controls (top-down).

You can customize the appearance or content of a control by handling the events for the control, such as the Click event for the Button control and the SelectedIndexChanged event for the ListBox control. Under some circumstances, you might also handle a control’s DataBinding or DataBound events. For more information, see the class reference topics for individual controls and Developing Custom ASP.NET Server Controls.

When inheriting a class from the Page class, in addition to handling events raised by the page, you can override methods from the page’s base class. For example, you can override the page’s InitializeCulture method to dynamically set culture information. Note that when creating an event handler using the Page_event syntax, the base implementation is implicitly called and therefore you do not need to call it in your method. For example, the base page class’s OnLoad method is always called, whether you create a Page_Load method or not. However, if you override the page OnLoad method with the override keyword (Overrides in Visual Basic), you must explicitly call the base method. For example, if you override the OnLoad method on the page, you must call base.Load (MyBase.Load in Visual Basic) in order for the base implementation to be run.

Catch-up Events for Added Controls

If controls are created dynamically at run time or are authored declaratively within templates of data-bound controls, their events are initially not synchronized with those of other controls on the page. For example, for a control that is added at run time, the Init and Load events might occur much later in the page life cycle than the same events for controls created declaratively. Therefore, from the time that they are instantiated, dynamically added controls and controls in templates raise their events one after the other until they have caught up to the event during which it was added to the Controls collection.

In general, you do not need to be concerned about this unless you have nested data-bound controls. If a child control has been data bound, but its container control has not yet been data bound, the data in the child control and the data in its container control can be out of sync. This is true particularly if the data in the child control performs processing based on a data-bound value in the container control.

For example, suppose you have a GridView that displays a company record in each row along with a list of the company officers in a ListBox control. To fill the list of officers, you would bind the ListBox control to a data source control (such as SqlDataSource) that retrieves the company officer data using the CompanyID in a query.

If the ListBox control’s data-binding properties, such as DataSourceID and DataMember, are set declaratively, the ListBox control will try to bind to its data source during the containing row’s DataBinding event. However, the CompanyID field of the row does not contain a value until the GridView control’s RowDataBound event occurs. In this case, the child control (the ListBox control) is bound before the containing control (the GridView control) is bound, so their data-binding stages are out of sync.

To avoid this condition, put the data source control for the ListBox control in the same template item as the ListBox control itself, and do not set the data binding properties of the ListBox declaratively. Instead, set them programmatically at run time during the RowDataBound event, so that the ListBox control does not bind to its data until the CompanyID information is available.

For more information, see Binding to Data Using a Data Source Control.

Data Binding Events for Data-Bound Controls

To help you understand the relationship between the page life cycle and data binding events, the following table lists data-related events in data-bound controls such as the GridView, DetailsView, and FormView controls.

Control Event Typical Use

DataBinding

This event is raised by data-bound controls before the PreRender event of the containing control (or of the Page object) and marks the beginning of binding the control to the data.

Use this event to manually open database connections, if required. (The data source controls often make this unnecessary.)

RowCreated (GridView only) or ItemCreated (DataList, DetailsView, SiteMapPath, DataGrid, FormView, and Repeater controls)

Use this event to manipulate content that is not dependent on data binding. For example, at run time, you might programmatically add formatting to a header or footer row in a GridView control.

RowDataBound (GridView only) or ItemDataBound (DataList, SiteMapPath, DataGrid, and Repeater controls)

When this event occurs, data is available in the row or item, so you can format data or set the FilterExpression property on child data source controls for displaying related data within the row or item.

DataBound

This event marks the end of data-binding operations in a data-bound control. In a GridView control, data binding is complete for all rows and any child controls.

Use this event to format data bound content or to initiate data binding in other controls that depend on values from the current control’s content. (For details, see "Catch-up Events for Added Controls" earlier in this topic.)

Login Control Events

The Login control can use settings in the Web.config file to manage membership authentication automatically. However, if your application requires you to customize how the control works, or if you want to understand how Login control events relate to the page life cycle, you can use the events listed in the following table.

Control Event Typical Use

LoggingIn

This event is raised during a postback, after the page’s LoadComplete event has occurred. It marks the beginning of the login process.

Use this event for tasks that must occur prior to beginning the authentication process.

Authenticate

This event is raised after the LoggingIn event.

Use this event to override or enhance the default authentication behavior of a Login control.

LoggedIn

This event is raised after the user name and password have been authenticated.

Use this event to redirect to another page or to dynamically set the text in the control. This event does not occur if there is an error or if authentication fails.

LoginError

This event is raised if authentication was not successful.

Use this event to set text in the control that explains the problem or to direct the user to a different page.

See Also

Categories: Uncategorized

Retrieve Row Index ID from GridView

December 7, 2006 Leave a comment

Using Gridview and you want to retrieve row index id (in consequence the Data value ID of it).
here is the trick.

HTML

<asp:GridView ID="FilmList" DataKeyNames="FilmID" OnRowCommand="FilmList_RowCommand" runat="server" AutoGenerateColumns="false" >

<

Columns>
<asp:TemplateField>

<

asp:ImageButton ID="ImageButton1" runat="server" ImageUrl="~/Images/submyscore.jpg" CommandArgument="<%# Container.DataItemIndex %>" CommandName="Vote" /> </td>

</

ItemTemplate>
</asp:TemplateField>

CODE.

protected

void FilmList_RowCommand(object sender, GridViewCommandEventArgs e)

{

//reference to http://msdn2.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.rowcommand.aspx

if (e.CommandName == "Vote")

{

// Convert the row index stored in the CommandArgument

// property to an Integer.

int index = Convert.ToInt32(e.CommandArgument); // This is the Gridview Row Index!

int filmid = (int)FilmList.DataKeys[index]["FilmID"]; //The value of FilmID;

// Retrieve the row that contains the button clicked

// by the user from the Rows collection.

GridViewRow row = FilmList.Rows[index];

Label lbl = (Label)row.FindControl("Label1");

lbl.Text =

"Dected row index!: " + index.ToString() + " and FilmID is:" + filmid.ToString() ;

}

}

Categories: .NET