September 19, 2014
Hot Topics:
RSS RSS feed Download our iPhone app

Consuming Membership and Profile Services via ASP.NET AJAX

  • February 26, 2007
  • By Bipin Joshi
  • Send Email »
  • More Articles »

User Registration

First of all, you will create the user registration page. Add a new web form named Registration.aspx. Drag and drop a ScriptManager control from the toolbox (see Figure 2).

Figure 2. Drag and Drop a ScriptManager Control

Also, drag and drop an UpdatePanel and UpdateProgress control on the web form. The UpdatePanel control represents a part of the total web form that can be refreshed without causing a post back of the entire form. The UpdateProgress control is used to display a progress message while the UpdatePanel is being refreshed.

Drag and drop a Label control inside the UpdateProgress control and set its Text property to "Please wait...". Also, set its AssociatedUpdatePanelID property to the ID of the UpdatePanel control. The AssociatedUpdatePanelID property links the UpdateProgress with an UpdatePanel.

Add a table into the UpdatePanel and design it as shown in Figure 3.

Figure 3. Design for Table in the UpdatePanel

The first column of the table contains Label controls that act as prompts for the textboxes. The second column of the table contains TextBox controls. Each TextBox control is validated by using a RequiredFieldValidator control. The TextMode property of the password and confirm password textboxes is set to Password. Similarly, the TextMode property of the street address textbox is set to MultiLine.

There is a Button called "Check Availability" that the end user can use to check the availability of a user ID. The "Check Availability" button will make an AJAX call to the web form to decide whether the specified user ID is available for registration. Set the OnClientClick property of the "Check Availability" button to "return CheckAvailability();" (CheckAvailability() is a client-side JavaScript function that you will write later). This function will call a web method to decide whether the user ID is available for registration. Finally, the Register button will create the user in the system with the help of the Membership features. The Label at the bottom is used for displaying success or error messages.

Now, go in the code behind of the Register.aspx and add a static web method called CheckAvailability. The following is the complete code of the method:

[WebMethod]
public static bool CheckAvailability(string uid)
{
   MembershipUser user = Membership.GetUser(uid);
   if (user == null)
   {
      return true;
   }
   else
   {
      return false;
   }
}

You might be wondering why you added a web method inside a web form. Remember that you have a "Check Availability" button that is supposed to check whether the specified user ID is available for registration. You will be making an AJAX call to do that. ASP.NET AJAX allows you to call web methods defined in web forms via an object called PageMethods. Therefore, you marked the CheckAvailability() method with a [WebMethod] attribute. Note that you must refer to the System.Web.dll and import the System.Web.Services namespace to use the [WebMethod] attribute.

The CheckAvailability() method accepts a user ID and returns true if that ID is available for registration. Inside, it calls the GetUser() method of the Membership object. The GetUser() method returns an instance of the MembershipUser class that represents the specified user. If it returns null, it indicates that the specified user doesn't exist and accordingly true or false is returned to the caller.

When the user clicks the Register button, you need to add user details in the membership and profile tables. Use the Membership and Profile objects to do this BECAUSE ASP.NET AJAX doesn't allow you to create users from client-side code. The following code shows the Click event handler of the Register button:

protected void Button1_Click(object sender, EventArgs e)
{
   try
   {
      MembershipUser user   = Membership.CreateUser
      (TextBox2.Text, TextBox3.Text, TextBox5.Text);
      ProfileCommon pc      = Profile.GetProfile(user.UserName);
      pc.FullName           = TextBox1.Text;
      pc.DOB                = DateTime.Parse(TextBox6.Text);
      pc.Address.Street     = TextBox7.Text;
      pc.Address.Country    = TextBox8.Text;
      pc.Address.PostalCode = TextBox9.Text;
      pc.Save();
      lblMsg.Text           = "User created successfully!";
   }
   catch (Exception ex)
   {
      lblMsg.Text = ex.Message;
   }
}

You call the CreateUser() method of the Membership object to create the user and pass user ID, password, and email. The CreateUser() method returns an instance of MembershipUser representing the newly created user. At this point, the user is not authenticated, so you cannot set the user's profile directly via the Profile object. Instead, you call the GetProfile() method of the Profile object. The GetProfile() method returns an instance of the ProfileCommon class. Through this instance, you set various profile properties. Once all the profile properties are saved, the Save() method of the ProfileCommon class is called to save profile information to the underlying database. A success message is then displayed in a Label control. Any exceptions during the registration process are captured BY using try-catch blocks and an error message is displayed in a Label control.

Now, code the client-side CheckAvailability() function. Switch to the HTML source view of the Register.aspx and add a script block in the HEAD section of the page. Then, add the following functions in the script block:

function CheckAvailability()
{
   var uid=document.getElementById('TextBox2').value;
   if(uid=="")
   {
      alert('Please enter user ID!');
      return false;
   }
   PageMethods.CheckAvailability(uid,OnComplete);
   return false;
}
function OnComplete(result)
{
   var lblMsg=document.getElementById('lblMsg');
   if(result)
   {
      lblMsg.innerText="The ID is available!";
   }
   else
   {
      lblMsg.innerText="The ID is unavailable!";
   }
}

The CheckAvailability() function retrieves the user ID textbox using the getElementById() method of the HTML DOM, which accepts the ID of an element and returns a reference to it. The code checks whether the user ID is empty and, if so, displays an error message. It then calls the CheckAvailability() web method via the PageMethods object and passes the specified user ID to it. The PageMethods object is a built-in object provided by ASP.NET AJAX that allows you to call web methods defined in web forms. The second parameter of the CheckAvailability() call is nothing but the name of another JavaScript function (OnComplete in this example) that gets called after the web method call completes. You may find this mechanism a bit odd, but remember that ASP.NET AJAX communication is always asynchronous. The OnComplete() function receives the return value of the web method as a result parameter. It then simply displays a success or error message in a Label control. Note that the CheckAvailability() JavaScript function returns false so that there won't be any post back.

This completes your registration page. To test it, run the Register.aspx in the browser and try creating new users. Also, check how the "Check Availability" button works. Figure 4 shows a sample run of the web form.

Figure 4. Sample Run of the Web Form

Developing a Login Page

Now that users can register themselves with the web site, you need to provide a facility that enables them to log in and access various pages. To do so, add a new web form called Login.aspx to the web site. Remember that you have set the loginUrl attribute of the forms tag to Login.aspx. Drag and drop a ScriptManager control on it and design the login page as shown in Figure 5 by assembling various controls.

Figure 5. The Login Page Design

As you can see, the login page consists of textboxes for entering a user ID and password. The "Remember Me" checkbox allows you to preserve your logged-in status even after closing the browser window. The TextMode property of the password textbox is set to Password. Further, the OnClientClick property of the Login button is set to "return BeginAuthenticateUser();". BeginAuthenticateUser() is a JavaScript function that uses the ASP.NET AJAX authentication service to authenticate the user. The following is the BeginAuthenticateUser() function:

function BeginAuthenticateUser()
{
   var uid;
   var pwd;
   var isPersistent;
   uid=document.getElementById('TextBox1').value;
   pwd=document.getElementById('TextBox2').value;
   isPersistent=document.getElementById('CheckBox1').checked;
   Sys.Services.AuthenticationService.login
   (uid,pwd,isPersistent,null,null,
   EndAuthenticateUser,OnError,uid);
   return false;
}

The BeginAuthenticateUser() JavaScript function retrieves the user IDs and passwords entered in their respective textboxes. It also retrieves the status of the "Remember Me" checkbox. ASP.NET AJAX provides a built-n class called AuthenticationService that resides in the Sys.Services namespace. Remember that the Sys.Services namespace is defined by the client-side framework of ASP.NET AJAX. The AuthenticationService class offers two methods: login() and logout(). The code above used the login() method, which takes in all eight parameters. Their significance is listed below:

Parameter Significance
1 A user ID
2 A password
3 A boolean value indicating whether an authentication cookie will be persistent
4 The web page where the user should be redirect after a successful login
5 Reserved for future use
6 A callback function that will be called after a successful login (EndAuthenticateUser in this example)
7 A callback function that will be called in case a login attempt fails (OnError in this example)
8 A custom value that is passed to the callback functions

If the user is successfully authenticated, the EndAuthenticateUser function will be called. The following is the EndAuthenticateUser function:

function EndAuthenticateUser(result,userContext,methodName)
{
   if(result)
   {
      window.location='default.aspx';
   }
   else
   {
      alert("Unable to login! Please check user id and password!!");
   }
}

The EndAuthenticateUser() function takes three parameters: the result of the login operation, the user context that you passed earlier in the eighth parameter of the login() method, and the method name. Inside, it checks whether the result is true (in other words, the user is successfully authenticated) and, if so, it sets the location property of the windows object to default.aspx. This way, the user is redirected to the default page after a successful login attempt. If there is any error, an error message is displayed using the alert() function.

The OnError() function is called whenever an error occurs when calling the authentication service. This function is shown below:

function OnError(result,userContext,methodName)
{
   alert(result.get_message());
}

The function simply displays an error message to the user. The result parameter received is actually an object and has a method called get_message() that returns a descriptive error message.

This completes the login page.





Page 2 of 3



Comment and Contribute

 


(Maximum characters: 1200). You have characters left.

 

 


Sitemap | Contact Us

Rocket Fuel