You are currently browsing the category archive for the ‘Uncategorized’ category.

This morning @JeffHandley tweeted this http://www.forkcan.com/viewcode/277/Null-Dot-Operator-Extension-Method essentially the idea is that you can call your code and apply default options. I kinda like the idea, but I wasn’t so convinced of the name he chose for the name of his extension method _ it kinda looks like an operator, but really isn’t and you have to start feeling for the guy reading your code 2 years after you left the company on this one.

Also, to use his code on nested properties you have to make a call like this:

var result = bar._(b => b.ChildProperty)._(c => c.StringProperty)

Which I’m not sure is exactly attractive to the eye. Also, if you did try to chain a whole bunch of properties together it might end up really, really hard to read.

Now, it’s easy to sit and snipe, but that’s crappy, so my implementation of his idea gets called like this:

var result = root.NeverNull((me) => me.SomeProperty.AnotherProperty.SomeProperty, defaultValue: new MyClass(3));

It’s not exactly beautiful, but I think it’s slightly more obvious. My implementation currently has the restriction that it only works for properties, not for methods. Anyway, the implementation is as follows, what do you think?

public static class CodeInsipredByJeff
{
    public static T NeverNull<T>(this object target, Expression<Func<T, T>> propertyExpression, T defaultValue) where T : class
    {
        var properties = GetProperties(GetExpression(propertyExpression));

        object currentTarget = target;
        foreach (var property in properties)
        {
            if (currentTarget == null)
            {
                return defaultValue;
            }
            currentTarget = property.GetValue(currentTarget, null);
        }

        if (currentTarget != null && currentTarget is T)
        {
            return (T)currentTarget;
        }
        else
        {
            return defaultValue;
        }
    }

    private static MemberExpression GetExpression<T>(Expression<Func<T>> expression)
    {
        var body = expression.Body;
        if (body is MemberExpression)
        {
            return body as MemberExpression;
        }
        else if (body is UnaryExpression)
        {
            var ue = body as UnaryExpression;
            return ue.Operand as MemberExpression;
        }
        else
        {
            throw new NotImplementedException();
        }
    }

    private static IEnumerable<PropertyInfo>GetProperties(Expression expression)
    {
        var memberExpression = expression as MemberExpression;
        if (memberExpression == null) yield break;

        var property = memberExpression.Member as PropertyInfo;
        if (property == null)
        {
            throw new NotSupportedException("Expression is not a property accessor");
        }
        foreach (var propertyInfo in GetProperties(memberExpression.Expression))
        {
            yield return propertyInfo;
        }
        yield return property;
    }
}
Advertisements

I’ve written this a couple of times this morning:

if (string.IsNullOrWhiteSpace(Name))
{
    errors.Add(new KeyValuePair("Name", "Name must contain some text"));
}

if ((Name ?? "").Length > 50)
{
    errors.Add(new KeyValuePair("Name", "Name cannot be more that 50 characters long"));
}

I couldn’t help but feel that if I had to write this more than about twice I would go nuts, never mind the obvious maintenance problems. If I rename a property I want the correct property name in the errors collection, not the name of the property from 9 months ago.

So since all this validation is being done at the domain level and all my domain entities implement the interface IBaseEntity (come on EF, let me pick my own base class)  I decided I’d write myself a little validation function that would use lambdas to take a property and validate its value meets the constraints. So I did and ended up with the following function:

public static void ValidateRequiredFieldWithMaxLength(this IBaseEntity entity, Expression> e, int maxLength, IList> errors)
{
    if (errors == null)
    {
        throw new ArgumentNullException("errors");
    }

    MemberExpression member = (MemberExpression)e.Body;
    Expression strExpr = member.Expression;
    string propertyName = member.Member.Name;
    string value = e.Compile()();

    if (string.IsNullOrWhiteSpace(value))
    {
        errors.Add(new KeyValuePair(propertyName, string.Format("{0} must contain some text", propertyName)));
    }

    if ((value ?? "").Length > maxLength)
    {
        errors.Add(new KeyValuePair(propertyName, string.Format("{0} cannot be more than {1} characters long", propertyName, maxLength)));
    }
}

Which may not be immediately obvious to you, but the long and the short is that I can now call my validation functions like this:

this.ValidateRequiredFieldWithMaxLength(() => this.Code, 10, errors);

It’s not perfect and I might end up fiddling around with it a bit more, but for now I like it.

I’ve been hacking around with database migrations and decided to give MigratorDotNet a go. The first problem I found was that I had to manually number the migrations. The trick of using the migration attribute with the current date and time formatted as yyyyMMddhhssfff works a charm, but is a pain to type more than once.

So to solve the problem I’ve created a code template that gives you something like this as a shell:

using System.Data;
using Migrator.Framework;

namespace MigrationLibrary
{
[Migration(201003040752265)]
public class Migration1 : Migration
{
public override void Up()
{
throw new System.NotImplementedException();
}

public override void Down()
{
throw new System.NotImplementedException();
}
}
}

To install it you need to do a couple of things, take the dll from in here and register it in your GAC and then take this zip and drop it into “\Visual Studio 2010\Templates\ItemTemplates\Visual C#”. Restart Visual studio and you can now add a migration from the new item menu.

I’ve only tried this in visual studio 2010 and have done no real testing. License wise, let people know I wrote it. If it breaks your machine, steals your financial identity, runs off with your wife and then crashes your car into a wall, it’s your own fault for running code you found on the internet. You have been warned.

The longer you use asp.net webforms the more likely it is that you will see this:

Exception type: System.ArgumentException

Exception message: Invalid postback or callback argument. Event validation is enabled using <pages enableEventValidation=”true”/> in configuration or <%@ Page EnableEventValidation=”true” %> in a page.  For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them.  If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation.

If you’re lucky enough to have it happen on a dev machine and you know which control is causing the problem you’re most of the way to tracking down the error. Just read this, this and this.

If like me, you can’t track it down, all you’re getting is vague error reports and users who can’t remember what they did (or curiously didn’t even see the error) then you need to know which control actually caused the error.

This is what I did:

Imports System.Net.Mail

Namespace Code.Controls

    Public Class TrackingLinkButton
        Inherits LinkButton

        Protected Overrides Sub RaisePostBackEvent(ByVal eventArgument As String)
            Try
                MyBase.RaisePostBackEvent(eventArgument)
            Catch argExc As ArgumentException
                SendPostbackError(argExc)
            End Try
        End Sub

        Private Sub SendPostbackError(ByVal argExc As ArgumentException)

            Dim subject As String = "ArgumentException: Additional info"
            Dim body As String = String.Format("Exception was caused by the control with ID: {0} and clientId of: {1}", _
                                               Me.ID, Me.ClientID)

Dim msg As New MailMessage("from@somesite.com", "support@somesite,com", _

                                       subject, body)

Dim client As New SmtpClient() client.Send(msg) End Sub End Class End Namespace
And hooked it in with this:

<tagMapping>
	<add tagType="System.Web.UI.WebControls.LinkButton"
		mappedTagType="AcademyPro.Code.Controls.TrackingLinkButton"/>

</tagMapping>

Now all I have to do it sit back and wait for the email to fire and I should be able to track down the error (I hope).

Roy Osherove is giving an hands-on TDD Masterclass in the UK, September 21-25. Roy is author of “The Art of Unit Testing” (http://www.artofunittesting.com/), a leading tdd & unit testing book; he maintains a blog at http://iserializable.com (which amoung other things has critiqued tests written by Microsoft for asp.net MVC – check out the testreviews category) and has recently been on the Scott Hanselman podcast (http://bit.ly/psgYO) where he educated Scott on best practices in Unit Testing techniques. For a further insight into Roy’s style, be sure to also check out Roy’s talk at the recent Norwegian Developer’s Conference (http://bit.ly/NuJVa).

Full Details here: http://bbits.co.uk/tddmasterclass

bbits are holding a raffle for a free ticket for the event. To be eligible to win the ticket (worth £2395!) you MUST paste this text, including all links, into your blog and email Ian@bbits.co.ukwith the url to the blog entry.  The draw will be made on September 1st and the winner informed by email and on bbits.co.uk/blog

If you have a web form and don’t want a users input to be saved by a browser for repeated entry later then you need to employ autocomplete attribte of a form.

The HTML below will give you a simple form that the browser should not prompt the user to save the credentials.

You should note, this is not standards compliant, but it does seem to work in chrome, IE and firefox.

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Strict//EN”

    “http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd”&gt;

<html xmlns=”http://www.w3.org/1999/xhtml&#8221; xml:lang=”en” lang=”en”>

    <head>

        <title>Prevent Autocomplete</title>

    </head>

    <body>

    <form id=”payment” autocomplete=”false” action=”#” method=”post”>

        <p><label for=”Name”>Name on Credit Card</label><input type=”text” id=”Name”/></p>

        <p><label for=”CCNum”>Creditcard Number </label><input type=”text” id=”CCNum”/></p>

        <p><label for=”Expiry”>Expiry Date</label><input type=”text” id=”Expiry”/></p>

        <input type=”submit” />

    </form>

    </body>

</html>

I’d like to think that I know a fair amount about core HTML.  That said there’s always room to learn more, and yesterday was a case in point.

Until now, when wanting to separate groups of elements in a selection list we’ve always introduced option elements surrounded by extra characters, e.g. (“–Intermediate / Higher /Advanced Higher”) in the example below.

<SELECT>
<OPTION>--National Assessments (5-14)
<OPTION>A
<OPTION>B
<OPTION>C
<OPTION>D
<OPTION>E
<OPTION>F
<OPTION>--Access 1,2,3 / Core Skills
<OPTION>Pass
<OPTION>Fail
<OPTION>--Intermediate / Higher /Advanced Higher
<OPTION>A
<OPTION>B
<OPTION>C
<OPTION>D
<OPTION>--Standard Grades
<OPTION>Grade 1 - Credit Level
<OPTION>Grade 2 - Credit Level
<OPTION>Grade 3 - General Level
<OPTION>Grade 4 - General Level
<OPTION>Grade 5 - Foundation Level
<OPTION>Grade 6 - Foundation Level
<OPTION>Grade 7 - Course Completed
<OPTION>-HNC/HND
<OPTION>Pass
<OPTION>Fail
<OPTION>--NVQ/SVQ
<OPTION>1
<OPTION>2
<OPTION>3
<OPTION>4
<OPTION>5</SELECT>

As a solution this is a bit messy as the user is still able to select the separator options, and therefore relies on client or server validation to prevent this being saved.  What a revolution then to find that there is an HTML element that allows you to group together a number of option elements – and it’s called OPTGROUP.  Go figure!

In action then, the list above then becomes:

<SELECT>
<OPTGROUP label="National Assessments (5-14)">
<OPTION>A
<OPTION>B
<OPTION>C
<OPTION>D
<OPTION>E
<OPTION>F
</OPTGROUP><OPTGROUP>Access 1,2,3 / Core Skills
<OPTION>Pass
<OPTION>Fail
</OPTGROUP><OPTGROUP label="Intermediate / Higher /Advanced Higher">
<OPTION>A
<OPTION>B
<OPTION>C
<OPTION>D
</OPTGROUP><OPTGROUP label="Standard Grades">
<OPTION>Grade 1 - Credit Level
<OPTION>Grade 2 - Credit Level
<OPTION>Grade 3 - General Level
<OPTION>Grade 4 - General Level
<OPTION>Grade 5 - Foundation Level
<OPTION>Grade 6 - Foundation Level
<OPTION>Grade 7 - Course Completed
</OPTGROUP><OPTGROUP label="HNC/HND">
<OPTION>Pass
<OPTION>Fail
</OPTGROUP><OPTGROUP label="NVQ/SVQ">
<OPTION>1
<OPTION>2
<OPTION>3
<OPTION>4
<OPTION>5</OPTGROUP></SELECT>

It’s browser compliant, and you can style the OptGroup elements different to the Option elements.

Now I can’t wait to see what I can learn today.

At least. that’s what I thought until today.

It’s been a bit of a running joke in our office that being cynical too early in the week is non-productive, and detracts from the job in hand.  And so it was that “Cynical Thursday” was born!  Why Thursday?  Well, obviously Wednesday signifies the middle of the week – still far too early for negative vibes.  And who wants to be downcast on a Friday, riding the cusp of the weekend?

Not to break with tradition, today has had it’s fair share of gripes and groans – about work, people, life etc.  But today is different.  Today our cynicism has reached the level whereby we challenged ourselves to do something about it.

Today, “theoldsewingfactory” has been reborn.  This blog is the start of things to come.

No longer will cynicism rule.  No longer will we allow our destiny to be taken from our hands.  We have a voice.  We have talent and skills.

We will succeed.