Tuesday, 24 February 2009

Static links for aspx pages in 20 lines of code

Still using WebForms? Sick of magic string URLs that break when you move you ASPX pages around? Try this! I've created a class called UrlFor<TSomePage>. It examines the page class and figures out the URL by making a few assumptions about your aspx pages (the aspx file has the same name as the class, the namespaces match the folder structure, that kind of thing...)

public class UrlFor<TAspxPage>
    where TAspxPage : Page
    private static string baseUrl = typeof(TAspxPage).FullName.Substring("YourAppBaseNamespace".Length).Replace('.', '/') + ".aspx";

    public Dictionary<string, string> QueryString = new Dictionary<string, string>();

    public UrlFor<TAspxPage> Set<TValue>(Expression<Func<TAspxPage, TValue>> getProp, TValue value)
    {
        this.QueryString[((MemberExpression)getProp.Body).Member.Name] = value.ToString();
        return this;
    }
    public override string ToString()
    {
        var qs = String.Join("&", this.QueryString.Select(pair =] pair.Key + "=" + HttpUtility.UrlEncode(pair.Value)).ToArray());
        return baseUrl + (qs.Length ] 0 ? ("?" + qs) : String.Empty);
    }
}
anyway, it lets you write things like this in your code:
[%= new UrlFor<Meetings.Details>().Set(d => d.WorkspaceId, 1).Set(d => d.MeetingId, 2) %>
where Meeting.Details is a Page class with a property on it called MeetingId and one called WorkspaceId. This generates a url like
/Meetings/Details.aspx?WorkspaceId=1&MeetingId=2
Of course your pages may not have properties that correspond to the querystring parameters, but you can always write an extension like
public static class UrlForExt
{
    public static UrlFor<T> SetWorkspaceId<T>(this UrlFor<T> url, int value)
        where T:WorkspacePage
    {
        url.QueryString["workspaceid"] = value.ToString();
        return url;
    }
}
and get the same effect by writing something like
new UrlFor<Default>().SetWorkspaceId(1)
Neat huh!? Use this to build your links and you can rename and move your pages to your hearts content!

Submit this story to DotNetKicks

Monday, 9 February 2009

MigrationScriptGenerator

Hi all, I thought I'd give you all a heads up on a new tool I've written for keeping your database schema in sync with your development schema
Basically its a tool for generating SQL scripts for changes (using Open DBDiff), with errors if you do a change that might lose data. It creates a script to you to review. If your changes are non destructive, then it just makes the change script for you.
Its pretty alpha at the moment, but seems functional enough for development work. Check out the sample project - it's hooked up with Fluent NHibernate. Try changing some of the entity classes and rebuilding, and have a look in the /Sql folder at the generated scripts.
You can find it at http://code.google.com/p/migrationscriptgenerator/

Submit this story to DotNetKicks