So, I'm making myself a small C# library for dialogues to use in an cRPG game.
The idea is, that the Dialogue object and it's fields (like DialogueNode and DialogueOption objects) are created based on an XML file, which I aim to make as simple as possible. The fields, except for lists or objects of types contained within the library, are - at best - string identifiers, to be acquired and parsed by outside means when needed.
I've basic funcionality implemented - XML serialization, running through the dialogue and exiting it - as well as basic, console based application interpreter and a WPF editor to create the dialogues, because writing the dialogue in plain XML is not the most comfortable thing in the world. (the last two are meant to be as much independent from the library as possible, except maybe for implementing what's inside to show/create)
All that being said, I've encountered a problem (actually two, the other one I'll cover in different question when I've the time after my exams).
After giving it some of my unexperienced 'noobish' thought, I've come to think, that I'd like to have some basic predicates stored either in my nodes or options - they would be later checked in game to determine, whether to display the node/option or leave it be (or whatever meddling with those to be honest). For example - an option is displayed if the player character have item X in his inventory, or the node is displayed when player has a certain minimum value of an attribute.
My idea of implementing is so far like that:
Having a field PredicateScript in an object
Having a bool method, that would be executed in runtime by the interpreter like this:
public bool DisplayPredicate(string predicateCode)
{
bool result = FunctionExecutingCSharpCode(predicateCode);
return result;
}
I've read some topics about compiling on the fly very brielfy, but I'm not sure if it's exactly what I want - I'm not sure how it would affect the performance of application (either the interpreter or the game itself), if it would be recompiled every few seconds...
I'm not pasting any code of what I'm trying to do, because either I'm yet to do this (as I'm not writing the code I'm not sure it will work) or it's the library structure which I don't think would be of relevance aside from what I explained I aim to do. ^^
Thanks. ^^
Given the standard .NET framework, there's no such thing as a C# "interpreter" you can feed code that gets executed. You could try to dynamically create C# code and have that compiled on the fly into an in-memory assembly, which you can then use using the .NET compiler services.
And example of this is given here: http://www.codeproject.com/Tips/715891/Compiling-Csharp-Code-at-Runtime.
Related
We have a MS SQL 2005 database. The data is uploaded in this database from Excel sheets. These Excel sheets come from various vendors and most of them never maintain a predefined structure so that we can create a separate insertion/update module.
Until now I have created a module which accepts an Excel sheet in a predefined format and uploads the data from it. For every vendor someone has to format it in the predefined manner manually which takes too long and is a donkey work.
Now we have removed the manual formatting and put all database columns in one column, and drop-downs containing all Excel columns in another column. The user maps the desired columns and updates the database.
But most of the time this simple mapping falls short, since mostly we have to split/combine values based on some logic. To make it more user friendly and since most of my users are themselves C# programmers I have decided to remove the drop-downs and use text boxes where users can enter direct logic. For example:
dbcol1 = excel[col1].ToString().Replace("-"," ")
+(int.Parse( excel[col6].ToString())*.1).ToString();
While searching for this I came across dynamically compiling C# code. Since I have never done so before and also I am not sure that this method will be efficient I need to know that am I moving in the right direction with this. Or is there a more efficient and faster way to do this?
Script it up? C# Script is pretty handy, if you want to compile and run code on the fly;
If you can string format something that is correct C# it'll let you compile and run it.
http://www.csscript.net/
For example:
dynamic script = CSScript.Evaluator
.LoadMethod(#"void SayHello(string greeting)
{
Console.WriteLine(greeting);
}");
script.SayHello("Hello World!");
Probably not great for production, but you can at least prototype your idea
Normally you would use Reflection.Emit to generate a .NET assembly on the fly and execute that. However, it accepts only Intermediate Language instructions, not C#. And creating a whole new assembly each time you want to execute a piece of code is not efficient at all.
Roslyn is Microsoft's attempt at a compiler as a service. This is a new rewritten compiler for C# and VB.Net that can be called by an application to compile code, and it provides information about the code it is compiling.
Anders Hejlsberg (I believe) showed an example using the Roslyn compiler to implement a C# scripting interface: type some C# and it gets executed on the fly. While Roslyn is still in development, you might want to see if it would meed your needs by trying the Roslyn CTP.
C# as a Scripting Language in Your .NET Applications Using Roslyn is a CodeProject article that goes into some detail.
Finally, if you cannot (yet) or don't want to use Roslyn, or if it does not provide the execution speed you were looking for, then I think your best bet (in terms of performance) is to parse and interpret the scripting code yourself. However, this is error-prone hard work.
The question is as simple as that: I need some way to identify composable part definitions before actually creating the parts.
In other words, I need to be able to send a string identifying the part to some remote site, which later would send the string back to me, and I should be able to pick that same part based on the string. I do not necessarily need a string (I can build my own map), but I need something that is unique and equality-comparable.
Some things I thought about and rejected:
I do realize that the "right" way for doing this is to decorate my parts with metadata, but I don't want to. First, using a meaningful string for identifier means risk of duplication, while using a random one (like GUID) means it would be ugly. Second, my plugins are numerous and I don't want to have to remember about decorating them all the time.
Another way that immediately jumps to mind is to use the part's type. However, MEF is generic enough to be above such formalities: a part is not necessarily a .NET class.
In trying to "fix" the previous point, I could use type of the actual object that is returned when I go and create the part, but then I would have to create all parts, which are numerous.
Metadata is really the only viable option, especially if you want the identifier to remain stable over time, e.g. in the face of application restarts or implementation class refactoring/renaming.
If you don't need stability between application restarts, you could either:
Use MEF 2's RegistrationBuilder to programmatically generate the necessary metadata values, e.g. based on an incrementing integer; or,
Create a custom [MetadataAttribute] that does roughly the same thing to generate an id value at runtime
If you need stability between restarts, but not between rebuilds, then using RegistrationBuilder to assign ids based on the type name is an option.
Of course, RegistrationBuilder is only available in the CodePlex preview builds of MEF 2 or the .NET 4.5 Developer Preview at this point.
TLDR; manually applying metadata attributes is your best bet. In debug mode you could write a post-initialisation routine in your app to ensure uniqueness/presence.
I have the situation that the same repeating refactoring tasks have to be done for a huge number of methods in my code.
For example imagine a interface with 100 methods, each of them has one or more parameters as well as a return value. For each of these methods I need to jump to the implementation change the return type and add a line of code which converts the old return value to its new type for callers of the interface method.
Is there any way to quickly automate such refactorings?
I even thought to write a custom script to do it, but writing a intelligent script would approximately take longer than doing it maually.
A tool supporting such task can save a lot of time.
It's a good question, but in the time it took since you posted it (not to mention the time you spent searching for an answer before posting), you could have completed the changes manually.
I know, I know, it's utterly unsatisfying, but if you think of it as a form of mediation, and only do this once a year, it's not that bad.
If your problem is one interface with 100 methods, then I agree with another poster: just doing it may seem painful but it is limited in effort and you can be done really soon.
If you have this problem repeatedly, or you have very large code base (many, many interfaces for which you want to perform this task), then what you need is a tool for implementing automated change: a program transformation engine. Such a tool provides the ability to parse source code, build a program representation (an abstract syntax tree), and enables one to apply "scripted" operations on the tree either through procedural interfaces and/or through source-to-source transformation patterns.
OUr DMS Software Reengineering Toolkit is such a program transformation system. It has a C# Front End to enable its application to C# code. Configuring such a tool for a complex task is not a matter of hours, so it is not useful for "small scale" changes. For large scale changes, such tools can make it possible to do things simply not practical by hand.
Resharper and CodeRush both have features which can help with this kind of task.
Resharper's change signature functionality is probably the closest match.
Can't you generate a new interface from the class you have and then remove the ones you don't need! if it's that simple!!
change the return type : by changing... the return type, provided it is not a standard type (...), and the converter can be implemented by a TypeConverter.
When i have such boring task to do, i often switch VS2010 and use a tool that allow regex search and replace. In your example, maybe change 'return xxx;' by 'var yyy=convert(xxx); return yyy;'
(for example editor Notepad++ (free) allready offers quite some possiblities to change everything in a project (use with caution))
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.
I'm writing a small visualization tool in wpf, the idea is that average users can create interesting visualizations without being programming wizards.
I have a controller class that has methods like StartPath(double x, double y) and LineTo(x,y) CurveTo(...) etc.
The idea is that a user can type these commands into a textbox and have it draw the result on a canvas.
StartPath(0,0);
LineTo(30,50);
LineTo(50,40);
EndPath();
One Idea I had was to use a .cs template that has all the methods implemented, and has an additional Run() command with a replacement token inside. I load the template as a string, insert the user commands into the Run() method, use the new .net 4.0 compilation service to create an assembly on the fly, then load it and invoke its Run() method and access the exposed Path to draw it on a canvas.
Another one would be to actually just parse the textbox, error check it and call the appropriate methods.
Are there any other methods, especially with the new dynamic keyword?
You don't need to use anything new from .NET 4.0. The ability to compile C# code in the framework has been present for ages. In fact, my Snippy tool does pretty much exactly what you say - it's a template that user code goes in. You're welcome to base your tool on mine, should you wish to. You can download the code from the C# in Depth site.
Aside from anything else, that way you won't require your users to have .NET 4.0.
As for dynamic - it doesn't really help in this case, unless you fancy letting your users write code in IronPython/IronRuby. C# still doesn't have a sort of "eval" call letting you just execute an arbitrary string.
I think you are better to try to define a LL1 language and generate a parser and a scanner and build your own interpreter.
Coco/R is a very stable and well known tool for this kind of job.
Check this out is should not be difficult for what you have in mind:
http://www.scifac.ru.ac.za/coco/cshcoco.htm
If you want to use the new dynamic you will still have problem parsing the input command text.
You could use dynamic to build your interpreter on top of the parser.
Hope this helps