Friday, November 21, 2008

Validating URIs in C#

I wanted to share a quick tip on how to validate if a given URI is well formed. Normally this will work in the case you want to make sure the URI you are passing is well formed, although it won't validate if the URI is not broken. This is very useful for making URI validations, especially when you are working with Silverlight image controls when setting the sources by code.

Let's say we are receiving the uriString as a parameter and we want to assign that string URI to an image control's source property. What we need to use is the Uri.IsWellFormedUriString(string uriString, UriKind uriKind) which will check that the URI is well formed and that it doesn't required further scaping:

public void SetImageSource(String uriString)
if (Uri.IsWellFormedUriString(uriString, UriKind.Absolute))
this.Thumbnail.Source = new BitmapImage(new Uri(uriString));

Then you can use the "else" block to set the thubmnail image of our control to a default well formed URI.

Hope it is useful for you.

Thursday, November 20, 2008

Windows Communication Foundation Overview

I have been working with Windows Communication Foundation (WCF) for a while now, but I haven't published anything related to it on my blog recently. There are really cool and useful features in WCF 3.5 and I have been also researching about WCF duplex communication paradigm especially for Silverlight 2 applications. But before I get into advanced stuff, I think it would be good to write an overview of this Microsoft technology.

What is Windows Communication Foundation?
  • Windows Communication Foundation (WCF) is a secure, reliable, and scalable messaging platform for the .NET Framework 3.0.
  • WCF is an integrated Microsoft solution for the existing suite of .NET distributed technologies like .NET Remoting, ASP .NET Web Services, MSMQ, COM+ and WSE into a single programming model.
  • With WCF, SOAP messages can be transmitted over a variety of supported protocols including IPC (named pipes), TCP, HTTP and MSMQ.

What are the WCF Characteristics and Benefits?
  • Provides a single programming model (Service Model).
  • Provides a runtime for your services.
  • Service oriented solution for distributed systems.
  • Focused on interoperability.
  • Provides Isolation
  • Secure.
  • Reliable.
  • Simplified.
  • Flexible.
  • Extensible.

WCF requirements?
  • Requires .NET 2.0 Framework.
  • WCF is part of the .NET 3.0 Framework.
  • Visual Studio 2008
  • .NET Framework 3.5 for Silverlight and LINQ best support

WCF Main Components:
  1. Service Contract
  2. Data Contract
  3. Message Contract
  4. Endpoint

WCF Communication Workflow:

Services expose one or more endpoints where messages can be sent. Each endpoint consists of an address, a binding, and a contract. The address specifies where to send messages. The binding describes how to send messages. The contract describes what the messages contain.

Clients need to know this information before they can access a service. Services can package up endpoint descriptions to share with clients, typically by using Web Services Description Language (WSDL). Then clients can use the provided service description to generate code within their environment capable of sending and receiving the proper messages.

1. Service Contract: You model service contracts in .NET using traditional C# interface definitions. You can use any .NET interface as a starting point.To make this a WCF service contract, you must annotate the interface itself with [ServiceContract] and each operation you want to expose with [OperationContract]. These attributes influence the mapping between the worlds of .NET and SOAP. WCF uses the information found in the service contract to perform dispatching and serialization.

public interface IUserManager
bool AddUser (User user);

Dispatching is the process of deciding which method to call for an incoming SOAP message.
Serialization is the process of mapping between the data found in a SOAP message and the corresponding .NET objects used in the method invocation. This mapping is controlled by an operation's data contract.

WCF dispatches based on the message action. Each method in a service contract is automatically assigned an action value based on the service namespace and method name. You can customize the action value for each method using [OperationContract]. A value of * can be used for any action when a specific match doesn't exist.

2. Data Contract: The data contract is defined by the types used in the method signature. The way WCF serializes .NET classes depends on the serialization engine in use. The default serialization engine is known as DataContract, a simplified version of XmlSerializer, the default serialization engine used in ASMX today. DataContract defines attributes for annotating class definitions to influence the serialization process. With DataContract, only fields marked with DataMember will be serialized. And you can serialize private fields.

public class User
string username;
string password;

You can control the name of each element, the order, and whether a particular element is required, but that's about it. If you need to do anything more sophisticated, WCF lets you fall back to using XmlSerializer. You indicate your desire to use XmlSerializer by annotating the interface with [XmlSerializerFormat]

WCF also supports serializing types marked with [Serializable], which allows .NET remoting types to work with WCF without change. WCF provides an implicit mapping for [Serializable] types where all public/private fields are automatically serialized.

3. Message Contract:If you need to support headers, you can write another class that models the structure of the entire SOAP envelope for the particular operation, specifying which fields map to headers versus the body.You define this mapping with the [MessageContract] attributes [MessageHeader] and [MessageBody]

Using MessageContract is a more advanced technique that is only necessary when you need direct control over the SOAP contract. In normal cases you shouldn't have to touch the messages. But in some cases it becomes necessary. For example, assuming that your service will provide a File Upload operation. Unfortunetly, when using Streams, our operation can not take other parameters. So we cannot tell the fileName to our operation when uploading a file. You may always create two operations, one for setting the fileName, and the other one for uploading the file, but this is not a good solution. In order to solve this problem we will need to create a new message.

public class FileMessage
public string fileName;

public Stream stream;

Our message class needs to have the MessageContract attribute. Since WCF only allows the Stream in message body, we are keeping the fileName in message headers. To keep a data in message header we are using the MessageHeader attribute, and to keep a data in message body we are using the MessageBody attribute.

4. Endpoint: The ServiceHost class gives you direct control over the WCF hosting infrastructure. You instantiate ServiceHost based on a particular service type. In addition to specifying the service type, you also specify the base addresses for the different transports you plan to use. This will be used as the base for any relative HTTP addresses I might specify when adding endpoints. The base HTTP address is also used as the default for retrieving the service description.

You then add the service endpoints. Again, a service may have one or more endpoints and each endpoint consists of an address, a binding, and a contract. You provide this information to your ServiceHost by calling AddServiceEndpoint. This is where you specify the service contract you defined.

For the binding, you typically choose from one of the many predefined bindings that ship with WCF and an appropriate address given the binding's transport.

<endpoint address = "xml"
= "xmlBehavior"
= "webHttpBinding"
= "WCFMSDemo.IPeopleManager" />

Hardcoding endpoint information into the host application is not ideal since endpoint details may change over time. WCF automatically provides this functionality through the predefined configuration section. This increases deployment flexibility since the communication details are completely factored out of the compiled code. You can also configure bindings within . You can even define new custom bindings from scratch using the element, which would be equivalent to deriving a new class from Binding. When it comes to configuring endpoints, bindings, and even behaviors, anything you can do in code, you can also do through configuration

Hardcoding endpoint information into client code is also less than ideal.
So WCF provides a similar configuration mechanism for specifying client endpoints within . The application configuration file specifies the same client endpoint details used in the code.

Now when you want to create a ChannelFactory for the TCP endpoint, you can simply change the configuration name to tcpEndpoint. You can also configure bindings in the client configuration file just like is done in the service configuration file.

If you add this configuration file to the client console application, comment out the code to create the ServiceEndpoint objects, and specify the endpoint names when constructing each ChannelFactory, the result will be the same.

Hope this gives you a nice overview about WCF, what it is, what are its characteristics and benefits and what are the main components and what are their purpose. I hope to be posting more advanced stuff about it soon. Let me know if you have any questions about this and I'll do my best to help you.

Happy WCF!

Visual Studio Code Metrics Overview

As a developer I have always care about the quality of the code I write. But generally the quality of your code you think you are implementing will depend on the level of expertise you have and how important are best practices, standards and naming conventions. When you work with other experienced developers you will always find that code varies from developer to developer, and although the code can be different and use different coding practices it doesn't necessarily means that the code quality is better or worst.

In Visual Studio Team System 2008 you have a great tool for analyzing your own code or even the other developer's code in an objective way. This tool is called Code Metrics and is pretty easy to use and understand.

First of all, let's understand the different metrics the tool uses:

  • Maintainability Index: Calculates an index value between 0 and 100 that represents the relative ease of maintaining the code. A high value means better maintainability. The calculation is based on the Halstead Volume, Cyclomatic Complexity and Lines of Code. Color coded ratings can be used to quickly identify trouble spots in your code. A green rating is between 20 and 100 and indicates that the code has good maintainability. A yellow rating is between 10 and 19 and indicates that the code is moderately maintainable. A red rating is a rating between 0 and 9 and indicates low maintainability.
  • Cyclomatic Complexity: Measures the structural complexity of the code. It is created by calculating the number of different code paths in the flow of the program such as if blocks, switch cases, and do, while, foreach and for loops then adding 1 to the total. A program that has complex control flow will require more unit tests to achieve good code coverage and will be less maintainable.
  • Depth of Inheritance: Indicates the number of class definitions that extend to the root of the class hierarchy. The deeper the hierarchy the more difficult it might be to understand where particular methods and fields are defined or/and redefined. At the class level the number is created by calculating the number of types that are above the type in the inheritance tree starting from 0 and excludes interfaces. At the namespace and project level the calculation consists of the highest Depth of Inheritance calculation of all of the types within the namespace or project.
  • Class Coupling: Measures the coupling to unique classes through parameters, local variables, return types, method calls, generic or template instantiations, base classes, interface implementations, fields that are defined on external types, and attribute decoration. The calculation excludes primitive and built-in types such as int32, string and object. Good software design dictates that types and methods should have high cohesion and low coupling. High coupling indicates a design that is difficult to reuse and maintain because of its many interdependencies on other types.
  • Lines of Code: Indicates the approximate number of lines in the code. The count is based on the IL code and is therefore not the exact number of lines in the source code file. The calculation excludes white space, comments, braces and the declarations of members, types and namespaces. A very high count might indicate that a type or method is trying to do too much work and should be split up. It might also indicate that the type or method might be difficult to maintain.
Once you are clear of what each metric means and how it is measured you can run and use code metrics to see how healthy is your project code.
To get started with code metrics, you'll need to have either Visual Studio 2008 Team System Development Edition or Team Suite.

Open Visual Studio, and then open the project you want to calculate code metrics against. After you open the project, in Solution Explorer, right-click on the project or solution, and select Calculate Code Metrics. The time it takes to calculate the metrics will depend on the size of your project. Once it's done, it will open the Code Metrics Results window. The window is pretty straight forward on showing you the analysis results for each metric used. It also gives you a quick reference on how healthy your application code is. With this tool you can filter the results by max and min values, add, remove or rearrange columns in the results window, copy results to the clipboard, export results to excel or create work items based on the results.
For this post I calculated the code metrics of a trading small applications I have using WCF duplex communication. The window looks like the following:
As you can see the application code looks healthy. When you perform your tests make sure everything looks right, since letting pass bad code metrics will result in a very expensive maintainability process.

Hope this is useful information for the readers.


Wednesday, November 19, 2008

DevConnections 08 Day 2

1. Introduction to the ASP.NET MVC Framework – Markus Egger, EPS Software Corporation

Not a very high level talk but good enough to reinforce the basics about the MVC framework. Along with Hanselman’s talk, they emphasized a lot about ASP.NET being greater than WebForms and not synonymous, as many people thought in the past. So ASP.NET contains WebForms and MVC and they can even be mixed together. Egger presented a few examples of when you should use MVC, and that WebForms isn’t going anyware and that it’s going to keep growing. He also implemented a couple of code samples and showed how the calls where routed to the controllers and how to modify them.

2. Language Integrated Query (LINQ) – Dave Sussman, IPONA LTD

I was expecting this presentation to have a higher level and learn some deep stuff about LINQ, but it was pretty much covering the basics behind how LINQ works and how to take advantage of its features. Sussman talked about how to use SQL not only for SQL, but for objects and XML. He covered a little about query expressions, lambda expressions, type inference, anonymous types and object initializers. He also talked about extension methods with LINQ and its benefits.

3. User Controls and Custom Controls in WPF – Dino Esposito, IDESIGN, INC.

Very basic talk about WPF controls and how user controls differentiate from custom controls. Again, disappointing because after having WPF around for a couple of years and having many development being done already, I was hoping to see advanced stuff about it, but instead it was the most basic overview about the different types of controls (containers, lists, text controls) and how to modify themes and templates to create custom controls. Honestly, I was hoping this was way over, and that people were already more familiar with WPF. I guess that since the conference was more focused on enterprise business solutions, the crowd was less familiar with “new” technologies. Dino also talked about the XAML and controls differences between Silverlight and WPF.

Anyway, here are some of my notes about what he presented:
Content Controls: constrained to contain a single item, although that item can be a full hierarchy of controls (Tab Control).
Item Controls: contain a collection of arbitrary controls.
Range Controls: numeric value in a range that doesn’t support arbitrary content (slider, progress bar).
Text Controls: interactive controls for text (like the SpeelCheckEnabled property of text controls)

Regarding styles and templates he talked about the two types of templates: Control Templates and Data Templates. About the last ones he remarked that they change the rendering of non UI elements. They are defined in the resources and also to use content presenter to bind properties. (Nothing we didn’t knew already).

Regarding User Controls he said that the need for a custom control should be based on the API you want and not on the appearance, because you already have styles and templates for that. You should also have present that they will have limited need for reuse, styling and theming.

4. Data Access with Silverlight 2 – John Papa, ASPSOFT

This presentation was one of the best ones in the conference. Papa is a really smart guy with a lot of experience with ASP.NET, WPF and Silverlight, so his presentation was on a good level, organized and well oriented. He talked about the different ways to retrieve data in Silverlight using bindings and presented a lot of running examples about it. At the end of the presentation I went to meet him (very cool guy) and he talked about having several silverlight controls on the same ASP.NET vs having a single control in ASP.NET. He was more inclined for the second option. Make sure to check out his site.

He started talking a little about when to use LINQ: To objects, to JSon, to XML, to SQL and to entities, and then talked about manual binding vs. declarative binding and how the latest can save you lots of work and be less prone to error.

He defined two rules for XAML binding:

• #1: the target of data binding must be a framework element (most of the cases)

• #2: the target property of the data binding must be a dependency property (dependency properties keep popping out everywhere).

On the demos he was showing he was demonstrating how to set the data context at the container control level and then how easy it was to just specify the properties in the child control bindings and how this helps on the designer-developer workflow since a Blend designer can receive the list of properties from the developer, bind them to the controls without having the actual object in place.

He talked about the different binding types: OneTime, OneWay and TwoWay binding depending on the functionality you want for your application. He remarked that objects must implement the INotificable interface in order to be able to receive notifications when the property changes. I know this is now new, but the way he explained with code samples was simple and concrete. He also mentioned the INotifyCollectionChanged which notifies when a list of content information changes. He also said that ObservableCollection generic can be used.

We now jumped on how to consume data services. You know have REST, SOAP/WS, RSS/ATOM JSON and POX. He remarked how easy and robust was to build data services with WCF using the Silverlight Enabled WCF template. He explained the two types of cross domain files that you can find: ClientAccessPolicy.xml which is the one for Silverlight, and the CrossDomain.xml which is the one that you will find in most cases. If the SL app cannot find the first one, it will look for the second one.

DevConnections 08 Day 1

1. KeyNote – Scott Guthrie, Microsoft
Scott Gu’s keynote wasn’t exactly impressive, since there weren’t surprising release news or anything like that (all that happened during PDC2008 a couple of weeks ago) but it was good to see him and get to meet him too.

During his presentation he talked a lot about ASP.NET MVC Framework and its enhancements for Visual Studio regarding the project templates. Unit Testing improvements, ASP.NET enhancements, CSS2 support, Master Pages optimizations were some of the topics he touched. He also remarked on the future capabilities of VS2010 for working with ASP.NET (WebForms and MVC). He also talked a little about Silverlight and presented six successful applications, and two of them were Schematic projects: NBCOlympics08 and Library of Congress, so that was pretty cool.

After the presentation I went to meet him and talk a little. He said that next version of Blend is going to support TFS connectivity and that the workflow between Blend and Visual Studio is going to be improved on the next versions. Visual Studio 2010 will have many improvements on the visual designer for XAML pages, so that’s great. He also said they were working very hard on making the integration between Silverlight and MVC as seamless as possible.

2. Visual Studio Team System: Soup to Nuts – Doug Seven, Microsoft
This presentation was pretty much covering the features of Visual Studio Team System and the differences with other Visual Studio versions. He covered Work Items, Documents, Reports and builds but he hadn’t enough time to present advanced techniques of higher level tools. He remarked the traceability enhancements that VSTS offers for large development teams with the source control and work items features. He said that they know that PM’s and people outside the .NET development teams have a hard time getting used to VS, so that in the future we could expect lots of improvements for Team Access and on the Team Project site that VSTS generates when creating a new team project. He mentioned also more integration between VSTS and Office applications like excel, which is already there but it is going to be enhanced. He also mentioned new enhancements for Agile Development templates, although he didn’t went into details. Regarding VSTS 2010 he showed a nice tool for previewing refactoring changes, so you can know exactly how the changes are going to look and what files and classes are going to be affected.

After that he went into details regarding the Data Base features showing how to make schema comparison between local and remote database versions, and that we will be able to use Unit Testing for the data base. One of the features he remarked was the data generation tools for testing with “almost real” data. At the end he pointed out that the next VSTS version will have heavy enhancements for testers.

3.Silverlight Controls, From Soup to Nuts – Jesse Liberty, Microsoft
This one was a disappointing one. I knew that Jesse Liberty is not that good just by looking at his tutorials on the Silverlight web site, but I was hoping to see something cool or learn a couple of tricks. The truth is that we are beyond the level of this conference, and what he exposed was very basic, pretty much how to use silverlight controls and change their styles and templates, something that I believe we all know how to do, and do it better than it was demonstrated.

4. ASP.NET MVC: So what? – Scott Hanselman, Microsoft
This one was a great presentation. He clarified a lot of confusing points about ASP.NET MVC framework and he is also a great speaker so this one was fun and interesting. The most important thing to remember about this one is that he made a lot of emphasis about ASP.NET being greater than WebForms or MVC, so they are all part and contained by ASP.NET. The key is to learn and to think about how to mix things like this inside ASP.NET. For example you could have ASP.NET applications that combine WebForms, MVC and Silverlight. He also mentioned that ASP.NET MVC will have full support for JQuery since Microsoft if fully supporting it.

Hanselman showed a couple of demos showing how MVC routes the requests hiding the URL details of each call, so the URLs remain friendly. MVC is contained in the System.Web.MVC namespace, so we know for sure that this thing is going to last since it has been included in the System.Web namespace.

There were three main concepts remarked about MVC: it is flexible, since you can rewrite or swap any part you want (like writing your own controllers). It promotes dry code (not having redundancy and duplication of code) and it uses HTTP handlers (he did a demonstration following the call stack to show how the calls are being made) meaning that MVC is playing by the rules, no magic behind the scenes.

Regarding MVC views he showed a couple of code samples on how you can chose to not specify a view and how it is going to try to return the view with the same name of the method, not caring or getting confused by extensions. On the other side, you can specify the exact view you want returned no matter the method’s name. I really think that the more we get familiar with MVC the better since Microsoft is putting so much attention on this.

5. Rest in WCF 3.5 – Rob Bagby, Microsoft
This was a good presentation too, and I was really interested since I have been researching a lot about WCF and more recently the WCF 3.5 capabilities for implementing RESTfull applications. This is his site.

He first talked about the Content Driven Web Architecture that has been the one followed in the past, where you had the browser, the URI’s, HTML, Hyperlinks and HTTP GET basically. He remarked that today’s web is equal to content plus capabilities. Then he switched to what he believes is the today’s web architecture: Capability-Enabled Web Architecture where you have rich browser clients, HTTP, domain neutral data oriented formats like JSon and ATOM, and presentation formats (HTML, CSS, XML).

He mentioned that web developers should retake the HTTP status codes (200, 201, 500, 404, etc) which are the simplest and most known error handling codes. This is something that REST architecture concepts also emphasize on. He pointed out that REST is an architecture or style of development and that this means that there’s always to be a debate around it.

Regarding code demonstrations, he showed how to create a RESTful applications with WCF 3.5 using Low Rest concepts, meaning that he was specifying a lot by code using attributes to set base addresses and names for the methods to call throw HTTP, and also using the application configuration file to define the services endpoints. Then he showed a similar demo using High REST concepts, which included the use of the REST STARTER KIT which gives you some factory namespaces for this type of applications. If you use the factory then the configuration happen behind the scenes and the configuration file endpoint sections are no longer needed unless you need to specify different bindings for the same service.

DevConnections 08

Last week I was in Las Vegas attending to the DevConnections 08 conference at the Mandalay Bay Hotel. I must say that I was expecting more cutting edge presentations and crowd, but instead people where more from the enterprise business solutions industry. However I got to see some really interesting presentations, specially John Papa's Data Access with Silverlight 2 presentation and also Scott Guthrie's keynote where he mentioned six successful Silverlight 2 projects and two of them were made by Schematic, so that was really cool. The Gu is a really nice person and I got to meet him and talk to him about the future enhancements of the Blend/VS workflow and VS2010.

I remained manly on the VisualStudio&Architects and the ASP.NET tracks, although there where tracks for SQL, SharePoint, Exchange and Windows. In my case, the VS and ASP tracks where the more compelling to me.

There were a lot of remarks about the new ASP.NET MVC framework and how to integrate it with other ASP.NET components and technologies and also with WFC and Silverlight 2. There was also a few presentations talking and demonstrating how to build RESTful services with WCF and Silverlight 2, so there's a lot of interesting things coming and it seems that integration of the Microsoft technologies is a big deal this days.

Anyway, this post is just introductory, I'm going to do a couple of posts with the summaries of the two days I was at the conference.


Presenting at the Microsoft eXpert RoadShow ‘08

Microsoft Multi Americas invited me to present at their eXpert RoadShow 08 this year. The event happens in different countries all around Latin América, although I'll be presenting only in Costa Rica.

I will be talking about the most recent cool technologies for the Next Generation Technologies session. This year's conference will be focused on building solutions for a case study, so people will get a more real sense on how this technologies can be applied.

If you are in Costa Rica, go ahead and register yourself. This event will be a good one and there will be many experts from different countries and industries.

Here is the schedule for the Costa Rica presentations:

San Carlos

Where Auditorio TEC, San Carlos
WhenDec 3rd, 2pm
WhateXperts Roadshow


WherePlaza Bratsi, Heredia, 200 norte del Paseo de la Flores, Contiguo a la Universal
WhenDec 4th, 2pm
WhateXperts Roadshow


WhereUniversidad de Costa Rica, Sede Puntarenas
WhenDec 5th, 2pm
WhateXperts Roadshow

Hope you can join us!

TIC-LatinFest 2008 Conference

I'm writing this post a little bit late since I have been really busy working on the latest WPF projects. I also went to the DevConnections conference last week in Las Vegas, so I have been quite busy for writing on the blog.

However I didn't want to miss the change to mention that I was invited to speak at the TIC-LatinFest 2008 Conference and Job Fair at the Universidad Latina de Costa Rica. The Fair was well organized having companies like Intel, Dell, and ManPower over there.

I gave a presentation on Wednesday, November 5 for this event. I talked about how to build scalable, flexible, reliable and perdurable .NET N-Tier applications applying the layer separation concepts and design and architecture best practices. I also presented several demos showing how to code less, reuse more and make your applications flexible enough that changing the presentation layer can be done with very little effort.

I showed a WCF sample and how to deliver the information in different ways without having to modify the service code just by adding [WebGet] attributes and configuring the service endpoints.

I also explained how to use the Microsoft DeepZoom Composer to create a Silverlight 2 photo viewer using the plug-in, Visual Studio 2008 and Expression Blend 2.

The other demo I showed was a WPF one, showing the water year's consumption by month expressed on a graphic 3D interface. Very nice because of the advantages of how to present the information and the interactivity it had with the user.

It was really nice to speak at this event. I got several people in the presentation from the financial industry to the university students.