home hardware prices news articles forums photos user reviews
Go Back   Tech Support Forums - TechIMO.com > PC Hardware and Tech > Webmastering and Programming
Ask a Tech Support Question (free)!

C# COM Writing Error

Reply
Get bargains at  »  Dealighted.com
 
Thread Tools Search this Thread
Currently Active Users: 2452
Discussions: 200,959, Posts: 2,379,551, Members: 246,329
Old April 23rd, 2008, 10:42 PM   Digg it!   #1 (permalink)
Senior Member
 
The Terk's Avatar
 
Join Date: Jul 2002
Location: Texas A&M
Posts: 611
Send a message via AIM to The Terk
C# COM Writing Error

Hello everyone, I have what seems to be an easy problem, but I have yet to figure it out. I have downloaded the SimpleSerial program from this website and have modified it to execute a page request. When I run the form, I can select a serial port and can insert a command to request a specific page. The error is that when it begins writing data to the serial port, it continues to write the same data to the COM port. I only have one serialport.write function so I want to say that it keeps looping. Here is the code:

Code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.IO;

namespace SimpleSerial
{
    public partial class Form1 : Form
    {
        // Add this variable 
        string RxString;
        string TxString;

        public Form1()
        {
            InitializeComponent();
        }

        private void buttonStart_Click(object sender, EventArgs e)
        {
            serialPort1.PortName = listBox1.Text;
            serialPort1.BaudRate = 38400;

            serialPort1.Open();
            if (serialPort1.IsOpen)
            {
                buttonStart.Enabled = false;
                buttonStop.Enabled = true;
                textBox1.ReadOnly = false;
            }
        }

        private void buttonStop_Click(object sender, EventArgs e)
        {
            if (serialPort1.IsOpen)
            {
                serialPort1.Close();
                buttonStart.Enabled = true;
                buttonStop.Enabled = false;
                textBox1.ReadOnly = true;
            }

        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (serialPort1.IsOpen) serialPort1.Close();
        }

        private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
        {
            // If the port is closed, don't try to send a character.
            if (!serialPort1.IsOpen) return;

            // If the port is Open, declare a char[] array with one element.
            char[] buff = new char[1];

            // Load element 0 with the key character.
            buff[0] = e.KeyChar;

            // Send the one character buffer.
            //serialPort1.Write(buff, 0, 1);

            // Set the KeyPress event as handled so the character won't
            // display locally. If you want it to display, omit the next line.
            e.Handled = true;
        }

        private void DisplayText(object sender, EventArgs e)
        {
            textBox1.AppendText(RxString);
        }
        private void DisplayText2(object sender, EventArgs e)
        {
            textBox1.AppendText(TxString);
        }
        private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
            RxString = serialPort1.ReadTo("!");
            char option = RxString[0];
            switch (option)
            {
                case 'L':
                    {
                        getList();
                        serialPort1.Write(TxString);
                        break;
                    }
                case 'S':
                    {
                        getSale();
                        serialPort1.Write(TxString);
                        break;
                    }
                case 'I':
                    {
                        getInfo();
                        serialPort1.Write(TxString);
                        break;
                    }
                default: break;
            }
        }
        private void getList()
        {
            // used to build entire input
            StringBuilder sb = new StringBuilder();

            // used on each read operation
            byte[] buf = new byte[8192];
            char[] userid = new char[4];
            for (int i = 1; i < 5; i++)
            {
                userid[i - 1] = RxString[i];
            }


            serialPort1.DiscardInBuffer();

            string Id = new string(userid);

            // prepare the web page we will be asking for
            HttpWebRequest request = (HttpWebRequest)
                WebRequest.Create("http://192.168.1.101/IGLU/getlist.php?userid="+Id);

            // execute the request
            HttpWebResponse response = (HttpWebResponse)
                request.GetResponse();

            // we will read data via the response stream
            Stream resStream = response.GetResponseStream();

            //string tempString = null;
            int count = 0;

            do
            {
                // fill the buffer with data
                count = resStream.Read(buf, 0, buf.Length);
                // make sure we read some data
                if (count != 0)
                {
                    // translate from bytes to ASCII text
                    TxString = Encoding.ASCII.GetString(buf, 0, count);
                    // continue building the string
                    //sb.Append(TxString);
                }
            }
            while (count > 0); // any more data to read?
            this.Invoke(new EventHandler(DisplayText2));          //display to form
        }

        private void getSale()
        {
            // used to build entire input
            StringBuilder sb = new StringBuilder();

            // used on each read operation
            byte[] buf = new byte[8192];
            char[] saleid = new char[10];
            for (int i = 1; i < 11; i++)
            {
                saleid[i - 1] = RxString[i];
            }
            string upc = new string(saleid);

            // prepare the web page we will be asking for
            HttpWebRequest request = (HttpWebRequest)
                WebRequest.Create("http://192.168.1.101/IGLU/sale.php?upc=" + upc);

            // execute the request
            HttpWebResponse response = (HttpWebResponse)
                request.GetResponse();

            // we will read data via the response stream
            Stream resStream = response.GetResponseStream();

            //string tempString = null;
            int count = 0;

            do
            {
                // fill the buffer with data
                count = resStream.Read(buf, 0, buf.Length);
                // make sure we read some data
                if (count != 0)
                {
                    // translate from bytes to ASCII text
                    TxString = Encoding.ASCII.GetString(buf, 0, count);
                    // continue building the string
                    //sb.Append(TxString);
                }
            }
            while (count > 0); // any more data to read?
            this.Invoke(new EventHandler(DisplayText2));      //display to form
        }

        private void getInfo()
        {
            // used to build entire input
            StringBuilder sb = new StringBuilder();

            // used on each read operation
            byte[] buf = new byte[8192];
            char[] infoid = new char[10];
            for (int i = 1; i < 11; i++)
            {
                infoid[i - 1] = RxString[i];
            }
            string Id = new string(infoid);

            // prepare the web page we will be asking for
            HttpWebRequest request = (HttpWebRequest)
                WebRequest.Create("http://192.168.1.101/IGLU/info.php?upc=" + Id);

            // execute the request
            HttpWebResponse response = (HttpWebResponse)
                request.GetResponse();

            // we will read data via the response stream
            Stream resStream = response.GetResponseStream();

            //string tempString = null;
            int count = 0;

            do
            {
                // fill the buffer with data
                count = resStream.Read(buf, 0, buf.Length);
                // make sure we read some data
                if (count != 0)
                {
                    // translate from bytes to ASCII text
                    TxString = Encoding.ASCII.GetString(buf, 0, count);
                    // continue building the string
                    //sb.Append(TxString);
                }
            }
            while (count > 0); // any more data to read?
            this.Invoke(new EventHandler(DisplayText2));      //display to form
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {

        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }
    }
}
I am not to familiar with C# so any help would be awesome. Thanks guys
__________________

The Terk

Last edited by The Terk : April 24th, 2008 at 07:21 PM.
The Terk is offline   Reply With Quote
Old April 24th, 2008, 02:02 PM     #2 (permalink)
Super F@D Folder
 
Join Date: Jun 2004
Posts: 5,083
Send a message via AIM to sr71000
from now on...if you're posting code, put it in the [ code] and the [ /code] tags. just take the space out in front word code in each bracket...makes it MUCH easier to read!!

Code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.IO;

namespace SimpleSerial
{
	public partial class Form1 : Form
	{
		// Add this variable
		string RxString;
		string TxString;

		public Form1()
		{
			InitializeComponent();
		}

		private void buttonStart_Click(object sender, EventArgs e)
		{
			serialPort1.PortName = listBox1.Text;
			serialPort1.BaudRate = 38400;

			serialPort1.Open();
			if (serialPort1.IsOpen)
			{
				buttonStart.Enabled = false;
				buttonStop.Enabled = true;
				textBox1.ReadOnly = false;
			}
		}

		private void buttonStop_Click(object sender, EventArgs e)
		{
			if (serialPort1.IsOpen)
			{
				serialPort1.Close();
				buttonStart.Enabled = true;
				buttonStop.Enabled = false;
				textBox1.ReadOnly = true;
			}
		}

		private void Form1_FormClosing(object sender, FormClosingEventArgs e)
		{
			if (serialPort1.IsOpen)
				serialPort1.Close();
		}

		private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
		{
			// If the port is closed, don't try to send a character.
			if (!serialPort1.IsOpen)
				return;

			// If the port is Open, declare a char[] array with one element.
			char[] buff = new char[1];

			// Load element 0 with the key character.
			buff[0] = e.KeyChar;

			// Send the one character buffer.
			//serialPort1.Write(buff, 0, 1);

			// Set the KeyPress event as handled so the character won't
			// display locally. If you want it to display, omit the next line.
			e.Handled = true;
		}

		private void DisplayText(object sender, EventArgs e)
		{
			textBox1.AppendText(RxString);
		}

		private void DisplayText2(object sender, EventArgs e)
		{
			textBox1.AppendText(TxString);
		}

		private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
		{
			RxString = serialPort1.ReadTo("!");
			char option = RxString[0];
			switch (option)
			{
				case 'L':
				{
					getList();
					serialPort1.Write(TxString);
					break;
				}
				case 'S':
				{
					getSale();
					serialPort1.Write(TxString);
					break;
				}
				case 'I':
				{
					getInfo();
					serialPort1.Write(TxString);
					break;
				}
				default: break;
			}
		}

		private void getList()
		{
			// used to build entire input
			StringBuilder sb = new StringBuilder();

			// used on each read operation
			byte[] buf = new byte[8192];
			char[] userid = new char[4];
			for (int i = 1; i < 5; i++)
			{
				userid[i - 1] = RxString[i];
			}

			serialPort1.DiscardInBuffer();
			string Id = new string(userid);

			// prepare the web page we will be asking for
			HttpWebRequest request = (HttpWebRequest)
			WebRequest.Create("http://192.168.1.101/IGLU/getlist.php?userid="+Id);

			// execute the request
			HttpWebResponse response = (HttpWebResponse)
			request.GetResponse();

			// we will read data via the response stream
			Stream resStream = response.GetResponseStream();

			//string tempString = null;
			int count = 0;

			do
			{
				// fill the buffer with data
				count = resStream.Read(buf, 0, buf.Length);
				// make sure we read some data
				if (count != 0)
				{
					// translate from bytes to ASCII text
					TxString = Encoding.ASCII.GetString(buf, 0, count);
					// continue building the string
					//sb.Append(TxString);
				}
			}
			while (count > 0); // any more data to read?

			this.Invoke(new EventHandler(DisplayText2)); //display to form
		}

		private void getSale()
		{
			// used to build entire input
			StringBuilder sb = new StringBuilder();

			// used on each read operation
			byte[] buf = new byte[8192];
			char[] saleid = new char[10];
			for (int i = 1; i < 11; i++)
			{
				saleid[i - 1] = RxString[i];
			}
			string upc = new string(saleid);

			// prepare the web page we will be asking for
			HttpWebRequest request = (HttpWebRequest)
			WebRequest.Create("http://192.168.1.101/IGLU/sale.php?upc=" + upc);

			// execute the request
			HttpWebResponse response = (HttpWebResponse)
			request.GetResponse();

			// we will read data via the response stream
			Stream resStream = response.GetResponseStream();

			//string tempString = null;
			int count = 0;

			do
			{
				// fill the buffer with data
				count = resStream.Read(buf, 0, buf.Length);
				// make sure we read some data
				if (count != 0)
				{
					// translate from bytes to ASCII text
					TxString = Encoding.ASCII.GetString(buf, 0, count);
					// continue building the string
					//sb.Append(TxString);
				}
			}
			while (count > 0); // any more data to read?

			this.Invoke(new EventHandler(DisplayText2)); //display to form
		}

		private void getInfo()
		{
			// used to build entire input
			StringBuilder sb = new StringBuilder();

			// used on each read operation
			byte[] buf = new byte[8192];
			char[] infoid = new char[10];
			for (int i = 1; i < 11; i++)
			{
				infoid[i - 1] = RxString[i];
			}
			string Id = new string(infoid);

			// prepare the web page we will be asking for
			HttpWebRequest request = (HttpWebRequest)
			WebRequest.Create("http://192.168.1.101/IGLU/info.php?upc=" + Id);

			// execute the request
			HttpWebResponse response = (HttpWebResponse)
			request.GetResponse();

			// we will read data via the response stream
			Stream resStream = response.GetResponseStream();

			//string tempString = null;
			int count = 0;

			do
			{
				// fill the buffer with data
				count = resStream.Read(buf, 0, buf.Length);
				// make sure we read some data
				if (count != 0)
				{
					// translate from bytes to ASCII text
					TxString = Encoding.ASCII.GetString(buf, 0, count);
					// continue building the string
					//sb.Append(TxString);
				}
			}
			while (count > 0); // any more data to read?

			this.Invoke(new EventHandler(DisplayText2)); //display to form
		}

		private void textBox1_TextChanged(object sender, EventArgs e)
		{

		}

		private void Form1_Load(object sender, EventArgs e)
		{

		}
	}
}
sr71000 is offline   Reply With Quote
Old April 24th, 2008, 09:29 PM     #3 (permalink)
Senior Member
 
The Terk's Avatar
 
Join Date: Jul 2002
Location: Texas A&M
Posts: 611
Send a message via AIM to The Terk
I fixed the problem, turns out the receive buffer was never getting cleared, so i created an oldrxstring and if the two were the same i discarded the command. Thanks for the views guys
The Terk is offline   Reply With Quote
Old April 29th, 2008, 01:45 PM     #4 (permalink)
Super F@D Folder
 
Join Date: Jun 2004
Posts: 5,083
Send a message via AIM to sr71000
Hey. Can you post the fixed code? I was trying to figure it out but I'd never worked with com ports before. I'd love to see how you fixed it!
sr71000 is offline   Reply With Quote
Reply
Thread Tools Search this Thread
Search this Thread:

Advanced Search

Similar Threads
Thread Thread Starter Forum Replies Last Post
resume writing e1iza8b IMO Community 1 October 2nd, 2007 12:42 PM
error writing drive c: / frequency over range when starting games kid_presentable Graphics Cards and Displays 1 October 23rd, 2005 11:14 PM
error writing drive c: / frequency over range when starting games kid_presentable Graphics Cards and Displays 0 October 20th, 2005 07:32 AM
writing C butch81385 Webmastering and Programming 5 September 2nd, 2004 12:07 PM
here was an error writing to brusb for the printer. The system cannot write to the sp carmacamin Technical Support 7 January 5th, 2003 03:02 AM


Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Most Active Discussions
Is It Just Me? (2976)
The disrespect of Obama by Russian .. (45)
Making Health Care Worse (181)
Wireless Televisions. (12)
CPU fan stops spinning randomly (10)
Regular Build (11)
windows 7 problem (7)
Laptop with wireless problem. (5)
windows vista security holes (13)
Is the PSU I received dead? (13)
Point and Shoot Camera Suggestions. (5)
Print spooler problem (16)
radeon x850xt platinum & shader.. (6)
HIS HD5770 graphic card question (15)
Recent Discussions
Point and Shoot Camera Suggestions. (5)
CPU fan stops spinning randomly (10)
Is the PSU I received dead? (13)
Print spooler problem (16)
Nvidia GTX 260 problem (0)
windows vista security holes (13)
Kingston Bluetooth Dongle Driver (1)
Multiple Restarts Required at Boot (3)
Open With ..... Win7 (1)
webcam (0)
upgrade for hp a6101 (0)
Laptop with wireless problem. (5)
Modern Warfare 2: Who Bought It? (64)
tv not turn on-makes clicking sound (2)
EVGA 9800 gtx help with finding a goo.. (11)
Regular Build (11)
Help with onclick and buttons (0)
Virus advise (8)
My monitor won't turn on after instal.. (1)
Internet Lost (3)
Dept. of HS: NSA 'Helped' Develop Vis.. (16)
Ideal cheap graph card for PC-Gaming? (18)
radeon x850xt platinum & shader 3 (6)
Graphics Card Upgrade Question (4)
For Sale BFG GTX285 OC2 with 10 year .. (3)


All times are GMT -4. The time now is 10:59 AM.
TechIMO Copyright 2009 All Enthusiast, Inc.



1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28