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();
    }
}

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!

.net, Fun with .net ,

Fun with .net: No more empty events

23. February 2010

This is the first 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 gotten tired of checking for null before calling events? Take, for example, this block of code:

public delegate void FunHandler();

public class FooBar
{
    public event FunHandler OnSomethingFun;

    private void DoFunStuff()
    {
        if(OnSomethingFun != null)
        {
            OnSomethingFun();
        }
    }
}

 

I don’t remember where I first saw this one, but if you initialize the event to an empty delegate, then you wouldn’t have to check for null. Before you start explaining to me why this is wrong – take a breath, relax, and realize this is all for fun. Remember, don’t try this in production:

public delegate void FunHandler();

public class FooBar
{
    //not recommended
    public event FunHandler OnSomethingFun = ()=>{};

    private void DoFunStuff()
    {
        OnSomethingFun();
    }
}

.net, Fun with .net ,

Programming by Contract with .net 4

17. February 2010

The basic idea of programming by contact (or design by contract if you will) is that you can define a contract for an object that will guarantee specified input and output for its callers. Typically this is done with preconditions, postconditions, and invariants.

  • Preconditions: a rule that must be true in order for the execution of some code. Think of a precondition as validating that the input is within a specified range.
  • Postconditions: a rule that must be true after the execution of some code. A post condition could be ensuring that the object being returned meets a given criteria.
  • Class invariants: used to constrain the objects of a class. If you have a queue you may want to constrain it to only contain a certain number of objects.

 

Spec# is a research project by Microsoft that brings this concept to .net, and shipping with v4 it is referred to Code Contracts. The formal definition is:

Code Contracts provide a language-agnostic way to express coding assumptions in .NET programs. The contracts take the form of preconditions, postconditions, and object invariants. Contracts act as checked documentation of your external and internal APIs. The contracts are used to improve testing via runtime checking, enable static contract verification, and documentation generation.

 

Now that we have an idea of what programming by contract it,what does it look like? Typically how one would go about this was by checking some value, and throwing an exception if it wasn’t valid.  If you were creating an object pool, and wanted to implement a contract it could look something like this.

public class ObjectPool<T> where T : new()
{
    private List<T> pool;
    private int maxItems;
    
    public ObjectPool(int startingCapacity, int maxItems)
    {
        //preconditions that constrain the input.
        if (startingCapacity < 1)
            throw new ArgumentOutOfRangeException("startingCapacity");

        if (maxItems < startingCapacity)
            throw new ArgumentOutOfRangeException("maxItems");
            
        pool = new List<T>(startingCapacity);
        maxItems = maxItems;
    }

    public T GetObject()
    {
        T result = GetNextObject();

        //postcondition: just an example. You proabably wouldn't do this
        if (result == null)
            throw new Exception("The returned object was null");
            
        return result;
    }
    
    private T GetNextObject()
    {
        return default(T); //dummy implementation
    }
    
    private void EnsureCapacity()
    {
        //invariant : just an example, you probably wouldn't do this
        if (pool.Count > maxItems)
        {
            throw new Exception("The returned object was null");
        }
    }
}

 

It works, but it feels sloppy, and it will only get executed at runtime. Code Contracts actually give you static analysis of the code, and will let you know if you are validating the contract before hand.

 

public class ObjectPool<T> where T : new()
{
    private List<T> pool;
    private int maxItems;

    public ObjectPool(int startingCapacity, int maxItems)
    {
        //preconditions that constrain the input.
        Contract.Requires(startingCapacity > 0, "startingCapcity must be >0");
        Contract.Requires(maxItems > startingCapacity,"maxItems must be >startingCapcity");

        pool = new List<T>(startingCapacity);
        maxItems = maxItems;
    }

    public T GetObject()
    {
        T result = GetNextObject();

        //postcondition: just an example. You proabably wouldn't do this
        Contract.Ensures(result != null);

        return result;
    }

    private T GetNextObject()
    {
        return default(T); //dummy implementation
    }

    [ContractInvariantMethod]
    private void EnsureCapacity()
    {
        Contract.Invariant(this.pool.Count < this.maxItems);
    }
}
 

CodeContracts If I were to try to initialize ObjectPool<T> with (0,10) I would see a warning before I even compiled it.

.net , ,

Social Media Is No Longer Child’s Play

15. January 2010

The other day my wife called Comcast to transfer service, and see if they would be able to provide any discounts. After a quick conversation, the rep actually suggested we switch to our local FIOS provider. I found this quite funny, so I decided to tweet about it. I wasn't complaining, but I knew Comcast would see it most would most likely respond.

source: http://www.fredcavazza.net/2008/06/09/social-media-landscape/Sure enough, not 5 minutes later a representative wanted to know more details on the conversation so she could "review with management". I figured I would humor her and sent over what I had, and while I was at it asked about those discounts I wasn't able to get over the phone. Not 12 hours later I had a voicemail from them  apologizing for my experience, and letting me know that reducing my bill would not be a problem. Fast forward through a game of phone tag, and I had a whopping $40/mo taken off my bill without a single feature being removed!

Some people find this surprising, but not me. I work for Visible Technologies and we provide the data companies need in order to do this. What we do is collect all kinds of consumer generated media (twitter, blogs, forums, etc...), apply sentiment analysis to it along with some BI analytics, and provide that to our clients. They can use the information to see what people are saying about them on the internet, and then use our software to help engage said user. (On a side note, if you are looking for a job, we are hiring.)

More and more companies are realizing that with the advent of social media, more power has been shifted to the consumer. Take for example my Twitter account: I have a measly 61 followers, BUT that is more reach than most people have off the internet. Add Facebook, MySpace, YouTube, and any other site you want to the list, and the potential reach of one person is tremendous.

 

dell If you don’t believe me just look around for yourself. On June 14, 2007 an article entitled 22 Confessions Of A Former Dell Sales Manager was posted on the Consumerist. The next day it was on the front page of digg.com. Dell saw it, issued a takedown notice, and that also hit the front page of digg. As you can imaging, that move was not well accepted.

The following day (June 16) Dell actually apologized, and issued their own “23 confessions”. If you search around for sites that picked up the apology, you will find the overall feeling towards Dell changed and it literally happened overnight.

 

Sweet360Still don’t believe me? February, 2008 – A story is posted of a person who sent his Xbox in for repairs, and was assured that the original case would remain unaltered. When he got his 360 back, he was  surprised to see that the custom artwork was removed from the case. He claims they scrubbed it off, but even if we give them the benefit of the doubt and say they sent him a completely different one, it was still kind of  bad move. It doesn’t matter if he made the entire thing up because Microsoft saw the potential impact, and made things right. Once again the general feeling toward the situation was turned around.

 

This kind of thing doesn’t just happen to stories that make it to the front page of popular websites. Businesses are no longer waiting for the consumer to come to them when there are problems. They have recognized that we have a voice and are trying to be as proactive as possible. This is a good thing – use it, don’t abuse it. Social media has become a powerful tool to make things happen, and as the saying goes: With great power comes great responsibility.

 

 

*Disclaimer: I am not claiming that Comcast, Dell, or Microsoft are clients of Visible Technologies. They just happen to make good examples :)

General Nonsense , ,