|
naouf10 wrote: Does it mean the port did not receive any data ?
Yes... Exactly that...
Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...
|
|
|
|
|
@ OriginalGriff. I tested the caller Id in different PC (PC2) which has EPOS and this EPOS could display the phone number so it means the port receives data when phone rings therefor I tested my C# code in PC2 and still my app didn't receive data from COM port although EPOS can read data from same port. any idea?
|
|
|
|
|
I've "heard" the DataReceived event doesn't always work (so I avoid it).
You first need to confirm that your SerialPort (class) settings match what's in Control Panel AND match what the device expects.
Also insure your "timeout" settings are high enough.
When you believe there is data on the serial port, you can do a .BytesToRead() call on the serial port to see if there is data waiting. You should "sleep" some amount of time before trying.
If you never have any "bytes to read" > 0, then you're still not configured / hooked-up properly.
(You should build a dialog (button) so that you can read / query the port on demand for testing. You cannot restart a program and serial port and expect data to persist).
|
|
|
|
|
@ Gerry Schmitz . Thank you for your good information.
yes both the SerialPort (class) and the Caller ID have the same settings.
maybe your ideas will work but I have to modify my code first. Can you please tell me how to do the following in my code:
-
.BytesToRead() call
- how to sleep before trying?
- how to insure my "timeout" settings are high enough. I don't have TimeOut in my code.
Please help me so I can modify my code. Thank you
|
|
|
|
|
int bytesToRead = 0;
for ( int i = 0; i < 5; i++ ) {
bytesToRead = _serialPort.BytesToRead;
if ( bytesToRead > 0 ) {
break;
}
Thread.Sleep( 50 );
}
Setting timeouts is trial-and-error; you just need to insure they are "long enough".
I've been in situations where the timeouts needed varying from 250ms up to 5000ms; depending on the environment (i.e. network).
Another thing: Serial devices don't typically just "send"; they respond to requests. i.e. You send data to the device; it responds ... even if it is just with an error.
If there is no "command" that you can send to the device and for which you can expect a response (like "current status"), then you are missing something (like RTFM).
|
|
|
|
|
Hi,
serial input on a Windows PC (or on any device for that matter) tends to be tricky, here are some pointers:
1. The code you have shown does NOT read any data, your DataReceived handler is empty.
2. I/O operations occur in "real time", making it hard to observe them correctly; typical debug operations (single-stepping and the like) don't work, the world doesn't stop when you stop typing the keyboard. My solution to this is: use logging. A simple Console.WriteLine() or a File.WriteLine() could do, prefixing a time stamp always proves useful. I tend to also log to a listbox, with auto-scroll, and obviously with the appropriate Invoke stuff built-in so it works from any thread that happens to call it. And no, you don't need a logging package for this, all the logging infrastructure requires is about 10 lines of code.
3. Advice on all software development: don't build your entire app, then test and watch it fail. Develop one basic operation at a time, get it to work properly, then proceed. Hence, do not touch WinForms Controls before you must.
4. Tricky bits part 1: AFAIK there is no decent description as to when an I/O event is called; for DataReceived it does not mean: "when my data is in" (the computer does not know what you consider "your data"), and we can only hope and observe it does not mean for each and every byte. What typically happens is the operating system collects incoming bytes, and signals an input operation when it has a reasonable amount of data (say 5 bytes), which probably is half a message in your application domain, so you get an event for half a message; and then the remaining bytes possibly aren't enough to cause a second signal, so you don't get them at all.
(Exception is when you read a text string and tell the driver what constitutes an end-of-message, by default that could be a CARRIAGE RETURN, a LINEFEED or both). Conclusion: you most often are better off not using those events, as they often do not connect well to your application. Yes they work, but not the way you would dream they work.
5. Advice on I/O: for simple things (and also when starting complex things), first use operations you perform explicitly AND synchronously (i.e. actual Read, ReadLine and the like, without events), avoid asynchronous stuff (such as the DataReceived operation).
6. Tricky bits part 2: how does one synchronize the external device and the code that reads data? the start of transmission is no good, reading a message often makes sense only when the entire message is available.
I see four useful schemes:
a) if you can choose the message format, use text, the proper end-of-line marker, and ReadLine; easy, but seldom possible;
b) otherwise, when an end-of-transmission event exists, use it and read the entire message.
c) otherwise, when a transmission-has-started event exists, and bandwidth and latency aren't real issues, then use that signal to start a delay, after the delay read the entire message. The delay must be long enough to transmit the longest possible message at the current (or the slowest expected) baud rate. This approach wastes both time (hence latency) and bandwidth. As you want to display incoming data, I expect latency and bandwidth aren't an issue, so this would be the right choice for you.
d) if the above schemes don't exist or aren't acceptable, construct your own data buffer, feed it with incoming data as and when it comes, then detect message starts and ends, and create a signal to your actual business logic as appropriate.
7. What I would do first is have a button that reads from the port and logs everything it got. Only proceed when that works. Next step could be: create a timer (I mean a Windows.Forms.Timer, which ticks on the main thread) that periodically reads the serial port.
Then start looking into the synchronization problem I mentioned under 6.
8. A number of I/O and timer operations run on a different thread, so you can't directly access WinForms Controls from there; that is where Control.Invoke() comes in. This applies to almost all events on incoming data (SerialPort.DataReceived, and most kinds of timers).
I hope this helps, and I wish you good luck!
PS: The following might be useful: Article: A simple logging scheme[^], Article: Invalid cross-thread operations[^], Article: Asynchronous operations run on ThreadPool threads[^], Article: Timer surprises, and how to avoid them[^]
modified 24-Dec-15 11:41am.
|
|
|
|
|
Thank you alot, I will consider what you have said.
|
|
|
|
|
Excellent post!
You have just been Sharapova'd.
|
|
|
|
|
I Need to call a method that is present on two different classes without istantiate two different objects one for any class and call the method from an object or other switching on a flag.
Example, in the following code i would call GetSheetAt(..)
XSSFWorkbook Xwb;
XSSFSheet Xsh;
HSSFWorkbook Hwb;
String Sheets;
switch (Type) {
case XLSType.XLS:
Hwb = new HSSFWorkbook(fs);
SheetCount = Hwb.Count;
for (int i = 0; i < SheetCount; i++)
Sheets += "\n" + Hwb.GetSheetAt(i).SheetName;
break;
case XLSType.XLSX:
Xwb = new XSSFWorkbook(fs);
SheetCount = Xwb.Count;
for (int i = 0; i < SheetCount; i++)
Sheets += "\n" + Xwb.GetSheetAt(i).SheetName;
break;
default:
break;
}
i would use something like objwb.GetSheetAt(i)
Many Thanx in Advance.
SFMBE
|
|
|
|
|
The two objects are different so you need to instantiate both so the correct code gets executed..
|
|
|
|
|
GetSheetAt is implemented in the "Workbook" class, from which both inherit; but you'd still have to instantiate the correct class.
Bastard Programmer from Hell
If you can't read my code, try converting it here[^]
|
|
|
|
|
Based on what I see here:
1. 'fs ... whatever that is ... is invariant
2. you are creating new instances of HSSF... and XSSF... in the scope of a 'switch statement just to get access to methods "in" them. That's a waste.
Think about creating one instance each of HSSF... and XSSF... outside the 'switch statement ... and, then, re-use them ... assuming those Classes are not doing some strange self-modifying voodoo.
And, you really should use StringBuilder here:
XSSFWorkbook Xwb = new XSSFWorkbook(fs);
HSSFWorkbook Hwb = new HSSFWorkbook(fs);
XSSFSheet Xsh;
StringBuilder sb = new StringBuilder();
String Sheets;
switch (Type) {
case XLSType.XLS:
for (int i = 0; i < Hwb.Count; i++)
sb.AppendLine(Hwb.GetSheetAt(i).SheetName);
break;
case XLSType.XLSX:
for (int i = 0; i < Xwb.Count; i++)
sb.AppendLine(Xwb.GetSheetAt(i).SheetName);
break;
default:
break;
}
Sheets = sb.ToString(); It should be obvious, but note that this code is not tested.
«Tell me and I forget. Teach me and I remember. Involve me and I learn.» Benjamin Franklin
|
|
|
|
|
If both inherit from the workbook class then the switch statement is superfluous
Bastard Programmer from Hell
If you can't read my code, try converting it here[^]
|
|
|
|
|
Merry Xmas, Eddy,
A good point; it's been a long time since I played with Excel automation.
In this case, we don't really know what the variable 'Type used in the switch-statement contains ... we do know that's a bad choice for a variable name ... is it even possible that 'Type contains a fully qualified name that would work in this context ? One can only hope the OP here is posting code that somewhat "works"
«Tell me and I forget. Teach me and I remember. Involve me and I learn.» Benjamin Franklin
|
|
|
|
|
BillWoodruff wrote: Merry Xmas, Eddy, Thanks, same to you
BillWoodruff wrote: In this case, we don't really know what the variable 'Type used in the switch-statement contains We Googled the type-names, and we think that there is a very low probability that there exists exactly two types with those names and documentation on a major website.
Could be just a coincidence.
Bastard Programmer from Hell
If you can't read my code, try converting it here[^]
|
|
|
|
|
The "Type" variable in my piece of code is symply an enumerator that assume two values observing the extension of a filename (not present in the code posted) used in fs that is a filestream.
Sorry for unusable code but when i posted the question i was in the first approach to the problem.
Thanx to all for suggestions but in the end i choiced a simply (much simply??) way to use the switch.
In the Visual Fox Pro (the my previous language) i can call a generic method from an object that can be anytype ... there is no strong type checking... the more similar way is use the Pinvoke ... but i don't like so much .. even if in some cases i used it. Initially i tryed to use a simple object of type 'object' ... but the use of switch was necessary with many cast ... so the partial initial (reaing only), but useful, result of my class for managing xls or xlsx with NPOI is :
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;
using NPOI.XSSF.UserModel;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
namespace XLSManagement
{
public class NPOIWrapper {
enum XLSType {XLS, XLSX}
public string FileName { get; set;}
private int _CurrentSheetIndex = 0;
public int CurrentSheetIndex { get {return _CurrentSheetIndex; } set {_CurrentSheetIndex = value; } }
public NPOIWrapper() { }
public NPOIWrapper(string cFileName) {
this.FileName = cFileName;
ReadXLS();
}
private string[] _Sheet;
public string[] Sheet {get { return _Sheet;} }
private int _SheetCount = 0;
public int SheetCount {get { return _SheetCount;} }
XLSType Type;
XSSFWorkbook Xwb;
HSSFWorkbook Hwb;
ISheet[] sh;
public bool ReadXLS(string XLSFileName = "") {
bool Ret = true;
string XLSName, Extension;
StringBuilder Sheets = new StringBuilder();
FileStream fs;
XLSName = String.IsNullOrEmpty(XLSFileName)?this.FileName:XLSFileName;
Extension = Path.GetExtension(XLSName).Substring(1).ToUpper();
switch (Extension) {
case "XLS":
Type = XLSType.XLS;
break;
case "XLSX":
Type = XLSType.XLSX;
break;
default:
Ret = false;
break;
}
if(Ret) {
fs = new FileStream(XLSName, FileMode.Open, FileAccess.Read);
if (fs==null) Ret = false;
else {
switch (Type) {
case XLSType.XLS:
try {
Hwb = new HSSFWorkbook(fs);
} catch (Exception ex){ MessageBox.Show("Lettura File XLSX: \n" + ex.Message);}
_SheetCount = Hwb.Count;
sh = new ISheet[_SheetCount];
for (int i = 0; i < _SheetCount; i++) {
sh[i] = Hwb.GetSheetAt(i);
Sheets.Append("\n" + sh[i].SheetName);
}
break;
case XLSType.XLSX:
try {
Xwb = new XSSFWorkbook(fs);
} catch (Exception ex){ MessageBox.Show("Lettura File XLSX: \n" + ex.Message);}
_SheetCount = Xwb.Count;
sh = new ISheet[_SheetCount];
for (int i = 0; i < _SheetCount; i++) {
sh[i] = Xwb.GetSheetAt(i);
Sheets.Append("\n" + sh[i].SheetName);
}
break;
default:
break;
}
this._Sheet = Sheets.ToString().Substring(1).Split('\n');
}
}
return Ret;
}
public ICell GetCell(int Row, int Col) {
ICell Ret;
Ret = GetCell(Row, Col, this.CurrentSheetIndex);
return Ret;
}
public ICell GetCell(int Row, int Col, int Sheet) {
ICell Ret;
Ret = sh[Sheet].GetRow(Row).GetCell(Col);
return Ret;
}
public String GetCellValue(int Row, int Col) {
String Ret;
Ret = GetCellValue(Row, Col, this.CurrentSheetIndex);
return Ret;
}
public string GetCellValue(int Row, int Col, int Sheet) {
string Ret;
Ret = sh[Sheet].GetRow(Row).GetCell(Col).ToString();
return Ret;
}
public IRow GetRow(int Row, int Sheet) {
IRow Ret;
Ret = sh[Sheet].GetRow(Row);
return Ret;
}
public IRow GetRow(int Row) {
IRow Ret;
Ret = GetRow(Row, CurrentSheetIndex);
return Ret;
}
}
}
|
|
|
|
|
I have no examined the NPOI classes hierarchy 8|.
Thanx
|
|
|
|
|
Is true ... my use of string in that manner (is c#) is not reccomended ... but, in my partial excuse, was my first draft and my was pointed in the use of class istantiation ... ecen if your seuggestion is an aswer to my question ... the better way is to use StringBuilders 8)
Thanx
|
|
|
|
|
Here are the elements you need; assuming you can reflect on your workbooks:
using System;
using System.Reflection;
namespace ConsoleApplication6 {
class Program {
static void Main( string[] args ) {
Run( typeof( Foo ), "butter" );
Run( typeof( Fee ), "jam" );
}
private static void Run( Type t, string s ) {
object o = Activator.CreateInstance( t );
MethodInfo mi = o.GetType().GetMethod( "Print" );
mi.Invoke( o, new object[] { s } );
}
}
class Foo {
public void Print( string s ) { Console.WriteLine( "I like bread and {0}", s ); }
}
class Fee {
public void Print( string s ) { Console.WriteLine( "I like toast and {0}", s ); }
}
}
|
|
|
|
|
Thanx
this is my second version of this incomplete but runnable piece of code:
public class NPOIWrapper {
enum XLSType {XLS, XLSX}
public string FileName { get; set;}
private int _CurrentSheetIndex = 0;
public int CurrentSheetIndex { get {return _CurrentSheetIndex; } set {_CurrentSheetIndex = value; } }
public NPOIWrapper() { }
public NPOIWrapper(string cFileName) {
this.FileName = cFileName;
ReadXLS();
}
private string[] _Sheet;
public string[] Sheet {get { return _Sheet;} }
private int _SheetCount = 0;
public int SheetCount {get { return _SheetCount;} }
XLSType xlsType;
object wb;
ISheet[] sh;
public bool ReadXLS(string XLSFileName = "") {
bool Ret = true;
string XLSName, Extension;
StringBuilder Sheets = new StringBuilder();
FileStream fs;
XLSName = String.IsNullOrEmpty(XLSFileName)?this.FileName:XLSFileName;
Extension = Path.GetExtension(XLSName).Substring(1).ToUpper();
switch (Extension) {
case "XLS":
xlsType = XLSType.XLS;
break;
case "XLSX":
xlsType = XLSType.XLSX;
break;
default:
Ret = false;
break;
}
if(Ret) {
fs = new FileStream(XLSName, FileMode.Open, FileAccess.Read);
if (fs==null) Ret = false;
else {
Type t = xlsType==XLSType.XLS?typeof(HSSFWorkbook):typeof(XSSFWorkbook);
try {
wb = Activator.CreateInstance(t, new object[] {fs});
} catch (Exception ex) { MessageBox.Show("Problemi nella lettura del foglio\n" + ex.Message);}
if (wb != null) {
_SheetCount = ((IWorkbook)wb).Count;
sh = new ISheet[_SheetCount];
for (int i = 0; i < _SheetCount; i++) {
sh[i] = ((IWorkbook)wb).GetSheetAt(i);
Sheets.Append("\n" + sh[i].SheetName);
}
this._Sheet = Sheets.ToString().Substring(1).Split('\n');
}
fs.Close();
}
}
return Ret;
}
public ICell GetCell(int Row, int Col) {
ICell Ret;
Ret = GetCell(Row, Col, this.CurrentSheetIndex);
return Ret;
}
public ICell GetCell(int Row, int Col, int Sheet) {
ICell Ret;
Ret = sh[Sheet].GetRow(Row).GetCell(Col);
return Ret;
}
public String GetCellValue(int Row, int Col) {
String Ret;
Ret = GetCellValue(Row, Col, this.CurrentSheetIndex);
return Ret;
}
public string GetCellValue(int Row, int Col, int Sheet) {
string Ret;
Ret = sh[Sheet].GetRow(Row).GetCell(Col).ToString();
return Ret;
}
public IRow GetRow(int Row, int Sheet) {
IRow Ret;
Ret = sh[Sheet].GetRow(Row);
return Ret;
}
public IRow GetRow(int Row) {
IRow Ret;
Ret = GetRow(Row, CurrentSheetIndex);
return Ret;
}
}
|
|
|
|
|
Yes; interfaces were an option; wasn't sure if your design allowed for them. You can make things a bit more succinct:
IWorkbook wb;
...
wb = Activator.CreateInstance( t, new object[] { fs } ) as IWorkbook;
...
_SheetCount = wb.Count;
...
|
|
|
|
|
Thank you very much fof your suggestion
|
|
|
|
|
|
Hello,
my problem is to fill a DataGrid in WPF C# Framework 4.0.
Code DataGrid.xaml:
<Grid>
<DataGrid ItemsSource="{Binding}" AutoGenerateColumns="True" HorizontalAlignment="Stretch" Margin="0,0,2,2" Name="dataGrid1" VerticalAlignment="Stretch" />
</Grid>
Code Page.cs :
public Page2()
{
InitializeComponent();
FillTable();
}
public class Lagerteile
{
public int ID { get; set; }
public DateTime Liefertermin { get; set; }
public string WANr { get; set; }
public string Name { get; set; }
public int Stk { get; set; }
public string Kunde { get; set; }
public string Pos { get; set; }
}
public void FillTable() {
string cs = "Driver={PostgreSQL Unicode};" +
"Server=localhost;" +
"Database=***;" +
"Uid=***;" +
"Pwd=***;";
string query = "SELECT *FROM xxxx";
OdbcConnection cn = null;
try
{
cn = new OdbcConnection(cs);
DataContext context = new DataContext(cn);
this.dataGrid1.DataContext = new ObservableCollection<Lagerteile>(
context.ExecuteQuery<Lagerteile>(query));
}
catch (Exception ex)
{
System.Windows.Forms.MessageBox.Show(ex.Message);
}
if (cn.State == ConnectionState.Open)
{
cn.Close();
cn.Dispose();
}
}
The Database is PostgreSQL 9.4. General it works but it took about 4 seconds to load 100 rows and only 1 second more for 15.000 rows. Is there any possibilty to speed this up ?
|
|
|
|
|
In WinForms (which this clearly isn't) you'd go for a virtual datagridview if the binding is too slow.
WPF might have something similar
Bastard Programmer from Hell
If you can't read my code, try converting it here[^]
|
|
|
|
|