Showing posts with label MVC. Show all posts
Showing posts with label MVC. Show all posts

Wednesday, June 8, 2016

Is ASP.NET MVC the new WebForms because of Smart Client JS Web Apps?

In the last few years JavaScript, JavaScript frameworks, and the browser have matured exponentially providing us with AngularJS, React, Aurelia, Ember, and others. These frameworks allow for web developers to create performant and rich smart client JavaScript web applications (a.k.a SPAs). So what about ASP.NET and that old trustworthy MVC implementation? As an analogy, is MVC the new 'WebForms' as to how WebForms were viewed when MVC came to the scene? Is ASP.NET MVC obsolete or considered now 'old hat' from an implementation perspective? I think it is mostly 'yes' and just a bit of 'no' to that question and I'll provide points to both.



The bold answer is yes - MVC is a relic of days past and anyone that uses it has their head in the sand. Well maybe not quite and certainly not near being obsolete. However there is some merit to the fact that ASP.NET MVC is showing it's age as an implementation choice. There are many things that JS web applications do very well and architecturally speaking just make sense. 

To begin, the JS Frameworks by nature move the heavy rendering and presentation logic to the client. This removes the burden on the server of packaging both markup and data to send to the client. The server's main responsibility is now returning only data typically in the way of JSON payloads via RESTful services (i.e. NodeJS, WebAPI), as well as the web artifacts on an as needed basis (i.e. views, images, JS, etc.). With most frameworks, once the views and associated JS is brought to the client it is cached. The combination of client side processing + caching of data and website artifacts = highly performant web applications.

The 1st time most developers get accustomed to a JS Framework creating a web application, and experience how the line between desktop applications and web application almost is non-existent they often see the many benefits and don't look back.


Add atop of all this, most JS Frameworks were built with testing in mind, have massive adoption, huge amounts of support, examples, and training which adds up to something one can feel confident moving forward with as an implementation choice.

Another advantage of smart client JS Web Applications is the fact that they make sense architecturally. MVC by nature is and should be a presentation layer architecture. In ASP.NET MVC, I still see often the architecture abused and used as the full-blown implementation for Enterprise Applications. I don't blame most for doing this as the majority of  '101' examples show this implementation so it must be what is used for everything, right? Wrong. It's analogous for those of you that have used Angular 1.x and having the controller make $http calls directly, or abusing $scope as the do-all for the app. 

A tattle-tale sign of using MVC incorrectly is if the 'Model' is directly making database calls (i.e. EF or whatever) and then having the Controller make calls to methods on the Model. This then results in bloating either the model or controller (or both) with additional business logic or model hydration/shaping. MVC should be the top layer of the cake and only concerned with presentation layer logic and manipulation. JS Frameworks for the most part solve this problem naturally because of the separation now between the client and server. It's more difficult and many times not even possible to abuse the JS Web App client implementation that was done so often in ASP.NET MVC. Now one is forced to call the server for data, and then on the server another layered implementation can exist within the RESTful service to handle logic, rules, additional underlying calls, hydration/shaping, etc.. With a JS Web App we should relegate the MV* implementation client side to only presentation layer concerns, and allow the server to do what it does best and offer up reusable RESTful endpoints, encapsulating all server logic. With MVC this was absolutely possible, however it was typically a conscious decision and had to be made usually at the project's onset in order to have decent SoC and testability. Otherwise the result would be behemoth of a web application stuffed into the slim MVC implementation. 

From a JavaScript perspective my experience as a whole in MVC usually yielded to a jQuery implementation for DOM manipulation and a multi-thousand line file named MyApp.js. At 1st this file seems like a good idea, but then it snowballs into a intermingled mess of reactionary code responding to events, registering callbacks, making AJAX calls, manipulating views, and a hundred other things all interwoven together. Most of the time I saw no forethought put into proper segregation using known JS patterns like the module or revealing module pattern, and mostly a mess of public values and methods that were a ticking time bomb of heavy maintenance. In JS Framework implementations, there is a separation of concerns between the Model and View logic allowing testing and scaling your application more correctly. The alleviates the need for JS DOM manipulation libraries like jQuery all together.

Let's pile on another thing helping out JS Web apps in the way of languages like TypeScript.
This gem which was originally created at Microsoft by the same guy that created C# and is OSS, is a superset of JavaScript and adds on a slew of features to help developers wrangle some of the JavaScript nuances. There isn't anyone here claiming JavaScript is a perfect language, but I'll tell you from 1st hand experience using TypeScript makes creating JS Web apps in my experience a whole lot easier. Static typing, build time checking of code, Interfaces and other language features that don't exist in JS, staying ahead of the ECMAScript standards and releases, OO familiarity, and many other goodies help make TypeScript a real joy to have in the toolbox when creating JS Web Apps.


So now let's look at the flip side of the coin: ASP.NET MVC's advantages. Well to begin Microsoft is doing ASP.NET in general a whole world of good in the way of .NET Core 1.0. From a project's physical structure and implantation, the new world of the web in VS.NET is brought inline with where the rest of the web and OSS community has already been in the last several years. This is to the tune of task runners like Gulp or Grunt, additional package managers in the way of NPM and Bower, .json configuration for many different project components or languages like TypeScript, and several other new changes. 

The irony is from WebForms to MVC we moved from a 'Convention over Configuration' phase. Now we are shifting back to 'Configuration over Convention'. However this is in a very good way. Instead of getting many tools, resources, and processes being dictated and packaged up by default, you need to tell your web app exactly what you want and how you want it to behave from start to finish. This is a good thing. We as developers should have full control over our applications and dictate this configuration. At first this might cause some heartburn as change sometimes does, but it's the right move and I applaud Microsoft. For so long I used to promote how much I liked living inside the comfortable confines of ASP.NET and VS.NET. This magic thing like 'bundling and minification' was done for me along with many other tasks to get up and running. There is a little more work now as this doesn't even exist anymore in .NET Core 1.0, but I can control and configure my apps to be lean and behave as I want them to.


So wait, what about the good bits of MVC?? The above was like a back-handed compliment about MVC finally catching up to more standard methods of configuring web applications. However there are a couple of big things MVC still has going for it.

1st it's quite mature. ASP.NET has been around since 2001 and the MVC implementation since 07`. That's almost 10 years going strong. In addition Microsoft is behind it and is now OSS. It's not going anywhere, anytime soon. If your looking for that rock of stability and being conservative MVC is a good choice. Keep in mind though, ASP.NET WebForms is stable and around too, but that doesn't mean it's the best decision.

2nd, because of it's maturity there are a slew of developers that have experience with using it and developing application for it. There are just some realities that exist. Things like deadlines and financial constraints are legitimate concerns. As the lead, architect, decision maker, etc. on your team you might have 10 developers that are strong in MVC and have relatively no experience with a JS Framework and JavaScript in general with a deadline fast approaching. Do you bite the bullet and try your hand at creating a JS Web App, or go with old trusty and bang it out in MVC? That's a decision you'll need to make and one I've encountered as well.

To sum things up, I do believe JS Web Apps are here and probably the best decision for net new web apps today. I personally view MVC as a bit of a heavy weight in the web ring and sometimes we need something a bit more lean to fight our development battle. I agree for the most part MVC is beginning to be viewed as the new 'WebForms' as far as making an analogy to how WebForms were viewed when MVC came to the scene. However as I've broken it down, ASP.NET MVC isn't going anywhere and is still a fine choice to make in certain scenarios. 

Who knows, maybe I'll be writing this same article in 5 years with the following title:

"Are JS Web Apps the new MVC because of WebAssembly?"

Friday, January 4, 2013

Route Debugging in ASP.NET MVC

Here are a couple of easy ways to have insight to route debugging your MVC applications. If you begin to build up your route tables with lots of different options, possibly including complex regular expressions, you might get undesired results based on incorrectly intended matching. Remember routing works in a top down matching methodology, so if a URL matches an earlier route then intended the incorrect view might be returned (if anything at all).

The easiest way in my opinion is to use the Route Debugger utility (thanks to Phil Haack) that can be installed from NuGet. This process takes all of 2 minutes, so check it out. Use the following command from the Package Manager Console to install:

The configuration for enabling and disabling is in the web.config <appSettings> section:
<add key="RouteDebugger:Enabled" value="true"></add>

As you can see the output shows the matched route at the bottom of each page:


Another technique for debugging routes not found via the result of a HTTP 404 is to use Fiddler. Open it up, but remember to place a dot '.' after the word 'localhost' if using the local IDE to spin up your web application (I have a post about this here: Using Fiddler With VS.NET And The Local Web Development Environment 'Cassini'). After refreshing the page, click on the the 404 entry in Fiddler, and then press the 'TextView' button on the response. Scroll to the bottom, and take a look; you get a much more meaningful response message to view.


Lastly, Glimpse is another route debugging tool but last I checked they are still working on support to port over the MVC3 version to MVC4. If you are still using MVC3, check out Glimpse on NuGet as well.

Friday, December 14, 2012

Visual Studio LIVE! Orlando Day 5 - All about MVC 4


1 more day to go and I'm looking forward to a full day on MVC! I have become a big fan of MVC over the last year, previously being a web forms developer for the past 9 or so years. The agenda looks great (this is not some intro course) so let's get to it!

Mastering ASP.NET MVC4 in Just One Day
Tiberiu Covaci, Microsoft MVP and Senior Trainer & Mentor


I'm looking at the agenda for today and it looks like we will be covering soup to nuts on MVC. Obviously there are a lot of web forms developers in attendance that are seeking out knowledge on MVC, so there has to be a general introduction to 'Model-View-Controller' As always the typical diagram displaying the general interaction between the parts is displayed below:

If you are new to MVC there are some goals, even say 'advantages', to this framework. Tibi mentioned testability, tight control over markup leverage the benefits of ASP.NET 4, and  conventions and guidance. I actually spoke in depth to some of these in a post I did a couple of years ago and you can look at it here: ASP.NET Web Forms vs. ASP.NET MVC 

One of the other main features of MVC is its extensibility. ASP.NET MVC is actually open source, so modifying it to your needs presents an endless about of customizations  For example, you don't have to use just the .aspx or Razor View engines. Others are available like Spark if you want to use it. Personally I'm a big fan of the Razor view engine out of the box and it fits my needs. However it's nice to have that flexibility if needed. Now with NuGet, you can get a slew of different packages to help with development. In fact if you strictly work with blinders on from only using out of the box MVC functionality, you are probably missing out on something that will make developing your application easier, How do you find out about the packages available  Blogs, conferences, magazine article, word of mouth from experience, etc.

It's always tough when explaining to those new to MVC which piece to explain 1st (Model-View-Controller). Starting with the Model is a good idea as you can really think of these as your old business logic layer classes. On this note a few of the architectural patterns were brought up that can used in MVC: Repository, DDD (big fan), and service pattern. If you are not familiar with DDD, in a nutshell the focus of the architecture is on the business domain, and after all this should be the focus of the application. Someday I would like to see a MVC implementation using DDD, but today we will be using the Repository pattern which I am also a big proponent.

The example used today had a single model class named 'Course'. This is where the getters/ setters are for the object and any method calls not directly related to persistence  The repository pattern is responsible for the interaction with the persistence layer (i.e. Entity Framework) and wraps the basic CRUD methods. To keep the focus on MVC, there was not any true implementation in the repository to fetch data, and the data was loaded from static data in a mock layer named 'TibiPublicSite.MockRepository'. The CourseRepository implemented ICourseRepository, and returned hardcoded/mocked up data. Works perfectly because this is not a session on EF or other ORM.

One thing I should mention that was being done in the solution referenced throughout the day was the layering of the application. You will notice by default that an MVC project will have all of the pieces in a single solution. This is ok and I recommend for beginners to just stick with this until they get the hang of the method calls and flow. However, MVC can be considered a and architecture for a UI only and this is why separating out the additional layers is a good idea. Here are the layers from today's application:

  • TibiPublicSite (MVC)
  • TibiPublicSite.MockRepository
  • TibiPublicSite.Models (contains repository interfaces and model classes)

The next key piece of the MVC architecture are the 'Controllers'. These are the server side classes, and each MVC request maps to a Action method in a Controller class  Remember, MVC uses routing, and the URL route is dictating an action on the controller to be executed. The classes here implement 'IController'.

An Action is a method that returns a ActionResult. ActionResult is the base class, but there are other result types as well like ViewResult, RedirectResult, and JsonResult to name a few. When you add a controller, you can actual scaffold it based on an existing class (make sure to build your project 1st so they are available for selection  This will create many of the action methods on the controller already needed based on the model class selected.


Using Dependency Injection on the Controller is a great was to loosely couple the persistence mechanisms from the controller itself. When the controller knows too much about the actual persistence details, you create tightly coupled code that is less reusable and more difficult to maintain in the future. Having the controller have intimate knowledge and making direct calls to the database is not a good idea. The repository is injected into the interface on the controller and is accessible by the methods on the class. It's better to call _repository.Save(myObject), rather than having to know how to directly work with the Entity Framework context, ADO.NET code, or other persistence mechanisms. You might be thinking that you could still push persistence details down to the model, but by injecting the repository into the Controller, you set yourself up much better for unit testing.

However to take this a step further in reality there is not a 1 to 1 relationship between the View and the Model. Therefore we will be using customized classes that contains a combination of data that may span > 1 model class. These classes are named 'ViewModels'.

HTTP verbs are decorated on controller actions in the form of attributes. The HttpGet is not required as it is the default. You can still add it for consistency and to be explicit. If you try and call an action with the incorrect verb it will obviously not get called.

It is important in controller actions to check if (ModelState.IsValid) to ensure model binding worked correctly.

Routing is a part of ASP.NET System.Web.Routing. /Bikes/MountainBike is much better that Products.aspx?Item=MountainBike  Routing is defined in Application_Start() and contains one default route {controller}/{action}/{id}. The ordering it is listed in the class is important. The routing process is to trickle down top to bottom to find the 1st match. If you have a match that was unintended, you might get the wrong controller action.

You know sandwiched here in the middle I have to say how exciting some of these technologies are to work with. Take a look at the following line of code:

var model = _repository.GetByCriteria( c=> c.Title.Contains(searchTerm));

MVC, Lambdas, Dependency Injection, entity framework, dynamic typing. One line of code that does so much would have taken many times the effort if not using these technologies. This is why it's so important to stay current, because otherwise you may be working 10x the effort when there is a better way.

Route debugging can be aided by a NuGet package created by Phil Haack named 'RouteDebugger'. This is a fantastic tool that when navigating to a URL, you will get the bottom portion of the browser breaking down the route and which patterns it matched and any constraints  This will help for what I discussed previously about trying to determine which route from Application_Start that the URL matched. Just remember to disable this in configuration before deployment or when not needed:

You know he started talking about web.config transformations and this is something I'm embarrassed to say I have not used. The result, over complication in code or going back and toggling values between test and production. Essentially is does a XSLT transformation on the web.config file for both 'Debug' and 'Release' scenarios. Need to start using this.

Views are another major component of MVC. They are as close to a page as it could get. Strongly typed views inherit from ViewPage for aspx pages. If using Razor, add @model directive for razor pages.

The Razor View Engine syntax is slick. I actually did not start using MVC until v3 so I never got into the .aspx engine syntax. In fact if you were driven away from MVC because it looked like classic ASP, give it another look and try out the Razor syntax. Razor syntax uses HTML helpers which can be accessed in the view via Intellisense by starting with the '@' symbol. Remember when adding a new Razor view, the difference between a 'Partial' view or not is the inclusion of the _Layout view. Partial views will not include it.

Tibi forgot to add the @RenderBody() helper to _Layout.cshtml (think of the _Layout view like a Master Page). This helper is required and is analogous to the ContentPlaceHolder server control in a MasterPage in web forms. The @RenderBody method indicates where view templates that are based on this master layout file should “fill in” the body content.

Make sure to declare the model directive at the top of the view like @model IEnumerable. This will allow strongly typed access to the 'Courses' data within the HTML helpers in the view. If you want to remove the redundant namespace declaration, add it to the web.config as an imported namespace. It can then be changed to @model IEnumerable. Even using a 'using' statement in the view at the top is acceptable as well.

The razor syntax HTML helpers flows very nicely in with existing HTML. With razor syntax JS is added in a section called @section scripts{} and CSS is in a section called @section styles{} You can also use the @RenderSection("scripts", false) helper in the _Layout view to dictate a section in other views. If you use JS or CSS on most views, this will keep it consistent in placing.

For those new to MVC and the Razor engine the HtmlActionLink will be your friend for making links on a page that route to controller actions. Remember there is no physical page on the server (like web forms). We have to route to an action on a controller to execute our code on the server. An example of this is the following: @Html.ActionLink("Start", "Start", "Courses"). This makes a link named 'Start', that will route to the 'Start' method on the 'Courses' controller. Remember MVC is based on convention and not configuration like web forms so you do not have to write 'CoursesController' because 'Controller' is redundant and known.

If you want to pass parameters you would pass them as object routeValues: @HtmlActionLink("Details", "Details", new{id = item.id}, new{@class  = "abc"}). Notice using '@' in front of class because 'class' is a reserved keyword.

The @using (Html.BeginForm()) wraps where the form starts and begins, and uses IDisposable to be disposed when not used anymore. 

Model Binding is probably my favorite thing in MVC. Remember the days of having to explicitly pull all form values server side to send off for manipulation (i.e. SaveValues() or something)? Not anymore. Model Binding will automatically send form values back to the controller and populate the object in the controller method parameter list. This saves on a lot of redundant code. I guess I get more excited about this because I did web forms for so many years and would sometimes have large methods to scrape values off controls into a business object. 

To add to how easy this all wires up, you can scaffold the View off a Model or ViewModel class and have all the markup created for you! Again, this was a lot of manual work in web forms (unless using a FormView or something but the server side operations had a heavy footprint and got messy quick). When scaffolding, you can select the class and type of View to create. The screen below shows how I scaffold a 'Create' View for 'Courses' model class:


Want even more streamlined? Use @Html.EditorForModel() on the view for the bound model. What you get from a single line is the entire form of fields to edit! One line, are you kidding me? Again, us old web forms folks appreciate this a a lot. By the way if you are wondering how you might exclude or control which fields show up on the form, because maybe you don't want SSN shown or at least disabled. You can control this by using data annotations on the model properties that the fields map to. Have a look at the System.ComponentModel.DataAnnotations namespace for the fields available. 

The annotations also work hand in hand with the jQuery validation scripts. Remember having to explicitly add all the RequiredFieldValidators or JS clientside? Not anymore, because ASP.NET will use these annotations to automatically do fields validation based on the presence of the jQuery validation scripts. In fact, these scripts will already be in your project upon creation, so you have to do very little to get it all working.

Annotations do (even with me) seem a bit like decorating values for UI purposes a few layers down which might be viewed as improper. An alternative is to create a MetaData class that abstracts away the annotations. So I might create a class called 'public class CourseMetadata' and decorate the model class with [MetadataType(typeof(CourseMetadata))]. Just remember the annotations are good for EF as well if doing a 'Code First' approach as it will define the constraints on the fields in the database. I do admit abstracting away the annotations into a MetaData class is pretty nice and probably something I will implement in future applications. The only downside might be developers coming behind not initially seeing the annotations where they expect them (on the Model class). This is why commenting never hurts. Just add a little note in the XML block on the class.

If you happen to being doing mobile apps, you could add separate versions of the View using the nomenclature 'index.mobile.cshtml'. This is a nice way to differentiate views. I would not be surprised in the next 2-5 years that a feature is available to streamline this duplication of Views between desktop and mobile Views. Today you still have to create separate views. Remember (from the other day), the user-agent is pulled when accessing the site, and ASP.NET knows how to serve up which version of the views. Check out "Framework64\v4..0.30319\Config\Browsers\" to get a list of the user-agent browser files. You can open these files in VS.NET if you want to inspect them. After the proper user agent is matched, then the view name by convention (index.mobile.cshtml) is rendered.

"How many want to hear about Web API?" The entire room raised their hands! How appropriate to finish the day and conference with a technology at the top of my list in interest in learning. It allows the creation of REST based services.

Now here is something to wrap your head around. Just learning MVC? Well there is a camp of folks that are writing application by making all calls to the controller via Web API. One of the goals here is to push more functionality to the client and prevent expensive server calls. Libraries like Knockout.js have to be leveraged to help in this. By doing this you make lean responsive applications. It's a balance between what goes on the client and what's on the server. One thing at a time for now...

Tibi added a folder to the existing MVC app named 'api' under the existing 'Controllers' folder. The 'api' will match the convention for the Web API URIs. This folder will contain the controller actions for 'api' calls. Notice in the routing (Application_Start) that no 'Action' is defined. This is because the Http verb infers this for us in API calls.

Using Fiddler is the easiest way to make API calls. Just click on the 'Composer' tab and select the proper Http verb along with the URL to call. You can also modify the request headers or body from here as well. This is a nice place to define the user-agent if you are testing that functionality. To build up the body, create JSON like {"Title": "My New Course", "Duration": "1"}. Make sure in the header to include "Content-type: application/json" (without quotes).

He finished off with a quick demo on a Dependency Resolver named Unity (Unity.MVC or Unity.WebAPI; there are different versions for different technologies). Unity is a lightweight, extensible dependency injection container that supports interception, constructor injection, property injection, and method call injection. You can get Unity from NuGet and add it as an installed package to your application. This way you do not have to manually instantiate the model type on the repository for each class. In Application_Start() you make a call to Bootstrapper.Initialize() to register the containers that map the Types to their concrete equivalent.

container.RegisterType();

Whew, that was a great day with a lot of information on MVC. Nice job Tibi!

Wrap Up Day 5 - That's a wrap!


Well it's the last day of the conference, and the 1st day the sun has been out since prior to conference registration! Sorry to the people that came here from the north and expected to see the 'sunshine state' along with 75 degree weather.

It's bittersweet at the end of the conference because it's sad it's over but it will be nice to go home. The comradery among attendees and networking that occurs is an awesome byproduct of the conference. My brain is absolutely jam packed with good information. I applaud all of the presenters and conference organizers and rank this as one of the best Visual Studio LIVE! conferences I've attended. If you have never attended a conference like this, I highly recommend breaking out of your cultural "bubble" at work, home, etc. and attend to see where the community is headed. These conferences doing a job second to none to validating and presenting a sort of "what's good and what's maybe not so good" based on community feedback (presenters don't pitch anything and just state the facts).

I am already looking forward to next year's conference, but in the meantime I feel I have the information needed to make great decisions on leading technology for the upcoming 2013 year. Hope everyone has a great trip home and see you next year! #Live360


Wednesday, December 12, 2012

Visual Studio LIVE! Orlando Day 3

All right let's get the day going! I have my fancy green tea (yes they have great coffee and really nice tea - energy drinks reserved for the afternoon :)) and I'm ready to on-load some great information. I'm spending almost the entire day on a web track, and as always there are multiple sessions I want to attend so it's always tough to choose. Here we go!

Visual Studio Live! Keynote: Building Applications with Windows Azure

James Conard, Sr. Director of Evangelism, Windows Azure



I have to admit that Azure is a technology that I thinks has a ton of potential, and the implementation seems to be done well, but it is not something I see using in the near future myself. Why you might ask? Well, professionally it's not an option for the time being. As far as personally, I looked once at messing around with hosting a site in Azure so I could get some experience with the technology. I was drawn in by the 3 or 6 months free hosting, but started looking at how much it would cost in the long run. It turns out the Azure hosting was going to cost much more than any other hosting company and did not make sense for me.

I have seen some sessions over the past year similar to this one done by Scott Guthrie. As I'm watching the demo today I have to say that the creation, deployment, and configuration couldn't be more straight forward. There is no excuse for entry if needing to do Azure development by saying it's too difficult to get set up. From the close ties in VS.NET and Azure and out to the Azure Management Portal, I can say the tooling on both ends appears to be well designed and intuitive.


The real power of Cloud Services are automation and ability to scale so easily. In Management Portal it is amazing how much can be configured. The (2) tabs I liked the most are 'Configure' and 'Scale'. It was mentioned that just recently that the VMs now support Windows Server 2012, .NET 4.5 including all of the new features like web sockets. On the 'Scale' tab you can use sliders to change the number of cores for both the front end and backend VMs. What they don't tell you (but I assume most here know) is that upping the cores used on the VM for a site that gets heavy traffic will result in a significant cost increase. Since the cloud based pricing model is based on what you use, they make it look so simple but it does come with a cost monetarily. 


Managing SQL server in the cloud is just as straight forward with support for many of the things a traditional SQL instance has.


There were multiple demos from web to mobile and again in my opinion the reoccurring theme was the one of ease to create, deploy, and manage any type of project hosted in Azure. I know that if I ever do get into cloud development in the future, I'll feel confident in using the right tools with Windows Azure.



JavaScript and jQuery for .NET
John Papa, Microsoft Regional Director



Ok this room is packed! Actually there are more people for this session than there were the keynote. However the planners this year seamed to have missed a tad on which sessions would be the 'popular' ones that needed moved to the larger Pacifica 6 room. This is the 3rd session I've been in that had to move from a smaller room to this one. Seems consistent that the web and .NET Framework sessions are much more attended than the Windows 8, XAML, and Azure sessions. John's sessions at CodeCamp or Visual Studio! live seem to always attract the masses and he does a great job presenting.

He delve right into the different data types for JavaScript. The differences between Dynamic (JavaScript, Ruby, SmallTalk) and Static (.NET, Java) languages were highlighted as well. A Dynamic language like JS can have objects or anything change at runtime, where in Static languages everything is already decided at runtime. 


He also highlighted a new typed JavaScript language from Microsoft named TypeScript. TypeScript is a superset of JS. Anything you already know in JS can be used in TypeScript. TypeScript will give you a lot more information at compilation time for code issues vs. getting that little yellow icon down in the status bar of the browser at runtime. Ahh, who needs something great like this, let's just type our JS perfectly and there will be no issue. From what John is highlighting, the next version of JS, ES6, should have a lot of cool enhancements in this arena that TypeScript is covering today. To see how the differences look between JS and TypeScript, check out the TypeScript Playground


Objects in JS are hash tables and can change at runtime. You can actually add properties to change the object on the fly. Arrays are just indexed hashes that can be redimensioned implicitly at runtime just based on the index accessed.


One thing John was doing that I think was an effective way to relay his topics was to make comparisons between how we do something with an object in C# and how we do it in JS. One point to make along this lines is there are no classes in JS and you need to wrap your head around this. However the next version of JS, ES6, will start to contain the class keyword.


He also spoke to the difference between double equals (==) and triple equals (===). Main point here, if you are unsure of a type coming in and need to do a comparison, use the triple equals (===). For example (if 0 === "") will not evaluate (which is good), where (if 0== "") will evaluate (which is bad).


"Avoid globals, globals are bad" says John. Yeah this doesn't just apply to JS and is just a good message regardless. Any variable created on the fly will be a global variable.


I do like function expressions in JavaScript and have used them before in some of the jQuery I've done. As with any JS defined variables, make sure to physically define the function before calling it or you will run into errors. Where JS programming deviates in implementation is to prevent hoisting issues, go ahead and declare all of your needed variables at the top of your functions so they will be available for use.


John spent a good amount of time using the afore mentioned TypeScript playground to show the niceties of the language. It really does bridge the gap to those of us more familiar with OO languages like C#. Who knows how long it could be until the next version of JS, so TypeScript is an attractive option today.


I would have to assume that I'm probably like the majority of people in this packed room. JavaScript is not something I get really excited about and to me it is a necessary evil, especially now more than ever. I guess this sentiment comes from the fact that I do not use JS day in and day out, so I've never broke through the barrier of being really proficient. I've written a lot for my web applications over the years moving from plain JS to using libraries like jQuery, so it's not new to me. JS is one of those areas I consider myself dangerous and productive but by no means highly proficient yet. The good news is I like what I hear from John, and all of the tooling and support that has wrapped around JS recently. The stronger OO syntax support is a really nice feature in TypeScript. As well VS.NET 2012 has a lot better Intellisense to help those like me that need the extra help. I know one thing JS is here to stay and a major player in the industry so I expect the sessions on JavaScript in the future will be plentiful.



Reach the Mobile Masses with ASP.NET MVC 4 and jQuery Mobile
Keith Burnell, Senior Software Engineer, Skyline Technologies, Inc.





Developing applications that not only work on mobile devices, but have an optimal mobile experience is key today. If you ever being up a traditional website on a mobile device that was not designed with a mobile experience in mind, it will probably not get used. Most people aren't developing 'mobile only' sites, so when developing websites used on the desktop (not mobile), then it's good to sprinkle in some functionality to allow sites be multi-purpose (mobile and desktop).


Interesting, "If you get nothing else out of this talk, make sure to add the viewport meta tag to your markup". It makes sure to set the width of the page to the device. Apple devices will actually go ahead and inject this tag for you. However, don't be fooled because overall Apple has a small market share worldwide (it's the US where it is so popular). For Android and other devices this will make the content fit as it should on a mobile device. It looks like the line below:


<meta name="viewport" content="width=device-width">

In a nutshell, if you can't invest in a lot of mobile device functionality in your MVC application, adding at least the tag above will shape the content much better with little effort; there is no reason not to use it. Taking the styling to the next level is to modify sets of CSS for mobile and traditional sites.

It's pretty cool because he was creating MVC apps from project templates in VS.NET 2012, and running them both in Browser and using an simulator. One note on difference between an emulator and a simulator. An emulator actually emulates the hardware of the device, where a simulator just simulates the user experience of the phone. Keith was using various simulators like Android, Apple, and a mobile device with an Opera browser.

Tangent here, he asked: "Anyone doing JavaScript development for Windows 8?" Not a single hand was raised. Not telling necessarily of this in the future, but as of today there doesn't seem to be a ton of Win8 development going on just yet.

Next he talked about (2) different layout files: _Layout.mobile.cshtml and _Layout.cshtml.The cool thing was that based on the browser type being sniffed out at runtime, the ViewEngine (Razor) looks at the user-agent value and then uses the proper _Layout file. Even though this is great, Keith does admit we are not at a euphoria when there is a single UI codebase for mobile and desktop devices. You still have differences in files but this is to be expected. He has done a ton of mobile sites and this is always the case.

Tangent again, he asked: "How many people are own a Windows Phone?" In a room of 150ish, there were like 5 hands raised.

Next he went down a level to have multiple display modes based on device: Android, iPhone, etc. This is avaliable as of MVC 4, and if you are doing mobile development for the masses, this is reason enough to upgrade. The 'display modes' are registered in Application_Start(). He used a slick lambda expression to compare the user agent to the string of the new display mode to override the user agent (context.GetOverriddenUserAgent()). A new display mode is registered with the ViewEngine. If the newly added display mode, say "iPhone" was added, and user-agent value (i.e. "iPhone") matches then the display mode will be used. Note: Google user-agent strings if you need a reference to the actual names that are used.

jQuery mobile is a JS library for touch optimized devices (tablets, phones, etc.). The scripts can be easily downloaded from NuGet (or directly from the web). NuGet by the way can be used within the enterprise (NuGet server exists internally) to download packages (i.e. custom internal components) to keep everyone on the latest and greatest. It is HTML5 markup driven. It is supported in about 99% of any modern mobile browser so no worries there.  Use the data-"dash" attribute to store data across HTML or JS. 'jQuery.Mobile.MVC' (superset of jQuery Mobile) will add everything the 'jQuery.Mobile' package does, but in addition it adds MVC views to allow switching views between the "Mobile View" and "Desktop View". It also adds the (2) Layout files: _Layout.mobile.cshtml and _Layout.cshtml.

This session had some great information on helping make MVC sites have mobile capabilities with very little work. After all we are all about working less and doing more.


Controlling ASP.NET MVC 4
Phillip Japikse, MVP & Developer, Telerik



With VS.NET 2010 and MVC 4 there have never been more project templates available to help us get started developing MVC sites. In fact enough of the industry complained and they even have a Facebook site template, yikes! For so long people would go 'File -> New Project' and then go, "Now what?" The various templates help get us started in a variety of ways. While the default home page on a MVC site may never be used out of the box, it at least shows how it's used.

So Phillip asked how many people do mobile development, and about 1/4 of the room raised their hands. Then he said how many are web developers, and the whole room did. He said, those that are developing for the web are also developing for mobile. Any web application exposed outside the firewall will be accessed by mobile devices, so it's something we need to embrace.

OAuth is not included in the 'Internet' template. We can leverage, Microsoft, Google, Facebook, etc. for the login and leverage their sign-on for creating a single-sign-on (SSO) scenario. Uncomment a few code blocks and it's done!

He also touched on the "viewport" tag which was discussed in the last session. It comes for free and makes it so we don't have to view desktop versions of a site (with a magnify glass) on a mobile device. Once again, jQuery.Mobile was touted for View Switching. He demonstrated how it adds a widget to the site to allow users to click on a link to switch between desktop and mobile versions. This is useful in scenarios where a website has not been customized for mobile devices yet. Imagine you have a production site, widely used, and all the sudden it does not work on the iPad mini. Do you have time to rewrite the CSS and markup? No, and this is where you can add in the View Switching functionality.

Love it! Phillip: "How many people are doing System.Threading.Thread.Start?... you're doing it wrong. It's hard and there's a reason C++ devs became C# developers. There is an easier way to do things."  This falls right in line with multiple of my previous posts (and some still in draft form: async in C# 5.0). Async and await in Framework 4.5, or TPL since Framework 4.0. One interesting note, in MVC 3 there was no way to modify the controller without creating a separate class, inheriting from IController and putting all the controller functionality within. In MVC 4, you just subclass all of the controllers to another class that derives from AsyncController and get all of the functionality of async operations.

Next he rolled into a little on Web API. He confirms as I have in several of my comments that WCF is a bit of a bear and has a significant learning curve. I think he was trying to show that WCF is too heavy and use just Web API because of its loads of features, but several in the crowd disagreed. WCF is one of those technologies that if you just dab in it, it's tough to be fully productive. He does say, and I agree, that the majority of people that like WCF have spent the time to learn how to use it. With the Fall 2012 ASP.NET update there are Web API performance enhancements.

Tangent - "How many people use Web Matrix?" Not one person in the crowd of 100-200.

On the note about the 'Fall 2012' ASP.NET update, it's pretty significant. There are actually breaking changes like some things removed from Razor (rare non-used methods) and breaking the MVC RTM. There are NuGet packages that can be downloaded (Tools Update) from Microsoft which will fix these issues. Bottom line, if starting a new project make sure to get the Fall update before building the project.

Tangent - Phillip always cracks me up (I have been to his sessions in the past). He has everyone stand up 'to stretch'. He tells people with even number birthdays to place there hands together (like prayer), and odd number birthdays to open their arms up with palms up. You get the entire crowd looking like there are standing up praising him, and then he takes a photo. Nice!

In a nutshell (yeah a lot of O'Reilly books with that title), MVC 4 has matured greatly and is loaded with features for both desktop and mobile website development.


Creating RESTful Web Services with the Web API
Rob Daigneau, Practice Lead, Slalom Consulting



This is a session I had starred on my agenda and have been looking forward to it all week. Top it off that I think Rob is a great presenter with over 20+ years of development experience (loved his 8mhz CPU with 16mb of RAM computer and the rest is ancient history). The room is packed as I would expect. He touts Web API to be a lot better to use than WCF Rest based services which is a more clear cut opinion than that of Miguel's class on Day 1. 

He started it off with a room vote of the following:

  • How many people use WCF: Almost 100% of the room
  • How many people use WCF RESTful services: About 1/5 of the room (including myself)
  • How many using ASP.NET MVC: About 1/2 the room.
Interesting that he mentioned that some think that REST based services are only used for basic CRUD operations. I had never know that to be, but interesting and yes very far from the truth.


The Web API is built atop of ASP.NET and the MVC architecture. They are also based on the REST architecture. The REST architecture has constraints like statelessness, requiring a Uniform Interface (HTTP - GET,POST,PLACE,DELETE), Unique URIs, and resources manipulated through representations (from client to server back to client to change the state of the client). Bottom line, Web API does not follow the REST architecture to a 'T', but nether does WCF. Just don't tell a Restafarian that you are creating a REST based service using Web API or you might get scolded (but who really cares, this is a purist thing).

Web API has a project template in VS.NET 2012 under the 'web' heading. The default template shows an example of basic calls which is nice to get started. The cool thing is scaffolding a new controller for a Web API call. Just like scaffolding a MVC controller off an entity or model class, we can do the same for a API controller:



He also highlighted the ability for the client to set in the header the ability to request XML or JSON to be returned. How much work for the developer? None. It's all baked into the Web API project and done for you. Nice!!

For MVC developers, routing is the same using Web API. The default route template will build a route like this:  /api/{controller}/{value}, where 'value' is optional. Once again convention is used when calling the controller. If a HttpGet is done, then the action sought out will be one with the name 'Get'. Cool thing is you can add descriptions on the end and it will still work (i.e. GetAllNames()) as long as the 'Get' is still there.

You can use an instance of the 'HttpClient' class to make calls to a RESTful service. Of course any type of client can call your RESTful service (Java, .NET, etc.) but this is the best way to make calls from .NET. Adding the header to request XML or JSON on this HttpClient instance is a single line of code: client.DefaultRequestHeaders.Accept.Add(). There was another method when doing a HttpPut called client.PutAsJsonAsync. This stuff is great!

He recommends not only sending back status codes from the server like (200 OK, 201 Created, 404 Not Found, 500 Internal Server Error), but also sending a timestamp. This way multiple clients trying to do say a PUT on the same resource will have the ability to handle concurrency with the time value.

Remember that HttpGet and HttpDelete are supposed to be idempotent. You can call over and over and the result will not change. A HttpPut is not idempotent.

He showed a few examples adding additional routes to constrain to HttpPost calls and allowed calling non-Http verb method name calls (i.e. DoSomething()). Obviously this is desired as mentioned before, you are really going to want to do more than just CRUD operations that map to the standard Http verbs. Just make sure to build a new route in Application_Start for this because the default route will not find a non-standard named method on the controller.

Rob also presented some examples on how you can expand beyond the XML/JSON return types to other supported media types over HTTP like 'CSV'. It's based on the client's accept header value so any of the supported types can technically be returned by the RESTful service. This was cool stuff, but I think for the majority of folks getting into REST based services will be fine with JSON and XML. This stems from the fact the the need to require a REST based service usually comes with a request to have client/technology/platform agnostic services.

A brief discussion was had on query string vs. URL parameters (between the slashes) vs. building up the body of the request with request parameter values. It's all preference, but there are URI length limits. If a query string or list of URL values gets too long, then one should build up the body of the request. Combine this with MVC model binding and you could have a pre built object from the request once it hits the server.

Lastly he spoke to errors. Returning 500 codes is not the best way. Remember with SOAP services we had rich .NET exception handling between the service and the client. This is not the case with REST based services. He suggested at a minimum to create a HttpResponseMessage(HttpStatusCode.BadRequest) and fill it with a robust description of what error occurred from the request. But the coolest method was to create a .NET exception and and add that to the Response message along with the BadRequest value.

This was one of the best sessions I've been to and I can take a lot of what I learned and that Rob provided and apply it in new Web API service applications.

Wrap Up Day 3




Another fantastic and information packed day here in Orlando! My favorite session was the one on Web API but I got great information from all of the sessions. I think the most popular session overall was John Papa's on JavaScript as it almost filled the entire keynote hall. JavaScript is not something I have an strong passion for, but I got a lot of information to sharpen my skills if needed. I'm also happy to announce we passed by 12/12/12 12:12:12.12 with no problem at all today. :-P Well it's time to rest up, eat some dessert, and get ready for another great day tomorrow!

Monday, August 13, 2012

Using ValueInjecter With ViewModels and Entity Framework in ASP.NET MVC

If you decide to use ASP.NET MVC with the Entity Framework, you will quickly come to see that the perfect one entity per view scenario that most of the examples show is not realistic. Enter the need for ViewModels. The ViewModels are specially shaped classes that act as an intermediary between the 1...n entities that will eventually comprise a single view (or partial view).

The challenge is when it comes to repopulating the original 1...n entities that comprised the ViewModel upon the user making an insert or an update. In our perfect one entity to one view scenario, MVC model binding takes care of all the work repackaging our entity in the controller, and it is a matter of a few lines of code to add that object to the EF context and save the changes. Code in this scenario would be as straight forward as the following:

[HttpPost]
public ActionResult Create(Contact contact)
{
    if (ModelState.IsValid)
    {
      using (var context = new AdventureWorksEntities())
      {
        //Add the model bound object to the context and save:
        context.Contacts.AddObject(contact);
        context.SaveChanges();
        return RedirectToAction("Index");
      }
    }
    return View(name);
}
When using ViewModels, a convenient option to help reduce any manual mapping back to entities is to use an open source product named ValueInjecter. You can download the binaries from NuGet located here.

Value Injecter allows us to easily map properties from a source object to a destination object without what would be normally required to rehydrate the multiple entities. The main method we will use is the exposed InjectFrom() which will allow us to inject the values from the source to destination object. Once complete, we can then persist our entities back to the data store using EF with only a minimal amount of additional coding.

To begin let's take a look at the following ViewModel class I created based on (3) different tables from the AdventureWorks database: Contact, Employee, and EmployeeDepartmentHistory. The idea here is that we need to add a new employee record here that spans these (3) tables. The focus here is not on the schema from the AdventureWorks database but rather just to display how Value Injecter can be used to persist data to these (3) entities. As you can see below the ViewModel class has fields from each of the tables; however for brevities sake I have kept the class small. In reality there are quite a few more required fields that would have to be defined.

namespace Mcv4ValueInjecterSample.ViewModels
{
  public class EmployeeViewModel
  {
    [StringLength(50), Required]
    [Display(Name = "Employee First Name:")]
    public string FirstName { get; set; }

    [StringLength(50), Required]
    [Display(Name = "Employee Last Name:")]
    public string LastName { get; set; }

    [StringLength(50), Required]
    [Display(Name = "Email Address:")]
    [DataType(DataType.EmailAddress)]
    [RegularExpression(@"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}", ErrorMessage="Please enter a properly formatted email address.")]
    public string EmailAddress { get; set; }

    [StringLength(25), Required]
    [Display(Name = "Phone Number:")]
    [DataType(DataType.PhoneNumber)]
    public string Phone { get; set; }

    [Required]
    [Display(Name = "Birth Date:")]        
    public DateTime BirthDate { get; set; }

    [StringLength(50), Required]
    [Display(Name = "Title:")]
    public string Title { get; set; }

    [Required]
    [Display(Name = "Employee Start Date:")]
    public DateTime StartDate { get; set; }
  }
}
Next I have an EmployeeController class with a Create() method that takes in my ViewModel type as its parameter. I am going to inject the values from the model bound ViewModel object data into the individual underlying entities and then save the changes.
[HttpPost]
public ActionResult Create(EmployeeViewModel employeeViewModel)
{
  if (ModelState.IsValid)
  {
    using (var context = new AdventureWorksEntities())
    {
      var contact = new Contact();  
      //Inject the values into a Contact entity using ValueInjecter                  
      contact.InjectFrom(employeeViewModel);

      //Do NOT use the title submitted by the client, 
      //but rather override with a default value
      contact.Title = string.Empty;

      var employee = new Employee();  
      //Inject the values into an Employee entity using ValueInjecter                  
      employee.InjectFrom(employeeViewModel);
        
      var employeeDepartmentHistory = new EmployeeDepartmentHistory();
      //Inject the values into a EmployeeDepartmentHistory entity using ValueInjecter
      employeeDepartmentHistory.InjectFrom(employeeViewModel);
        
      employee.EmployeeDepartmentHistories.Add(employeeDepartmentHistory);
      contact.Employees.Add(employee);

      context.Contacts.AddObject(contact);
      context.SaveChanges();

      return RedirectToAction("Index");
    }
    return View(employeeViewModel);
  }
}
Note the explicit assignment of the Title property on the Contact object above. In the Adventureworks database, both the Contact and Employee tables have a Title field. My Employee view had an input for the client intended to fill out the Employee's title and not the Contact's title. Value Injecter by default will not discriminate and simply hydrate the destination object based on the matched property name (as designed so this is OK). Just make sure to intervene where needed if you run into a situation with identically named properties on objects.

That's it! There is actually a lot more functionality to ValueInjecter than what was shown here so I encourage you to look at the Documentation section on its CodePlex page. However even just this example can be scaled nicely to large legacy or existing databases where the 1:1 view per entity scenario rarely occurs. In this case consider using ValueInjecter to save on a lot of additional coding when using ViewModels in ASP.NET MVC.

Tuesday, March 22, 2011

ASP.NET Web Forms vs. ASP.NET MVC

So it has been a few years now since Microsoft introduced the ASP.NET MVC Framework which is Microsoft's implementation of the MVC Architecture for ASP.NET. No the MVC (Model-View-Controller) architecture is not a new concept; just Microsoft's implementation of it in the .NET Framework. There has been a lot of buzz around whether to continue to use ASP.NET web forms which have been around since 2001, or to go with this "hot" new technology in ASP.NET MVC... or something else! There is no 'Silver-Bullet' answer to this, and with most situations, 'it depends'.

Oh I know, you might have "Googled" the exact phrase of this blog post and were hoping to get some answer to exactly which one is better. Nope. I just want to highlight a few of the strengths and weaknesses of both from an abstract point of view, and briefly mention some other alternatives too.

To begin, I am going to repeat a stat that Andrew Duthie (Twitter handle: @devhammer) brought up on this topic at an ASP.NET Firestarter event in Orlando last December. He showed a stat that somewhere in the range of 80%+ dev shops were still using ASP.NET web forms for their bread and butter applications, and that ASP.NET web forms were not going away! Anyone trying to spread a rumor like that needs to check with the folks direct from Redmond 1st, because it simply isn't true. To this end, folks shouldn't feel like they missed the last train to MVC euphoria because everyone hasn't boarded yet. I am not building up an article against MVC; I just want to point out that it is a misnomer that ASP.NET MVC has completely replaced an outdated web forms architecture that some may speak convincingly of on forums and blogs.

So maybe you are leading a team of developers and are looking to decide the pros and cons of MVC, or maybe you are about to build a site for a friend/family member as fast as possible, or involved in a large scale enterprise application that will be web based. Whatever the scenario, you want to know the details of which architecture to choose. After all it will be quite difficult to change between the two once the code begins to flow. Making the right decision up front is important in any of these scenarios no matter how small or large the project.

Let's 1st speak to the advantages of the MVC framework. 1st and foremost in my book is the Architecture itself: M-V-C. It is going to be tough to break this model and rearrange how the application is built. Having your or your team's hand forced into a stable and mature architecture like MVC is a good thing. Raise your hand (like anyone can see...) if you have ever seen or maybe written one of those spaghetti sandwich ASP.NET web forms application that has raw SQL right behind "btnSave_Click()". Blah! Awful nasty, all code-behind the forms, non-scalable mess of an application. So 'point' to MVC for guiding developers to a decent architecture. You can adhere to several good architectures using ASP.NET, but it is up to the developer or team of developers to be disciplined enough to stick to the architecture and not lay back on a fat UI layer. Separation of concerns is a key Object Oriented Concept and a real winner for the MVC architecture. Each layer has its own responsibility, and placing the proper code in its responsible layer will make for a much better code base to scale, maintain, inherit, etc.

Next ASP.NET MVC allows the developer to have "Full Control" over the rendered HTML. For now I am going to leave this as an advantage for MVC, but caution that not everyone fully understands what this means, and it might not be advantageous for a vast majority of applications not needing this type of control. Let me elaborate a bit; that wonderful winter of 2001 when many of our lives took a turn for the better as Scott Guthrie (Twitter handle: @scottgu) came up with what is ASP.NET web forms, and decided while sipping hot cocoa that if you drug a label onto a web form, it would get rendered as a DIV tag. He made this decision (or Microsoft) and not you. You pick the ASP.NET server controls you want to drag onto a web form, but don't have control over what HTML elements actually get rendered on the client as a result. You just know that when a Gridview is dragged onto a form, it will be displayed on the client. You don't know (or need to in many situations) that it might be a series of DIVs and Input HTML controls. This abstraction is actually an advantage for ASP.NET web forms. For many web applications built, we have relied on this drag and drop capability, and trusted the final output that will be rendered to ASP.NET. However, if you have ever found the way the ASP.NET sever controls get rendered is not exactly how you want or need it, then MVC is a better choice as it will allow you to have control over the final rendering. If you do not have any main issues with how ASP.NET web form server controls get rendered in your applications, then this might not be an "advantage" that you can sell to your tech manager or team when trying to build the next project using MVC.

Another advantage of using ASP.NET MVC that ties back into the individual layers is testability, specifically unit testing. Because the application is loosely coupled with code in its separate layers, the ability to create unit tests increases greatly. The event based ASP.NET pages that rely on things like Session, Context, Response, etc are quite difficult to effectively test because of the inability to isolate specific page functionality due to its nature of being spread out and external dependencies as well. MVC improves on this greatly, and is architected to be testable. 'Point' MVC.

So let's examine ASP.NET web forms for a minute. As I mentioned they were born sometime in late 2001, so maturity and a rich tool set (both from Microsoft and 3rd party) is a big advantage. These "tools", or ASP.NET server controls make up a style of development referred to often when speaking of ASP.NET web forms called RAD or Rapid Application Development. "Hey I can drag a few ASP.NET text boxes, some labels, this Gridview thingy, press publish, and WHAT??!! I have a website!" Now that website might be junk, but hey its done already. On to the next project, right? Well not quite. 'Fast', especially in our field doesn't mean better. That site might be done, but as eluded to prior, its design is junk and it will not maintain or scale well. But what if you know the scope is a single, simple page? Well then a tool like web forms is probably perfect, and MVC might be overkill if speed of development is of the essence. Don't be fooled, web forms + data binding, etc. will be faster to generate just based on the drag-and-drop + wizardry capabilities. Just don't have a code review and everything will be fine! So the RAD capabilities of ASP.NET web forms can be a double edged sword. A quality ASP.NET web forms with a pre-determined architecture (3-layer, Domain Driven Design, MVP, etc.) that uses developers with discipline to adhere to it, is a much better choice when creating ASP.NET web form applications.

Along these lines is another advantage with web forms and that is 'Experience'; specifically in relation to a developer's experience with the technology. Again with web forms being a mature technology going on 10 years, there is a solid developer core with ample experience. If you are leading a team of 8-10 developers, you are the only one with MVC experience, and everyone else knows web forms, then this needs to play into your decision of which technology to use. Are you prepared to take the financial impact of formal MVC training through remote seminars, current books, or on-sight training? Can you afford the 1-3 month setback while the team gets up to speed on ASP.NET MVC to say a beginner/intermediate level? If these are not an issue, and the advantages of ASP.NET MVC mentioned previously are present, then it may be the better choice regardless of the upfront cost in time, money, etc. If however, you need to begin writing code immediately with a team of web form rich experience developers and are under a tight deadline, then maybe holding off on using MVC is the better decision. In the end you need to weigh the factors to make the best decision.

There are some other disadvantages to the web forms technology that I will mention briefly here as well. The web form's postback model uses client side generated '_doPostBack()' events for each server callback. If JavaScript is disabled this will cause several problems for the web forms application. It is also difficult to manipulate manually if writing your own client side scripts. MVC improves on this using REST based URLs. The next disadvantage with web forms is ViewState. Referring back to my comments about poorly designed web form applications, a bloated ViewState can cause pages to be larger and slower than they need to be. ViewState stores a base64 encoded string with information about controls state to persist postbacks and to help combat the stateless nature of the web. This however becomes a disadvantage for web forms when abused.

Now let's throw a cog into the wheel and add in another choice for web development in the .NET realm: Silverlight. Oh yeah, and honestly my favorite when it comes to rich UI content. However, you still need a hosting application and Silverlight can be integrated into either ASP.NET web forms or ASP.NET MVC applications. And I don't want to confuse anyone either because Silverlight is not an entire 'web' Framework onto its own and only works alone as individual controls. The Silverlight controls integrate into a web forms or MVC application as just another control and can co-exist with controls of either technology. However, since Silverlight can't invoke the controller class in MVC, or directly postback to the server when using web forms, you will need to use services (WCF) to accomplish this task. Anyone using Silverlight previously knows that WCF services can bridge the gap between the Silverlight control and the server.

Decisions, decisions, which technology to pick? There is a lot to weigh when it comes to these two technologies: ASP.NET web forms or ASP.NET MVC. Are you trying to draw a line in the sand and say, "Only MVC web apps from here on out!!" Personally I would not do that, because it wasn't like 10 years ago when we moved from classic ASP to ASP.NET and were able to be that bold. Now ASP.NET MVC has to be looked at as another tool (a very powerful and cool one) in the proverbial toolbox. There will be a time when MVC is the proper decision, and a time when web forms is the proper one. I strongly urge those picking web forms to at a minimum not fall into the trap of bad or poorly architected code, and be disciplined to use an architecture that is more scalable and maintainable (check my review of the book Professional ASP.NET Design Patterns). And lastly and maybe most importantly, be a 'realist' and not a 'purist' when making this decision. Do what is best and right, and not just which one theoretically is better in argument. This will help you decide. Either way its great to be a .NET developer with such a plethora of technologies to choose from.