Simulate page hit in Global.asax

RTSol
RTSol used Ask the Experts™
on
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

Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®

Commented:
Where are you calling the HitPage() from ?

~Ajitha

Author

Commented:
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

Commented:
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

Acronis in Gartner 2019 MQ for datacenter backup

It is an honor to be featured in Gartner 2019 Magic Quadrant for Datacenter Backup and Recovery Solutions. Gartner’s MQ sets a high standard and earning a place on their grid is a great affirmation that Acronis is delivering on our mission to protect all data, apps, and systems.

Author

Commented:
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()?

Commented:
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

Author

Commented:
The DummyPageUrl contains the full path.  client.DownloadData(DummyPageUrl); returns a byte array so it seems to be working ok.
Commented:
But since it contains the full path... does the request go through the web server? is the full path http://<<servername> .... etc?

~Ajitha

Author

Commented:
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. :-)

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial