Click here to Skip to main content
15,891,704 members
Home / Discussions / C#
   

C#

 
QuestionCondition of C#. Pin
Member 113461537-Jun-17 22:11
Member 113461537-Jun-17 22:11 
AnswerRe: Condition of C#. Pin
Richard MacCutchan7-Jun-17 22:39
mveRichard MacCutchan7-Jun-17 22:39 
AnswerRe: Condition of C#. Pin
OriginalGriff7-Jun-17 22:55
mveOriginalGriff7-Jun-17 22:55 
QuestionFetching data from multiple mailboxes Pin
Member 132459727-Jun-17 4:23
Member 132459727-Jun-17 4:23 
AnswerRe: Fetching data from multiple mailboxes Pin
OriginalGriff7-Jun-17 8:06
mveOriginalGriff7-Jun-17 8:06 
AnswerRe: Fetching data from multiple mailboxes Pin
F-ES Sitecore7-Jun-17 22:47
professionalF-ES Sitecore7-Jun-17 22:47 
GeneralRe: Fetching data from multiple mailboxes Pin
Member 113461538-Jun-17 3:52
Member 113461538-Jun-17 3:52 
QuestionMissing data on Windows App form C# Pin
Member 131317266-Jun-17 23:33
Member 131317266-Jun-17 23:33 
Hello,

i am trying to analyze the issue of missing data over my Datagridview in C#.

I am receiving data from Serial port with 5250000 (5,25 Mbps)& Splitting it over datagridview (Datatable). Simultaneously i am saving this data over PC using Binarywriter.

However when i am analysing my dumped data file over pc, i found almost 30% of data is missing between two intervals. My timer Event is 1 milisec & i am updating datagridview in timer tick.

So how i can get contineous stream of data both over datagrid view & write it in file to save over PC?

Possible Error is use of Serialport.BytesToRead method as its blocking type.

SO can anybody tell where exactly i am wrong?

My Code is as below:
C#
<pre>using System;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO.Ports;
using System.IO;
using System.Threading;
using System.Diagnostics;
using System.Text.RegularExpressions;

namespace DataGridView
{
    public partial class DataGridView : Form
    {

        DataTable table = new DataTable("Sniffer Data Logger");
        byte[] buffer = new byte[5 * 1024];

        public DataGridView()
        {
            InitializeComponent();

            //Add Columns in the form
            table.Columns.Add("System Time");        // column to display system time
            table.Columns.Add("Source");             // column to display source i.e addr bus, data bus, reverse addr bus or reset & so on
            table.Columns.Add("T.S Begin");          // column to display beginning of timestamp
            table.Columns.Add("T.S End");            // column to display end of the timestamp
            table.Columns.Add("Duration (uS)");      // Add duration of the Frame
            table.Columns.Add("Length");             // column to dispaly length of the datafield
            table.Columns.Add("Data");               // column to display Data content of the protocol
            table.Columns.Add("CRC");                // CRC Check for frame valiadation
            table.Columns.Add("CRC_PC");             // CRC generated by PC         

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

        /*Load Form1 to show the results*/
        private void Form1_Load(object sender, EventArgs e)
        {

        }

        /*Port Data received event handler*/
        private void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            this.BeginInvoke(new EventHandler(Timer1_Tick));

        }

        /*Byte array to Hex conversion using string builder*/
        private string ByteArrayToHexString(byte[] data)
        {
            StringBuilder sb = new StringBuilder();
            foreach (byte b in data)
                sb.Append(Convert.ToString(b, 16).PadLeft(2, '0').PadRight(3, ' '));
            return sb.ToString().ToUpper().Replace(" ", "");
        }

        /*Update Datagrid View at each timer tick (zb. Timer Tick is 100mSec)*/
        private void Timer1_Tick(object sender, EventArgs e)
        {

                /*Read Data coming from ComPort Byte by Byte &store in the buffer*/
                int Bytes = serialPort1.BytesToRead;                            // Read Bytes coming from the Serial Port with data rate of 5.25 Mbps
                byte[] buffer = new byte[5 * 1024];                             // Store the bytes in buffer of Size 5KByte
                                                                                //Byte[] buffer = new byte[Bytes];                              // Read new coming bytes
                long read = serialPort1.Read(buffer, 0, Bytes);

                /*Binary Writer*/
                BinaryWriter writer = new BinaryWriter(File.Open("c:\\temp\\snifftimetick.dat", FileMode.Append));
                writer.Write(buffer);
                writer.Close();

                /*Check if buffer length is full*/
                if (read == buffer.Length)
                {
                    byte[] newbuffer = new byte[buffer.Length * 2];             // Double the buffer length i.e 5KB x 2 = 10KB
                    Array.Copy(buffer, newbuffer, buffer.Length);               // Copy the previous buffer data in to new buffer
                    newbuffer[read] = (byte)Bytes;                              // Read the new coming bytes from the serial port
                    buffer = newbuffer;                                         // show all data together in buffer
                    read++;

                }
            }

            /*Check if the incoming stream contains preamble "AA"*/
            DataRow row = table.NewRow();                                           // Insert New row in datagridview

            if (ByteArrayToHexString(buffer).Contains("AA"))
            {
                if (ByteArrayToHexString(buffer).StartsWith("AA"))                  // Check if buffer starts with "AA"
                {
                    switch (ByteArrayToHexString(buffer).Substring(6, 2))           // Switch statement to check if substring startswith CMD ID
                    {
                        // Case for "ABUS_L/R"
                        case "11":
                            table.Rows.Add(row);                                                // Add new row

                            row["Source"] = string.Format("{0}", "ABUS_L/R");                   // Insert source name in row
                            row["System Time"] = DateTime.Now.ToString("HH:mm:ss:fff");         // Insert time in row
                                                                                                //row["Source"] = ByteArrayToHexString(buffer).Substring(9, 2);     
                            row["T.S Begin"] = ByteArrayToHexString(buffer).Substring(8, 8);    // Insert TS Begin
                            row["T.S End"] = ByteArrayToHexString(buffer).Substring(16, 8);    // Insert TS End
                            row["Length"] = ByteArrayToHexString(buffer).Substring(24, 2);      // Insert length Field
                            row["Data"] = ByteArrayToHexString(buffer).Substring(26, 2);        // Insert Data field
                            row["CRC"] = ByteArrayToHexString(buffer).Substring(28, 2);         // Compare CRC field with Protocol & validate the information
                            row["CRC_PC"] = crc8.ComputeChecksum(buffer);                       // Compute & compare CRC generated by PC       
                            break;

                        // Case for "ABUS_RK"
                        case "12":
                            table.Rows.Add(row);                                                // Add new row

                            row["Source"] = string.Format("{0}", "ABUS_RK");
                            row["System Time"] = DateTime.Now.ToString("HH:mm:ss:fff");
                            //row["Source"] = ByteArrayToHexString(buffer).Substring(9, 2);

                            row["T.S Begin"] = ByteArrayToHexString(buffer).Substring(8, 8);
                            row["T.S End"] = ByteArrayToHexString(buffer).Substring(16, 8);
                            row["Length"] = ByteArrayToHexString(buffer).Substring(24, 2);
                            row["Data"] = ByteArrayToHexString(buffer).Substring(26, 2);
                            row["CRC"] = ByteArrayToHexString(buffer).Substring(28, 2);
                            row["CRC_PC"] = crc8.ComputeChecksum(buffer);
                            break;

                        // Case for "DataBus"
                        case "13":
                            table.Rows.Add(row);                                                // Add new row

                            row["Source"] = string.Format("{0}", "DataBus");
                            row["System Time"] = DateTime.Now.ToString("HH:mm:ss:ffffff");

                            //row["Source"] = ByteArrayToHexString(buffer).Substring(9, 2);

                            //row["T.S Begin"] = ByteArrayToHexString(buffer).Substring(8, 8);
                            //row["T.S End"] = ByteArrayToHexString(buffer).Substring(16, 8);

                            // Convert Timestamp values to Decimal UInt values
                            string ts1 = ByteArrayToHexString(buffer).Substring(8, 8);              // Assign new string for timestamp begin
                            UInt32 number = Convert.ToUInt32(ts1, 16);                              // convert Hex value to UINT32
                            UInt32 time1 = swap(number);                                            // Big Endian to Little Endian Conversion
                            double tmil1 = ((double)time1 / (double)1000);                          // Time in Mikrosecond
                            string res1_tmil = tmil1.ToString();

                            string ts2 = ByteArrayToHexString(buffer).Substring(16, 8);             // Assign new string for timestamp begin
                            UInt32 number1 = Convert.ToUInt32(ts2, 16);                             // convert Hex value to UINT32
                            UInt32 time2 = swap(number1);                                           // Big Endian to Little Endian Conversion
                            double tmil2 = ((double)time2 / (double)1000);
                            string res2_tmil = tmil2.ToString();

                            row["T.S Begin"] = time1;
                            row["T.S End"] = time2;
                            row["Duration (uS)"] = ((time2 - time1));                               // Calculate the duration of the Frame as per timestamps

                            row["Length"] = ByteArrayToHexString(buffer).Substring(24, 2);

                            // Convert string to integer data for counting the byte information in the string
                            string len = ByteArrayToHexString(buffer).Substring(24, 2);
                            int count = int.Parse(len, System.Globalization.NumberStyles.HexNumber);                            // Get integer value of the substring
                            row["Data"] = ByteArrayToHexString(buffer).Substring(26, count * 2);                                  // Count number of bytes based on count value
                            row["CRC"] = ByteArrayToHexString(buffer).Substring((26 + count * 2), 2);                              // Count 1 Byte of CRC after Length field
                            row["CRC_PC"] = crc8.ComputeChecksum(buffer).ToString("X2").ToUpper();
                            break;

                        // Case for "RESET" Signal
                        case "14":
                            table.Rows.Add(row);                                                // Add new row
                            row["Source"] = string.Format("{0}", "RESET");
                            row["System Time"] = DateTime.Now.ToString("HH:mm:ss:fff");

                            row["T.S Begin"] = ByteArrayToHexString(buffer).Substring(8, 8);
                            row["T.S End"] = ByteArrayToHexString(buffer).Substring(16, 8);
                            break;

                        // Default Case
                        default:
                            table.Rows.Add(row);                                                // Add new row
                            row["Source"] = string.Format("{0}", "ERROR_CMD_ID");
                            row["System Time"] = DateTime.Now.ToString("HH:mm:ss:fff");
                            int startIndex = 0;
                            string pattern = "AA";
                            string input = ByteArrayToHexString(buffer);
                            var regex = new Regex(pattern);
                            int endIndex = regex.Match(input, startIndex).Index;
                            int length = endIndex - startIndex;
                            row["Length"] = length;
                            break;

                    }

                }

                /*Check if buffer not startswith "AA"*/
                else if (!(ByteArrayToHexString(buffer).StartsWith("AA")))
                {
                    table.Rows.Add(row);                                                // Add new row

                    row["Source"] = string.Format("{0}", "ERROR_PA_POS");
                    row["System Time"] = DateTime.Now.ToString("HH:mm:ss:fff");
                    int startIndex = 0;
                    string pattern = "AA";
                    string input = ByteArrayToHexString(buffer);
                    var regex = new Regex(pattern);
                    int endIndex = regex.Match(input, startIndex).Index;
                    int length = endIndex - startIndex;
                    row["Length"] = length;

                }
            }

            /*Check if buffer not contains "AA"*/
            else if (!(ByteArrayToHexString(buffer).Contains("AA")))
            {
                table.Rows.Add(row);                                                // Add new row

                row["Source"] = string.Format("{0}", "ERROR_PA");
                row["System Time"] = DateTime.Now.ToString("HH:mm:ss:fff");
            }
            /*Update the Datattable*/
            dataGridView1.Update();

            /*Bind the Gridview with Source*/
            dataGridView1.DataSource = table;
        }

        /*Byte Swaping Function for Timestamp to convert Big Endian to Little Endian*/
        public static UInt32 swap(UInt32 value)
        {
            return (value & 0x000000FFU) << 24 | (value & 0x0000FF00U) << 8 |
         (value & 0x00FF0000U) >> 8 | (value & 0xFF000000U) >> 24;

        }

        /*CRC8 Implementation for received data*/
        public static class crc8
        {
            static byte[] table = new byte[256];
            const byte poly = 0xd5;

            public static byte ComputeChecksum(params byte[] bytes)
            {
                byte crc = 0;
                if (bytes != null && bytes.Length > 0)
                {
                    //if (!BitConverter.IsLittleEndian)
                    //{
                    //    Array.Reverse(bytes);
                    //}
                    foreach (byte b in bytes)
                    {
                        crc = table[crc ^ b];

                    }
                }

                return crc;
            }
            static crc8()
            {
                for (int i = 0; i < 256; i++)
                {
                    int temp = i;
                    for (int j = 0; j < 8; ++j)
                    {
                        if ((temp & 0x80) != 0)
                        {
                            temp = (temp << 1) ^ poly;
                        }
                        else
                        {
                            temp <<= 1;
                        }
                    }
                    table[i] = (byte)temp;
                }
            }

        }

        /*Button Functionalities*/
        /*Start Button*/
        private void btnStart_Click(object sender, EventArgs e)
        {

            /*Password Protection for Start*/
            if (txtUser.Text.ToString().CompareTo("test") == 0 & txtPass.Text.ToString().CompareTo("test") == 0)
            {
                txtUser.PasswordChar = '*';             // Once Logged in hide the User name
                txtPass.PasswordChar = '*';             // Once Logged in hide the Password
                MessageBox.Show("Login Successfull", "Start", MessageBoxButtons.OK, MessageBoxIcon.Information);        // Show message box

                /*Check whether user selected Online mode for Sniffing*/
                if (radioButton1.Checked == true)
                {

                    serialPort1.Open();         // Open the serial Port after putting correct Login ID & Password
                    label4.Visible = true;      // Indicate Green label
                    label3.Visible = false;     // Disable all other labels
                    label5.Visible = false;
                    timer1.Enabled = true;      // Enable the timer for counting time

                }
                else
                {
                    MessageBox.Show("Choose Online Mode / Data Mode", "Start", MessageBoxButtons.OK, MessageBoxIcon.Warning);    // Show Error Message
                }
            }
            else
            {
                label3.Visible = true;           // Show Error Label
                MessageBox.Show("Wrong Username/Password! \n Please try again!", "Login", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtPass.Text = "";
                txtUser.Text = "";
            }

        }
        /*Checkbox click to Show or Hide the Password (Not using in this Program)*/
        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBox1.Checked == true)
            {
                txtPass.PasswordChar = (char)0;
                checkBox1.Text = "Show Password";
            }
            else
            {
                txtPass.PasswordChar = '*';
                checkBox1.Text = "Hide password";
            }
        }

        /*Stop Button*/
        private void btnStop_Click(object sender, EventArgs e)
        {
            serialPort1.Close();         // Close the serial Port
            timer1.Enabled = false;      // Disable the timer for counting time
            label3.Visible = true;
            label4.Visible = false;
        }

        /*Save / Export data to .Text File*/
        private void btnSave_Click(object sender, EventArgs e)
        {
            TextWriter writer = new StreamWriter(@"C:\temp\Sniffer_log.txt");        // Initiate streamwriter to write data from datagrid window
            label5.Visible = true;                                                  // Show Yellow Color label for saving file
            for (int i = 0; i < dataGridView1.Rows.Count - 1; i++)                          // Row count 
            {
                for (int j = 0; j < dataGridView1.Columns.Count; j++)               // count the columns 
                {
                    writer.Write("\t" + dataGridView1.Rows[i].Cells[j].Value.ToString() + "\t" + ";");      // write value of rows & columns with proper format
                }
                writer.WriteLine("");                                               // Write the data in the log file

            }
            writer.Close();                                                         // Close the writer
            MessageBox.Show("Data Saved");                                          // Show Message
            label5.Visible = false;                                                 // Disable data save Label
        }

        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }

        /*Clear the content of the datagridview*/
        private void btnclear_Click(object sender, EventArgs e)
        {
            table.Clear();
            table.DefaultView.RowFilter = null;                             // Disable all enabled filter options
        }

        /*Implementation of Filter property for particular rows*/
        private void button1_Click(object sender, EventArgs e)
        {
            table.DefaultView.RowFilter = "Length LIKE '*09*'";             // Filter data row containing length field of 9
            dataGridView1.Refresh();
        }

        /*Implemenation of Progress bar based on the buffer size. As buffer gets filled progress bar show green color*/
        private void progressBar1_Click(object sender, EventArgs e)
        {

        }

        /*Select Online Mode for Sniffer*/
        private void radioButton1_CheckedChanged(object sender, EventArgs e)
        {
            btnStart.Enabled = true;        // Enable Open port button
            btnLoad.Enabled = false;        // Disable Load button which is useful for offline mode
        }

        private void btnLoad_Click(object sender, EventArgs e)
        {

        }

        private void radioButton3_CheckedChanged(object sender, EventArgs e)
        {
            //serialPort1.Open();
        }

    }
}

AnswerRe: Missing data on Windows App form C# Pin
Jochen Arndt7-Jun-17 1:46
professionalJochen Arndt7-Jun-17 1:46 
GeneralRe: Missing data on Windows App form C# Pin
Member 131317267-Jun-17 2:47
Member 131317267-Jun-17 2:47 
GeneralRe: Missing data on Windows App form C# Pin
Gerry Schmitz7-Jun-17 3:16
mveGerry Schmitz7-Jun-17 3:16 
GeneralRe: Missing data on Windows App form C# Pin
Jochen Arndt7-Jun-17 3:26
professionalJochen Arndt7-Jun-17 3:26 
AnswerRe: Missing data on Windows App form C# Pin
Luc Pattyn8-Jun-17 13:44
sitebuilderLuc Pattyn8-Jun-17 13:44 
GeneralRe: Missing data on Windows App form C# Pin
Member 1313172611-Jun-17 20:41
Member 1313172611-Jun-17 20:41 
GeneralRe: Missing data on Windows App form C# Pin
Luc Pattyn12-Jun-17 6:15
sitebuilderLuc Pattyn12-Jun-17 6:15 
GeneralRe: Missing data on Windows App form C# Pin
Member 1313172612-Jun-17 20:39
Member 1313172612-Jun-17 20:39 
GeneralRe: Missing data on Windows App form C# Pin
Luc Pattyn12-Jun-17 23:42
sitebuilderLuc Pattyn12-Jun-17 23:42 
QuestionJson parser error when converting iphone images from bytes to base64 string in a MVC JsonResult Pin
jkirkerx6-Jun-17 10:22
professionaljkirkerx6-Jun-17 10:22 
AnswerRe: Json parser error when converting iphone images from bytes to base64 string in a MVC JsonResult [solved] Pin
jkirkerx6-Jun-17 12:49
professionaljkirkerx6-Jun-17 12:49 
SuggestionRe: Json parser error when converting iphone images from bytes to base64 string in a MVC JsonResult [solved] Pin
Richard Deeming7-Jun-17 0:57
mveRichard Deeming7-Jun-17 0:57 
GeneralRe: Json parser error when converting iphone images from bytes to base64 string in a MVC JsonResult [solved] Pin
jkirkerx7-Jun-17 6:33
professionaljkirkerx7-Jun-17 6:33 
QuestionCreate a chart in PowerPoint using C#. Pin
Member 126813284-Jun-17 22:30
Member 126813284-Jun-17 22:30 
AnswerRe: Create a chart in PowerPoint using C#. Pin
OriginalGriff4-Jun-17 22:43
mveOriginalGriff4-Jun-17 22:43 
Questioncustom controls not binding wpf Pin
Member 112967764-Jun-17 7:52
Member 112967764-Jun-17 7:52 
AnswerRe: custom controls not binding wpf Pin
Gerry Schmitz5-Jun-17 5:36
mveGerry Schmitz5-Jun-17 5:36 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.