Saturday, June 30, 2012

.Skip() and .Take() in C#'s LINQ seem made for paginated lists.

Johnny, Sid, Paul, and Steve were the names of the four guys ... on Twitpic

The test below (which passes and was inspired by page 374 of C# 4.0 in a Nutshell) shows first how a query brings back four contacts and then how a second query brings back the two contacts in the middle of the four by skipping the first record and taking the next two. A tiny record set like this is hardly worthy of pagination, but I'm sure that you can see how IQueryable and LINQ may work well with paginated lists by utilizing Skip and Take.

using System.Collections.Generic;
using System.Data.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Whatever.Models;
using System.Linq;
namespace Whatever.Tests
{
   [TestClass]
   public class IQueryableTest
   {
      [TestMethod]
      public void DataTest()
      {
         string Ok = @"server=.\sqlexpress;database=OK;Integrated Security=true;";
         DataContext dataContext = new DataContext(Ok);
         Table<Contact> contacts = dataContext.GetTable<Contact>();
         IQueryable<Contact> query = contacts.OrderBy(c => c.City);
         List<Contact> list = query.ToList();
         Assert.AreEqual(list.Count(), 4);
         Assert.AreEqual(list[0].Name, "Johnny");
         Assert.AreEqual(list[1].Name, "Sid");
         Assert.AreEqual(list[2].Name, "Paul");
         Assert.AreEqual(list[3].Name, "Steve");
         query = contacts.OrderBy(c => c.City).Skip(1).Take(2);
         list = query.ToList();
         Assert.AreEqual(list.Count(), 2);
         Assert.AreEqual(list[0].Name, "Sid");
         Assert.AreEqual(list[1].Name, "Paul");
      }
   }
}

append to the html inside of a div with jQuery

$('#Tweets').items.join(''));...is part o... on Twitpic

 
 

Addendum 6/5/2014: $('#MyDiv').append('my copy'); ...is an example of appending. I sure was lazy when I made this post.

Friday, June 29, 2012

IIS7 notes

  1. In the application pools in IIS7:
    1. Managed Pipeline Mode
      1. Classic Mode emulates IIS6
      2. Integrated Security is new and can, among other things, block random .html or .txt or .jpg files from being seen if a user is not permissioned.
    2. Identity (can define what user one connects to a database as)
  2. http://blog.dczweb.net/post/Migration-of-ASPNET-app-from-IIS6-to-IIS7-(75).aspx touches on upgrading ASP.NET apps from those which run on IIS6 to those which run on IIS7:
    1. system.web will be in Web.config in IIS6
    2. system.webServer will be in Web.config in IIS7

Paul Hammant's Next Generation UI technologies presentation!

See http://www.youtube.com/watch?v=Qo0XCz-neNs&feature=youtu.be

get the Mongo .dll

Install-Package mongocsharpdriver installs the Mongo .dll for ASP.NET via NuGet.

Right-click on the desktop in Windows 7 and type the first letter of the file you want to find.

Type the letter over and over again. The selected file will tab from file to file where each file starts with the applicable letter. You'll find what you are looking for soon!

One may view the HTML source of emails in Microsoft Outlook 2010.

This feature which used to exist in Outlook Express while being left out of Outlook itself, has been incorporated!

  1. Open an email and pick "Actions" from the "Message" tab.
  2. Pick "Other Actions" from the "Actions" menu.
  3. Pick "View Source" from the "Other Actions" menu.

scriptResourceHandler AppPool problem

<section name="scriptResourceHandler" type="System.Web.Configuration.ScriptingScriptResourceHandlerSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/>

...is causing me some heartache as defined here.

I can't speak my mind and I have fake teammates.

This has nothing to do with my current job, but, while I'm thinking about it, two staples of bad work environments I've seen that frustrate me:

  1. I cannot point out a problem. When I point out of a problem higher-ups are frustrated and just wish I would shut up. I should be thanked for pointing out a problem dammit. At the worst a higher-up could just tell me: "Yes, we are aware of that. Here is why we need to just live with the problem..." The absence of this sort of response, the opposite in which one tries to be helpful and they are met with defensive, reactionary anger suggests that precarious relationships and processes are being held together with duct tape. If your boss has a working Rube Goldberg machine that is making a profit, that accomplishment really isn't that admirable in my opinion. A functional mess is still a mess.
  2. I have fake teammates. At some point someone lets me know indirectly, never directly, that so-and-so is not performing and thus not to be taken seriously as a teammate. For some reason this person isn't being let go. They will be present for some time, but I should not take them seriously or waste too much time showing them how to do things or helping them grow. When the person in question earnestly wants to learn, grow, and do well, this is unbelievably frustrating. I find myself more keen to give respect to struggling developers than those who do not give them respect.

Bottom line: If you are someone who is just hiding in middle management, pushing bad policy in the name of just feeding your family, I hate you.

HttpContext.Current.User is ending up null

Consider a Windows authentication gremlin. I have tried to upgrade an old application which uses HttpContext.Current.User to use C# 4.0 and Visual Studio 2010 and have thus requested an application pool that will support C# 4.0 in ISS and a side effect seems to be that HttpContext.Current.User is ending up null. This doesn't happen when I run locally in Cassini. It happens at IIS. Some links on this phenomenon are:

Thursday, June 28, 2012

ipconfig/flushdns

...is a command you may run at a command prompt in Windows to get rid of your DNS cache!

Wednesday, June 27, 2012

expressions in C#

What follows is a rewrite of this code using Johnny, Sid, Steve, and Paul as defined here.

using System;
using System.Collections.Generic;
using System.Data.Linq;
using System.Linq.Expressions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Whatever.Models;
using System.Linq;
namespace Whatever.Tests
{
   [TestClass]
   public class IQueryableTest
   {
      [TestMethod]
      public void DataTest()
      {
         Expression<Func<Contact, bool>> expression = c =>
               c.Email.EndsWith("example.com");
         string Ok = @"server=.\sqlexpress;database=OK;Integrated Security=true;";
         DataContext dataContext = new DataContext(Ok);
         Table<Contact> contacts = dataContext.GetTable<Contact>();
         
         IEnumerable<Contact> unfilteredIEnumerableFromIQueryable = contacts.OrderBy(c
               => c.Name);
         Assert.AreEqual(unfilteredIEnumerableFromIQueryable.Count(),4);
         Assert.AreEqual(unfilteredIEnumerableFromIQueryable.ElementAt(0).Name,
               "Johnny");
         Assert.AreEqual(unfilteredIEnumerableFromIQueryable.ElementAt(1).Name,
               "Paul");
         Assert.AreEqual(unfilteredIEnumerableFromIQueryable.ElementAt(2).Name, "Sid");
         Assert.AreEqual(unfilteredIEnumerableFromIQueryable.ElementAt(3).Name,
               "Steve");
         
         IEnumerable<Contact> filteredIEnumerableFromIQueryable =
               contacts.Where(expression).OrderBy(c => c.Name);
         Assert.AreEqual(filteredIEnumerableFromIQueryable.Count(), 3);
         Assert.AreEqual(filteredIEnumerableFromIQueryable.ElementAt(0).Name,
               "Johnny");
         Assert.AreEqual(filteredIEnumerableFromIQueryable.ElementAt(1).Name, "Paul");
         Assert.AreEqual(filteredIEnumerableFromIQueryable.ElementAt(2).Name, "Steve");
         
         IEnumerable<Contact> filteredIEnumerableFromIEnumerable =
               unfilteredIEnumerableFromIQueryable.Where(expression.Compile()).OrderBy(c
               => c.Name);
         Assert.AreEqual(filteredIEnumerableFromIEnumerable.Count(), 3);
         Assert.AreEqual(filteredIEnumerableFromIEnumerable.ElementAt(0).Name,
               "Johnny");
         Assert.AreEqual(filteredIEnumerableFromIEnumerable.ElementAt(1).Name, "Paul");
         Assert.AreEqual(filteredIEnumerableFromIEnumerable.ElementAt(2).Name,
               "Steve");
      }
   }
}

 
 

An Expression type is an expression tree wrapping a predicate (a Func returning a bool) and may be used as a predicate in an IQueryable where clause as shown above! An expression tree can become SQL where a predicate itself cannot. .Compile() will dumb an expression tree down to be just a predicate so that it may be used against an IEnumerable!

select both SUM and COUNT (it's not that hard)

SELECT OurWord,
SUM(OurNumber) AS OurSum,
COUNT(OurNumber) As OurCount
FROM OurTable
Group By OurWord

Cross Join Queries and Non-equi Join Queries

using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace LinqStuff.Tests
{
   [TestClass]
   public class LinqTests
   {
      public LinqTests()
      {
      }
      
      [TestMethod]
      public void CrossJoinTest()
      {
         int[] numbers = {1, 2, 3, 4};
         string[] letters = {"a", "b", "c"};
         IEnumerable<string> query = from x in numbers
                              from y in letters
                              select x.ToString() + y;
         Assert.AreEqual(query.Count(), 12);
         Assert.AreEqual(query.ElementAt(0), "1a");
         Assert.AreEqual(query.ElementAt(1), "1b");
         Assert.AreEqual(query.ElementAt(2), "1c");
         Assert.AreEqual(query.ElementAt(3), "2a");
         Assert.AreEqual(query.ElementAt(4), "2b");
         Assert.AreEqual(query.ElementAt(5), "2c");
         Assert.AreEqual(query.ElementAt(6), "3a");
         Assert.AreEqual(query.ElementAt(7), "3b");
         Assert.AreEqual(query.ElementAt(8), "3c");
         Assert.AreEqual(query.ElementAt(9), "4a");
         Assert.AreEqual(query.ElementAt(10), "4b");
         Assert.AreEqual(query.ElementAt(11), "4c");
      }
      
      [TestMethod]
      public void NonEquiJoinTest()
      {
         string[] names = { "Tom", "Dick", "Harry" };
         IEnumerable<string> query = from x in names
                              from y in names
                              where x.CompareTo(y) < 0
                              select x + " vs " + y;
         Assert.AreEqual(query.Count(), 3);
         Assert.AreEqual(query.ElementAt(0), "Dick vs Tom");
         Assert.AreEqual(query.ElementAt(1), "Dick vs Harry");
         Assert.AreEqual(query.ElementAt(2), "Harry vs Tom");
      }
   }
}

 
 

The first query is a Cross Join. It returns one record for every possible combination across two flat collections, finding the same possibilities one might find in making a grid of results:

  a b c
1 1a 1b 1c
2 2a 2b 2c
3 3a 3b 3c
4 4a 4b 4c

...while returning a flat collection:

1a 1b 1c 2a 2b 2c 3a 3b 3c 4a 4b 4c

The second query is a Non-equi Join. If not for where x.CompareTo(y) < 0 it would do the same thing as a Cross Join. The where clause keeps an item from being matched to itself and ending up in a variation of an existing match. Pretty cool. This comes from page 384 of C# 4.0 in a Nutshell.

Tuesday, June 26, 2012

The Lambda Operator

=>

COUNT in SQL

Taking a row count is really not unlike taking a sum or average in SQL.

SELECT COUNT(*) as mycount From userbase
Group By firstname

Html.RenderPartial in Razor

This example will show a Partial View. It uses two C# objects. This is one:

using System.Collections.Generic;
namespace RenderPartialExample.Core
{
   public class Customer
   {
      public string FirstName { get; set; }
      public string LastName { get; set; }
      public string PhoneNumber { get; set; }
      public string EmailAddress { get; set; }
      public List<Address> Addresses { get; set; }
   }
}

 
 

This is the other object:

using System;
namespace RenderPartialExample.Core
{
   public class Address
   {
      public Guid Id { get; set; }
      public string Street { get; set; }
      public string Suite { get; set; }
      public string City { get; set; }
      public string State { get; set; }
      public string ZipCode { get; set; }
      public bool IsBilling { get; set; }
   }
}

 
 

This is my view which repeats a partial in a foreach loop:

@using RenderPartialExample.Core
@model RenderPartialExample.Core.Customer
@{
   ViewBag.Title = "Update";
}
<h2>Update @Model.FirstName @Model.LastName</h2>
@using (Html.BeginForm("Index", "Customer"))
{
   <div>@Html.LabelFor(m => m.FirstName) @Html.TextBoxFor(m => m.FirstName)
         </div>
   <div>@Html.LabelFor(m => m.LastName) @Html.TextBoxFor(m => m.LastName)</div>
   <div>@Html.LabelFor(m => m.PhoneNumber) @Html.TextBoxFor(m =>
         m.PhoneNumber)</div>
   <div>@Html.LabelFor(m => m.EmailAddress) @Html.TextBoxFor(m =>
         m.EmailAddress)</div>
   <table style="border: 2px solid #000000;">
      <tr><th>delete</th><th>primary</th><th></th></tr>
      @foreach(Address address in @Model.Addresses)
      {
         Html.RenderPartial("Address", new Tuple<bool, bool, Address>(false,
               address.IsBilling, address));
      }
   </table>
   <input type="submit" value="submit" />
}

 
 

This is my partial:

@model Tuple<bool,bool,RenderPartialExample.Core.Address>
<tr>
   <td>@Html.CheckBoxFor(m => m.Item1)</td>
   <td><input type="radio" name="primary" value="@Model.Item3.Id" @{
                                          if (Model.Item2)
                                          {
                                             <text>checked</text>
                                          }
                                       }/></td>
   <td nowrap>
      @Model.Item3.Street<br />
      @Model.Item3.Suite<br />
      @Model.Item3.City<br />
      @Model.Item3.State<br />
      @Model.Item3.ZipCode<br />
      @Html.ActionLink("edit me", "Update", "Address", new { Id = Model.Item3.Id }, null)
   </td>
</tr>

 
 

The end result looks like:

some MVC tinkering on Twitpic

Upcast to an Interface!

Imagine we have two animals, a dog and a parrot:

  1. namespace MyApp.Core
    {
       public class Dog : Animal
       {
          public string Speak()
          {
             return "Woof!";
          }
       }
    }
     
  2. namespace MyApp.Core
    {
       public class Parrot : Animal
       {
          public string Speak()
          {
             return "Polly wants a cracker.";
          }
          
          public string Squawk()
          {
             return "QuaWk!";
          }
       }
    }

 
 

Their types both inherit from an interface called Animal:

namespace MyApp.Core
{
   public interface Animal
   {
      string Speak();
   }
}

 
 

Alright, we may now hand instantiations of Dog and Parrot into a method signature that consumes an Animal. The methods defined at Animal would be accessible at the instance of animal that lives inside of the method signature. For example, we could make a Parrot, hand the Parrot into the method where it would become of Animal shape and then make the Parrot speak but not squawk as Speak() is a method on Animal while Squawk() is not. When the animal speaks it will speak as a parrot speaks given that Animal itself does not define what happens in speaking. Moreover, if one does reflection against the animal one will get Parrot-tainted goodies. This is another means to have children of many types bottleneck through a parent when entering a common assembly line. This is more inheritance detailed in C# 4.0 in a Nutshell.

using System;
namespace MyApp.Core
{
   public static class AnimalInterpreter
   {
      public static string Interpret(Animal animal)
      {
         string animalAnalysis = "When a " + DigNameOutOfType(animal.GetType());
         animalAnalysis = animalAnalysis + " says: " + animal.Speak();
         animalAnalysis = animalAnalysis + " ...it is hungry!";
         return animalAnalysis;
      }
      
      private static string DigNameOutOfType(Type type)
      {
         string tooMuchInformation = type.FullName;
         string fullName = tooMuchInformation.Split(",".ToCharArray())[0];
         string[] bitsOfFullName = fullName.Split(".".ToCharArray());
         return bitsOfFullName[bitsOfFullName.Length - 1];
      }
   }
}

 
 

This test passes:

using Microsoft.VisualStudio.TestTools.UnitTesting;
using MyApp.Core;
namespace MyApp.Tests
{
   [TestClass]
   public class AnimalTester
   {
      [TestMethod]
      public void Test()
      {
         Dog dog = new Dog();
         Parrot parrot = new Parrot();
         Animal animal = dog;
         string dogTalk = AnimalInterpreter.Interpret(dog);
         string parrotTalk = AnimalInterpreter.Interpret(parrot);
         string animalTalk = AnimalInterpreter.Interpret(animal);
         Assert.AreEqual(dogTalk, "When a Dog says: Woof! ...it is hungry!");
         Assert.AreEqual(parrotTalk, "When a Parrot says: Polly wants a cracker. ...it is
               hungry!");
         Assert.AreEqual(animalTalk, "When a Dog says: Woof! ...it is hungry!");
      }
   }
}

wrap TFS with GIT

GIT-TFS is a way to wrap TFS with GIT. I wonder if this opens up using a TFS library with something better than MSBuild, say JetBRAINS TeamCity.

Monday, June 25, 2012

Mongo Update!

var mycollection = db.things.find({name:"foo"});
mycollection;

...gave me:

  • { "_id" : ObjectId("4fe8c09ce4dada0af3bde933"), "name" : "foo", "other" : "bar" }
  • { "_id" : ObjectId("4fe8c09ce4dada0af3bde934"), "name" : "foo", "other" : "baz" }

 
 

This updated the second record:

db.things.update( { other:"baz" }, { name:"foo", other:"baz", more:"qux" } );

 
 

Note that I had to respecify existing data points or they would be DROPPED from the object! When I reran the first two commands in this blog posting I got:

  • { "_id" : ObjectId("4fe8c09ce4dada0af3bde933"), "name" : "foo", "other" : "bar" }
  • { "_id" : ObjectId("4fe8c09ce4dada0af3bde934"), "name" : "foo", "other" : "baz", "more" : "qux" }

Mongo tutorial!

http://www.mongodb.org/display/DOCS/Tutorial tells us...

 
 

j = { name : "mongo" };
db.things.save(j);

...seemed to create...

( "_id" : ObjectId("4fe8b073e4dada0af3bde91e"), "name" : "mongo" )

...per what comes back from...

db.things.find();

 
 

for (var i = 1; i <= 25; i++) db.things.save({x : 4, j : i});

...will add numerous records and when one uses...

db.things.find();

...to retrieve them one will only see the first twenty with...

has more

...at the bottom of the dump. Typing...

it

...will give the next records.

 
 

var cursor = db.things.find();
while (cursor.hasNext()) printjson(cursor.next());

...should show everything in the cursor all at once.

 
 

db.things.findOne({name:"mongo"});

...retrieves the one record we created with a name of mongo.

 
 

k = { name : "foo", other "bar" };
l = { name : "foo", other "baz" };
db.things.save(k);
db.things.save(l);
db.things.findOne({name:"foo"});

...returns only first of the two foo records while...

db.things.find({name:"foo"});

...returns a complete collection.

 
 

var cursor = db.things.find();
cursor[4];

...will return the appropriate item from the array.

 
 

db.things.findOne({_id:ObjectId("4fe8b073e4dada0af3bde91e")});

...shows finding by Guid.

 
 

db.things.find({name:"foo"}, {other:"bar"});

...will find records where either name is "foo" or other is "bar" and NOT records that meet BOTH conditions.

 
 

db.things.find({name:"foo", other:"bar"});

...will find records where BOTH name is "foo" or other is "bar"

 
 

db.things.find().limit(3);

...will constrain what is returned.

diving into Mongo

I put the mongo source code at c:\mongo at my PC which means that mongod.exe is at c:\mongo\bin\mongod.exe

  • Mongo will store its files at c:\data\db\
  • I ran mongod.exe as administrator by right-clicking upon it.
  • With mongo running I then typed "cmd" at Windows 7's start menu to spin up a second shell where I entered all of my commands
    1. Typing "c:\mongo\bin\mongo.exe" returned the messages: "MongoDB shell version: 2.0.4" and "Connecting to: test" ...as if letting me into Mongo administration. Typing "exit" drops me back out again.
    2. http://docs.mongodb.org/manual/tutorial/install-mongodb-on-windows/ asserts that "c:\mongo\bin\mongo.exe -- config c:\mongo\mongod.cfg --install" will install the service. This must be run from outside of administering Mongo.
    3. Running Mongo, I typed "use mydb" (which did not yet exist as a database) and was told "switched to db mydb"
      • Add stuff like so:
        1. j = { name : "mongo" };
        2. db.things.save(j);
      • see what is in the database with: db.things.find();

Saturday, June 23, 2012

AngularJS and Knockout

I saw Paul Hammant (co-creator of Selenium) of ThoughtWorks speak on client-side MVC at an IEEE CS meeting held at Pervasive three days ago. His talk was high level and really ultimately only suggested that one pick either AngularJS made by Google peeps or Knockout.js made by Microsoft peeps for the task. Neither are verbose, with AngularJS even less wordy than Knockout, and both are certainly superior, in Paul's opinion, to Backbone.js which is verbose:

Knockout looks better than Backbone in this chart. on Twitpic

I sensed it made sense to pick AngularJS over Knockout, but Paul cautioned that ASP.NET teams will use Knockout given the Microsoft bias.

excuse me, it's a Knockout foreach on Twitpic

Friday, June 22, 2012

This is a C# example of the observer pattern which could offend PETA.

I am finding that I have screwed up this blog posting. I will try to recreate it. Grrrr...

OK... I have made this!

Addendum 10/11/2014: I have recreated what was lost here.

Thursday, June 21, 2012

A brain dump of notes from watching Rob Vettor present on patterns is given herein.

Rob Vettor spoke on five patterns detailed in Design Patterns: Elements of Reusable Object-Oriented Software which is the book by the Gang of Four (Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides) on 6/9/2012.
my Rob Vettor notes - finished book I've been scribbling... on Twitpic

  1. Factory: This pattern tries to curtail having object instantiation sprinkled all over a code base which can be painful to change should the instantiation of the object be nontrivial. In Vettor's example, whenever one needed a distributor for strawberries, one would ask a factory that would instantiate the distributor. The decision as to the nature of the distributor would be facilitated by the factory based upon variables handed into a method call. The factory in his example would create either a Mexico or a California object which inherited from IDistributor and then hand the object back as an IDistributor.
    Where do Strawberries come from? #austincodecamp on Twitpic
  2. Strategy: As detailed by Josh Arnold here, this is a way to clean up messes that materialize in case statements or nested if/then/else logic gunk.
    Vettor Note on Strategy Pattern on Twitpic
    In this pattern each case in a case statement gets abstracted to its own class which inheirts a common interface. A context object gets the interface at a getsetter. In Rob Vettor's example, he made a duck quack... or scream... or bark depending on a differentiator.
    Vettor Note on Strategy Pattern on Twitpic
    His code:
    var duck = new Duck();
    var quackResult = duck.Quack();
    duck.QuackStrategy =
       QuackBehaviorFactory.SetQuackStrategy(QuackBehavior.Whisper);
    quackResult = duck.Quack();

    Vettor Note on Strategy Pattern on Twitpic
    Here quackResult is an IQuackStrategy defined by a QuackBehavior differentiator at QuackBehaviorFactory which contains a case statement. The case statement is kept lean however. All of the real behavior is abstracted out to the IQuackStrategy children.
  3. Vettor Note on Strategy Pattern on Twitpic
    Note that at var quackResult = duck.Quack(); above before QuackBehaviorFactory is called, that quackResult will be null. QuackBehaviorFactory will need occasional surgical updating so this pattern does break with O/CP somewhat.
  4. Observer: This pattern has to do with listening for events!
    a slide from Rob Vettor's presentation on patterns at #a... on Twitpic a slide from Rob Vettor's presentation on patterns at #a... on Twitpic a slide from Rob Vettor's presentation on patterns at #a... on Twitpic a slide from Rob Vettor's presentation on patterns at #a... on Twitpic a slide from Rob Vettor's presentation on patterns at #a... on Twitpic a slide from Rob Vettor's presentation on patterns at #a... on Twitpic
  5. Decorator: Extends an existing object by adding state to it at runtime. In his example, Lamborghni subclasses Car and the constructor for Lamborghni sets the price getsetter on Car to something Lamborghni appropriate. The price may climb as we add options like so (where "car" is an existing variable of type Lamborghni):
    car = new OptionalLeather(car);
    Yay!
  6. Template Method: This is for algorithms. One holds most algorithmic logic in a parent while deferring sections to child classes. Mr. Vettor's example was of lotteries which may differ in number generation from state to state.
    Rob Vettor is speaking on the Factory Pattern at #austincodecamp on Twitpic

IDisposable and using in C#

http://msdn.microsoft.com/en-us/library/yh598w02%28v=vs.80%29.aspx tells us that in order for a class to use a using loop that it must inheirt from IDisposable.

using System;
   
class C : IDisposable
{
   public void UseLimitedResource()
   {
      Console.WriteLine("Using limited resource...");
   }
   
   void IDisposable.Dispose()
   {
      Console.WriteLine("Disposing limited resource.");
   }
}
   
class Program
{
   static void Main()
   {
      using (C c = new C())
      {
         c.UseLimitedResource();
      }
      Console.WriteLine("Now outside using statement.");
      Console.ReadLine();
   }
}

the difference between ref and out in C#

...is that out MUST be set inside of a method that has it in its signature. Otherwise an exception is thrown! Otherwise ref and out are comparable. One may instantiate variable x and variable y in C#, call a method that uses variable x and variable y as a ref variable and an out variable respectively, and then go about using x and y in later code while enjoying the alterations made in the method to the two variables (certainly true of y).

SQL transactions

declare @foo int
begin transaction bar
   insert into baz (qux)
   values ('qux')
   set @foo = @@error
   if @foo <> 0
      begin
         rollback transaction bar
         return(1)
      end
commit transaction bar
return(0)

HAVING in SQL

Having is used in tandem with GROUP BY.

SELECT department, SUM(sales) as "Total sales"
FROM order_details
GROUP BY department
HAVING SUM(sales) > 1000;

Tuesday, June 19, 2012

.AsQueryable() is really ghetto.

This provides a way to cast an IEnumerable to IQueryable shape in the naming of horrible hacking. C# 4.0 in a Nutshell mentions this in Chapter 8 and I witnessed it some firsthand at AMD. Bad, bad, bad. An IQueryable that is not a lifeline to a database is just misleading. Ick!

A digit in double curly brackets ends up in single curly brackets on the other side a of String.Format manipulation in C#.

string foo = "The {0} red {1} jumps {2} the {{0}} {{1}} dog.";
string bar = String.Format(foo, "quick", "fox", "over");
string baz = String.Format(bar, "lazy", "brown");

 
 

The variables instantiated above will end up with the following values:

fooThe {0} red {1} jumps {2} the {{0}} {{1}} dog.
barThe quick red fox jumps over the {0} {1} dog.
bazThe quick red fox jumps over the lazy brown dog.

classic CASE statement

UPDATE Books
   SET price = CASE WHEN price <= $25.00
      THEN price *1.10
      WHEN price > $25.00
      THEN price *0.85
      ELSE price END;

 
 

Here we make expensive books less so while making cheap books less so too. We have to have an ELSE as otherwise ELSE would be null. This is one of many SQL things that Joe Celko spoke about at the Austin .NET User Group last night in a presentation.

Joe Celko on Twitpic

This was sort of a Scott Hanselmanesque talk that constantly went off on wild tangents assuming, wisely, short attention spans for audience members. Random things mentioned:

  1. Joe’s advice: Don’t duplicate tables when you don’t need to. Boss and Employee are not two separate database tables. Boss is a kind of Employee. Joe had a story about a company that only made steel-toed work boots. From the perspective of manufacturing there was only one type of product. From the perspective of marketing there were two products however because construction workers bought the boots with shoe sizes of 12 or greater while Goth Girls! bought the boots with small shoe sizes. Different shoe sizes were sold to different types of stores. The big boots were not sold to Hot Topic I suppose. The gap between the two sizes allowed marketing to use the same database as manufacturing while merely refining its querying to account for shoe size in the name of understand data. The wrong thing to do in this case would have been to break MensBoots and GirlsBoots into two separate database tables.
  2. It’s a good thing we finally got away from Roman numbers! When the church did not recognize the number zero one could have logic problems as highlighted by this syllogism:
    One cat has one more tails than no cat.
    No cat has twelve tails.
    Therefore, one cat has thirteen tails.
  3. Joe recommend "The Manga Guide to Databases" as the best book on SQL!

Monday, June 18, 2012

How to create and populate a temporary table in SQL.

USE [Foo]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE Whatever
AS
BEGIN
   CREATE TABLE #squarednumbers
   (
      numericvalue INT
   )
   declare @unalterednumber INT
   DECLARE curs CURSOR FOR SELECT TOP 10 Bar From dbo.[Baz]
   OPEN curs
   FETCH NEXT FROM curs into @unalterednumber
   WHILE @@FETCH_STATUS = 0
      BEGIN
         INSERT INTO #squarednumbers (numericvalue)
         VALUES (@unalterednumber * @unalterednumber)
         FETCH NEXT FROM curs into @unalterednumber
      END
   CLOSE curs
   DEALLOCATE curs
   SELECT * FROM #squarednumbers
END

JetBrains dotPeek

The JetBrains company, which makes ReSharper, also makes a free tool called dotPeek which will allow one to see what is inside of a .dll that was once a C# project. "What is the application?" you ask. Glad you asked. Where I work (HDRI), I have been asked to retire two servers running MSSQL2000 databases. Every database on the server must die or get migrated to MSSQL2008. In the MSSQL2008 environment DBEncrypt for encryption will NOT be used as it is for MSSQL2000 databases. I have pulled the source code for an old app using one of the MSSQL2000 databases and have tried to get it working with a MSSQL2008 copy of the applicable database. No dice. When I attempt to log in the compiler makes its way from the UI project of the app into a referenced compiled library (for which source code was not checked in) and then causes a red and yellow screen of death informing me of an error vaguely to do with DBEncrypt:

The red and yellow screen of death has a pretty good stack hi... on Twitpic

The compiled .dll, like the app, is something made by the company I work for, and like the app running on MSSQL2000, it is old, old, old. The .dll was intended, I surmise, in its day to facilitate some common concerns for numerous applications and hence it is not merely a project within the existing application. I tried to find the source code for this other thing but had some trouble. This makes the error opaque. The red and yellow screen of death offered more of a stack history than the Call Stack window in Visual Studio.

The Call Stack window is less helpful than the red and yellow... on Twitpic

The problem has to lie at the database, correct? Somewhere something that looks like this:

SELECT cast(master.[dbo].dbefn_session_decrypt_varchar([Foo], '238', 'AES', 'CBC', NULL) as varchar(20)) as 'Foo' FROM [dbo].[Bar]

 
 

...needs to be redacted to merely:

SELECT [Foo] FROM [dbo].[Bar]

 
 

...but where? The database is deep with numerous views and stored procedures. Should I just dig into them all? No, Will Hendrix recommend that I use dotPeek. We installed it and he drug the .dll into the Assembly Explorer Window. We could then see the code inside the .dll. It turns out that the method called in the .dll turned around and reached back into the data layer of the existing application!

today's challenge on Twitpic

We found an NHibernate .hbm.xml mapping file that corresponded to a view at the database. The view had to be "cleaned up." I did not expect this! I was betting that the .dll was reaching into a stored procedure on its own accord. Not so.

MSSQL Management Studio Express will allow you to create a script for editing every view in a database.

  1. Click on the "Views" folder to select it.
  2. Select "Object Explorer Details" from the View menu.
  3. A new pane should appear listing all of the views. Select them all.
  4. Right-click in the swath of selected views and select:
       Script View as > CREATE To > New Query Editor Window
  5. You will be handed one big SQL script for creating all of the views which may be doctored up as needed.

Sunday, June 17, 2012

Global.asax.cs has changed within the Web API template!

I saw Shawn Weisfeld's talk on ASP.NET Web API eight days ago. I also wrote a blog posting on it earlier today in which I forgot to mention how Global.asax.cs has changed:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;

using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
 
namespace MvcApplication1
{
   
// Note: For instructions on enabling IIS6 or IIS7 classic mode,
   // visit http://go.microsoft.com/?LinkId=9394801

 
   public class WebApiApplication : System.Web.HttpApplication
   {
      protected void Application_Start()
      {
         AreaRegistration.RegisterAllAreas();
 
         FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
         RouteConfig.RegisterRoutes(RouteTable.Routes);
         BundleConfig.RegisterBundles(BundleTable.Bundles);
      }
   }
}

 
 

RouteConfig.cs contains the routes!

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

using System.Web.Http;
using System.Web.Mvc;
using System.Web.Routing;
 
namespace MvcApplication1
{
   public class RouteConfig
   {
      public static void RegisterRoutes(RouteCollection routes)
      {
         routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
 
         routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
         );
 
         routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
         );
      }
   }
}

I saw Shawn Weisfeld's talk on ASP.NET Web API eight days ago.

@shawnweisfeld is speaking on ASP.NET Web API at #austincodecamp on Twitpic

ASP.NET Web API and getting started with it were made to seem easy by Shawn Weisfeld at a talk he gave eight days ago. This was the best of several talks I saw at Code Camp. Note: I already had MVC4, but I had to install it anew to get the Web API Project Template. I guess I had an older version of the MVC4 Beta. To reinstall MVC4 I clicked on the link which read "ASP.NET MVC 4 RC for Visual Studio 2010 SP1" here. Hey, that is a good hint towards how to spin up a Web API app: First, make a MVC4 project and, second, pick the Web API template. These are the two wizard steps one should undertake after selecting "Project..." from the "New" menu from within the "File" menu from within Visual Studio 2010. This post will offer another of the goofy calculator examples I am so fond of. I put this HTML in the Index.cshtml view for the HomeController in a new project:

The square of <input type="text" id="number" value="3" style="width: 20px;" /> is...
<div id="calcuation" style="font-size: 40px;">9</div>
<button id="button">Update</button>

 
 

The square of is...
9

 
 

OK, here we go! In the Controllers folder one will notice ValuesController which inheirts from ApiController instead of Controller! It's default code is like so:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;

using System.Web.Http;
   
namespace MvcApplication1.Controllers
{
   public class ValuesController : ApiController
   {
      
// GET api/values
      public IEnumerable Get()
      {
         return new string[] { "value1", "value2" };
      }
   
      
// GET api/values/5
      public string Get(int id)
      {
         return "value";
      }
   
      
// POST api/values
      public void Post(string value)
      {
      }
   
      
// PUT api/values/5
      public void Put(int id, string value)
      {
      }
   
      
// DELETE api/values/5
      public void Delete(int id)
      {
      }
   }
}

 
 

I changed the Post method like so:

public HttpResponseMessage Post(string value)
{
   decimal number = Convert.ToDecimal(value);
   value = (number*number).ToString();
   return this.Request.CreateResponse<string>(HttpStatusCode.Created, value);
}

 
 

I then put this blob of jQuery into Index.cshtml and had a working calculator:

<script src="/Scripts/jquery-1.6.2.js" type="text/javascript"></script>
<script type="text/javascript">
   $(function () {
      $('#button').bind('click', function () {
         var userinput = $('#number').val();
         $.ajax({
            type: 'POST',
            url: '/api/Values?value=' + userinput,
            statusCode: {
               201: function (value) {
                  document.getElementById('calcuation').innerHTML = value;
               }
            }
         });
      });
   });
</script>

 
 

Let me also mention:

  1. For starters, what about error handling? What if one hands in a letter instead of a number in this scenario? Well, in Shawn's demo he suggested that errors should be handled on the client side. Just as my code offers a to-do for status code 201, it could comparably offer a to-do for errors. I tried to append a 400 scenario to my own code to catch the problem but it doesn't work (at least not in Cassini testing). It could be that 400 is just the wrong status code. I suppose I should look at this and study up. Ugh, I'm going to have to learn what the status codes are to use ASP.NET Web API! :P
    this is how @shawnweisfeld addresses ASP.NET Web API errors on Twitpic
  2. By default ASP.NET Web API uses JSON. One may specify XML instead or roll one's own format. At http://bit.ly/A6ybsy, Headspring's Pedro Reys has a blog posting on this. Something Shawn called a “Formatter” delineates what format is used. Again, JSON is the default.
  3. ASP.NET Web API exists so that one may escape XML-heavy WCF in lieu of a HTTP requests-favored interface. Shawn recommended using Fiddler to inspect HTTP traffic.

Saturday, June 16, 2012

Chris Weldon of Improving on SOLID

Chris Weldon is speaking on SOLID at #austincodecamp on Twitpic

What more might I say about SOLID I have not yet articulated here and here? Well, Chris Weldon of Improving offered some insights that were new to me when I heard them at Code Camp one week ago:

  1. In the name of the open/closed principal, do not change the signature of an existing method that has had any significant life within your application. Why not? Well, one nightmare scenario may occur when your code base gets compiled to a .dll file that is deployed for others to use. In this scenario, a change in method signature can sabotage others downstream who long ago wrote code that expected something different! Even with less extreme division lines this can happen. Another party working in the same code base as you could be writing new code to interact with a method independent of you on the same day that you are changing its signature. If a method's signature DOES really need to change, use some overloading. Make a new signature for a method with the same name. Leave the deprecated method be. Even if you think you can get away with deleting it, such a move is not wise. Fear of changing a method's signature drives OCP. It's healthy.
  2. In the name of the Dependency Inversion Principal, avoid ever having an interface with unused methods. If four classes use all three methods on a common interface and a fifth class uses only two, then the outlying method will have to be nonetheless supported in a ghetto way by the fifth class. Perhaps, a junk method that just throws an exception can sit as a placeholder in the fifth class for the unneeded method. Boo! This should smell to you. The fix is to break the interface with three methods into two separate interfaces so that the fifth class may utilize ONLY one of the two interfaces (cleanly). Perhaps the first four classes that needed all three methods can inherit from a new, third interface which then uses the other two. Chris recommended creating wrapper interfaces of this nature rather than having God interfaces exposing methods that are not always applicable.
  3. Liskov bug: A parent has a Save() method. Most children use the method. The one child that does not merely overrides the Save() method so that it does nothing. Bad! Now we have a method with a misleading name. This mess should exposition that the child has the wrong parent.
another pic of Chris Weldon of improving at #austincodecamp on Twitpic

When lives depend on tests...

@jmarnold is speaking on testing at #austincodecamp on Twitpic

One week ago, I saw Austin's Josh Arnold, the CTO of Surgery Logistics (the developer, not the recruiter... I've interviewed for both), speak on testing at Code Camp! His domain has to do with whether or not surgeries are scheduled on time and whether or not an emergency room will be prepped for an arriving individual, so there really is no room for error as he is writing code that lives depend upon! Who better to talk about testing, no? Some bullet points:

  • Regression test everything! If you have a test that runs a swath of steps be sure the individual steps all get their own tests.
  • Keep your code DRY but your tests damp. DRY is the rule "Don't repeat yourself" ...and you should ignore it in your tests. It is better to have code copied all over the place in test than to have test logic abstracted out of the test itself. Authentication credentials are an exception. Do not copy these about.
  • Write your app firstly without a database! Get the core logic under test, then incorporate hydrated data!
  • It is alright to have a fast build/slow build split in testing. The fast build will contain vital tests run at every demonstrable update. The slow build will be more comprehensive and will run daily as part of the automation process. The slow build will test everything end-to-end.
  • Use front doors when you can. This means testing through public methods and not using reflection to test private methods. This means fabbing data with Selenium scripts in lieu of SQL scripts or C# code.
  • If you need to pause to wait for something to happen, it is better to run Thread.Sleep(X) over and over again in a loop in tiny increments until the desired effect occurs than to try to specify a length for napping. The former approach is easier to maintain.
    the Until method runs Thread.Sleep over&over in tiny blip... on Twitpic

Node.js

Teague at #austincodecamp on Twitpic

I saw John Teague speak on Node.js at Code Camp one week ago today and came away concluding that I do not want to try to learn Node.js. At this point in time it just seems like it is too much of a mountain to climb. Nonetheless, thank you to John Teague for giving a great talk! Here is the bird's eye view which will show off why this is hard stuff in an unrefined infancy:

  • Elevator Speech: Node.js offers server side JavaScript. What makes Node a little different is that it uses events instead of threads. Node starts one event loop and waits for events to be triggered. I/O (file input/output) costs are heavy and if you build an application (not of Node) on a single thread it can run slow and keep the user waiting when struggling through I/O morasses. Using an event-driven, server-side architecture can alleviate this pain and this is the whole reason to use Node.js as JavaScript is very good at "eventing." If there is another way to go, I don't know what it is. The subtext of John's talk was that you should use Node to solve this problem and that it was THE way to go. Node's non-blocking I/O model sets it apart.
  • Still Listening? ASP.NET and Java are NOT asynchronous. They fake asynchronous behavior through threading calls which are abstracted away. There can be starvation situations in which one thread dies while waiting for a resource which can lead to pain. Use event callbacks in Node to make the magic happen, i.e. play to JavaScript's strengths. Instead of worrying about whether or not customers can find what they are looking for in your store, just be ready for them to come up to the register. Sound harsh? Think about how much time you might spend in vain otherwise, for example:
  • Even versions of Node are stable. Odd versions are development versions. PM is the Node package manager. Think: NuGet
  • What's not to like? Node does not run on IIS on Windows 7. It has its own web server. I could not understand how "it" is set up or found via Port 80 or how one gets an A record to resolve to it. Also, by "it," I mean something that YOU write yourself in a few lines of code. Express and Railway (MVCesque) which is built on top Express are third-party tools for empowering routing that the "it" you write yourself will not have standalone. Derby is another routing framework yet. Headspring's Steve Donie was in the audience at the talk and piped up about how many random things one had to learn tangentially in name of spinning up a Node project and how, moreover, the grocery list was nebulous given that one could use Express or could use Railway or could use Derby. The Express/Railway/Derby decision dilemma is just of routing. There are other decisions like this to make for other frameworks for other fill-in-the-gaps work to do in the name of getting Node.js to cough up "Hello World" in a web browser, but once I realized that I stopped scribbling down notes on Node.js. :( I'll check back on Node in... two years.

You may switch from IQueryable to IEnumerable midway through a chain!

In following this and repurposing some of its code, I crafted this test which passes, but would throw a SQL exception if .AsEnumerable() were to be cut from the script as the whole of the casting-to-a-list would be of an IQueryable implementation thus staging an inability to cast the line immediately below .AsEnumerable() to SQL where my StateHelper class would make no sense. To solve the problem: part of our chain is of IQueryable and, later, part of our chain is of IEnumerable. If not for the one objectionable use of StateHelper, the whole thing could be of IQueryable.

using System.Collections.Generic;
using System.Data.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Whatever.Models;
using System.Linq;
namespace Whatever.Tests
{
   [TestClass]
   public class IQueryableTest
   {
      [TestMethod]
      public void DataTest()
      {
         string Ok = @"server=.\sqlexpress;database=OK;Integrated Security=true;";
         DataContext dataContext = new DataContext(Ok);
         Table<Contact> contacts = dataContext.GetTable<Contact>();
         List<Address> list = contacts.Where(c => c.Email.EndsWith("example.com"))
            .OrderBy(c => c.Name)
            .AsEnumerable()
            .Where(c => StateHelper.GetStateForCity(c.City) != "Florida")
            .Select(c => new Address
            {
               Street = c.Street,
               City = c.City,
               State = StateHelper.GetStateForCity(c.City)
            }).ToList();
         Assert.AreEqual(list.Count, 2);
         Assert.AreEqual(list[0].Street, "500 East Stassney");
         Assert.AreEqual(list[0].City, "Austin");
         Assert.AreEqual(list[0].State, "Texas");
         Assert.AreEqual(list[1].Street, "1515 Ocean");
         Assert.AreEqual(list[1].City, "Santa Cruz");
         Assert.AreEqual(list[1].State, "California");
      }
   }
}

 
 

This is another nugget of wisdom from Chapter 8 of C# 4.0 in a Nutshell! Chapter 8 also goes into LINQ to SQL which is less interesting. I suppose I should note the change I made to the Contact class however. It is like so:

using System;
using System.Data.Linq.Mapping;
namespace Whatever.Models
{
   [Table(Name="Contacts")]
   public class Contact
   {
      [Column(IsPrimaryKey=true)]
      public Guid Id;
      [Column]
      public string Name;
      [Column]
      public string Phone;
      [Column]
      public string Email;
      [Column]
      public string Street;
      [Column]
      public string City;
   }
}

 
 

I made the Contacts table like so:

BEGIN TRANSACTION
GO
CREATE TABLE Contacts
   (
   Id uniqueidentifier NOT NULL DEFAULT newid(),
   Name varchar(50) NOT NULL,
   Phone varchar(50) NOT NULL,
   Email varchar(50) NOT NULL,
   Street varchar(50) NOT NULL,
   City varchar(50) NOT NULL
   )
GO
ALTER TABLE Contacts ADD CONSTRAINT
   PK_Whatever PRIMARY KEY CLUSTERED
   (
   Id
   ) WITH( STATISTICS_NORECOMPUTE = OFF,
      IGNORE_DUP_KEY = OFF,
      ALLOW_ROW_LOCKS = ON,
      ALLOW_PAGE_LOCKS = ON)
GO
INSERT INTO Contacts (Name, Phone, Email, Street, City)
Values ('Johnny', '(512) 419-8788', 'pil@example.com', '500 East Stassney', 'Austin')
INSERT INTO Contacts (Name, Phone, Email, Street, City)
Values ('Sid', '(928) 425-629', 'fevercheese@gmail.com', '1 South Broad', 'Globe')
INSERT INTO Contacts (Name, Phone, Email, Street, City)
Values ('Steve', '(561) 790-0349', 'metal@example.com', '5055 Club', 'West Palm Beach')
INSERT INTO Contacts (Name, Phone, Email, Street, City)
Values ('Paul', '(831) 475-8325', 'cook@example.com', '1515 Ocean', 'Santa Cruz')
COMMIT

DISTINCT!

This touches on DISTINCT and how it may be used in a query to remove duplicate records. I think this is an MSSQL only thing.

SELECT DISTINCT city, state
FROM suppliers;

query from one IEnumerable type collection to another

In reading C# 4.0 in a Nutshell, I have encountered ways to make one IEnumerable from another of a different type in the midst of a LINQ query. I will give an example that uses these three silly classes:

  1. namespace Whatever.Models
    {
       public class Contact
       {
          public string Name { get; set; }
          public string Phone { get; set; }
          public string Email { get; set; }
          public string Street { get; set; }
          public string City { get; set; }
       }
    }
       
  2. namespace Whatever.Models
    {
       public class Address
       {
          public string Street { get; set; }
          public string City { get; set; }
          public string State { get; set; }
       }
    }
       
  3. namespace Whatever.Models
    {
       public static class StateHelper
       {
          public static string GetStateForCity(string city)
          {
             switch (city)
             {
                case "Globe":
                   return "Arizona";
                case "West Palm Beach":
                   return "Florida";
                case "Santa Cruz":
                   return "California";
                default:
                   return "Texas";
             }
          }
       }
    }
       

Here is my example. This test passes.

using System.Collections.Generic;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Whatever.Models;
using System.Linq;
namespace Whatever.Tests
{
   [TestClass]
   public class ContactTests
   {
      [TestMethod]
      public void QueryTest()
      {
         Contact[] contacts = new Contact[]
            {
               new Contact()
               {
                  Name = "Johnny",
                  Phone = "(512) 419-8788",
                  Email = "pil@example.com",
                  Street = "500 East Stassney",
                  City = "Austin"
               },
               new Contact()
               {
                  Name = "Sid",
                  Phone = "(928) 425-629",
                  Email = "fevercheese@gmail.com",
                  Street = "1 South Broad",
                  City = "Globe"
               },
               new Contact()
               {
                  Name = "Steve",
                  Phone = "(561) 790-0349",
                  Email = "metal@example.com",
                  Street = "5055 Club",
                  City = "West Palm Beach"
               },
               new Contact()
               {
                  Name = "Paul",
                  Phone = "(831) 475-8325",
                  Email = "cook@example.com",
                  Street = "1515 Ocean",
                  City = "Santa Cruz"
               }
            };
         IEnumerable<Address> addresses = contacts
            .Where(c => c.Email.EndsWith("example.com"))
            .OrderBy(c => c.Name)
            .Select(c => new Address
               {
                  Street = c.Street,
                  City = c.City,
                  State = StateHelper.GetStateForCity(c.City)
               });
         List<Address> list = addresses.ToList();
         Assert.AreEqual(list.Count, 3);
         Assert.AreEqual(list[0].Street, "500 East Stassney");
         Assert.AreEqual(list[0].City, "Austin");
         Assert.AreEqual(list[0].State, "Texas");
         Assert.AreEqual(list[1].Street, "1515 Ocean");
         Assert.AreEqual(list[1].City, "Santa Cruz");
         Assert.AreEqual(list[1].State, "California");
         Assert.AreEqual(list[2].Street, "5055 Club");
         Assert.AreEqual(list[2].City, "West Palm Beach");
         Assert.AreEqual(list[2].State, "Florida");
      }
   }
}

 
 

Here is the same thing with an anonymous type.

using Microsoft.VisualStudio.TestTools.UnitTesting;
using Whatever.Models;
using System.Linq;
namespace Whatever.Tests
{
   [TestClass]
   public class ContactTests
   {
      [TestMethod]
      public void QueryTest()
      {
         Contact[] contacts = new Contact[]
            {
               new Contact()
               {
                  Name = "Johnny",
                  Phone = "(512) 419-8788",
                  Email = "pil@example.com",
                  Street = "500 East Stassney",
                  City = "Austin"
               },
               new Contact()
               {
                  Name = "Sid",
                  Phone = "(928) 425-629",
                  Email = "fevercheese@gmail.com",
                  Street = "1 South Broad",
                  City = "Globe"
               },
               new Contact()
               {
                  Name = "Steve",
                  Phone = "(561) 790-0349",
                  Email = "metal@example.com",
                  Street = "5055 Club",
                  City = "West Palm Beach"
               },
               new Contact()
               {
                  Name = "Paul",
                  Phone = "(831) 475-8325",
                  Email = "cook@example.com",
                  Street = "1515 Ocean",
                  City = "Santa Cruz"
               }
            };
         var addresses = contacts
            .Where(c => c.Email.EndsWith("example.com"))
            .OrderBy(c => c.Name)
            .Select(c => new
               {
                  Street = c.Street,
                  City = c.City,
                  State = StateHelper.GetStateForCity(c.City)
               });
         Assert.AreEqual(addresses.Count(), 3);
         Assert.AreEqual(addresses.ElementAt(0).Street, "500 East Stassney");
         Assert.AreEqual(addresses.ElementAt(0).City, "Austin");
         Assert.AreEqual(addresses.ElementAt(0).State, "Texas");
         Assert.AreEqual(addresses.ElementAt(1).Street, "1515 Ocean");
         Assert.AreEqual(addresses.ElementAt(1).City, "Santa Cruz");
         Assert.AreEqual(addresses.ElementAt(1).State, "California");
         Assert.AreEqual(addresses.ElementAt(2).Street, "5055 Club");
         Assert.AreEqual(addresses.ElementAt(2).City, "West Palm Beach");
         Assert.AreEqual(addresses.ElementAt(2).State, "Florida");
      }
   }
}