.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month
Gaurav Pal
Post New Web Links

Accessing Session or Cookie in Custom RoleProvider

Posted By:      Posted Date: September 29, 2010    Points: 0   Category :ASP.Net

We have a requirement like, a logged in user, who play administrator role, can act as a general user. When the administrator acts like a general user he will be authorized to view the pages allowed to the general user.

For every request the framework calls GetRolesForUser by passing the logged in user id. Here instead of returning the administrator role we want to return the roles associated to the general user. When we access HttpContext.Current.Session, unfortunately the session is null, even the Cookies are deleted by the framework before we access it. We are not able to use either Session or Cookies to know the logged in user acting as a general user.

The act as General user page:

Session["UID"] = "General User ID";

// Redirect to General user home page.


The custom role provider code:

public override

View Complete Post

More Related Resource Links

Accessing Session State in a User Control

We have a web site that implements a custom SiteMapProvider using a User Control added in the master page. I need to be able to limit the sitemap nodes added depending on the logged in user, that is, certain users should not see certain sitemap nodes. Currently, the login processing code determines if users are in the certain category or role and then sets a value in session state, for example, Session["UserInRoleXXX"] = "Yes"; I tried changing the code in the user control to check the session state, but I got the following error: NullReferenceException ... Object reference not set to an instance of an object." Can session state be accessed in a user control? If so, how? If not, any suggested solutions? Thanks in advance for any help.

Best way to connect a Cookie to a session?

I usually like to do it the hard way, just to get a feel of what you can do! In ASP.net there is probably a really simple way Forms authentication etc. but this is what I have. I know from previous experience that you should never save a Cookie that contains a password, so how to connect a session to a cookie when the user accesses the website, with saved cookies information. I though about using a Guid, in the cookie, and then check the database to see if that guid is available, but this could be a sort of password like effect. Here is my code. Private Sub Login1_LoggingIn(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.LoginCancelEventArgs) Handles Login1.LoggingIn Dim mDbase As New SQL("<Server>", "<Database>", "", "", True) mDbase.Open() Dim mUserItem As UserItem = mDbase.Record.Item("SELECT TOP 1 Username, First, Surname, AccessLevel, LastVisited FROM TBLUsers WHERE Username='" & Me.Login1.UserName & "' AND Password='" & Me.Login1.Password & "'", GetType(UserItem)) If mUserItem IsNot Nothing Then If Me.Login1.RememberMeSet = True Then 'Dim mGuid As Guid = System.Guid.NewGuid 'mGuid.ToString() 'Create cookie data End If If Session("User") Is Nothin

Weird problem with session cookie

Hi all,I'm having a weird problem with my web application, and I can't find the solution to it.I'm using a Java applet to read some data from an electronic ID. This applet posts its captured data to a HttpHandler class and stores the data back in some session variables. It all works smoothly, unless in some cases.Every time a do a new publish to the webserver or the website isn't touched for some time. There is a problem with the session.The applet can't find a session cookie, and so it crashes.I did some tests and indeed, the cookie ("ASP.NET_SessionId") does not exists. But it seems that other session variables (user login, etc) are working fine.To make sure that the cookie for the session ID is readable from the applet I do the following in the global.asax: Sub Session_Start(ByVal sender As Object, ByVal e As EventArgs) ' Code that runs when a new session is started Dim isSessionFound As Boolean = False If Response.Cookies.Count > 0 Then For Each s As String In Response.Cookies.AllKeys If s = "ASP.NET_SessionId" Then Response.Cookies("ASP.NET_SessionId").HttpOnly = False isSessionFound = True 'just for test End If Next End If End SubI tried to do something with the isSessionFound, wh

Accessing Custom Property in HTML???


i have a usercontrol with a few dropdownlist....n i am using that usercontrol in few pages and depending on pages those dropdownlist  can be enabled mode or disabled mode.

so i created a property:

private string _readOnly;
        public string ReadOnly
         set {
                if (value == "true")
                    ddlOTime.Enabled = false;

Now i am accessing in HTML as

<uc3:OpenTime ID="OpenTime1" OTime='<%#Bind("OpeningTime")%>' ReadOnly="true" runat="server" />

it seems to work.

Just curious know that am i going in right direction or any better approach is available?


Accessing SelectedItem of DropDownList in WebPart Custom Properties



I've made a simple Visual Web Part using an AJAX timer to count down to dates.

I have added a custom property which is a list of events, but I cannot find the Selected Item value in my ascx.cs file.

Here is how the property is set:















 VisualWebPart1 : WebPart




 EventList myEventList;


), Category("Configuration&quo

Session management and Cookie related to ASP.NET MVC


I'm looking the article on Session management and Cookie related to ASP.NET MVC.
Can somebody please provide links on that topics?



in asp.net mvc, how to use session and cookie ?


This is a newbie question .

in asp.net mvc, how to use session and cookie ?

I am trying to understand how a login session stored and implemented.

Can I only create session on login and redirect to login from other apps if not using custom provide


I have created custom a MembershipProvider, SessionIDManager, and SessionStateStore since I need to use custom legacy sessions and logins.. When the Application is ran, it runs the GetSessionID in the SessionIDManager(which is correct)..

The problem then is if there is no session meaning the GetSessionID method returns null, it tries to create a new session using CreateSessionID.. I want it to redirect to the login application(another application)..

We only create and store session information for logged in users and the "session id numbers" come from a file that is pre-populated with "session id numbers"(I didnt design this and its out of my control).. So its not feasable to give everyone who visits the site one of the "session id" numbers..

I also need for users with an "invalid" session(when checked through Validate()) to be redirected to the login page..


Any help here would be great..

Accessing my custom aspx page in the place of Newform.aspx of the list



I have a aspx page where i have designed the controls as per the need.Now my requirement is as soon as user click on 'New' of the List,i am expecting to aspx page to come as Newform.aspx of the list.Could you please share your ideas regarding this?

Thanks & Regards,


How do you manage custom objects and session state



I've created a whole bunch of rather complex classes and now i'm starting to work on the ASP.net user interface.  Basically the user will open 1 page which will be used to load, edit, save an object. The object has many fields and they are often other classes i've created. To create a nice interface i've used popups and used AJAX to reload parts of the page to avoid reloading the whole thing.

My plan was to create the object and save it to the session. Then each time the page is loaded copy the object values to the asp fields and do the reverse when the page has been submitted copying the asp values to the object field then updating the session object.

So the code will go something like:


if session is not null load from session otherwise create new
this.txtID.text = object.id
this.txtName.text = object.name
etc etc

on submit:

object.id = this.txtID.text
object.name = this.txtName.text
etc etc
update session.

Is this what you guys would do? or am i over thinking this, seems like a lot of code to load all the object fields each time the page is opened and submitted etc.

Just looking to bounce ideas of off other developers :D


Cannot deploy custom MemshipProvider/RoleProvider assembly to web-site


I have written an assembly (DLL) containing two classes, MyMembershipProvider and MyRoleProvider, which are derived from MembershipProvider and RoleProvider, respectively.  I have implemented most but not all of the abstract methods; the remaining ones all throw a NotImplementedException.  I have signed the assembly and added a reference to it in my web-site project, where the relevant web.config sections look like this:

<membership defaultProvider="MyMembershipProvider">
    <add name="MyMembershipProvider" type="MyAuthentication.MyMembershipProvider"/>


<roleManager enabled="true" defaultProvider="MyRoleProvider">
    <add name="MyRoleProvider" type="MyAuthentication.MyRoleProvider"/>

When I fire up the site, however, I get the following error:

Configuration Error

Description: An error occurred during the processing of a configuration file required to service this request. Please review the specific error detail

Accessing Property Value of a Custom Control by another Custom Control in Design-time



I created an Extender which has a custom property that drills down a list XML elements from an xml file, where users can select xml elements during design-time. This works perfectly fine. However, my code only has a hardcoded xml filename (source of the xml elements list) and I need to change this by maxing the xml file user-specified.

What I did is that I created another control (panel) which has a custom property that when clicked (through the ellipsis), it will allow a developer to select the xml file which is supposed to be the source xml file that the Extenders shall use. The filedialog from custom panel's property works perfectly fine.

However, my problem now is that when I drag-drop my Extender, I cannot find a way to get the property value of the custom Panel Control which contains the xml filename. I tried creating a static variable which I thought the custom controls can share but VS2010 is breaking.

Please take note that my problem is on Design-time, asp.net.

Appreciate any help. Thanks a lot.

Dhon Nuevo.

Setting Task Field Values in Custom .aspx Edit Form and accessing through ExtendedProperties


Since we're using WSS 3.0 and not MOSS 2007, we have to create and use ASP forms for any custom Workflow Task Edit pages instead of being able to use InfoPath forms (which would be nice...maybe some day we'll step up to MOSS). The custom Workflow Edit Pages are used for custom Task Content Types that we create so that our Workflow Tasks can have additional fields beyond the standard Workflow Task fields. Once you've collected the values for the Task fields from the user on the ASP Workflow Task Edit form, the typical procedure is to create a hashtable and fill the hashtable with key/value pairs that represent the names of your Task fields and their associated values, as such:

// This function is called when the user clicks the Save/Submit button
// on the Custom Task Edit ASP form
public void btnSubmit_Click(object sender, EventArgs e)
  // Create a hashtable that will be used to update the values of task fields
  Hashtable taskHash = new Hashtable();
  // For each field, create two values in the hashtable. If the field name 
  // matches a field in the Task content type, the field name will not be 
  // searchable as a key within the ExtendedProperties hashtable. So 
  // create a second field that is a duplicate of the first but having a 
  // name that doesn't exactly match an existing field in the Task 
  // content type. That way it will be a searchable ke

How to get new Session Cookie in IE7


We have a local homepage, which connect to our production security environment. When I need to test my site in test environment, I need to get fresh cookie (not the one that was sent to me via production security service, when I opened IE with local homepage).

I am getting fresh cookie fine in Mozilla; but in IE I always have production cookie, and this disables my testing. What I should fix here?


Custom error on session expiration



I have an issue with my asp .net application. I am using custom errors on my pages. So I configured in web.config like,

<customErrors mode="On" defaultRedirect="~/ErrorPage.aspx">

      <error statusCode="403" redirect="~/ErrorPage.aspx"/>

      <error statusCode="404" redirect="ServerError.aspx?errorCode=404"/>

If an internal server error comes, ie, 500 then I have to send an email to the administrator with all the error details with error number.

For this I have created a code in the application_error section of global.asax page. If a 500 error comes it will be send a mail to the admin with details.

But if 403 error came, ie, session expired; it will loop to the application_error and sending mail repeatedly.

In the Error page, I am checking the session variable and if there is no session exists the page will redirect to login page.

How to handle this Problem? Can any one suggest a good solution for this?

Below is the app_error code

void Application_Error(object sender, EventArgs e)


Exception exception = Server.GetLastError();

Exception objErr = Server.GetLastErro

access denied error in custom login page using custom membership provider/ roleprovider in the FBA u



I have deployed my custommebrship assembly and role provider assembly in the sts web config , central admin web config  and current web appln web config 's. i have created a  dll which has  login control and in the sign_authenticate event i am creating the securitytoken.

when i establish a session using the security token created using the iissettings object, and  while tryibng to redirect to the   home page of the/landing page of the web appln am Getting access denied error. 

signInControl_Authenticate(object sender, AuthenticateEventArgs e)




e.Authenticated = true; //till this line  it worked success.

 base.RedirectToSuccessUrl(); //here it throws  :" Eror: access  denied "     current ly signed in user : myname sign is as   diuff. user


anybody knows how to overcome this , means authentication is  success, but authoriation didnt work.

 how can i get asuccessfull login to theweb appln/ siteccollection? in my role provder class i  have created my own roles

for user name: myname

role name:  Administrators, Contributor.

any help is appreciated





Accessing a session variable in html for a boolean expression


I've defined a session variable in my Session_Start procedure

        void Session_Start(object sender, EventArgs e)


        <other stuff>

                string sAdmin= bAdmin.ToString();

                Session["SessionAdmin"] = sAdmin;



Then in my masterpage I want to use the Session Variable to conditionally show some links in a list.

How do I write the Boolean expression to correctly access the session variable SessionAdmin?

Here's what I have:

       <div id="menu">


            <li><a href="/EmployeeTime.aspx">Employee Time</a></li>

            <% if (  *** a Boolean expression involving Session variable "SessionAdmin" *** ) {%>

ASP.NetWindows Application  .NET Framework  C#  VB.Net  ADO.Net  
Sql Server  SharePoint  Silverlight  Others  All   

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend