Convert Enum to Dictionary: Another Silly Method

So what if you want the names and values from an Enum, but wanted them in dictionary form. Well shoot, a little bit of linq and little bit of that and you got this:

public static IDictionary<String, Int32> ConvertEnumToDictionary<K>()
{
 if (typeof(K).BaseType != typeof(Enum))
 {
   throw new InvalidCastException();
 }

 return Enum.GetValues(typeof(K)).Cast<Int32>().ToDictionary(currentItem => Enum.GetName(typeof(K), currentItem));
}

As you might see, pretty simple.

Ok so ToDictionary is kind of odd looking maybe, but really isn’t that big of a deal. Basically it assumes the items in the list are the value, but you need to tell it what the key is. In this case, the int values for the enum are the value for the dictionary where the name that matches said int value will become the key for the dictionary.

So basically, get the values for the enum. Turn that into an IEnumerable list of Int32, create a Dictionary from that.

USINGS!!111

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

Yeah SessionTryParse

So I got tired of seeing If Session[“SomeKey”] != null… blah blah blah and thought it would be a semi worthwhile task to create a TryParse method because I’m bad like that. Not a Bad Enough Dude to Save the President, but bad.

 public static Boolean SessionTryParse<K&gt;(HttpSessionState session, String key, out K itemToSet) where K : class
 {
     itemToSet = null;

     if (session[key] != null)
     {
        itemToSet = session[key] as K;
     }

     return itemToSet != null;
 }

And for structures… which I have to cheat and only allow them to be nullable.

public static Boolean SessionTryParse<K>(HttpSessionState session, String key, out K? itemToSet) where K : struct
{
     itemToSet = null;

     if (session[key] != null && session[key] is K)
     {
        itemToSet = (K)session[key];
     }

     return itemToSet != null;
}

The idea is simple, pull in the Session, the needed Session key, and something to throw the value in. After that, just check to see if the Session + Key is null and if Session + Key is the same type of said something. That’s how it’s done Detroit greater metropolitan area style… punk.

USE THIS:

   using System;
   using System.Web.SessionState;

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.

I’m starting to worry about myself

So the “dynamic” linq query so far isn’t just enough to stop. Oh no, now that I can have methods pass back expressions, what about a dictionary of order by expressions to allow an even more dynamic feel? Huh? How’s about that kids? I hate myself too.

//Enum created for the dictionary key
public enum OrderByChoice
{
  FirstName,
  LastName,
  UserName
}

//dictionary of expressions
private static Dictionary<OrderByChoice, Expression<Func<User, String>>>  GetOrderByList()
{
  if(orderByList == null)
  {
    orderByList = new Dictionary<OrderByChoice,Expression<Func<User, String>>>();

    orderByList.Add(OrderByChoice.FirstName, currentUser => currentUser.FirstName);
    orderByList.Add(OrderByChoice.LastName, currentUser => currentUser.LastName);
    orderByList.Add(OrderByChoice.UserName, currentUser => currentUser.UserName);
  }

  return orderByList;
}

That’s right, I know. Silly, but I think it’s cool. Now mind you, I could have methods that return expressions instead of the expressions themselves, but I wanted to show the expressions.

And for the method call:

public static IList<User> GetUserList(OrderByChoice orderBy)
{
  return GetUserList(currentUser => true, GetOrderByList()[orderBy]).ToList();
}

And now you have an even more dynamicish call.

I FORGOT THE USINGS!!!!

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

And some days I love programming

This is the newest edition of Linq madness. So I added an OrderBy to my lame dynamic query thing.

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

    return query;
}

Now you will notice there is a new Expression in town and it’s name isn’t Reggie Hammond. It is my order by Expression which uses a Func<User, String>. It took me a minute to figure out how this works. I thought it was somehow in need of the property name to order by, but in reality it is looking for a list of strings to order by. Simple. I could do something like: (Ignore the WhereLikeFirstNameLastNameUserName for now)

    return GetUserList
           (
            WhereLikeFirstNameLastNameUserName(name),
            currentUser => currentUser.UserName
           ).ToList();

But that’s boring. I want to be able to pass a method that would give the correct string to orderby somewhat cleaner. In comes a method that returns an Expression. OooOoOOo.

private static Expression<Func<User, String>> SortOnUserName()
{
    return currentUser => currentUser.UserName;
}

So now it looks like:

public static IList<User> GetUserListByLikeName(String name)
{
   return GetUserList
          (
           WhereLikeFirstNameLastNameUserName(name),
           SortOnUserName()
          ).ToList();
}

Cleaner… Now what is WhereLikeFirstNameLastNameUserName? Simple, that is my where Expression just being returned in this method:

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 + "%");
}

By the way, SqlMethods.Like is just a built in method used only with Linq to Sql. Probably shouldn’t have used it in this example but oh well. Live with it.

OH NO NOT THE USINGS!!

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

Convert a String to a Number String With Linq… YAY

Really stupid little thing I came up with today… but I wanted to use Linq to strip any non number from a string and return the string with only numbers. I told you this was a stupid little thing.

public static String CreateNumberOnlyString(String textToCheck)
{
  String returnText;

  var queryForIntegers = from currentChar in textToCheck
                         where Char.IsNumber(currentChar)
                         select currentChar;

  returnText = new String(queryForIntegers.ToArray());

  return returnText;
}

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;

I ain’t gettin’ paid enough for this…

Remember when I said I’m not exactly great with programming terms? Well if I didn’t, I am saying it now. So I saw the word “closures” today and had no idea what this was. All excited about something new, I found out that closures is just another word for anonymous methods, although it may include stuff outside that scope but I’m not sure. Anyhow, although this seemed to be yet another attack of the stupid I stumbled across something here. Basically what caught me is how value types are handled with Funcs. Take this method:

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

public static Func<Int32> ReturnIntegerWithinFuncReturningMethod(WhichMethod methodToReturn)
{
  Int32 integerToIncrement;
  Func<Int32> returnMethod;

  integerToIncrement = 0;
  returnMethod = null;

  switch(methodToReturn)
  {
  case WhichMethod.AddOne:
   returnMethod = new Func<Int32>(() => { return integerToIncrement += 1;} );
   break;
  case WhichMethod.AddTwo:
   returnMethod = new Func<Int32>(() => { return integerToIncrement += 2; });
   break;
}

 return returnMethod;
}

Let’s say we test it like this:

Func<Int32> returnedMethod;
Int32 integerToCheck;

returnedMethod = ReturnIntegerWithinFuncReturningMethod(WhichMethod.AddOne);
integerToCheck = returnedMethod();
Assert.IsTrue(integerToCheck == 1, "Actual value is:" + integerToCheck.ToString());

integerToCheck = returnedMethod();
Assert.IsTrue(integerToCheck == 2, "Actual value is:" + integerToCheck.ToString());

These both pass. How does that make sense? You would think that it would return 1 both times since from first glance integerToIncrement lives outside the actual Func that is returned. You would think from this that Int32 is a reference type. When a value type is “attached” to a Func like this one is, apparently it keeps a reference to it and therefore the original Int32 is updated every time the Func is called. Something to remember.

Guard Clause Method

So I was introduced to the idea of a “guard clause” in methods when I started my latest job. The idea is to make sure that all the passed in parameters of a method are, for example, not null. If they are, just throw an exception. This is what I have been doing:

if(someField == null)
{
throw new ArgumentNullException();
}

Well just recently I was somewhat schooled in the idea of removing if statements and creating simple methods in their steed. Now this isn’t always a need, but in complex (ie annoying) nested ifs, it might help to clean things up. So in light of this, I came up with this method:

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

private void ThrowExceptionIfNull<TException, TObject>(TObject objectToCheck, String message)
where TException : Exception 
where TObject : class
{
  if(objectToCheck == null)
  {
      TException exception;

      exception = Activator.CreateInstance<TException>();
      //Set the message field on System.Exception since the property is Get only
      if(message != null)
      {
          List<FieldInfo> fieldInfoList;
           FieldInfo neededInfo;

          fieldInfoList = new List<FieldInfo>(typeof(Exception).GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public));
          neededInfo = fieldInfoList.Find(currentItem => String.Compare(currentItem.Name, "_message") == 0);
          //make sure that the message field is still called _message, otherwise
           //forget the message.
           if(neededInfo != null)
          {
              neededInfo.SetValue(exception, message);
          }
      }
      throw exception;
  }
}

And the use:

ThrowExceptionIfNull<ArgumentNullException, String>(someParameter, "someParameter");

Couple things to keep in mind:

  • This uses reflection to find the message field since there is no set accessor to the Message property. This could be dangerous if Microsoft decides to rename the _message field.
  • The use of reflection would usually include the caching of the field info since you don’t want to keep using reflection for the same class every time. In this case, you’re throwing an exception so everything is done anyhow. The cost advantage of a cache is pointless.

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.