|
If you're getting a runtime exception, then it's probably because the object actually isn't of the right type. The exception message should tell you what it is and what it's trying to cast it to.
|
|
|
|
|
hi ,
yes , that's the case , I was searching for a way to solve this at runtime. anyway I got a clue a from Simon_Whale.
thanks.
|
|
|
|
|
Hi, I am a Qt C++ programmer and wish to build a Windows 8 flow chart style app where I can create rectangular rich text boxes, polygon shapes, and link any of these elements with lines and/or arrows etc.
The issue I'm having is not drawing these elements to the screen but rather working out the correct components to use in C#. For example, in the C++ Qt framework there is a concept of a QGraphicsView, a QGraphicsScene, and QGraphicsItems. The QGraphicsView acts somewhat like a C# viewport; however, I can't find anything equivalent to a QGraphicsScene in C#. A QGraphicsScene acts like a model and keeps track of all QGraphicItem elements drawn onto it (i.e. it is the parent to all these all child objects drawn onto it). It keeps track of things like collision detection and makes it very easy to enumerate over it's collection of items. QGraphicItems', too, can parent other QGraphicItems - making nesting of objects very easy to manage.
Is there anything like this in C# that I'm missing. For example, if I draw two Rich Text Boxes and then drag a line between them to link the boxes (with dozens of other Rich Text Boxes around them that I'm not linking to), how do I keep track of and detect which boxes the dragged line relates to, and do so efficiently?
Appreciate any guidance here. Thanks.
Lee
modified 31-Oct-12 1:39am.
|
|
|
|
|
Unfortunately, this functionality isn't built into .NET, but it is relatively straightforward to implement. If I were doing this, I would look to create a SceneManager class which was responsible for managing the child items. In other words, it would create the item and maintain them in some form of collection. For example:
public sealed class SceneManager
{
private List<SceneItem> children = new List<SceneItem>();
public T AddVisual<T>(T visual) where T : SceneItem
{
children.Add(visual);
}
} I would then wrap the RichTextBox and polygons up into somethnig that can be added to the list, and which knows how to position and draw itself. This wouuld then enable you to add a single point of entry to allow you to draw the scene. It would look something like this in the SceneManager class.
public void Draw()
{
foreach(SceneItem child in children)
{
child.Draw();
}
} Obviously this is all very simplistic, but it should serve to give you some idea of how to implement it. The point is - this class and the classes for the items you are going to draw on the screen simply contain the data that is needed to draw the items. By changing the data, you can change the underlying elements. Suppose, for instance, that you had a method called Offset that you wanted to use to move the children by a certain amount. It simply becomes a case of doing this:
public void Offset(int x, int y)
{
foreach (SceneItem child in children)
{
child.Top += x;
child.Left += y;
child.Draw();
}
}
|
|
|
|
|
Every so often I got a deserialization exception from my multi-threaded client/server app while attempting to read from NetworkStream - after digging around for sometime, with the help from Paulo (accidentally deleted prev thread, so this is fyi only), I found out that it's a sync issue.
From MSDN:[^]
Read and write operations can be performed simultaneously on an instance of the NetworkStream class without the need for synchronization. As long as there is one unique thread for the write operations and one unique thread for the read operations, there will be no cross-interference between read and write threads and no synchronization is required.
I just put a lock around NetworkStream.Read/Write and the problem goes away.
dev
|
|
|
|
|
Hooray, I can define an array of bytes and send it/them out the serial port; in proper order, proper speed, and everything. Thanks Dave and Gerry.
Anyway, I would imagine that this question has been answered several times before, but I couldn't figure out how to search for it.
I want to allow several different methods to use the same serial port; preferably by the same name.
What I'm observing is that opening a serial port in one method restricts the access (to that port) to that one method.
My previous knowledge and experience was on the order of, set up N-8-1, set up the speed, and then just stick in the bits when there's a space in the FIFO buffer.
Clearly, I have a few things to learn with C#
How do I do something like this...
SerialPort OurChosenSerialPort = new
SerialPort(
ThePortName,
OurChosenSerialPortSpeed,
Parity.None,
8,
StopBits.One
)
;
...and then let another method elsewhere use OurChosenSerialPort for sending and receiving ?
I know for a fact that I will be using that same port to receive a lot of data (a lot; barrels of the stuff) and I don't want to have to open the port each time; indeed, I don't think I can, logistically.
|
|
|
|
|
You've defined this as a method level variable. If you change it to a member variable then all the methods in your class will have access to it. Be aware, though, that you will have to manage synchronising access to the device yourself. In order to define the member variable, just use
SerialPort OurChosenSerialPort; Then, in your instantiation code, you can call
OurChosenSerialPort = new SerialPort(ThePortName, OurChosenSerialPortSpeed,
Parity.None, 0, StopBits.One);
|
|
|
|
|
From your code snippet it appears that "OurChosenSerialPort" is a varialbe local to the function that opens it. If that's the case, only that function can use it. I would suggest making a member variable so that other functions in that class can use it.
I suggest you create a class for your serial port communication, giving it methods such as Open(..), Close(), Send(string message), etc.
I haven't seen the post where Dave and Gerry helped, so maybe you've already done that.
BDF
I often make very large prints from unexposed film, and every one of them turns out to be a picture of myself as I once dreamed I would be.
-- BillWoodruff
|
|
|
|
|
Big Daddy Farang wrote: I haven't seen the post where Dave and Gerry helped, so maybe you've already done that.
I was having fits getting the elementary step of sending one byte out the serial port; the kind where the boss wonders if he hired the right guy.
Turned out that Windows was lying to me; reporting the name of a non-existent port, like this
string[] The_List_Of_ComPorts = SerialPort.GetPortNames();
There were members of The_List_Of_ComPorts which did not exist on the machine.
|
|
|
|
|
Big Daddy Farang wrote: From your code snippet it appears that "OurChosenSerialPort" is a varialbe local to the function that opens it. If that's the case, only that function can use it. I would suggest making a member variable so that other functions in that class can use it.
Perceptive, Big Daddy; I think the Australians say "Spot On !"
I am just now learning about member variables. My "fix", not sure how smart this is, is to do something like this.
First off, I'm slightly foggy on how this happened, but this thing just appeared in my source code; generated by whom, not totally sure...
public partial class Form1 : Form
{
So, making a guess, I put these lines just inside that curly brace...
public const int OurChosenSerialPortSpeed = 115200;
public const int OurChosenNumberOfDataBits = 8;
public const int SomeIntegerXyzz = 65537;
public string ThePortName;
public SerialPort The_Port_We_Are_Using;
Then in my method that opens the serial port, I did this
SerialPort OurChosenSerialPort = new
SerialPort(
ThePortName,
OurChosenSerialPortSpeed,
Parity.None,
OurChosenNumberOfDataBits,
StopBits.One
)
;
OurChosenSerialPort.Open
The_Port_We_Are_Using = OurChosenSerialPort;
();
Pointers and clues about member variables are welcome
Please pardon my current shallow level of understanding; as this is my first C# project (I'm from embedded systems, single tasking with a dozen competing interrupts, state machine type of stuff with supervisor-sorts of central dispatch routines) but from 30 seconds of reflection on your comment, I can pretty much infer that your class and method idea is way superior to my grab-and-go thinking.
I welcome your suggestions on this.
Oh, for context; I'll be receiving packs of 24-bit signed integers, twenty times over, at a speed of 256 Hz, which I think is doable on the system we have in mind. I will be receiving a continual stream of packs of data which are 64 bytes each (twenty individual 3-byte values plus a 4-byte protocol header).
Each of these points will then be immediately turned into a number which will be then be interpolated into a position on an individual moving graph (there will be 20 such graphs, and they must all move in synch).
It's an interesting project; I'm honestly enjoying it.
The attempt at organizing the individual syntax appears to be the major barrier to entry.
Whatever, whatever, thank you for your suggestion. I'd like to read more of your ideas (and ideas from others who have done this sort of thing).
|
|
|
|
|
Here's some sample code that might help. I've removed most of the stuff, but left some to give you some ideas. I used this in its original form to communicate with a device, a bit different from what you're doing in terms of amount of traffic.
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.IO.Ports;
namespace YourNameHere
{
class Device
{
private SerialPort Port;
private const int BufferSize = 256;
private char[] ReadBuffer;
private string LastResponse;
public Device(string CommPort)
{
if (CommPort.IndexOf("COM", StringComparison.CurrentCultureIgnoreCase) < 0)
{
throw new ArgumentException("Argument must be of the form \"COMn\"", "CommPort");
}
Port = new SerialPort(CommPort, 9600, Parity.None, 8, StopBits.One);
Port.RtsEnable = true;
Port.DtrEnable = true;
Port.ReadTimeout = 500;
Port.WriteTimeout = 500;
Port.Open();
Port.DiscardInBuffer();
ReadBuffer = new char[BufferSize];
}
public string GetLastResponse()
{
return LastResponse;
}
public bool Connect()
{
Send("");
LastResponse = Receive();
if (LastResponse == "!>")
{
return true;
}
else
{
return false;
}
}
public bool SetLoad(int Load)
{
string digits;
if (Load < 10 || Load > 5200)
{
throw new ArgumentOutOfRangeException("Load", "Must be between 10 and 5200");
}
digits = ResistanceTable(Load);
Send("L" + digits);
LastResponse = Receive();
if (LastResponse == "!>")
{
return true;
}
else
{
return false;
}
}
public bool StartMeasuring()
{
Send("S");
LastResponse = Receive();
if (LastResponse == "!>")
{
return true;
}
else
{
return false;
}
}
public bool StopMeasuring()
{
Send("E");
LastResponse = Receive();
if (LastResponse == "!>")
{
return true;
}
else
{
return false;
}
}
public void Send(string Command)
{
if (Port.IsOpen)
{
char[] buffer = Command.ToCharArray();
Port.Write(buffer, 0, buffer.Length);
Port.Write(new char[] { (char)0x0D }, 0, 1);
}
}
public string Receive()
{
const int delay = 75;
int received = 0;
char ch;
StringBuilder result = new StringBuilder();
if (Port.IsOpen)
{
System.Threading.Thread.Sleep(delay);
try
{
received = Port.Read(ReadBuffer, 0, BufferSize);
}
catch (TimeoutException)
{
result.Append("Error.");
}
if (received > 0)
{
for (int loop = 0; loop < received; loop++)
{
ch = ReadBuffer[loop];
if (ch >= ' ' && ch <= '~')
{
result.Append(ch);
}
}
}
}
else
{
result.Append("Not open.");
}
return result.ToString();
}
public void Close()
{
if (Port.IsOpen)
{
Port.Close();
}
}
}
}
BDF
I often make very large prints from unexposed film, and every one of them turns out to be a picture of myself as I once dreamed I would be.
-- BillWoodruff
|
|
|
|
|
Big Daddy Farang wrote: class Device
{
private SerialPort Port;
private const int BufferSize = 256;
private char[] ReadBuffer;
private string LastResponse;
public Device(string CommPort)
When, and what things, do I want "private" and "public" ?
For that matter, just exactly what do those words mean ?
Am I headed in the right direction via reading stuff like this page ?...
http://msdn.microsoft.com/en-us/library/ms173121(v=VS.80).aspx
"...Access modifiers are keywords added to the class, struct, or member declaration to specify these restrictions. Those keywords are public, private, protected, and internal. For example:..."
|
|
|
|
|
If you mark something as private, it cannot be seen outside the class. If you mark something as public, you are telling the compiler that this item can be used from outside the class.
|
|
|
|
|
Pete O'Hanlon wrote: If you mark something as public, you are telling the compiler that this item can be used from outside the class.
That is where I am turbo-confused.
I just did exactly that; Marked some stuff (byte arrays, nothing but some bytes that don't mean anything to anyone except my little Barn Door Box) "public" in a class in another file, and the method in the first file does not know they exist. He gives me an error "...The name So_And_So does not exist in the current context..."
So now I need to learn/guess the definition of the word "context" in the mind of the developers of C#, and then learn how to make the name "exist" (whatever that has transmuted to mean in C#).
|
|
|
|
|
Let me start with the meanings. As Pete said, private variables or functions can only be used from within the class. Public variables or functions can be used from outside the class. For example, from another class such as your main form you could do the following.
Device device = new Device("COM1");
device.Connect();
because the constructor and Connect() are public. If you're interested in the device's response to connect command you'd want to see LastResponse. If you try
string connectResponse = device.LastRepsonse;
that's not allowed because LastRepsonse is private. You could however write
string connectResponse = device.GetLastResponse();
because that function is public.
What you want private and pubic is up to you, but basically data that should not be changed by outsiders should be private. Things that should be available to users of your class need to be public.
When deciding which ask, "Who wants to know?" Things are private by default, but if users should have access to them make them public. If we made Port public, users could close the serial port and the Device object wouldn't know about it, so that should be kept private.
As far as MSDN goes, yes that's a good reference. But it is designed to be a reference more than an instructional work. You might consider visiting your local bookstore (or online of course) and looking at books that teach C# programming. That depends on your learning style, some people can do fine with reference materials. Given your background you might do well with just reference materials.
BDF
I often make very large prints from unexposed film, and every one of them turns out to be a picture of myself as I once dreamed I would be.
-- BillWoodruff
|
|
|
|
|
I tried to declare this public in one method...
public string ThePortName = "";
...but then no other method could see it.
When I moved it way up to the top along with the first ints just after the class was named, like this...
public partial class Form1 : Form
{
:
:
:
public string ThePortName;
:
public Form1()
{
...then everybody could see it.
There is, as I understand it, only one class in this practice app; so there are probably things that I need to increase in my understanding about this.
Again, NewBee NoClue here, flying high.
|
|
|
|
|
Just curious, If I declare a class as public, and within that class, I declare a...
-- Serial Port
-- Integer
-- Method
-- Whatever
...as also being public, then will other methods in other classes be able to use the Serial Port / Integer / Method / whatever ?
|
|
|
|
|
Yes, those will be visible to other classes that instantiate the object you are using.
I too was a long time embedded programmer who jumped into PC development. I also am using serial ports HEAVILY in .NET.
A suggestion for you:
Abstractions are a good thing. For example, I have a wireless device that uses 900MHz to communicate. This device has a companion (Aerocomm antenna) that attaches to a PC through a serial port. So, instead of accessing serial ports through out my software, I encapsulated the functionality into one class (object). So, the Aerocomm antenna class has all the stuff for the serial port contained within it. It exposes functions to other classes in order to communicate with the Aerocomm antenna - like configuring it, setting what device to communicate with, set it into broadcast mode, etc.
In your case, you are communicating with a device. I would create a class that represents the device. Then, create functions within the class that will get abstracted data from the device. So, for example, say you want to get the version number of the device. You would have a function in your class like:
string GetVersionNumber()
{
// Code to get the version number from the device, including the serial port commands, etc.
}
This function could also possibly be a property as well, but it would still have functional code in it.
Basic idea is to keep the accesses and functionality where it needs to be. This is a fundamental idea behind object-oriented programming.
Oh and one other thing - USB-Serial devices can cause exceptions when pulled out of a computer while the serial port is open. You will need to be aware of that and handle that as well.
Good luck!
|
|
|
|
|
David Knechtges wrote: "...instantiate the object you are using...."
Terribly sorry about my frozen brain cells, but just exactly what does "instantiate" mean ?
Also, the word "object" comes up again.
What I'm going to be doing is communicating with this external embedded system; normally with BlueTooth, and
-- drawing a lot of little wiggly lines on the user's screen
-- putting some blips on the screen (think of it as virtual LEDs)
-- watching for button clicks by the user
-- De-Confusing itself when noise appears on the serial port
|
|
|
|
|
What you the programmer write is a Class. Form1, Device in my earlier example, etc. are classes. When you "instantiate" an object, it means you are creating an instance of a class.
int count;
Device device;
device = = new Device("COM1");
BDF
I often make very large prints from unexposed film, and every one of them turns out to be a picture of myself as I once dreamed I would be.
-- BillWoodruff
|
|
|
|
|
Okay, so it's...
[1] Declare
[2] Instantiate
[3] Use it
Am I thinking properly ?
I'm still having trouble getting the linker to let my methods in one file see names that are declared and (I hope I'm getting the nomenclature correct) instantiated in another file.
e.g.,
My method for sending a group of bytes cannot see the name of those bytes unles they are in the same source file; which absolutely destroys any hope of having a manageable arrangement of source files.
|
|
|
|
|
David Knechtges wrote: Oh and one other thing - USB-Serial devices can cause exceptions when pulled out of a computer while the serial port is open. You will need to be aware of that and handle that as well.
Good thinking.
My mind immediately reverts to what has worked excellently for years; "Include" files.
Do they work in C# like they do with (many of, most of, almost all) embedded systems assembly language development systems ?
e.g., for ease of reading, and for code organization, the sub-sections are Included; I'm thinking like Macros and constant definitions, but I suppose that code can also be included.
I just searched for "C#, #Include" here on codeproject.com and barely understood the hits I got. Suggestions welcome.
Do I just give every source file the same Namespace, and make the all the classes within the namespace public ?
By the way, is the process the same here as elsewhere ? e.g., write then compile then link then execute ?
|
|
|
|
|
C# does not #include header files the way C and C++ do. Everything that's part of a class is (usually) in one file. You've already seen "partial" class that Visual Studio uses to separate forms into the file you edit, Form1.cs for example and the file it edits, Form1.designer.cs in this case.
For simpler programs, and to get started, I'd stick with using the same namespace throughout. Same with making classes public. There are reasons to use different namespaces and possibly classes that are not public, but let's not worry about that yet.
The build process is basically the same. Your various .cs file get compiled into .obj files and then all of those objects get linked into an executable (.exe) file. And if all goes well you execute it. Using Visual Studio the compliling and linking usually happens as a result of pressing F6 (see the Build menu.)
BDF
I often make very large prints from unexposed film, and every one of them turns out to be a picture of myself as I once dreamed I would be.
-- BillWoodruff
|
|
|
|
|
Thank you; you are helping me tremendously.
The Build/Build keystroke has become my friend; the best critic my code has.
Sortta'kinda like "Find the most egregious errors, please".
|
|
|
|
|
David Knechtges wrote: Then, create functions within the class that will get abstracted data from the device. Are the words "function" and "method" the same thing ?
|
|
|
|
|