Manage database of ASP.NET 2.0 Membership & Role services in non-ASP.NET context
One question I’ve seen asked a few times by people in the NG is “how do I manage ASP.NET Membership, Role Management database in non-ASP.NET application/context”. This blog entry walks you though a few simple steps on how to-do this.
Quick Review: What are the new ASP.NET 2.0 membership & role management Services?
The ASP.NET version 2.0 membership feature provides secure credential storage for application users. It also provides a membership API that simplifies the task of validating user credentials when used with forms authentication. Membership providers abstract the underlying store used to maintain user credentials. ASP.NET 2.0 includes the following providers:
- ActiveDirectoryMembershipProvider. This uses either an Active Directory or Active Directory Application Mode (ADAM) user store.
- SqlMembershipProvider. This uses a SQL Server user store.
Here I’ll concentrate on the SQL Server provider since it is used mostly for FormsAuthentication based ASP.NET web applications. By default ASP.NET SqlServer membership/role provider use SQL Express database file(aspnetdb.mdf) as the storage, however, you can easily change it to your own SQL Server database in a certain server instance. What you need to do is simply override/customize the membership setting in the application web.config file. E.g.
<connectionStrings> <add name="MySqlConnection" connectionString="Data Source=MySqlServer;Initial Catalog=aspnetdb;Integrated Security=SSPI;" /> </connectionStrings> <system.web> ... <membership defaultProvider="SqlProvider" userIsOnlineTimeWindow="15"> <providers> <clear /> <add name="SqlProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="MySqlConnection" applicationName="MyApplication" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="true" requiresUniqueEmail="true" passwordFormat="Hashed" /> </providers> </membership> |
How do I manage ASP.NET Membership, Role Management database in non-ASP.NET application/context?
Sometimes you may want to manage the SQL Server membership/role database in non-ASP.NET application/context(such as winform or console application) for some certain reasons:
l Need to add some initial data(users/roles) in the setup program of the application
l Want to create a non-ASP.NET application to manage the membershp/role database offline
l Create a non-ASP.NET application that can help create a membership/role database as template(used in other ASP.NET application).
Well, this is certainly supported by the ASP.NET 2.0 membership/role(also some other) providers and you can do this follow these steps:
1. add the connectionstring to your SQL Server membershp & role provider database into the winform/console application’s App.confg file. e.g.
<connectionStrings>
<add name="ProfileAppDB" connectionString="Data Source=localhost;Initial Catalog=ProfileAppDB;Integrated Security=True" providerName="System.Data.SqlClient" /> </connectionStrings> |
2. copy the membershp & role setting fragment from your ASP.NET application into the winform/console application’s App.config file. e.g.
………….. <system.web> <anonymousIdentification enabled="true"/> …………… <membership defaultProvider="NewAspNetSqlMembershipProvider"> <providers> <add name="NewAspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" connectionStringName="ProfileAppDB" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="true" applicationName="/" requiresUniqueEmail="false" passwordFormat="Hashed" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="7" minRequiredNonalphanumericCharacters="1" passwordAttemptWindow="10" passwordStrengthRegularExpression="" /> </providers> </membership> <roleManager defaultProvider="NewAspNetSqlRoleProvider" enabled="true"> <providers> <add name="NewAspNetSqlRoleProvider" connectionStringName="ProfileAppDB" applicationName="/" type="System.Web.Security.SqlRoleProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" /> </providers> </roleManager> </system.web> …………… |
3. Use the built-in façade classes to manage the membership users and roles. E.g.
/// <summary> /// Dump the users and associated roles from membership database /// </summary> private void Dump_Users() { MembershipUserCollection users = Membership.GetAllUsers(); txtOutput.Text += "\r\n=========Total User Count: " + users.Count + "=========="; txtOutput.Text += "\r\n\r\n"; foreach (MembershipUser user in users) { txtOutput.Text += "\r\n\tUsername: " +user.UserName + "\t, Creation Time: " + user.CreationDate;
string[] roles = Roles.GetRolesForUser(user.UserName); txtOutput.Text += "\r\n Roles: " + string.Join(", ",roles); } } /// <summary> /// create a new membership user /// </summary>
private void btnCreate_Click(object sender, EventArgs e) { MembershipCreateStatus ret; MembershipUser user = Membership.CreateUser( txtUsername.Text, txtPassword.Text, txtUsername.Text + "@test.org", "who am i?", txtUsername.Text, true, null, out ret); MessageBox.Show(ret.ToString()); } |
Winform App UI
Additional common questions here:
Q1: What shall I do if I can not add an App.config file for the program at design-time(used in a setup program)? How can I provide the connectionstring and membershp provider configuration info?
A1: You can dynamically create an app.exe.config file for your program in the initialization/startup time. Use built-in API to get the runtime main exe path and create a config file on the fly, then write the configuration info into it(load from resource or any other place).
Q2: How can I programmatically install the membership & role services into an empty SQL Server database(in a certain server instance)?
A2: You have two options here:
ü Call the aspnet_regsql.exe utility the install the services in your database
https://msdn2.microsoft.com/en-us/library/x28wfk74.aspx
ü Directly use the System.Web.Management.SqlServices class to install the services into your SQL Server database
https://msdn2.microsoft.com/en-us/library/system.web.management.sqlservices.aspx
Q3: How can I do programmatically create a SQL Express database file which has the membershp & role services installed
A3: Well, you can find that ASP.NET Sqlmembership provider will automatically create a mdf file if you’ve configured to use the default SQL Express connectionstring. Thus, you can inspect it through reflector and find out the SqlConnectionHelper.CreateMdfFile method which include the complete code for creating such as database file on the fly
Hope this helps.
Steven Cheng
Comments
Anonymous
December 16, 2006
This article explains how to manage database of ASP.NET 2.0 Membership & Role services in non-ASP.NETAnonymous
April 10, 2007
When i use a custom membershipProvider in a windows application, i get the following error: Could not load type 'GISVL.DALI.daliRegistration.daliRegistrationMembershipProvider' from assembly 'System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' In my app.config: <system.web> <membership defaultProvider="DALIMembershipProvider"> <providers> <clear/> <add name="DALIMembershipProvider" type="GISVL.DALI.daliRegistration.daliRegistrationMembershipProvider" connectionStringName="DALITestDatabank" enablePasswordRetrieval="false" enablePasswordReset="true" passwordFormat="Hashed" passwordAttemptWindow="3" requiresQuestionAndAnswer="false" requiresUniqueEmail="true" minRequiredPasswordLength="8" minRequiredNonalphanumericCharacters="1" passwordStrengthRegularExpression="" applicationName="AGIV"/> </providers> </membership> </system.web> Can u help me?Anonymous
April 25, 2007
change to this: ============ <add name="DALIMembershipProvider" type="GISVL.DALI.daliRegistration.daliRegistrationMembershipProvider, [put theASSEMBLY_NAME here]" ............ /> ============== when specify type in config file, you need to put both class full name and its assembly nameAnonymous
August 08, 2007
I need to connect one web server to two different databases containing asp.net membership class tables. How should asp.net membership class be configured?Anonymous
April 23, 2008
Hi, I want to use membership APIs in C# dll, instead of in windows app, is it durable? Thanks. WilliamAnonymous
April 24, 2008
How can I add additional attributes to the role in the Role Provider? I need to have some attributes like a location for the role and not for the user.Anonymous
May 18, 2008
Hi When I use Dim ret As MembershipCreateStatus in VB.nat I get the error 'Type 'MembershipCreateStatus' is not defined'. What am I doing wrong? Thanks Regards YahyaAnonymous
June 23, 2008
Hi,I found this post extremely helpful. I am pushing the boundaries a bit. I have a custom membership provider and I would like to call it from vb6 .I have created a an interop dll that calls myCustomMembership but i cannot seem to be able to get the initialize method to get fired. Any ideas? thanksssssAnonymous
December 02, 2008
Linked to original entry on MSDNTS blog: Manage database of ASP.NET 2.0 Membership & Role services