Link to home
Start Free TrialLog in
Avatar of RTSol
RTSol

asked on

Simulate page hit in Global.asax

Hi,

I am trying to simulate a page hit in Global.asax in order to fire Application_BeginRequest. I can't get it working - se the code below. Is there a better way to do this?

Best regards
RTSol
//Code in Global.asax

    /// <summary>
    /// Hits a local webpage in order to add another expiring item in cache
    /// </summary>
    private void HitPage()
    {
        System.Net.WebClient client = new System.Net.WebClient();
        client.DownloadData(DummyPageUrl); // I was hoping this should fire Application_BeginRequest
    }

    protected void Application_BeginRequest(Object sender, EventArgs e)
    {
        DummyPageUrl = System.Web.HttpContext.Current.Server.MapPath("CacheDummy.aspx");
        // If the dummy page is hit, then it means we want to add another item
        // in cache
        if (HttpContext.Current.Request.Url.ToString() == DummyPageUrl)
        {
            // Add the item in cache and when succesful, do the work.
            RegisterCacheEntry();
        }
    }

Open in new window

Avatar of ajitha75
ajitha75
Flag of India image

Where are you calling the HitPage() from ?

~Ajitha
Avatar of RTSol
RTSol

ASKER

From within Global.asax. Se the complete code below
<%@ Application Language="C#" %>

<script runat="server">

    
    private string DummyPageUrl;
    private const string DummyCacheItemKey = "GagaGuguGigi";

    private System.ComponentModel.IContainer components = null;

    void Application_Start(object sender, EventArgs e) 
    {
        DummyPageUrl = System.Web.HttpContext.Current.Server.MapPath("CacheDummy.aspx");
        RegisterCacheEntry();
    }


    /// <summary>
    /// Register a cache entry which expires in 1 minute and gives us a callback.
    /// </summary>
    /// <returns></returns>
    private void RegisterCacheEntry()
    {
        // Prevent duplicate key addition
        if (HttpContext.Current.Cache[DummyCacheItemKey] != null) return;

        HttpContext.Current.Cache.Add(DummyCacheItemKey, "Test", null, DateTime.MaxValue,
            TimeSpan.FromMinutes(1), CacheItemPriority.NotRemovable,
            new CacheItemRemovedCallback(CacheItemRemovedCallback));
    }

    /// <summary>
    /// Callback method which gets invoked whenever the cache entry expires.
    /// We can do our "service" works here.
    /// </summary>
    /// <param name="key"></param>
    /// <param name="value"></param>
    /// <param name="reason"></param>
    public void CacheItemRemovedCallback(
        string key,
        object value,
        CacheItemRemovedReason reason
        )
    {
        System.Diagnostics.Debug.WriteLine("Cache item callback: " + DateTime.Now.ToString());
        // We need to register another cache item which will expire again in one
        // minute. However, as this callback occurs without any HttpContext, we do not
        // have access to HttpContext and thus cannot access the Cache object. The
        // only way we can access HttpContext is when a request is being processed which
        // means a webpage is hit. So, we need to simulate a web page hit and then 
        // add the cache item.
        HitPage();

        // Do the service works
        DoWork();

    }

    /// <summary>
    /// Hits a local webpage in order to add another expiring item in cache
    /// </summary>
    private void HitPage()
    {
        System.Net.WebClient client = new System.Net.WebClient();
        client.DownloadData(DummyPageUrl);
    }

    /// <summary>
    /// Asynchronously do the 'service' works
    /// </summary>
    private void DoWork()
    {
        System.Diagnostics.Debug.WriteLine("Begin DoWork...");
        System.Diagnostics.Debug.WriteLine("Running as: " + System.Security.Principal.WindowsIdentity.GetCurrent().Name);

        //DoSomeFileWritingStuff();
        //DoSomeDatabaseOperation();
        //DoSomeEmailSendStuff();
        //DoSomeMSMQStuff();
        //ExecuteQueuedJobs();

        System.Diagnostics.Debug.WriteLine("End DoWork...");
    }

    protected void Application_BeginRequest(Object sender, EventArgs e)
    {
        DummyPageUrl = System.Web.HttpContext.Current.Server.MapPath("CacheDummy.aspx");
        // If the dummy page is hit, then it means we want to add another item
        // in cache
        if (HttpContext.Current.Request.Url.ToString() == DummyPageUrl)
        {
            // Add the item in cache and when succesful, do the work.
            RegisterCacheEntry();
        }
    }

    protected void Application_EndRequest(Object sender, EventArgs e)
    {
        DummyPageUrl = System.Web.HttpContext.Current.Server.MapPath("CacheDummy.aspx");
        // If the dummy page is hit, then it means we want to add another item
        // in cache
        if (HttpContext.Current.Request.Url.ToString() == DummyPageUrl)
        {
            // Add the item in cache and when succesful, do the work.
            RegisterCacheEntry();
        }
    }
    
    void Application_End(object sender, EventArgs e) 
    {
        //  Code that runs on application shutdown
        //HttpContext.Current.Cache.Remove(DummyCacheItemKey);

    }
        
    void Application_Error(object sender, EventArgs e) 
    { 
        // Code that runs when an unhandled error occurs

    }

    void Session_Start(object sender, EventArgs e) 
    {
        // Code that runs when a new session is started

    }

    void Session_End(object sender, EventArgs e) 
    {
        // Code that runs when a session ends. 
        // Note: The Session_End event is raised only when the sessionstate mode
        // is set to InProc in the Web.config file. If session mode is set to StateServer 
        // or SQLServer, the event is not raised.

    }
       
</script>

Open in new window

You are setting the CacheExpiration to 1 minute from now. In that case, you need to change as below

        HttpContext.Current.Cache.Add(DummyCacheItemKey, "Test", null, DateTime.Now.AddSeconds(60),
           Cache.NoSlidingExpiration, CacheItemPriority.NotRemovable,
            new CacheItemRemovedCallback(CacheItemRemovedCallback));

~Ajitha

Avatar of RTSol

ASKER

The problem is not the CacheExpiration but rather to fire Application_BeginRequest. It fires when the appication starts but not when I run HitPage() as I had hoped. How can I fire Application_BeginRequest from within HitPage()?
In the below code what is the value of dummyURL? are you getting the full path to the page that you want? did you step through and debug that vaue?

        System.Net.WebClient client = new System.Net.WebClient();
        client.DownloadData(DummyPageUrl);

~Ajitha
Avatar of RTSol

ASKER

The DummyPageUrl contains the full path.  client.DownloadData(DummyPageUrl); returns a byte array so it seems to be working ok.
ASKER CERTIFIED SOLUTION
Avatar of ajitha75
ajitha75
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of RTSol

ASKER

I was very stupid - the full path was the physical path and it did not go through the server. Thanks a lot - now it works perfect. :-)