[dba-VB] Using the ASP.NET 2.0 membership, roles etc.

Shamil Salakhetdinov shamil at users.mns.ru
Thu Oct 25 16:21:53 CDT 2007


Hi Robert,

The below test C# code seems to work well in VS2005 console application with
app.config defining system.web section with membership and role providers
referring MS SQL database defined in connectionStrings section:

    //+ user
    public class TestRolesAndUsersInConsoleApp
    {
        public static void Test()
        {
            try
            {
                //' Creating a new user
                string userName = "user1";
                string userName2 = "user2";
                string password = "test";
                string email = "test at mail.ru";
                string passwordQuestion = "Password question";
                string passwordQuestionAnswer = "test";

                string roleName = "Developers";
                System.Web.Security.MembershipUser user = null;
                MembershipCreateStatus status;


                if (System.Web.Security.Membership.ValidateUser(userName,
password))
                {
                    System.Web.Security.Membership.DeleteUser(userName,
true);
                    Console.WriteLine("User " + userName + " - deleted."); 
                }
                
                if (System.Web.Security.Membership.ValidateUser(userName2,
password))
                {
                    System.Web.Security.Membership.DeleteUser(userName2,
true);
                    Console.WriteLine("User " + userName2 + " - deleted."); 
                }

                if (System.Web.Security.Roles.RoleExists(roleName))
                {
                    System.Web.Security.Roles.DeleteRole(roleName); 
                    Console.WriteLine("Role " + roleName + " - deleted."); 
                }

                user =  System.Web.Security.Membership.CreateUser(userName,
password, email, passwordQuestion, passwordQuestionAnswer, true, out
status);

                if (status == MembershipCreateStatus.Success)
                {
                    int aa = 1;
                }
                //' Validate a username/passworduserName
                if (System.Web.Security.Membership.ValidateUser(userName,
password))
                    Console.WriteLine(userName + " - User validated. " +
status.ToString() );
                else
                    Console.WriteLine(userName + " - User invalid! ");


                //' Create a new Developer role.
                //' Add the <roleManager enabled="true" /> to the app.config
for this to work
                if (!System.Web.Security.Roles.RoleExists(roleName)) {
                    System.Web.Security.Roles.CreateRole(roleName); 
                }

                //' Add a new role to a known user.
                if (!System.Web.Security.Roles.IsUserInRole(userName,
roleName))
                {
                    System.Web.Security.Roles.AddUserToRole(userName,
roleName);
                }
                if (!System.Web.Security.Roles.IsUserInRole(userName,
roleName))
                {
                    Console.WriteLine(userName + " added to role " +
roleName); 
                    System.Web.Security.Roles.AddUserToRole(userName,
roleName);
                }

                //' Create a second user with only username/password
                //' Add the <membership><providers> element to the
app.config first
                user = System.Web.Security.Membership.GetUser(userName2);
                if (user == null) {
                     user =
System.Web.Security.Membership.CreateUser(userName2, password);
                     System.Web.Security.Roles.AddUserToRole(userName2,
roleName);
                     Console.WriteLine("Created user: " + user.UserName);
                }

                //' Set the current application principal information to a
known user
                System.Security.Principal.GenericIdentity identity;
                RolePrincipal principal;
                user = System.Web.Security.Membership.GetUser(userName);
                identity = new
System.Security.Principal.GenericIdentity(user.UserName);
                principal = new System.Web.Security.RolePrincipal(identity);
                System.Threading.Thread.CurrentPrincipal = principal;

                //' Check if the current principal is in a specific role
 
Console.Write(System.Threading.Thread.CurrentPrincipal.Identity.Name);
                if (System.Web.Security.Roles.IsUserInRole(roleName))
                    Console.WriteLine(" Is a developer.");
                else
                    Console.WriteLine(" Doesn't write code.");
               
                //' Set the current application principal information to
another known user
                user = System.Web.Security.Membership.GetUser(userName2);
                identity = new GenericIdentity(user.UserName);
                principal = new RolePrincipal(identity);
                System.Threading.Thread.CurrentPrincipal = principal;

                //' Use the principal to check for role information
 
Console.Write(System.Threading.Thread.CurrentPrincipal.Identity.Name);
                if
(System.Threading.Thread.CurrentPrincipal.IsInRole(roleName))
                    Console.WriteLine(" is a developer.");
                else
                    Console.WriteLine(" doesn't write code.");

                //+ delete
                if (System.Web.Security.Membership.ValidateUser(userName,
password))
                {
                    System.Web.Security.Membership.DeleteUser(userName,
true);
                    Console.WriteLine("User " + userName + " - deleted.");
                }

                if (System.Web.Security.Membership.ValidateUser(userName2,
password))
                {
                    System.Web.Security.Membership.DeleteUser(userName2,
true);
                    Console.WriteLine("User " + userName2 + " - deleted.");
                }
                
                if (System.Web.Security.Roles.RoleExists(roleName))
                {
                    System.Web.Security.Roles.DeleteRole(roleName);
                    Console.WriteLine("Role " + roleName + " - deleted.");
                }

                //- delete

                Console.ReadLine();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);  
            }
        }
    }
    //- user

--
Shamil
 
P.S. app.config for console app's test class above looks like that (watch
line wraps):

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <connectionStrings>
    <remove name="DatabaseServer" />
    <add name="DatabaseServer" ... blah blah blah ... />
    </connectionStrings>

  <system.web>
    <roleManager enabled="true" cacheRolesInCookie="false"
cookieName="TEST_ROLES" defaultProvider="TEST_APP_RoleProvider">
      <providers>
        <remove name = "AspNetSqlMembershipProvider1"/>
        <add connectionStringName="DatabaseServer"
applicationName="/TEST_APP_Web" name="TEST_APP_RoleProvider" 
          type="System.Web.Security.SqlRoleProvider, System.Web,
Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>
      </providers>
    </roleManager>
    
    
    <membership defaultProvider="TEST_APP_MembershipProvider"
userIsOnlineTimeWindow="15">
      <providers>
        <remove name = "AspNetSqlMembershipProvider"/> 
        <add name="TEST_APP_MembershipProvider"
connectionStringName="DatabaseServer" applicationName="/TEST_APP_Web"
             enablePasswordRetrieval="true" enablePasswordReset="true" 
             requiresQuestionAndAnswer="false" requiresUniqueEmail="false"
             passwordFormat="Encrypted" maxInvalidPasswordAttempts="5" 
             passwordAttemptWindow="10" minRequiredPasswordLength="2"
             minRequiredNonalphanumericCharacters="0" 
             type="System.Web.Security.SqlMembershipProvider, System.Web,
Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
        />
      </providers>
    </membership>

    <machineKey  ... blah blah blah... validation='SHA1'/>

  </system.web>

</configuration>


-----Original Message-----
From: dba-vb-bounces at databaseadvisors.com
[mailto:dba-vb-bounces at databaseadvisors.com] On Behalf Of Robert L. Stewart
Sent: Friday, October 26, 2007 12:54 AM
To: dba-vb at databaseadvisors.com
Subject: Re: [dba-VB] Using the ASP.NET 2.0 membership, roles etc.

The roles/membership stuff is currently available only in ASP.net pages.
But, in VS 2008, it will also be available in WinForm/Smart Client
applications.

Robert

<<< tail skipped >>>




More information about the dba-VB mailing list