Calendrier

Novembre 2009
L M M J V S D
            1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30            
<< < > >>

Présentation

Recherche

W3C

  • Flux RSS des articles

Windows Application

[ System.CodeDom ] – exemple de génération de code
Ajouter les deux imports :
using System.CodeDom;
using System.CodeDom.Compiler;
Le but de cet exemple est de présenter avant tout quelques utilisations
 I préparation du code à générer
// 1 Namespace
            CodeNamespace _namespace = new CodeNamespace("MyNamespace");
            // ajout d'imports
            _namespace.Imports.Add(new CodeNamespaceImport("System.Text"));
            // 2 création d'une classe
            CodeTypeDeclaration _class = new CodeTypeDeclaration("Contact");
            _class.Attributes = MemberAttributes.Public;
            _class.Comments.Add(new CodeCommentStatement("mon commentaire 1"));
 
            // a - ajout de fields à la classe
            _class.Members.Add(new CodeMemberField(new CodeTypeReference(typeof(string)), "_contactName"));
           // b - ajout de properties à la classe
            CodeMemberProperty property1=new CodeMemberProperty();
            property1.Attributes = MemberAttributes.Public | MemberAttributes.Final;
            property1.Name = "ContactName";
            property1.Type = new CodeTypeReference(typeof(string));
            property1.HasGet = true;
            property1.HasSet = true;
            // get
            property1.GetStatements.Add(new CodeMethodReturnStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(),"_contactName")));
            // set
            property1.SetStatements.Add(new CodeAssignStatement(
                new CodeFieldReferenceExpression(new CodeThisReferenceExpression(),"_contactName"),
                new CodePropertySetValueReferenceExpression()));
 
            _class.Members.Add(property1);
            // c - ajout de methodes à la classe
            CodeMemberMethod method1 = new CodeMemberMethod();
            method1.Attributes = MemberAttributes.Public | MemberAttributes.Static;
            method1.ReturnType = new CodeTypeReference(typeof(string));
            method1.Name = "GetContactName";
            method1.Statements.Add(new CodeSnippetStatement("this._contactName="Romagny";"));
            method1.Statements.Add(new CodeMethodReturnStatement(new CodeArgumentReferenceExpression("this._contactName")));
 
II génération du code
 
            StringBuilder stringBuilder = new StringBuilder();
            StringWriter stringWriter = new StringWriter(stringBuilder); 
            CSharpCodeProvider provider = new CSharpCodeProvider();
            //
            CodeGeneratorOptions options = new CodeGeneratorOptions();
            options.BracingStyle = "C";
            options.IndentString = " ";
            provider.GenerateCodeFromNamespace(_namespace,stringWriter, options);
 
            richTextBox1.Text = stringBuilder.ToString();
 

ici je me contente d'afficher le code dans une richtextbox
voici la sortie affichée
namespace MyNamespace
{
 using System.Text;
 
 
 // mon commentaire 1
 public class Contact
 {
   
    private string _contactName;
   
    public string ContactName
    {
      get
      {
        return this._contactName;
      }
      set
      {
        this._contactName = value;
      }
    }
   
    public static string GetContactName()
    {
                this._contactName="Romagny";
                 return this._contactName;
    }
 }
}


http://msdn2.microsoft.com/fr-fr/library/system.codedom(VS.80).aspx
Par Romagny13
Ecrire un commentaire - Voir les 1 commentaires - Recommander
LLBLGEN PRO v2.5 (released on August 22nd, 2007)
http://www.llblgen.com/defaultgeneric.aspx
Par Romagny13
Ecrire un commentaire - Voir les 0 commentaires - Recommander
Quelques astuces
1 - operateur ternaire
// resultat = condition? valeur retour condition vraie : valeur retour condition fausse
            // ex: int
            int i=11;
            int nResult = (i > 10) ? i * 2 : i;
2 – System.Enum
   Priority priority = Priority.Normal;
            // exemple : retourne "Normal"
            string result = System.Enum.Format(typeof(Priority), priority, "D"); //G ou g renvoie le nom (ex:"Normal"),D ou d renvoie la valeur (ex "2")
            string name = System.Enum.GetName(typeof(Priority), priority);//retourne "Normal
            // retourne les noms dans un tableau de string
            string[] priorities = System.Enum.GetNames(typeof(Priority));
            bool isDefined = System.Enum.IsDefined(typeof(Priority),"High");// retourne true
            // ... voir les autres membres
        

public enum Priority
{
None = 0,
Low = 1,
Normal=2,
High = 3,
NotRemovable = 4
}

3 – Délégués
Appeler plusieurs methods avec un délégué
Récuypèrer la liste des méthodes à appeler grace à System.Delegate
       private delegate void doActionEventHandler();
        private doActionEventHandler doAction;
 
        private void Form1_Load(object sender, EventArgs e)
        {
            //doAction +=new doActionEventHandler(DoFirstAction);
            //doAction +=new doActionEventHandler(DoSecondAction);
            // OU (inference de type)
            doAction += DoFirstAction;
            doAction += DoSecondAction;
 
 
            System.Delegate[] delegatesOfDoAction = doAction.GetInvocationList();
 
          // appeler un delegue de maniere asynchrone , attention le delegue ne doit avoir qu'une seule cible dans ce cas
            doAction.BeginInvoke(null, null);
        }
 
        public void DoFirstAction()
        { }
        public void DoSecondAction()
        { }
Par Romagny13
Ecrire un commentaire - Voir les 0 commentaires - Recommander

Caching Architecture Guide for .NET Framework Applications

http://msdn2.microsoft.com/en-us/library/ms978498.aspx

Par Romagny13
Ecrire un commentaire - Voir les 0 commentaires - Recommander
Encrypter des sections des fichiers de configuration

Exemple ici je vais encrypter une chaine connexion (connectionString de la section ConnectionStringSection)
On peut bien entendu encrypter ce que l’on veut (méthode protectSection()) et pas seulement les chaines de connexions
 private void button1_Click(object sender, EventArgs e)
        {
            Encrypt();
        }
        private void button2_Click(object sender, EventArgs e)
        {
            MessageBox.Show(Decrypt());
        }
       
        void Encrypt()
        {
            // Configuration config = ConfigurationManager.OpenExeConfiguration(“chemin vers fichier de configuration”);
            // ou
           Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
           config.ConnectionStrings.ConnectionStrings.Add(new ConnectionStringSettings("ConnectionStringContactDB",@"Data Source=.;Initial Catalog=ContactDB;User Id=romagny13;Password=motpasse;","System.Data.SqlClient"));
           config.ConnectionStrings.SectionInformation.ProtectSection("RsaProtectedConfigurationProvider");
           config.Save();
        }
        string Decrypt()
        {
            //Configuration config = ConfigurationManager.OpenExeConfiguration(“chemin vers fichier de configuration”);
            // ou
            Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            return config.ConnectionStrings.ConnectionStrings[1].ConnectionString;
        }
 
1 – au départ le fichier de configuration est « vide » :
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
</configuration>
 
2 – Après encryption  (J’utilise l’algorithme rsa > voir Machine.config C:/WINDOWS/Microsoft.NET/Framework/v2.0.50727/CONFIG)
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
 <connectionStrings configProtectionProvider="RsaProtectedConfigurationProvider">
    <EncryptedDataType="http://www.w3.org/2001/04/xmlenc#Element"
        xmlns="http://www.w3.org/2001/04/xmlenc#">
      <EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#tripledes-cbc" />
      <KeyInfo xmlns="http://www.w3.org/2000/09/xmldsig#">
        <EncryptedKey xmlns="http://www.w3.org/2001/04/xmlenc#">
          <EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#rsa-1_5" />
          <KeyInfo xmlns="http://www.w3.org/2000/09/xmldsig#">
            <KeyName>Rsa Key</KeyName>
          </KeyInfo>
          <CipherData>
            <CipherValue>njgfypi1V8zpQ182KzJSE0bXcXzIKssG66qGPcVFhmyfI7aKgwyLZ6xODZJFIoLbsicyCKRbOXDw3CavkWkkATWvUSbJXygz
qI3dmAN6iaqPf/z59pTvh/9n0dIo7cqEJ7bINhjSVWjEw8WaWsOZ1+l7hXaoA08EFuqISvGaZdw=</CipherValue>
          </CipherData>
        </EncryptedKey>
      </KeyInfo>
      <CipherData>
        <CipherValue>3QGWQVaQLe7Heh12eUQ+QklEtQm9bOBgdezJcu5FQeFZOmphx2zaB8ItJSqYLmjAMv5uBapHvAor9+kT80kxPPB/5dCDJj8r8aRDe
RYmdeWlT9iq9n95OP+9chuPLEn/bfQaJROq1C+FgGnnAhZwQAM0/qbcBs7c2u2yKiitMz8+Nd4yai1GYZtKpd+z/bpQ8/qLFHAeU1lEZDZ6lOJsU18B5pZvu2F
HTyjp5OTFfRm7yDunYhA4ER/YUIInSNKcuxGQ+eO65imEiUOlKCuSl6iV6fRU67SQcuAAm+oV5rIkOI+gBYTXPg==</CipherValue>
      </CipherData>
    </EncryptedData>
 </connectionStrings>
</configuration>
 
3 – je récupère très simplement ma chaine de connexion (méthode Decrypt)
encryption.jpg
Par Romagny13
Ecrire un commentaire - Voir les 0 commentaires - Recommander
Bien structurer ses événements

Je me suis inspiré de PropertyChanging pour cet exemple..
 
ClassDiagram1-copie-2.jpg

 
-          1 classe contenant l’EventArgs (héritant de EventArgs)
-          1 classe contenant le délégué (EventHandler)
-          Dans les classes utilisant l’EventArgs :
o   1 délégué
o   1 méthode On… retournant le délégué
-          Références de la classe + abonnement à l’événement (par += et méthode appelée)
1 - Créer une classe contenant l’EventArgs
    public class ContactPropertyChangingEventArgs : EventArgs
    {
        private readonly string propertyName;
 
        public virtual string PropertyName
        {
            get { return this.propertyName; }
        }
        public ContactPropertyChangingEventArgs(string propertyName)
        {
            this.propertyName = propertyName;
       
    }
 
2 - Créer une classe contenant le délégué :
-          Suffixé par Handler
-          Retournera l’objet ayant déclenché l’événement et L’EventArgs 

Note : étant donné l'on passe par l'intermédiaire d'un délégué, il est tout à fait possible de lancer l'événement de manière asynchrone avec BeginInvoke
    public delegate void ContactPropertyChangingEventHandler(object sender, ContactPropertyChangingEventArgs e);
 
3 - Créer une classe qui va utiliser l’événement  
    public class Contact
    {
        public event ContactPropertyChangingEventHandlerContactPropertyChanging;
 
        private int _contactID;
 
        public int ContactID
        {
            get { return _contactID; }
            set
            {
                this.OnContactPropertyChanging("ContactID");
                _contactID = value;
            }
        }
 
        private string _contactName;
 
        public string ContactName
        {
            get { return _contactName; }
            set
            {
                this.OnContactPropertyChanging("ContactName");
                _contactName = value;
            }
        }
 
        private int _contactAge;
 
        public int ContactAge
        {
            get { return _contactAge; }
            set
            {
                this.OnContactPropertyChanging("ContactAge");
                _contactAge = value;
            }
        }
 
        public Contact()
        { }
        public Contact(int contactID,string contactName,int contactAge)
        {
            this.ContactID = contactID;
            this.ContactName = contactName;
            this.ContactAge = contactAge;
        }
 
        public void OnContactPropertyChanging(string propertyName)
        {
            if ((this.ContactPropertyChanging != null))
            {
                this.ContactPropertyChanging(this, new ContactPropertyChangingEventArgs(propertyName));
            }
        }
    }
 
4 - La classe abonnée
       Contact contact;
 
        private void Form1_Load(object sender, EventArgs e)
        {
            contact = new Contact(2, "Bellin", 25);
            // on s’abonne à l’evenement
            contact.ContactPropertyChanging += new ContactPropertyChangingEventHandler(contact_ContactPropertyChanging);
        }
        // la méthode qui sera appelée
        void contact_ContactPropertyChanging(object sender, ContactPropertyChangingEventArgs e)
        {
            MessageBox.Show(e.PropertyName);
        }
 
        private void button1_Click(object sender, EventArgs e)
        {
            contact.ContactAge = 26;// birth day !!
        }
 
Par Romagny13
Ecrire un commentaire - Voir les 1 commentaires - Recommander
[resgen.exe] –
Générer une classe pour une gestion des ressources « typée »
 
Resgen.exe  est un utilitaire du SDK de Visual Studio (C:/Program Files/Microsoft Visual Studio 8/SDK/v2.0/ par défaut)
Ici je vais générer une classe à partir du fichier de ressources d’une application de manière à accéder très facilement à celles –ci , les fichiers de resources des forms sont egalement exploitables,
 l’interet est d’avoir un accès typé aux ressources et de ce fait bien simplifié et plus rapide que de passer par le ressourceManager
La commande :
resgen  « C:/Documents and Settings/romagny/Mes documents/Visual Studio 2005/Projects /DemoRessources/Properties/Resources.resx” /str:cs
 
Pour plus de renseignements sur les options disponibles :
ou tout simplement dans l’invite de commande
 resgen / ?
Le fichier resources.resources est généré ainsi qu’une classe Resources.cs comprenant des champs static
Au départ j’ai ajouté deux chaines de caracteres dans les ressources du projet (MessageAccueil et MessageFin) on les retrouve bien dans le code généré
Resources.cs
//------------------------------------------------------------------------------
// <auto-generated>
//     Ce code a été généré par un outil.
//     Version du runtime :2.0.50727.1378
//
//     Les modifications apportées à ce fichier peuvent provoquer un comportement incorrect et seront perdues si
//     le code est régénéré.
// </auto-generated>
//------------------------------------------------------------------------------
 
using System;
 
 
 
///<summary>
///   Une classe de ressource fortement typée destinée, entre autres, à la consultation des chaînes localisées.
///</summary>
// Cette classe a été générée automatiquement par la classe StronglyTypedResourceBuilder
// à l'aide d'un outil, tel que ResGen ou Visual Studio.
// Pour ajouter ou supprimer un membre, modifiez votre fichier .ResX, puis réexécutez ResGen
// avec l'option /str ou régénérez votre projet VS.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "2.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources {
   
    private static global::System.Resources.ResourceManager resourceMan;
   
    private static global::System.Globalization.CultureInfo resourceCulture;
   
    [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
    internal Resources() {
    }
   
    ///<summary>
    ///   Retourne l'instance ResourceManager mise en cache utilisée par cette classe.
    ///</summary>
    [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
    internal static global::System.Resources.ResourceManager ResourceManager {
        get {
            if (object.ReferenceEquals(resourceMan, null)) {
                global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Resources", typeof(Resources).Assembly);
                resourceMan = temp;
            }
            return resourceMan;
        }
    }
   
    ///<summary>
    ///   Remplace la propriété CurrentUICulture du thread actuel pour toutes
    ///   les recherches de ressources à l'aide de cette classe de ressource fortement typée.
    ///</summary>
    [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
    internal static global::System.Globalization.CultureInfo Culture {
        get {
            return resourceCulture;
        }
        set {
            resourceCulture = value;
        }
    }
   
    ///<summary>
    ///   Recherche une chaîne localisée semblable à Bienvenue.
    ///</summary>
    internal static string MessageAccueil {
        get {
            return ResourceManager.GetString("MessageAccueil", resourceCulture);
        }
    }
   
    ///<summary>
    ///   Recherche une chaîne localisée semblable à à bientot.
    ///</summary>
    internal static string MessageFin {
        get {
            return ResourceManager.GetString("MessageFin", resourceCulture);
        }
    }
}
 
 
Utilisation simplissime ,exemple :
lblMessage.Text = Resources.MessageAccueil;
 
Par Romagny13
Ecrire un commentaire - Voir les 0 commentaires - Recommander
Programmation orientée objet en C# - quelques points
I – sealed – une classe ne pouvant etre dérivée
// une classe ne pouvant pas etre héritée
    public sealed class ClassNotInheritable
    { }
 
 // non !! impossible
 ClassNotInheritable c = new ClassNotInheritable();
 
II virtual – pour avoir une méthode définie dans la classe de base mais que l’on peut redéfinir si l’on veut dans les classes dérivées
 public class VirtualClassBase
    {
        public virtual string virtualMethod()
        {
            return "depuis VirtualClassBase";
        }
    }
 
    public class ChildVirtual : VirtualClassBase
    {
        public override string virtualMethod()
        {
            return "depuis ChildVirtual";
        }
    }
 
Exemple :
            // si ChildVirtual redefini virtualMethod() > c'est viratualMethod() de ChildVirtual qui est appelé
            // sinon c'est virtualMethod() de VirtualClassBase
            ChildVirtual t = new ChildVirtual();
            MessageBox.Show(t.virtualMethod());
 
III  abstract – une classe de base ayant des membres abstract devant etre implémentés par les classes dérivées + des membres non abstract accessibles depuis les classes dérivées
    // une classe abstraite est une classe ayant des membres abstraits, qui devront etre implementés par les classes derivant
    // de plus les classes derivant d'une classe abstraite ont accès aux membres de celle-ci
    public abstract class abstractClassBase
    {
        // property
        public abstract int abstractProperty
        {
            get;
            set;
        }
        // methode
        public abstract string abstractMethod();
 
        // un membre non abstrait
        public int count = 10;
    }
    public class ChildAbstractClass : abstractClassBase
    {
        public override int abstractProperty
        {
            get
            {
              // à implementer
            }
            set
            {
              // à implémenter
            }
        }
        public override string abstractMethod()
        {
            return "implementé !!";
        }      
    }
 
            // classe abstraite
            ChildAbstractClass a = new ChildAbastractClass();
            a.count = 20;
 
IV – interface – ne contenant que des méthodes devant etre implémentées par les classes en dérivant + nouveautés avec .NET 2.0
public interface interfaceDemo
    {
        void Method();
    }
 
    public class ChildInterfaceDemo : interfaceDemo
    {
        //implemenetation "classique"
        //#region interfaceDemo Membres
 
        //public void Method()
        //{
        //    throw new Exception("The method or operation is not implemented.");
        //}
 
        //#endregion
 
        // force à utiliser cette methode depuis une instance de l'interface !! (.NET 2.0)
        #region interfaceDemo Membres
 
        void interfaceDemo.Method()
        {
            throw new Exception("The method or operation is not implemented.");
        }
 
        #endregion
    }
 
Exemple :
           // interface
            ChildInterfaceDemo ci = new ChildInterfaceDemo();
            // pas accès a Method() ici !!
 
            interfaceDemo ademo = new ChildInterfaceDemo();
            ademo.Method();
Par Romagny13
Ecrire un commentaire - Voir les 2 commentaires - Recommander
Surcharger un operateur (operator)

Exemple ici je vais surcharger les operateurs + et – permettant de renvoyer directement le résultat des prix des 2.
Je crées une classe Product
public class Product
    {
        private int _ProductID;
 
        public int ProductID
        {
            get { return _ProductID; }
            set { _ProductID = value; }
        }
 
        private string _ProductName;
 
        public string ProductName
        {
            get { return _ProductName; }
            set { _ProductName = value; }
        }
        private Decimal _UnitPrice;
 
        public Decimal UnitPrice
        {
            get { return _UnitPrice; }
            set { _UnitPrice = value; }
        }
        public Product()
            { }
 
            public Product(int ProductID,string ProductName,Decimal UnitPrice)
            {
                  this.ProductID = ProductID;
                  this.ProductName = ProductName;
                  this.UnitPrice = UnitPrice;
            }
 
        public static Decimal operator +(Product p1,Product p2)
        {
            return p1.UnitPrice + p2.UnitPrice;
        }
        public static Decimal operator -(Product p1, Product p2)
        {
            return p1.UnitPrice + p2.UnitPrice;
        }
    }
 
Utilisation
Ici je n’ai qu’à faire p1 + p2 au lieu de p1.UnitPrice + p2.UnitPrice
 private void button1_Click(object sender, EventArgs e)
        {
            Product p1 = new Product(1, "Chai", 18);
            Product p2 = new Product(1, "Chang", 19);
 
            Decimal result = p1 + p2;
            MessageBox.Show(result.ToString());
        }
 
Une autre utilisation assez connue est celle faite par les Nullables
Celles-ci retournent un type (ex :int )
Ce qui permet de faireNullable<int> intNullable = 10;
        // exemple avec le type int
        public static implicit operator int(intNullable i)
        {
            return i.Value;
        }
        public static explicit operator intNullable(int i)
        {
            return new intNullable(i);
        }
        // avec les generics
        public static implicit operator T?(T value)
        {
            return new T?(value);
        }
 
        public static explicit operator T(T? value)
        {
            return value.Value;
        }
 
Par Romagny13
Ecrire un commentaire - Voir les 0 commentaires - Recommander
Avoir plusieurs signatures pour accéder aux éléments d’une collection
 
Peut être avez-vous déjà remarqué que lorsque vous accédez à certaines collections du framework vous avez plusieurs signatures
Exemple avec un DataSet lorsque l’on désire accéder à une DataTable de ce DataSet on fait :
dataSet.Tables[0]
ou
dataSet.Tables[« nomtable »]
Cet article explique comment on peut mettre en place cela
 
 
Dans mon exemple je vais faire en sorte d’avoir deux signatures pour accéder à un élément de la collection
-          Soit par l’index
-          Soit par le contactName
  Collection1.jpg
collection2.jpg
préparation
Ma classique classe contact
 public class Contact
    {
        private int _ContactID;
 
        public int ContactID
        {
            get { return _ContactID; }
            set { _ContactID = value; }
        }
 
        private string _ContactName;
 
        public string ContactName
        {
            get { return _ContactName; }
            set { _ContactName = value; }
        }
 
        private Nullable<int> _ContactAge;
 
        public Nullable<int> ContactAge
        {
            get { return _ContactAge; }
            set { _ContactAge = value; }
        }
 
        public Contact()
        { }
 
        public Contact(int contactID, string contactName, Nullable<int> contactAge)
        {
            this.ContactID = contactID;
            this.ContactName = contactName;
            this.ContactAge = contactAge;
        }
 
        public override string ToString()
        {
            return "ContactID = " + ContactID.ToString() + ",Contactname = " + ContactName + ",ContactAge = " + ContactAge.ToString() ;
        }
 
    }
 
 
I - avec une collection [.NET 1.0]
(je dérive ici ma collection de collectionBase pour ne pas avoir toutes les méthodes à réimplementer mais rien ne vous empeche bien sur de deriver de ICollection,…)
public class ContactCollection : CollectionBase
    {
        public Contact this[int index]
        {
            get
            {
                return (Contact) this.List[index];
            }
        }
 
        public Contact this[string contactName]
        {
            get
            {
                return this.Find(contactName);
            }
        }
 
 
        public void Add(Contact c)
        {
            this.List.Add(c);
        }
        private Contact Find(string contactName)
        {
            foreach (Contact c in this)
                if (c.ContactName == contactName)
                    return c;
 
            return null;
        }   
    }
 
II - avec une liste générique [.NET 2.0]
 
 public class ContactCollection : List<Contact>
    {
        public Contact this[string contactName]
        {
            get
            {
                return this.Find(delegate(Contact c)
                {
                    return c.ContactName == contactName;
                });
            }
        }
    }
 
 
Exemples d’utilisations
Code de la form principale
       ContactCollection Contacts = new ContactCollection();
 
        private void Form1_Load(object sender, EventArgs e)
        {
            Contacts.Add(new Contact(1, "Romagny", 31));
            Contacts.Add(new Contact(2, "Bellin",25));
            Contacts.Add(new Contact(3, "Durand", 50));
        }
 
        private void button1_Click(object sender, EventArgs e)
        {
            MessageBox.Show(Contacts["Romagny"].ToString());
        }
 
        private void button2_Click(object sender, EventArgs e)
        {
            MessageBox.Show(Contacts[2].ToString());
        }
 

Un dernier point les properties à la compilation sont converties en méthode (comme on peut le constater avec Reflector) : 
exemple ici avec la classe héritant de CollectionBase
       public Contact get_Item(string contactName)
        {
            return this.Find(contactName);
        }
        public Contact get_Item(int index)
        {
            return (Contact)base.List[index];
        }
 
get.jpg
Par Romagny13
Ecrire un commentaire - Voir les 0 commentaires - Recommander
Astuces - Appeler un constructeur de la même class avec le mot clé this

Pour mieux l’observer il suffit de placer des points d’arrêts
I rappel appeler le constructeur de la classe de base avec Base()
Tout le monde sait que l’on peut appeler le constructeur de la classe de base avec Base() depuis le constructeur de la classe dérivée
Exemple :
Student student = new Student("maxime");
 
Le constructeur de Student sera appelé puis automatiquement le constructeur de Person dans la foulée
public class Person
    {
        private string _name;
 
        public string Name
        {
            get { return _name; }
            set { _name = value; }
        }
 
        public Person()
        { }
        public Person(string name)
        {
            this.Name = name;
        }
    }
    public class Student : Person
    {
 
        public Student(string studentName)
            : base(studentName)
        { }
    }
 
II Appeler un constructeur de la même classe avec this()
 
Exemple :
Le constructeur avec le texte SQL de la commande et la connexion sera appelé puis dans la foulée le constructeur par défaut
Bien entendu on peut appelé un constructeur qui aurait des parametres et lui passer
           OleDbConnection OleDbConnection=new OleDbConnection();
            OleDbCommandManager oleDbCommandManager = new OleDbCommandManager("select * from [Contact]",OleDbConnection);
 
public class OleDbCommandManager
    {
 
        private OleDbCommand _oleDbCommand;
 
        public OleDbCommand OleDbCommand
        {
            get { return _oleDbCommand; }
            set { _oleDbCommand = value; }
        }
 
        public OleDbCommandManager()
        {
            this.OleDbCommand.CommandTimeout = 30;
            this.OleDbCommand.UpdatedRowSource = System.Data.UpdateRowSource.Both;
            GC.SuppressFinalize(this);
        }
public OleDbCommandManager(string cmdText, OleDbConnection connection)
            : this()
        {
            this.OleDbCommand.CommandText = cmdText;
            this.OleDbCommand.Connection = connection;
        }
 
        private OleDbCommandManager(OleDbCommand from)
            : this()
        {
            this.OleDbCommand.CommandText = from.CommandText;
            this.OleDbCommand.CommandTimeout = from.CommandTimeout;
            this.OleDbCommand.CommandType = from.CommandType;
            this.OleDbCommand.Connection = from.Connection;
            this.OleDbCommand.DesignTimeVisible = from.DesignTimeVisible;
            this.OleDbCommand.UpdatedRowSource = from.UpdatedRowSource;
            this.OleDbCommand.Transaction = from.Transaction;
            OleDbParameterCollection parameters = this.OleDbCommand.Parameters;
            foreach (object obj2 in from.Parameters)
            {
                parameters.Add((obj2 is ICloneable) ? (obj2 as ICloneable).Clone() : obj2);
            }
        }
 
       
    }
 
Par Romagny13
Ecrire un commentaire - Voir les 0 commentaires - Recommander
Undo/Redo manager


Une notion importante, exemple comment annuler ou retablir l'etat courant d'un objet aprés l'avoir modifier(je pense notamment à un treeview permettant d'editer du Xml que j'ai mis en place dans une application)
juste que je penchais sur le sujet voila que je tombe sur cette source postée sur codeproject hier soir,pour avoir survoler le code avant d'alller me coucher cela parait bon et en plus l'exemple utilisé est agréable

http://www.codeproject.com/cs/library/AutomatingUndoRedo.asp
Par Romagny13
Ecrire un commentaire - Voir les 0 commentaires - Recommander
Utiliser les « predicates » en .NET 1.0,
avoir "presque le confort des generics" en .NET 1.0
Avec le Framework .NET 1.0, on ne dispose pas des generics, aussi on est obligé par exemple d’utiliser une classe collection dérivée de System.Colllections.CollectionBase pour remplacer les fameuses listes génériques, on ne dispose donc pas des méthodes Find,FindAll,etc.
Ici je montre que l’on peut quand même se débrouiller pour implémenter des méthodes Find,FindAll,etc . en .NET 1.0
-          Utiliser un délégué
-          Créer une méthode FindAll recevant une méthode qui sera appelée par le délégué
-           passer la méthode qui devra etre appelée par le délégué en paramètre
using System;
using System.Text;
 
namespace cs2GenProject1.BusinessObjects
{
    public class ContactCollection : System.Collections.CollectionBase
    {
        public delegate bool PredicateMethod(Contact obj);
 
        public Contact this[int nIndex]
        {
            get { return ((Contact)List[nIndex]); }
            set { List[nIndex] = value; }
        }
 
        public ContactCollection()
        { }
        public void Add(Contact oContact)
        {
            this.List.Add(oContact);
        }
 
        public ContactCollection FindAll(PredicateMethod match)
        {
            ContactCollection result = new ContactCollection();
            foreach (Contact oContact in this)
            {
// appel de la méthode passée en paramètre, si le résultat renvoyé par la méthode est true alors on ajoute l’element à la collection retournée par FindAll()
                if (match(oContact))
                    result.List.Add(oContact);
            }
            return result;
        }
// exemple de méthode,ici on voit si le nom du contact commence par "a"
        public bool StartsWith(Contact oContact)
        {
            bool result = false;
            if (oContact.nom_contact.Substring(0, 1) == "A")
                result = true;
 
            return result;
        }
    }
}
 
 
IMPORTANT (format de la méthode) la méthode doit renvoyer un booléen indiquant si oui ou non l’élément passé en paramètre doit être ajouté dans la collection en résultat
Public bool nométhode(Type t)
{
// test,
return result
}
 
 
 
Utilisation
        private void button1_Click(object sender, EventArgs e)
        {
            ContactCtrl oContactCtrl = new ContactCtrl();
            ContactCollection Contacts = oCONTACTCtrl.GetContacts();
 
            ContactCollection result = Contacts.FindAll(Contacts.StartsWith);
 
            dataGridView1.DataSource = result;
        }
 
 
 
Note : on peut pousser son raisonnement plus loin
Et définir un délégué  « générique », sauf qu’en .NET 1.0 on utilisera le type objet (au lieu de T des generics avec .NET 2.0) :
public delegate bool PredicateMethod(object obj);
 
Il faudra alors utiliser la reflection pour effectuer la comparaison par rapport aux properties
 
En fait si on veut vraiment,il y a beaucoup d’éléments de .NET 2.0 que l’on peut reproduire en .NET 1.0 (ex : Nullables,…), par contre il faut utiliser le type object à la place de T des generics souvent
Car c’est vrai il faut bien l’avouer plus on goutte au confort en .NET 2.0 voir .NET 3.0 et plus on a du mal à retourner vers les versions antérieures du Framework :p
Par Romagny13
Ecrire un commentaire - Voir les 0 commentaires - Recommander
Créer une solution Visual Studio 2005 avec plusieurs projets


solution.jpg

L’exemple ici est très simple(pas de fichiers)
Comme je vais peut être créer un générateur de code NTiers (ou plutôt créer une version 2 avec tout ce que j’ai appris), je vais essayé de générer directement la solution avec toutes les couches
 
Bon Microsoft m’en voudra pas je ne vais pas dévoiler des « secrets » ou du moins peut etre pas encore :p (il suffit un peu d’observer c’est tout)
 (j'ai du enlever les tabulations t qui ne sont pas pris en charge sur le blog)
private void button1_Click(object sender, EventArgs e)
        {
 
            // demarche
            // créer le dossier prinicpal
            // créer le dossier contenant le premier projet
            // ajouter les fichiers dans ce dossier
            // creer le csproj
            // .. créer tous les autres projets avec la même démarche
            //
            // .. finalement créer la solution pointant chaque projet créé
 
            string path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "/TEST";
            System.IO.Directory.CreateDirectory(path);
            string GuidOfBLL=GetNewGuid();
            string GuidOfDAL=GetNewGuid();
 
            //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
            // 1 er projet
            //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
            string xmlOfBLL= "<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">" + Environment.NewLine;
            xmlOfBLL += "<PropertyGroup>" + Environment.NewLine;
            xmlOfBLL += "<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>" + Environment.NewLine;
            xmlOfBLL += "<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>" + Environment.NewLine;
            xmlOfBLL += "<ProductVersion>8.0.50727</ProductVersion>" + Environment.NewLine;
            xmlOfBLL += "<SchemaVersion>2.0</SchemaVersion>" + Environment.NewLine;
            xmlOfBLL += "<ProjectGuid>" + GuidOfBLL + "</ProjectGuid>" + Environment.NewLine;
            xmlOfBLL += "<OutputType>Library</OutputType>" + Environment.NewLine;
            xmlOfBLL += "<AppDesignerFolder>Properties</AppDesignerFolder>" + Environment.NewLine;
            xmlOfBLL += "<RootNamespace>Cs2Gen.BLL</RootNamespace>" + Environment.NewLine;
            xmlOfBLL += "<AssemblyName>Cs2Gen.BLL</AssemblyName>" + Environment.NewLine;
            xmlOfBLL += "</PropertyGroup>" + Environment.NewLine;
            xmlOfBLL += "<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">" + Environment.NewLine;
            xmlOfBLL += "<DebugSymbols>true</DebugSymbols>" + Environment.NewLine;
            xmlOfBLL += "<DebugType>full</DebugType>" + Environment.NewLine;
            xmlOfBLL += "<Optimize>false</Optimize>" + Environment.NewLine;
            xmlOfBLL += "<OutputPath>binDebug</OutputPath>" + Environment.NewLine;
            xmlOfBLL += "<DefineConstants>DEBUG;TRACE</DefineConstants>" + Environment.NewLine;
            xmlOfBLL += "<ErrorReport>prompt</ErrorReport>" + Environment.NewLine;
            xmlOfBLL += "<WarningLevel>4</WarningLevel>" + Environment.NewLine;
            xmlOfBLL += "</PropertyGroup>" + Environment.NewLine;
            xmlOfBLL += "<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">" + Environment.NewLine;
            xmlOfBLL += "<DebugType>pdbonly</DebugType>" + Environment.NewLine;
            xmlOfBLL += "<Optimize>true</Optimize>" + Environment.NewLine;
            xmlOfBLL += "<OutputPath>binRelease</OutputPath>" + Environment.NewLine;
            xmlOfBLL += "<DefineConstants>TRACE</DefineConstants>" + Environment.NewLine;
            xmlOfBLL += "<ErrorReport>prompt</ErrorReport>" + Environment.NewLine;
            xmlOfBLL += "<WarningLevel>4</WarningLevel>" + Environment.NewLine;
            xmlOfBLL += "</PropertyGroup>" + Environment.NewLine;
            // Item group : references
            xmlOfBLL += "<ItemGroup>" + Environment.NewLine;
            xmlOfBLL += "<Reference Include="System" />" + Environment.NewLine;
            xmlOfBLL += "<Reference Include="System.Data" />" + Environment.NewLine;
            xmlOfBLL += "<Reference Include="System.Xml" />" + Environment.NewLine;
            xmlOfBLL += "</ItemGroup>" + Environment.NewLine;
            // Item group : Compile
            xmlOfBLL += "<ItemGroup>" + Environment.NewLine;
            xmlOfBLL += "</ItemGroup>" + Environment.NewLine;
            xmlOfBLL += "<Import Project="$(MSBuildBinPath)Microsoft.CSharp.targets" />" + Environment.NewLine;
            xmlOfBLL += "</Project>";
 
            System.IO.Directory.CreateDirectory(path + "/Cs2Gen.BLL");
            Write(path + "/Cs2Gen.BLL/Cs2Gen.BLL.csproj", xmlOfBLL);
 
            //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
            // 2 eme projet
            //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
            string xmlOfDAL = "<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">" + Environment.NewLine;
            xmlOfDAL += "<PropertyGroup>" + Environment.NewLine;
            xmlOfDAL += "<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>" + Environment.NewLine;
            xmlOfDAL += "<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>" + Environment.NewLine;
            xmlOfDAL += "<ProductVersion>8.0.50727</ProductVersion>" + Environment.NewLine;
            xmlOfDAL += "<SchemaVersion>2.0</SchemaVersion>" + Environment.NewLine;
            xmlOfDAL += "<ProjectGuid>" + GuidOfDAL + "</ProjectGuid>" + Environment.NewLine;
            xmlOfDAL += "<OutputType>Library</OutputType>" + Environment.NewLine;
            xmlOfDAL += "<AppDesignerFolder>Properties</AppDesignerFolder>" + Environment.NewLine;
            xmlOfDAL += "<RootNamespace>Cs2Gen.DAL</RootNamespace>" + Environment.NewLine;
            xmlOfDAL += "<AssemblyName>Cs2Gen.DAL</AssemblyName>" + Environment.NewLine;
            xmlOfDAL += "</PropertyGroup>" + Environment.NewLine;
            xmlOfDAL += "<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">" + Environment.NewLine;
            xmlOfDAL += "<DebugSymbols>true</DebugSymbols>" + Environment.NewLine;
            xmlOfDAL += "<DebugType>full</DebugType>" + Environment.NewLine;
            xmlOfDAL += "<Optimize>false</Optimize>" + Environment.NewLine;
            xmlOfDAL += "<OutputPath>binDebug</OutputPath>" + Environment.NewLine;
            xmlOfDAL += "<DefineConstants>DEBUG;TRACE</DefineConstants>" + Environment.NewLine;
            xmlOfDAL += "<ErrorReport>prompt</ErrorReport>" + Environment.NewLine;
            xmlOfDAL += "<WarningLevel>4</WarningLevel>" + Environment.NewLine;
            xmlOfDAL += "</PropertyGroup>" + Environment.NewLine;
            xmlOfDAL += "<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">" + Environment.NewLine;
            xmlOfDAL += "<DebugType>pdbonly</DebugType>" + Environment.NewLine;
            xmlOfDAL += "<Optimize>true</Optimize>" + Environment.NewLine;
            xmlOfDAL += "<OutputPath>binRelease</OutputPath>" + Environment.NewLine;
            xmlOfDAL += "<DefineConstants>TRACE</DefineConstants>" + Environment.NewLine;
            xmlOfDAL += "<ErrorReport>prompt</ErrorReport>" + Environment.NewLine;
            xmlOfDAL += "<WarningLevel>4</WarningLevel>" + Environment.NewLine;
            xmlOfDAL += "</PropertyGroup>" + Environment.NewLine;
            // Item group : references
            xmlOfDAL += "<ItemGroup>" + Environment.NewLine;
            xmlOfDAL += "<Reference Include="System" />" + Environment.NewLine;
            xmlOfDAL += "<Reference Include="System.Data" />" + Environment.NewLine;
            xmlOfDAL += "<Reference Include="System.Xml" />" + Environment.NewLine;
            xmlOfDAL += "</ItemGroup>" + Environment.NewLine;
 
            // Item group : Compile
            xmlOfDAL += "<ItemGroup>" + Environment.NewLine;
            xmlOfDAL += "</ItemGroup>" + Environment.NewLine;
            xmlOfDAL += "<Import Project="$(MSBuildBinPath)Microsoft.CSharp.targets" />" + Environment.NewLine;
            xmlOfDAL += "</Project>";
 
            System.IO.Directory.CreateDirectory(path + "/Cs2Gen.DAL");
            Write(path + "/Cs2Gen.DAL/Cs2Gen.DAL.csproj", xmlOfDAL);
 
            //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
            // SOLUTION
            //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
            string GuidOfSolution = "{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}";
            string xmlOfSolution = "Microsoft Visual Studio Solution File, Format Version 9.00" + Environment.NewLine;
            xmlOfSolution += "# Visual Studio 2005" + Environment.NewLine;
            xmlOfSolution += "Project("" + GuidOfSolution + @""") = ""Cs2Gen.BLL"",""Cs2Gen.BLLCs2Gen.BLL.csproj"", " + GuidOfBLL + "" + Environment.NewLine;
            xmlOfSolution += "EndProject" + Environment.NewLine;
            xmlOfSolution += "Project("" + GuidOfSolution + @""") = ""Cs2Gen.DAL"",""Cs2Gen.DALCs2Gen.DAL.csproj"", " + GuidOfDAL + "" + Environment.NewLine;
            xmlOfSolution += "EndProject" + Environment.NewLine;
            xmlOfSolution += "Global" + Environment.NewLine;
            xmlOfSolution += "     GlobalSection(SolutionConfigurationPlatforms) = preSolution" + Environment.NewLine;
            xmlOfSolution += "           Debug|Any CPU = Debug|Any CPU" + Environment.NewLine;
            xmlOfSolution += "           Release|Any CPU = Release|Any CPU" + Environment.NewLine;
            xmlOfSolution += "     EndGlobalSection" + Environment.NewLine;
            xmlOfSolution += "     GlobalSection(ProjectConfigurationPlatforms) = postSolution" + Environment.NewLine;
            xmlOfSolution += "           " + GuidOfBLL + ".Debug|Any CPU.ActiveCfg = Debug|Any CPU" + Environment.NewLine;
            xmlOfSolution += "           " + GuidOfBLL + ".Debug|Any CPU.Build.0 = Debug|Any CPU" + Environment.NewLine;
            xmlOfSolution += "           " + GuidOfBLL + ".Release|Any CPU.ActiveCfg = Release|Any CPU" + Environment.NewLine;
            xmlOfSolution += "           " + GuidOfBLL + ".Release|Any CPU.Build.0 = Release|Any CPU" + Environment.NewLine;
            xmlOfSolution += "           " + GuidOfDAL + ".Debug|Any CPU.ActiveCfg = Debug|Any CPU" + Environment.NewLine;
            xmlOfSolution += "           " + GuidOfDAL + ".Debug|Any CPU.Build.0 = Debug|Any CPU" + Environment.NewLine;
            xmlOfSolution += "           " + GuidOfDAL + ".Release|Any CPU.ActiveCfg = Release|Any CPU" + Environment.NewLine;
            xmlOfSolution += "           " + GuidOfDAL + ".Release|Any CPU.Build.0 = Release|Any CPU" + Environment.NewLine;
            xmlOfSolution += "     EndGlobalSection" + Environment.NewLine;
            xmlOfSolution += "     GlobalSection(SolutionProperties) = preSolution" + Environment.NewLine;
            xmlOfSolution += "           HideSolutionNode = FALSE" + Environment.NewLine;
            xmlOfSolution += "     EndGlobalSection" + Environment.NewLine;
            xmlOfSolution += "EndGlobal" + Environment.NewLine;
 
 
            Write(path + "/Cs2Gen.sln", xmlOfSolution);         
 
        }
 
        public static string GetNewGuid()
        {
            String result= "{";
            result += System.Guid.NewGuid().ToString();
            result += "}";
 
            return result;
        }
        public static void Write(string path, string value)
        {
            System.IO.StreamWriter oStreamWriter;
            oStreamWriter = new System.IO.StreamWriter(path, false);
 
            try
            {
                oStreamWriter.Write(value);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                oStreamWriter.Close();
            }
        }
 
Par Romagny13
Ecrire un commentaire - Voir les 0 commentaires - Recommander

[ Développement en couches - Ce que j'essaie de mettre en place ]


> couches NTiers
Couches1.JPG


> Ce que j'essaie de mettre en place 

couche2-copie-2.JPG  

Par Romagny13
Ecrire un commentaire - Voir les 0 commentaires - Recommander
Etude sur les 3 « frêres » Xml,Objet,Base de données
 
Plus j’apprends sur Xml et plus je me rends compte de pleins de choses  ...

Dans tout type information on a :
              - la structure des informations 
              - les données
              (- voir également la présentation ex :OpenXml ou les fichiers Xslt)
Mon objectif > éviter des recopies dans l’application (dans une couche métier) d’informations qui existent déjà (soit dans un fichier xml ou  une base de données), et comme Microsoft le fait avec .NET 3.0 j’essaie aussi de quitter le monde des collections beaucoup trop pénalisant en termes de monopolisation en ressources vers le monde des énumérations qui allègent considérablement les traitements
I - Dans le monde Xml :
-          accès générique à tout type de format de fichier Xml : Bibliothèques de classes System.Xml (XmlDocument,…) ,expressions XPath pour une sélection rapide – en .NET 3.0 ce serait plutôt System.Linq.Xml + Linq To Xml
-          Il faut dabord créer son schèma xml celui-ci permet de définir la structure que devront respecter les fichiers Xml (Xml Spy est un bon outil pour cela,je suis tombé aussi sur un pas mauvais outil Liquid Xml Studio disponible en version beta)
-          Une fois le schèma défini – on peut créer les fichiers Xml qui en fait eux contiendront les données « typées »
Xml convient très bien au monde des objets du fait de ses imbrications
II - Dans le monde objet :
-          Accès générique à tout type objet : la reflection,le type object et les generics + requetage par itération,énumération,prédicats for/foreach + conditions de sélections if et boléen (renvoyant true ou false si la condition est remplie ou non)
-          La structure serait la couche métier(  ex : classe contact, contenant fields,properties et constructeurs)
-          Les collections (liste générique, classes collections,array,objet,etc.) représentent les données « typées »
III - Dans le monde relationnel (bases de données) :
-          Accès générique aux bases de données : via odbc ou >System .Data.Common (DbProverFactory en .NET 2.0/fabrique de classes) + SQL pour le requêtage
-          La structure des tables (colonnes,contraintes,etc.)
-          Les lignes des tables représentent les données « typées »
Les bases de données posent des problèmes du fait que les tables se basent sur des clés étrangères(champ) pour définir des relations entre tables
Alors que dans le monde des objets , l’objet contient l’objet en lui-même et non une clé vers une autre classe ou table (en fait le problême vient du fait qu'une table n'a que des types "value" on pourrait dire et ne peut avoir de type référence)

en fait lorsque l'on a par exemple à ajouter un contact en base (qui a un nom,prenom,age) et qui aurait également une collection de livres (par exemple)
> utiliser les transactions
> il faudrait ajouter en 1 la collection de livre dans la table livre
> 2 ajouter le contact en base avec les clés étrangères pointant sur les livres de ce contact (en fait ici dans une table relation)

la démarche est en fait la même qu'en objet, en objet on ferait :
> 1 créer la collection de livres
> 2 ajouter la collection de livres a ce contact
> 3 ajouter le contact à la collection de contacts
 (l'exemple n'est pas forcément trés parlant mais c'est le principe qu'il faut voir)
 
Par Romagny13
Ecrire un commentaire - Voir les 0 commentaires - Recommander
Attributs personnalisés
Dans mon exemple je vais simuler un attribut personnalisé de Mapping comme le fait Linq To SQL
1 – Créer une classe pour cet attribut personnalisé
celle-ci doit hériter de System.Attribute
[AttributeUsage(AttributeTargets.Property,AllowMultiple=false)]
public class MappingAttribute : System.Attribute
    {
        private string _Storage;
 
        public string Storage
        {
            get { return _Storage; }
            set { _Storage = value; }
        }
 
        private string _Name;
 
        public string Name
        {
            get { return _Name; }
            set { _Name = value; }
        }
 
 
        private bool _isPrimaryKey;
 
        public bool IsPrimaryKey
        {
            get { return _isPrimaryKey; }
            set { _isPrimaryKey = value; }
        }
 
        private bool _CanBeNull;
 
        public bool CanBeNull
        {
            get { return _CanBeNull; }
            set { _CanBeNull = value; }
        }
 
        private string _DBType;
 
        public string DBType
        {
            get { return _DBType; }
            set { _DBType = value; }
        }
 
        public MappingAttribute()
        { }
        public MappingAttribute(string Storage, string Name, bool IsPrimaryKey, bool CanBeNull, string DBType)
        {
            this.Storage = Storage;
            this.Name = Name;
            this.IsPrimaryKey = IsPrimaryKey;
            this.CanBeNull = CanBeNull;
            this.DBType = DBType;
        }
 
 
2 – Utilisation de l’attribut personnalisé que je viens de créer
public class Contact
    {
        private string _ContactName;
 
        [MappingAttribute(Storage = "ContactName", Name = "Name", DBType = "CHAR(150)", IsPrimaryKey = false, CanBeNull = false)]
        public string ContactName
        {
            get { return _ContactName; }
            set { _ContactName = value; }
        }
 
        public Contact()
        { }
        public Contact(string ContactName)
        {
            this.ContactName = ContactName;
        }
    }
 
3 – Récupérer les informations grâce à la reflection durant l’exécution du programme
private void button1_Click(object sender, EventArgs e)
        {
            Contact oContact = new Contact("Romagny");
 
            MessageBox.Show(GetMappingAttributeOfProperty("ContactName").Name);
        }
 
        public MappingAttribute GetMappingAttributeOfProperty(string PropertyName)
        {
            MappingAttribute oMappingAttribute = null;
            System.Reflection.Assembly oAssembly = System.Reflection.Assembly.GetExecutingAssembly();
            foreach(Type oType in oAssembly.GetTypes())
            {
                if (oType.Name == "Contact")
                {
                    foreach (System.Reflection.PropertyInfo oPropertyInfo in oType.GetProperties())
                    {
                        if (oPropertyInfo.Name == PropertyName)
                        {
                            object[] CustomAttributes = oPropertyInfo.GetCustomAttributes(typeof(MappingAttribute), true);
                            oMappingAttribute = CustomAttributes[0] as MappingAttribute;
                        }
                    }
                }
            }
            return oMappingAttribute;
        } 
  
// OU plus rapide
 public MappingAttribute GetMappingAttributeOfProperty(string PropertyName)
        {
            System.Reflection.Assembly oAssembly = System.Reflection.Assembly.GetExecutingAssembly();
            return oAssembly.GetType("AttributsPersonnalises.Contact").GetProperty(PropertyName).GetCustomAttributes(typeof(MappingAttribute), true)[0] as MappingAttribute;
        }
 
Par Romagny13
Ecrire un commentaire - Voir les 0 commentaires - Recommander
Drag and Drop depuis l’explorateur de fichiers Windows vers son application
 
2 méthodes qui pourront être appelées par n’importe quel control depuis leurs évènements DragEnter et DragDrop
       public string[] DropFiles;
 
        private void GetDropFiles(DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                DropFiles = (string[])e.Data.GetData(DataFormats.FileDrop);
                e.Effect = System.Windows.Forms.DragDropEffects.Move;
            }
        }
        private string GetDropFile(int Index)
        {
            string DropFile = string.Empty;
 
            if (DropFiles.Length == 0 || DropFiles.Length - 1 < Index)
            { }
            else
                DropFile = DropFiles[Index];
 
            return DropFile;
        }
 
Exemple d’utilisation avec une treeview (de la même manière cela pourrait être une listbox ou même la form en elle – même)
> ne pas oublier de mettre la propriété AllowDrop à true pour le control recevant le drag drop
        private void treeView1_DragEnter(object sender, DragEventArgs e)
        {
            GetDropFiles(e);
        }
 
        private void treeView1_DragDrop(object sender, DragEventArgs e)
        {
            try
            {
                string DropFile = GetDropFile(0);
                if (!string.IsNullOrEmpty(DropFile))
                    LoadFromFile.BeginInvoke(DropFile, null, null);
            }
            catch
            { }
        }
 
Par Romagny13
Ecrire un commentaire - Voir les 0 commentaires - Recommander
Créer une dll afin d’améliorer les performances de traitement d’une expression régulière
Pour une application (éditeur avec coloration syntaxique) j’essaie de trouver tout ce qui me permettrait de gagner en performance, et notamment au chargement de fichier de taille conséquente (5000 lignes)
Dernière tentative en date > compilation d’une dll contenant la regex à utiliser, il parait que l’on peut gagner la moitié de temps en performance .. bof je ne l’ai pas encore verifié 
            string Keywords = @"(?<=s|{|}|(|)|,|=|^)(ABSOLUTE|ACTION|ADD|ALL|ALLOCATE|ALTER|AND|ANY|ARE|AS|ASC|ASSERTION|AT|AUTHORIZATION|AVG|BEGIN|BETWEEN|BIT|BIT_LENGTH|BOTH|BY|CASCADE|CASCADED|CASE|CAST|CATALOG|CHAR|CHARACTER|CHAR_LENGTH|CHARACTER_LENGTH|CHECK|CLOSE|COALESCE|COLLATE|COLLATION|COLUMN|COMMIT|CONNECT|CONNECTION|CONSTRAINT|CONSTRAINTS|CONTINUE|CONVERT|CORRESPONDING|COUNT|CREATE|CROSS|CURRENT|CURRENT_DATE|CURRENT_TIME|CURRENT_TIMESTAMP|CURRENT_USER|CURSOR|DATE|DAY|DEALLOCATE|DEC|DECIMAL|DECLARE|DEFAULT|DEFERRABLE|DEFERRED|DELETE|DESC|DESCRIBE|DESCRIPTOR|DIAGNOSTICS|DISCONNECT|DISTINCT|DOMAIN|DOUBLE|DROP|ELSE|END|END-EXEC|ESCAPE|EXCEPT|EXCEPTION|EXEC|EXECUTE|EXISTS|EXTERNAL|EXTRACT|FALSE|FETCH|FIRST|FLOAT|FOR|FOREIGN|FOUND|FROM|FULL|GET|GLOBAL|GO|GOTO|GRANT|GROUP|HAVING|HOUR|IDENTITY|IMMEDIATE|IF|IN|INDICATOR|INITIALLY|INNER|INPUT|INSENSITIVE|INSERT|INT|INTEGER|INTERSECT|INTERVAL|INTO|IS|ISOLATION|JOIN|KEY|LANGUAGE|LAST|LEADING|LEFT|LEVEL|LIKE|LOCAL|LOWER|MATCH|MAX|MIN|MINUTE|MODULE|MONTH|NAMES|NATIONAL|NATURAL|NCHAR|NEXT|NO|NOT|NULL|NULLIF|NUMERIC|OCTET_LENGTH|OF|ON|ONLY|OPEN|OPTION|OR|ORDER|OUTER|OUTPUT|OVERLAPS|PAD|PARTIAL|POSITION|PRECISION|PREPARE|PRESERVE|PRIMARY|PRIOR|PRIVILEGES|PROCEDURE|PUBLIC|READ|REAL|REFERENCES|RELATIVE|RESTRICT|REVOKE|RIGHT|ROLLBACK|ROWS|SCHEMA|SCROLL|SECOND|SECTION|SELECT|SESSION|SESSION_USER|SET|SIZE|SMALLINT|SOME|SPACE|SQL|SQLCODE|SQLERROR|SQLSTATE|SUBSTRING|SUM|SYSTEM_USER|TABLE|TEMPORARY|THEN|TIME|TIMESTAMP|TIMEZONE_HOUR|TIMEZONE_MINUTE|TO|TRAILING|TRANSACTION|TRANSLATE|TRANSLATION|TRIM|TRUE|UNION|UNIQUE|UNKNOWN|UPDATE|UPPER|USAGE|USER|USING|VALUE|VALUES|VARCHAR|VARYING|VIEW|WHEN|WHENEVER|WHERE|WITH|WORK|WRITE|YEAR|ZONE)b";
            System.Text.RegularExpressions.RegexCompilationInfo oRegexCompilationInfo = new System.Text.RegularExpressions.RegexCompilationInfo(Keywords, System.Text.RegularExpressions.RegexOptions.IgnoreCase, "SQLEditorRegex", "SQLEditorRegex", true);
            System.Text.RegularExpressions.RegexCompilationInfo[] oRegexCompilationInfos = new System.Text.RegularExpressions.RegexCompilationInfo[] { oRegexCompilationInfo };
            System.Reflection.AssemblyName oAssemblyName = new System.Reflection.AssemblyName();
            oAssemblyName.Name = "Regex";
            System.Text.RegularExpressions.Regex.CompileToAssembly(oRegexCompilationInfos, oAssemblyName);
 
Une dll lest donc créée, il suffit ensuite de faire appel à celle-ci, le code généré dans la dll est plus que conséquent
compilationregex.JPG
Utilisation  :
SQLEditorRegex.SQLEditorRegex oSQLEditorRegex;
 
           oSQLEditorRegex=new SQLEditorRegex.SQLEditorRegex();
 
// etc.
 
public void ColorLine(int offset, string sCurrentLine)
        {
            if (!this.Created)
            { }
            else
            {
                Int32 endpos = offset + sCurrentLine.Length;
                tom.ITextRange rg = this.ITextDocument.Range(offset, endpos);
                if (rg.Font.CanChange() != 0)
                {
                    rg.Font.ForeColor = ColorToRGB(System.Drawing.Color.Black);
                    rg.Font.BackColor = 16777215;
                }
                System.Collections.IEnumerator oEnum = oSQLEditorRegex.Matches(sCurrentLine).GetEnumerator();
                while (oEnum.MoveNext())
                {
                    System.Text.RegularExpressions.Match oMatch = (System.Text.RegularExpressions.Match)oEnum.Current;
                    rg.SetRange(offset + oMatch.Index, offset + oMatch.Index + oMatch.Length);
                    rg.Font.BackColor = 16777215;
                    rg.Font.ForeColor = ColorToRGB(System.Drawing.Color.Blue);
                }
            }
        }
 
 
Bon je ne suis encore satisfait, car avec un gros fichier à traiter, il me faut bien 5 à 10 secondes
Par Romagny13
Ecrire un commentaire - Voir les 0 commentaires - Recommander
DragDrop TreeView
 
la treeview doit avoir sa propriété AllowDrop réglée à true 
 
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
 
namespace NET2CsGenObjects.UI
{
    public partial class UCHierarchy : UserControl
    {
  
       TreeNode oTreeNodeBase;
        public UCHierarchy()
        {
            InitializeComponent();
            oTreeNodeBase = new TreeNode();
        }
 
 
        private void UCHierarchy_Load(object sender, EventArgs e)
        {
            TreeNode ParentNode1;
            TreeNode ParentNode2;
            ParentNode1 = treeView1.Nodes.Add("tv1");
            {
                ParentNode1.Nodes.Add("tv1FirstChild");
                ParentNode1.Nodes.Add("tv1SecondChild");
                ParentNode1.Nodes.Add("tv1ThirdChild");
                ParentNode1.Nodes.Add("tv1FourthChild");
                ParentNode1.Expand();
            }
            ParentNode2 = treeView1.Nodes.Add("tv2");
            {
                ParentNode2.Nodes.Add("tv2FirstChild");
                ParentNode2.Nodes.Add("tv2SecondChild");
                ParentNode2.Expand();
            }
        }
   
        // 1
        private void treeView1_DragEnter(object sender, DragEventArgs e)
        {
            e.Effect = DragDropEffects.Move;
            Point pt = treeView1.PointToClient(new Point(e.X, e.Y));
            TreeNode targetNode = treeView1.GetNodeAt(pt);
 
            oTreeNodeBase = targetNode;
        }
 
        // 2
        private void treeView1_ItemDrag(object sender, ItemDragEventArgs e)
        {
            DoDragDrop(e.Item, DragDropEffects.Move);
        }
 
        // 3
        private void treeView1_DragDrop(object sender, DragEventArgs e)
        {
            Point pt = treeView1.PointToClient(new Point(e.X, e.Y));
            TreeNode targetNode = treeView1.GetNodeAt(pt);
            string sText = oTreeNodeBase.Text;
 
 
            // suppression
            treeView1.Nodes.Remove(oTreeNodeBase);
            // ajout
            targetNode.Nodes.Add(sText);
 
          
        }
 
   
    }
}
 
Par Romagny13
Ecrire un commentaire - Voir les 0 commentaires - Recommander
Créer un blog sur over-blog.com - Contact - C.G.U. - Rémunération en droits d'auteur - Signaler un abus