Command pattern and complex operations in C# - c#

I am writing a program in C# that needs to support undo/redo. For this purpose, I settled on the Command pattern; tldr, every operation that manipulates the document state must be performed by a Command object that knows about the previous state of the document as well as the changes that need to be made, and is capable of doing/undoing itself.
It works fine for simple operations, but I now have an operation that affects several parts of the document at once. Likewise, the Command object must be smart enough to know all the old state it needs to preserve in case it needs to be undone.
The problem is exposing all that state using public interfaces has the potential for misuse if someone attempts to call the interface directly, which can lead to state corruption. My insticts tell me the most OO way of doing this is to expose specialized Command classes -- rather than allowing you to directly manipulate the state of the document, all you can do is ask the document to create a Command object which has access to its internal state and is guaranteed to know enough to properly support undo/redo.
Unfortunately, C# doesn't support the concept of friends, so I can't create a Command class that has access to document internals. Is there a way to expose the private members of the document class to another class, or is there some other way to do what I need without having to expose a lot of document internals?

It depends, if you are deploying a library your Document could declare 'internal' methods to interact with it's internal state, these methods would be used by you Command class, internal methods are limited to the assembly they are compiled.
Or you could nest a private class to your Document, that way allowing it to access Document's internal state and expose a public interface to it, your Document would then create a command class hidden by that interface.

First, C# has the internal keyword that declares "friend" accessibility, which allows public access from within the entire assembly.
Second, the "friend" accessibility can be extended to a second assembly with an assembly attribute, InternalsVisibleTo, so that you could create a second project for your commands, and yet the internals of the document will stay internal.
Alternatively, if your command objects are nested inside the document class, then they will have access to all its private members.
Finally, complex commands could also simply clone the document before making changes. That is an easy solution, albeit not very optimized.

You could always access fields and properties, private or not, through reflection (Type.GetField(string, BindingFlags.Private) & friends).
Maybe with a custom attribute on the class (or the field/property) to automate the process of grabbing enough state for each Command?

Instead of having a command doing changes at different places of the document, you could have two dummy commands that mark the start and end of multi-step operations. Let us call them BeginCommand and EndCommand. First, you push the BeginCommand on the undo-stack, and then you perform the different steps as single commands, each of them doing a change at a single place of the document only. Of cause, you push them on the undo-stack as well. Finally, you push the EndCommand on the undo-stack.
When undoing, you check whether the command popped from the undo stack is the EndCommand. If it is, you continue undoing until the BeginCommand is reached.
This turns the multi-step command into a macro-command delegating the work to other commands. This macro-command itself is not pushed on the undo stack.

Related

Multistep composition using MEF in C#

I have a rather complex application which is initialized in multiple steps or phases. Some components are created during construction, some when user context is available, some when frond end gets available. I want to use MEF to create an easy extensible initialization process.
My question now... is is possible to have a MEF compose in multiple steps? Some imports can be satisfied, but some others only after e.g. user context is available within second composition.
If I understand you correctly you want to compose in an initial step and want to use the results from this initial step in the following ones. If this is what you mean by
...is it possible to have a MEF compose in multiple steps? ...
you can look into this thread stackoverflow.com and continue with the MSDN for CompositionBatch.
Otherwise if your object tree can be initialized anytime, you can just call Container.GetExportedValue() with the type you need in your process.

How to prevent multiple loads in C#?

I've got a class hierarchy in C# describing some data structure. There are base classes, which automate and perform some general tasks and on top of them there are specialized classes, which reflect the actual structure.
I want that structure to be able to be loaded only once. If you load it - or modify any of its fields - loading should no longer be available.
I came up with three solutions:
Create a flag bool loaded field and set it when class is loaded (or changed).
Pros: Structure does not have to be changed from what it currently is, straightforward usage (new + .Load())
Cons: I would have to work hard to propagate this flag throughout the whole structure and generally take care of it, such that it would be updated in every possible case. Also, this is runtime solution (second load = exception), while I always prefer compile-time solutions.
Move the loading to constructor of class, such that one might create an empty structure or create it and load immediately after.
Pros: Compile-time solution: one would not be able to simply load the structure at any time.
Cons: Loading relies on derived classes and virtual methods cannot be called in the constructor, what complicates things. This can be overcome, but in the cost of simplicity of the interface. Also it happens, that while loading, I have to return a object, what would require the ctor to have an out parameter (that seems to be a necessity anyway).
Create class factory, hide the ctor and provide factory methods for creating empty and pre-loaded structure.
Pros: Compile-time solution. Factory can be generic to cover all derived classes
Cons: Complicated code and non-intuitive interface (factories are a little less obvious way to create things than new operator). Also, this solution relies on internal modifier to make the structure and factory friends.
My questions are:
Is there a better way to prevent one from loading a structure a few times?
Or: is there a way to overcome downsides of proposed solutions?
Edit: In response to answers
Think of my structure as of Word document or Excel sheet. Word document can only be loaded once, you cannot "call load" on already loaded document. This is a kind of security measure I want. In other words I want to prevent someone from calling:
MyStructure s = new MyStructure();
s.Load("file1.str");
s.Load("file2.str"); // Doesn't make sense
And also:
MyStructure s = new MyStructure();
s.SomeProperty = 15;
s.Load("file1.str"); // Doesn't make sense
You should use an Identity Map for that. It keeps track of which entities have already been loaded.
Additional cons:
1 - Your data object is no longer holding just business data - it's also holding a loaded state - this is against the SRP.
3 - Factories may have to change when more types are created - this will mean more maintenance
It looks like you are using the active record pattern. I would not use the active record pattern as it combines business data and data loading - this is against the SRP.
Instead, use the repository pattern with POCOs to create your objects.
However, if you are keeping the current code you could add checks in the Load method - if the file name is different to the current file name (surely a property) prevent the load because it doesn't make sense in this context.
I want that structure to be able to be loaded only once.
Have you looked at the Singleton pattern?
The singleton pattern restricts the instantiation of a class to one object. Using the pattern will ensure you are not re-inventing the wheel.
However, I am not sure if you really only want one object in your application, or you want to ensure your code doesn't retrieve the data more than once for performance reasons - hence two answers.

C# object metadata

Is there any way to glue metadata to an object in C#?
Context: Framework which is sending messages between peers over the network. Messages can be arbitrary serializable user-defined .NET types.
Of course, when a message is sent by a peer, the framework could wrap the object into a Message class which saves the metadata, and the receiver could unwrap it. However, the processing method of the peer could decide to resend the message to another peer - however, I want to keep the original metadata. The user should not be required to use Message.RealMessage all the time except when resending it.
I thought about keeping the wrapped instance in a dictionary and upon resending looking up if there is already a wrapped instance in the dictionary and resending that one, however, as messages may not be resent at all (or resent multiple times) this would require more and more memory.
Any solutions? Maybe C# directly supports gluing additional information to an object? Normally I would go for an internal interface, however, the user would have to derive all its classes from a framework's base class, which is not possible.
Edit: I kind of want to say "here is an object of WrappedMessage but you are only allowed to use the interface provided by the class T".
There is the ConditionalWeakTable that should do what you want a little better than using directly a Dictionary.
To quote:
Enables compilers to dynamically attach object fields to managed objects.
You can ignore the part about the class being for compiler :-)

Streaminsight user defined functions limitation

What are the limitation of stream insight user defined functions?
Does the object need to be serializable?
Can it call external (remote) services?
If so these look to be very - very - very powerful!
Off the top of my head, a User Defined Function (UDF) is a static method call and operates on one event at a time. If you need something to work with more than one event at a time, you'll need to take a look at User Defined Operators (UDO) or User Defined Aggregates (UDAs). If you need to maintain state for any reason, you should be looking at UDOs or User Defined Stream Operators (UDSOs).
Remember that your payload classes only provide a schema to StreamInsight. So they don't need to be marked as serializable. Anything that gets serialized by StreamInsight will need to be marked serializable (i.e. configuration classes for adapters).
You can call out to external/remote services using the different UDFs, UDOs, UDAs, and UDSOs. However, these calls will be effectively blocking calls on one of the StreamInsight scheduler threads and this will increase latency. Event input and output should be done by the adapters only and the UDFs etc, should be used for processing the streams.

Static method as part of a contract

I am implementing an infrastructure for access control of models in a web application. The library has a context class that controllers (and maybe views) use for determining if the current user has access to a certain object. For keeping relevant information close to the target object, I've decided to pass on the access check request to the models themselves from the context object.
Implementing this mechanism for model object modification is almost trivial. Declare an interface, say, ICheckModifyAccess; and implement it in your model. The same goes for delete check. In both these cases, it is possible to ask an instance of a model whether it is OK to modify or delete them.
Unfortunately, it is not the case for read and create operations. These operations require that I ask the question to the model class. So using an interface for this is not an option.
I ended up creating an attribute, CheckCreateAccessAttribute, and then ended up using this attribute to mark a static function as the interface function. Then, in my context object, I can use reflection to check if such a marked function exists, if it matches the signature I expect, and eventually call it. In case it makes a difference, the method for create access check is public bool CanCreate<TObj>();. A typical model that supports access control would add something like the following to the class:
[CheckCreateAccess]
public static bool CanCreate()
{
return true;
}
I am not very fluent in C# yet, and I have a nagging feeling that I'm doing something wrong. Can you suggest a more elegant alternative? Especially, can you get rid of examining TObj by reflection?
It sounds like you've combined concerns in your object classes instead of separating them.
The temptation to "keep relevant information close to the target object" has perhaps led you to this structure.
Perhaps you could instead handle permissions in a separate class, see for example this article.
I think you shouldn't ask some specific user whether you can modify him (unless the modify right is per concrete entity). Just create a class that handles the rights (or use appropriate existing class).
This would eliminate your need for static classes and reflection.
If you are going to have lots of types, with custom rules (i.e. code) for every one of them, you could have a generic abstract type (interface or abstract class) that is able to check the rules for one type and some repository to retrieve the specific instance.

Categories