KevinUp

real world programming

Archive for May, 2007

GPS Gas finder.

Posted by kevinup on May 28, 2007

So I had this awesome idea the other day for a software idea. I would write it myself, but I really don’t have the capital to set it up, or the means to create or distribute it.

My idea is to write a software package that runs on a Internet enabled GPS device. Basically it would find you cheap gas. You would enter either how many minutes, or distance you wish to travel. Then it would feed off of a site like http://www.cincygasprices.com/ and find the cheapest gas within you input parameters. It could even filter out certain gas stations, like I only buy Shell gas (Like I won’t buy gas where I can’t pay at the pump).

Looking at cincy gas prices right now. The difference between the top and bottem price is 31 cents. If you have a 15 gallon tank that can make a difference of about $5. I figure you could sell the GPS software for $50 bucks, and it would pay for itself over time. You could even distribute a GPS device, with the software already installed for around $150. I bet anyone who is in the market for a GPS, would probably either buy this one, or at least seriously consider it. The other thing that would have to be figured out, would be how it would communicate with the internet. I would assume that you would need some kind of cell phone service that would charge a monthly fee. The pricing would have to be such that it would pay for itself every month.

If I could distribute it, I would sell it in a Kiosk in the mall. Perhaps I could get a Best Buy, or Microcenter to sell it as well.  I think that as this software would begin to penetrate the market, gas prices would go down. Or at least, there wouldn’t be huge flucuations in price. Even as I’m writing this post. I’m seeing holes in it, like what about Internet enabled cell phones? I never said it was perfect. Anyway so there it is. 

Posted in software ideas | Leave a Comment »

optimizing viewstate

Posted by kevinup on May 24, 2007

I’ve always heard of optimizing viewstate, like you hear about an urban legend. I never understood what you would optimize or how to go about doing it. Let me be clear. I have made pages such that certain controls had their enable viewstate property disabled. I’ve moved things around such that the view state is smaller, but I’ve never really looked at manipulating view state directly. I think it would be really cool if you could do this with using as an httpModule mas, c’est la vie. There are two methods which are important:

protected override void SavePageStateToPersistenceMedium(object state)
protected override object LoadPageStateFromPersistenceMedium()

These methods do pretty much what you think, drop them on your page, and then you can manipulate the view state. Viewstate comes in as an object on the save. Then you can do anything crazy you feel like doing. Like maybe we could gzip it. Here’s a quicky little gzip class.

 

public static class Compressor
{
    public static byte[] Compress(byte[] data)
    {
        MemoryStream output = new MemoryStream();
        GZipStream gzip = new GZipStream(output,
                          CompressionMode.Compress, true);
        gzip.Write(data, 0, data.Length);
        gzip.Close();
        return output.ToArray();
    }
    public static byte[] Decompress(byte[] data)
    {
        MemoryStream input = new MemoryStream();
        input.Write(data, 0, data.Length);
        input.Position = 0;
        GZipStream gzip = new GZipStream(input,
                          CompressionMode.Decompress, true);
        MemoryStream output = new MemoryStream();
        byte[] buff = new byte[64];
        int read = -1;
        read = gzip.Read(buff, 0, buff.Length);
        while (read > 0)
        {
            output.Write(buff, 0, read);
            read = gzip.Read(buff, 0, buff.Length);
        }
        gzip.Close();
        return output.ToArray();
    }
}

Now lets put it all together:

protected override void SavePageStateToPersistenceMedium(object state)
{
    LosFormatter formatter = new LosFormatter();
    StringWriter writer = new StringWriter();
    formatter.Serialize(writer, state);
    string viewStateString = writer.ToString();
    byte[] bytes = Convert.FromBase64String(viewStateString);
    bytes = Compressor.Compress(bytes);
    string base64string = Convert.ToBase64String(bytes);
    ClientScript.RegisterHiddenField("__VSTATE", base64string);
}

 

protected override object LoadPageStateFromPersistenceMedium()
{
    string viewState = Request.Form["__VSTATE"];
    byte[] bytes = Convert.FromBase64String(viewState);
    bytes = Compressor.Decompress(bytes);
    LosFormatter formatter = new LosFormatter();
    return formatter.Deserialize(Convert.ToBase64String(bytes));
}

Posted in ASP.net, C# | Leave a Comment »

TDD

Posted by kevinup on May 15, 2007


Test driven development. Is there any other way to develop? I was first exposed to this kind of development on my current project about a year ago by Dave Donaldson. While I don’t think that I’ll go into all the points of TDD, but let’s just say if you aren’t doing it, you suck. I remember dave would go through our code base looking for optimizations, problems, basically general code auditing. And our testing framework would make sure that his refactors wouldn’t break anything. Something I noticed was about 20% of our test were something like this:

[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void AddCustomer_NullExceptionTest()
{
    CustomerManager.AddCustomer(null);
}

Here is what is being tested.

public static long AddCustomer(Customer customer)
{
    if (customer == null)
    {
        throw new ArgumentNullException("customer", "Customer cannot be null");
    }
    //rest of add logic code...
}


Back to the point, now every time you write a new public static method, and are writing tests, you always have to write a negative test to get your code coverage up. Here’s the thing about negative tests, they are always the same. So I thought it would be cool if I write a test that passes null into every public static function, and verify it is either throwing an expected exception, or not throwing an exception at all. So now we down the number of tests we have to write by 20%, and we put it into 1 test. Here is my test (Modified slightly for this post):

[TestMethod]
public void NullCheckTests()
{
    Assembly assembly = Assembly.Load("Target.Assembly");
    Type[] assemblyTypes = assembly.GetTypes();
    for (int counter = 0; counter < assemblyTypes.Length; counter++)
    {
        if (assemblyTypes[counter].IsPublic)
        {
            MethodInfo[] methods = assemblyTypes[counter].GetMethods(BindingFlags.Public | BindingFlags.Static);
            for (int i = 0; i < methods.Length; i++)
            {
                if (methods[i].GetParameters().Length > 0)
                {
                    List<object> parms = new List<object>();
                    int para = methods[i].GetParameters().Length;
                    foreach (ParameterInfo p in methods[i].GetParameters())
                        parms.Add(null);
                    try
                    {
                        methods[i].Invoke(null, parms.ToArray());
                    }
                    catch (Exception ex)
                    {
                        if ((ex.InnerException is ArgumentNullException) ||
                        (ex.InnerException is ArgumentException) ||
                        (ex.InnerException is InvalidOperationException))
                        { /*everything worked*/}
                        else
                            throw ex.InnerException;
                    }
                }
            }
        }
    }
}

Even if your methods take value types, like ints, longs or enums, it still will pass in the default value. When I first ran this test, I found a lot of tests that weren’t throwing the correct exception, weren’t checking exceptions at all, or were throwing the exception I hate the most, NullReferenceException. Initially out of around 900 public tests in our testing framework. Only around 500 were passing this test. It took a while, but now I’ve got this test passing. Now developers don’t have to write ‘negative’ tests. And there is a test making sure that they are handling negative input. I know there is an FxCop rule that checks for this, but now, we can get some coverage out of it.

Posted in tdd | 1 Comment »

web development

Posted by kevinup on May 11, 2007

I’ve been doing web development for about 8 years. I started off with the typical HTML, branched into some javascript, then ASP and PHP, a little bit of Perl, then eventually into ASP.net and C#.

It baffles me how developers have totally missed the fundamentals of web development. I probably sound like a C developer talking about how no one cares about memory management anymore.

Specifically I’m talking about post backs, and client server communication. Such as when I find a button on a page that posts back to the page so that it can redirect to another page. Eh? You could just make an onclick event that does a window.location=’myNewUrl.html’. Or better yet, just make it a link. You save yourself a round trip, improve user experience, everyone wins.

Posted in web development | Leave a Comment »

Utils.HasRows

Posted by kevinup on May 8, 2007

 

I hate getting NullReferenceException. It’s the bane of my existence. My feeling is if you get to the point that you get a NullReferenceException, then you haven’t done your job as a developer. I’m also lazy. Who wants to check for Null all the time? Not me. That was one of many reasons I wrote this function:

public static bool HasRows(ICollection list)
{
    if ((list == null) || (list.Count == 0))
        return false;
    return true;
}

There are developers out there that would just do something like this:


List<SearchResults> results = GetSearchResults();
if (results.Count > 0)
{
    //do something
}

The problem is if another developer comes in and changes GetSearchResults() to return null instead of an empty list then things start to bomb. The thing is, at least in this example, you can tell that the logic would be the same, so now to code defensively we do this.


List<SearchResults> results = GetSearchResults();
if (results!=null && results.Count > 0)
{
    //do something
}

Now we make every list that comes back from every call, before we use it we do that. Now our code base is a lot bigger than it needs to be. Enter Utils.HasRows.


List<SearchResults> results = GetSearchResults();
if (Utils.HasRows(results))
{
    //do something
}

I could just ramble on and on about why this is cool, and better and faster, but if you can’t make the connection at this point then you probably would keep writing your ‘== null .count>0′ code.

Posted in C# | Leave a Comment »