Application Insights for Xamarin- and UWP apps with TinyInsights

About two and a half years ago I created a library with the name TinyInsights with the idea to abstract away the underlying provider for diagnostics and analytics. The reason was that I wanted to make it possible to change the provider without that it affected my code more than in the initial setup of the app. Because diagnostics- and analytics services have a tendency to come and go, for example, Xamarin Insights and HockeyApp are no longer with us. Instead, we now have AppCenter, which also was my first provider for TinyInsights. I also wanted to make it possible to use multiple providers at the same time, because I have worked with apps where business analysts want the data to be in Google Analytics and developers want another service because other services are better for finding errors in apps.

My default provider has been AppCenter the last years, but recently I have missed a couple of important features and you can not analyze the data any deeper. You can export the data to Application Insights and then you can create deeper reports etc. But the way AppCenter store data make some questions harder to make in a good way. For example, if you want to track page views, you have to do that as an event. Application Insights is not built to handle page views that way, because it has real support for page views. AppCenter also lacks the future of tracking dependencies.

So what I decided to do was to create a new provider to TinyInsights with support for Application Insights. But I still using AppCenter for crashes and errors, because it also supporting me to upload symbols to it and Application Insights have no good way to distinguish between an error and a crash. But when I am logging crashes to Application Insights I am setting a custom property with the name "IsCrash" to "true".

I have implemented TrackDependency to all providers, but for AppCenter it only saves all data as custom properties and there is no good way to visualize them, but the data is there if you want to export it to your own visualizer.

Below I have written a short introduction about how to get started with the ApplicationInsightsProvider and TinyInsights in general.

Initializing Application Insights Provider

When initializing TinyInsights you need to specify what provider or providers you want to use. For Application Insights, you only need to give it the IntrumentationKey. If you don't pass different keys for different platforms all data will be collected together and not as in AppCenter where you create one app per platform.

var appInsights = new ApplicationInsightsProvider("{InstrumentationKey}");
var appCenter = new AppCenterProvider("{keyForIOS}", "{keyForAndroid}", {keyForUWP});
appCenter.IsTrackPageViewsEnabled = false;
appCenter.IsTrackEventsEnabled = false;
appCenter.IsTrackDependencyEnabled = false;
 
TinyInsights.Configure(appCenterProvider, applicationInsightsProvider);

Handling exceptions

To track exceptions/errors, just use the TrackErrorAsync method. Crashes will automatcially be tracked and sent to Application Insights next time the user is starting the app.

catch(Ecception ex)
{
     await TinyInsights.TrackErrorAsync(ex);
}
 
//with properties
var properties = new  Dictionarty<string, string>();
properties.Add("MyFirstProperty", "MyFirstValue");
properties.Add("MySecondProperty", "MySeconndValue");
 
catch(Ecception ex)
{
     await TinyInsights.TrackErrorAsync(ex, properties);
}

Tracking dependencies

There are a two of ways to track dependencies with TinyInsights.
The first and the basic method is TrackDependencyAsync, and is also used in the background by the other way to do it.

var startTime = DateTimeOffset.Now;
 
var success = await GetData();
 
var duration = DateTimeOffset.Now - startTime
 
await TinyInsights.TrackDependencyAsync("api.mydomain.se", "https://api/mydomain.se/v1/data/get", startTime, duration, success);

The second way is to create a TinyDependency object that handles most of the tracking for you. You will do that by just by wrapping your code for the dependency in a using statement.

using (var tracker = TinyInsights.CreateDependencyTracker("api.mydomain.se", "https://api/mydomain.se/v1/data/get"))
{
     await GetData();
}

If the dependency succeded that is fine, but if it not you need to handle that on your own, using the Finish method of the TinyDependency object.

using (var tracker = TinyInsights.CreateDependencyTracker("api.mydomain.se", "https://api/mydomain.se/v1/data/get"))
{
     try
     {
          var repsonse = await GetData();
 
          if(!response.IsSuccessStatusCode)
          {
               await tracker.Finish(false, (int)response.StatusCode);
          }
     }
     catch(Exception ex)
     {
          tracker.Finish(false, ex);
     }
}

Tracking page views

To track page views, just use the TrackPageViewAsync method.

await TinyInsights.TrackPageViewAsync("SuperCoolView");
 
//with properties
var properties = new  Dictionarty<string, string>();
properties.Add("MyFirstProperty", "MyFirstValue");
properties.Add("MySecondProperty", "MySeconndValue");
 
await TinyInsights.TrackPageViewAsync("SuperCoolView", properties);

Tracking events

To track events, just use the TrackEventAync method.

await TinyInsights.TrackEventAsync("SuperCoolEvent");
 
//with properties
var properties = new  Dictionarty<string, string>();
properties.Add("MyFirstProperty", "MyFirstValue");
properties.Add("MySecondProperty", "MySeconndValue");
 
await TinyInsights.TrackEventAsync("SuperCoolEvent", properties);

Feedback

If you have any feedback, please create an issue on GitHub. You will also be welcome to contribute to the library with improvments or/and other providers.
 

Using the symbol enumeration for icons/symbols in Windows 10 universal app

If you are developer and not a graphic artist it is always a challange to find/create icons. Windows 10 has a symbol enumeration that you can use that contains the most common icons/symbols (you find the complete list of symbols here: https://msdn.microsoft.com/en-us/library/windows/apps/windows.ui.xaml.controls.symbol.aspx).

The not only look good they are easy to use to, just use the SymbolIcon element. The code below shows a settings icon.

<SymbolIcon Symbol="Setting" />

If you want to change color on the icon just use the Foreground attribute.

<SymbolIcon Foreground="Gold" Symbol="Favorite" />

The symbols is based on the "Segoe MDL2 Assets" font (You can read more about it here: https://msdn.microsoft.com/en-us/library/windows/apps/jj841126.aspx).

Symbols in a Windows 10 app

Symbols in a Windows 10 app

If you want to read more about Windows 10 development I have created a list with all my Windows 10 blog posts, http://danielhindrikes.se/windows-10/, more will be added.

Pivot in Windows 10 universal apps

If you are a Windows Phone developer I guess you are familiar with the Pivot control. In Windows 10 the pivot control has taken the step into desktop apps.

Pivot is a easy way to navigate between pages in your app. To navigate to an other page in the control just click the header or swipe left or right.
 

Pivot

Pivot in a desktop app

Pivot

Pivot on phone app




The pivot control is easy to implement, for every page you want to add to the Pivot control you just add a PivotItem as in the code below.

<Pivot Title="Pivot sample">
            <Pivot.Items>
                <PivotItem Header="Pivot 1">
                    <Grid>
                        <TextBlock Text="Content of pivot 1" />
                    </Grid>
                </PivotItem>
                <PivotItem Header="Pivot 2">
                    <views:MyView />
                <PivotItem Header="Pivot 3">
                    <Grid>
                        <TextBlock Text="Content of pivot 3" />
                    </Grid>
                </PivotItem>
            </Pivot.Items>
        </Pivot>

Customize the Pivot
Customizations of Pivot is done with DataTemplates. The Pivot control has a property called TitleTemplete for the template for the title of the pivot and a property called HeaderTemplate for the headers of the pivot items. Templates can be defined in resources for the page or for the application (in App.xaml). The template can only have one child element, but it could be for example a StackPanel or a Grid if you want to add more than text in your headers. For example if you will have ha more tab like experience with icons and text as you may have seen in some apps.

<Page.Resources>
        <DataTemplate x:Key="PivotHeader">
                <TextBlock FontSize="18" Foreground="Blue" Text="{Binding}" />
        </DataTemplate>
</Page.Resources>

Next step is to set the new template to the Pivot.

 <Pivot HeaderTemplate="{StaticResource PivotHeader}" Title="Pivot sample">

You can also define a style in App.xaml if you want it to be on all Pivots in the app.

 <Application.Resources>
        <Style TargetType="Pivot">
            <Setter Property="HeaderTemplate">
                <Setter.Value>
                    <DataTemplate>
                        <Grid>
                            <TextBlock FontSize="18" Foreground="Blue" Text="{Binding}" />
                        </Grid>
                    </DataTemplate>
                </Setter.Value>
            </Setter>
        </Style>
 
The code examples above is for PivotItem headers, if you want it to be for the Pivot title, just change HeaderTemplate to TitleTimplate.
</Application.Resources>

The complete code can be found on GitHub, https://github.com/dhindrik/windows10samples

If you want to read more about Windows 10 development I have created a list with all my Windows 10 blog posts, http://danielhindrikes.se/windows-10/, more will be added.

SplitView in Windows 10 universal app

One of the new controls in the SDK for Windows 10 universal apps is the SplitView control. I guess you have seen the apps with the hamburger menu. If you want to create an app with a hamburger menu I recommend you to use SplitView.


SplitView

The control is splitting the views/pages in two parts, the left one is called Pane and can be used for menus, for example. The Pane has for different display modes.

Overlay
When the pane is open it will be shown over the main content of the page.

CompactOverlay
Is shown the same way as overlay, but with thinner. I recommend yo just show icons in this mode.

Inline
When the pane is open it will be beside the main content, see the screenshot above.

CompactInline
Inline also has a compact mode as with the CompactOverlay I recommend you to just use icons when showing the pane in CompactInline

<SplitView Name="Split" OpenPaneLength="200" IsPaneOpen="False" DisplayMode="Overlay">
            <SplitView.Pane>
                <StackPanel Padding="10">
                    <TextBlock Text="Item 1" />
                    <TextBlock Margin="0,10" Text="Item 2" />
                    <TextBlock Text="Item 3" />
                    <TextBlock Margin="0,10" Text="Item 4" />
                </StackPanel>
            </SplitView.Pane>
            <Grid>
                <Grid.RowDefinitions>
                    <RowDefinition Height="50" />
                    <RowDefinition Height="*" />
                </Grid.RowDefinitions>
                <Button Background="White" Click="Button_Click">
                    <StackPanel>
                        <Rectangle Height="3" Width="20" Fill="Black" />
                        <Rectangle Margin="0,5" Height="3" Width="20" Fill="Black" />
                        <Rectangle Height="3" Width="20" Fill="Black" />
                    </StackPanel>
                </Button>
 
                <TextBlock Margin="10" Grid.Row="1" Text="Main content here" />
 
            </Grid>
        </SplitView>

The default placement of the pane is to left, but you can also have it on the right side. Just set the PanePlacement property to right.

 <SplitView Name="Split" PanePlacement="Right" OpenPaneLength="200" IsPaneOpen="False" DisplayMode="Inline">

The complete code can be found on GitHub, https://github.com/dhindrik/windows10samples

If you want to read more about Windows 10 development I have created a list with all my Windows 10 blog posts, http://danielhindrikes.se/windows-10/, more will be added.

Using compiled bindings in your Windows 10 universal app

One of the news in the Windows 10 SDK is that you can use compiled binding. In pre Windows 10 bindings was created in run time. When you're building your windows universal app for windows 10 you can created bindings in compile time. This to boost the performance of the bindings, compiled bindings will make the page load much faster. This blog post will introduce you with the basics of compiled bindings.

To create a binding that will be created in compile time you will use x:Bind instead of Binding to create the binding.

      <TextBlock Text="{x:Bind Title}" />

One big difference against is that the binding will not be to DataContext, it will be to the page. If the code above should work you have to create a Title property in the code behind file. If you don't do that you will get a error when you compiling your app. The reason to to bind to the actuall page instead of DataContext is that DataContext is of type object and the compiler will not know what you will assign to it during run time. Because you binding to the actual page it is also possible to bind directly to other controls on your page.

If you using a binding in a data template you have to specify data type for the data template with x:DataType as in the code below. Don't forget to declare the namespace for your data type. In this example I have created a property in my code behind file called ViewModel that has a Items property that I binding to the ItemsSource of the ListView.

<ListView ItemsSource="{x:Bind ViewModel.Items}">  
            <ListView.ItemTemplate>
                <DataTemplate x:DataType="model:ItemModel">
                        <TextBlock Text="{x:Bind Title}" />
                    </Grid>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>

The code behind can looks like the code below. In this example DataContext is set when the view is created and the ViewModel will have a method for loading data.

public sealed partial class ItemsView
{
        protected ItemsViewModel ViewModel { get { return DataContext as ItemsViewModel; } }
 
        public ItemsView()
        {
            this.InitializeComponent();
            DataContextChanged += ItemsView_DataContextChanged;
        }
 
        private async void ItemsView_DataContextChanged(FrameworkElement sender, DataContextChangedEventArgs args)
        {
            if(ViewModel != null)
            {
                await ViewModel.LoadData();
            }
        }
}