Saturday, October 11, 2008

I've moved

For those 3 people that have actually found this place, I moved to a new place. http://www.byatool.com

Friday, October 3, 2008

Fabulous Adventures in Reading

So on my new favoritest site ever for the week StackOverflow someone asked if this could be done in C#:
$patterns[0] = '/=C0/';
$patterns[1] = '/=E9/';
$patterns[2] = '/=C9/';


$replacements[0] = 'à';
$replacements[1] = 'é';
$replacements[2] = 'é';
return preg_replace($patterns, $replacements, $text);
I thought this could be an interesting challenge with Linq. And all things can be solved with Linq. Also, this post provides a valuable moral at the end.

So what the hell is that? Basically the idea is to take in some text, you know the stuff you send to people on your phone, and replace one set of characters with another. Make sense talk: TAKE TEXT! SMASH BAD THINGS! PUT GOOD THINGS IN!
String text;
List<Char> patternsToReplace;
List<Char> patternsToUse;

patternsToReplace = new List<Char>();
patternsToReplace.Add('a');
patternsToReplace.Add('c');
patternsToUse = new List<Char>();
patternsToUse.Add('X');
patternsToUse.Add('Z');

text = "This is a thing to replace stuff with";

var allAsAndCs = text.ToCharArray()
               .Select
               (
                 currentItem => patternsToReplace.Contains(currentItem)
                   ? patternsToUse[patternsToReplace.IndexOf(currentItem)]
                   : currentItem
               )
               .ToArray();
        
text = new String(allAsAndCs);
It's actually very simple. First convert the text into a character array. Then select through them one by one. If the list of ones to be replaced (patternsToReplace) just happens to have the current character, replace it with the corresponding one from the replacements (patternsToUse) otherwise just return the original.

Now the annoying thing about this example is that in preg_replace the two lists have no real correlation. It just assumes you want and index to index match. Therefore patternsToUse[0] replaces patternsToReplace[0]. But hey, I didn't invent the thing.

Another note is that instead of using Char[] I used List<Char> because arrays don't have index of and it saves the one step of charArray.ToList().IndexOf. I'm lazy and I like lists.

Now for the moral of the story:

'Course I dove right into Linq and responded... not reading that he/she needed a 2.0 solution and ultimately gave the client NOTHING THAT HE/SHE WANTED. So, if you take anything from this... and you probably won't... Always read the requirements first.

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

Wednesday, October 1, 2008

OrderBy using a Property Name

Now this is kind of dangerous to do since there is no compile time check (Like most things set in markup) but say you want to sort a collection, using the Linq extension methods, but you don't know what you what to sort on at any given time. On top of that, you have a datagrid and a bunch of sort expressions to deal with. Now you could do something like create a hashtable full of lambda expressions that the key is the sort expression:
Dictionary<String, Func<User, IComparable>> list;

userList = User.GetUserList();
list = new Dictionary<String, Func<User, IComparable>>();
list.Add("UserName", currentUser => currentUser.UserName);
list.Add("UserID", currentUser => currentUser.UserID);
userList.OrderBy(list["UserID"]);
Works just fine, and might be preferable to what I'm about to show. OooOoOO sound eerie?
//This is just to get the property info using reflection.  In order to get the value
//from a property dynamically, we need the property info from the class
public static PropertyInfo[] GetInfo<K>(K item) where K : class
{
  PropertyInfo[] propertyList;
  Type typeInfo;
        
  typeInfo = item.GetType();
  propertyList = typeInfo.GetProperties();
        
  return propertyList;
}

//This is the dynamic order by func that the OrderBy method needs to work
public static IComparable OrderByProperty<T>(String propertyName, T item)
  where T : class
{
  PropertyInfo[] propertyList;
        
  propertyList = GetInfo(item);

  //Here we get the value of that property of the passed in item and make sure
  //to type the object (Which is what GetValue returns) into an IComparable
  return (IComparable)propertyList.First(currentProperty
    => currentProperty.Name == propertyName).GetValue(item, null);
}
And use:
//This takes the current user and calls the OrderByProperty method which in turn
//gives us the Func OrderBy is requesting.
var test = userList.OrderBy(currentUser
  => DynamicPropertySort.OrderByProperty("UserID", currentUser)).ToList();
Ok so what the hell? I mean intellisense on the OrderBy method doesn't give much help. Func<<User, TKey>>. Yeah ok. So basically the return type is open. Well this kind of sucks right? Because I would have to return a Func that already knows the return type. (Be it string, int, ect) Of course, this would mean we would have to handle each sort expression in code. NOT VERY DYNAMIC IS IT? Well f that. Truth is, what the order by is looking for is a Func that takes in a User and returns something it can compare. This is where IComparable comes in. The OrderBy has to take the returned value, say UserID which is an int, and figure out how to compare it to another value. Pretty simple. So as long as the property you are ordering by uses IComparable, you're good to go. Pretty nice huh? Now I would suggest, if you use this (HAHAHAHA), is to cache a dictionary of the property info with the class type as the key so that you don't have to use as much reflection everytime. I just didn't put that in. U U USING

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

Tuesday, September 30, 2008

More Fun With Linq

Say you have a class named BannedProgram and it has a collection of DayOfWeek and a string ProcessName. Now the collection of DayOfWeek is basically a way to set the days of the week it's banned. With this you want to create a collection of these BannedPrograms, each with their own names and days they are banned. Simple, I know. Next you have a list of processes that are currently running and you want to get all the processes that match the names in the BannedPrograms list AND if the current day is a banned day. First you need the day checked function:

private static Func<DayOfWeek, Boolean> dayIsToday = 
  currentDay => currentDay == DateTime.Now.DayOfWeek;

Then you need the method to get the banned processes that are currently running:

private static Process[] GetBannedProcesses(BannedProgram[] programs, Process[] processes)
{
  var processList = from process in processes
  where
  (
    from program in programs
    where program.DaysBanned.Any(dayIsToday)
    select program.ProcessName
  ).Contains(process.ProcessName)
  select process;

  return processList.ToArray();
}
What this is doing: Well if you look at this:
from program in programs
where program.DaysBanned.Any(dayIsToday)
select program.ProcessName
This is going to grab any BannedProgram that has a DayOfWeek that matches today and it will select only it's name. This will give you a list of names of the BannedProcesses that can not be played today.
var processList = from process in processes
where
(
  from program in programs
  where program.DaysBanned.Any(dayIsToday)
  select program.ProcessName
).Contains(process.ProcessName)
This checks to see if any of the currently running processes have a name that matches a name in the banned program list. And now you have a list of processes to kill. Yay. Not sure this is a big deal, just thought it was a fun example of using linq and subselects. USING???
using System;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Windows.Forms;

More Useless info

Just in case you wanted to create something to kill a process, I have this little bit:
using System;
using System.Diagnostics;

Action<Process> killProcess = currentProcess => currentProcess.Kill();
Process[] processes;
String processToKill;

processToKill = "WAR";
processes = Process.GetProcesses();

processes.Select(currentProcess => currentProcess.ProcessName == processToKill)
.ToList()
.ForEach(killProcess);

I originally intended this as a service that would kill processes that were running on a specific day. IE To stop myself from playing games during the week. Problem was finding a way to stop me from killing the service. Now you can set a service to disallowing stopping it. The idea being that I would have another program that would stop it only if a password was enter correctly. (A certain woman would have this password) Trouble is, I can just open up the task manager and kill the process. Now I have to rely on self control. WHICH IS THE REASON WHY I WANTED THIS IN THE FIRST PLACE.

Tuesday, September 9, 2008

Combining Lambda Expressions

Found this post here but wanted to make a really simple example to demonstrate this. The idea is simple, take something like this:
currentItem => currentItem.BooleanMethodOne() && currentItem.BooleanMethodTwo()
but say you only want to have one clause or both. Well you could make three separate expressions, but what if you wanted to add even more later? What if you wanted to mix and match? What if you're reading thing because you watched to see what page could possibly be on the last page of a google search? Well I have answers... stolen answers. First the needed And and Or methods:

public static Expression<Func<T, Boolean>> And<T>(
   Expression<Func<T, Boolean>> expressionOne,
    Expression<Func<T, Boolean>> expressionTwo
)
{
  //Basically this is like a bridge between the two expressions.  It will take the T
  //parameter from expressionOne and apply it to expression two. So if 
  // oneItem => oneItem.OneMethod() is expressionOne
  // twoItem => twoItem.TwoMethod() is expressionTwo
  //it would be like replacing the twoItem with the oneItem so that they now point
  //to the same thing.
  var invokedSecond = Expression.Invoke(expressionTwo, expressionOne.Parameters.Cast<Expression>());
  
  //Now this is to create the needed expresions to return.  It will take both early expressions
  //and use the item from the first expression in both.
                    
  //It will look something like this:
  //currentItem => (currentItem.OneMethod And Invoke(currentItem => currentItem.TwoMethod()))
  //As you can see, it looks to be running expressionOne and then a new method that basically
  //calls expressionTwo with the same value (currentItem)
  return Expression.Lambda<Func<T, Boolean>>(
   Expression.And(expressionOne.Body, invokedSecond), expressionOne.Parameters
  );
}

public static Expression<Func<T, Boolean>> Or<T>(
Expression<Func<T, Boolean>> expressionOne, 
Expression<Func<T, Boolean>> expressionTwo
)
{
  var invokedSecond = Expression.Invoke(expressionTwo, expressionOne.Parameters.Cast<Expression>());

  return Expression.Lambda<Func<T, Boolean>>(
   Expression.Or(expressionOne.Body, invokedSecond), expressionOne.Parameters
  );
}
And here's a test for it:
String[] list;
  
list = new String[] { "a", "b", "c", "ac", "ab", "cc", "d", "dd", "dc" };

Expression<Func<String, Boolean>> stringLikeA = currentString => currentString.Contains("a");
Expression<Func<String, Boolean>> stringLikeB = currentString => currentString.Contains("b");
Expression<Func<String, Boolean>> stringLikeC = currentString => currentString.Contains("c");

Expression<Func<String, Boolean>> neededUser = And<String>(stringLikeA, stringLikeB);
list.Where(neededUser.Compile());

//a
Assert.IsTrue(list.Where(neededUser.Compile()).Count() == 1);  //ab

//a, c, ac, ab, cc, dc
neededUser = Or<String>(stringLikeA, stringLikeC);

Assert.IsTrue(list.Where(neededUser.Compile()).Count() == 6);

//ab, c, ac, cc, dc
neededUser = And<String>(stringLikeA, stringLikeB);
neededUser = Or<String>(neededUser, stringLikeC);
Assert.IsTrue(list.Where(neededUser.Compile()).Count() == 5);
USINGS!!ONEONE
using System;
using System.Linq;
using System.Linq.Expressions;
using Microsoft.VisualStudio.TestTools.UnitTesting;

Monday, September 8, 2008

FIzzBuzz with Linq extension methods

So if you haven't heard of the FizzBuzz test, it's basically taking in a list of numbers and figuring out if they are divisible, cleanly, by two numbers. Say you have 3 and 5 and this is your list:

1
3
5
10
15

If the number is divisible by 3, then return the Fizz string. If the number is divisible by 5, return a Buzz string. If it's divisible by both, then return FizzBuzz.

1
Fizz
Buzz
Buzz
FizzBuzz
Pretty simple and in actuality pretty easy to do with old C# tools, but I wanted to do this with Linq. With the use of Funcs, Actions, and Linq extension methods it can be done fairly easily. Technically you can do the whole thing in one line if you don't want to bother with refactoring.

I have no idea how to format this cleanly, so sorry if the format is confusing. Basically it is take a list, get the ones you want, concatenate it with the next list.
public static IList<KeyValuePair<Int32, String>> ConvertListOfIntegersWithLinqMethods(IList<Int32> listToConvert, Int32 fizzNumber, Int32 buzzNumber)
{
var result =
  listToConvert
    .Where(WhereBothDivisible(fizzNumber, buzzNumber))
    .Select(selectKeyValuePair("FizzBuzz"))
    .Concat(
  listToConvert
    .Where(WhereBuzzDivisable(fizzNumber, buzzNumber))
    .Select(selectKeyValuePair("Buzz")))
    .Concat(
  listToConvert
    .Where(WhereFizzDivisable(fizzNumber, buzzNumber))
    .Select(selectKeyValuePair("Fizz")))
    .Concat(
  listToConvert
    .Where(WhereNeitherDivisable(fizzNumber, buzzNumber))
    .Select(selectKeyValuePair("Nothing")));

 return result.ToList().OrderBy(currentItem => currentItem.Key).ToList();                
}
Using these:
private static Func<Int32, KeyValuePair<Int32, String>> selectKeyValuePair(String value)
{
 return currentItem => new KeyValuePair<Int32, String>(currentItem, value);
}
          
private static Func<Int32, Boolean> WhereBothDivisible(Int32 fizzNumber, Int32 buzzNumber)
{           
 return  currentItem => IsDivisible(currentItem, fizzNumber) && IsDivisible(currentItem, buzzNumber);
}

private static Func<Int32, Boolean> WhereFizzDivisable(Int32 fizzNumber, Int32 buzzNumber)
{
 return currentItem => IsDivisible(currentItem, fizzNumber) && !IsDivisible(currentItem, buzzNumber);
}

private static Func<Int32, Boolean> WhereBuzzDivisable(Int32 fizzNumber, Int32 buzzNumber)
{
 return currentItem => !IsDivisible(currentItem, fizzNumber) && IsDivisible(currentItem, buzzNumber);
}

 private static Func<Int32, Boolean> WhereNeitherDivisable(Int32 fizzNumber, Int32 buzzNumber)
{
 return currentItem => !IsDivisible(currentItem, fizzNumber) && !IsDivisible(currentItem, buzzNumber);
}

Tuesday, September 2, 2008

Beyond the wall

So I never gave a solution to this problem and thought I might do that real fast. If you recall, this was the main sticking point of creating a Func for a select clause:
Func<User, EHH??> selectUserID = currentUser =>  new { currentUser.ID, currentUser.UserName };
Well there is no one solution to this, but there is an easy and clean solution:
 public class UserQueryItem
 {
   public UserQueryItem ( Int32 userID, String userName )
   {
      UserID = userID;
      UserName = userName;
   }

   public Int32 UserID { get; set; }
   public String UserName { get; set; }
 }
Create a class to hold the information.
 Func<User, UserQueryItem> selectUserID = currentUser =>  new UserQueryItem { UserID = currentUser.ID, UserName = currentUser.UserName };
Or

 Func<User, UserQueryItem> selectUserID = currentUser =>  new UserQueryItem (currentUser.ID, currentUser.UserName);
Pretty simple, just a little more work.

Friday, August 29, 2008

DID U NO?!?!!111

So maybe I'm slow, but it just dawned on me that:
 SomeClass class = new SomeClass() { SomeProperty = "" };
Is the same as:
 SomeClass class = new SomeClass { SomeProperty = "" };
What?? Look closely. The "new SomeClass" no longer needs the () if you are using 3.0's property initializers. Not ground breaking, but interesting.

And now for Contravariance

Take the classes in the last post (First, Second, Third) and assume they are exactly the same in this example. In Covariance, we learned that whatever variable to you set equal to the return of a method has to be equal in type of larger. Or in other words, it has to have equal or less functionality.
  Second second = ReturnThird();  //OK since second has less functionality

  Third third = ReturnSecond(); //BAD since third has more functionality
Now I think you can guess what Contravariance is, but if you can't it's ok. Most likely you're a tool just like me. Contravariance is the movement from small to large meaning that the type must be equal to or larger than. Following the "in other words" manor, it has to have equal or more functionality. Now small note before I go on, saying that it has to have more/less functionality can be somewhat dangerous. After all, Third could inherit from Second and add no functionality, but I find this is an easier way to think of it. I suppose another way of thinking of it is that with Covariance the return type has to have equal or more knowledge. Meaning, Second has full knowledge of what First is, but Second has no idea what Third is. Anywho, onto some examples. Say we take the FillX methods and add something to it.
  private void FillFirst(First firstToFill)
  {
    firstToFill.FirstOutput = "";
  }

  private void FillSecond(Second secondToFill)
  {
    secondToFill.SecondOutput = "";
  }

  private void FillThird(Third thirdToFill)
  {
    thirdToFill.ThirdOutput = "";
  }
Right off the bat you might notice that if methods allowed Covariance with parameters, you'd be in trouble. After all, if FillThird allowed parameter covariance, you could pass in a First object. What what that object do with ThirdOutPut? As things are, you would have a bad day. Lucky for you, at least if you aren't adamant about wanting Covariance in parameters, this can't happen. Well shoot, I just gave away the fun of this post. Oh well, I'll keep going in case you just have more time.
  Action<First> fillFirstAction = FillFirst;
  //No problems here since FillFirst expects a First
    
  Action<Second> fillSecondAction = FillFirst;
  //Still no problems although this may look odd.  But remember, FillFirst
  //just needs an object that : First, it doesn't care if the object
  //has more functionality than first.
  //
  //The FillFirst method uses the FirstOutput property and by inheritance
  //the Second being passed in has said property
    
  Action<Second> fillThirdAction = FillThird;
  //Not gonna happen.  The FillThird expects a third or smaller object.  Since
  //Third : Second, third is smaller than second.  Implications?  Look in the 
  //FillThirdMethod
  //
  //The method expects the object to have the ThirdOutput property which means
  //Second has to inherit from Third.  We know this to be untrue.
So basically Contravariance is used with parameters in methods to guarantee the object being passed in has at least the functionality used within the method. Apparently there was a problem in the lobby so there will be no refreshments served tonight.

Thursday, August 28, 2008

Covariance versus Contravariance

Ok so I stumbled on to this subject the other day and thought it was worth noting. Take these simple classes:
public class First
{
  public String FirstOutput { get; set; }
}

public class Second : First
{
  public String SecondOutput { get; set; }
}

public class Third : Second
{
  public String ThirdOutput { get; set; }
}
So from this you can see that Third inherits Second which in turns inherits First. By terminology this would mean that Third is "smaller" than Second and First is "larger" than both. Here's an example of Covariance:
public class Covariance
{
  public Covariance()
  {
    
      Func<First> returnFirstFunc = ReturnFirst;
      //This works since the Func has a return type of First
    

      Func<Second> returnSecondFunc = ReturnThird;
      Second secondTest = returnSecondFunc();
      secondTest.FirstOutput = "First";
      secondTest.SecondOutput = "First";
      //This works since the Func has a return type of Third which is smaller
       //that Second.  Therefore anyone using this Func will expect a Second to
       //be returned and will only use the methods/properties that a Second object
       //would have.  Methods/Properties that Third has by inheritance.


      Func<Third> returnThirdFunc = ReturnSecond;
      //THIS WILL NOT WORK
       //Due to Covariance, the return of the method must be equal or smaller
       //that the expected type.  returnThirdFunc expects a Third or smaller object
       //but the ReturnSecond method returns a Second which is not smaller than Third.
       //Afterall, Third : Second
       //
       //Third thirdTest = returnThirdFunc();
       //Is the same as:
       //Third thirdTest = new Second();
  }

  private First ReturnFirst()
  {
      return new First();
  }

  private Second ReturnSecond()
  {
      return new Second();
  }

  private Third ReturnThird()
  {
      return new Third();
  }
}
Basically what this all means is that with return types, the return type must be smaller or equal to the field it's being set to. When you are dealing with Funcs, the return type must be smaller or equal to the return type for the method it's being set it. Why is that? Well think of it like this: It's your first day on the job and some guy tells you to write something with whatever returnFirstFunc() returns. Now you have no way to look at the code, so you can only know that it returns First. For all you know, it could return First, Second, or Third. So you would do this:
First someFirst;

someFirst = returnFirstFunc();  //Could return anything smaller than First
someFirst.FirstOutput;  //Completely legal and safe
But would you do this?
someFirst.ThirdOutput;
Of course not since you only can assume it is a First. Now let's do this in reverse. Say from the above example you were allowed to do this:
Func<Third> returnThirdFunc = ReturnSecond;
Could you do this?
Third third;

third = returnThirdFunc();
third.ThirdOutput;
Yeah you can't since the Second type doesn't have the ThirdOutput property. In short Covariance is the allowance of Smaller types or equal. If a method returns back Third, then you can use that method for anything that is Third or Smaller (Second, First, Object) but not for something Larger (Fourth, Fifth, ect).

Tuesday, August 26, 2008

And then you hit the wall.

So as this dynamic nonsense continues, there is a sticking point to how much fun I can have. The wall? Anonymous types and generic declarations.

Here's the old:
  Func<User, Int32> selectUserID = currentUser => currentUser.UserID;
Great if I want to select userIDs, but what if I want UserIDs AND UserNames... Easy right?
 userList.Select(currentUser => new { currentUser.ID, currentUser.UserName });
Now this is the old way, but I want the new way... IE the Func way. Problem is here
  Func<User, EHH??> selectUserID = currentUser =>  new { currentUser.ID, currentUser.UserName };
You see, there's a problem. What the hell do I put at the return type? Fact is, without creating a method that passes back a Func or a class that has UserName and UserID properties, I'm screwed. Now from what I read here I think I get it. First take the func:
  Func<K, T>
I have K and T that the compiler has to figure out what they are. Well it's safe to say in the example User is K, but what is T? Well it has to figure that out from the Lamdba expression. The lambda expression has no idea what it is because it's an anonymous type. So why not just use var?
  Func<User, var>
Seems easy enough. I don't have to know the type because of var right? Wellll problem is the compiler is looking at the lambda expression to figure out what var will be. Mr. Lambda expression can't really figure out the type either. Enter the wall. Currently there is no way around this without methods or classes created. Supposedly there are things called Mumble Types on the way that will solve this problem.

When is a field not a field?

Ok so for the last few things I've been showing a more dynamic approach to linq queries , mostly dealing with collections rather than say linq to sql. Now take the new method:
public List<K> SelectFromUserList<K, L>(Func<User, K> selectMethod, Func<User, L> orderBy, List<User> userList)
{
    List<K> userList = new List<K>();
    userList = userList.OrderBy(orderBy).Select(selectMethod).ToList();

    return userList;
}
and the call was this:
  List<String> newList = userList.Select(selectUser => selectUser.Name, orderUser => orderUser.ID, userList);
Let's say you have two needs, selecting all the userNames and all the IDs. You could go ahead and call that method twice and inserting the lambda expressions. But let's say you want to be able to mix and match things. Say select user names and order by user id or maybe select user names and order by use names. Well there's a solution to avoid rewriting the lambda expressions:
  Func<User, Int32> selectUserID = currentUser => currentUser.UserID;
  Func<User, String>selectUserName = currentUser => currentUser.UserName;

  Func<User, Int32> orderByUserID = currentUser => currentUser.UserID;
  Func<User, String> orderByUserName = currentUser => currentUser.UserName;
What the? See a while ago I had a method to pass back the expression, but in this case there's nothing to create the expression from (a passed in parameter) since they are really simple expressions. How would I use them?

  List<Int32> userIDs;
  List<User> userList;
  List<String> userNames;
  userIDs = SelectFromUserList(selectUserID, orderByUserID, userList);
  userNames = SelectFromUserList(selectUserName, orderByUserID, userList);
Pretty nice huh?

Monday, August 25, 2008

Adding to the Select

So in the last post there was something like this:
 public List<K> SelectUserNameList<K>(Func<User, K> selectMethod, List<User> userList)
 {
   return userList.Select(selectMethod, userList).ToList();
 }
Called by this:
 List<String> newList = userList.Select(user => user.Name, userList);
Ok so what if you want to order something? Well same idea, just another Func. But remember, a Func that can order by any type. If you look at the OrderBy method, it expects a Func<User, L> where L is just some type you are returning. If you were ordering by UserID, well that would be an integer. Problem is, like select, you don't want to be held down by a specific type.
 public List<K> SelectFromUserList<K, L>(Func<User, K> selectMethod, Func<User, L> orderBy, List<User> userList)
 {
   List<K> userList = new List<K>();

   userList = userList.OrderBy(orderBy).Select(selectMethod).ToList();

   return userList;
 }
And the new call would be:
 List<String> newList = userList.Select(selectUser => selectUser.Name, orderUser => orderUser.ID, userList);
Now something of note is the order in which you call the methods. Remember, x.OrderBy().Select() is saying take collection X, order it by L and create a new collection of X, then select whatever you want. You can not do the reverse. Say you want to select a list of UserNames ordered by UserName. Well you can either:

1) Order the list by user name in a list of users then select the user names.

2) Select a list of user names into a list of strings, order that list by a string.

What if you want to select user names but order by user id? You can:

1) Order the list by user id and create a list of users then select the user names.

2) Select a list of user names into a list of string and... eh LOSE

Best part about:
 userList = userList.Select(selectMethod).OrderBy(orderBy).ToList();
Is that the error is somewhat misleading. It gives you the "Cannot be inferred by usage" error, not the "Idiot, you can't order a list of Strings by UserID". So you have to be careful on how you have things in order.

Friday, August 22, 2008

Speaking of Select

So like Where and other fine Extension methods, Select allows you to either give it a lambda expression like so:
  List<String> newList = userList.Select(user => user.Name);
Or
  List<Int32> newList = userList.Select(user => user.ID);
So either you get a list of Names or IDs. What the hell do you care? Well if you are capable of breathing, you should also notice that one list is a list of strings the other a list of integers. What if you wanted a generic select method? Well for starters you would do something like this:
public List<String> SelectFromUserList(Func<User, String> selectMethod, List<User> userList)
{
  return userList.Select(selectMethod).ToList();
}
Where the select method for a user name would be something like this:
  List<String> nameList = SelectFromUserList(currentUser => currentUser.UserName, userList);
Sweet... oh wait, that only works if I want a list strings. Great if I wanted LastName, FirstName, ect but sucks if I wanted an integer ID.
  List<String> nameList = SelectFromUserList(currentUser => currentUser.UserID, userList); //BOOM
But wait, you can do that!
public List<K> SelectUserNameList<K>(Func<User, K> selectMethod, List<User> userList)
{
  return userList.Select(selectMethod).ToList();
}
Aw snap, now I can get a list of anything I want, well at least a one type, one dimensional array. By the way, this is the first step in probably a series of posts that will end up with a much cleaner way of doing this.

Linq query versus just a Select

Something I ran into using the Ajax.dll and AjaxMethods (Or basically the idea of being able to call a method from .cs file in javascript) is that when returning a list of Users there was difficulty in serialization. Basically, if you have a list of users that contain a list of roles that contain a list of permissions that contain seven wives with seven children with seven dogs and seven cats... Basically a lot of information. Now lazy loading should take care of this, but lets assume there is no lazy loading.(No idea what would cause that...) Well you have an awful lot to pushout to the front end. Let's just say it can be a little sluggish. Lets assume you are just sending the list out, and you've already done all the querying. You could do:
 return userList;
Which is what I was doing. Kind of slow. You could do:
 var query = from user in userList
             select new
             {
                UserName = user.UserName,
                UserID = user.ID
             };

 return query.ToList();
Nothing wrong with that, just a bit verbose for something so simple. You could do this:
 return userList.Select(currentItem => new { Username = currentItem.UserName, UserID = user.ID });
All in one line. Now I personally like the sql-ish linq expressions, but for this why not fit it into one line?

Union to find if two lists match

So let's say you have two lists you want to compare to see if they hold the same items, but the items are not equal reference. Now, if you are comparing two lists that have unique values to compare, Union is perfect.

List 1 { 1, 2, 3, 4, 5 }
List 2 { 2, 1, 4, 3, 5 }

As you can see, there are no repeated values in these two lists. Easy way to figure out if all the values are the same in the two lists:
  var query = (from first in firstList
            select first).Union(from second in secondlist
                                select second);

  Assert.IsTrue(query.Count() == first.Count());
Why does this work? Union combine the two lists, removing any duplicates. So if everything goes correctly, the count of the new list has to match the count of either of the olds lists. After all 5 pairs of duplicate items gets reduced to a list of 5. Now, if there is anything different between the lists the count will get screwed. Why? Because even one difference will cause an extra item to show up in the list.

List 1 { 1, 2, 3, 4, 5 }
List 2 { 1, 2, 3, 4, 6 }
Union { 1, 2, 3, 4 , 5, 6 }

And it will only get worse for every mismatch.

Real worldish example:
    var query = (from user in userListFirst
              select user.UserID).Union(from secondUser in userListSecond
                                       select second.UserID);

    Assert.IsTrue(query.Count() == userListFirst.Count());
Bonus points if you can figure out why this would fail at times. Actually, I already told you...

UsInGS
  using System;
  using System.Linq;

Tuesday, August 19, 2008

Life is fun when you are slow

public void IfTrueRunMethod(Func<Boolean> trueMethod, Action action)
{
  if(trueMethod())
  {
    action();
  }
}
Just something I made for the hell of it to remove:
if(someClass != null && someClass.Property == "hi")
{
  SomeMethod();
}
This can be reduced to one line... yay!
IfTrueRunMethod(() => { someClass != null && someClass.Property == "hi" }, () => SomeMethod());
You could even transform the first part into a method if you want:
IfTrueRunMethod(() => TrueMethod(someClass), () => SomeMethod());
Weeeee!
using System;
using System.Linq;

Thursday, August 14, 2008

Another silly method just for you

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;

Tuesday, August 12, 2008

You can do that in Javascript? Part 2

Creating divs on the fly and assigning methods: As I have been working with Script Controls lately, I've been forces to learn more about javascript.... yeah I know, bleh. However, in my learnin' I've actually been forced to like Javascript.... yeah I know, bleh. Well one this I was doing was tranfering a front end control to a Script Control. Basically I am building an Auto Complete control that is using the Ajax.dll AjaxMethod stuff. Thus skipping the need for web services that the Ajax Control AutoComplete needs. Anyhow, the reason I am saying this is that it gets a list of Users and dynamically creates a list of divs that change color when hovered over and fill in a textbox when selected. Originally I was doing this by creating the html needed, then appending the innerHTML property on the container div.
function buildSelectableDiv(currentCount, innerText, textboxName, parentDiv)
{
   var defaultClass;
   var divChild;
   var divToAdd;
   var picker;

   //create the parent div
   divToAdd = document.createElement('div');
   //set the id of the div
   divToAdd.setAttribute('name', 'divNames' + currentCount);

   //Create child div
   divChild = document.createElement('div');
   //getting the child ready
   divChild.setAttribute('name', 'divNamesChild' + currentCount);

   //Add child to new parent
   divToAdd.appendChild(divChild);

   return divToAdd;
}
And there you go. Creating a div and adding div to it.

You can do that in Javascript?

So found out yesterday that anonymous methods exist in javascript. Who knew?
 divToAdd.onmouseover = function() { picker.changeStyles(divToAdd, true); };
Where picker.changeStyles is a method on a class. Javascript is starting to grow on me.

Thursday, July 24, 2008

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;

Tuesday, July 22, 2008

Like versus Contains

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.

Friday, July 18, 2008

Backtrack

Couple posts ago I said "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." when I was talking about how to create an order by expression. I thought about it more, and that doesn't make sense as far as the sql goes. What I was saying would mean it would get the list of strings and sort based on them. What I think actually happens is it takes the Expression (Hense the name) and derives the order by from the epression. Say I want tell the thing I will want to sort by user.UserName, it will take that expression and translate it into ORDER BY someAlias.UserName. Magic. I would like to know how it does this. Reflection and a ton of it I would assume.

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;

Thursday, July 17, 2008

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;

Quick Linq thing... String to Number String

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;

Monday, July 14, 2008

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.

Thursday, July 10, 2008

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.

Wednesday, July 9, 2008

Sub Select and IN Clause faking

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.

Joining By Anonymous Types

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.

Monday, July 7, 2008

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.

Tuesday, July 1, 2008

Filling a Private Field on a Base Class

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.