Archive for December, 2009

Refactor rename on LINQ to SQL Classes 2

This is a quick, dirty work around to renaming the properties of the LINQ to SQL classes. Say you have a simple DBML class you want to rename.

image

Simple enough right? Just click in there and edit the WidgetName to Name right? Wrong! You have code like this.

public Widget CreateNewWidget(string name, string description)
{
    return new Widget {
        WidgetDescription = description,
        WidgetName = name
    };
}

You’re going to abandon all those calls to WidgetName and do a search and replace refactor. That sucks. So rename it to WidgetName2 for now and let all the references break.

image

That breaks our code.

image

Fine for now. Create a partial class for the Widget.cs and add our WidgetName back in

public partial class Widget
{
    public string WidgetName { get; set; }
}

Use ReSharper to rename that property to name.

image

Then delete the partial class, or property and rename the property in the DBML to Name.

Done.

Keeping an Eye on Stack Overflow Questions – Taking advantage of RSS 0

It’s probably hard to find a programmer whom hasn’t asked, answered or read a question on Stack Overflow these days. It’s becoming, if not already, the wealthiest pool of talented developers and all those brains are just seething for a challenge. Your problem is another man’s puzzler.

So you’ve asked your question, and now spend every other minute returning to the website to see if anyone has saved your day, or ridiculed your ignorance. Well, there’s an easier way may friends. Even easier than e-mail notifications.

RSS feeds.

it might be easily over looked, but in the bottom of every question there is an RSS feed for that individual question.

image

In fact, there are a couple feeds provided by SO, but for me, today, this one is Queen Bee. Well, this feed and the new Google Reader extension to Google Chrome. Once I get this feed into my Google Reader, all I need to do is wait…

image

…and wait….and stare…and wait….and stare…and wait for the feed icon to update.

image

Sweet. Someone solved my problem. …Nope, just a comment telling me I’m an idiot, but hopefully my rephrased question makes enough sense to get a valid answer.

Feeds make it easy to subscribe to specific information you wish to monitor and lets you do so in a central, e-mail free way. So subscribe until your hearts content, but don’t forget to drop the old questions you no longer care about.

Asp.net MVC 2.0 Data Annotations Validation doesn’t emit correct JSON 1

Apparently I’m not the only one to have this sneaky little problem that has been driving me mad. Given the simple model:

public class Foo {
    [Required] public string Bar {get;set;}
}

And a simple view:

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master"
Inherits="System.Web.Mvc.ViewPage<Foo>" %>
<%@ Import Namespace="MvcApplication2.Models"%>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
	Index
</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

<script src="/Scripts/jquery-1.3.2.js" type="text/javascript"></script>
<script src="/Scripts/jquery.validate.js" type="text/javascript"></script>
<script src="/Scripts/MicrosoftMvcJQueryValidation.js" type="text/javascript"></script>

 <h2>Index</h2>
 <%= Html.ValidationSummary() %>
 <% Html.EnableClientValidation(); %>
 <%
  using (Html.BeginForm())
  {
    ViewContext.FormContext.ClientValidationFunction = "EnableClientValidation"; %>
    <%= Html.LabelFor(x=>x.Bar) %>
    <%= Html.TextBoxFor(x=>x.Bar) %>
    <input type="submit" />
<%  } %>
</asp:Content>

You would expect the form to emit the JSON needed to pass to the jQuery validator right? WRONG! It just outputs the following

<script type="text/javascript">
//<![CDATA[
EnableClientValidation({"Fields":[],"FormId":"form0"}, null);
//]]>
</script>

That’s no help; however, when you give it the <%= Html.ValidationMessageFor(x=>x.Bar) %> you start to see what you expect.

You sneaky deferred execution! 0

As I’ve mentioned we have a series of Extension methods that help with some trivial, but isolated tasks. Here is an example.

public static IEnumerable<SelectListItem> CreatePaymentTypeDropDownListItems(
                                          this IQueryable<PaymentType> @this)
{
    return  @this
            .OrderBy(x => x.Description)
            .Select(x => new SelectListItem
                             {
                                 Value = x.Code,
                                 Text = x.Description,
                             })
            .MarkAsSelected(x=>x.Text == CreditCard);
}

Simple enough right? The MarkAsSelected is another extension method we have to help out. It’s not all that exciting, but here it is.

public static IEnumerable
 MarkAsSelected(this IEnumerable
 @this, Func
 where)
{
    var items = @this.Where(where);
    foreach (var item in items)
    {
        item.Selected = true;
    }
    return @this;

}

Simple enough right? But the credit card payment type was never getting defaulted with the select value. We have unit tests around MarkAsSelected and it works! What’s the problem? Let’s try something really quick.

public static IEnumerable<SelectListItem> CreatePaymentTypeDropDownListItems(
                                          this IQueryable<PaymentType> @this)
{
    return  @this
            .OrderBy(x => x.Description)
            .Select(x => new SelectListItem
                             {
                                 Value = x.Code,
                                 Text = x.Description,
                             })
            .ToArray()
            .MarkAsSelected(x=>x.Text == CreditCard);
}

That works! What’s up? Oh you sneaky deferred execution. I bet it’s you! I’m not an expert, but here is my best guess. When the MarkAsSelected does its foreach, it asks the @this to create an enumerator. It does, but since it is from an IQueryable<T>, it now executes all that deferred execution in the Select and OrderBy. Fair enough. The enumerator spits out all the SelectListItems we want/need.

We pass on the enumerable incase we want to do something after it, and actually we do. Down the road we want to enumerate again. The Select and OrderBy kick in again and we get all brand new SelectListItems.

Throwing that ToArray in there gets us out of operating on the IQueryable<T>, does the Select and OrderBy and lets us operate on a straight list. Makes sense, but not obviously apparent…at least to me.

But you know what? After all that, I think I just prefer this.

public static IEnumerable<SelectListItem> CreatePaymentTypeDropDownListItems(
                                          this IQueryable<PaymentType> @this)
{
    return  @this
            .OrderBy(x => x.Description)
            .Select(x => new SelectListItem
                             {
                                 Value = x.Code,
                                 Text = x.Description,
                                 Selected = (x.Description == CreditCard)
                             });
}

No need to overcomplicate the problem right?