Fun with .net: Scheduled tasks in asp.net

9. March 2010

This is the third in a series of blog posts highlighting interesting snippets hacks I have run across. Although these do work, I do not recommend trying them in production code.

Have you ever been in a situation where you needed a scheduled task to kick off, but you didn’t have access to the server (think shared hosting)? I originally saw this hack on Samir’s blog about a year ago now.

Essentially, you just create a System.Timers.Timer in the Application_Start event of your global.asax, and bam – instant scheduled task! I don’t necessarily recommend this, but I guess if you had no other option it could work.

 

using System.Timers; 

public class Global : System.Web.HttpApplication
{
    protected void Application_Start(object sender, EventArgs e)
    {
        Timer timer = new Timer(1000);
        timer.Elapsed += (object s, ElapsedEventArgs args) =>
        {
            LetsDoSomethingAwesome();
        };
        timer.Start();
    }
}

short link to this post:

asp.net, Fun with .net , ,

Fun with .net: Programmatically determine variable name

1. March 2010

This is the second in a series of blog posts high lighting interesting snippets hacks I have run across. Although these do work, I do not recommend trying them in production code.

Have you ever re-factored some code, only to find out that you missed a place were a variable name was referred to in a string? Let’s say you were checking the input of a method, and throw an exception if it was out of bounds.

if (string.IsNullOrEmpty(someInput))
{
    throw new ArgumentNullException("someInput");
}

 

With this trick, you will never have to worry about forgetting to update the ArgumentNullException when you change the parameter name. It will programmatically determine the variable name for you!

void CheckInput(string someInput)
{
    if (string.IsNullOrEmpty(someInput))
    {
        //do not do this...ever!
        string varName = NameOfVariable(() => someInput);
        throw new ArgumentNullException(varName);
    }
}

string NameOfVariable(Expression<Func<object>> expressionTree)
{
    return ((MemberExpression)expressionTree.Body).Member.Name;
}

 

Ok, ok…so this falls apart fast, and I feel dirty for even sharing.  Just don’t use this in production…Or anywhere for that matter!


short link to this post:

.net, Fun with .net ,