I cant figure out how to use Profile.GetProfile() method in a library class.
I tried using this method in a Page.aspx.cs and it worked perfectly.
How can I make a method that works in the page.aspx.cs, work in the class library.
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
In ASP.NET, Profile is a hook into the HttpContext.Current.Profile property, which returns a dynamically generated object of type ProfileCommon, derived from System.Web.Profile.ProfileBase.
ProfileCommon apparently includes a GetProfile(string username) method, but you wont find it documented officially in MSDN (and it wont show up in intellisense in visual studio) because most of the ProfileCommon class is dynamically generated when your ASP.NET application is compiled (The exact list of properties and methods will depend on how ‘profiles’ are configured in your web.config). GetProfile() does get a mention on this MSDN page, so it seems to be real.
Perhaps in your library class, the problem is that the configuration info from web.config is not being picked up. Is your library class part of a Solultion that includes a Web Application, or are you just working on the library in isolation?
Method 2
Have you tried adding reference to System.Web.dll to your class library and then:
if (HttpContext.Current == null)
{
throw new Exception("HttpContext was not defined");
}
var profile = HttpContext.Current.Profile;
// Do something with the profile
Method 3
You can use ProfileBase, but you lose type-safety. You can mitigate that with careful casting and error handling.
string user = "Steve"; // The username you are trying to get the profile for.
bool isAuthenticated = false;
MembershipUser mu = Membership.GetUser(user);
if (mu != null)
{
// User exists - Try to load profile
ProfileBase pb = ProfileBase.Create(user, isAuthenticated);
if (pb != null)
{
// Profile loaded - Try to access profile data element.
// ProfileBase stores data as objects in a Dictionary
// so you have to cast and check that the cast succeeds.
string myData = (string)pb["MyKey"];
if (!string.IsNullOrWhiteSpace(myData))
{
// Woo-hoo - We're in data city, baby!
Console.WriteLine("Is this your card? " + myData);
}
}
}
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0