20 - Application Service Providers

20.1 Introduction to ASP.NET Providers

The service providers is offers individual or access at management over the internet. It provides services for storing state in databases and various storage media. The session state service manages session state for every user. They store the state in the memory, in external process or in SQL server database. The membership service stores user names, passwords and other membership data in SQL server.

The list of providers included in the ASP.NET model are as mentioned below:

Provider Type

Built-In Providers

Membership

System.Web.Security.SqlMembershipProvider

System.Web.Security.ActiveDirectoryMembershipProvider

Role Management

System.Web.Security.AuthrorizationStoreRoleProvider

System.Web.Security.SqlRoleProvider

System.Web.Security.WindowsTokenRoleProvider

Sitemap

System.Web.XmlSiteMapProvider

Session state

System.Web.SessionState.InProcSessionStateStore

System.Web.SessionState.OutOfProcSessionStateStore

Profile

System.Web.Profile.SqlProfileProvider

Web events

System.Web.Management.EventLogWebEventProvider

System.Web.Management.SimpleMailWebEventProvider

System.Web.Management.TemplatedMailWebEventProvider

Protected configuration

System.Configuration.RSAProtectedConfigurationProvider

System.Configuration.DPAPIProtectedConfigurationProvider

Web Parts personalization

System.Web.UI.WebControls.WebParts.SqlPersonalization.Provider

20.2 Membership Providers

The Membership provider is used to enable the developers to create web sites allowing users to create user login credentials. User can establish an account an account with the site and access the services associated with it. It requires a SQL server database to store the user information.

User can configure the membership provider in the application. The steps to create it are as mentioned below:

1) In the Web.config file, in the <system.web> element, create the <membership> element

2) In the <membership> element, create the <providers> element

3) Add the <clear> element to flush the collection of the providers

4) Create an <add> element with the appropriate elements in the hierarchy of the element

The example for the configuration is as shown below:

<membership defaultProvider=”SqlMembershipProvider” >
 <providers>
  <clear/>
    <add
       name=”SqlMembershipProvider”
       type=”System.Web.Security.SqlMembershipProvider”
       applicationName=”MembershipAndRoleProvider”
       enablePasswordRetrieval=”false”
       requiresUniqueEmail=”true”
       passwordFormat=”Clear” />
 </providers>
</membership>

User can configure a service for using the membership provider. The steps to create the provider are as follows:

1) Add the <behaviors> element to the <system.serviceModel> element

2) Add the <serviceBehaviors> section to the <behaviors> element

3) Add a Behavior element and set the name attribute to corresponding value

4) Add a <serviceCredentials> element to the <behavior> element

5) Add the userNameAuthentication element to the <serviceCredentials> element

6) Set the userNamePasswordValidationMode attribute to the Membership provider

7) Set the membershipProviderName attribute to the name of the provider

The example for the membership provider is as shown below:

<behaviors>
  <serviceBehaviors>
    <behavior name=”Service1”>
      <serviceCredentials>
     <userNameProviderName=”SqlMembershipProvider” />
      </serviceCredentials>
    </behavior>
  </serviceBehaviors>
</behaviors>

20.3 Role Providers

Role Provider provides the interface between the role management service and role data sources. There are three role providers in ASP.NET as mentioned below:

1) SqlRoleProvider: It is the Microsoft role provider for the SQL server database. It is used to store the role data using the data schema. It uses the stored procedure documented in the Data Access.

Some of the properties of the SqlRoleProvider are as mentioned below:

Property

Description

ApplicationName

It gets or sets the name of the application used for storing and retrieving role information

Description

It gives the appropriate description values for the respective interface

Name

It gets the user friendly name for the provider in the configuration

Some of the methods of the SqlRoleProvider are as mentioned below:

Methods

Description

CreateRole

It adds a new role to the new database

DeleteRole

It removes the role from the role database

AddUsersToRoles

It adds the specified user name to each of the specific role

FindUsersInRole

It gets an array of user names in a role

GetAllRoles

It gets a list of all the roles for the application

GetUsersInRole

It gets a list of users in the specified role

RemoveUserFromRoles

It removes the specified user names from the specified roles

The SqlRoleProvider.CreateRole is used to call the stored procedure aspnet_Roles_CreateRole. The task performed by the stored procedure is as follows:

1) It calls the aspnet_Application_CreateApplication to obtain the application ID

2) It checks that the specified role does not exists in the aspnet_Roles table

3) It adds a record representing a new role in the aspnet_Roles table

A sample code to create role in ASP.NET is as shown below:

<b>New Role</b>
<asp:TextBox ID=”Role1” runat=”server”></asp:TextBox>
<br/>
<asp:Button ID=”CreateRole” runat=”server” Text=”CreateRole” />

The code behind file for the application is as shown below:

protected void CreateRole_Click(object sender, EventArgs e)
{
   string newRole=RoleName.Text.Trim();
   if(!Roles.RoleExists(newRole))
   Roles.CreateRole(newRole);
   RoleName.Text=string.Empty;
}

The Roles.DeleteRole method is used to delete roles in an application. It calls the DeleteRole method from the default provider. The SqlRoleProvider.DeleteRole calls the stored procedure aspnet_Roles_DeleteRoles. The task performed by the stored procedure are as mentioned below:

1) Check for the roles that need to be deleted from the list of roles

2) If the throwOnPopulatedRole is true, the aspnet_UsersInRoles table is checked for the role ID

3) It deletes all the records for the specific role ID from the aspnet_UsersInRole table

4) It deletes all the records for the specific role ID from the aspnet_Roles table

A sample code for deleting roles in ASP.NET is as shown below:

var roles=Roles.GetAllRoles();
var role = Request[“role”];
var msg1 = string.Empty;
if(IsPost)
{
  Roles.DeleteRole(role, false);
  msg1=role+”is detected from the system”;
}
 

20.4 Writing Custom Providers

ASP.NET membership providers enable user to use different membership providers for the ASP.NET applications. User can use the membership providers created by the .NET framework or implement own providers.

The reasons to create custom providers are as mentioned below:

1) User needs a data source to store membership information that is not present in the .NET Framework.

2) User needs to manage membership information using a database schema different from the database schemas.

The steps to create the custom membership provider are as mentioned below:

1) Create a class library project in visual studio application

2) Add the assembly System.Web.ApplicationServices in an application

3) Create a class CustomMembershipProvider and derive it from the MembershipProvider class

4) Override the ValidateUser method as follows

public override bool ValidateUser(string username, string password)
{
    If(String.IsNullOrEmpty(password.Trim()))
    return false;
    string hash = EncryptPassword(password);
    User user = repository.GetByIserName(username);
    if( user.Password==hash)
    {
        User = user;
        return true;
    }
    return false;
}

5) Open the Web.Config file, in the <system.web> tag add the following code:

<authentication mode=”Forms”>
 </authentication>
  <authorization>
    <deny users=”?” />
  </authorization>
  <membership defaultProvider=”AdminMembershipProvider” userIsOnlineTimeWindow=”1” />
    <providers>
      <clear/>
      <add name=”AdminMemberProvider” type=”User.Admin.DomainEnitities.Admin” />
    </providers>
  </membership>
  <roleManager defautProvider=”AdminRoleProvider” enabled=”true” />
    <providers>
     <clear/>
     <add name=”AdminRoleProvider” type=”UserAdmin.DomainEntities.AdminRole” />
    </providers>
  </roleManager>

6) Add code for the controllers in the application. Create the controller class and add the following code in it.

public class LoginAccountController:Controller
{
    UserMemberProvider provider=(UserMemberProvider)Membership.Provider;
    public LoginAccountController()
    {
    }
    public ActionResult LogOn()
    {
        return View();
    }
    [ AcceptVerbs(HttpVerbs.Post) ]
    public ActionResult LogOn(string userName, string password, string returnUrl )
    {
        if(!ValidateLogOn(userName, password)
        {
            return View();
        }
    UserAdmin.DataEntities.User user = provider.GetUser();
    FormsAuthentication.SetAuthCookie(user.UserName, false);
    if( !String.IsNullOrEmpty(returnUrl) && returnUrl !=”/” )
    {
        return Redirect(returnUrl);
    }
    else
    {
        return RedirectAction(“Index”, “Home”);
    }
}

The login form code for the application is as shown below:

<b>Email Id</b>
<asp:TextBox ID=”username” runat=”server” /><br/>
<b>Password</b>
<asp:TextBox ID=”password” runat=”server” /><br/>
<asp:Button ID=”btn1” runat=”server” Text=”Log in” />

20.5 Profile Providers

The ASP.NET profile feature enables user to easily use different providers in the application. User can implement a custom profile provider for the following requirements:

1) User needs to store profile information in a data source that is not supported by the profile providers included in the .NET framework.

2) User can manage the profile information using the database schema different from the schema used by the providers included in the .NET framework

The properties and methods of the Profile Providers are as mentioned below:

Methods

Description

Initialize

It takes input as the name of the provider instance and a NameCollection of the configuration settings

GetPropertyValues

It takes input as SettingsContext and a SettingsPropertyCollection object

SetPropertyValues

It takes input as SettingsContext and a SettingsPropertyValueCollection object

DeleteProfiles

It takes input as a string array of user names and deleted from the data source all the profile information

DeleteInactiveProfiles

It takes input a ProfileAuthenticationOption value and DateTime object and deletes from the data source all the profile information

GetAllProfiles

It takes an integer value specifying the page index and page size for the total count of the profile. It returns the ProfileInfoCollection containing the ProfileInfo objects as output

GetAllInactiveProfiles

It takes input as ProfileAuthenticationOption value and DateTime object and returns the ProfileInfoCollection containing the ProfileInfo objects as output

FindProfilesByUserName

It takes a string as user name, page index and page size and a reference integer as input and returns the ProfileInfo object as output

FindInactiveProfilesByUserName

It takes a username, Datetime object, page index and page size to count the number of profiles. It returns the ProfileInfo object as output

GetNumberOfInactiveProfiles

It takes input as ProfileAuthenticationValue, DateTime object and returns a count of all profiles in the data source containing the last activity date less than or equal to the specified DateTime values

The steps to create the Profile Provider database are as follows:

1) Create a Microsoft Access database in the system

2) In the Access tool, create tables in the Access database and add the following data definition query in the Profiles tables

CREATE TABLE Profiles
(
  UserID int PRIMARY KEY,
  UserName Text (200) NOT NULL,
  CourseName Text (200) NOT NULL,
  LastActiveDate DateTime,
  CONSTRAINT PKProfiles UNIQUE ( UserName, ApplicationName)
)

3) Create the following data definition query to create College table as shown below:

CREATE TABLE College
(
  UserID int,
  CollegeName Text(20),
  CONSTRAINT FKProfiles FOREIGN KEY ( UserID)
  REFERENCES Profiles
)

4) Create an ASP.NET page named Login.aspx in the application. Add a login control if it is already configured to use the ASP.NET membership

5) Create a DSN named OdbcProfile on the system and configure to include connection information to Access database created by the user

6) Place the source code into the application App_Code folder.

7) Compile the code and place the assembly in the applications Bin folder or in the global assembly cache

8) Execute the command mentioned below:

csc /out:OdbcProfileProvider.dll /t:library OdbcProfileProvider.cs /r:System.Web.dll /r:System.Configuration.dll

Where, /t:library compiler option creates a library. /out option provides the name of the assembly and /r option lists the assemblies linked to the specific assembly.

20.6 Web Parts Personalization Providers

Web Parts Personalization Providers provide an interface between ASP.NET Web parts personalization services and data sources. The uses of creating the personalization providers are as mentioned below:

1) User can store the personalization data in the data source that is not supported by the personalization providers included in the .NET framework

2) User can store personalization data in SQL Server database whose schema is different from the database used by System.Web.UI.WebControls.WebParts.SqlPersonalizationProvider

Some of the properties and methods of the Web Parts Personalization Providers are as mentioned below:

Property or Method

Description

ApplicationName

It is the name of the application using the personalization provider

CreateSupportedUserCapabilites

It returns a list of WebPartUserCapability objects indicating the users can access the personalization state

DetermineInitialScope

It is used by the WebPartsPersonalization to determine the initial scope of previously loaded personalization state is shared

DetermineUserCapabilites

It returns the dictionary of WebPartsUserCapability object indicating the current user access share personalization state and saves it

ResetPersonalizationState

It deleted the personalization state from the Data Source

LoadPersonalizationState

It retrieves the personalization data from the Data Source and converts into PersonalizationState object

SavePersonalizationState

It writes the personalization state object into the Data Source

FindState

It returns the collection of PersonalizationStateInfo object containing the information about the records in the data source

GetCountOfState

It returns the number of records in the Data Source that matches the specified criteria

LoadPersonalizationBlobs

Retrieves the personalization state as opaque blobs from the Data Source

ResetState

It deletes the personalization state corresponding to the specified user and specified page from the Data Source

ResetUserState

It deletes the user personalization state corresponding users and pages from the Data source

The sample code to demonstrate the Web Parts Personalization Provider is as shown below:

<webParts>
  <personalization defaultProvider=AspNetSqlPersonalizationProvider”>
    <providers>
    <add name=”AspNetSqlPersonalizationProvider” type=”System.Web.UI.WebControls.WebParts.SqlPersonalizationProvider” connectionStringName=”LocalSqlServer” applicationName=”/” />
    </providers>
    <authorization>
    <deny users=”*” verbs=”enterSharedScope” />
    <allow users=”*” verbs=”modifyState” />
    </authorization>
  </personalization>
</webParts>

Like us on Facebook