|
|
Thank you. This stuff is relevant to my interests !
|
|
|
|
|
I have found the paper very helpful. It has been updated a few time, especially with TPL. Sort of got back to it after reading up on TPL in Task Parallel Library: 1 of n[^]
|
|
|
|
|
hi ,
I got an object which is a generic, at runtime i pass the type for T and create the proper object. the generic object as follows
class parent <T>
{
string name;
T childObject;
}
I create the parent<x> in runtime using the reflection , for e.g.
Type type = x;
Dynamic response = Activator.CreateInstance(typeof(parent<>).MakeGenericType(type));
it works fine , but the problem is when I try to assign an object to response.childObject it gives me an exception saying that i'm missing cast and it cannot implicitly cast the object.
the object try to assign is also created using reflection,
ADDED LATER: I'm not sure this part will be important for this issue , but anyway , the object i'm trying to assign to response.childObject is also an object created by deserialization , means
for in order to deserialize this object i have to give the type , so that type also crated using reflection in a similar way described above.
i would really appreciate your help on this.
thanks in advance.
modified 31-Oct-12 12:43pm.
|
|
|
|
|
I dont know how it actual works if I am honest (as I found the question interesting) but my modifying your code to this
Type t = typeof(Parent<>);
int y = 1234;
Type type = y.GetType();
dynamic response = Activator.CreateInstance(t.MakeGenericType(type));
response.MyValue = 123;
public class Parent<T>
{
public string name = string.Empty;
public T MyValue;
}
I was able to assign a value to the property MyValue.
*Edit* Not sure if it helps but I've just read through this MSDN article on Type.MakeGenericType[^], I found this an interesting Question
Lobster Thermidor aux crevettes with a Mornay sauce, served in a Provençale manner with shallots and aubergines, garnished with truffle pate, brandy and a fried egg on top and Spam - Monty Python Spam Sketch
|
|
|
|
|
thanks , I also tried the value types and it works , but the problem came when i'm trying to assign reference type.
|
|
|
|
|
Type t = typeof(Parent<>);
Type type = typeof(Data);
dynamic response = Activator.CreateInstance(t.MakeGenericType(type));
Data es = new Data() { Name = "Fred", value = 213 };
response.value = es;
public class Parent<T>
{
public string name = string.Empty;
public T value;
}
public class Data
{
public string Name = string.Empty;
public int value = 0;
}
I have also tried it with the following and it still works can you expand your problem with some sample code? or a snippet?
Lobster Thermidor aux crevettes with a Mornay sauce, served in a Provençale manner with shallots and aubergines, garnished with truffle pate, brandy and a fried egg on top and Spam - Monty Python Spam Sketch
|
|
|
|
|
Thanks again , ok then I think I have to focus on the deserialzed object , unfortunately i haven't got the code snippet right now , but I will definitely post that code snippet soon.
thanks .
|
|
|
|
|
Your welcome
Lobster Thermidor aux crevettes with a Mornay sauce, served in a Provençale manner with shallots and aubergines, garnished with truffle pate, brandy and a fried egg on top and Spam - Monty Python Spam Sketch
|
|
|
|
|
hi ,
this is how i'm doing the deserialization
Type genericSyncObj = typeof(SyncObject<>);
Type syncObj = genericSyncObj.MakeGenericType(type);
IList customObjectList = (IList)Activator.CreateInstance((typeof(List<>).MakeGenericType(type)));
foreach (string value in pullRequest.Knowledge)
{
dynamic syncObject = JasonSerializer.Deserialize(value, syncObj, null);
customObjectList.Add(syncObject.Object);
}
and i'm getting the exception at here
dynamic responseSync = Activator.CreateInstance(typeof(SyncObject<>).MakeGenericType(type));
responseSync.Object = customObjectList[y] ;
thanks .
|
|
|
|
|
The problem is that customObject[y] is returned as an object which is why it fails.
if you then hard code a cast such as for example.
responseSync.Object = (SomeTestClass)customObject[y];
it works as you need it to do, but how to create this as a generic routine I'm not sure at the moment as (typeof(SomeTestClass))customObject[y] or even (typeof(SomeTestClass))CustomObject[y] is rejected by the compiler.
Lobster Thermidor aux crevettes with a Mornay sauce, served in a Provençale manner with shallots and aubergines, garnished with truffle pate, brandy and a fried egg on top and Spam - Monty Python Spam Sketch
|
|
|
|
|
thanks , yes this is the place where i'm stuck , need to cast in runtime , if you find a way please share it .
|
|
|
|
|
IList datalist = (IList)Activator.CreateInstance(typeof(List<>).MakeGenericType(typeof(Data)));
datalist.Add(new Data {Name = "SIMON", value = 1});
datalist.Add(new Data {Name = "SIMON", value = 2});
datalist.Add(new Data {Name = "SIMON", value = 3});
Type t = typeof(Parent<>);
Type type = typeof(Data);
dynamic response = Activator.CreateInstance(t.MakeGenericType(type));
Type SingleRecordType = datalist[0].GetType();
dynamic Destination = Activator.CreateInstance(SingleRecordType);
Desintation = datalist[0];
response.value = Desintation;
have a look at this. it is a bit of a work around converting the list item from object to a specific type at runtime.
Thanks
Simon
**edit** missed a GetType()
Lobster Thermidor aux crevettes with a Mornay sauce, served in a Provençale manner with shallots and aubergines, garnished with truffle pate, brandy and a fried egg on top and Spam - Monty Python Spam Sketch
modified 1-Nov-12 11:24am.
|
|
|
|
|
hi
thanks it seems to be working, though it is a workaround . thanks for the clue .
** yes i noticed that and i fixed it by calling the GetType()
thanks.
|
|
|
|
|
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
|
|
|
|
|