Setting Membership/Profile/Role provider's connection string at runtime...?

Last post 07-30-2009 4:18 AM by markarmitage. 19 replies.

Sort Posts:

  • Setting Membership/Profile/Role provider's connection string at runtime...?

    06-08-2006, 12:12 AM
    • Member
      357 point Member
    • sebatwerk
    • Member since 04-18-2006, 6:03 AM
    • Posts 72

    How can I set the connection string for the built-in membership, profile and role providers at runtime?

    Since each site in our multi-site application uses a separate API to retrieve its specific connection string (via key, for security purposes), I cannot set the connection string to my providers in the web.config file. I need to be able to set the connection strings programmatically at runtime, but I cannot find how to implement this.

    I thought many people must have run into this problem, but I can't seem to find anything regarding this.Can anyone here help me with this problem?

     

    Sebastian

    Sebastian G.
  • Re: Setting Membership/Profile/Role provider's connection string at runtime...?

    06-08-2006, 4:15 AM
    • Contributor
      4,070 point Contributor
    • zhuhua1006
    • Member since 04-04-2006, 10:07 AM
    • Posts 808

    You'd better configure each web site as an application. After seoarating the application, you can set the connection string for each web site easily in web.config.

    <connectionStrings>

            <remove name=”LocalSqlServer”/>

            <add name="LocalSqlServer" connectionString="Data Source=localhost;Initial Catalog=appservicesdb;Integrated Security=True" providerName="System.Data.SqlClient"/>

        </connectionStrings>

  • Re: Setting Membership/Profile/Role provider's connection string at runtime...?

    06-08-2006, 12:28 PM
    • Member
      357 point Member
    • sebatwerk
    • Member since 04-18-2006, 6:03 AM
    • Posts 72

    No, that's not an option for us. We HAVE to set the connection s tring programmatically, we have no choice. I will explain:

    I work for an interactive/ marketing agency, and the project I am working on is a large site for a well-known multi-national company. This company has 200+ websites with a common user database and their own hosting. For their own security reasons, they do not give out database connection strings to be hard-coded. Instead, they developed an application (with an API given out to their interactive agencies) to which you pass a predetermined key as a parameter and get back the connection string. This is our only option.

    So, based on this, you're telling me that there's no way in the world to set the connection string outside of the web.config file?!? That just can't be, there has to be a way.

    If it helps, I am using a custom membership provider to handle interfacing with our client's common user database.

    Sebastian G.
  • Re: Setting Membership/Profile/Role provider's connection string at runtime...?

    06-08-2006, 12:34 PM
    • Member
      357 point Member
    • sebatwerk
    • Member since 04-18-2006, 6:03 AM
    • Posts 72
    sebatwerk:

    I work for an interactive/ marketing agency, and the project I am working on is a large site for a well-known multi-national company. This company has 200+ websites with a common user database and their own hosting. For their own security reasons, they do not give out database connection strings to be hard-coded. Instead, they developed an application (with an API given out to their interactive agencies) to which you pass a predetermined key as a parameter and get back the connection string. This is our only option.

    Keep in mind that using this system of connection string management also helps when you use a multi-server development/staging/production process. We do not have to change the connection strings in our application because we are always passing the same key to the ConnectionStringManager API, but getting back different strings depending on which server the calling application is running. It's really very handy.

    Sebastian G.
  • Re: Setting Membership/Profile/Role provider's connection string at runtime...?

    06-10-2006, 5:48 AM
    • Member
      357 point Member
    • sebatwerk
    • Member since 04-18-2006, 6:03 AM
    • Posts 72

    zhuhua1006 ,

    So can you, or anyone else here, come up with a solution to help me out?

    Sebastian G.
  • Re: Setting Membership/Profile/Role provider's connection string at runtime...?

    01-16-2008, 11:25 AM
    • Member
      19 point Member
    • pliant
    • Member since 08-30-2007, 1:10 PM
    • Posts 26

    did you ever find a solution to this?

  • Re: Setting Membership/Profile/Role provider's connection string at runtime...?

    03-03-2008, 5:57 PM
    • Member
      4 point Member
    • BDawg
    • Member since 03-03-2008, 10:54 PM
    • Posts 2

     Sounds like your agency is working for the same multi national company that  mine is. any one find anything on this??

     


    --B

  • Re: Setting Membership/Profile/Role provider's connection string at runtime...?

    03-04-2008, 3:50 PM
    • Member
      4 point Member
    • BDawg
    • Member since 03-03-2008, 10:54 PM
    • Posts 2

     OK figured it out...and my multi national company is now saved...ha ha

    This is a one liner gang........

    you will need to create your own providers however, We simply downloaded the SampleProviderToolkitSampleProviders from microsoft to lessen the blow.

    http://download.microsoft.com/download/a/b/3/ab3c284b-dc9a-473d-b7e3-33bacfcc8e98/ProviderToolkitSamples.msi

    Class to modify

    SQLConnectionHelper.cs

    Method to modify

    --------------------------------------------------------------------------------------------------------------------------------------------------------------------------
     

    internal static string GetConnectionString(string specifiedConnectionString, bool lookupConnectionString, bool appLevel)
            {

    //Your Conn String goes here!!

               return Factory.ConnectionString;
            }


    --------------------------------------------------------------------------------------------------------------------------------------------------------------------------

     
    we used our own namespace to be used in the web.congif as well.

    complile that bad boy and your golden..

    have fun

    --b
       
     

     
     

  • Re: Setting Membership/Profile/Role provider's connection string at runtime...?

    08-24-2008, 10:06 PM
    • Member
      4 point Member
    • RGabo
    • Member since 10-16-2006, 8:53 PM
    • Budapest, Hungary
    • Posts 2

     A simpler, albeit somewhat eyebrow-raising solution is just modifying the connection string in the providers early enough in the request's lifecycle:

              private void SetProviderConnectionString(string connectionString)
            {
                // Set private property of Membership, Role and Profile providers. Do not try this at home!!
                var connectionStringField = Membership.Provider.GetType().GetField("_sqlConnectionString", BindingFlags.Instance | BindingFlags.NonPublic);
                if (connectionStringField != null)
                    connectionStringField.SetValue(Membership.Provider, connectionString);

                var roleField = Roles.Provider.GetType().GetField("_sqlConnectionString", BindingFlags.Instance | BindingFlags.NonPublic);
                if (roleField != null)
                    roleField.SetValue(Roles.Provider, connectionString);

                var profileField = ProfileManager.Provider.GetType().GetField("_sqlConnectionString", BindingFlags.Instance | BindingFlags.NonPublic);
                if (profileField != null)
                    profileField.SetValue(ProfileManager.Provider, connectionString);
            }

     Calling this method from Global.asax.cs inside Application_PreRequestHandlerExecute does the job. Haven't tested it too much, but even if something doesn't work, it just means it needs to be done earlier. No guarantees this will work with future versions of the framework, although most likely it will.

    Gabor

    Gabor
  • Re: Setting Membership/Profile/Role provider's connection string at runtime...?

    10-02-2008, 8:00 PM
    • Member
      2 point Member
    • antmx
    • Member since 10-19-2006, 2:05 PM
    • Posts 2

    RGabo you're a star. Your post prompted me to create my own custom SqlMembershipProvider class to tidy this up.

    namespace MyNamespace
    {
    	public class MyMembershipProvider : SqlMembershipProvider
    	{
    		public override void Initialize(string name, System.Collections.Specialized.NameValueCollection config)
    		{
    			base.Initialize(name, config);
    
    			// Update the private connection string field in the base class.
    			string connectionString = "my new connection string value that I get from a custom decryption class not shown here"
    			// Set private property of Membership provider.
    			FieldInfo connectionStringField = GetType().BaseType.GetField("_sqlConnectionString", BindingFlags.Instance | BindingFlags.NonPublic);
    			connectionStringField.SetValue(this, connectionString);
    		}
    	}
    }

     Then in app/web.config I put this:

     

    		<membership defaultProvider="MyMembershipProvider">
    			<providers>
    				<clear />
    				<add name="MyMembershipProvider"
    					  type="MyNamespace.MyMembershipProvider, MyAssembly"
    					  connectionStringName="name of a real but dummy connection string from the connectionStrings section that will never actually get used. Its value could just be 'x'" 
    					  applicationName="MyApp" 
    					  enablePasswordRetrieval="false" 
    					  enablePasswordReset="true" 
    					  requiresQuestionAndAnswer="false" 
    					  requiresUniqueEmail="false" 
    					  minRequiredNonalphanumericCharacters="0" 
    					  passwordFormat="Hashed" />
    			</providers>
    		</membership>
     

     

  • Re: Setting Membership/Profile/Role provider's connection string at runtime...?

    12-22-2008, 12:45 PM
    • Member
      10 point Member
    • pearsonbe
    • Member since 05-15-2008, 2:22 PM
    • Posts 14

    antmx, does this have to go into a separate project from the main one where it is used? I simply created a new class within my main project (LT) like so:

    ==== In Class COBWEBMembershipProvider.vb

    Imports System.Reflection

    Namespace COBWEB
        Public Class COBWEBMembershipProvider
            Inherits SqlMembershipProvider

            Public Overrides Sub Initialize(ByVal name As String, ByVal config As System.Collections.Specialized.NameValueCollection)
                Me.Initialize(name, config)

                ' Update the private connection string field in the base class.
                Dim connString As String = "Data Source=Some Connection String Here"

                ' Set private membership provider property. Reflection is used to discover the attributes of a field and
                ' provide access to the field metadata.

                ' Note: Not sure about the parameter for GetType. C# example did not have it, but VB needs something.

                Dim connStringField As FieldInfo = GetType(FieldInfo).BaseType.GetField("_sqlConnectionString", BindingFlags.Instance Or _
                    BindingFlags.NonPublic)

                connStringField.SetValue(Me, connString)
            End Sub

        End Class
    End Namespace

     

    Add added this to my web.config

    ===== In Web.Config

        <membership defaultProvider="COBWEBMembershipProvider">
          <providers>
            <clear/>
            <add name="COBWEBMembershipProvider"
                 type="COBWEB.COBWEBMembershipProvider, LT"
                 connectionStringName="LTDummy"
                 applicationName="LT"
                 enablePasswordRetrieval="false"
                 enablePasswordReset="true"
                 minRequiredPasswordLength="5"
                 requiresQuestionAndAnswer="true"
                 requiresUniqueEmail="false"
                 passwordFormat="Hashed"
                 maxInvalidPasswordAttempts="5"
                 minRequiredNonalphanumericCharacters="0"
                 passwordAttemptWindow="10"
                 passwordStrengthRegularExpression=""/>
          </providers>
        </membership>

    But i get this error:

    System Message: Could not load type 'COBWEB.COBWEBMembershipProvider' from assembly 'LT'. (C:\Inetpub\wwwroot\LT\LT\LT\web.config line 33)

     I'm looling at the Toolkit Sample Providers now.

  • Re: Setting Membership/Profile/Role provider's connection string at runtime...?

    12-22-2008, 1:15 PM
    • Member
      10 point Member
    • pearsonbe
    • Member since 05-15-2008, 2:22 PM
    • Posts 14

    Since the compiler is telling me it can't find the type (in the *dll), i am going to try putting the code in a separate project and copying to the bin folder.

  • Re: Setting Membership/Profile/Role provider's connection string at runtime...?

    01-06-2009, 2:46 AM
    • Member
      22 point Member
    • Gewgala
    • Member since 07-26-2007, 9:18 PM
    • Posts 71

    RGabo and Antmx - THANK YOU!  That's exactly what I needed.  Searched all over the internet and finally found this thread, I did exactly what you did Antmx and it works like a charm!

  • Re: Setting Membership/Profile/Role provider's connection string at runtime...?

    01-12-2009, 5:49 AM
    • Member
      10 point Member
    • pearsonbe
    • Member since 05-15-2008, 2:22 PM
    • Posts 14

    Gewgala, so you didn't have any issues? I still haven't had it work in the VB version I created so I think I'll try using the exact code in C#.

  • Re: Setting Membership/Profile/Role provider's connection string at runtime...?

    01-12-2009, 12:10 PM
    • Member
      22 point Member
    • Gewgala
    • Member since 07-26-2007, 9:18 PM
    • Posts 71
    Not a single issue, it just worked. One thing I did differently was I erased ", MyAssembly" in the "type" property as shown below, as I'm working on a regular website: <add name="MyMembershipProvider" type="MyNamespace.MyMembershipProvider" ... />
Page 1 of 2 (20 items) 1 2 Next >