Search code examples
asp.netprofile-provider

C# Switching Between Multiple .NET Profile Providers


I am trying to define two profile providers in my web.config. One that uses an external service with its own database and one that connects to the current application's database:

<profile defaultProvider="LocalProfileProvider">
<providers>
   <clear />
   <add name="LocalProfileProvider" ... />
   <add name="ExternalProfileProvider" ... />
</providers>

I am assuming "LocalProfileProvider" will be used by default, but I have some cases when I need to use the "ExternalProfileProvider". I see that I can reference a specific Provider in the ProfileManager like so:

ProfileManager.Providers["ExternalProfileProvider"]

But I'm not seeing how I can tell the application to use this specific provider to allow me to save some profile data in the other system for the current user. Is it possible to define two profile providers and then specify which one you are using at a specific point in the code to save specific properties?


Solution

  • Figured it out... very simple really, but my google searches never turned up the specific answer I needed:

    SqlProfileProvider p = (SqlProfileProvider)Profile.Providers["ExternalProfileProvider"];
    SettingsPropertyValueCollection pvalues = p.GetPropertyValues(Profile.Context, ProfileBase.Properties);
    
    pvalues["FirstName"].PropertyValue = "Bob";
    pvalues["LastName"].PropertyValue = "Bobertson";
    
    
    p.SetPropertyValues(Profile.Context, pvalues);
    

    Additional Edit:

    If you want to access and edit a different user's profile, be sure to use the proper profile context like so:

    ProfileCommon userProfile = Profile.GetProfile("bob");
    SqlProfileProvider p = (SqlProfileProvider)userProfile.Providers["ExternalProfileProvider"];
    SettingsPropertyValueCollection pvalues = p.GetPropertyValues(userProfile.Context, ProfileBase.Properties);
    
    pvalues["FirstName"].PropertyValue = "Bob";
    pvalues["LastName"].PropertyValue = "Bobertson";
    
    p.SetPropertyValues(userProfile.Context, pvalues);