Few random development Tips-N-Tricks-5

File Processing with ASP.Net comes with lot of callbacks and can avoid polling almost always.
If you are working with a file which is in cache, and want to know, if any other external process has modified that file in anyway (rename, delete, changed the contents), then File based CacheDependency along with CacheItemRemovedCallback does exactly that. Another dedicated class is the FileSystemWatcher from System.IO namespace.It raises event for any directory or file level changes like create/delete/rename/modify.
http://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher.aspx 

An example with CacheDependency/CacheItemRemovedCallback

public static CacheItemRemovedCallback RemovedCallback;
protected void Page_Load(object sender, EventArgs e)
{
    RemovedCallback = new CacheItemRemovedCallback(OnCacheRemoved);
    g1();
}
private void g1()
{
    HttpRuntime.Cache.Add("l1", "xxxx", 
        new System.Web.Caching.CacheDependency(Server.MapPath("TextFile1.txt")), 
        Cache.NoAbsoluteExpiration, 
        Cache.NoSlidingExpiration, 
        CacheItemPriority.NotRemovable, 
        RemovedCallback);
}
private void OnCacheRemoved(string key, Object value, CacheItemRemovedReason reason)
{
    //The File has been either modified/deleted/renamed.
    //Run whatever relevant logic here.
    //Context and response object are not available here
    g1();
}

Thanks for reading.

Advertisements
This entry was posted in Tips-n-Tricks. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s