ASP.Net MVC 2/C# 4… Dynamic Model and Should You Use It?

So there’s a new sheriff in town and its name is dynamic. Actually, its not really that new and that’s a horribly misused cliche. My lack of literary genius aside, I’ve been looking for a reason to use dynamic. Then it came to me: Models. Now the only reason why I started down that path was the use of Python where pretty much anything is dynamic. In using python, I got used to not embracing the rigidity of classes for models and adopted a more “Oh what the f–k” attitude. Back in the .net world though, I was using typed views. Then I readopted the “Oh what the f–k” attitude and applied it to .net mvc.

Here’s an example:

    [RequiresAuthentication]
    public ActionResult ShowBasicInfo()
    {
      IState currentState = ObjectFactory.Create();
      dynamic returnModel = new ExpandoObject();

      returnModel.UserName = currentState.CurrentUser.UserName;

      return View(AccountActions.ShowBasicInfo, returnModel);
    }

As you can see, I created a dynamic class and just added a property to it. Now on the view side:

...
@model dynamic
...
          <label id="showBasicInfoEmail" name="showBasicInfoEmail">@Model.UserName</label>
...

So if that’s all you’re here for, well there you go. Now get out.

Ok so the real point to this post was actually the “should I?” Now with .Net, you really have to adopt a “should I?” attitude on anything that is new otherwise it might come back to bite you in the a–. (Update panels anyone?) Just using something because it looks easier is NOT a reason to do so.

The reason why I originally gravitated toward typed views was I didn’t like all the magic sting junk that came with the View dictionary, or whatever the hell it was called. (I’m too lazy to look it up) Typed views gave a sort of concrete nature much like an interface does to a class. You knew exactly WHAT the view could show based on the model. This is good I still think in an environment where you don’t trust people to code correctly or when a person needs an easy place to look up what the incoming model contains. After all, on the second point I mean, its a lot easier to look at a class to find EXACTLY what the model has than looking at a controller action code. Simple for reference.

With that being said, getting stuck in model hell can happen. After all for every action there is an equal and… wait… there is a model. Yeah you can reuse models to cut that down, but its not too hard to imagine it becoming a model infested nightmare. Sometimes you just have to take the good and the bad, but sometimes you’re able to trust people and just go with what is easier.

Why trust? With Python and it overall dynamic nature, it was easy to see that such a tool put in the wrong hands could be a disaster. Anyone who has worked with JavaScript will know this pain. Python is just a fancy way to annihilate your foot, so the concept of allowing dynamic models only made me shiver like a prostitute on Christmas. Sorry, that wasn’t appropriate. I meant a prostitute on a non religious holiday like Thanksgiving or the Chinese New Year. (Sorry non Christian readers)

On the other hand, when in a small group where you have less time and more to do, it could be used as a compromise as it doesn’t use the hated magic string dictionary thing approach, but still had a class like feel. And on top of that, if you wish to create models later, it would be extremely easy to swap the @model dynamic with whatever class type you need. So in that way, I can almost stop my non stop convulsing that is a natural reaction to doing something I deem bad.

Answer is: I don’t f–king know right now, but I’m going to fly with it and see how I like it.

Side note: One drawback of the dynamic route is the lack of intellisense. That could be a deal killer for some.

ByATool.com gets a shiny new tool!

A while back, we put up an offer to write for our blog.  Only one has risen to the top as someone having both the technical know-how and the razor sharp wit required to write on a site such as this.

ByATool.com Readers… Amy.

Amy… ByATool.com Readers.

Amy is a magnificent geek and almost 10 year veteran of server administration and software development. She has worked at IBM, Concurrent Technologies Corporation, and University of Pittsburgh Medical Center. Currently, she is doing custom SharePoint development connected with Team Foundation Server and the ASP.NET MVC framework development using the Entity Framework, C#, and jQuery. She is currently living in Pittsburgh and not happy at all about commuting into a city with 3 rivers because of the many bridges and no serious commuter subway systems… Who plans this stuff?

Welcome Amy!

Data Annotations, MVC, and Why You Might Like Them

So if you were like me before I knew what Data Annotations were, you most likely would be thinking, “What are Data Annotations?”. Well I’m glad I can read your mind and therefore I am glad you asked.

Now the fun part about this post is that I might have to admit I was wrong. Why would that be? Well in this post I suggested that validation rules would be set in the controller. Turns out, there is possibly a better place, on the model itself. How can this be done??? Well that’s what you’re about to find out.

Say you have a user create model:

  public class AddUserModel
  {
    public String UserName { get; set; }
    public String Password { get; set; }
    public String RepeatPassword { get; set; }
  }

Now you could have a method on the controller like:

  public ActionResult AddUser(AddUserModel model)
  {
    if(IsValid(model))
    {
      ...
    }
  }

Where you have to create the IsValid method for every model on the controller that you need to validate (And possibly on other controllers if you are sharing models between them…) Or you can have this:

  public ActionResult AddUser(AddUserModel model)
  {
    if(ModelState.IsValid)
    {
      ...
    }
  }

And that is already built in so no validation method needed. But how is that possible? Attributes on the model or namely the ValidationAttribute class.

First off you have to include the System.ComponentModel dll in the project. Simple enough. Please say you know how to do that or do me a favor and remind yourself to blink. OK done? Good.

Now you can use some of the built in attributes which is good. Things like required are nice:

  public class AddUserModel
  {
    [Required]
    public String UserName { get; set; }
    ...
  }

There you go. Now if the UserName is null or empty, the ModelState will no longer be valid and will fail this check:

  ModelState.IsValid

Now you might wonder what the error message will be for that? Honest answer: I have no f–king clue. That’s why you can actually set it. Those guys at Microsoft thought of everything.

  public class AddUserModel
  {
    [Required(ErrorMessage = "ENTER A USERNAME IDIOT!"]
    public String UserName { get; set; }
    ...
  }

The guys in the legal department have told me I have to note that your error message should change depending on your use and you shouldn’t use the one above. Whatever.

Now you might want to actually pass the errors back, and why wouldn’t you? You’re a fine, upstanding, and thoughtful person and I lie like a crook. The errors, if there are any, are in here:

  ViewData.ModelState.Values

And you can use two loops to get to all of them, but I think the parent loop will only run once.

  foreach (ModelState state in ViewData.ModelState.Values)
  {
    foreach (ModelError error in state.Errors)
    {
      messageList.Add(error.ErrorMessage);
    }
  }

Pretty nice huh? Maybe if you’re an idiot who just learned about this. For cool people like me, it’s old news.

What’s the point this? If “this” is data annotations: Well it helps move some of the validation off the controller if you are looking for a more “Fat model, skinny controller” design which I’m told is a good idea. This also gets rid of all the validation methods and saves time because of it.

If “this” is your life? I have no idea. But if you’re to the point that you’re asking me about the meaning of your life, you are in some serious trouble.

Random Add-On – Automapper

So if you’ve bothered reading my posts in the past, and don’t worry cause I haven’t, you might have seen me express my rule about not wanting to use third party stuff. Well things change. Actually they don’t, as I’m not bending the rule because I’m becoming a better person, just more lazy. This is where Automapper comes in.

Automapper is pretty much what it sounds like, it maps class properties automatically. Maybe a more clevererest name would have been ClassPropertyAutoMapper, but the guys who made it shouldn’t be persecuted for lacking creativity.

How simple is Automapper? Simple enough that even you can use it. Now that’s simple! Say you have two classes, a entity class and a model, and you want to map the model to the entity in the constructor. You could do:

  public class SomeModel
  {
    public SomeModel(SomeEntity someEntity)
   {
     SomeProperty = someEntity.SomeProperty;
   }
  }

But where’s the lazyiness? I expect so much less from you. But it’s ok, salvation is right here:

  public SomeModel(SomeEntity someEntity)
  {
    Mapper.CreateMap();
    Mapper.Map(someEntity, this);
  }

But… but what if there are properties on SomeModel that don’t directly map by name? Well, there’s an ap…i for that. (Not sure that even makes sense but it was clever.)

  public SomeModel(SomeEntity someEntity)
  {
    Mapper.CreateMap<FiftyPostUser, UserInfoViewModel>()
     .ForMember(test => test.Status, tester => tester.MapFrom(item => item.Status.ToString()));
    Mapper.Map(someEntity, this);
  }

So I know you’re thinking that there’s a catch, well there is. You have to actually get the dll and reference in your project. I know! Work is hard. Why can’t these guys just come to your place of work/home/mom’s basement and do it for you? What kind of world is it when you can’t get all that for free? Personally, I hate it.

State List in Dictionary Form

Tired of having to look this up from time to time, so I’m putting this here for my own use. If you get something out of it, good for you. In the end, I really don’t care.

    public Dictionary GetAllStates()
    {
      if(_stateList == null)
      {
        _stateList = new Dictionary();

        _stateList.Add("Alabama","AL");
        _stateList.Add("Alaska","AK");
        _stateList.Add("American Samoa","AS");
        _stateList.Add("Arizona","AZ");
        _stateList.Add("Arkanas","AR");
        _stateList.Add("California","CA");
        _stateList.Add("Colorado","CO");
        _stateList.Add("Connecticut","CT");
        _stateList.Add("Delaware","DE");
        _stateList.Add("District Of Colombia","DC");
        _stateList.Add("Federated States Of Micronesia","FM");
        _stateList.Add("Florida","FL");
        _stateList.Add("Georgia","GA");
        _stateList.Add("Guam","GU");
        _stateList.Add("Hawaii","HI");
        _stateList.Add("Idaho","ID");
        _stateList.Add("Illinois","IL");
        _stateList.Add("Indiana","IN");
        _stateList.Add("Iowa","IA");
        _stateList.Add("Kansas","KS");
        _stateList.Add("Kentucky","KY");
        _stateList.Add("Lousiana","LA");
        _stateList.Add("Maine","ME");
        _stateList.Add("Marshall Islands","MH");
        _stateList.Add("Maryland","MD");
        _stateList.Add("Massachusetts","MA");
        _stateList.Add("Michigan","MI");
        _stateList.Add("Minnesota","MN");
        _stateList.Add("Mississippi","MS");
        _stateList.Add("Missouri","MO");
        _stateList.Add("Montana","MT");
        _stateList.Add("Nebraska","NE");
        _stateList.Add("Nevada","NV");
        _stateList.Add("New Hampshire","NH");
        _stateList.Add("New Jersey","NJ");
        _stateList.Add("New Mexico","NM");
        _stateList.Add("New York","NY");
        _stateList.Add("North Carolina","NC");
        _stateList.Add("North Dakota","ND");
        _stateList.Add("Northern Mariana Islands","MP");
        _stateList.Add("Ohio","OH");
        _stateList.Add("Oklahoma","OK");
        _stateList.Add("Oregon","OR");
        _stateList.Add("Palau","PW");
        _stateList.Add("Pennsylvania","PA");
        _stateList.Add("Puerto Rico","PR");
        _stateList.Add("Rhode Island","RI");
        _stateList.Add("South Carolina","SC");
        _stateList.Add("South  Dakota","SD");
        _stateList.Add("Tennessee","TN");
        _stateList.Add("Texas","TX");
        _stateList.Add("Utah","UT");
        _stateList.Add("Varmont","VT");
        _stateList.Add("Virgin Islands","VI");
        _stateList.Add("Virginia","VA");
        _stateList.Add("Washington","WA");
        _stateList.Add("West Virginia","WV");
        _stateList.Add("Wisconsin","WI");
        _stateList.Add("Wyoming","WY");
      }

      return _stateList;
    }

So there. Hope you’re happy.

Entity Framework: Possible Lazy Loading Solution

So been a while since I posted last, and I’m sure everyone has been worried. Turns out that I’ve been banging my head against the wall named MVC. And man I have a slew of new posts back logged for when I have more time. However, due to the new project I’ve been working one, I forced myself to tackle Lazy Loading in the Entity Framework. Turns out the solution isn’t that hard since it has everything needed to make it work.

One of the biggest waaaaahbumlance calls is the fact that Entity Framework doesn’t have lazy loading. This isn’t true. It does, you just have to do a little work, which is to be expected from a FRAMEWORK. Now I have to admit, I wish there were a slightly less odd way of doing this, but eh it’s not too bad.

Say you have a class named Topic and it has a reference to a Forum class named ParentForum. Now this is just a property on the actual class created by the E-Work to represent a many to one foriegn key relationship between the Topic table and the Forum table. Now the problem comes in when you try to use something from that property like:

    Int32 someInt = topic.ParentForum.ForumId;

If you didn’t use the Include method when you got that topic:

    context.Include("ParentForum").Select(topic => topic);

You are screwed because the ParentForum property will return a null. So this forces you to use Include every time you want to get a Topic and access it’s ParentForum property. Sucks.

So next thought is to find out how to lazy load and then plunk it into that generated property. Eh I don’t know about you, but that sounds like a bad idea to mess around with a generated file. You have no idea when the E-Work will just trash the file and rebuild.

Next thought was to create a proxy property to check the real one and then load if it’s not already loaded. Something like:

    public Forum ParentForumLazyLoaded
    {
        get
        {
           //check and return
        }
    }

Ok so that’s not horrible except two things: The name looks dumb and people can still get at the original ParentForum property.

So in comes my solution and it’s pretty simple. Rename the property name on the class to something ParentForumInner and make it private.

bat_lazyload1

Then you can create a much nicer outward facing property like:

    public Forum ParentForum
    {
      get
      {
          if (!ParentForumInnerReference.IsLoaded)
          {
              ParentForumInnerReference.Load();
          }

        return ParentForumInner;
    }
    set
    {
        ParentForumInner = value;
    }
}

Now one of the issues with this is that although outside the class only the ParentForum property can be seen, within the class they both can be seen which can lead to issues like:

    context.Topics.Where(topic => topic.ParentForum.ForumId == id);  //boom

Where you should be using:

    context.Topics.Where(topic => topic.ParentForumInner.ForumId == id);  //yay

E-Work doesn’t know how to handle that situation when evaluating that expression and the kicker is that it does just fine compile time. You won’t know this is bad until runtime.

Other issue is that you have to do a little more work then just some setting on the property which is what most people wish for. I guess that may be true, but again this is a framework. It gives you all the tools you need to makes things work, you just have to do some coding.

The plus side to this is that with minimal coding, you can completely get rid of Include which to me is huge.

By Reference in C# and How to Get Schooled By It

WARNING: If you understand The concept of By Reference, skip the first part of this post:

So you have an object, huh? Ok well what does that mean? Basically there is a stack and a heap. When you declare an object, space is made on the stack, basically it’s a placeholder saying that there will be something to point.

    User someUser;

Now when you instatiate:

    someUser = new User();

That user Object is put on the heap and that placeholder (reference) on the stack? Well it’s given a pointer which SURPRISE points to the object on the heap. Now when you pass the object into the method, you aren’t really passing what’s on the heap. You are actually copying and passing the pointer. Inside the method, a new entry is thrown on the stack that points to the same object on the heap. This way if you change anything on the object in the method, the changes are reflected outside the method. (Say if you added items to a list in the method) Now this all changes if the object inside the method is reinitialized or repointed:

    SomeMethod(User user)
    {
        user = new User();
        user.UserName = "Sean";
    }

Remember that user we passed in? It now has nothing to do with the one in the method now. There is now a new object on the heap and “user” in the method now points to it. Why did I tell you all of this?

END REFERENCE EXPLANATION:

Say you have this:

    ...

    UserList userList = new UserList();
    SomeList list = new SomeList();
    FillListFromUserList(list, userList);

    ...

    void FillListFromUser(SomeList listToCopyTo, UserList userList)
    {
       foreach(User currentUser in userList)
       {
          listToCopyTo.Add(userList);
       }
    }

Easy, and basically at this point list should have the same items as userList. Now say list needs what’s in userList but in order by UserID. Suppose you did it like this:

    void FillListFromUser(SomeList listToCopyTo, UserList userList)
    {
       foreach(User currentUser in userList)
       {
          listToCopyTo.Add(userList);
       }

       var sorted = from user in userList
                    orderby user.UserID
                    select user;

       listToCopy = sorted.ToList();
    }

Ok so a quick check to see if list now contains items will show it does. Now say you looked at this method and thought it was a little more than needed. You decide to do this:

    void FillListFromUser(SomeList listToCopyTo, UserList userList)
    {
        listToCopyTo = userList.OrderBy(user => user.ID);
    }

Now a quick check to see if list has something in it shows that it doesn’t. But wait, what the hell? The first one worked and the second is just short hand right? Eh well the problem is how objects are passed. By reference means that it doesn’t pass the original pointer from the stack but it copies it so that there are two references on the stack that point to the same object on the heap. What does this all mean? Well both

    listToCopy = sorted.ToList();
 And
    listToCopyTo = userList.OrderBy(user => user.ID);

Have now reset the pointer for the reference in the method (listToCopyTo) making it no longer have anything to do with the list outside of it (list). The reason why it gave a false positive on the first one was that I had added to the list within, and therefor to the object the list outside points to. So the changing of the pointer:

    listToCopy = sorted.ToList();

would no longer affect the list oustide. However, in the second example I never added to the object they both pointed to before I changed the pointer on the inner. Hense why the second example had nothing in the outer list. To make matters worse I would have noticed this before if the original userList hadn’t been sorted by ID already.

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.

Linq Extension Methods Versus Linq Query Language… DEATHMATCH

Today I was writing out an example of why the extension methods are for the most part better to use than the querying language. Go figure I would find a case where that’s not entirely true. Say you are using these three funcs:

    Func<User, String> userName = user => user.UserName;
    Func<User, Boolean> userIDOverTen = user => user.UserID < 10;
    Func<User, Boolean> userIDUnderTen = user => user.UserID > 10;

As you can see the first one replaces the lamdba expression to get the user name, the second replaces a lamdba expression used to check if the ID is lower than 10, and let’s face it, the third should be pretty easy to understand now.

NOTE: This is a silly example but it works.

    var userList =
      from user in userList
      where userIDOverTen(user)
      select userName;
Versus

    var otherList =
      userList
      .Where(IDIsBelowNumber)
      .Select(userName)

In this example, the second is a little less verbose since the extension method can make full use of the Func, but he Linq expression can’t since it is look just for a Boolean rather than a Func that returns boolean. However, this is where it might be better to use the expression language. Say you already had a method that takes in more than just a user:

    private Boolean IDIsBelowNumber(User user, Int32 someNumber, Boolean doSomething)
    {
      return user.UserID < someNumber;
    }

Note: doSomething is just there because of the where extension method being ok with a method that takes in a user and integer and returns boolean. Kind of annoying for this example.

Now if you look at the Linq query:

    var completeList =
      from user in userList
      where userIDOverTen(user, 10)
      select userName;

You’re good for it. Now the Extension Method:

    var otherList =
      userList
      .Where(IDIsBelowNumber????)
      .Select(userName)

Without a lambda expression, I really can’t call that method. So now what I have to do is create a method that creates a Func based off the original method call.

    private Func<User, Boolean> IDIsBelowNumberFunc(Int32 number)
    {
      return user => IDIsBelowNumber(user, number, true);
    }

And then plug it in:

    var otherList =
      userList
      .Where(IDIsBelowNumberFunc(10))
      .Select(userName)

What does this all mean? You just lost 5 minutes of your life. I hope it was worth it.

Static Abstract … should I bother?

So it came up recently that someone was bummed that you can’t create a static abstract method. Now conceptually, this is blocked by C# but I came up with this “work around”… And I have no idea if I would ever use it. This was more of a “Do it because I can” rather than “Do it because I should.”

  public abstract class Parent
  {
    public abstract String ReturnAValue(String returnThis);

    public static String ReturnAValue(String returnThis) where K : Parent
    {
        K classToCreate;

        classToCreate = Activator.CreateInstance();
        return classToCreate.ReturnAValue(returnThis);
    }
  }

So what I did here was create a parent class that causes any child to override the ReturnAValue method so that I could create a static method on the parent that basically would just instantiate the child class and call the overridden method. How’s that for a run on sentence?

  public class ChildA : Parent
  {
    public override String ReturnAValue(String returnThis)
    {
        return "ChildA " + returnThis;
    }
  }

And this in full use:

  String testReturn;
  testReturn = Parent.ReturnAValue("returned");

Can you guess what that returns? If you can, you’re special. You might wonder why I have to use generics in this. Well I mean you could do this:

    public static String ReturnAValue(Parent returnThis)
    {
        return returnThis.ReturnAValue(returnThis);
    }

But that assumes you have to instantiate the child and pass it in.

Now the main problem with this, beyond the fact that you’ll probably never use this, is Activator.CreateInstance() need a default public constructor to use. Kind of a catch.