background preloader

C#

Facebook Twitter

Opérations synchrones et asynchrones. Scénarios asynchrones suggérés Implémentation d'une opération de service asynchrone Modèle asynchrone basé sur des tâches public class SampleService:ISampleService { // ... public async Task<string> SampleMethodTaskAsync(string msg) { return Task<string>.Factory.StartNew(() => { return msg; }); } // ... } Modèle asynchrone basé sur des événements public class AsyncExample { // Synchronous methods. public int Method1(string param); public void Method2(double param); // Asynchronous methods. public void Method1Async(string param); public void Method1Async(string param, object userState); public event Method1CompletedEventHandler Method1Completed; public void Method2Async(double param); public void Method2Async(double param, object userState); public event Method2CompletedEventHandler Method2Completed; public void CancelAsync(object userState); public bool IsBusy { get; } // Class implementation not shown. } Modèle asynchrone IAsyncResult Appels asynchrones côté client.

ILSpy. Data Points: Data Binding in WPF. Data Points Data Binding in WPF John Papa Code download available at:DataPoints2007_12.exe(161 KB) By now, many of you know that Windows® Presentation Foundation (WPF) makes it easy to design robust user interfaces. But what you probably didn't know is that it also provides powerful data-binding capabilities. Data Binding Specifics To use WPF data binding, you must always have a target and a source. Now let's take a look at how the WPF data-binding techniques work and I'll present practical examples that illustrate their use. Creating a Simple Binding Let's start with a simple example that illustrates how to bind a TextBlock's Text property to a ListBox's selected item. The code listed in Figure 1 can be modified slightly to use a shorthand syntax for data binding. This syntax, called the attribute syntax, condenses the data binding code inside of the Text attribute of the TextBlock.

Binding Modes Figure 2 Binding a Source to Two Targets Figure 3 TwoWay Binding in Action A Time to Bind. Serialize List Tutorial. A List can be serialized to the disk. We want to serialize (to a file) a List of objects. The next time the program runs, we get this List straight from the disk. We see an example of BinaryFormatter and its Serialize methods. List Example This is the first part of the code example. Program that describes serializable type: C# using System; using System.Collections.Generic; using System.IO; using System.Runtime.Serialization.Formatters.Binary; [Serializable()] public class Lizard { public string Type { get; set; } // String property for Lizard object public int Number { get; set; } // Number of lizards public bool Healthy { get; set; } // Whether lizard is healthy public Lizard(string t, int n, bool h) { Type = t; Number = n; Healthy = h; } } We see a class called Lizard, and it has three automatic properties.

The Serializable attribute is specified right before the class definition. Example 2 The second part of this tutorial is the Main method in your C# console program. File.Open Examples. C# Tutorial - Serialize Objects to a File. While storing information in memory is great, there comes a time your users will have to shut your application down. This means (probably) that you will need to write information to a file at some point, because you will want to store whatever data was in memory.

Today, we are going to take a look at a feature built into .NET called Serialization that makes writing and reading data structures to and from a file extremely easy. For this example, let's say I want to create a program that keeps track of all the cars my friends own. I'm going to create two objects to achieve this: Car and Owner. The Car object will store the make, model, and year of the car. The Owner object will save some information about who owns the car.

//information about the carpublic class Car{ private string make; private string model; private int year; private Owner owner; public Car() { }} //information about the car's ownerpublic class Owner{ private string firstName; private string lastName; public Owner() { }} COM Interop Part 1: C# Client Tutorial (C#) COM Interop provides access to existing COM components without requiring that the original component be modified.

When you want to incorporate COM code into a managed application, import the relevant COM types by using a COM Interop utility (TlbImp.exe) for that purpose. Once imported, the COM types are ready to use. In addition, COM Interop allows COM developers to access managed objects as easily as they access other COM objects. Again, COM Interop provides a specialized utility (RegAsm.exe) that exports the managed types into a type library and registers the managed component as a traditional COM component. At run time, the common language runtime marshals data between COM objects and managed objects as needed. This tutorial shows how to use C# to interoperate with COM objects.

Sample Files Further Reading Tutorial C# uses .NET Framework facilities to perform COM Interop. Creating COM objects. This tutorial covers the following topics: Creating a COM Class Wrapper Declaring a COM coclass. Calling a .NET Component from a COM Component. Mike Gunderloy Lark Group, Inc. January 2002 Summary: Walks through the details of how to call Microsoft .NET servers from COM clients. (12 printed pages) Objectives Understand the concept of COM callable wrappers Create a .NET server that can be called from Microsoft® Visual Basic® 6.0 Use the sn, regasm, and gacutil utilities Write Visual Basic 6.0 code that uses a .NET class Assumptions The following should be true for you to get the most out of this document: You are familiar with Visual Basic programming You are familiar with COM concepts You have access to Visual Basic .NET You understand the overall .NET architecture You understand how to create public classes in Visual Basic .NET Contents The Joy of Interoperability Creating .NET Classes for Use in COM Applications Practice Calling a .NET Component From COM What's New Since Visual Basic 6.0?

The Joy of Interoperability Sometimes a revolution in programming forces you to abandon all that's come before. COM Callable Wrappers Figure 1. Shapes and Basic Drawing in WPF Overview. // Add a Line Element myLine = new Line(); myLine.Stroke = System.Windows.Media.Brushes.LightSteelBlue; myLine.X1 = 1; myLine.X2 = 50; myLine.Y1 = 1; myLine.Y2 = 50; myLine.HorizontalAlignment = HorizontalAlignment.Left; myLine.VerticalAlignment = VerticalAlignment.Center; myLine.StrokeThickness = 2; myGrid.Children.Add(myLine); The following image shows the rendered shape. The second segment begins with an absolute horizontal "lineto" command H, which specifies a line drawn from the preceding subpath's endpoint (400,175) to a new endpoint (280,175). Because it is a horizontal "lineto" command, the value specified is an x-coordinate.

The following illustration shows the rendered shape. The Stretch property takes one of the following values: ... ... .net - C# Generic new() constructor problem. Concurrency - How do I know if a C# method is thread safe. Www.dotnet-france.com/Documents/WCF/Hebergement et configuration de services WCF.pdf. Threads WPF: Créez des applications plus réactives avec le répartiteur. Threads WPF Créez des applications plus réactives avec le répartiteur Shawn Wildermuth Il serait dommage que vous ayez passé plusieurs mois à créer une interface intuitive, naturelle, voire magnifique et que les utilisateurs en soient réduits à taper impatiemment du doigt sur leur bureau en attendant que celle-ci réponde.

Constater que votre application ralentit inexorablement en raison d'un processus à l'exécution longue est tout simplement pénible. Ma première véritable expérience de réactivité remonte très loin, à Visual C++®, MFC et la première grille que j'ai écrite. Windows® Presentation Foundation (WPF) est une technologie idéale pour la création d'interfaces utilisateur attrayantes, mais cela ne signifie pas que la réactivité de votre application ne nécessite pas d'être prise en compte. Modèle de threading Toutes les applications WPF démarrent avec deux threads importants, le premier pour le rendu et le second pour la gestion de l'interface utilisateur.

DispatcherObject. Comment changer la langue IDE dans Visual Studio .NET 2002, Visual Studio .NET 2003 ou Visual Studio 2005. Vous pouvez installer plusieurs versions linguistiques de Visual Studio sur le même ordinateur, et des puis vous pouvez basculer vers la langue de l'IDE entre les langages que vous installez. Par exemple, si vous installez la version espagnole de Visual Basic 2005 Express sur le même ordinateur qui exécute la version anglaise de Visual Basic 2005 Express, vous aurez une version unique de l'IDE. Changer la langue de Visual Studio IDE Pour changer la langue IDE de Visual Studio, procédez comme suit une fois que vous avez installé deux versions de langue différente de Visual Studio 2005 Express.

Démarrez Visual Studio 2005.Dans le menu Outils , cliquez sur Options . Dans la fenêtre Options , cliquez pour sélectionner Afficher tous les paramètres .Dans le volet gauche, développez environnement , puis cliquez sur Paramètres internationaux .Dans le volet droit, sélectionnez la langue dans laquelle vous souhaitez, puis cliquez sur OK . Traduction automatique.

Setup

Chatez avec WCF. Nous avons vu précédemment la création du contrat (l'interface IChatWCF) de notre service. Nous allons maintenant passer à son implémentation au travers de la classe ChatWCF. Le comportement d'instanciation (défini à l'aide de la propriété InstanceContextMode) contrôle la façon dont les objets du service sont instanciés suite aux requêtes clientes. WCF supporte trois modes d'instanciation: PerCall : un nouvel objet de service est créé à chaque appel du client. PerSession : un nouvel objet de service est créé pour chaque nouvelle session cliente et est conservé pendant toute la durée de vie de celle-ci (cela requiert une liaison capable de prendre les sessions en charge). Il s'agit du mode par défaut. Single: un objet de service unique gère toutes les demandes du client pendant toute la durée de vie de l'application.

Nous allons choisir pour notre service de chat le mode PerSession. Notez la présence de la propriété ConcurrencyMode dont nous parlerons un peu plus loin. IV-A-1. IV-A-2. WCF, WPF et Linq : Mini-Projet SNCF , David REI. Bonsoir à tous ! Pour illustrer quelques possibilités offertes par WCF et Linq To SQL dans un projet .NET 3.5, j'ai choisis la thématique SNCF. En ces temps de grève, on peut imaginer (avec un peu d'effort), que le nom des trains change fréquemment. Cette solution contiendra donc une interface WPF, avec laquelle nous pourrons modifier les noms des trains et ... c'est déjà pas mal. Encore une fois le but du jeu est de tester et de réfléchir sur l'architecture que l'on peut mettre en place.

I Architecture de la solution : Un projet SNCF.DataAccessLayer avec LinqToSQL. II Aperçu de l'interface WPF : III DataAccess et LinqToSQL Pour le projet d'accès aux données, il me suffit d'ajouter un fichier dbml, d'y ajouter ma table et les différentes procédures stockées, et le tour est joué.

C'est très physique le "glisser déplacer". III Business Layer La couche métier définit trois méthodes statiques. IV WCFInterfaces VI WCFServices VII WCFHost C'est l'objectif de cette application console. Conclusion : How To: Do image comparison in Coded UI Test - Gautam Goenka (MSFT) This is guest blog by my colleague Rajeev Kumar. Getting the Test API Download the Test API from here. Add reference of TestAPICore.dll in the Coded UI Test project.

Add this using statement in your code- using Microsoft.Test.VisualVerification; General Test API terms Snapshot: A pixel buffer used for representing and evaluating screen image data. The general Visual Verification workflow Search the UI Test Control. Sample code to use Test API. From the Test API copy these files to Coded UI Test: Samples\MSTest\Tests\bin\Debug\Master.png Samples\MSTest\Tests\bin\Debug\ToleranceMap.png Samples\MSTest\Tests\bin\Debug\SampleApp.exe Add these files in the Coded UI Test project and make “Copy to Output Directory = Copy Always” in the property window for each files.

Description of the code Launch the sample application. This was guest blog by my colleague Rajeev Kumar. Mise en route. Pour commencer à utiliser Dotfuscator and Analytics CE, procédez comme suit : Lancez Visual Studio. Dans la barre de menus de Visual Studio, cliquez sur Outils > PreEmptive Dotfuscator and Analytics. Au lancement de PreEmptive Dotfuscator and Analytics CE, l'écran de démarrage s'affiche sur votre bureau : Le programme est composé de trois panneaux : arborescence de navigation, zone de travail et sortie de génération.

Définition des préférences utilisateur Dans l'écran de démarrage, si le contenu dynamique est désactivé, vous trouverez un lien sur lequel vous pourrez cliquer pour définir les Préférences utilisateur. Vous pouvez également cliquer sur Outils > Préférences utilisateur. Si nécessaire, entrez les détails de configuration du serveur proxy de votre réseau dans la section Paramètres du réseau de la boîte de dialogue Préférences utilisateur. Dernière version de Dotfuscator and Analytics État de l'inscription Dans cette section. C# Tutorial - Using The ThreadPool. A thread pool takes away all the need to manage your threads - all you have to do is essentially say "hey! Someone should go do this work! ", and a thread in the process' thread pool will pick up the task and go execute it. And that is all there is to it. Granted, you still have to keep threads from stepping on each other's toes, and you probably care about when these 'work items' are completed - but it is at least a really easy way to queue up a work item.

In fact, working with the ThreadPool is so easy, I'm going to throw all the code at you at once. We have three arrays at the top of the program: one for input to the work items (inputArray), one for the results (resultArray), and one for the ManualResetEvents (resetEvents). So we initialize these arrays, and then we get to a for loop, which is where we will be pushing out these work items. So what are we queuing here? So what are we doing in this DoWork function? Pretty simple, eh? That's it for this intro to thread pools in C#.

Data Processing

Couverture du code. Web. Documentation. Types (C#)