Friday, November 20, 2009

Hardware Interfacing C#, Serial Port Communication with Hankshake / Flow Control in C#



In this post I will describe how can we use System.IO.Ports class to listen data coming from external hardware devices, In my next post I will describe how to send data to external devices via serial port or USB.

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 ComPortListener
{
    public partial class Form1 : Form
    {

       
      //Creating newSerial Port Object
        private SerialPort port = new SerialPort();
      // String container for data
        List<String> messages= new List<String>();
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
             try
            {
                /*
                  GUI oprations, getting data from GUI and setting it into SerialPort object
                  */   
                button2.Enabled = true;
                button1.Enabled = false;

                  // Setting Form GUI values into SerialPort object    
                port.PortName = TxtPortName.Text.ToString();
                port.BaudRate = Convert.ToInt16(TxtbaudRate.Text.ToString());
                port.Parity = (Parity)ComboParity.SelectedIndex;
                port.DataBits = Convert.ToInt16(TxtDataBits.Text.ToString());
                port.StopBits = (StopBits)(ComboStopBits.SelectedIndex);
                 
                  //Setting flow control or handshake
                port.Handshake = (Handshake)(comboFlowControl.SelectedIndex);
                port.Open();
               
            }
            catch (Exception ex)
            {
         MessageBox.Show("Port Already open or some other error preventing opening             port");
                button2.Enabled = false;
                button1.Enabled = true;
            }
        }
        private void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
           
            string dataReceived =port.ReadExisting();
            ListBoxInComingData.Items.Add(dataReceived);
        
        }
        void processHeader(String dataReceive)
        {
            RecID = dataReceive.Substring(29, 15).Trim();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            button2.Enabled = false;
            ComboParity.SelectedIndex = 1;
            ComboStopBits.SelectedIndex = 1;
            comboFlowControl.SelectedIndex = 0;
            ListBox.CheckForIllegalCrossThreadCalls = false;
            port.DataReceived += new  SerialDataReceivedEventHandler(port_DataReceived);

        }

        private void button2_Click(object sender, EventArgs e)
        {
            port.Close();
           
            button1.Enabled = true;
            button2.Enabled = false;
        }
    

    }
}


Download Code Here(Password:"asadyousufi.blogspot.com") 
Direct Download Link

Thursday, November 12, 2009

A Complete C# Example LINQ DataTable Query - Group Aggregation

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.IO;
using System.Data;
using System.Data.OleDb;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {

            DataTable table = new DataTable();
            table.Columns.Add("Id", typeof(int));
            table.Columns.Add("Value", typeof(decimal));
            table.Rows.Add(123, 4.0M);
            table.Rows.Add(123, 5.0M);
            table.Rows.Add(234, 1.0M);
            table.Rows.Add(345, 2.0M);
            table.Rows.Add(345, 3.0M);

           
            var query = from row in table.AsEnumerable()
                        group row by new
                        {
                            Id = row.Field<Int32>("Id")
                           
                        } into grp
                      
                        select new
                        {
                            Key = grp.Key,
                           
                          
                            SumValue = grp.Sum(r => r.Field<decimal>("Value")),
                           
                        };

            foreach (var grp in query)
            {
                Console.WriteLine("{0}\t{1}", grp.Key, grp.SumValue);

            }
            Console.ReadLine();
        }

    }
}

LINQ DataTable Query - Group Aggregation

var  query = from  row in  dtInvoice.AsEnumerable()
    group  row by   new  { InvNo =  row.Field< string >( "InvNo" ),
    EmpUNID = row.Field< decimal >( "EmployeeUNID" )} into  grp                        
    orderby  grp.Key.InvNo
        select new
        {                           
            Key =  grp.Key,  
            InvNo = grp.Key.InvNo,
            EmpID = grp.Key.EmpUNID,                                                           
            TotalCost = grp.Sum(r => r.Field< decimal >( "TotalCost" )),
            TotalRev = grp.Sum(r => r.Field< decimal >( "TotalRev" ))
        };

Thursday, November 5, 2009

Join, Intersec, Expect options on Data Table / Dataset using LINQ


/*
1. Querying DataTable using Linq 
    Here i am going to explain how you can use linq to get data from DataTable.
    You need to use AsEnumerable() method of DataTable object to query datatable using linq.
*/
//Example :  
DataTable dt = new DataTable();

dt.Columns.Add("ID");
dt.Columns.Add("Name");
DataRow dr = dt.NewRow();
dr["ID"] = "1";
dr["Name"] = "Test1";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr["ID"] = "2";
dr["Name"] = "Test2";
dt.Rows.Add(dr);
var result = from user in dt.AsEnumerable()
                     where user.Field<string>("ID") == "1"
                     select user;
/*
2. Join Two DataTable using Linq.
     Example : Here i take two datatables.
*/
        DataTable dt = new DataTable();
        dt.Columns.Add("ID");
        dt.Columns.Add("Name");
        DataRow dr = dt.NewRow();
        dr["ID"] = "1";
        dr["Name"] = "Test1";
        dt.Rows.Add(dr);
        dr = dt.NewRow();
        dr["ID"] = "2";
        dr["Name"] = "Test2";
        dt.Rows.Add(dr);
        DataTable dt1 = new DataTable();
        dt1.Columns.Add("ID");
        dt1.Columns.Add("Product");
        dr = dt1.NewRow();
        dr["ID"] = "1";
        dr["Product"] = "Test-Product";
        dt1.Rows.Add(dr);
//Linq Query:

            var c = from p in dt.AsEnumerable()
            join d in dt1.AsEnumerable() on p.Field<string>("ID") equals d.Field<string>("ID")
            select new { ID = p.Field<string>("ID"), Name = p.Field<string>("Name"), Product = d.Field<string>("Product") };
/*
3. Except and Intersect operation between two DataTable using Linq .
*/
        DataTable dt = new DataTable();
        dt.Columns.Add("ID");
        dt.Columns.Add("Name");
        DataRow dr = dt.NewRow();
        dr["ID"] = "1";
        dr["Name"] = "Test1";
        dt.Rows.Add(dr);
        dr = dt.NewRow();
        dr["ID"] = "2";
        dr["Name"] = "Test2";
        dt.Rows.Add(dr);
        DataTable dt1 = new DataTable();
        dt1.Columns.Add("ID");
        dt1.Columns.Add("Name");
        dr = dt1.NewRow();
        dr["ID"] = "1";
        dr["Name"] = "Test1";
        dt1.Rows.Add(dr);
        var  exceptresult = dt.AsEnumerable().Except(dt1.AsEnumerable(), System.Data.DataRowComparer.Default);
         var intersectresult  = dt.AsEnumerable().Intersect(dt1.AsEnumerable(), System.Data.DataRowComparer.Default);
/*
For both of above operation you need to specify DataRowComparer . System.Data.DataRowComparer is a static sealed class and its static property Default contain comparer reference.  You must have to specify comparer for this operation on Reference datatype.
*/


Tuesday, October 27, 2009

Simple Delegate example in C#


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DelegateExample
{
    public class Program
    {
      
        public delegate int Calculate(int a,int b);
        static void Main(string[] args)
        {
            myClass objMC;
            objMC = new myClass();
            // Creating objects / instances of delegate and assigning them methods of myClass
            Calculate add = new Calculate(objMC.add);
            Calculate sub = new Calculate(objMC.sub);

            // Calling myclass methods via delegate
            Console.WriteLine("2  + 3 =" + add(2, 3));
            Console.WriteLine("10  - 3 =" + sub(10, 3));
            Console.ReadLine();

  

        }
    }

    public class myClass
    {
        public myClass()
        {
        }
        public int add(int n1, int n2)
        {
            return n1 + n2;
        }
        public int sub(int n1, int n2)
        {
            return n1 - n2;
        }
    }
   
}

Monday, October 19, 2009

Using Enum in C#


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
    class Program
    {
        public enum BillType { OPD, IPD, STORE }
        static void Main(string[] args)
        {
            generateInvloce(BillType.IPD);
        }
        public static bool generateInvloce(BillType billType)
        {
            switch (billType)
            {
                case BillType.IPD:
                    Console.WriteLine((int)BillType.IPD);
                    break;
                case BillType.OPD:
                    Console.WriteLine(BillType.OPD.ToString());
                    break;
                case BillType.STORE:
                    Console.WriteLine(BillType.STORE.ToString());
                    break;
                default:
                    break;
            }
            Console.ReadKey();
            return true;
        }
    }
}

C# CSV to Table and Table to CSV converter




using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;
using System.Data;

///
/// Summary description for CSVTools
///
namespace Tools
{
    public class CSVTools
    {
        public CSVTools()
        {
            //
            // TODO: Add constructor logic here
            //
        }

        static void ExportTableToCsvFile(DataTable table, bool printHeaders, String fileName)
        {
            StringBuilder sb = new StringBuilder();
            StreamWriter CSVFile = new StreamWriter(fileName);

            if (printHeaders)
            {
                //write the headers.
                for (int colCount = 0;
                     colCount < table.Columns.Count; colCount++)
                {
                    sb.Append(table.Columns[colCount].ColumnName);
                    if (colCount != table.Columns.Count - 1)
                    {
                        sb.Append(",");
                    }
                    else
                    {
                        sb.AppendLine();
                    }
                }
            }

            // Write all the rows.
            for (int rowCount = 0;
                 rowCount < table.Rows.Count; rowCount++)
            {
                for (int colCount = 0;
                     colCount < table.Columns.Count; colCount++)
                {
                    sb.Append(table.Rows[rowCount][colCount]);
                    if (colCount != table.Columns.Count - 1)
                    {
                        sb.Append(",");
                    }
                }
                if (rowCount != table.Rows.Count - 1)
                {
                    sb.AppendLine();
                }
            }
            CSVFile.Write(sb.ToString());
            CSVFile.Close();
            //return sb.ToString();
        }

        public static DataTable csvToDataTable(string file, bool isRowOneHeader)
        {

            DataTable csvDataTable = new DataTable();

            //no try/catch - add these in yourselfs or let exception happen
            String[] csvData = File.ReadAllLines(HttpContext.Current.Server.MapPath(file));

            //if no data in file ‘manually’ throw an exception
            if (csvData.Length == 0)
            {
                throw new Exception("CSV File Appears to be Empty");
            }

            String[] headings = csvData[0].Split(',');
            int index = 0; //will be zero or one depending on isRowOneHeader

            if (isRowOneHeader) //if first record lists headers
            {
                index = 1; //so we won’t take headings as data

                //for each heading
                for (int i = 0; i < headings.Length; i++)
                {
                    //replace spaces with underscores for column names
                    headings[i] = headings[i].Replace(" ", "_");

                    //add a column for each heading
                    csvDataTable.Columns.Add(headings[i], typeof(string));
                }
            }
            else //if no headers just go for col1, col2 etc.
            {
                for (int i = 0; i < headings.Length; i++)
                {
                    //create arbitary column names
                    csvDataTable.Columns.Add("col" + (i + 1).ToString(), typeof(string));
                }
            }

            //populate the DataTable
            for (int i = index; i < csvData.Length; i++)
            {
                //create new rows
                DataRow row = csvDataTable.NewRow();

                for (int j = 0; j < headings.Length; j++)
                {
                    //fill them

                    row[j] = csvData[i].Split(',')[j];
                }

                //add rows to over DataTable
                csvDataTable.Rows.Add(row);
            }

            //return the CSV DataTable
            return csvDataTable;

        }

    }

}




Followers

Search This Blog