Using IIS for ASP.net 2.0 member/role Management (2): Implementing

Source: Internet
Author: User
Tags empty functions sql sort sorts sql server express microsoft iis microsoft c
Asp.net|iis

  Summary: This article describes how to maintain the membership database and role database in the IIS production server by creating a three-tier structured asp.net 2.0 application.

Brief introduction

  Membership Editor

There is no "out-of-the-box" solution in Microsoft Visual Studio version 2005 for maintaining the membership database and role database in Microsoft IIS. This can be a problem when you move an application from a development environment to an IIS production server. Microsoft-provided utilities asp.net Web Configuration can only run in a production-only development environment. This article and its associated code will address this problem by implementing a three-tier solution for member and role management and using the Microsoft asp.net standard tool. This means that the utility will be available to run in any ASP.net 2.0 environment, including IIS. The solution is flexible enough to be easily added to any existing ASP.net 2.0 Web site project.

The layers of the solution are defined as follows. The first Level asp.net page (also called the presentation layer) connects to two business objects through an object data source. These business objects play a middle-tier role and are wrappers for members and roles. The third tier (that is, the back end) consists of the membership and Role Manager APIs provided by ASP.net. Middle-tier objects can easily be added to any ASP.net 2.0 project and can be used directly without making any changes.

In this paper, the implementation of middle layer (i.e. data object and its associated ObjectDataSource) is introduced in depth. It then describes how to use these objects in an ASP.net Web project that uses Microsoft SQL Server Express 2005 (bundled with Visual Studio 2005). However, because the membership API provided by Microsoft uses the technology of its provider, the solution described here is not database-independent. Membership and role information can easily be obtained from LDAP, SQL Server, or Oracle.

  The technology used

  ObjectDataSource

Two ObjectDataSource instances are defined. One is about membership data (user name, creation date, approval status, and so on), and the other is about roles (administrators, friends, and so on). Both data sources are fully populated with all data access methods, both of which contain the member functions that perform inserts, updates, deletes, and selections. All two ObjectDataSource instances return the Generic List type, which means that in the GridView, the column names are automatically set to the ObjectDataSource property value names. In addition, custom sorting is implemented so that users can click on the column headings in the GridView to sort the data forward or reverse as needed.

  SQL Server Express 2005 and Web.config

The data provider source for the membership and role databases is SQL Server Express 2005. To achieve this, you need to set the appropriate entry in the Web.config file. A brief introduction to how to set up a new project from scratch is presented later in this article. The SQL Server Express 2005 connection string is not mentioned in the Web.config file because it is already defined in the default partial machine.config file of the Microsoft. NET 2.0 Framework.

  Support for IIS (5.1 and 6.0)

The WEB server can be version 5.1 or version 6.0. To test multiple users who are logged on to a WEB application, you must use IIS. The built-in development Web server does not correctly maintain the status of different logged-in users. The built-in development Web server does not correctly maintain the status of different logged-in users. Although you can make the asp.net Web Configuration tool work with IIS, the additional security required to achieve this is not yet complete.

  GridView Control

The GridView is used to display data for membership and roles. As noted above, because the Generic type of ObjectDataSource is used, the column names of the GridView are automatically named for the ObjectDataSource property values. If the Generic type is not used, the column name reverts to a meaningless default value and must be edited manually.

  Applications and projects

The project required to run this utility is simple and independent. The project file can be downloaded to include a fully functional sample. Because users and roles do not have direct access to the database, the thing to do is to get three data Objects (MembershipDataObject.cs, MembershipUserSortable.cs, and RoleDataObject.cs, see Figure 2).

Figure 2: Membership Editor Project

There are several other examples in the Samplepages folder that illustrate the use of the modules mentioned earlier. The membership.aspx shown in Figure 1 is one example that can be used to select, UPDATE, insert and delete members and roles, and to assign roles to members.

When working asp.net 2.0 applications with existing work membership modules, you do not need to configure external configurations for these pages. You can copy these files directly into your project and use them once you have copied them.

If you are implementing membership and role management for the first time in your application, the process of creating a solution that uses these objects is as follows:

1. Create a new Web project of type asp.net Web site using Visual Studio 2005.

2. Click Website/asp.net Configuration on the menu (site/asp.net configuration).

3. Follow the steps in the wizard prompts (1 to 7) to create some sample users and roles. This effectively creates a valid Web.config file in the current project that contains sufficient information to start and run member management. By default, it will use SQL Server Express 2005 in its default configuration.

4. Add three. cs files to your project, and then add the sample. aspx page as an example.

  ObjectDataSource Detailed information

Using ObjectDataSource technology, you can create a data source that is very similar to SqlDataSource, which provides an interface that allows you to select, Update, insert, and delete records (or objects of similar records) from a persistent data store, such as a database. The following sections of this article discuss the objects (that is, class files) that are used by ObjectDataSource to manipulate memberships. Its name in the project is MembershipUserODS.cs.

Class (MembershipUserODS)

Because you are retrieving data through the Microsoft membership API, use ObjectDataSource to solve the problem. The first step is to create a separate class that wraps the MembershipUser so that it can be associated with ObjectDataSource. The following example describes a set of typical methods that need to be implemented, and this article describes how to implement each member function. This article omits a lot of details, but the source code included with this article contains these details.

[DataObject (True)
public class Membershipuserwrapper {

[DataObjectMethod (Dataobjectmethodtype.select, True)]
static public collection<membershipuserwrapper> GetMembers (string
Sortdata) {
Return GetMembers (True, true, NULL, sortdata);
}

[DataObjectMethod (Dataobjectmethodtype.insert, True)]
static public void Insert (string UserName, bool isapproved,
String comment, DateTime lastlockoutdate, ...) {
}

[DataObjectMethod (Dataobjectmethodtype.delete, True)]
static public void Delete (object UserName, string original_username) {
Membership.deleteuser (Original_UserName, true);
}

[DataObjectMethod (Dataobjectmethodtype.update, True)]
static public void Update (string original_username,string email,...) {
}
}

  class declaration

The class declaration shown above is special because it has attributes [(DataObject (true)]. This property tells Visual Studio the ObjectDataSource Create Wizard to find only members with this special attribute when searching for DataObject in a data class. See the example in this section where to assign this class to the GridView component.

  Insert method

The details of each section involve using the membership APIs provided by Microsoft in a very simple way. For example, the following is a more detailed, typical Insert method.

[DataObjectMethod (Dataobjectmethodtype.insert,true)]
static public void Insert (string userName, string password,)
{
MembershipCreateStatus status;
Membership.CreateUser (userName, password,);
}

This type of insert is polymorphic, which means that multiple insert methods can exist for different purposes. For example, you might want to use it dynamically to determine whether a user created by the environment should be approved. Another example is that a new user created in the administration screen may want to create a user that defaults to approved, and the user Registration screen may default to unapproved. To do this, another Insert method with extra parameters is required. The Insert method to achieve this goal is roughly as follows.

[DataObjectMethod (Dataobjectmethodtype.insert,false)]
static public void Insert (string userName, string password, bool isapproved)
{
MembershipCreateStatus status;
Membership.CreateUser (UserName, password,
IsApproved, out status);
}

As with the other methods listed here, the example shown is not an example of an actual presence in the source. The example here is to illustrate the typical use of each method. The source code contains a more complete and annotated usage.

  Update method

The Update method is a very simple way to implement the membership API. As with the Insert method, the Update method can have multiple implementations. Only one implementation is described here. In the downloadable code, there are more polymorphic implementations of the Update, one of which sets the IsApproved property only (as shown in the following example).

[DataObjectMethod (Dataobjectmethodtype.update,false)]
static public void Update (String Username,bool isapproved)
{
BOOL Dirtyflag = false;
MembershipUser mu = membership.getuser (UserName);
if (mu.isapproved!= isapproved)
{
Dirtyflag = true;
Mu. isapproved = isapproved;
}
if (Dirtyflag = = True)
{
Membership.updateuser (MU);
}
}

  Delete method

The Delete method is the simplest method, and it uses only one parameter UserName.

static public void Delete (string UserName)
{
Membership.deleteuser (username,true);
}

  Select method with Sort attribute

In this example, the Select method GetMembers has multiple components, each of which is worth introducing. It first describes the value it returns, then the method itself, and finally how it sorts the return value.

  Return value of the Select method (type Collection)

The return value of the Select method (also known as Get) is the Generic Collection class. Generic is used because eventually the ObjectDataSource associated with the class uses reflection to determine the column name and type. These names and types are associated with each row of data that is returned. This method determines the same column name for each row as SqlDataSource uses the database metadata for the table or stored procedure. Because the return type of the Select method is Membershipuserwrapper (inherited from MembershipUser), most of the properties of this class are the same attributes associated with MembershipUser. These properties include the

providerUserKey

username

lastlockoutdate

CreationDate

passwordquestion

lastactivitydate

providername

Islockedout

Email

lastlogindate

Isonline

lastpasswordchangeddate

Comment

In this sentence, attribute values have a very good feature-they can be read-only (no set method), write-only (no Read method), and of course, can be read/write. The ObjectDataSource Wizard takes this into account and creates the appropriate parameters so that only updatable (read/write) fields can be edited when the data control is rendered using ObjectDataSource. This means that you cannot change certain properties, such as the UserName property. If this is not clear now, it is easy to understand later when we describe ObjectDataSource and data components in more detail.

  Select method itself

As with the Insert and Update methods, the Select method is polymorphic. How many types of Select methods can be available. For example, it is a good idea to use the Select method to select users according to their approval status (approved, unapproved, or both). Typically, there is a GET method that has as many parameters as possible associated with it, and calls to it by other got methods. In our example, there are three get methods, one to retrieve all records, one to retrieve records based on the approval status, and one to retrieve a single record based on the selection string. The following example describes a method that calls back all users. Set the two Boolean values to True to return all users.

[DataObjectMethod (Dataobjectmethodtype.select, True)]
static public list<membershipdata> GetMembers (string sortdata)
{
Return GetMembers (True,true,null,null);
}

The following example describes a more detailed get method. This example only describes the beginning of the method and does not cover the details of the method, including completing property assignments, filtering by approval status, rejecting records that do not meet the criteria, and applying sorting criteria. This example follows a detailed description of the sorting criteria. (Note that calling GetAllUsers to a database that contains hundreds of users [not more than 500] will quickly become a costly operation.) )

[DataObjectMethod (Dataobjectmethodtype.select, True)]
static public list<membershipdata> GetMembers (bool allapprusers,
BOOL Allnotapprusers, String usertofind, String sortdata)
{
list<membershipdata> memberlist = new list<membershipdata> ();
Membershipusercollection MUC = Membership.getallusers ();
foreach (MembershipUser mu in MUC)
{
MembershipData MD = new MembershipData ();
Md.comment = mu.comment;
Md. CreationDate = Mu. CreationDate;
...

  Custom sort Criteria

Note that in the preceding code, the parameter string named Sortdata is passed to the getmembers. If the sortparametername is specified as one of its properties in the ObjectDataSource declaration, this parameter is automatically passed to all Select methods. The value will be the name specified for the SortExpression property in the Data Control column. In our example, the data control is the GridView.

The comparer method is invoked based on the Sortname parameters passed to the GetMembers method. Because these asp.net web pages are stateless, you must assume that the direction of the current sort (forward or reverse) is stored in view state. Each call reverses the direction of the previous call. That is, when the user clicks a column heading, it switches between forward and reverse sorting.

It is assumed that the GridView is used, and the parameters passed to GetMembers (sortdata) contain the data in the attribute SortExpression of the GridView column. If you request a reverse sort, the word "DESC" is appended to the sort string. For example, when a user clicks an email column for the first time, the sortdata that is passed to GetMembers is "email". When the user clicks the column for the second time, the parameter sortdata becomes "email DESC", then "email", "email DESC", and so on. It is particularly noteworthy that the first time the page is loaded, the Sortdata parameter passed is a 0-length string (non-empty). The following is part of the GetMembers method that retrieves and sorts the data so that it can be returned in the correct order.

[DataObjectMethod (Dataobjectmethodtype.select, True)]
static public list<membershipdata> GetMembers (string sortdata)
{
list<membershipdata> memberlist = new list<membershipdata> ();
Membershipusercollection MUC = Membership.getallusers ();
list<membershipuser> memberlist = new list<membershipuser> (MUC);

foreach (MembershipUser mu in MUC)
{
MembershipData MD = new MembershipData (MU);
Memberlist.add (MD);
}

... Code that implements Comparison

Memberlist.sort (comparison);

return memberlist;
}

In the next section, it is more clear that this is incorporated into the GridView.

  ObjectDataSource statement

The easiest way to declare ObjectDataSource is to use the Visual Studio 2005 Wizard to create an empty ASP.net page, and then drag and drop the data controls in the data control onto the toolbar. After you create the ObjectDataSource, you can get the small marker in the upper-right corner of the new ObjectDataSource, and then click Configure Data Source to open a wizard that displays "Configure data Source-objectdatasource1 (Configure Data Source-ObjectDataSource1) (see Figure 3).

Figure 3: Configuring ObjectDataSource

At this point, the two classes that can be associated with the ObjectDataSource are displayed. MembershipUserODS is the main theme of this article. Roledataobject are basically the same, but they encapsulate membership roles. Also, keep in mind that the only objects shown here are declarations with special class attributes [DataObject (TRUE)] (described in the class definition).

When you select MembershipUserODS, a dialog box with four tabs is displayed. The methods to be invoked through the MembershipUserODS class are defined in these tabs. The Select, Update, Insert, and Delete methods are associated with member functions in MembershipUserODS. In many cases, there are several methods in a class that apply to each of these cases. An appropriate method must be chosen based on the desired data scheme. The four tabs are shown in Figure 4. By default, members that are marked with special properties [DataObjectMethod (Dataobjectmethodtype.select, false) are populated in these tabs. Of course, this special property is the default value for Select. Change the expression Dataobjectmethodtype.select to Dataobjectmethodtype.insert, Dataobjectmethodtype.update, and Dataobjectmethodtype.delete will determine the corresponding default values for the other tabs. The second parameter is a Boolean value that represents this method (remember that it can be defined in a polymorphic manner) is the default method and should be used in a tab control.

  Select method

As described earlier in the section on introducing the MembershipUserODS class, the GetMembers function returns the Generic Collection class. Thus, the Objectdatasourcemembershipuser control defined here can use reflection and determine the invocation parameters associated with the GetMembers call. In this example, the parameters used to invoke GetMembers are Returnallapprovedusers, Returnallnotapprovedusers, Usernametofind, and Sortdata. Based on this, the actual definition of the new ObjectDataSource is as follows.

Figure 4: Specifying the Select method

<asp:objectdatasource id= "Objectdatasourcemembershipuser" runat= "Server"
Selectmethod= "GetMembers" updatemethod= "Update"
Sortparametername= "Sortdata"
Typename= "Membershiputilities.membershipdataods"
Deletemethod= "Delete" insertmethod= "Insert" >
<SelectParameters>
<asp:parameter name= "Returnallapprovedusers" type= "Boolean"/>
<asp:parameter name= "Returnallapprovedusers" type= "Boolean"/>
<asp:parameter name= "Usernametofind" type= "String"/>
<asp:parameter name= "Sortdata" type= "String"/>
</SelectParameters>
...
...
</asp:ObjectDataSource>

  Insert method

In this example, the Insert method is assigned to the member function insert (). Note that only two parameters are used when calling this method, UserName and Password (see Figure 5). The number of arguments must be equal to the number of arguments declared in ObjectDataSource. The parameter declarations in ObjectDataSource are shown below. Another defined function is Insert member, which is used to add a third parameter, Approvalstatus. If the functionality of this ObjectDataSource is to include an insert operation when setting approvalstatus, you should select a different insert method from the Drop-down list. This causes the following insertparameters to be inserted into the. aspx page. If you select a method that contains two parameters, Asp:parameter named isapproved will not be included in the block. Keep in mind that this example may be inconsistent with the accompanying source code, which is only an example. The source code to be included is much more complete.

Figure 5: Specifying the Insert method

<asp:objectdatasource id= "Objectdatasourcemembershipuser" runat= "Server"
Selectmethod= "GetMembers" updatemethod= "GetMembers"
Sortparametername= "Sortdata"
Typename= "Membershiputilities.membershipdataobject"
Deletemethod= "Delete" insertmethod= "Insert" >
<InsertParameters>
<asp:parameter name= "UserName" type= "String"/>
<asp:parameter name= "Password" type= "String"/>
<asp:parameter name= "isapproved" type= "Boolean"/>
</InsertParameters>
...
</asp:ObjectDataSource>

Keep in mind that if you are using the Insert method with the least parameters, you need to set the default password in the method. In a production system, this is a bad idea. For a better example of how to handle insertions, see the accompanying source code. Specifically, see the membership.aspx page to learn about this feature.

 Update method

In this example, the Update method is assigned to the member function update (). Note that this method is invoked with multiple parameters, UserName, Email, isapproved, and Comment (see Figure 6). In addition, there is an update method that contains all updatable parameters. This is useful if you want to create a control that has as many update capabilities as possible. As with inserts, select the appropriate Update method for this ObjectDataSource. When you complete the wizard, the UpdateParameters is created automatically, as shown below.

Figure 6: Specifying the Update method

<asp:objectdatasource id= "Objectdatasourcemembershipuser" runat= "Server"
Selectmethod= "GetMembers" insertmethod= "Insert"
Sortparametername= "Sortdata"
Typename= "Membershiputilities.membershipuserods"
Updatemethod= "Update" deletemethod= "Delete" >
<UpdateParameters>
<asp:parameter name= "Original_UserName"/>
<asp:parameter name= "Email" type= "String"/>
<asp:parameter name= "isapproved" type= "Boolean"/>
<asp:parameter name= "comment" type= "String"/>
</UpdateParameters>
...
...
</asp:ObjectDataSource>

  Delete method

In this example, the Delete method is assigned to the member function delete (). Of course, just a Delete method (see Figure 7). The following is the declaration of the ObjectDataSource that supports this Delete method.

Figure 7: Specifying the Delete method

<asp:objectdatasource id= "ObjectDataSource1" runat= "Server"
Selectmethod= "GetMembers" insertmethod= "Insert"
Sortparametername= "Sortdata"
Typename= "Membershiputilities.membershipuserods"
Updatemethod= "Update" deletemethod= "Delete" >
<DeleteParameters>
<asp:parameter name= "UserName"/>
<asp:parameter name= "Original_UserName"/>
</DeleteParameters>
...
</asp:ObjectDataSource>

  Class (Roledataobject)

As with membership, it also uses its own DataObject when setting roles. Because the role is not special, this article does not detail its settings. Once you know how membership DataObject is set up, you can see how the role is set up. In membership, the Microsoft C # object that encapsulates the membership API is MembershipDataObject.cs. The similar class for encapsulating role APIs is RoleDataObject.cs.

  ObjectDataSource (Data Control) in the GridView

Class declarations for membership users and roles have been established in the previous section of this article. In addition, the complete ObjectDataSource object is added to the ASP.net page. The final step is to create the user interface, also known as the user interaction layer or presentation layer of the application. Because the objects that are created do so much work, all you need to do is create a simple GridView and associate it with the ObjectDataSource. Steps as follows,

1. In the visual mode of the ASP.net page designer, drag the GridView data component onto the ObjectDataSource associated page that was previously created.

2. Enable SELECT, Delete, update, insert, and sort.

Figure 8 shows the dialog box associated with configuring the Gridview.

Figure 8: Configuring the GridView

It should be noted here that the DataKeyNames in the GridView control shown below is set automatically. This is because the primary key is tagged in the Membershipusersortable class with property [Dataobjectfield (True), as shown below. Note that because UserName is a property of the MembershipUser class, you need to provide a default property in the class that extends MembershipUser. Because it is a read-only property, only the Get method is declared (for Membershipuser,username is public virtual).

[Dataobjectfield (True)]
public override string UserName {
get {return base. UserName;
}

One of the attributes in the GridView must be set manually, and the primary key must be set in the control. To do this, you need to associate attribute datakeyname with UserName. The GridView statement is as follows.

<asp:gridview id= "GridView1" datakeynames= "UserName" runat= "Server"
allowpaging= "True" autogeneratecolumns= "False"
Datasourceid= "Objectdatasourcemembershipuser"
allowsorting= "True" >
<Columns>
...
...

  Conclusion

Now you should be familiar with how to create your own three-tier structured asp.net application. In addition, there are currently two objects that can be used arbitrarily to encapsulate members and roles. For example, you can now use the DetailView control to create a complete DetailView interface for members within minutes to navigate, insert, UPDATE, and delete members. Give it a try!

I didn't specifically describe how to implement adding, updating, and deleting members or roles. If you look at the source code, you'll find that the way I use the API is very simple. It is not very useful to introduce those calls in detail, as I am sure that if you are still reading this article, you will learn to practice as much as I do.

This year I was privileged to attend the MS TechEd in Orlando and the PDC in Los Angeles, and had the opportunity to ask the ASP.net team a lot of questions. Thank you very much, Brad Millington and Stefan Schackow have answered many of the questions I raised in the weeks, thanking Jeff King and Brian Goldfarb for all the help they have given to this article. In some ways, this article is a reward for those who have provided help, hoping that they will not have to answer so many questions in the future.



Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.