I have problem. I can't find mechanism in .Net which allow me compile code in Windows form.
I want have 1 textbox with code and later compiled code show in another box.
How I can do this?
It sounds like you want to use a C# compiler from within your Windows Forms app, but I'm unsure what your other box would show.
If you're looking for just compiling and visually displaying IL, there are certainly ways to call Roslyn from Windows Forms.
If you're looking to dynamically generate a GUI, your options are a little less clear. I would consider exposing your own wrapper functions to another language. I would consider using Moonsharp to compile Lua code on the fly. IronPython would also work. I'm unfamiliar with whether F# language services could be invoked in a similar way, but these are options I'd consider.
If you're specifically looking to compile C# and use the results to display a WinForms GUI, you'll need to use CodeDOM. CodeDOM is a pretty deep rabbit hole even if it's powerful, and it won't be easy to sandbox any GUI it renders to the output container you have in mind.
As has been mentioned, compiling code using Roslyn is certainly the way forward.
If you wish to see some output by executing the compiled code you may wish to create an abstract class for script writing which provides an entry point and a way of reporting output. You could then compile the script into a dll and use reflection to load the output assembly, instantiate an instance of your class (a class that implements ScriptTemplate below) and execute via the entry point.
abstract class ScriptTemplate
{
public abstract void Main();
public string Output
{
get;
protected set;
}
}
Your form could then write the Output property to a text box for example.
class Script : ScriptTemplate
{
public override void Main()
{
Output = "Hello world!";
}
}
Related
As the title suggests I am having a bit of trouble communicating with my wpf application's MainWindow.cs class during runtime when the code compiles.
Context:
This is a application I am writing for myself that utilizes CodeDom's compiler to compile code stored in xml format at runtime or in a triggered event(like a button or voice command)
The compiler is working neatly but I have been stuck at communicating with my classes from the original application.(MainWindow.cs)
I would like to be able to call functions and access variables from within the runtime compiled CodeDom Scripts. I have found method invoking but I don't quite understand how it works yet, any help would be appreciated!
Example of what I want to do:
Main Window Class Example
namespace WpfOverlay
{
public partial class MainWindow : Window
{
public string AccessThis;
public void ExampleFunctionToAccess(string InputString)
{
AccessThis = InputString;
}
}
}
And access that class to call ExampleFunctionToAccess(); from a CodeDom Compiled script/class in a different namespace (if possible I wouldn't mind having them in the same namespace)
The fact that you compile it at runtime has no bearing on your actual problem, what you actually want is to implement any of the myriad forms possible of IPC.
I recommend an UDP client/server approach, it's relatively easy to implement robustly.
I know you cant override or inherit from a static class and why. That is clear.
I am looking for some advice on how to replace that static class with my own static class. Any hackish or wildest attempts please.
I am basically writing a MOD for a game and the way the game writer wrote one class in particular, he set it as static and put the implementation in there. So when we write our own DLL with this thing, the only way to execute a calculation on the pixel grid is when his code calls this particular calculation in his static class. Both classes are static but I only need to change one.
That is great for him but I want my thing to do another calculation and make it more awesome. I used ILspy and can see all the code in that static class of the base game, so I can copy and paste it and I only need to modify two or three lines.
But now I want to nuke the games core static class and make mine the only implementation.
I want to force replace that static class at runtime, before the static class is ever called and after loading my mod, how? There must be a way to swap static classes?
I read about creating a proxy DLL that redirects all methods to the old DLL and my method to my DLL but that would require gamers to replace a core game DLL and that is even dirtier than just telling people what my mod does. I am changing thas implementation for this mod, if you dont like don use my mod. That is more reasonable.
I will assume you don't have access to the source and thus can't modify it directly.
You COULD (probably shouldn't) use microsoft fakes since it is mainly for testing. You could create a fakes assembly based on the original author's dll, and override just the type you want. It even supports overriding static classes. Again, I am not saying that you necessarily SHOULD do this, but you COULD.
Here is the page for isolating code under test, it includes an example for shimming a static class (DateTime) https://msdn.microsoft.com/en-us/library/hh549175.aspx
A few options ...
Review how the original developer said to modify the game
You could use something like JustDecompile to get their code.
Use Fakes as suggested above
Create your own assembly that calls into their assembly and hack the IL dynamically
This seems pretty close to this question: Can I redirect .NET method calls to a new method at runtime?
One of the answers to this post suggests looking at a library called Moles which seems to be similar to Detours and may help
Moles allows to replace any .NET method with a delegate. Moles supports static or non-virtual methods
I am trying to create a windows form project, and use speech recognition for the Kinect with the Kinect to Windows SDK. I have
the form application project (p1) and
the Kinect speech project (p2) which is a command prompt.
I made it a command prompt because it was the easiest way to do things. Anyway, I have read and found two things about this.
1)I found out how to run two projects at the same time in the same solution.
2) I also found out how to add references to get classes from each project to the other.
So, how would I get variables from each project? Just by using project references, or something? P2 can recognize speech and save it to variables, if that counts for anything.
I made it a command prompt because it was the easiest way to do things.
That sounds like the problem. It sounds like really you should be looking at making your Kinect project a class library. Then you can just call into that class library from the Windows Forms application.
If you want a "test bed" console app, you can always write one which also references the class library.
Note that generally you shouldn't be sharing variables between projects - they're implementation details in most well-encapsulated systems - but you would create types which expose properties, appropriate methods etc.
Here's a couple of options if I'm understanding you right:
Add those variables to your classes as properties then
using Solution.MyNamespace;
in the class that uses the other project
If you have variables that need to be independent, consider adding a class library project called Abstract or something that both projects reference
I hope this might help,
Cheers
Another method is to use named pipes for interprocess communication.
MSDN has the references to use the name pipes API here.
Named pipes are part of the .NET framework and are a reliable method for communication without having to worry about access permissions on files.
To go down the static variable path, you would need to run a single process and turn one project into a dll and load the Program Main manually.
Of course you dont even need to use static variables but use synchronisation on reference variables passed in at load time. I would probably go this method if you didnt need to run two separate processes.
Just depends on what your goal is for having the projects separate processes.
Like #JonSkeet said, create a class library, then you can save the information like this:
public class SpeechRecognizer
{
public List<string> SpeechRecognized = new List<string>
{
};
public void SaveRecognizedSpeech(string foundSpeech)
{
SpeechRecognized.Add(foundSpeech);
}
}
In code:
SpeechRecognizer sr = new SpeechRecognizer();
sr.SaveRecognizedSpeech("blah blah");
sr.SaveRecognizedSpeech("BLAH BLAH");
Console.WriteLine("{0}, {1}", sr.SpeechRecognized[0], sr.SpeechRecognized[1]);
Console.Read();
Oh and to make your whole program know variables(I hope these are both in the same solution!) make them public. Hope this helps!
We're currently investigating how we can embed IronPython (scripting) into our C# application.
We see the benefits it will provide to our end users, giving them the ability to hook into our application but one question that keeps arising is how do we provide the end-user with code editing abilities that are aware of the different entry contexts in our application.
I know that we can provide a simple text editor with syntax highlighting but how do we go one step further and allow a user to test their scripts against objects that we expose from our application. Keeping in mind that we will expose different objects depending upon the context of the entry-point.
How do you allow end users to test, write and edit scripts in your application?
PS - I am new here so let me know if I am not doing this right!!!
Maybe what you want is to use the Visual Studio 2010 Shell Isolated. It can be used to provide a visual studio environment within an application, kind of how VBA used to be. As far was Python support you can look at IPyIsolatedShell
You could host IronPython in your C# application. Then you can pass in variables from your C# application and execute IronPython code which uses them. Dino Viehland did a talk at PDC about this called Using Dynamic Languages to Build Scriptable Applications. Dino made the source code for the application he created at the PDC available but it is using an older version of IronPython.
Here is some code for IronPython 2.7.1 that shows you how you can host IronPython in a few lines of code.
using System;
using IronPython.Hosting;
using Microsoft.Scripting.Hosting;
public class MyIronPythonHost
{
ScriptEngine scriptEngine;
ScriptScope scriptScope;
public void Initialize(MyApplication myApplication)
{
scriptEngine = Python.CreateEngine();
scriptScope = scriptEngine.CreateScope();
scriptScope.SetVariable("app", myApplication);
}
public void RunPythonCode(string code)
{
ScriptSource scriptSource = scriptEngine.CreateScriptSourceFromString(code);
scriptSource.Execute(scriptScope);
}
}
The code above passes an application object called MyApplication to IronPython via a script scope and sets its variable name to be app. This app variable is then available to the IronPython code where it can call methods on it, access properties, etc.
The final method in the code above is the RunPythonCode method which takes in the IronPython code written by the user and executes it.
Going further than this and allowing the user to debug their IronPython code in a similar way to how you can debug VBA macros is a major piece of development work however.
I want to build a flexible reporting system for my application. So far I only have a concept in my head and need some tips on implementation. I'm using Crystal Reports to render reports and I know how to load reports dynamically.
Now, the idea is that every report will be packaged as a separate assembly (.dll). The reporting framework will be loading every custom report and communicating with it via clearly defined interface like this:
public interface IReport
{
string GetTitle();
string GetDescription();
void SetParameter();
void Print();
}
Also, there will be some base implementation (as an abstract class) that will handle some common operations on the reports (like binding to data source, etc.):
public abstract class Report
{
...
}
Inside every dll there will be an implementation of concrete class, representing this or that report:
public class CustomersReport : Report
{
...
}
Now, I have to figure out the following:
1) How to dynamically locate and load the dll?
2) How to create an instance of concrete class (CustomerReport) and cast it to IReport in order to call necessary methods on it?
Have you ever implemented such an extensible system? Could you please share your expertise / code snippets?
Thanks in advance.
EDIT:
While investigating this question I found Jon Skeet's article on Plug-ins and Cast Exceptions that might be helpful.
See this:
Problem with dynamic loading of a dll into my program
Is doing exactly what you want wihtout all the YAGNI around it.
Have a look at Mono.Addins (it's MIT license so it's ok with closed software). From your description it does what you need. Basically it uses a dependency tree + plugins based on interfaces. It has it's own manager for loaded .dll-s and its objects are based on the loaded interface, so you don't need any more magic casting to call anything.
You can consider MEF from Microsoft. It is a composition engine that can be set up to monitor a local folder and automatically load assemblies that export parts (implementation of IReport in your case) that you're interested in.
We do have a system like that we implemented sometime ago. We have a single assembly with reports that we load into a separate application domain and reload if the file version has changed. Then we use .NET remoting to communicate between app domains. We considered using Add-in framework from Microsoft but we found it to be very complex and imposing and decided it was too heavy and complex in our case.