Solved

Problem with lossing session after redirect

Posted on 2006-07-11
5
390 Views
Last Modified: 2012-05-05
I am in the process of completing a project and ran into a issue. The backend of the site allows the administrator to create and remove a simple website for the instructors who work for the company. Everything works well, except when you delete the instructors website it signs you out of the backend.
I am using a session to manage the userid and then it loops through a database which contains the allowed permissions by checking against a list of id numbers. I can find no area where it clears the session that would be called. I will try to post some code and would appreiciate any help that would be available:

Thanks in advance
CJSantora

Call to delete website:
            protected void cmdDelete_Click(object sender, System.EventArgs e)
            {

            // check for files and delete if they exist
            try
            {
                if (Directory.Exists(hidInstructorsPath.Text))
                {
                    Directory.Delete(hidInstructorsPath.Text, true);
                }
            }
            catch (Exception ex)
            {
                Response.Write("Error with deletion of folders " + ex.ToString());
            }

                  // update database
                  // assign values
                  string intuserid = lblUserid.Text.Trim();                  
                  string strwebaddress = "";
                  
                  SqlConnection oConn;
                  oConn = new SqlConnection(ConfigurationManager.AppSettings["connString"]);

                  string oString = "";

                  oString = "Update tbl_users Set webaddress = @webaddress Where userid = @userid ";

                  SqlCommand oCommand = new SqlCommand(oString,oConn);
                  oCommand.Parameters.Add(new SqlParameter("@userid", intuserid));
                  oCommand.Parameters.Add(new SqlParameter("@webaddress", strwebaddress));
                  
                  
                  try
                  {
                        oConn.Open();
                        int irecords = oCommand.ExecuteNonQuery();                        
                        lblUserMessage.Text = "You have successfully removed this users website.";
                        lblUserMessage.ForeColor = Color.Red;
                  }
                  catch(Exception ee)
                  {
                        bool bReturnLog = false;
                        ErrorLog.LogFilePath = "ErrorLogFile.txt";
                        bReturnLog  = ErrorLog.ErrorRoutine(false,ee);
                  }
                  finally
                  {
                        oConn.Close();
                        oConn.Dispose();                                                
                  }

             
                  Response.Redirect("~/admin/Default.aspx?load=user_list");      
            }


Check permissions:

public partial class _Default : System.Web.UI.Page
      {
      
            protected void Page_Load(object sender, System.EventArgs e)
            {

                  string load = "";
                  if( Session["userid"] == null )
                  {
                                                                 Response.Write("No Session");  //testing session
               

                        if( Request.QueryString["load"] == "reset" )
                        {
                              BodyCell.Controls.Add(LoadControl("~/includes/_private/ResetPassword.ascx"));
                        }
                        else
                        {
                              notAuth();
                              loadPage(load);
                        }
                  }
                  else
                  {
                Response.Write(Session["userid"].ToString());


                        // set defaults                        
                        if( Request.QueryString["load"] != null )
                        {

                    Response.Write(Request.QueryString["load"].ToString());

                              chkPermissions(Convert.ToInt32(Session["userid"]));
                              load = Request.QueryString["load"];
                        }
                        loadPage(load);
                  }      

            }

            private void loadPage(string load)
            {

            //BodyCell.Controls.Clear();

                  // Handles loading of appropriate pages into main table
                  switch(load)
                  {
                        case("main"):
                        {
                              MenuCell.Controls.Add(LoadControl("~/includes/_private/adminMenu.ascx"));
                              BodyCell.Controls.Add(LoadControl("~/includes/_private/adminMain.ascx"));
                              break;
                        }
                                       case("user_list"):
                        {            
                              MenuCell.Controls.Add(LoadControl("~/includes/_private/adminUserMenu.ascx"));
                              BodyCell.Controls.Add(LoadControl("~/includes/_private/adminUserList.ascx"));
                              break;
                        }
                        case("user_edit"):
                        {
                              MenuCell.Controls.Add(LoadControl("~/includes/_private/adminUserMenu.ascx"));
                              BodyCell.Controls.Add(LoadControl("~/includes/_private/adminUserEdit.ascx"));
                              break;
                        }
                        case("user_rights"):
                        {
                              MenuCell.Controls.Add(LoadControl("~/includes/_private/adminUserMenu.ascx"));
                              BodyCell.Controls.Add(LoadControl("~/includes/_private/adminUserRights.ascx"));
                              break;
                        }
                        case("logout"):
                        {
                              notAuth();
                              BodyCell.Controls.Add(LoadControl("~/includes/_private/login.ascx"));
                              break;
                        }
                        case "reset":
                              BodyCell.Controls.Add(LoadControl("~/includes/_private/ResetPassword.ascx"));
                              break;
                        default:
                        {
                    BodyCell.Controls.Clear();
                              BodyCell.Controls.Add(LoadControl("~/includes/_private/login.ascx"));
                              break;
                        }

                  }
            }

            private void notAuth()
            {
                  Session["firstname"] = null;
                  Session["lastname"] = null;
                  Session["userid"] = null;                                                                                                      
                  Session["title"] = null;
                  Session["department"] = null;
                  Session["browserStatus"] = null;
            }

            private void chkPermissions(int uid)
            {
                  string req = "";
                  int reqid = 0;
                  string straction = "denied";

                  // capture Request.QueryString["load"]
                  if( Request.QueryString["load"] != null )
                  {
                        req = Request.QueryString["load"];
                  }
                  
                  // returns list of adminsections
                  foreach( DataRow dr in auth.Adminsections().Tables[0].Rows )
                  {
                        // matches the request to the database entry
                        //Response.Write(dr["shortname"].ToString() + " == " +  req  + "<br>");
                        if( dr["shortname"].ToString() == req )
                        {
                              reqid = Convert.ToInt32(dr["id"]);
                              Response.Write(reqid  + "<br>");
                              // returns a list of the users permissions
                              foreach( DataRow perm in auth.Permissions(uid).Tables[0].Rows )
                              {
                                    // assigns the list to an array
                                    string[] arr = perm["sectionid"].ToString().Split(new Char[]{','});
                                    foreach( string i in arr )
                                    {
                                          // matches the id in the array of permissions with the id of the requested section
                                          if( Convert.ToInt32(i) == reqid )
                                          {
                                                straction = "approved";
                                                break;
                                          }
                                    }
                              }
                        }
                  }

                  if( straction == "denied" )
                        Response.Redirect("~/admin/default.aspx?load=main&m=denied");
            }

            #region Web Form Designer generated code
            override protected void OnInit(EventArgs e)
            {
                  //
                  // CODEGEN: This call is required by the ASP.NET Web Form Designer.
                  //
                  InitializeComponent();
                  base.OnInit(e);
            }
            
            /// <summary>
            /// Required method for Designer support - do not modify
            /// the contents of this method with the code editor.
            /// </summary>
            private void InitializeComponent()
            {    

            }
            #endregion
      }
}



0
Comment
Question by:CJSantora
  • 3
  • 2
5 Comments
 
LVL 7

Expert Comment

by:whatsit2002
ID: 17084222
CJSantora,

Is the directory that is being deleted in the same virtual directory as the application doing the deleting? If so, changing the folder structure within the application's virtual directory is probably causing the worker process to cycle. That would explain why you are loosing your sessions.

You can see the same results by changing the Web.config or recompiling and replacing the contents of the /bin folder.

Also, one more question: does everyone using the web app loose their session or just the user doing the deleting?

Jason
0
 

Author Comment

by:CJSantora
ID: 17085521
Hi Jason the only time the session is lost is after the deleting of the directory. Everything else is fine. And the folder structure is within the application. Is there a way round this?

CJSantora
0
 
LVL 7

Accepted Solution

by:
whatsit2002 earned 500 total points
ID: 17085590
The only way around the "disappearing session" problem that I know of is to use an out of process state store. Your options include: IIS State Server, a Microsoft SQL Server, or rolling your own (yuck).

IIS State Server can run on the same server your app is running on and should preserve your sessions when the worker process recycles itself. I believe it is faster than the SQL Server option.

Jason
0
 

Author Comment

by:CJSantora
ID: 17085602
Thanks I will look into the IIS Server and let you know how it works.

CJsantora
0
 

Author Comment

by:CJSantora
ID: 17086137
Hi Jason, I appreciate your help, I battled with this for a while and thought it was in the code. But your suggestion worked perfectly, thanks again.

CJSantora
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
detecting  the added row index in a datagridview 3 62
Programmatically signing Word macros 4 61
Problem to error 4 47
Exit the loop 4 40
Introduction                                                 Was the var keyword really only brought out to shorten your syntax? Or have the VB language guys got their way in C#? What type of variable is it? All will be revealed.   Also called…
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
This tutorial gives a high-level tour of the interface of Marketo (a marketing automation tool to help businesses track and engage prospective customers and drive them to purchase). You will see the main areas including Marketing Activities, Design …
Learn how to create flexible layouts using relative units in CSS.  New relative units added in CSS3 include vw(viewports width), vh(viewports height), vmin(minimum of viewports height and width), and vmax (maximum of viewports height and width).

863 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

26 Experts available now in Live!

Get 1:1 Help Now