Affichage des articles dont le libellé est c#. Afficher tous les articles
Affichage des articles dont le libellé est c#. Afficher tous les articles

mardi 31 juillet 2012

Integrating a SQLite database in your c# application

Hello all,
I needed in one of my project to store data in a database, So as I only know Mysql I directly jump on it.
But my big problem was that I have to put all of the files in one package the thing that Mysql won't allow me to do, cause Mysql is a server database witch means that we can only connect to it and not integrate it in our application like this example . (correct me if I'm wrong please)
So I searched more and I found this little piece of jewellery System.data.sql.dll witch is a SQL based database direct link library that could be simply integrated in your C# application.
These are some tools I used to create and manage my database:
Some useful tutoriels:
using the sqlite function and send SQL queries. 
Gives a very useful class to manage data with dataGridView, inserting , updating and all those stuff
I added a method that can create data table:

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SQLite;
using System.Windows.Forms;

class SQLiteDatabase
{
    String dbConnection;

    /// <summary>
    ///     Default Constructor for SQLiteDatabase Class.
    /// </summary>
    public SQLiteDatabase()
    {
        dbConnection = "Data Source=REMOTES.s3db";
    }

    /// <summary>
    ///     Single Param Constructor for specifying the DB file.
    /// </summary>
    /// <param name="inputFile">The File containing the DB</param>
    public SQLiteDatabase(String inputFile)
    {
        dbConnection = String.Format("Data Source={0}", inputFile);
    }

    /// <summary>
    ///     Single Param Constructor for specifying advanced connection options.
    /// </summary>
    /// <param name="connectionOpts">A dictionary containing all desired options and their values</param>
    public SQLiteDatabase(Dictionary<String, String> connectionOpts)
    {
        String str = "";
        foreach (KeyValuePair<String, String> row in connectionOpts)
        {
            str += String.Format("{0}={1}; ", row.Key, row.Value);
        }
        str = str.Trim().Substring(0, str.Length - 1);
        dbConnection = str;
    }

    /// <summary>
    ///     Allows the programmer to run a query against the Database.
    /// </summary>
    /// <param name="sql">The SQL to run</param>
    /// <returns>A DataTable containing the result set.</returns>
    public DataTable GetDataTable(string sql)
    {
        DataTable dt = new DataTable();
        try
        {
            SQLiteConnection cnn = new SQLiteConnection(dbConnection);
            cnn.Open();
            SQLiteCommand mycommand = new SQLiteCommand(cnn);
            mycommand.CommandText = sql;
            SQLiteDataReader reader = mycommand.ExecuteReader();
            dt.Load(reader);
            reader.Close();
            cnn.Close();
        }
        catch (Exception e)
        {
            throw new Exception(e.Message);
        }
        return dt;
    }

    /// <summary>
    ///     Allows the programmer to interact with the database for purposes other than a query.
    /// </summary>
    /// <param name="sql">The SQL to be run.</param>
    /// <returns>An Integer containing the number of rows updated.</returns>
    public int ExecuteNonQuery(string sql)
    {
        SQLiteConnection cnn = new SQLiteConnection(dbConnection);
        cnn.Open();
        SQLiteCommand mycommand = new SQLiteCommand(cnn);
        mycommand.CommandText = sql;
        int rowsUpdated = mycommand.ExecuteNonQuery();
        cnn.Close();
        return rowsUpdated;
    }

    /// <summary>
    ///     Allows the programmer to retrieve single items from the DB.
    /// </summary>
    /// <param name="sql">The query to run.</param>
    /// <returns>A string.</returns>
    public string ExecuteScalar(string sql)
    {
        SQLiteConnection cnn = new SQLiteConnection(dbConnection);
        cnn.Open();
        SQLiteCommand mycommand = new SQLiteCommand(cnn);
        mycommand.CommandText = sql;
        object value = mycommand.ExecuteScalar();
        cnn.Close();
        if (value != null)
        {
            return value.ToString();
        }
        return "";
    }

    /// <summary>
    ///     Allows the programmer to easily update rows in the DB.
    /// </summary>
    /// <param name="tableName">The table to update.</param>
    /// <param name="data">A dictionary containing Column names and their new values.</param>
    /// <param name="where">The where clause for the update statement.</param>
    /// <returns>A boolean true or false to signify success or failure.</returns>
    public bool Update(String tableName, Dictionary<String, String> data, String where)
    {
        String vals = "";
        Boolean returnCode = true;
        if (data.Count >= 1)
        {
            foreach (KeyValuePair<String, String> val in data)
            {
                vals += String.Format(" {0} = '{1}',", val.Key.ToString(), val.Value.ToString());
            }
            vals = vals.Substring(0, vals.Length - 1);
        }
        try
        {
            this.ExecuteNonQuery(String.Format("update {0} set {1} where {2};", tableName, vals, where));
        }
        catch
        {
            returnCode = false;
        }
        return returnCode;
    }

    /// <summary>
    ///     Allows the programmer to easily delete rows from the DB.
    /// </summary>
    /// <param name="tableName">The table from which to delete.</param>
    /// <param name="where">The where clause for the delete.</param>
    /// <returns>A boolean true or false to signify success or failure.</returns>
    public bool Delete(String tableName, String where)
    {
        Boolean returnCode = true;
        try
        {
            this.ExecuteNonQuery(String.Format("delete from {0} where {1};", tableName, where));
        }
        catch (Exception fail)
        {
            MessageBox.Show(fail.Message);
            returnCode = false;
        }
        return returnCode;
    }

    /// <summary>
    ///     Allows the programmer to easily insert into the DB
    /// </summary>
    /// <param name="tableName">The table into which we insert the data.</param>
    /// <param name="data">A dictionary containing the column names and data for the insert.</param>
    /// <returns>A boolean true or false to signify success or failure.</returns>
    public bool Insert(String tableName, Dictionary<String, String> data)
    {
        String columns = "";
        String values = "";
        Boolean returnCode = true;
        foreach (KeyValuePair<String, String> val in data)
        {
            columns += String.Format(" {0},", val.Key.ToString());
            values += String.Format(" '{0}',", val.Value);
        }
        columns = columns.Substring(0, columns.Length - 1);
        values = values.Substring(0, values.Length - 1);
        try
        {
            this.ExecuteNonQuery(String.Format("insert into {0}({1}) values({2});", tableName, columns, values));
        }
        catch (Exception fail)
        {
            MessageBox.Show(fail.Message);
            returnCode = false;
        }
        return returnCode;
    }

    /// <summary>
    ///     Allows the programmer to easily delete all data from the DB.
    /// </summary>
    /// <returns>A boolean true or false to signify success or failure.</returns>
    public bool ClearDB()
    {
        DataTable tables;
        try
        {
            tables = this.GetDataTable("select NAME from SQLITE_MASTER where type='table' order by NAME;");
            foreach (DataRow table in tables.Rows)
            {
                this.ClearTable(table["NAME"].ToString());
            }
            return true;
        }
        catch
        {
            return false;
        }
    }

    /// <summary>
    ///     Allows the user to easily clear all data from a specific table.
    /// </summary>
    /// <param name="table">The name of the table to clear.</param>
    /// <returns>A boolean true or false to signify success or failure.</returns>
    public bool ClearTable(String table)
    {
        try
        {

            this.ExecuteNonQuery(String.Format("delete from {0};", table));
            return true;
        }
        catch
        {
            return false;
        }
    }
    public bool CreateTable(String TableName)
    {
        try
        {
            this.ExecuteNonQuery("CREATE TABLE IF NOT EXISTS " + TableName + " ( id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, name VARCHAR(100) NOT NULL);");
            return true;
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());
            return false;
        }
    }
}






lundi 30 janvier 2012

Reading from a Sony joystick


Well this is all started when I wanted to send data from a joystick to my laptop to control a robot. What seemed to be obvious for me is that I have to use one of the gaming library to interface my joystick.
after a lot of researches I found 2 decent library the XNA framework and the SlimDx library.
I didn't know why but I didn't like these frameworks.
So I thought .. the joystick is an HID device hence I can interface it just like any other HID device
I started with searching HID library fot c#. I found libusbdotnet seemed intresting but lack of documentation. then I found the USBHIDLIBRARY and I work on it.
This library is just amazing not so complex, simple documentation and does the job properly.
Here is my C# code for interfacing the joystick:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using USBHIDDRIVER.USB;
using USBHIDDRIVER.TESTS;
using USBHIDDRIVER.List;
using USBHIDDRIVER;
using System.Threading;

namespace USBWork
{
    public partial class Form1 : Form
    {
        USBHIDDRIVER.USBInterface usb = new USBInterface("vid_0079", "pid_0006");
        byte[] currentread=new byte[1024];

        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            USBHIDDRIVER.USBInterface usb = new USBInterface("vid_0079", "pid_0006");
            if (usb.Connect()) lblcnx.BackColor = Color.Green;
        }

        private void usbEventHandler(object sender, EventArgs args)
        {
            lblreading.BackColor = Color.Green;
            ListWithEvent list = (ListWithEvent)sender;
            byte[] byte_array = (byte[])list[list.Count-1];
            //txtusb.Text = "start!\n";
            for (int i = 0; i < byte_array.Length; i++)
            {
                currentread[i] = byte_array[i];
            }
          
          
         }
       
            private void btnread_Click(object sender, EventArgs e)
            {
                usb.enableUsbBufferEvent(new EventHandler(usbEventHandler));
                usb.startRead();
                timer1.Enabled = true;
            }

            private void Form1_FormClosing(object sender, FormClosingEventArgs e)
            {
                usb.stopRead();
            }

            private void timer1_Tick(object sender, EventArgs e)
            {
                txtusb.Text+= currentread[6].ToString();
                if (currentread[6] == 15) chknone.Checked = true; else chknone.Checked = false;
                if (currentread[6] == 143) chkcercle.Checked = true; else chkcercle.Checked = false;
                if (currentread[6] == 31) chktriangle.Checked = true; else chktriangle.Checked = false;
                if (currentread[6] == 47) chkcarreau.Checked = true; else chkcarreau.Checked = false;
                if (currentread[6] == 79) chkX.Checked = true; else chkX.Checked = false;
            }          
                  
        }      

 }



samedi 21 janvier 2012

A simple example of Gmap.net with c#

This tutorial is specially made for a member in my team Explorer who has the task to locate the position of our robot in a  map.
gmap.net is a great .net framework nonetheless it lacks of documentation.
So what I'm going to do is to show you how to refer gmap.net in your application  and how to locate something in the world map.
So let's get started!

First of all we need to download the binary package which contains all the *.dll that we need.
http://greatmaps.codeplex.com/releases/view/20235#DownloadId=67818
extract the folder in a decent place, say for exemple c:\\projects\
we will need only 2 files:
GMap.NET.Core.dll
GMap.NET.WindowsForms.dll
Now we will add the GMap.NET.WindowsForms.dll to our Visual Studio IDE toolbox.
to do so go to tools-->choose toolbox items

before clicking brows, make sure you selected the ".NET Framework Components"
Select the Gmap.NET.WindowsForms.dll
click Open or "ouvrir" the click ok
now go to your toolbox (view-->toolbox) you should find a new control the "GmapControl".


Next step  is even more simple :))
we need to add a reference to our new library in our projects so go to:
(view-->Solution explorer)
Select the GMap.NET.Core.dll click Ok
Note that the reference are being added to your projects reference,
we can now go back to the design and set our gmap control


Right click on the control and choose "propoerties"
In the properties windows set the Name to "mapexplr"

Finally we can start coding

Add these lines to the using lines
using GMap.NET.WindowsForms;
using GMap.NET;
using GMap.NET.MapProviders;



The Code
namespace WindowsFormsApplication2
{
    public partial class Form1 : Form
    {
        GMapOverlay overlayOne;
        String contry;
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void mapexplr_Load(object sender, EventArgs e)
        {
            //initialisation de notre map
            mapexplr.SetCurrentPositionByKeywords("Tunisia");
            mapexplr.MapProvider = GMapProviders.BingMap;
            mapexplr.MinZoom = 3;
            mapexplr.MaxZoom = 17;
            mapexplr.Zoom = 5;
            mapexplr.Manager.Mode = AccessMode.ServerAndCache;
            //ajout des overlay
            overlayOne = new GMapOverlay(mapexplr, "OverlayOne");
            //ajout de Markers
            overlayOne.Markers.Add(new                                         GMap.NET.WindowsForms.Markers.GMapMarkerGoogleGreen(new PointLatLng(36.657403,10.327148)));
            //ajout de overlay à la map
            mapexplr.Overlays.Add(overlayOne);
        }
    }
}
The final result:



Love you tunisia !
I hope this tutorial was helpful, till the next time don't stop sharing

dimanche 31 juillet 2011

Programme de gestion de stock avec c# et MySql

Bonjour tout le monde,
Je vous présente mon projet qui consiste à un simple programme de gestion de stock qu'il sera mis à jour plusieurs fois dans le future inch'Allah.

Le programme est codé avec c# et la base de donnés est créer avec mysql.
vous devez tout d'abord téléchargerle le pilote connector/net http://dev.mysql.com/downloads/connector/net/5.2.html qui va occupé à la connexion entre l'application c# et la base de donnés MySql.





mercredi 27 juillet 2011

Asservissement vitesse d'un moteur à courant continu

Dans le cadre d'un projet en matière technologie d’acquisition et d'interfaçage j'ai réaliser ce projet qui est mieux expliquer dans la photo en bas.
Schéma synoptique
l'interface:
La carte sur isis:
 PCB sur ARES:

 

Code en c#


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;

namespace WindowsFormsApplication1
{
    using ZedGraph;
    public partial class Form1 : Form
    {
        float temps=0;
        float consigne=0;
        float commande=0;
        float fecartold;
        float fIntegral = 0;
        float fDerive = 0;
        float freponseOld=0;
        byte[] buffer = new byte[8];
        #region partie test pour une foction de transfert numerique        
        float reponse = 0;
        #endregion        
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            CreerGraphique(zedGraphControl1);
        }
        #region  creeer graphique
        private void CreerGraphique(ZedGraphControl zgc)
        {
            GraphPane Pane = zgc.GraphPane;
            PointPairList list1 = new PointPairList();
            PointPairList list2 = new PointPairList();
            PointPairList list3 = new PointPairList();
            LineItem CourbeConsigne = Pane.AddCurve("Consigne", list1, Color.Red);
            LineItem CourbeMesure = Pane.AddCurve("Commande", list2, Color.Black);
            LineItem CourbeCommande = Pane.AddCurve("Mesure", list3, Color.Green);
            Pane.Title.Text = "Simulation en temps réel de la vitesse";
            Pane.XAxis.Title.Text = "Axe X";
            Pane.YAxis.Title.Text = "Axe Y";
            CourbeConsigne.Symbol.Size = 1.0F;
            CourbeConsigne.Line.Width = 2.0F;
            CourbeMesure.Symbol.Size = 1.0F;
            CourbeMesure.Line.Width = 2.0F;
            CourbeCommande.Symbol.Size = 1.0F;
            CourbeCommande.Line.Width = 2.0F;
        }
        #endregion

        #region taswer mte3 lgraph
        private void addDataToGraph(ZedGraphControl zg1, XDate x, double tconsigne,double tcommande, double treponse )
        {
            LineItem curve = zg1.GraphPane.CurveList[0] as LineItem;
            IPointListEdit list = curve.Points as IPointListEdit;
            list.Add(x,tconsigne);
            LineItem curve2 = zg1.GraphPane.CurveList[1] as LineItem;
            IPointListEdit list2 = curve2.Points as IPointListEdit;
            list2.Add(x, tcommande);
            LineItem curve3 = zg1.GraphPane.CurveList[2] as LineItem;
            IPointListEdit list3 = curve3.Points as IPointListEdit;
            list3.Add(x, treponse);            
            zg1.Invalidate();
            zedGraphControl1.AxisChange();
        }
#endregion

    

        private void zedGraphControl1_Load(object sender, EventArgs e)
        {
        }

        private void rdncnvar_CheckedChanged(object sender, EventArgs e)
        {
            if (rdncnvar.Checked==true)
            {
                hscrCons.Value = 0;
                hscrCons.Enabled = true;
                NumConVar.Enabled = true;
            }
            else
            {
                hscrCons.Enabled = false;
                NumConVar.Text = "0";
                NumConVar.Enabled = false;
            }
        }

        private void hscrCons_Scroll(object sender, ScrollEventArgs e)
        {
            NumConVar.Text = hscrCons.Value.ToString();
        }

        private void chkConsBoucleOuverte_CheckedChanged(object sender, EventArgs e)
        {
            if (chkConsBoucleOuverte.Checked == true)
            {
                Régulation.Enabled = false;                
            }
            else
            {
                Régulation.Enabled = true;                
            }
        }

        private void btnOuvrPort_Click(object sender, EventArgs e)
        {
            try
            {
                serialPort1.Open();
                lbCommunication.BackColor = Color.Green;
                lbCommunication.Text = "Connexion établie";
                Consignes.Enabled = true;                
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), "Impossible d'ouvrir le port ");
                
            }
        }

        private void comboCom_SelectedIndexChanged(object sender, EventArgs e)
        {
            serialPort1.PortName = comboCom.Text;
        }

        private void ComboBaude_SelectedIndexChanged(object sender, EventArgs e)
        {
            serialPort1.BaudRate = int.Parse(ComboBaude.Text);
        }

        private void btnFermPort_Click(object sender, EventArgs e)
        {
            timer.Enabled = false;
            serialPort1.Close();
            lbCommunication.BackColor = Color.Red;
            lbCommunication.Text = "Pas de connexion";
            Consignes.Enabled = false;
        }

        private void btnValider_Click(object sender, EventArgs e)
        {
          
            timer.Enabled = true;            
            
        }

        private void timer_Tick(object sender, EventArgs e)
        {
            float inter;
            temps += 0.1F;
            if (rdnEchel.Checked == true)
            {
                float.TryParse(numConEche.Text,out consigne);
            }
            if (rdnRamp.Checked == true)
            {
                if (consigne >= 100) consigne = 100;
                else
                {
                    float.TryParse(NumConRamp.Text, out inter);
                    consigne = inter * temps;
                }                
            }
            if (rdncnvar.Checked == true) //Consigne variable
            {
                float.TryParse(NumConVar.Text,out consigne);
            }            
            float rconsigne = (commande / 100) * 255;
            int iconsigne = (int)rconsigne;
            if (iconsigne>255)
            {
                iconsigne = 255;
            }
            else if(iconsigne<0)
            {
                iconsigne = 0;
            }
            txtMesVit.Text = iconsigne.ToString();
            #region envoi serial
            byte[] wbuffer = new byte[1];
            byte buffe = Convert.ToByte(iconsigne);
            wbuffer[0] = buffe;
            serialPort1.Write(wbuffer, 0, wbuffer.Length);
            #endregion  
            serialPort1.Read(buffer, 0, 1);            
            reponse= BitConverter.ToInt16(buffer, 0);
            reponse = (reponse / 255) * 100;
            if (chkConsBoucleOuverte.Checked == true) commande = consigne;
            else RegulationPID();
            prgbrVitesse.Value = (int)reponse;
            if (commande < 0) commande = 0;
            if (commande > 100) commande = 100;
            txtMesEcar.Text = commande.ToString();    
            addDataToGraph(zedGraphControl1, temps, consigne, commande, reponse);            
            serialPort1.DiscardInBuffer();
            serialPort1.DiscardOutBuffer();
            freponseOld = reponse;  //enregistre la dernière mesure de la reponse
        }
        
        private void button1_Click(object sender, EventArgs e)
        {
            timer.Enabled = false;
        }

        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            if (chkSimul.Checked == true)
            {
                GrpRs232.Enabled = false;
                chkSimul.Text = "End Simulation";
                timer.Enabled = false;
                serialPort1.Close();
                lbCommunication.BackColor = Color.Red;
                lbCommunication.Text = "Pas de connexion";
                Consignes.Enabled = true;
            }
            if (chkSimul.Checked == false)
            {
                GrpRs232.Enabled = true;
                chkSimul.Text = "Start Simulation";
                Consignes.Enabled = false;
            }
        }

        private void RegulationPID()
        {
            float ftermeP = 0;
            float ftermeI = 0;
            float ftermeD = 0;
            float fEcart = consigne-reponse;
            if (rdbTypeIntegral.Checked == true)
            {
                float fI0 = (fEcart + fecartold) / 2f;
                fIntegral+=fI0;
            }
            else fIntegral=0F;

            if (rdbTypeDeriv.Checked == true)
            {
                fDerive = freponseOld - reponse;
            }
            else fDerive = 0f;
           float kp = 0;
           float Ti = 0;
           float Td = 0;
           float.TryParse(txtParaKp.Text.ToString(), out kp);
           float.TryParse(txtParaTi.Text.ToString(), out Ti);
           float.TryParse(txtParaTd.Text.ToString(), out Td);
           ftermeP = fEcart * kp;
           if (Ti > 0.01f)
           ftermeI = fIntegral / Ti;
           ftermeD = Td * fDerive;

           if (rdbTypeProp.Checked==true)//P
           {
               commande = ftermeP;
           }
           else if (rdbTypeIntegral.Checked == true)//PI
           {
               commande = ftermeP + ftermeI;
           }
           else
           {
               commande = ftermeP+ftermeI+ftermeD;
           }
            fecartold=fEcart;
        }

        private void numConEche_TextChanged(object sender, EventArgs e)
        {
            if (this.Text == "1") this.Text = "2";
        }

        private void lbCommunication_Click(object sender, EventArgs e)
        {

        }
    }
}
Code C for PIC
unsigned int reponse=0;
int commande=0;
char txt[4];
void init(){
adc_init();//initialisation du module ANALOGIQUE
uart1_init(9600);//initialisation du module RS232
pwm1_init(12000);
pwm1_set_duty(0);
pwm1_start();
}
void main() {
     init();
     while(1){
        reponse=adc_read(0);
        reponse/=4;
        uart1_write(reponse);
        delay_ms(10);
        if(uart1_data_ready()){
          commande=uart1_read();
          pwm1_set_duty(commande);
        }
     }
}