Posts
203
Comments
1119
Trackbacks
51
August 2010 Entries
DC DNUG Presentation Code Samples

Thanks to everyone who attended my MVC 2 presentation last night at DC DNUG. I was very impressed with this new user group. We had a good turn out and got good questions from the participants. The code and PowerPoint from the presentation can be downloaded here.

Posted On Thursday, August 26, 2010 11:49 AM | Comments (0)
MVC 2 Presentation at DC DNUG

Wednesday night (8/25/2010) I will be presenting Top 10 Ways MVC 2 Will Boost Your Productivity at DC DNUG. This is a brand new user group that just started a couple of months ago and it will be my first time there. I hope to see you there!

Posted On Monday, August 23, 2010 8:02 PM | Comments (2)
RESTful WCF Services with No svc file and No config

While Microsoft continues to add features to WCF with each version, they are also adding features that simplify working with WCF services as well. Historically WCF has been somewhat intimidating to the uninitiated because of the non-trivial configuration for endpoints including behaviors, bindings, and much more. For this reason, a lot of people stayed with “old school” asmx web services. With the new features of WCF 4, you can build powerful web services with *no* svc file and *no* endpoint configuration.

Building a RESTful WCF service in this way is quite easy and you don’t need rely on any item templates.  Just start with a blank asp.net web application project in Visual Studio. The web.config file is virtually empty:

   1:  <configuration>
   2:      <system.web>
   3:          <compilation debug="true" targetFramework="4.0" />
   4:      </system.web>
   5:  </configuration>

Next just add a regular C# class - for this example, I call mine PersonService and it will have basic CRUD operations. Typically we create interfaces in WCF to define our ServiceContract and operations like this:

   1:  [ServiceContract]
   2:  interface IPersonService
   3:  {
   4:      [OperationContract]
   5:      Person GetPerson(string id);
   6:   
   7:      [OperationContract]
   8:      Person InsertPerson(Person person);
   9:   
  10:      [OperationContract]
  11:      Person UpdatePerson(string id, Person person);
  12:   
  13:      [OperationContract]
  14:      void DeletePerson(string id);
  15:  }

Keep in mind, this step is *not* required. You *could* decorate your service class directly with these attributes and not even have the interface at all. However, in this case, it’s a nice convenience to encapsulate all the WCF attributes on the interface rather than your implementation class. The implementation of our PersonService class looks like this (I’ve removed the code that access the data store for brevity):

   1:  [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
   2:  public class PersonService : IPersonService
   3:  {
   4:      [WebGet(UriTemplate = "Person({id})")]
   5:      public Person GetPerson(string id)
   6:      {
   7:      }
   8:   
   9:      [WebInvoke(UriTemplate = "Person", Method = "POST")]
  10:      public Person InsertPerson(Person person)
  11:      {
  12:      }
  13:   
  14:      [WebInvoke(UriTemplate = "Person({id})", Method = "PUT")]
  15:      public Person UpdatePerson(string id, Person person)
  16:      {
  17:      }
  18:   
  19:      [WebInvoke(UriTemplate = "Person({id})", Method = "DELETE")]
  20:      public void DeletePerson(string id)
  21:      {
  22:      }
  23:  }

This is just a normal C# class that implement an interface. It’s also decorated with the typical WebGet/WebInvoke attributes (in the System.ServiceModel.Web namespace) that we use for RESTful services. Also notice that 3 of the 4 methods have the same UriTemplate but they are differentiated by the HTTP method (i.e., GET/PUT/DELETE). Also notice the AspNetCompatibilityRequirements attribute – this is needed for RESTful services that are processed in the ASP.NET pipeline as described here. You also have to add this to the config file (I know, I know – I said “no config” but I meant “no ugly WCF endpoint config”!):

   1:  <system.serviceModel>
   2:    <serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
   3:  </system.serviceModel>

So how do we take this regular C# class and make it into a service without an *.svc file?  The System.Web.Routing infrastructure has now been incorporated into WCF 4 to make this possible.  Just add the line of code (line #5) to your global.asax:

   1:  public class Global : System.Web.HttpApplication
   2:  {
   3:      protected void Application_Start(object sender, EventArgs e)
   4:      {
   5:          RouteTable.Routes.Add(new ServiceRoute("", new WebServiceHostFactory(), typeof(PersonService)));
   6:      }
   7:  }

The WebServiceHostFactory makes RESTful services possible in WCF. The first parameter of my ServiceRoute constructor is an empty string which means that my URI of my service will hang right off of the root – this get combined with the UriTemplate defined in the WebGet/WebInvoke attributes.  So to get a person from my service, a URI would look like this:  http://mydomain.com/Person(21).  If I had specified “foo” instead of an empty string in the first parameters of the ServiceRoute constructor, then my URI would look like this:  http://mydomain.cmo/foo/Person(21).

That’s it!  You now have a fully functioning RESTful WCF service that you can fully test with Fidder for all HTTP verbs.

One interesting aspect to all this is that you can do all this in MVC as well. In fact, I typically do use MVC to return JSON to views for AJAX calls in my MVC apps. However, if you were building stand-alone services for this, would MVC be easier than the example of above? Keep in mind, we could simplify the example above even further by eliminating the IPersonService interface all together. I daresay that setting up RESTful routes like the ones shown above is easier with WCF than MVC (this, coming from an “MVC guy”) because we can apply the UriTemplates directly to the methods. To accomplish the same in MVC, you have to create custom route constraints to avoid the name of the C# methods from showing up in the URL (and honoring the REST HTTP verbs).  If you are going to do this, I really like the approach shown here. It’s a cool approach, but it’s *more* work than just doing it with RESTful WCF – no svc file and no configuration.

In fact, using the WCF infrastructure gets you even more features for free.  For example, if we add 1 more line of configuration (check out line #5 below) we get a help page and automatic format selection for free! Now our entire configuration just looks like this (and still no WCF endpoint configuration needed):

   1:  <system.serviceModel>
   2:    <serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
   3:    <standardEndpoints>
   4:      <webHttpEndpoint>
   5:        <standardEndpoint name="" helpEnabled="true" automaticFormatSelectionEnabled="true"/>
   6:      </webHttpEndpoint>
   7:    </standardEndpoints>
   8:  </system.serviceModel>

Notice all we had to do to get the help page was the request “/help”:

wcf help page

The automatic format selection in WCF will honor the Accept header and/or the Content-type header and return XML, JSON, etc. to the caller based on the value specified in the header. Again, that takes custom code in MVC which you get for free in WCF.

Posted On Saturday, August 21, 2010 9:17 PM | Comments (98)
Generics, Reference Types, Value Types, and Interview Questions

Generics are nothing new and have been part of .NET for over 5 years. Reference types and value types are core concepts in the CLR type system and these concepts have been the same since .NET was released – they are also nothing new. However, when I ask about these concepts during interviews, I often get a wide range in quality of the answers to these questions. If you get asked about these topics in an interview, be prepared to give great answers! You don’t have to give a textbook perfect memorized definition – but make sure you show that you fully understand and can apply the concepts to real-world development.

Question: why are generics such a big deal? I typically get answers discussing greater type safety and better performance. OK, the type safety one is pretty easy and straightforward. We had the ArrayList in .NET 1:

   1:  ArrayList list = new ArrayList();
   2:  list.Add(1);
   3:  list.Add(2);
   4:  list.Add("hello"); // compiler doesn't help me avoid!

When generics were introduced, we could declare a strongly-typed list of int’s to avoid this:

   1:  List<int> list = new List<int>();
   2:  list.Add(1);
   3:  list.Add(2);
   4:  list.Add("hello"); // compiler error!

So drilling into the second answer a little - *why* is performance better with generics? Often I hear, “you can avoid boxing and unboxing.”  OK great!  So what *specifically* is boxing and unboxing? (This is where people often start to struggle.)  Boxing is the act of converting a value type to a reference type. If we look at line #2 of the first code sample above, we’re putting an Int32 (a value type) into an ArrayList which stores everything as System.Object (a reference type). Therefore, unboxing is the act of converting a reference type to a value type (e.g., if we were taking an item out of the ArrayList and having to cast: int num = (int)list[0];). So with boxing/unboxing, don’t focus on casting or sub-classes (they’re not directly relevant!) – focus on converting from reference types and values types.

Question: what’s the difference between a reference type and a value type? Just focus on the basics: Reference types are stored in the heap (which means they are garbage collected) and value types are stored in the stack (cannot be allocated on the GC heap). Reference types can be null; value types cannot be null. Reference type variables do not contain the value – it has a pointer to its value. A value type variable contains the value itself.

Question: how do you know if a type is a reference type or a value type? Is a DateTime a reference type or a value type? A String? If you’re creating your own Person data structure, how can you control whether it’s a value type or a reference type? The short answer: a “class” is a reference type and a “struct” is a value type. If you “View Definition” in Visual Studio on a DateTime, for example, you’ll see:

datetime

DateTime is a struct so it’s a value type. System.String is a class so it’s a reference type (plus, the fact that it can be null is also a tip off that it’s a reference type). So if you create your own data structure as a class, it will be a reference type (as a struct, a value type).

For further reading on reference types, value types, and boxing/unboxing, have a look at this article by Jeffrey Richter written in December 2000. These are core concepts in the .NET type system that are still just as relevant today as they were 10 years ago.

Let’s circle back to our original generics performance question. So far we have 3 assertions:

  • Generics result in better performance because you can avoid boxing/unboxing
  • Boxing/unboxing is the act of converting between reference types and value types
  • A “struct” is a value type (e.g., DateTime); a “class” is a reference type (e.g., String)

Question: given all three of these assertions, is performance *really* better with a generic List<string> (string being a reference type) versus a non-generic list of strings? Answer: NO! Generics still provide *plenty* of benefit for these situations in terms of type-safety and allowing us to reduce noise in our code by avoiding having to cast objects (or code-gen objects if we want strongly-typed objects) – but a performance benefit is *not* on the list. However, if we’re talking about List<int> or List<DateTime> (value types) then here is a significant performance improvement. Not only is the run-time performance benefit significantly better because we can avoid the expensive boxing/unboxing operations, but we also avoid making the GC do extra work by having to collect these boxed objects that were just heap-based wrappers around what were originally value types.

In fact, let’s say you use 5 different generic List<T> in your application: List<string>, List<int>, List<DateTime>, List<Foo>, List<Bar> (where Foo and Bar are both reference types).  What happens behind the scenes is that the JIT will actually produce 3 versions of the generic list.  For each value type it will generate a totally strongly-typed version (so we’ll have 1 for List<int> and 1 for List<DateTime>). Then it will generate a single generic List<T> whose type gets re-used for all reference types behind the scenes (so it will get used for List<string>, List<Foo>, List<Bar>). But it is providing you the type-safety features along with allowing you to avoid all of the ugly casting in your code.

New .NET technologies come and go and as professional developers we are constantly working to learn and stay up-to-date on these new technologies. However, we also have to make sure we stay grounded in the fundamentals that .NET is based on. If you ever end up in an interview with me, I trust that you’ll ace these questions. :)  And, by the way, my company is hiring so if you’re interested, please contact me!

Posted On Friday, August 6, 2010 9:35 AM | Comments (11)

View Steve Michelotti's profile on LinkedIn

profile for Steve Michelotti at Stack Overflow, Q&A for professional and enthusiast programmers




Google My Blog

Tag Cloud