Best way to run a string as c# code - c#

Let's say I have:
#{
var str= "DateTime.Now";
}
I want to process this string as a c# code
#Html.Raw(App.ProcessAsCode(str));
The output should be the current date time.

Final Edit:
Based on further information - if the goal here is to simply have a formatting engine there are lots of options out there. One such option is based around the .liquid syntax from shopify (see here). You can find a .NET port of this on gitHub here: https://github.com/formosatek/dotliquid/. The main purpose of this is to turn something like:
<h2>{{product.name}}</h2>
Into something like:
<h2>Beef Jerky</h2>
I would strongly recommend reading more about the liquid engine and syntax and I believe this will lead you in the right direction. Best of luck!
Initial Answer
This is definitely possible - although as others have said you will want to be careful in what you do. Using C# the key to compiling and running code generically is the "CSharpCodeProvider" class. Here is a brief example of how that looks:
string[] references = { "System.dll" };
CompilerParams.ReferencedAssemblies.AddRange(references);
var provider = new CSharpCodeProvider();
CompilerResults compile = provider.CompileAssemblyFromSource(CompilerParams, formattedCode);
In this example, "formattedCode" is a string with the C# code. Any references must be manually added. For the full example see this stack question (How to get a Type from a C# type name string?).
NOTE -- If all you are looking to do here is a format string or something simple like that you might have the user pass in a .NET format string (eg "MM/dd/yyyy"), then use that in a call to the "ToString" method. That would provide the user some configurability, while still making sure your system stays secure. In general running code on a server that hasn't been properly checked/escaped is really dangerous!
Reference - For your reference, the current msdn page for CSharpCodeProvider also has some examples.

Another option would be using a dynamic language such as IronRuby or IronPython.

Related

ToIntArray - Replacement function

According to http://crsouza.blogspot.com.br/2012/01/decision-trees-in-c.html I use
DataTable symbols = codebook.Apply(data);
int[][] inputs = symbols.ToIntArray("Outlook", "Temperature", "Humidity", "Wind");
int[] outputs = symbols.ToIntArray("PlayTennis").GetColumn(0);
But in .net 4.0 and in mono there is no ToIntArray, also I could not find any replacement function for it.
How does ToIntArray convert symbols or, what does ToIntArray look like?
If you don't want to download and add the Accord framework to your project (Note: there is a chance it might have dependencies which are not supported by Xamarin's .NET implementation), then luckily it's open source, so if you want to just see the code it's available to the public.
To answer the specific question, the .ToIntArray extension method (which is just an "alias" method for ToArray<int>()) can be seen here:
https://code.google.com/p/accord/source/browse/trunk/Sources/Accord.Math/Matrix/Matrix.Conversions.cs
However, the .Apply and .GetColumn methods (from your sample code) is also part of the framework, so you'd probably need to look at that code as well. See Matrix.Common and Matrix.Selection.
As of the current version, you can use ToInt32(), as well as ToDouble(), ToSingle(), ToBoolean() and others to perform type conversions of arrays.

Error calling C++/CLI constructor from C#

I am trying to save and restore state by using a StateBlock in SlimDX via the following snippet:
StateBlockMask mask = new StateBlockMask(null) { RasterizerState = true };
var sb = new StateBlock(device.Device, mask);
Both StateBlockMask and StateBlock are classes. This gives me a compilation error:
'.ctor' is not supported by the language
Reading from some other posts here on SO, it seems that this is a problem that has to do with calling the managed code with the wrong arguments. In the source of SlimDX, I find:
StateBlock::StateBlock(SlimDX::Direct3D10::Device^ device, StateBlockMask mask)
I have no experience at all with C++/CLI, so I am wondering if there is something wrong here (like a missing or extra ^), or should I concentrate of faults on my side?
(NOTE: This question has been cross-posted to gamedev.net, future users with the same question may also want to check for answers given there)
Is StateBlockMask a struct? If not, use StateBlockMask^ mask in the C++ constructor.
This looks like a bug in SlimDX. You might want to use the issue tracker to make sure it gets dealt with properly.

A program that creates another program

I need to create a program that creates another program but not a compiler though.
For example,
I write a program that accepts a string input from the user. Let's say user enter "Pluto". This program should then create a separate .exe that says "Hello Pluto" when executed.
How can I do this? If you could give example in C# and Windows Forms, it's better.
Thanks.
Basically that is a compiler - just for a particularly simple language.
If you can express the final program in C#, the easiest solution is probably to use CSharpCodeProvider. That's what I do for Snippy, a little tool to help run code snippets easily for C# in Depth. The source code to Snippy is on the C# in Depth web site and can give you an idea of what you might do - basically you'd just want it to write the executable to a file instead of building it in memory.
Alternatively, look at the MSDN docs which have an example generating an executable.
The classes you are looking for are in the Microsoft.CSharp namespace
CSharpCodeProvider codeProvider = new CSharpCodeProvider();
ICodeCompiler icc = codeProvider.CreateCompiler();
System.CodeDom.Compiler.CompilerParameters parameters = new CompilerParameters();
parameters.GenerateExecutable = true;
parameters.OutputAssembly = Output;
CompilerResults results = icc.CompileAssemblyFromSource(parameters,SourceString);
(from microsoft support found by using google - taking less than 20 sec)
Tentatively, you can also achive this throught he use of things in the System.Reflection.Emit namespace and I believe it's possible to provide the implementation of a method through the use of LINQ expression trees. Which is kind of neat:
var assembly = AppDomain.CurrentDomain.DefineDynamicAssembly(new AssemblyName("TestAssembly"), AssemblyBuilderAccess.RunAndSave);
var mod = assembly.DefineDynamicModule("TestModule");
var type = mod.DefineType("TestType");
var method = type.DefineMethod("Increment", MethodAttributes.Public, typeof(int), Type.EmptyTypes);
Expression<Func<int, int>> inc = (a) => a + 1; // this is cool
inc.CompileToMethod(method);
It might look a bit daunting at first, but it's really cool stuff, and you let the compiler generate the hard stuff, the method implementation. But you can't really create fields like this, that's gonna require some IL. Which is great fun but really tedious work.
DISCLAIMER:
I haven't tried to run the above code. But I know it goes something like that, it's been a while since I've done something like that.
The easiest thing to do would be to create (in advance) a really short simple program that reads a resource from itself and prints it. Then your application needs only to place that program binary on disk somewhere and call the UpdateResource function to change the string. .NET also has resource support, but I don't know of any function that directly corresponds to UpdateResource.
Use Reflection.Emit.
http://msdn.microsoft.com/en-us/library/8ffc3x75.aspx
http://www.codeproject.com/KB/cs/DynamicCodeGeneration2.aspx
How to build a HelloWorld.exe using Reflection.Emit (it's less than half-page of code):
Link

How will you use the C# 4 dynamic type?

C# 4 will contain a new dynamic keyword that will bring dynamic language features into C#.
How do you plan to use it in your own code, what pattern would you propose ? In which part of your current project will it make your code cleaner or simpler, or enable things you could simply not do (outside of the obvious interop with dynamic languages like IronRuby or IronPython)?
PS : Please if you don't like this C# 4 addition, avoid to bloat comments negatively.
Edit : refocussing the question.
The classic usages of dynamic are well known by most of stackoverflow C# users. What I want to know is if you think of specific new C# patterns where dynamic can be usefully leveraged without losing too much of C# spirit.
Wherever old-fashioned reflection is used now and code readability has been impaired. And, as you say, some Interop scenarios (I occasionally work with COM).
That's pretty much it. If dynamic usage can be avoided, it should be avoided. Compile time checking, performance, etc.
A few weeks ago, I remembered this article. When I first read it, I was frankly appalled. But what I hadn't realised is that I didn't know how to even use an operator on some unknown type. I started wondering what the generated code would be for something like this:
dynamic c = 10;
int b = c * c;
Using regular reflection, you can't use defined operators. It generated quite a bit of code, using some stuff from a Microsoft namespace. Let's just say the above code is a lot easier to read :) It's nice that it works, but it was also very slow: about 10,000 times slower than a regular multiplication (doh), and about 100 times slower than an ICalculator interface with a Multiply method.
Edit - generated code, for those interested:
if (<Test>o__SiteContainer0.<>p__Sitea == null)
<Test>o__SiteContainer0.<>p__Sitea =
CallSite<Func<CallSite, object, object, object>>.Create(
new CSharpBinaryOperationBinder(ExpressionType.Multiply,
false, false, new CSharpArgumentInfo[] {
new CSharpArgumentInfo(CSharpArgumentInfoFlags.None, null),
new CSharpArgumentInfo(CSharpArgumentInfoFlags.None, null) }));
b = <Test>o__SiteContainer0.<>p__Site9.Target(
<Test>o__SiteContainer0.<>p__Site9,
<Test>o__SiteContainer0.<>p__Sitea.Target(
<Test>o__SiteContainer0.<>p__Sitea, c, c));
The dynamic keyword is all about simplifying the code required for two scenarios:
C# to COM interop
C# to dynamic language (JavaScript, etc.) interop
While it could be used outside of those scenarios, it probably shouldn't be.
Recently I have blogged about dynamic types in C# 4.0 and among others I mentioned some of its potential uses as well as some of its pitfalls. The article itself is a bit too big to fit in here, but you can read it in full at this address.
As a summary, here are a few useful use cases (except the obvious one of interoping with COM libraries and dynamic languages like IronPython):
reading a random XML or JSON into a dynamic C# object. The .Net framework contains classes and attributes for easily deserializing XML and JSON documents into C# objects, but only if their structure is static. If they are dynamic and you need to discover their fields at runtime, they can could only be deserialized into dynamic objects. .Net does not offer this functionality by default, but it can be done by 3rd party tools like jsonfx or DynamicJson
return anonymous types from methods. Anonymous types have their scope constrained to the method where they are defined, but that can be overcome with the help of dynamic. Of course, this is a dangerous thing to do, since you will be exposing objects with a dynamic structure (with no compile time checking), but it might be useful in some cases. For example the following method reads only two columns from a DB table using Linq to SQL and returns the result:
public static List<dynamic> GetEmployees()
{
List<Employee> source = GenerateEmployeeCollection();
var queyResult = from employee in source
where employee.Age > 20
select new { employee.FirstName, employee.Age };
return queyResult.ToList<dynamic>();
}
create REST WCF services that returns dynamic data. That might be useful in the following scenario. Consider that you have a web method that returns user related data. However, your service exposes quite a lot of info about users and it will not be efficient to just return all of them all of the time. It would be better if you would be able to allow consumers to specify the fields that they actually need, like with the following URL
http://api.example.com/users?userId=xxxx&fields=firstName,lastName,age
The problem then comes from the fact that WCF will only return to clients responses made out of serialized objects. If the objects are static then there would be no way to return dynamic responses so dynamic types need to be used. There is however one last problem in here and that is that by default dynamic types are not serializable. In the article there is a code sample that shows how to overcome this (again, I am not posting it here because of its size).
In the end, you might notice that two of the use cases I mentioned require some workarounds or 3rd party tools. This makes me think that while the .Net team has added a very cool feature to the framework, they might have only added it with COM and dynamic languages interop in mind. That would be a shame because dynamic languages have some strong advantages and providing them on a platform that combines them with the strengths of strong typed languages would probably put .Net and C# ahead of the other development platforms.
Miguel de Icaza presented a very cool use case on his blog, here (source included):
dynamic d = new PInvoke ("libc");
d.printf ("I have been clicked %d times", times);
If it is possible to do this in a safe and reliable way, that would be awesome for native code interop.
This will also allow us to avoid having to use the visitor pattern in certain cases as multi-dispatch will now be possible
public class MySpecialFunctions
{
public void Execute(int x) {...}
public void Execute(string x) {...}
public void Execute(long x) {...}
}
dynamic x = getx();
var myFunc = new MySpecialFunctions();
myFunc.Execute(x);
...will call the best method match at runtime, instead of being worked out at compile time
I will use it to simplify my code which deals with COM/Interop where before I had to specify the member to invoke, its parameters etc. (basically where the compiler didn't know about the existence of a function and I needed to describe it at compile time). With dynamic this gets less cumbersome and the code gets leaner.

Overhead for not simplifying names in C#

I am working with a C# windows forms application (I doubt the project type affects answer but there it is anyways) and everything is going good. Code works fine. However Visual studio likes to tell me that Name can be simplified' when I do things like like usingthisin some methods where thethis` may not be needed. Here is an example:
public class xyz
{
string startdate;
string enddate;
private void calculateElapsedTime()
{
var endDate = Convert.ToDateTime(this.enddate).ToUniversalTime();
var startDate = Convert.ToDateTime(this.startdate).ToUniversalTime();
elapsedtime = (decimal)(endDate - startDate).TotalSeconds;
}
}
The names that can be simplified are this.startdateand this.enddate
The code runs fine without the this keyword but personally I like using the 'this' as for me it makes it more clear what is being done.
I tried running tests on memory usage and time if I go through and simplify all places where VS says I should and I ran the same test without simplifying names and got the same results.
So this has lead me to the question, Is there any actual performance hit for not simplifying names or is the hit so small that I just don't see the difference because my program isn't big enough or some third option?
EDIT
Since this is starting to get into a discussion on naming conventions figured I would add this. The above is a just an example of code that has a name that can be simplified not the actual way I write code. The name can be simplified message also would show up if you use the namespaceX.class.functionname in code already x namespace.
Is there any actual performance hit for not simplifying names or is the hit so small that I just don't see the difference because my program isn't big enough or some third option?
Not in the slightest. This is just a style choice that has no impact on the compiled code.
I would pick a different name for your local variables, though. Having the same name with just different casing on one letter makes it hard to distinguish between the local variable and the member name.
There will not be a difference in the performance or memory footprint of the application. Your C# code is translated into IL by the compiler, and that is the code that is executed - since the compiler understands both the version with this and without, the resulting IL will be identical in both cases, and as such so will the performance of the program.
You can like or not qualifying class member access with this, but since in C# is avoidable and one of most important premises in programming is keep as simple as possible, while it's just a coding style issue, it's still interesting that you understand that this in C# is used when you need to disambiguate an access to a local variable and a class member.
There's no performance hit and it's just about that you get used with C# coding style. For example, you use camel-casing on method identifiers while C# coding style says that they should be pascal-cased.
Like any other convention and guideline, it's just there to make your code more predictable to others rather than to yourself (and once you get used with these guidelines, they're also predictable for you too ;)).
BTW - the reason not to use this is because it makes you think that you dont need a naming convention for member variables.
Many people use a convention like
string _enddate
string endate_
string m_endate
that way you can tell by looking at the code that this is a member variable.
Using this.endate also says it is a member variable but the same code compiles if you just say enddate. Now you have code that compiles but you cannot tell at a glance if its a member or not

Categories

Resources