Search code examples
c#asp.netmembership-providersqlprofileprovider

Modifying ProfileBase ConnectionString dynamically


I have the following code, which I want to use to modify the ProfileBase connectionString:

ProfileBase profile = ProfileBase.Create(username);

string _connectionString = (_DataModel.Connection as System.Data.EntityClient.EntityConnection).StoreConnection.ConnectionString;

FieldInfo connectionStringField = profile.Providers["MySqlProfileProvider"].GetType().BaseType.GetField("_sqlConnectionString", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
connectionStringField.SetValue(profile.Providers["MySqlProfileProvider"], _connectionString);

profile["FirstName"] = firstName;
profile["Surname"] = surname;

profile.Save();

First of all the connectionStringField always comes back as null, however I can see that profile.Providers does contain MySqlProfileProvider. This is specified within my Web.Config:

<profile defaultProvider="MySqlProfileProvider">
  <providers>
    <clear/>
    <add name="MySqlProfileProvider" connectionStringName="MyApp" applicationName="MyApp" type="System.Web.Profile.SqlProfileProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>
  </providers>
  <properties>
    <add allowAnonymous="false" defaultValue="" name="FirstName" readOnly="false" serializeAs="String" type="System.String"/>
    <add allowAnonymous="false" defaultValue="" name="Surname" readOnly="false" serializeAs="String" type="System.String"/>
  </properties>
</profile>

My question is how come connectionStringField is coming back as null? Does this mean I cannot modify the connection string like I normally would with a custom MembershipProvider by overriding its Initialize method?


Solution

  • You went one too many basetypes down:

    .Providers["MySqlProfileProvider"].GetType()**.BaseType**.GetField
    .Providers["MySqlProfileProvider"].GetType().GetField
    

    The following code should work:

    string _connectionString = (_DataModel.Connection as System.Data.EntityClient.EntityConnection).StoreConnection.ConnectionString;
    Type type = profile.Providers["MySqlProfileProvider"].GetType();
    FieldInfo connectionStringField = type.GetField("_sqlConnectionString", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
    connectionStringField.SetValue(profile.Providers["MySqlProfileProvider"], _connectionString);