NUnit Hangs Up When Run Through Nant Using .Net 4.0

Ran into this one yesterday starting with Cruise Control not finishing. At first I just thought Cruise Control just wasn’t that into it, but turns out something was hanging up and that something was N-N-N-UNIT. Well to be more specific it was NUnit while being run through Nant although in the end it wasn’t Nant’s fault. Turns out it has to do the latest stable release of NUnit… 2.5.8.something.whatever.

The fix? Grab 2.5.9.yayayaya from the download page and use the nunit-console from that instead. I guess the whole issue had to do with the latest .Net 4.0 and the latest stable version of NUint. I guess they don’t like each other. They go together like water and something that doesn’t go well with water.

ASP.Net MVC Issue: Form With Get Method Not Passing Request Values

DISCLAIMER: This has a solution but there has to be a better way.

So I came across a really odd situation with the MVC framework today, and I’m on the edge of some serious Nerd Rage. Here’s the issue:

I have a route that looks like this:

  "{controller}/{action}/{roomId}/{name}"

And a form that looks like this:

  <form action="Room/Index/6/SomeThing?pageNumber=1&amountToShow=5" method="get">
   <button type="submit">SomeButton</button>
  </form>

Can’t get much simpler… or is it more simple? Whatever. Point is, when the the button is clicked, it should go to that page like the form action says to. And it does, sort of. For some reason it ends up stripping the values from the pageNumber and amoutToShow request variables. How do I know this? Well break points at certain times show me that the current ActionExecutingContext ActionParameters (the thing that stores all the request parameters) has the two I need but neither has a value. And since they are not included in that route description, it must see them in the url.

You might think it has to do with forms and submitting, and it might except here’s the kicker… with a route like this:

   "{controller}/{action}/{roomId}/{name}/{pageNumber}/{amountToShow}"

All of a sudden it can see the values. Mind you the url ends up like:

  Room/Index/1/Something/1/5

Which you would expect from the route definition. To add to the fun, if I add hidden values:

  <form action="Room/Index/6/SomeThing?pageNumber=1&amountToShow=5" method="get">
    <input type="hidden" name="pageNumber" value="1" />
    <input type="hidden" name="amountToShow" value="5" />
    <button type="submit">SomeButton</button>
  </form>

It works with the original route. Doesn’t really make sense to me, but my understanding of the system isn’t exactly expert level. However, I could buy this if the hidden field method worked and the extended route definition didn’t.

For now I can use the hidden input method since there’s no issue with showing the parameters. Just not what I’d call “Best solution” types stuff.

Sigh. MVC : One step forward, two steps back.

Entity Framework: LINQ to Entities only supports casting Entity Data Model primitive types

So in typical tool fashion I posted this little gem without realizing a glaring error… the order by clause. The whole idea is to create a method that can get a collection, sort it, then grab a certain number for paging. The issue was this:

    Expression<Func<K, IComparable>> orderBy

The problem comes in when the entire expression is run, meaning when Entity Frame work takes:

    context.Select(selectMethod).Where(whereClause).OrderBy(orderBy).ToList();

and creates SQL out of it. Entity Framework doesn’t really know how to handle IComparable as it has not primitive/sql type to match to it. Why it can’t see the underlying type of say DateTime, no idea, but this is life.

So this should be an easy fix, right? Eh… yeah. First I thought instead of IComparable I could just convert to some kind of primitive type so that the EF could be on it’s merry. Not so much. Turns out this probably isn’t possible.

Well thanks to a push from Ben M at The O Flow I got to thinking about how to attack this. Instead of sending in an expression for the order by, why not send in a method that would take in a query and tell it how to order itself. Sounds hard right? (If not then you’re obviously too cool for this school) Well it’s not, just a different way to think about it.

Right off the bat, the change to the method signature would look like this:

Old order by parameter signature:

    Expression<Func<K, IComparable>> orderBy

New order by parameter signature:

    Func<IQueryable<T>, IOrderedQueryable<T>> orderBy

So what does that mean? It means that I am going to supply the method with a method that will take in a query and return an ordered query… well not ordered yet per se but the blueprint on how to order when that time comes around. Now here’s how that’s used:

First you need the query:

    var initialQuery = query
    .Where
    (
        somethingEqualsSomething
    );

Then you apply the orderby method, and in the case of the original paging method, the paging too:

    var orderedQuery = orderBy(initialQuery);

    returnValue = orderedQuery
      .Skip(numberToShow * realPage)
      .Take(numberToShow)
      .ToList();

So overall, doesn’t look too much different. Just instead of supplying the OrderBy method with a Func, you give a method that creates an ordered query.

How would you use this? Remember the signature was (whereClause, selectClause, orderBy, pageNumber, numberToShow, realPage, totalCountOfPages)

    Tools.GetListForGrid
    (
      tool => tool.EntityId == userId,
      tool => new { Name = tool.Name },  //Select Clause, I'll get to that next
      toolOuter => toolOuter.OrderBy(toolInner => toolInner .Name),  //OrderBy
      ...
    )

Two things you might notice. One would be the OrderBy signature:

   toolOuter => toolOuter.OrderBy(toolInner => toolInner .Name),

What the hell? Remember the method you are sending takes in a query and returns an ordered query. toolOuter is your query, toolOuter.OrderBy(toolInner => toolInner .Name) is your blueprint (IOrderedQueryable) on how it should be queried.

Second thing is that when I showed how to use the OrderBy method above:

    var orderedQuery = orderBy(initialQuery);

    returnValue = orderedQuery
      .Skip(numberToShow * realPage)
      .Take(numberToShow)
      .ToList();

I didn’t include the select clause. Partially because I didn’t want to complicate it yet, partially because it has it’s own issue. If you’re like me, you use the select clause a lot. Why? Because it limits the amount of information you take from the database. Say if you are trying to fill a drop down list, why select an entire Tool object (Which could have a ton of mapped properties) when all you need is Id and Name? Seems silly. That’s where the Select clause comes in. Now the issue is where to put the order by. You would think after the select clause, since you want to sort on only what you are selecting. Problem is, with paging that gets screwed up. The way sql server “pages” is that it selects twice.

Select all the things that match this where clause.
Select a certain number of items from that starting at X.

The first select creates a dataset with row numbers, and the second one selects the items based on those row numbers. IE take 5 starting at row 5. Now the way the EF handles the order by is to grab the info you need from the Select (Ordered by something… you don’t get to choose) and THEN order and grab. As you can guess this may not give the needed results. So how can this be solved? Order before the select as witnessed in the new and improved method:

public static IList<K> GetListForGrid<T, K>
(
    this ObjectQuery<T> query,
    Expression<Func<T, Boolean>> somethingEqualsSomething,
    Expression<Func<T, K>> selectClause,
    Func<IQueryable<T>, IOrderedQueryable<T>> orderBy,
    Int32 pageNumber,
    Int32 numberToShow,
    out Int32 realPage,
    out Int32 totalCountOfPages
)
{
    IList<K> returnValue;

    Int32 totalItemCount =
        query
        .Count
        (
          somethingEqualsSomething
        );

    totalCountOfPages = Methods.TotalCountOfPages(totalItemCount, numberToShow);
    realPage = Methods.GetRealPage(totalCountOfPages, pageNumber);

    var initialQuery =
      query
      .Where
      (
        somethingEqualsSomething
      );

   var orderedQuery = orderBy(initialQuery);

    returnValue = orderedQuery
      .Select
      (
        selectClause
      )
      .Skip(numberToShow * realPage)
      .Take(numberToShow)
      .ToList();

      return returnValue;
}

And usage:

    Tools.GetListForGrid
    (
       tool => tool.Id == userId,
       tool => new { Name = tool.Name },  //Select Clause
       toolOuter => toolOuter.OrderBy(toolInner => toolInner .Name),  //OrderBy
       pageNumber,
       amountToShow,
       out realPage,
       out totalCountOfPages
    );

Now this one actually works with Entity Framework and not just Linq to objects like the last one.

A relationship is being added or deleted from an AssociationSet … With cardinality constraints, a corresponding … must also be added or deleted.

So I ran into this error yesterday trying to delete a user which in turn has multiple collections that would be deleted too. You would think that I would have to manually delete the entire User tree, on collection at a time. Well the way thing work is that Entity framework will do the work for you if your tables are set to Cascade Delete. Now, you might see that error and be confused as to why it crops up even when you do have Cascade Delete on the needed tables. Here’s the situation:

As I said, I was trying to delete a user through the entity framework but noticed that all the addresses the user had were still in the database after deletion. Whoops. I dun forgot to set Cascade Delete on the tables. No big deal. So after I fixed the tables, I went to update the edmx file… ie update from database… and I thought all was well. Yeah not so much. I started to get this error. So the next thing I did was open the .edmx file in notepad and looked for “delete”. Sure enough I found it.

        <Association Name="FK_UserAddress_User">
          <End Role="ChatUser" Type="BAT.Data.Store.User" Multiplicity="1"">
            <OnDelete Action="Cascade" /">
          </End">

Eh ok… it’s there. Well after some searching I ran into this post. Basically what was happening is although that shows the OnDelete Action=”Cascade”, it’s still not everywhere it needs to be. Then it dawned on me that the way the .edmx file works is that pretty much everything has to be doubled in the file, once for the database and once for the actual class. What was missing was the class half. For some reason when adding Cascade to a foreign key and then updating the .edmx file, only the table part of the markup gets updated. Bummer. So, what to do? Kind the foreign key name in the file (FK_UserAddress_User for example) and do a search on it. You’ll find something like this:

     <Association Name="FK_UserAddress_User">
           <End Type="BAT.Data.ChatUser" Role="User" Multiplicity="1" />

Oooo right there is the problem. You see, if this were correctly done, it would have the action=”delete” added to it, just like the one in the SSDL area. So how do you fix this? Manually. Hooray.

     <Association Name="FK_UserAddress_User">
           <End Type="BAT.Data.ChatUser" Role="User" Multiplicity="1" >  //RIGHT HERE
             <OnDelete Action="Cascade"></OnDelete>  //RIGHT HERE
           </End>  //RIGHT HERE
     <End Type="BAT.Data.UserAddress" Role="UserAddress" Multiplicity="*" /></Association>

As you can see, it’s a simple change and you only have to do it to the object of Multiplicity=”1″, which of makes sense you wouldn’t want a user deleted if an address is. But it’s still annoying and a real pain if you have more than say one to fix.

My jQuery Primer

So you have been reading about jQuery and want to dive in and try some? I recently attended the MSDN Dev Conference in Detroit where jQuery integration and client-side programming were very hot topics. With Microsoft’s acceptance of the open source library, I figured I would give it a try. This is what I have learned so far. Before I can show you what you can do with jQuery, I think I should probably show you how to get a reference to jQuery into your code. In ASP.NET you can add your reference directly to your Script Manager

<asp:scriptmanager id="pageScriptManager" runat="server">
<scripts>
<asp:scriptreference path="/client/jquery-1.3.1.min.js" />
</scripts>
</asp:scriptmanager>

What does jQuery have to offer? First and foremost, jQuery has given me power over the Document Object Model (DOM)! jQuery Selectors are the greatest thing since sliced bread, no lie. Being able to EASILY find an object or group of objects in the DOM by ID, CSS Class, or by HTML Tag is something web developers have long needed. To select an object from the DOM by ID would look like this:

$('#ID_Goes_Here')

To select an object from the DOM by CSS Class would look like this:

$('.CSS_Class_Name_Goes_Here')

To select an object from the DOM by HTML Tag would look like this:

$('<tag_goes_here>')

With jQuery Selectors being so simple, it allows the developer to easily select an object or a group of objects. Now that we can select objects, what can we do with them? This is where the power of Selectors really builds into what else you can do. In a web application, round trips to the server to manage UI is wasteful. I avoid JavaScript like the plague because it’s a pain in the ass. jQuery makes client-side UI management feel like climbing the rope in gym class. For example, if I have a label that I want to be rendered but not visible I could create the label.

<asp:label id="Label4" runat="server" cssclass="myLabel" text="This is " />

And later on in jQuery I can hide it like this.

$('#Label4').css('display', 'none');

It’s nice to be able to easily select an object and modify it, but what if you have a whole group of items you want to modify? With jQuery, you can EASILY loop through a collection of objects. In this example I have a group of labels.

<asp:label id="Label1" runat="server" cssclass="myLabel" text="This is " />
<asp:label id="Label2" runat="server" cssclass="myLabel" text="This is " />
<asp:label id="Label3" runat="server" cssclass="myLabel" text="This is " />
<asp:label id="Label4" runat="server" cssclass="myLabel" text="This is " />

Now I want to update the text of each label to include its ID. I am going to loop through each object in the DOM with a CSS Class of .myLabel.

$('.myLabel').each(function() { $(this).append(this.id); });

What the jQuery code above does is execute a function that will append the object’s ID to its text value. Notice the Selector inside the function $(this). The syntax is used to find the loop’s current object in the DOM. I do a lot of web work where I create controls on the fly. For my last example, I just wanted to show a way to quickly insert some HTML into a container object. I will start with a Panel AKA a DIV.

<asp:panel id="Panel1" runat="server" />

Now I am going to use jQuery to select my DIV and add some HTML to it.

$("#Panel1").html("<ul><li>Item One</li><li>Item 2</li></ul>");

Now I have shown you some snippets here and there, let me show you what my page actually looks like.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
	<title>jQuery Examples</title>
	<link href="/style/jQuery.css" rel="Stylesheet" type="text/css" />

	<script type="text/javascript">  function pageLoad() { $('.myLabel').each(function() { $(this).append(this.id); }); $('.myLabel').css('color', '#FFFFFF').css('font-size', '30px'); $('#Label4').css('display', 'none'); $("#Panel1").html("<ul><li>Item One</li><li>Item 2</li></ul>"); } </script>

</head>
<body>
	<form id=	<form id="pageForm" runat="server">
	<asp:scriptmanager id="pageScriptManager" runat="server">  <scripts>  <asp:scriptreference path="/client/jquery-1.3.1.min.js" />  </scripts>  </asp:scriptmanager>
	<asp:label id="Label1" runat="server" cssclass="myLabel" text="This is " />
	<br />
	<asp:label id="Label2" runat="server" cssclass="myLabel" text="This is " />
	<br />
	<asp:label id="Label3" runat="server" cssclass="myLabel" text="This is " />
	<br />
	<asp:label id="Label4" runat="server" cssclass="myLabel" text="This is " />
	<br />
	<asp:panel id="Panel1" runat="server" />
	<br />
	</form>
</body>
</html>

Links
jQuery: http://www.jQuery.com/
Object Model: http://en.wikipedhttp://en.wikipedia.org/wiki/Document_Object_Model

Change Target Framework on a Class Library (Visual Studios 2008)

Ok so this is a quick one but annoys the hell of of me.

Basically I am working with a 2.0 class library project and I wanted to use Linq. Now you would think when you “upgrade” the project to 3.5 using the wizard, the target framework would follow. Well, you are stupid. Now for web projects it seems you can look at the properties -> build and boom you can see it bright as day. Try doing this with a class library you and got nothin’.

Here’s the solution:

Goto the project properties -> compile -> Advanced Compile Options AND YOU WILL BE VICTORY!!11

So easy even a child could do it… after an hour of searching on google…

Cannot Resolve Method, Can’t Infer Return Type, and Funcs

So ran into this today and the answer was actually a lot easier to understand than I thought it would be.

Say you want to order a list of objects by a number. Seems simple. Now if you have been paying attention you would know I like using Funcs.

  Func<SomeClass, Int32> orderByNumber =
    currentClass =>  currentClass.SomeNumber;

  anotherCollection = someCollection.OrderBy(orderByNumber);

Seems simple, but what if you wanted to use a method already defined in the class?

  private Int32 ReturnNumber(SomeClass currentClass)
  {
    return currentClass.SomeNumber;
  }

It seems like this could be the way to go, right?

  someCollection.OrderBy(ReturnNumber);

Compile and BOOOOOOM you get an error. It says it can’t infer the return type of the method. Wait what? It’s pretty obvious right, it’s an integer. It had no problem inferring from the Func and you have to figure that the method itself is “typed” also. Well here’s the problem (And you’re dumb for not knowing this, but I’m not because I’m immune to dumb), ReturnNumber isn’t a method, it’s part of a method group. You can have a million (well maybe not that many) methods named ReturnNumber, all with different parameters. Why is this a problem? Well let’s use lambda expressions:

  someCollection.OrderBy(currentClass =>  currentClass.SomeNumber);

At this point it knows two things: currentClass is a SomeClass and there is a Method that takes in a SomeClass and returns something. So with that in mind, it looks for such a method and finds the return type. This is no different with the Func since the Func is basically unique due to it being a named field. After all you can’t have two fields named orderByNumber, but you can have many methods named ReturnNumber. That is where the problem is. When you use the second example:

  someCollection.OrderBy(ReturnNumber);

It can infer the SomeClass from the list and it sees the method. For there it has to find the method’s return type. Wait, which method? If i Have 10 overloads, each with different return types, how does it know what type to use? Well the answers is, it doesn’t. So basically you’re screwed. Sucks, huh?

Side note: This works

  Func<SomeClass, Int32> orderByNumber = ReturnNumber;

Like versus Contains in Linq

So have to figure this one out. Say you have:

private static Expression<Func<User, Boolean>> WhereLikeFirstNameLastNameUserName(String name)
{
  return currentUser => SqlMethods.Like(currentUser.UserName, "%" + name + "%")
  || SqlMethods.Like(currentUser.FirstName, "%" + name + "%")
  || SqlMethods.Like(currentUser.LastName, "%" + name + "%");
}

And

private static Expression <Func<User, Boolean>> WhereLikeFirstNameLastNameUserNameWithoutLike(String name)
{
  return currentUser => currentUser.UserName.Contains(name)
  || currentUser.FirstName.Contains(name)
  || currentUser.LastName.Contains(name);
}

The first one should look familiar, its part of the “dynamic” linq stuff I’ve been posting. Now guess which one gives me this SQL when profiled:

exec sp_executesql N
'SELECT
 [t0].[UserID],
 [t0].[FirstName],
 [t0].[LastName],
 [t0].[Password],
 [t0].[UserName],
 [t0].[UserTypeID]
FROM
 [dbo].[User] AS [t0]
WHERE
 ([t0].[UserName] LIKE @p0)
OR
 ([t0].[FirstName] LIKE @p1)
OR
 ([t0].[LastName] LIKE @p2)
ORDER BY
 [t0].[UserName]',

N'@p0 varchar(3),
 @p1 nvarchar(3),
 @p2 nvarchar(3)',
 @p0='%s%',
 @p1=N'%s%',
 @p2=N'%s%'

If you answered both, you are correct or you looked ahead for the answer and therefore are a tool. Now which do you think that…

query.ToList()

Produces the correct list? If you answered Contains, then you are correct again. If you are a tool, you probably looked ahead again…

Why is this? I HAVE NO IDEA… Something I have to look into for sure.