建立一个使用.Net 2.0 MemberShip功能的标准例程(三)——绑定访问篇


经过上一章的例子  我们已经建立了一个标准的,有很多有趣(甚至有些是专业级)功能的登陆系统了。
可是我们如何管理这个系统呢?难道我们要用m$提供的asp.net管理工具管理一辈子么?

——当然不!那太可怕了!T_T

——我们要自己写一个后台,一个可以根据用户权限自己修改的后台!@_@

当然有一种数据库狂人,他们只冷冷的瞥了几眼m$提供的数据库结构,轻描淡写的破译了其中所有的奥妙之处,随手拖了5-6个grid 写了10多行SQL 就用数据库方式搞定了。对于这种高手,我们仰慕,我们恨不得马上吸光他的百年功力,然后杀之后快,NND.

但是成为这样的高手需要非常的经验和手腕。我们这些小菜鸟,没有写轮眼,也不是圣斗士,所谓“看穿”技能在我们的身上是不能工作的。我们只有membership标准对象  profile标准对象  和roles标准对象。

难道就不能很方便的通过绑定方式访问这些对象么?





通过页面访问较为复杂的对象——在.net 1.x 的时代——对我们曾是一种煎熬。明明好多对象有着数据行的特性,为什么不能直接访问呢?于是好多人---包括我,尝试过各种办法。我是失败那批5555,也有很多的人成功了,研究出一些很有效的办法。可是这个状况没有持续多久——自从.net 2.0推出了ODS ,我的失败阴影就再也不复回来~~~




1     用ODS绑定MemberShip的总体思想

如图所示
       MembershipODS.png


从战略上 我们把每个用户看成一个行,把Membership中的GetAllUsers ()看成一个Select语句。
但是一个标准的System.Web.Security.MembershipUser并不具有数据绑定对象的特性 
比如主键/只读等信息所以我们可以重写它为它添加上这些特性

2  简单的绑定方法
这里采用的是MSDN上的部分c#代码修改成的VB代码  顺便我也把版权信息粘贴上来
None.gif ' /*
None.gif'
Copyright ?2005, Peter Kellner
None.gif'
All rights reserved.
None.gif'
http://peterkellner.net
None.gif

None.gif
' Redistribution and use in source and binary forms, with or without
None.gif'
modification, are permitted provided that the following conditions
None.gif'
are met:
None.gif

None.gif
' - Redistributions of source code must retain the above copyright
None.gif'
notice, this list of conditions and the following disclaimer.
None.gif

None.gif
' - Neither Peter Kellner, nor the names of its
None.gif'
contributors may be used to endorse or promote products
None.gif'
derived from this software without specific prior written 
None.gif'
permission. 
None.gif

None.gif
' THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
None.gif'
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
None.gif'
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
None.gif'
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE 
None.gif'
COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
None.gif'
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES INCLUDING,
None.gif'
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 
None.gif'
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER 
None.gif'
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 
None.gif'
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN 
None.gif'
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
None.gif'
POSSIBILITY OF SUCH DAMAGE.
None.gif'
*/
None.gif

None.gif
None.gif
Imports  System
None.gif
Imports  System.Data
None.gif
Imports  System.Configuration
None.gif
Imports  System.Web
None.gif
Imports  System.Web.Security
None.gif
Imports  System.Web.UI
None.gif
Imports  System.Web.UI.WebControls
None.gif
Imports  System.Web.UI.WebControls.WebParts
None.gif
Imports  System.Web.UI.HtmlControls
None.gif
Imports  System.Collections.Generic
None.gif
Imports  System.ComponentModel
None.gif
None.gif _
None.gif
None.gif
None.gif
None.gif
' / <summary>
None.gif'
/ Summary description for MembershipUserWrapper
None.gif'
/ This class is inherited from MembershipUser 
None.gif'
/ Using the sytax public class ClassName (..) : base(initializersdot.gif) allows for calling the
None.gif'
/ contstructor of the base class.  In this case MembershipUser.
None.gif'
/ </summary>
None.gif'

None.gif

ExpandedBlockStart.gifContractedBlock.gif
Namespace Membership_Tool Namespace Membership_Tool
InBlock.gif
InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif    
Public Class MembershipUserWrapperClass MembershipUserWrapper
InBlock.gif        
Inherits MembershipUser
InBlock.gif
InBlock.gif
InBlock.gif        
'/ <summary>
InBlock.gif
        '/ This constructor is used to create a MembershipUserWrapper from a MembershipUser object.  MembershipUser is a default type used
InBlock.gif
        '/ in the Membership API provided with ASP.NET 2.0
InBlock.gif
        '/ </summary>
InBlock.gif
        '/ <param name="mu">MembershipUser object</param>
ExpandedSubBlockStart.gifContractedSubBlock.gif
        Public Sub New()Sub New(ByVal mu As MembershipUser)
InBlock.gif            
MyBase.New(mu.ProviderName, mu.UserName, mu.ProviderUserKey, mu.Email, mu.PasswordQuestion, mu.Comment, mu.IsApproved, mu.IsLockedOut, mu.CreationDate, mu.LastLoginDate, mu.LastActivityDate, mu.LastPasswordChangedDate, mu.LastLockoutDate)
ExpandedSubBlockEnd.gif        
End Sub
 'New<DataObjectField(True)>  _
InBlock.gif

InBlock.gif
InBlock.gif
InBlock.gif        
'/ <summary>
InBlock.gif
        '/ This calls the base class UserName property.  It is here so we can tag
InBlock.gif
        '/ this property as the primary key so that datakeynames attribute gets set in the data control.
InBlock.gif
        '/ </summary>
InBlock.gif
        '
InBlock.gif
        <DataObjectField(True)> _
ExpandedSubBlockStart.gifContractedSubBlock.gif        
Public Overrides ReadOnly Property UserName()Property UserName() As String
InBlock.gif            
Get
InBlock.gif                
Return MyBase.UserName
InBlock.gif            
End Get
ExpandedSubBlockEnd.gif        
End Property

InBlock.gif
InBlock.gif
InBlock.gif
InBlock.gif        
'/ <summary>
InBlock.gif
        '/ This constructor is used to create a MembershipUserWrapper from individual parameters values.  
InBlock.gif
        '/ For details of what each parameter means, see the Microsoft Membership class.
InBlock.gif
        '/ </summary>
InBlock.gif
        '/ <param name="comment">Passes to MembershipUser.comment</param>
InBlock.gif
        '/ <param name="creationDate">Passes to MembershipUser.creationDate</param>
InBlock.gif
        '/ <param name="email">Passes to MembershipUser.email</param>
InBlock.gif
        '/ <param name="isApproved">Passes to MembershipUser.isApproved</param>
InBlock.gif
        '/ <param name="lastActivityDate">Passes to MembershipUser.lastActivityDate</param>
InBlock.gif
        '/ <param name="lastLoginDate">Passes to MembershipUser.lastLoginDate</param>
InBlock.gif
        '/ <param name="passwordQuestion">Passes to MembershipUser.passwordQuestion</param>
InBlock.gif
        '/ <param name="providerUserKey">Passes to MembershipUser.providerUserKey</param>
InBlock.gif
        '/ <param name="userName">Passes to MembershipUser.userName</param>
InBlock.gif
        '/ <param name="lastLockoutDate">Passes to MembershipUser.lastLockoutDate</param>
InBlock.gif
        '/ <param name="providerName">Passes to MembershipUser.providerName</param>
InBlock.gif
        '
ExpandedSubBlockStart.gifContractedSubBlock.gif
        Public Sub New()Sub New(ByVal comment As StringByVal creationDate As DateTime, ByVal email As StringByVal isApproved As BooleanByVal lastActivityDate As DateTime, ByVal lastLoginDate As DateTime, ByVal passwordQuestion As StringByVal providerUserKey As ObjectByVal userName As StringByVal lastLockoutDate As DateTime, ByVal providerName As String)
InBlock.gif            
MyBase.New(providerName, userName, providerUserKey, email, passwordQuestion, comment, isApproved, False, creationDate, lastLoginDate, lastActivityDate, DateTime.Now, lastLockoutDate)
ExpandedSubBlockEnd.gif        
End Sub
 'New
ExpandedSubBlockEnd.gif
    End Class
 'MembershipUserWrapper
InBlock.gif
    ' This calls a constructor of MembershipUser automatically because of the base reference above
InBlock.gif

ExpandedBlockEnd.gif
End Namespace

这样MembershipUser  的Username  被标记成 只读/主键 在绑定的时候  GridView会识别这一说明生成相应的编辑模式模板。






数据行已经被我们建立好了,那么数据从哪里来呢?我们建立一个新类MembershipUserODS 把提供我们的数据的方法集中在这个类中,它就能起到Dataadepter的作用。
None.gif      < DataObject( True ) >  _
ExpandedBlockStart.gifContractedBlock.gif    
Public   Class MembershipUserODS Class MembershipUserODS
InBlock.gif
ExpandedBlockEnd.gif    
End Class

其中加入如下方法来实现数据的读取,也就是Select操作:
None.gif      < DataObjectMethod(DataObjectMethodType.Select,  False ) >   Public   Shared  _
ExpandedBlockStart.gifContractedBlock.gif
Function GetMembers() Function GetMembers(ByVal returnAllApprovedUsers As BooleanByVal returnAllNotApprovedUsers As BooleanByVal usernameToFind As StringAs List(Of MembershipUserWrapper)
InBlock.gif
InBlock.gif
InBlock.gif
InBlock.gif
InBlock.gif            
Dim memberList As New List(Of MembershipUserWrapper)
InBlock.gif
InBlock.gif
InBlock.gif            
'看看是否只需要返回某个特定的用户
InBlock.gif
            If Not (usernameToFind Is NothingThen
InBlock.gif                
'           {
InBlock.gif
                Dim mu As MembershipUser = Membership.GetUser(usernameToFind)
InBlock.gif                
If Not mu Is Nothing Then
InBlock.gif
InBlock.gif
InBlock.gif
InBlock.gif                    
Dim md As MembershipUserWrapper = New MembershipUserWrapper(mu)
InBlock.gif                    memberList.Add(md)
InBlock.gif                
End If
InBlock.gif
InBlock.gif            
Else
InBlock.gif
InBlock.gif                
Dim muc As MembershipUserCollection = Membership.GetAllUsers()
InBlock.gif                
Dim mu As MembershipUser
InBlock.gif                
For Each mu In muc
InBlock.gif                    
If returnAllApprovedUsers = True And mu.IsApproved = True Or (returnAllNotApprovedUsers = True And mu.IsApproved = FalseThen
InBlock.gif                        
Dim md As New MembershipUserWrapper(mu)
InBlock.gif                        memberList.Add(md)
InBlock.gif                    
End If
InBlock.gif                
Next mu
InBlock.gif       
return  memberList
ExpandedBlockEnd.gif
end Function

(在随后的源代码包里面有排序的功能 大家参考下就好)

这时候我们已经可以对 MembershipUserODS   进行数据绑定了----这个方法实现了数据绑定的最基础的动作:选择。

利用同样的方式  我们建立对应 插入、更新和删除操作的 方法:
插入:
None.gif   < DataObjectMethod(DataObjectMethodType.Insert,  True ) >   Public   Shared  _
ExpandedBlockStart.gifContractedBlock.gif    
Sub Insert() Sub Insert(ByVal userName As StringByVal isApproved As BooleanByVal comment As StringByVal lastLockoutDate As DateTime, ByVal creationDate As DateTime, ByVal email As StringByVal lastActivityDate As DateTime, ByVal providerName As StringByVal isLockedOut As BooleanByVal lastLoginDate As DateTime, ByVal isOnline As BooleanByVal passwordQuestion As StringByVal lastPasswordChangedDate As DateTime, ByVal password As StringByVal passwordAnswer As String)
InBlock.gif
InBlock.gif
InBlock.gif            
' The incoming parameters, password and passwordAnswer are not properties of the
InBlock.gif
            ' MembershipUser class.  Membership has special member functions to deal with these
InBlock.gif
            ' two special properties for security reasons.  For this reason, they do not appear
InBlock.gif
            ' in a datacontrol that is created with this user object.  
InBlock.gif
            '
InBlock.gif
            ' the only reason you may want to have defaults is so you can build insert into your
InBlock.gif
            ' datacontrol.  A better approach would be to either follow the example shown in the
InBlock.gif
            ' Membership.asp page where the parameters are set directly to the userobject, or not
InBlock.gif
            ' include "new" at all in your control and use the other controls in the Membership API
InBlock.gif
            ' for creating new members.  (CreateUserWizard, etc)
InBlock.gif
            '
InBlock.gif
            ' It is recommended that you only enable the following lines if you are sure of what you are doing
InBlock.gif
            'if (password == null)
InBlock.gif
            '{
InBlock.gif
            '    password = "pass0word";
InBlock.gif
            '}
InBlock.gif
            'if (passwordAnswer == null)
InBlock.gif
            '{
InBlock.gif
            '    passwordAnswer = "Password Answer";
InBlock.gif
            '}
InBlock.gif

InBlock.gif
InBlock.gif            
Dim status As MembershipCreateStatus
InBlock.gif            Membership.CreateUser(userName, password, email, passwordQuestion, passwordAnswer, isApproved, status)
InBlock.gif
InBlock.gif            
If status <> MembershipCreateStatus.Success Then
InBlock.gif                
Throw New ApplicationException(status.ToString())
InBlock.gif            
End If
InBlock.gif
InBlock.gif            
Dim mu As MembershipUser = Membership.GetUser(userName)
InBlock.gif            mu.Comment 
= comment
InBlock.gif            Membership.UpdateUser(mu)
ExpandedBlockEnd.gif        
End Sub
 

更新:
None.gif     < DataObjectMethod(DataObjectMethodType.Update,  True ) >   Public   Shared  _
ExpandedBlockStart.gifContractedBlock.gif    
Sub Update() Sub Update(ByVal UserName As StringByVal email As StringByVal isApproved As BooleanByVal comment As StringByVal lastActivityDate As DateTime, ByVal lastLoginDate As DateTime)
InBlock.gif            
Dim dirtyFlag As Boolean = False
InBlock.gif
InBlock.gif            
Dim mu As MembershipUser = Membership.GetUser(UserName)
InBlock.gif
InBlock.gif            
If mu.Comment Is Nothing Or (mu.Comment & "").CompareTo(comment) <> 0 Then
InBlock.gif                dirtyFlag 
= True
InBlock.gif                mu.Comment 
= comment
InBlock.gif            
End If
InBlock.gif
InBlock.gif            
If mu.Email Is Nothing Or (mu.Email & "").CompareTo(email) <> 0 Then
InBlock.gif                dirtyFlag 
= True
InBlock.gif                mu.Email 
= email
InBlock.gif            
End If
InBlock.gif
InBlock.gif            
If mu.IsApproved <> isApproved Then
InBlock.gif                dirtyFlag 
= True
InBlock.gif                mu.IsApproved 
= isApproved
InBlock.gif            
End If
InBlock.gif
InBlock.gif            
If dirtyFlag = True Then
InBlock.gif                Membership.UpdateUser(mu)
InBlock.gif            
End If
ExpandedBlockEnd.gif        
End Sub
 

删除:
None.gif       < DataObjectMethod(DataObjectMethodType.Delete,  True ) >   Public   Shared  _
ExpandedBlockStart.gifContractedBlock.gif    
Sub Delete() Sub Delete(ByVal UserName As String)
InBlock.gif            Membership.DeleteUser(UserName, 
True)
ExpandedBlockEnd.gif        
End Sub


以上的工作,我们在ODS和membership之间  建立了一条桥梁,通过我们的代码,membership 复杂的对象被我们用简单的数据属性所代理,而能够被ODS正确识别

下面我们简单的试验下我们工作的成果,亲手绑定一下。



建立一个新页面Default.aspx  在上面放置一个GridView和一个ODS控件。
效果如下图示:
MembershipTestPage1.PNG

选择“配置数据源”,你刚才建立的、带有<DataObject>声明的类便会被枚举出来:
MembershipTestPage2.png

下一步 选择每种动作的对应方法:

MembershipTestPage3.png

当你把4种基本动作全部配置完毕  ,在属性栏把ObjectDataSource1.OldValuesParameterFormatString 的内容设置为{0}  就可以绑定了:

MembershipTestPageok.png


基本上不会出现什么错误拉。。。。
 

同样的方式   你可以用如下的代码建立Roles和Profile 的绑定


Roles
None.gif ' /*
None.gif'
Copyright ?2005, Peter Kellner
None.gif'
All rights reserved.
None.gif'
http://peterkellner.net
None.gif

None.gif
' Redistribution and use in source and binary forms, with or without
None.gif'
modification, are permitted provided that the following conditions
None.gif'
are met:
None.gif

None.gif
' - Redistributions of source code must retain the above copyright
None.gif'
notice, this list of conditions and the following disclaimer.
None.gif

None.gif
' - Neither Peter Kellner, nor the names of its
None.gif'
contributors may be used to endorse or promote products
None.gif'
derived from this software without specific prior written 
None.gif'
permission. 
None.gif

None.gif
' THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
None.gif'
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
None.gif'
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
None.gif'
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE 
None.gif'
COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
None.gif'
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES INCLUDING,
None.gif'
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 
None.gif'
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER 
None.gif'
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 
None.gif'
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN 
None.gif'
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
None.gif'
POSSIBILITY OF SUCH DAMAGE.
None.gif'
*/
None.gif

None.gif
None.gif
Imports  System
None.gif
Imports  System.Data
None.gif
Imports  System.Configuration
None.gif
Imports  System.Web
None.gif
Imports  System.Web.Security
None.gif
Imports  System.Web.UI
None.gif
Imports  System.Web.UI.WebControls
None.gif
Imports  System.Web.UI.WebControls.WebParts
None.gif
Imports  System.Web.UI.HtmlControls
None.gif
Imports  System.Collections.Generic
None.gif
Imports  System.ComponentModel
None.gif
Imports  System.Collections.ObjectModel
None.gif
ExpandedBlockStart.gifContractedBlock.gif
Namespace Membership_Tool Namespace Membership_Tool
InBlock.gif
InBlock.gif
InBlock.gif
InBlock.gif    
'/ <summary>
InBlock.gif
    '/ A class used to encapsulate the Roles in ASP.NET Membermanagement 2.0
InBlock.gif
    '/ </summary>
InBlock.gif
    <DataObject(True)> _
ExpandedSubBlockStart.gifContractedSubBlock.gif    
Public Class RoleDataODSClass RoleDataODS
InBlock.gif        
' This attribute allows the 
InBlock.gif

InBlock.gif        
'/ <summary>
InBlock.gif
        '/ Used to get all roles available
InBlock.gif
        '/ </summary>
InBlock.gif
        '/ <returns></returns>
InBlock.gif
        '
InBlock.gif
        <DataObjectMethod(DataObjectMethodType.Select, True)> Public Overloads Shared _
ExpandedSubBlockStart.gifContractedSubBlock.gif       
Function GetRoles()Function GetRoles() As List(Of RoleData)
InBlock.gif            
Return GetRoles(NothingFalse)
ExpandedSubBlockEnd.gif        
End Function
 'GetRoles
InBlock.gif

InBlock.gif
InBlock.gif        
'/ <summary>
InBlock.gif
        '/ Returns a collection of RoleData type values.  This specialized constructor lets you request by
InBlock.gif
        '/ an individual user
InBlock.gif
        '/ </summary>
InBlock.gif
        '/ <param name="userName">if null and showOnlyAssignedRolls==false, display all roles</param>
InBlock.gif
        '/ <param name="showOnlyAssignedRolls">if true, just show assigned roles</param>
InBlock.gif
        '/ <returns></returns>
InBlock.gif
        <DataObjectMethod(DataObjectMethodType.Select, False)> Public Overloads Shared _
ExpandedSubBlockStart.gifContractedSubBlock.gif       
Function GetRoles()Function GetRoles(ByVal userName As StringByVal showOnlyAssignedRolls As BooleanAs List(Of RoleData)
InBlock.gif            
Dim roleList As New List(Of RoleData)
InBlock.gif
InBlock.gif            
Dim roleListStr As String() = Roles.GetAllRoles()
InBlock.gif            
Dim roleName As String
InBlock.gif            
For Each roleName In roleListStr
InBlock.gif                
Dim userInRole As Boolean = False
InBlock.gif                
' First, figure out if user is in role (if there is a user)
InBlock.gif
                If Not (userName Is NothingThen
InBlock.gif                    userInRole 
= Roles.IsUserInRole(userName, roleName)
InBlock.gif                
End If
InBlock.gif
InBlock.gif                
If showOnlyAssignedRolls = False Or userInRole = True Then
InBlock.gif                    
' Getting usersInRole is only used for the count below
InBlock.gif
                    Dim usersInRole As String() = Roles.GetUsersInRole(roleName)
InBlock.gif                    
Dim rd As New RoleData()
InBlock.gif                    rd.RoleName 
= roleName
InBlock.gif                    rd.UserName 
= userName
InBlock.gif                    rd.UserInRole 
= userInRole
InBlock.gif                    rd.NumberOfUsersInRole 
= usersInRole.Length
InBlock.gif                    roleList.Add(rd)
InBlock.gif                
End If
InBlock.gif            
Next roleName
InBlock.gif
InBlock.gif            
' FxCopy will give us a warning about returning a List rather than a Collection.
InBlock.gif
            ' We could copy the data, but not worth the trouble.
InBlock.gif
            Return roleList
ExpandedSubBlockEnd.gif        
End Function
 'GetRoles
InBlock.gif

InBlock.gif
InBlock.gif        
'/ <summary>
InBlock.gif
        '/ Used for Inserting a new role.  Doesn't associate a user with a role.
InBlock.gif
        '/ This is not quite consistent with this object, but really what we want.
InBlock.gif
        '/ </summary>
InBlock.gif
        '/ <param name="RoleName">The Name of the role to insert</param>
InBlock.gif
        <DataObjectMethod(DataObjectMethodType.Insert, True)> Public Shared _
ExpandedSubBlockStart.gifContractedSubBlock.gif       
Sub Insert()Sub Insert(ByVal roleName As String)
InBlock.gif            
If Roles.RoleExists(roleName) = False Then
InBlock.gif                Roles.CreateRole(roleName)
InBlock.gif            
End If
ExpandedSubBlockEnd.gif        
End Sub
 'Insert
InBlock.gif

InBlock.gif
InBlock.gif        
'/ <summary>
InBlock.gif
        '/ Delete any given role while first removing any roles associated with existing users
InBlock.gif
        '/ </summary>
InBlock.gif
        '/ <param name="roleName">name of role to delete</param>
InBlock.gif
        <DataObjectMethod(DataObjectMethodType.Delete, True)> Public Shared _
ExpandedSubBlockStart.gifContractedSubBlock.gif       
Sub Delete()Sub Delete(ByVal roleName As String)
InBlock.gif            
' remove this role from all users.  not sure if deleterole does this automagically
InBlock.gif
            Dim muc As MembershipUserCollection = Membership.GetAllUsers()
InBlock.gif            
Dim allUserNames(1As String
InBlock.gif
InBlock.gif            
Dim mu As MembershipUser
InBlock.gif            
For Each mu In muc
InBlock.gif                
If Roles.IsUserInRole(mu.UserName, roleName) = True Then
InBlock.gif                    allUserNames(
0= mu.UserName
InBlock.gif                    Roles.RemoveUsersFromRole(allUserNames, roleName)
InBlock.gif                
End If
InBlock.gif            
Next mu
InBlock.gif            Roles.DeleteRole(roleName)
ExpandedSubBlockEnd.gif        
End Sub
 'Delete
ExpandedSubBlockEnd.gif
    End Class
 'RoleDataObject
InBlock.gif

InBlock.gif    
'/ <summary>
InBlock.gif
    '/ Dataobject class used as a base for the collection
InBlock.gif
    '/ </summary>
ExpandedSubBlockStart.gifContractedSubBlock.gif
    Public Class RoleDataClass RoleData
InBlock.gif
InBlock.gif        
' Non normalized column which counts current number of users in a role
InBlock.gif
        Private number_OfUsersInRole As Integer
InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
Public Property NumberOfUsersInRole()Property NumberOfUsersInRole() As Integer
InBlock.gif            
Get
InBlock.gif                
Return number_OfUsersInRole
InBlock.gif            
End Get
InBlock.gif            
Set(ByVal value As Integer)
InBlock.gif                number_OfUsersInRole 
= value
InBlock.gif            
End Set
ExpandedSubBlockEnd.gif        
End Property

InBlock.gif        
Private role_Name As String
InBlock.gif
InBlock.gif        
<DataObjectField(True)> _
ExpandedSubBlockStart.gifContractedSubBlock.gif        
Public Property RoleName()Property RoleName() As String
InBlock.gif            
Get
InBlock.gif                
Return role_Name
InBlock.gif            
End Get
InBlock.gif            
Set(ByVal value As String)
InBlock.gif                role_Name 
= value
InBlock.gif            
End Set
ExpandedSubBlockEnd.gif        
End Property

InBlock.gif        
Public user_Name As String
InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
Public Property UserName()Property UserName() As String
InBlock.gif            
Get
InBlock.gif                
Return user_Name
InBlock.gif            
End Get
InBlock.gif            
Set(ByVal value As String)
InBlock.gif                user_Name 
= value
InBlock.gif            
End Set
ExpandedSubBlockEnd.gif        
End Property

InBlock.gif        
Private user_InRole As Boolean
InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
Public Property UserInRole()Property UserInRole() As Boolean
InBlock.gif            
Get
InBlock.gif                
Return user_InRole
InBlock.gif            
End Get
InBlock.gif            
Set(ByVal value As Boolean)
InBlock.gif                user_InRole 
= value
InBlock.gif            
End Set
ExpandedSubBlockEnd.gif        
End Property

ExpandedSubBlockEnd.gif    
End Class
 'RoleData
ExpandedBlockEnd.gif
End Namespace

Profile
None.gif Imports  System
None.gif
Imports  System.Data
None.gif
Imports  System.Configuration
None.gif
Imports  System.Web
None.gif
Imports  System.Web.Security
None.gif
Imports  System.Web.UI
None.gif
Imports  System.Web.UI.WebControls
None.gif
Imports  System.Web.UI.WebControls.WebParts
None.gif
Imports  System.Web.UI.HtmlControls
None.gif
Imports  System.Collections.Generic
None.gif
Imports  System.ComponentModel
ExpandedBlockStart.gifContractedBlock.gif
Namespace Membership_Tool Namespace Membership_Tool
InBlock.gif    
<DataObject(True)> _
ExpandedSubBlockStart.gifContractedSubBlock.gif    
Public Class ProfileODSClass ProfileODS
InBlock.gif        
<DataObjectMethod(DataObjectMethodType.Select, False)> _
ExpandedSubBlockStart.gifContractedSubBlock.gif        
Public Function GetUserProfile()Function GetUserProfile(ByVal UserName As StringAs List(Of ProfileEntry)
InBlock.gif            
Return GetUserProfile(UserName, Nothing)
InBlock.gif
InBlock.gif
ExpandedSubBlockEnd.gif        
End Function

InBlock.gif
InBlock.gif
InBlock.gif        
<DataObjectMethod(DataObjectMethodType.Select, False)> _
ExpandedSubBlockStart.gifContractedSubBlock.gif    
Public Function GetUserProfile()Function GetUserProfile(ByVal UserName As StringByVal PropertyNames As StringAs List(Of ProfileEntry)
InBlock.gif
InBlock.gif            
Dim doFilter As Boolean = False
InBlock.gif            
Dim PNames As String() = Nothing
InBlock.gif            
If PropertyNames Is Nothing Then
InBlock.gif            
ElseIf PropertyNames = "" Then
InBlock.gif            
Else
InBlock.gif                PNames 
= PropertyNames.Split("|")
InBlock.gif                doFilter 
= True
InBlock.gif            
End If
InBlock.gif
InBlock.gif            
Dim pelist As New List(Of ProfileEntry)
InBlock.gif            
Dim pf As Profile.ProfileBase = System.Web.Profile.ProfileBase.Create(UserName)
InBlock.gif            
'因为PrifileCommon的一个未知bug 在没有访问任何已知属性前,属性的集合将不可访问,所以需要一个缺省的属性来支持
InBlock.gif
            '以下为试图访问默认的属性bugjumper来获得属性集合
InBlock.gif
            Try
InBlock.gif                
Dim x As String = pf.GetPropertyValue("bugjumper")
InBlock.gif            
Catch ex As Exception
InBlock.gif                
'  Throw New Exception("管理员并没有为profilecommon的bug设置默认的属性参数bugjumper")
InBlock.gif
            End Try
InBlock.gif            
'处理bug过程结束
InBlock.gif

InBlock.gif
InBlock.gif            
For Each itm As System.Configuration.SettingsPropertyValue In pf.PropertyValues
InBlock.gif
InBlock.gif                
If itm.Name <> "bugjumper" Then '忽略处理bug用的公共属性
InBlock.gif
                    Dim doAdd As Boolean = False
InBlock.gif                    
If Not doFilter Then
InBlock.gif                        doAdd 
= True
InBlock.gif                    
ElseIf Array.IndexOf(PNames, itm.Name) <> -1 Then
InBlock.gif                        doAdd 
= True
InBlock.gif
InBlock.gif                    
End If
InBlock.gif                    
If doAdd Then
InBlock.gif                        
Dim pe As New ProfileEntry(UserName, itm.Name, itm.PropertyValue)
InBlock.gif                        pelist.Add(pe)
InBlock.gif                    
End If
InBlock.gif               
InBlock.gif                
End If
InBlock.gif
InBlock.gif
InBlock.gif            
Next
InBlock.gif
InBlock.gif
InBlock.gif
InBlock.gif
InBlock.gif            
Return pelist
InBlock.gif
ExpandedSubBlockEnd.gif        
End Function

InBlock.gif        
<DataObjectMethod(DataObjectMethodType.Update, False)> _
ExpandedSubBlockStart.gifContractedSubBlock.gif        
Public Sub UpdateUserProfile()Sub UpdateUserProfile(ByVal UserName As StringByVal Key As StringByVal Value As String)
InBlock.gif            
Dim pf As Profile.ProfileBase = System.Web.Profile.ProfileBase.Create(UserName)
InBlock.gif            pf.SetPropertyValue(Key, Value)
InBlock.gif            pf.Save()
ExpandedSubBlockEnd.gif        
End Sub

ExpandedSubBlockEnd.gif    
End Class

InBlock.gif
InBlock.gif
InBlock.gif
InBlock.gif
InBlock.gif
InBlock.gif
InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif    
Public Class ProfileEntryClass ProfileEntry
InBlock.gif        
Private k, v As String
InBlock.gif        
Private U As String
InBlock.gif        
<DataObjectField(True)> _
ExpandedSubBlockStart.gifContractedSubBlock.gif   
Property Key()Property Key() As String
InBlock.gif            
Get
InBlock.gif                
Return k
InBlock.gif            
End Get
InBlock.gif            
Set(ByVal value As String)
InBlock.gif                k 
= value
InBlock.gif            
End Set
ExpandedSubBlockEnd.gif        
End Property

InBlock.gif
InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
Property Value()Property Value() As String
InBlock.gif            
Get
InBlock.gif                
Return v
InBlock.gif            
End Get
InBlock.gif            
Set(ByVal value As String)
InBlock.gif                v 
= value
InBlock.gif            
End Set
ExpandedSubBlockEnd.gif        
End Property

InBlock.gif
InBlock.gif        
<DataObjectField(True)> _
ExpandedSubBlockStart.gifContractedSubBlock.gif        
Property UserName()Property UserName() As String
InBlock.gif            
Get
InBlock.gif                
Return U
InBlock.gif            
End Get
InBlock.gif            
Set(ByVal value As String)
InBlock.gif                U 
= value
InBlock.gif            
End Set
ExpandedSubBlockEnd.gif        
End Property

ExpandedSubBlockStart.gifContractedSubBlock.gif        
Sub New()Sub New(ByVal NewUserName As StringByVal NewKey As StringByVal NewValue As String)
InBlock.gif            
Me.UserName = NewUserName
InBlock.gif            
Me.Key = NewKey
InBlock.gif            
Me.Value = NewValue
ExpandedSubBlockEnd.gif        
End Sub

ExpandedSubBlockEnd.gif    
End Class

InBlock.gif
InBlock.gif
ExpandedBlockEnd.gif
End Namespace

ProFile可是我自己写的阿^_^

这里发现了一个bug,由vs2005 生成的profilecommon类 在第一次成功访问某属性前,Properties集合不会正确的枚举出所有成员,所以我在程序中作了一些小小的调整,具体请看示例工程:DDDD
 
下载地址  C#核心代码
-------------------------------
终于填完了  连续睡眠不足词不达意  回头再作修改555555

转载于:https://www.cnblogs.com/waynebaby/archive/2006/12/18/591882.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值