Getting the Profile property value in the Class Library Project

This question was asked many times on www.asp.net forums so I decided to take a look at it. The question is that how we can get the value from the Profile object when using the Profile object inside the class library. I am assuming that your project contains the object of type User. The class User is created inside the ClassLibrary project which is part of the same solution as the Web Application Project.

Here is the class User defined in the ClassLibrary Project.

 [Serializable]
    
public class User
    {
        
private string firstName; 
        
private string lastName;

        
public string FirstName
        {
            
get return this.firstName; }
            
set this.firstName = value; } 
        }

        
public string LastName
        {
            
get return this.lastName; }
            
set this.lastName = value; } 
        }

Next, step is to define the properties inside the Web.config.

<connectionStrings>
    <
add name="ConnectionString"
    connectionString="Server=localhost
    
    ;Database=Tasks;Trusted_Connection=
true"/>
  </connectionStrings>
    <system.web>


    <!-- PROFILE CONFIGURATION -->

    <profile defaultProvider="MyProfileProvider">
      <providers>
        <
add connectionStringName="ConnectionString"
        name="MyProfileProvider"
        type="System.Web.Profile.SqlProfileProvider"/>
      </providers>
      <properties>
        <
add name="User" type="ClassLibrary1.User"/>        
      </properties>
      
    </profile>
  

Now, you can assign the values to the Profile from the Web Application Project.

Profile.User.FirstName = "Mohammad";
        Profile.User.LastName = "Azam";

        ClassLibrary1.User newUser = 
new ClassLibrary1.User();
        newUser.Save(); 

And now to access the Profile object from the ClassLibrary project you can use the following code:

ProfileBase pb = HttpContext.Current.Profile;
            User user = (User)pb["User"];  
 

Your user will contain the FirstName and LastName which you set in the Web Application Project.

powered by IMHO 1.3

Print | posted @ Friday, April 14, 2006 10:31 AM

Twitter