Fernando Machado Píriz's Blog

Posts about digital transformation, enterprise architecture and related topics

Posts Tagged ‘C# 4.0

First look to the Microsoft Visual Studio LightSwitch beta

with 7 comments

A new member of the developers’ tools family has been announced earlier this month and the first beta will be available soon for download: Microsoft Visual Studio LightSwitch.

What it is and what it is for?

With LightSwitch we can easily and quickly create business applications from the scratch, including not only the application user interface forms, but also the application database; you can also create applications from existing databases.

In this article I will provide an overview of LightSwitch using the beta version soon to be available. The project I will create is a simple application to record the books I loan to my friends.

A new LightSwitch application starts by creating a new Visual Studio project. A LightSwitch project will contain application’s data and forms definitions. By using these definitions LightSwitch generates a SQL Server database and the source code in C# or Visual Basic.

In this article I will use a C# project template. Here you can see the familiar Visual Studio new project dialog box, with the two templates provided by LightSwitch.


Once the project is created we can connect to an existing data source or create a new data definition for the application. In this post I will show how to create data definitions from the scratch.


The first thing to do is to define how book entities are. I am interested in each book’s author and title. Then we create an entity Book, with Author and Title fields, both of type String and both required. These entities will be stored in a Books table.


Then a definition for loans is created. From each loan I am interested in knowing to whom I loaned the book, when the book was loaned, and when it was returned. Then we create a second entity called Loan, with fields ToFriend, DateLoaned and DateReturned; the first field is of type String and the two other are of type Date; the first two fields are required, but the latest is not. These entities will be stored in the Loans table.


Now a new relationship between books and loans is defined.


See below how the definition of the entity Loan and its relationship with Book looks:


Now we need to define the forms to edit these entities. Many different form templates are available -allowing one record to be edited at a time, multiple records in a grid, etc. I will use a template for a simple record insertion.


The form definition created by the wizard can be modified. I have changed only the name to display and the description of the form.


Once the form definition is finished, we can test the application. This LightSwitch version allows creating the following application types:


When the build is started LightSwitch:

  • Creates the database
  • Generates the source code
  • Compiles the application

A LightSwitch application is typically a three tier application, using certain specific technologies for each tier:

In this article you can find more information about the architecture of a LightSwitch application.

When a LightSwitch application gets executed:

  • A local web server is started
  • The application is deployed on this web server
  • The application is started

That is what we see:


Let us complete the fields to add the first book:


The application automatically assigns a new identifier to the first book.


Out of the box, the application already has some simple validations, like the one corresponding to the fields marked as required.




The second form is to insert loans. This is also a simple new record form. We can see how LightSwitch assigns a Date Picker control to the DateLoaned and DateReturned fields, of type Date. It also assigned a Modal Window Picker control to edit the association between a Loan and a Book.


When we run the application we can see how the controls assigned to Date fields looks:


The Modal Window Picker control allows searching and selecting a book to be associated with a loan. The control includes not only the search features, but also allows paging results.


Although this way to edit loans is not so bad, I would prefer to see the list of books, and from there to easily access each book’s loans, and eventually adding new books in the same place. The template for this kind of editing form is called List and Details Screen. Look how LightSwitch allows indicating if books’ and loans’ details should be included on the form.


Once the form is created, we can edit its definition. Like in previous cases, I only slightly change the name to display and add a description.


We can see how the new form looks when running the application. The list of books appears on the left. From there we can add, modify, and delete books. For the book selected in the list on the left, we can see the loans in the right. From there we can also add, modify, and delete loans.


Be aware that for adding and modifying books and loans, LightSwitch automatically generated a form with the same controls defined in their respective new record forms.



These forms have also the default behavior for validating the rules defined in the entities.


When more than one record is changed in a list, modifications are not sent to the database until the list is saved by using the Save button.


How much time takes this application to be created? Not too much, as you can see in this video:


You can download the video from here.

Okay, but what kind of applications is LightSwitch for? Perhaps we need to wait for a while to see who really takes advantage of this new technology. Simple applications like the one I created in this post can be created really quickly, but we all know that real world applications are not as easy to build as the ones I have demoed, are they? For non-professional or occasional developers –for whom other technologies like Microsoft Access or Visual FoxPro was created in the past-, LightSwitch can be their new preferred tool. Professional developer will probably not be able to build 100% of the complex business applications they create today by using LightSwitch, but at least they can use LightSwitch as a tool for rapid prototyping.

In certain places in the application definition we can write C# code to add functions not provided by LightSwitch -for business rules for example. But then we need to know the object model of the code generated by LightSwitch, to be able to consume from our own handwritten code the types automatically generated by LightSwitch.

Some of the templates seem to be extensible –this beta version includes templates lists with just an element, but probably it is because it is a beta. Furthermore, it seems that LightSwitch will be able to create applications for Windows Azure also. Since all the code and the database are generated from definitions, the same application could be migrated from the desktop to the cloud just by changing a setting in the project properties page.

With an object model easy to be consumed in extension points and a strong ecosystem augmenting LightSwitch capabilities, it looks like we will be able to use it to develop applications more complex than the one created here. It is too soon yet, time will tell.


Written by fmachadopiriz

August 20, 2010 at 12:50 am

The new Visualization and Modeling Feature Pack allows generating UML diagrams from code and vice versa

with one comment

Microsoft recently published the Visualization and Modeling Feature Pack for Visual Studio 2010. Download is available for MSDN subscribers here. The following (longly awaited) features are included:

  • Generate code from UML class diagrams.
  • Create UML class diagrams from code.
  • Import UML class, sequence, and use case elements from XMI 2.1 files.
  • Create and view links from work items to model elements.
  • Generate dependency graphs for ASP.NET Web, C, and C++ projects.
  • Create and validate layer diagrams for C and C++ code.
  • Write custom code to create, modify, and validate layer diagrams.

The following UML class diagram from Giving a Presentation was created using the Visualization and Modeling Feature Pack in just a couple of minutes:


Do you recognize how the Model View View Model pattern was used? It is easy from the diagram, is not it?

Written by fmachadopiriz

June 16, 2010 at 9:15 pm

A simple introduction to the Model View ViewModel pattern for building Silverlight and Windows Presentation Foundation applications

with 5 comments

Some time ago I was looking for a simple introduction to the Model View ViewModel pattern (also known as MVVM) and all the samples I was able to find were a bit complicated to my taste. I this post I will try to present you the MVVM pattern using the simplest possible example, focusing just on the key MVVM concepts. In other posts I will deep dive on other closely related concepts, but let us start with the basics.

MVVM is a successor of another well-known and very successful pattern so called Model View Controller (MVC). MVC was born (like many other well-known and successful patterns) in the Smalltalk world more than thirty years ago. Using MVC the application is composed by three kinds of objects, with very clear and differentiated responsibilities:

  • The model. Usually there is only one model per application. The model is responsible for all application’s data and related business logic.
  • The view or views. One or more representations for the end user of the application’s model. The view is responsible for showing data to end users and for allowing end users to manipulate application’s data.
  • The controller or controllers. Usually there is one controller per view, although it is not uncommon to see one controller per domain entity controlling multiple views. The controller is responsible for transferring data from the model to the associated view and vice versa. It is also responsible for implementing view’s behavior to respond to user actions.


With MVC each type of object is responsible for just one thing, which simplifies developing, understanding and testing the code. In addition, it is easy to replace views, or to have more than one view of the same data.

In the case of Silverlight and Windows Presentation Foundation (SL/WPF) applications, the .NET framework provides the ability to use binding to transfer data to and from the view, so the controller is only responsible for implementing view’s behavior. In this case, the controller is called view model, leading to the MVVM pattern:

  • The model. Same as with MVC.
  • The view or views. Also the same as with MVC. Views are SL/WPF windows.
  • The view model. One view model per view. The view model is responsible for implementing view’s behavior to respond to user actions and for exposing model’s data in an “easy-to-bind” way to the view.


MVVC shares all of the benefits of MVC, but it has an additional benefit: the simplification resulting from using declarative binding to transfer data back and forth the view model to the view.

I will illustrate how MVVC works with an example. The code I will be using in this post comes from my sample application Giving a Presentation (although you are encouraged to download the installation file and the source code of Giving a Presentation from CodePlex, there is no need to do it in order to follow this post).

Giving a Presentation is a simple application to change certain setting while delivering a presentation, e.g., hide desktop icons, remove or replace desktop background, etc. Changes are reverted back when presentation ends.

The ability to change settings is provided by extensible parts and is not implemented in the application itself (more details in this post). So strictly speaking, the data Giving a Presentation deals with is just a boolean value indicating if the user is giving a presentation or not: the user sets the value on true when presentation starts, and set it back on false when presentation ends.

The model’s code is as follows. As promised, it is very simple; it has just a boolean property:

public class Model
    public bool GivingAPresentation { get; set; }

Here’s the view model’s code. It is also very simple. Like the model, it has a just a boolean property, whose value is get and set from an instance of the model.

public class MainViewModel
    private Model model;
    public bool GivingAPresentation
        get { return model.GivingAPresentation; }
            model.GivingAPresentation = value;

    public MainViewModel()
        this.model = new Model();

The view (without any extensible part on it) looks like this:


The corresponding XAML code is:

<Window x:Class="GivingAPresentation.MainView"
        xmlns:vm="clr-namespace:GivingAPresentation "
        Title="Giving a Presentation" Height="350" Width="525" Icon="/MvvmDemo;component/Images/Presentation.ico">
        <vm:MainViewModel x:Key="mainViewModel"/>
        <CheckBox Content="I'm currently giving a presentation"
                  HorizontalAlignment="Left" VerticalAlignment="Top" Margin="12,12,0,0"
                  IsChecked="{Binding Source={StaticResource mainViewModel}, Mode=TwoWay, Path=GivingAPresentation}" />

Interestingly, there is no code behind for this view[1] (furthermore, I have deleted the file MainView.xaml.cs from the project, and obviously the solution compiles and the application runs perfectly). Do you wonder why? Because there is no need to have any code in view’s code behind class; view’s behavior is coded in the view model, not in the view, do you remember?

The view is connected with the view model in three steps. First, an xmlns attribute in the Window node is used to alias the GivingAPresentation namespace as vm with xmlns:vm=”clr-namespace:GivingAPresentation. Second, an instance of the view model is created in the Window.Resources node; the name of the instance is declared with x:Key=”mainViewModel”. And finally, the IsChecked property of the view’s check box is binded with view model’s GivingAPresentation property with IsChecked=”{Binding Source={StaticResource mainViewModel}, Mode=TwoWay, Path=GivingAPresentation}”.

And that’s it. WPF/SL does the magic of getting check box’s state from view model’s property value, which in turn is taken from the corresponding model’s property value. WPF/SL also does the magic of setting view model’s property value whenever the user checks or unchecks the check box. The view model propagates property value change to the corresponding property in the model. Through this chain, a change in the view is reflected in the model.

This example is perhaps too basic, but it has all the key components of the MVVM pattern, and clearly shows the basis for implementing WPF/SL applications using that pattern.

What is next? There many things, very common in real world scenarios, not resolved at all in this very simple demo; for example:

  1. Not only the view, but probably other objects need to be aware of changes in view model’s properties values. That is where the INotifyPropertyChanged interface comes in to play. By firing a PropertyChanged event every time properties’ values change, other objects can react to these changes. It is worth to mention that those objects are not known by the view model, but will be notified anyway, thanks to the .NET Framework’s events infrastructure.
  2. It is very common for the view to ask its view model to execute certain actions. This can be achieved by the view model exposing commands, and the view binding control’s actions (like click) to those commands.
  3. It is also very common in real live applications to have interdependent views that need to communicate between them. To keep those views, and their associated view models, independent from each other, view models can use messages to communicate between them.
  4. Who creates who? In this simple demo the view declaratively creates the view model (in view’s XAML code), and the view model creates the model. In large applications, this approach is not always feasible, and you need other helper classes to manage objects creation.

These aspects are really not part of the MVVM pattern, but are actually needed to implement real world applications using WPF/SL; that is why you usually will see them covered together with the MVVM pattern in the literature. I plan to cover them in future posts, just to keep the MVVM basics, basic.

Hope you have enjoyed this explanation. Looking forward to see you soon. Bye.

[1] In this example. In Giving a Presentation’s real code, the view is responsible for presentation related tasks, like showing the notification icon when minimized for example, that requires code behind the view.

Written by fmachadopiriz

June 10, 2010 at 12:41 am

Do you usually give presentations? Check this out

with 13 comments

For end users: Giving a Presentation is a simple application to change certain setting while delivering a presentation, e.g., hide desktop icons, disable screensaver, close selected programs, etc. Changes are reverted back when presentation ends. Initially built to show how to use certain technologies, it turned out to be useful by itself.

Watch this video to see Giving a Presentation in action:

If you want to try Giving a Presentation for youself, you can download installation bits from Codeplex.

For developers: Giving a Presentation is a WPF application sample created in C# that I use when blogging about Managed Extensibility Framework, Dependency Injection and Inversion of Control, etc. It demonstrates how an extensible application can be built as a container of component parts.

In this sample application, the container is the main window, plus the tab control on it. The tab control has just a Default tab and an About tab. The Default tab is initially empty; it will be dynamically filled by component parts.


The About tab shows typical information about application version, etc.


Component parts need to fulfill three requisites:

  1. Should implement an interface GivingAPresentation.Common.Contract.
  2. Should the decorated with the System.ComponentModel.Composition’s Export attribute.
  3. Should be deployed in an assembly in the same folder as the container.

The Managed Extensibility Framework and the MainWindow of the application will do the rest. The former will load instances of all exported types implementing the mentioned required interface in a list. The later will take the instances in the list and add the controls to the appropriate tab in the control tab.

Until now, I have created three component parts, to solve some of the typical problems that appear when giving a presentation:

  • Hide desktop icons. Usually you place working documents in your desktop. Some of these documents are private and you don’t want your audience see them before you start delivering a presentation. Use this feature to hide your desktop icons during a presentation and unhide them at the end
  • Disable screen saver. You may have your screen saver configured to start after certain time of inactivity. If you spend some time in a single slide during a presentation, your screen saver can interrupt your presentation. Use this feature to disable your screen saver during a presentation and enable it back at the end.
  • Close programs. Some programs pop up notification messages, e.g., mail or instant messaging clients when messages arrive. Despite of the interruption, the content of the notification might be inappropriate to be seen by your audience during a presentation. Use this feature to close selected programs during a presentation and open them back at the end.

Watch this video to see how these parts effectively extend the container:

You can download the source code also from Codeplex.

Give it a try. Hate it? Love it? Let me know.

Intellitrace in Visual Studio 2010 and Team Foundation Server 2010

with one comment

This is the seventh (and latest) post of a series about testing tools and techniques using Visual Studio 2010, Team Foundation Server 2010, Microsoft Test Manager 2010, and C# 4.0.

Certain bugs can be reproduced only if code is executed under certain conditions. If developers can’t recreate such conditions in their developing environment, it’s very unlikely for them to find these bugs. Visual Studio 2010 and Team Foundation Server 2010 can record events and calls during the execution of tests by using Intellitrace. Developers can later debug code reproducing those recorded Intellitrace files, like if they were using a VCR: they can go back and forward in the call stack, analyze parameters and result values, etc., even if their environment is completely different from the one where the Intellitrace file was recorded.

You can also download the video.

Written by fmachadopiriz

May 24, 2010 at 7:40 pm

Including tests in builds with Team Foundation Server 2010

with one comment

This is the sixth post of a series about testing tools and techniques using Visual Studio 2010, Team Foundation Server 2010, Microsoft Test Manager 2010, and C# 4.0.

Just because code compiles, we can’t be sure it’s bug-free. Only when all test cases passed, we can have certain degree of confidence, depending on how good tests are. Team Foundation Server 2010 easily allows adding tests cases execution to the build process, automatically generating bugs in the work items repository for failed tests.

You can also download the video.

More videos coming soon… keep tuned!

Written by fmachadopiriz

May 24, 2010 at 7:29 pm

Test Impact Analysis with Visual Studio 2010

with one comment

This is the fifth post of a series about testing tools and techniques using Visual Studio 2010, Team Foundation Server 2010, Microsoft Test Manager 2010, and C# 4.0.

Every time you modify your code, you need to run all tests cases again, to ensure no bugs were introduced in previously bug-free code; this is called regression testing. When the number of tests grows, the time to run all test gets longer. With test impact analysis, Visual Studio selects the minimal set of tests to cover modified code, optimizing the time required to do regression testing. In this video you will see a modification in the Subtract method of the Calculator class, and how Visual Studio selects the unit test that tests that method.

You can also download the video.

More videos coming soon… keep tuned!

Written by fmachadopiriz

May 24, 2010 at 7:24 pm