On my form I have a button click
private void button1_Click(object sender, EventArgs e)
{
do something
}
How on the click would I load my do something from a text file, for example my text file looks like this:
MessageBox.Show("hello");
label1.Text = "Hello";
on click it does everything in my text file, if possible.
Here is a very simple example, just to prove this is possible. Basically, you use CodeDomProvider to compile source at runtime, then execute using reflection.
var provider = CodeDomProvider.CreateProvider("C#");
string src=#"
namespace x
{
using System;
public class y
{
public void z()
{
Console.WriteLine(""hello world"");
}
}
}
";
var result = provider.CompileAssemblyFromSource(new CompilerParameters(), src);
if (result.Errors.Count == 0)
{
var type = result.CompiledAssembly.GetType("x.y");
var instance = Activator.CreateInstance(type);
type.GetMethod("z").Invoke(instance, null);
}
Edit
As #Agat points out, the OP seems to require a sort of scripting framework (it makes use of label1, a property of the current object), whereas my answer above obviously does not provide that. The best I can think of is a limited solution, which would be to require dependencies to be specified explicitly as parameters in the "script". Eg, write the scripted code like this:
string src = #"
namespace x
{
using System.Windows;
public class y
{
public void z(Label label1)
{
MessageBox.Show(""hello"");
label1.Text = ""Hello"";
}
}
}
";
Now you can have the caller examine the parameters, and pass them in from the current context, again using reflection:
var result = provider.CompileAssemblyFromSource(new CompilerParameters(), src);
if (result.Errors.Count == 0)
{
var type = result.CompiledAssembly.GetType("x.y");
var instance = Activator.CreateInstance(type);
var method = type.GetMethod("z");
var args = new List<object>();
// assume any parameters are properties/fields of the current object
foreach (var p in method.GetParameters())
{
var prop = this.GetType().GetProperty(p.Name);
var field = this.GetType().GetField(p.Name);
if (prop != null)
args.Add(prop.GetValue(this, null));
else if (field != null);
args.Add(field.GetValue(this));
else
throw new InvalidOperationException("Parameter " + p.Name + " is not found");
}
method.Invoke(instance, args.ToArray());
}
Like the other answers have stated, it isn't an easy thing to implement and can possibly be done through reflection depending on how advanced your scripts are.
But no one #BrankoDimitrijevic mentioned Roslyn and it is a great tool. http://msdn.microsoft.com/en-us/vstudio/roslyn.aspx
It hasn't been updated in quite awhile (Sept.2012) and doesn't have all of the features of C# implemented, however, it did have a lot of it implemented when I played around with this release.
By adding your assembly as a reference to the scripting session, you're able to gain access to all of your assembly's types and script against them. It also supports return values so you can return any data that a scripted method generates.
You can find what isn't implemented here.
Below is a quick and dirty example of Roslyn that I just wrote and tested. Should work right out of box after installing Roslyn from NuGet. The small bloat at the initialization of the script engine can easily be wrapped up in a helper class or method.
The key is passing in a HostObject. It can be anything. Once you do, your script will have full access to the properties. Notice that you just call the properties and not the host object in the script.
Basically, your host object will contain properties of the data you need for your script. Don't necessarily think of your host object as just a single data object, but rather a configuration.
public class MyHostObject
{
public string Value1 { get; set; }
public string Value2 { get; set; }
}
public class RoslynTest
{
public void Test()
{
var myHostObject = new MyHostObject
{
Value1 = "Testing Value 1",
Value2 = "This is Value 2"
};
var engine = new ScriptEngine();
var session = engine.CreateSession(myHostObject);
session.AddReference(myHostObject.GetType().Assembly.Location);
session.AddReference("System");
session.AddReference("System.Core");
session.ImportNamespace("System");
// "Execute" our method so we can call it.
session.Execute("public string UpdateHostObject() { Value1 = \"V1\"; Value2 = \"V2\"; return Value1 + Value2;}");
var s = session.Execute<string>("UpdateHostObject()");
//s will return "V1V2" and your instance of myHostObject was also changed.
}
}
No. You can not.
At least in any simple way.
The thing you want is something like eval('do something') from javascript.
That's not possible to do with C#. C# is a language which needs compilation before execution unlike javascript (for instance).
The only way to implement that is to build your own (pretty complicated as for beginner) parser and execute it in such way.
UPDATED:
Actually, as JDB fairly noticed, that's really not the only way. I love programming! There are so many ways to make a freakky (or even sometimes that really can be necessary for some custom interesting tasks (or even learning)!) code. he he
Another approach I've got in my mind is building some .cs file, then compiling it on-the-fly and working with it as some assembly or some other module. Right.
Related
With Mono.Cecil it looks quite simple when we can just set the Body of the target MethodDefinition to the Body of the source MethodDefinition. For simple methods, that works OK. But for some methods whereas a custom type is used (such as to init a new object), it won't work (with an exception thrown at the time writing the assembly back).
Here is my code:
//in current app
public class Form1 {
public string Test(){
return "Modified Test";
}
}
//in another assembly
public class Target {
public string Test(){
return "Test";
}
}
//the copying code, this works for the above pair of methods
//the context here is of course in the current app
var targetAsm = AssemblyDefinition.ReadAssembly("target_path");
var mr1 = targetAsm.MainModule.Import(typeof(Form1).GetMethod("Test"));
var targetType = targetAsm.MainModule.Types.FirstOrDefault(e => e.Name == "Target");
var m2 = targetType.Methods.FirstOrDefault(e => e.Name == "Test");
var m1 = mr1.Resolve();
var m1IL = m1.Body.GetILProcessor();
foreach(var i in m1.Body.Instructions.ToList()){
var ci = i;
if(i.Operand is MethodReference){
var mref = i.Operand as MethodReference;
ci = m1IL.Create(i.OpCode, targetType.Module.Import(mref));
}
else if(i.Operand is TypeReference){
var tref = i.Operand as TypeReference;
ci = m1IL.Create(i.OpCode, targetType.Module.Import(tref));
}
if(ci != i){
m1IL.Replace(i, ci);
}
}
//here the source Body should have its Instructions set imported fine
//so we just need to set its Body to the target's Body
m2.Body = m1.Body;
//finally write to another output assembly
targetAsm.Write("modified_target_path");
The code above was not referenced from anywhere, I just tried it myself and found out it works for simple cases (such as for the 2 methods Test I posted above). But if the source method (defined in the current app) contains some Type reference (such as some constructor init ...), like this:
public class Form1 {
public string Test(){
var u = new Uri("SomeUri");
return u.AbsolutePath;
}
}
Then it will fail at the time writing the assembly back. The exception thrown is ArgumentException with the following message:
"Member 'System.Uri' is declared in another module and needs to be imported"
In fact I've encountered a similar message before but it's for method calls like (string.Concat). And that's why I've tried importing the MethodReference (you can see the if inside the foreach loop in the code I posted). And really that worked for that case.
But this case is different, I don't know how to import the used/referenced types (in this case it is System.Uri) correctly. As I know the result of Import should be used, for MethodReference you can see that the result is used to replace the Operand for each Instruction. But for Type reference in this case I totally have no idea on how.
All my code posted in my question is fine BUT not enough. Actually the exception message:
"Member 'System.Uri' is declared in another module and needs to be imported"
complains about the VariableDefinition's VariableType. I just import the instructions but not the Variables (which are just referenced exactly from the source MethodBody). So the solution is we need to import the variables in the same way as well (and maybe import the ExceptionHandlers as well because an ExceptionHandler has CatchType which should be imported).
Here is just the similar code to import VariableDefinition:
var vars = m1.Body.Variables.ToList();
m1.Body.Variables.Clear();
foreach(var v in vars){
var nv = new VariableDefinition(v.Name, targetType.Module.Import(v.VariableType));
m1.Body.Variables.Add(nv);
}
I'm writing an app which converts keys to use resources from a RESX File. This code was working with local variables before:
public static void AnalyzeConstDeclaration(SyntaxNodeAnalysisContext context)
{
var fieldDeclaration = (FieldDeclarationSyntax)context.Node;
if (false == IsValidFieldDeclaration(context, fieldDeclaration))
{
return;
}
var firstVariable = fieldDeclaration.Declaration.Variables.FirstOrDefault();
var dataFlowAnalysis = context.SemanticModel.AnalyzeDataFlow(firstVariable);
var variableSymbol = context.SemanticModel.GetDeclaredSymbol(firstVariable);
if (dataFlowAnalysis.WrittenOutside.Contains(variableSymbol))
{
return;
}
var firstSymbol = context.SemanticModel.GetDeclaredSymbol(firstVariable);
context.ReportDiagnostic(Diagnostic.Create(Rule, context.Node.GetLocation(), firstSymbol.Name));
}
However when I try to get the dataFlowAnalysis I receive an error:
Additional information: statementOrExpression is not a StatementSyntax or an ExpressionSyntax.
How can Ideally just need to see if anyone has written to this variable outside of the declaration.
DataFlow works by analyzing order of execution within a single method.
It doesn't make sense for class-level fields.
Instead, you should use a simple syntax visitor (or SymbolFinder) to search the entire class for assignments to the field.
You'll probably also want to check whether it's ever passed as a ref parameter.
So I want to build this little code sandbox in Unity, which would allow me to teach students the basics of algorithmics and coding.
The idea would be for them to enter (very basic) code in a text box or something of the kind, and to observe the effects of their code onto objects present in a Unity scene. I'm pretty sure this has been done a million times, but I'd love to try my hand at this. The rub is, I have no idea where to start...
I guess the idea is that the string would be compiled into code & executed at runtime, at the press of a button.
I've read about numerous other questions on SO, and have come up with very diverse solutions such as using a C# parser, reflection, expression trees, CodeDom, etc.
From what I understood of all these (i.e., not much), CodeDom seemed more appropriate, but then I read that it only ran inside of Visual Studio and generated errors in public builds. So does that mean that this is going to be a problem within Unity3D (as it is based on Mono?)
Thank you for your help,
In the following case, you look for an existing method of the given name on the same script (you can easily convert it to another script or any script in the assembly (not recommended though)):
string actionStr = inputField.text;
Type t = this.GetType();
MethodInfo mi = t.GetMethod(actionStr);
if(mi == null)
{
ErrorMethod(actionStr + " method could not be found");
}else
{
mi.Invoke(this);
}
Another way would be to store all the methods in a dictionary (faster):
Dictionary<string, Action>dict = null;
void Start()
{
this.dict = new Dictionary<string, Action>();
this.dict.Add("dosomething", DoSomething);
}
void DoSomething(){}
public void OnActionCall(string inputFieldStr)
{
string str = inputFieldStr.ToLower();
if(this.dict.Contains(str) == false)
{
ErrorMethod(actionStr + " method could not be found");
return;
}
this.dict[str]();
}
I have a bit of complicated situation. I must create analyzers/ code fix providers for situations such as a parameter is only assigned but never used or local variable are never used.
For the parameter situation, I'm going for the method declaration and looking at the parameter list to get all the analyzer. I'm going through assignment expressions within the method and I filter the parameters that were assigned with an helper method.
Where it gets fuzzy is I have no clue or to know when a local variable/parameter is used or not. I've gone through symbols but they can't tell me that variable used/ not used. I could try to find how many times a variable's name was mentioned inside a method by turning the method declaration syntax context in a string and look for the parameters that were assigned but that's simply such a BAD idea.
I'm really stuck and I would some help for this from anyone who had previous experience with this kind of situation.
For people who might ask, I'm mostly looking for the missing logic for the analyzer. I have no idea how the code fix provider will work. If you have an idea of what I could do, feel free to include it in your answer ! As of now, I was thinking that a local variable that's not used could be deleted from a method and the same could go for an unused parameter. I'm not sure at the moment.
UPDATE
I'm now trying to use the DataFlow API but it's not working for me at the moment. The oldest answer of this thread gave me a starting point but it's actually not working.
I came up with my own way :
private static bool IsLocalVariableBeingUsed(VariableDeclaratorSyntax variableDeclarator, SyntaxNodeAnalysisContext syntaxNode)
{
var model = syntaxNode.SemanticModel.Compilation.GetSemanticModel(variableDeclarator.SyntaxTree);
var methodBody = variableDeclarator.AncestorsAndSelf(false).OfType<MethodDeclarationSyntax>().First();
var lastMethodNode = methodBody?.ChildNodes().LastOrDefault();
if (lastMethodNode == null)
return false;
var readWrite = syntaxNode.SemanticModel.AnalyzeDataFlow(variableDeclarator, lastMethodNode);
}
But this also is not working. When using a test with NUnit :
var input = #"
class TestClass {
void TestMethod ()
{
int i;
}
}";
I get the following message when the runtime gets to either readWrite or result(from oldest answer):
System.ArgumentOutRangeException Index was out of range Must be non negative and lesser than the size of the collection"
But before that in my analyzer, when I try to validate my node to make sure it's not null and create the appropriate elements for the data flow API, there's no code break (not sure if that is the appropriate term) but at the moment I cannot progress.
You can see whether or not most variable are used (read/written) via the DataFlowAnalysis APIs. I've written an introduction to this API on my blog.
I believe in your case, you're looking for variables that are never read.
var tree = CSharpSyntaxTree.ParseText(#"
public class Sample
{
public void Foo()
{
int unused = 0;
int used = 1;
System.Console.Write(used);
}
}");
var Mscorlib = PortableExecutableReference.CreateFromAssembly(typeof(object).Assembly);
var compilation = CSharpCompilation.Create("MyCompilation",
syntaxTrees: new[] { tree }, references: new[] { Mscorlib });
var model = compilation.GetSemanticModel(tree);
var methodBody = tree.GetRoot().DescendantNodes().OfType<MethodDeclarationSyntax>().Single().Body;
DataFlowAnalysis result = model.AnalyzeDataFlow(methodBody);
var variablesDeclared = result.VariablesDeclared;
var variablesRead = result.ReadInside.Union(result.ReadOutside);
var unused = variablesDeclared.Except(variablesRead);
foreach(var variable in unused)
{
Console.WriteLine(variable);
}
Building on JoshVarty's answer, to get this to work in a diagnostic, I would register a SyntaxNodeAction for all MethodDeclaration Syntax Kinds and then look inside the body for unused variables:
public override void Initialize(AnalysisContext context)
{
context.RegisterSyntaxNodeAction(AnalyzeIt, SyntaxKind.MethodDeclaration);
}
private static void AnalyzeIt(SyntaxNodeAnalysisContext context)
{
var method = context.Node as MethodDeclarationSyntax;
var dataFlow = context.SemanticModel.AnalyzeDataFlow(method.Body);
var variablesDeclared = dataFlow.VariablesDeclared;
var variablesRead = dataFlow.ReadInside.Union(dataFlow.ReadOutside);
var unused = variablesDeclared.Except(variablesRead);
if (unused.Any())
{
foreach (var unusedVar in unused)
{
context.ReportDiagnostic(Diagnostic.Create(Rule, unusedVar.Locations.First()));
}
}
}
Suppose I am watching something in VS2008 and I want to search the object I'm watching for an instance of a particular value.
For example, say I'm watching this and I want to search for a control called mycontrol inside it or I want to search for a string that currently has the value of "Hello World".
I know it's kind of a brute force way of doing things, but I find it would be a quick way of identifying where things are going wrong whilst debugging. Warning: I'm about to swear... When I was using PHP, I could see all variables that were currently set by using get_defined_vars(). It was dirty, but it was quick and I'd like to know if there's something similar I can do in VS.
Sorry if I've been a little vague, I'd be happy to elaborate if you have questions.
Cheers
Iain
Edit:
What I'm actually tring to do is interrogate the current state of the application and quickly search for the various classes that I want to debug. What I'm doing is trying to debug where I don't have the source code (I'm writing a control for a CMS). So I know what the value of something should be, but I don't know where in the structure it exists - that's what I want to find.
e.g. An exeption is thrown by the application because foo should be a list of the type bar. I want to find out where foo is defined so I can look around and see what the other variables in the same class are set to.
Sorry again, I'm finding it hard to explain :(
Edit #2:
I find a good tree might help me visualise it better...
Quickwatch
-this
-var1
+var1a
+var1b
-var1c
-base
-foo = "Hello World"
+var1ca
+var2
+var3
In the above, how would I quickly drill down through the structure to find foo?
It sounds like you want a conditional breakpoint:
When the breakpoint location is
reached, the expression is evaluated
and the breakpoint is hit only if the
expression is true or has changed.
Create a new breakpoint, right-click on it, and select "Condition..." Enter the condition you'd like to wait for. It'll be something like:
this.MyString == "Hello World"
EDIT: Ok, I understand now you want to interrogate another, running application. Assuming it was built in a managed language, you may be interested in Hawkeye:
Hawkeye is the only .Net tool that
allows you to view, edit, analyze and
invoke (almost) any object from a .Net
application. Whenever you try to
debug, test, change or understand an
application, Hawkeye can help.
Free. Not been updated in a while.
I wrote this the other day. It did the job well enough (however it is only some utility code for debugging, so use at your own risk --> the design is pretty bad >_< ). Dumps out the fields and iterates downwards. It might not be perfect, but it solved my problem at the time.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
public static class Dumper
{
public class Dump
{
public Dump(bool spacesInsteadOfTab)
{
_spacesIndeadOfTab = spacesInsteadOfTab;
}
private readonly StringBuilder _sb = new StringBuilder();
public string Result
{
get
{
return _sb.ToString();
}
}
private readonly bool _spacesIndeadOfTab;
private int _currentIndent;
public int CurrentIndent
{
get
{
return _currentIndent;
}
set
{
_currentIndent = value > 0 ? value : 0;
}
}
public void IncrementIndent()
{
CurrentIndent += 1;
}
public void DecrementIndent()
{
CurrentIndent -= 1;
}
private void AppendIndent()
{
if (_spacesIndeadOfTab)
_sb.Append(' ', _currentIndent * 4);
else
_sb.Append('\t', _currentIndent);
}
public void Log(string logValue)
{
AppendIndent();
_sb.AppendLine(logValue);
}
public void Log(string logValue, params object[] args)
{
AppendIndent();
_sb.AppendFormat(logValue, args);
_sb.AppendLine();
}
}
public static Dump TakeDump(object objectToDump, int maxDepth)
{
Dump result = new Dump(false);
int currentDepth = 0;
TakeDump(ref result, ref currentDepth, maxDepth, objectToDump);
return result;
}
private static void TakeDump(ref Dump result, ref int currentDepth, int maxDepth, object objectToDump)
{
currentDepth++;
if (currentDepth > maxDepth)
{
result.IncrementIndent();
result.Log("MaxDepth ({0}) Reached.", maxDepth);
result.DecrementIndent();
return;
}
var objectType = objectToDump.GetType();
result.Log("--> {0}", objectType.FullName);
result.IncrementIndent();
var fields = objectType.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
if (fields.Count() == 0)
result.Log("No fields");
foreach (var fieldInfo in fields)
{
var fieldValue = fieldInfo.GetValue(objectToDump);
if (fieldValue == null)
result.Log("{0} is null", fieldValueType.FullName, fieldInfo.Name);
var fieldValueType = fieldValue.GetType();
if (fieldValueType.IsValueType)
result.Log("{2} as {0} (ToString: {1})", fieldValueType.FullName, fieldValue.ToString(), fieldInfo.Name);
else
TakeDump(ref result, ref currentDepth, maxDepth, fieldValue);
}
result.DecrementIndent();
}
}
It sounds like you are envisioning a feature which would descend down the tree presented in the debugger UI looking for a typed in value. This is not a feature of the debugger at this time (although at first glance it sounds handy). It would have problems though in cases where the expression had infinite expansions.
Circular references for instance will cause an infinite expansion. Those are fairly easy to track down but there are more nefarious tricks which can be done to make infinite expansion harder / impossible to track. True we could probably control for depth and such ...
I think your best bet is to write a reflection based searching mechanism with a depth control mechanism. Then call this API from the debugger window.