Thursday, April 26, 2012

C# 4.5 | Uso de async para mejorar la experiencia de usuario en una aplicación para Windows

C# | Uso de un objeto BackgroundWorker para hacer tareas en segundo plano

Muestra como utilizar un objeto BackgroundWorker para ejecutar métodos en segundo plano

Wednesday, April 18, 2012

WPF | Iniciar sesión con GenericPrincipal, Hashes y Entity Framework

Muestra como iniciar sesión en una aplicación WPF usando GenericPrincipal, Hashes y Entity Framework en Windows 8 con Visual Studio 11. El proceso consiste en:
1. Crear una aplicación WPF
2. Crear una ventana de login
3. Usar GenericIdentity para iniciar sesión
4. Usar una base de datos SQL Srvr 12 para guardar las contraseñas
5. Crear un creador de Hashes para crear usuarios
6. Implementar la comparación de hashes en la aplicación WPF


Tuesday, April 17, 2012

.net Winforms | Creación de una biblioteca de controles para Winforms

Muestra como crear una biblioteca de controles para que sean utilizados en una aplicación winforms. Se muestra como crear un control base con funcionalidad y elementos comunes que serán derivados a los controles que hereden de este control.


.net Winforms | Uso de instancias de formas y controles en Winforms

Video que muestra como crear una aplicación con Winforms que hace llamadas a otras formas utilizando instancias de las mismas. Como segunda demostración se crean controles de usuario para sustituir las llamadas de las formas.

Monday, April 16, 2012

.net Winforms | Uso básico de forma en una aplicación para Windows


Forma muy básica de usar una forma en una aplicación para Windows.
Se usa Windows 8 y Visual Studio 11 para los ejemplos.


C# | Monitoreo de archivos en carpetas con un FileSystemWatcher

Forma de usar FileSystemWatcher para monitorear una carpeta y disparar acciones cuando sus archivos tengan un cambio.

Se usó Visual Studio 11 y Windows 8 Customer Preview para crear el ejemplo.


Friday, April 13, 2012

C# 4.5 | Asynchronous Programming in the .NET Framework 4.5

Content

- Asynchronous Operations
- Async - Task-based Asynchronous Pattern -
    Task and Task<IResult>
    async
    await
    Requirements to use Async
  - Example using async and await
       First example: Creating the synchronous implementation
       Second example: Creating the asynchronous application

Asynchronous tasks are necessary when applications are frozen due to actions that do not stop and let the user continue using them, you have probably seen the message "Application not responding ...". Let's see how to solve this problem with a new feature of Framework 4.5.

Asynchronous operations

A computer has a fixed number of processors and each of these processors can perform only one operation at a time, let's call this operation thread. Each thread in an application is programmed to run on the processor for a period of time.

If a code performs some I / O action, the thread is suspended until the device has completed its work. If you have a very slow task it can start working on a separate thread and get the result of the operation once the task is completed. While the separate thread running the application can perform other tasks unrelated to the task of long duration. Thus, we can isolate the work they do homework.

Most methods are called synchronous, which means that the method is completed in the current thread. However, some methods are called asynchronous which means that the current thread begins execution of the method in another thread and the call returns immediately. Synchronous methods are known as block because the thread that calls the method does other work until the method completes.

Here is how to call another task using a wire with framework 2.0

namespace Threads
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a threar to call the SlowTask method
            System.Threading.Thread task =
                new System.Threading.Thread(
                    new System.Threading.ParameterizedThreadStart(SlowTask));
            //Start the task
            task.Start(900);
            //Task is stopped?
            if (task.ThreadState != System.Threading.ThreadState.Stopped)
                System.Console.WriteLine("Task is still running");
            //Actual thread stops until the other task stops
            //or until 1000 milliseconds are reached
            tarea.Join(1000);
            //Ask again - Task is stopped?
            if (task.ThreadState != System.Threading.ThreadState.Stopped)
                System.Console.WriteLine("1 second and task is still running");
            else
                System.Console.WriteLine("Finally, the task is stopped!");
            System.Console.ReadLine();
        }

        /// <summary>
        /// Method that last param milliseconds
        /// </summary>
        /// <param name="param"></param>
        static void SlowTask(object param)
        {
            //param as int
            int gap = (int)parametro;
            //Wait some time
            System.Threading.Thread.Sleep(gap);
            System.Console.WriteLine("This slow task has ended.");
        }
    }
}


For more information about threads go to::
http://msdn.microsoft.com/en-us/library/6kac2kdh.aspx
 
Changes to data are also time-consuming resulting in a poor user experience. Another way to use alternate tasks using threads is to use a BackgroundWorker object as shown below.

namespace SampleBackgroundWorker
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create BackgroundWorker object
            System.ComponentModel.BackgroundWorker task =
                new System.ComponentModel.BackgroundWorker();
            //Attach anonymous code to delegate
            task.DoWork += (o, params) =>
            {
                //Simulate a 1 second gap
                System.Threading.Thread.Sleep(1000);
                //Use Result to fill it with a value (date)
                params.Result = System.DateTime.Now;
            };
            //Get results
            task.RunWorkerCompleted += (o, params) =>
            {
                if (params.Error != null)
                {//Show error message
                    System.Console.WriteLine("Error raised");
                }
                else
                {//Show success message
                    System.Console.WriteLine("Success!");
                    //Write value to screen
                    System.Console.WriteLine(parametros.Result.ToString());
                }

            };
            //Start task
            task.RunWorkerAsync();
            System.Console.ReadLine();
        }
    }
}


It starts to look very complicated and we always need a method or block of code that responds to events "DoWork" and "CompletedWork".

Async - Asynchronous Pattern

When using the pattern-based asynchronous tasks. NET Framework 4.5 (TAP) asynchronous methods return a Task object representing the task. Use Task and Task<TResult> types from System.Threading.Tasks namespace to represent arbitrary asynchronous operations.

When invoking a task and its completion is expected, use the keyword "await" when you call a method. Use the syntax:

await myMethodAsync();

In this way the code flow does not stop. No need to assign methods to events, even more, there is no callbacks because now the compiler is responsible for creating them.

Task and Task<IResult>

The return type of an asynchronous method must be void, Task or Task <T>. The return type of an anonymous function is the type of return (if any) of the delegate.

In an asynchronous function with void return type or Task, return statements should not be an expression.

When the return type is Task <T> return statements should have an expression that is implicitly convertible to T.

async

Conventionally asynchronous methods use the Async suffix to indicate that execution can be carried out after the method has ended.

An async method provides a convenient way to do things that take a long time without causing blockages in the calling thread. The thread that makes an async method call can continue without having to wait until the method finishes.

await

An expression await is only allowed when it is within an asynchronous method. Commonly, a modified method for the modifier async contains at least one instruction await. Such a method runs synchronously until it meets the first expression await, at which execution is suspended until the task ends.

 

Requirements to use Async

Async is available in the Beta version of Visual Studio 11 or as a download CTP (Community Technology Preview) for Visual Studio 2010 SP1.

Example using async and await

As a small example to understand how you can use async and await generate a small program that allows us to see the effect of TAP pattern.

First exercise: Creating the synchronous implementation

Task 1 - Create an application synchronously.
1.     Start Visual Studio 11 and created a new WPF application in C # called SampleAsync.
2.      Change the properties of the main window to have a size of 480 by 480 pixels.
3.      Add two buttons and a ListBox. Name the controls. ButtonRead, ButtonMessage and FileList, respectively..
4.     Arrange the components so that they have the following appearance:




5.   Open the file in C # code associated with MainWindow and add the following code just below the constructor.

private IEnumerable<string> GetFiles()
        {
var files = from file
in
System.IO.Directory.GetFiles(@"C:\Windows\System32")
select file;
System.Threading.Thread.Sleep(5000);
            return files;
        }

6.       Double-click on the button to generate a ButtonRead_Click event handler and add the following code.

private void ButtonRead_Click(object sender, RoutedEventArgs e)
        {
ButtonRead.IsEnabled = false;
FileList.ItemsSource = GetFiles();
ButtonRead.IsEnabled = true;
        }

7.     Return to design mode and double-click on ButtonMessage to generate the Click event handler. Next, add the following code to the generated method.

private void ButtonMessage_Click(object sender, RoutedEventArgs e)
        {
           MessageBox.Show("Local time: " +
DateTime.Now.ToLongTimeString());
        }

8.      Run the application and press the Files button. Note that the application freezes and you can not press the Time button. After 5 seconds the ListBox is populated with the files in the directory and theTime button is functional and displays the message.



Exercise Two: Creating the asynchronous application

 

Task 1 - Modify the method GetFiles to be asynchronous.
1.      Go to the contents of this method and modify its structure so that the return data type changes from IEnumerable<String> to Task<IEnumerable<String>> and the name of the method now has the suffix "Async" as shown.

private Task<IEnumerable<String>> GetFilesAsync()

2.      Now wrap the code in the method to return an object of type Task.

private Task<IEnumerable<String>> GetFilesAsync()
        {
                return Task.Run(() =>
            {
                  System.Threading.Thread.Sleep(5000);
                  var files = from file in
  System.IO.Directory.GetFiles(@"C:\Windows\System32")
  select file;
                  return files;
            });
        }

Task 2 - Modify the Click event handler to be able to make asynchronous calls..
1.      Change the structure of the method by adding the async modifier as shown.

private async void ButtonRead_Click(object sender, RoutedEventArgs e)

2.      Now modify the method call, to be done through an asynchronous call using the keyword x as a modifier of the method call. Remember that we have already changed the name of the method by adding the suffix Asycn. 

FileList.ItemsSource = await GetFilesAsync();

3.     Run the application, press the button Files and check that the application is not frozen and is receptive. You can now press the Time button without having to wait the end of the period of 5 seconds. 

 

In this second example we have created an application that does not freeze its operation for initiating a call to a method.

References:


C# 4.5 | Programmation asynchrone avec Framework. net 4.5


Contenu

- Opérations asynchrones
- Async - Modèle asynchrone des tâches
   Task et Task<IResult>
   async
   await
   Articles nécessaires pour utiliser Async
   Exemple d'utilisation avec async et await
 - Premier tutoriel: Création d'un logiciel synchrone
 - Deuxième tutoriel: Création d'un logiciel asynchrone

Les tâches asynchrones sont nécessaires lorsque les applications sont gelés en raison des actions qui ne finissent pas et ils ne laissent pas l'utilisateur de continuer à les utiliser, vous avez probablement vu le message "L'application ne répond ...". Voyons comment résoudre ce problème avec une nouvelle fonctionnalité du Framework 4.5.

Opérations asynchrones

Un ordinateur comporte un nombre fixe de processeurs et chacun de ces processeurs peuvent exécuter une seule opération à la fois. Appelons cette opération "thread". Chaque thread dans une application est programmé pour s'exécuter sur le processeur pour une période de temps.
Si un code effectue une action de I / O, le fil est suspendu jusqu'à ce que le dispositif a achevé ses travaux. Si vous avez une tâche très longtemps il peut commencer à travailler sur un thread séparé et obtenir le résultat de l'opération une fois que la tâche est terminée. Alors que le thread séparé qui exécute l'application peut effectuer d'autres tâches sans rapport avec la tâche de longue durée. Ainsi, nous pouvons isoler les tâches de travail.
La plupart des méthodes sont appelées synchrone, ce qui signifie que la méthode est terminée dans le thread en cours. Toutefois, certaines méthodes sont appelées asynchrones, ce qui signifie que le thread courant commence l'exécution de la méthode dans un autre thread et l'appel retourne immédiatement. Méthodes synchrones sont connus en tant que bloc, car le thread qui appelle la méthode fonctionne jusqu'à ce que d'autres la méthode complète.

Voici comment appeler une autre tâche à l'aide d'un
thread avec framework 2.0

namespace Threads
{
    class Program
    {
        static void Main(string[] args)
        {
            //Créer un thread qui commence par un appel à TacheLente
            System.Threading.Thread tache =
                new System.Threading.Thread(
                    new System.Threading.ParameterizedThreadStart(TacheLente));
            //Démarrer une autre tache
            tache.Start(900);
            //Demander si l'autre tâche est terminéea
            if (tache.ThreadState != System.Threading.ThreadState.Stopped)
                System.Console.WriteLine("L'autre tâche est en cours d'exécution");
            //Arrêter le thread en cours jusqu'à la fin d'une autre tâche ou
            //jusqu'à 1000 millisecondes
            tache.Join(1000);
            //Demandez à nouveau si la tâche est déjà terminé
            if (tache.ThreadState != System.Threading.ThreadState.Stopped)
                System.Console.WriteLine("On a passé une seconde, l'autre tâche continue");
            else
                System.Console.WriteLine("Enfin terminé une autre tâche!");
            System.Console.ReadLine();
        }

        /// <summary>
        /// Méthode avec une période égale au paramètre
        /// </summary>
        /// <param name="param"></param>
        static void TacheLente(object parametre)
        {
            //Paramètre comme un entier
            int periode = (int)parametre;
            //Arrêter la tâche par le temps indiqué
            System.Threading.Thread.Sleep(periode);
            System.Console.WriteLine("Achèvement de la tâche lente");
        }
    }
}


Pour plus d'informations sur les threads aller à::
http://msdn.microsoft.com/fr-fr/library/6kac2kdh.aspx
 
Modifications apportées aux données sont aussi des tâches qui durent longtemps, résultant en une mauvaise expérience. Une autre façon d'utiliser les tâches d'autres avec des threads est d'utiliser un objet BackgroundWorker comme indiqué ci-dessous.

namespace ExempleBackgroundWorker
{
    class Program
    {
        static void Main(string[] args)
        {
            //Créer un objet BackgroundWorker
            System.ComponentModel.BackgroundWorker tache=
                new System.ComponentModel.BackgroundWorker();
            //Méthode anonyme qui correspond à l'événement DoWork
            tache.DoWork += (o, parametres) =>
            {
                //Simuler un retard d'un seconde
                System.Threading.Thread.Sleep(1000);
                //Retourner quelque chose avec Result
                parametres.Result = System.DateTime.Now;
            };
            //Obtenir le valoir dans 'parametres'
            tache.RunWorkerCompleted += (o, parametres) =>
            {
                if (parametres.Error != null)
                {//Afficher un message d’erreur
                    System.Console.WriteLine("Erreur");
                }
                else
                {//Afficher un message de succès
                    System.Console.WriteLine("Sans erreurs");
                    //Imprimer le résultat
                    System.Console.WriteLine(parametres.Result.ToString());
                }

            };
            //Démarrer la tâche 
            tache.RunWorkerAsync();
            System.Console.ReadLine();
        }
    }
}


Il commence à sembler aussi compliqué, nous avons toujours besoin d'une méthode ou un bloc de code qui répond à des événements "DoWork" et "RunWorkerCompleted"

Async - Modèle asynchrone des tâches (TAP)

Si vous utilisez le modèle asynchrone des tâches du NET Framework 4.5 (TAP par son sigle en anglais) le méthode asynchrone retourne un objet Task qui représentant la tâche. Ce modèle utilise Task et Task<TResult> dans l'espace de noms System.Threading.Tasks pour représenter les opérations asynchrones arbitraires.   
Lors de l'appel d'une tâche et son achèvement est prévu, vous utilisez le mot "await" sous la forme:

await maMethodeAsync();
Cela ne modifie pas le flux d'exécution, ni est là pour accrocher des méthodes à des événements, encore plus, il n'y a pas d'événements pour gérer parce que maintenant le compilateur est responsable de leur création.

Task et Task<IResult>

Le type de retour d'une méthode asynchrone doit être void, Task ou Task<T>. Le type de retour d'une méthode anonyme est le type retourné par 'return' (si il ya un 'return') du délégué.

Dans un méthode asynchrone avec type de retour void ou de travail, les déclarations de retour ne doit pas avoir une expression.

Lorsque le type de retour est Task<T>, les déclarations de retour doit avoir une expression qui est implicitement convertible en T.

async

Classiquement méthodes asynchrones utilisent le suffixe Async pour indiquer que l'exécution peut être effectuée qu'après que la méthode que vous appelez a pris fin.

Une méthode asynchrone fournit un moyen pratique de faire des choses qui prennent beaucoup de temps sans causer des blocages dans le thread appelant. Le thread qui appelle une méthode asynchrone peut continuer sans attendre que la méthode async est terminée.

await

Une expression await n'est autorisée que dans une méthode de façon asynchrone. Généralement, une méthode modifiée pour le modificateur async contient au moins une expression await. Une telle méthode s'exécute de façon synchrone jusqu'à ce qu'il rencontre la première expression await, au cours de laquelle l'exécution est suspendue jusqu'à ce que la tâche est terminée.


Articles nécessaires pour utiliser Async

Async est disponible dans la version bêta de Visual Studio 11, ou au téléchargement CTP (Community Technology Preview) de Visual Studio 2010 SP1..

Exemple d'utilisation asynchrone avec asycn et await

Comme un petit exemple pour comprendre comment vous pouvez utiliser async et await, nous allons générer un projet WPF qui nous permettra de voir l'effet de modèle TAP

Premier exercice: Création d'une application de manière synchrone.

1.      Démarrez Visual Studio 11 et créé une nouvelle application WPF en C # appelé ExempleAsynn.
2.      Modifiez les propriétés de la fenêtre principale d'avoir une taille de 480 par 480 pixels.
3.      Ajoutez deux boutons et une ListBox. Attribuer des noms aux boutons, BoutonLire et BoutonMessage respectivement. Attribuer du nom a la Listbox ListeDesFichiers.
4.      Disposez les composants afin qu'ils aient l'apparence suivante:




5.      Ouvrez le fichier de code en C# MainWindow associée à MainWindox.xaml.cs et ajoutez la ligne suivante juste en dessous de la méthode constructeur.

        private IEnumerable<string> RecupererDesFichiers()
        {
            var fichiers = from fichier in
System.IO.Directory.GetFiles(
@"C:\Windows\System32")
              select fichier;

            System.Threading.Thread.Sleep(5000);
            return fichiers;
        }

6.       Double-cliquez sur le bouton BoutonLire pour créer la méthode, ajoutez le code suivant:

        private void BoutonLire_Click(object sender, RoutedEventArgs e)
        {
            BoutonLeer.IsEnabled = false;
            ListeDesFichiers.ItemsSource = RecupererDesFichiers();
            BoutonLeer.IsEnabled = true;
        }

7.      Maintenant, retournez à «MainWindow.xaml» et double-cliquez sur BoutonMessage pour générer le gestionnaire d'événements Click. Ensuite, ajoutez le code suivant.


        private void BoutonMessage_Click(object sender, RoutedEventArgs e)
        {
            MessageBox.Show("L'heure exacte: " +
DateTime.Now.ToLongTimeString());
        }


8.      Exécutez l'application et appuyez sur le bouton. Notez que l'application s'arrête et vous ne pouvez pas appuyer sur le bouton Message. Après 5 secondes, le ListBox est rempli avec les noms de fichiers et ​​le bouton Message est fonctionnel. On voit également le message.



Deuxième exercice: Création de l'application asynchrone

1.      Allez au contenu de la méthode RecupererDesFichiers, modifiez sa structure de sorte que le type de données pour retourner change de IEnumerable<String> à Task<IEnumerable<String>> et le nom de la méthode a maintenant le suffixe «Async» comme le montre. N'oubliez pas de déclarer l'espace de noms System.Threading.Tasks.

private Task<IEnumerable<string>> RecupererDesFichiersAsync()


2.      Maintenant, mettez le code de la méthode dans une tâche, pour retourner un objet de type de tâche.

        private Task<IEnumerable<string>> RecupererDesFichiersAsync()
        {
            return Task.Run(() =>
            {
                System.Threading.Thread.Sleep(5000);
                var fichiers = from fichier in
System.IO.Directory.GetFiles(@"C:\Windows\System32")
select fichier;
                return fichiers;
            });
        }


1.      Changez la structure de la méthode en ajoutant le modificateur async pour BoutonLire_Click comme le montre.

   private async void BoutonLire_Click(object sender, RoutedEventArgs e)

.
2.      Maintenant modifiez l'appel de méthode, de sorte se fait maintenant par le biais d'un appel asynchrone à l'aide du mot réservé "await" comme un modificateur. Rappelez-vous que nous avons déjà changé le nom de la méthode en ajoutant le suffixe du "Async".

ListeDesFichiers.ItemsSource = await RecupererDesFichiersAsync();

3.      Démarrez le programme, appuyez sur le bouton "Fichiers" et vérifiez que l'application n'est pas arrêtée et est sensible et qu'il est maintenant possible d'appuyer sur le bouton Message sans attendre la fin de la période de 5 secondes.



Dans ce deuxième exemple, nous avons créé une application qui ne s'arrête pas son fonctionnement pour initier un appel à une méthode.

Références: