Click here to Skip to main content
15,922,309 members
Please Sign up or sign in to vote.
4.00/5 (2 votes)
See more:
hi,

am developing project on handheld system. now am using two c# applications just for testing whether they are sending /receiving data through serial port.

1st application is on COM5-->port ,first ,1st application will send excel data row by row ,when one row is received by 2nd application that should send $ machID # back to first application.
Here machid is in exceldata whatever it is received.

second thing is : i need to load excel data from 2nd apllication to 1st application.in that case
1st application should read in correct formet and save in excel sheet.

here my question is:upto first thing am somewhat ok, coming to second thing where i need to write the code in 1st application.is it in serialPortDatareceived event or in some where


1st application code is
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 Excel=Microsoft.Office.Interop.Excel;
using System.IO;
using System.Threading;
using System.IO.Ports;



namespace Hand_Held_Data_Transporter
{
    public partial class Form1 : Form
    {
        int[] stream_buffer;
        String final = null;
        String machId = null, custId = null, name = null, totalBal = null, paid = null, lastPaid = null, due = null;
        String inputdata;
    
        public Form1()
        {
            InitializeComponent();
            progressBar1.Enabled = false;
            progressBar2.Enabled = false;
            

          //  serialPort1.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(serialPort1_DataReceived);
           
        }



        private void Browse_Click(object sender, EventArgs e)
        {

            OpenFileDialog fdlg = new OpenFileDialog();
            fdlg.Filter = "All Files(*.*)|*.*";
            if (fdlg.ShowDialog() == DialogResult.OK)
            {


                textBox1.Text = fdlg.FileName;
                File.ReadAllText(textBox1.Text);

            }
        }

       



        private void Upload_Click(object sender, EventArgs e)
        {

           // StringBuilder sb = new StringBuilder();
  

            Excel.Application xlApp = new Excel.Application();
            Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(textBox1.Text, 0, true, 5, "", "", true, Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
            Excel._Worksheet xlWorksheet = (Excel._Worksheet)xlWorkbook.Sheets[1];
            Excel.Range xlRange = xlWorksheet.UsedRange;

            int rowCount = xlRange.Rows.Count;
            int colCount = xlRange.Columns.Count;
            progressBar1.Visible = true;
            

            int k = 100 / rowCount;

            for (int i = 2; i <= rowCount; i++)
            {

               
                for (int j = 1; j <= colCount; j++)
                {

                    if (j == 1)
                     machId = xlRange.Cells[i, j].Value.ToString();
                 

                        //upload1 = xlRange.Cells[i, j].Value.ToString();
                    if (j == 2)
                        custId = xlRange.Cells[i, j].Value.ToString();
                   
                  
                    if (j == 3)
                        name = xlRange.Cells[i, j].Value.ToString();
                
                    if (j == 4)
                        totalBal= xlRange.Cells[i, j].Value.ToString();
                    
                     if (j == 5)
                        paid = xlRange.Cells[i, j].Value.ToString();

                     if (j == 6)
                         lastPaid = xlRange.Cells[i, j].Value.ToString("dd/MM/yyyy");
                    //MessageBox.Show("lastpaid:"+lastPaid);
                  
                    if (j == 7)
                       due = xlRange.Cells[i, j].Value.ToString();


                    final = "$ POST," + machId + "," + custId + "," + name + "," + totalBal + "," + paid + "," + lastPaid + "," + due + " # ";


                }

                if (serialPort1.IsOpen)
                {
                  if(machId.Length<=5 && custId.Length<=10 && name.Length<=15 && totalBal.Length<=7 && paid.Length<=7 && lastPaid.Length<=14 && due.Length<=7 )
                  serialPort1.Write(final);
                    

            }     serialPort1.DataReceived += new SerialDataReceivedEventHandler(serialPort1_DataReceived);

              // MessageBox.Show(final);
                if (progressBar1.Value < 100)
                {
                    Thread.Sleep(100);
                    progressBar1.Value += k;
                }


            }
            progressBar1.Value = 100;

        }

        private void Form1_Load(object sender, EventArgs e)
        {
            progressBar1.Visible = false;
            progressBar2.Visible = false;
           serialPort1.Open();

           string[] ArrayComPortsNames = null;
           int index = -1;
           string ComPortName = null;

           ArrayComPortsNames = SerialPort.GetPortNames();
           do
           {
               index += 1;
               comboBox1.Items.Add(ArrayComPortsNames[index]);
           }

           while (!((ArrayComPortsNames[index] == ComPortName)
                         || (index == ArrayComPortsNames.GetUpperBound(0))));
           Array.Sort(ArrayComPortsNames);

           //want to get first out
           if (index == ArrayComPortsNames.GetUpperBound(0))
           {
               ComPortName = ArrayComPortsNames[0];
           }
           comboBox1.Text = ArrayComPortsNames[0];

          
          

         
        }

        private void Download_Click(object sender, EventArgs e)
        {
                    Excel.Application xlApp = default(Excel.Application);
            Excel.Workbook xlWorkBook = default(Excel.Workbook);
            Excel.Worksheet xlWorkSheet = default(Excel.Worksheet);
            serialPort1.DataReceived += new SerialDataReceivedEventHandler(serialPort1_DataReceived);
            string fName = @"C:\STL\Download\Download_" + DateTime.Now.ToString("dd MMM YY HH mm").Trim() + ".xls ";
            try
            {
           
                object misValue = System.Reflection.Missing.Value;
                xlApp = new Excel.Application();
                xlWorkBook = xlApp.Workbooks.Add(misValue);
                xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
                xlWorkSheet.Cells[1, 1] = "Name";
                xlWorkSheet.Cells[1, 2] = "ID Number";
                xlWorkSheet.Cells[1, 3] = "Installment";
                xlWorkSheet.Cells[1, 4] = "Paid Amount";
                xlWorkSheet.Cells[1, 5] = "Due Amount";

                xlWorkSheet.Cells[1, 1].Interior.ColorIndex = 39;
                xlWorkSheet.Cells[1, 2].Interior.ColorIndex = 39;
                xlWorkSheet.Cells[1, 3].Interior.ColorIndex = 39;
                xlWorkSheet.Cells[1, 4].Interior.ColorIndex = 39;
                xlWorkSheet.Cells[1, 5].Interior.ColorIndex = 39;

               // serialPort1.Open();
               // String s = "$GET,Chsum#";
               // if (serialPort1.IsOpen)
              //  {
                  //  serialPort1.WriteLine(s);
                    
                  // String s1= serialPort1.ReadLine();
                  // MessageBox.Show(s1);
               // }


                xlWorkBook.SaveAs(fName, Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
                xlWorkBook.Close(true, misValue, misValue);
                xlApp.Quit();
                releaseObject(xlWorkSheet);
                releaseObject(xlWorkBook);
                releaseObject(xlApp);
            }
            finally
            {
                if (xlApp != null)
                    releaseObject(xlApp);
                if (xlWorkBook != null)
                    releaseObject(xlWorkBook);
                if (xlWorkSheet != null)
                    releaseObject(xlWorkSheet);
            }
            if (System.IO.File.Exists(fName))
            {
                if (MessageBox.Show("Would you like to open the excel file?", this.Text, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    try
                    {
                        System.Diagnostics.Process.Start(fName);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("Error opening the excel file." + Environment.NewLine +
                          ex.Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
            

            }
        private void releaseObject(object obj)
        {
            try
            {
                System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
                obj = null;
            }
            catch (Exception ex)
            {
                obj = null;
                MessageBox.Show("Unable to release the Object " + ex.ToString());
            }
            finally
            {
                GC.Collect();
            }
        }

      private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
            try
            {
               
                inputdata = serialPort1.ReadLine();
               // MessageBox.Show("data received");
                MessageBox.Show("value is:" +inputdata);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }


            //this method will execute when buffer is full
          /*  stream_buffer[0] = serialPort1.ReadByte();   //read 1st byte
            stream_buffer[1] = serialPort1.ReadByte();   //read another byte and so on
            stream_buffer[2] = serialPort1.ReadByte();
            stream_buffer[3] = serialPort1.ReadByte();
            stream_buffer[4] = serialPort1.ReadByte();
            stream_buffer[5] = serialPort1.ReadByte();
            stream_buffer[6] = serialPort1.ReadByte();

             StreamWriter MyStreamWriter = new StreamWriter(@"c:\Testing.txt, true");
             for (int i = 0; i < 7;i++ )
                 MyStreamWriter.Write(stream_buffer[i]);

            MyStreamWriter.Flush();

            MyStreamWriter.Close();


            for (int j = 0; j < 7; j++)
                textBox1.Text = Convert.ToString(stream_buffer[j]);*/



        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            MessageBox.Show("Do you want to close this Application");
            serialPort1.Close();
        }

        

       

       
        }
    }


and 2nd application is

:
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;
using System.Threading;
using System.IO;

namespace handheld_Responce
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            serialPort1.Open();
            serialPort1.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(serialPort1_DataReceived);
     
       
        }

      
        private void Form1_Load(object sender, EventArgs e)
        {




        }

        private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
           
                if (serialPort1.IsOpen)
                {
                    String RecievedData;
                    RecievedData = serialPort1.ReadExisting();
                    if (!(RecievedData == ""))
                    {
                        //textBox2.Text += RecievedData;
                        textBox2.Invoke((MethodInvoker)delegate { textBox2.Text += RecievedData; });
                    }
                    Thread.Sleep(100);
                    serialPort1.WriteLine("$M121,0#");
            }
            
        }

        private void browse_Click(object sender, EventArgs e)
        {
            OpenFileDialog fdlg = new OpenFileDialog();
            fdlg.Filter = "All Files(*.*)|*.*";
            if (fdlg.ShowDialog() == DialogResult.OK)
            {


                textBox1.Text = fdlg.FileName;
                File.ReadAllText(textBox1.Text);

            }
        }

        private void button1_Click(object sender, EventArgs e)
        {

        }
    }
}
Posted

1 solution

 
Share this answer
 
Comments
Member 10263519 14-Dec-13 1:55am    
ok but i need in second thing . from 2nd application to 1st application . where can i write
Member 10263519 14-Dec-13 2:33am    
plz anybody help me.........

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900