Tuesday, October 18, 2011

Accessing Website object in Class Library

Few days ago I was stuck in a problem. I was working in web-application, which has multiple projects in it. I had a user object, for storing user information. It was stored in a session object.

In order to fulfill one of my requirements, it was required in a class library. I did some RND and found a solution to create a separate shared class library project, for both my website and other project.

It was not a good idea for me to change the user object reference everywhere. So I thought that reflection may help in this. After playing with it, I found a solution

and here it is:


object type = System.Web.HttpContext.Current.Session["User"];

// Get the FieldInfo of MyClass.
System.Reflection.FieldInfo[] myFields = myType.GetType().GetFields(System.Reflection.BindingFlags.Public
| System.Reflection.BindingFlags.Instance);


// Display the values of the fields.
Console.WriteLine("\nDisplaying the values of the fields of {0}.\n",
type);

//iterate Field-info and get values.... :)

for(int i = 0; i < myFields.Length; i++)

{
Console.WriteLine("The value of {0} is: {1}",
myFields[i].Name, myFields[i].GetValue(type));

}

Thank You.

Happy Coding.......

No comments:

Post a Comment

Earn Money ! Affiliate Program
Open Directory Project at dmoz.org