Showing posts with label MultiTargeting. Show all posts
Showing posts with label MultiTargeting. Show all posts

Friday, August 17, 2012

Portable Library Tools & Type Forwarding

This post is part of a series of posts where we are discussing Portable Class Library Tools. It allows same library to be targeting multiple frameworks including any combination of .net framework, Silverlight, Windows Phone, Metro and Xbox360 development. In the previous post we discussed how development environment determines what features set to support for a combination of selected environments. We also discussed how we can limit targeting frameworks on development machines.

Here we discussed how common feature set is available for development based on the target frameworks selected. We used a few interface and concrete types including ICommand, ObservableCollection<T> and INofityDataErrorInfo. Basically the availability of these types in a common codebase is in itself a great achievement. This is because these types are defined at different assemblies in different frameworks. Even if we keep the namespace similar then which implementation should be used by the compiler?

Let's first look at INotifyDataErrorInfo. This is available in Silverlight framework as follows:


The same interface is available in .net framework 4.5 at different location. Let's see the following definition:


Similar are the following examples:
  • ObservableCollection<T>
  • System.dll [.net Framework 4 & 4.5 Dev preview], System.Windows.dll [Silverlight]

  • ICommand
  • System.dll [.net Framework 4.5 Dev preview], PresentationCore.dll [.Net Framework 4], System.Windows.dll [Silverlight]
Now if we are targeting for .net framework 4.5 Developer's preview and Silverlight 4 then the observable collection type would be used from System.dll or System.Windows.dll?? In this post we will try to address how this is actually happening inside the hood of portable libraries.

In the previous post, we discussed about reference libraries and profiles. These reference libraries contain the metadata information for these types. The metadata information might be about where to get the actual definition of the type with necessary forwarding details. In order to look at the actual definition, we will be needing to disassemble a reference library. The reference libraries for .net portable can be found here:


The concept of Reference assemblies was introduced in .net framework 3.0. This is to provide design time version of these assemblies. At runtime the assemblies would be directly used from Global Assembly Cache. We have seen in the previous post how profiles are used for targeting a set of selected target frameworks.


As we have previously seen, portable libraries can only be referenced by any of the selected target frameworks specified during development of the portable library. When loaded at runtime it would be using libraries directly from the host framework inlcuding Silverlight and .net framework. So for the case of mscorlib, the library [mscorlib] would be used from "Reference Libraries" folder during development. At runtime, the host framework's version of mscorlib would be used. You might be wondering about the API differences and differences in Types' behaviors for different frameworks. Don't worry about it, some changes were made in .net framework 4 to support just that. You can find the details here:

http://msdn.microsoft.com/en-us/library/gg597392.aspx

Let's look at the following chart:


These are names of types and their relevant assemblies. Most of the types in .net framework are at the same assembly, yet they are supported for portable libraries for .net framework 4.5 and not supported for .net framework 4. That seems quite strange. If they can be used by one then why can't they be used by the other one?? The explanation should cover how type's locations in different assemblies in multiple target frameworks (including Silverlight & .net framework 4.5) is addressed. The whole idea is type forwarding. Please remember that this is not a new concept introduced by Microsoft but this has been there for a while, Portable Library Tools is just cashing into that feature.

Basically, a portable library would always refer a type from the same assembly. Now it would be loaded in a certain framework including Silverlight or .net frameworks (or any other) with the assembly with same identification (e.g. System.Windows.dll). Based on the reference information in portable library, the framework would access the referred type from the same assembly as specified by the portable library. Now it is the assembly's responsibility to either provide the type or direct to some other assembly in the framework as a guidance for the type's location by using TypeForwardedToAttribute. There would be different System.Windows.dll for Silverlight and .net framework 4.5 with different manifest information. In Silverlight this would be directly provided by System.Windows but in .net framework 4.5, System.Windows would redirect the request to System.dll for the types specified in the chart.


The above explanation answers both questions. First, since the portable library always access the types from the same assembly, there is no magic in the portable library itself to for redirection of type's assembly location. It is actually the framework where the assembly is loaded which helps the portable library finding the specified type using type forwarding. Second, since the assemblies with type forwarding information is not available in .net framework 4 [e.g. System.Windows.dll], we can't use types for multitargeting where they are coming from different assemblies. So this Type Forwarding assembly is kind of a mediator. When the mediator is not present, there can't be any portability.


If you are curious like me then you might want to look at the definition of the assembly [System.Windows.dll] in .net framework 4.5. Well we can use ILDASM to see the assembly manifest. Please specially focus on the forwarder attribute for class type being forwarded. Now where to get this type from?? This is specified as ".assembly extern System", which is just saying that, "Look at the definition of this type in System assembly.". This is from the folder [C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.5] instead of any profile from .NetPortable folder.


Now let's have a look at our portable library to see how System.Windows is referenced. It is referenced as retargetable assembly, which means that it would be loaded based on the host framework [Silverlight, .net framework 4.X etc].


Thursday, August 2, 2012

Portable Class Library & MVVM

This is continued from the previous post where we introduced Portable Library Tools from Microsoft. In this post we will be discussing how useful portable library tools are for the incorporation of MVVM for an application which have multiple UI requirements. The application can be consumed by users from different platforms. These might include Silverlight, WPF, Windows Phone and now Metro. Since all of these platforms can be developed in XAML, we don't need to find many developers with platform specific expertise to develop for a particular platform, keeping in mind that the XAML might be closely similar but same XAML cannot be used for these platforms. It might have a different class hierarchy, different defaults and non-matching behaviors. This also helps in shuffling developers across these teams.

Based on the above discussion, we cannot use same view for these platforms. Back in the days, we couldn't even share the view model across these platforms as many MVVM specific features are not available across these platforms, Or they are not provided similarly. With .Net 4.5 and portable libraries, this gap is being minimized. The features available in one platform is being available in the other platform. It's example is INotifyDataErrorInfo. This used to be available only in Silverlight platform. This is used to notify the errors to the interested UI logic. With .net framework 4.5 Developer's preview, this has been incorporated in .net framework. Before this, we weren't able to share the same view models from silverlight to .net framework because of same reason. Even if we minimize the features to better incorporate multitargeting, we still couldn't use the same assembly across these platforms as the assembly is compiled differently across these frameworks.

Portable Libraries make our lives easier by making only those features available which are supported by all of the selected platforms. If we are targeting our libraries for .net framework 4.5 and Silverlight 4 then only those features would be available which are available in both of these platforms. Let's try to understand this with an example. We are using the same concept of CoffeeHouse application as we have been using for a while. But in order to minimize the noise, we are tasked with a simple interface to enter Barista's information. We only need to provide the details about First and Last name of Barista.

Creating Projects and Adding References
Let's first add a portable class library project for holding view models as follows:


Since this is a portable library based project, we can target multiple platforms. As per the requirement, we are selecting .net framework 4.5 and Silverlight 4 platforms.


Similarly, we add another portable library project to hold our models. This project also targets .net framework 4.5 and Silverlight 4.


Since both model and view model based projects are portable library projects targeting the same platforms, we can add the reference of one in other project. In MVVM view model can hold model's instance when model is not aware of the view model it belongs to. This is similar to Dependency Inversion idea where higher level module (view model) uses lower level modules (models). Here we are adding model project's reference to the view model project.


Now we can add WPF and Silverlight projects for UI logic.


Both of them would need a reference of view model's project so that view model types are available to the UI logic.


The project's references are added as follows:


Please notice that the Silverlight and WPF projects are using the same view model and model's libraries which is the core idea of multitargeting.


Adding Model
Let's add a simple model to Model's project to hold Barista's information. It simply has two properties to hold first and last names of Barista.


Adding View Model
Now we need to add view model. The view model needs to provide the view state. It is responsible for passing the state between view and model at appropriate time. It is also exposing properties for first and last name of the barista. It implements INotifyPropertyChanged to provide value change notification for its properties. The view would be using PropertyChanged event to update itself based on the state of the view model. It also implements INotifyDataErrorInfo for validating the view state. It is supposed to raise ErrorsChanged event whenever error state of a property is updated. The property can be updated from valid to invalid state or vice versa. It is maintaining a collection to hold error details of these properties.

The view model also exposes an ICommand, named SaveBaristaCommand. When executed, this should pass on the view state to the model.


ICommand Implementation for Portable Library Tools
Here we can provide a custom implementation of ICommand in view model's project. This has just been used from Josh's article with minor changes. See the following series of posts from Jeremy to find out how portable class library uses type forwarders to locate the definition of ICommand in a non-SL framework.


Silverlight based UI
Let's add simple interface to enter Barista's information. Let's do it first for Silverlight. It just has two TextBox (es) to enter first and last names of the barista. It also has a button, when clicked the values should be passed to the model.

While running, this should look like as follows:


WPF based Interface
Now let's add WPF based interface to the .net framework 4.5 project. As you might have noticed, the XAML is similar but not same. For silverlight, Label is not available in the framework and we need to use it from the toolkit. In order to minimize the noise there, we ended up using TextBlock(s). Additionally, the default binding Mode is OneWay in Silverlight. Since we need TwoWay binding, we needed to explicitly specify so. We don't need this specification for WPF based XAML as the default here is TwoWay. When you run it, you might miss the error message which is available in Silverlight. this appears when INotifyDataErrorInfo specifies the presence of error for a property. Although the control is highlighted in WPF, we need to provide additional logic to display the actual error message(s).


When executed, this should look like as follows [This is similar to the Silverlight based UI]:


Existing MVVM Frameworks and Toolkits
Although it would be a big relief for most of the developers who are maintaining different versions of their libraries for specific platforms. If they were already writing multitarget enabled code, then they were still using the features which were overlapping across these frameworks. With Portable library tools, this has been taken care for them. We would just need to maintain one set of libraries which support multi-targeting for the selected platforms.

The only caveat is the already existing MVVM frameworks and toolkits which are used heavily for our MVVM designs. Since Portable libraries can only reference other portable libraries supporting the selected frameworks so we wouldn't be able to use the existing frameworks and libraries. As for our code, we needed to provide our own implementation of ICommand [RelayCommand]. Since the portable feature is so promising, I am sure that the frameworks and toolkits authors are already thinking about it.

http://mvvmlight.codeplex.com/SourceControl/network/forks/onovotny/MvvmLightPortable

Download Code

Saturday, July 28, 2012

Multi Plaftorm Targeting using Portable Class Libraries - An Introduction

I have been putting off the discussion about portable class library tool for a long time now. But since Microsoft has released RC2 of the tool this month with exciting new features, it is very appealing to carry the message forward to followers of my blog.

Multi-platform targeting has been a big issue when we want to reuse our code for these platforms. It is common when we are working on a rich UI application with Silverlight and WPF interfaces. It has been so difficult to reuse our code because of incompatible class libraries. Silverlight does not support regular class libraries targeted for Windows platform and we need to create separate Silverlight Class Libraries.

Existing Workarounds for Multi-Targeting:
There are several workarounds developed to cope with this issue. One of them is project link. We create links between project to use types from the other project.

Project Linker:
This is a Visual Studio Add-on provided by Microsoft P&P. It makes life easier for linking the project items in multiple projects. If we link a project with another project, then if an item is added in the source project, the same item is added to the destination project. For a long time, developers have used this to be the only option for multi-targeting to WPF and Silverlight projects.

http://msdn.microsoft.com/en-us/library/ff648745.aspx

This can be downloaded from Visual Studio Gallery from here:

http://visualstudiogallery.msdn.microsoft.com/5e730577-d11c-4f2e-8e2b-cbb87f76c044/

Once installed, it can be used to add a project link to a destination project. Just right click a project and select Add Project Link. You can then specify the source project.


Adding Existing Item as Link: . This is the same thing as "Project Linker" does. It is just doing the same thing manually. Add an item in source project. Go to destination project, add existing item and make sure that you add it as link.

Pre-requisite:
Visual Studio 2010 sp1 or Visual Studio 2011 can be used to create portable class libraries. We do need to install Portal Library Tools. It can be downloaded from Visual Studio Gallery [http://visualstudiogallery.msdn.microsoft.com/b0e0b5e9-e138-410b-ad10-00cb3caf4981]


We can also use Extension Manager to install Portable Class Library.


Installation On Build Machines
In this time and age, you wouldn't find an organization with no Continuous Integration [CI] support. Mostly they use Jet Brain's Team City or Cruise Control .net. The pre-requisite described above are for development machines. Portable Class Library tools can be installed on build machines using /buildmachine switch. From msdn:

Run the installation program from a Command Prompt window, and include the /buildmachine switch on the command line.

Creating Portable Class Library Project
After installation of extension in Visual Studio 2010 Sp1, a project template is added for creating portable class library project. It is also available in Visual Studio 2011. We can find it in Add New Project dialog as follows:


While creating the project, an option is provided to select the required target frameworks. We can select the supported .net, silverlight and WP frameworks. It also supports the selection of XBox 360 and Metro Style App support.


These options can also be changed later on from the project's Properties page. Please notice the new Library tab available. Here we can select the target frameworks. This is equivalent to Application tab of .net framework class library where we can select the target framework.


Please not that there are other tabs too which are not available for portable class libraries.


Feature Set & Selected Frameworks:
The feature set available for portable libraries depend on the selected target frameworks. There is a universal set of feature supported by all the frameworks which are possible targets. Out of these universal features, each individual framework would support a subset.

It is very tempting to select all available frameworks for target. But doing that is limiting ourselves. As described above each framework would only support a subset of available features. Selecting multiple frameworks would make only the intersection of the features of supported frameworks. In the following example, we are selecting the .net framework and Silverlight as target frameworks. The available feature set is the overlapping area between two circles [Remember Venn diagram from your statistics courses :)]. If this is .net framework 4, then the library wouldn't have any view model support.


This could be further limiting if we select other frameworks.


Selecting all frameworks would only provide the little overlapping features supported by all frameworks.


This shouldn't be a limiting factor for your development. The library which is supposed to be shared across different platform would never have such code which have a dependency for a particular framework. The selected frameworks is basically an indication that the code is generic enough that it could be shared across these platforms.

The following subset is available for Silverlight 4, .Net for Metro style app and Windows Phone 7 platforms.


The following is the list of available libraries for the multiple targets of .net framework 4.0.3, Silverlight 4, Windows Phone 7, .Net for Metro style apps and Xbox 360.


Please not that if there is an additional framework which could also be selected without any effects to the available set for the selected frameworks than it is automatically selected.


Referencing Portable Libraries and Portable Library References:
Portable libraries cannot add references from non-portable libraries. Here ClassLibrary1 is a .net framework 4.0 class library. An attempt to add a reference to the portable class library causes the following:


Portable Library references can be added to regular libraries belonging to the supported frameworks. The same error message is displayed if an a portable library's assembly references is being added to an unsupported framework.