I likz demz linq

So today I had this weird need to try creating a sort of dynamic linq thing in which I could query a User list but not have to write a Linq query for every method. I just wanted to make a method that would return the correct query that I wanted based on a simple “dynamic” where clause. Well part of the reason this should be easy is if you look at the Where extension method on an IEnumerable collection, you will see it needs a Func<T, K> where T is the type of the items in the list. So ding!, create a method that takes in a Func<User, Boolean> and puts it in them thar where clause. Then you could easily use a lambda expression to create the Func. At first you might thing something like this:

private static IQueryable<User> GetUserList(Func<User, Boolean> whereClause)
{
  var query = from user in Users
            where whereClause(user)
            select user;

  return query;
}

public static IList<User> GetUserListByUserName(String userName)
{
  return GetUserList(currentUser => currentUser.UserName == userName).ToList();
}

AND YOU WOULD BE WRONG! I only know this because… eh… I saw a friend of mine try this and it failed. Fact is, the Linq where doesn’t take in a Func, but rather it expects and Expression. So no big deal right? Slap on an expression and go… except you can’t keep the same syntax. (Trust me, my… friend tried) Being the absolute genius that I am, I offered my friend a solution, and it’s slightly ugly:

private static IQueryable<User> GetUserList(Expression<Func<User, Boolean>> whereClause)
{
  var query = (from user in Users
            select user).Where(whereClause);

  return query;
}

Could be used like:

public static IList<User> GetUserList()
{
  return GetUserList(currentUser => true).ToList();
}

Or

public static IList<User> GetUserListByFirstName(String firstName)
{
  return GetUserList(currentUser => currentUser.FirstName == firstName).ToList();
}

Yeah, not the prettiest of things, but it is what it is. I’m not even sure this is useful yet. Still screwing around with it. Does cut down on code for easy queries.

AND NOW FOR THE ASSEMBLIES!

using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;

Sub Select and IN Clause With Linq

I have yet to find a good way to represent an IN clause in Linq, but I found this yesterday and kind of liked it. Mind you, I’ve used this only on two lists, not database involved. Will check what it does on the database call later.

Anyhow, I needed a way to check if the records in one list are the same as the other. I’m sure there are a billion ways to do this, but I wanted a Linq way. I stumbled onto this idea when looking for a solution to something else. Basically I have two lists of users and a user contains a UserID. listOne and listTwo are both List<User>.

var query = from listOneUser in listOne
            where
            !(
                from listTwoUser in listTwo
                select listTwoUser.UserID
            ).Contains(listOneUser.UserID)
              select listOneUser;

I select all the IDs from the second list and then see if the first list has any users that don’t exist in the second list. If this query gives me a list with a count greater then 0, I know that list one has at least one different item. Again, this isn’t bullet proof, just a way to show the kind of IN clause.

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.

Hashing and you

This is really simple, but don’t feel bad if you didn’t know about this. No one tells me nothin’ either.

The other day while reading through a blog, I got schooled without going to class. I had no idea that passwords should be one way only, as in you shouldn’t be able to retrieve a forgotten password, only reset it. Well shoot, I missed that one. So they start talking about hashing the password and saving that. Good thing I had built something to hash request items in a url to help stop people with screwing with a site url. Well ok, I didn’t totally build it. I got the idea from somewhere else. But I f-ing integrated it so don’t look at me like that.

Basically you take a password, add a salt (fancy name for a predetermined string or number) to the password, and get the hash value for that.

Why getting the same hash everytime sucks

Well the problem with hashing, or really the reason why we are doing this, is that the word “pass” creates the same hash value every time. Now if some sort of mean person figures out the hash for “pass” (That isn’t too hard since most people use some sort of standard like the .net MD5CryptoServiceProvider), he/she could search for a slew of typical password words. See the problem? Now enters the salt. The salt is some word that you come up with to add anywhere you want. This makes it a little difficult to figure out since the word “passSalt” is no longer like “pass”. one could try every word known and still fail because said person doesn’t know to add the word “Salt”.

Why getting the same hash everytime is great:

Right now you might be wonder what the point of having a password saved that can’t be unhashed to check against. Easy, you don’t have to unhash. Since the hash for “passSalt” will always be the same, the password in the database will always match the entered password + the salt. So basically the user enters the password, the system adds the salt to the password, the system then gets the hash, and finally checks that against the database record. Fun huh?

Now for the code:


public class HashString
{
 private const String DEFAULT_SALT = "8745";

 public static String CreateHash(String originalValue, String salt)
 {
   Byte[] computedHash;
   StringBuilder hashedValues;
   StringBuilder hashString;

   //Take the string and append your "secret" string at the end.
   hashString = new StringBuilder(originalValue);
   hashString.Append(salt);

   //Get the hash for the new word.
   computedHash = new MD5CryptoServiceProvider().ComputeHash(Encoding.UTF8.GetBytes(hashString.ToString()));
   hashedValues = new StringBuilder();

   //Go through computedHash and create a string from it.
   computedHash.ToList().ForEach(currentItem =>
ashedValues.Append(currentItem.ToString("x2")));

   return hashedValues.ToString();
 }

 //Not needed overload, just have it here for ease of use
 public static String CreateHash(String originalValue)
 {
   return CreateHash(originalValue, DEFAULT_SALT);
 }
}

And I even have a test for you… if you have VS Professional or higher. If not, no big deal. Just remove the asserts, attributes, and step through.


[TestClass]
public class HashStringTest
{
 private class UserTable
 {
   private const String SALT_VALUE = "SomeValue";
   private List table;

   public UserTable()
   {
     table = new List();
   }

   public void AddUser(String password, String userName)
   {
     table.Add(new UserRow(){Password = HashString.CreateHash(password, SALT_VALUE), UserName = userName});
   }

   public Boolean UserExists(String password, String userName)
   {
     String hashedPassword;

     hashedPassword = HashString.CreateHash(password, SALT_VALUE);

     var query = from user in table
                 where user.Password == hashedPassword && user.UserName == userName
                 select user;

     return query.ToList().Count == 1;
   }

   private class UserRow
   {
     public String Password { get; set; }
     public String UserName { get; set; }
   }
 }

 [TestMethod]
 public void CreateHash_PasswordMatchPass()
 {
   UserTable table;
   String userName;
   String goodPassword;
   String failedPassword;

   userName = "SomeUser";
   goodPassword = "goodPassword";

   table = new UserTable();
   table.AddUser(goodPassword, userName);
   Assert.IsTrue(table.UserExists(goodPassword, userName));

   failedPassword = "failedPassword";
   Assert.IsFalse(table.UserExists(userName, failedPassword));
 }
}

And last, the namespaces:


using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using Microsoft.VisualStudio.TestTools.UnitTesting;

For the record, I hate the word salt in this use.

Using the ForEach method on List Collections


public static StateCollection GetByName(String partialName)
{
 StateCollection returnValue;

 returnValue = new StateCollection();

  //baseList is some list I wasn't nice enough to show where it came from.
  //It's just a list of states.  Get over it.
 var stateList = from state in baseList
                 where state.Name.StartsWith(partialName)
                 select new State(state.Name, state.Code);

 stateList.ToList().ForEach(currentState => returnValue.Add(currentState));

 return returnValue;
}

So what is done here:

Basically I am using a linq expression to get states from a list of states (Like Michigan, Illinois, or Canada) based on name. No big deal. Then I take the query and produce a List from it. AMAZIN!


stateList.ToList().ForEach(curretState => returnValue.Add(curretState));

ForEach is an extension method for List<>. Now if you remember from previous posts, that means it resides in a static class somewhere that “tacks” it on to the List<> class. Basically this method acts like a typical foreach loop. (You know, go through the list and do something. Or nothing. I suppose you could just loop through if you wanted to. I won’t tell you how to live your life.) Simple but in my opinion, much cleaner looking.

I mean I could do this:


public static StateCollection GetByName(String partialName)
{
 StateCollection returnValue;

 returnValue = new StateCollection();

 foreach(State currentState in baseList)
 {
   if(currentState.Name.StartsWith(partialName)
   {
     returnValue.Add(currentState);
   }
 }

 return returnValue;
}

Really it’s just up to what you prefer. (And I’m sure you could drive a car with no power brakes. You’ll still get there.) Also, I really didn’t need the linq expression since I could have done this all with ForEach (Provided baseList is IEnumerable).

One last note, all IEnumerable collections have the ToList() method (And a bunch of other ones for that matter.)

Random Enumeration Generator with Generics


public static I RandomEnumeration<I>()
{
  I enumerationToCheck;
  Int32 indexToUse;
  String[] names;

  //Use activator to create an instance of the type I
  enumerationToCheck = System.Activator.CreateInstance<I>();

  //Make sure the instance is an Enumeration
   //Unfortunately you can't check that in the method 
   //delcaring using "which".
  if (enumerationToCheck as Enum == null)
  {
    throw new InvalidOperationException();
  }

  //Get the list of the enumeration item names
  names = Enum.GetNames(typeof(I));

  if (names.Length > 0)
  {
    //Grab a random name within the boundaries of the
     //names collection.
    indexToUse = RandomInt32(0, names.Length);
    //parse the name to create the random enum
    enumerationToCheck = (I)Enum.Parse(typeof(I), names[indexToUse]);
  }

  return enumerationToCheck;

}

Usage:


  SomeEnum test = RandomEnumeration();

Why bother? For unit testing and creating test classes. Possibly
for defaults on an enumeration, but not really needed since
they are value types. Oh yeah AND BECAUSE I FELT LIKE IT. I don’t
have to explain myself to you.

IEnumerable Extention Methods and Action

This may be slightly off, but I’ve pretty much figured them out and how they work with lambda expressions.

First off, Lambda expressions. These are the odd looking currentItem => expressions you might see in my examples. They are a little misleading, at least to me they were. When I saw:


 ilist.SomeExtension(currentItem => SomeMethod(currentItem));

I thought that meant:

Loop through the list of currentItems and use that method. Well that’s sort of it, but really misleading. In order to fully understand some of the more fun extension methods and lamba fun, a clearer explanation is needed. (I say fun instead of more complicated since I think the word “complicated” is exaggerating .)

What


 ilist.SomeExtension(currentItem => SomeMethod(currentItem));

really means is that I am going to call this method SomeExtension, give it a method to use, and that’s it. What it does with that method is the heart of what SomeExtension is.

Small note: currentItem => helps to infer the type of whatever it is that you’re going to pass into SomeMethod.

Say SomeExtension looks like this:


public static void SomeExtension(this IList<I> items, <I>, Action<I> action)
{
   SomeExtension(I item in items)
  {
    action(item);
  }
}

Now what is action? It’s basically a place holder for a method that returns nothing. Only thing it cares about is what it has to send in, and that is Type I. From there, it will call the method it points to and magic happens.
Small note: What the hell is items? Well that is the list that you called this method from. This is an example of an extension method. Extension methods, in short, allow a person to “tack” a method onto a class without changing the class itself. this IList<I> items tells me that the extension method SomeExtension will be “tacked” onto ANY IList.

In this instance, what action really looks like is this:


public void action
(
  delegate (I Item)
  {
    SomeMethod(item);
  }
)

As you can see, the SomeMethod from the original SomeExtension call comes into play now. The above examples really could be the List<> extention method of ForEach most likely looks like.

Now what might not look familiar there is the delegate key word. This is what’s called an anonymous method. Basically, this allows you to create delegates on the fly. An example of this would be List<>.Contains. A normal call to this might be:


someList.Contains(delegate(String currentItem){ return currentItem == someVariable); });

What this says is that contains will do whatever it does, but it will use the method you have provided to do that. Most likely the method itself looks like (And this is pseudo code for sure):


Boolean contains;

contains = false;

foreach(String currentItem in theList)
{
  contains = delegate(currentItem);

  if(contains)
  {
     exit;
  }
}

return contains;

Although, this is misleading in this post since this would deal with Func not Action.

Filling a list of classes with random values using linq

Filling a list of classes (10 for this example) with random values using linq.

Enumerable.Range(0, 10)
– This means give me a list from 1 to 10

Enumerable.Range(0, 10).Select
(
  j =>

– This means you are going to select every j in the list Enumerable created

Enumerable.Range(0, 10).Select
(
  j => new JunkItemB()

– For every J in the list, create a new junkItem

Enumerable.Range(0, 10).Select
(
  j => new JunkItemB()
  {
    SomeNumber = Enumerable.Range(0, 1).Select
    (
      i => randomGenerator.Next()
    ).ElementAt(0)
  }
)

– This is the new way to set a property in 3.5. I could just use a constructor, and probably should but this was just thrown together.

Enumerable.Range(0, 10).Select
(
  j => new JunkItemB()
  {
    SomeNumber = Enumerable.Range(0, 1).Select
    (
      i => randomGenerator.Next()
    ).ElementAt(0)
  }
)

– Once again, I am using Enumerable to create a list. This one will have 1 item. I will use Select to go through the list.For every i in the list, test (this is the Random object) will create a random number and give me a list of random numbers the size of the Enumerable.Range list.

Enumerable.Range(0, 10).Select
(
  j => new JunkItemB()
  {
    SomeNumber = Enumerable.Range(0, 1).Select
    (
      i => randomGenerator.Next()
    ).ElementAt(0)
 }
).ToList()

– I just want one random number, so I will get the number t the first index. Although with this, I only have on number in the list anyhow. The property of the current JunkItemB will be set to this. Once this is done, it will be repeated 9 more times.

Enumerable.Range(0, 10).Select
(
  j => new JunkItemB()
  {
    SomeNumber = Enumerable.Range(0, 1).Select
    (
      i => randomGenerator.Next()
    ).ElementAt(0)
 }
).ToList()
- Now that I have my list of 10 JunkItemBs, I will create a new list and from it giving me 10 JunkItemBs with preset SomeNumber properties.

Now that I look at this again (This is taken from notes I had somewhere else) I could have just used Random to get a number instead of Enumerator. Yay for over complicating things. Also my explanation of Select is a bit misleading for those who haven’t used lambda expressions. I’ll explain further in my next post.

Namespaces:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;