Ajax Webmethods, Javascript, and Anonymous Types… Booyah

As witnessed in this super awesome post I showed how to use a webmethod to get server side information with client side methods. (I know, I’m pretty sweet.) And in this one I had an example of filling a drop down list with a web method and javascript, though it was more about the anonymous method used. So what do I have now? Well a little thing about why I heart anonymous types.

What’s an anonymous type? Well it’s a type that built at compile time and requires no class file to create, but you probably have already used them if you’ve used Linq:

    var anonymous = from item in list
                    select new {
                                 Name = item.Name,
                                 Address = item.Address
                                };

And now you have a whole list of a new type that is created at compile time. Anyways, you might have been wondering why you would want these beyond linq use. Well that’s what I’m here for… that and making sure I give you a low point in your day so that things can only get better.

Now in the example from before, it was basically the idea of filling a drop down list without a postback and using a WebMethod. Now I showed the javascript needed, but I didn’t show you the web method itself.
Time to start!

        [System.Web.Services.WebMethod]
        [System.Web.Script.Services.ScriptMethod]
        public static Object GetUserList()
        {
            IList <User>userList;

            userList = LinqData.DataClasses.User
                           .GetUserList("");
            return userList
                      .Select(item => new { item.UserName, item.UserID })
                      .ToList();
        }

So there you have a method that gets some users (Waring: Actual method may vary) and you are creating a list of anonymous types that have UserName and UserID.

Now you may have noticed this:

    .Select(item => new { item.UserName, item.UserID })

Now why would I want to do that? Why can’t I just send a list of users? Well there’s nothing really stopping you from doing that, after all javascript will handle whatever you throw at it. Problem is: If you send an entire user, you’re sending everything. What if the user has an image on it? (Like an avatar) Maybe the user has a collection of addresses. Point is, that’s a lot to send out when you only need the two things. (Text and value for the dropdown list) The beauty of the anonymous types is you don’t need a new class file for the smaller version of the user thus allowing you to create a specific type that is only needed for this situation.

The nice thing to take from this is that you can easily create the bare minimum and really not sacrifice much. Why is that? Well you would think that the type is created for every user or maybe every time there is at least one instance running on the server. Fact is, the type itself is created at compile time so you don’t suffer that kind of pain. Beyond that, and I said this before, Javascript is more than capable of “reading” and “knowing” what the class has so you don’t have to worry about it needing some class off in some class file to send.

Now you could argue that you should have that class file and that it’s just good practice but I’m not convinced in this case. Mostly because this is a one time situation but, and yes it sounds funny to use “situation” again, situationally this is specific only to this instance… SITUATION

I suppose someone could argue that if I use other anonymous types elsewhere that use the same properties than I should make a new class file. There’s probably some truth to this, but on the other hand is it really necessary to go that far if you aren’t certain? I don’t know. But then again I’m fascinated by popcorn so you might not want to take my opinions seriously.

C#, Var, and Objec- Propert- I have no idea what the term is

So I caugh this the other day and I’m not really sure it’s useful but it got me thinking…

Say you have a string and you want to create what ReSharper calls a “implicitly typed local variable declaration”, or as most people know it as “var”, and intialize it with a created value:

  String someThing = "hi";
  var onTheFly = new { someThing };

And now you can do this:

  String somethingElse = ontTheFly.something;

What it basically did was not only take the value of the string, but the name too and made a property on the var. In fact you may have seen this already with Linq:

    var hi = from item in test
               select new {item.UserRole};

    UserRole someRole = hi.ToList()[0].UserRole;

So what does this all mean? Right now, I’m not really sure. I suppose if you have a method that you want to combine a bunch of value/objects into one var so you don’t have to keep refering to 8 different objects that might work:

    //Get the user
    User user = new User (1);
    //Get some icecream... couldn't think of any better fake class name
    IceCream iceCream = new IceCream(1);

    var stuff = new { user.UserName, user.UserRoles, user.UserLastName,
                             iceCream.Flavor, iceCream.Texture };

    //IMAGINARY CODE GOES HERE
    //MORE IMAGINARY CODE
    //??
    //PROFIT
    if(stuff.UserName.Equals("Sean", StringComparison.OrdinalIgnoreCase)
       && stuff.Flavor == IceCreamFlavor.Chocolate)
    {
       //BLAH BLAH BLAH
    }

As you can see, it could be a way to group together a bunch of things in a method, but I’m not sure that is really useful.

*WARNING THIS IS NOT TO BE TAKEN AS FACT, JUST MUSINGS OF AN IDIOT*

Now for the theory… As is, this isn’t useful but with 4.0 that might change with Duck Typing and dynamic types. Why? Well take a method like this:

    CallMe(userName, userFirstName, userLastName, userAddress,
             thisIsStupid, makeItEnd, iNeedAnAdult... endMe);

Now that’s a lot of parameters. Conventional wisdom says I should create a new class whose properties match the parameters I would be sending in and just send in that class:

    parameterClass.UserName = userName;
    parameterClass.UserFirstName = firstName;
    .....
    CallMe(parameterClass);

Now the only annoying thing is having to make the class to do this. What if dynamic types + duck typing takes that step away?

    var parameter = new { userName, userFirstName, userLastName .... };
    CallMe(parameter);

Then CallMe would take in a dynamic type and just look to see if it has the needed properties. Would be nice if this is possible but I haven’t used 4.0 yet to know, I’m only guessing from what I’ve read.

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.

Join By Anonymous Types in Linq

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

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

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

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

              foundUsers = query.ToList();

  return foundUsers;
}

As you can see here:

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

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