Click here to Skip to main content
Licence CPOL
First Posted 26 Apr 2007
Views 142,025
Downloads 506
Bookmarked 99 times

Suite of MySQL Provider Implementations for ASP.NET 2.0

By | 22 Oct 2007 | Article
An Article on Implementing MySQL Providers for ASP.NET 2.0 Membership, Roles, Site Map and Personalization
 
Part of The SQL Zone sponsored by
See Also

Contents

Introduction

As I started to work on a new AJAX-enabled website, I looked around for a MySQL implementation of the ASP.NET 2.0 membership provider. To my amazement, I couldn't find anything. So I decided to do my own implementation. After a few days of dev work, on and off, I found that I hadn't only implemented the membership provider but also the roles provider, site map provider and personalization provider.

All the providers inherit from the generic providers from Microsoft.

[^]

Using the Code

Using the providers is really easy.

  1. Create a new database on your MySQL server, e.g. SimpleProviders.

  2. Execute the following SQL statement on the newly created database.

    CREATE TABLE `personalization` (
      `username` varchar(255) default NULL,
      `path` varchar(255) default NULL,
      `applicationname` varchar(255) default NULL,
      `personalizationblob` blob
    );
    
    CREATE TABLE `profiles` (
      `UniqueID` int(8) NOT NULL auto_increment,
      `Username` varchar(255) NOT NULL default '',
      `ApplicationName` varchar(255) NOT NULL default '',
      `IsAnonymous` tinyint(1) default '0',
      `LastActivityDate` datetime default NULL,
      `LastUpdatedDate` datetime default NULL,
      PRIMARY KEY  (`UniqueID`),
      UNIQUE KEY `PKProfiles` (`Username`,`ApplicationName`),
      UNIQUE KEY `PKID` (`UniqueID`)
    );
    
    CREATE TABLE `roles` (
      `Rolename` varchar(255) NOT NULL default '',
      `ApplicationName` varchar(255) NOT NULL default '',
      PRIMARY KEY  (`Rolename`,`ApplicationName`)
    );
    
    CREATE TABLE `sitemap` (
      `ID` int(11) NOT NULL auto_increment,
      `ApplicationName` varchar(255) NOT NULL default '',
      `Title` varchar(255) default NULL,
      `Description` text,
      `Url` text,
      `Roles` text,
      `Parent` int(11) default NULL,
      PRIMARY KEY  (`ID`)
    );
    
    CREATE TABLE `users` (
      `PKID` varchar(255) NOT NULL default '',
      `Username` varchar(255) NOT NULL default '',
      `ApplicationName` varchar(255) NOT NULL default '',
      `Email` varchar(128) default NULL,
      `Comment` varchar(255) default NULL,
      `Password` varchar(128) NOT NULL default '',
      `FailedPasswordAttemptWindowStart` datetime default NULL,
      `PasswordQuestion` varchar(255) default NULL,
      `IsLockedOut` tinyint(1) default '0',
      `PasswordAnswer` varchar(255) default NULL,
      `FailedPasswordAnswerAttemptCount` int(8) default '0',
      `FailedPasswordAttemptCount` int(8) default '0',
      `IsApproved` tinyint(1) NOT NULL default '0',
      `FailedPasswordAnswerAttemptWindowStart` datetime default NULL,
      `LastActivityDate` datetime default NULL,
      `IsOnLine` tinyint(1) default '0',
      `CreationDate` datetime default NULL,
      `LastPasswordChangedDate` datetime default NULL,
      `LastLockedOutDate` datetime default NULL,
      `LastLoginDate` datetime default NULL,
      PRIMARY KEY  (`PKID`),
      UNIQUE KEY `PKID` (`PKID`),
      KEY `PKID_2` (`PKID`),
      KEY `usr` (`Username`)
    );
    
    CREATE TABLE `usersinroles` (
      `Username` varchar(255) NOT NULL default '',
      `Rolename` varchar(255) NOT NULL default '',
      `ApplicationName` varchar(255) NOT NULL default '',
      PRIMARY KEY  (`Username`,`Rolename`,`ApplicationName`)
    );

    There is an SQL file named DBStructure.sql included with the source code ZIP file that contains the code above.

  3. Open Visual Studio and create a new Website Project.

  4. Add a reference to the Simple.Providers.MySQL.dll file.

  5. Make the following changes to your web.config file:

    1. Add the connection string to your newly created database to the connectionStrings section, e.g. <add connectionstring="Driver={MySQL ODBC 3.51 Driver};server={Your Server IP};port={Your Server Port No.};option=3;database={New Database Name};uid={Your username};pwd={Your password}" name="SimpleProviderConnectionString" providername="System.Data.Odbc" />.

      * Please replace the {Your Server IP}, {Your Server Port No.}, {New Database Name}, {Your username} and {Your password} entries in the connection string with your own values.

    2. Under the <system.web> section add the following:

      <siteMap defaultProvider="siteMapProvider" enabled="true">
      
          <providers>
              <clear />
              <add name="siteMapProvider" 
                 type="Simple.Providers.MySQL.MysqlSiteMapProvider" 
                 connectionStringName="SimpleProviderConnectionString" 
                 applicationName="{Your App Name}" 
                 description="MySQL site map provider" 
                 securityTrimmingEnabled="true"/>
          </providers>
      </siteMap>
      <roleManager defaultProvider="roleProvider" enabled="true" 
          cacheRolesInCookie="false" cookieName=".ASPROLES" 
          cookieTimeout="7200" cookiePath="/" cookieRequireSSL="false" 
          cookieSlidingExpiration="true" cookieProtection="All">
          <providers>
      
              <clear />
              <add name="roleProvider" 
                  type="Simple.Providers.MySQL.MysqlRoleProvider" 
                  connectionStringName="SimpleProviderConnectionString" 
                  applicationName="{Your App Name}" 
                  description="MySQL role provider"/>
          </providers>
      </roleManager>
      <membership defaultProvider="membershipProvider" 
          userIsOnlineTimeWindow="15">
          <providers>
              <clear />
      
              <add name="membershipProvider" 
                  type="Simple.Providers.MySQL.MysqlMembershipProvider" 
                  connectionStringName="SimpleProviderConnectionString" 
                  applicationName="{Your App Name}" 
                  enablePasswordRetrieval="true" 
                  enablePasswordReset="true"
                  requiresQuestionAndAnswer="true" 
                  requiresUniqueEmail="true" passwordFormat="Encrypted" 
                  minRequiredPasswordLength="6" 
                  minRequiredNonalphanumericCharacters="0"  
                  description="MySQL membership provider"/>
          </providers>
      </membership>
      <profile defaultProvider="profileProvider" 
          automaticSaveEnabled="true">
          <providers>
              <clear />
              <add name="profileProvider" 
                  type="Simple.Providers.MySQL.MysqlProfileProvider" 
                  connectionStringName="SimpleProviderConnectionString" 
                  applicationName="{Your App Name}" 
                  description="MySQL Profile Provider"/>
      
          </providers>
          <properties>
              <clear />
              <!--
                  Add any needed attributes for profiles here.
                  eg. <add name="Theme" type="System.String" 
                          defaultValue="Default"/>
              -->
          </properties>
      
      </profile>
      <webParts>
          <personalization defaultProvider="personalizationProvider">
              <providers>
                  <clear />
                  <add name="personalizationProvider" 
                      type="Simple.Providers.MySQL.
                      MysqlPersonalizationProvider" 
                      connectionStringName=
                      "{Your Connection String Name}" applicationName="
                      {Your App Name}" 
                      description="MySQL Personalization Provider/>
              </providers>
      
          </personalization>
      </webParts> 
      
      /* !!! Please replace the {Your App Name} instances with a valid 
      application name. The application name should not contain 
      any spaces or special characters. !!! */
  6. Everything should be set up correctly now. Continue with the rest of your project and make sure to make use of the features provided by the above mentioned providers.

[^]

Points of Interest

I made use of the Microsoft MSDN site while developing the provider suite. For more info on...

[^]

History

  • 2007-04-25: Initial release of the article
  • 2007-10-18: Update of the UpdateUser code to enable LastActivityDate functionality
[^]

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

J Snyman

Web Developer

South Africa South Africa

Member

Jacques Snyman is an Analyst Developer from Midrand, South Africa. He has developed numerous entreprise applications using C#, VB.Net, Java and various other languages.
 
His hobbies include programming, cricket, blogging and a fair bit of reading (mostly on developent).

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
GeneralReset Password Error PinmemberSojan8014:35 14 Jul '09  
GeneralRe: Reset Password Error PinmemberJ Snyman19:17 14 Jul '09  
GeneralProblem running on IIS 5.1 Pinmemberanderea22:53 26 Feb '09  
GeneralMySQL Membership, Role, Personalization and Profile providers for ASP.NET PinmemberAlexRiley8:34 14 Feb '09  
GeneralOnly passwordFormat = "Clear" is accepted. PinmemberMichael Dolittle11:07 15 Nov '08  
GeneralRe: Only passwordFormat = "Clear" is accepted. PinmemberJ Snyman18:20 16 Nov '08  
GeneralBecause in Asp.Net website he does not recognize the Web.config of the MySqlSiteMapProvider ApplicationName PinmemberLuizItatiba14:02 11 Nov '08  
GeneralRe: Because in Asp.Net website he does not recognize the Web.config of the MySqlSiteMapProvider ApplicationName PinmemberJ Snyman21:44 12 Nov '08  
AnswerRe: Because in Asp.Net website he does not recognize the Web.config of the MySqlSiteMapProvider ApplicationName PinmemberLuizItatiba4:38 13 Nov '08  
QuestionHow CurrentNodes and accented with spaces in SiteMapPath? For example São Paulo-SP. PinmemberLuizItatiba9:23 22 Oct '08  
AnswerRe: How CurrentNodes and accented with spaces in SiteMapPath? For example São Paulo-SP. PinmemberJ Snyman9:30 22 Oct '08  
QuestionHow to correctly set the standard MemberShipProvider Provider of the SqlServer2005 to work together with the MySqlSiteMapProvider? PinmemberLuizItatiba6:04 8 Oct '08  
Generalspeed problems Pinmemberpeteresorensen2:44 8 Aug '08  
GeneralRe: speed problems PinmemberJ Snyman2:51 8 Aug '08  
GeneralMySQL/Net Connector Pinmemberpeteresorensen3:07 8 Aug '08  
GeneralRe: MySQL/Net Connector PinmemberJ Snyman21:40 10 Aug '08  
GeneralRe: MySQL/Net Connector Pinmemberpeteresorensen22:36 10 Aug '08  
GeneralMembershipProvider passwordFormat Encrypted/Hashed Error Pinmemberfpajaro9:03 11 Jun '08  
QuestionSo near, and yet.... PinmemberRoss Holland11:11 25 May '08  
Dear Jacques, many thanks for your excellent post. I am a real newbie to asp, having spent 25 years in 4GLs, and I have spent the last 3 days trying to find out how to use MySQL database as a membership database, so I can use the CreateUserWizard in my aspx files. I have finally, with your help, get as far as the whole application running without errors in the web.config file, however now when I go to the createuserwizard page, I get the error below. I can't for the life of me work out where this is going wrong. I have reduced it to just the rolemanager and membership bit in the web.config, and have changed the cookiepath to ~/cookies. I have added <@ Import Namespace="Simple.Providers.MySQL" %> into my master page, and your dll into the bin directory of my application.
 
Where am I going wrong???? Any help would be greatly appreciated to stop me going completely bananas on this (should be simple) issue!
 
Kind Regards, Ross Holland
 
Stack Trace:
 

[InvalidOperationException: Failed to map the path '/'.]
System.Web.Configuration.ProcessHostConfigUtils.MapPathActual(String siteName, VirtualPath path) +223
System.Web.Configuration.ProcessHostMapPath.MapPathCaching(String siteID, VirtualPath path) +611
System.Web.Configuration.ProcessHostMapPath.GetPathConfigFilenameWorker(String siteID, VirtualPath path, String& directory, String& baseName) +14
System.Web.Configuration.ProcessHostMapPath.System.Web.Configuration.IConfigMapPath.GetPathConfigFilename(String siteID, String path, String& directory, String& baseName) +38
System.Web.Configuration.HostingPreferredMapPath.GetPathConfigFilename(String siteID, String path, String& directory, String& baseName) +77
System.Web.Configuration.WebConfigurationHost.GetStreamName(String configPath) +162
System.Configuration.Internal.DelegatingConfigHost.GetStreamName(String configPath) +10
System.Configuration.BaseConfigurationRecord.InitConfigFromFile() +265
 
[ConfigurationErrorsException: An error occurred loading a configuration file: Failed to map the path '/'.]
System.Configuration.ConfigurationSchemaErrors.ThrowIfErrors(Boolean ignoreLocal) +111
System.Configuration.BaseConfigurationRecord.ThrowIfParseErrors(ConfigurationSchemaErrors schemaErrors) +41
System.Configuration.Configuration..ctor(String locationSubPath, Type typeConfigHost, Object[] hostInitConfigurationParams) +413
System.Configuration.Internal.InternalConfigConfigurationFactory.System.Configuration.Internal.IInternalConfigConfigurationFactory.Create(Type typeConfigHost, Object[] hostInitConfigurationParams) +30
System.Web.Configuration.WebConfigurationHost.OpenConfiguration(WebLevel webLevel, ConfigurationFileMap fileMap, VirtualPath path, String site, String locationSubPath, String server, String userName, String password, IntPtr tokenHandle) +934
System.Web.Configuration.WebConfigurationManager.OpenWebConfigurationImpl(WebLevel webLevel, ConfigurationFileMap fileMap, String path, String site, String locationSubPath, String server, String userName, String password, IntPtr userToken) +71
System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(String path) +23
Simple.Providers.MySQL.MysqlMembershipProvider.Initialize(String name, NameValueCollection config) +1429
System.Web.Configuration.ProvidersHelper.InstantiateProvider(ProviderSettings providerSettings, Type providerType) +579
System.Web.Configuration.ProvidersHelper.InstantiateProviders(ProviderSettingsCollection configProviders, ProviderCollection providers, Type providerType) +115
System.Web.Security.Membership.Initialize() +1593
System.Web.UI.WebControls.LoginUtil.GetProvider(String providerName) +33
System.Web.UI.WebControls.CreateUserWizard.get_QuestionAndAnswerRequired() +90
System.Web.UI.WebControls.CreateUserWizard.UpdateValidators() +1134
System.Web.UI.WebControls.CreateUserWizard.CreateChildControls() +32
System.Web.UI.Control.EnsureChildControls() +97
System.Web.UI.WebControls.Wizard.OnInit(EventArgs e) +100
System.Web.UI.Control.InitRecursive(Control namingContainer) +345
System.Web.UI.Control.InitRecursive(Control namingContainer) +196
System.Web.UI.Control.InitRecursive(Control namingContainer) +196
System.Web.UI.Control.InitRecursive(Control namingContainer) +196
System.Web.UI.Control.InitRecursive(Control namingContainer) +196
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +7915
System.Web.UI.Page.ProcessRequest(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +223
System.Web.UI.Page.ProcessRequest() +85
System.Web.UI.Page.ProcessRequestWithNoAssert(HttpContext context) +20
System.Web.UI.Page.ProcessRequest(HttpContext context) +110
ASP.register_aspx.ProcessRequest(HttpContext context) +30
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +441
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +65
AnswerRe: So near, and yet.... PinmemberJ Snyman19:06 25 May '08  
GeneralRe: So near, and yet.... PinmemberRoss Holland21:18 25 May '08  
GeneralRe: So near, and yet.... PinmemberJ Snyman21:26 25 May '08  
Generalhelp me :(( PinmemberDasty0:57 18 Apr '08  
GeneralRe: help me :(( PinmemberChristian Wikander22:24 14 May '08  
QuestionHow to Order Alphabetically by the children MySqlSiteMapProvider us PinmemberLuizItatiba16:23 1 Apr '08  

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Mobile
Web01 | 2.5.120529.1 | Last Updated 22 Oct 2007
Article Copyright 2007 by J Snyman
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid