How to assign Profile values? - asp.net

I don't know what I am missing, but I added Profile properties in the Web.config file but cannot access Profile.Item in the code or create a new profile.

I had the same problem today, and learned a lot.
There are two kinds of project in Visual Studio -- "Web Site Projects" and "Web Application Projects." For reasons which are a complete mystery to me, Web Application Projects cannot use Profile. directly... the strongly-typed class is not magically generated for you from the Web.config file, so you have to roll your own.
The sample code in MSDN assumes you are using a Web Site Project, and they tell you just to add a <profile> section to your Web.config and party on with Profile.property, but that doesn't work in Web Application Projects.
You have two choices to roll your own:
(1) Use the Web Profile Builder. This is a custom tool you add to Visual Studio which automatically generates the Profile object you need from your definition in Web.config.
I chose not to do this, because I didn't want my code to depend on this extra tool to compile, which could have caused problems for someone else down the line when they tried to build my code without realizing that they needed this tool.
(2) Make your own class that derives from ProfileBase to represent your custom profile. This is easier than it seems. Here's a very very simple example that adds a "FullName" string profile field:
In your web.config:
<profile defaultProvider="SqlProvider" inherits="YourNamespace.AccountProfile">
<providers>
<clear />
<add name="SqlProvider"
type="System.Web.Profile.SqlProfileProvider"
connectionStringName="sqlServerMembership" />
</providers>
</profile>
In a file called AccountProfile.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Profile;
using System.Web.Security;
namespace YourNamespace
{
public class AccountProfile : ProfileBase
{
static public AccountProfile CurrentUser
{
get { return (AccountProfile)
(ProfileBase.Create(Membership.GetUser().UserName)); }
}
public string FullName
{
get { return ((string)(base["FullName"])); }
set { base["FullName"] = value; Save(); }
}
// add additional properties here
}
}
To set a profile value:
AccountProfile.CurrentUser.FullName = "Snoopy";
To get a profile value
string x = AccountProfile.CurrentUser.FullName;

Web Application Projects can still use the ProfileCommon object but only at runtime. The code for it is just not generated in the project itself but the class is generated by ASP.Net and is present at runtime.
The simplest way to get to object is to use a dynamic type as demonstrated below.
In the Web.config file declare the profile properties:
<profile ...
<properties>
<add name="GivenName"/>
<add name="Surname"/>
</properties>
Then to access the properties:
dynamic profile = ProfileBase.Create(Membership.GetUser().UserName);
string s = profile.GivenName;
profile.Surname = "Smith";
To save changes to profile properties:
profile.Save();
The above works fine if you are comfortable using dynamic types and don't mind the lack of compile-time checking and intellisense.
If you use this with ASP.Net MVC you have to do some additional work if you pass the dynamic profile object to your views since the HTML helper methods don't play well with "model" objects that are dynamic. You will have to assign profile properties to statically typed variables before passing them to HTML helper methods.
// model is of type dynamic and was passed in from the controller
#Html.TextBox("Surname", model.Surname) <-- this breaks
#{ string sn = model.Surname; }
#Html.TextBox("Surname", sn); <-- will work
If you create a custom profile class, as Joel described above, ASP.Net will still generate the ProfileCommon class but it will inherit from your custom profile class. If you don't specify a custom profile class ProfileCommon will inherit from System.Web.Profile.ProfileBase.
If you create your own profile class make sure that you don't specify profile properties in the Web.config file that you've already declared in your custom profile class. If you do ASP.Net will give a compiler error when it tries to generate the ProfileCommon class.

Profile can be used in Web Application Projects too.
The properties can be defined in Web.config at design time or programmatically. In Web.config:
<profile enabled="true" automaticSaveEnabled="true" defaultProvider="AspNetSqlProfileProvider">
<providers>
<clear/>
<add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="ApplicationServices" applicationName="TestRolesNProfiles"/>
</providers>
<properties>
<add name="FirstName"/>
<add name="LastName"/>
<add name ="Street"/>
<add name="Address2"/>
<add name="City"/>
<add name="ZIP"/>
<add name="HomePhone"/>
<add name="MobilePhone"/>
<add name="DOB"/>
</properties>
</profile>
or Programmatically, create the profile section by instantiating a ProfileSection and creating individual properties using ProfilePropertySettings and ProfilePropertySettingsColletion, all of which are in System.Web.Configuration Namespace.
To use those properties of the profile, use System.Web.Profile.ProfileBase Objects. The profile properties cannot be accessed with profile. syntax as mentioned above, but can be easily done by instantiating a ProfileBase and using SetPropertyValue("PropertyName") and GetPropertyValue{"PropertyName") as follows:
ProfileBase curProfile = ProfileBase.Create("MyName");
or to access the profile of current user:
ProfileBase curProfile = ProfileBase.Create(System.Web.Security.Membership.GetUser().UserName);
curProfile.SetPropertyValue("FirstName", this.txtName.Text);
curProfile.SetPropertyValue("LastName", this.txtLname.Text);
curProfile.SetPropertyValue("Street", this.txtStreet.Text);
curProfile.SetPropertyValue("Address2", this.txtAdd2.Text);
curProfile.SetPropertyValue("ZIP", this.txtZip.Text);
curProfile.SetPropertyValue("MobilePhone", txtMphone.Text);
curProfile.SetPropertyValue("HomePhone", txtHphone.Text);
curProfile.SetPropertyValue("DOB", txtDob.Text);
curProfile.Save();

When you create a new Web site project in Visual Studio then the object that is returned from Profile will be (automatically) generated for you. When you create a Web application project or an MVC project, you will have to roll your own.
This probably sounds more difficult than it is. You need to do the following:
Create a database using aspnet_regsql.exe This tool is installed along with the .NET framework.
Write a class that derives from ProfileGroupBase or install the Web Profile Builder (WPB) that can generate the class for you from the definition in Web.Config. I have been using WPB for a while and up until now it has done what is expected of it. If you have a lot of properties, using WPB can save quite a bit of time.
Make sure the connection to the database is properly configured in Web.Config.
Now you are set to create an instance of your profile class (in the controller)
You will probably need the profile property values in your views. I like to pass the profile object itself along to the view (not individual properties).

If you are using a web application project, you cannot access the Profile object at design-time out-of-the-box. Here is a utility that supposedly does it for you: http://weblogs.asp.net/joewrobel/archive/2008/02/03/web-profile-builder-for-web-application-projects.aspx. Personally, that utility caused an error in my project so I ended up rolling my own profile class to inherit from ProfileBase. It was not hard to do at all.

MSDN walkthrough for creating a custom class (a.k.a. Joel's method):
http://msdn.microsoft.com/en-us/magazine/cc163624.aspx

I was also running through the same issue. But instead of creating a class which inherits from ProfileBase, I used the HttpContext.
Specify properties in web.config file as follows : -
Now, write the following code : -
Compile and run the code. You will get following output: -

The Web Profile Builder worked great for me. The class it generated has a lot more in it than as described by Joel's post. Whether or not its actually needed or useful I dont know.
Anyway for those looking for an easy way to generate the class, but not wanting to have an external build tool dependency you can always
use the web profile builder
delete all trace of it!
keep using the generated Profile class
OR (untested but may just work)
create a web site project
create your element
snap the generated class and copy it over to your web project project
if this second approach does work can someone let me know for future reference

Just want to add to Joel Spolsky's answer
I implemented his solution, working brilliantly btw - Cudos!
For anyone wanting to get a user profile that's not the logged in user I used:
web.config:
<connectionStrings>
<clear />
<add name="LocalSqlConnection" connectionString="Data Source=***;Database=***;User Id=***;Password=***;Initial Catalog=***;Integrated Security=false" providerName="System.Data.SqlClient" />
</connectionStrings>
and
<profile defaultProvider="SqlProvider" inherits="NameSpace.AccountProfile" enabled="true">
<providers>
<clear/>
<add name="SqlProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="LocalSqlConnection"/>
</providers>
And then my custom class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Profile;
using System.Web.Security;
namespace NameSpace
{
public class AccountProfile : ProfileBase
{
static public AccountProfile CurrentUser
{
get
{
return (AccountProfile)
(ProfileBase.Create(Membership.GetUser().UserName));
}
}
static public AccountProfile GetUser(MembershipUser User)
{
return (AccountProfile)
(ProfileBase.Create(User.UserName));
}
/// <summary>
/// Find user with matching barcode, if no user is found function throws exception
/// </summary>
/// <param name="Barcode">The barcode to compare against the user barcode</param>
/// <returns>The AccountProfile class with matching barcode or null if the user is not found</returns>
static public AccountProfile GetUser(string Barcode)
{
MembershipUserCollection muc = Membership.GetAllUsers();
foreach (MembershipUser user in muc)
{
if (AccountProfile.GetUser(user).Barcode == Barcode)
{
return (AccountProfile)
(ProfileBase.Create(user.UserName));
}
}
throw new Exception("User does not exist");
}
public bool isOnJob
{
get { return (bool)(base["isOnJob"]); }
set { base["isOnJob"] = value; Save(); }
}
public string Barcode
{
get { return (string)(base["Barcode"]); }
set { base["Barcode"] = value; Save(); }
}
}
}
Works like a charm...

Great post,
Just a note on the web.config
if you dont specify the inherit attribute in the profile element
you will need to specify each indiviudal profile property inside the profile
element on the web.config as below
<properties>
<clear/>
<add name="property-name-1" />
<add name="property-name-2" />
..........
</properties>

Related

How to re-implement legacy aspx with ServiceStack and maintain the address?

Is it possible to keep the following address and re-implement it with ServiceStack?
http://example.com/Routing/LeadPost.aspx?LeadType=AAA&MYId=3000
I don't have access to the original code as it was a 3rd party who created it, but I do know what the post to it, a gigantic xml package. This I have mimicked perfectly with a clean request DTO and service, but I'm not clear on the addressing part, or if it's even plausible. Below is my implementation so far.
public class Service : ServiceStack.Service
{
public IMessageQueueClient MessageQueueClient { get; set; }
public object Post(LeadInformation request)
{
if (request == null) throw new ArgumentNullException("request");
var sw = Stopwatch.StartNew();
MessageQueueClient.Publish(request);
return new LeadInformationResponse
{
TimeTakenMs = sw.ElapsedMilliseconds,
};
}
}
Thank you,
Stephen
You can use this route definition to handle the Legacy ASP.NET WebForms Request:
[Route("/Routing/LeadPost.aspx")]
public class LegacyLeadPost
{
public string LeadType { get; set; }
public int MyId { get; set; }
}
Which will let you handle the desired route with LeadType and MyId properties populated:
/Routing/LeadPost.aspx?LeadType=AAA&MYId=3000
An alternative approach is to use a WebForms Page and call into ServiceStack, the ServiceStack Integration docs explores the different ways from accessing ServiceStack from external ASP.NET MVC or WebForms Web Frameworks.
When you installed ServiceStack (at least up to version 3, which is what I last used), it adds something to your application's Web.Config file that looks like:
<system.web>
<httpHandlers>
<add path="somePath/*" type="ServiceStack.WebHost.Endpoints.ServiceStackHttpHandlerFactory, ServiceStack" verb="*" />
</httpHandlers>
</system.web>
If you modify the path attribute to match your legacy URL, it may work. Then again, without knowing what other HttpHandlers are set up for your application, it is impossible to tell for sure. Also keep in mind that you may introduce conflicts, because there is an HttpHandler that passes all .aspx urls to the .NET webforms Page base class and all the other code-behind files in your application.

Profile Provider and Properties have been set but I can't access Profile properties

I'm using MVC4 and I want to store a couple of values in the profile.
Why does
TempData["badgerName"] = Profile.BadgerName;
say that ProfileBase does not contain a definition for BadgerName?
I have set up Profile as below.
<profile defaultProvider="DefaultProfileProvider">
<providers>
<add
name="DefaultProfileProvider"
type="System.Web.Providers.DefaultProfileProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
connectionStringName="FALContext"
applicationName="/" />
</providers>
<properties>
<add name="BadgerName" type="String"/>
</properties>
</profile>
In ASP MVC you don't have a profile object generated for your site with the properties defined in the web.config file. The property Profile that can be accessed from the controller methods is of type ProfileBase (see msdn) and does not contains strongly typed properties for your custom profile properties. As you may also be aware, this profile is loaded for the logged in user at the beggining of the request and any changes are saved at the end of the request.
There are different ways you can work the ProfileBase class. The most used ones are:
use directly the ProfileBase class
create a derived custom profile class.
When ProfileBase is used directly, you need to either use the instance from the controller method or get an instance given an user name. Then you should use indexers to access the profile properties. Let's say your controller method received an object of type UserModel that contains your user data like an email and the BadgerName, then you could write code like this:
//Getting the instance from the controller property:
ProfileBase profile = this.Profile; //or even: this.HttpContext.Profile
//You can also get the profile for a given existing user.
ProfileBase profile = ProfileBase.Create(userModel.Name);
//Then update properties using indexer
profile["Email"] = userModel.Email;
profile["BadgerName"] = userModel.BadgerName;
//Manually save changes
//(Can be skipped for the profile automatically loaded in the Controller)
profile.Save();
However if you create a derived class from ProfileBase, you will end up using your class much in the same way you originally intended. You will basically create a wrapper class with strongly typed properties that internally access the ProfileBase using indexers (A summary of the approach is here):
public class MyCustomProfile : ProfileBase
{
public string Email
{
get { return base["Email"] as string; }
set { base["Email"] = value; }
}
public string BadgerName
{
get { return base["BadgerName"] as string; }
set { base["BadgerName"] = value; }
}
//If needed, you can provide methods to recover profiles
//for the logged in user or any user given its user name
public static MyCustomProfile GetCurrent()
{
return Create(Membership.GetUser().UserName) as MyCustomProfile;
}
public static MyCustomProfile GetProfile(string userName)
{
return Create(userName) as MyCustomProfile;
}
}
If you use this option, you also need to make sure the <profile> element of the web.config has the inherits attribute set to your custom model class:
<profile enabled="true" defaultProvider="DefaultProfileProvider" inherits="yourNamespace.MyCustomProfile">
With this code and config in place, you can start using your custom profile class by either recovering user profiles yourselve or by casting the controller Profile property to your custom class:
//Cast the Profile property of the controller to your custom class
MyCustomProfile profile = this.Profile as MyCustomProfile // or even: HttpContext.Profile as MyCustomProfile
//You could also manually load the profile for given an user name
profile = MyCustomProfile.GetProfile(userModel.Name);
//Or even manually load the profile for the logged in user
profile = MyCustomProfile.GetCurrent();
//Now get/set the profile properties using the strongly typed properties of your class
profile.Email= userModel.Email;
profile.BadgerName= userModel.BadgerName;
//Manually save changes
//(Can be skipped for the profile automatically loaded in the Controller)
profile.Save();
Hope this helps!

How to use Custom SiteMapProvider in ASP NET MVC?

I am currently trying to implement a Custom SiteMap Provider. I have read several tutorials about it, and followed their lead.
I have created a subclass of XmlSiteMapProvider named MySiteMapProvider which is located in MyProject.Security.
I have added the following code to the system.web section of my Web.config:
<siteMap defaultProvider="MySiteMapProvider" enabled="true">
<providers>
<add name="MySiteMapProvider"
description="Custom SiteMap provider."
type="MyProject.Security.MySiteMapProvider "
siteMapFile="Web.sitemap"
securityTrimmingEnabled="true" />
</providers>
</siteMap>
But I am sure that my Provider is not used correctly. I couldn't even start with the implementation. To verify that I have included the following (pseudo) implementation:
public override bool IsAccessibleToUser(System.Web.HttpContext context, System.Web.SiteMapNode node)
{
Debug.Print("Hello World");
throw new Exception();
return base.IsAccessibleToUser(context, node);
}
public override void Initialize(string name, System.Collections.Specialized.NameValueCollection attributes)
{
Debug.Print("Hello World");
throw new Exception();
base.Initialize(name, attributes);
}
public override SiteMapNode BuildSiteMap()
{
Debug.Print("Hello World");
throw new Exception();
return base.BuildSiteMap();
}
But I can use the site and navigate as much as I want to, no Exception comes up and the Debug console shows no Hello World at all.
Did I forget something important?
Instead of implementing my own Provider, I went along with the MvcSiteMapProvider.
The customization of the behaviour that I needed to implement was realized in one day with dynamic sitemaps and a custom SiteMapNodeVisibilityProvider.
I also considered implementing the whole SiteMapProvider, maybe on SQL basis, and I am glad that I did not have to do it.
Try calling System.Web.SiteMap.RootNode from code.

Correct way of adding Page Method to ASP MVC project?

I'm just getting started with ASP.NET and the MVC model. I've worked my around the basic concepts and have a few models, controllers, and views working fine. I know how to add Web Methods and Page Methods to a Web Service, but cannot figure it out for MVC projects.
I (think) I need to add a Page Method to my project as the correct way of responding to AJAX requests. This is what my controller looks like:
namespace MyProject
{
public class OrderController : Controller
{
public ActionResult Place (ProductSku sku)
{
var order = Order.NewOrder(sku);
var db = new SystemDiscsLib.Database();
db.SaveOrder(order);
return View(order);
}
[WebMethod]
public static string GetDate ()
{
return DateTime.Now.ToString();
}
POSTing to /Order/Place works fine, and the view is created displaying the contents of Views/Order/Place.aspx and everyone is happy. However, any requests made to /Order/GetDate fail with a The resource cannot be found error. I (think) I have correctly enabled Page Methods by adding this to my Web.config, under system.web:
<httpModules>
<add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
</httpModules>
I do not have a view called GetDate as I don't want a view, I'll just be returning JSON data. I intend to use JQuery, so I didn't do the EnablePageMethods and ScripManager stuff, per this article.
PageMethods are for WebForms, not MVC. Change your method to look more like this:
public JsonResult GetDate()
{
return Json(DateTime.Now.ToString());
}
Note that the method is no longer static, and you should not use the [WebMethod] attribute.

profile in asp.net MVC [duplicate]

I don't know what I am missing, but I added Profile properties in the Web.config file but cannot access Profile.Item in the code or create a new profile.
I had the same problem today, and learned a lot.
There are two kinds of project in Visual Studio -- "Web Site Projects" and "Web Application Projects." For reasons which are a complete mystery to me, Web Application Projects cannot use Profile. directly... the strongly-typed class is not magically generated for you from the Web.config file, so you have to roll your own.
The sample code in MSDN assumes you are using a Web Site Project, and they tell you just to add a <profile> section to your Web.config and party on with Profile.property, but that doesn't work in Web Application Projects.
You have two choices to roll your own:
(1) Use the Web Profile Builder. This is a custom tool you add to Visual Studio which automatically generates the Profile object you need from your definition in Web.config.
I chose not to do this, because I didn't want my code to depend on this extra tool to compile, which could have caused problems for someone else down the line when they tried to build my code without realizing that they needed this tool.
(2) Make your own class that derives from ProfileBase to represent your custom profile. This is easier than it seems. Here's a very very simple example that adds a "FullName" string profile field:
In your web.config:
<profile defaultProvider="SqlProvider" inherits="YourNamespace.AccountProfile">
<providers>
<clear />
<add name="SqlProvider"
type="System.Web.Profile.SqlProfileProvider"
connectionStringName="sqlServerMembership" />
</providers>
</profile>
In a file called AccountProfile.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Profile;
using System.Web.Security;
namespace YourNamespace
{
public class AccountProfile : ProfileBase
{
static public AccountProfile CurrentUser
{
get { return (AccountProfile)
(ProfileBase.Create(Membership.GetUser().UserName)); }
}
public string FullName
{
get { return ((string)(base["FullName"])); }
set { base["FullName"] = value; Save(); }
}
// add additional properties here
}
}
To set a profile value:
AccountProfile.CurrentUser.FullName = "Snoopy";
To get a profile value
string x = AccountProfile.CurrentUser.FullName;
Web Application Projects can still use the ProfileCommon object but only at runtime. The code for it is just not generated in the project itself but the class is generated by ASP.Net and is present at runtime.
The simplest way to get to object is to use a dynamic type as demonstrated below.
In the Web.config file declare the profile properties:
<profile ...
<properties>
<add name="GivenName"/>
<add name="Surname"/>
</properties>
Then to access the properties:
dynamic profile = ProfileBase.Create(Membership.GetUser().UserName);
string s = profile.GivenName;
profile.Surname = "Smith";
To save changes to profile properties:
profile.Save();
The above works fine if you are comfortable using dynamic types and don't mind the lack of compile-time checking and intellisense.
If you use this with ASP.Net MVC you have to do some additional work if you pass the dynamic profile object to your views since the HTML helper methods don't play well with "model" objects that are dynamic. You will have to assign profile properties to statically typed variables before passing them to HTML helper methods.
// model is of type dynamic and was passed in from the controller
#Html.TextBox("Surname", model.Surname) <-- this breaks
#{ string sn = model.Surname; }
#Html.TextBox("Surname", sn); <-- will work
If you create a custom profile class, as Joel described above, ASP.Net will still generate the ProfileCommon class but it will inherit from your custom profile class. If you don't specify a custom profile class ProfileCommon will inherit from System.Web.Profile.ProfileBase.
If you create your own profile class make sure that you don't specify profile properties in the Web.config file that you've already declared in your custom profile class. If you do ASP.Net will give a compiler error when it tries to generate the ProfileCommon class.
Profile can be used in Web Application Projects too.
The properties can be defined in Web.config at design time or programmatically. In Web.config:
<profile enabled="true" automaticSaveEnabled="true" defaultProvider="AspNetSqlProfileProvider">
<providers>
<clear/>
<add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="ApplicationServices" applicationName="TestRolesNProfiles"/>
</providers>
<properties>
<add name="FirstName"/>
<add name="LastName"/>
<add name ="Street"/>
<add name="Address2"/>
<add name="City"/>
<add name="ZIP"/>
<add name="HomePhone"/>
<add name="MobilePhone"/>
<add name="DOB"/>
</properties>
</profile>
or Programmatically, create the profile section by instantiating a ProfileSection and creating individual properties using ProfilePropertySettings and ProfilePropertySettingsColletion, all of which are in System.Web.Configuration Namespace.
To use those properties of the profile, use System.Web.Profile.ProfileBase Objects. The profile properties cannot be accessed with profile. syntax as mentioned above, but can be easily done by instantiating a ProfileBase and using SetPropertyValue("PropertyName") and GetPropertyValue{"PropertyName") as follows:
ProfileBase curProfile = ProfileBase.Create("MyName");
or to access the profile of current user:
ProfileBase curProfile = ProfileBase.Create(System.Web.Security.Membership.GetUser().UserName);
curProfile.SetPropertyValue("FirstName", this.txtName.Text);
curProfile.SetPropertyValue("LastName", this.txtLname.Text);
curProfile.SetPropertyValue("Street", this.txtStreet.Text);
curProfile.SetPropertyValue("Address2", this.txtAdd2.Text);
curProfile.SetPropertyValue("ZIP", this.txtZip.Text);
curProfile.SetPropertyValue("MobilePhone", txtMphone.Text);
curProfile.SetPropertyValue("HomePhone", txtHphone.Text);
curProfile.SetPropertyValue("DOB", txtDob.Text);
curProfile.Save();
When you create a new Web site project in Visual Studio then the object that is returned from Profile will be (automatically) generated for you. When you create a Web application project or an MVC project, you will have to roll your own.
This probably sounds more difficult than it is. You need to do the following:
Create a database using aspnet_regsql.exe This tool is installed along with the .NET framework.
Write a class that derives from ProfileGroupBase or install the Web Profile Builder (WPB) that can generate the class for you from the definition in Web.Config. I have been using WPB for a while and up until now it has done what is expected of it. If you have a lot of properties, using WPB can save quite a bit of time.
Make sure the connection to the database is properly configured in Web.Config.
Now you are set to create an instance of your profile class (in the controller)
You will probably need the profile property values in your views. I like to pass the profile object itself along to the view (not individual properties).
If you are using a web application project, you cannot access the Profile object at design-time out-of-the-box. Here is a utility that supposedly does it for you: http://weblogs.asp.net/joewrobel/archive/2008/02/03/web-profile-builder-for-web-application-projects.aspx. Personally, that utility caused an error in my project so I ended up rolling my own profile class to inherit from ProfileBase. It was not hard to do at all.
MSDN walkthrough for creating a custom class (a.k.a. Joel's method):
http://msdn.microsoft.com/en-us/magazine/cc163624.aspx
I was also running through the same issue. But instead of creating a class which inherits from ProfileBase, I used the HttpContext.
Specify properties in web.config file as follows : -
Now, write the following code : -
Compile and run the code. You will get following output: -
The Web Profile Builder worked great for me. The class it generated has a lot more in it than as described by Joel's post. Whether or not its actually needed or useful I dont know.
Anyway for those looking for an easy way to generate the class, but not wanting to have an external build tool dependency you can always
use the web profile builder
delete all trace of it!
keep using the generated Profile class
OR (untested but may just work)
create a web site project
create your element
snap the generated class and copy it over to your web project project
if this second approach does work can someone let me know for future reference
Just want to add to Joel Spolsky's answer
I implemented his solution, working brilliantly btw - Cudos!
For anyone wanting to get a user profile that's not the logged in user I used:
web.config:
<connectionStrings>
<clear />
<add name="LocalSqlConnection" connectionString="Data Source=***;Database=***;User Id=***;Password=***;Initial Catalog=***;Integrated Security=false" providerName="System.Data.SqlClient" />
</connectionStrings>
and
<profile defaultProvider="SqlProvider" inherits="NameSpace.AccountProfile" enabled="true">
<providers>
<clear/>
<add name="SqlProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="LocalSqlConnection"/>
</providers>
And then my custom class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Profile;
using System.Web.Security;
namespace NameSpace
{
public class AccountProfile : ProfileBase
{
static public AccountProfile CurrentUser
{
get
{
return (AccountProfile)
(ProfileBase.Create(Membership.GetUser().UserName));
}
}
static public AccountProfile GetUser(MembershipUser User)
{
return (AccountProfile)
(ProfileBase.Create(User.UserName));
}
/// <summary>
/// Find user with matching barcode, if no user is found function throws exception
/// </summary>
/// <param name="Barcode">The barcode to compare against the user barcode</param>
/// <returns>The AccountProfile class with matching barcode or null if the user is not found</returns>
static public AccountProfile GetUser(string Barcode)
{
MembershipUserCollection muc = Membership.GetAllUsers();
foreach (MembershipUser user in muc)
{
if (AccountProfile.GetUser(user).Barcode == Barcode)
{
return (AccountProfile)
(ProfileBase.Create(user.UserName));
}
}
throw new Exception("User does not exist");
}
public bool isOnJob
{
get { return (bool)(base["isOnJob"]); }
set { base["isOnJob"] = value; Save(); }
}
public string Barcode
{
get { return (string)(base["Barcode"]); }
set { base["Barcode"] = value; Save(); }
}
}
}
Works like a charm...
Great post,
Just a note on the web.config
if you dont specify the inherit attribute in the profile element
you will need to specify each indiviudal profile property inside the profile
element on the web.config as below
<properties>
<clear/>
<add name="property-name-1" />
<add name="property-name-2" />
..........
</properties>

Resources