Modifying auto-generated Fortran code with C# - 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?

Related

How to exports strings from a WPF application code for internationalization?

I'm trying to modify an existing C# application for internationalization. The process for WPF has some documentation here and seems reasonably transparent as I can continue to develop normally and run msbuild from time to time and check if everything holds. However, while going through the sample project, I realized that it won't cover strings defined in code. In my case, most of them are used for logging and could more or less be easily exported with regexes. This seems a bit hazardous as well as I'm not certain the center will hold if I try to extract C# source with regex. I guess that I could wrap every string in a translation function that will perform the lookup in resources.
I'm not sure how to proceed from there. I'll have a bunch of strings that I could dump in a resx file and another set of strings extracted from the baml files internationalized in another way. Since I'm expecting each method to bring their own complications, I'd rather deal with only half of those complications if possible.
Is there any way to have either method work for both cases? I'd honestly prefer the second one since it makes more sense to me but I guess I could roll with generating a gazillion of Uids and only using 5% - 10% of them.
I develop multi-language check-in kiosks for one of the worlds busiest international airports (either #1 or #3, depending on how you define it), and in my experience the best solution for this in WPF apps is custom markup extensions. First, you can use regular language as your key, which means all of your XAML can be written in whatever language is most convenient for your developers. Secondly, you can add custom namespaces to the XAML namespaces, which helps keep your XAML tidy. Third, it's very easy to write utilities to extract your XAML extensions and collate them into Excel spreadsheets (say) for your translators, then incorporate the translations themselves back into your application. Finally, the translation tables themselves can be easily switched at runtime, allowing you to change your language on-the-fly.
Put all this together and all your XAML looks like this:
<TextBlock Text="{Translate 'Text to be translated appears here'}" />
And of course it's easy to control which text goes through your translation engine and which text doesn't, by simply controlling exactly where you use your Translate markup extension.

Implementing a refactoring system for my autogenerated code

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.

XML with .NET - Build in code or read from a file?

I am building a web application that will generate charts and graphs using a 3rd party charting component. This charting component requires it receive an XML file containing the design parameters and data in order to render the chart. The application may render up to 10 to 20 charts per page view. I am looking for suggestions for the most efficient way to handle this.
I need to load XML templates, of which there will be about 15-20, one for each chart type definition. With the templates loaded, I will them add the chart specific data and send it off to the charting component for rendering. Some of the possible ways of handling this off the top of my head include ->
Build each XML template in code, using StringBuilder
Build each XML template in code, using one of the .NET XML classes
Store each XML template in a file, load it from the disk on demand
Store each XML template in a file, load them all at once on application start
Storing the XML templates in files would greatly simplify the development processes for me, but I don't know what kind of performance hit I would take, especially if I was continually reading them off the disk. It seems like option 4 would be the better way to go, but I'm not quite sure the best practice way to implement that solution.
So.. any thoughts out there?
I'm just taking a crack at it but I'd save the templates into a constant like so and then use string.format to substitute any values and convert to XML file and pass it along to the 3rd party component.
const string cChart1 = #"<chart type='pie'>
<total>{0}</total>
<sections count={1}>
<section>{2}</section>
<section>{3}</section>
<section>{4}</section>
</section>
</chart>";
XmlDocument xmlChart1 = new XmlDocument();
xmlChart1.LoadXML(String.format(cChart1, somevalue1, somevalue2, somevalue3, somevalue4, somevalue5));
3rdPartyChartComponent cc = new 3rdPartyChartComponent(xmlChart1);
Thanks for your suggestions everyone.
I created a test application that ran x number of trials for each of the suggested methods to see which performed best. As it turns out, building the XML string directly using StringBuilder was orders of magnitude faster, unsurprisingly.
Involving an XmlDocument in any way greatly reduced performance. It should be noted that my results were based off of running thousands of trials for each method... but in a practical sense, any of these method are fast enough to do the job right, in my opinion.
Of course, building everything using StringBuilder is a bit on the messy side. I like Jarealist's suggestion, it's a lot easier on the eyes, and if I handle the XML as a string throughout rather than loading it into an XmlDocument, its one of the fastest ways to go.
Are the same templates used more than once? You could store the template as a static variable. Then add a property getter that builds the template (I would probably use your #2) if it hasn't yet been created, and then return it.
This would impose a performance hit the first time the template is used and be very fast after that.
I am pretty sure you can tell the compiler to bundle those XML files inside your CLR exe. Reading from these would not imply a noticeable performance hit as they would be already in memory. You will need to research a bit as i cant get the code out of my head right now, too sleepy.
EDIT.
http://msdn.microsoft.com/en-us/library/f45fce5x(v=vs.100).aspx - More info on the subject.
Another benefit from using this approach is that the CLR can guarantee the readability and existance of those files, else your executable will be corrupt and wont run.

Make an executable at runtime

Ok, so I was wondering how one would go about creating a program, that creates a second program(Like how most compression programs can create self extracting self excutables, but that's not what I need).
Say I have 2 programs. Each one containing a class. The one program I would use to modify and fill the class with data. The second file would be a program that also had the class, but empty, and it's only purpose is to access this data in a specific way. I don't know, I'm thinking if the specific class were serialized and then "injected" into the second file. But how would one be able to do that? I've found modifying files that were already compiled fascinating, though I've never been able to make changes that didn't cause errors.
That's just a thought. I don't know what the solution would be, that's just something that crossed my mind.
I'd prefer some information in say c or c++ that's cross-platform. The only other language I'd accept is c#.
also
I'm not looking for 3-rd party library's, or things such as Boost. If anything a shove in the right direction could be all I need.
++also
I don't want to be using a compiler.
Jalf actually read what I wrote
That's exactly what I would like to know how to do. I think that's fairly obvious by what I asked above. I said nothing about compiling the files, or scripting.
QUOTE "I've found modifying files that were already compiled fascinating"
Please read and understand the question first before posting.
thanks.
Building an executable from scratch is hard. First, you'd need to generate machine code for what the program would do, and then you need to encapsulate such code in an executable file. That's overkill unless you want to write a compiler for a language.
These utilities that generate a self-extracting executable don't really make the executable from scratch. They have the executable pre-generated, and the data file is just appended to the end of it. Since the Windows executable format allows you to put data at the end of the file, caring only for the "real executable" part (the exe header tells how big it is - the rest is ignored).
For instance, try to generate two self-extracting zip, and do a binary diff on them. You'll see their first X KBytes are exactly the same, what changes is the rest, which is not an executable at all, it's just data. When the file is executed, it looks what is found at the end of the file (the data) and unzips it.
Take a look at the wikipedia entry, go to the external links section to dig deeper:
http://en.wikipedia.org/wiki/Portable_Executable
I only mentioned Windows here but the same principles apply to Linux. But don't expect to have cross-platform results, you'll have to re-implement it to each platform. I couldn't imagine something that's more platform-dependent than the executable file. Even if you use C# you'll have to generate the native stub, which is different if you're running on Windows (under .net) or Linux (under Mono).
Invoke a compiler with data generated by your program (write temp files to disk if necessary) and or stored on disk?
Or is the question about the details of writing the local executable format?
Unfortunately with compiled languages such as C, C++, Java, or C#, you won't be able to just ``run'' new code at runtime, like you can do in interpreted languages like PHP, Perl, and ECMAscript. The code has to be compiled first, and for that you will need a compiler. There's no getting around this.
If you need to duplicate the save/restore functionality between two separate EXEs, then your best bet is to create a static library shared between the two programs, or a DLL shared between the two programs. That way, you write that code once and it's able to be used by as many programs as you want.
On the other hand, if you're really running into a scenario like this, my main question is, What are you trying to accomplish with this? Even in languages that support things like eval(), self modifying code is usually some of the nastiest and bug-riddled stuff you're going to find. It's worse even than a program written completely with GOTOs. There are uses for self modifying code like this, but 99% of the time it's the wrong approach to take.
Hope that helps :)
I had the same problem and I think that this solves all problems.
You can put there whatever code and if correct it will produce at runtime second executable.
--ADD--
So in short you have some code which you can hard-code and store in the code of your 1st exe file or let outside it. Then you run it and you compile the aforementioned code. If eveything is ok you will get a second executable runtime- compiled. All this without any external lib!!
Ok, so I was wondering how one would
go about creating a program, that
creates a second program
You can look at CodeDom. Here is a tutorial
Have you considered embedding a scripting language such as Lua or Python into your app? This will give you the ability to dynamically generate and execute code at runtime.
From wikipedia:
Dynamic programming language is a term used broadly in computer science to describe a class of high-level programming languages that execute at runtime many common behaviors that other languages might perform during compilation, if at all. These behaviors could include extension of the program, by adding new code, by extending objects and definitions, or by modifying the type system, all during program execution. These behaviors can be emulated in nearly any language of sufficient complexity, but dynamic languages provide direct tools to make use of them.
Depending on what you call a program, Self-modifying code may do the trick.
Basically, you write code somewhere in memory as if it were plain data, and you call it.
Usually it's a bad idea, but it's quite fun.

Is there an existing way to turn source code back into a CodeCompileUnit?

We use the DesignSurface and all that good IDesignerHost goodness in our own designer. The designed forms are then persisted in our own bespoke format and all that works great. WE also want to export the forms to a text-based format (which we've done as it isn't that difficult).
However, we also want to import that text back into a document for the designer which involves getting the designer code back into a CodeCompileUnit. Unfortunately, the Parse method is not implemented (for, no doubt, good reasons). Is there an alternative? We don't want to use anything that wouldn't exist on a standard .NET installation (like .NET libraries installed with Visual Studio).
My current idea is to compile the imported text and then instantiate the form and copy its properties and controls over to the design surface object, and just capture the new CodeCompileUnit, but I was hoping there was a better way. Thanks.
UPDATE: I though some might be interested in our progress. So far, not so good. A brief overview of what I've discovered is that the Parse method was not implemented because it was deemed too difficult, open source parsers exist that do the work but they're not complete and therefore aren't guaranteed to work in all cases (NRefactory is one of those from the SharpDevelop project, I believe), and the copying of controls across from an instance to the designer isn't working as yet. I believe this is because although the controls are getting added to the form instance that the designer surface wraps, the designer surface is not aware of their inclusion. Our next attempt is to mimic cut/paste to see if that solves it. Obviously, this is a huge nasty workaround, but we need it working so we'll take the hit and keep an eye out for alternatives.
You could always write your own C# parser. That way you can be sure of it's completeness.
In your case, because you don't need anything like intellisense, you could probably get away with just using a parser generator.
Even if you wrote one by hand, however, it probably wouldn't take you more than about a month.
It's not exactly what you asked for, but you could try to use the CodeDomComponentSerializationService class to generate the CodeDom graph based on the current state of the design surface.
We use that class to handle copy/paste functionality in our built-in designer.

Categories