lundi 25 juin 2018

UWP/XAML using PopupThemeTransition / PopOutThemeAnimation / PopInThemeAnimation to animate elements coming in and out of your app

In UWP we have this great control called Popup this control can allow you to quickly and cleanly have element pop in and pop out of your view. Also we will look at how to do more of less the same thing with only a Grid.

In this post I wont go into details about the popup control itselft however if you are interested in getting more information msdn is the best place to look.

First we are going to create our simple popup element, make sure that you set the IsOpen property to false (this will hide your popup),  IsLightDismissEnabled to true will mean that if the user clicks outside of the popup it will disappear.

Here is what the XAML can look like:

        <Popup
            x:Name="PopupFromBottom"
            Grid.Row="0"
            Width="459"
            Height="90"
            Margin="20,0,20,20"
            VerticalAlignment="Bottom"
            IsLightDismissEnabled="True"
            IsOpen="False"/>

To add transition to when the popup will be shown we will add ChildTransitions:

 <Popup.ChildTransitions>
      <TransitionCollection>
           <PopupThemeTransition FromVerticalOffset="100" />
      </TransitionCollection>
 </Popup.ChildTransitions>

This will add an animation, the popup will come from the bottom with a translation of 100px. If you have wanted a Horizontal translation then you could have used FromHorizontalOffset.

For this popup to be displayed all you need is to set the IsOpen to true :

 PopupFromBottom.IsOpen = true;

Now if we wanted the popup to hide it self after 3 seconds all we would need to add is a wait of 3 seconds and again change the IsOpen to false as follows:

 //show
PopupFromBottom.IsOpen = true;

//wait 3 sec
await Task.Delay(TimeSpan.FromSeconds(3));

//close 
PopupFromBottom.IsOpen = false;

In the previous example we used the default popup control which allowed us to use the lightdismiss and directly attach the PopupThemeTransition animations to the popup.  However we always have custome cases where we need custome code and sometimes the default controls just wont cut it.  NOw we are going to see how to use a Grid as a popup.

first we are going to create our Grid as follows:

<Grid
            x:Name="GridPopup"
            Grid.Row="0"
            Width="459"
            Height="90"
            Margin="20,0,20,20"
            VerticalAlignment="Bottom"
            Background="LightGray"
            Opacity="0" />

Next we are going to add storyboards and use PopInThemeAnimation and PopOutThemeAnimation
to pop in and pop out our grid.  Here is the Storyboard XAML code:

 <Storyboard x:Name="PopOutStoryboard">
            <PopOutThemeAnimation SpeedRatio="2" TargetName="GridPopup" />
 </Storyboard>
 <Storyboard x:Name="PopInStoryboard">
            <PopInThemeAnimation
                FromVerticalOffset="150"
                SpeedRatio="0.3"
                TargetName="GridPopup" />
            <DoubleAnimation
                d:IsOptimized="True"
                Storyboard.TargetName="GridPopup"
                Storyboard.TargetProperty="Opacity"
                To="1"
                Duration="0" />
 </Storyboard>

and now to easily call this code all we need to do:

        private void OpenStoryboard_Click(object sender, RoutedEventArgs e)
        {
            PopInStoryboard.Begin();
        }

        private void CloseStoryboard_Click(object sender, RoutedEventArgs e)
        {
            PopOutStoryboard.Begin();
        }

And there you are! You can find the full code here.

jeudi 22 mars 2018

UWP, C# - Retrieve the redirect url using HttpClient from the Headers of the Response - [HttpClient,C#]

I wanted to share this little piece of code because I did not quickly find any great documentation on this. 

My needs where as follows: I had a URL lets say http://bit.ly/2pwccfo and I did not have the direct access to the image of the URL.  So I ended up creating a small static class that holds a method GetRedirectedUrl that will get my redirect url.

Here is my code:

public static class CoreTools
{
       public static async Task<string> GetRedirectedUrl(string url)
        {
            //this allows you to set the settings so that we can get the redirect url
            var handler = new HttpClientHandler()
            {
                AllowAutoRedirect = false
            };
            string redirectedUrl = null;


            using (HttpClient client = new HttpClient(handler))
            using (HttpResponseMessage response = await client.GetAsync(url))
            using (HttpContent content = response.Content)
            {
                // ... Read the StatusCode in the response 
                // to see if we have the redirected url
                if (response.StatusCode == System.Net.HttpStatusCode.Found)
                {
                    HttpResponseHeaders headers = response.Headers;
                    // do we have headers 
                    //do we have something in location
if (headers != null && headers.Location != null) { redirectedUrl = headers.Location.AbsoluteUri; } } } return redirectedUrl; } }

You can find my gist here.
Happy Coding

jeudi 1 mars 2018

UWP Imbricking a ItemTemplateSelector in a ItemTemplateSelector to create a dynamic listview with horizontal and vertical items

In this tutorial we are going to see how to create a dynamic listview that can hold horizontal and vertical items, this tutorial will be broken into 3 parts :

  • First we will create ou Model and and Data
  • Next we we create the UserControl and DataTemplates to hold our listview and gridviews
  • Lastly we will look at how to use a ItemTemplateSelectoron our first listview.

Now here are 2 screen shots of what we would like to do, the first one is from the Window Store App and the second one from the dailymotion UWP app.


this one looks like one listview that is holding another listview with an ItemTemplateSelector, however these seem to have a fix number of items they are showing so in the end it could be the it is only one listview with an ItemTemplateSelector that select the correct template for when you have 4 items, 6 items or 3 items and so on.

I want to create something more generic like in the dailymotion app :




Let start coding!

Here is a quick diagram of how the idea of imbricking 2 DataTemplateSelector selector will work:



We are going to need 2 enums that will allow us to say when the segment is vertical or horizontal and the second one will allow us to know which template we will need to set in the second gridview.

This allows us to know what to sent in our first listview in its ItemTemplate: Horizontal/Vertical
public enum SegmentType
  {
        HorizontalSegment,
        VerticalSegment,
  }


This is for when we are in the Horizontal/Vertical Control so that we can set the ItemTemplate for the GridView:
 public enum ItemTemplateType
    {
        CircleUserItem,
        SquareUserItem,
    }

Next we are going to need to create two DataTemplateSelector so that depending on what kind of enum the EntityViewModel is passing we can assign the correct DataTemplate.

This is our DataTemplateSelector for our main listview, it will server either a horizontal gridview or a vertical Gridview:


 public class SegementTemplateSelector : DataTemplateSelector
    {
        public DataTemplate KeyHorizontalControl = Application.Current.Resources["KeyHorizontalControl"] as DataTemplate;
        public DataTemplate KeyVerticalControl = Application.Current.Resources["KeyVerticalControl"] as DataTemplate;

        protected override DataTemplate SelectTemplateCore(object item, DependencyObject container)
        {

            var element = item as BaseSegementEntityViewModel;

            if (element != null)
            {
                if (element.ItemType == SegmentType.HorizontalSegment)
                    return KeyHorizontalControl;
                else
                    return KeyVerticalControl;
            }
            return base.SelectTemplateCore(item, container);
        }
    }


This is our DataTemplateSelector for the Gridviews that are inside our Horizontal/Vertical Control it allows to know if we are serving a square or a circle DataTemplate:


 public class ItemTemplateSelector : DataTemplateSelector
    {
        public DataTemplate KeyCircleUserControl = Application.Current.Resources["KeyCircleUserControl"] as DataTemplate;
        public DataTemplate KeySquareUserControl = Application.Current.Resources["KeySquareUserControl"] as DataTemplate;
        
        protected override DataTemplate SelectTemplateCore(object item, DependencyObject container)
        {

            var element = item as BaseItemEntityViewModel;
            
            if (element != null)
            {
                switch (element.ItemTemplate)
                {
                    case ItemTemplateType.CircleUserItem:
                        return KeyCircleUserControl;


                    default:
                        return KeySquareUserControl;
                }

            }
            return base.SelectTemplateCore(item, container);
        }
    }

Bonus: this could also be used to serve BOTH a Circle DataTemplate and a square DataTemplate in the Gridview depending on the type of the item.

Next we will be looking at the XAML in our Horizontal/Vertical Controls.

HorizontalControl.xaml :


 <GridView
        x:Name="HorizontalGridView"
        Height="250"
        Margin="26,0,0,0"
        HorizontalAlignment="Stretch"
        ItemTemplateSelector="{StaticResource KeyItemTemplateSelector}"
        ItemsSource="{Binding MyItemSource}"
        ScrollViewer.HorizontalScrollBarVisibility="Hidden"
        ScrollViewer.HorizontalScrollMode="Enabled"
        ScrollViewer.VerticalScrollBarVisibility="Disabled">

        <GridView.ItemsPanel>
            <ItemsPanelTemplate>
                <ItemsStackPanel
                    Margin="5"
                    HorizontalAlignment="Left"
                    Orientation="Horizontal" />
            </ItemsPanelTemplate>
        </GridView.ItemsPanel>
    </GridView>

In the HorizontalControl we need to change the orientation of the ItemsStackPanel of the ItemsPanelTemplate. In this GridViewI edit the ScrollViewer settings so that they match my neededs.

VerticalControl.xaml :


 <GridView
        x:Name="VerticalGridView"
        Width="300"
        Margin="26,0,0,0"
        HorizontalAlignment="Stretch"
        ItemTemplateSelector="{StaticResource KeyItemTemplateSelector}"
        ItemsSource="{Binding MyItemSource}"
        ScrollViewer.HorizontalScrollBarVisibility="Disabled"
        ScrollViewer.HorizontalScrollMode="Disabled"
        ScrollViewer.IsHorizontalScrollChainingEnabled="False"
        ScrollViewer.IsVerticalScrollChainingEnabled="False"
        ScrollViewer.VerticalScrollBarVisibility="Disabled"
        ScrollViewer.VerticalScrollMode="Disabled">
    </GridView>

This is really just your normal GridView with an item template selector.

Now we will look at our main page which will be holding our Listview with an ItemTemplateSelector which will select if your items will be displayed Horizontally or Verticaly.

 <ListView
            Grid.Row="0"
            Margin="0,0,0,0"
            HorizontalAlignment="Stretch"
            VerticalAlignment="Stretch"
            IsTabStop="False"
            ItemTemplateSelector="{StaticResource KeySegementTemplateSelector}"
            ItemsSource="{Binding MyData}"
            ScrollViewer.VerticalScrollBarVisibility="Auto"
            ScrollViewer.VerticalScrollMode="Enabled"
            SelectionMode="None"
            ShowsScrollingPlaceholders="False"
            VirtualizingStackPanel.VirtualizationMode="Recycling"
            Visibility="Visible" />


Now we need to create some data, first we will start by creating 2 lists. One that will hold our list of Circles and the second one that will hold our list of Squares:

 //circle list
 var CircleList = new List<SmallItemViewModel>();

//square list
var SquareList = new List<SmallItemViewModel>();

Next we will need to populate these 2 lists:

for (int i = 0; i < 10; i++)
{
     CircleList.Add(new SmallItemViewModel(string.Format("title circle {0}", i ), ItemTemplateType.CircleUserItem));
   
     SquareList.Add(new SmallItemViewModel(string.Format("title square {0}", i), ItemTemplateType.SquareUserItem));
}

Now we create another list that will hold the Segements and their data.

//horizontal // vertical  
MyData = new ObservableCollection<BaseSegementEntityViewModel>();

now we populate this list:
MyData.Add(NeonExploreTemplateEngine(SquareList, SegmentType.HorizontalSegment));        
MyData.Add(NeonExploreTemplateEngine(CircleList.Take(3).ToList(), SegmentType.VerticalSegment));
MyData.Add(NeonExploreTemplateEngine(CircleList, SegmentType.HorizontalSegment));
           
Here is the full code:


private async Task Init()
        {
            //horizontal // vertical  
            MyData = new ObservableCollection<BaseSegementEntityViewModel>();

            //circle list
            var CircleList = new List<SmallItemViewModel>();

            for (int i = 0; i < 10; i++)
            {
                CircleList.Add(new SmallItemViewModel(string.Format("title circle {0}", i ), ItemTemplateType.CircleUserItem));
            }

            //square list
            var SquareList = new List<SmallItemViewModel>();

            for (int i = 0; i < 10; i++)
            {
                SquareList.Add(new SmallItemViewModel(string.Format("title square {0}", i), ItemTemplateType.SquareUserItem));
            }


            //data
            MyData.Add(NeonExploreTemplateEngine(SquareList, SegmentType.HorizontalSegment));        
            MyData.Add(NeonExploreTemplateEngine(CircleList.Take(3).ToList(), SegmentType.VerticalSegment));
            MyData.Add(NeonExploreTemplateEngine(CircleList, SegmentType.HorizontalSegment));
            MyData.Add(NeonExploreTemplateEngine(SquareList.Take(3).ToList(), SegmentType.VerticalSegment));
            MyData.Add(NeonExploreTemplateEngine(SquareList, SegmentType.HorizontalSegment));
            MyData.Add(NeonExploreTemplateEngine(CircleList, SegmentType.HorizontalSegment));
            MyData.Add(NeonExploreTemplateEngine(CircleList.Take(3).ToList(), SegmentType.VerticalSegment));

        }

        public BaseSegementEntityViewModel NeonExploreTemplateEngine(List<SmallItemViewModel> item, SegmentType type)
        {
            if (type == SegmentType.HorizontalSegment)
            {
                return new HorizontalSegmentViewModel(item);
            }
            else
            {
                return (new VerticalSegmentViewModel(item));
            }          
        }


And here is what we would get:



In the same Listview you will have elements position Vertically and Horizontally at the same time, also you will be able to change your design on the fly depending on the data that you send to your application.  

We can quickly see how powerful it can be to design an application that relies on ItemTemplateSelector , for example this could mean that if you didn't want to use a certain template anymore you would not need to update the application but just the API that the application is using. This could be a great time saver! 

You could also do some form of A/B testing, if for example you had multiple Circles Template you could try different templates to see which templates your user will more likely click on!

I hope that this will help you build better apps!

Happy Coding!
You can find the full sample here.





mercredi 21 février 2018

WebView using InvokeScriptAsync and calling a method and passing the parameters using JSON.parse [WebView,C#]

Calling a method on your WebView is simple just call the WebView.InvokeScriptAsync( method , param) (more information on MSDN) and you are good to go.  However imagine if you need to send json in the param, how do you send it?


This is the issue that we are going to have a quick look in the post, here is an example in of a javascript call that needs to be called with JSON data.  Looking at the MSDN documentation  , we can see that we need to surrond ou json string with JSON.parse({0}), in the params value in the InvokeScriptAsync.

Here is an example of the method name 'eval' and the javascript parameter that I would like to send to the UWP WebView:

 loadUrl javascript:object.load('xsazphf',
JSON.parse('{  
   "props":{  
      "param":{  
         "action":{  
            "gesture":"click",
            "id":"63825b13-dff5-4f45-81e9-a9dbe2aca39b"
         },
         "screen":{ 
            "id":"662dfa95-6ad2-43c1-b403-4e9a4118be4c"
         },
         "section":{  
            "id":"2bcd2be7-9c10-49e9-b71e-b77dee17c7fb",
            "index":1
         }
      }
   }
}'))

All in all,the json string that we want to pass to our javascript object needs to be wrapped in JSON.parse('{0}')).  This will allow the javascript to understand that the data that we are passing is JSON.

When we are building our string to call with the eval function in javasciprt  we will need to have some like this : myJsObject.MyMethode(Paramater1, ,JSON.parse("MyJSONStringFormat")) , when using StringBuilder we just need follow the pattern above.

Here is the code that will help you pass the correct string to your webview:

        public async void CallPlayerMethod(string method, string param, string json)
        {
            StringBuilder builder = new StringBuilder();
            builder.Append("myJSObject.");
            builder.Append(method);
            builder.Append(string.Format("('{0}'", param)) ;
            builder.Append(string.Format(",JSON.parse('{0}'))", json));  
// old
            //builder.Append('(');
            //builder.Append("'" + param + "'");
            //builder.Append(",JSON.parse('" + json + "')");
            //builder.Append(')');
//call webview CallEvalWebviewMethod(builder.ToString()); } private async void CallEvalWebviewMethod(string callMethod) {
            List<string> callingJsMethod = new List<string>();
            callingJsMethod.Add(callMethod);

            try
            {
                await MyWebView?.InvokeScriptAsync("eval", callingJsMethod);
            }
            catch (Exception e)
            {
                //silent fail
            }
        }

You can find my sample here
Happy coding





lundi 19 février 2018

Building a Placeholder Loading UI like Facebook using only XAML for your UWP application [XAML,C#,Composition]

Building beautiful native UI is very important, and keeping your users informed of what is going in the app is even more important.

We are going to look at creating a placeholder loading control that looks like what facebook is using in its application.

Here is a static version of the loading control:


Here is what we could do if we add some animation using composition.

It is super important to remember that the loading animation should not hide or distract the user from using y our application, the loading animation should just be there to help your user understand that they must wait a bit for the loading to end.

For this example we will be build 2 different UI loaders to show that data is being loaded, here is what the placeholders will have to show that they are loading:



Here is an example of what we want to do:


You have two options either we have a control with a shimmer over to simulate that something is loading or we just have a static rectangle (or grid) with a background color.   If you only want to use the backgroudn color you can look at the RectangleNoShimmerControl.xaml file, if you do want the shimmer keep on reading =).

First we are going to create a RectangleControl UserControl that will hold a ContentControl and a StackPanel with a FontIcon.

The ContentControl with its LinearGradientBrush is what will allow you have the gradient effect when we move the element, in the samlpe you can change: 
<GradientStop Offset="0.5" Color="#dcdcdc" />
by
<GradientStop Offset="0.5" Color="Red" />

which will give you this for example:

Next we will need to add the animation on the content control, we need something to move on the X axis, so using a DoubleAnimationUsingKeyFrames  and targeting  CompositeTransform.TranslateX  we will be able to do this.

<Storyboard>
    <DoubleAnimationUsingKeyFrames
            EnableDependentAnimation="True"
            RepeatBehavior="Forever"
Storyboard.TargetName="contentControl" Storyboard.TargetProperty="(Control.Foreground).(Brush.RelativeTransform).(CompositeTransform.TranslateX)"> <EasingDoubleKeyFrame KeyTime="0" Value="-1" /> <EasingDoubleKeyFrame KeyTime="0:0:1.5" Value="1" /> </DoubleAnimationUsingKeyFrames> </Storyboard>

We are going to nest our Storyboard inside a <Grid.Triggers> =>        <EventTrigger RoutedEvent="Grid.Loaded"> => <EventTrigger.Actions> which will allow us to start the animation when the Grid is loaded.

Here is the full XAML code for the page:

    <UserControl.Resources>         
        <Color x:Key="EmptyStateLightgray">#ebebeb</Color>
        <Color x:Key="EmptyStatebackground">#f7f7f7</Color>
        <SolidColorBrush x:Key="EmptyStateColorBrush" Color="{StaticResource EmptyStateLightgray}" />
    </UserControl.Resources>

     <Grid>
        <Grid.Triggers>
            <EventTrigger RoutedEvent="Grid.Loaded">
                <EventTrigger.Actions>
                    <BeginStoryboard>
                        <Storyboard>
                            <DoubleAnimationUsingKeyFrames
                                EnableDependentAnimation="True"
                                RepeatBehavior="Forever"
                                Storyboard.TargetName="contentControl"
                                Storyboard.TargetProperty="(Control.Foreground).(Brush.RelativeTransform).(CompositeTransform.TranslateX)">
                                <EasingDoubleKeyFrame KeyTime="0" Value="-1" />
                                <EasingDoubleKeyFrame KeyTime="0:0:1.5" Value="1" />
                            </DoubleAnimationUsingKeyFrames>
                        </Storyboard>
                    </BeginStoryboard>
                </EventTrigger.Actions>
            </EventTrigger>
        </Grid.Triggers>
<ContentControl x:Name="contentControl" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" HorizontalContentAlignment="Stretch"> <ContentControl.Foreground> <LinearGradientBrush StartPoint="0.5,0" EndPoint="0.5,1"> <LinearGradientBrush.RelativeTransform> <CompositeTransform CenterX="0.5" CenterY="0.5" Rotation="95" /> </LinearGradientBrush.RelativeTransform> <GradientStop Offset="0" Color="{StaticResource EmptyStateLightgray}" /> <GradientStop Offset="0.5" Color="#dcdcdc" /> <GradientStop Offset="1" Color="{StaticResource EmptyStateLightgray}" /> </LinearGradientBrush> </ContentControl.Foreground> <StackPanel HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Background="{StaticResource EmptyStateColorBrush}"> <FontIcon FontSize="800" Glyph="&#xE009;" /> </StackPanel> </ContentControl> </Grid>


Now that we have our Facebook like shimmer animation we will create our loading states using that UserControl. Now we are going to create another UserControl to resemble something like this:
To create this in XAML I will use a Grid which will use multiple RowDefinitions , which gives us this:


<Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="120" />
            <RowDefinition Height="15" />
            <RowDefinition Height="20" />
            <RowDefinition Height="15" />
        </Grid.RowDefinitions>

        <local:RectangleControl
            Grid.Row="0"
            Width="290"
            Margin="0"
            />
        <local:RectangleControl
            Grid.Row="1"
            Width="60"
            Margin="0,5,0,0"
            />
        <local:RectangleControl
            Grid.Row="2"
            Width="210"
            Margin="0,9,0,0"
            />
        <local:RectangleControl
            Grid.Row="3"
            Width="170"
            Margin="0,5,0,0"
            />
    </Grid>

You can find my code sample here.
Happy coding 



vendredi 16 février 2018

Return of development expirence on using XAMARIN for Tizen TV [XAML,C#,TIZEN]

My return of Experience on the 16th of February 2018
Long story short: I have been playing around for a while now with Xamarin for Tizen TV, and this will be great for us XAML/.NET developer when:

  1. It is fully finished and compatible with Tizen TV,  Tizen 4 Tv are released to the public
  2. that the emulator really works "correctly"
  3. the debugger from Visual Studio actually works
  4. that you can create custom controls to make beautiful UI

I am not in the habit of writing negative posts and this is not one, so let me explain why we should hold off just a bit before we really start using this:
  • After having played with the framework and after feed back from Samsung and having spoken with a developer from the Xamarin porting team from Samsung, as of today Xamarin for Tizen is more in beta IMO then in release even thought the road map says that it is finished:

 The framework is working however there as still a lot of missing pieces.  From what I am told 2018 will allow Samsung to finish developing/debug and see who is interested in using Xamarin for Tizen TV.
  • The Visual Studio Debugger is not working as it should, for example if you set a break point and launch the application on the emulator for Tizen TV I would be hit by one of the following issues either the app will crash, visual studio will crash or when you do hit the break point you will not be able to see the value in you objects using quick watch. (When using the same code FORMS code for UWP, Android or IOS the debugger worked perfectly)
As you can see here:

  • Another issue that Samsung has informed me is that the Emulator for Tizen 4 Tv, is not the best way to develop for their TVs they very strongly recommend that you buy a Tizen 4 TV, the Tv will be updated with the latest firmware and OS.  The emulator doesn't have the same performance as a TV, it has more limitation because it is being vitalized.
  • Currently Rendering custom controls on Tizen with Xamrin is not working which can also be issue as you can imagine. In my case I was trying to create a listview that we holding another listview horizontally, this worked fine on the UWP app but nothing happened of the Tizen TV App. 

All in all Samsung has a little way to go to finish the Tizen APIs for Xamarin and to finish polishing their code before we (developers) can start building awesome Tizen TV application =).  From what I am told the Xamarin porting team at Samsung are working at 100% to fix everything and I am sure that within a few months everything will be finished.






.

lundi 5 février 2018

Reactive UI with your UWP applications Example II (using your ViewModel) [XAML,C#,RxUI]

In the previous example we saw how to us Reactive UI on a auto complet, in this example we will see another example of how to Reactive UI on a ViewModel in your UWP application.

Here we will connect an property to a Service and a SelectedItem using ReactiveCommand.

First we will create a small class:

    public class MyItem
    {
        public int id { get; set; }
        public string name { get; set; }
    }


Next we will create a small service:

    
    public class MyItemService
    {
        public IObservable<IEnumerable<MyItem>> GetUpcomingItems(int index)
        {
            //get your items here
            //do your http call here
            return null;
        }
    }


Here is my ViewModel:


    public class MainViewModel : ViewModelBase
    {
        //My item loader
        public ReactiveCommand<int, IEnumerable<MyItem>> LoadMyItems
        {
            get;
        }

        //my selected item
        MyItem m_selectedItem;
        public MyItem MySelectedItem
        {
            get { return m_selectedItem; }
            set { RaisePropertyChanged("MySelectedItem"); }
        }

        //my service
        private MyItemService myItemService;

        public MainViewModel()
        {
            //init the serivce
            myItemService = new MyItemService();

            //getting items using the CreateFromObservable
            LoadMyItems = ReactiveCommand
                .CreateFromObservable((int index) =>
                    myItemService.GetUpcomingItems(index));

            //when the vm is activated bind the properties
            this.WhenActivated((CompositeDisposable disposables) =>
            {
                //init
                SelectedItem = null;

                //when SelectedItem has a value go to page
                this
                    .WhenAnyValue(x => x.SelectedItem)
                    .Where(x => x != null)
                    .Subscribe(x => LoadSelectedPage(x))
                    .DisposeWith(disposables);          
            });
        }


        public void LoadSelectedPage(MyItem item)
        {
            //load this page
        }
    }

The interesting part are the loading of the items using ReactiveCommand.CreateFromObservable this will start the loading once this property is binded to a ListView or GridView.

Next the SelectedItem and the this.WhenAnyValue(x => x.SelectedItem) will allow me to navigate or perform an action when this property has a value.

As you can see, Reactive UI  allows us to bind events in the ViewModel, of course you could have used ICommand or RelayCommand but I find Reactive UI to be a much more elegant solution!

Happy coding!






mercredi 10 janvier 2018

[Return of experience] UWP WebView and playing with it http headers to change the user-agent [C#,WebView,HTTP]

Over the years I have had the opportunity to work a lot with the UWP Webview on Windows Mobile (sic), Desktop, Xbox and HoloLens.

This has given me the opportunity to really see what happens when you play with the user-agent of the WebView.  One would imagine that even if the WebView was used on Desktop / Mobile and Xbox that even if you had used the same user agent for all three platform that everything would work.  This will probably be the case for 90% of your HTTP calls but every now and then this will not be the case.

First a little bit of back story about why did I override the WebViews user-agent, by default it works great, however I encountered a case that when the WebView calls other urls (redirections mainly) on Desktop and Xbox the HTTP headers are lost/ not passed along. Which is why I had to set the user-agent in the first place.

The next issue that I encounter was that I was using the same user-agent on all 3 platforms Desktop/Mobile/Xbox which meant that the url that I was calling thought that for all 3 platforms I was a desktop.  The url that I calling was serving a video media element and depending on which platforms it was being called it would either be using the media stack from the device or the media stack for the webview.

Here are 2 user agents for Xbox One and Windows 10 Desktop devices:
Xbox One
Mozilla/5.0 (Windows Phone 10.0; Android 4.2.1; Xbox; Xbox One) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2486.0 Mobile Safari/537.36 Edge/13.10586
The issue that I was having with this user-agent is that on our servers the app was serving the video on the wrong  media stack again. This was because on the Xbox the application would think that it was being run on a Windows Mobile wish is not great. In the end i ended up edit the string as follows "(Windows NT 10.0; Win64; x64; Xbox; Xbox One)" instead of "(Windows Phone 10.0; Android 4.2.1; Xbox; Xbox One)".

Windows 10-based PC using Edge browser
Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36 Edge/12.246

In the end everything ended up working as expected and the Media stack of the device was used and not the WebViewmedia stack.  This however was only achieved by being able to send the correct user-agent to the WebView so that the url called would then give back the correct information.

Happy coding,

Website with all lots of user agents: https://deviceatlas.com/blog/list-of-user-agent-strings