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.