Microsoft ASP. NET 2.0 Member/role management using IIS, Part 1: Implementation

Source: Internet
Author: User
Tags sql server express microsoft iis microsoft c

Release date: 2006-2-10 | update date: 2006-2-10

Peter Kellner
Http://peterkellner.net/

Applicable:
Microsoft ASP. Network 2.0
Microsoft Visual maxcompute 2005
Microsoft Internet Information Service

Abstract:This article describes how to maintain the membership database and role database on the IIS production server by creating a three-tier structured ASP. NET 2.0 application.

Click here to download the sample code.

Content on this page

Introduction
Technologies used
Applications and projects
Objectdatasource details
Return Value of the select method (type: Collection)
Select method itself
Custom sorting Conditions
Objectdatasource (Data Control) in the gridview)
Conclusion

Introduction

Member Editor

Microsoft Visual Studio 2005 does not have a "ready-to-use" solution for maintaining the membership database and role database in Microsoft IIS. This is a problem when you move applications in the development environment to the IIS production server. The utility ASP. NET web configuration provided by Microsoft can only be run in a non-production development environment. This article and its associated code implement a three-tier solution through member and role management, and use Microsoft ASP. NET standard tools to solve this problem. This means that the utility will run in any ASP. NET 2.0 Environment (including IIS. This solution is flexible and can be easily added to any existing ASP. NET 2.0 website project.

The solution layer is defined as follows. The first ASP. NET page (also known as the presentation layer) is connected to two business objects through the object data source. These Business Objects Act as middle layers and are members and roles of the package. The third layer (backend) consists of the membership identity provided by ASP. NET and the role manager API. Intermediate layer objects can be easily added to any ASP. NET 2.0 project and can be directly used without any changes.

This article introduces the implementation of the intermediate layer (that is, the data object and its associated objectdatasource. Next, we will introduce 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 provided by its provider, the solution described here is irrelevant to the database. You can easily obtain membership and role information from LDAP, SQL Server, or Oracle.

Back to Top

Technologies used

Objectdatasource

Two objectdatasource instances are defined. One is about member identity data (user name, creation date, approval status, etc.), and the other is about roles (administrators, friends, etc. Both data sources are completely filled with all data access methods, that is, both of them contain the member functions that execute insertion, update, deletion, and selection. Both objectdatasource instances return the generic list type, which means that in the gridview, the column name is automatically set to the Attribute Value Name of objectdatasource. In addition, custom sorting is implemented so that you can click the column title in the gridview to sort the data in the forward or reverse order as needed.

SQL Server express 2005 and web. config

The data provider source of the membership database and role database is SQL Server express 2005. To achieve this, you need to set the corresponding entries in the web. config file. This article will briefly introduce how to set up a new project from the beginning. The connection string of SQL Server express 2005 is not mentioned in the web. config file, because it has been defined in the default part of Microsoft. NET 2.0 Framework in the machine. config file.

Support for IIS (5.1 and 6.0)

The Web server can be version 5.1 or 6.0. To test multiple users logging on to the web application, you must use IIS. The built-in development web server does not properly maintain the status of different login users. The built-in development web server does not properly maintain the status of different login users. Although the Asp.net web configuration tool can work with IIS, additional security work is not completed to achieve this goal.

Gridview Control

The gridview is used to display the data of the member identity and role. As described above, because the generic type of objectdatasource is used, the names of the columns in the gridview are automatically named by the attribute value of objectdatasource. If the generic type is not used, the column name is restored to the meaningless default value and must be edited one by one manually.

Back to Top

Applications and projects

The project required to run this utility is very simple and independent. Project files can be downloaded, including complete examples. Because users and roles do not have the permission to directly access the database, the only thing to do is to obtain three Data Objects (Membershipdataobject. CS,Membershipusersortable. CSAndRoledataobject. CS, See Figure 2 ).

Figure 2: Member identity editor Project

There are several other examples in the samplepages folder, which demonstrate the usage of the previously mentioned modules. The membership. aspx shown in Figure 1 is one of the examples. It can be used to select, update, insert and delete members and roles, and assign roles to members.

When you use a work ASP. NET 2.0 application that already has a work member Identity Module, you do not need to perform external configurations other than those on these pages. You can copy these files directly to the project.

If it is the first time to implement membership and role management in an application, the process of creating a solution to use these objects is as follows,

  1. Use Visual Studio 2005 to create a new web project of the ASP. NET Website type.

  2. ClickWebsite/ASP. NET Configuration(Website/ASP. NET configuration ).

  3. Follow the steps (1 to 7) prompted by the Wizard to create some sample users and roles. This will effectively create a valid Web. config file in the current project, which contains sufficient information to enable and run member management. By default, it uses SQL Server express 2005 in its default configuration.

  4. Add three. CS files to the project, and then add the sample. ASPX page as an example.

Back to Top

Objectdatasource details

The objectdatasource technology can be used to create data sources that function very similar to sqldatasource, that is, it provides the ability to allow data from permanent data storage areas (such as databases) to select, update, insert, and delete records (or similar record objects. The following sections describe the objects (class files) That objectdatasource uses to operate on member identities ). Its name in the project isMembershipuserods. CS.

Class (membershipuserods)

Because data is retrieved through the Microsoft membership API, The objectdatasource is used to solve the problem. The first step is to create an independent class.MembershipuserSo that it can be associated with objectdatasource. The following example describes a set of typical implementation methods. The following sections describe how to implement each member function. Many details are omitted in this article, but the source code included in 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 has attributes.[(Dataobject (true)], Special. This attribute tells Visual Studio 2005 objectdatasource creation wizard that only Members with this special attribute can be searched for dataobject in the data class. See this section to describe how to assign this class to the gridview component.

Insert Method

The details of each part involve using the membership API provided by Microsoft in a very simple way. For example, the following is a more detailed typicalInsertMethod.

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

SuchInsertIs polymorphism, which means there can be multipleInsertMethod. For example, you may need to use it when dynamically deciding whether to approve a user created based on the environment. Another example is that a new user created on the Management screen may want to create a user that is approved by default, while a user registration screen may be unapproved by default. For this reason, anotherInsertMethod. Which can achieve this goalInsertThe method 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);}

Like other methods listed here, the displayed examples are not examples that actually exist in the source. The example here is to illustrate the typical usage of each method. The source code is more complete and annotated.

Update Method

UpdateThe method is a very simple method to implement the membership API. AndInsertSame method,UpdateMethods can also be implemented in multiple ways. Only one implementation is introduced here. In downloadable code, there are moreUpdateOne of them is only setIsapprovedProperties (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

DeleteThe method is the simplest method. It only uses one parameter.Username.

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

Select Method With sort attribute

In this example,SelectMethodGetmembersIt has multiple components, and each component is worth introducing. First, we will introduce the returned values, then the method itself, and finally how to sort the returned values.

Back to Top

Return Value of the select method (type: Collection)

SelectMethod (also knownGet. Generic is used because the objectdatasource associated with this class uses reflection to determine the column name and type. These names and types are associated with each row of returned data. This method is the same as sqldatasource using the database metadata of tables or stored procedures to determine the column names of each row. BecauseSelectThe return type of the method is membershipuserwrapper (inherited from membershipuser). Most of these attributes are the same attributes associated with membershipuser. These attributes include,

  • Provideruserkey

  • Username

  • Lastlockoutdate

  • Creationdate

  • Passwordquestion

  • Lastactivitydate

  • Providername

  • Islockedout

  • Email

  • Lastlogindate

  • Isonline

  • Lastpasswordchangeddate

  • Comment

Here, the attribute values have a very good feature-they can be read-only (no setting method), write-only (no reading method ), of course, it can also be read/write. The objectdatasource wizard takes this into consideration and creates corresponding parameters. In this way, only the updatable (read/write) fields can be edited when the data control is rendered using objectdatasource. This means that you cannot change certain attributes, suchUsernameAttribute. If this is not clear yet, it will be easy to understand later when we describe objectdatasource and data components in more detail.

Back to Top

Select method itself

AndInsertAndUpdateSame method,SelectThe method is also polymorphism. In either caseSelectMethod. For example, it is best to useSelectThe method selects the user based on the user's approval status (approved, not approved, or both. Generally, there isGetThe method has as many parameters as possible associated with it.GetMethod. In our example, there are threeGetMethod, one to retrieve all records, one to retrieve records based on the approval status, and one to retrieve a single record based on the selected string. The following example describes how to call a method that returns all users. Set both boolean valuesTrue, Returns all users.

[DataObjectMethod(DataObjectMethodType.Select, true)]static public List<MembershipData> GetMembers(string sortData){   return GetMembers(true,true,null,null);}

The following example introduces a more detailedGetMethod. This example only describes the beginning of a method, without detailed information about the method, including completing attribute assignment, filtering by approval status and rejecting records that do not meet the conditions, and applying sorting conditions. This example is followed by a detailed description of the sorting conditions. (Note: For database calls that contain hundreds of users [no more than five hundred]GetallusersAnd will soon become a very expensive 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;            ...

Back to Top

Custom sorting Conditions

Note that in the previous codeSortdataParameter string passedGetmembers. In the objectdatasource declaration,SortparameternameThis parameter is automatically passed to allSelectMethod. The value isSortexpressionThe name specified by the property. In our example, the data control is a gridview.

ComparerThe method is based onGetmembersMethodSortnameParameter. Because these ASP. NET web pages are stateless, you must assume that the direction (forward or backward) of the current sorting is stored in the view State. Each call reverses the direction of the previous call. That is, when you click the column title, switch between forward and reverse sorting.

Assume that you are using the gridview and pass itGetmembers (sortdata)Contains the properties of the gridview column.Sortexpression. If the request is reverse sorted, the word "DESC" is appended to the sort string. For example, when you click the email column for the first timeGetmembersOfSortdataIs "email ". When you click this column for the second timeSortdataIt becomes "email DESC", followed by "email" and "email DESC", and so on. Note thatSortdataThe parameter is a zero-length string (not empty ). Below isGetmembersThis method retrieves and sorts the data to return the data 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 clearer to merge the data into the gridview.

Objectdatasource Declaration

The easiest way to declare objectdatasource is to first create an empty ASP. NET page using the Visual Studio 2005 wizard, and then drag and drop the Data Control in the Data Control to the toolbar. After creating the objectdatasource, you can obtain the small tag in the upper-right corner of the newly created objectdatasource. Then, clickConfigure Data Source(Configure the data source) open a wizard that displays the configure data Source-ObjectDataSource1 (configure the data source-objectperformance1) (see figure 3 ).

Figure 3: Configure objectdatasource

The two classes that can be associated with objectdatasource are displayed.MembershipuserodsIs the main topic of this article.RoledataobjectThey are basically the same, but they encapsulate member identity roles. In addition, remember that only declarations with special class attributes are shown here.[Dataobject (true)](Introduced in "Class Definition.

SelectMembershipuserodsA dialog box with four tabs is displayed. To passMembershipuserodsThe class call methods are defined in these tabs.Select,Update,InsertAndDeleteThe method will beMembershipuserodsMember function Association in. In many cases, classes have multiple methods that apply to each of them. You must select an appropriate method based on the required data scheme. Figure 4 shows the four tabs. By default, the tabs are filled with special properties[Dataobjectmethod (dataobjectmethodtype. Select, false)]. Of course, this special attribute isSelect. Convert expressionsDataobjectmethodtype. SelectChangeDataobjectmethodtype. insert,Dataobjectmethodtype. UpdateAndDataobjectmethodtype. DeleteThe corresponding default values are determined for other tabs. The second parameter is a Boolean value, indicating that this method (remember that it can be defined in polymorphism mode) is the default method and should be used in the tab control.

Select Method

As described aboveMembershipuserodsClass,GetmembersThe function returns the generic collection class. In this way,Object‑cememembershipuserControls can be reflected and determinedGetmembersCall the associated call parameters. In this exampleGetmembersThe parameter isReturnallapprovedusers,Returnallnotapprovedusers,UsernametofindAndSortdata. Based on this, the actual definition of the new objectdatasource is as follows.

Figure 4: 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,InsertThe method is specified to the member function.Insert (). Note that only two parameters are used to call this method,UsernameAndPassword(See figure 5 ). The number of parameters must be equal to the number of parameters declared in objectdatasource. The parameter declaration in objectdatasource is as follows. Another defined function isINSERT MEMBERTo add the third parameter,Approvalstatus. If the objectdatasource function needs to be included in the settingsApprovalstatusInsert operation, select other insert methods 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, the block does not contain a method namedIsapprovedOfASP: Parameter. Remember that this example may be different from the source code that comes with it. This example is only used as an example. The source code is much more complete.

Figure 5: 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>

Remember, if you are usingInsertMethod, you need to set the default password in the method. This is a bad way in the production system. For a better example of how to handle inserts, see the source code that comes with it. For more information, see the membership. ASPX page.

Update Method

In this example,UpdateThe method is specified to the member function.Update (). Note that multiple parameters are used to call this method,Username,Email,IsapprovedAndComment(See figure 6 ). In addition, there isUpdateMethod, which contains all updatable parameters. This is useful if you want to create controls with as many update functions as possible. AndInsertSimilarly, select the appropriateUpdateMethod. After the Wizard is complete, updateparameters will be automatically created, as shown below.

Figure 6: Specify 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,DeleteThe method is specified to the member function.Delete (). Of course, only oneDeleteMethod (see figure 7 ). Below is the support for thisDeleteObjectdatasource Declaration of the method.

Figure 7: 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)

Like a member identity, a role also uses its own dataobject. This document does not describe the role settings in detail. After learning about how to set dataobject as a member, you can understand how to set the role. In a member identity, the Microsoft C # object that encapsulates the member identity API isMembershipdataobject. CS. Similar classes that encapsulate role APIs areRoledataobject. CS.

Back to Top

Objectdatasource (Data Control) in the gridview)

In the previous section of this article, you have created a class declaration for the user and role as a member. In addition, the completeObjectdatasourceObject. The last step is to create a user interface, also known as the user interaction layer or presentation layer of the application. Because the created object has completed so much work, all you need to do is create a simple gridview and associate it with objectdatasource. The procedure is as follows,

  1. In the visual mode of the ASP. NET page designer, drag and drop the gridview data component to the previously created objectdatasource Association page.

  2. Enable selection, deletion, update, insertion, and sorting.

Figure 8 shows the dialog box associated with the configuration of the gridview.

Figure 8: configure the gridview

Note the following:GridviewInDatakeynamesIs set automatically. This is because[Dataobjectfield (true)]OfMembershipusersortableThe primary key is marked as follows. Note thatUsernameYesMembershipuserClass attributes, which must be extendedMembershipuserProvides default properties. Because it is a read-only attribute, onlyGetMethod (Membershipuser,UsernameIs public virtual ).

[DataObjectField(true)]public override string UserName {  get { return base.UserName;}

One Property in the gridview must be set manually and the primary key must be set in the control. Therefore, you need to set the attributeDatakeynameAndUsernameAssociated. The gridview statement is as follows.

<asp:GridView ID="GridView1" DataKeyNames="UserName" runat="server"         AllowPaging="True" AutoGenerateColumns="False"        DataSourceID="ObjectDataSourceMembershipUser"        AllowSorting="True">    <Columns>    ...    ...

Back to Top

Conclusion

Now, you should be familiar with how to create your own three-tier structured ASP. NET application. In addition, two objects can be used to encapsulate members and roles at will. For example, you can useDetailviewControls. A complete detailview interface for Members is created within a few minutes to navigate, insert, update, and delete members. Try it!

I have not specifically introduced how to add, update, and delete members or roles. If you view the source code, you will find that the method of using the API is very simple. It is not very useful to detail those calls here, because I am sure that if you are still reading this article, you will learn and practice like me.

This year I had the honor to attend MS Teched in Orlando and the PDC in Los Angeles and had the opportunity to ask a lot of questions to the ASP. NET team. We are particularly grateful to Brad milington and Stefan schackow for answering many of my questions over the weeks and to jeff king and Brian Goldfarb for all their help in this article. In some respects, this article is a return to those who have helped, and I hope they will not have to answer so many questions in the future.

Author Profile

Peter Kellner founded 73rd street associates in 1990, where he successfully provided a system for University Clinic scheduling, insurance company management, and one-stop doctor Clinic management for more than 500 customers nationwide. Ten years later (in 2000), Peter started his new career as an independent software consultant after a large insurance company acquired 73rd street associates. Currently, the technologies involved include ASP. NET, Oracle, Java, and VoIP, and SQL server will soon be included. When he is not working, Peter spends most of his free time on his bike trip. He has traveled around the world by bike. Recently, he and his wife Tammy took only 27 days to complete the ride from California to Georgia.

His blog website is http://peterkellner.net /. You can find the Code listed in this article in the download area.

Go to the original English page

Back to Top

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.