Join By Anonymous Types in Linq

Just found this out yesterday so I thought I would post and pass on to all two of you reading this.

Suppose you have a User table and a Contacts table and you wanted to find all the users that match up with the contacts table. Now suppose there is no direct correlation. What to do? You could do something really brilliant by joining the tables together on FirstName and LastName, because we all know that there will always only be one John Smith in either table. Screw you, I couldn’t think of a better example at the time.

public static List<User> GetAllUsersWithMatchingContactInformationUsingJoin()
{
  List<User> foundUsers;

  var query = from user in dataContext.Users
              join contact in dataContext.Contacts on new {user.FirstName, user.LastName } equals new { contact.FirstName, contact.LastName }
              select user;

              foundUsers = query.ToList();

  return foundUsers;
}

As you can see here:

join contact in dataContext.Contacts on new {user.FirstName, user.LastName } equals new { contact.FirstName, contact.LastName }

You can create a type on the fly and then compare it to another. I thought that was interesting.

I are tupid

This may be novel or really dumb, but I like it. Say you want to convert a Dictionary to a List of KeyValuePairs that are sorted by something within the dictionary Key or Value. Don’t ask why, just go with it. You could do this:

Where someDictionary is Dictionary<Type, string> :

List<KeyValuePair<Type, String>> dataSource = new List<KeyValuePair<Type, String>>(someDictionary);
dataSource.Sort(new SomeComparer<KeyValuePair<Type, String>>("Value", true));

To:

var query = from keyValuePair in someDictionary
          orderby keyValuePair.Value
          select new KeyValuePair<Type, String>(keyValuePair.Key, keyValuePair.Value);
SomeMethod(query.ToList());

If nothing else, you don’t have to create or implement a System.Collections.IComparer class to use the .Sort method. That seems worth it. That and I think it just plain looks better, but that just me. If I am completely wrong here, refer to the title of this post. Just a thought really.

Filling a Private Field on a Base Class Using Reflection

Ok here’s the next step in this testing kick. So now you have your test classes that create classes. Swell. Problem is, there are private fields on the base class of whatever class you are creating. So you’re screwed, right? Not really. Now what I am about to do is nothing new. It’s just basically using Reflection and FieldInfo to fill a field on a base class. Actually very easy. Here’s the code for the example.

using System;
using System.Collections.Generic;
using System.Reflection;

public class UserBase
{
  private Boolean _isBaseUser;

  public UserBase()
  {
      _isBaseUser = true;
  }

  public Boolean IsBaseUser
  {
      get
      {
          return _isBaseUser;
      }
  }
}

public class MainUser : UserBase
{
  //Simple list used to "cache" the field info so reflection doesn't have to be used
        //again for a type that has already been used.
  private static Dictionary<Type, List<FieldInfo>> typeToInfoList;

  /// <summary>
        /// This is used to fill in the needed field on the passed in object.  This is done by reflection/
        /// FieldInfo.  Basically you get the field info you want off the type, then you use the info to
        /// fill the field on the object.  
        /// </summary>
        /// <param name="objectToFill">This is the object that needs the field changed.</param>
        /// <param name="fieldName">This is the name of the field.</param>
        /// <param name="value">This is the value to be set.</param>
        /// <param name="typeToCheck">This is the type of the class that the field resides.</param>
  public static void FillField(Object objectToFill, String fieldName, Object value, Type typeToCheck)
  {
      List<FieldInfo> fieldInfoList;
      FieldInfo neededFieldInfo;
      Boolean heldInfoList;

      if (typeToInfoList == null)
      {
          typeToInfoList = new Dictionary<Type, List<FieldInfo>>();
      }
      //Check to see of the list already has the field info and save that 
          //boolean for later use.
      heldInfoList = typeToInfoList.ContainsKey(typeToCheck);
      //If it is in the "cache", grab it.  If not, create a new list
          //for the passed in type.
      fieldInfoList = heldInfoList ? typeToInfoList[typeToCheck] : new List<FieldInfo>(typeToCheck.GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public));

     //Now just look for the needed field info in the list. 
     neededFieldInfo = fieldInfoList.Find(currentItem => currentItem.Name == fieldName);
      //Use the field info to set the value on the object.
      neededFieldInfo.SetValue(objectToFill, value);

      //Store the field info list if it isn't being stored already.
      if (!heldInfoList)
      {
          typeToInfoList.Add(typeToCheck, fieldInfoList);
      }
  }

  //Simple constructor to create the user.
  public static MainUser Create()
  {
      MainUser testUser;

      testUser = new MainUser();

      return testUser;
  }
}

That’s pretty much it. What the hell is all that? Well basically you have the UserBase as the base class for the example. MainUser that in inherits UserBase. The FillField method that does all the work. And lastly, the dictionary used as a lame cache for this example. Why cache anything? Well everything you get the field info, reflection is used. This can be expensive. So why bother getting the same field info for the same type every time this method is called? Just store it somewhere so that if the same class type is passed through again, you can easily access the field info for the class without going for reflection again.

Here’s an example of the use:

using Microsoft.VisualStudio.TestTools.UnitTesting;

 [TestClass]
 public class FillFieldTest
 {
     [TestMethod]
     public void FillField_CheckFieldForChange()
     {
         MainUser testUser;

         testUser = new MainUser();
         Assert.IsTrue(testUser.IsBaseUser);

         MainUser.FillField(testUser, "_isBaseUser", false, typeof(UserBase));
         Assert.IsFalse(testUser.IsBaseUser);

         MainUser.FillField(testUser, "_isBaseUser", true, typeof(UserBase));
         Assert.IsTrue(testUser.IsBaseUser);
     }
 }

First test is checking to see if the IsBaseUser property is true. This will be true since UserBase sets _isBaseUser to true on instantiation.

Second test is checking to see if the FillField method worked correctly.

Third test is really just to step through a second time so you can see how the quasi-caching works.

Mulitple Constraint Generics and Test Base Classes

This was basically an idea I had to have test classes inherit a TestBase that has a Static Create method on it. The reason for this is that I have found it easier to have a Create method that takes care of creating a temporary class of the type the test represents. Say I have a UserTest class and I need an address. Instead of creating and filling a whole address object in the UserTest, it easier to have a Create Method on the AddressTest class that gives me a premade Address object. Why would I want to redo a lot of the same code by having the create method on every class when I can have it on a base class and just have the non base classes specify how to create the object?

Is this really needed? I can’t argue absolutely, but this forces a Create method to appear on any test class that inherits from TestBase and by use of Exceptions, forces the child classes to define how to create the object they represent. (As in it forces AddressTest to define how to create an Address object.) This also allows the Create method to be static and inherited. You could make it abstract, to skip the need for the two create methods(Create and CreateInstance), but that would hose the whole situation since static abstract is a no no. Static is a must for this situation.

The idea behind the code is to have a static Create method on the TestBase class that when called will create the test class type passed in through generics.

public static I Create()
 {
     I returnValue;
     J testToUse;

     testToUse = System.Activator.CreateInstance<J>();
     returnValue = testToUse.CreateInstance();

     return returnValue;
 }

Where J is the test class type to create. Once that test class is instantiated, the virtual method CreateInstance is called. This is where the test class creates the instance of the object it represents.

protected override I CreateInstance()
{
     I returnValue;

     returnValue = (I)new SimpleItem();
     returnValue.IsSimple = true;
     return returnValue;
}

Where I is the type of object it is going to create. In use it will look something like this:

  ItemBase itemToCreate;

  itemToCreate = SimpleItemTest<SimpleItem>.Create();

Now for the code:

//Some junk base items to demostrate the creating of an item with a base class
public class ItemBase 
{
}

//One item that will be created
public class SimpleItem : ItemBase
{
 public Boolean IsSimple { get; set; }
}

//The other item that can be created.
public class ComplexItem : ItemBase
{
 public Boolean IsComplex { get; set; }
 public Boolean IsNotSimple { get; set; }
}

//This test will be used to create a SimpleItem
public class SimpleItemTest<I> : TestBase<I, SimpleItemTest<I>> where I : SimpleItem
{
 protected override I CreateInstance()
 {
     I returnValue;

     returnValue = (I)new SimpleItem();
     returnValue.IsSimple = true;
     return returnValue;
 }
}

//This test will be used to create a ComplexItem
public class ComplexItemTest<I> : TestBase<I, ComplexItemTest<I>> where I : ComplexItem
{
 protected override I CreateInstance()
 {
     I returnValue;

     returnValue = (I)new ComplexItem();
     returnValue.IsComplex = true;
     returnValue.IsNotSimple = true;
     return returnValue;
 }
}

//This is the base class where the Create Method resides
public class TestBase<I, j> where I : class where J : TestBase<I, j>
{
 //This will either be overridden or throw an error.  Kind of a forced
 //abstract.  This is the method that the child test classes will use to
 //create whatever class they represent.
 protected virtual I CreateInstance()
 {
     throw new System.NotImplementedException();
 }

 //This is used to create a test class and call the CreateInstance method
 //so that this method can return the correct object.  The object type is
 //dependent on the type of test class that is being created.
 public static I Create()
 {
     I returnValue;
     J testToUse;

     testToUse = System.Activator.CreateInstance<J>();
     returnValue = testToUse.CreateInstance();

     return returnValue;
 }
}