Hosting BizTalk WCF Send Adapters in your Custom Application

The BizTalk Adapters for WCF is a collection of several adapters that are designed to make it easy to create BizTalk applications that communicate with WCF-based services or line-of-business applications.

It ships with five physical adapters, corresponding to predefined WCF bindings (such as, BasicHttp, WsHttp, NetTcp, NetNamedPipe and NetMsmq). For more flexibility, it also ships with a custom adapter that can be configured with more control over WCF binding and behavior informations.

Also included with a BizTalk Server license, the Line of Business Adapter Pack includes several adapters for communication with line-of-business applications or databases from common vendors.

Additionnaly, thanks to the WCF LOB Adapter SDK, one can build his custom connectors for enabling access to in-house or proprietary data sources in a streamlined way. Many commercial vendors offer additional adapters built this way to enable BizTalk Applications to communicate with and expanded choice of line-of-business systems.

As a matter of fact, adapters built with the WCF LOB Adapter SDK are exposed as plain WCF transport-level bindings and thus can be reused in your custom .net applications, or any application that can consume a WCF binding.

In this post, I will show you how simple it is to re-use adapters that ship with BizTalk, or custom adapters built with the WCF LOB Adapter SDK, and host them in your custom applications.

Hosting Send Side WCF Adapters in your Custom Application

Using a WCF binding from a C# application is quite straightforward. After all, using WCF is as simple as ABC, right ?

1. A stands from Address.

The address represents the location of the WCF endpoint. It is commonly represented as a Uniform Resource Locator (URL).

var address = new EndpointAddress("mssql://localhost//SampleDb?");

2. B stands from Binding.

The binding is a collection of binding elements that gives the WCF runtime informations about the communication “stack” through which any given message passes through. A typical WCF communication stack can contain many channels, each of which is responsible for transforming and adapting the message so that it can be eventually transmitted to the target system. For this reason, the last channel in the stack is a transport-level channel.

Adapters build with the WCF LOB Adapter SDK are themselves transport-level WCF binding elements and therefore can be used directly in a communication stack. Those adapters, like any other bindings, are registered in the machine.config. For instance, here is the relevant snippet, corresponding to the WCF-SQL adapter:

      <bindingElementExtensions>
        <!- ... -->
        <add name="sqlAdapter" type="Microsoft.Adapters.Sql.SqlAdapterBindingElementExtensionElement, Microsoft.Adapters.Sql, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
      </bindingElementExtensions>

So, instantiating any given binding can be done very easily:

// create binding element

var adapter = new Microsoft.Adapters.Sql.SqlAdapterBindingElementExtensionElement();
adapter.AllowIdentityInsert = false;
adapter.EnableBizTalkCompatibilityMode = false;

var bindingElement = (BindingElement) Activator.CreateInstance(adapter.BindingElementType);
...

// create custom binding

var binding = new CustomBinding();
binding.Elements.Add(bindingElement); // add transport-level binding element last

// configure binding

binding.OpenTimeout = TimeSpan.FromSeconds(30);
...

Adapters built using the WCF LOB Adapter SDK all have a binding class, such as SqlAdapterBinding for instance. This class be instantiated and configured directly, instead of using a CustomBinding class like I have shown in my example above. However, I’m not sure how to get to this class directly from the information stored in machine.config.

3. C stands for Contract.

The contract represents the set of methods, with their arguments and return types, that the line-of-business system exposes. In most C# application, the service contract is exposed as a C# interface. Since we are dealing with adapters, however, there is no specific interface that can be used.

Instead, we need to rely on the channel shape, that corresponds to the most common communication exchange pattern used to access various systems, applications or databases.

Most adapters that ship with BizTalk support two-way communication. Therefore, the most sensible contract would be IRequestChannel. This contract allows an application to send and abitrary request, represented by a WCF Message object, and receive a response in return.

A Message is constructed with an Action, that makes sense to the adapter and a payload, supplied in the form of a class derived from BodyWriter.

private static Message InvokeAdapterRequest(Binding sqlBinding, EndpointAddress sqlAddress, String action, BodyWriter bodyWriter)
{
    using (var message = Message.CreateMessage(MessageVersion.Default, action, bodyWriter))
        return InvokeAdapterRequest(sqlBinding, sqlAddress, message);
}

private static Message InvokeAdapterRequest(Binding sqlBinding, EndpointAddress sqlAddress, Message message)
{
    var channel = ChannelFactory<IRequestChannel>.CreateChannel(sqlBinding, sqlAddress);
    try
    {
        if (channel.State != CommunicationState.Opened)
            channel.Open();
        return channel.Request(message);
    }
    catch
    {
        channel.Abort();
    }
    finally
    {
        channel.Close();
    }
}

Here is, for instance, a simple way to call a stored procedure on SQL Server using the WCF-SQL Adapter:

public class XmlBodyWriter : BodyWriter
{
    private readonly string body_;

    public XmlBodyWriter(string body)
        : base(true)
    {
        body_ = body;
    }

    protected override void OnWriteBodyContents(XmlDictionaryWriter writer)
    {
        writer.WriteRaw(body_);
        writer.Flush();
    }
}


private static void Main(string[] args)
{
    var address = new EndpointAddress("mssql://localhost//SampleDb?");

    // create binding element

    var adapter = new Microsoft.Adapters.Sql.SqlAdapterBindingElementExtensionElement();
    adapter.AllowIdentityInsert = false;
    adapter.EnableBizTalkCompatibilityMode = false;

    var bindingElement = (BindingElement) Activator.CreateInstance(adapter.BindingElementType);

    // create custom binding

    var binding = new CustomBinding();
    binding.Elements.Add(bindingElement); // add transport-level binding element last

    // configure binding

    binding.OpenTimeout = TimeSpan.FromSeconds(30);

    const string action = "TypedProcedure/dbo/usp_SelectRecords";
    var bodyWriter = new XmlBodyWriter("<ns0:usp_SelectRecords xmlns:ns0='http://schemas.microsoft.com/Sql/2008/05/TypedProcedures/dbo' />");

    using (var response = InvokeAdapterRequest(binding, address, action, bodyWriter))
    {
        // use response message
        Console.WriteLine(response.ReadOuterXml());
    }
}

Conclusion

This post shows a simple way to re-use any WCF LOB Adapter SDK-based adapters, in your own custom applications.

You probably will not have a use for this very often. Be we, at Moskitos, are building a new generation EAI/ESB Platform available as a Cloud-based application and our custom adapters are based on the WCF LOB Adapter SDK. Additionnaly, if our clients want to use BizTalk on-premise as well, we can take advantage of the BizTalk Adapter pack to allow our solution to communicate with other line-of-business systems.

Posted in BizTalk, Wcf | Leave a comment

Déployer une Machine Virtuelle SQL Server 2012 sur Windows Azure

This article has been written in an effort by the Windows Azure France team to coordinate the writing of tutorials and how-to guides for various Windows Azure features and technologies. This guide is a direct translation in french of the ‘Provisioning a SQL Server Virtual Machine on Windows Azure‘ guide, available on MSDN

La galerie de machines virtuelles Windows Azure contient des
images virtuelles prêtes à l’emploi, parmi lesquelles on trouve une
installation complète de SQL Server 64 bits sur Windows Server 2008 R2, Service
Pack 1 (64 bits). Après avoir choisi l’une des images disponibles, il vous est
possible, en quelques clics, de mettre en œuvre un environnement complet sur
Windows Azure.

Si vous voulez utiliser votre propre image virtuelle en lieu
et place de celles mises à disposition sur la galerie, veuillez consulter l’un
des articles officiels, référencés à la fin de ce guide.

Ce guide a pour objectif de vous accompagner dans la mise en
œuvre d’un environnement SQL Server complet sur Windows Azure.

Mettre en œuvre un environnement à partir d’une image virtuelle de la galerie Windows Azure

La mise en œuvre d’un environnement virtuel sur Windows
Azure nécessite une souscription. Si vous n’avez pas de compte Windows Azure,
vous pouvez souscrire à la version d’évaluation de Windows Azure, qui vous
offre la possibilité d’essayer le service pendant 90 jours à un tarif
préférentiel.

1. Se connecter au Portail Windows Azure, situé à l’emplacement suivant:
http://manage.windowsazure.com

2. Dans le bandeau situé à gauche de l’écran, sélectionner l’option « ORDINATEURS
VIRTUELS
 ». Cliquer sur + CRÉER UNE IMAGE, puis sur ORDINATEUR
VIRTUELS
et enfin sur À PARTIR DE LA GALERIE.

3. Dans l’assistant de création d’un ordinateur virtuel, sélectionne
l’image virtuelle correspondant à la version d’évaluation de SQL Server 2012
(64 bits).

Avertissement : la version d’évaluation de SQL
Server 2012 est mise à disposition gratuitement à des fins de tests. Cette
version ne peut pas être mise à jour vers une version complète ultérieurement.

4. Sur l’écran « Configuration de l’ordinateur virtuel », préciser les
éléments suivants :

· Préciser le NOM DE L’ORDINATEUR VIRTUEL, par exemple
« TestSQLServer2k12 ».

· Préciser le NOUVEAU MOT DE PASSE, en choisissant un mot de
passe répondant aux critères de sécurité de SQL Server 2012. Les critères sont
précisés à l’emplacement suivant : http://msdn.microsoft.com/en-us/library/ms161962.aspx

· CONFIRMER LE MOT DE PASSE, en le saisissant de nouveau.

· Choisir ensuite une TAILLE appropriée pour la machine
virtuelle.

Note : Voici quelques considérations pour
choisir la taille de la machine virtuelle.

· La taille Moyenne est la taille minimum recommandée pour un usage
en production.

· Sélectionner l’une des tailles Grande ou Très Grande si vous
utilisez l’Édition Entreprise de SQL Server.

· La taille sélectionnée limite le nombre de disques que vous
pouvez configurés (à partir de Moyenne <=4, Grande <=8 ou Très Grande
<= 16).

5.       Cliquer
sur la flèche située en bas à droite pour continuer.

6. Sur l’écran « Mode de l’ordinateur virtuel », préciser les éléments
suivants :

· Sélectionner un ORDINATEUR VIRTUEL AUTONOME.

· Choisir une portion de NOM DNS, de façon à composer un nom
complet de la forme « nomdns.cloudapp.net ».

· Choisir la RÉGION/GROUPE D’AFFINITÉS/RÉSEAU VIRTUEL
sera hébergée la machine virtuelle.

7. Cliquer sur la flèche située en bas à droite pour continuer.

8. Sur l’écran « Options de l’ordinateur virtuel », laisser les
options par défaut. Lire et accepter les conditions d’utilisation.

9. Cliquer sur l’icône de validation située en bas à droite pour terminer.

Une fois ces informations saisies, attendre que la machine
virtuelle soit déployée sur l’environnement Windows Azure.

Les étapes par lesquelles le statut de la machine virtuelle
est reporté sont les suivantes :

  • Démarrage en cours (Déploiement)
  • En cours d’exécution (Déploiement)
  • En cours d’exécution

La machine virtuelle est désormais hébergée sur
l’environnement Windows Azure. Il reste à finaliser l’installation avant
qu’elle soit disponible à l’utilisation. Pour cela, il est nécessaire de se
connecter à distance à la machine virtuelle.

Se connecter à l’environnement distant pour finaliser l’installation

1. Une fois le déploiement d’une machine virtuelle effectué, cliquer sur le
nom de votre machine virtuelle pour afficher le TABLEAU DE BORD. Cliquer sur CONNECTER,
en bas de la page.

2. Accepter le téléchargement et ouvrir le fichier .rdp à l’aidre du
programme de Connexion de Bureau à Distance (%windir%\system32\mstsc.exe).

3. Dans la boîte de dialogue de Sécurité, taper le mot de passe du compte Administrator, préciser lors de la configuration de la machine virtuelle. Si une fenêtre d’avertissement s’affiche, cliquer sur OK
pour ignorer ou accepter le certificat.

Lors de la première connexion à la machine virtuelle,
plusieurs étapes se succèdent pour finaliser l’installation de l’environnement.
Ceci inclut l’installation du bureau, Windows Updates et la finalisation des
tâches de configuration de la machine virtuelle (SysPrep).

Une fois ces étapes terminées, le programme d’installation
de SQL Server finalise les tâches de configuration. Ces tâches prennent un
certain temps, pendant lequel la commande SQL « SELECT @@SERVERNAME »
risque de ne pas retourner une valeur correcte. Tout rentre dans l’ordre une
fois ces tâches de configuration terminées.

Une fois connectée à l’aide de la Connexion de Bureau à
Distance, la machine virtuelle se comporte en tout point comme n’importe quel
autre ordinateur. Il est possible de se connecter localement à l’instance par
défaut de SQL Server à l’aide du programme « SQL Server Management
Studio », installé préalablement sur la machine virtuelle.

Compléter la configuration de SQL Server pour
permettre la connexion à la base de données depuis un autre ordinateur

Par défaut, l’installation de SQL Server configure une base
de données qui n’est pas exposée à distance. Avant de pouvoir se connecter à
l’instance SQL via Internet, il est nécessaire de procéder à la configuration
de l’accès à distance en suivant les étapes suivantes :

  • Créer un point de terminaison TCP pour l’accès à la machine virtuelle.
  • Ouvrir les ports TCP sur le Pare-feu Windows de la machine virtuelle.
  • Configurer le service SQL Server pour activer l’écoute sur le protocole TCP.
  • Configurer SQL Server de façon à accepter le mode d’authentification SQL Server.
  • Créer les logins pour la connexion à SQL Server.

Ces étapes sont décrites ci-après dans la suite de ce guide.

Créer un point de terminaison TCP pour l’accès à la machine virtuelle

Par défaut, les machines virtuelles déployées sur Windows
Azure ne sont pas configurées pour accepter des connexions réseau. Pour établir
une connexion, il est donc nécessaire d’établir un canal de communication TCP
en créant un “point de terminaison” (endpoint).

Cette étape de la configuration permettra de rediriger le
trafic réseau vers un port TCP accessible à la machine virtuelle.

1. Dans le Portail Windows Azure, cliquer sur ORDINATEURS VIRTUELS, dans le
bandeau situé sur le côté gauche, puis cliquer sur le nom de la machine
virtuelle concernée. Le TABLEAU DE BORD de la machine virtuelle est
alors affiché.

2. Dans la portion supérieure de la fenêtre, cliquer sur l’option POINTS DE
TERMINAISON
, puis cliquer sur AJOUTER.

3. Sur la page AJOUTER UN POINT DE TERMINAISON, laisser l’option sélectionnée
par défaut et cliquer sur la flèche, situé en bas à droite, pour continuer.

4. Sur la page qui s’affiche, préciser les éléments suivants :

· Saisir un NOM pour le point de terminaison.

· Choisir le PROTOCOLE de communication TCP.

· Dans la zone PORT PUBLIC, choisir un numéro de port TCP,
par exemple 1433. Il s’agit du port qui recevra le trafic réseau depuis
Internet. Le numéro 1433 est typiquement utilisé par SQL Server pour les
communications TCP et il s’agit de la valeur par défaut utilisée par la console
SQL Server Management Studio. Étant donné qu’il peut être la cible d’attaques
malveillantes, de nombreuses organisations choisissent un numéro de port
différent.

· Dans la zone PORT PRIVÉ, saisir 1433. Tout autre numéro de
port peut également convenir.

5. Cliquer sur l’icône de validation, située en bas à droite, pour
continuer.

Le point de terminaison est ainsi créé.

Ouvrir les ports TCP sur le Pare-feu Windows de la
machine virtuelle

Lancer la console de configuration avancée du Pare-feu
Windows. Dans le Menu Démarrer, choisir “Start”, taper
“WF.msc”, puis ENTER.

1. Dans la console de configuration du Pare-feu,
sélectionner sur “Inbound Rules“,
puis cliquer avec le bouton droit de la souris sur “Inbound
Rules
” et choisir l’option “New
Rule…
“.

2. Dans la boîte de dialogue “New
Inbound Rule Wizard
“, sélectionner “Port
puis cliquer sur “Next“.

4. À l’étape « Protocol and Ports », sélectionner le
protocole TCP, choisir l’option « Specific local ports »
et saisir le numéro de port « 1433 » dans la zone de texte
correspondante. Cliquer sur « Next » pour continuer.

5. À l’étape « Action », choisir l’option « Allow the connection », puis cliquer sur « Next ».

Avertissement de sécurité : sélectionner
l’option « Allow the connection if it is secure »
procure une meilleure sécurité pour la connexion. Choisir cette option pour
configurer des paramètres additionnels permettant de renforcer la sécurité de
votre environnement.

6.      
À l’étape « Profile »,
sélectionner l’option « Public », puis
cliquer sur « Next ».

Avertissement : sélectionner l’option « Public »
autorise tout accès à la machine virtuelle depuis Internet. À chaque fois que
c’est possible, choisir une option de sécurité plus forte.

7. À la dernière étape « Name »,
saisir un nom en clair et, éventuellement, une courte description pour la règle
du Pare-feu, puis cliquer sur « Finish »
pour terminer.

Configurer SQL Server pour activer l’écoute sur le protocole TCP

De même qu’une machine virtuelle n’est pas configurée par
défaut pour accepter le trafic réseau depuis Internet, le service d’écoute SQL
Server doit être configuré pour permettre l’utilisation du protocole TCP.

Il est possible que cette étape soit déjà effectuée.

1. Une fois connecté à la machine virtuelle via la Connexion de Bureau à
Distance, lancer le programme SQL Server Configuration Manager, depuis
le Menu Démarrer. S’il n’apparaît pas dans le menu, choisir All Programs,
Microsoft SQL Server 2012, puis SQL Server Configuration Manager.

2. Dans la console de configuration SQL Server Configuration Manager,
développer le nœud SQL Server Network Configuration, puis cliquer sur Protocols for MSSQLSERVER.

3. Dans la zone de détail, si nécessaire, cliquer avec le bouton droit de la souris sur
le protocole TCP/IP, puis sélectionner Enable.

Un redémarrage du service SQL Server peut être nécessaire,
mais cette opération peut être différée à l’étape suivante.

Configurer SQL Server pour accepter le mode
d’authentification SQL Server

Le moteur de base de données SQL Server ne peut pas utiliser
l’authentification Windows en l’absence d’un domaine. Pour permettre la
connexion à SQL Server depuis un autre ordinateur, il est nécessaire de
configurer également le mode d’authentification propre à SQL Server.

Précision : la configuration de ce mode
d’authentification n’est pas strictement nécessaire si vous avez déjà configuré
un réseau privé virtuel Windows Azure, c’est-à-dire que vos machines virtuelles
Windows Azure ont été ajoutées à votre domaine d’entreprise.

4. Une fois connecté à la machine virtuelle via la Connexion de Bureau à
Distance, lancer le programme SQL Server Management Studio, depuis le
Menu Démarrer. S’il n’apparaît pas dans le menu, choisir All Programs, Microsoft
SQL Server 2012
, puis SQL Server Management Studio.

Le lancement initial de la console de gestion SQL Server
peut prendre un certain temps, durant lequel l’environnement utilisateur est
créé.

5. Dans la boîte de dialogue Connect to Server, vérifier
que le nom de la machine virtuelle est renseigné dans la zone de texte Server name. À défaut du nom du serveur, il est possible
de saisir la valeur (local) ou tout simplement le caractère ‘.
(point). Vérifier que le mode d’authentification sélectionné est Windows Authentication. Dans ce mode, le nom d’utilisateur est grisé et possède sa valeur par défaut, sous la forme nom_de_la_machine\Administrator.
Cliquer sur Connect.

6. Dans le panneau Object Explorer, situé sur le côté gauche, cliquer avec le
bouton droit de la souris sur le nom de l’instance SQL Server par défaut – qui
correspond au nom de la machine virtuelle – puis sélectionner Properties.

7. Dans la boîte de dialogue « Server Properties »,
sélectionner la page « Security ». Puis, dans la rubrique « Server Authentication », choisir l’option « SQL Server and Windows Authentication mode ». Puis
cliquer sur OK.

Suite à ce changement, un redémarrage du service SQL Server
est nécessaire. Une boîte de dialogue de confirmation s’affiche à cet effet.
Cliquer sur OK.

8. Dans Object Explorer, cliquer avec le bouton droit de la souris sur le
nom de l’instance SQL Server par défaut, puis sélectionner Restart, pour
redémarrer le service. Si l’agent SQL Server est en cours d’exécution, il doit
également être redémarré.

Dans la boîte de dialogue, cliquer sur Yes
pour confirmer le redémarrage du service SQL Server.

Créer les logins de connexion à SQL Server

La connexion à SQL Server depuis un autre connecteur
nécessite au minimum un login d’authentification.

1. Dans la console de gestion SQL Server Management Studio, développer le nœud
correspondant à l’instance par défaut SQL Server, dans laquelle créer un login
d’authentification.

2. Cliquer avec le bouton droit de la souris sur le nœud Security, puis sélectionner New|Login….

1. Dans la boîte de dialogue Login – New, sélectionner
la page General, puis saisir le nom de l’utilisateur
dans la zone de texte Login name.

2. Sélectionner le mode d’authentification SQL Server authentication.

3. Dans la zone de texte Password, saisir un mot de
passe pour le nouvel utilisateur. Confirmer le mot de passe dans la zone de
texte Confirm Password.

4. Pour renforcer la sécurité, il est recommandé d’opter pour le respect des règles de
complexité du mot de passe. Sélectionner l’option Enforce
password policy
. Cette option est sélectionnée par défaut lorsque le
mode d’authentification SQL Server est choisi.

5. Pour limiter les risques, il est recommandé de changer fréquemment le mot de passe
associé à un utilisateur SQL Server. Pour cela, sélectionner l’option Enforce password expiration. Cette option est
sélectionnée par défaut lorsque le mode d’authentification SQL Server est
choisi.

6. Pour forcer l’utilisateur à changer son mot de passe lors de la première connexion,
sélectionner l’option User must change password at next
login
. Il est recommandé d’utiliser cette option si le login
est destiné à un autre utilisateur. Cette option est sélectionnée par défaut
lorsque le mode d’authentification SQL Server est choisi.

7. Dans la liste Default database, sélectionner une base
de données par défaut pour le login. La base de données sélectionnée par
défaut est master.

8. Dans la liste Default language, laisser la valeur <default> renseignée par défaut.

9. S’il s’agit du premier login créé, il peut être opportun de
désigné ce login en tant qu’administrateur SQL Server. Pour cela,
sélectionner la page Server Roles, puis cocher
la case sysadmin.

Avertissement de sécurité : les membres du rôle
de serveur sysadmin ont un contrôle complet sur le moteur de base de
données. L’appartenance à ce rôle doit être restreinte et évaluée avec soin.

10. Cliquer sur OK pour terminer.

Félicitations : la machine virtuelle est prête à
l’emploi et la connexion à SQL Server est correctement configurée. Vous pouvez
désormais vous connecter à la base de données depuis un autre ordinateur ou une
application.

Se connecter à SQL Server depuis un autre ordinateur

Déterminer le nom DNS de la machine virtuelle

Pour se connecter à la base de données, il est important de
connaître le nom DNS de la machine virtuelle. Il s’agit du nom enregistré
auprès des serveurs Internet pour identifier la machine virtuelle. Bien qu’il
soit possible d’utiliser l’adresse IP de la machine virtuelle, celle-ci peut
changer à tout moment lorsque Windows Azure réorganise ses ressources à des
fins de redondance ou de maintenance. Il est donc recommandé d’utiliser le nom
DNS de la machine, qui est stable car il peut être redirigé lorsque l’adresse
IP change.

1.Dans le Portail Windows Azure, cliquer sur ORDINATEURS VIRTUELS,
dans le bandeau situé sur le côté gauche, puis cliquer sur le nom de la machine
virtuelle concernée. Le TABLEAU DE BORD de la machine virtuelle est
alors affiché.

2. Dans la rubrique aperçu rapide, située en bas à droite de la
page, repérer et copier le nom DNS dans le presse-papier. Il s’agit d’un nom de
la forme nom_de_la_machine.cloudapp.net.

Se connecter à l’aide de SQL Server Management
Studio

1. Sur un ordinateur connecté à Internet, lancer la console de gestion SQL Server
Management Studio,

2. Dans la boîte de dialogue Connect to Server ou Connect to Database Engine, saisir ou coller, dans la zone de texte Server name, le nom DNS déterminé
précédemment. Ne pas inclure de préfixe http://. Si le numéro du port TCP
public choisi pour le point de terminaison est différent de 1433, il doit être
précisé dans la zone de texte, précédé d’une virgule. Le nom complet est donc
de la forme : nom_de_la_machine.cloudapp.net,numero_de_port_tcp.

3. Sélectionner le mode d’authentification SQL Server Authentication.

4. Dans la zone de texte Login, saisir le nom
d’utilisateur créé précédemment.

5. Dans la zone de texte Password, saisir le mot de
passe choisi lors de la création du login.

6. Enfin, cliquer sur Connect pour se connecter à la base
de données.

Félicitations : vous êtes maintenant connecté à
votre environnement SQL Server hébergé sur Windows Azure.

Se connecter depuis une application

Si la connexion à SQL Server hébergé sur Windows Azure a pu
être établie avec succès depuis la console SQL Server Management Studio,
vous devriez être en mesure de connecter vos applications en utilisant une
chaîne de connexion de la forme :

connectionString="Server=nom_dns.cloudapp.net,numéro_de_port_tcp;Integrated
Security=false;User Id=login;Password=mot_de_passe;"

Pour aller plus loin

Les étapes optionnelles suivantes peuvent vous permettre de
tirer le meilleur parti de votre nouvel environnement virtuel hébergé sur
Windows Azure.

Migrer une base de données existante

Votre base de données SQL Server peut être déplacée sur votre
nouvel environnement Windows Azure en utilisant l’une des méthodes
suivantes :

  • Copier le fichier de sauvegarde de la base de données sur la
    machine virtuelle, puis effectuer une restauration. Pour plus d’informations,
    se reporter à la documentation, située à l’emplacement :
    Back Up and Restore of SQL Server Databases.
  • Copier les fichiers de base de données portant les extensions mdf,
    ndf et ldf dans un dossier de la machine virtuelle, puis attacher
    la base de données. Pour plus d’informations, se reporter à la documentation,
    située à l’emplacement :
    Attach a Database.
  • Créer un script de création de la base de données source, puis
    exécuter ce script à partir de la nouvelle instance SQL Server hébergée sur
    Windows Azure. Pour plus d’informations, se reporter à la documentation, située
    à l’emplacement :
    Generate and Publish Scripts Wizard.
  • Utiliser l’assistant de copie de bases de données, dans la
    console de gestion SQL Server Management Studio. Pour plus d’informations, se
    reporter à la documentation, située à l’emplacement :
    Copy Database Wizard.
  • En utilisant une application Data-tier (DAC). Déployer l’application en n’utilisant que le schéma
    de la base de données, ou bien importer une base de données en utilisant le
    fichier de sauvegarde BACPAC. Pour plus d’information, se reporter à la
    documentation, située à l’emplacement :
    Deploy a Data-tier Application
    How to Use Data-Tier Application Import and Export with SQL Azure (en-US)

Copier des fichiers sur la machine virtuelle

De petits fichiers (sauvegardes de base de données, fichiers
BACPAC, etc.) peuvent être copiés directement sur la machine virtuelle en
utilisant le mécanisme copier/coller du presse-papier à travers la Connexion de
Bureau à Distance.

Pour transférer des fichiers plus volumineux, utiliser l’une
des options suivantes :

  • Charger le fichier dans un BLOB, à l’aide d’un compte de stockage
    Windows Azure située sur le même centre de données que celui sur lequel est
    hébergée la machine virtuelle. Utiliser la Connexion de Bureau à Distance pour
    télécharger ce fichier depuis le BLOB.
  • Transférer le fichier sur un disque de partage réseau et
    configurer un réseau privé virtuel Windows Azure. Pour plus d’information,
    consulter la page suivante :
    Vue d’ensemble de la Mise en Réseau Windows Azure.
  • Transférer le fichier en utilisant FTP. Plusieurs étapes sont
    requises pour activer le transfert FTP sur la machine virtuelle, notamment,
    configurer IIS, créer un compte FTP, configurer un certificat SSL, etc. Pour
    plus d’informations, se reporter à la documentation Windows:
    FTP Publishing Service.
  • Utiliser un navigateur internet et télécharger une base de
    données d’exemple, telle que AdventureWorks depuis CodePlex, par exemple.

Désactiver le cache d’écriture disque

Pour des raisons de performances, le moteur de base de
données nécessite que le cache d’écriture soit désactivé pour les disques – à
la fois pour les données et le système d’exploitation.

Par défaut, le cache est désactivé pour un disque de
données, à la fois pour les opérations de lecture et d’écriture. En revanche,
le cache est activé par défaut pour un disque système.

Les nouveaux utilisateurs qui souhaitent évaluer les
performances d’un système SQL Server composé d’un seul disque – comme la
machine virtuelle hébergée sur Windows Azure – doivent au préalable désactiver
le cache du disque système pour les opérations d’écriture.

Utiliser PowerShell et les CmdLet Set-AzureOSDisk et Set-AzureDataDisk.

Créer des utilisateurs de base de données supplémentaires

Pour permettre l’accès à une base de données, les
utilisateurs dont le login n’est pas membre du rôle de serveur sysadmin
doivent être associés à une base de données et à un schéma. Pour ce faire,
créer un utilisateur supplémentaire dans la base de données.

Pour plus d’informations, se reporter à la documentation,
située à l’emplacement :

Créer un compte de connexion
http://msdn.microsoft.com/fr-fr/library/aa337562.aspx

Ajouter des instances de base de données supplémentaires

Le disque d’installation de SQL Server est disponible sur la
machine virtuelle dans un dossier situé à l’emplacement C:\SqlServer11.0Full.

Exécuter le programme d’installation pour ajouter ou
supprimer des fonctionnalités, ajouter ou réparer des instances, etc.

Ressources

Ce guide a été écrit dans le cadre d’un travail mené par
l’équipe Windows Azure France pour mettre en œuvre la création ou le relais de
tutoriaux pour la communauté francophone. Il est directement inspiré de la
documentation officielle
.

Par ailleurs, les ressources suivantes ont également été
utilisées pour la rédaction de ce guide :

[1] Windows
Azure Virtual Machines

[2]
Tarifs pour le service Machines Virtuelles Windows sur Windows Azure

Posted in Windows Azure | Tagged , , , | 1 Comment

Microsoft® MVP Integration 2013

It is with great honor and pleasure that I have been awarded Microsoft Most Valuable Professional for the third consecutive year.

This year marks the change in name from my previous expertise around “BizTalk”, to a more broad and general expertise in “Integration”.

In second part of last year, I have accompanied the creation of a new startup, where I have been working full time on designing, architecting and building the next generation EAI/ESB platform on the Cloud.

This year, I will strive to build a strong expertise around Windows Azure and the Cloud Computing, in order to complete my knowledge around integration.

Posted in Non classé | Tagged , , | Leave a comment

Prise en Main du Cache sous Windows Azure

This article has been written in an effort by the Windows Azure France team to coordinate the writing of tutorials and how-to guides for various Windows Azure features and technologies. This guide is a direct translation in french of the ‘How to Use Windows Azure Caching‘ guide, available on MSDN

Introduction

« Windows Azure Caching », est une nouvelle fonctionnalité de mémoire cache distribuée disponible pour vos applications Windows Azure.

Elle apporte une amélioration des performances de vos applications Windows Azure, en permettant le stockage en mémoire d’informations provenant de différentes sources de données, telles que des bases de données, par exemple. En stockant en mémoire les informations fréquemment utilisées en provenance d’une base de données, il est possible de réduire le nombre de transactions effectuées, améliorant d’autant la capacité de l’application à pouvoir monter en charge, par exemple.

Le Cache sous Windows Azure supporte l’enregistrement de tout objet .Net persistant (serialisable) et inclut un fournisseur de session et d’enregistrement du rendu des pages ASP.Net préconfigurés, permettant l’accélération des applications web sans modification.

Un modèle de développement unique, que ce soit pour le déploiement d’applications sur Windows Azure ou AppFabric 1.1 for Windows Server, permet d’exploiter la mise en cache.

Avertissement : le Cache sous Windows Azure remplace avantageusement une fonctionnalité similaire, « Windows Azure AppFabric Caching », qui s’appuie sur une infrastructure mutualisée. Celle-ci devient obsolète et il est recommandé de ne plus l’utiliser.

Au contraire, « Windows Azure Caching » introduit un nouveau modèle pour la mise en cache, en utilisant une portion de la mémoire des machines virtuelles sur lesquelles les instances de rôles s’exécutent.

En comparaison, l’utilisation des instances de rôles pour la mise en cache offre les avantages suivants :

  • Des options de déploiement plus souples, sans limites de taille ni quota de restrictions.
  • Pas de coût supplémentaire pour l’utilisation des ressources de mise en cache.
  • Un contrôle et un niveau d’isolation plus fins.
  • Une capacité à suivre la charge de l’application, en adaptant la taille du cache au nombre d’instances s’exécutant pour un rôle. La mémoire disponible pour le cache est effectivement augmentée ou réduite au fur et à mesure que des instances de rôle sont ajoutées ou supprimées.
  • Des performances améliorées.

En outre, une expérience du débogage proche du fonctionnement en production est également proposée, avec un service d’émulation du cache sur le poste de développement.

Ce guide de prise en main offre un aperçu rapide de la fonctionnalité de mise en cache de la mémoire sous Windows Azure. Les fonctionnalités démontrées dans ce guide sont les suivantes :

  • Configuration d’un cache cluster pour mise à disposition d’un cache d’application.
  • Configuration d’un rôle client du cache.
  • Ajout et récupération d’objets dans le cache.
  • Enregistrement du cache des sessions ASP.Net dans le cache Windows Azure.
  • Activation du cache pour le rendu des pages ASP.Net.

Pour une référence plus détaillée du Cache sous Windows Azure, n’hésitez pas à vous reporter à l’un des articles officiels, référencés à la fin de ce guide.

Premiers pas

Comme indiqué, le Cache sous Windows Azure utilise la mémoire des machines virtuelles associées aux instances de rôle pour fournir un espace de mémoire cache. Les instances de rôle qui contribuent à fournir de l’espace au cache forment collectivement le cache cluster.

Le cache cluster doit être configuré au préalable à la mise à disposition aux clients du cache.

Configuration du cache cluster

Le Cache sous Windows Azure peut être déployé selon deux topologies de mise en cache qui se distinguent par l’utilisation ou non de rôles existants :

  • Cache colocalisé : l’utilisation de rôles existants pour la fourniture du cache mutualise les ressources – en particulier, la mémoire vive – utilisées pour l’exécution de vos applications.
  • Cache dédié : la création de rôles dédiés à la fourniture du cache permet l’utilisation de l’intégralité des ressources associées aux machines virtuelles qui forment le cache cluster.

La configuration d’un cache colocalisé se fait en spécifiant un pourcentage d’utilisation de la mémoire disponible pour chaque instance d’un rôle. Pour ce faire, afficher les propriétés d’un rôle existant et sélectionner la rubrique « Cache » d’application :

L’activation du cache sur un rôle existant crée, par défaut, un cache cluster colocalisé qui tire parti de 30% de la mémoire associée à chacune des instances. Un cache par défaut est également configuré automatiquement, mais il est possible de créer d’autres espaces de cache logiques si nécessaire.

Un cache cluster doit maintenir les données de configuration et synchroniser sont état de fonctionnement entre les différentes machines virtuelles qui contribuent au cache. C’est pourquoi il est nécessaire de préciser un compte de stockage Windows Azure valide à cet effet.

Avertissement : si aucun compte de stockage n’est configuré, le rôle ne pourra pas démarrer.

La configuration d’un cache dédié peut se faire via l’ajout d’un projet de rôle « Cache Worker Role » à la solution:

La création d’un rôle dédié au cache créé un rôle sans implémentation particulière et auquel il est recommandé de ne rien ajouter, sous peine d’impacter négativement les performances du cache.

De même que précédemment, ne pas oublier de préciser un compte de stockage Windows Azure valide pour le maintien et la synchronisation de l’état de fonctionnement du cache.

Dans tous les cas, la taille exacte du cache résulte d’une combinaison de facteurs, parmi lesquels :

  • Le caractère colocalisé ou dédié du cache cluster.
  • La taille des machines virtuelles associées au rôle.
  • Le nombre d’instances configurées.

La taille et le nombre d’instances configurées pour l’exécution d’un rôle sont accessibles dans les propriétés de configuration de chacun des rôles :

Pour référence, la taille totale pour la mémoire allouée aux machines virtuelles est listée ci-après. Cette mémoire est partagée entre l’exécution du système d’exploitation, le processus de gestion et les données du cache, ainsi que, dans le cas de la colocalisation, de vos applications. En tout état de cause, la taille disponible pour le cache lui-même peut-être inférieure.

  • Small : 1,75 Go.
  • Medium : 3,5 Go.
  • Large : 7 Go.
  • Extra Large : 14 Go.

À noter que le cache n’est pas supporté sur des machines dont la taille est configurée à Extra Small.

Configuration des rôles clients du cache

Les rôles clients du cache doivent être situés dans le même déploiement que celui dans lequel est configuré le cache cluster.

Dans le cas d’un cache dédié, les rôles clients du cache sont tout simplement les autres rôles hébergés dans le service. Si le cache est colocalisé, il peut s’agir de n’importe quels rôles hébergés dans le service, y compris ceux destinés à l’exécution du service de cache.

La configuration de chaque rôle client du cache peut être effectuée via l’installation d’un package NuGet « Microsoft.WindowsAzure.Caching » qui peut être directement installé à l’aide du gestionnaire de packages dans Visual Studio :

Avec le bouton droit de la souris, cliquer sur le projet de rôle auquel ajouter l’accès au cache, et sélectionner « Manage NuGet Packages… ». Dans la boîte de dialogue qui s’affiche, sélectionner le package « Windows Azure Caching », cliquer sur Install puis sur I accept.

Si le package n’apparaît pas dans la liste, utiliser la zone de texte Search Online (Ctrl+E) pour effectuer une recherche sur « WindowsAzure Caching ».

Le package NuGet effectue les actions suivantes ; il modifie le fichier de configuration du rôle, ajoute un paramètre de niveau de diagnostique pour le client du cache au fichier ServiceConfiguration.csfg associée à l’application Windows Azure, et ajoute les références d’assembly appropriées.

De plus, pour un web rôle ASP.Net, le package NuGet ajoute deux sections au fichier web.config ; la première concerne le paramétrage du cache de session ASP.Net et la seconde active la mise en cache du rendu des pages ASP.Net. Ces deux fonctionnalités sont expliquées plus bas dans ce guide.

Les références d’assembly suivantes sont nécessaires pour l’accès au cache :

  • Microsoft.ApplicationServer.Caching.Client.dll
  • Microsoft.ApplicationServer.Caching.Core.dll
  • Microsoft.WindowsFabric.Common.dll
  • Microsoft.WindowsFabric.Data.Common.dll
  • Microsoft.ApplicationServer.Caching.AzureCommon.dll
  • Microsoft.ApplicationServer.Caching.AzureClientHelper.dll

Dans le cas d’un web rôle ASP.Net, la référence d’assembly suivante est également ajoutée :

  • Microsoft.Web.DistributedCache.dll.

La configuration du rôle est modifiée lors de l’installation du package NuGet. Deux nouveaux éléments, dataCacheClients et cacheDiagnostics, sont ajoutés au fichier web.config ou app.config, dans la section de configuration configSections. S’il n’y avait pas d’élément configSections dans le fichier, il est initialement créé en tant qu’enfant de l’élément configuration.

 <configuration>
 <configSections>
 ...
 <section name="dataCacheClients"
 type="Microsoft.ApplicationServer.Caching.DataCacheClientsSection, Microsoft.ApplicationServer.Caching.Core"
 allowLocation="true" allowDefinition="Everywhere"
 />

 <section name="cacheDiagnostics"
 type="Microsoft.ApplicationServer.Caching.AzureCommon.DiagnosticsConfigurationSection, Microsoft.ApplicationServer.Caching.AzureCommon"
 allowLocation="true" allowDefinition="Everywhere"
 />
 </configSections>

Ces deux sections font référence à deux nouveaux éléments, respectivement, dataCacheClients et cacheDiagnostics, tous deux également ajoutés sous l’élément configuration.

<dataCacheClients>
    <dataCacheClient name="default">
      <autoDiscover isEnabled="true" identifier="[cache cluster role name]" />
      <!--
     <localCache isEnabled="true"
              sync="TimeoutBased"
              objectCount="100000"
              ttlValue="300" />
     -->
    </dataCacheClient>
  </dataCacheClients>
  <cacheDiagnostics>
    <crashDump dumpLevel="Off" dumpStorageQuotaInMB="100" />
  </cacheDiagnostics>

Une fois la configuration ajoutée, modifier l’emplacement réservé [cache cluster role name] par le nom du rôle configuré pour l’exécution du cache cluster.

Avertissement : à défaut, une exception TargetInvocationException sera levée au moment de l’exécution. Sa propriété InnerException renverra un objet DatacacheException avec le message « No such role exists. »

L’installation du package NuGet ajoute également un paramètre ClientDiagnosticLevel à la section ConfigurationSettings associée au rôle client du cache dans le fichier ServiceConfiguration.csfg. À titre d’exemple, voici une section correspondante du fichier ServiceConfiguration.csfg :

  <Role name="WebRole1">
    ...
    <ConfigurationSettings>
    ...
    <Setting name="Microsoft.WindowsAzure.Plugins.Caching.ClientDiagnosticLevel"
             value="1" />
    </ConfigurationSettings>
  </Role>

Le Cache sur Windows Azure est sensible à la fois au niveau de diagnostic du cache cluster et à celui du ou des rôles clients du cache. Le niveau de diagnostic est un paramètre utilisé pour filtrer le niveau d’informations collectées lors de l’exécution du cache. Sa valeur par défaut est 1.

Une fois le rôle client du cache correctement configuré, se reporter aux techniques décrites dans les sections suivantes pour la manipulation du cache.

Manipulation du cache

Instanciation d’un objet DataCache de manipulation du cache

Afin de pouvoir interagir avec le cache, il est nécessaire d’y faire référence, en ajoutant l’espace de nommage suivant parmi le groupe des instructions using situées en haut de chaque fichier source dans lequel il est nécessaire d’accéder au cache.

using Microsoft.ApplicationServer.Caching;

Si Visual Studio ne reconnaît pas l’instruction using, même après avoir installé le package NuGet « Windows Azure Caching » qui ajoute les références d’assembly appropriées, s’assurer que la cible du projet est correctement configurée à .Net Framework 2.0 ou ultérieure, à l’exception des profils affublés de la mention « Client Profile ». Se reporter à la section précédente relative à la configuration des rôles clients du cache pour obtenir des instructions plus précises.

Un premier moyen pour instancier un objet DataCache est tout simplement de créer une nouvelle instance en passant le nom du cache logique en paramètre du constructeur. Il est ensuite possible d’ajouter des objets dans le cache ou de récupérer des objets depuis le cache en suivant les instructions décrites dans la section suivante de ce guide.

DataCache dataCache = new DataCache("default");

Un autre moyen pour instancier un objet DataCache est d’utiliser l’objet DataCacheFactory dans votre application. L’utilisation du constructeur par défaut force l’utilisation des paramètres figurant dans le fichier de configuration.

Appeler, sur l’instance DataCacheFactory, la méthode GetDefaultCache ou bien la méthode GetCache en précisant le nom du cache logique. Ces deux méthodes renvoient un objet DataCache avec lequel il est possible d’utiliser le cache comme indiqué dans la prochaine section.

// cache client configured by settings in configuration file

DataCacheFactory cacheFactory = new DataCacheFactory();
DataCache cache = cacheFactory.GetDefaultCache();

// or select named cache 
//DataCache cache = cacheFactory.GetCache("MyCache");

// cache can now be used to add, retrieve or remove items 

Ajout et récupération d’objets dans le cache

Pour ajouter un élément dans le cache, l’une des méthodes Add ou Put peut être utilisée. La méthode Add ajoute l’objet spécifié en l’associant à une clé, précisée par la valeur du paramètre key. Si un objet possédant la même clé est déjà enregistré dans le cache, une exception de type DataCacheException sera levée au moment de l’exécution, avec le message suivant :

ErrorCode:SubStatus: An attempt is being made to create an object with a Key that already exists in the cache. Caching will only accept unique Key values for objects.

// adds the string "value" to the cache, keyed by "item"
string value = "value";
cache.Add("item", value);

La méthode Put ajoute également un élément dans le cache, en utilisant la clé précisée. Si un objet possédant la même clé est déjà présent dans le cache, il est remplacé par le nouvel élément spécifié lors de l’appel de cette méthode.

// adds or replaces the string keyd by "item" in the cache
string newValue = "newValue";
cache.Put("item", newValue);

Pour récupérer un élément enregistré dans le cache, utiliser la méthode Get. Cette méthode retourne l’objet spécifié s’il existe. Dans le cas contraire, cette méthode retourne null.

string value = String.Empty;

// retrieves an item from the cache, keyed by "item"
object result = cache.Get("item");
if (result == null)
{
    // "item" not in cache. Obtain it from specified data source
    // and add it to the cache for later retrieval
    value = GetItemValue(...);
    cache.Add("item", value);
}
else
{
    // "item" is in cache, cast result to correct type.
    System.Diagnostics.Debug.Assert(result is string);
    value = result as String;
}

Gestion du délai d’expiration des éléments du cache

Par défaut, les éléments placés dans le cache expirent, et sont supprimés du cache, au bout de 10 minutes. Ce délai est précisé par la valeur du paramètre Time to Live (min) associée au cache nommé dans les propriétés du rôle qui héberge le cache cluster.

Il y a trois façons de préciser le délai d’expiration d’un objet dans le cache, en sélectionnant le paramètre Expiration Type associé au cache nommé.

Par défaut, le délai d’expiration est exprimé de manière absolue. Le délai d’expiration d’un élément commence dès qu’il est placé dans le cache. Une fois le délai écoulé, l’élément expire et est supprimé du cache. Cela correspond au réglage Absolute. Placé sur Sliding Window, le délai d’expiration d’un élément est remis à zéro à chaque fois qu’une tentative de récupérer ou mettre à jour cet élément est effectuée dans le cache. L’élément n’expire que si aucun accès n’y est fait pendant toute la durée du délai d’expiration. Enfin, si le paramètre est placé à la valeur None, le délai d’expiration doit avoir pour valeur 0. Les éléments placés dans le cache n’expirent jamais et restent valides tant qu’ils sont dans le cache.

Si un délai d’expiration différent de celui configuré dans les propriétés du rôle est nécessaire, il est possible de préciser une valeur spécifique au moment de l’ajout ou de la mise à jour d’un élément du cache en utilisant les surcharges des méthodes Add et Put qui acceptent un paramètre de type TimeSpan. À titre d’exemple, voici comment préciser un délai de trente minutes :

// adds the string "value" to the cache, keyed by "item"
string value = "value";
cache.Add("item", value, TimeSpan.FromMinutes(30));

Pour obtenir le délai d’expiration d’un élément particulier dans le cache, la méthode GetCacheItem permet d’obtenir un objet DataCacheItem qui contient certaines informations relatives à l’élément placé dans le cache, y compris le temps restant jusqu’à expiration :

// obtain a DataCacheItem containing informations about a cache item.
// if no object keyed "item" exists, then null is returned.
DataCacheItem item = cache.GetCacheItem("item");
if (item != null)
{
    TimeSpan remaining = item.Timeout
    ...
}

Enregistrement du cache de session ASP.Net dans le cache

Le Cache sur Windows Azure inclut un fournisseur ASP.Net pour l’enregistrement de l’état de session dans le cache, plutôt que directement en mémoire ou dans une base de données SQL. Pour utiliser ce fournisseur, s’assurer au préalable d’avoir correctement configuré le cache cluster et le web rôle en tant que client du cache en suivant les étapes décrites plus haut dans ce guide.

L’installation du package NuGet ajoute une section commentée dans le fichier web.config. Cette section contient tout le paramétrage nécessaire à l’utilisation du fournisseur d’enregistrement de l’état de session pour la Cache sur Windows Azure.

    <!-- Windows Azure Caching session state provider -->
    <!--<sessionState mode="Custom" customProvider="AFCacheSessionStateProvider">
      <providers>
        <add name="AFCacheSessionStateProvider"
type="Microsoft.Web.DistributedCache.DistributedCacheSessionStateStoreProvider, Microsoft.Web.DistributedCache"
                cacheName="default"
                dataCacheClientName="default"
                applicationName="AFCacheSessionState"/>
      </providers>
    </sessionState>-->

Si le fichier web.config ne contient pas cette section commentée, s’assurer que la version la plus à jour du gestionnaire de packages NuGet est installée. Au besoin, supprimer puis ré-installer le package NuGet « Windows Azure Caching » pour que le fichier web.config soit correctement mis à jour.

Pour activer l’utilisation du fournisseur d’enregistrement de session, supprimer simplement les commentaires autour de la section correspondante dans le fichier web.config. Dans l’exemple ci-dessus, le cache par défaut est utilisé. Pour utiliser un autre cache nommé, préciser simplement son nom dans l’attribut cacheName.

Pour plus d’information sur l’utilisation du fournisseur d’enregistrement de l’état de session ASP.Net, se reporter aux liens officiels qui figurent en ressources à la fin de ce guide.

Activation du cache pour le rendu des pages ASP.Net

Le Cache sur Windows Azure inclut également un fournisseur ASP.Net pour l’enregistrement du rendu des pages web dans le cache. Ce fournisseur est spécifiquement conçu pour l’enregistrement de réponses http complètes – ce qui correspond à des pages entières. Le fournisseur tire parti du nouveau mécanisme d’extension des fournisseurs d’enregistrement du rendu des pages introduit avec ASP.Net 4.

Pour utiliser ce fournisseur, s’assurer au préalable d’avoir correctement configuré le cache cluster et le web rôle en tant que client du cache en suivant les étapes d’installation du package NuGet décrites plus haut dans ce guide.

L’installation du package NuGet « Windows Azure Caching » ajoute une section commentée dans le fichier web.config. Cette section contient tout le paramétrage nécessaire à l’utilisation du fournisseur d’enregistrement du rendu des pages en cache dans Windows Azure.

    <!-- Windows Azure Caching output caching provider -->
    <!--<caching>
      <outputCache defaultProvider="AFCacheOutputCacheProvider">
        <providers>
          <add name="AFCacheOutputCacheProvider"
type="Microsoft.Web.DistributedCache.DistributedCacheOutputCacheProvider, Microsoft.Web.DistributedCache"
                cacheName="default"
                dataCacheClientName="default"
                applicationName="AFCacheOutputCache" />
        </providers>
      </outputCache>
    </caching>-->

Si le fichier web.config ne contient pas cette section commentée, s’assurer que la version la plus à jour du gestionnaire de packages NuGet est installée. Au besoin, supprimer puis ré-installer le package NuGet « Windows Azure Caching » pour que le fichier web.config soit correctement mis à jour.

Pour activer l’enregistrement du rendu des pages ASP.Net en cache, supprimer simplement les commentaires autour de la section correspondante dans le fichier web.config. Dans l’exemple ci-dessus, le cache par défaut est utilisé. Pour utiliser un autre cache nommé, préciser simplement son nom dans l’attribut cacheName.

Ajouter ensuite une directive OutputCache en en-tête de chacune des pages qui doivent être mises en cache.

<%@ OutputCache Duration="60" VaryByParam="*" %>

Dans cet exemple, les données de page mises en cache le seront pendant 60 secondes. Une version différente de la page sera également mise en cache pour chaque combinaison de paramètres.

Pour plus d’information sur l’utilisation du fournisseur d’enregistrement de l’état de session ASP.Net, se reporter aux liens officiels qui figurent en ressources à la fin de ce guide.

Autres ressources

Ce guide a été écrit dans le cadre d’un travail mené par l’équipe Windows Azure France pour mettre en œuvre la création ou le relais de tutoriaux pour la communauté francophone. Il est directement inspiré du tutorial officiel, situé à l’emplacement suivant :

[1] How to Use Windows Azure Caching
http://www.windowsazure.com/en-us/develop/net/how-to-guides/cache/

Les ressources suivantes ont également été utilisées, en partie, pour la rédaction de ce guide de prise en main :

[2] Overview of Windows Azure Caching

[3] Windows Azure Caching FAQ

[4] Capacity Planning Considerations for Windows Azure Caching

[5] Session State Provider for Windows Azure Caching

[6] Output Cache Provider for Windows Azure Caching

Posted in Windows Azure | Tagged , , | 1 Comment

My Review of the Microsoft Surface for Windows RT

Ever since Windows 8 has been announced to the world back in September 2011, I have been very excited and interested in the direction that Microsoft is taking, in order to virtually regain a foothold in the mobile industry – a market that has been taken over by competitors such as Apple and Google for so long.

And ever since Microsoft announced the line of Surface Tablet computing devices back in June, I have been doubly excited and knew I would be one of the first to purchase one when available.

I’ve been using Windows 8 virtually from day one, on a Samsung Tablet – the one that has been given to every //build/ attendee, back in September 2011 – using each and every publicly available iteration of the system – from the Developer Preview, the Consumer Preview, the Release Preview, the RTM version and finally the Generally Available version that everybody can use now, with a vastly optimized system, slightly updated or enhanced built-in Apps and a substantially larger number of Windows Store Apps to choose from.

Most of you know that, by now, Windows 8 has launched and is available for purchase. What’s more interesting however, is the availability of new hardware accompanying the operating system, most noticeably new tablets of which Microsoft Surface for Windows RT is but the first available.

In the recent weeks leading up to the launch of Surface, I have seen mostly mixed and even negative reviews. But I always had a feeling the authors of these reviews either did not fully grasp what Windows RT is about or, most probably, did not have the chance to use and touch the tablet for real before writing their review.

Since I have been using Windows RT for a little less than a week, now is therefore a good time for a fair an honest review.

Here goes.

Evaluating the Hardware

Surface for Windows RT Packaging

Out of the box, the Surface for Windows RT feels heavy, in a sturdy and solid sort of way. Its boasts this distinctive industrial design that is the hallmark of any great product. Looking at the specs, it’s actually just a teeny bit 28-grams heavier than the current-generation iPad, so that’s more of an impression.

One of the distinguishing features of the Surface is its kickstand. Why didn’t anybody ever think of this before? Its primary use, together with the included keyboard cover, is to make the tablet look like a laptop. But you can use it to show off pictures and slideshows during family events.

The Touch Cover is brilliant. Its serves as a protecting cover with a rough scratch-resilient and spill-resistant finish. It “clicks-in” automagically to its intended position and doubles as a multi-touch keyboard. The keyboard has a decent size and each key is where it should be – with the odd omission of the Fn-keys usually found on the upper row of any standard keyboard. It sure beats using the on-screen keyboard for more than casual editing and you can rest your fingers on the keyboard without fear of inadvertent typing.

However, typing on the Touch Cover is not an entirely satisfying experience because there is no feedback and one needs to constantly check for any typo. You also need to dose the applied pressure for typing and that certainly takes a certain amount of getting used to. My guess is that this situation will improve a bit over time – as will the speed of typing – as the habit sinks in.

In terms of connectivity, the tablet boasts a full-size USB connector that allows you to plug a wide range of peripherals. I’ve been able to insert thumb drives and a couple of wireless mouse dongles that have been instantly recognized. Key scenarios for using the USB port is to allow file transfer, accessing pictures from a digital camera and, of course, making the device a laptop-like productivity tablet with a mouse and Microsoft Office.

The Surface also has a micro-SD slot located just beneath the kickstand which is a welcome addition and gives us yet more options for expansion.

The micro-HDMI connector allows for full-HD video output on a secondary monitor, which makes the prospect of using the including Microsoft Office Suite much more appealing. But why on earth does Microsoft think you need a set or proprietary adapters – whose retail price starts at 40€ in the Microsoft Store – is beyond me.

On a final note, I was slightly disappointed to observe that the stylus that comes with the //build/ tablet does not work on the Surface RT screen. I’m told that any capacitive stylus should work just fine, but I find this confusing at this stage.

Likewise, the lack of GPS and NFC chipsets in the Surface RT disappoints the geek in me. But, to be honest, I had them on my //build/ tablet and actually never used them – perhaps due to a lack of software. Without capabilities to access 3G/4G mobile broadband networks, the Surface RT is primarily positioned for home use so that’s a point worth bearing in mind when evaluating which tablet to purchase.

One of the most touted feature found on competitor’s tablets is their obscenely high™ resolution display. Well, clearly, at only 1366×768, the Surface for Windows RT is way behind in terms of raw spec. However, watching movies and working on Word documents this week has been entirely satisfying so that’s not something that will have a noticeable impact in everyday use. Sure, it would have been nice for a 2012-ish tablet to match the current state of the competition, though.

Evaluating the Software

As its name suggest, Surface for Windows RT runs a special-purpose, modified version of Windows 8 primarily dedicated to running on low power devices equipped with an ARM processor. It is important to stress that Windows RT is different enough from Windows 8 in that it does not run Win32 applications but only Apps available from the Windows Store. This limitation is to make sure the system stays responsive and the performances do not degrade over time.

That said, Windows RT includes nonetheless a desktop version of Microsoft Office that has been ported to the ARM architecture. Currently, Microsoft Office is the only piece of desktop software running on Windows RT and it is not possible for anyone outside Microsoft to write desktop applications for Windows RT.

Just after joining a WiFi network and setting up a user account, one of the first things to do is performing a system update and downloading latest versions of the built in Apps. This left me a capacity of around 45 Gb for a maximum of 54 Gb – which is the capacity seen by Windows for the advertised 64 Gb storage. This is quite a substantial loss for the remaining capacity. That probably explains why the Surface RT is not available with 16 Gb of storage capacity.

However, the micro-SD slot offers cheap storage expansion and, while it’s not possible to make use of this extra space for installing applications, it’s certainly possible to use it for storing extra documents and media. Although it’s not supported to bring this added space in your Windows Libraries – because it comes from removable storage – there are ways to circumvent this by making directory junctions, using the mklink.exe command-line utility which is present on the tablet. So you can definitely take advantage of this extra space and make it appear to be part of your Documents, Pictures, Music and Videos folders.

The ability to setup multiple user accounts makes sharing the tablet with other members of the family straightforward and secure, with the built in parental control. This, to me, is one of the killer features of Windows, not seen as far as I know on any other competitor’s device.

On the subject of security, the tablet comes with an enhanced version of its antivirus and malware prevention software called Windows Defender – formerly called Microsoft Security Essentials. The software is setup to be updated automatically and protects the tablet in real-time. No regular security scans are planned though, since this would consume power and mostly make sense after having installed third-party software, which is not possible here. But you can still perform security scans, either scheduled or on-demand if you receive suspicious attachments or transfer files from unknown or unreliable sources.

On the Modern UI side – the new Start Screen – everything is exactly the same as in Windows 8. It provides a host for all Windows Store immersive Apps, pinned sites and live tiles as well as shortcuts to favorite desktop apps – most notably Microsoft Office applications. This is where you’ll spend most of your time using the tablet, consuming contents and enjoying a “fast and fluid” experience. There are currently thousands of Apps in the Store and – if sources are to be trusted – many more are coming in the next few months.

Most applications launch in a few seconds but need to perform network synchronization in the background upon start, so it can take up a tiny bit of extra time before being fully usable. After that, you can switch between all open applications very quickly. Mind you, the tablet being a mobile device, you’re not supposed to “close” an application and it is best to let Windows manage the lifetime of each application. It will take care of killing least used applications when memory is at a premium and will ensure the system always stays responsive over time.

The Modern UI Start Screen is very pleasant to use, with is vibrant colors and live tiles. But the desktop is still there, should you need it for advanced tweaking or productivity work.

Microsoft Office Home and Student 2013 Preview is there and, what to say? This in itself is probably the number one argument in favor of purchasing a Windows RT powered tablet. At this stage, I haven’t had the time to use it extensively but the experience appears to be identical to that of using Office on Windows 8 – apart from the obvious differences between editions and the expected omission of macros and support for ActiveX components. There seems to be confusion, though, over whether this edition of Office can be used in a business or commercial way. But my understanding is that your company must have a valid license of Microsoft Office already for this to permitted. In my view, that does not constitute a realistic problem since virtually every company I’ve ever worked with or for does indeed have a valid license of Microsoft Office.

Let’s not forget that this tablet targets home users and students. Therefore, Outlook is missing. But that can easily be replaced with the browser-based Outlook Web App or the built in, albeit simpler, Mail App.

There was a slight but noticeable latency when typing in Microsoft Word, until I realized that I was still using the preview version that was installed in the factory. Oddly enough, the final version of Office did not update automatically when I first set the device up because it was not considered an “important” update. After downloading and installing the required update, I found Word performing quickly and efficiently as it always should have. So, if you purchase the Surface, make doubly sure that Office is up to date before using it.

Another major application on the desktop is Internet Explorer 10. By and large, IE 10 is designed around a plugin-free browsing experience in favour of a more modern hardware-accelerated HTML5 and JavaScript powered web sites.

With the notable exception of Adobe Flash, which works in most – as in, “approved by Microsoft” – websites, including YouTube.

It’s interesting to note that, on full Windows 8, « Desktop IE » is the elder brother to the Modern UI App on the Start Screen and is there mostly to play legacy websites. Those requiring ActiveX and Silverlight plugins obviously, but also all those Adobe Flash powered websites not on the whitelist. This means that “Desktop IE” on Windows 8 displays more of the web than its Modern UI brethren.

However, sources at Microsoft confirm that, on Windows RT, both “Desktop IE” and the Modern UI IE are subject to the whitelist of approved web sites for which Adobe Flash content will be played. That’s a point worth mentioning for people trying to list differences between (the shared portions of) Windows RT and Windows 8.

To be honest, the web is already moving on from Flash – in no small part, thanks to the stance taken by Apple against this technology. But pragmatism at Microsoft makes it so that YouTube works so, what’s there to complain about?

On the desktop, the list of other software is meagre, but that is to be expected on a tablet not able to run (any arbitrary) Win32 applications. I would have welcomed little tools, though, such as the Journal application, Sticky Notes, and several others usually found on touched-enabled versions of Windows and which would have made sense on this tablet. Conversely, there’s an XPS viewer which, at first glance, seems redundant with the Modern UI Reader App.

To be complete, Windows Media Player is not there but would have been of no use in my opinion, since it almost always requires additional codecs to fully play popular videos. I think the built in Video App is better suited for this task on a mobile device anyway.

Please note, however, that the following software is present:

  • Voice Recognition – I don’t know what this is worth but it might be interesting to find out what is the quality and usefulness of this application on the Surface RT.
  • Windows Powershell – for the geeks? If it is included, there might be interesting things to do. Again, might be interesting to find out exactly.

In closing, I would like to address a few points worth considering, to make it clear where Windows RT sits exactly in the Windows universe.

Where does the Surface for Windows RT sit in the Windows 8 ecosystem?

In terms of capabilities, the Microsoft Surface for Windows RT tablet is a direct competitor to the Apple iPad. And one that, objectively, has the potential to be more capable than the iPad.

Given the recent growth to the number of available apps in the Windows Store – which went from about 5000 to more than 9000 apps in a matter of three to four days – it is safe to say that, given the right set of Apps, the iPad does virtually nothing that the Surface for Windows RT can’t do.

Conversely, there are a lot of things that the Surface does out of the box, that aren’t readily possible on the iPad.

What about gaming and entertainment? Just plug an XBox-compatible game controller and you have access to hardware-accelerated current generation games. You can even connect the tablet to an external monitor or TV and there you go! You have what essentially amounts to a game console.

Someone said : “if Angry Birds does not run on your system, you don’t have a platform”. Well Angry Birds is there…

The truth is, a fairly large selection of games are available since launch, and more are coming along the way.

Mapping a network folder is also a good scenario, whereby a user will be able to quickly access his or her content, stored on another home computer or network drive.

Even though the “Surface RT” is intended to be used by casual users and students, in this day and age of “BYOD” – Bring your own device – a lot of people would want to make use of their tablet for business purposes while on the go.

What, for instance, if you receive a ZIP file, containing slides for a business presentation that you need to make last-minute adjustments to? Just save the ZIP attachment somewhere on the file system, drop to the Desktop and fire up PowerPoint. You can make edits and modifications using the integrated Touch Cover all you want, no problem there… How about trying that on an iPad?

For more advanced usage, you can use any of the included remote desktop clients – on the Desktop or as a Modern UI App – and have access to virtually all corporate workstations and servers.

Out of the box.

So, who is Windows RT for?

So is it for everybody? Let’s put it this way : is a single product for everybody? It never is, that’s a fact of life. In that same way, Windows RT is probably not for everybody.

But, my view is that all the different versions of “Windows 8” and all the different hardware combinations it runs on have a vastly greater intended audience than any of their competitors.

Is the iPad for everyone? Its price alone makes it a premium product, which, by definition, is not for everyone. Some want more expansion ports or connectivity options. Some want more compatibility with standards or existing hardware products – Lightning Connector, anyone?

Again, is an Android tablet for everyone? Perhaps not. Some want a more streamlined and homogeneous user interface. Some do not tolerate even a slight lag when swiping user interface elements.

The truth is, Windows 8 is not a single product. It’s actually many different products, all sharing the same central, touch-based, Windows Store-distributed, Modern UI “fast and fluid” immersive Apps. And each one of these different products is targeting a different segment of the market.

With Windows 8 and Windows RT, chances are you’ll find one combination that’s right for you.

So, there you have it. A quick review of the last few days using the Surface for Windows RT. I have strived to give you a fair and balanced point of view. Please, leave comments, suggestions for improvements or requests for thing I may have missed. But please, keep the comments polite and civilized.

Posted in Non classé | Tagged , , | 2 Comments

IISConfigurator stopped working

In the past few months, I’ve worked on a large project involving the design and implementation of a SaaS offering powered by Windows Azure. The learning curve was quite steep but I think I have become more confortable over time and can now make sensible choices for my design and architectures.

Anyways, using Windows Server 2012 and Visual Studio 2012 exclusively for the past few weeks, one of the first error I encountered was an unexpected crash when starting a Cloud Service in the Development Environment. Even though the role instances start and execute successfully, there’s always this nagging error below:

As it turns out, this seems to be a rather known error, due to the ASP.Net application expecting IIS 7.0 instead of the new IIS 8.0 version that ships with Windows Server 2012. The solution is rather simple, as you need to install the IIS Management Console feature to make this error go away.

PS> Add-WindowsFeature Web-Mgmt-Console

Success Restart Needed Exit Code      Feature Result
------- -------------- ---------      --------------
True    No             Success        {IIS Management Console, Management Tools}
PS>
Posted in PowerShell, Windows Azure | Leave a comment

Creating Strongly-Typed C# Event Tracing for Windows (ETW) Assemblies with Visual Studio

The Event Tracing for Windows (ETW) Framework is a high-performance logging subsystem of Windows available to kernel-mode and user-mode developers for instrumenting mission critical and large scale applications.

Starting with Windows Vista, ETW is the foundation for instrumenting many components of Windows, including the Windows Event Log.

For this reason, ETW is primarily meant to be used from native code and the support tools and associated APIs are geared towards C++ developers. For a long time, there was no easy or straightforward way to instrument ones’s own managed application for ETW. However, things are starting to change.

The System.Diagnostics.Eventing namespace in the .Net 3.5 Framework has brought developers basic support for using ETW by wrapping core structures and APIs. With this support, it’s relatively easy to build a managed wrapper around logging and tracing. However, one still needs to declare and maintain the event structures themselves in an XML instrumentation manifest file. Surely, things will get even easier with and improved and streamlined support in the upcoming 4.5 version of the .Net framework.

If you ever wanted to add ETW support to your application, you might have stumbled upon this post where the author has made some efforts to bridge the gap between the native way and the .net way of using the tooling necessary to make use of ETW. And you might have walked away and reverted to using plain old vanilla Trace.WriteLine statements in your code… I know I nearly have !

Fear not ! In this post, I would like to walk you through a quick and easy way for using ETW in your managed application directly from Visual Studio. The solution involves using the proper tooling in an automated and integrated way so as to make it a very streamlined operation from the developer’s standpoint.

A Quick Recap

But, first, let’s recap what needs to be done for proper usage of ETW:

a) At design-time:

  • First, you need to declare and maintain the event and message structures in an Instrumentation Manifest file. This is cumbersome but, in fact, quite easy, thanks to the Manifest Generator (ecmangen.exe) authoring utility from the Windows SDK.
  • Second, you need to create a C# managed class for wrapping those event and message structures in your code. Again, this is straightforward, since the Message Compiler (mc.exe) tool includes a couple of switches to generated a C# source-code file for this purpose.
  • Third, you need to embed a binary representation of the Instrumentation Manifest, known as a Message File, as a Win32 resource in your assembly. This requires, yet again, the use of the Message Compiler (mc.exe) tool – in order to produce a Resource Script (.rc) file – followed by the Resource Compiler (rc.exe) tool in order to create a Win32 resource (.res) file. This, in turn, gets embedded in a managed assembly by specifying the resource file in the project properties and tweaking the compiler switches in order to allow the compilation of unsafe code.

In fact, these are a lot of steps, but, once you have created and authored the Instrumentation Manifest file, all of them can be automated. This is what I’m going to show you now.

Creating a Managed Wrapper Visual Studio Project

In essence, Visual Studio C# Project (.csproj) files are MSBuild-based XML files. This means that we can leverage the extensibility of MSBuild to perform the necessary steps by slightly modifying the project files. As an added bonus, such modified projects can also be built from the command-line or from a TFS build server.

Managed ETW Wrapper Project in Visual Studio

In my proposal, a developer creates a regular C# project and includes the Instrumentation Manifest XML file. Then, the developer needs to perform a one-time modification to the project, that consists in changing the build action associated with the manifest to InstrumentationManifest and add an import statement, at the end of the project file, referring to an external .targets MSBuild file in which all the required logic will be centralized.

In practice, here how it looks like, in Visual Studio:

A regular C# project file that has been modified to include support for
compiling an ETW Instrumentation Manifest file.

In fact, adding an import statement at the end of the file is the only manual modification required, for it will point to an external MSBuild .targets file where the custom InstrumentationManifest Build Action is registered. So, associating the Instrumentation Manifest to the appropriate Build Action can be done within Visual Studio when the project file is reloaded.

Once that’s done, the project behaves just like any regular C# project. It produces a managed assembly. It understands the Build, ReBuild and Clean actions. It even takes advantage of incremental compilation, in order to only perform the necessary actions when required. Finally, it can be referenced from other projects without any side effects. For all intents and purposes, it is a regular C# project file.

A Custom MSBuild Project for Supporting ETW from Managed Code

Here, I will show the structure and content of a custom MSBuild .targets Project that can be imported into any regular C# project file in order to include support for compiling ETW Instrumentation Manifest files into a strongly-typed C# managed wrapper:

<Project InitialTargets="_InitialTarget" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">

 <!-- Compiling ETW Instrumentation Manifest files requires Windows SDKtools -->
 <PropertyGroup>
   <WindowsSdkDir Condition="'$(WindowsSdkDir)'=='' ">C:\ProgramFiles (x86)\Microsoft SDKs\Windows\v7.0A\</WindowsSdkDir>
   <RootNamespace Condition="'$(RootNamespace)'=='' ">$(AssemblyName)</RootNamespace>
 </PropertyGroup>

 <!-- _InitialTarget -->
 <!--
 
       Normalizes the $(WindowsSdkDir) variable and retrieves the path tovarious SDK tools and dependent files.
       
       Inputs:
       =======
       (none)
       
       Outputs:
       ========
       $(Win32MessageCompiler) : path to the Message Compiler (mc.exe) SDKutility
       $(Win32ResourceCompiler) : path to the Resource Compiler (rc.exe) SDKutility
       $(Win32InstrumentationMetadata) : path to the core ETW metadatadefinitions (winmeta.xml)
       
 -->
 <Target Name="_InitialTarget">
   <PropertyGroup>
     <WindowsSdkDir Condition="!HasTrailingSlash('$(WindowsSdkDir)') ">$(WindowsSdkDir)\</WindowsSdkDir>
     <Win32MessageCompiler Condition="Exists('$(WindowsSdkDir)bin\mc.exe') ">$(WindowsSdkDir)bin\mc.exe</Win32MessageCompiler>
     <Win32ResourceCompiler Condition="Exists('$(WindowsSdkDir)bin\rc.exe') ">$(WindowsSdkDir)bin\rc.exe</Win32ResourceCompiler>
     <Win32InstrumentationMetadata Condition="Exists('$(WindowsSdkDir)include\winmeta.xml') ">$(WindowsSdkDir)include\winmeta.xml</Win32InstrumentationMetadata>
   </PropertyGroup>
 </Target>

First, some bookkeeping. Compiling ETW Intrumentation Manifests requires tools from the Windows SDK, so references to the various tools are established into a set of corresponding properties. The _InitialTarget is run first, in order to setup those properties before any other processing.

 <!-- _ComputeIntrumentationManifestResource -->
 <!--
 
       Calculates the paths (location) to the resulting .res resource file andassociated strongly-typed .cs file.

       Input ItemGroup:
       ================
       @(InstrumentationManifest) : path to the XML Instrumentation Manifest(.man) file
       
       Output ItemGroups:
       ==================
       @(InstrumentationManifestResource) : path to the resulting compiledwin32 resource (.res) file
       @(EventProviderSource) : path to the resulting strongly-typed managedwrapper class (.cs) file
 
 -->
 <Target Name="_ComputeInstrumentationManifestResource">
   <ItemGroup>
     <InstrumentationManifestResource Remove="@(InstrumentationManifestResource)" />
     <InstrumentationManifestResource Include="@(InstrumentationManifest->'$(IntermediateOutputPath)res\%(Filename).res')" />
   </ItemGroup>
   <ItemGroup>
     <EventProviderSource Remove="@(EventProviderSource)" />
     <EventProviderSource Include="@(InstrumentationManifest->'%(RootDir)%(Directory)%(Filename).cs')" />
   </ItemGroup>
 </Target>
  
 <!-- _CreateInstrumentationManifestResource -->
 <!--
 
       Compiles the resulting .res resource file.
       The win32 resource (.res) file is located in an intermediate outputpath.
       Leverages incremental compilation (i.e. only performs compilation ifrequired.)

       Inputs:
       ================
       @(InstrumentationManifest) : path to the XML Instrumentation Manifest(.man) file
       
       Outputs
       ==================
       @(InstrumentationManifestResource) : path to the resulting compiledwin32 resource (.res) file
 
 -->
 <Target Name="_CreateInstrumentationManifestResource" Inputs="@(InstrumentationManifest)" Outputs="@(InstrumentationManifest->'$(IntermediateOutputPath)res\%(Filename).res')">
   <MakeDir Condition="!Exists('$(IntermediateOutputPath)res') " Directories="$(IntermediateOutputPath)res" />
   <Exec Command="&quot;$(Win32MessageCompiler)&quot; -W &quot;$(Win32InstrumentationMetadata)&quot; &quot;@(InstrumentationManifest)&quot; -h &quot;$(IntermediateOutputPath)res&quot; -r &quot;$(IntermediateOutputPath)res&quot;" />
   <Exec Command="&quot;$(Win32ResourceCompiler)&quot; -nologo -r &quot;@(InstrumentationManifest->'$(IntermediateOutputPath)res\%(Filename).res')&quot;" />
 </Target>

 <!-- _CreateEventProviderSourceFile -->
 <!--
 
       Generates the resulting strongly-typed managed EventProvider wrapper.
       The strongly-typed C# managed wrapper class (.cs) file is located at the root of the project.
       Leverages incremental compilation (i.e. only performs generation if required.)

       Inputs:
       ================
       @(InstrumentationManifest) : pathto the XML Instrumentation Manifest (.man) file
       
       Outputs
       ==================
       @(EventProviderSource) : path to the resulting strongly-typed managed wrapper class (.cs) file
 
 -->
 <Target Name="_CreateEventProviderSourceFile" Inputs="@(InstrumentationManifest)" Outputs="@(InstrumentationManifest->'%(RootDir)%(Directory)%(Filename).cs')">
   <Exec Command="&quot;$(Win32MessageCompiler)&quot; -cs $(RootNamespace) &quot;@(InstrumentationManifest)&quot; -r &quot;$(IntermediateOutputPath)res&quot;" />
 </Target>

Then, three simple targets, each one associated with a single responsibility.

The _ComputeInstrumentationManifestResource target creates some meaningful ItemGroup created as part of the processing below. This simplifies writing subsequent targets. As you see, the resulting Win32 resource (.res) file is created under a res subdirectory of the intermediate output path and has the same base file name as the Instrumentation Manifest. Likewise, the EventProvider source file has the same base file name as the Manifest and is created in the project root.

The _CreateInstrumentationManifestResource target runs the Message Compiler (mc.exe) and Resource Compiler (rc.exe) tools in sequence, in order to create a binary representation of the manifest as a Win32 resource (.res) file.

The _CreateEventProviderSourceFile target runs the Message Compiler (mc.exe) tool in order to create a strongly-types C# managed wrapper class for an ETW EventProvider object.

Both targets take advantage of MSBuild support for incremental compilation. By comparing the timestamps of the generated artifacts relative to that of the Instrumentation Manifest, the processing only happens when necessary. Those targets are specified as dependencies of the BeforeCompile target, shown below, in order to trigger the actual custom processing.

 <!-- BeforeCompile -->
 <!--
 
       Overrides the BeforeCompile MSBuild extension point in order to generated files and alter compiler flags.
 
 -->
 <Target Name="BeforeCompile" DependsOnTargets="_ComputeInstrumentationManifestResource;_CreateInstrumentationManifestResource;_CreateEventProviderSourceFile">
   <Message Text="Createstrongly-typed ETW assembly from specified instrumentation manifest..." />
   <PropertyGroup>
     <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
     <Win32Resource>@(InstrumentationManifestResource->'%(Identity)')</Win32Resource>
   </PropertyGroup>
   <ItemGroup>
     <Compile Include="@(EventProviderSource->'%(Identity)')" />
   </ItemGroup>
   <Message Text="@(Compile)" />
 </Target>

The MSBuild BeforeCompile target is then overridden and performs the following actions:

  • Its dependencies trigger the custom generation of the C# EventProvider source file and compilation of the win32 binary resource, shown above.
  • The @(Compile) ItemGroup is modified to include the newly generated EventProvider source file.
  • The /unsafe compiler switches is turned on, in order to allow the compilation of unsafe code.
  • The /win32res compiler flag is specified with the location of the generated binary Win32 resource Message File.
 <!-- AfterClean -->
 <!--
 
       Overrides the AfterClean MSBuild extension point in order to clean generated files.
 
 -->
 <Target Name="AfterClean" DependsOnTargets="_ComputeInstrumentationManifestResource">
   <RemoveDir Condition="Exists('@(InstrumentationManifestResource->'%(RootDir)%(Directory)')') " Directories="@(InstrumentationManifestResource->'%(RootDir)%(Directory)')" />
   <Delete Condition="Exists('@(EventProviderSource)') " Files="@(EventProviderSource)"/>
 </Target>

Finally, in order to support the Clean action, the MSBuild AfterClean target is overridden to delete the generated artifacts.

Conclusion

In this post, I have focused on providing an automated and integrated way of using ETW from the perspective of a Visual Studio developer.

In order to produce ETW traces from one’s application, it is necessary to register the managed Event Provider to the system at install-time (using wevtutil.exe) and collect and analyse the resulting traces at run-time (using logman.exe, svctraceview.exe, tracerpt.exe, xperf.exe, etc.) Please, refer to the articles I linked to, as well as this excellent ETW FAQ, for more information…

Posted in ETW | Tagged , , , | 7 Comments