Putting It Together The Login Example


Putting It Together ”The Login Example

We'll now develop a Login control that implements postback event handling and data processing functionality to allow a user to log into a Web site.

In Chapter 8, we developed a LoginUI control that renders two HTML text boxes and a button and provides unique names for those elements. We'll now derive from that control and add event-handling and data-processing functionality to it. Note that LoginUI derives from Control to demonstrate rendering only; we are reusing LoginUI only because it has most of the functionality we need. In general, if you want to implement a control such as Login , you should derive from WebControl and use WebControl 's built-in style properties.

Listing 9-11 contains the code for Login . The highlighted code is responsible for ensuring that, on postback, the page calls Login in the postback data-processing and event phases. We'll discuss the sample after the code listing.

Listing 9-11 Login.cs
 usingSystem; usingSystem.Collections.Specialized; usingSystem.ComponentModel; usingSystem.Web.UI; namespaceMSPress.ServerControls{ [DefaultEvent("Logon")] publicclassLogin:LoginUI,IPostBackDataHandler,IPostBackEventHandler{ privatestaticreadonlyobjectEventLogon=newobject(); privatestring_password; privatestring_userName; [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] publicstringUserName{ get{ return((_userName==null)?String.Empty:_userName); } } [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] publicstringPassword{ get{ return((_password==null)?String.Empty:_password); } } 
 [Category("Action"), Description("Raisedwhenthebuttonisclickedtologin")] publiceventEventHandlerLogon{ add{ Events.AddHandler(EventLogon,value); } remove{ Events.RemoveHandler(EventLogon,value); } } boolIPostBackDataHandler.LoadPostData(stringpostDataKey, NameValueCollectionvalues){ //UserInputNameisdefinedinLoginUI. _userName=values[UserNameInputName]; //PasswordInputNameisdefinedinLoginUI. _password=values[PasswordInputName]; //Checkwhetherthebuttonwasclickedonthe //client.Ifitwas,tellthepageto //invokeIPostBackEventHandler.RaisePostBackEvent. //ButtonNameisdefinedinLoginUI. stringbuttonValue=values[ButtonName]; boolbuttonClicked= (buttonValue!=null)&&(buttonValue.Length!=0);  if(buttonClicked)Page.RegisterRequiresRaiseEvent(this);  //Returnfalsebecausewedonotwanttoraisea //changedevent. returnfalse; } voidIPostBackDataHandler.RaisePostDataChangedEvent(){ } voidIPostBackEventHandler.RaisePostBackEvent(stringeventArgument){ OnLogon(EventArgs.Empty); } protectedvirtualvoidOnLogon(EventArgse){ EventHandlerlogonHandler= (EventHandler)Events[EventLogon]; if(logonHandler!=null){ logonHandler(this,e); } } protectedoverridevoidOnPreRender(EventArgse){ base.OnPreRender(e);  Page.RegisterRequiresPostBack(this);  } protectedoverridevoidRender(HtmlTextWriterwriter){ //Ensuresthatthiscontrolisnestedinaserverform. if(Page!=null){ Page.VerifyRenderingInServerForm(this); } base.Render(writer); } } } 

The Login control accomplishes the following:

  • Handles a postback event and processes postback data by implementing both the IPostBackEventHandler and IPostBackData ­Handler interfaces.

  • Exposes UserName and Password properties. However, it does not use the ViewState dictionary as the backing store for these properties because it is unnecessary to round-trip the properties. Note that a password value should never be round-tripped in a control's view state because it could compromise security.

  • Populates the UserName and Password properties with form data in the LoadPostData method. Login returns false from this method because it does not want to raise any changed events.

  • Defines a Logon postback event and raises the event from its RaisePostBackEvent method.

  • Invokes the RegisterRequiresPostBack method of its page in OnPre ­Render to ensure that the page calls the control during postback processing, even though its UniqueID does not exist in the posted names in the form's name /value collection. (If you look at the code for the base LoginUI control in Chapter 8, you will see that the name attributes it renders for the three elements are UniqueID + ":UserName" , UniqueID + ":Password" , and UniqueID + ":Button" .)

  • Invokes the RegisterRequiresRaiseEvent of its containing page in LoadPostData to inform the page that, in addition to processing postback data, Login raises a postback event. Login makes this call only if the user has clicked the HTML button it renders. Your control needs the call to RegisterRequiresRaiseEvent when it implements both IPostBackDataHandler and IPostBackEventHandler . Otherwise, the page will not invoke the RaisePostBackEvent method of your control in the Raise Postback Event phase.

Listing 9-12 contains a page that uses the Login control and handles its Logon event to validate the user. Figures 9-9 and 9-10 show the page viewed in a browser before and after the form is submitted.

Listing 9-12 LoginTest.aspx
 <%@PageLanguage="C#"%> <%@RegisterTagPrefix="msp"Namespace="MSPress.ServerControls" Assembly="MSPress.ServerControls"%> <html> <head> <scriptrunat="server"> voidlogin1_Logon(objectsender,EventArgse){ if(ValidateUser()){ login1.Visible=false; label1.Text="Hello"+login1.UserName+ ",youareloggedin."; } else{ label1.Text="Loginfailed."+ "Enteryourusernameandpassword."; } } boolValidateUser(){ //Performlogictoauthenticateuser.We'll //simplyreturntrueforthisdemo. returntrue; } </script> </head> <body> <formrunat="server"> <br> <msp:Loginid="login1"runat="server"ButtonText="Submit" NameLabel="LoginName:"PasswordLabel="Password:" BackColor="Gainsboro"BorderColor="Gray"BorderStyle="Solid" 
 BorderWidth="1px"FontFamily="Verdana"FontSize="10" FontBold="True"onLogon="login1_Logon"/> <br> <asp:Labelid="label1"runat="server"/> </form> </body> </html> 
Figure 9-9. LoginTest.aspx viewed in a browser on first request

graphics/f09hn09.jpg

Figure 9-10. LoginTest.aspx viewed in a browser after data is entered and form is submitted

graphics/f09hn10.jpg



Developing Microsoft ASP. NET Server Controls and Components
Developing Microsoft ASP.NET Server Controls and Components (Pro-Developer)
ISBN: 0735615829
EAN: 2147483647
Year: 2005
Pages: 183

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net