I am building a C# (.NET 4.5) generic "telegram" - for lack of a better word - that communicates between a plc and a regular pc using tcp and JSON, especially JSON.NET. I have a tcp server set up and working, and I can create Json strings out of objects, which can then be passed on. So I am left with defining a standard way to pass information, commands and events back and forth. What I am now struggling with is how to easily format the "payload". I have a JsonTelegram class with a dynamic variable called "payload" - more or less this:
private dynamic _payload;
public dynamic payload
{
get
{
return _payload;
}
set
{
_payload = value;
updateContents();
}
}
So if I update this variable like this:
myTelegram.payload = rampTime;
I would like to see the final JSON be this:
{
"purpose": "Update this variable",
"payload": {
"rampTime": 2000
},
"timeStamp": "2000-01-01T00:00:00.000-00:00",
"returnID": "2000-01-01T00:00:00.000-00:00"
}
It is the payload part that I am really struggling with, because that code there will end up looking like this:
{
"purpose": "Update this variable",
"payload": 2000,
"timeStamp": "2000-01-01T00:00:00.000-00:00",
"returnID": "2000-01-01T00:00:00.000-00:00"
}
when updateContents() uses this:
... Newtonsoft.Json.JsonConvert.SerializeObject(_payload) ...
Do you see how the word "ramp" gets replaced with "payload"? I know I could just make a method and pass both the object and the name of the object - this would definitely work. But I would like to get trickier than that, just because it should be possible, and also because down the road I can see some other reasons that this design may work better. I want the code to simply know the name of the variable that called it and use that. I have seen many suggestions using some stuff I barely understand, but when I try to adapt it, it seems to get hung up on one issue or another. So I thought I would ask a fresh question, because surely many people want to do the same thing with JSON and the new dynamics?
StackOverflow has information on attributes and dictionaries, reflection, something to do with t, expressions, and so on. For instance, this question: How do you get a variable's name as it was physically typed in its declaration? and this Finding the variable name passed to a function
I don't mind making the class code as messy and hacky as all get out, but I want the calling code to be as clean as "myTelegram.payload = rampTime;"
I'm sorry that I can't wade through all the suggestions well enough - I spend most of my time writing plc code, and just now have a plc that one side does C#.
Also, if there is simply a more elegant way to do things that is totally different, I am eager to hear it.
Thanks!