Le Post Infeeny

Les articles des consultants et experts Infeeny

Archives Mensuelles: mai 2015

Writing Windows 10 App Services in JavaScript

What is an App Service ?

Windows 10 introduce a bunch of new ways for applications to communicate with each others. One way is to implement « App Services ». App Services are a request/response model where one app can call a service located within another app. App Services enable communication between apps, but also with the system. If you want to implement interactive scenarios with Cortana, you will have to implement an App Service to provide data to Cortana.

If you’re the kind of people who prefer code than blabla, you may head directly to the github repository with sample applications.

App Services use the same infrastructure as BackgroundTasks, and most of the logic and implementation details still applies. It means that when your service is called, you don’t have the whole application running, but only your service. It also means that your application don’t communicate directly with your App Service. For example, your application does not get notify when your service is called, or terminated.

In all resources I can found (Build session, Channel 9 videos, samples, …), App Services are implemented in C#. Those resources are really helpfull (especially this one on Channel 9), but if (like me) you are writing apps in HTML and JavaScript, it is likely that you prefer writing those services in JavaScript and share business code with the rest of your application. Porting C# resources to JavaScript is actually very easy. In this post, we will dive into implementing an App Service in Javascript, based on a C# sample from Microsoft Virtual Academy.

Show me some code !

In a Windows Web Application (Windows application written in HTML and JavaScript), a background task, therefore an App Service, should be thought of as a special Web Worker (no postMessage with it unfortunately). It’s a standalone JavaScript file that will get caught independently by the system.

The first step to implement your App Service is to create this file. As with web workers, you could use « importScripts » to reference any code you want to share between your app and the service. Be aware that, like with Web Workers, there is no « window » or « window.document » objects inside your background task or app service. The global context points to a completely different beast, and there is no DOM.

Inside your task or service, you will access to the current instance of the BackgroundTask object using WinRT APIs, and get a deferral on it to control the lifecycle of your service. As with background task, your service can also be canceled by the system if it needs to recover memory, or if battery is running low on the device. Your task instance provide a « cancel » event that will get caught is such cases.

A minimalistic background task/app service would look like this

var backgroundTaskInstance = Windows.UI.WebUI.WebUIBackgroundTaskInstance.current;
var triggerDetails = backgroundTaskInstance.triggerDetails;
var bgtaskDeferral = backgroundTaskInstance.getDeferral();

function endBgTask() {
    backgroundTaskInstance.succeeded = true;
    bgtaskDeferral.complete();
    bgtask.close();
}

backgroundTaskInstance.addEventListener("canceled", function onCanceled(cancelEventArg) {
    return endBgTask();
});

Now we must declare this file as an App Service. For that, we must add an extension to our application in its manifest, pointing to our javascript.

<Applications>
    <Application Id="App" StartPage="default.html">
        ...
        <Extensions>
            <uap:Extension Category="windows.appService" StartPage="js/appservice.js">
                <uap:AppService Name="MyJavascriptAppService"/>
            </uap:Extension>
        </Extensions>
    </Application>
</Applications>

As you can see, we provide the path to our JavaScript file, and we are giving a name (MyJavascriptAppService) to the App Service.

Now we must implement the service logic. To do that, we will check the trigger details on our background task, and register for a request event. When the event gets activated, we received an App Service request. This request will contains a message (with request arguments), and a sendResponseAsync method to reply to the caller. On both sides, the values in the request and in the response are provided with a ValueSet object.

//check that the app service called is the one defined in the manifest. You can host
//multiple AppServices with the same JavaScript files by adding multiple entries in the application manifest
if (triggerDetails && triggerDetails.name == 'MyJavascriptAppService') {
    triggerDetails.appServiceConnection.onrequestreceived = function (args) {
        if (args.detail && args.detail.length) {
            var appservicecall = args.detail[0];
            //request arguments are available in appservicecall.request.message
            var returnMessage = new Windows.Foundation.Collections.ValueSet();
            returnMessage.insert("Result", 42);
            appservicecall.request.sendResponseAsync(returnMessage)
        }
    }        
}

Calling your App Service

The app calling your service can be any app. If you want to restrict access, you will have to implement your own security mecanism. As you may have understood, the caller and the callee doesn’t have to be written in the same language. You can call a service written in C++ from a JavaScript app. All data are passing throught Windows APIs.

Calling the app service require some arguments, the caller should provide the package family name (PFN) of the target application, and the name of the App Service (as declared in the target’s app manifest). If you don’t know your PFN, you can get it through WinRT APIs by calling « Windows.ApplicationModel.Package.current.id.familyName » in your service application.

Using the PFN and service name, you will first get a connection to your App Service, and register to the « serviceclosed » event to be notified if your service terminate.

function getServiceConnection(){
    var connection = new Windows.ApplicationModel.AppService.AppServiceConnection();
    connection.appServiceName = "MyJavascriptAppService";
    connection.packageFamilyName = "...your PFN here...";

    return connection.openAsync().then(function(connectionStatus){
        if (connectionStatus == Windows.ApplicationModel.AppService.AppServiceConnectionStatus.success) {
            connection.onserviceclosed = serviceClosed;
            return connection;
        }
        else {
            return WinJS.Promise.wrapError({ message: 'service not available' });
        }
    });
}

Once you get a valid connection, you will be able to send requests to the service

function callService(){
    return getServiceConnection().then(function (connection) {
        var message = new Windows.Foundation.Collections.ValueSet();
        message.insert("Command", "CalcSum");
        message.insert("Value1", 8);
        message.insert("Value2", 42);

        return connection.sendMessageAsync(message).then(function (response) {
            var e = response;
            if (response.status === Windows.ApplicationModel.AppService.AppServiceResponseStatus.success) {
                document.getElementById('result').innerHTML = 'calculated ' + response.message.Result;
	                
                return response.message;
            }
        });
    });
}

And voilà ! you’re ready to go. A picture is worth a thousand words, so I put a sample with service and caller apps on github for you.

Debugging your service

If you grab the sample, you can see how easy it is to debug your service. If you configure the solution to run both caller and callee on debug, you can set breakpoints in your app service. If you don’t want to run the full service app, you could also edit the properties of the project hosting the service. In the debugging section, you could set « Launch Application » to false. In that case, when you run debug for both apps, you will only see the caller application starting, but your breakpoints in the app service will get called appropriately.

Porting Windows API calls from C# to JavaScript

Windows 10 is still in preview, and as of this writing, a lot of the samples available are written in C#.
The fact that samples are not available in JavaScript does not means that the feature is not available in JavaScript. The only things that may not be available is all topics about XAML controls, like the new InkCanvas, the RelativePanel, and so on. All code related to Windows APIs may be used in JavaScript.

Porting C# code to JavaScript is actually straightforward, especially if you are familiar with WinRT development. Windows APIs (aka WinRT) are projected in all available languages (C++, C#, and JavaScript), using each language paradigms. So, moving C# code to JavaScript is just about changing variable names to lowercase (ex « connection.SendMessageAsync() » => « connection.sendMessageAsync() »), or use the « on… » syntax for event. For example « connection.RequestReceived += someEventHandlerCallback » will convert to « connection.onrequestreceived += someEventHandlerCallback ».

As you can see, this is really easy…

[NCrafts] Continuous delivery, the missing parts

Paul Stack commence cette présentation avec une définition du Continuous Delivery (déploiement continue), qui est composé de principes et de pratiques pour construire, tester , deployer plus rapidement et plus fréquemment.

Les principes:

  1. Le processus doit être répétable et fiable
  2. Tout tâche soit être automatisée
  3. Si quelque chose est difficile, le faire plus souvent
  4. Tout mettre dans un contrôleur de source
  5. Le done (terminé) s’applique à une fonctionnalité livrée
  6. La qualité doit aussi être présente dans le code
  7. Tout le monde est responsable du processus de déploiement
  8. Le processus doit être constamment éprouvé

Lire la suite

Microsoft Ignite 2015 – SharePoint Online and OneDrive for Business Management and Control – Mercredi 6 mai

Microsoft Ignite 2015 – SharePoint Online and OneDrive for Business Management and Control – Mercredi 6 mai

SharePoint Online and OneDrive for Business Management and Control
Code : BRK3123

Par Adrien,
Pôle SharePoint MCNEXT

• Niveau : 300
• Cible : IT Influance & implementers
• Présentateur : Chris Bortik, Productivity Architect Microsoft

Lire la suite

Microsoft Ignite 2015 – A new experience in Delve : Discover People through content, and content through people – Mercredi 6 mai

A new experience in Delve : Discover People through content, and content through people
Code : BRK2176

Par Adrien,
Pôle SharePoint MCNEXT

• Niveau : 200
• Cible : IT Decision makers

Comment trouver la bonne information et la bonne personne rapidement ?
Delve permet de savoir ce qui se passe autour des personnes avec lesquelles on interagit.
Delve permet de localiser des expertises en s’appuyant sur son réseau.
Cette session montre comment Delve permet d’avoir une vision 365° des personnes constituant son réseau.
Beaucoup d’éléments présentés ici ne sont pas encore en production sur Office 365 actuel, il faudra attendre les prochaines releases.

Lire la suite

Microsoft Ignite 2015 – Yammer for team Collaboration – Mercredi 6 mai

Yammer for team Collaboration
Code : BRK2190

Par Adrien,
Pôle SharePoint MCNEXT

• Niveau : 200
• Cible : IT Influencers and Implementers
• Présentateurs
○ Jay Sethna : Product Marketing Manager, Yammer
○ Lindsay Matthews : Senior Product Manager, Yammer (Microsoft)
Dans cette session, on montre comment utiliser Yammer pour le travail d’équipe, comment rendre la collaboration plus intelligente et efficace tout en mesurant son impact sur les autres.
Il y a également des présentations de nouvelles fonctionnalités.

Lire la suite

Microsoft Ignite 2015 – Building Solutions with Office Graph – Mardi 5 mai

Building Solutions with Office Graph
Code : THR0726

Par Adrien,
Pôle SharePoint MCNEXT

• Niveau : 300
• Cible : Enterprise Developper
• Présentateurs : Helge Grenager Solheim, Jon Meling
In this demo packed roadmap session, we’ll take a closer look at Office Graph – the engine powering Delve. We’ll explain how Office Graph works behind the scenes and showcase how to query it to bring new insights and intelligence into your own apps. We’ll also demonstrate how you in the future can push external content and signals into the Office Graph from Line of Business systems and 3rd party services to enrich it even further.

Lire la suite

Microsoft Ignite 2015 – SharePoint 2013 & Azure Iaas : Better together – Mardi 5 mai

SharePoint 2013 & Azure Iaas : Better together
Code : BRK3124

Par Adrien,
Pôle SharePoint MCNEXT

• Niveau : 300
• Cible : IT Influencers and Implementers
• Présentateur : Brian Alderman


Get an overview of the options that Microsoft Azure provides for SharePoint. This session explains and demos how you can utilize Azure to host SharePoint farms for hot and warm standby, segregated farms for your developers, farms for integration testing or productive farms. We explain how you can create your own template for SharePoint servers that enables you to add a server to your farm in Azure or on-premises in 15 minutes. We also help you to develop a backup strategy for SharePoint that uses Azure as the storage for long-term backups.

Lire la suite

Microsoft Ignite 2015 – Microsoft Office 365 Video End-to-End Portal Setup for Admins – Mardi 5 mai

Microsoft Office 365 Video End-to-End Portal Setup for Admins
Code : ILL3101

Par Adrien,
Pôle SharePoint MCNEXT

• Niveau : 300
• Audience : IT Influencers and Implementers
• FORMAT : Lab
Join Mikael as he takes you step-by-step from not having a video portal within your Office 365 environment to establishing your ready-to-go Office 365 Video destination with channels and permissions intact. This instructor-led lab walks you through how to enable the portal so it shows up in the main Office 365 app launcher, shows you how to create new channels and properly assign both ownership to each channel and apply desired permissions, and finally how to upload and curate video content for the broadest outreach within your company. This is a very hands-on approach to learning and controlling Office 365 Video.

Lire la suite

Microsoft Ignite 2015 – Pré migration best practice – Mardi 5 mai

Pré migration best practice 
Code : BRK3153

Par Adrien,
Pôle SharePoint MCNEXT

Make new annoncement about migration API

Lire la suite