Fernando Machado Píriz's Blog

Posts about digital transformation, enterprise architecture and related topics

Archive for the ‘C# 4.0’ Category

New release of Visual Studio 2010 and .NET Framework 4 Training Kit

with one comment

imageMicrosoft yesterday published for download the March 2011 release of the Visual Studio 2010 and .NET Framework 4 Training Kit. You can download the kit from here. This training kit includes presentations, hands-on labs, and demos, covering the latest topics in the recently updated versions of Visual Studio 2010 and .NET Framework 4. Enjoy.

 

 

 

 

 

 

 

Written by fernandomachadopiriz

March 15, 2011 at 10:15 pm

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.

image

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.

image

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.

image

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.

image

Now a new relationship between books and loans is defined.

image

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

image

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.

image

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

image

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

image

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:

image

Let us complete the fields to add the first book:

image

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

image

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

image

image

image

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.

image

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

image

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.

image

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.

image

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.

image

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.

image

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.

image

image

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

image

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.

image

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 fernandomachadopiriz

August 20, 2010 at 12:50 am

Give me a handle and I will move the Earth

with one comment

image

This post’s title paraphrases a saying attributed to Archimedes, who is said to have remarked of lever “Give me a place to stand on, and I will move the Earth”.

For people like me who started developing Windows applications a long time ago, handles were the entry door to almost any resource through Win32 API. Do you want to close or minimize a window? You need that window handle. Do you want to write some text into a window client area? You need the font handle, the device context handle, and the window handle. And so on.

Fortunately, in actual .NET Framework times, almost no one cares about using handles, nor cares about knowing what they are. The .NET Framework hides the complexity of handling Windows resources through the Win32 API, and with that, it also hides the handles.

However, once in a while, there appear some problems for which the only solution is to get a handle. Here is an example.

One of the features of the Giving a Presentation demo application is the ability to hide desktop icons during a presentation, showing them back again when the presentation ends. While developing thsi feature, I unsuccessfully searched for a way to do that. As far as I could found, there is no public API function to do it; and most hacks available on the web -for example this one– use handles and Win32 API function calls, but does not work correctly: they disable the entire desktop, not only its icons; as a consequence, the desktop’s pop up menu disappears.

Speaking about desktop’s popup menu, what I needed was a feature like the one in the Show desktop icons command.

image

Then it was when the old knowledge about handles and the like became useful again. I knew that this command ended sooner or later being transformed into a WM_COMMAND sent to the desktop. What I needed to emulate this behavior was to know the arguments of the WM_COMMAND message and –as you can imagine- the desktop handle. Once I get this information, I could send the same WM_COMMAND to the desktop. The desktop would not distinguish between a message sent by the menu command or by my program, so it should handle it in the same way.

For both two things I used an old tool still included in Visual Studio installation: Spy++. This tool allow finding a particular window, and among other things, look at the messages it receives. The following picture show the Spy++ windows list node corresponding to the desktop. Please note that desktop is a window of the SHELLDLL_DefView class; we will see later how this information is used.

clip_image003

The following image shows the messages received by this window when command Show desktop icons is executed. Please not the command ID 29698 of the WM_COMMAND message; we will also see later how to use this information.

clip_image004

The function to hide or show desktop icons finally gets something like this:

/// <summary>
/// Toggles desktop icons visibility by sending a low level command to desktop window in the same way as the popup menu "Show desktop  
/// icons" does. Use <code>AreDesktopIconsVisible</code> to get current desktop icons visibility status.  
/// </summary>  
private static void ToggleDesktopIconsVisibility()  
{  
    IntPtr defaultViewHandle = FindShellWindow();
    UIntPtr resultArgument; 
    IntPtr returnValue = NativeMethods.SendMessageTimeout(  
        defaultViewHandle,  
        NativeMethods.WM_COMMAND,  
        new IntPtr(29698),  
        IntPtr.Zero,  
        NativeMethods.SendMessageTimeoutFlags.SMTO_ABORTIFHUNG,  
        1000,   
       out resultArgument);
} 

The NativeMethods class contains all the functions and constants imported from Win32 API; code is not shown here due to simplicity, but you can download it from CodePlex. The function SendMessageTimeout is used to send the WM_COMMAND with ID 29698 to the window whose handle was obtained with the FindShellWindow function.

On the other side, the FindShellWindow function finds and returns the desktop handle, strictlyspeaking, the handle to the window containing desktop icons, whose class is SHELLDLL_DefView. Finding this window was not easy. Due to unknown reasons, in certain systems the window is in some place in the windows’ hierarchy, but in other systems is in another place – both system being Window 7 RTM 32 bits. Because of this, the Giving a Presentation feature to hide and show desktop icons, did not work in every situations. I should thanks to my MVP coleague Elías Mereb for his help to test different candidate solutions until finding the good one.

/// <summary>
/// Called by EnumWindows. Sets <code>shellWindowHandle</code> if a window with class "SHELLDLL_DefView" is found during enumeration.
/// </summary>
/// <param name="handle">The handle of the window being enumerated.</param>
/// <param name="param">The argument passed to <code>EnumWindowsProc</code>; not used in this application.</param>
/// <returns>Allways returns 1.</returns>
private static int EnumWindowsProc(IntPtr handle, int param)
{
    try
    {
        IntPtr foundHandle = NativeMethods.FindWindowEx(handle, IntPtr.Zero, "SHELLDLL_DefView", null);
        if (!foundHandle.Equals(IntPtr.Zero))
        {
            shellWindowHandle = foundHandle;
            return 0;
        }
    }
    catch
    {
        // Intentionally left blank
    }

    return 1;
}

/// <summary>
/// Finds the window containing desktop icons.
/// </summary>
/// <returns>The handle of the window.</returns>
private static IntPtr FindShellWindow()
{
    IntPtr progmanHandle;
    IntPtr defaultViewHandle = IntPtr.Zero;
    IntPtr workerWHandle;
    int errorCode = NativeMethods.ERROR_SUCCESS;

    // Try the easy way first. "SHELLDLL_DefView" is a child window of "Progman".
    progmanHandle = NativeMethods.FindWindowEx(IntPtr.Zero, IntPtr.Zero, "Progman", null);

    if (!progmanHandle.Equals(IntPtr.Zero))
    {
        defaultViewHandle = NativeMethods.FindWindowEx(progmanHandle, IntPtr.Zero, "SHELLDLL_DefView", null);
        errorCode = Marshal.GetLastWin32Error();
    }

    if (!defaultViewHandle.Equals(IntPtr.Zero))
    {
        return defaultViewHandle;
    }
    else if (errorCode != NativeMethods.ERROR_SUCCESS)
    {
        Marshal.ThrowExceptionForHR(errorCode);
    }

    // Try the not so easy way then. In some systems "SHELLDLL_DefView" is a child of "WorkerW".
    errorCode = NativeMethods.ERROR_SUCCESS;
    workerWHandle = NativeMethods.FindWindowEx(IntPtr.Zero, IntPtr.Zero, "WorkerW", null);
    Debug.WriteLine("FindShellWindow.workerWHandle: {0}", workerWHandle);

    if (!workerWHandle.Equals(IntPtr.Zero))
    {
        defaultViewHandle = NativeMethods.FindWindowEx(workerWHandle, IntPtr.Zero, "SHELLDLL_DefView", null);
        errorCode = Marshal.GetLastWin32Error();
    }

    if (!defaultViewHandle.Equals(IntPtr.Zero))
    {
        return defaultViewHandle;
    }
    else if (errorCode != NativeMethods.ERROR_SUCCESS)
    {
        Marshal.ThrowExceptionForHR(errorCode);
    }

    shellWindowHandle = IntPtr.Zero;

    // Try the hard way. In some systems "SHELLDLL_DefView" is a child or a child of "Progman".
    if (NativeMethods.EnumWindows(EnumWindowsProc, progmanHandle) == 0)
    {
        errorCode = Marshal.GetLastWin32Error();
        if (errorCode != NativeMethods.ERROR_SUCCESS)
        {
            Marshal.ThrowExceptionForHR(errorCode);
        }
    }

    // Try the even more harder way. Just in case "SHELLDLL_DefView" is in another desktop.
    if (shellWindowHandle.Equals(IntPtr.Zero))
    {
        if (NativeMethods.EnumDesktopWindows(IntPtr.Zero, EnumWindowsProc, progmanHandle))
        {
            errorCode = Marshal.GetLastWin32Error();
            if (errorCode != NativeMethods.ERROR_SUCCESS)
            {
                Marshal.ThrowExceptionForHR(errorCode);
            }
        }
    }

    return shellWindowHandle;
}

In certain situations, even in the .NET Framework era, it is still useful to get a handle: give me one, and I will move the Earth. Or at least, I will hide and show desktop icons. See you later.

Written by fernandomachadopiriz

August 9, 2010 at 2:46 pm

Posted in C# 4.0

Tagged with

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:

ClassDiagram

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

Written by fernandomachadopiriz

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.

image 

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.

image

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; }
        set
        {
            model.GivingAPresentation = value;
        }
    }

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

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

image

The corresponding XAML code is:

<Window x:Class="GivingAPresentation.MainView"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:vm="clr-namespace:GivingAPresentation "
        Title="Giving a Presentation" Height="350" Width="525" Icon="/MvvmDemo;component/Images/Presentation.ico">
    <Window.Resources>
        <vm:MainViewModel x:Key="mainViewModel"/>
    </Window.Resources>
    <Grid>
        <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}" />
    </Grid>
</Window>

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 fernandomachadopiriz

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.

clip_image002

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

clip_image003

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 fernandomachadopiriz

May 24, 2010 at 7:40 pm