Extension SDKs in Build Server without installing it!

I have an automatic build server that will compile the source code after each check-in (I am using TFS).

And in my project i use

  • Microsoft.Media.AdaptiveStreamingClient
  • Microsoft.Media.PlayReadyClient
  • Microsoft.PlayerFramework.Xaml.Adaptive
  • Microsoft.PlayerFramework.Xaml

That was installed using a VSI file. And when i need to add a reference i will use:

visual studio extention dialog
Ok, this was easy, but when my build server compile cannot found that references…

The solution is to put the libraries in version control in a “libs” directory. NuGet does this for existing libraries in a \packages directory at the solution-level; it does not yet support Extension SDKs. The good news is that both Visual Studio 11 and MSBuild already support defining additional locations for Extension SDK’s by overriding the SDKReferenceDirectoryRoot variable. The key is to add the override after the <Import> element near the end of the csproj/vbproj file like this:

<Import Project="$(MSBuildExtensionsPath)\Microsoft\WindowsXaml\v11.0\Microsoft.Windows.UI.Xaml.CSharp.targets" />
<PropertyGroup>
  <SDKReferenceDirectoryRoot>$(SolutionDir)\libs;$(SDKReferenceDirectoryRoot)</SDKReferenceDirectoryRoot>
</PropertyGroup>

With that in place, you can then put your Extension SDK files alongside your solution:

\\libs\\Windows\\v8.0\\ExtensionSDKs\\[SDKName]\\[SDKVersion]\\…

Once there, it will be available in the Visual Studio Add References dialog like any other Extension SDK.

Read more in this article:  How To Use Extension SDKs per-project

[PT] Resumo e recursos do evento Windows 8 App Swipe

microsoft_21_janeiro

Eis o resumo de cada uma das sessões apresentadas no evento “App Swipe” a 21 de Janeiro de 2013 no auditório da Microsoft Portugal, bem como os links mais relevantes.

 

09:30 Introduction, Tools and Advertising // Tiago Andrade e Silva, Microsoft Portugal

Resumo: Nesta sessão será apresentado um resumo de ferramentas úteis para quem desenvolve Apps, bem como algumas dicas que não são óbvias de encontrar na documentação. Será também demonstrado como monetizar aplicações recorrendo ao Microsoft Ads SDK.

 

Recursos:

 

10:00 Multilanguage Toolkit // Emanuel Amiguinho, Microsoft Portugal

Resumo: Hoje em dia o alcance das aplicações é maior, logo tem de se ter em conta os targets bem como poder trazer a melhor experiência de utilizador para todos, para isso as apps devem estar em multilanguage.  Nesta sessão irei abordar como utilizar multilinguage toolkit nas aplicações, com o uso resources, privacy policies e outros aspetos necessários a correta implementação, tanto em C# como em Javascript.

 

Recursos:

Código fonte da solução apresentadada na sessão

Download do Multilanguage Toolkit: http://msdn.microsoft.com/en-us/windows/apps/hh848309.aspx

Translating UI Recourses (JS): http://msdn.microsoft.com/en-us/library/windows/apps/hh943060.aspx

Translating UI Recourses (C#): http://msdn.microsoft.com/en-us/library/windows/apps/xaml/Hh965329(v=win.10).aspx

How to use the Multilingual App Toolkit (JS): http://msdn.microsoft.com/en-us/library/windows/apps/jj569303.aspx

How to use the Multilingual App Toolkit (C#): http://msdn.microsoft.com/en-us/library/windows/apps/xaml/JJ572370(v=win.10).aspx

 

10:30 Registo e publicação de Apps na store // Pedro Serrano, Cavedigital

Resumo: O registo na Windows Store é o primeiro passo a dar para fazer chegar uma app ao resto do Mundo. Nesta sessão abordaremos os passos necessários para se registar e publicar uma app na Windows Store, sobrevivendo a tax profiles e outras zonas de desconforto para developers.

Recursos:

Requisitos de certificação na store: http://aka.ms/StoreReq

Como resolver questões de certificação: http://aka.ms/StoreFix

Problemas com a Store? http://aka.ms/StoreSupport

 

11:00 Coffee Break & NiceReader presentation // Filipe Clérigo, Viatecla

Resumo: A grande penetração no mercado de devices digitais, nomeadamente tablets dos vários fabricantes, exige soluções que permitam criar e distribuir informação interativa de forma eficiente. O Nicereder é uma solução completa de publishing digital, desde a criação de conteúdos à distribuição em múltiplas plataformas.

 

Recursos:

Apresentação do produto:

Informação, case studies e vídeo de demonstração

 

11:30 Pagamentos, inapp purchases, trial (time / feature) // Nelson João, Viatecla

Resumo: A monetização é um aspeto crucial de qualquer aplicação de e-commerce. O In-app Commerce no Windows 8 desempenha um papel fundamental na rentabilidade da aplicação.

Desenvolvendo uma aplicação Windows 8 (com XAML / C #) de raiz, vamos demonstrar o uso prático do ambiente de desenvolvimento CurrentAppSimulator e CurrentApp aplicado a alguns exemplos de In-app Commerce, como por exemplo, modo trial e compras in-app.

 

Recursos:

Source Code da App demo utilizada no evento

Trial app and in-app purchase sample

Validação de recibos e restauro de compras:

How to support in-app purchases (Windows)

 

12:00 Identidade em Windows 8 (Live SDK) // Tiago Barbosa, Microsoft Portugal

Resumo: Nesta sessão vou mostrar como integrar uma Windows Store App com o Live SDK. Começando por criar uma Windows Store App a partir do template do Visual Studio 2012 e integrar a mesma com o LiveSDK. Autenticar o utilizador e pedir autorização para aceder à informação do utilizador e ao Skydrive respectivo. Em seguida, vamos fazer a integração dos controlos Signin/Signout no charm de definições do Windows 8. E por fim, alterar a App de modo a que esta receba informação do Skydrive do utilizador.

 

Recursos:

Código fonte da Solução apresentada no evento

Live Connect documentation

Guidelines for the Microsoft account sign-in experience

 

12:30 Consumindo serviços OData em Windows 8 Store Apps // Sara Silva, Zon

Resumo: Esta demo tem como objetivo mostrar os passos necessários para consumir um serviço OData em Windows Store Apps. (C# / XAML)

 

Recursos:

Código fonte da solução apresentada na sessão

WCF Data Services Blog

WCF Data Services

OData 101: Building our first OData-based Windows Store app (Part 1)

OData 101: Building our first OData-based Windows Store app (Part 2)

 

 

14:30 Media Player Framework // Marco Silva, CreateIT

Resumo: As Windows 8 Store Apps são um novo modelo de aplicação disponibilizado com o Windows 8, adaptadas a dispositivos tácteis e tablets. Neste tipo de aplicações, o suporte a experiências ricas de multimédia é requisito especialmente importante para a implementação de aplicações na área de media.

 

Esta sessão apresenta os conceitos base e tecnologias de suporte ao desenvolvimento de aplicações Windows 8 (Store Apps) que integram vídeo e áudio. Será implementada e demonstrada uma aplicação tipo que integra um player de vídeo.

 

Recursos:

Código fonte da solução apresentada na sessão

Building a rich and extensible media platform

Building video application on Windows 8 – things you want to know

Player Framework: an open source component of the Microsoft Media Platform

 

15:00 Bing Maps // Ricardo Pinto, Agap2

Resumo: Introdução às funcionalidades principais providenciadas pelos serviços REST dos Bing Maps, com foco no cálculo de rotas e informação de trânsito.

 

Recursos:

Código fonte da solução apresentada na sessão

Bing Maps SDK for Windows Store apps

Add Bing Maps to a Windows Store app

Bing Maps SDK for Windows Store apps Samples

Bing Maps Portal

 

15:30 Local Storage and caching / Making your app work offline, detecting offline mode, caching sets of data // Ricardo Pinto, Agap2

Resumo: Introdução à API de Storage das aplicações Windows 8, com foco na elaboração de uma camada de serialização e de persistência local de objectos.

 

Recursos:

Código fonte da solução apresentada na sessão

 

16:00 Coffee Break & 3D printing // Francisco Mendes, Bitbox

Resumo: Impressão 3D é sem dúvida a grande novidade que abre um leque muito interessante de possibilidades. Nesta sessão

 

Recursos:

http://www.bitbox.pt

http://www.reprap.org/wiki/RepRap

http://www.3dprinting-r2c2.com/

http://www.thingiverse.com/

http://www.openscad.org/

Nokia 3D Printing Development Kit Announced For Lumia 820

 

16:30 Typescript // Alexandre Marreiros, Innovagency

Resumo: TypeScript is a language for application-scale JavaScript development.

TypeScript is a typed superset of JavaScript that compiles to plain JavaScript.

Any browser. Any host. Any OS. Open Source.

 

Recursos:

Código fonte da solução apresentadada na sessão

http://www.typescriptlang.org/

TypeScript Templates for Windows 8

 

17:00 Azure Mobile Services (Identity, WPS…) // Nuno Silva, Microsoft Portugal

Resumo: As melhores aplicações estão ligadas à cloud. Esta sessão mostra como utilizar os Windows Azure Mobile Services, que de forma simples, permite que aplicações Windows 8, Windows Phone e até iOS possam guardar e ler informação na cloud, autenticar os utilizadores, enviar push notifications e correr lógica server-side. Isto permite construir uma experiência consistente em múltiplas plataformas e dispositivos, sem ser necessário qualquer conhecimento prévio de Azure.

 

Recursos:

Windows Azure Training Kit

A Demo apresentada no evento está incluída no training kit (Demos -> Building Block Services -> Event Buddy)

17:30 Code Sharing (WP+WP8) // Nuno Silva, Microsoft Portugal

Resumo: Esta sessão demonstra diversas técnicas para partilhar/portar código entre aplicações Windows Phone e Windows 8. São usadas técnicas como MVVM, Linked Files, Conditional Compilation e Portable Class Libraries com e sem Dependency Injection.

 

Recursos:

Código fonte da solução apresentadada na sessão

[PT] 35ª Reunião Presencial da Comunidade NetPonto em Lisboa

No dia 26-01-2013 será realizada a 35ª Reunião Presencial da Comunidade NetPonto em Lisboa. Para participar, efectue o registo de acordo com as instruções abaixo.

Agenda

09:45  – Recepção dos participantes
10:00  – Como deixar de fazer “copy and paste” entre Windows Store e Windows Phone AppsSara Silva [MVP]
No desenvolvimento de aplicações para Windows Phone e Windows Store, usando Silverlight ou C#/XAML respetivamente, deparamo-nos com código semelhante, se não igual, e por vezes dá-mos nos conta que durante o desenvolvimento apenas fazemos “copy and paste” entre os projetos das várias plataformas. E que tal deixar de o fazer? Partilhar, reutilizar código, economizar tempo, diminuir o tempo de manutenção, seria interessante? Mas como?Pois é, nesta apresentação a Sara vai falar de Portable Class Libraries e de como poderemos partilhar o código entre várias plataformas de forma a não ter que voltar a fazer “copy and paste” entre projectos!
11:30  – Intervalo
12:00  – Empowering Mobile Apps with Windows Azure Mobile ServicesVirgílio Esteves [MVP]
Estamos claramente na era das aplicações móveis para consumidores em larga escala e com elevados requisitos de performance e rapidez de desenvolvimento. Por cada aplicação que criamos, estamos recorrentemente a desenvolver suporte para as mesmas coisas, sejam elas mecanismos de autenticação, suporte para Push Notifications, armazenamento estruturado de informação, iada iada iada…E se desse para esquecermos isto tudo de uma vez e usar algo que nos simplificasse a vida, acelerasse o desenvolvimento e permitisse suportar várias plataformas e sistemas ao mesmo tempo (Microsoft Account, Facebook, Twitter, Windows 8, Windows Phone 8, iOS…)?!?

“Windows Azure Mobile Services (WAMS) to the rescue!”

13:30  – Painel de Discussão e Sorteio de Prémios
Nota: Ao final da reunião, escolhemos um restaurante próximo e fazemos um almoço em grupo para continuar o convívio e aproximar as pessoas. A participação é opcional.

Registo / Inscrição

Para participar, basta efectuar a inscrição através do site:
http://netponto-lisboa-janeiro-2013.eventbrite.com/A entrada é gratuita.

Qualquer questão / esclarecimento, entre em contacto connosco.


Local

Microsoft Portugal – Auditório
Rua do Fogo de Santelmo, Lote 2.07.02
1990-110 Lisboa
Portugal

Clique para ampliar o mapa.

Developing an End-to-End Windows Store app using C++ and XAML: Hilo

p&p

Patterns & Practices has released Hilo guidance: Developing a Windows Store app using C++ and XAML which is part of the Windows SDK.

Table of contents at a glance

Here are the major topics in this guide. For the full table of contents, see Hilo table of contents.

Consuming Odata Service in Windows Store Apps (Include MVVM Pattern)

Introduction

This demo has the main goal to show the steps that is need to consuming an OData service in Windows Store Apps, and use the MVVM Pattern and has Ioc container for manage the dependencies.

Get the sample here.

Building the Sample

You only need Visual Studio 2012 and Windows 8, both the RTM version.

Description

For concretizate this sample i used the Netflix OData Catalog API (Preview), that can be found where:

For who is starting with OData service in Windows Store Apps i recommend to install the:

WCF Data Services Tools for Windows Store Apps

“The WCF Data Services Tools for Windows Store Apps installer extends the Add Service Reference experience with client-side OData support for Windows Store Apps in Visual Studio 2012.”

Here is the main points:

1. Creating a Blank Project like you can see in the following image:

2. Add Service Reference

3. Analizing the NetflixService

4. The IServiceManager, FakeServiceManager and ServiceManager

4.1. The LoadNewDVDMoviesAsync method

4.2. The LoadTopDVDMoviesAsync method

4.3. The DataServiceContextAsyncExtension

4.4 The model

5. The TitlesViewModel

5.1 The LoadDataAsync method

5.2 The GroupView and ItemView

6. Binding the view model with the view

6.1. ViewModelLocator

6.2. In App.xaml

6.3. In the TitlesPage.xaml

6.4. In the TitlesPage.xaml.cs

6.5. Binding Data

7. The output / running the demo

8. Fiddler


Let’s start:

1. Creating a Blank Project like you can see in the following image:

new project image

Note: I used te name Netflix.ClientApp (Win8) for the project, but i will change the namespace for Netflix.ClientApp and in the future if I need to create the Netflix.ClientApp (WP8,  i can use the same namespace and if need to “linked as” some file i will not have problems with namespaces.

2. Add Service Reference

add reference

add metadata

The service reference that i added is: http://odata.netflix.com/v2/Catalog/

3. Analizing the NetflixService

The result will be:
add reference

Note: Is not required, but you can create a class diagram that will show all classes and its properties, method and events. It helps to understand that was added when you added the service reference.
class diagram
4. The IServiceManager, FakeServiceManager and the ServiceManager

Now the project has the service, and I decided to get the top of the DVD Movies and the new releases of the DVD Movies. With this i will define an interface for my service manager.

Here is the code:

 /// <summary> 
    /// Defines the service manager interface 
    /// </summary> 
    public interface IServiceManager 
    { 
        /// <summary> 
        /// Loads the new dvd movies async. 
        /// </summary> 
        /// <returns> 
        /// Represents an asynchronous operation that return a IEnumerable. 
        /// </returns> 
        Task<IEnumerable> LoadNewDVDMoviesAsync(); 

        /// <summary> 
        /// Loads the top dvd movies async. 
        /// </summary> 
        /// <returns>Represents an asynchronous operation that return a IEnumerable.</returns> 
        Task<IEnumerable> LoadTopDVDMoviesAsync(); 
    }

The fake implementation will be

FakeServiceManager

/// <summary> 
    /// The fake service manager. 
    /// </summary> 
    public class FakeServiceManager : IServiceManager 
    { 
        /// <summary> 
        /// The bitmap soure 
        /// </summary> 
        private readonly BitmapImage _bitmapSoure; 

        /// <summary> 
        /// Initializes a new instance of the <see cref="FakeServiceManager" /> class. 
        /// </summary> 
        public FakeServiceManager() 
        { 
           _bitmapSoure = new BitmapImage(new Uri("ms-appx:///Images/FakeImage.png")); 
        } 

        /// <summary> 
        /// Creates the items. 
        /// </summary> 
        /// <param name="number">The number.</param> 
        /// <returns>the list of mytitles</returns> 
        public IEnumerable CreateItems(int number) 
        { 
            var myTitles = new List<MyTitle>(); 
            for (var i = 0; i < number; i++) 
            { 
                myTitles.Add(new MyTitle 
                        { 
                            Name = string.Concat("Fake Name ", i), 
                            AvailableFrom = DateTime.Now, 
                            Rating = 0, 
                            Image = _bitmapSoure 
                        }); 
            } 

            return myTitles; 
        } 

        /// <summary> 
        /// Loads the new dvd movies async. 
        /// </summary> 
        /// <returns> 
        /// Represents an asynchronous operation that return an IEnumerable. 
        /// </returns> 
        public async Task<IEnumerable> LoadNewDVDMoviesAsync() 
        { 
            return await Task.Run(() => CreateItems(20)); 
        } 

        /// <summary> 
        /// Loads the top dvd movies async. 
        /// </summary> 
        /// <returns> 
        /// Represents an asynchronous operation that return an IEnumerable. 
        /// </returns> 
        public async Task<IEnumerable> LoadTopDVDMoviesAsync() 
        { 
            return await Task.Run(() => CreateItems(20)); 
        } 
    }

The implementation for the real service will be

ServiceManager

public class ServiceManager : IServiceManager 
    { 
        /// <summary> 
        /// The _netflix catalog. 
        /// </summary> 
        private readonly NetflixCatalog _netflixCatalog; 

        /// <summary> 
        /// Initializes a new instance of the <see cref="ServiceManager"/> class. 
        /// </summary> 
        public ServiceManager() 
        { 
            _netflixCatalog = new NetflixCatalog(new Uri("http://odata.netflix.com/v2/Catalog/"), UriKind.Absolute); 
        } 

        /// <summary> 
        /// Loads the new dvd movies async. 
        /// </summary> 
        /// <returns> 
        /// Represents an asynchronous operation that return a IEnumerable. 
        /// </returns> 
        public async Task<IEnumerable> LoadNewDVDMoviesAsync() 
        { 
            var query = ((DataServiceQuery<Title>)_netflixCatalog.Titles.Where(title => title.ReleaseYear >= 2012 
                                                                            && title.Dvd.Available 
                                                                            && title.Type == "Movie") 
                                                                       .OrderByDescending(item => item.Dvd.AvailableFrom) 
                                                                       .Take(30)).Expand(item => item.Genres).Expand(item => item.Directors); 
            var result = await query.ExecuteAsync(); 

            return ConvertToMyTitles(result); 
        } 

        /// <summary> 
        /// Loads the top dvd movies async. 
        /// </summary> 
        /// <returns> 
        /// Represents an asynchronous operation that return a IEnumerable. 
        /// </returns> 
        public async Task<IEnumerable> LoadTopDVDMoviesAsync() 
        { 
            var query = ((DataServiceQuery<Title>)_netflixCatalog.Titles.Where(title => title.ReleaseYear >= 2012 
                                                                                        && title.Dvd.Available 
                                                                                        && title.Type == "Movie") 
                                                                         .OrderByDescending(item => item.AverageRating) 
                                                                         .Take(20)).Expand(item => item.Genres).Expand(item => item.Directors); 
            var result = await query.ExecuteAsync(); 

            return ConvertToMyTitles(result); 
        } 

        /// <summary> 
        /// Converts to my titles. 
        /// </summary> 
        /// <param name="titles">The titles.</param> 
        /// <returns>The my titles list.</returns> 
        private IEnumerable ConvertToMyTitles(IEnumerable<Title> titles) 
        { 
            return 
                titles.Select( 
                    title => 
                    new MyTitle 
                    { 
                        Name = title.Name, 
                        Image = new BitmapImage(new Uri(title.BoxArt.MediumUrl)), 
                        AvailableFrom = title.Dvd.AvailableFrom, 
                        Rating = title.AverageRating 
                    }).ToList(); 
        } 
    }

Here, there are two importante methods:

  • LoadNewDVDMoviesAsync
  • LoadTopDVDMoviesAsync

4.1. The LoadNewDVDMoviesAsync method

First i will create the query that will be used for the service request:

  var query = ((DataServiceQuery<Title>)_netflixCatalog.Titles.Where( 
title => title.ReleaseYear >= 2012 &&  
title.Dvd.Available && 
title.Type == MovieStringValue) 
.OrderByDescending(item => item.Dvd.AvailableFrom) 
.Take(30)) 
.Expand(item => item.Genres) 
.Expand(item => item.Directors);

Here, I want all title that release year is greater than 2012 and DVD is available and type is Movie and i want these title order by data from dvd is available. At the end i only want the first 30 items and i want with Genres and Directors filled.

4.2. The LoadTopDVDMoviesAsync method

In this method the query will be:

var query = ((DataServiceQuery<Title>)_netflixCatalog.Titles.Where( 
title => title.ReleaseYear >= 2012 &&  
title.Dvd.Available && 
 title.Type == MovieStringValue) 
.OrderByDescending(item => item.AverageRating) 
.Take(20)) 
.Expand(item => item.Genres) 
.Expand(item => item.Directors);

Here, I want all title that release year is greater than 2012 and DVD is available and type is Movie and i want these title order by average rating. At the end i only want the first 20 items and i want with Genres and Directors properties filled.

4.3. The DataServiceContextAsyncExtensions

Inside the both methods i will execute the query like this:

var result = await query.ExecuteAsync();

and it will do a call to the server and request the data.

For simplicate the calls i added DataServiceContextAsyncExtension that allow to use the async and await keyworks.

 /// <summary> 
    /// Defines the DataServiceContext Async Extensions 
    /// </summary> 
    public static class DataServiceContextAsyncExtensions 
    { 
        /// <summary> 
        /// Executes the async. 
        /// </summary> 
        /// <typeparam name="TResult">The type of the result.</typeparam> 
        /// <param name="query">The query.</param> 
        /// <returns>the task of the enumerable of the type TResult</returns> 
        public static async Task<IEnumerable<TResult>> ExecuteAsync<TResult>(this DataServiceQuery<TResult> query) 
        { 
            return await Task.Factory.FromAsync<IEnumerable<TResult>>(query.BeginExecute(null, null), query.EndExecute); 
        } 
    }

4.4 The Model

Here is the class diagram:

GroupView is used to group a list of itemview that can have a MyTitle or Title object ( dependes if your view dependents of the service data or not, if yes when there is an update you maybe need to udpate the view and the viewmodel if not, you only need to update the ConvertToMyTitles method in ServiceManager.

Note: This solution is good when you have for example:

Group 1 with a list of A data type elements and a Group 2 with a list of B data type elements.

You only need create a class similar i do with MyTitleItemView or TitleItemView and the binding as easy and only need to define one ItemTemplateSelector that will choose the correct DataTemplate (normally by data type or group when both groups has the same data type).

5. The TilesViewModel

Because I am using the MVVM pattern, I will call theses methods in my view model, i could implement it inside of the view model but i don´t want have dependencies in my view model.

In the view model i will have:

 /// <summary> 
        /// Initializes a new instance of the <see cref="TitlesViewModel"/> class.  
        /// </summary> 
        /// <param name="serviceManager"> 
        /// The service Manager. 
        /// </param> 
        /// <param name="navigationService"> 
        /// The navigation Service. 
        /// </param> 
        public TitlesViewModel(IServiceManager serviceManager, INavigationService navigationService) 
        { 
            IsToShowProgress = true; 
            _serviceManager = serviceManager; 
            _navigationService = navigationService; 
        }

and inside the LoadDataAsync i will have:

public async Task LoadDataAsync() 
        { 
            IsToShowProgress = true; 

            try 
            { 
                var newDVDMovies = _serviceManager.LoadNewDVDMoviesAsync(); 
                var topDVDMovies = _serviceManager.LoadTopDVDMoviesAsync(); 

                await Task.WhenAll(new Task[] { newDVDMovies, topDVDMovies }); 

                if (newDVDMovies.IsCompleted && topDVDMovies.IsCompleted) 
                { 
                    Groups = new List<GroupView> 
                                 { 
                                     ViewModelHelper.GetGroupView(NameDefinitions.TopDVDMoviesId, NameDefinitions.TopDVDMoviesLabel, topDVDMovies.Result), 
                                     ViewModelHelper.GetGroupView(NameDefinitions.NewDVDMoviesId, NameDefinitions.NewDVDMoviesLabel, newDVDMovies.Result) 
                                 }; 
                } 
                else 
                { 
                    ErrorMessage = GetErrorMessage(newDVDMovies, topDVDMovies); 
                } 

                IsToShowProgress = false; 
            } 
            catch (Exception exception) 
            { 
                IsToShowProgress = false; 

                // TODO: Define a better message error for the user 
                ErrorMessage = exception.Message; 
            } 
        }

Here, is important to refer that i will do two service requests in the same time and will wait until the both are finish, this is great because i don´t need to request one by one and the time spent with the request is maximun of the both.

6. Binding the view model with the view

 

6.1. ViewModelLocator

 

This class continas the SimpleIoc for dependecy injection and helps to binding the view model with the view.

/// <summary> 
    /// This class contains static references to all the view models in the 
    /// application and provides an entry point for the bindings. 
    /// </summary> 
    public class ViewModelLocator 
    { 
        /// <summary> 
        /// Initializes a new instance of the ViewModelLocator class. 
        /// </summary> 
        public ViewModelLocator() 
        { 
            ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default); 

            if (!SimpleIoc.Default.IsRegistered<IServiceManager>()) 
            { 
                // For use the fake data do: 
                // SimpleIoc.Default.Register<IServiceManager, FakeServiceManager>(); 
                SimpleIoc.Default.Register<IServiceManager, ServiceManager>(); 
            } 

            SimpleIoc.Default.Register<TitlesViewModel>(); 
        } 

        /// <summary> 
        /// Gets the titles view model. 
        /// </summary> 
        public TitlesViewModel TitlesViewModel 
        { 
            get 
            { 
                return ServiceLocator.Current.GetInstance<TitlesViewModel>(); 
            } 
        } 
    }

6.2. In App.xaml

<viewModel:ViewModelLocator x:Key="Locator" d:IsDataSource="True" />

6.3. In the TitlesPage.xaml

DataContext="{Binding TitlesViewModel, Source={StaticResource Locator}}"

Here is defined the DataContext and with this all the page can be binding to the view model.

6.4. In the TitlesPage.xaml.cs:

 

         /// <summary> 
        /// Invoked when this page is about to be displayed in a Frame. 
        /// </summary> 
        /// <param name="e">Event data that describes how this page was reached.  The Parameter 
        /// property is typically used to configure the page.</param> 
        protected override async void OnNavigatedTo(NavigationEventArgs e) 
        { 
            if (_titlesViewModel != null) 
            { 
                await _titlesViewModel.LoadDataAsync(); 
            } 
        }

Here is the moment the view model will load the data.

6.5 Binding Data

In TitlesPage.xaml i have a CollectionViewSource the allow to defined a what is the source and in grouped data which are the path of the Items.

<CollectionViewSource 
            x:Name="GroupedItemsViewSource" 
            Source="{Binding Groups}" 
            IsSourceGrouped="true" 
            ItemsPath="Items" 
            d:Source="{Binding Groups}"/>

This will help to group data in GridView.

<GridView 
                x:Name="ItemGridView"                              AutomationProperties.AutomationId="ItemGridView" 
                AutomationProperties.Name="Grouped Items" 
                Grid.Row="1" Grid.Column="0" Grid.ColumnSpan="2" 
                Visibility="{Binding IsToShowProgress, Converter={StaticResource NagationBooleanToVisibilityConverter}}" 
                Padding="116,0,40,46" 
                IsSwipeEnabled="True" 
                IsItemClickEnabled="True" 
                ItemClick="ItemGridViewOnItemClick" 
                ItemsSource="{Binding Source={StaticResource GroupedItemsViewSource}}" 
                ItemTemplateSelector="{StaticResource NetFlixItemTemplateSelector}" 
                SelectionMode="Single" ItemContainerStyle="{StaticResource GridViewItemStyle}"> 
                <GridView.ItemsPanel> 
                        <ItemsPanelTemplate> 
                            <VirtualizingStackPanel Orientation="Horizontal"> 
                                <VirtualizingStackPanel.ChildrenTransitions> 
                                    <TransitionCollection> 
                                        <EntranceThemeTransition /> 
                                        <RepositionThemeTransition /> 
                                    </TransitionCollection> 
                                </VirtualizingStackPanel.ChildrenTransitions> 
                            </VirtualizingStackPanel> 
                        </ItemsPanelTemplate> 
                    </GridView.ItemsPanel> 
                <GridView.GroupStyle> 
                    <GroupStyle> 
                        <GroupStyle.HeaderTemplate> 
                            <DataTemplate> 
                                <Grid Margin="1,0,0,6"> 
                                    <Button 
                                        AutomationProperties.Name="Group Title" 
                                        Style="{StaticResource TextPrimaryButtonStyle}" > 
                                        <StackPanel Orientation="Horizontal"> 
                                            <TextBlock Text="{Binding Label}" 
                                                       Margin="3,-7,10,10" 
                                                       Style="{StaticResource GroupHeaderTextStyle}" /> 
                                            <TextBlock Text="{StaticResource ChevronGlyph}"  
                                                       FontFamily="Segoe UI Symbol"  
                                                       Margin="0,-7,0,10"  
                                                       Style="{StaticResource GroupHeaderTextStyle}"/> 
                                        </StackPanel> 
                                    </Button> 
                                </Grid> 
                            </DataTemplate> 
                        </GroupStyle.HeaderTemplate> 
                        <GroupStyle.Panel> 
                            <ItemsPanelTemplate> 
                                <VariableSizedWrapGrid Orientation="Vertical" Margin="0,0,80,0"/> 
                            </ItemsPanelTemplate> 
                        </GroupStyle.Panel> 
                    </GroupStyle> 
                </GridView.GroupStyle> 
            </GridView>

And the

<templateSelector:NetFlixItemTemplateSelector x:Key="NetFlixItemTemplateSelector"/>

will help to define the ItemTemplate that will be apply in each group.

Each item data template is defined in Template.xaml

<DataTemplate x:Key="TopDVDMoviesItemTemplate"> 
        <Grid HorizontalAlignment="Left" Width="82" Height="120" Background="#B9090B"> 
            <Image Source="{Binding Item.BoxArt.MediumUrl}"  Width="82" Height="120"  CacheMode="BitmapCache" Stretch="Uniform" /> 
        </Grid> 
    </DataTemplate> 

    <DataTemplate x:Key="NewDVDMoviesItemTemplate"> 
        <StackPanel Orientation="Horizontal" HorizontalAlignment="Left" Width="300" Height="120"> 
            <Image  CacheMode="BitmapCache" Source="{Binding Item.BoxArt.MediumUrl}"   Width="82" Stretch="Uniform"  Margin="10,10,5,10"/> 
            <StackPanel  Margin="10,10,5,10"> 
                <TextBlock Text="{Binding Item.Name}" TextWrapping="Wrap"  Margin="0,0,5,0"/> 
                <StackPanel Orientation="Horizontal" Margin="0,10,10,0"> 
                    <TextBlock  Margin="0,0,5,5" Text="Rating:" /> 
                    <TextBlock  Margin="0,0,0,5" Text="{Binding Item.AverageRating}" /> 
                </StackPanel> 
                <StackPanel Orientation="Vertical" Margin="0,0,10,0" > 
                    <TextBlock  Margin="0,0,0,5" Text="Available:"  /> 
                    <TextBlock Text="{Binding Item.Dvd.AvailableFrom,  
                                                   Converter={StaticResource StringFormatConverter}, ConverterParameter=\{0:d MMMM yyyy\}}"  
                                                   TextWrapping="Wrap"  /> 
                </StackPanel> 
            </StackPanel> 
        </StackPanel> 
    </DataTemplate>

7. The output/ running the demo

 

The result of the TitlesPage is:

 

8. Fiddler

In fiddler we can see the service requests:

GET

/v2/Catalog/Titles()?$filter=ReleaseYear%20ge%202012%20and%20Dvd/Available%20and%20Type%20eq%20’Movie’&$orderby=Dvd/AvailableFrom%20desc&$top=30&$expand=Genres,Directors

HTTP/1.1

GET

/v2/Catalog/Titles()?$filter=ReleaseYear%20ge%202012%20and%20Dvd/Available%20and%20Type%20eq%20’Movie’&$orderby=AverageRating%20desc&$top=20&$expand=Genres,Directors

HTTP/1.1

 

Notes:

for use Fiddler with Windows 8 Store Apps is required the Win8 config installed.

See the Fiddler Extensions.

Others Notes:

1. Because i am using MVVM Light, from this library i used:

  • A ViewModelBase class to be used as the base class for ViewModels.
  • A ViewModelLocator class that comes with MVVM – Light serves two purposes:

1 .It allows you to locate your ViewModel from inside your XAML and hook it to the DataContext.

2. It allows you to control two different ViewModels:  a design time view model, and a run time ViewModel.   Because one of the author’s goals of MVVM – Light is to make your XAML – ViewModel connection visibile in blend (or ‘blendable’) ,   the ViewModelLocator comes in handy for this purpose.

  • A SimpleIoc is a simple container for dependency injection.

For more about MVVM Light see http://mvvmlight.codeplex.com/

(It is not the unique solution)

2. Because this is a demo, maybe there is some points related with UI that is not completed, I focused in the propose of the sample. In the future i would like to work more in this sample and implement more sample using this sample.

Source Code Files

The solution has the following structure:

Details:

  • IServiceManager.cs has the IServiceManager interface and define the interface for the ServiceManager.
  • ServiceManager.cs has the ServiceManager class and it encapsulate the NetFlixService and exposes only the methods that is need in ViewModel.
  • FakeServiceManager.cs is the implementation of the IServiceManager, but is a fake data.
  • TitlesViewModel.cs has TitlesViewModel class and it is used for binding with the DataContext from TitlesPage.
  • ViewModelLocator.cs has the ViewModelLocator class that help to binding the view model with the view.
  • ViewModelHelper.cs has the ViewModelHelper class the helps to create grouped data.
  • TitlesPage.xaml and TitlesPage.xaml.cs that is the main page.
  • Templates.xaml is a resource dictionary that has the DataTemplate for the view.
  • NetFlixItemTemplateSelector.cs has the NetFlixItemTemplateSelector that is used for get the ItemTemplate for each item in gridView.

More Information

Run the sample

To debug the app and then run it, press F5 or use Debug > Start Debugging. To run the app without   debugging, press Ctrl+F5 or use Debug > Start Without Debugging.

More Information

Ask me on twitter @saramgsilva

 

Oficial Source:

http://code.msdn.microsoft.com/windowsapps/Consuming-Odata-Service-in-a97758e5

 

[PT] Windows 8 App Swipe (Devs)

microsoft_21_janeiro

Com o Windows 8, as Apps são o verdadeiro centro da experiência do utilizador final. As Apps criadas por si, e levadas a qualquer parte do mundo através da Windows Store.
Criámos o Windows 8 App Swipe para lhe mostrar, com a tecnologia em acção e sem slides (!), os melhores recursos que tem ao seu dispor para dar vida a Apps deslumbrantes, num conjunto de sessões técnicas seguidas e cadenciadas (como um swipe) que lhe irão permitir ficar a conhecer alguns dos novos pormenores mais entusiasmantes da plataforma que agora tem nas mãos.
Ou seja, e como pode ver pela agenda, “o” evento que lhe irá permitir dar o passo seguinte no seu caminho pelas Apps Windows 8.
Contamos consigo!
A Equipa Windows da Microsoft Portugal

AGENDA:

09:00 Credenciação e Boas-vindas ao evento

09:30 Introduction, Tools and Advertising // Tiago Andrade e Silva, Microsoft Portugal

10:00 Multilanguage Toolkit // Emanuel Amiguinho, Microsoft Portugal

10:30 Registo e publicação de Apps na store // Pedro Serrano, Cavedigital

11:00 Coffee Break & NiceReader presentation // Viatecla

11:30 Pagamentos, inapp purchases, trial (time / feature) // Nelson João, Viatecla

12:00 Identidade em Windows 8 (Live SDK) // Tiago Barbosa, Microsoft Portugal

12:30 Consumindo serviços OData em Windows 8 Store Apps // Sara Silva, Zon

13:00 Almoço Livre

14:30 Media Player Framework // Marco Silva, CreateIT

15:00 Bing Maps // Ricardo Pinto, Agap2

15:30 Local Storage and caching / Making your app work offline, detecting offline mode, caching sets of data // Ricardo Pinto, Agap2

16:00 Coffee Break & 3D printing // Francisco Mendes, Bitbox

16:30 Typescript // Alexandre Marreiros, Innovagency

17:00 Azure Mobile Services (Identity, WPS…) // Nuno Silva, Microsoft Portugal

17:30 Code Sharing (WP+WP8) // Nuno Silva, Microsoft Portugal

18:00 Encerramento

 

Link:

https://msevents.microsoft.com/CUI/EventDetail.aspx?EventID=1032541591&Culture=pt-PT&community=0

Listview header with the same listview’s width [XAML]

Today i found a question in forum that is related with the fact when we have a child control that need to have the same size from the parent.

The tip for this kind of problems is bingind the Height or Width property from child control with the ActualHeight or ActualWidth from parent.
Something like i said in that question.

 <ListView Background="Gold" Name="listview">
      <ListView.Header>
        <StackPanel Background="Red" Width="{Binding ActualWidth, ElementName=listview}">
           <TextBlock Text="ListView header"/>
         </StackPanel>
      </ListView.Header>

 </ListView>

The header of Listview has the auto size but if you binding the Width property to the ActualWidth form the ListView you will sure that the both has the same size!

See this test:

   <Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
        <Grid.RowDefinitions>
            <RowDefinition Height="*"/>
            <RowDefinition Height="50"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>

        <ListView Background="Gold" Grid.Row="0">
            <ListView.Header>
                <StackPanel Background="Red">
                    <TextBlock Text="ListView with auto size header."/>
                </StackPanel>
            </ListView.Header>
        </ListView>

        <ListView Background="Gold" Name="listview" Grid.Row="2">
            <ListView.Header>
                <StackPanel Background="Red" Width="{Binding ActualWidth, ElementName=listview}">
                    <TextBlock Text="ListView with header that has the same Listview's Width"/>
                </StackPanel>
            </ListView.Header>
        </ListView>
    </Grid>

UPDATE:

Please read the comments to understand one important point about it!

 

I’m Microsoft Visual C# MVP

This year started with a big news for me! Microsoft presented me with the Microsoft Most Valuable Professional (MVP) Award. I am very happy and I hope contribute with more community contributions.

Award

For more about Microsoft Most Valuable Professional see the official website.