Serializing Events into JSON [closed] - c#

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I am working on a serialization system using Json, but I need to save events from Buttons (onClick, onHover, etc.) Is there a way about doing this efficiently? (NOTE: The events are all Actions)

Frankly, it is is terrible idea to try to serialize events.
JSON is usually used to serialize data; events are not data - they are implementation details. Most JSON serializers (or more broadly: most serializers) are not interested in delegates / events, because that isn't relevant to data, so: there's a good chance that anything you'd want to do here will need to be manual. Specifically, the problem here is that an event (or rather, the underlying multicast delegate) is effectively zero, one, or multiple pairs of "instance" (optional) and "method" (required).
The method here is a MethodInfo, and there aren't great ways to serialize a MethodInfo as text (although it is at least theoretically possible, although it would be very brittle vs changes to your code.
The instance, however, is an object - and most serializers hate that; in this case, it would combine object (reference) tracking, possibly of objects not otherwise inside the payload, of indeterminate types (so: possibly needing to store type metadata).
Also, deserializing an object model that allows you to point to arbitrary types and methods is a massive security hole, and is a well-known RCE weakness in serializers that (unwisely, IMO) allow this kind of thing (such as BinaryFormatter; for a longer discussion of this topic, see here).
As for what to do instead: whenever an implementation isn't a great fit for a given serializer, the most pragmatic option is to stop fighting the serializer, and work with it instead of against it. For example, it might be that you can create a model that looks kinda like your domain model, but instead of having events/delegates, it might just have a string[] / List<string> that represents the events you need to apply, and your code would worry about how to map between them (mapping methods to strings, and figuring out what the target instance should be, etc). This avoids all of the pain points above, and additionally means that your data is now platform independent, with the payload and the implementation details (your form layout) separate from each-other.

Related

Is protobuf a good choice of the universal data model? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 11 months ago.
Improve this question
We are trying to find a universal data model, which can be applied everywhere.
I think there is no doubt that protobuf is good in the microservice architecture as a protocol among processes of different platforms (Windows, Linux, etc.) and languages (Java, C#, C++, Python, etc.)
But how about using protobuf within the process?
To make it simple and easy to illustrate the problems, let say I am making a C# gRPC service and GUI (gRPC client).
After some study, it seems that it is not suitable from what I can see.
Stability: It looks like that protobuf is still in a changing phase. For example, removing Optional keyword in proto3, but adding it back again in proto release 3.15.
Data type: The data types in proto are not fully compatible with common data types. For example, decimal. We need to define another complex data type (What's the best way to represent System.Decimal in Protocol Buffers?) and doing the conversion.
Conversion: We need conversion before we can utilize it in the related language. You cannot add the self-defined proto decimal directly in c#.
Repeated conversion: Conversion is not one off, but back and forth. Let say we have this proto object passing through 5 functions and need to have some calculations on the decimal field at each function. That means, we will need to convert the decimal field in the proto object to C# decimal in each function, have the calculation to get the result, convert and assign the result back to the decimal field in the proto object, then pass the proto object to the next function.
GUI control binding: We cannot bind the proto field (for those without an matched type in C#). Even we can specify the conversion to do so in the control somehow, (Indeed, I am not sure if we can/it is good to do so) in simple control, like textbox. It may not be easy for complicated control like datagridview because there may be different built-in editors for different native data types. If we use proto data types, that means we need to write customized editors for them. And also, we may need to define other behaviors, like how to sort them.
Using the auto-generated proto class within the process seems not a good idea to me as the reasons listed above. The above case only focus on C# service and client. When it comes to different languages, the cases should be more complicated.
Although .net soap services are slow and wordy (if you look at the wsdl definition), one thing I appreciate very much is that both the service and the client are using the same object with native data types, which can be used directly without any issue. The conversion is done in the communication directly and automatically.
The way I can think of at the moment is that:
Using proto as a communication protocol only
Write a class (use native/built-in data types) for each proto message type and our own conversion logic. Doing so because I cannot find any framework/lib to do so.
After receiving the proto object, convert it directly to an object with native/built-in types before further processing. (the benefit here is that even there is a major change in proto spec, we only need to change the conversion logic only without affecting other layers).
Am I on the right track? What is common/best practice to resolve the problems listed above?
Any help is highly appreciated!!!

Json serialization and storage strategy [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
Json is often used in web applications. I set a field in the database to text to store json strings. It may not be a good idea to design a database in this way, but my reason is that the composition of the data may be volatile and does not require external connections. Using Json serialization tools such as Newtonsoft can easily de-serialize a json string from a database into a JObject object, but in a static language program, it will definitely require some more concrete objects to express it, and now I'm facing some Optional options:
De-serialize the json string from the database to get JObject, then
use this object directly
continue to resolve JObject, instantiate a more specific object A, and then use the object A
Option 1 is very convenient for storage and initialization of the read, but when used to get the value string, error-prone. Scenario 2 requires an extra layer of conversion for storing and initializing reads, but it is more intuitive and convenient to use. I am very tangled about which scheme to use.
"More intuitive and convenient to use" is the key here. You should always try to write code in a readable and maintainable way, and if creating model objects for your JSON data helps you achieve this goal, and this doesn't impact performance beyond what's acceptable for your project, do it; the extra conversion layer will be worth it.
Unless there is a reason that you cannot, I would have a concrete dto that your JSON can be de-serialised into. This provides you compile time type safety for all usages (at least after the initial instantiating). I would normally go another step and have a business object class that can instantiate itself from that dto, but that obviously depends on your specific requirements.
On top of type safety, you get a whole bunch more benefits when using a concrete object, but I suspect that at this point I'm preaching to the choir.
One reason you may not be able to is where the content itself is dynamic in nature (and by extension your code expects nothing specific about the JSON string other than maybe that it is well formed). Very few problems are like this though.
So the downside is usually the overhead of the time and effort in writing those concrete classes. Once you have them defined, deserialising them is literally 1 line of code. The trick then is to use a tool to reverse engineer the necessary classes from the JSON string. Due to SO policies, I cannot recommend tools, but if you were to use a search engine that rhymes with frugal and search for something like JSON to c#, you are bound to find a quick way to create those dtos.

The best way to pass values between classes in C# [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
First case:
If I have a set/get method for a value inside the class A, I can
set that value from the class B and use it inside A.
Second case:
I can just pass the value in a traditional way like Method(value);
Please, explain me which way is better.
I appreciate your answers.
Properties (what you call the set/get method) are essentially a "syntax sugar" on top of regular C# methods. There will be no performance difference between using properties and using regular methods.
Generally, though, you should prefer properties to methods for readability, i.e. when they present an appropriate semantics to the readers of your class.
Setters and Getters should be used for general properties of classes, used across several methods.
A parameter to a method call is appropriate for a variable tied to that one method (though possibly stored and used elsewhere, for instance if it is part of initialisation).
As always, do what looks best and works well in your context. If the using code feels awkward, look for another way. If it feels right, it's probably OK.
The goal of Object oriented programming is to have your data and operations together.
The goal is to reduce coupling between different kinds of objects so that we can re use the classes.
Never expose the data inside the class to the outside world but provide interfaces to do so

Can anyone please explain events in a way that I can understand? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
I have been programming for about 2 months now and I'm self-learned, while I get the basics about inheritance, polymorphism, interfaces, delegates, data & reference types, loops, if/switch, LINQ, xml, SQL, etc etc. I just cannot wrap my head around events!
I have read at least 4-5 different tutorials and writeups online but they are way too confusing to me, there's an Event type, EventHandler, delegates, event raise/subscribe, there's just too much stuff going on and, I don't know if I'm thickheaded or not but it's INCREDIBLY confusing for me.
Please explain events to me in a way that a complete beginner programmer like me can understand, many thanks!
Action and reaction.
As John said in your comments.. "When I click a button, something happens!"
It doesn't get much simpler than this:
http://en.wikipedia.org/wiki/Observer_pattern
At their core event simply contain a list of functions (or at least a way to access these functions) which will be called the event is raised. Raising an event is simply the act of triggering the subject to notify all the functions which are subscribed (read: contained in the list) to that event.
How this list of subscriptions is comprised varies greatly depending on the capabilities of the framework. In the observer pattern (commonly used in Java) you do this by passing in an object that has implemented the appropriate interface. The subject iterates through the list of observers and call the function defined by the interface. The drawback to this pattern is that you have to have the potential for a naming collision between two entirely different subjects which can be difficult (though not impossible) to work around.
Delegates remedy this issue by allowing you to pass in the function or method itself. A delegate is sort of like an interface in that it establishes a contract but instead of class members it just specifies a set of parameters for a function. The subject can then iterate through a list of these methods, which are commonly referred to as event handlers, and pass the appropriate parameters. Delegates are less troublesome than an observer pattern but they can still be time consuming.
More recently C# added the generic delegates Action and Func which are a bit easier to work with.

Why anonymous types aren't dynamic as the ExpandoObject? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
With dynamic we pretty much have a dynamic pointer, but not exactly a dynamic object. The true dynamic object in C# is the ExpandoObject, but that is a really unknown class for most of people. The expando allows creating and removing members at runtime, much like a hash (similar to JavaScript).
Why the ExpandoObject goodness was implemented in a separate class rather than just being, let's say, implemented as a feature of anonymous types?
Maybe that wouldn't be a good move because the lacking of type-safety? Or maybe due the (DLR) overhead involved?
Because anonymous types have other very important feature - they provide you compile time type safety.
And because dynamic and anonymous types are just different concepts. The first one gives you ability to dispatch object members at runtime, the second lets you create statically typed objects with some base functionality (equality, hashcode, etc) without creating corresponding POCO classes. Why should they be implemented in the same way then?
btw. I use them quite a lot and really rarely needed to use dynamic to deal with them. Are you sure you're using these language features correctly?
Update
I think that's very important part of anonymous types tutorial:
If you must store query results or pass them outside the method boundary, consider using an ordinary named struct or class instead of an anonymous type.

Categories