Apologies and Greetings

I have just changed hosts for my blog, and the export from the old host to the import into the new host didn’t go too well. The posts seem OK, but images etc. are missing. I am working on this as hard as I can to restore things to the quality blog I used to know and love. Of course ‘as hard as I can’ isn’t that much for non-paying work, but I’m doing what I can.

- Brady

Make F5 Execute the Query in the Visual Studio Query Editor Just like in the SSMS Query Editor

As if the command mapped to the F5 key in most browsers versus the command mapped to the F5 key in SQL Server Management Studio (SSMS) doesn’t cause me enough grief, Visual Studio brings more annoyance to the party with its two easily confused SQL windows, the Transact-SQL Editor and the Query Designer. I think the database management tools in Visual Studio 2010 are a vast improvement even on Visual Studio 2008, and I often find them more useful than just having SSMS running in a separate application window, but as a seasoned SSMS user, I expect results when I press F5, or Execute in SSMS. Hitting F5 in a data window in Visual Studio has only one result by default, and that is to start a build. Inadvertently triggering a build in Visual Studio doesn’t make for a shiny, pretty, Sunday School type situation, especially with large solutions and complex build processes, so I think my advice to remap the F5 key for data windows in Visual Studio, to rather execute the current SQL query, is pretty good advice. This is very easy to do once you know where to look, and that’s where I hope this show and tell post will be helpful to you.  Let’s start with the Transact-SQL Editor. My favourite addition to the database tools in Visual Studio, this is the closest you get to the good old, free text query window in SSMS. I find the Query designer a schlep to open, as I always get subjected to the Add Tabledialogue, and then still have to hide the noisome Diagram and Criteria panes before I can get hacking away at a cool query.

Let’s make F5 execute the SQL query in the active Transact-SQL Editor pane. Bring up the Options dialogue by clicking Tools->Options on the main Visual Studio menu.  This will present you with the unfriendly and anachronistic spectre of a very densely populated dialogue that is both modal and fixed size. Hard to believe in this day and age, but it’s all we have.  Here it is, together with numbered steps which I explain below:

Shot of VS Dialogue for settings shortcuts.
Lets look at the numbers, as they say:
  1. Type the word execute into the Show Commands containing field. This really narrows down an otherwise punitively long list of commands. I initially tried using the term sql, but still that filtered list was even longer than anything you want to deal with in a retarded dialogue that can’t be resized and only shows about five commands at a time.
  2. There are only three commands in VS 2010, and I don’t know what Data.Execute does, but it doesn’t concern us here. Select the Data.SqlEditorExecuteSql command to proceed.
  3. Remove the existing key binding for this command.
  4. Limit the scope of our binding to the SQL Editor.
  5. Give the Press shortcut keys textbox focus and press F5. Don’t try and type F and 5.
  6. Assign the shortcut key to the Data.SqlEditorExecuteSql command.
  7. After repeating this procedure for the QueryDesigner.ExecuteSql command, tidy up by closing the Options dialogue.

Now you can enjoy the peace of mind that whenever you are editing a SQL query, be it in SSMS or VSA 2010, hitting F5 will execute your query, which will hopefully be quicker that waiting for a build and getting taken against your will into a debugging session.

Making passwords visible with jQuery

I very recently coded up some views for new members on a site to register, to change their passwords, and in one user story, for administrative members to sign up other members, and be able to set temporary passwords for them. I’ve always prefered a UI that allows an option for passwords to be visible, and I thought I’d offer my users that option. It also helps a bit having it myself when I do some manual testing. Here is the somewhat hackish solution I came up with. I am no jQuery wizard, but this code seems to work just fine.

function copyDataAttributes(source, destination) {
    for (var i = 0; i < source.attributes.length; i++) {
        var a = source.attributes[i];
        if (a.name.indexOf("data-") == 0) {
            destination.attr(a.name, a.value);
        }
    }
}
function setPasswordVisibility() {
    if ($("#PasswordsVisible").is(':checked')) {
        $('form').find('input:password').each(function() {
            var newText = $("");
            copyDataAttributes(this, newText);
            newText.attr({ id: $(this).attr("id"), name: $(this).attr("name"), value: $(this).attr("value") })
                .addClass("password").bind('copy', function() { return false; })
                .insertBefore(this);
        }).remove();
    } else {
        $('form').find('input:text.password').each(function() {
            var newPassword = $("");
            copyDataAttributes(this, newPassword);
            newPassword.attr({ id: $(this).attr("id"), name: $(this).attr("name"), value: $(this).attr("value") })
                .insertBefore(this);
        }).remove();
    }
}
jQuery(function () {
    setPasswordVisibility();
    $("#PasswordsVisible").click(function () {
        setPasswordVisibility();
    });
});
My main function, setPasswordVisibility, checks if passwords should be visible or not, and if so, sets about making them visible. Initially I though this would be as easy as changing the type of an input from ‘password’ to ‘text’, but changing the type attribute is simply not allowed. Some researched found an acceptable workaround in replacing a ‘password’ type input with an almost identical ‘text’ type input. This is of course reversed and a ‘text’ input replaced with a ‘password’ one to hide a password again.

What complicates matters here is having two inputs for the password, with one for confirmation, so I brutishly applied this to all passwords on a form. Feel free to add some finesse and narrow down the target. Further complications are provided by the ‘data-’ validation attributes that MVC scaffolding adds to elements based on model metadata; in this case stuff used to compare the two password fields using jQuery validation. I didn’t want to copy all attributes, but I felt safe copying all ‘data-’ attributes, as they are for all intents and purposes my domain, and not that of the DOM.

Notice that when I turn a ‘password’ input into a ‘text’ input, I add a ‘password’ class to it, so when I hide passwords again, I don’t just hide all text inputs.

What happens here is when the page loads, I grab the click event of a checkbox that you would use check to make passwords visible. I also run the main function independently of the click event, because the checkbox might already be checked.

Intro to ReSharper’s Live Templates

Every so often I have the pleasure of doing some work with the DevExpress eXpressApp Framework (XAF), a really powerful application framework for ASP.NET and Windows Forms applications. Tedious LOB code is just not my heavy metal (well, not for your average B), and XAF’s model designers and components almost save me from writing any of that kind of code, save for the actual business objects and a few custom UI validations.

It is with the business objects I have problems though. These use the proprietary DevExpress ORM library, so I can’t plug in EF Code First, with its ever so sweet POCO business objects, and I am forced to use backing field based properties, having to raise a change notification in every setter. At it’s simplest, a XAF domain class will look like this:

    public class Person : BaseObject
    {
        public Person(Session session)
            : base(session)
        {

        }

        private string _surname;
        public string Surname
        {
            get { return _surname; }
            set { SetPropertyValue("Surname", ref _surname, value); }
        }
    }

I’m sure the reader will agree that manually typing up more than just the above example quickly becomes very tedious; is also a huge waste of truly productive development time, and unnecessarily introduces risk, what with typos and all, especially with that oh-so-nasty string literal property name. While I am most sure that DevExpress’s CodeRush IDE assistant has something that magically helps coders produce these extremely fast and accurately, I am a died in the wool ReSharper man, and my honey doesn’t automatically handle proprietary structures. Now ReSharper has a powerful feature called Live Templates, of which I have only used a small sample of the built-in templates, for things like foreach loops, where ReSharper inserts all the boilerplate text and automatically focuses an edit field only where required, i.e. on variable declarations, like so:

List of property names in a dropdown that ReSharper automatically chooses for loop the variable in a For loop Live Temple.

List of property names in a dropdown that ReSharper automatically chooses for loop the variable in a For loop Live Temple.

Here the template guessed I wanted a loop over Problems, but also gave me a dropdown of other available collections – I just rather captured the more impressive choice of variable names – and at worst, the word Problems is the first thing I would have had to type after invoking the template. Next, I press TAB to travel over to var where, besides typing something new and interesting, the template gives me a dropdown choice of var or PropertyBag, and then last, but not least, for the loop variable name I get given the choice shown in the image, or, of course whatever I want to laboriously type for myself. Now I’ve known for a long time that I can somehow create such templates for myself, but I tried once and it didn’t work, and pressure was on at the time, plus I can code pretty fast anyway, so I left it there. Yesterday I took time out to investigate this monster, and discovered ReSharper makes it shockingly easy to create such templates. Please note that I am not plugging here but praising, besides pointing out an amazing feature to the chosen few, i.e. readers of this blog.

By now only the slowest readers won’t have guessed which template I set out to create, but that wasn’t the only factor that prompted me to check this out when I did. I discovered, much to my small happiness, that ReSharper has local help. I’m using version 6, and I don’t know when last I used ReSharper help, but back then it was only online, and I am using a GPRS connection right now, so any time online is strictly rationed to Very Important ThingsTM. With this local help, I found how to begin and complete a cool little template, and I outline this below.

To start I select the property declaration you see right at the top of this post, then from the ReSharper menu, select the command Tools->Create Live Template from Selection. This brings up a dialogue showing the template fields that ReSharper has inferred, and gives me an opportunity to remove unwanted fields. Unfortunately ReSharper guesses no fields for my example property, so if you’ll allow me to cross examples, doing the same thing with my foreach loop in the closer image yields one field, $IENUMERABLE$, in place of the literal text Problems. After I accept the assumed fields, or lack thereof, in my property, I get taken into the template editor, where I edit the template, replacing literal text with field names, which as you see are indicated by surrounding the field name with the $ token.

Guessed-Fields

Now for the magic! To the right of the text editing pane the template editor presents a grid showing each one of my fields, the source of that field’s value, and, where a field occurs more than once, an option for the editable instance of that field. This determines the instance you edit; which determines the value of the other instances.  The images below show the inferred field in the loop and my template after I have edited it and inserted fields where I want it to replace literal text.

Template-Editor_All

I can only show a small sample of the built-in macros, but there are many. I choose a macro for each field and save the template, and on to my final cliché  Voilà  By simply typing the shortcut I defined for my template, dxp, as seen above right – followed by TAB – I get my whole property declaration expanded and I only have to type the name once, for both private and public parts. This is because the template field doesn’t include the underscore for the private name – you have to type one underscore once – to it can juts make that properties first letter upper case, as the chosen, built-in, macro does.

Spatial Entities

Recent work has given me my first real exposure to the spatial data types of SQL Server. Even though I’m not using these directly, as they are nicely abstracted behind already existing stored procedures and functions, I do find getting to know them very interesting. One problem with the reporting project I’m busy with though, is that the current Entity Framework (EF) RTM does not support the spatial data types, and I’ve had to use good ol’ ADO.NET and typed data sets instead.
I thought I’d do a little research into spatial data in EF over the weekend, as was delighted to find that the Entity Framework June 2011 CTP caters for spatial data. I have Jason Follas to thank for this, for his Entity Framework Spatial: First Look blog post. In the work I’m doing right now, a common task is finding e.g. all the suburbs in a given radius from one particular suburb, and Jason’s very first example query is a very similar distance query. When I saw that, I knew my research was going to be fun.

To illustrate how to find closest suburbs to a given suburb, I have created a simple EF data model, with just a Suburb table, which has one spatial field of SQL Server data type geometry:

Model_2

Here the Geometry property contains a polygon that describes the borders of the suburb, with vertices defined in terms of degrees latitude and longitude. This shows just one of the neat DdGeometry methods, Distance. The two null checks in the CenterDistanceFromCenterDistanceFrom method are because a DbGeometry may not always be a shape, and thus not always have a valid Centroid property:

public class Suburb
{
    public int Id { get; set; }
    public string PostalCode { get; set; }
    public string Name { get; set; }
    public int CityId { get; set; }
    public DbGeometry Perimeter { get; set; }

    public double? ClosestDistanceFrom(Suburb there)
    {
        if ((there == null) || (there.Perimeter == null))
        {
            return null;
        }
        return Perimeter.Distance(there.Perimeter);
    }

    public double? CenterDistanceFrom(Suburb there)
    {
        var centerHere = this.Perimeter.Centroid;
        var centerThere = there.Perimeter.Centroid;

        if ((centerHere != null) && (centerThere != null))
        {
            return centerHere.Distance(centerThere);
        }
        return null;
    }
}

And now for the part you’ve all been waiting for, a LINQ to Entities query using a spatial column:

public IEnumerable GetClosestSuburbs(Suburb homeSuburb)
{
    var dbContext = new GeometryEntities();
    var weAreHere = dbContext.Suburbs.FirstOrDefault(s => s.Name == homeSuburb.Name);
    if (weAreHere == null)
    {
        return new List();
    }
    var inRadius = dbContext.Suburbs
                            .Where(s => s.Name != homeSuburb.Name)
                            .OrderBy(s => s.Perimeter.Distance(homeSuburb.Perimeter))
                            .Take(20)
                            .ToList();
    return inRadius;
}

In the above code, I first retrieve my home suburb, Morninghill, and then query for the twenty closest suburbs, by ordering by distance from Morninghill, ascending. Distance, as used in this example, is the distance between the ‘centre’ of Morninghill and another suburb, hence my using the Centroid property, which returns a Point that is effectivly the ‘centre’ of a Polygon. Properties and functions like Centroid are available out of the box with the new Spatial data types.

Removing Unused Default ID’s from ASPX tags.

I can hardly believe it has taken me this long, several few years in fact, to discover just how few ASP.NET Web Forms controls need an explicit ID attribute. I mean even the default kind of ID value assigned by the designer, e.g. TextBox4, Label7, DropDownList1 and other such abominations; in common or garden data binding scenarios most of these aren’t necessary at all.

This pleases me. It pleases me no end, because I have finally been relieved of my tortuous obsession for reassigning meaningful ID attributes to controls, like renaming TextBox1 to surnameText etc. If you have any idea how just seeing those default ID’s laying around in markup makes me, read on. If you actually write code against such ID’s, you may stop reading though, and step outside to be shot.

I quite by accident discovered I can simply delete most of these. Data bound controls don’t need them and controls that raise events don’t need them. That’s why we have object sender in our events after all. We can simply delete them when they pop up, and only worry about a meaningful ID if we are going to use it, i.e. if it is really going to be meaningful. It is, however, quite the pain to do this manually every time I create or paste a control (VS is considerate enough that it provides one if you thoughtlessly paste a server-side tag without an ID attribute. Enter the macro!

Every time my eyes are offended by the encroaching masses of default ID’s, I run this little baby, and it removes any ID attribute that ends in a number. Yes, there may me some casualties one day, but it is unlikely I will hand-code control ID’s that require a numbered ID attribute; collateral damage if you will, but I’m happy to accept that and move on. This Macro code carries no warranties, only warnings, but try it if you, like me, like neat code.

Sub RemoveDefaultIds()
DTE.Windows.Item("{CF2DDC32-8CAD-11D2-9302-005345000000}").Activate() 'Find and Replace
DTE.Find.Action = vsFindAction.vsFindActionReplaceAll
DTE.Find.FindWhat = " ID="".#:z"""
DTE.Find.ReplaceWith = ""
DTE.Find.Target = vsFindTarget.vsFindTargetFiles
DTE.Find.MatchCase = True
DTE.Find.PatternSyntax = vsFindPatternSyntax.vsFindPatternSyntaxRegExpr
DTE.Find.SearchPath = "Current Document"
DTE.Find.ResultsLocation = vsFindResultsLocation.vsFindResults1
Debug.Print(DTE.Find.Execute())
DTE.Windows.Item("{CF2DDC32-8CAD-11D2-9302-005345000000}").Close() 'Find and Replace

End Sub

Keeping things brief.

Yesterday I installed MVC 3 RC2, and I am loving it!  I haven’t looked at anything from MVC 3 yet, and to jump straight into coding Razor views made my day.  Look, for what I did on a small, example project for a client , there are no major differences between the Razor and WebForms view engines, except for Razor’s glaring brevity.  One of the most immediate pleasures of using Razor for the first time, is not being constantly plagued by proper closing of code blocks.  Hot on that one’s heels is the wonderful terseness of Layouts, the Razor equivalent of master pages.  Notice the neat absence of angle brackets et al in this mark-up sample:

An 'if' block in a Razor view.

Also notice the new <text> tag.  This is specific to Razor and indicates content to be interpreted as a text literal, not part of the enclosing code block, the if block in this case.  Text within HTML tags, within a code block, does not require a <text> tag, like the last ActionLink.  BTW, I know the second pipe character should actually be inside the if block, but this is an example, for illustration only.  The Model.ViewMode is specific to my view model base class and not part of Razor.

Razor replaces traditional master pages with layouts.  I don’t intend to really go into layouts here, as I think Scott Guthrie gives ample detail in the blog post I link to, but I will stress their brevity compared to master pages here.  Consider this excerpt from a basic content page:

Old fashioned content page

That’s quite a handful of mark-up that doesn’t mean much to me.  Compare it to this mark-up from the equivalent Razor view:

Code excerpt of Razor view using layouts.

I’m sure you already appreciate the brevity!  Notice how nearly every character in the latter example actually means something to me, not just the compiler.

That is all for now, that is, I haven’t really explored MVC3 and Razor any further yet, after spending yesterday afternoon converting views in an example project from traditional syntax to Razor.  Tonight I will explore using some JavaScript and MVC3 AJAX capabilities for a pop-up editor dialogue.  I can hardly wait to share those experiences as well, so please stay tuned.