Tag Archives: open source

Windows App Studio being sunset

We want to directly thank each of the users of Windows App Studio and we want to be sure you have a smooth transition off when Windows App Studio service ends on December 1, 2017. What will happen to App Studio afterwards? Windows Template Studio is the evolution of Windows App Studio. We took our learnings from the code generation engine and the existing wizard to provide a strong foundation for our code generation and developer experience in Windows Template Studio. Best of all, it is open source over at http://aka.ms/wts.

Details on the transition

Windows App Studio has been a free, online app creation tool that allowed enthusiasts and developers to quickly build complete Windows Universal Apps. Applications using Windows App Studio then could also be downloaded, extended and compiled with Visual Studio and submitted to the Windows Dev Center.

Any user of Windows App Studio will need to download your projects and data prior to December 1, 2017.

We’ll provide multiple email communications with users between now and December 1, 2017, but we want to be upfront and clear that you have a path forward to continue building great apps for Windows 10. We’re doing a phased approach with the sun setting process. Here are the three critical dates:

  • July 15, 2017
    • Only existing users can sign in
    • Finished application projects can be downloaded
    • No new dynamic collections data sources allowed to be created
    • Dynamic data will be allowed to be downloaded with a migration path provided
  • September 15, 2017
    • Application editor will stop working
    • Dynamic collections API will stop providing data to your existing applications
  • December 1, 2017
    • Windows App Studio will be shut down

Once again, we want to thank each of the users of Windows App Studio, and we view the smooth transition for users critical.

Toolkits, Toolkits, Toolkits!

As a UWP developer, you have many options to help build your application quickly and reliably. In fact, there are so many options that you may feel like you can choose only one. Luckily, that’s not the case, and many toolkits complement each other in various ways.

Today, we’ll talk about two open source toolkits:

Both are open source, but each has different strengths. These two particular toolkits can bring tools and controls for a variety of application scenarios. Let’s start by introducing the toolkits and how they can help.

UWP Community Toolkit

The UWP Community Toolkit is the ultimate collaboration between Microsoft and the UWP developer community. With dozens of features such as helper functions, custom UI components, animations and app services, the UWP Community toolkit is a great time saver and can bring your application to the next level.

The toolkit has had 12 releases so far and is currently on v 1.4 (released on April 3, 2017). It has more than 80 contributors, with thousands of commits, and the community is constantly working on improvements. Conveniently, it’s broken up into several nuget packages so you can pick and choose exactly what you need.

Examples of this toolkit’s power can be found in the Services namespace, where you can easily interact with social media services with as little as two lines of code.

Here’s an example of getting a Twitter user’s timeline:


TwitterService.Instance.Initialize("consumer-key", "consumer-secret", "callback-uri");
ListView.ItemsSource = await TwitterService.Instance.GetUserTimeLineAsync("user-screenname", 50);

You can find a full demo application here in the source code or here in the Windows Store. Go here to see a full list of the available features (controls, helpers, etc.) and go here to find the documentation.

Telerik UI for UWP

Telerik UI for UWP, from Progress Software, is a recently open sourced toolkit that contains an amazing set of Line of Business (LOB) controls with which you can create native, business-focused, UWP applications. With controls such as DataGrid and RadListView, the Telerik UI provides the powerful sorting, grouping and editing experiences you might expect from a desktop application, as well as rich data visualization experiences with controls such as Charts, Gauges and BulletGraphs.

We recommend you check out the Customer Database Example application here on GitHub to see the DataGrid in action, as well as the SDK Examples app here. You can see a full list of available controls here and find the documentation here (if you’re looking for a little extra help, Progress Software also offers professional support in the premium package).

An example of this toolkit’s power is the RadDataGrid. With one line of code you get a bunch of out-of-the-box features like grouping, sorting and filtering.

You can install UI for UWP in your application using the nuget package or build from the source directly. If you would like to read more about why Progress Software open sourced Telerik UI for UWP, we recommend you check out this great article.

Contributing

If you’re a developer who likes contributing to GitHub repos and giving back to the community, or if you have ideas to make things better for other developers, both toolkits accept pull requests and each has its own contribution guidelines (here for UWP community toolkit and here for Telerik UI for UWP).

Wrapping up

Both toolkits complement each other. You can use them side by side in your application to bring the user a delightful, yet powerful, experience in your UWP application. With dozens of UI controls, helpers, services and more, you can get your UWP app to market faster and with more confidence than ever. We look forward to seeing your UWP Community Toolkit and UI for UWP powered applications in the Windows Store!

Resources

Announcing Windows Template Studio

Today, we are pleased to announce the next evolution in your File New Universal Windows Platform app in Visual Studio – Windows Template Studio. Windows Template Studio addresses a top community ask in our developer survey to make it easier and provide guidance to create new projects that target the Universal Windows Platform. In this post, we’d like to spend a few minutes introducing Windows Template Studio and show you how it works.

Windows Template Studio uses a dev-friendly wizard to get your UWP apps to F5 in no time, bringing together the pages, frameworks and features that you want. Our wizard walks developers through four steps to quickly scaffold a new UWP app:

  1. Project Type: Select between standard layouts and predefined controls.
  2. Framework selection: Select the structure of your UWP app with in-house and third-party support.
  3. App pages: Select which pages that make sense for the app, that you are trying to create.
  4. App features: Easily add features such as background tasks with one click.

Furthermore, we’re open-sourcing Windows Template Studio, welcoming UWP devs to take the generation engine further – adding additional capabilities and app pages, improving the implemented best practices and patterns – and encouraging UWP devs to make the engine their own – tailoring it to their company’s specific needs.

Windows Template Studio is the evolution of Windows App Studio. App Studio was a free, online app creation tool that allowed developers and enthusiasts to quickly build Windows Universal Apps. We are taking our learnings from the code generation engine and the existing wizard to provide a strong foundation for our code generation and developer experience in Windows Template Studio.

A Lap Around Windows Template Studio

We kick off Windows Template Studio by creating a new UWP app project. In the Visual Studio 2017 ‘New Project’ dialog, select the Visual C# Windows Universal node.

Here you’ll see the Windows Template Studio project. Select the project type, enter in your new UWP app’s name and click ‘OK’. Windows Template Studio will now fire up and walk you through the UWP app creation wizard, step by step.

Step 1: Project Type

You begin by selecting a project type. We’ve started you with the most common types such as: blank, navigation pane and pivot and tabs.

Step 2: Framework

Once you have selected a project type, you need to select a framework. You can select from Code behind, MVVM Basic or the very popular MVVM Light.

Step 3: Pages and app lifecycle features

Once you have selected a project and framework, then it is time to add in pages and features. We’ve already added the most common pages such as Master/Detail, Settings and Web view. You can also easily add in Application Lifecycle features such as Suspend and Resume as well as Background Work and User Interaction.

Best practices and patterns

To wrap all of this up, with a couple of simple clicks, you can wire up an app that uses the Navigation Pane, MVVM Light framework, a Master Detail page and a couple of features such as suspend and resume and Azure hub notifications. You save time, your app is adhering to our design guidance and industry standard patterns and practices come free.

Below is an example of an app generated with Windows Template Studio. Again, we provide the foundation of a great UWP app and get you to F5 in a couple of clicks.

Get Started Today

Windows Template Studio v1.0 is available now and you can expect updates every 6 weeks. We have extremely easy to use instructions for installing the VS extension on our GitHub page as well. A public roadmap is currently available and we’d encourage you to check out The Tips and Tricks for UWP Developer session that was shown at Build to learn more. You can get started creating your own app in three simple steps:

  1. Download Visual Studio 2017 and select Universal Windows Platform development under Workloads.
  2. Install the Visual Studio Extension for Windows Template Studio by downloading the VSIX from the Visual Studio Gallery.
  3. Once installed, open Visual Studio 2017 and select FileNew Project→ C# → Windows Universal and you should see the new template that was just added.

And Best of All…Windows Template Studio is Open Source

Windows Template Studio is completely open-source and available now on GitHub. This project is community led and we’re very excited to already have contributions from the following community members: Matt Lacey and James Croft. We would love for you to contribute to the project and would encourage you to read our contribution guidelines for next steps.

In the spirit of being transparent, the roadmap for the next release is always available. If you have a bug that you would like to report or share a feature request, then please add it to our issue tracker.

We would love to hear how your experiences are using it and the helpfulness of the project. You can reach Clint at @clintrutkas and Michael at @mbcrump.  What are you waiting for? Go and try it out for yourself now!

Managing Windows IoT Core devices with Azure IoT Hub

Device management in Windows IoT Core

In Fall 2016, Microsoft announced Azure IoT Hub device management, providing the features and extensibility model, including an SDK for a wide range of platforms, to build robust device management solutions. With the recent release of the Windows 10 Creators Update, we are excited to announce the availability of the Windows IoT Azure DM Client Library. The open source library allows developers to easily add device management capabilities to their Azure connected Windows IoT Core device. Enterprise device management for Windows has been available for many years. The Windows IoT Azure DM Client Library makes these capabilities, such as device restart, certificate and application management, as well as many others, available via Azure IoT Hub device management.

A quick introduction

IoT devices, in comparison to desktops, laptops and phones, have in many cases a much more restricted connectivity, less local resources and in many cases no UI. Remote device management also requires devices to be provisioned for a DM service, adding another challenge to the device setup.

Azure IoT DM is designed for devices with resource and connectivity restrictions. Those devices will also use Azure IoT for their operation, so they need to be provisioned for Azure IoT. This makes Azure IoT DM a very attractive choice for remote device management for IoT devices.

Device management in Windows 10 is based on the Configuration Service Provider (CSP) model. A CSP is an interface in Windows that allows reading and modification of settings of a specific feature of the device. For example, a Wi-Fi profile can be configured with the Wi-Fi CSP, the Reboot CSP is used to configure reboot settings, and so on.

All the CSPs ultimately map into API calls, registry keys and changes in the file system. The CSPs raise the level of abstraction and offer a consistent interface that works on all editions of Windows – desktop, mobile and IoT. The Windows IoT Azure DM Client Library will use the same, proven infrastructure.

Windows IoT Core + Azure IoT Hub: Better together

Azure IoT Hub provides the features and an extensibility model that enable device and back-end developers to build robust device management solutions. Devices can report their state to the Azure IoT Hub and can receive desired state updates and management commands from the Azure IoT Hub.

Device management in Azure IoT is based on the concepts of the device twin and the direct methods. The device twins are JSON documents that store device state information (metadata, configurations and conditions). IoT Hub persists a device twin for each device that you connect to IoT Hub. The device twin contains the reported properties that reflect the current state of the device, and the desired properties that represent the expected configuration of the device. Direct methods allow the back-end to send a message to a connected device and receive a response.

The device twin and the direct methods can be used to support the business logic of your IoT solution as well as implementing the device management operations.

The Windows IoT Azure DM Client Library connects the CSP-based device management stack in Windows IoT Core with the cloud back-end based on Azure IoT Hub. The client runs on the device and translates the direct method calls and desired properties updates to the CSP calls. The client also queries the device state using the CSP calls and translates that into reported properties for the device twin in the Azure IoT Hub.

Before an IoT device can be managed through the Azure IoT Hub, it must be registered with a unique device identity and an authentication key. The authentication key needs to be securely stored on the device to prevent accidental or malicious duplication of the device identity. In Windows 10 IoT Core the key can be stored in the TPM. How this is done is described in the previous post Building Secure Apps for Windows IoT Core.

With the device provisioned with Azure IoT Hub credentials (connection information and authentication key), managing Windows 10 Core devices through Azure IoT Hub requires no additional enrollment or configuration.

In this post, we will focus mostly on the client aspects of the device management. Please refer to the general Azure IoT Hub device management documentation for a broader look at what the service provides. Below we explore how the Azure IoT Hub device twin and direct methods can be used to manage Windows IoT Core devices.

How to use the Windows IoT Azure DM Client Library

Devices connecting to Azure IoT Hub can only have one connection to the service. This means that all applications, including the DM library, must share an Azure IoT Hub connection. We will provide two sample implementations that you can use depending on if your device has other applications that will connect to the same IoT Hub, as the same device.

Standalone device management client

If your device only needs Azure IoT Hub for device management and no other application will connect to the same IoT Hub using the same Azure device ID, you can use the IoTDMBackground sample to add DM capabilities to your device.

The IoTDMBackground is a background app that can be deployed on your device. The IoTDMBackground app requires the device to be securely connected to Azure IoT. Once started, the IoTDMBackground will receive direct method calls and device twin updates from the Azure IoT Hub, and perform the device management operations.

Integrated device management client

There are scenarios where the capabilities of the standalone device management client are insufficient:

  1. Some device management, e.g. a device reboot or an application restart, might interrupt the normal operation of the device. In cases where this is not acceptable, the device should be able to declare itself busy and decline or postpone the operation.
  2. If your app is already connected to the Azure IoT Hub (for example, sending telemetry messages, receiving direct method calls and device twin updates), it cannot share its Azure identity with another app on the system, such as the IoTDMBackground.
  3. Some IoT devices expose basic device management capabilities to the user – such as the “check for updates” button or various configuration settings. Implementing this in your app is not an easy task even if you know which API or CSP you need to invoke.

The purpose of the integrated device management client is to address these scenarios. The integrated device management client is a .NET library that links to your IoT app. The library is called the IoTDMClientLib and is part of the IoTDM.sln solution. The library allows your app to declare its busy state, share device identity between itself and your app, and invoke some common device management operations.

To integrate the device management to your app, build the IoTDMClientLib project, which will produce the IoTDMClientLib.dll. You will reference it in your app.

The ToasterApp project in the IoTDM.sln solution is a sample application that uses the integrated client. You can study it and use it as an example, or if you prefer step-by-step instructions, follow the guidance below.

1. If your app is already connected to the Azure IoT Hub, you already have an instance of DeviceClient instantiated somewhere in your app. Normally it would look like this:


DeviceClient deviceClient =
   DeviceClient.CreateFromConnectionString(connectionString, TransportType.Mqtt);

2. Now use the DeviceClient object to instantiate the AzureIoTHubDeviceTwinProxy object for connecting your device management client to Azure IoT Hub:


IDeviceTwin deviceTwinProxy = new AzureIoTHubDeviceTwinProxy(deviceClient);

3. Your app needs to implement the IDeviceManagementRequestHandler interface which allows the device management client to query your app for busy state, app details and so on:


IDeviceManagementRequestHandler appRequestHandler = new MyAppRequestHandler(this);

You can look at ToasterDeviceManagementRequestHandler implementation for an example of how to implement the request handler interface.

Next, add the using Microsoft.Devices.Management statement at the top of your file, and the systemManagement capability to your application’s manifest (see ToasterAppPackage.appxmanifest file).

You are now ready to create the DeviceManagementClient object:


this.deviceManagementClient = await
    DeviceManagementClient.CreateAsync(deviceTwinProxy, appRequestHandler);

You can use this object to perform some common device management operations.

Finally, we will set up the callback that handles the desired properties updates (if your application already uses the device twin, it will already have this call):


await deviceClient.SetDesiredPropertyUpdateCallback(OnDesiredPropertyUpdate, null);

The callback will be invoked for all the desired properties – those specific to device management and those that are not. This is why we need to let the device management client filter out and handle properties that it is responsible for:


public Task OnDesiredPropertyUpdate(TwinCollection desiredProperties, 
        object userContext)
{
    // Let the device management client process properties 
    // specific to device management
    this.deviceManagementClient.ProcessDeviceManagementProperties(desiredProperties);

    // App developer can process all the top-level nodes here
    return Task.CompletedTask;
}

As an app developer, you’re still in control. You can see all the property updates received by the callback but delegate the handling of the device management-specific properties to the device management client, letting your app focus on its business logic.

To deploy and run your app, follow the instructions here.

The end-to-end solution

Obviously, the entire device management solution requires two parts – the client running on the device and the back-end component running in the cloud. Typically, your back-end component will consist of the Azure IoT Hub, which is the entry point into the cloud for your devices, coupled with other Azure services that support the logic of your application – data storage, data analytics, web services, etc.

Fortunately, you don’t need to build a full solution to try out your client. You can use the existing tools such as the DeviceExplorer to trigger direct method calls and device twin changes for your devices.

For example, to send the immediate reboot command to your IoT device, call microsoft.management.immediateReboot direct method on your device:

The device management client running on the IoT device will respond to the direct method and (unless it is in busy state) proceed with rebooting the device.

The Windows IoT Azure DM Client Library supports a variety of device management operations listed in the documentation on the GitHub site. In addition to the reboot management, application management, update, factory reset and more are supported. The list of capabilities will grow as the project evolves.

The Windows IoT Azure DM Client Library includes a sample called the DM Dashboard, which hides the implementation detail of the device management operations. Unlike the Device Explorer, you don’t need to consult the documentation and manually craft JSON to use it.

Here is how you can invoke the reboot operation using the DM Dashboard tool:

The DM Dashboard is a convenient tool for testing the client side of your device management solution, but since it operates on one device at a time, it is not suitable for managing multiple devices in a production environment.

Next steps

The Windows IoT Azure DM Client Library is still in beta phase and will continue to evolve. We’re very interested in your feedback, and we want to learn about your IoT needs. So, head over to our GitHub page, clone the repo and tell us what you think.

Real-Time Communications on the Universal Windows Platform with WebRTC and ORTC

Readers of this blog interested in Real-Time Communications are probably familiar with Google’s WebRTC project. From the WebRTC site:

“WebRTC is a free, open project that provides browsers and mobile applications with Real-Time Communications (RTC) capabilities via simple APIs. The WebRTC components have been optimized to best serve this purpose.”

At Microsoft, we’ve seen tremendous support grow for WebRTC over the past five years. One of the most pivotal uses of WebRTC is building native video chat apps, which now reach more than one billion users.

Google’s native supported platforms for WebRTC include iOS, Android and traditional Win32 desktop apps. On Windows, Microsoft Edge already supports ORTC APIs and now supports WebRTC 1.0 APIs in Insider Preview builds on Desktop devices. For example, if you need to build a WebRTC app in HTML/JS targeted at desktop browsers or desktop web apps using the Web App Template, then Microsoft Edge and Windows web platform are a great choice.

But what if you want to write in C# or C++ and run WebRTC on Xbox, HoloLens, Surface Hub or Windows Phone, or write in HTML/JS and run on Raspberry Pi? What if you are using Google’s iOS and Android libraries and need bit-for-bit compatibility for your UWP application? What if you modify WebRTC source in your application and need to use those modifications in your Universal Windows Platform (UWP) application?

To fulfill these additional scenarios, we have ported and optimized WebRTC 1.0 for UWP. This is now available as an Open Source project on GitHub as well as in binary form as a NuGet package. The project is 100 percent compatible with Google’s source, enabling scenarios such as a WebRTC video call from Xbox running UWP to a Chrome browser on the Desktop.


WebRTC ChatterBox sample running as a native Windows 10 application.

Microsoft has also long been a supporter of the ORTC APIs and we work closely with the Open Peer Foundation to ensure optimal support of ORTC  for UWP apps. ORTC is an evolution of the WebRTC API, which gives developers fine-grained control over the media and data transport channels, and uses a standard JSON format to describe peer capabilities rather than SDP, which is unique to WebRTC.

ORTC was designed with WebRTC interoperability in mind and all media is wire-compatible with WebRTC. ORTC also includes an adapter that converts SDP to JSON and exposes APIs that match WebRTC. Those two considerations make it possible for developers to migrate from WebRTC to ORTC at their own pace and enable video calls between WebRTC and ORTC clients. ORTC for UWP is available both as an Open Source project on GitHub as well as a NuGet package.

The net result of combined UWP and Edge support for WebRTC 1.0 and ORTC is that all Windows 10 platforms support RTC and developers can choose the solution they prefer.

Let’s take a look at an example from our samples repository on GitHub.

DataChannel via ORTC

The DataChannel, part of both the WebRTC and ORTC specs, is a method for two peers to exchange arbitrary data. This can be very useful in IoT applications – for example, a Raspberry Pi may collect sensor data and relay it to a Mobile or HoloLens peer in real-time.  Keep in mind that while the sample code below uses ORTC APIs, the same scenario is possible via WebRTC.

To exchange messages between peers in ORTC, a few things must happen first (see MainPage.OpenDataChannel() in the sample code):

  1. The peers must exchange ICE candidates, a successful pair of which will be used to establish a peer-to-peer connection.
  2. The peers must exchange ICE parameters and start an ICE transport session – the underlying data path used for the peers to exchange data.
  3. The peers must exchange DTLS parameters. which includes encryption certificate and fingerprint data used to establish a secure peer-to-peer connection, and start a DTLS transport session.
  4. The peers must exchange SCTP capabilities and start an SCTP transport session. At this stage, a secure connection between the peers has been established and a DataChannel can be opened.

It’s important to understand two things about the above sequence. First, the data exchanges are in simple JSON, and as long as two peers can exchange strings, they can exchange all necessary data. Second, the identification of the peers and the exchange of these parameters, called signaling, is outside of the specification of ORTC and WebRTC by design. There are plenty of mechanisms available for signaling and we won’t go into them, but NFC, Bluetooth RFCOMM or a simple TCP socket server like the one included in the sample code, would suffice.

With the SCTP transport session established, the peers can open a Data Channel. The peer initiating the call creates an instance of an RTCDataChannel() passing the SCTP transport instance, and the remote peer receives the event RTCSctpTransport.OnDataChannel.  When the remote peer receives this event, the Data Channel has been established and the peers can send messages to each other.

The code below is an excerpt from MainPage.Signaler_MessageFromPeer() in the sample code. The string message contains data received from the peer via the signaling method (in this case, the TCP socket server):


var sctpCaps = RTCSctpCapabilities.FromJsonString(message);
 
if (!_isInitiator)
{
// The remote side will receive notification when the data channel is opened.  Send SCTP capabilities back to the initiator and wait.
_sctp.OnDataChannel += Sctp_OnDataChannel;
_sctp.Start(sctpCaps);
 
var caps = RTCSctpTransport.GetCapabilities();
_signaler.SendToPeer(peer.Id, caps.ToJsonString());
}
else
{
// The initiator has received SCTP caps back from the remote peer, which means the remote peer has already
// called _sctp.Start().  It's now safe to open a data channel, which will fire the Sctp.OnDataChannel event on the remote peer.
_sctp.Start(sctpCaps);
_dataChannel = new RTCDataChannel(_sctp, _dataChannelParams);
_dataChannel.OnMessage += DataChannel_OnMessage;
_dataChannel.OnError += DataChannel_OnError;
}

When the DataChannel has been established, the remote peer receives the OnDataChannel event. The parameter data for that event includes a secure DataChannel which is open and ready to send messages:


private void Sctp_OnDataChannel(RTCDataChannelEvent evt)
{
_dataChannel = evt.DataChannel;
_dataChannel.OnMessage += DataChannel_OnMessage;
_dataChannel.OnError += DataChannel_OnError;
 
_dataChannel.SendMessage("Hello ORTC peer!");
}

You can now freely exchange encrypted messages between the peers over the DataChannel. The signaling server is no longer required and that connection can be closed.

Real-time peer connectivity in Universal Windows Applications enables many exciting scenarios. We’ve seen developers use this technology to enable a remote peer to see what HoloLens users sees in real-time and interact with their 3D environment. Xbox developers have used the DataChannel to enable low-latency FPS style gaming. And one of our close collaborators, Blackboard, relies on the technology to stream classroom video feeds and enable collaboration in their Windows app. Check out our Universal Windows samples and the library source on GitHub – we look forward to your PRs!

ICYMI – Your weekly TL;DR

What a week!

In addition to the Windows Developer Day – Creators Update that took over our feeds on Wednesday, we also released a new Insider Preview, Docs.Microsoft.com, and the Project Rome Android SDK. That’s not even all! Take a look below to see a few of the many updates from this past week.

Catch up on Windows Developer Day

Windows 10 Insider Preview Build 15031 for PC

Here’s what’s new in this Build:

  • The new Compact Overlay window
  • Dynamic Lock
  • New Share icon
  • Windows Game Bar improved full-screen support
  • Fixes and updates

Open Source UWP Controls from Telerik

We are pleased to announce that one of Microsoft’s top partners, Telerik, (now a part of Progress) has released their UI for UWP suite of offerings as an Open Source project under Apache license through the .NET foundation. This makes 20+ high-quality controls, including premier Line of Business (LOB) controls like ChartsGrid and DataForm available immediately for free and open source for UWP development.

The New & Improved Microsoft Docs

Docs.Microsoft.com is the one place for Microsoft’s technical documentation.  As part of this release, we’ve also included the docs for the UWP APIsMicrosoft Edge, and Cortana.

The New Project Rome Android SDK

Project Rome is a platform for creating experiences that transcend a single device and driving up user engagement – empowering a developer to create human-centric scenarios that move with the user and blur the lines between their devices regardless of form factor or platform.

SQLite Databases in UWP Apps

Since the Windows 10 Anniversary Update (Build 14393), SQLite has also shipped as part of the Windows SDK. This means that when you are building your Universal Windows Platform (UWP) app that runs across the different Windows device form factors, you can take advantage of the SDK version of SQLite for local data storage. This comes with some advantages…

Download Visual Studio to get started.

The Windows team would love to hear your feedback. Please keep the feedback coming using our Windows Developer UserVoice site. If you have a direct bug, please use the Windows Feedback tool built directly into Windows 10.

Windows SDK for Google Analytics

Google Analytics is one of the most popular analytics libraries for websites and mobile apps. Google Analytics is widely used to track user sessions, screen views, events, crashes, social interactions and promotional campaigns on Android and iOS.

Today, we are excited to announce that Microsoft is launching a Windows SDK for Google Analytics, providing an easy way for Windows 10 developers to access these valuable services. The SDK can be integrated into your apps via a NuGet package. The source is hosted on GitHub.

There is a C# SDK that can be used both by Universal Windows Store apps and desktop apps, and there is also a C++ WinRT component for developers targeting UWP apps written in C++ or JavaScript.  Both the C# SDK and the C++ WinRT component use the same API names, so moving between them is seamless.

The SDK is built on top of Google’s Measurement Protocol, a service that allows developers to send engagement data to the Google Analytics Servers over HTTP requests. The APIs in the Windows SDK for Google Analytics are modeled on class names and design patterns from Google’s Android SDK, to ensure maximum portability and readability for those already familiar with Google Analytics on other platforms.

Getting started

If you prefer video format, this “Getting Started with the Windows SDK for Google Analytics” demonstrates every step below.

If you prefer written form, here is how you would add the Windows SDK for Google Analytics to your project:

The following are a few examples for a C# app. (If you prefer to see examples written for JavaScript or C++, the GitHub project includes additional samples in these languages.)


var tracker =  AnalyticsManager.Current.CreateTracker("EnterYourPropertyIdHere");
            AnalyticsManager.Current.ReportUncaughtExceptions = true;

            //create a timing event 
            var screenName = "MainPage";
            TimeSpan timeSpanToLoad = TimeSpan.FromMilliseconds(237); // sample:) 
            tracker.Send(HitBuilder.CreateTiming("load", screenName, timeSpanToLoad).Build());

            //Send a page view 
            tracker.ScreenName = screenName; 
            tracker.Send(HitBuilder.CreateScreenView().Build()); 
                         
            // Send a userclick event 
tracker.Send(HitBuilder.CreateEvent("user-events-category", "click", "sharing-button", 0).Build());

            // Send a social interaction 
            tracker.Send(HitBuilder.CreateSocialInteraction("facebook", "share", "link").Build());

Roadmap, feedback and contributions

We are excited about this feature-rich first release and the new capabilities it lights up for Windows developers. We welcome your suggestions for improvements as well as reports of any issues you find on our GitHub. Finally, remember that this is an open source initiative. We invite you to contribute your own code to make the SDK even better.

Enterprise/LOB controls for UWP from Telerik are now Open Source

The Microsoft community and ecosystem has long been a great support system for our enterprise and .NET developers. Partners such as Telerik, SyncFusion, DevExpress, Infragistics, ComponentOne, ActiPro and many more have been great partners over the years, augmenting Windows and .NET technologies with custom controls and services.

We are pleased to announce that one of Microsoft’s top partners, Telerik, (now a part of Progress) has released their UI for UWP suite of offerings as an Open Source project under Apache license through the .NET foundation. This makes 20+ high-quality controls, including premier Line of Business (LOB) controls like Charts, Grid and DataForm available immediately for free and open source for UWP development.



Other interesting controls that were released include:

  • Gauge
  • BulletGraph
  • Expander
  • NumericBox
  • RadialMenu
  • HexView
  • SideDrawer
  • HubTile, and several more.

You can now access and include these controls from Telerik, which are already Visual Studio 2017 RC compatible, in your UWP app by installing the Telerik UI for Universal Windows Platform nuget package.

You can install the package via two options:

  1. In Visual Studio, right-click on your UWP project. Select “Manage NuGet Packages.” Search for and install ”Telerik.UI.for.UniversalWindowsPlatform” package
  2. Use the Package Manager Console with command : Install-Package  Telerik.UI.for.UniversalWindowsPlatform

On Windows Dev Center, you can take a look at the UWP sample app, Customer order database, for pointers on how to access and incorporate these controls in your UWP project.  It has been updated to use Telerik’s advanced Grid control.

Resources

Universal Windows Platform (UWP) docs are now on Docs.Microsoft.com

I’m excited to announce the release of Universal Windows Platform (UWP) documentation on Docs.Microsoft.com. Docs.Microsoft.com is the one place for Microsoft’s technical documentation.  As part of this release, we’ve also included the docs for the UWP APIs, Microsoft Edge, and Cortana.

Why move Windows documentation to docs.microsoft.com?

Here are the benefits for developers:

  • One place for Microsoft’s technical docs, offering you a complete and consistent content experience.
  • A modern, community-oriented approach that’s open to your contributions and feedback, and responsive design that works on your phone, tablet or PC.
  • Better content discoverability and navigation.
  • Ongoing improvements to the site, new features based on your input and updated content from community contributions. Check out the November 2016 platform update post by Jeff Sandquist to see the latest features on Docs.Microsoft.com.
  • Moving to docs will enable us open source all Windows documentation and enable community contributions.

We’re very excited to connect with our developers through Docs.Microsoft.com. Be sure to watch this short video that explains how to start contributing to the content.

Improvements to finding Windows samples

In addition to new and updated docs, we created a new Code Samples page to help you find the Windows samples on GitHub.  There are a bunch of samples already available, and we want you to be able to easily find them by narrowing down your search criteria by technology area, language and platform.

Here’s a look at the new Code Samples page:

We’ll keep updating this page, creating new samples and adding GitHub repos, so bookmark it and keep coming back.

What’s next

We want you to have a great experience with Windows docs, so we’ll keep moving more of them to Docs.Microsoft.com. This will include docs for hardware developers, desktop developers, and more. We’ll keep you posted on our progress. Feel free to give us your feedback.

Using SQLite databases in UWP apps

For many developers, SQLite has become the preferred client-side technology for data storage. It is a server-less, embedded, open-source database engine that satisfies most local data access scenarios. There are numerous advantages that come with its use, many of which are explained in the SQLite about page.

Since the Windows 10 Anniversary Update (Build 14393), SQLite has also shipped as part of the Windows SDK. This means that when you are building your Universal Windows Platform (UWP) app that runs across the different Windows device form factors, you can take advantage of the SDK version of SQLite for local data storage. This comes with some advantages:

  • Your application size reduces since you don’t download your own SQLite binary and package it as part of your application
    • Note: Microsoft.Data.SQLite (used in the example below) currently has an issue where both SQLite3.dll and WinSQLite.dll are loaded in memory whenever a .NET Native version of your application is run. This is a tracked issue that will be addressed in subsequent updates of the library.
  • You can depend on the Windows team to update the version of SQLite running on the operating system with every release of Windows.
  • Application load time has the potential to be faster since the SDK version of SQLite will likely already be loaded in memory.

Below, we provided a quick coding example on how to consume the SDK version of SQLite in your C# application.

Note: Since the Windows SDK version of SQLite has only been available since the Windows 10 Anniversary Update, it can only be used for UWP apps targeting Build 14393 or higher.

C# Example

In this example, we will build a UWP application that will allow users to input text into an app local database. The goal is to provide developers with concise guidance on how to use the SQLite binary that’s shipped as part of the Windows SDK. Therefore this code sample is meant to be as simple as possible, so as to provide a foundation that can be further built upon.

An example of the end product is shown below:

SQLite C# API Wrappers

As mentioned in the SQLite documentation, the API provided by SQLite is fairly low-level and can add an additional level of complexity for the developer. Because of this, many open-source libraries have been produced to act as wrappers around the core SQLite API. These libraries abstract away a lot of the core details behind SQLite, allowing developers to more directly deal with executing SQL statements and parsing the results.

For SQLite consumption across Windows, we recommend the open-source Microsoft.Data.Sqlite library built by the ASP.NET team. It is actively being maintained and provides an intuitive wrapper around the SQLite API. The rest of the example assumes use of the Microsoft.Data.Sqlite library.

Alternative SQLite wrappers are also linked in the “Additional Resources” section below.

Visual Studio set-up

The packages used in this sample have a dependency on NuGet version 3.5 or greater. You can check your version of NuGet by going to HelpAbout Microsoft Visual Studio and looking through the Installed Products for NuGet Package Manager. You can go to the NuGet download page and grab the version 3.5 VSIX update if you have a lower version.

Note: Visual Studio 2015 Update 3 is pre-installed with NuGet version 3.4, and will likely require an upgrade. Visual Studio 2017 RC is installed with NuGet version 4.0, which works fine for this sample.

Adding Microsoft.Data.Sqlite and upgrading the .NET Core template

The Microsoft.Data.Sqlite package relies on at least the 5.2.2 version of .NET Core for UWP, so we’ll begin by upgrading this:

  • Right click on ReferencesManage NuGet Packages
  • Under the Installed tab, look for the Microsoft.NETCore.UniversalWindowsPlatform package and check the version number on the right-hand side. If it’s not up to date, you’ll be able to update to version 5.2.2 or higher.

Note: Version 5.2.2 is the default for VS 2017 RC. Therefore, this step is not required if you are using this newest version of Visual Studio.

To add the Microsoft.Data.Sqlite NuGet package to your application, follow a similar pattern:

  • Right-click on ReferencesManage NuGet Packages
  • Under the Browse tab, search for the Microsoft.Data.Sqlite package and install it.

Code

Application User Interface

We’ll start off by making a simple UI for our application so we can see how to add and retrieve entries from our SQLite database.


<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
    <StackPanel>
        <TextBox Name="Input_Box"></TextBox>
        <Button Click="Add_Text">Add</Button>
        <ListView Name="Output">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding}"/>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
    </StackPanel>
</Grid>

There are three important parts to our application’s interface:

  1. A text box that allows us to take text from the user.
  2. A button linked to an event for pulling the text and placing it in the SQLite database.
  3. An ItemTemplate to show previous entries in the database.

Code Behind for Application

In the App.xaml.cs and MainPage.xaml.cs files generated by Visual Studio, we’ll start by importing the Microsoft.Data.Sqlite namespaces that we’ll be using.


using Microsoft.Data.Sqlite;
using Microsoft.Data.Sqlite.Internal;

Then as part of the app constructor, we’ll run a “CREATE TABLE IF NOT EXISTS” command to guarantee that the SQLite .db file and table are created the first time the application is launched.


public App()
{
    this.InitializeComponent();
    this.Suspending += OnSuspending;
    SqliteEngine.UseWinSqlite3(); //Configuring library to use SDK version of SQLite
    using (SqliteConnection db = new SqliteConnection("Filename=sqliteSample.db"))
    {
        db.Open();
        String tableCommand = "CREATE TABLE IF NOT EXISTS MyTable (Primary_Key INTEGER PRIMARY KEY AUTOINCREMENT, Text_Entry NVARCHAR(2048) NULL)";
        SqliteCommand createTable = new SqliteCommand(tableCommand, db);
        try
        {
        createTable.ExecuteReader();
        }
        catch (SqliteException e)
        {
            //Do nothing
        }
    }
} 

There are couple of points worth noting with this code:

  1. We make a call to SqliteEngine.UseWinSqlite3() before making any other SQL calls, which guarantees that the Microsoft.Data.Sqlite framework will use the SDK version of SQLite as opposed to a local version.
  2. We then open a connection to a SQLite .db file. The name of the file passed as a String is your choice, but should be consistent across all SqliteConnection objects. This file is created on the fly the first time it’s called, and is stored in the application’s local data store.
  3. After establishing the connection to the database, we instantiate a SqliteCommand object passing in a String representing the specific command and the SqliteConnection instance, and call execute.
  4. We place the ExecuteReader() call inside a try-catch block. This is because SQLite will always throw a SqliteException whenever it can’t execute the SQL command. Not getting the error confirms that the command went through correctly.

Next, we’ll add code in the View’s code-behind file to handle the button-clicked event. This will take text from the text box and put it into our SQLite database.


private void Add_Text(object sender, RoutedEventArgs e)
{
    using (SqliteConnection db = new SqliteConnection("Filename=sqliteSample.db"))
    {
        db.Open();

        SqliteCommand insertCommand = new SqliteCommand();
        insertCommand.Connection = db;
                
        //Use parameterized query to prevent SQL injection attacks
        insertCommand.CommandText = "INSERT INTO MyTable VALUES (NULL, @Entry);";
        insertCommand.Parameters.AddWithValue("@Entry", Input_Box.Text);        

try
        {
            insertCommand.ExecuteReader();
        }
        catch (SqliteException error)
        {
            //Handle error
            return;
        }
        db.Close();
    }
    Output.ItemsSource = Grab_Entries();
}

As you can see, this isn’t drastically different than the SQLite code explained in the app’s constructor above. The only major deviation is the use of parameters in the query so as to prevent SQL injection attacks. You will find that commands that make changes to the database (i.e. creating tables, or inserting entries) will mostly follow the same logic.

Finally, we go to the implementation of the Grab_Entries() method, where we grab all the entries from the Text_Entry column and fill in the XAML template with this information.


private List<String> Grab_Entries()
{
    List<String> entries = new List<string>();
    using (SqliteConnection db = new SqliteConnection("Filename=sqliteSample.db"))
    {
        db.Open();
        SqliteCommand selectCommand = new SqliteCommand("SELECT Text_Entry from MyTable", db);
        SqliteDataReader query;
        try
        {
            query = selectCommand.ExecuteReader();
        }
        catch(SqliteException error)
        {
            //Handle error
            return entries;
        }
        while(query.Read())
        {
            entries.Add(query.GetString(0));
        }
        db.Close();
    }
    return entries;
}

Here, we take advantage of the SqliteDataReader object returned from the ExecuteReader() method to run through the results and add them to the List we eventually return. There are two methods worth pointing out:

  1. The Read() method advances through the rows returned back from the executed SQLite command, and returns a boolean based on whether you’ve reached the end of the query or not (True if there are more rows left, and False if you’ve reached the end).
  2. The GetString() method returns the value of the specified column as a String. It takes in one parameter, an int that represents the zero-based column ordinal. There are similar methods like GetDataTime() and GetBoolean() that you can use based on the data type of the column that you are dealing with.
    1. The ordinal parameter isn’t as relevant in this example since we are selecting all the entries in a single column. However, in the case where multiple columns are part of the query, the ordinal represents the column you are pulling from. So if we selected both Primary_Key and Text_Entry, then GetString(0) would return the value of Primary_Key String and GetString(1) would return the value of Text_Entry as a String.

And that’s it! You can now build your application and add any text you like into your SQLite database. You can even close and open your application to see that the data persists.

A link to the full code can be found at: https://github.com/Microsoft/windows-developer-blog-samples/tree/master/Samples/SQLiteSample

Moving Forward

There are plenty of additions that you can make to tailor this sample to your needs:

  • Adding more tables and more complicated queries.
  • Providing more sanitation over the text entries to prevent faulty user input.
  • Communicating with your database in the cloud to propagate information across devices.
  • And so much more!

What about Entity Framework?

For those developers looking to abstract away particular database details, Microsoft’s Entity Framework provides a great model that lets you work at the “Object” layer as opposed to the database access layer. You can create models for your database using code, or visually define your model in the EF designer. Then Entity Framework makes it super-easy to generate a database from your defined object model. It’s also possible to map your models to existing databases you may have already created.

SQLite is one of many database back-ends that Entity Framework is configured to work with. This documentation provides an example to work from.

Conclusion

From embedded applications for Windows 10 IoT Core to a cache for enterprise relations database server (RDBS) data, SQLite is the premier choice for any application that needs local storage support. SQLite’s server-less and self-contained architecture makes it compact and easy to manage, while its tried and tested API surface coupled with its massive community support provides additional ease of use. And since it ships as part of Windows 10, you can have peace of mind, knowing that you’re always using an up-to-date version of the binary.

As always, please leave any questions in the comments section, and we’ll try our best to answer them. Additional resources are also linked below.

Additional Resources