Community Server专题八:MemberRole之Membership

 

Community Server专题八:MemberRoleMembership<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />

 

MemberRole是一个在asp.net 1.1下实现用户管理、角色管理、用户特性信息存储(profile)等的一个组件,该组件被ASP.NET 2.0 Beta 2所采用,也就是ASP.NET 2.0 Beta 2中所说的Membership and Roles。如果你在asp.net 1.1下采用了MemberRole,那么你的web程序将会很容易的过渡到asp.net 2.0,另外多个采取MemberRole进行用户管理的web程序需要整合时也非常容易。我将分4个专题来分析MemberRole,探索一下MemberRole到底是如何工作的,无论对CS的构架还是对了解asp.net 2.0都是非常有帮助的。

CS中,运用该组件的4个部分:membershiproleManagerprofileanonymousIdentification的运用(整个MemberRole也这四部分功能)

在分析前,准备需要一个工具:Reflector.exe,没有的朋友google一下,下载它。

本次专题分析membership,先看一下CSMembership的配置文件(Web.Config)

None.gif < membership  userIsOnlineTimeWindow ="15"   >
None.gif
None.gif              
< providers >
None.gif
None.gif                   
< add 
None.gif
None.gif                       
name ="CommunityServerSqlProvider"               
None.gif
None.gif                       type
="Openlab.AutoRegister.CSAutoBlogGalleryMembershipProvider, Openlab.CSAddOns"
None.gif
None.gif                       connectionStringName
="SiteSqlServer"
None.gif
None.gif                       enablePasswordRetrieval
="false"
None.gif
None.gif                       enablePasswordReset
="true"
None.gif
None.gif                       requiresQuestionAndAnswer
="false"
None.gif
None.gif                       requiresUniqueEmail
="true"
None.gif
None.gif                       passwordFormat
="Hashed"
None.gif
None.gif                       applicationName
="dev"
None.gif
None.gif                       description
="Stores and retrieves membership data from the local Microsoft SQL Server database"
None.gif
None.gif                       autoCreateBlog
="false"
None.gif
None.gif                       defaultBlogGroupID
="3"
None.gif
None.gif                       autoCreateGallery
="false"
None.gif
None.gif                       defaultGalleryGroupID
="2"
None.gif
None.gif                       maxInvalidPasswordAttempts 
= "999"
None.gif
None.gif                       passwordAttemptWindow 
= "999"
None.gif
None.gif                       minRequiredPasswordLength 
= "4"
None.gif
None.gif                       minRequiredNonalphanumericCharacters 
= "0"
None.gif
None.gif                   
/>
None.gif
None.gif              
</ providers >
None.gif
None.gif
</ membership >
None.gif

userIsOnlineTimeWindow

:这是一个数值,用来计算在线用户的数量,例如: 15 ,就表示如果用户在 15 分钟后不活动 ( 发出 Http 请求 )CS 系统将视该用户不在线。

Name:名称

type:类的名字空间与所在的程序集合

connectionStringName:数据库连接字符串节点的key。通过这个key就可以找到连接数据库的用户名与密码

enablePasswordRetrieval:是否打开取回秘密功能

enablePasswordReset:是否打开秘密重新设功能

requiresQuestionAndAnswer:注册时是否需要填写QuestionAnswer

requiresUniqueEmail:注册时是否Email唯一

passwordFormat:密码的加密格式

applicationName:使用该membership应用程序的名称

description:描述信息

 

以下4个参数是CCS中添加的,目的是给注册用户自动开通相册和博客

autoCreateBlog:是否当用户注册时自动为该用户建立一个Blog

defaultBlogGroupID:默认的建立blog的分组ID

autoCreateGallery:是否当用户注册时自动为该用户建立一个相册

defaultGalleryGroupID:默认的建立相册的分组ID

 

Reflector.exe打开MemberRole.dll,你可以看到以下的内容:

<?xml:namespace prefix = v ns = "urn:schemas-microsoft-com:vml" />%7B71D68E35-BC68-4C5F-898E-5F6AD12D9B17%7D0.jpg

再打开Microsoft.ScalableHosting.Configuration节点

%7B351C0A5E-87AB-461B-99EC-A23607266CE3%7D0.jpg

这次我们只关注两个类MembershipConfigMembershipConfigHandlerMembershipConfigHandler实现了IConfigurationSectionHandler接口。也就是说,CS启动后如果调用ConfigurationSettings.GetConfig("memberrolesprototype/membership"),系统将会自动的调用MembershipConfigHandler中的Create方法把web.configmemberrolesprototype/membership的配置内容读入进行处理。先看以下Create做了些什么:

None.gif public   virtual   object  Create( object  parent,  object  configContextObj, XmlNode section)
ExpandedBlockStart.gifContractedBlock.gif
dot.gif {
InBlock.gif      MembershipConfig config1 
= new MembershipConfig(parent as MembershipConfig);
InBlock.gif      
int num1 = -1;
InBlock.gif      ConfigUtils.GetAndRemovePositiveIntegerAttribute(section, 
"userIsOnlineTimeWindow"ref num1);
InBlock.gif      
if (num1 > 0)
ExpandedSubBlockStart.gifContractedSubBlock.gif      
dot.gif{
InBlock.gif            config1.UserIsOnlineTimeWindow 
= num1;
ExpandedSubBlockEnd.gif      }

InBlock.gif      
string text1 = null;
InBlock.gif      ConfigUtils.GetAndRemoveStringAttribute(section, 
"hashAlgorithm"ref text1);
InBlock.gif      
if ((text1 != null&& (text1.Length > 0))
ExpandedSubBlockStart.gifContractedSubBlock.gif      
dot.gif{
InBlock.gif            config1.HashAlgorithmType 
= text1;
ExpandedSubBlockEnd.gif      }

InBlock.gif      ConfigUtils.CheckForUnrecognizedAttributes(section);
InBlock.gif      MembershipProvider provider1 
= null;
InBlock.gif      
foreach (XmlNode node1 in section.ChildNodes)
ExpandedSubBlockStart.gifContractedSubBlock.gif      
dot.gif{
InBlock.gif            
if (node1.NodeType != XmlNodeType.Element)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                  
continue;
ExpandedSubBlockEnd.gif            }

InBlock.gif            
if (node1.Name != "providers")
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                  
throw new ConfigurationException("Unrecognized tag: " + node1.Name, node1);
ExpandedSubBlockEnd.gif            }

InBlock.gif            
foreach (XmlNode node2 in node1.ChildNodes)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                  
if (node2.NodeType == XmlNodeType.Element)
ExpandedSubBlockStart.gifContractedSubBlock.gif                  
dot.gif{
InBlock.gif                        
if (node2.Name != "add")
ExpandedSubBlockStart.gifContractedSubBlock.gif                        
dot.gif{
InBlock.gif                              
throw new ConfigurationException("Unrecognized tag: " + node2.Name, node2);
ExpandedSubBlockEnd.gif                        }

InBlock.gif                        
if (provider1 != null)
ExpandedSubBlockStart.gifContractedSubBlock.gif                        
dot.gif{
InBlock.gif                              
throw new ConfigurationException("Only one provider can be configured", node2);
ExpandedSubBlockEnd.gif                        }

InBlock.gif                        
string text2 = null;
InBlock.gif                        
string text3 = null;
InBlock.gif                        ConfigUtils.GetAndRemoveRequiredNonEmptyStringAttribute(node2, 
"name"ref text2);
InBlock.gif                        ConfigUtils.GetAndRemoveRequiredNonEmptyStringAttribute(node2, 
"type"ref text3);
InBlock.gif                        NameValueCollection collection1 
= new NameValueCollection();
InBlock.gif                        
foreach (XmlAttribute attribute1 in node2.Attributes)
ExpandedSubBlockStart.gifContractedSubBlock.gif                        
dot.gif{
InBlock.gif                              
if ((attribute1.Name != null&& (attribute1.Name.Length > 0))
ExpandedSubBlockStart.gifContractedSubBlock.gif                              
dot.gif{
InBlock.gif                                    collection1.Add(attribute1.Name, attribute1.Value);
ExpandedSubBlockEnd.gif                              }

ExpandedSubBlockEnd.gif                        }

InBlock.gif                        provider1 
= (MembershipProvider) Activator.CreateInstance(Type.GetType(text3, true));
InBlock.gif                        provider1.Initialize(text2, collection1);
InBlock.gif                        config1.Provider 
= provider1;
ExpandedSubBlockEnd.gif                  }

ExpandedSubBlockEnd.gif            }

ExpandedSubBlockEnd.gif      }

InBlock.gif      
return config1;
ExpandedBlockEnd.gif}

None.gif
None.gif

 

代码有点长,其实这里就是把web.config下面membership节点的配置信息读入,进行初始化,然后通过GetTypeActivator.CreateInstance方法反射后实例化一个MembershipProvider

MembershipProvider又是什么,继续看看:

None.gif public   abstract   class  MembershipProvider : ProviderBase
ExpandedBlockStart.gifContractedBlock.gif
dot.gif {
InBlock.gif      
// Events
InBlock.gif
      public event MembershipValidatePasswordEventHandler ValidatingPassword;
InBlock.gif 
InBlock.gif      
// Methods
InBlock.gif
      protected MembershipProvider();
InBlock.gif      
public abstract bool ChangePassword(string username, string oldPassword, string newPassword);
InBlock.gif      
public abstract bool ChangePasswordQuestionAndAnswer(string username, string password, string newPasswordQuestion, string newPasswordAnswer);
InBlock.gif      
public abstract MembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out MembershipCreateStatus status);
InBlock.gif      
protected virtual byte[] DecryptPassword(byte[] encodedPassword);
InBlock.gif      
public abstract bool DeleteUser(string username, bool deleteAllRelatedData);
InBlock.gif      
internal string EncodePassword(string pass, int passwordFormat, string salt);
InBlock.gif      
protected virtual byte[] EncryptPassword(byte[] password);
InBlock.gif      
public abstract MembershipUserCollection FindUsersByEmail(string emailToMatch, int pageIndex, int pageSize, out int totalRecords);
InBlock.gif      
public abstract MembershipUserCollection FindUsersByName(string usernameToMatch, int pageIndex, int pageSize, out int totalRecords);
InBlock.gif      
internal string GenerateSalt();
InBlock.gif      
public abstract MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords);
InBlock.gif      
public abstract int GetNumberOfUsersOnline();
InBlock.gif      
public abstract string GetPassword(string username, string answer);
InBlock.gif      
public abstract MembershipUser GetUser(object providerUserKey, bool userIsOnline);
InBlock.gif      
public abstract MembershipUser GetUser(string username, bool userIsOnline);
InBlock.gif      
public abstract string GetUserNameByEmail(string email);
InBlock.gif      
protected virtual void OnValidatingPassword(ValidatePasswordEventArgs e);
InBlock.gif      
public abstract string ResetPassword(string username, string answer);
InBlock.gif      
internal string UnEncodePassword(string pass, int passwordFormat);
InBlock.gif      
public abstract bool UnlockUser(string userName);
InBlock.gif      
public abstract void UpdateUser(MembershipUser user);
InBlock.gif      
public abstract bool ValidateUser(string username, string password);
InBlock.gif 
InBlock.gif      
// Properties
ExpandedSubBlockStart.gifContractedSubBlock.gif
      public abstract string ApplicationName dot.gifgetset; }
ExpandedSubBlockStart.gifContractedSubBlock.gif      
public abstract bool EnablePasswordReset dot.gifget; }
ExpandedSubBlockStart.gifContractedSubBlock.gif      
public abstract bool EnablePasswordRetrieval dot.gifget; }
ExpandedSubBlockStart.gifContractedSubBlock.gif      
public abstract int MaxInvalidPasswordAttempts dot.gifget; }
ExpandedSubBlockStart.gifContractedSubBlock.gif      
public abstract int MinRequiredNonAlphanumericCharacters dot.gifget; }
ExpandedSubBlockStart.gifContractedSubBlock.gif      
public abstract int MinRequiredPasswordLength dot.gifget; }
ExpandedSubBlockStart.gifContractedSubBlock.gif      
public abstract int PasswordAttemptWindow dot.gifget; }
ExpandedSubBlockStart.gifContractedSubBlock.gif      
public abstract MembershipPasswordFormat PasswordFormat dot.gifget; }
ExpandedSubBlockStart.gifContractedSubBlock.gif      
public abstract string PasswordStrengthRegularExpression dot.gifget; }
ExpandedSubBlockStart.gifContractedSubBlock.gif      
public abstract bool RequiresQuestionAndAnswer dot.gifget; }
ExpandedSubBlockStart.gifContractedSubBlock.gif      
public abstract bool RequiresUniqueEmail dot.gifget; }
InBlock.gif 
InBlock.gif      
// Fields
InBlock.gif
      private MembershipValidatePasswordEventHandler _EventHandler;
InBlock.gif      
private const int SALT_SIZE_IN_BYTES = 0x10;
ExpandedBlockEnd.gif}

None.gif

原来MembershipProvider是实现继承了ProviderBase的一个类,其实ProviderBase并没有什么,看看代码

None.gif public   abstract   class  ProviderBase
ExpandedBlockStart.gifContractedBlock.gif
dot.gif {
InBlock.gif      
// Methods
InBlock.gif
      protected ProviderBase();
InBlock.gif      
public virtual void Initialize(string name, NameValueCollection config);
InBlock.gif 
InBlock.gif      
// Properties
ExpandedSubBlockStart.gifContractedSubBlock.gif
      public virtual string Description dot.gifget; }
ExpandedSubBlockStart.gifContractedSubBlock.gif      
public virtual string Name dot.gifget; }
InBlock.gif 
InBlock.gif      
// Fields
InBlock.gif
      private string _Description;
InBlock.gif      
private bool _Initialized;
InBlock.gif      
private string _name;
ExpandedBlockEnd.gif}

None.gif
None.gif

ProviderBase仅仅只是保护了两个虚属性的类,设置这个类只是一种设计模式,没有特别的用途。我们把重点集中到MembershipProvider上,MembershipProvider类是Provider构架的一种体现形式,Provider构架常常用到对数据库的访问上,实现多数据库,同时也可以很好的隔离数据层与业务层的代码有利于协作开发。具体实现是这样的,先把要操作数据库的方法抽象出来,单独的放入一个abstract类,例如:MembershipProvider,然后通过继承,把这些抽象的方法全部的实现出来,例如:SqlMembershipProvider。这样有什么好处呢?对于三层构架的web应用程序来说,中间的业务逻辑层调用操作数据库的方法是从MembershipProvider,对于该层来说它并不关心该抽象层是如何被继承后实现抽象方法的。它只关心抽象层中是否有它想要的方法。如果能理解到这里,嘿嘿,我们的机会就来了,因为这隔离了具体的数据库操作实现,更进一步说就是隔离了使用何种数据库。再从团队协作考虑,假设你的MembershipProvider定义的完善后,继承MembershipProvider实现SQL Server操作的SqlMembershipProvider类中的方法无论怎么改变,都不会影响其它人员在业务逻辑层的开发。听起来这种方式好像很美,但是要实现这样的功能还需要一个关键的技术,那就是反射,所以我们看到在配置的字段里有这样的字节:。

type="Openlab.AutoRegister.CSAutoBlogGalleryMembershipProvider, Openlab.CSAddOns"

这就是为了通过反射找到MembershipProvider具体方法实现的类而做的准备。

注:由于分析的代码来源于宝玉的CCS,在CCS中为了实现注册后能自动开通博客与相册又继承了SqlMembershipProvider类,重写了几个方法(关键是其中的InitializeCreateUser方法)

只要你继承MembershipProvider类,对其中的抽象方法进行实现,无论你是实现对Access的操作,还是其它数据库,都是没有问题的。在asp.net 2.0 beta2中的Membership已经提供accesssql server两种数据库操作实现。不过MemberRole.dll程序集中只实现了SqlMembershipProvider,也就是对SQL Server的操作。

Membership是一个没有表示层的运用组件,它包含了逻辑层与数据操作层,数据层我在这个专题中就不多做解释,他的实现是在SqlMembershipProvider类中,你可以通过Reflector.exe慢慢研究。上面的文字说过,实现Provider模式后业务逻辑层对数据层具体实现就不关心了,在MemberRole.dll中的Membership,它把所有的这些逻辑用一个类包装起来,那就是Membership类:

%7B11DB1E16-9403-4D6A-97A6-ACEF61BF57AB%7D0.jpg

对于引用MemberRole.dll实现Membership功能的web app(DNN,CS就是典型)来说,只要做合适的配置之后就可以直接使用了。

例如,要建立一个用户只要调用Membership.CreateUser的静态方法,就可以完成(Membership会根据内部的方法和具体的数据库操作,把用户信息写入数据库)。

对于使用Membership来开发web app的程序员来说,完全可以不必要了解这些细节,asp 2.0 beta2就没有提供这样的机会,MS只要求你会用就可以了,不过很庆幸的是CS给我们提供了这样的一个机会,了解这些操作的实质(包括URL Rewrite等功能也是一样,这些功能都可以在asp 2.0 beta2中直接使用,而不要构架如何代码)

这个专题只是大致的讲解了Membership,下一个专题,我们将更深入的去看看Membership的数据层的操作实现以及数据库表的设计(包括存储过程)

转载于:https://www.cnblogs.com/ugoer/archive/2005/09/17/238978.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值