Click here to Skip to main content
Licence 
First Posted 23 Jun 2006
Views 131,341
Downloads 636
Bookmarked 65 times

C# MySQL Profile Provider for .NET 2.0

By | 13 Sep 2006 | Article
This is a MySQL based Profile Provider written in C# for .NET 2.0
 
Part of The SQL Zone sponsored by
See Also

Introduction

This is about a MySql Profile Provider.

I did not write the profile provider from scratch. I used a sample Microsoft Access profile provider from the Microsoft SDK, and modified it to work with MySQL.

If you are new to the .NET 2.0 Provider technology, then refer to this article to learn about how the Membership and Role provider works. Membership and Role providers for MySQL by Rakotomalala Andriniaina.

Note: This profile provider was written to work with a specific MySQL Membership and Role Provider which is from another codeproject article. This profile provider will not work unless the membership and role providers are setup and working! The Source download for this article has been updated to include the MYSQL Role,Membership, and Profile provider source.

If you are new to the .NET 2.0 Provider technology, then refer to this article to learn about how the Membership and Role provider works. However, do not use the source from the link below because the code has been updated in the link above: Membership and Role providers for MySQL by Rakotomalala Andriniaina.

Using the Provider

Step 1: Add two new tables, aspnet_profile and aspnet_applications.

CREATE TABLE 'aspnet_profile' (
  'UserId' bigint(20) default NULL,
  'PropertyNames' text,
  'PropertyValuesString' text,
  'LastUpdatedDate' datetime default NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

CREATE TABLE 'aspnet_applications' (
  'ApplicationName' text,
  'ApplicationId' int(11) NOT NULL auto_increment,
  'Description' text,
  PRIMARY KEY  ('ApplicationId')
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

Step 2: Add the MySqlProfileProvider.cs source file to the app_code of the project. If you are using VB.NET, then you have two options:

  • Add a C# class Library project to your solution. Then, add the MySqlProfileProvider.cs source file to the class library project. Add the following references: MySql.Data, System.configuration, and System.Web. Next, add a project reference that points to the new class library project you just added to your original project that will be using the profile provider. When you compile the solution, the C# class library project will compile first and create the DLL, because it is being referenced by the main project. This method will allow you to debug the C# code with your main project even if it is in VB.NET.

    Note: You can also use this method for your membership and role provider source. Just add a separate C# class library project for each provider source file.

  • You will need to compile the C# source into a DLL and then add the reference to your project. Here is a link (Membership and Role providers for MySQL) to the message that will explain compiling the source into a DLL for VB.NET.

Step 3: Modify the Web.config.

<connectionStrings>
 <add name="ConnString" 
      connectionString="Database=;DataSource=;User Id=;Password=;"/>
</connectionStrings>

<profile defaultProvider="MySqlProfileProvider">
  <providers>
    <add name="MySqlProfileProvider" 
         type="Malachi.MySqlProviders.MySqlProfileProvider"
         connectionStringName="ConnString" 
         applicationName="Intranet"/>
  </providers>
  <properties>
    <add name="FirstName" />
    <add name="LastName" />
  </properties>
</profile>

Step 4: Create users.

In order for this profile provider to work, you must use the membership provider from the above mentioned article and create users through that membership provider. A profile provider is an extension of the user. The profile property records are linked to the users table via the UserId field. The UserId field should be auto incremented so it is populated when the user is created. If you would like to populate and create profile properties when the user is created, then you will need to override the ASP.NET control "CreateUserWizard". I will try to write another article soon regarding how to do that. Otherwise, use the methods in the next step in the page loads or other events.

Step 5: Read and write profile properties.

Here is the login page code-behind. This example is in VB.NET.

Protected Sub Page_Load(ByVal sender As Object, _
          ByVal e As System.EventArgs) Handles Me.Load
    If User.Identity.IsAuthenticated Then
        IntranetLogin.Visible = False
        Profile.GetProfile(User.Identity.Name)
        lblWelcome.Text = "<p><strong>Welcome back " & _
                          Profile.FirstName & " " & Profile.LastName & _
                          "</strong></p><p>Applications " & _ 
                          "are available from the menu on the right side."
    Else
        lblWelcome.Text = "<p>Login or Create a user account to " & _ 
                          "access Intranet applications.</p><p>" & _ 
                          "Quick Links on this page are available " & _ 
                          "to unregistered and registered users."
    End If
End Sub

Protected Sub SaveProfile_Click(ByVal sender As Object, _
          ByVal e As System.EventArgs) Handles SaveProfile.Click
         'Get Profile of current user
    If User.Identity.IsAuthenticated Then
        Profile.GetProfile(User.Identity.Name)

        'Populate some Profile properties
        Profile.FirstName = "My FirstName"
        Profile.LastName = "My LastName"
    End If
     
End Sub

History

  • 09-13-2006 - Updated the source and article information
  • 07-10-2006 - Updated some typos and errors

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Edacio

Web Developer

United States United States

Member

.Net Developer

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
Generalstrange problem Pinmembermascix6:34 11 Jul '09  
GeneralProfiler Pinmemberlav naphade23:39 24 Apr '09  
GeneralData not passing to PropertyStringsValue field Pinmembermaven4champ18:31 25 Mar '09  
GeneralMySQL Membership, Role, Personalization and Profile providers PinmemberAlexRiley8:32 14 Feb '09  
QuestionWhat I did... [modified] PinmemberZachMcBunklesnot12:23 22 Sep '08  
Hello all, just wanted to give a big thanks to the author of this code and the other helpful posters on this forum... It took me a while to get everything working and some parts were a little hard to piece together, but here is what I did to get everything working. **I am not using the RoleProvider, so I am not sure if that works with this setup...
 
1. Copy the code into the AppCode folder of my project.
 
2. Create the database using pc.huff's creation strings:
 
CREATE TABLE aspnet_profile (
PKID varchar(36) collate latin1_general_ci NOT NULL default '',
LastUpdatedDate datetime default NULL,
PropertyNames text default NULL,
PropertyValuesString text default NULL
);
 

CREATE TABLE aspnet_applications (
ApplicationName text default NULL,
ApplicationId int(11) default NULL,
Description text default NULL,
PropertyValuesString text default NULL,
PRIMARY KEY (`ApplicationId`)
);
 
CREATE TABLE `users` (
PKID varchar(36) NOT NULL default '',
Username varchar(255) NOT NULL default '',
ApplicationName varchar(100) NOT NULL default '' ,
Email varchar(100) NOT NULL default '',
`Comment` varchar(255) default NULL,
`Password` varchar(128) NOT NULL default '',
PasswordQuestion varchar(255) default NULL,
PasswordAnswer varchar(255) default NULL,
IsApproved tinyint(1) default NULL,
LastActivityDate datetime default NULL,
LastLoginDate datetime default NULL,
LastPasswordChangedDate datetime default NULL,
CreationDate datetime default NULL,
IsOnLine tinyint(1) default NULL,
IsLockedOut tinyint(1) default NULL,
LastLockedOutDate datetime default NULL,
FailedPasswordAttemptCount int(11) default NULL,
FailedPasswordAttemptWindowStart datetime default NULL,
FailedPasswordAnswerAttemptCount int(11) default NULL,
FailedPasswordAnswerAttemptWindowStart datetime default NULL,
ApplicationId bigint(20) default NULL,
MobileAlias text NULL,
IsAnonymous varchar(5) NULL default NULL,
PRIMARY KEY (`PKID`)
);

 
3. Make drobol's changes (starting at line 410 of the MySQLProfileProvider)
 
410 cmd = new MySqlCommand("SELECT PKID FROM aspnet_Profile WHERE PKID = '" + userId + "'", conn, trans);
411 object result = cmd.ExecuteScalar();
412 if (result != null ) {
413 string userid1 = result.ToString();
414 string userid2 = userId.ToString();
415 if (userid1 == userid2){
416 cmd = new MySqlCommand("UPDATE aspnet_Profile SET PropertyNames ='" + names + "', PropertyValuesString ='" + values + "', LastUpdatedDate ='" + DateTime.Now.ToString("yyyy:MM:dd hh:mm:ss") + "' WHERE PKID ='" + userId + "'", conn, trans);
417 }
418 else {
419 cmd = new MySqlCommand("INSERT INTO aspnet_Profile (PKID, PropertyNames, PropertyValuesString, LastUpdatedDate) VALUES ('" + userId + "','" + names + "','" + values + "','" + DateTime.Now.ToString("yyyy:MM:dd hh:mm:ss") + "')", conn, trans);
420 }
421 } else {
422 cmd = new MySqlCommand("INSERT INTO aspnet_Profile (PKID, PropertyNames, PropertyValuesString, LastUpdatedDate) VALUES ('" + userId + "','" + names + "','" + values + "','" + DateTime.Now.ToString("yyyy:MM:dd hh:mm:ss") + "')", conn, trans);
423 }

 
4. Configure my web.config in the same way as described in the author's original post...
 
5. Insert a record into my aspnet_profile database table with the same Application Name that I used in web.config and a "1" for my ApplicationId and NULL for PropertyValuesString
 
6. I am using the CreateUserWizard control customized to use Email as the UserName and take FirstName and LastName on registration. I set the "loginCreatedUser" property of the CreateUserWizard to "true" and handle the CreateUserWizard_CreatingUser event to copy the CreateUserWizard.UserName field into the CreateUserWizard.Email. I handle the CreateUserWizard_CreatedUser event to set Profile variables for the new user.
 
Hope this helps... There are a lot of Googleable guides to customizing the CreateUserWizard and setting Profile values, so I won't give my code there, just get 1-6 working and the examples using the default Microsoft providers will work the same. I think if you you follow these steps you will really find yourself in Hog Heaven as far as ASP.NET membership and profiles using MySQL are concerned.
 
modified on Monday, September 29, 2008 11:39 AM

AnswerRe: What I did... Pinmembermathinayagam12322:36 30 Sep '08  
GeneralMySql 5 Code [modified] Pinmemberpc.huff9:22 25 Apr '08  
GeneralRe: MySql 5 Code PinmemberHawkmoth3:47 7 Aug '08  
GeneralRe: MySql 5 Code [modified] PinmemberHawkmoth4:43 7 Aug '08  
AnswerRe: MySql 5 Code Pinmemberdrobole14:33 21 Sep '08  
Generalbugs [modified] PinmemberPerth_shan23:02 3 May '07  
GeneralRe: bugs PinmemberEdacio6:23 12 Oct '07  
Generalmysql 5.0 Pinmemberdarkducke6:15 21 Apr '07  
General404 on the mentioned download PinmemberSeanKinsey2:05 2 Mar '07  
GeneralRe: 404 on the mentioned download Pinmemberverocp2:13 8 Jun '07  
GeneralRe: 404 on the mentioned download PinmemberFordGT9023:49 25 Jul '07  
GeneralRe: 404 on the mentioned download Pinmembercabaret22:57 3 Sep '07  
Generalnull reference PinmemberDanillo5516:07 14 Dec '06  
QuestionSetPropertyValues getting called for reading values? Pinmemberratty761:20 2 Nov '06  
AnswerRe: SetPropertyValues getting called for reading values? PinmemberEdacio6:22 9 Nov '06  
GeneralWeb Application Projects Pinmemberjawstress3:53 28 Oct '06  
GeneralRe: Web Application Projects PinmemberEdacio6:15 9 Nov '06  
GeneralRe: Web Application Projects Pinmemberjawstress6:32 9 Nov '06  
GeneralReport of bugs Pinmembergarfield_ml12:16 5 Oct '06  
GeneralRe: Report of bugs [modified] PinmemberEdacio10:17 6 Oct '06  

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
Web04 | 2.5.120604.1 | Last Updated 13 Sep 2006
Article Copyright 2006 by Edacio
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid