Overblog
Suivre ce blog Administration + Créer mon blog

Présentation

  • : Romagny13 - Du .NET,du pur .NET
  • : Cycle de progression Faire (quelque chose qui marche) -> comprendre ce que l’on fait/comment cela marche -> pousser plus loin les notions
  • Contact

Recherche

Articles RÉCents

9 mars 2014 7 09 /03 /mars /2014 00:46

1 – Task

         public async Task<List<Client>> GetAllAsync()
         {
             List<Client> clients = new List<Client>();
             using (SqlConnection connection = new SqlConnection(@"Data Source=.\SQLEXPRESS;Initial Catalog=dbDemo;Integrated Security=SSPI;"))
             {
                 await connection.OpenAsync();
 
                 using (SqlCommand command = connection.CreateCommand())
                 {
                     command.CommandText = "SELECT [Id],[Name],[Email],[CategoryId] FROM [dbo].[Client]";
                     using (SqlDataReader reader = await command.ExecuteReaderAsync())
                     {
                         while (await reader.ReadAsync())
                         {
                             Client client = new Client();
                             client.ClientID = reader["Id"] == DBNull.Value ? default(int) : int.Parse(reader["Id"].ToString());
                             client.ClientName = reader["Name"] == DBNull.Value ? default(string) : reader["Name"].ToString();
                             client.Email = reader["Email"] == DBNull.Value ? default(string) : reader["Email"].ToString();
                             client.CategoryID = reader["CategoryId"] == DBNull.Value ? default(int) : int.Parse(reader["CategoryId"].ToString());
                             clients.Add(client);
 
                         }
                     }
                 }
             }
             return clients;
         }

 

 Ne pas oublier async
        private async void button2_Click(object sender, EventArgs e)
        {
            IClientService<Client> clientService = new ClientService();
            List<Client> clients= await clientService.GetAllAsync();
 
            dataGridView1.DataSource = clients;
        }

 

2- WaitCallback

public class ClientService :IService

    {

        private SynchronizationContext synchronizationContext = SynchronizationContext.Current ?? new SynchronizationContext();

 

        public virtual bool GetAllAsync(Action<OperationResult<List<Client>>> callback)

        {

            // Le résultat comprenant l'objet ou l'erreur

            OperationResult<List<Client>> response = new OperationResult<List<Client>>();

 

            WaitCallback waitCallBack = param =>

            {

                try

                {

                    response.Result = GetAll();

                }

                catch(Exception ex)

                {

                    response.Error = ex;

                }

                finally { synchronizationContext.Post(d => callback((OperationResult<List<Client>>)d), response); }

            };

            return ThreadPool.QueueUserWorkItem(waitCallBack);

        }

 

        public List<Client> GetAll()

        {

            List<Client> result = new List<Client>();

            DbProviderFactory factory = DbProviderFactories.GetFactory("System.Data.SqlClient");

            using (DbConnection connection = factory.CreateConnection())

            {

                connection.ConnectionString = @"Data Source=.\SQLEXPRESS;Initial Catalog=dbDemo;Integrated Security=SSPI;";

                connection.Open();

 

                using (DbCommand command = connection.CreateCommand())

                {

                    command.CommandText = "select TOP 1000 Id,Name,Email from [dbo].[Client]";

                    using (DbDataReader reader = command.ExecuteReader())

                    {

                        while (reader.Read())

                        {

                            Client client = new Client();

                            client.ClientID = Convert.ToInt32(reader["Id"]);

                            client.ClientFullName = reader["Name"].ToString();

                            client.Email = reader["Email"].ToString();

 

                            result.Add(client);

                        }

                    }

                }

            }

            return result;

        }

}

 

OperationResult(contenant soit le résultat soit l'erreur)

  public interface IOperationResult

    {

        Exception Error { get; }

    }

    public interface IOperationResult<T> : IOperationResult

    {

        T Result { get; }

    }

    public class OperationResult : IOperationResult

    {

        public Exception Error

        {

            get;

            protected internal set;

        }

    }

    public class OperationResult<T> : OperationResult, IOperationResult<T>

    {

        public T Result

        {

            get;

            protected internal set;

        }

    }

 Client , une classe métier implémentant INotifyPropertyChanged

«Context »

public class Context :ObservedBase

    {

        private ObservableCollection<Client> _clients;

 

        public ObservableCollection<Client> Clients

        {

            get { return _clients; }

            set

            {

                _clients = value;

                RaisePropertyChanged<ObservableCollection<Client>>(() => Clients);

            }

        }

        private IService service;

 

        public Context()

        {

            this.service = new ClientService();

            service.GetAllAsync(Callback);

        }

 

        private void Callback(OperationResult<List<Client>> response)

        {

            Clients =new ObservableCollection<Client>(response.Result);

        }

}

 

Ou Méthode anonyme    

public Context()

        {

            this.service = new ClientService();

            service.GetAllAsync(

                (response) =>

                {

                    Clients =new ObservableCollection<Client>(response.Result);

                });

        }

 

 Il suffit ensuite de définir le datacontext et binder les controls sur les propriétés de Clients   

 

3 Ressources  

Task-based Asynchronous Pattern

await

Asynchronous
Partager cet article
Repost0
10 février 2014 1 10 /02 /février /2014 17:07

Exemple : on essaie d’insérer deux nouvelles lignes dans la table Catégories de la base Northwind La  deuxième requête ne renseignant pas CategoryName (qui n’accepte pas les valeurs nulles), l’insertion sera annulée

public void DoTransaction()

        {

            using (SqlConnection connection = new SqlConnection(@"Data Source=.\SQLEXPRESS;Initial Catalog=Northwind;Integrated Security=SSPI;"))

            {

                connection.Open();

                SqlTransaction transaction = connection.BeginTransaction();

                SqlCommand command = connection.CreateCommand();

                command.Transaction = transaction;

                try

                {

                    //      

                    command.CommandText = "INSERT INTO [dbo].[Categories]([CategoryName],[Description]) VALUES('Cakes','Good cakes .');";

                    command.ExecuteNonQuery();

                   

                    // CategoryName n'acceptant pas de valeur nulle ....  

                    command.CommandText = "INSERT INTO [dbo].[Categories]([Description]) VALUES('Category unnamed .');";

                    command.ExecuteNonQuery();

 

                    transaction.Commit();

                }

                catch (Exception Ex)

                {

                    transaction.Rollback();

                    MessageBox.Show(Ex.Message);

                }

            }

        }

 

transaction1.png 

 

IsolationLevel http://msdn.microsoft.com/fr-fr/library/system.transactions.isolationlevel(v=vs.110).aspx

 

Exemple IsolationLevel.Serializable : les données peuvent être lues mais pas modifiées pendant la transaction

SqlTransaction transaction = connection.BeginTransaction(IsolationLevel.Serializable);

 

 

TransactionScope

http://msdn.microsoft.com/fr-fr/library/system.transactions.transactionscope(v=vs.110).aspx

 

Partager cet article
Repost0
4 février 2014 2 04 /02 /février /2014 01:33

1-Préparation

 

MySQL 5.6.16

http://dev.mysql.com/downloads/file.php?id=450945  

Normalement le connector .NET est compris dans le package (sinon http://dev.mysql.com/downloads/connector/net/6.8.html)

 

Il faut ajouter une référence dans son projet à MySql.Data.dll (située dans le répertoire C:\Program Files (x86)\MySQL\Connector NET 6.8.3\Assemblies\v4.5)

 

Ajouter using MySql.Data.MySqlClient;  en haut de ses pages

   

MySqlConnection, MySqlCommand, MySqlDataReader, etc. : Se connecter à une base MySQL est relativement simple .De la même manière qu’avec une base Access ou SQL Server on va utiliser une connexion, des commandes, des datareaders et utiliser les méthodes ExecuteNonQuery(),ExecuteScalar() ,...Il est également possible d’exécuter des procédures stockées .

 

La documentation sur le connector .NET http://dev.mysql.com/doc/connector-net/en/index.html

 

Le PL/SQL diffère un peu du T-SQL.Il faudra par exemple préférer les apostrophes aux crochets.

 

Exemple de création de base de données simple . Deux tables (Client et Category) ayant une clé primaire auto incrémentée , et une relation (un client a une catégorie) et une procédure stockée

CREATE TABLE `dbdemo`.`client` (

  `Id` INT NOT NULL AUTO_INCREMENT,

  `Name` VARCHAR(45) NOT NULL,

  `Email` VARCHAR(100) NULL,

  `CategoryId` INT NOT NULL,

  PRIMARY KEY (`Id`));

 

CREATE TABLE `dbdemo`.`category` (

  `Id` INT NOT NULL AUTO_INCREMENT,

  `Name` VARCHAR(50) NOT NULL,

  PRIMARY KEY (`Id`));

 

ALTER TABLE `dbdemo`.`client`

ADD INDEX `CategoryId_idx` (`CategoryId` ASC);

ALTER TABLE `dbdemo`.`client`

ADD CONSTRAINT `CategoryId`

  FOREIGN KEY (`CategoryId`)

  REFERENCES `dbdemo`.`category` (`Id`)

  ON DELETE NO ACTION

  ON UPDATE NO ACTION;

 

CREATE PROCEDURE `GetAllClients`()

BEGIN

SELECT `Id`, `Name`, `Email`, `CategoryId`

from `client`;

End                    

 

2-La chaine de connexion

Une aide si besoin http://www.connectionstrings.com/mysql-connector-net-mysqlconnection/

Il est possible de la stocker dans le fichier de configuration

<connectionStrings>

        <add name="dbConnectionString" connectionString="server=localhost;user id=root;password=monmotdepasse;database=dbdemo" providerName="MySql.Data.MySqlClient" />          

    </connectionStrings>

 

3- Exécuter une requête /récupérer une liste   

               public List<Client> GetClients()

        {

            List<Client> clients = new List<Client>();

            using (MySqlConnection connection = Sql.Instance.GetConnection())

            {

                using (MySqlCommand command = connection.CreateCommand())

                {

                    command.CommandType = CommandType.Text;

                    command.CommandText = "SELECT `Id`, `Name`, `Email`, `CategoryId` FROM `client`;";

                    using (MySqlDataReader reader = command.ExecuteReader())

                    {

                        while (reader.Read())

                        {

                            Client client = new Client();

                            client.Id = reader["Id"] == DBNull.Value ? default(int) : int.Parse(reader["Id"].ToString());

                            client.Name = reader["Name"] == DBNull.Value ? default(string) : reader["Name"].ToString();

                            client.Email = reader["Email"] == DBNull.Value ? default(string) : reader["Email"].ToString();

                            client.CategoryId = reader["CategoryId"] == DBNull.Value ? default(int) : int.Parse(reader["CategoryId"].ToString());

                            clients.Add(client);

 

                        }

                    }

                }

            }

            return clients;

        }

 

4 – Procédure stockée

Un autre exemple cette fois avec une procédure stockée .Je récupère le client par sa clé primaire

                         public Client GetClient(int id)

             {

                    Client client = new Client();

                    using(MySqlConnection connection = Sql.Instance.GetConnection())

                    {

                           using (MySqlCommand command = connection.CreateCommand())

                           {

                                  command.CommandType = CommandType.StoredProcedure;

                                  command.CommandText = "GetClient";

                                  command.Parameters.Add(new MySqlParameter("parid", id));

 

                                  using (MySqlDataReader reader = command.ExecuteReader())

                                  {

                                        while (reader.Read())

                                        {

                                               client.Id = reader["Id"] == DBNull.Value ? default(int) : int.Parse(reader["Id"].ToString());

                                               client.Name = reader["Name"] == DBNull.Value ? default(string) : reader["Name"].ToString();

                                               client.Email = reader["Email"] == DBNull.Value ? default(string) : reader["Email"].ToString();

                                               client.CategoryId = reader["CategoryId"] == DBNull.Value ? default(int) : int.Parse(reader["CategoryId"].ToString());

                                        }

                                  }

                           }

                    }

                    return client;

             }

 

Je passe ici le paramètre parid, portant le même nom que le paramètre de la procédure stockée

CREATE PROCEDURE `GetClient`(parid int)

BEGIN

SELECT `Id`, `Name`, `Email`, `CategoryId`

from `client`

where `Id`=parid;

 

5-Récupérer la clé auto incrémentée après un ajout

command.CommandText = "SELECT LAST_INSERT_ID()";

result = Convert.ToInt32(command.ExecuteScalar());

 

6 – ADO.NET Entity Framework et MySQL

Rien de plus facile

dbdemoEntities mySqlDemoEntities = new dbdemoEntities();

// affichage d'une liste

DbSet<client> clients = mySqlDemoEntities.client;

dataGridView1.DataSource = clients.ToList();

        

// OU

// utilisation de la procédure stockée GetAllClients()

dataGridView1.DataSource = mySqlDemoEntities.GetAllClients();

 

Partager cet article
Repost0
3 février 2014 1 03 /02 /février /2014 19:05

Avec DbProvider aucun changement au niveau du code de la présentation, de même pour le fichier pour de configuration

public class ClientDAO : DbBase          

{          

             public List<Client> GetClients()          

             {

                 List<Client> clients = new List<Client>();

            using (DbConnection connection = Sql.Instance.GetConnection())

            {

 

                using (DbCommand command = connection.CreateCommand())

                {

                    command.CommandType = CommandType.Text;

                    command.CommandText = "SELECT [Id],[Name],[Email],[CategoryId] FROM [Client]";

                    using (DbDataReader reader = command.ExecuteReader())

                    {

                        while (reader.Read())

                        {

                            Client client = new Client();

                            client.Id = reader["Id"] == DBNull.Value ? default(int) : int.Parse(reader["Id"].ToString());

                            client.Name = reader["Name"] == DBNull.Value ? default(string) : reader["Name"].ToString();

                            client.Email = reader["Email"] == DBNull.Value ? default(string) : reader["Email"].ToString();

                            client.CategoryId = reader["CategoryId"] == DBNull.Value ? default(int) : int.Parse(reader["CategoryId"].ToString());

                            clients.Add(client);

                        }

                    }

                }

            }

                    return clients;

              }

              public Client GetClient(int id)

              {

                   Client client = new Client();

                   using (DbConnection connection = Sql.Instance.GetConnection())

              {

 

                using (DbCommand command = connection.CreateCommand())

                {

                    command.CommandType = CommandType.Text;

                    command.CommandText = "SELECT [Id],[Name],[Email],[CategoryId] FROM [Client] WHERE [Id]=parid";

                    command.Parameters.Add(CreateParameter(command, "@id", id));

 

                    using (DbDataReader reader = command.ExecuteReader())

                    {

                        while (reader.Read())

                        {

                            client.Id = reader["Id"] == DBNull.Value ? default(int) : int.Parse(reader["Id"].ToString());

                            client.Name = reader["Name"] == DBNull.Value ? default(string) : reader["Name"].ToString();

                            client.Email = reader["Email"] == DBNull.Value ? default(string) : reader["Email"].ToString();

                            client.CategoryId = reader["CategoryId"] == DBNull.Value ? default(int) : int.Parse(reader["CategoryId"].ToString());

                        }

                    }

                }

            }

                    return client;

               }

              public int AddClient(Client client)

              {

                  int result = 0;

            using (DbConnection connection = Sql.Instance.GetConnection())

            {

                using (DbCommand command = connection.CreateCommand())

                {

                    command.CommandType = CommandType.Text;

                    command.CommandText = "INSERT INTO [Client]([Name],[Email],[CategoryId]) VALUES(?,?,?);";

                    command.Parameters.Add(CreateParameter(command, "@name", client.Name));

                    command.Parameters.Add(CreateParameter(command, "@email", client.Email));

                    command.Parameters.Add(CreateParameter(command, "@categoryId", client.CategoryId));

                    command.ExecuteNonQuery();

 

                    command.CommandText = "SELECT @@IDENTITY";

                    result = Convert.ToInt32(command.ExecuteScalar());

                }

            }

 

                    return result;

               }

               public int UpdateClient(Client client)

               {

                 int result = 0;

            using (DbConnection connection = Sql.Instance.GetConnection())

            {

                using (DbCommand command = connection.CreateCommand())

                {

                    command.CommandType = CommandType.Text;

                    command.CommandText = "UPDATE [Client] SET [Name]=?,[Email]=?,[CategoryId]=? WHERE [Id]=?";

                    command.Parameters.Add(CreateParameter(command, "@name", client.Name));

                    command.Parameters.Add(CreateParameter(command, "@email", client.Email));

                    command.Parameters.Add(CreateParameter(command, "@categoryId", client.CategoryId));

                    command.Parameters.Add(CreateParameter(command, "@categoryId", client.Id));

                    result = command.ExecuteNonQuery();

                }

            }

 

                    return result;

             }

             public int DeleteClient(Client client)

             {

                 int result = 0;

            using (DbConnection connection = Sql.Instance.GetConnection())

            {

 

                using (DbCommand command = connection.CreateCommand())

                {

                    command.CommandType = CommandType.Text;

                    command.CommandText = "DELETE FROM [Client] WHERE [Id]=?";

                    command.Parameters.Add(CreateParameter(command, "@id", client.Id));

                    result = command.ExecuteNonQuery();

                }

            }

 

                    return result;

                }

       }

Je fais hériter d’une classe DbBase au lieu de réécrire la méthode dans toutes les classes DAO

public class DbBase

{

           protected DbParameter CreateParameter(DbCommand command, string parameterName, object value)

            {

                    DbParameter parameter = command.CreateParameter();

                    parameter.ParameterName = parameterName;

                    parameter.Value = value;

                    return parameter;

             }          

}          

 

Le singleton

public class Sql

       {

             private static Sql _instance;

             private DbConnection connection;

             private static object locker = new object();

             public ConnectionStringSettings ConnectionStringSettings { get; set; }

 

             private Sql() { }

 

             public static Sql Instance

             {

                    get

                    {

                           lock (locker)

                           {

                                  if (_instance == null)

                                  _instance = new Sql();

                           }

                           return _instance;

                    }

             }

 

             public DbConnection GetConnection()

             {

                    if (connection == null)

                    {

                           ConnectionStringSettings = ConfigurationManager.ConnectionStrings["dbConnectionString"];

                           DbProviderFactory factory = DbProviderFactories.GetFactory(ConnectionStringSettings.ProviderName);

                           connection = factory.CreateConnection();                    

                    }

            connection.ConnectionString = ConnectionStringSettings.ConnectionString;

                    if (connection.State == ConnectionState.Closed)

                           connection.Open();

                    return connection;

 

             }                        

       }

 

Partager cet article
Repost0
3 février 2014 1 03 /02 /février /2014 19:04

 

Le singleton utilisé pour la connexion

public class Sql

       {

             private static Sql _instance;

             private OleDbConnection connection;

             private static object locker = new object();

             public ConnectionStringSettings ConnectionStringSettings { get; set; }

 

             private Sql() { }

 

             public static Sql Instance

             {

                    get

                    {

                           lock (locker)

                           {

                                  if (_instance == null)

                                  _instance = new Sql();

                           }

                           return _instance;

                    }

             }

 

             public OleDbConnection GetConnection()

             {

                    if (connection == null)

                    {

                           ConnectionStringSettings = ConfigurationManager.ConnectionStrings["dbConnectionString"];

                           connection = new OleDbConnection();

                    }

            connection.ConnectionString = ConnectionStringSettings.ConnectionString;

                    if (connection.State == ConnectionState.Closed)

                           connection.Open();

                    return connection;

 

             }

                                 

       }

 

La classique classe Client

public class Client          

{

        public int Id { get; set; }

        public string Name { get; set; }

        public string Email { get; set; }

        public int CategoryId { get; set; }

}

 

 

Partager cet article
Repost0
3 février 2014 1 03 /02 /février /2014 18:44

Dans le fichier de configuration

  <connectionStrings>

    <add name="dbConnectionString" providerName="System.Data.OleDb" connectionString="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\romagny\Documents\metier\sources\DbDemo.mdb;" />

  </connectionStrings>

 

Pour bien faire il faudrait utiliser une BindingList(avec un projet windows forms) et implémenter INotifyPropertyChanged

BindingList<Client> bindingClients = new BindingList<Client>(clients);

 

GetAll

MainForm

        private ClientDAO clientDAO;

        private List<Client> clients;

 

        private void MainForm_Load(object sender, EventArgs e)

        {

            clientDAO = new ClientDAO();

            clients = clientDAO.GetClients();

            dataGridView1.DataSource = clients;

        }

 

ClientDAO

public List<Client> GetClients()

        {

            List<Client> clients = new List<Client>();

            using (OleDbConnection connection = Sql.Instance.GetConnection())

            {

                using (OleDbCommand command = connection.CreateCommand())

                {

                    command.CommandType = CommandType.Text;

                    command.CommandText = "SELECT [Id],[Name],[Email],[CategoryId] FROM [Client]";

                    using (OleDbDataReader reader = command.ExecuteReader())

                    {

                        while (reader.Read())

                        {

                            Client client = new Client();

                            client.Id = reader["Id"] == DBNull.Value ? default(int) : int.Parse(reader["Id"].ToString());

                            client.Name = reader["Name"] == DBNull.Value ? default(string) : reader["Name"].ToString();

                            client.Email = reader["Email"] == DBNull.Value ? default(string) : reader["Email"].ToString();

                            client.CategoryId = reader["CategoryId"] == DBNull.Value ? default(int) : int.Parse(reader["CategoryId"].ToString());

                            clients.Add(client);

                        }

                    }

                }

            }

            return clients;

        }

 

GetOne

MainForm

// récupération du client par la clé primaire

Client client = clientDAO.GetClient(12);

ClientDAO

public Client GetClient(int id)

        {

            Client client = new Client();

            using (OleDbConnection connection = Sql.Instance.GetConnection())

            {

                using (OleDbCommand command = connection.CreateCommand())

                {

                    command.CommandType = CommandType.Text;

                    command.CommandText = "SELECT [Id],[Name],[Email],[CategoryId] FROM [Client] WHERE [Id]=?";

                    command.Parameters.Add(new OleDbParameter("@id", id));

 

                    using (OleDbDataReader reader = command.ExecuteReader())

                    {

                        while (reader.Read())

                        {

                            client.Id = reader["Id"] == DBNull.Value ? default(int) : int.Parse(reader["Id"].ToString());

                            client.Name = reader["Name"] == DBNull.Value ? default(string) : reader["Name"].ToString();

                            client.Email = reader["Email"] == DBNull.Value ? default(string) : reader["Email"].ToString();

                            client.CategoryId = reader["CategoryId"] == DBNull.Value ? default(int) : int.Parse(reader["CategoryId"].ToString());

                        }

                    }

                }

            }

 

            return client;

        }

 

Add

MainForm

// création d'un client

Client client = new Client() { Name="Prenium Patrick",Email="preniumpat54@msn.com",CategoryId=2};

 

// ajout

clientDAO.AddClient(client);

ClientDAO

public int AddClient(Client client)

        {

            int result = 0;

            using (OleDbConnection connection = Sql.Instance.GetConnection())

            {

 

                using (OleDbCommand command = connection.CreateCommand())

                {

                    command.CommandType = CommandType.Text;

                    command.CommandText = "INSERT INTO [Client]([Name],[Email],[CategoryId]) VALUES(?,?,?);";

                    command.Parameters.Add(new OleDbParameter("@name", client.Name));

                    command.Parameters.Add(new OleDbParameter("@email", client.Email));

                    command.Parameters.Add(new OleDbParameter("@categoryId", client.CategoryId));

                    command.ExecuteNonQuery();

 

                    command.CommandText = "SELECT @@IDENTITY";

                    result = Convert.ToInt32(command.ExecuteScalar());

                }

            }

            return result;

        }

 

Update

MainForm

// récupérer le client à modifier

Client client = clients.Where(c=> c.Id ==14).First();

client.Email = "preniumpatrick54@voila.fr";

 

// mise à jour

clientDAO.UpdateClient(client);

ClientDAO

public int UpdateClient(Client client)

        {

            int result = 0;

            using (OleDbConnection connection = Sql.Instance.GetConnection())

            {

 

                using (OleDbCommand command = connection.CreateCommand())

                {

                    command.CommandType = CommandType.Text;

                    command.CommandText = "UPDATE [Client] SET [Name]=?,[Email]=?,[CategoryId]=? WHERE [Id]=?";

                    command.Parameters.Add(new OleDbParameter("@name", client.Name));

                    command.Parameters.Add(new OleDbParameter("@email", client.Email));

                    command.Parameters.Add(new OleDbParameter("@categoryId", client.CategoryId));

                    command.Parameters.Add(new OleDbParameter("@Id", client.Id));

                    result = command.ExecuteNonQuery();

                }

            }

            return result;

        }

 

Delete

MainForm

// récupérer le client à supprimer, exemple le client sélectionné dans le datagridView(propiétés du datagridView MultiSelect à false et SelectionMode à FullRowSelect)

Client client = (Client)dataGridView1.SelectedRows[0].DataBoundItem;

 

clientDAO.DeleteClient(client);

 

ClientDAO

public int DeleteClient(Client client)

             {

                    int result = 0;

            using (OleDbConnection connection = Sql.Instance.GetConnection())

            {

                using (OleDbCommand command = connection.CreateCommand())

                {

                    command.CommandType = CommandType.Text;

                    command.CommandText = "DELETE FROM [Client] WHERE [Id]=?";

                    command.Parameters.Add(new OleDbParameter("@id", client.Id));

                    result = command.ExecuteNonQuery();

                }

            }

 

                    return result;

             }

 

Partager cet article
Repost0
3 février 2014 1 03 /02 /février /2014 17:35

1-Types de données

ACCESS

SQL

C#

Numérique

Long

int

Texte court

VarChar

string

Texte long

LongText

string

Date/Heure

DateTime

DateTime

Monétaire

Currency

double

Oui/Non

Bit

bool

Objet OLE

LongBinary

byte[]

Lien hypertexte

LongText

string

 

A cela on peut ajouter Short, Single, Double, Decimal, Byte, VarBinary

Exemple :

On crée une table Product avec Access   

  access1.png

La même table en SQL

Create table [Product]

(

[ProductId] LONG NOT NULL IDENTITY (1,1) PRIMARY KEY,

[ProductName] VarChar(50) NOT NULL,

[Description] LongText NULL,

[UnitsInStock] Long NOT NULL,

[RequiredDate] DateTime NOT NULL,

[UnitPrice] Currency NULL,

[Discontinued] Bit NULL,

[Picture] LongBinary NULL,

[ProduitUrl] LongText NULL

)

 

La classe C# (simplifiée) correspondante

public class Product

{

        public int ProductId { get; set; }

        public string ProductName { get; set; }

        public string Description { get; set; }

        public int UnitsInStock { get; set; }

        public DateTime RequiredDate { get; set; }

        public double UnitPrice { get; set; }

        public bool Discontinued { get; set; }

        public byte[] Picture { get; set; }

        public string ProduitUrl { get; set; }

}

 

2-Syntaxe des requêtes et procédures

 

Le nom des paramètres (OleDbParameter  et DbParameter) est « inutile », c’est plus l’ordre d’ajout des paramètres à la commande qui compte .

On peut aussi bien écrire

command.CommandText = "INSERT INTO [Client]([Name],[Email],[CategoryId]) VALUES(@name,@mail,@categoryId)";

command.Parameters.Add(new OleDbParameter("@name", client.Name));

command.Parameters.Add(new OleDbParameter("@email", client.Email));

command.Parameters.Add(new OleDbParameter("@categoryId", client.CategoryId));

que

command.CommandText = "INSERT INTO [Client]([Name],[Email],[CategoryId]) VALUES(?,?,?)";

command.Parameters.Add(new OleDbParameter("?", client.Name));

command.Parameters.Add(new OleDbParameter("?", client.Email));

command.Parameters.Add(new OleDbParameter("?", client.CategoryId));

 

C’est tellement vrai que l’on peut même donner un nom de paramètre ne correspondant pas du tout à celui utilisé dans la requête.

  • Pour les vues/procédures il faut respecter une écriture.

Ajouter un préfixe « par » devant les paramètres peut éviter les conflits  avec les noms de colonnes.

Ne pas utiliser non plus @ pour les paramètres si on ne veut pas avoir de mauvaises surprises :o

Exemple

CREATE PROCEDURE [InsertCategory](parName VarChar(100))

AS

INSERT INTO [Category]([Name] )

VALUES(parName)

GO

 

3- Récupérer @@IDENTITY

Il est possible de récupérer la clé auto incrémentée ajoutée, mais on ne peut pas ajouter la requête avec l’insert comme c’est le cas avec SQL Server.

command.CommandText = "Select @@IDENTITY";

result = Convert.ToInt32(command.ExecuteScalar());

 

Partager cet article
Repost0
2 février 2014 7 02 /02 /février /2014 01:39

binding5-copie-2.png

 

 

On crée un constructeur dans la form détail qui reçoit le bindingSource de la form de départ

FListClient

public partial class FListClient : Form

    {

        public FListClient()

        {

            InitializeComponent();

        }

 

        DataSet dataSet;

        SqlConnection connection;

        SqlDataAdapter clientAdapter;

        BindingSource bindingSource;

 

        private void FListClient_Load(object sender, EventArgs e)

        {

            dataSet = new DataSet();

            connection = new SqlConnection(@"Data Source=.\SQLEXPRESS;Initial Catalog=dbDemo;Integrated Security=True");

 

            clientAdapter = new SqlDataAdapter("Select * from [dbo].[Client]", connection);

            dataSet.Tables.Add(new DataTable("Client"));

            clientAdapter.Fill(dataSet.Tables["Client"]);

 

            bindingSource = new BindingSource();

            bindingSource.DataSource = dataSet;

            bindingSource.DataMember = "Client";

            bindingSource.BindingComplete += bindingSource_BindingComplete;

 

            clientDataGridView.DataSource = bindingSource;

        }

 

        void bindingSource_BindingComplete(object sender, BindingCompleteEventArgs e)

        {

            if (e.BindingCompleteContext == BindingCompleteContext.DataSourceUpdate && e.Exception == null)

                e.Binding.BindingManagerBase.EndCurrentEdit();

        }

 

        private void button1_Click(object sender, EventArgs e)

        {

            FDetailClient detailForm = new FDetailClient(bindingSource);

            detailForm.Show();

        }

 

    }

 

FDetailClient

public partial class FDetailClient : Form

    {

        private BindingSource bindingSource;

 

        public FDetailClient()

        {

            InitializeComponent();

        }

 

        private BindingSource bindingSourceFDetail;

 

        public FDetailClient(BindingSource bindingSourceFList)

        {

            InitializeComponent();

 

            bindingSourceFDetail = bindingSourceFList;

 

            lblClientId.DataBindings.Add("Text", bindingSourceFDetail, "Id",true);

            txtClientName.DataBindings.Add("Text", bindingSourceFDetail, "Name");

            txtClientEmail.DataBindings.Add("Text", bindingSourceFDetail, "Email");

 

 

 

            // on remplit la comboBox avec la liste des catégories                     

            DataSet dataSet = new DataSet();

            SqlDataAdapter categoryAdapter = new SqlDataAdapter("Select * from [dbo].[Category]", new SqlConnection(@"Data Source=.\SQLEXPRESS;Initial Catalog=dbDemo;Integrated Security=True"));

            dataSet.Tables.Add(new DataTable("Category"));

            categoryAdapter.Fill(dataSet.Tables["Category"]);

            cboClientCategory.DataSource = dataSet;

            cboClientCategory.DisplayMember = "Category.Name";

            cboClientCategory.ValueMember = "Category.Id";

            cboClientCategory.DataBindings.Add("SelectedValue", bindingSourceFDetail, "CategoryId");

 

       

        }    

}

         


 

 

 

  Astuces  

Supprimer des colonnes du DatagridView

// supprimer des colonnes inutiles du DatagridView

 clientDataGridView.Columns.Remove("Id");

 clientDataGridView.Columns.Remove("CategoryId");

 

 

Ajouter une DataGridViewComboBoxColumn liée aux données

binding6.png  

 

DataGridViewComboBoxColumn cboClientCategory = new DataGridViewComboBoxColumn();

          

// 1 on crée un BindingSource avec pour DataSource la table Category

BindingSource categoryBindingSource = new BindingSource();

categoryBindingSource.DataSource = dataSet;

categoryBindingSource.DataMember = "Category";

 

// 2 on affecte le bindingSource à la DataGridViewComboBoxColumn

cboClientCategory.DataSource = categoryBindingSource;

// lié à la propriété/clé étrangère CategoryId de la table Client

cboClientCategory.DataPropertyName = "CategoryId";

// on affiche la propriété Name de la table Category dans la DataGridViewComboBoxColumn

cboClientCategory.DisplayMember = "Name";

// ValueMemeber est réglé sur la clé primaire Id de la table Category

cboClientCategory.ValueMember = "Id";

clientDataGridView.Columns.Add(cboClientCategory);                    

 

Partager cet article
Repost0
2 février 2014 7 02 /02 /février /2014 01:38

Dans l'exemple j'affiche la liste des clients de la catégorie sélectionnée

 

  binding3.png

 

1-Avec un DataSet Typé

  private dbDemoDataSet dataSet = new dbDemoDataSet();

 

        private void Form1_Load(object sender, EventArgs e)

        {

            SqlConnection connection = new SqlConnection(@"Data Source=.\SQLEXPRESS;Initial Catalog=dbDemo;Integrated Security=True");

 

            // on remplit la table Category du dataset

            CategoryTableAdapter categoryAdapter = new CategoryTableAdapter();

            categoryAdapter.Connection = connection;

            categoryAdapter.Fill(dataSet.Category);

 

            // on remplit la table client du dataset

            ClientTableAdapter clientAdapter = new ClientTableAdapter();

            clientAdapter.Connection = connection;

            clientAdapter.Fill(dataSet.Client);

 

            categoryDataGridView.DataSource = dataSet;

            categoryDataGridView.DataMember = "Category";

 

            // on affiche dans le premier datagridView la liste des catégories

            // et dans le second datagridView la liste des clients de la catégorie sélectionnée dans le premier datagridView

            // syntaxe Tablemere.Nomrelation

            clientDataGridView.DataSource = dataSet;

            clientDataGridView.DataMember = "Category.Client_Category";

        }

 

binding1.png  

 

2-Avec un DataSet

private DataSet dataSet = new DataSet();

 

        private void Form2_Load(object sender, EventArgs e)

        {           

            SqlConnection connection = new SqlConnection(@"Data Source=.\SQLEXPRESS;Initial Catalog=dbDemo;Integrated Security=True");

 

            SqlDataAdapter categoryAdapter = new SqlDataAdapter("Select * from [dbo].[Category]",connection);

            // on crée et ajoute les DataTables au DataSet

            dataSet.Tables.Add(new DataTable("Category"));

            categoryAdapter.Fill(dataSet.Tables["Category"]);

 

 

            SqlDataAdapter clientAdapter = new SqlDataAdapter("Select * from [dbo].[Client]", connection);

            dataSet.Tables.Add(new DataTable("Client"));

            clientAdapter.Fill(dataSet.Tables["Client"]);

 

            // On crée la relation

            dataSet.Relations.Add("Client_Category", dataSet.Tables["Category"].Columns["Id"], dataSet.Tables["Client"].Columns["CategoryId"]);

 

            categoryDataGridView.DataSource = dataSet;

            categoryDataGridView.DataMember = "Category";

 

            clientDataGridView.DataSource = dataSet;

            clientDataGridView.DataMember = "Category.Client_Category";

 

        }

 

Partager cet article
Repost0
2 février 2014 7 02 /02 /février /2014 01:38

1– DataBinding ComboBox, label/textBox

  binding3a

ComboBox

// On peut également afficher la liste des catégories dans une comboBox par exemple

// en changeant la catégorie sélectionnée le binding se fera automatiquement et la liste des clients pour cette catégorie sera listée dans le datagridView

cboCategories.DataSource = dataSet;

cboCategories.DisplayMember = "Category.Name";

cboCategories.ValueMember = "Category.Id";

 

Remplir une comboBox avec la liste des noms de catégories et sélectionner la catégorie du Client,sachant que ce client a une clé étrangère Categoryd(int)

// on remplit la comboBox avec la liste des catégories .On affiche la propriété Name, et en SelectedValue on réupérera l'Id

cboClientCategory.DataSource = dataSet;

cboClientCategory.DisplayMember = "Category.Name";

cboClientCategory.ValueMember = "Category.Id";

// à partir de la clé étrangère CategoryId de la table Client(elle est de type int) on sélectionne la catégorie

cboClientCategory.DataBindings.Add("SelectedValue", dataSet, "Client.CategoryId");          

 

Label

//on peut aussi afficher dans un label : la propriété Text le nom de la table Category du dataSet

lblCategoryId.DataBindings.Add("Text",dataSet,"Category.Name");

// autre exemple on affiche l'id de la catégorie correspondant la valeur courante de la comboBox(affichera "2" par exemple)

lblCategoryId.DataBindings.Add("Text", cboCategories, "SelectedValue");                    

 

2-Afficher le détail

binding4-copie-1.png  

J’utilise un BindingSource qui permet de mettre à jour facilement l’UI .

Avec un DataSet typé il est possible d’appeler la méthode AcceptChanges() pour valider les changements dans le dataSet et mettre à jour l’UI .

La méthode HasChanges() du dataSet permet de savoir si des modifications ont été apportées dans celui-ci

Il existe également le control BindingNavigator qui peut être utile pour la navigation et les actions de base .

   SqlConnection connection = new SqlConnection(@"Data Source=.\SQLEXPRESS;Initial Catalog=dbDemo;Integrated Security=True");

        DataSet dataSet = new DataSet();

        SqlDataAdapter categoryAdapter;

        SqlDataAdapter clientAdapter;

        BindingSource clientBindingSource;

 

        private void FDetail_Load(object sender, EventArgs e)

        {

 

            categoryAdapter = new SqlDataAdapter("Select * from [dbo].[Category]", connection);

            dataSet.Tables.Add(new DataTable("Category"));

            categoryAdapter.Fill(dataSet.Tables["Category"]);

 

 

            clientAdapter = new SqlDataAdapter("Select * from [dbo].[Client]", connection);

            dataSet.Tables.Add(new DataTable("Client"));

            clientAdapter.Fill(dataSet.Tables["Client"]);

 

            clientBindingSource = new BindingSource();

            clientBindingSource.DataSource = dataSet;

            clientBindingSource.DataMember = "Client";

 

            clientDataGridView.DataSource = clientBindingSource;

 

            lblClientId.DataBindings.Add("Text", clientBindingSource, "Id");

            txtClientName.DataBindings.Add("Text", clientBindingSource, "Name");

            txtClientEmail.DataBindings.Add("Text", clientBindingSource, "Email");

 

            cboClientCategory.DataSource = dataSet;

            cboClientCategory.DisplayMember = "Category.Name";

            cboClientCategory.ValueMember = "Category.Id";

 

            cboClientCategory.DataBindings.Add("SelectedValue", clientBindingSource, "CategoryId");

 

 

Validation et mise à jour de la base

Valider les changements au niveau du dataSet(la base de données n’est pas modifiée ici,seule le dataSet et l’UI est mise à jour)

private void button1_Click(object sender, EventArgs e)

        {

            this.Validate();

            clientBindingSource.EndEdit();

        }

 

Mise à jour de la base (cas on a modifié un client)

  private void UpdateClient()

        {

            try

            {

                clientAdapter.UpdateCommand = new SqlCommand(@"UPDATE [dbo].[Client]

                                                            SET [Name] = @Name, [Email] = @Email, [CategoryId] = @CategoryId

                                                            WHERE Id = @Id", connection);

                clientAdapter.UpdateCommand.CommandType = CommandType.Text;

                clientAdapter.UpdateCommand.Parameters.Add(new SqlParameter("@Name", SqlDbType.Char, 0, ParameterDirection.Input, 0, 0, "Name", DataRowVersion.Current, false, null, "", "", ""));

                clientAdapter.UpdateCommand.Parameters.Add(new SqlParameter("@Email", SqlDbType.Char, 0, ParameterDirection.Input, 0, 0, "Email", DataRowVersion.Current, false, null, "", "", ""));

                clientAdapter.UpdateCommand.Parameters.Add(new SqlParameter("@CategoryId", SqlDbType.Int, 0, ParameterDirection.Input, 0, 0, "CategoryId", DataRowVersion.Current, false, null, "", "", ""));

                clientAdapter.UpdateCommand.Parameters.Add(new SqlParameter("@Id", SqlDbType.Int, 4, ParameterDirection.Input, 0, 0, "Id", DataRowVersion.Current, false, null, "", "", ""));

 

 

                clientAdapter.Update(dataSet.Tables["Client"]);

            }

            catch (DBConcurrencyException)

            {

                MessageBox.Show("Impossible de mettre à jour.");

            }

        }

}

Et donc il suffit d’appeler la méthode pour valider les changements

private void button1_Click(object sender, EventArgs e)

        {

            this.Validate();

            clientBindingSource.EndEdit();

            UpdateClient() ;

        }

 

Il est possible de s’abonner aux événements  des DataTables tel que RowChanged,ColumnChanged,etc.

dataSet.Tables["Client"].ColumnChanged += FDetail_ColumnChanged;

 

  void FDetail_ColumnChanged(object sender, DataColumnChangeEventArgs e)

        {

          

            // peut permettre de vérifier si la saisie est correcte

            if (string.IsNullOrEmpty(e.ProposedValue.ToString().Trim()) && e.Column.ColumnName=="Name")

            {

                // on peut par exemple utiliser un errorProvider pour une textBox

                errorProvider1.SetError(txtClientName, "Nom nécessaire");

            }

        }

 

Rejeter les changements

La méthode RejectChanges() du dataSet annule les changements de valeur

CancelEdit() du bindingSource permet de mettre à jour l’UI

 

  private void btnCancel_Click(object sender, EventArgs e)

        {

            dataSet.RejectChanges();

            clientBindingSource.CancelEdit();

          

        }

 

Partager cet article
Repost0