Showing posts with label Windows Phone. Show all posts
Showing posts with label Windows Phone. Show all posts

Tuesday, February 23, 2016

Dependancy Injection With Unity

In Last post I gave you introduction for dependency  Injection.

Here we gonna Use it in real code

First I create MVC project and Add following classes to it.

public interface IUserService
   {
       string GetUserName(string name);
   }
 
public class UserService : IUserService
    {
        public string GetUserName(string name)
        {
            return string.Format("Hello {0}", name);
        }
    } 
 


Here is my folder structure



















Then  I create My MVC UserController and Its View. Code is same as I did in prev post

public class UserController : Controller
   {
       private IUserService _userService;
 
       public UserController(IUserService userService)
       {
           _userService = userService;
       }
       // GET: User
       public ActionResult Index()
       {
           ViewBag.UserMessage = _userService.GetUserName("Dependency Unity");
           return View();
       }
   }

Here is View

@{
    ViewBag.Title = "Index";
}
 
<h2>@ViewBag.UserMessage</h2> 
 
 
 That's all. 

Now I'm gonna install Unity Nuget package for DI framework






 Then real Dependency Injection begins.

Main Focus  
  1. Register
  2. Resolver
 We use dependency Injection Register for register dependency  and resolver for resolve dependency.  It will be done by Unity framework for you if you implement it


1. Create Class DI_Register 

public static class Di_Register
    {
        /// <summary>
        /// Register And resolver of Dependency 
        /// </summary>
        public static void RegisterDependancy()
        {
            IUnityContainer container = new UnityContainer();
            RegisterDependancy(container);
 
            DependencyResolver.SetResolver(new UserResolver(container));
        }
 
        /// <summary>
        /// Type registration
        /// </summary>
        /// <param name="container"></param>
        private static void RegisterDependancy(IUnityContainer container)
        {
            container.RegisterType<IUserServiceUserService>();
        }
    }
 

2. Create UserResolver Class for dependency resolving. It will  using the Unity's IDependancyResolver Interface for resolving implementation . It eill take care of your dependency resolving 


/// <summary>
   /// Resolver 
   /// </summary>
   internal class UserResolver : IDependencyResolver
   {
       private IUnityContainer _unityContainer;
 
       public UserResolver(IUnityContainer unityContainer)
       {
           _unityContainer = unityContainer;
       }
 
       /// <summary>
       /// For one object 
       /// </summary>
       /// <param name="serviceType"></param>
       /// <returns></returns>
       public object GetService(Type serviceType)
       {
           try
           {
               return _unityContainer.Resolve(serviceType);
           }
           catch (Exception)
           {
 
               return null;
           }
       }
 
       /// <summary>
       /// For multiple objects 
       /// </summary>
       /// <param name="serviceType"></param>
       /// <returns></returns>
       public IEnumerable<object> GetServices(Type serviceType)
       {
           try
           {
               return _unityContainer.ResolveAll(serviceType);
 
           }
           catch (Exception)
           {
 
               return null;
           }
       }
   }

 3. Then go to the AppStart (startup.auth.cs) and call dependency register in application bigining

Di_Register.RegisterDependancy(); 
 
 


 Then Run and see the magic :)


Full code In Git ..

https://github.com/prabathsl/DI_Sample


 Enjoy Coding


 









Sunday, June 7, 2015

Alternative way for enable developer mode in windows 10 device

Hi ,

Have you ever seen bug when going to enabling developer mode in windows 10 preview (IP)? The application crashes.

Now how we enable developer mode for application development ?

There is option available. When we are deploying apps with side loading in windows 8/8.1 we are doing the policy editing to allow app installation in client machine. the same is helpfull here too

Open your group policy editor  -> Computer Configurations-> Administrative templates -> Windows Components -> App Package development 

In there enable
Allow development of windows store apps and installing them from integrated development environment ...
and
allow all trusted apps to install 





You are done and enjoy  

Friday, February 6, 2015

Prism MVVM pattern with Applcaition development

Prism is one of the design patterns which defined by Microsoft Patterns and Practices team for building composite Applications in C# , XAML (WPF,Store Applications etc ) .

Why MVVM is not enough ?

When we creating application with MVVM there is few questions and practices we need to figure out. 
  • Should I use Prism to provide support for MVVM?
  • Should I use a dependency injection container?
    • Which dependency injection container should I use?
    • When is it appropriate to register and resolve components with a dependency injection container?
    • Should a component's lifetime be managed by the container?
  • Should the app construct views or view models first?
  • How should I connect view models to views?
    • Should I use XAML or code-behind to set the view's DataContext property?
    • Should I use a view model locator object?
    • Should I use an attached property to automatically connect view models to views?
    • Should I use a convention-based approach?
  • Should I expose commands from my view models?
  • Should I use behaviors in my views?
  • Should I include design time data support in my views?
  • Do I need to support a view model hierarchy?
 (reference https://msdn.microsoft.com/en-us/library/windows/apps/xx130657.aspx )

Why Prism?

Prism contains wire frame which can help to accelerate application development in  MVVM and It already contains commonly required core features in application development.


Let's Start Coding 


Here we are going to create windows store application using Prism

1. Create new windows store application project (Blank application)
2. Go to package manager console or manage nuget packages and install prism nuget to the application

 3. Now starts coding . Here we are using MVVM and I create few folders to isolate resources in the project such as
  • ViewModel - for ViewModel
  • Model - for Model
  • Controles - for BaseControls
  • View - for XAML pages 
  • Enum - for enumerations
  • Interfaces - for Interfaces 
and then put MainPage.xaml  in to teh View Folder (drag and drop)

Now my project like this


















 Code for prism
 Now we have to convert our application to prism
1. App.XAML and App.XAML.cs

<prism:MvvmAppBase
    x:Class="SamplePrism.App"
    xmlns:prism="using:Microsoft.Practices.Prism.Mvvm"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:SamplePrism">
 
</prism:MvvmAppBase> 
 
 
sealed partial class App : MvvmAppBase
   {
       public App()
       {
           this.InitializeComponent();
       }
 
       protected override Task OnLaunchApplicationAsync(LaunchActivatedEventArgs args)
       {
          //Main is the name of view i need to navigate 
           this.NavigationService.Navigate("Main"null);
 
           return Task.FromResult<object>(null);
       }
   } 


2. Then create PageBase in controls  from Prism MVVM

public abstract partial class PageBasePage,IView
   {
   } 
3. Then Use this page base in our Views, xaml

 Change MainPage.xaml and MainPage.xaml.cs as  follows
<controls:PageBase
    x:Class="SamplePrism.Views.MainPage"
    xmlns:prism="using:Microsoft.Practices.Prism.Mvvm"
    xmlns:controls="using:SamplePrism.Controls"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:SamplePrism.Views"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    prism:ViewModelLocator.AutoWireViewModel="True"
    xmlns:designtime="using:SamplePrism.DesignTimeViewModel"
    mc:Ignorable="d">

public sealed partial class MainPage : PageBase
    {
        public MainPage()
        {
            this.InitializeComponent();
        }
    }

4. In here I'm craeting Interface to keep the properties of MainPage But this is optional. You can jsut implement the ViewModel without this interface


Here is My interface


public interface IMainPageViewModel
   {
       string Title { getset; }
   }


5. Lets Starts MainPageViewModel

public class MainPageViewModel : ViewModelIMainPageViewModel
   {
       string _Title = default(string);
       public string Title { get { return _Title; } set { SetProperty(ref _Title, value); } }
 
       public override void OnNavigatedTo(object navigationParameter, NavigationMode navigationMode, Dictionary<stringobject> viewModelState)
       {
           this.Title = "Hello prism";
       }
   }

With prism MVVM it conains basic funtions in store app such like OnNavigatedTo , OnNavigatedFrom etc. You can directly use them inside the ViewModel 

Run and Enjoy the Prism.

It is really easy to build in complex applications in enterprise level. even if you  not like Prism code in specific scenario you can switch with your old MVVM too inside the same project










Full Code 
http://bit.ly/1DL68OI







Tuesday, February 3, 2015

Tips to build Real time Applications (SignalR)

What is real time ? People who use the applications they need to see the actions one it happens . No delays or refreshing even it is desktop application, App , web or some other application.

How its possible ?

There is few options that developer can looking at.
1. Running background thread
2. Use SignalR

1st option that I describe here is not the best option in most of the times. Running background thread all times is resource consuming and it always use pulling (grab the data from the remote). And there is security concerns as well. But believe me there is some applications which we need to use this and thread is worth than other .


Most pf the time best option is SignalR

What is SignalR ?
 SignalR is series of abstractions around various methods of providing persistent Http Connections. Simply it makes real time communication without effort 

 Where ?
SignalR can be in
  1. Web application
  2. Desktop Applicaton 
  3. App (windows /iOs/Android/berry ) 

 It is cross platform tool  (totally open source) which capable of running with any platform.


SignalR is Client Server

To use SignalR you need to have Server (basically you can create serever with asp.net i'll add posts future)

And client application, (if you use javascript no need to have client nuget to consume SignalR) you can make any application by just adding SignalR nugets to your project.

Microsoft Asp.Net SignalR 









Modern servers from Windows Server 2012 is support SignalR (Real time Communication perfectly )

There is life beyond  Web Sockets


Lets meet with handons later :) enjoy

SignalR Coading 

Sunday, January 18, 2015

Working in designtime with Data in MVVM

If we develop applications ( XAML based) we have a problem with see the data in design view. Every application become successful when its interface is attractive. If our application is based on internet or any other computational task there is difficulty on make Interfaces without running the application real time. Here is solution for it

Use design time data binding which already with the xaml based application 

Today we going to develop the windows 8.1 store application. ( This is same with any XAML based Application )

1. Create Windows 8.1 store application form the Visual studio. (I named it as DesignTimedata )
2. Create ViewModel to bind the run time data , In following here is My MainViewModel.cs

With this example we are not going to the use internet or other tasks .therefore just hard corded the values in constructor 

namespace DesignTimeData.Runtime
{
    public class MainViewModel:INotifyPropertyChanged
    {
 
        private string _Title { getset; }
        public string Title
        {
            get { return _Title; }
            set
            {
                _Title = value;
                OnPropertyChanged("Title");
            }
        }
 
        private string _Description { getset; }
        public string Description
        {
            get { return _Description; }
            set
            {
                _Description = value;
                OnPropertyChanged("Description");
            }
        }
 
 
 
        public MainViewModel()
        {
        // Hard coded runtime data
            this._Title = "Title in Run time";
            this._Description = "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Maecenas porttitor congue massa. Fusce posuere, magna sed pulvinar ultricies, purus lectus malesuada libero, sit amet commodo magna eros quis urna.";
        }
 
        // Create the OnPropertyChanged method to raise the event 
        // Use in MVVM
        public event PropertyChangedEventHandler PropertyChanged;
        protected void OnPropertyChanged(string name)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null)
            {
                handler(thisnew PropertyChangedEventArgs(name));
            }
        }
    }
}


2. Then bind the ViewModel to the View with relevant tags.
You can use Singleton or Page Resource binding . In here Im using Bind the ViewModel to the Page in XAML . It gives me intellisense in XAML .

Here is my MainPage.xaml

<Page
    x:Class="DesignTimeData.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:DesignTimeData"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:runtime="using:DesignTimeData.Runtime"
    mc:Ignorable="d">
    
    <Page.DataContext>
        <runtime:MainViewModel/>
    </Page.DataContext>
 
3 .Then Create New Class which have exact name of your view model. Better to use different namespace / folder . In this case It is MainViewModel 
Here is my design time ViewModel. It will contains all test data which displayed in design view in visual studio


namespace DesignTimeData.DesignTimedata
{
    public class MainViewModel
    {
        public string Title { get { return "DesignTime Title"; } }
 
        public string Description { get { return "Design time description"; } }
    }
} 

4. Then lets bind the design time data into the design (xaml) . In here there is always tag like this
      mc:Ignorable="d" 
with every page. something defines under this tag will not be displayed in the runtime. then this is the one that we need to use.

With this d we can define all the properties which page have and change them. but none of them are effecting the real application .

Lets bind the ViewModel to the page and use it with design time . Here is my full page

<Page
    x:Class="DesignTimeData.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:DesignTimeData"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:desgn="using:DesignTimeData.DesignTimedata"
    xmlns:runtime="using:DesignTimeData.Runtime"
    mc:Ignorable="d">
    
    <Page.DataContext>
        <runtime:MainViewModel/>
    </Page.DataContext>
    
    <d:Page.DataContext>
        <desgn:MainViewModel />
    </d:Page.DataContext>
    
    <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
        <StackPanel Margin="100,150,0,0">
            <TextBlock Style="{StaticResource HeaderTextBlockStyle}" Text="{Binding Title}"/>
            <TextBlock Style="{StaticResource SubtitleTextBlockStyle}" Text="{Binding Description}"/>
        </StackPanel>
    </Grid>
</Page>

Now we can see the vaues that we put to test the Application UI and make any changes to it.














Here is runtime result of the app















Enjoy







Full Code 
http://bit.ly/1xiJ3yZ

 

Thursday, November 6, 2014

Authentication with third party Auth providers in new era of Mobile Apps

When you are developing app, to increase security and manipulate users without taking user details is use authentication providers help such like Live, Google, Facebook, twitter , linked in, flickers etc.

With the newer versions of mobile BCL is not supported the olde way of authenticating with third party SDK's. All the BCL are updated with 8.1 and Universal apps.

With this post I'm gonna explain how to implement those authentication (ex: facebook)

1. you need to have facebook app. (http:\\developer.facebook.com)

To implement the Authentication you need to create separate class and interface that can handle Continuation events. Once authentication done it will redirect to the app using these Continuation objects.

Here is ContinuationManager Class that I used

using System.Text;
using Windows.ApplicationModel.Activation;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
 
#if WINDOWS_PHONE_APP
    /// <summary>
    /// ContinuationManager is used to detect if the most recent activation was due
    /// to a continuation such as the FileOpenPicker or WebAuthenticationBroker
    /// </summary>
    public class ContinuationManager
    {
        IContinuationActivatedEventArgs args = null;
        bool handled = false;
        Guid id = Guid.Empty;
 
        /// <summary>
        /// Sets the ContinuationArgs for this instance. Using default Frame of current Window
        /// Should be called by the main activation handling code in App.xaml.cs
        /// </summary>
        /// <param name="args">The activation args</param>
        internal void Continue(IContinuationActivatedEventArgs args)
        {
            Continue(args, Window.Current.Content as Frame);
        }
 
        /// <summary>
        /// Sets the ContinuationArgs for this instance. Should be called by the main activation
        /// handling code in App.xaml.cs
        /// </summary>
        /// <param name="args">The activation args</param>
        /// <param name="rootFrame">The frame control that contains the current page</param>
        internal void Continue(IContinuationActivatedEventArgs args, Frame rootFrame)
        {
            if (args == null)
                throw new ArgumentNullException("args");
 
            if (this.args != null && !handled)
                throw new InvalidOperationException("Can't set args more than once");
 
            this.args = args;
            this.handled = false;
            this.id = Guid.NewGuid();
 
            if (rootFrame == null)
                return;
 
            switch (args.Kind)
            {
               
 
                case ActivationKind.WebAuthenticationBrokerContinuation:
                    var wabPage = rootFrame.Content as IWebAuthenticationContinuable;
                    if (wabPage != null)
                    {
                        wabPage.ContinueWebAuthentication(args as WebAuthenticationBrokerContinuationEventArgs);
                    }
                    break;
            }
        }
 
        /// <summary>
        /// Marks the contination data as 'stale', meaning that it is probably no longer of
        /// any use. Called when the app is suspended (to ensure future activations don't appear
        /// to be for the same continuation) and whenever the continuation data is retrieved 
        /// (so that it isn't retrieved on subsequent navigations)
        /// </summary>
        internal void MarkAsStale()
        {
            this.handled = true;
        }
 
        /// <summary>
        /// Retrieves the continuation args, if they have not already been retrieved, and 
        /// prevents further retrieval via this property (to avoid accidentla double-usage)
        /// </summary>
        public IContinuationActivatedEventArgs ContinuationArgs
        {
            get
            {
                if (handled)
                    return null;
                MarkAsStale();
                return args;
            }
        }
 
        /// <summary>
        /// Unique identifier for this particular continuation. Most useful for components that 
        /// retrieve the continuation data via <see cref="GetContinuationArgs"/> and need
        /// to perform their own replay check
        /// </summary>
        public Guid Id { get { return id; } }
 
        /// <summary>
        /// Retrieves the continuation args, optionally retrieving them even if they have already
        /// been retrieved
        /// </summary>
        /// <param name="includeStaleArgs">Set to true to return args even if they have previously been returned</param>
        /// <returns>The continuation args, or null if there aren't any</returns>
        public IContinuationActivatedEventArgs GetContinuationArgs(bool includeStaleArgs)
        {
            if (!includeStaleArgs && handled)
                return null;
            MarkAsStale();
            return args;
        }
    }
 
    /// <summary>
    /// Implement this interface if your page invokes the web authentication
    /// broker
    /// </summary>
    interface IWebAuthenticationContinuable
    {
        /// <summary>
        /// This method is invoked when the web authentication broker returns
        /// with the authentication result
        /// </summary>
        /// <param name="args">Activated event args object that contains returned authentication token</param>
        void ContinueWebAuthentication(WebAuthenticationBrokerContinuationEventArgs args);
    }

To handle the continuation after authentication you nee to modify your app.xaml.cs as well. Because Once you redirect to auth providers screen you are exit (deactivate) your app. then once auth provider redirect back your app gets activate .

Create object of ContinuationManager  in App.xml.cs

public static ContinuationManager continuationManager { getprivate set; }

Then OnActivated event of the app add the continuation handle

protected async override void OnActivated(IActivatedEventArgs e)
{
   continuationManager = new ContinuationManager();
 
   //Check if this is a continuation 
   var continuationEventArgs = e as IContinuationActivatedEventArgs;
   if (continuationEventArgs != null)
   {
	continuationManager.Continue(continuationEventArgs);
   }
 
  Window.Current.Activate(); 
}



Then you are free to go with any kind of authentication that provide from auth provider 

    internal async Task FacebookLoginMethod()
        {
            String FacebookURL = "https://www.facebook.com/dialog/oauth?client_id=" + Uri.EscapeDataString("Your app Id") + "&redirect_uri=" + Uri.EscapeDataString("https://m.facebook.com/dialog/return/ms") + "&scope=read_stream&display=popup&response_type=token";
 
            System.Uri StartUri = new Uri(FacebookURL);
//To use windows phone or windows app with Fb authentication user this end uri and redirect uri. Both are working 
             System.Uri EndUri = new Uri("https://m.facebook.com/dialog/return/ms");
 
#if WINDOWS_PHONE_APP
            try
            {
                WebAuthenticationBroker.AuthenticateAndContinue(StartUri, EndUri, null, WebAuthenticationOptions.None);
            }
            catch
            {
 
            }
#endif
        }


and use this ContinueWeb authentication method inside the page that you call authentication. otherwise it will not working. Inherit the IWebAuthnticationContinuable interface to the page and add this method

public async void ContinueWebAuthentication(WebAuthenticationBrokerContinuationEventArgs args)
       {
           WebAuthenticationResult result = args.WebAuthenticationResult;
           if (result.ResponseStatus == WebAuthenticationStatus.Success)
           {
               token = await FilterToken(result.ResponseData.ToString());
 
           }
           else
           {
               MessageDialog Msg = new MessageDialog("Login failed");
               Msg.ShowAsync();
           }
 
       }


This WebAuthentication result wil contains the Authprovider's access token. Filterout it and do what ever graph is available with authentication provider. 


Enjoy ..








HttpClient Caching

Is any one of you have an experience on when send http request through http client the response become the same (no change) even your source of the response (server) is updated.

It is the way that default http protocol behaves

By default HttpClient use a cache to store responses that come up with response headers without Cache-Control header. ( Ref: HTTP Header fields)

In a scenario you need to change the cache behavior with HttpClient you can have two options

1. Edit the service (server) to response with relevant cache headers
2. Modify your request headers

Edit the service (server) to response with relevant cache headers

In this model it give two benefits to you
  • A content you will not use again is not stored in the client machine.
  • Other requests can benefit from the cache (when using the same instance of HttpClient).
In your web service go to web.config file and in-side the system.serviceModel add following tag with relevant headers you need


     <client>
      <endpoint address="http://localhost/..." >
        <headers>
          <Cache-Control>no-cache</Cache-Control>
        </headers>
      </endpoint>
    </client>


Modify your request headers

if you don't have the access to the server you can go with this option. Just ad additional header with HttpClient and send the request then response automatically include these headers

HttpClient Client = new HttpClient();
Client.DefaultRequestHeaders.Add("Cache-Control""no-cache");


Now your HttpClient is ready to handle http request with no cache .


here is Cache contol values that provide from W3 with Http headers.

    cache-directive = cache-request-directive
         | cache-response-directive
    cache-request-directive =
           "no-cache"                          
         | "no-store"                          
         | "max-age" "=" delta-seconds         
         | "max-stale" [ "=" delta-seconds ]   
         | "min-fresh" "=" delta-seconds       
         | "no-transform"                      
         | "only-if-cached"                    
         | cache-extension                     
     cache-response-directive =
           "public"                               
         | "private" [ "=" <"> 1#field-name <"> ] 
         | "no-cache" [ "=" <"> 1#field-name <"> ]
         | "no-store"                             
         | "no-transform"                         
         | "must-revalidate"                      
         | "proxy-revalidate"                     
         | "max-age" "=" delta-seconds            
         | "s-maxage" "=" delta-seconds           
         | cache-extension 
 
 
 
 Enjoy the code .. 
 
 




Saturday, October 11, 2014

Windows Azure Mobile Authentication Service

Magic with Azure mobile services is easy handling in Authentication for users. It allows you to authenticate users
1. Microsoft Account
2. Facebook Account
3. Twitter Account
4. Google Account
5. Azure Active Directory

What else developer need..

To enable all of those authentications you need to have apps running on those platforms. Url's for creating apps on each service provider is given below (Creating app on your hand *Get the developer manual help according to each technology)

1. Microsoft - https://account.live.com/developers/applications
2. Facebook - https://developers.facebook.com/ (Click on App's menu)
3. Twitter - https://apps.twitter.com/app/new
4. Google - https://console.developers.google.com/project

** In every instance that you create apps use your Azure Mobile Service Url 
HERE is URL for Microsoft Login
for json backend :https://<mobile_service>.azure-mobile.net/login/microsoftaccount
for .NET backend :https://todolist.azure-mobile.net/signin-microsoft


With later posts you can see how to use Azure Active directory

Start from the beginning

1. First login to your Azure portal and go to Mobile Services



2. Then select your Mobile Service , in here I have already created Mobile Service for the Azure Mobile Services post named as prabathblog. Select it and go inside. Then select IDENTITY  Tab from menu.














3. Fill the values according to the Login provider with details


4. Then go to the dashboard and download the app.

5. Use this code to authenticate in client side

        /// <summary>
        /// Simple authenticate
        /// </summary>
        /// <returns></returns>
        private async Task AuthenticateAsyncSimple()
        {
            while (user == null)
            {
                string message;
                try
                {
                    user = await App.MobileService
                        .LoginAsync(MobileServiceAuthenticationProvider.MicrosoftAccount);
                    message =
                        string.Format("You are now logged in - {0}", user.UserId);
                }
                catch (InvalidOperationException)
                {
                    message = "You must log in. Login Required";
                }
 
                var dialog = new MessageDialog(message);
                dialog.Commands.Add(new UICommand("OK"));
                await dialog.ShowAsync();
            }
        }


Enjoy your code