Implementing a refactoring system for my autogenerated code - c#

I have a little visual system for generation FSM's where the user can draw a graph using boxes (states) and link them with lines (transitions). This, in the end, generates c# code when user presses the "Generate code" button that defines the FSM in runtime.
I want my users to be able to change things like graph name, transitions names, states names, delete nodes, delete transitions and a bit more after the first save, so, I need a way to handle refactoring.
I'm struggling trying to find a non intrusive way to accomplish this. Have tried to apply a modification of a do/redo algorithm I made some time ago but couldn't be able to get something nice.
Could anyone explain how to create such a system, making it as less intrussive with existent code as possible?
Cheers.

I would suggest keeping the state in your graph datastructure, and generating the C# code anew on changes to the FSM, this is a simple solution that will allow arbitrary modification of the FSM-datastructure without having to worry about applying said modifications to the generated code.
For implementing 'refactorings' of the base FSM-data structure, you could use something like a Command Pattern to encapsulate the refactorings and undo/redo operations.

Related

Modifying auto-generated Fortran code with C#

I am working with a project where I am generating a significant amount of fortran code using an automated tool but then I need to do modifications to that code by hand prior to compiling. These modifications have no specific pattern, other than that I know what sections of code need to be modified. Furthermore, I need to be able to apply these modifications anytime I regenerate the base code, so it must be automated (for both speed and for consistency). I'm quite aware that in an deal world the base product should be modified to simply generate the code properly. However, that is not possible in this case.
What I'm wondering is what the cleanest way to do this would be in C#. Currently the best plan I've been able to come up with is to create an xml file where each node has a set of text to replace with another set for a certain file. I would then read all the xml files into my program and make the modifications detailed therein. I believe this will work, and it is much more flexible than hard coding the modifications into my program, but I'm trying to determine if there is a more appropriate design pattern or extension, that could or should be used in this case.
Main concern is time required to code and extensibility (i.e. if I want to add more modifications later on, that I'm able to do so). I have the full code for what it should look like, as well as what it currently looks like.
Is storing each find and replace snippet in a flat file a reasonable organizational structure? Or is there a smarter way to approach this problem?

Limiting Functionality of Dynamic Invocation in C#

I have created some utility code that allows me to take text entered into our content management system and dynamically compile and invoke it with a method similar to this.
But this raises a security risk--since a content author could mistakenly (or worse--maliciously) enter code that would do things outside of what I am looking for. Any recommendations for keeping this functionality open, but be able to prevent certain types of code from being written? For example, there are obvious things to limit like writing to the file system.
My initial thought is excluding certain assemblies, but I am curious if anyone has any clever ideas on this.
Don't do this. There are endless possibilities for what a user could write and you won't be able to prevent them all. In security you should always specify what a user can do instead of what he can't do (whitelist instead of blacklist) because you will miss something if you do it otherwise.
In this specific case, allowing a user to write arbitrary code never seems like a good idea. Instead, you should choose specific operations that a user can perform and add a button/control for each one.
If you REALLY need such functionality consider creating very limited functionality. Don't allow users to enter text; give them "blocks".
Start with very basic, limited set of instructions and add new ones only when asked to.

Undo/Redo Best Practices with MVVM

I am working on essentially a drawing editor that allows you to define geometries based on key points on existing geometries. The user is then able to add some information about the thing they just added, such as name, expected size, etc. The API I am using to accomplish it is the awesome Reversible API, though I hope that the question extends beyond the API that I am using.
There are basically a couple questions that I am seeking a little clarity on:
1) If you are supporting Undo/Redo with an application that supports selection in a Master/Detail manner, should changing the state of a drawing object also cause it to be selected? The example being that an undo operation changed the name of an element, and that change would not be obvious unless the element was selected. Is there considered a standard behavior for something like this?
2) When dealing with certain types of incremental changes (Dragging box, or using a numeric spinner), it seems to be standard form for a set of changes to be grouped into a single user interaction (mouse swipe, or the act of releasing the spinner button), but when dealing with MVVM, I currently only know that the property has changed and not the source of the change. Is there a standard way for these types of interactions to propagate to the view model without completely disintegrating the pattern?
When in doubt the best approach is to take a look at typical behaviour of OS controls and other applications on the platform in order to be consistent with what users will be familiar with. In particular, consistency with the most commonly-used applications. If you examine how other apps approach a UI issue you can often learn a lot, especially about subtle cases you may not have considered in your own design.
1) Conventionally, undoing tends to select the changed item(s), both to highlight what changed and to move the user's input focus back to the last edit so that they can continue. This works particularly well for content like text because if you undo/redo something you typed, chances are you want to continue editing in the area of the text you've just undone/redone. The main choice for you to make with master/detail is whether to select the master object only, or to select the precise detail that changed.
2) Your undo manager can use some intelligence to conglomerate similar actions into a single undo step. For example, if the user types several characters in a row, it could notice that these actions are all alike and concatenate them into a single undo step. Just how it does this depends on how you are storing and processing the undo, but with a decent object oriented design this should be an easy option to add (i.e. ask undo records themselves if they can be conglomerated so you can easily add new types of undo record in future). Beware though that accumulating too many changes into one step can be intensely irritating, so you may find the lazier implementation of one action = 1 step actually achieves a better UX than trying to be too clever. I'd start with brute force and add conglomeration only if you find you end up with lots of repetitive undo sequences (like 100 single pixel-left movements instead of just one 100-pixel jump)

Undo Redo in WPF/C# in an already functional application

I have done some research already as to how I can achieve the title of this question. The app I am working on has been under development for a couple of years or so (slow progress though, you all know how it is in the real world). It is now a requirement for me to put in Undo/Redo multiple level functionality. It's a bit late to say "you should have thought about this before you started" ... well, we did think about it - and we did nothing about it and now here it is. From searching around SO (and external links) I can see that the two most common methods appear to be ...
Command Pattern
Memento Pattern
The command pattern looks like it would be a hell of a lot of work, I can only imagine it throwing up thousands of bugs in the process too so I don't really fancy that one.
The Memento pattern is actually a lot like what I had in my head for this. I was thinking if there was some way to quickly take a snapshot of the object model currently in memory, then I would be able to store it somewhere (maybe also in memory, maybe in a file). It seems like a great idea, the only problem I can see for this, is how it will integrate with what we have already written. You see the app as we have it draws images in a big panel (potentially hundreds) and then allows the user to manipulate them either via the UI or via a custom built properties grid. The entire app is linked up with a big observer pattern. The second anything changes, events are fired and everything that needs to update does. This is nice but I cant help thinking that if a user is entering text into a texfield on the properties grid there will be a bit of delay before the UI catches up (seems as everytime the user presses a key, a new snapshot will be added to the undo list). So my question to you is ....
Do you know of any good alternatives to the Memento pattern that might work.
Do you think the Memento pattern will fit in here or will it slow the app down too much.
If the Memento pattern is the way to go, what is the most efficient way to make a snapshot of the object model (i was thinking serialising it or something)
Should the snapshots be stored in memory or is it possible to put them into files?
If you have got this far, thankyou kindly for reading. Any input you have will be valuable and very much appreciated.
Well , Here is my thought on this problem.
1- You need multi level undo/redo functionality. so you need to store user actions performed which can be stored in a stack.
2- Your second problem how to identify what has been changed by a operation i think through Memento pattern , it is quite a challenge. Memento is all about toring initial object state in your memory.
either , you need to store what is changed by a operation so that you can use this information to undo the opertions.
Command pattern is designed for the Undo/Redo functionality and i would say that its late but its worth while to implement the design which is being used for several years and works for most of the applications.
If performance allows it you could serialize your domain before each action. A few hundred objects is not much if the objects aren't big themselves.
Since your object graph is probably non trivial (i.e. uses inheritance, cycles,...) the integrated XmlSerializer and JsonSerializers are out of question. Json.net supports these, but does some lossy conversions on some types (local DateTimes, numbers,...) so it's bad too.
I think the protobuf serializers need either some form of DTD(.proto file) or decoration of all properties with attributes mapping their name to a number, so it might not be optimal.
BinaryFormatter can serialize most stuff, you just need to decorate all classes with the [Serializable] attribute. But I haven't used it myself, so there might be pitfalls I'm not aware of. Perhaps related to Singletons or events.
The critical things for undo/redo are
knowing what state you need to save and restore
knowing when you need to save the state
Adding undo/redo after the fact is always a painful thing to do - (I know this comment is of no use to you now, but it's always best to design support into the application framework before you start, as it helps people use undo-friendly patterns throughout development).
Possibly the simplest approach will be a memento-based one:
Locate all the data that makes up your "document". Can you unify this data in some way so that it forms a coherent whole? Usually if you can serialise your document structure to a file, the logic you need is in the serialisation system, so that gives you a way in. The down side to using this directly is usually that you will usually have to serialise everything so your undo will be huge and slow. If possible, refactor code so that (a) there is a common serialisation interface used throughout the application (so any and every part of your data can be saved/restored using a generic call), and (b) every sub-system is encapsulated so that modifications to the data have to go through a common interface (rather than lots of people modifying member variables directly, they should all call an API provided by the object to request that it makes changes to itself) and (c) every sub-portion of the data keeps a "version number". Every time an alteration is made (through the interface in (b)) it should increment that version number. This approach means you can now scan your entire document and use the version numbers to find just the parts of it that have changed since you last looked, and then serialise the minimal amount to save and restore the changed state.
Provide a mechanism whereby a single undo step can be recorded. This means allowing multple systems to make changes to the data structure, and then when everything has been updated, triggering an undo recording. Working out when to do this may be tricky, but it can usually be accomplished by scanning your document for changes (see above) in your message loop, when your UI has finished processing each input event.
Beyond that, I'd advise going for a command based approach, because there are many benefits to it besides undo/redo.
You may find the Monitored Undo Framework to be useful. http://muf.codeplex.com/
It uses something similar to the memento pattern, by monitoring for changes as they happen and allows you to put delegates on the undo stack that will reverse / redo the change.
I considered an approach that would serialize / deserialize the document but was concerned about the overhead. Instead, I monitor for changes in the model (or view model) on a property by property bases. Then, as needed, I use the MUF library to "batch" related changes so that they undo / redo as a unit of change.
The fact that you have your UI setup to react to changes in the underlying model is good. It sounds like you could inject the undo / redo logic there and the changes would bubble up to the UI.
I don't think that you'd see much lag or performance degradation. I have a similar application, with a diagram that we render based on the data in the model. We've had good results with this so far.
You can find more info and documentation on the codeplex site at http://muf.codeplex.com/. The library is also available via NuGet, with support for .NET 3.5, 4.0, SL4 and WP7.

Creating a Menu Stack

I'm trying to create a menu system that allows you to go backward and forward while returning the final selected data to the calling method.
Take for example a orderFood() method displays a menu of choices of types of food that can be ordered. If someone selects seafood a seafood() method would run and query what types of seafood is availble to order then display it
if the user selects fishsticks, fishsticks would be returned to the method that called order food. Likewise, this menu system would allow the user to go back to the previous menu.
I'm thinking (Using C#) I'd have to use reflection and unsafe code (pointers) to get this sort of effect but I am positive that there is a simpler way to do this. Any suggestions?
Thanks,
Michael
Instead of thinking about the menus as a stack, try thinking of them like a tree.
If you do this, it should be fairly easy to "walk" up and down the tree as you need to implement your stack approach.
This would be fairly easy to read from a file or database (very easy from XML, in particular), and also shouldn't be too tough to walk up and down.
There isn't really anything in this that should require unsafe code or reflection - it can all be done with standard collections in C#.
You could easily do what you are describing without unsafe code provided you know at compile time, by making it data driven. Instead of thinking of menus as routines that do these things, think of menus as a class of objects that does these things. Ommm.
Even if you don't know everything at compile time (say you need to read the options from a file) you could still do it by building the nest of objects which represent your menus at run time, based on the contents of the file.

Categories