Can Bilgin

CubiSoft Solutions

  • Home
  • Downloads
  • About

Retrying Transient Exceptions

Posted by Can Bilgin on March 1, 2016
Posted in: C#. Tagged: OptionalAttribute, Retry Block, Safe Navigation Block, Transient, WithRetryAsync. Leave a comment

Exception handling is not always a straightforward implementation paradigm. At times you are faced with decisions such as to catch or not to as well as is it foolish to retry with same strategy and expect a different outcome.

Dealing with mobile network connections (especially cellular network connections – no matter what protocol the mobile interface suggests) is always a shady business. Even though everything is setup properly, sometimes the results are not as expected and you might endup with timeout expcetions, dns errors as well as server side errors (e.g. 400, 502 etc.)

Recently I was dealing a server side implementation on the new Azure Service Fabric platform. The biggest problem we were having was dealing with the realiable collections timing out because of the deadlock safeguards (i.e. 4sec timeout). Especially with replica failures and/or other failover/recovery type of situations these timeouts were unavoidable.

One option we analyzed was to use the Transient Error block implementation of Enterprise Library and Microsoft Patterns and Practices team ( Transient Fault Handling ). However this seemed like an overkill for a simple task such as this.

Instead, I decided go with a simpler extension method implementation.

public static async Task<T> WithRetryAsync<T>(this Func<Task<T>> executionTask,
    [Optional, DefaultParameterValue(3)] int retryCount)
{
    var trials = 0;

    Retry:

    try
    {
        var results = await executionTask();

        return results;
    }
    catch (Exception)
    {
        if (++ trials > retryCount) throw;

        goto Retry;
    }
}

In this implementation, we are using a Func to carry over our asynchronous delegate and try to execute it as long as the retry count allows us.

And the call to this function would look simmilar to:

// Using method group
Func<Task<int>> myFunction = CalculateAsync;
// Or using lamdba
//Func<Task<int>> myFunction = () => CalculateAsync();

await myFunction.WithRetryAsync(4);

Cancellation

But what if the retries are taking way too long and we want to cancel the task at hand. For this scenario, we can of course resort to CancellationToken. Expanding our method implementation a little bit:

public static async Task<T> WithRetryAsync<T>(this Func<Task<T>> executionTask,
    [Optional, DefaultParameterValue(3)] int retryCount,
    [Optional] CancellationToken cancellationToken)
{
// commented out for brevity
    }
    catch (Exception)
    {
        if (++trials > retryCount || cancellationToken.IsCancellationRequested) throw;

// ...
    }
}

So not if the cancellation token is signalled, the process is cancelled after the last trial and the original exception is thrown.

Progress

You are probably wondering what does progress have to do with a failing task. Well in some scenarios the number of retries is an indication of application or system health and can be part of telemetry data. The easiest way to incorporate the retry events into this execution was using the IProgress interface.

Again extending our method signature with another optional parameter (on a side note the use of Optional attribute can be exchanged with parameters with default values, the choice here was simply syntactic):

public static async Task<T> WithRetryAsync<T>(this Func<Task<T>> executionTask,
    [Optional, DefaultParameterValue(3)] int retryCount,
    [Optional] CancellationToken cancellationToken,
    [Optional] IProgress<int> retryCallback)

and the catch block would become simmilar to (using the new safe navigation operator of C#):

catch (Exception)
{
    if (++trials > retryCount || cancellationToken.IsCancellationRequested) throw;

    retryCallback?.Report(trials);

    goto Retry;
}

Now everytime a retry occurs the Progress callback is executed notifying the caller about the retry.

Transient Errors

This implementation can be further improved by implementing a similar policy check implementation of Transient Fault Handling block for evaluating the exception to be transient or not.

Happy coding everyone,

Share this:

  • Email
  • Facebook
  • LinkedIn
  • Twitter

Like this:

Like Loading...

Xamarin Applications on VSTS & HockeyApp

Posted by Can Bilgin on January 11, 2016
Posted in: VSTS, Xamarin. Tagged: Android, HockeyApp, iOS, VSTS, Xamarin. Leave a comment

HockeyApp, the new attraction of Microsoft cross platform development enthusiasts, is a beta testing platform tool for iOS, Android and Windows Phone. Using HockeyApp, applications can be distributed to QA teams or simply used as a beta testing hub. Its feature set is comparable to Apple’s TestFlight for iOS platform. (It is worth it to mention that HockeyApp started out as an independent software, developed by a Stuttgart based team until it was acquired by Microsoft).

However, HockeyApp not only provides an easy testing and analysis platform but also fills in an important gap in the Application Lifecycle Management (DevOps). In a general implementation scenario using VSTS for project management and/or source control, application projects developed in Visual Studio using Xamarin (for iOS and Android, and Windows Phone) are stored in the online repository. This repository can be Team Foundation Services or a Git repository can be associated with the TFS project. After the developer handoff, the code can be built using one of the build templates in Visual Studio.

VSTS BuildTemplates

VSTS BuildTemplates

This workflow can be extended to run unit tests for possible portable class libraries that requires testing. On top of the unit tests, Xamarin Test Cloud and calabash tests can be employed to run automated UI tests for platform specific applications.

Now the application is built, tests are run (even possibly integration tests), but where do we go from here. There is no automated service integration to MDM (Mobile Device Management), or possible way for beta tester to download packages from some drop location. Although, in all fairness, android application packages can be dropped to an FTP or other shared folder so they can downloaded by the beta users from this location. For windows phone applications, some custom company hub can be used to read the appx packages and serve them as available applications for download. However, none of these solutions provide a single framework to deploy the CI build artifacts to beta devices.

At this point HockeyApp comes into the story. With their release of VSTS service endpoint and the associated build step; TFS builds can now include a HockeyApp deployment.

In order to use the HockeyApp deployment, you first need to install HockeyApp for VSTS from the Visual Studio market place.

HockeyApp VSTS Installation

HockeyApp VSTS Installation

Once the installation is complete, the HockeyApp service endpoint should be configured in Visual Studio Team Services configuration page. However, since we will need the API token for HockeyApp, it would be useful first to create a Full Access API token in HockeyApp dashboard.

HockeyApp API Tokens

HockeyApp API Tokens

The API token will be used by the VSTS Service to access and deploy the application bundles. In order to set up the HockeyApp Service on VSTS, you will need to navigate to the Services section of the Control Panel for the specific team project. If you click on “New Service Endpoint”, you should now have the option of HockeyAp. In order to create this endpoint, you will need to define the API token and the service endpoint connection name.

HockeyApp Service Configuration

HockeyApp Service Configuration

Now that the HockeyApp connection is setup and configured, you can head back to your build definition and the HockeyApp build step right after the application package is prepared (and possibly signed). In the connection field, you will need to select the service endpoint we setup in the previous step. For the binary file path, you can use the previous Copy and Publish Build Artifacts tasks location (i.e. by default “drop” which would refer to $(Agent.BuildDirectory)\drop). You can use a more generic wildcard path similar to $(Agent.BuildDirectory)\**\*.apk for an Android Application.

HockeyApp Build Task

HockeyApp Build Task

You can additionally include release notes, symbol files, or add download restrictions for HockeyApp tags, teams and users. If you want to associate the application package with an existing application metadata saved on the HockeyApp dashboard, you would need to use the App ID. In my trials, I didn’t need to create the application on HockeyApp dashboard before triggering the build (i.e. Empty Application Id worked out).

HockeyApp Build Task Configuration

HockeyApp Build Task Configuration

And that’s about it… Now each build will automatically deploy the application to your HockeyApp Repo and the application can be downloaded onto the testing devices using the HockeyApp install link that is generated for your HockeyApp account.

Currently HockeyApp offers a free tier with 2 applications. Also if you are quick you might get a free HockeyApp puck if you integrate with Visual Studio Team Services (http://hockeyapp.net/blog/2015/11/24/score-a-free-puck.html). :)

Happy coding everyone…

And thank you HockeyApp team for this great product.

Share this:

  • Email
  • Facebook
  • LinkedIn
  • Twitter

Like this:

Like Loading...

Connected Apps With Windows 10 Mobile (UWP) – III

Posted by Can Bilgin on January 9, 2016
Posted in: UWP, Windows 10, WinRT. Tagged: App2App, LauncherOptions, SharedStorageAccessManager, TargetApplicationPackageFamilyName, UWP, Windows Phone 10. Leave a comment

In the previous posts (Connected Apps – I and Connected Apps – II), we discussed the app communication scenarios with external sources and the windows runtime. In this post, we will be discussing the app-2-app communication scenarios. As you might have remembered, app2app communication scenarios on Windows Phone 8.1 was limited to app contract implementations such as Association, Sharing and Pickers. Windows 10 platform extends these implementation providing additional app2app communication patterns.

App2App Connection Scenarios (UWP)

App2App Connection Scenarios (UWP)

Improved Deep-Linking

Deep linking is generally used to describe the protocol activation application contract. In Windows Phone 8.1, any deep link described with a certain URI scheme, would be handled by the operating system to launch the default application associated with this URI scheme (sinergija:?SpeakerId=23421). So in this case, if there were two or more applications associated with the custom protocol, the consuming application (i.e. the application calling Launcher.LaunchUriAsync) will not be able to choose the specific application to open the link but the user will need to choose the default application. In Windows 10, on top of the usual launch uri elements, you can define additional parameters for deciding on which app will be handling this using the LauncherOptions class.

  • PreferredApplicationDisplayName defines the application display name for the app to install if there are no applications to handle this protocol
  • PrefferedApplicationPackageFamilyName, similarly, defines the package family name for the desired application to handle the protocol.
  • TargetApplicationPackageFamilyName defines a very specific application to handle the launch

Now Using the launcher options we can specify the exact application to handle this protocol:

var options = new LauncherOptions();
options.TargetApplicationPackageFamilyName = "Sinergija.ContactsApp_8wekyb3d8bbwe";

Uri uri = new Uri(“sinergija:?SpekerId=3748937");
await Launcher.LaunchUriAsync(uri, options);

Another important addition to this activation strategy is the ability to use additional data for the launch method. On Windows Phone 8.1, the target application would have to handle the protocol activation only through the received URI parameters. On UWP, consuming application can additionally send a ValueSet containing key/value pairs of data.

var options = new LauncherOptions();
options.TargetApplicationPackageFamilyName = "Sinergija.ContactsApp_8wekyb3d8bbwe";
 
var additionalValue = "My Additional Value Data";
 
ValueSet inputData = new ValueSet();
inputData.Add("MyValue", additionalValue );
 
Uri uri = new Uri(“sinergija:?SpekerId=3748937");
await Launcher.LaunchUriAsync(uri, options, inputData);

Launch For Result

What if I, as the developer of the consumer application, want to receive the data related to the requested item using the custom URI scheme, rather than opening the target application interface. This, of course, was not possible in Windows Phone 8.1. With the improved app2app communication capabilities, this is now possible in UWP. Application can launch other applications only to receive complete a certain operation or receive data using the LaunchUriForResultsAsync.

In this implementation pattern, the target application should set the resultant data and report the operation to be completed, so that the consumer app can get the result from the await statement.

In the target application, the activation should be handled similar to protocol activation:

protected override void OnNavigatedTo(NavigationEventArgs e)
{
    var protocolForResultsArgs = e.Parameter as ProtocolForResultsActivatedEventArgs;

    var protocolOperation = protocolForResultsArgs.ProtocolForResultsOperation;
     
    //....
    
    var result = new ValueSet();
    result["result"] = "<Could be the serialized data for the content item>";
    protocolOperation .ReportCompleted(result);
}

And on the consumer application, it is executed as a mere asynchronous method call:

var options = new LauncherOptions();
options.TargetApplicationPackageFamilyName = "Sinergija.ContactsApp_8wekyb3d8bbwe";
var launchUri = new Uri("sinergija:?SpeakerId=3748937");
var result = await Launcher.LaunchUriForResultsAsync(launchUri, options);

if(result.Status == LaunchUriStatus.Success && result.Result?.Contains("result"))
{
    var myStringContent = result.Result["result"];
    // TODO:
}

NOTE: It is important to note that the data that is exchanged between the applications should not be larger than 100KBs. Shared Storage can be a solution for exchanging larger content.

Shared Storage

Shared Storage is also another feature that was improved in UWP. Combining the new launcher options and the shared storage, developers can exchange larger content sets using the shared storage tokens.

Access to the shared storage is provided by the SharedStorageAccessManager similar to Windows Phone Silverlight applications. However, the implementation of the shared storage is completely renewed. Each file that uploaded to the shared storage get an assigned access token. The access token then can be shared to other applications.

var options = new LauncherOptions();
options.TargetApplicationPackageFamilyName = "Sinergija.ContactsApp_8wekyb3d8bbwe";
 
var token = SharedStorageAccessManager.AddFile(contactPhoto);
 
ValueSet inputData = new ValueSet();
inputData.Add("Token", token);
 
Uri uri = new Uri(“sinergija:?SpekerId=3748937");
await Launcher.LaunchUriAsync(uri, options, inputData);

Now the target application can use the image added from the consumer app using the RedeemTokenForFile method.

In addition to the features described here; UWP brings the powerful feature set called the “App Services”. However, in my opinion, App Services deserves a post of its own.

Happy coding everyone…

Share this:

  • Email
  • Facebook
  • LinkedIn
  • Twitter

Like this:

Like Loading...

Connected Apps With Windows 10 Mobile (UWP) – II

Posted by Can Bilgin on December 2, 2015
Posted in: UWP, Windows 10, WinRT. Tagged: NetworkOperatorTetheringManager, NetworkReport, Tethering, UWP, WiFiAdapter, Windows 10 Mobile. 3 Comments

In my previous post, we talked about the communication scenarios in windows runtime applications, categorized them in three main sections. We walked through applications of different scenarios for these domains on Windows Phone 8.1 platform. We also had a quick look at the External communication domain changes in UWP platform and Windows 10 Mobile.

Connection Scenarios on UWP

Connection Scenarios on UWP

Communication with the System

One of the areas that saw the introduction of many new features is the application’s communication line with the system and control over certain features.

UWP application now can access so-called Radios (networking peripherals), turn them on/off and even enumerate available networks, provided that the application has the right capability declared in the manifest.

In order for a mobile application to access the management features, the application first needs to call RequestAccessAsync function and wait for the consent of the user. Once the consent is provided, in-built functionality can be used to manage the radios.

For instance in order to turn the Wi-Fi adapter on:

// Request access to set the radio state
// must be called at least once from the UI thread
await Radio.RequestAccessAsync();
 
// Turn on WiFi radios
var radios = await Radio.GetRadiosAsync();
foreach (var radio in radios)
{
    if (radio.Kind == RadioKind.WiFi)
    {
        await radio.SetStateAsync(RadioState.On);
    }
}

Another example implementation would be to Enumerate Wireless Network Connections using the Wi-Fi adapter:

var access = await WiFiAdapter.RequestAccessAsync();
if (access != WiFiAccessStatus.Allowed)
{
    // TODO: throw exception? exit the current process? User denied access
}
else
{
    var result = await Windows.Devices.Enumeration.DeviceInformation.
			FindAllAsync(WiFiAdapter.GetDeviceSelector());
    if (result.Count >= 1)
    {
        firstAdapter = await WiFiAdapter.FromIdAsync(result[0].Id);
    }
    else
    {
        // TODO: throw exception? dialog? no Wi-Fi adapters.
    }
}

Once we receive the Wi-Fi adapter, all we have to do is to scan the are and see if there are any available networks (and details about available networks such as SSID, BSSID, Network Strength, Freq.):

await firstAdapter.ScanAsync();

var report = firstAdapter.NetworkReport;

var message = string.Format(“Network Report Timestamp: {0}”, report.Timestamp);
foreach (var network in report.AvailableNetworks)
{
	//Format the network information
	message += string.Format("\nNetworkName: {0}, 
                                    BSSID: {1}, 
                                    RSSI: {2}dBm, 
                                    Channel Frequency: {3}kHz",
                   network.Ssid, 
                   network.Bssid, 
                   network.NetworkRssiInDecibelMilliwatts, 		
		   network.ChannelCenterFrequencyInKilohertz);

And connecting to a Wi-Fi network is as simple as connecting a network service with a client SDK:

WiFiAvailableNetwork availableNetwork = availableNetworks[0];
 
string passPhrase = “password”;

var passwordCredentials = new PasswordCredential(null, null, passPhrase);
 
var connectionResult = await firstAdapter.ConnectAsync(availableNetwork, 
                  WiFiConnectionKind.Permanent, passwordCredentials);
 
if (connectionResult.ConnectionStatus != WiFiConnectionStatus.Success)
{
	// Connection was unsuccessful
}

Finally another attractive system management feature that was added to the Windows 10 mobile platform is the connection sharing. From the user perspective is a dream come through to be able to initialize the mobile hotspot on the mobile device with the click of a button from the pc. From the developers perspective, NetworkOperatorTetheringManager supplies us with the required methods to start connection sharing within your application.

NOTE: It is important to include the wiFiControl capability in the package manifest to be able to use the NetworkOperatorTetheringManager like any other manager from the Windows.Devices.WiFi namespace.

In order to initialize the manager, we would have to check if a certain connection on the mobile device suitable for sharing, if so, just use the internet profile to start the manager:

NetworkOperatorTetheringManager tetheringManager = null;
 
ConnectionProfile InternetConnectionProfile = NetworkInformation.GetInternetConnectionProfile();
 
if (InternetConnectionProfile != null && InternetConnectionProfile.IsWwanConnectionProfile)
{
	tetheringManager = NetworkOperatorTetheringManager.CreateFromConnectionProfile(InternetConnectionProfile);
}

The we can use the tethering manager to initiate the shared connection:

try
{
    NetworkOperatorTetheringOperationResult result = await tetheringManager.StartTetheringAsync();
    if (result.Status != TetheringOperationStatus.Success)
    {
        if (result.AdditionalErrorMessage != "")
        {
            // TODO: Additional Error Message
        }
        else
        {
            var errorStatus = result.Status;
            // TODO: Error Status
        }
    }
    else
    {
        // Success
    }
}
catch (Exception ex)
{
	// TODO:
}

This completes the system domain communication scenarios on UWP applications for Windows 10 Mobile. In the next post, we will be talking about App2App communication scenarios.

Happy coding everyone…

Share this:

  • Email
  • Facebook
  • LinkedIn
  • Twitter

Like this:

Like Loading...

Connected Apps With Windows 10 Mobile (UWP) – I

Posted by Can Bilgin on December 2, 2015
Posted in: UWP, Windows 10. Tagged: AllJoyn, HttpClient, UWP, WCF, Windows 10 Mobile, Windows Phone 8.1. 2 Comments

In this post, I would like to talk about the “next big thing”; Windows 10 Mobile. Most of you already had the opportunity to play around with Windows 10 on your Microsoft devices or even started using it daily (like myself). It was made possible with the Windows Insider program freely for whoever wants to take a peek at this newcomer. Windows 10 has a lot of differences from its predecessor (i.e. Windows Phone 8.1) in both UI and what is under the hood. As the release date of Windows 10 on mobile devices is approaching, I would like to focus this post on how to create connected applications on Windows 10.

First of all, connected apps is a very vague term and can be used to describe a number scenarios. We can, essentially, divide these connection scenarios into three domains: External, App2App, System. These domains applied to Windows Phone 8.1 applications too.

Connection Domains on WP

Connection Domains on WP

App-2-App Communication Scenarios (WP 8.1)

One of the most innovative element of Windows Runtime was the use of contracts, and how application could, so-to-say, communicate with each other. We could divide the App2App communication domain into 3 subsections: Sharing, Association and Pickers. Sharing contract provided us the ability to share content (in several formats) between the source application and the target applications. Naturally, both source and target apps had to implement the respective activation scenarios and contracts. Associations came in two flavors: protocol and file type. Protocol association opened up the doors for creative scenarios where the calling application could use the custom protocol almost as if making a HTTP GET call. However, this setup only allowed one-way communication, there was no response from the target application. And finally, applications could provide pickers for (abstract) documents or other content types which then can be served by the runtime to the users of multiple applications.

External Communication Scenarios (WP 8.1)

In this category, we can talk about all the external resources that an app running on Windows Phone 8.1. From the external communication perspective, developers had the luxury of using multiple peripherals and connection protocols. There were multiple options such as HttpClient, Syndication Api, Proximity/NFC, partially supported sockets and Bluetooth. Background Transfer API was another pioneering implementation introduced by Windows Runtime. Especially, HttpClient introduced lots of improvement and customization options, differing from the original implementation of the .NET stack. Bluetooth API, however capable as it was, it was different than the implementation in Windows 8 (desktop) counter-part of Windows Phone 8.1.

System Communication Scenarios (WP 8.1)

The only tangible system communication scenario in WP 8.1 was related to the Connection Profile. Applications had the ability to retrieve the type and availability of a connection.

Connection Scenarios on Windows Phone 8.1

Connection Scenarios on Windows Phone 8.1

Windows 10 on mobile devices introduces many new or improved features on each domain, providing developers with the opportunity to use their imagination while creating interactive patterns.

Networking is nicer with WCF

When we are talking about external communication scenarios, perhaps one of the most exciting changes in mobile platform (especially for WCF lovers) is the fact that WCF client runtime which was removed from Windows Phone runtime in the earlier release is BACK! There were many theories as for the reason of this decision but it is a fact that many developers had to jump through hoops to connect windows phone applications to their already existing WCF infrastructure even though WCF has always been support on the Windows 8 desktop runtime. WCF runtime was later on was included in Windows Phone 8 Silverlight runtime but never could be used on Windows Phone 8.1. The WCF client runtime that is re-introduced in Windows 10 mobile is a subset of the WCF on .NET and is an improved version of the client library from Windows Phone 8 Silverlight.

HttpClient also gets a revamp with Windows 10 runtime. HttpClient in UWP is a combination of .NET client & WinRT implementation. It supports and uses HTTP/2 protocol and supposed to be “up to 100% faster”.

Sockets is another area that gets a noticeable improvement from the previous mobile implementations. Sockets API included in Windows 10 mobile runtime is an improved version of Windows Phone 8 Silverlight module. One of the most anticipated feature of the new sockets API is the ability to trigger background tasks using the SocketActivityTrigger. This helps applications run the socket connections in the background and execute tasks on incoming connections or messages. SocketBroker implementation helps developers listen on sockets even when the application is not working an trigger tasks. Web Sockets are also supported now on Window 10 mobile runtime.

Wi-Fi Direct Services
Wi-Fi Direct Services are introduced as an app specific Wi-Fi direct implementation in UWP and on Window 10 mobile runtime. The implementation follows the advertiser/connector model. It support bi-directional seeking and advertising scenarios.

In a general scenario, the advertising application on a device has to create a publisher and set the discoverability flag.

// Create an Advertisement Publisher
var publisher = new WiFiDirectAdvertisementPublisher();

// Turn on Listen state
publisher.Advertisement.ListenStateDiscoverability = WiFiDirectAdvertisementListenStateDiscoverability.Normal;

// Register for connection requests
var listener = new WiFiDirectConnectionListener();
listener.ConnectionRequested += OnConnectionRequested;

// Start the advertiser
publisher.Start();

Once the advertiser is created, target applications can search for advertising devices using the same application and send a connection request.

String deviceSelector = WiFiDirectDevice.GetDeviceSelector(WiFiDirectDeviceSelectorType.AssociationEndpoint);

// Get all WiFiDirect devices that are advertising and in range
DeviceInformationCollection devInfoCollection = await DeviceInformation.FindAllAsync(deviceSelector);

// Connection parameters – GO Intent
WiFiDirectConnectionParameters connectionParams = new WiFiDirectConnectionParameters();
connectionParams.GroupOwnerIntent = “1”;

// Connect to the WiFiDirect device
String deviceId = devInfoCollection[0].Id;

var wfdDevice = await WiFiDirectDevice.FromIdAsync(deviceId, connectionParams);

Now that we know which device we want to connect, you can use the GetConnectionEndpointPairs method to get the local and remote IP addresses to initialize a WinRT socket.

And on the publisher side, this connection request is captured on the OnConnectionRequested event handler which we subscribed in the previous step.

private async void OnConnectionRequested(WiFiDirectConnectionListener sender, WiFiDirectConnectionRequestedEventArgs args)
{
var ConnectionRequest = args.GetConnectionRequest();

// Prompt the user to accept/reject the connection request
// If rejected, exit

// Connect to the remote device
WiFiDirectDevice wfdDevice = await WiFiDirectDevice.FromIdAsync(ConnectionRequest.DeviceInformation.Id);

// Get the local and remote IP addresses
var EndpointPairs = wfdDevice.GetConnectionEndpointPairs();

// Establish standard WinRT socket with above IP addresses

}

There you have it, a direct communication line between the applications running on two separate devices over Wi-Fi direct.

Other Networking Goodies

Bluetooth stack on UWP has implementations of new profiles such as Beacon, Advertisement and LE. Another noticeable change on UWP for mobile is that the Bluetooth API is completely merged with its desktop counterpart and provides a uniform structure to write code for universal applications.

Another important introduction in Windows 10 mobile is that AllJoyn now has its own namespace and is supported natively on UWP applications.

Connection Scenarios on UWP

Connection Scenarios on UWP

Let us take a break at this point. In the next post, we will talking about system communication scenarios in UWP (such as radios management, Wi-Fi adapter connections, etc.)

Share this:

  • Email
  • Facebook
  • LinkedIn
  • Twitter

Like this:

Like Loading...

Retarget Projects to Windows 10

Posted by Can Bilgin on April 3, 2015
Posted in: Windows 10, WinRT. Tagged: Retarget, Visual Studio 2015, Windows 10, Windows 10 Development SDK. 1 Comment

Following the changes to the project structure and the appxmanifest schema changes, I decided to put together a little Visual Studio 2015 Extension to upgrade the existing Windows Store 8.1 or Windows Phone 8.1 (not Silverlight) projects to Windows 10 UAP applications.

After the extension is installed you will have an additional menu item in the project file context menu.

Retarget Windows Store Project to Windows 10

Retarget Windows Store Project to Windows 10

You can with ease upgrade the project file and the package appxmanifest to the UAP platform.

Instructions
To demonstrate this retargeting process, I am going to start by creating a default universal Hub application.

Create Universal Hub App

Create Universal Hub App

Once the solution and the projects are created, we have a Windows 8.1 and Windows Phone 8.1 projects.

Project Structure

Project Structure

Now, after selecting the windows phone project, you will have to use the new menu item.

Retarget Menu Item

Retarget Menu Item

NOTE: The retarget menu item will only be available on Windows Store 8.1 (C#) and Windows Phone 8.1 (C#) projects.

Once the retargeting operation is completed, visual studio will be asking to reload the project. You can select “Reload All” option.

Reload Dialog

Reload Dialog

When the project is reloaded, you will see the new Windows 10 project added to the solution hierarchy.

UAP Application Added

UAP Application Added

Keep in mind you still might need to change couple of things in the project to get it running. (e.g. Phone specific styles left from Windows Phone 8.1 implementation, Tile sizes left from the Windows Store application – in the new package manifest the tile sizes are the same as the phone package manifest from 8.1)

Happy coding everyone,

P.S. I want to thank Andy Wigley (@andy_wigley) for putting the effort to write the PowerShell script to upgrade the projects. This extension is inspired by his script.

Share this:

  • Email
  • Facebook
  • LinkedIn
  • Twitter

Like this:

Like Loading...

Windows 10: Changing Paradigms

Posted by Can Bilgin on April 1, 2015
Posted in: Windows 10, WinRT. Tagged: ApiInformation, IsApiContractPresent, PickSingleFileAndContinue, UAP, Windows 10, Windows Core. Leave a comment

Windows 10 is the main discussion topic in the online development communities. This new operating system that is currently in the technical preview (and available through the Microsoft insider program) is a milestone in the platform unification journey that Microsoft embarked upon with starting with Windows Phone and Windows 8 operating systems. With Windows 10, developers and users are introduced to one development kit, one store, one application and one binary distribution package.

Windows 10 - Evolution

Windows 10 – Evolution

Introducing Windows Core

With Windows 10, developers are introduced to the new Windows Core concept. Windows Core is the refactored common core of Windows. It is the common set of APIs, a common infrastructure, which gives a, for the first time, truly binary compatibility across different platforms.

Up until Windows 10, a lot of the operating systems shared lots of commonality. In essence, most features were re-written from scratch for different platforms by separate development teams. Windows 8 was the first attempt to create a unified core with the so-called windows 8 kernel. The Windows CE kernel that was used for Windows Phone 7 was finally replaced with the Windows 8 kernel on Windows Phone 8. Xbox platform with the same kernel joined the unified platform with the release of Xbox One.

However, even though the kernels were the same, the implementation still differed on certain features which led to the Universal App Concept. The core functionality for mobile and desktop apps were implemented in either shared libraries or windows runtime class libraries targeting certain platforms that could be reused on the separate binaries for the respective platforms.

Universal App Platform

Universal App Platform is another new concept that we, developers, will need to get acquainted with. UAP is a collection of contracts and versions. It defines the platform that is running your application and acts as a broker between the application and the operating systems. It is built on top of the Windows Core and can be described as a superset of all the APIs that are supported on different devices and platforms running Windows 10.

With this new concept, the developers’ responsibility towards the OS shifts towards the UAP and in return the operating system is responsible for providing the UAP to the applications. Targeting platforms with the UAP is as simple as a manifest declaration.

<TargetPlaform Name="Microsoft.Universal" minVersion="2.0.0.0" maxVersionTested="3.5.0.0" />

The existence of a broker between the application and the operating system also creates an OS-agnostic development experience. For instance, if/when a new version of the OS becomes available, the application does not need to be aware of the version of the OS. Only important thing is to check if the UAP version is compatible with the current application.

Extensions SDK

Extensions SDK is really what makes the device specific APIs accessible. In an object oriented analogy, if the UAP is defining the abstract classes and interfaces to all the available APIs, the extensions SDK provides the implementations for these device specific feature sets. For instance, without adding the windows phone extension SDK as a reference to your application (the extension SDKs can be added using the Add Reference link in the project menu), the UAP will not be able to provide your application the access to types like BackButtonPressed or a contract like Wallet.

API Information Metadata

Since your application communicates with the OS through the UAP, and using the implementation by the extension sdks, the easiest way to probe for a certain API or device is the foundation metadata namespace. ApiInformation static class lets developers/application probe the current platform any of the supported classes, APIs, contracts, etc.

On Windows 8.1 Universal App:

#if Windows_Phone_App
Windows.Phone.UI.Input.HardwareButtons.BackPressed += HardwareButtons_Pressed
#else

On Windows 10 App:

If(Windows.Foundation.Metadata.ApiInformation.IsTypePresent("Windows.Phone.UI.Input.HardwareButtons"))
{
    Windows.Phone.UI.Input.HardwareButtons.Backpressed += HardwareButtons_BackPressed;
}

Since the HardwareButtons class and the Backpressed event is infact included in the UAP, even though the runtime type does not exist in the current device, there is no need for conditional compilation.

Instead of using IsTypePresent, you can test for the presence of individual members by using IsEventPresent, IsMethodPresent, IsPropertyPresent, and similar methods.

The set of APIs within a device family is further broken down into subdivisions known as API contracts. And you can use the ApiInformation.IsApiContractPresent method to tests for the presence of an API contract. This is useful if you want to test for the presence of a large number of APIs that all exist in the same version of an API contract.

public boolean HasScannerApi
{
	get 
         {
	    return Foundation.Metadata.ApiInformation
                  .IsApiContractPresent("Devices.Scanners.ScannerDeviceContract", 3);
         }
}

Windows 10 Changes

Other than the basic concepts in the development methodology, there are also changes in the framework and app model itself.

Continuation Manager No More (Windows Phone)

The infamous continuation context and the continuation manager are completely removed from windows phone to create a more unified programming model.
The methods that provide a continuation context such as FileOpenPicker.PickSingleFileAndContinue or WebAuthenticationBroker.AuthenticateAndContinue are replaced with their Windows Runtime counter parts such as FileOpenPicker.PickSingleFileAsync, WebAuthenticationBroker.AuthenticateAsync.

Charms Bar No More (Windows)

A concept that was introduced with Windows 8, the so-called charms bar, has been removed from Windows 10. In order to support the Windows 8 applications running on Windows 10, a top navigation button is introduced to access the charm functionalities like settings or sharing contracts.

Windows 8 Application Running on Windows 10

Windows 8 Application Running on Windows 10

For windows 10 applications, this top menu item does not appear. It is the developer’s responsibility to make these contracts accessible either with an app bar button or a button in the application interface.

Windows 10 - Settings Flyout

Windows 10 – Settings Flyout

Another change related to the charms is that the flyouts related to the charm bar buttons, such as the settings flyout; does not appear in the side of the whole client window but rather uses the application window.

Changing Layout Concepts (Windows)

Windows application on Windows 8 two separate models of layout. First one was the full screen layout, and the second one was the snapped layout. Snapped layout was initially a fixed half window sized view but later changed to an adjustable window.

Windows 10 - Tablet Mode

Windows 10 – Tablet Mode

Windows 10 user interface can be used in two different modes. One is the tablet mode, which resembles to the previous layout and the application is visible either in snapped or full screen views. The second mode is the desktop mode, which makes the windows runtime apps visually no different than classic windows applications. On the desktop mode, the applications can be moved by the user or resized as desired.

App Bar (Windows)

App bar is still accessible and usable in Windows 10 applications. The only change is the fact that now the app bar became part of the window that is presenting your application. This change does not affect the developers directly, only directed towards the user experience.

However, windows 8 applications running on Windows 10 still display their app bar just like before.

I tried to give a quick overview of the changes related to Windows 10. Overall, Windows 10 is coming with a lot of surprises both for developers and users.
Happy coding every one,

P.S. In the next post, we will be discussing the sample Windows 10 app I was using to present this topic in Belgrade, MVP Open Days. (The sample can be downloaded from the Msdn Code Gallery).

Share this:

  • Email
  • Facebook
  • LinkedIn
  • Twitter

Like this:

Like Loading...

Posts navigation

← Older Entries
  • Follow Can Bilgin on WordPress.com
  • Mastering Cross Platform Development with Xamarin

  • Can Bilgin

    Can Bilgin

    Can Bilgin works at Authority Partners Inc. as a Program Architect. He has been working in software industry with Microsoft technologies for over a decade. In this period he took key roles in projects for high profile clients such as Microsoft, General Electric, Raiffeisen Bank, Jettainer and Adobe EchoSign using technologies such as BizTalk, SharePoint, InfoPath, Windows Mobile, Windows Phone, WinRT and WCF.

    He is especially interested in Windows app platform and windows phone development. He tries to share his experience on his blog and through different MSDN activities. He regularly attends local Microsoft conferences and community events in the Balkan region. He is a Microsoft MVP with Windows Platform Development expertise.

  • Recent Posts

    • Retrying Transient Exceptions
    • Xamarin Applications on VSTS & HockeyApp
    • Connected Apps With Windows 10 Mobile (UWP) – III
    • Connected Apps With Windows 10 Mobile (UWP) – II
    • Connected Apps With Windows 10 Mobile (UWP) – I
  • Follow me on Twitter

    My Tweets
  • March 2016
    M T W T F S S
    « Jan    
     123456
    78910111213
    14151617181920
    21222324252627
    28293031  
  • Archives

    • March 2016
    • January 2016
    • December 2015
    • April 2015
    • March 2015
    • February 2015
    • December 2014
    • June 2014
    • March 2014
    • May 2013
    • January 2013
    • October 2012
    • August 2012
    • July 2012
    • June 2012
    • April 2011
    • June 2010
  • Categories

    • C#
    • CRM
    • Cryptography
    • DataContractJsonSerializer
    • DataContractSerializer
    • Devices
    • Diagnostics
    • FTP
    • Inking
    • Inking
    • IRandomAccessStream
    • Live Tiles
    • Metro
    • Microsoft Dynamics CRM
    • MVVM
    • oData
    • REST
    • Serialization
    • Sockets
    • Task
    • Task
    • Threading
    • Transitions
    • Uncategorized
    • UWP
    • VSTS
    • WCF
    • Windows 10
    • Windows 8
    • WinRT
    • Xamarin
  • Meta

    • Register
    • Log in
    • Entries RSS
    • Comments RSS
    • WordPress.com
Blog at WordPress.com. The Parament Theme.
Can Bilgin
Create a free website or blog at WordPress.com. The Parament Theme.
Follow

Get every new post delivered to your Inbox.

Join 98 other followers

Build a website with WordPress.com
loading Cancel
Post was not sent - check your email addresses!
Email check failed, please try again
Sorry, your blog cannot share posts by email.
%d bloggers like this:
    Cancel