.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

PostBack triggers Session_Start on Global.asax

Posted By:      Posted Date: October 06, 2010    Points: 0   Category :ASP.Net

Hi all, I'm facing a strange issue.

I have a simple aspx Page, which html contains:

<asp:Button ID="btn1" runat="server" Text="Set Session" onclick="btn1_Click" /> 
<asp:Button ID="btn2" runat="server" Text="Get Session" onclick="btn2_Click" />

and code behind:

public partial class MyPage : System.Web.UI.UserControl
    private List<string> myElements
        get { return (List<string>)Session["elements"]; }
        set { Session["elements"] = value; }

    protected void Page_Load(object sender, EventArgs e)


    protected void btn1_Click(object sender, EventArgs e)
        List<string> strs = new List<string>();

        myElements = strs;

    protected void btn2_Click(object sender, EventArgs e)
        List<string> strs = myElements;

        if (strs != null && strs.Count > 0)
            string s = "Ok";


This is quite simple. When I press btn1, it sets correctly the Session Key

View Complete Post

More Related Resource Links

Quick Error messages with Global.asax

The article Quick Error messages with Global.asax was added by lykasd on Wednesday, August 11, 2010.

Error pages without any effort void Application_Error(object sender, EventArgs e) { Server.Transfer("/error.aspx"); //Displays the error page } In error.aspx add this to the content area. p>We&#39;re sorry, but the %=Server.GetLastError

Windows 7, IIS 7.5 and VS2010: can't edit global.asax


Hey and thanks!


As the subject line notes the software in use, anyone have an idea why I can't edit global.asax in VS2010 (being ran with the 'run as administrator' advanced property check box checked)?  The file properties in explorer show local machine admins have full control (I am in that category) and also that IIS has windows auth enabled for the default web site.  What is this other level of security on here that I'm missing?  I can edit web.config, vb files and general aspx files with no problem--just the global.asax file causing a headache...





I have a problem Global.asax

Master  Desing        <head runat="server"><title><asp:ContentPlaceHolder ID="TitleContent" runat="server" />    </title>    <link href="../../Content/Site.css" rel="stylesheet" type="text/css" />    <link href="../../Content/menu/chromestyle2.css" rel="stylesheet" type="text/css" />    <script src="../../Scripts/menu/chrome.js" type="text/javascript"></script></head>   Global.asax  //Routes Event Catagory  routes.MapRoute("eventCatagory", "Catagory/{catagoriesID}/{catagories}",                                 new { controller = "Catagory", action = "Catagory", catagories = "", catagoriesID = UrlParameter.Optional }); //Routes Event Catagory Detailroutes.MapRoute("eventCatagoryDetail", "Catagory/{subCatagoryID}/{subCatagoryname}",                        &n

Using Global.asax to Set Session Variables Pulled From SQLServer

I have a custom class that pulls user information from a SQL Server table. Now that I'm expanding the site from a single page to others. I want to shift the code to the Session_Start event so that the information is always loaded when the site is accessed. How do I call my custom code from global.asax since its script and not a class. 

Function in Global.asax is not running

Hi, I am using a Global.asax in on my webpage to run a function with an interval. In this test I have set the interval to 1 minute to be able to see what happens. I have declared a timer in the Application Start which should mean that when I open up the webpage after I have uploaded the Global.asax the timer will start.   However with this code below where I try to create a file named newFile.txt, this file is not created. I cant really understand what I could be missing. It seems that the function is not running ?<%@ Application Language="C#" %> <%@ Import Namespace="System" %> <%@ Import Namespace="System.Collections.Generic" %> <%@ Import Namespace="System.Linq" %> <%@ Import Namespace="System.Web" %> <%@ Import Namespace="System.Web.UI" %> <%@ Import Namespace="System.Web.UI.WebControls" %> <%@ Import Namespace="System.Drawing" %> <%@ Import Namespace="System.Net.Mail" %> <%@ Import Namespace="System.Net" %> <%@ Import Namespace="System.Threading" %> <%@ Import Namespace="System.IO" %> <%@ Import Namespace="System.Text" %> <%@ Import Namespace="Microsoft.Win32" %> <%@ Import Namespace="System.Reflection" %> <%@ Impo

Global.asax Application_BeginRequest

When I was in the link page is a link to the site all the program, Application_BeginRequest event in Global.asax is triggered, But my link is a link to an external time will not trigger this event, and I ask when my link is connected to an external URL, How to trigger Application_BeginRequest event Thank you.   Such as web link in the URL if connected to yahoo, I take it lead to another page.  Protected Sub Application_BeginRequest(ByVal sender As Object, ByVal e As System.EventArgs) Dim originalPath As String = HttpContext.Current.Request.Url.Host.ToLower() If originalPath.Contains("yahoo") Then Context.Response.Redirect("StopUrl.aspx") End If End Sub  

Update Panels, Postback Triggers, and GridViews, Oh my

I've been battling with this page for the past couple days and it works, but it's annoying, so I am hoping someone maybe has dealt with this and can help me a little.   I have an UpdatePanel that acts as a container for a number of other update panels, everything in this container works.  I got the bright idea to add a ModalPopup Extender to enhance the user experience a little when performing a certain function on the site.  The panel that acts as the container for the ModalPopup sits outside the UpdatePanel Container because if it's in the container, any interaction with a child control throws "Input string not in the correct format" error message.  Because this is outside the comfort of the UpdatePanel Container, any control that populates information into the Popup control has to register a Postback.  Thus my problem: the controls that populate the Popup are GridViews.  The only GridView Event I care to cause a PostBack is the SelectedIndexChanged, but PostBack Triggers don't care, they take all comers.  Want to go to the next page? PostBack. Sort? Hell Yeah, Postback. My initial solution is to provide a confirm type of a message under the gridview and have the user confirm their selection by clicking a button to avoid causing a postback until it's necessary, but you know what? That kinda sucks, so I sub

Application level event without global.asax

I have a need to add an application level event (like Application_Start) but not in global.asax.  The reason that I can't use global.asax is because this is a web application for which I don't have source code but I want to add some functionality to it.  I need to insert an application start code and was wondering it there was anyway to do it.  I'm not sure that if I add a class or aspx page to the sie if it will dynamically compile since this is a web application.  I know this is a crazy request but let me know what you think.Also, this web site was written in .NET 2.0.Thanks.

Passing data to a Controller from global.asax


Hello all! I'm in a situation where I need to pass some information (state) to a base controller from which all of my controllers derive. In my global.asax, I'm calling a web service to get some state about the user. This state applies to every page in my web app, so the base controller needs to know about it. The state consists of about 4 fields. Is there a standard way to do this? 

I'm using ASP.NET MVC 2.

Thanks in advance for your time!


Empty Catch in Global.asax to prevent exception from stopping a web application?



I'm using a static Timer in my Global.asax to run a method at regular intervals. When the method throws an exception, my application is stopped. I have used an empty catch to prevent exceptions from stopping the application something like below code. Is there a disadvantage to use such an approach?


 protected void Application_Start(object sender, EventArgs e)

 public class TimerStarter
            private static System.Threading.Timer threadingTimer;

            public static void StartTimer()
                if (null == threadingTimer)
                    threadingTimer = new System.Threading.Timer(new System.Threading.TimerCallback(CheckData),HttpContext.Current, 0, 50000);

            private static void CheckData(object sender)
                   // a method that reading xml file from another url              
                    // empty catch to prevent stopping the application




Session end and global.asax



I'm wondering if ther's a simple way of achieving the following.

When a new session starts, I create some cookies and session objects from global.asax session start.

If a user logs out, I want to abandon the session - I presume using session.abandon, and i also want to clear the cookies.  They are set to expire after the session ends (no expiry date).  This may be an automatic thing, but I've not tested as yet.

When a user logs back in again I want to recreate those objects - in other words, kick off global.asax again.  Is that what happens or do I need to recreate manually?



Exception handling in Global.asax of ASP.net


I want to handle exceptions in my applications in Global.asax and transfer the exception to my custom error page, so that is in a central place. I want to take this exception object into my oopserror.aspx page and format it and display a custom message. i tried to use GetLastError() in my oopsError.aspx page, but my exception object was always null. Following is the code snippet that i'm using and i'm getting exception.

void Application_Error(object sender, EventArgs e)
   // Code that runs when an unhandled error occurs
   Exception exception;
   exception = Server.GetLastError();

   Session.Add("Exception", exception);


Following is the exception when the above code is executed.

{"Session state is not available in this context."}
   at System.Web.HttpApplication.get_Session()
   at UserInterface.Global.Application_Error(Object sender, EventArgs e) in C:\UserInterface\Global.asax.cs:line 51
   at System.EventHandler.Invoke(Object sender, EventArgs e)
   at System.Web.HttpApplication.RaiseOnError()

Is there a way that i can securly take my session object from global.asax to my oopserror.aspx? Any ideas?

Global.asax file in WCF for different end points


Global.asax is available in asp.net application. But when I added WCF application i couldn’t find the file. I saw read in one of the questions that global.asax cannot be used for tcp endpoints.

I’m trying to use application_error method in global.asax and catch all the exceptions in this method.


How can I use global.asax with http and tcp endpoint? Or is there any other way to implement this?


Session and global asax


i use session state for logged in  users
if session lost(finished) for user and i use this session to insert as a forien key in a table
this will generate runtime error as this id become equal to zero
how can i develop a method to log out the user automatically when session timeout reached
inseted to check at every button on the velue of session.
i have ideia to check on session on global file in Application_BeginRequest event

but give me error
what do you think of this method???

Redundant SQL code to "set up" my code behind. Can I put it in the global.asax?


I've moved away from using sqldatasources, and now I exeucte all my sql in my code behind.   However, I'm looking to make my codebehind a little more cleaner/neater.  For example, on one page, there are three stored procedures that must execute, and All three have these same 8 lines of code for each of my three stored procedures.   How can I condense my code behind to not always have to add this...

        SqlConnection conn = default(SqlConnection);
        SqlCommand comm = default(SqlCommand);
        SqlDataReader reader = default(SqlDataReader);
        string connectionString = ConfigurationManager.ConnectionStrings["xyz"].ConnectionString;
        conn = new SqlConnection(connectionString);
        comm = new SqlCommand();
        comm.Connection = conn;
        comm.CommandType = System.Data.CommandType.StoredProcedure;


Session Events of Global.asax doesn't fire in sharepoint

As I have some requiremnt, i've written some code in session_start and session_end events in global.asax of the sharepoint web applicaion. But the events don't fire when the user logs in or logs out. Even the application_start also not working when the application starts. So do i need to make any changes in web.config or anywhere ? Please help.

Dynamically adding DataAnnotations outside of Global.asax... possible?


Is it possible to add/remove/edit System.ComponentModel.DataAnnotations (for example [Display(Name = "Foreign")] or [ScaffoldColumn(true)] ) AT RUNTIME, outside of Global.asax?   For example,  one user logs in and the column is shown the column name "Foreign", another logs in and the same column is named "Extranjero" and would NOT see the scaffolded DB column [USPriceInDollars].

I realize the MetaModel is registered at Application_Start(), but I would like to actually register the model on Login....

Any code samples or techniques appreciated.

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