Making modular program which support dll extension in C# - c#

I am creating a program which shows a form with a text field and activate button, there are certain code which are entered by the user in the text field and on clicking activate button it does the work based on the code inputted by user.
I have successfully created a form and in the activate button click event it calls the method of another class (named Output) like below
Output o = new Output();//Created object for output class
o.effect(s.Text);//here effect() is function of Output and s is textfield
And in Output class's effect() function
void effect(String str)
{
switch(str)
{
case "code1": Console.Write("you enter code1"); //all the things to be done if code1 input
break;
...
...
default: ...;
break;
}
}
The above classes were successfully compiled and run properly. But now I want to make a dll support for this program so that whenever I have to add more code I can just easily create a new dll (Say, Outputversion2.dll) in which there are code like above Output class which can be entered in main program form.
Something like a code extension...
I don't want to mistakenly damage the main program by editing every time to add more codes that's why I thought of it.
Hope you understand what I want to do.
I am just beginner with c# , just learned a month ago.
Sorry for any Grammar error, my English is also not so good.
Thank U.

I'm not sure what you are trying to do here. If you're hoping to be able to dynamically add new DLLs, each with a set of handlers (i.e. cases), then you should probably use the Managed Extensibility Framework. Otherwise, if what you are trying to do is to simply have all handlers in one separate DLL that can be replaced at any time, you should place the Output class in a Class Library, which will compile into a DLL; you can then swap out versions of this DLL without worrying about changing the main program, so long as you don't change the interface (the classes and their functions' return types and parameters; you can change the code inside the function as much as you want).
Also, if your worried about destabilizing the main program, I would recommend keeping backups of the source code, and not releasing new versions until you have fully tested them multiple times.
I hope this helps.

Related

Keyboard event C#

i have this problem, i want to create a small game, for an university project using c#, i need to create a small dll library that contains the game logic, but the core of logic is handle the keyboard events. I know that "System.Form.." allow to listen for keyboard events, but is there a method to handle single keyboard events without using the Form library? I need to create a event that is "launched" when a keyboard button is pressed, an event "like" this:
public OnKeyPress(KeyCode c)
There is a method?
Thanks in advance.
You need something that loads and uses a DLL. The DLL by itself is not going to run. We need some more information regarding how this library will be used. You can create a library that has only processing classes/functions, but somewhere the keyboard will have to be monitored.
Here is a post that discusses global keyboard monitoring. The answer of that question links out to an MSDN article.
Back to what I initially mentioned, you do not need to have the actual events in your library. You can create a library containing only functional code. That code could then be called from a higher level in the overall application where the events are handled. Here is a very simplistic, and honestly hackish, example:
public static class MyKeyboardActions
{
public void HandleKeyCharPress(char keyPressed)
{
switch(keyPressed)
{
case 'A':
// do code for key: A
break;
case 'B':
// do code for key: B
break;
// etc...
}
}
}
If you want something more specific than this, you would need to elaborate more about your project in your question, then I can expand my answer more if needed. As you can see though, there is no need for a System.Windows.Forms reference with that code.

How to invoke method from other file in C#?

In my program, I need Memory Scanner. I've used this one: http://www.codeproject.com/Articles/716227/Csharp-How-to-Scan-a-Process-Memory
I've created a new C# file named MemoryScanner.cs and copied the code there.
How to run it from here:
private void startButton_Click(object sender, EventArgs e)
{
//here I would like to invoke the MemoryScanner
}
Thanks in advance for every help. :)
Apparently (from looking at the code of the link your provided), the entry point of the program is the static method Main in class Program in namespace MemoryScanner. Call this method to start the code.
Some points should be noted:
The implementation is left as an exercise. (If you really don't know how to call a static method in C#, please start with a good, basic C# tutorial.)
Currently, the code analyzes a process called notepad, outputs the result to dump.txt and waits for Console entry before returning. If you want to use that as part of your program, you will need to change these things. (Hint: Remove the Console parts and pass the values, which are currently hard-coded, as method parameters.)
In a nutshell: If you want to use the code, you won't get around reading and (at least partly) understanding it.
You need to add a using statement at the top of your page.
using MemoryScanner;

Global functions

Kind of embarassing to ask this question as it feels like it should be obvious but after god only knows how many google searches I cant seem to find what I'm looking for. Perhaps im just searching the wrong words?
anyway I've started working on a basic to get to grips with the WP8 device to start porting some of my old c# games to play on my shiny new lumia.
anyways. I've created a simple app with a few pages that dont really do a whole lot. few buttons/images etc. the buttons do things and all thats fine and dandy. now i'm wanting to use a particular function on multiple pages but cant for the life of me find where I can put a function in 1 single place that I can use from everywhere.
ie
public void(string blah) {
MessageBox.Show("This is button " + blah);
}
I'd rather not have to have a copy of the same functions on all my created pages. I've got my class file and that works all nice and dandy. Ideally i'd like a functions file. Even if I have to declare it with a line I'd be happy. beats having hundreds of line of the same code throughout my app.
The keyword is static
public static void print(string blah) {
MessageBox.Show("This is button " + blah);
}
lets say this function is in class x
then you would call it as followed: x.print("blah");
You can take a look at WP8 how to create base-page & use it to create base pages with methods, or like what #Svexo said, you can create static functions but also bear in mind Static classes in C#, what's the pros/cons? that recklessly creating static functions all over the place is going create problems in the long run

Using Dynamic Code in C# with Events?

I'm currently implementing a script engine in a game I wrote using the C# "dynamic" feature.
How the system should work is when a script is called, it should register the events it listens for, then return control to the application. Then when an event that the script is listening for is fired the script should execute. One thing I'd really like to implement in the script engine is to have methods with certain names automatically bind to events. For example, the onTurnStart() listener should automatically bind to the turnStart event.
The scripts will mostly need to execute existing methods and change variable values in classes; stuff like player.takeDamage() and player.HP = somevalue. Most scripts will need to wait for the start of the players' turn and the end of the players' turn before being unloaded.
The complicated part is that these scripts need to be able to be changed without making any code changes to the game. (Security aside) the current plan is to have all the script changes automatically download when the game starts up to ensure all the players are using the same version of the scripts.
However I have three questions:
1) How do I register and unregister the script event listeners?
2) Can dynamic code listen for events?
3) (How) can I register events dynamically?
This is my first time using C#'s dynamic feature, so any help will be appreciated.
Thanks
--Michael
I'm not sure you've got the right end of the stick with the dynamic keyword. It doesn't by itself let you interpret new code at runtime. All it does it let you bypass static type checking by delaying the resolution of operations until runtime.
If you're looking to "script" your game, you probably want to take a look at integrating Lua, IronPython, or one of the other DLR languages:-
C#/.NET scripting library
IronRuby and Handling XAML UI Events
Otherwise, the usual thing to do is have something along the lines of:-
interface IBehavior
{
// Binds whatever events this behaviour needs, and optionally adds
// itself to a collection of behaviours on the entity.
void Register(Entity entity);
}
// Just an example
public abstract class TurnEndingDoSomethingBehavior
{
public void Register(Entity entity)
{
entity.TurnEnding += (s, e) => DoSomething();
}
private abstract void DoSomething();
}
The question is, do you want to be able to add entirely new behaviours after compile-time? If so you'll need to expose some or all of your game-state to a scripting language.
Or is it sufficient to be able to compose existing behaviours at runtime?
After your edit
I'm still unsure, to be honest, about your requirement for the dynamic keyword and the DLR. Your game's launcher can download a class library full of behaviours just as easily as it can pull down a set of scripts! (That's what Minecraft's launcher does if memory serves)
If you absolutely must use the DLR then take a look at the links I posted. You'll have to expose as much of your game state as necessary to one of the DLR languages. Events get exposed as first-order-function properties. You shouldn't even need the "dynamic" keyword for basic stuff.
Quick example in IronPython:-
def DoSomethingWhenDamageTaken(*args):
#do whatever...
player.DamageTaken += DoSomethingWhenDamageTaken
The player class:-
public class Player
{
public event EventHandler DamageTaken;
// ...
}
You set it up like:-
ScriptEngine engine = Python.CreateEngine();
ScriptRuntime runtime = engine.Runtime;
ScriptScope scope = runtime.CreateScope();
// In an actual application you might even be
// parsing the script from user input.
ScriptSource source = engine.CreateScriptSourceFromFile(...);
Player p = new Player();
scope.SetVariable("player", p);
source.Execute(scope);
Some links to get you started:-
IronPython: http://ironpython.net/
IronRuby: http://www.ironruby.net/
Lua: http://www.lua.inf.puc-rio.br/post/9

Is is possible to return an object or value from a Python script to the hosting application?

For example in Lua you can place the following line at the end of a script:
return <some-value/object>
The value/object that is returned can then be retrieved by the hosting application.
I use this pattern so that scripts can represent factories for event handlers. The script-based event handlers are then used to extend the application. For example the hosting application runs a script called 'SomeEventHandler.lua' which defines and returns an object that is an event handler for 'SomeEvent' in your application.
Can this be done in Python? Or is there a better way to achieve this?
More specifically I am embedding IronPython in my C# application and am looking for a way to instance these script-based event handlers which will allow the application to be extended using Python.
It's totally possible and a common technique when embedding Python. This article shows the basics, as does this page. The core function is PyObject_CallObject() which calls code written in Python, from C.
This can be done in Python just the same way. You can require the plugin to provide a getHandler() function / method that returns the event handler:
class myPlugin(object):
def doIt(self,event,*args):
print "Doing important stuff"
def getHandler(self,document):
print "Initializing plugin"
self._doc = document
return doIt
When the user says "I want to use plugin X now," you know which function to call. If the plugin is not only to be called after a direct command, but also on certain events (like e.g. loading a graphics element), you can also provide the plugin author with possibilities to bind the handler to this very event.
See some examples in Embedding the Dynamic Language Runtime.
A simple example, setting-and-fetching-variables:
SourceCodeKind st = SourceCodeKind.Statements;
string source = "print 'Hello World'";
script = eng.CreateScriptSourceFromString(source, st);
scope = eng.CreateScope();
script.Execute(scope);
// The namespace holds the variables that the code creates in the process of executing it.
int value = 3;
scope.SetVariable("name", value);
script.Execute(scope);
int result = scope.GetVariable<int>("name");
The way I would do it (and the way I've seen it done) is have a function for each event all packed into one module (or across several, doesn't matter), and then call the function through C/C++/C# and use its return value.

Categories