Friday, April 10, 2009

Asp Net Service setup

You can create windows service functionality usinig aspnet service.
On Application_Start Event you have to register cacheitem like below:-
private const string DummyCacheItemKey = "TestKey";
void Application_Start(object sender, EventArgs e)
{
RegisterCacheEntry();
}

private void RegisterCacheEntry()
{
// Prevent duplicate key addition
if (null != HttpContext.Current.Cache[DummyCacheItemKey]) return;

HttpContext.Current.Cache.Add(DummyCacheItemKey, "Test", null, DateTime.MaxValue,
TimeSpan.FromMinutes(1), CacheItemPriority.NotRemovable,
new CacheItemRemovedCallback(CacheItemRemovedCallback));
}
public void CacheItemRemovedCallback(string key, object value, CacheItemRemovedReason reason)
{


// Do the service works
DoWork();

// 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();
}
private void DoWork()
{

//task that you want to perform;
}

private void HitPage()
{
System.Net.WebClient client = new System.Net.WebClient();
client.DownloadData(Application["AppUrl"].ToString()+ "/DummyForm.aspx");
}
protected void Application_BeginRequest(object sender, EventArgs e)
{
System.Web.HttpApplication app = (System.Web.HttpApplication)sender;
string url = app.Request.Url.AbsoluteUri.ToString();
if (url.IndexOf("DummyForm.aspx") != -1)
{
// Add the item in cache and when succesful, do the work.
RegisterCacheEntry();
}
}

No comments: