Tag Archives: C#

MVVM Light–Visual Studio 2013, Universal Apps, Windows Phone 8.1, Windows Store 8.1 Apps–Part 3 of N

In this part 3, let us see how to build a Universal Application for Windows Phone 8.1 and Windows 8.1 with MVVM Light support. We will also learn how to create a shared viewmodel layer, how to detect design mode and what the result is in Blend and at runtime.

In Part 2, we created a Universal Phone 8.1 app that still uses all the components present inside the project. We will use MVVM Light toolkit and remove some of the classes we created as well as code written in code behind files. Then we will make this a truly Universal App, which can be created for Windows Phone 8.1 and Windows 8.1.  This offers a nice way to structure your app in order to share as much code and other files (Views, View Models, etc) as possible. It makes it easier than ever to create apps which target both the Windows Phone 8.1 and the Windows RT devices like Surface, XBox.

MVVM is the design pattern used to develop apps in Windows Store apps as well as Windows Phone apps. Lets use MVVM Light framework to develop a windows store app. You can get the latest MVVM Light toolkit from http://mvvmlight.codeplex.com/

Creating the Application

Step 1: Open the project created in Part 2 using Visual Studio 2013.
Step 2: Right click on the References folder in the Windows Phone 8.1 application, and select Manage Nuget Packages.
Step 3: Select the Online source for Nuget and search for MVVM Light.
Step 4: Select the package MVVM Light Libraries only. Alternatively you can select the package named MVVM Light Libraries Only (PCL). This will install the exact same binaries and eventually I will remove this package and keep only the main one.
Step 5: Repeat steps 2 to 5 for the Windows 8.1 application.
Step 6: At this point, you have added MVVM Light support to both your applications as shown in Figure 1. Now we can add the files that will bring the full support for the ViewModel layer and the design support.

image

Figure 1: MVVM Light libraries referenced in Universal Projects in VS 2013

Adding ViewModel Layer:

it’s time to instantiate and create the ViewModels. This is the ViewModelLocator class task. This class is quite important in the application structure enabled by MVVM Light. It’s created as a XAML resource in the file App.xaml. This creates the important link between XAML markup and source code, allowing the visual designers to create the ViewModels and to run the design-time code. Lets create two files ViewModelLocator and the MainViewModel.

Adding ViewModelLocator & PersonViewModel:

The main task of ViewLocator is to link up your views with the view models. It’s responsible for creating and disposing of all of your View-Models. In this ViewLocator, mostly we just add additional views. Let’s do that.

The main task of ViewLocator is to link up your views with the view models. It’s responsible for creating and disposing of all of your View-Models. In this ViewLocator, mostly we just add additional views. Let’s do that.

Step 7: Right click on the Shared node and select Add, New Folder. Name this folder ViewModel.
Step 8: Right click on the new ViewModel again and select Add, New Item. Select a Class, and name it ViewModelLocator.cs
Step 9: Modify the ViewModelLocator code to look like in the code segment 1 below.
Step 8: Move the class PersonViewModel.cs from Windows Phone 8.1 to ViewModel present in shared node.
Step 9: Modify the MainViewModel class to look like code snippet 2 below. Of course you can add a bunch of new methods, observable properties and commands to this ViewModel as usual in MVVM.

Here I created PersonViewModelProp property that returns an instance of PersonViewModel and we registered this PersonViewModel class in line 23 of code snippet 1.

Code Snippet 1
  1. public class ViewModelLocator
  2.     {
  3.         public MainViewModel Main
  4.         {
  5.             get
  6.             {
  7.                 return ServiceLocator.Current.GetInstance<MainViewModel>();
  8.             }
  9.         }
  10.  
  11.         public PersonViewModel PersonViewModelProp
  12.         {
  13.             get
  14.             {
  15.                 return ServiceLocator.Current.GetInstance<PersonViewModel>();
  16.             }
  17.         }
  18.  
  19.         static ViewModelLocator()
  20.         {
  21.             ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);
  22.             SimpleIoc.Default.Register<MainViewModel>();
  23.             SimpleIoc.Default.Register<PersonViewModel>();
  24.         }
  25.     }

Code Snippet 1: ViewModelLocator

Code Snippet 2
  1. public class PersonViewModel : ViewModelBase
  2.     {
  3.         public ObservableCollection<Person> Persons
  4.         {
  5.             get;
  6.             set;
  7.         }
  8.  
  9.         public Person personObject
  10.         {
  11.             get;
  12.             set;
  13.         }
  14.  
  15.  
  16.         private ICommand _savePersonCommand;
  17.         public ICommand SavePersonCommand
  18.         {
  19.             get
  20.             {
  21.                 return _savePersonCommand;
  22.             }
  23.  
  24.             set
  25.             {
  26.                 _savePersonCommand = value;
  27.             }
  28.         }
  29.         public PersonViewModel()
  30.         {
  31.             ObservableCollection<Person> _persons = new ObservableCollection<Person>();
  32.             _persons.Add(new Person { FirstName = IsInDesignMode
  33.                                     ? "bill" : "Bill",
  34.                                       LastName = IsInDesignMode
  35.                                           ? "gates" : "Gates" });
  36.             _persons.Add(new Person { FirstName = "Steve", LastName = "Ballmer" });
  37.             Persons = _persons;
  38.             personObject = new Person { FirstName = "Satya", LastName = "Nadella" };
  39.             _savePersonCommand = new RelayCommand(SavePerson, CanSavePerson);
  40.         }
  41.  
  42.         private bool CanSavePerson()
  43.         {
  44.             if (string.IsNullOrEmpty(personObject.FirstName) || string.IsNullOrEmpty(personObject.LastName))
  45.                 return false;
  46.             else
  47.                 return true;
  48.         }
  49.  
  50.         private void SavePerson()
  51.         {
  52.             Persons.Add(new Person { FirstName = personObject.FirstName, LastName = personObject.LastName });
  53.             //MessageDialog dialog = new MessageDialog(string.Format("Saved: {0}  {0}", personObject.FirstName, personObject.LastName));
  54.             //await dialog.ShowAsync();
  55.  
  56.         }
  57.  
  58.  
  59.     }

Code Snippet 2: PersonViewModel

Adding Locator resource to App.XAML

Open the App.xaml file in Visual Studio 2013 and modify it to look like code snippet 3 below. This creates a new resource with the ViewModelLocator, which we will use in the designer. Notice the addition of the “d” and “mc” XML namespaces so that we can mark the ViewModelLocator as a DataSource, which will make it show up in the Data panel in Blend.

Code Snippet 3
  1. <Application
  2.     x:Class="UniBlank_MVVMBasics.App"
  3.     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;
  4.     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml&quot;
  5.     xmlns:local="using:UniBlank_MVVMBasics"
  6.      xmlns:d="http://schemas.microsoft.com/expression/blend/2008&quot;
  7.     xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006&quot;
  8.     mc:Ignorable="d"
  9.     xmlns:vm="using:UniBlank_MVVMBasics.ViewModel">
  10.     
  11.     <Application.Resources>
  12.         <vm:ViewModelLocator x:Key="Locator"
  13.                              d:IsDataSource="True"/>
  14.     </Application.Resources>
  15.  
  16. </Application>

Making it a truly Universal App:

Since there is nothing great we are doing here, we can easily make it a universal app with all the code shared between both the projects.  Move all the files that we created from Windows Phone 8.1 to Shared node as shown in Figure 2. Delete the files from Windows Phone 8.1 project. In Windows 8.1 project too, delete MainPage.XAML and hurray, we have our first universal app with MVVM. Now, Windows 8.1 store app begins to show up the same UI we have created for Windows Phone 8.1. Amazing!!!!

image

Figure 2: Moving files to Shared node for making this a Universal app code.

Connecting View and ViewModel:

Step 10: Set the DataContext of the Page to the MainViewMode as shown in Code Snippet 4.

Code Snippet 4
DataContext="{Binding PersonViewModelProp, Source={StaticResource Locator}}"

This is the complete code of PersonView User control.

Code Snippet
  1. <UserControl
  2.     x:Class="UniBlank_MVVMBasics.PersonView"
  3.     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;
  4.     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml&quot;
  5.     xmlns:d="http://schemas.microsoft.com/expression/blend/2008&quot;
  6.     xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006&quot;
  7.     mc:Ignorable="d"
  8.     d:DesignHeight="300"
  9.     d:DesignWidth="400" Loaded="UserControl_Loaded"
  10.     xmlns:local="using:UniBlank_MVVMBasics"
  11.     DataContext="{Binding PersonViewModelProp, Source={StaticResource Locator}}" >

Comment the code we wrote in PersonView.xaml.cs

Code Snippet
  1. private void UserControl_Loaded(object sender, RoutedEventArgs e)
  2.       {
  3.           //PersonViewModel personViewModelObject = new PersonViewModel();
  4.           //this.DataContext = personViewModelObject;
  5.       }

 

Download the source code from here.

Advertisements

Getting Started with Visual Studio 2013, Windows Phone 8.1, Window Store 8.1, MVVM –Part 2 of N

 

In Part 1, we have seen how to write code in Model, view and viewmodel to wire up data and show it in the UI. There is a clear separation among the three layers. Now let us extend the sample and see how we can implement commanding. We will just add a Save button and when the user clicks Save, add a record to ObservableCollection and the UI automatically shows the data.

Step 1: Add a new class called DelegateCommand.cs and inherit from ICommand

DelegateCommand.cs
  1. public class DelegateCommand : ICommand
  2.     {
  3.         private readonly Action<object> _executeMethod = null;
  4.         private readonly Predicate<object> _canExecuteMethod = null;
  5.         private bool _isAutomaticRequeryDisabled = false;
  6.  
  7.         public DelegateCommand(Action<Object> executeMethod, Predicate<object> canExecuteMethod, bool isAutomaticRequeryDisabled)
  8.         {
  9.             if (executeMethod == null)
  10.             {
  11.                 throw new ArgumentNullException("executeMethod is null. Please set executeMethod.");
  12.             }
  13.             _executeMethod = executeMethod;
  14.             _canExecuteMethod = canExecuteMethod;
  15.             _isAutomaticRequeryDisabled = isAutomaticRequeryDisabled;
  16.         }
  17.  
  18.         public bool CanExecute(object parameter)
  19.         {
  20.             return _canExecuteMethod == null ? true : _canExecuteMethod(parameter);
  21.         }
  22.  
  23.         public event EventHandler CanExecuteChanged;
  24.  
  25.         public void Execute(object parameter)
  26.         {
  27.             if (_executeMethod != null)
  28.                 _executeMethod(parameter);
  29.         }
  30.  
  31.         //In WinRT, there is no CommandManager to raise events globally. you must update/raise CanExecuteChanged manually
  32.         public void RaiseCanExecuteChanged()
  33.         {
  34.             if (CanExecuteChanged != null)
  35.                 CanExecuteChanged(this, EventArgs.Empty);
  36.         }
  37.  
  38.     }

Step 2: Modify the person class created in Part 1 to includes command for Save.

PersonViewModel.cs
  1. public class PersonViewModel
  2.     {
  3.         public ObservableCollection<Person> Persons
  4.         {
  5.             get;
  6.             set;
  7.         }
  8.  
  9.         public Person personObject
  10.         {
  11.             get;
  12.             set;
  13.         }
  14.  
  15.  
  16.         private ICommand _savePersonCommand;
  17.         public ICommand SavePersonCommand
  18.         {
  19.             get
  20.             {
  21.                 return _savePersonCommand;
  22.             }
  23.  
  24.             set
  25.             {
  26.                 _savePersonCommand = value;
  27.             }
  28.         }
  29.         public PersonViewModel()
  30.         {
  31.             ObservableCollection<Person> _persons = new ObservableCollection<Person>();
  32.             _persons.Add(new Person { FirstName = "Bill", LastName = "Gates" });
  33.             _persons.Add(new Person { FirstName = "Steve", LastName = "Ballmer" });
  34.             Persons = _persons;
  35.             personObject = new Person { FirstName = "Satya", LastName = "Nadella" };
  36.             _savePersonCommand = new DelegateCommand(SavePerson, CanSavePerson, false);
  37.         }
  38.  
  39.         private bool CanSavePerson(object obj)
  40.         {
  41.             if (string.IsNullOrEmpty(personObject.FirstName) || string.IsNullOrEmpty(personObject.LastName))
  42.                 return false;
  43.             else
  44.                 return true;
  45.         }
  46.  
  47.         private void SavePerson(object obj)
  48.         {
  49.             Persons.Add(new Person { FirstName = personObject.FirstName, LastName = personObject.LastName });
  50.             //MessageDialog dialog = new MessageDialog(string.Format("Saved: {0}  {0}", personObject.FirstName, personObject.LastName));
  51.             //await dialog.ShowAsync();
  52.  
  53.         }
  54.  
  55.  
  56.     }

Step 3: Add a button to UserControl in PersonView.xaml and add Command property from viewmodel.

PersonView.xaml
  1. <UserControl
  2.     x:Class="UniBlank_MVVMBasics.PersonView"
  3.     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;
  4.     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml&quot;
  5.     xmlns:d="http://schemas.microsoft.com/expression/blend/2008&quot;
  6.     xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006&quot;
  7.     mc:Ignorable="d"
  8.     d:DesignHeight="300"
  9.     d:DesignWidth="400" Loaded="UserControl_Loaded"
  10.     xmlns:local="using:UniBlank_MVVMBasics">
  11.     <Grid>
  12.         <StackPanel HorizontalAlignment="Left">
  13.             <ListView ItemsSource="{Binding Path=Persons, Mode=TwoWay}">
  14.                 <ListView.ItemTemplate>
  15.                     <DataTemplate>
  16.                         <StackPanel Orientation="Horizontal" Margin="20,20,0,0">
  17.                             <TextBlock Margin="10,0,20,0" Text="{Binding Path=FirstName, Mode=TwoWay}" Style="{StaticResource HeaderTextBlockStyle}"></TextBlock>
  18.                             <TextBlock Text="{Binding Path=LastName, Mode=TwoWay}" Style="{StaticResource HeaderTextBlockStyle}"></TextBlock>
  19.                         </StackPanel>
  20.                     </DataTemplate>
  21.                 </ListView.ItemTemplate>
  22.             </ListView>
  23.         </StackPanel>
  24.  
  25.         <StackPanel>
  26.              <Button Content="Save" HorizontalAlignment="Right" Width="80" Command="{Binding Path=SavePersonCommand}"/>
  27.         </StackPanel>
  28.  
  29.     </Grid>
  30. </UserControl>

Note: In WinRT, you must update/raise CanExecuteChanged manually. There is no CommandManager to do this globally. You could look at this as a pain in the neck, or a serious performance boost now that CanExecute is not called constantly. It does mean you have to think about cascading property changes where before you did not have to. But this is how it is. Manual.

Download the source code from here.

Getting Started with Visual Studio 2013, Windows Phone 8.1, Window Store 8.1, MVVM –Part 1 of N

With the recent release of Universal Apps, Windows Phone 8.1, Visual Studio 2013 Ultimate Update 2 RC , Windows Store 8.1 Update & Windows 8.1 update from Microsoft, I thought to blog some articles on these new technologies and there is no better design pattern to use than MVVM. So I will walk through some of the latest programming updates from MS along with MVVM.

Required Software’s:

Benefits of MVVM:

1. Separation of Concerns (View, ViewModel, Model)
2. Clean testable and manageable code. Can include presentation tier logic in unit testing.
3. No code behind code, so the presentation layer and the logic is loosely coupled.
4. Better way of data binding.
5. With the new Window Runtime support for Windows Phone 8.1, we can now use the same Windows Store code for ICommand pattern implementation.

Overview MVVM Layers

image

Steps to Implement MVVM:

Lets get our hands dirty. Here we are going to develop a Windows Phone 8.1 application using Windows Runtime & XAML (Not Silverlight). Figure 1 shows the UI we are planning to develop.

Before writing code, analyze what we want to achieve and then come up with the class names, draw relation ships on paper and see how all the components fit together. Here I have two variables firstname and lastname and I wanted to show the data in the UI as shown in figure 1. So lets use MVVM to achieve this.

image

Figure 1: Views showing Model data using MVVM design pattern

Step 1: Fun with MVVM begins. Create a Universal Project by opening VS 2013 –> New –> Project –> Templates->Visual C#->Store Apps->Universal Apps and select Blank App (Universal Apps). Name it as UniBlank_MVVMBasics as shown in Figure 2.

image

Figure 2: New Universal Apps Project template in Visual Studio 2013

Step 2: VS 2013 creates two projects. One for Windows Store and other for Windows Phone. Both use Windows Runtime API as the core targeting 8.1 platforms. Shared project is the shared component between the two projects and we will get to this when we learn more about Universal Apps Project template.

image

Figure 3: Universal Apps Projects in VS 2013.

Step 3: Adding a class. Right click on UniBlank_MVVMBasics.WindowsPhone –>Add->Class as shown in Figure 4.image

Figure 4: Adding a class in Visual Studio 2013.

Step 5: Name it as Person.cs as shown in Figure 5.image

Figure 5: Add New Item Dialog

Step 6: Create a Simple Model (Person.cs) with required properties and implement PropertyChanged property of INotifyPropertyChanged.

Person Class Code
  1. class Person : INotifyPropertyChanged
  2.     {
  3.         public event PropertyChangedEventHandler PropertyChanged;
  4.  
  5.         private string _firstName;
  6.         public string FirstName
  7.         {
  8.             get
  9.             {
  10.                 return _firstName;
  11.             }
  12.  
  13.             set
  14.             {
  15.                 if (_firstName != value)
  16.                 {
  17.                     _firstName = value;
  18.                     OnPropertyChanged("FirstName");
  19.                 }
  20.             }
  21.         }
  22.  
  23.         private string _lastName;
  24.         public string LastName
  25.         {
  26.             get
  27.             {
  28.                 return _lastName;
  29.             }
  30.  
  31.             set
  32.             {
  33.                 if (_lastName != value)
  34.                 {
  35.                     _lastName = value;
  36.                     OnPropertyChanged("LastName");
  37.                 }
  38.             }
  39.  
  40.         }
  41.  
  42.         public void OnPropertyChanged(string property)
  43.         {
  44.             if (PropertyChanged != null)
  45.             {
  46.                 PropertyChanged(this, new PropertyChangedEventArgs(property));
  47.             }
  48.         }
  49.     }

Step 7: Create a ViewModel (PersonViewModel.cs) with required logic to bind Model to ViewModel. (Repeat step 3 t step 5 and name class as PersonViewModel.cs.

Code Snippet
  1. class PersonViewModel
  2.     {
  3.         public ObservableCollection<Person> Persons
  4.         {
  5.             get;
  6.             set;
  7.         }
  8.  
  9.         public void LoadPersons()
  10.         {
  11.             ObservableCollection<Person> _persons = new ObservableCollection<Person>();
  12.             _persons.Add(new Person{ FirstName="Bill", LastName="Gates"});
  13.             _persons.Add(new Person{ FirstName="Satya", LastName="Nadella"});
  14.             Persons = _persons;
  15.         }
  16.     }

Step 8: Instead of using MainPage.XAML to show the data, let us create Views as we do typically in a software development. Create a View (PersonView.xaml) and bind the data with ViewModel. Add a User Control to the solution and name it as PersonView.xaml as shown in Figure 6.image

Figure 6: Adding View (User Control) to the project in VS 2013

Step 9: As we have to display firstname and lastname, lets use TextBlock’s. We will use  ItemsControl and Persons (observablecollection property) as DataContext and put them inside a DataTemplate to display the data from model in the view. In PersonView.XAML, write the following code inside Grid tag as shown below.

XAML code- Person User Control
  1. <Grid>
  2.         <StackPanel HorizontalAlignment="Left">
  3.             <ItemsControl ItemsSource="{Binding Path=Persons}">
  4.                 <ItemsControl.ItemTemplate>
  5.                     <DataTemplate>
  6.                         <StackPanel Orientation="Horizontal" Margin="20,20,0,0">
  7.                             <TextBlock Margin="10,0,20,0" Text="{Binding Path=FirstName, Mode=TwoWay}" Style="{StaticResource HeaderTextBlockStyle}"></TextBlock>
  8.                             <TextBlock Text="{Binding Path=LastName, Mode=TwoWay}" Style="{StaticResource HeaderTextBlockStyle}"></TextBlock>
  9.                         </StackPanel>
  10.                     </DataTemplate>
  11.                 </ItemsControl.ItemTemplate>
  12.             </ItemsControl>
  13.         </StackPanel>
  14.  
  15.     </Grid>

Step 10: In PersonView.xaml.cs, let us create an object of PersonViewModel class and pass it as DataContext to the View we just created as shown below.

PersonView.xaml.cs code
  1. private void UserControl_Loaded(object sender, RoutedEventArgs e)
  2. {
  3.     PersonViewModel personViewModelObject = new PersonViewModel();
  4.     personViewModelObject.LoadPersons();
  5.     this.DataContext = personViewModelObject;
  6. }

Step 11: In MainPage.xaml, let us import the xmlns:views=”using:UniBlank_MVVMBasics” namespace and put the views inside the grid as shown below.

MainPage.xaml code
  1. <Page
  2.     x:Class="UniBlank_MVVMBasics.MainPage"
  3.     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;
  4.     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml&quot;
  5.     xmlns:local="using:UniBlank_MVVMBasics"
  6.     xmlns:d="http://schemas.microsoft.com/expression/blend/2008&quot;
  7.     xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006&quot;
  8.     mc:Ignorable="d"
  9.     Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"
  10.     xmlns:views="using:UniBlank_MVVMBasics" >
  11.  
  12.     <Grid>
  13.         <views:PersonView></views:PersonView>
  14.     </Grid>
  15. </Page>

That’s it. Download the source code here.

Below are some of the points to remember about MVVM layers.

Model:

1. Represents the Data.
2. The Entity.
3. Model classes are non-visual classes that encapsulate the application’s data and business logic.
4. They are responsible for managing the application’s data and for ensuring its consistency and validity by encapsulating the required business rules and data validation logic.
5. The model classes do not directly reference the view or view model classes and have no dependency on how they are implemented.
6 The model classes typically provide property and collection change notification events through the INotifyPropertyChanged and INotifyCollectionChanged interfaces.
7. This allows them to be easily data bound in the view.
8. Model classes that represent collections of objects typically derive from the ObservableCollection<T> class.
9. The model classes typically provide data validation and error reporting through either the IDataErrorInfo or INotifyDataErrorInfo interfaces.
10. The model classes are typically used in conjunction with a service or repository that encapsulates data access and caching.
11. Not required to know where it gets its data from i.e from a WCF service. WCF RIA Services, etc.
12. May contain validation.

View:

1. The view is a visual element, such as a window, page, user control, or data template.
2. The view defines the controls contained in the view and their look and feel, visual layout and styling.
3. The view references the view model through its DataContext property.
4. The controls in the view are data bound to the properties and commands exposed by the ViewModel.
5. The view may customize the data binding behavior between the view and the view model.
For e.g, the view may use value converters to format the data to be displayed in the UI, or it may use validation rules to provide additional input data validation to the user.
6. The view defines and handles UI visual behavior, such as animations or transitions that may be triggered from a state change in the view model or via the user’s interaction with the UI.
7. The view’s code-behind may define UI logic to implement visual behavior that is difficult to express in XAML or that requires direct references to the specific UI controls defined in the view. 

ViewModel:

1. The ViewModel is a non-visual class and does not derive from any WPF or Silverlight base class.
2. It encapsulates the presentation logic required to support a use case or user task in the application.
3. The ViewModel is testable independently of the view and the model.
4. The ViewModel typically does not directly reference the view. It will have UI Friendly Entities, UI State, Actions and Public properties that are bound to a View.
5. It implements properties and commands to which the view can data bind.
6. It notifies the view of any state changes via change notification events via the INotifyPropertyChanged and INotifyCollectionChanged interfaces.
7. Interacts with View with various Commands.
8. The view model coordinates the view’s interaction with the model.
9. It may convert or manipulate data so that it can be easily consumed by the view and may implement additional properties that may not be present on the model.
10. It may also implement data validation via the IDataErrorInfo or INotifyDataErrorInfo interfaces.
11. The view model may define logical states that the view can represent visually to the user.
12. Invokes services to communicate outside the MVVM triad.

My First Windows Store App : Emergency – Help Me

You can download from Windows Store at http://apps.microsoft.com/webpdp/en-US/app/emergency-help-me/477b898a-6781-4b75-a439-44dee5904f14

Have you ever thought what you would do, if an unforeseen events happens and you need to alert/contact someone immediately, but for whatever reason you can’t? An emergency might impose itself in various ways, someone is stalking/following you, traffic accidents, car trouble, walking at night, lost during hiking/camping trip, threat during a foreign visit, and many more. Odds are that you might have your mobile device with you but given the nature of the situation you might not have time or the means to communicate conventionally via a text message/call for help and to let someone know of your situation. Unlikely? Maybe. But what if…?

Emergency – Help Me is the first go-to app in case of an emergency. The App generates a SOS distress signal to attract attention of others, simulates a police siren and lights, displays emergency phone numbers for all countries, displays your current location, stores ‘In Case of Emergency’ information, Flash Light and has Request and Respond to alpine emergency (mountain help) light signal. Additionally, this provides you a feature to communicate with a click of a button. You can tell your current location, contact details when in emergency, your medical conditions, blood group, allergies and other information useful during an emergency situation. With just a click of a button, you can send the information to a variety of apps like Facebook, Twitter, Email and any app on Windows Store that accepts text to share.

You can take advantage of 8 sensational features as shown in Fig 0.1:

  • SOS Emergency Flasher
  • Police Emergency
  • International Emergency Phone Numbers
  • GPS Location Data
  • In Case of Emergency (ICE)
  • Flash Light
  • Alpine Distress Signal
  • Respond to Alpine Distress Signal

image 

Fig 0.1: Figure showing the main launch page of the application

Windows features supported in the app:
  • Color Preference and ICE Data Roaming – Roaming personalization settings is key to feeling connected to your preferences and data. You don’t want to configure or choose preferences every time you use a new device. The ‘Help Me’ app creates a connected experience by allowing the user to configure ICE (In Case of Emergency) data and color preference once and use it everywhere, so you don’t have to re-configure the app each time you access it from a different system. When you change the color of the screen by using app bar, it is automatically saves to your preferences. So the next time you open the app and use any feature from any PC or device, it knows the color of your choice and your configured data. The app helps you connect to your data from anywhere by having a continuous experience as you transition from one device to another. image

Fig 1: Choose color preference from App Bar. The choice of color is automatically remembered by the application. image 

Fig 2: Enter information of the person to be contacted during emergency and your medical data. The data is automatically saved and synced to your personal account you used to login.

  • Semantic Zoom – Users can now easily navigate countries list within a single view. Semantic Zoom organizes countries alphabetically in a single view and presents the data using the letters of the alphabet. The user could then zoom in on a letter to see the countries associated with that letter as shown in figure 3. image image

Fig 3: Semantic Zoom of International Emergency Numbers.

  • Share charm – You often come across a situation where you want to share your emergency situation, current location and ICE information with someone or use it in another app. The “Help Me” app exchanges data with other apps without having to navigate away to share data. The app helps you to share content with another app or service quickly and easily by using Windows Share charm. So you can continue using the Help Me app and still share your information.

         image

Fig 4: Sharing data with other apps using Share charm.

  • Search charm – Lets users search the app from anywhere in the system, including the app itself. Users will be able to use the Search charm to open a search pane where they can enter search queries and the app displays the search results with the following. 

Suggestions: Start typing country name in the search pane, and you will get a list of suggestions as well. This displays a maximum of 5 countries in the suggestions list as shown in figure 5. image    Fig 5: Search pane automatically showing the Search suggestions as the user types in.

Filter List: Country names and emergency numbers can be searched. Simply start typing in the search charm and you’ll see your list of countries or emergency numbers filter down to the one you are looking for as shown in figure 6. image image

Fig 6: Search results displaying the countries that contain the string user searched for.

  • Secondary Tile – Help Me app enables you to pin a specific content or experience from an app to the start screen. Secondary tiles provide a direct link to the feature within the app. Pin any country or main features tile to the main screen and the app takes you directly to that feature shown in figure 7.

image    

Fig 7: Large Secondary Tiles (Shortcuts) to the app features.

image

Fig 7.1: Small Secondary Tiles (Shortcuts) to the app features.

  • Help Page: Help information is included to explain the features of the app. Every feature (tile) has a help page include with it to explain the functionality in detail as shown in figure 8.

image image

Fig 8: Help information displayed on Help screen.

  • Settings – Help me app implements Settings contract so that you can access its settings like switching location access on or off from the Settings charm.

image

Fig 9: Application Settings.

  • App Bars: The app bar contains contextual actions or commands for each screen in the app. Frequently used commands are kept near the right and the left edges so that they are easy to reach by hand as shown in figure 10.

image

Fig 10: One of the features showing App Bar.

All tiles (screens) in the app support Share and Search contracts of Windows Store apps. The app adjusts the screen display perfectly in landscape, portrait, filled and snapped view as shown in the following figures A-K.

image

Fig A: Main Screen shown in portrait view.

image

Fig B: Main Screen shown in snapped view.

image

Fig C: Main Screen shown in filled view.

image

Fig D: SOS Emergency Signal Screen shown in snapped view.

image

Fig E: SOS Emergency Signal Screen shown in filled view.

image

Fig F: Police Emergency Signal Screen shown in portrait view.

image

Fig G: Police Emergency Signal Screen shown in snapped view.

image

Fig H: Police Emergency Signal Screen shown in filled view.

image

Fig I: International Emergency Numbers Screen shown in snapped view.

image

Fig J: International Emergency Numbers Screen shown in portrait view.

image

Fig K: International Emergency Numbers Screen shown in filled view.

A distress signal is an internationally recognized means for obtaining help. Distress signals are commonly made by displaying a visually detected item or illumination, or making an audible sound, from a distance. In order for distress signaling to be the most effective, two parameters must be communicated:

  1. Alert or notification of a distress in progress
  2. Position or location of the party in distress.
SOS Emergency Flasher:

This is super easy to use. Just run it! A flashing emergency light with high distress signal sound for alerting people that you are in an emergency situation as shown in figure 11. A realistic light, in a variety of colors, that blinks and has attention grabbing pattern to make yourself visible in the dark, attract attention or warn others about an emergency or safety hazard.

Simply run it to continuously display a flashing light and distress sound – perfect for use in traffic accidents, car trouble, running or walking at night, and more. Emergency Flasher is a feature dedicated to everyone who want to feel more secure any place, any time.

Features:
* Intuitive and elegant UI design
* Realistic screen display with flashing.
* Distress sound to alert or attract attention of others.
* Variety of color options to choose from App bar. Your choice of color is remembered by the device automatically. If you open the app on a new device, it displays the light with your preferred color automatically.
* App bar to play or stop the sound.
* Use Windows Share charm to share your location and ICE details with other people or apps.

image 

Fig 11: SOS Emergency Signal screen.

Police Emergency:

Is someone stalking you? Use this feature to alert others. Real high quality police beacon and blue/red strobe light blow up to full screen that will turn any vehicle (such as your own personal vehicle) into your very own emergency vehicle! This is a cool feature that continuously simulates a police siren and lights. The app bar displays the controls to play, pause or stop the sound

Features:
* Realistic screen display with flashing.
* Police Beacon sound to alert or attract attention of others.
* App bar to play, pause or stop the sound.
* Use Windows Share charm to share your location and ICE details with other people or apps.

image

Fig 12: Police Beacon screen.

International Emergency Phone Numbers:

Travel the world with peace of mind. Ever been on vacation abroad or on a business trip and an emergency occurs, and you wonder what number to call? Ever wondered how to call the police? The firefighter? Or an ambulance? To be perfectly honest, most people are not aware of these and added to that not every country in the world has the same emergency numbers. The problem arises when you need something fast and in case of emergency.. Don’t forget, roaming internet can be very expensive in other countries. With this app, simply select the country you are in and with just one tap the app displays the emergency numbers for the country you are in. It is possible to call an emergency number right away, without going to menus using snapped view. It doesn’t use internet, so no roam costs! Hopefully this app makes your holiday a lot safer. Have fun!

Features:
* Zooming functionality to easily navigate to the country that you are searching for.
* Share emergency details with your friends and family members with just a button click.
* No GPS or cell data network required.
* Fast selection of which country you are in. Search by index or free search to quickly select the country. Each country is listed by its name and national flag.
* No cell coverage? You can still call! It displays the emergency phone numbers from the country you select. Just read the emergency numbers from the app and make the call from a landline based phone.
* Supports 237 countries (covers most of the world that support emergency telephone numbers).
* Using Windows start screen, you can search for police, fire or medical emergency number of any country in this world and the app shows you the information directly with just a click.
* Directly search for a country by typing in the Windows Search charm.

image

Fig 13: International Emergency Numbers screen.

GPS Location Data:

Never get lost. Using this feature, you can let others know your current location with just a click. GPS Location uses the device GPS to show your position coordinates and current address in case of emergency. With just a press of a button, you can send your position details to any of your contacts using any Windows Store app that can share information. Your GPS location will be displayed on the screen in any view so that you can quickly provide you exact location.

Features:
* Get GPS coordinates
* See how accurate the GPS coordinates are
* Send your position to a family member or friend through any Windows store app that shares information.
* You can activate the Track Me feature and the app displays your current location coordinates, in real-time. You can stop the tracking feature when you want!
* The application automatically detects your GPS coordinates [location]. These coordinates along with the information you entered into the In Case of Emergency tile of the application can be send with any Windows Store app that accepts text like Twitter, Facebook, Email and other social media services.

image

Fig 14: GPS Location Data screen.

In Case of Emergency (ICE):

This screen provides all the information needed in case of emergency. You can add your own emergency contacts. This fantastic tile rolls so many features into one screen:

Features:
* Store your Emergency contact Details like the person name to be contacted during emergency, phone number, Twitter ID, Facebook ID and email address of the person.
* Store your allergies information
* Store you prescriptions & important medical conditions
* Record your insurance details (travel, car, home etc.) – making sure you have these details to hand at the right time.
* Store your doctors contact details
* Store your address in case someone needs it during emergency.
* Use Windows Share charm to share your location and ICE details with other people or apps.

image

Fig 15: ICE Information screen.

Flash Light:

Bright. Fast. Simple. The most elegant and functional flashlight tile. Flashlight fills the device screen with bright white light to illuminate your world when you find yourself in a dark spot or concert.

Features:
* Full white screen.
* Brightest Flashlight instantly ON.
* Change flashlight color with just a click.
* Choose from a variety of widely useful colors from App bar. Your choice of color is remembered by the device automatically.
* Use Windows Share charm to share your location and ICE details with other people or apps.

image

Fig 16: Flash Light screen.

Alpine Distress Signal (Mountain Emergency Help):

Alpine Request is a feature that uses the device screen to transmit alpine distress help light indicating mountain emergency. The entire process is controlled automatically. The only thing you need to do is to trigger the process.

Features:
* Choose from a variety of commonly used colors to transmit light signal during daytime or night. Your choice of color is remembered by the device automatically.
* Easy to use interface.
* Share your location and ICE details with others.

image

Fig 17: Alpine Distress Signal screen.

Respond to Alpine Distress Signal:

Alpine Response is a feature that uses the device screen to transmit response to an alpine distress signal indicating that you have received the Alpine Emergency Signal. The entire process is controlled automatically. The only thing you need to do is to trigger the process.

Features:
* Choose from a variety of commonly used colors to transmit light signal during daytime or night. Your choice of color is remembered by the device automatically.
* Easy to use interface
* Share your location and ICE details with others
* If the device has a light sensor, the app displays light in Red color if it is daytime and in bright white color if it is night.

image

Fig 18: Respond to Alpine Distress Signal screen.

While we hope that you never need this app, we would like to give you peace of mind. Our goal is that in case of an emergency or an unforeseen event, you are prepared and you can easily communicate your situation and current location to others.

The creator of this application is under no circumstances liable for any direct, indirect, incidental, consequential or exemplary injury or damages resulting from the use of this application. Calling an emergency number without reason is forbidden in most countries.

There will be a continued commitment from the developer to implement new features or solve problems you encounter! Just drop a comment on this blog.

Privacy Policy

Your privacy is very important to us. Accordingly, we have developed this Policy in order for you to understand how we collect, use, communicate and disclose and make use of personal information. The following outlines our privacy policy.

  • The application uses internet connection only to retrieve your location information upon request. Other than that, we do not use internet connection at all.
  • Before or at the time of collecting personal information, we will identify the purposes for which information is being collected.
  • We do not collect any personal information. Personal information is used solely with the objective of fulfilling those purposes specified by us like In Case of Emergency information, unless we obtain the consent of the individual concerned or as required by law.
  • The application only retain ICE information as long as necessary for the fulfillment of those purposes. ICE information is saved onto your device and is stored with your device Windows account. Other than displaying the ICE information in the app, we do not use your ICE data at all for any other purposes.
  • ICE Personal data should be relevant to the purposes for which it is to be used, and, to the extent necessary for those purposes, should be accurate, complete, and up-to-date.
  • We will protect personal information by reasonable security safeguards against loss or theft, as well as unauthorized access, disclosure, copying, use or modification.
  • We will make readily available to customers information about our policies and practices relating to the management of personal information.

We are committed to conducting our business in accordance with these principles in order to ensure that the confidentiality of ICE information is protected and maintained.

25 Reasons to develop Microsoft Design Style Apps in C#/XAML

Windows 8 introduces Microsoft Design Style as a new a development paradigm on the Microsoft platform. Windows store apps can be developed using .NET/XAML, C++/XAML or HTML5/Java Script technologies. Now, the tricky question is “which technology should people choose to develop Windows store apps?”. For me, I chose C#/XAML. Here I wanted to walk through some of the key reasons for the choice of technology. Also,  as a Windows Store App developer, there are some things XAML developers should know that will save them serious time.

1. Easy to find .NET developers

It’s easy to find .NET developers for development and maintenance of Windows Store Apps. Also, Windows 8 provides no-compromise options to developers to choose JavaScript/HTML5, C#/XAML, and C++/XAML without giving up on features and support. But i would choose C++ if i am developing an application that has to perform at the highest level with good memory management.

2. Bind to Anything

The power of XAML really starts at its native ability to data bind. Nothing data binds like XAML – one way, two way, one time, and to almost any property. Not only is it built-in, not only is it powerful, not only is it fast, but it’s simple. Check out this snippet:

image

In the code above, I am binding the Text property of of the TextBox to the Value property of the Slider. All of the event listening and value conversion is done for me. I just write it up with a syntax that is easy to understand (although you have to get it correct).

3. Resolution Independence

XAML has always had resolution independency. And, here’s what it means. Let’s say you have a 17 inch monitor with 1024×768 resolution. The XAML app looks perfect. You upgrade to the same size (17 inches) but higher pixel density (1680×1050). What happens to your app? Because of XAML’s resolution independency, it looks completely the same – just clearer, sharper.

Hh465362.ux_scaling(en-us,WIN.10).png

Resolution dependency would have caused the application to get smaller. But we don’t buy high resolution to get application thumbnails. We get high resolution so applications are crisp and clear. Size values in XAML are not pixels, they are device-independent units.

4. Dependency Properties

A XAML UI could have a hundred controls, easily – especially in the visual tree. XAML controls could have a hundred properties, easily – especially with attached properties. 100×100 is 10,000 properties. That’s a lot, huh? Fortunately, XAML solves this with Dependency Properties.

Dependency Properties can be inherited from parent controls. They can be attached by outside assemblies. They can be animated and automated. Plus they fire change events. But, even better is – they take up no memory until they are actually set. Brilliant.

MSDN: The purpose of dependency properties is to provide a way to compute the value of a property based on the value of other inputs. These other inputs might include system properties such as themes and user preference, just-in-time property determination mechanisms such as data binding and animations/storyboards, multiple-use templates such as resources and styles, or values known through parent-child relationships with other elements in the element tree. In addition, a dependency property can be implemented to provide self-contained validation, default values, callbacks that monitor changes to other properties, and a system that can coerce property values based on potentially runtime information. Derived classes can also change some specific characteristics of an existing property by overriding dependency property metadata, rather than overriding the actual implementation of existing properties or creating new properties.

5. Platform Adoption

Name a Microsoft platform. Xbox? Windows Phone? Windows Embedded? Windows Desktop? Windows Microsoft Design Style? Silverlight? Every one has something in common: XAML. Some platforms support other UI technologies, but XAML is the common denominator.

XAML has a strategic value to developers and enterprises alike because the developed skillset is reusable across the Microsoft stack. From WPF to Silverlight to Microsoft Design Style, XAML is pervasive. One reason XAML is great is because of its wide platform adoption.

6. Object Oriented Programming

HTML5 and JavaScript are powerful. Granted. But unit testing, inheritance, polymorphism, architectural reuse, and pervasive design patters are enabled by object oriented languages like C++, C#, and Visual Basic. If it is up to me, and it is, I want OOP so my projects are logical, testable, and scalable.

7. State

XAML applications are persistent (stateful). It means static methods and properties work. It means in memory references work. And, it means MVVM works. XAML applications maintain state which helps developers maintain sanity – and  prevents the many hacks like state stores. More.

Gg430869.C1C498204EFDB6E753EC8164CD18F023(en-us,PandP.40).png

8. Expression Blend

Since WPF, XAML designers and developers have enjoyed Expression Blend (part of the Expression Suite of tools). Expression Blend provides a visual and designer interface to accomplish complex actions and interactions in XAML UIs. Nothing compares.

Many developers have avoided Blend because of the initial learning curve. The reality is, whatever can be accomplished in Blend could also be accomplished in Visual Studio. Similarly, whatever could be accomplished in Visual Studio could be accomplished in Notepad. Blend is worth it.

9. Debugging

C# developers have long used the debugging features in Visual Studio. Just set a breakpoint a build. Now with Intellitrace, there’s even more ways developers can debug an application. But XAML developers (evident in Silverlight 5) have the option to debug bindings right in the XAML.

But it’s not just that. Only robust languages like C# give you full intellisense, symbolic refactoring, incredible code analysis, and complexity metrics. One of the reasons I choose XAML is because I choose C#. And I choose C# because it has everything.

10. Vectors, Vectors, Vectors

Vector and Bitmap Differences

A key benefit of WPF (the first XAML) over WinForms was that WPF was a vector-based rendering engine. It could leverage GPU acceleration and scale indefinitely. All XAML is vector-based, can leverage GPU acceleration and scale indefinitely. Boom!

MSDN: WPF uses vector graphics as its rendering data format. Vector graphics—which include Scalable Vector Graphics (SVG), Windows metafiles (.wmf), and TrueType fonts—store rendering data and transmit it as a list of instructions that describe how to recreate an image using graphics primitives… One of the key benefits of vector graphics is the ability to scale to any size and resolution.

11. Attached Properties

Dependency Properties made it in my first list. But I was remiss to not mention Attached Properties. Like Dependency Properties, they are property bags and can be bound and animated. But, unlike Dependency Properties, Attached Properties can be “attached” to controls (any control) without the control’s knowledge.

Attached Properties let developers extend control behavior or store information. Canvas.* and Grid.* are familiar attached properties. Literally, they extend controls to meet the developer’s needs, easily.

Hint: there is a built-in Visual Studio C# snippet (propa) that creates the basic structure of an attached property for you.

imageMSDN: One scenario that calls for the creation of an attached property is to enable an object to specify a unique value for a property that is defined in a different class object model. The defining class can read this value at run time after the various objects are created in relationships in an object tree.

Remember the pain

Native and third party controls deliver 99% of what your applications needs. With attached properties you extend behaviors without work-around or non-standard implementations. Problem solved.

12. Control Templates

Control templates remind me of OuterHtml but without losing the functionality of the element. XAML developers, using Control Templates, turn controls (visually) into anything without losing its underlying behaviors. It’s like a Transformer (the good kind!).

As a result, we see scroll bars looking like candles, radio buttons like chilies, and textboxes like televisions. Textboxes can be Images, Grids can be Radio Buttons, whatever you need! The real advantage is when you want to “tweak” a control by inheriting its template and adding some extra something your application needs. If you can dream it, XAML can do it.

imageMSDN: In the XAML framework for Microsoft design style apps, you create a control template when you want to customize a control’s visual structure and visual behavior. Controls have many properties, such as Background, Foreground, and FontFamily, that you can set to specify different aspects of the control’s appearance. But the changes that you can make by setting these properties are limited. You can use the ControlTemplate class to create a template that provides additional customization. Here we show you how to create a ControlTemplate to customize the appearance of a CheckBox control.

Remember the pain

Native and third party controls provide significant benefit to your project but do not match the overall look and feel. With control templates, you can “skin” controls to fit your model. Problem solved.

13. Data Template Selectors

Data templates are fundamentally your ability to show data. If you are repeating data in some type of items control or individually in a content control, it’s the data template that defines how the data appears. Just set it or select it.

imageMSDN: You can place a DataTemplate as the direct child of an ItemTemplate property element in XAML. You can also define a DataTemplate as a resource and then reference the resource as the value of the ItemTemplate property. The XAML usage that defines the content for creating a data template is not exposed as a settable property. It is special behavior built into the XAML processing of a DataTemplate object element.

Even cooler? Let’s say you have a list of mixed data types – like dogs, cats, and birds. You may have a data template for each. It’s the data template selector that allows you to use ANY logic you want to determine which data template is used for a record. Go selectors!

imageMSDN: The base DataTemplateSelector class is not used as an object element in XAML. However, it is a common scenario to derive a custom DataTemplateSelector, map a xmlns prefix for the custom class and its namespace/assembly, and then refer to an instance of the custom class as defined in a Resources block in XAML. This makes it possible to refer to the custom template selector class by x:Key, and use that reference to set the value of properties such as ItemTemplateSelector in XAML templates and particular visual states.

Remember the pain

You show the same data in multiple places in your application. Because data templates can be a shared resource, you don’t have to repeat yourself. Some lists contain a mixture of item types, using data template selectors you can swap the data template before it is applied. Problem solved.

14. Linq & Lambda

To understand Linq & Lambda is to understand what makes them different. Regardless, they have been part of the .Net family since Framework 3.5 (Visual Studio 2008). Although there is a learning curve, developers who use them swear by them for enumerable operations like sorting, filtering, and so much more. There are technical reasons why they improve on traditional techniques. Linq (Language integrated query) has exposed databases, XAML, objects, even custom sources like Twitter to .Net developers with super-easy interoperability.

imageMSDN: LINQ introduces standard, easily-learned patterns for querying and updating data, and the technology can be extended to support potentially any kind of data store. Visual Studio 2008 includes LINQ provider assemblies that enable the use of LINQ with .NET Framework collections, SQL Server databases, ADO.NET Datasets, and XML documents.

Lambda expressions are anonymous methods that build expression trees to accomplish some task. I think Lambdas are *the* sufficient reason for picking XAML, period. What I mean is, the productivity gains, the reduction code, they are all amazing. I could stop here. But I won’t.

imageMSDN: When you use method-based syntax to call the Where method in the Enumerable class (as you do in LINQ to Objects and LINQ to XML) the parameter is a delegate type System.Func<T, TResult>. A lambda expression is the most convenient way to create that delegate. When you call the same method in, for example, the System.Linq.Queryable class (as you do in LINQ to SQL) then the parameter type is an System.Linq.Expressions.Expression<Func> where Func is any Func delegates with up to sixteen input parameters. Again, a lambda expression is just a very concise way to construct that expression tree. The lambdas allow the Where calls to look similar although in fact the type of object created from the lambda is different.

Remember the pain

Working with collections is a common task. You frequently have to filter, bubble sort, and distinct your lists. The work isn’t hard but the code is long and confusing to maintain. With Linq and Lambda the same solutions are just a few characters. Maintenance is easier. problem solved.

15. It’s not standards-based

Anyone noticed the return of browser wars? It frustrates developers and is expensive for companies. Why? Because browser subtleties are not ironed out, they are positioned as differentiators. And so it goes.

This will never end you know. The HTML5 peace & harmony dream is a little naïve and a little stupid. Why? Because everyone wants to make their mark. Everyone wants to make their buck. And everyone sees themselves in a crusader.

The disadvantage to HTML is specification; as noble and as comprehensive as it may be, it will always be incomplete, always in despite, and always speculative. The tides of opinion may prefer one implementation over another, but it will never matter. Non-standard is the density of standards.

XAML, on the other hand, is less like democracy and more a dictatorship. The analogy is bitter but the reality is sweet. There is always a consensus, and it is what it is. It’s like comfort food. There is never wiggle room. Implementation is consistent across platforms.  Period.

Remember the pain

Writing HTML and JavaScript that worked the same on all systems and all browsers meant a lot of extra development and, eventually, the lowest common denominator. Your lines of code exploded. XAML applications are all the same and always look the same. Problem solved.

16. Model view view model (MVVM)

One of the most popular and easy to use design patterns is Model View View Model (MVVM). Believe it or not, MVVM is from XAML! True. Check out this article snippet:

MSDN Mag: In 2005, John Gossman, currently one of the WPF and Silverlight Architects at Microsoft, unveiled the Model-View-ViewModel (MVVM) pattern on his blog. MVVM is identical to Fowler’s Presentation Model, in that both patterns feature an abstraction of a View, which contains a View’s state and behavior. Fowler introduced Presentation Model as a means of creating a UI platform-independent abstraction of a View, whereas Gossman introduced MVVM as a standardized way to leverage core features of WPF to simplify the creation of user interfaces. In that sense, I consider MVVM to be a specialization of the more general PM pattern, tailor-made for the WPF and Silverlight platforms.

It’s easy to love MVVM. It’s appeal explains its popularularity. It’s abstraction and separation of duties is clean and simple. And, it goes with XAML like peanut butter and jelly.

Remember the pain

Adding data to your application used to mean adding complexity. But MVVM is a consistent, simple approach. Now there’s similarity across projects and development teams. Problem solved.

17. Intellectual Property

Intellectual property is a legal term, right? We’re all grown ups here. We know there is no software silver bullet to hide code or logic from prying eyes. Tempt the tech community and it’s game over. We can make it difficult, but that’s it. Let’s not pretend.

So, this is a real problem. You or your company is paying real money to build a real product. Your solution, your approach, your code – it’s all property and it’s all worthwhile and worth money.

If you take your keys with you when you into the mall. If you lock your house when you go on vacation. Any of those, then you understand the value of risk and value. You’ve spent the money and time. Why give it away?

Having said that, we want to make it freaking difficult. 99% of all the IP snoops will stop at the first (maybe second) gate they hit. .Net developers have enjoyed dotfuscator for a long time. It makes .Net code run faster,sure, but also nearly impossible to reflect (reverse-engineer).

Boom. JavaScript has a similar obfuscator, but really is just a minify engine. Minify. That helps. Good for JavaScript, but .Net obfuscation is significant, improves performance, provides error reporting, and so much more. Give me a choice. I choose .Ne obfuscation to protect my software investment.

Techniques to protect IP (oh yeah, these are built in to the obfuscators!) – and makes it obvious why JS minify is more like a toy than real Intellectual Property protection: Symbol renaming, Overload renaming, String encryption, Tamper detection, Flow obfuscation, ILDASM suppression, Reflection suppression, Decompile suppression, Resource encryption, and Assembly encryption.

Remember the pain

Your code is worth time and money and you didn’t spend it to teach everyone else your magic. Using obfuscation, your intellectual property is protected. Problem solved.

18. Service Proxy Generation

When I call a cloud service, data is returned to me. Sometimes it is a string I parse myself, deserializing XML or JSON. I love to use Json2Sharp to save time (check it out!).

The process is easy and fast.  But the bulk of well-designed line-of-business services are SOAP, not REST. For a WSDL-defined service, adding a reference in Visual Studio automatically builds the proxies for to interoperate and leverage client-side, typed classes.

Unless you are paid by the hour (or the line), you will love the code generation in Visual Studio. (called T4 templates). Now, the interoperability is something you can assume. Best of all, updates or changes to service signatures is as simple as a right-click “Update Service Reference”.

imageMSDN: A WCF client consists of a proxy that enables an application to communicate with a WCF service, and an endpoint that matches an endpoint defined for the service. The proxy is generated on the client side in the app.config file and includes information about the types and methods that are exposed by the service. For services that expose multiple endpoints, the client can select the one that best fits its needs, for example, to communicate over HTTP and use Windows Authentication.

Remember the pain

Manually accessing services meant your application was brittle and needlessly complex. Using Visual Studio service proxy generation creates your code for robust interaction. Problem sovled.

19. The Desktop

If you are building a skill, why not unlock every Microsoft platform? XAML does that. Best of all, learning XAML gives you both the ability to write awesome, touch-ready Microsoft design style apps, windows phone apps, and web apps.

But, also use XAML for Windows 8 desktop applications (in WPF); reuse your C# in services, leverage it in web sites. XAML makes the most of your skills – even unlocking the desktop for custom LOB applications.

Remember the pain

Adobe Air and tech like HTML are cool but limit you too much. With the .Net framework and XAML you have the skills to build on every Microsoft platform. Problem solved.

20. A Culture of Design

WPF enabled it, Silverlight made it real, and it continues today through Microsoft design style. Any app, in any tech, must meet the needs of users, the business, and efficiency. That’s custom software’s definition of success. The latter, however, is best handled through User Experience and design.

XAML, more than most, intentionally targets designers to get involved early and often. Its separation of UI and implementation is a huge first step. But, Blend seals the deal. Blend delivers designers tooling  designers specific to UI layout and interactions.

MSDN: Depending on your own role in the development process, you might not interact with XAML much. The degree to which you do interact with XAML files also depends on which development environment you are using, whether you use interactive design environment features such as toolboxes and property editors, and the scope and purpose of your Microsoft design style app. Nevertheless, it is likely that during development of the app, you will be editing a XAML file at the element level using a text or XML editor. Using this info, you can confidently edit XAML in a text or XML representation and maintain the validity of that XAML file’s declarations and purpose when it is consumed by tools, markup compile operations, or the run-time phase of your Microsoft design style app.

And here’s my point. Now that we (Microsoft) have extended Blend to serve HTML developers, too, everyone benefits. I won’t attempt to equate the functionality of Blend for HTML to Blend for XAML, but who’s counting? XAML, however, is steeped in a culture of design. It is the go-to UI for anything cool (think Silverlight & Surface) that Microsoft creates.

Reality check: many software projects don’t benefit from a budget that affords a designer. Or, many projects don’t benefit from a manager who values design. XAML’s culture of design is a self-fulfilling prophesy, a kind of positive peer pressure. Because XAML focuses on UX, XAML projects often reflect this predilection – even without a formal designer. It’s not ideal, but it’s better. Really better.

Remember the pain

Most apps are ugly. Just admit it. And your’s might be part of the problem. XAML enables better design, but also fosters it. Slowly we are seeing better UX. Problem solved.

21. Separation of Concerns

In software engineering separation of concerns has a few different meanings: To some it means scope creep. To others it means maintenance nightmare. To others it means job security. But, to a few, it means encapsulation, components, and testability.

Wiki: In computer science, separation of concerns (SoC) is the process of separating a computer program into distinct features that overlap in functionality as little as possible.

Look, your mother’s cookies are not the reason your are fat. But, they are an enabler that makes it possible. XAML is not the reason for separation of concerns, other technologies allow the same principles with distinct implementations, but the fundamental structure of XAML enables it, too. And when you end up knee deep in SoC, you end up liking it.

Listen, I am not talking about the shallow separation of HTML, CSS, and JavaScript. I am talking about symbolic separation in software. This is Aspect-oriented programming; it partitions code based on duty, vertical domain, or use case. One is a black box of function, one is a black box of activity.

Your architect can choose one over the other based on the latest magazine cover. 😉 Either way, both are important – and show up frequently and rightly in larger projects. And, of course, both are equally enabled by XAML and the underlying OOP code.

Soap box: I am *not* talking about reuse here. Budgets are frequently subjected to developers chasing reusability. But developers rarely accomplish it, fellow developers rarely know about reusable components, and calcification sets in fast – reducing reusability to an expensive pipe dream. Yes, work to eliminate redundant code when possible; but, please, don’t target endless reuse. Just complete your task card and deliver a working product. Be proud of completion, not complexity.  </speech>

Remember the pain

Repeating yourself in software is sometimes okay, but typically just introduces needless maintenance costs. With Seperation of Concerns you get less redundancy. Problem solved.

22. Inline Invocation

XAML isn’t really markup, you know. XAML is a declarative UI referencing CLR objects, not page content, text, or layout. For example, placing a <GridView/> in XAML really is invoking the GridView control. The control then manipulates presentation. Built-in or custom, XAML references controls. This is what makes XAML powerful, but it is also why XAML provides inline invocation.

Consider these classes:

image

Such a structure is common to create a containers with data. When PEOPLE is invoked, data is generated by its constructor. Since we can invoke classes directly in XAML, our PEOPLE constructor runs before we ever debug the app! This gives us real data that really binds in our design surface – executing transitions, bindings, and repeaters inside Visual Studio.

Here’s how we do it:

image

In the code above, we are invoking a new instance of People. That instance is placed in the DataContext property of the Page. But we leverage the “d:” prefix which indicates XAML intended only for design time. As a result of this approach we have design time data that we know wont pollute our runtime experience. (This is an excellent way to implement MVVM with Design-time data)

But XAML also allows us to set properties after our invocation. Imagine the same scenario but without a constructor that creates sample data. We can, instead, create the sample data we need in our XAML directly. This helps us manage the data to suit our Page’s use case.

Like this:

image

In the code above, just like before, we are invoking the People list. But in addition, we are invoking our own Person members of the collection. With every invocation we have the ability to specify property values and use the resulting instances as our design time data context. I love it. You will, too.

Remember the pain

Design time data let’s you manipulate our UI with a real context. Otherwise, you have to run everytime you want to see a chance. With inline invocation design data is a snap. Problem solved.

23. Drawing Objects

Path illustrationNo need for canvas. No need for SVG containers. Just stinkin’ draw – anywhere. That’s right, and the drawing capabilities in XAML are (and have been) flexible and vector-based.

MSDN: The Path class enables you to draw curves and complex shapes. These curves and shapes are described using Geometry objects. To use a Path, you create a Geometry and use it to set the Path object’s Data property.

image

In the code above, you can see the value of a design tool like Blend, no? I know Data could do it, but some of us need tooling. Nonetheless, the data attribute contains the definition for the arc. The rest are styling properties you use to make it look just so.

Line, Ellipse, and Rectangle are all wrappers for the Path element – so common shapes can be easily integrated by XAML developers. XAML can draw any 2/3d shape and leverage any transform to give the perspective or movement (which can leverage animation) you want.

MSDN: Because they derive from UIElement, shape objects can be used inside panels and most controls. The Canvas panel is a particularly good choice for creating complex drawings because it supports absolute positioning of its child objects.

Remember the pain

Not everything in your UI is going to be a rectangle. When you need a custom shape, there’s no need for third party libraries. Complex drawing is part of XAML. Problem solved.

24. Event and Data Triggers

XAML has the Routed Event. Consider this: a Routed Event can raise an event like a button’s click event, but it can also travel upward through the XAML visual tree (called bubbling). This allows containers to register for their children’s events.

MSDN: A routed event is a CLR event that is backed by an instance of the RoutedEvent class and registered with the WPF event system. The RoutedEvent instance obtained from registration is typically retained as a public static readonly field member of the class that registers and thus “owns” the routed event.

Here’s how Triggers look:

image

But even better than Routed Events are Routed Event Triggers. On XAML controls, developers leverage Routed Event Triggers to listen and react to Routed Events. Routed Event Triggers can then start or restart waiting storyboards. In this way, developers can declare a response to user action(s) without code behind. The execution engine builds the implementation.

MSDN: EventTrigger s apply a set of actions when the specified routed event occurs. For example, you may want to use EventTriggers to start a set of animations when the mouse pointer is over a certain user interface (UI) control.

Remember the pain

Interacting with the user is important but not always worth an additional code base. Using Event Triggers, your XAML can declare storyboard interactions directly. Problem solved.

25. Cascading Styles

XAML’s “cascading styles” are so much more than simple CSS classes. Remember in #22 where we discussed how XAML elements actually invoke CLR objects? <Style> is the same. And just like inheritance in Object Oriented Programming is a goliath benefit, Style inheritance is the ultimate!

Aside: I talked bout BasedOn in a previous article

Consider this:

image

In the code above, I am creating two TextBox styles – each of the two (good/green and bad/red) inherit from the base. This allows me to maintain the complexity within the base, then adjustment it in the concrete styles that are based on it.

Unlike CSS, I do not use multiple or nested styles or classes (confusing developers with an invisible priority tree), just the style I want. And every style can have a base or lineage of bases that create rich, themed and skinned interfaces that I can control programatically.

MSDN: There are several ways that styles in WPF can be extended or inherited. Styles can be based on other styles through this property. When you use this property, the new style will inherit the values of the original style that are not explicitly redefined in the new style.

Remember the pain

Themes, skins, and styles are important to create a rich application but can make things complex and confusing. With style inheritence, we control the style tree intuitively. Problem solved.

XAML developers can save time by knowing the deltas between the previous XAML development experience and what to expect in Microsoft design style. 

  1. The binding Mode is not TwoWay by default. OneWay is, even for TextBoxes. That means Mode=TwoWay needs to become something you type by default. Otherwise, you might start thinking that simple binding does not work when it really works just fine.
  2. The ImageBrush’s TileMode is missing because TileBrush is missing. The RadialGradientBrush and VisualBrush are missing. You can burn hours looking for these (like I did). As a result, you will be using more images than you typically would in your designs.
  3. There is no ability to PriorityBinding or MultiBinding in Microsoft design style(this was also true in SL). Combine that with missing StringFormat and TargetNullValue, though, and you will be using more converters than you might otherwise. Leverage MVVM for formatting, too.
  4. Like Silverlight, Loaded is the only RoutedEvent supported in EventTriggers. The error when trying any other event is confusing. In the end, it means most of your animation will be handled through VisualStates more than animating the style.
  5. At least in the Release Candidate, the editor reports a WindowsUIXamlBindingWrapper exception when attempting to bind anything to a control’s DataContext. This is only a design-time issue; You can continue developing – but with lots of blue underlines.
  6. It is not possible to bind the ColumnSpan or RowSpan of a DataGridViewItem to any value inside the DataGrid’s ItemTemplate or DataContext for to support VariableSizedWrapGrid. Instead, you must inherit from GridView, overriding PrepareContainerForItemOverride(). Note: I will blog about this one soon because it is complicated.
  7. To animate properties that cannot be hardware accelerated, you must set EnableDependentAnimation which explicitly allows this, and acknowledges the resulting animation is CPU-based. Otherwise, your animations are ignored (no error).
  8. There is a new method argument property called CallerMemberNameAttribute (you might not have even known that arguments could have their own attributes) which sniffs out the calling method or property’s name. This is useful to implement INotifyPropertyChanged. Cool.
  9. To implement a Flyout you need to use the Popup control
  10. To implement a Flyout/Popup you need to write the “placement” logic
  11. RequestedTheme in App.xaml cannot be set per-page
  12. Search for Callisto if you are looking for a date picker
  13. You cannot debug bindings like in SL5 (commonly asked)
  14. Color Picker is not available with the default controls provided in Windows Store Apps project.

Internals (Deep dive) of Metro Application calling WinRT Component DLL

We have created a C++ XAML application that consumes the WinRT C++ DLL in part 1

we have seen the compiler generated components when we compile a WinRT Component DLL.  Part2  discusses how the C# application interacts with the C++ WinRT component.

We have seen the packaging and installation process that happens in the background during building and deploying of the applications here Under the hood Part 3 : WinRT, Windows 8, C++, C#.NET, Metro, WinRT Component DLL

We have seen the C++ XAML application calling the C++ WinRT Component DLL here Under the hood Part 4 : C++ WinRT Component DLL & C++ XAML application – WinRT, Windows 8, C++, Metro

Part5 discusses developing JavaScript application that consumes WinRT Component DLL

Lets dig deeper into how the C++ Application makes  a call across the WinRT Application Binary Interface to access the class methods inside the WinRT DLL. The slide in fig 1 is taken from the build conference which shows the internals of the method calls. We will examine the ABI and how C++ compiler extensions help reference that ABI without exposing the internal details of dealing with COM interfaces and COM activation.

Download the source code from here.

image

Fig 1: Slide showing the flow of the method calls across the boundaries.

A WinRT component implements the IInspectable interface, which is derived from IUnknown. IInspectable is used by the dynamic language bindings from JavaScript. Given a reference to a WinRT component, the JavaScript interpreter can call the IInspectable::GetRuntimeClassName method and obtain the fully-qualified class name of the WinRT component. Using the namespace name the interpreter can ask Windows to load the metadata file (.winmd) describing the component, and from the metadata determine how to use the interfaces implemented by the component.

When WinRT components are accessed from C++ or from .NET languages, there is no need for the IInspectable interface – IUnknown::QueryInterface suffices for all intents and purposes. In fact, .NET “interop” with WinRT relies on simple COM interop – an RCW created by the CLR manages the lifetime of the underlying WinRT component. For C++ language bindings, the story is somewhat more complicated, and the language extensions come into play.

The left side in Fig 1 is the C++ client application code which calls the method in right side WinRT DLL. So here if the method in C++ DLL throws an exception, it should be caught by the C++ application. But it’s not a good practice throw exceptions directly across boundaries.

The left side call (C++ Client App: Consumer) to Add() method causes the compiler to create an inline native to COM wrapper method. Also, on the left hand side, COM HRESULTs are converted to exceptions and COM “retval” arguments are converted to return values. The Add() method makes a call to this wrapper method. This inline methods generated will be something like a COM method that we write in COM components. We can see the source code generated by the compiler using some compiler switch options. we have seen the compiler generated components for making the C# application access the C++ WinRT component here Under the hood Part 2 : C++ WinRT Component DLL & C#.NET Metro application.

From the WinMD file, the C++ application knows the WinRT API signature(shown at the top of the slide) and makes the appropriate call across the WinRT ABI.

HRESULT __stdcall Add(Calculator* this, int i, int j, int * result)

//On the LHS Application, the native to COM Wrapper is as follows (Consumer-side stub pseudo-code) . See the last section of this post to see the compiler generated code. 
inline int Add(int i, int j) {
int res;
HRESULT hr = __cli_Add(this, i, j, &res);
if (hr != 0) {

__throw_hr_as_exception(hr); }
return res;
}

On the right hand side too (C++ Component DLL), C++ compiler generates inline functions. Also, WinRT and C++ exceptions are converted to HRESULTs and return values are converted to “retval” arguments. Note that the only HRESULT, which does not represent an exceptional condition, is S_OK (numeric value 0). No more positive HRESULTs (such as S_FALSE) that need to be checked explicitly by the caller.

//On the RHS C++ Component, COM to Native Wrapper stub pseudo-code is as follows:
HRESULT __stdcall ___cli_Add(Calculator* calc,
int i, int j, int* result) {
try { *result = calc->Add(i, j); }
catch(Platform::Exception^ e) { return e->HResult; }
return S_OK;
}

See the last section of this post to see the compiler generated code.

By the way, the inline wrappers can be called directly, bypassing the C++ language extensions.

image

The C++ language extensions (enabled by the /ZW switch) map WinRT to standard C++ patterns like constructors, destructors, class methods, and exceptions. For example, the language extensions hide the COM-style activation (RoActivateInstance) behind a constructor call (albeit with the ref new keyword), and hide reference counting (IUnknown::AddRef and Release) by automatically managing references. The syntax of these extensions is very similar to C++/CLI

Code Snippet
    CalculatorSample^ calcobj = ref new  CalculatorSample();
    txtAddResult->Text = calcobj->Add(10,20).ToString();

In the above code snippet, you can see we created the object of CalculatorSample class which is present in WinRT C++ Component using ref new. If you know COM, this is something like cocreateinstance() but its more than that. For now, use ref new to create objects of WinRT classes.

Let us see how to skip to exception wrapper and directly calling the Add() method present in WinRT Component. Every function in the class has a low level equivalent inside the class and currently it is prefixed with __cli_ and it takes the output as last parameter. So using ToString() on an integer. So this is another way of calling the methods inside the WinRT components. If we need HResult, we need reference to windows.h. For that include Windows.h in pch.h file as shown below.

Code Snippet
//
// pch.h
// Header for standard system include files.
//

#pragma once

#include <Windows.h>
#include "App.xaml.h"

The complete code to call the WinRT component method is as follows.

Code Snippet
MainPage::MainPage()
{
    InitializeComponent();

    CalculatorSample^ calcobj = ref new  CalculatorSample();
    //txtAddResult->Text = calcobj->Add(10,20).ToString();

    // declare a stack variable to hold the value of the result
    int result;
    //call into  calc object low level __cli_Add() but no intellisense in this preview
    HRESULT hr = calcobj->__cli_Add(10,20,&result);

    //typedef HRESULT (__std

    txtAddResult->Text = result.ToString();
}

 

Another (3rd) way is to use function pointers and call the methods using pointers. Basically, we we can take the calculator^ object, which is a pointer to a pointer to a vtable and reinterpret cast it so that it has a pointer to virtual function, which are vtables. Then we can find out the location of the method we need to call using some compiler switches which I will show below. For the Add function, we are going to specifically pick the sixth function of that and call into it. In the class layout mentioned below, I highlighted the member at 6th location. reinterpret_cast takes the calcobj ^ and cast it to a pointer to a pointer, that’s it. This is how the functions inside the components are called internally at a low level.

Code Snippet
MainPage::MainPage()
{
    InitializeComponent();

    CalculatorSample^ calcobj = ref new  CalculatorSample();
    //txtAddResult->Text = calcobj->Add(10,20).ToString();

    // declare a stack variable to hold the value of the result
    int result;
    //call into  calc object low level __cli_Add() but no intellisense in this preview
    //HRESULT hr = calcobj->__cli_Add(10,20,&result);

    //create a c function that actually represent an ABI call we will be making
    //to add function which takes this pointer, 2 input parameters and an out parameter.
    typedef HRESULT (__stdcall* AddFunc_t) (CalculatorSample^ calc, int i, int j, int * result);
    //now we can take the calculator^ object, which is a pointer to a pointer to a vtable
    //and reinterpret cast it so that it can say ok now i have a pointer of  virtual function
    //which are vtables and i am going to specifically pick the sixth function of that and call into it.
    //reinterpret_cast takes the calcobj ^ and cast it to a pointer to a pointer
    AddFunc_t* addFunc = *reinterpret_cast<AddFunc_t**>(calcobj);
    addFunc[6](calcobj,10,20, &result);

    txtAddResult->Text = result.ToString();
}

Basically a hat is a pointer to a pointer to an array of function pointers, which is Pointer to vptr to vtable. Hat (^) provides automatic reference counting.

To find out the class layout, use the /d1reportSingleClassLayout<class name> compiler switch option. Right click on the WinRTComponent.cpp file in C++ WinRT Component DLL project and select Command Line which is under C/C++. In the Additional Options, mention /d1reportSingleClassLayoutCalculatorSample, click ok and compile the project. See the output window for the magic. There is also another option to see all classes layout by using the option /d1reportAllClassLayout.

image

 

1>—— Rebuild All started: Project: CppWinRTComponentDll, Configuration: Debug Win32 ——
pch.cpp
WinRTComponent.cpp
class __ICalculatorSamplePublicNonVirtuals    size(4):
    +—
    | +— (base class Object)
0    | | {vfptr}
    | +—
    +—

__ICalculatorSamplePublicNonVirtuals::$vftable@:
    | &__ICalculatorSamplePublicNonVirtuals_meta
    |  0
0    | &Object::__cli_QueryInterface
1    | &Object::__cli_AddRef
2    | &Object::__cli_Release
3    | &Object::__cli_GetIids
4    | &Object::__cli_GetRuntimeClassName
5    | &Object::__cli_GetTrustLevel
6    | &__ICalculatorSamplePublicNonVirtuals::__cli_Add
7    | &__ICalculatorSamplePublicNonVirtuals::Add

__ICalculatorSamplePublicNonVirtuals::Add this adjustor: 0
__ICalculatorSamplePublicNonVirtuals::__cli_Add this adjustor: 0

class __CalculatorSampleActivationFactory    size(12):
    +—
    | +— (base class IActivationFactory)
    | | +— (base class Object)
0    | | | {vfptr}
    | | +—
    | +—
    | +— (base class Object)
4    | | {vfptr}
    | +—
8    | __cli_MultiThreadedRefCount __cli_refcount
    +—

__CalculatorSampleActivationFactory::$vftable@Object@:
    | -4
0    | &thunk: this-=4; goto __CalculatorSampleActivationFactory::__cli_QueryInterface
1    | &thunk: this-=4; goto __CalculatorSampleActivationFactory::__cli_AddRef
2    | &thunk: this-=4; goto __CalculatorSampleActivationFactory::__cli_Release
3    | &thunk: this-=4; goto __CalculatorSampleActivationFactory::__cli_GetIids
4    | &thunk: this-=4; goto __CalculatorSampleActivationFactory::__cli_GetRuntimeClassName
5    | &thunk: this-=4; goto __CalculatorSampleActivationFactory::__cli_GetTrustLevel

__CalculatorSampleActivationFactory::$vftable@IActivationFactory@:
    | &__CalculatorSampleActivationFactory_meta
    |  0
0    | &__CalculatorSampleActivationFactory::__cli_QueryInterface
1    | &__CalculatorSampleActivationFactory::__cli_AddRef
2    | &__CalculatorSampleActivationFactory::__cli_Release
3    | &__CalculatorSampleActivationFactory::__cli_GetIids
4    | &__CalculatorSampleActivationFactory::__cli_GetRuntimeClassName
5    | &__CalculatorSampleActivationFactory::__cli_GetTrustLevel
6    | &__CalculatorSampleActivationFactory::__cli_Platform_IActivationFactory____cli_ActivateInstance
7    | &__CalculatorSampleActivationFactory::ActivateInstance

__CalculatorSampleActivationFactory::ActivateInstance this adjustor: 0
__CalculatorSampleActivationFactory::__cli_QueryInterface this adjustor: 0
__CalculatorSampleActivationFactory::__cli_AddRef this adjustor: 0
__CalculatorSampleActivationFactory::__cli_Release this adjustor: 0
__CalculatorSampleActivationFactory::__cli_GetIids this adjustor: 0
__CalculatorSampleActivationFactory::__cli_GetRuntimeClassName this adjustor: 0
__CalculatorSampleActivationFactory::__cli_GetTrustLevel this adjustor: 0
__CalculatorSampleActivationFactory::__cli_Platform_IActivationFactory____cli_ActivateInstance this adjustor: 0

class CalculatorSample    size(12):
    +—
    | +— (base class __ICalculatorSamplePublicNonVirtuals)
    | | +— (base class Object)
0    | | | {vfptr}
    | | +—
    | +—
    | +— (base class Object)
4    | | {vfptr}
    | +—
8    | __cli_MultiThreadedRefCount __cli_refcount
    +—

CalculatorSample::$vftable@__ICalculatorSamplePublicNonVirtuals@:
    | &CalculatorSample_meta
    |  0
0    | &CalculatorSample::__cli_QueryInterface
1    | &CalculatorSample::__cli_AddRef
2    | &CalculatorSample::__cli_Release
3    | &CalculatorSample::__cli_GetIids
4    | &CalculatorSample::__cli_GetRuntimeClassName
5    | &CalculatorSample::__cli_GetTrustLevel
6    | &CalculatorSample::

__cli_CppWinRTComponentDll___ICalculatorSamplePublicNonVirtuals____cli_Add
7    | &CalculatorSample::Add

CalculatorSample::$vftable@Object@:
    | -4
0    | &thunk: this-=4; goto CalculatorSample::__cli_QueryInterface
1    | &thunk: this-=4; goto CalculatorSample::__cli_AddRef
2    | &thunk: this-=4; goto CalculatorSample::__cli_Release
3    | &thunk: this-=4; goto CalculatorSample::__cli_GetIids
4    | &thunk: this-=4; goto CalculatorSample::__cli_GetRuntimeClassName
5    | &thunk: this-=4; goto CalculatorSample::__cli_GetTrustLevel

CalculatorSample::Add this adjustor: 0
CalculatorSample::__cli_QueryInterface this adjustor: 0
CalculatorSample::__cli_AddRef this adjustor: 0
CalculatorSample::__cli_Release this adjustor: 0
CalculatorSample::__cli_GetIids this adjustor: 0
CalculatorSample::__cli_GetRuntimeClassName this adjustor: 0
CalculatorSample::__cli_GetTrustLevel this adjustor: 0
CalculatorSample::__cli_CppWinRTComponentDll___ICalculatorSamplePublicNonVirtuals____cli_Add this adjustor: 0

Analyzing the layout:

Every WinRT object is laid out in the following way. The first 3 methods in the Vtable are from IUnknown and the next 3 interfaces methods are there for dynamic languages. The important one is GetRuntimeClassName and it allows JavaScript to call into .net  obtain the fully-qualified class name of the WinRT component. When JavaScript calls GetRuntimeClassName, it returns  CppWinRTComponentDll. CalculatorSample. JavaScript then goes and finds out which WinMD file in the system has the classname CppWinRTComponentDll.CalculatorSample. so Windows 8 will inform that it is inside CppWinRTComponentDll.DLL. It then loads the WinMD file of CppWinRTComponentDll.DLL and calls the Add function inside it. In C++, we don’t use these methods as we can directly interact with the class. It doesn’t do dynamic dispatch.

0 | &CalculatorSample::__cli_QueryInterface
1 | &CalculatorSample::__cli_AddRef
2 | &CalculatorSample::__cli_Release

3 | &CalculatorSample::__cli_GetIids
4 | &CalculatorSample::__cli_GetRuntimeClassName
5 | &CalculatorSample::__cli_GetTrustLevel

6 | &CalculatorSample::

__cli_CppWinRTComponentDll___ICalculatorSamplePublicNonVirtuals____cli_Add

 

Coming to the calculator class, you notice CalculatorSample is of size 12. The first vprt we have is ICalculatorSamplePublicNonVirtuals and then we have vprt to Object and then the ref count.

class CalculatorSample size(12):
+—
| +— (base class __ICalculatorSamplePublicNonVirtuals)
| | +— (base class Object)
0 | | | {vfptr}
| | +—
| +—
| +— (base class Object)
4 | | {vfptr}
| +—
8 | __cli_MultiThreadedRefCount __cli_refcount
+—

If we analyze the first vptr, it points to ICalculatorSamplePublicNonVirtuals. The layout of the interface is as follows. The first 3 methods are for IUnknown and the other 3 are IInspectable. Notice 6 and 7 are referencing the Add method we wrote in the DLL. There are here for a reason. No 7 is to support compile time inheritance. The C++ can directly call into C++.

CalculatorSample::$vftable@__ICalculatorSamplePublicNonVirtuals@:
| &CalculatorSample_meta
| 0
0 | &CalculatorSample::__cli_QueryInterface
1 | &CalculatorSample::__cli_AddRef
2 | &CalculatorSample::__cli_Release
3 | &CalculatorSample::__cli_GetIids
4 | &CalculatorSample::__cli_GetRuntimeClassName
5 | &CalculatorSample::__cli_GetTrustLevel
6 | &CalculatorSample::__cli_CppWinRTComponentDll___ICalculatorSamplePublicNonVirtuals____cli_Add
7 | &CalculatorSample::Add

To understand more, let us use the compiler option. right click on WinRTComponent.cpp and add /d1ZWtokens as shown below and compile the WinRTComponent.cpp class.

image

In the output window, search for __cli_CppWinRTComponentDll___ICalculatorSamplePublicNonVirtuals____cli_Add and see the inline code generated by the compiler. This gives us a better understanding of the inner workings of calling the WinRT components.

 

1>—— Build started: Project: CppWinRTComponentDll, Configuration: Debug Win32 ——
1>  WinRTComponent.cpp
1>  Declaring Member 2: __ICalculatorSamplePublicNonVirtuals::Add (int __cdecl CppWinRTComponentDll::__ICalculatorSamplePublicNonVirtuals::Add(int,int)). [isVirtual=1 isPure=0 isStatic=0]
1> 
1>  Declaring Member 2: __ICalculatorSamplePublicNonVirtuals::__cli_Add (long __stdcall CppWinRTComponentDll::__ICalculatorSamplePublicNonVirtuals::__cli_Add(int,int,int *)). [isVirtual=1 isPure=1 isStatic=0]
1> 
1>  Declaring Member 4a: CalculatorSample::__cli_refcount
1> 
1>  Declaring Member 2: CalculatorSample::__cli_QueryInterface (long __stdcall CppWinRTComponentDll::CalculatorSample::__cli_QueryInterface(class Platform::Guid %,void **)). [isVirtual=0 isPure=0 isStatic=0]
1> 
1>  Declaring Member 2: CalculatorSample::__cli_AddRef (unsigned long __stdcall CppWinRTComponentDll::CalculatorSample::__cli_AddRef(void)). [isVirtual=0 isPure=0 isStatic=0]
1> 
1>  Declaring Member 2: CalculatorSample::__cli_Release (unsigned long __stdcall CppWinRTComponentDll::CalculatorSample::__cli_Release(void)). [isVirtual=0 isPure=0 isStatic=0]
1> 
1>  Declaring Member 2: CalculatorSample::__cli_GetIids (long __stdcall CppWinRTComponentDll::CalculatorSample::__cli_GetIids(unsigned long *,class Platform::Guid **)). [isVirtual=0 isPure=0 isStatic=0]
1> 
1>  Declaring Member 2: CalculatorSample::__cli_GetRuntimeClassName (long __stdcall CppWinRTComponentDll::CalculatorSample::__cli_GetRuntimeClassName(struct __cli_HSTRING__ **)). [isVirtual=0 isPure=0 isStatic=0]
1> 
1>  Declaring Member 2: CalculatorSample::__cli_GetTrustLevel (long __stdcall CppWinRTComponentDll::CalculatorSample::__cli_GetTrustLevel(enum __cli_TrustLevel *)). [isVirtual=0 isPure=0 isStatic=0]
1> 
1>  Declaring Member 2: CalculatorSample::__cli_CppWinRTComponentDll___ICalculatorSamplePublicNonVirtuals____cli_Add (long __stdcall CppWinRTComponentDll::CalculatorSample::__cli_CppWinRTComponentDll___ICalculatorSamplePublicNonVirtuals____cli_Add(int,int,int *)=long __stdcall CppWinRTComponentDll::__ICalculatorSamplePublicNonVirtuals::__cli_Add(int,int,int *)). [isVirtual=1 isPure=0 isStatic=0]
1> 
1>  Declaring Member 2: IActivationFactory::__cli_ActivateInstance (long __stdcall Platform::IActivationFactory::__cli_ActivateInstance(class Platform::Object ^*)). [isVirtual=1 isPure=1 isStatic=0]
1> 
1>  Declaring Member 2: __CalculatorSampleActivationFactory::ActivateInstance (class Platform::Object ^__thiscall CppWinRTComponentDll::__CalculatorSampleActivationFactory::ActivateInstance(void)). [isVirtual=1 isPure=0 isStatic=0]
1> 
1>  Declaring Member 2: __CalculatorSampleActivationFactory::CreateFactory (long __stdcall CppWinRTComponentDll::__CalculatorSampleActivationFactory::CreateFactory(unsigned int *,struct __cli___classObjectEntry *,class Platform::Guid %,struct __cli_IUnknown **)). [isVirtual=0 isPure=0 isStatic=1]
1> 
1>  Declaring Member 2: __CalculatorSampleActivationFactory::GetTargetClassName (const wchar_t *__stdcall CppWinRTComponentDll::__CalculatorSampleActivationFactory::GetTargetClassName(void)). [isVirtual=0 isPure=0 isStatic=1]
1> 
1>  Declaring Member 4a: __CalculatorSampleActivationFactory::__cli_refcount
1> 
1>  Declaring Member 2: __CalculatorSampleActivationFactory::__cli_QueryInterface (long __stdcall CppWinRTComponentDll::__CalculatorSampleActivationFactory::__cli_QueryInterface(class Platform::Guid %,void **)). [isVirtual=0 isPure=0 isStatic=0]
1> 
1>  Declaring Member 2: __CalculatorSampleActivationFactory::__cli_AddRef (unsigned long __stdcall CppWinRTComponentDll::__CalculatorSampleActivationFactory::__cli_AddRef(void)). [isVirtual=0 isPure=0 isStatic=0]
1> 
1>  Declaring Member 2: __CalculatorSampleActivationFactory::__cli_Release (unsigned long __stdcall CppWinRTComponentDll::__CalculatorSampleActivationFactory::__cli_Release(void)). [isVirtual=0 isPure=0 isStatic=0]
1> 
1>  Declaring Member 2: __CalculatorSampleActivationFactory::__cli_GetIids (long __stdcall CppWinRTComponentDll::__CalculatorSampleActivationFactory::__cli_GetIids(unsigned long *,class Platform::Guid **)). [isVirtual=0 isPure=0 isStatic=0]
1> 
1>  Declaring Member 2: __CalculatorSampleActivationFactory::__cli_GetRuntimeClassName (long __stdcall CppWinRTComponentDll::__CalculatorSampleActivationFactory::__cli_GetRuntimeClassName(struct __cli_HSTRING__ **)). [isVirtual=0 isPure=0 isStatic=0]
1> 
1>  Declaring Member 2: __CalculatorSampleActivationFactory::__cli_GetTrustLevel (long __stdcall CppWinRTComponentDll::__CalculatorSampleActivationFactory::__cli_GetTrustLevel(enum __cli_TrustLevel *)). [isVirtual=0 isPure=0 isStatic=0]
1> 
1>  Declaring Member 2: __CalculatorSampleActivationFactory::__cli_Platform_IActivationFactory____cli_ActivateInstance (long __stdcall CppWinRTComponentDll::__CalculatorSampleActivationFactory::__cli_Platform_IActivationFactory____cli_ActivateInstance(class Platform::Object ^*)=long __stdcall Platform::IActivationFactory::__cli_ActivateInstance(class Platform::Object ^*)). [isVirtual=1 isPure=0 isStatic=0]
1> 
1>  inline function header symbol: {ctor}
1> 
1>  {
1> 
1>   
1> 
1>  }
1> 
1>  inline function header symbol: {ctor}
1> 
1>  {
1> 
1>   
1> 
1>  }
1>  <TokenStream>
1> 
1>  namespace CppWinRTComponentDll
1> 
1>  {
1> 
1>   inline int :: CppWinRTComponentDll :: __ICalculatorSamplePublicNonVirtuals :: Add ( int x , int y )
1> 
1>    {
1> 
1>      int __cli_returnValue ;
1> 
1>      long __hr = __cli_Add ( x , y , & __cli_returnValue ) ;
1> 
1>      __cli_WinRTThrowError ( __hr ) ;
1> 
1>      return __cli_returnValue ;
1> 
1>     
1> 
1>    }
1> 
1>   
1> 
1>  }
1>  </TokenStream>
1> 
1>  <TokenStream>
1> 
1>  namespace CppWinRTComponentDll
1> 
1>  {
1> 
1>    inline long __stdcall :: CppWinRTComponentDll :: CalculatorSample :: __cli_CppWinRTComponentDll___ICalculatorSamplePublicNonVirtuals____cli_Add ( int x , int y , int * __cli_returnValue )
1> 
1>    {
1> 
1>      long __hr = 0 ;
1> 
1>      * __cli_returnValue = 0 ;
1> 
1>      try
1> 
1>      {
1> 
1>        auto __tempValue = Add ( x , y ) ;
1> 
1>        * __cli_returnValue = __tempValue ;
1> 
1>       
1> 
1>      }
1> 
1>      catch ( :: Platform :: Exception ^ __param0 )
1> 
1>      {
1> 
1>        __hr = __param0 -> HResult ;
1> 
1>       
1> 
1>      }
1> 
1>      catch ( … )
1> 
1>      {
1> 
1>        __hr = -2147467259 ;
1> 
1>       
1> 
1>      }
1> 
1>      return __hr ;
1> 
1>     
1> 
1>    }
1>
 
1>   
1> 
1>  }
1>  </TokenStream>
1> 
1>  <TokenStream>
1> 
1>  namespace CppWinRTComponentDll
1> 
1>  {
1> 
1>    long :: CppWinRTComponentDll :: CalculatorSample :: __cli_QueryInterface ( class Platform::Guid % __param0 , void ** __param1 )
1> 
1>    {
1> 
1>      if ( __param0 . Equals ( __uuidof ( __cli_IUnknown ) ) || __param0 . Equals ( __uuidof ( __cli_IInspectable ) ) || __param0 . Equals ( __uuidof ( struct CppWinRTComponentDll::__ICalculatorSamplePublicNonVirtuals ^ ) ) )
1> 
1>      {
1> 
1>        * __param1 = reinterpret_cast < void * > ( static_cast < struct CppWinRTComponentDll::__ICalculatorSamplePublicNonVirtuals ^ > ( this ) ) ;
1> 
1>        __cli_refcount . Increment ( ) ;
1> 
1>        return 0 ;
1> 
1>       
1> 
1>      }
1> 
1>      return -2147467262 ;
1> 
1>     
1> 
1>    }
1> 
1>    unsigned long :: CppWinRTComponentDll :: CalculatorSample :: __cli_AddRef ( )
1> 
1>    {
1> 
1>      long __cli_returnValue = __cli_refcount . Increment ( ) ;
1> 
1>      return ( unsigned long ) __cli_returnValue ;
1> 
1>     
1> 
1>    }
1> 
1>    unsigned long :: CppWinRTComponentDll :: CalculatorSample :: __cli_Release ( )
1> 
1>    {
1> 
1>      long __cli_returnValue = __cli_refcount . Decrement ( ) ;
1> 
1>      if ( ! __cli_returnValue )
1> 
1>      {
1> 
1>        delete this ;
1> 
1>        :: Platform :: Heap :: Free ( reinterpret_cast < void * > ( this ) ) ;
1> 
1>       
1> 
1>      }
1> 
1>      return ( unsigned long ) __cli_returnValue ;
1> 
1>     
1> 
1>    }
1> 
1>    long :: CppWinRTComponentDll :: CalculatorSample :: __cli_GetIids ( unsigned long * __param0 , class Platform::Guid ** __param1 )
1> 
1>    {
1> 
1>      struct __s_GUID __interfaceList [ ] =
1> 
1>      {
1> 
1>       
1> 
1>        {
1> 
1>          -1302793136 , 5274 , 13110 , 160 , 43 , 249 , 241 , 108 , 73 , 159 , 212
1> 
1>        }
1> 
1>       
1> 
1>      } ;
1> 
1>     
1> 
1>      return __winRT :: __winRTRuntime . __getIids ( 1 , __param0 , __interfaceList , __param1 ) ;
1> 
1>     
1> 
1>    }
1> 
1>    long :: CppWinRTComponentDll :: CalculatorSample :: __cli_GetRuntimeClassName ( struct __cli_HSTRING__ ** __param0 )
1> 
1>    {
1> 
1>      return __winRT :: __winRTRuntime . __windowsCreateString ( ( const wchar_t * ) L"CppWinRTComponentDll.CalculatorSample" , 37 , __param0 ) ;
1> 
1>     
1> 
1>    }
1> 
1>    long :: CppWinRTComponentDll :: CalculatorSample :: __cli_GetTrustLevel ( enum __cli_TrustLevel * __param0 )
1> 
1>    {
1> 
1>      * __param0 = __cli_FullTrust ;
1> 
1>      return 0 ;
1> 
1>     
1> 
1>    }
1> 
1>   
1> 
1>  }
1>  </TokenStream>
1> 
1>  <TokenStream>
1> 
1>  namespace Platform
1> 
1>  {
1> 
1>    inline class Platform::Object ^ :: Platform :: IActivationFactory :: ActivateInstance ( )
1> 
1>    {
1> 
1>      class Platform::Object ^ __cli_returnValue ;
1> 
1>      long __hr = __cli_ActivateInstance ( & __cli_returnValue ) ;
1> 
1>      __cli_WinRTThrowError ( __hr ) ;
1> 
1>      return __cli_returnValue ;
1> 
1>     
1> 
1>    }
1> 
1>   
1> 
1>  }
1>  </TokenStream>
1> 
1>  <TokenStream>
1> 
1>  namespace CppWinRTComponentDll
1> 
1>  {
1> 
1>    inline long __stdcall :: CppWinRTComponentDll :: __CalculatorSampleActivationFactory :: __cli_Platform_IActivationFactory____cli_ActivateInstance ( class Platform::Object ^* __cli_returnValue )
1> 
1>    {
1> 
1>      long __hr = 0 ;
1> 
1>      * __cli_returnValue = nullptr ;
1> 
1>      try
1> 
1>      {
1> 
1>        auto __tempValue = ActivateInstance ( ) ;
1> 
1>        * __cli_returnValue = __tempValue ;
1> 
1>       
1> 
1>      }
1> 
1>      catch ( :: Platform :: Exception ^ __param0 )
1> 
1>      {
1> 
1>        __hr = __param0 -> HResult ;
1> 
1>       
1> 
1>      }
1> 
1>      catch ( … )
1> 
1>      {
1> 
1>        __hr = -2147467259 ;
1> 
1>       
1> 
1>      }
1> 
1>      return __hr ;
1> 
1>     
1> 
1>    }
1> 
1>   
1> 
1>  }
1>  </TokenStream>
1> 
1>  <TokenStream>
1> 
1>  namespace CppWinRTComponentDll
1> 
1>  {
1> 
1>    long :: CppWinRTComponentDll :: __CalculatorSampleActivationFactory :: __cli_QueryInterface ( class Platform::Guid % __param0 , void ** __param1 )
1> 
1>    {
1> 
1>      if ( __param0 . Equals ( __uuidof ( __cli_IUnknown ) ) || __param0 . Equals ( __uuidof ( __cli_IInspectable ) ) || __param0 . Equals ( __uuidof ( struct Platform::IActivationFactory ^ ) ) )
1> 
1>      {
1> 
1>        * __param1 = reinterpret_cast < void * > ( static_cast < struct Platform::IActivationFactory ^ > ( this ) ) ;
1> 
1>        __cli_refcount . Increment ( ) ;
1> 
1>        return 0 ;
1> 
1>       
1> 
1>      }
1> 
1>      return -2147467262 ;
1> 
1>     
1> 
1>    }
1> 
1>    unsigned long :: CppWinRTComponentDll :: __CalculatorSampleActivationFactory :: __cli_AddRef ( )
1> 
1>    {
1> 
1>      long __cli_returnValue = __cli_refcount . Increment ( ) ;
1> 
1>      return ( unsigned long ) __cli_returnValue ;
1> 
1>     
1> 
1>    }
1> 
1>    unsigned long :: CppWinRTComponentDll :: __CalculatorSampleActivationFactory :: __cli_Release ( )
1> 
1>    {
1> 
1>      long __cli_returnValue = __cli_refcount . Decrement ( ) ;
1> 
1>      if ( ! __cli_returnValue )
1> 
1>      {
1> 
1>        delete this ;
1> 
1>        :: Platform :: Heap :: Free ( reinterpret_cast < void * > ( this ) ) ;
1> 
1>       
1> 
1>      }
1> 
1>      return ( unsigned long ) __cli_returnValue ;
1> 
1>     
1> 
1>    }
1> 
1>    long :: CppWinRTComponentDll :: __CalculatorSampleActivationFactory :: __cli_GetIids ( unsigned long * __param0 , class Platform::Guid ** __param1 )
1> 
1>    {
1> 
1>      struct __s_GUID __interfaceList [ ] =
1> 
1>      {
1> 
1>       
1> 
1>        {
1> 
1>          53 , 0 , 0 , 192 , 0 , 0 , 0 , 0 , 0 , 0 , 70
1> 
1>        }
1> 
1>       
1> 
1>      } ;
1> 
1>     
1> 
1>      return __winRT :: __winRTRuntime . __getIids ( 1 , __param0 , __interfaceList , __param1 ) ;
1> 
1>     
1> 
1>    }
1> 
1>    long :: CppWinRTComponentDll :: __CalculatorSampleActivationFactory :: __cli_GetRuntimeClassName ( struct __cli_HSTRING__ ** __param0 )
1> 
1>    {
1> 
1>      return __winRT :: __winRTRuntime . __windowsCreateString ( ( const wchar_t * ) L"CppWinRTComponentDll.__CalculatorSampleActivationFactory" , 56 , __param0 ) ;
1> 
1>     
1> 
1>    }
1> 
1>    long :: CppWinRTComponentDll :: __CalculatorSampleActivationFactory :: __cli_GetTrustLevel ( enum __cli_TrustLevel * __param0 )
1> 
1>    {
1> 
1>      * __param0 = __cli_FullTrust ;
1> 
1>      return 0 ;
1> 
1>     
1> 
1>    }
1> 
1>   
1> 
1>  }
1>  </TokenStream>
1> 
1>  <TokenStream>
1> 
1>  namespace CppWinRTComponentDll
1> 
1>  {
1> 
1>    class Platform::Object ^ :: CppWinRTComponentDll :: __CalculatorSampleActivationFactory :: ActivateInstance ( )
1> 
1>    {
1> 
1>      return gcnew class CppWinRTComponentDll::CalculatorSample ( ) ;
1> 
1>     
1> 
1>    }
1> 
1>   
1> 
1>  }
1>  </TokenStream>
1> 
1>  <TokenStream>
1> 
1>  namespace CppWinRTComponentDll
1> 
1>  {
1> 
1>    long __stdcall :: CppWinRTComponentDll :: __CalculatorSampleActivationFactory :: CreateFactory ( unsigned int * , struct __cli___classObjectEntry * , class Platform::Guid % __param2 , struct __cli_IUnknown ** __param3 )
1> 
1>    {
1> 
1>      class CppWinRTComponentDll::__CalculatorSampleActivationFactory ^ __pActivationFactory = gcnew :: CppWinRTComponentDll :: __CalculatorSampleActivationFactory ( ) ;
1> 
1>      return __pActivationFactory -> __cli_QueryInterface ( __param2 , reinterpret_cast < void ** > ( __param3 ) ) ;
1> 
1>     
1> 
1>    }
1> 
1>    const wchar_t * __stdcall :: CppWinRTComponentDll :: __CalculatorSampleActivationFactory :: GetTargetClassName ( )
1> 
1>    {
1> 
1>      return L"CppWinRTComponentDll.CalculatorSample" ;
1> 
1>     
1> 
1>    }
1> 
1>   
1> 
1>  }
1>  </TokenStream>
1> 
1>  <TokenStream>
1> 
1>  namespace CppWinRTComponentDll
1> 
1>  {
1> 
1>    const struct __cli___classObjectEntry __CalculatorSampleActivationFactory_Registration =
1> 
1>    {
1> 
1>      :: CppWinRTComponentDll :: __CalculatorSampleActivationFactory :: CreateFactory , :: CppWinRTComponentDll :: __CalculatorSampleActivationFactory :: GetTargetClassName , nullptr , & __cli_no_factory_cache , nullptr
1> 
1>    } ;
1> 
1>   
1> 
1>    extern "C" __declspec ( allocate ( "minATL$__r" ) ) __declspec ( selectany ) const :: __cli___classObjectEntry * const CppWinRTComponentDll___CalculatorSampleActivationFactory__Entry = & __CalculatorSampleActivationFactory_Registration ;
1> 
1>   
1> 
1>  }
1>  </TokenStream>
1> 
========== Build: 1 succeeded, 0 failed, 0 up-to-date, 0 skipped ==========

 

The complete code of MainPage.xaml.cpp is as follows.

Code Snippet
//
// MainPage.xaml.cpp
// Implementation of the MainPage.xaml class.
//

#include "pch.h"
#include "MainPage.xaml.h"

using namespace Windows::UI::Xaml;
using namespace Windows::UI::Xaml::Controls;
using namespace Windows::UI::Xaml::Data;
using namespace CPPApplication1;

using namespace CppWinRTComponentDll;

MainPage::MainPage()
{
    InitializeComponent();

    CalculatorSample^ calcobj = ref new  CalculatorSample();
    //txtAddResult->Text = calcobj->Add(10,20).ToString();

    //// declare a stack variable to hold the value of the result
    int result;
    //call into  calc object low level __cli_Add() but no intellisense in this preview
    //HRESULT hr = calcobj->__cli_Add(10,20,&result);

    //create a c function that actually represent an ABI call we will be making
    //to add function which takes this pointer, 2 input parameters and an out parameter.
    typedef HRESULT (__stdcall* AddFunc_t) (CalculatorSample^ calc, int i, int j, int * result);
    //now we can take the calculator^ object, which is a pointer to a pointer to a vtable
    //and reinterpret cast it so that it can say ok now i have a pointer of  virtual function
    //which are vtables and i am going to specifically pick the sixth function of that and call into it.
    //reinterpret_cast takes the calcobj ^ and cast it to a pointer to a pointer
    AddFunc_t* addFunc = *reinterpret_cast<AddFunc_t**>(calcobj);
    addFunc[6](calcobj,10,20, &result);

    ////CalculatorSample^ calcobj = ref new CalculatorSample();
    ////int* vtable_array = (int*)calcobj;
    ////int* icalc_vtable = (int*)vtable_array[0];
    ////int* compute_will_be_fptr = (int*)icalc_vtable[6];
    ////typedef HRESULT (__stdcall *compute_fptr_t)(CalculatorSample^, int, int, int*);
    ////compute_fptr_t compute_fptr = (compute_fptr_t)compute_will_be_fptr;
    ////compute_fptr(calcobj,10,20, &result);

    txtAddResult->Text = result.ToString();
}

MainPage::~MainPage()
{
}

 

Download the source code from here.

"If you limit your choices only to what seems possible or reasonable, you disconnect yourself from what you truly want, and all that is left is a compromise."

WinRT from the eyes of a .NET developer

Following is the compilation of information related to what the .NET developer need to know about WinRT.

This biggest confusion, has been around the use of the .NET Framework across the blue side and green side. The reason for the, as I call it, .NET Metro Profile is because the Metro style apps run in an app container that limits what the application can have access to in order to protect the end user from potentially malicious apps. As such, the Metro Profile is a subset of the .NET Client Profile and simply takes away some of the capabilities that aren’t allowed by the app container for Metro style apps. Developers used to .NET will find accessing the WinRT APIs very intuitive – it works similarly to having an assembly reference and accessing the members of said referenced assembly.

At the lowest level, WinRT is an object model defined on ABI level. It uses COM as a base (so every WinRT object implements IUnknown and does refcounting), and builds from there. It does add quite a lot of new concepts in comparison to COM of old, most of which come directly from .NET – for example, WinRT object model has delegates, and events are done .NET-style (with delegates and add/remove subscriber methods, one per event) rather than the old COM model of event sources and sinks. Of other notable things, WinRT also has parametrized (“generic”) interfaces.

One other big change is that all WinRT components have metadata available for them, just like .NET assemblies. In COM you kinda sorta had that with typelibs, but not every COM component had them. For WinRT, the metadata is contained in .winmd files – look inside “C:\Program Files (x86)\Windows Kits\8.0\Windows Metadata\” in Developer Preview. If you poke around, you’ll see that they are actually CLI assemblies with no code, just metadata tables. You can open them with ILDASM, in fact. Note, this doesn’t mean that WinRT itself is managed – it simply reuses the file format.

Then there are a number of libraries implemented in terms of that object model – defining WinRT interfaces and classes. Again, look at “Windows Metadata” folder mentioned above to see what’s there; or just fire up Object Browser in VS and select “Windows 8.0” in the framework selector, to see what’s covered. There’s a lot there, and it doesn’t deal with UI alone – you also get namespaces such as Windows.Data.Json, or Windows.Graphics.Printing, or Windows.Networking.Sockets.

Then you get several libraries, which are specifically dealing with UI – mostly these would be various namespaces under Windows.UI or Windows.UI.Xaml. A lot of them are very similar to WPF/Silverlight namespaces – e.g. Windows.UI.Xaml.Controls is closely matching System.Windows.Controls; ditto for Windows.UI.Xaml.Documents etc.

Now, .NET has the ability to directly reference WinRT components as if they were .NET assemblies. This works differently from COM Interop – you don’t need any intermediate artifacts such as interop assemblies, you just /r a .winmd file, and all types and their members in its metadata become visible to you as if they were .NET objects. Note that WinRT libraries themselves are fully native (and so native C++ programs that use WinRT do not require CLR at all) – the magic to expose all that stuff as managed is inside the CLR itself, and is fairly low level. If you ildasm a .NET program that references a .winmd, you’ll see that it actually looks like an extern assembly reference – there’s no sleight of hand trickery such as type embedding there.

It’s not a blunt mapping, either – CLR tries to adapt WinRT types to their equivalents, where possible. So e.g. GUIDs, dates and URIs become System.Guid, System.DateTime and System.Uri, respectively; WinRT collection interfaces such as IIterable<T> and IVector<T> become IEnumerable<T> and IList<T>; and so on. This goes both ways – if you have a .NET object that implements IEnumerable<T>, and pass it back to WinRT, it’ll see it as IIterable<T>.

Ultimately, what this means is that your .NET Metro apps get access to a subset of the existing standard .NET libraries, and also to (native) WinRT libraries, some of which – particularly Windows.UI – look very similar to Silverlight, API-wise. You still have XAML to define your UI, and you still deal with the same basic concepts as in Silverlight – data bindings, resources, styles, templates etc. In many cases, it is possible to port a Silverlight app simply by using the new namespaces, and tweaking a few places in code where the API was adjusted.

WinRT itself doesn’t have anything to do with HTML and CSS, and it bears relation to JavaScript only in a sense that it is also exposed there, similar to how it is done for .NET. You don’t need to deal with HTML/CSS/JS when you use WinRT UI libraries in your .NET Metro app (well, I guess, if you really want to, you can host a WebView control…). All your .NET and Silverlight skills remain very much relevant in this programming model.