Solved

Problem with lossing session after redirect

Posted on 2006-07-11
5
383 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

What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

Join & Write a Comment

Suggested Solutions

Extention Methods in C# 3.0 by Ivo Stoykov C# 3.0 offers extension methods. They allow extending existing classes without changing the class's source code or relying on inheritance. These are static methods invoked as instance method. This…
This article introduced a TextBox that supports transparent background.   Introduction TextBox is the most widely used control component in GUI design. Most GUI controls do not support transparent background and more or less do not have the…
Excel styles will make formatting consistent and let you apply and change formatting faster. In this tutorial, you'll learn how to use Excel's built-in styles, how to modify styles, and how to create your own. You'll also learn how to use your custo…
Access reports are powerful and flexible. Learn how to create a query and then a grouped report using the wizard. Modify the report design after the wizard is done to make it look better. There will be another video to explain how to put the final p…

744 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

10 Experts available now in Live!

Get 1:1 Help Now