C# taking arguments & declaring at runtime from text file - c#

I have a text file with the following:
int A = 5 ;
string str = "tempstring" ;
str DosomeMethod 15 16 20 22 ;
When reading the text file thru my program, I want to declare int A = 5 & string str = "tempstring" at runtime.
It can be like
string[] st = freader.readline().split(' ');
if (st[0]=="int")
{
str[0] str[1] = str[4];
}
I know that the above is the wrong syntax but I want to do something like this with some reference.
Can anybody help without using irony .net?

This is relatively advanced material.
You can't really do as you said. C# is a strongly-typed language.
Although, you may seek to one of these solutions:
IronPython - a script language which uses .NET.
C#'s dynamic keyword.
Reflection
Dynamically compiling C# code within application
Or, if you seek a quick solution, you may set these variables (string temp and so on) within your code, then put values into them according to the string.

Related

Symbolic Manipulation Within .Net

I recall an assigment in one of my computer science classes that involved symbolic differentiation with Common Lisp. The properties of common lisp allows you to take an equation and apply symbolic manipulation.
My question is, are there any libraries and programming languages within the .Net framework that allows symbolic manipulation? I'd prefer using C# to solve this. I've already looked at this link but it doesn't give concrete answers.
Let me explain my situation in more detail.
Suppose I have conditional formula, the entirety as a String.
Each name 1DPZ_XY represents an integer variable.
Each of these variables have already been assigned a value.
"
{
1DPZ_a2 = (2 OR 3)
AND
(
1DPZ_a6 = 9
OR
1DPZ_b3 = (3 OR 7)
AND
(
1DPZ_b4 = 8
OR
1DPZ_b5 = 2
OR
1DPZ_b6 = (4 OR 2)
)
)
}
"
Obviously this formula will return either true or false.
How can I convert this String logic into a if-statement I can interact with?
You can parse your string and build a .NET Expression Tree from it. You can then manipulate that expression tree to evaluate it, print it, or transform it (typically using an ExpressionVisitor).

what kind of language is that?

I received a piece of code but I cannot understand what kind of language it is. It looks like C# but C# uses the "using" clause in order to import a library where on this programming language file it uses a "use" clause. I cannot find any information about the "use" clause and I am actually confused because this programming language looks like C#/Java/Visual Basic but on these languages I cannot find the use of the "use" clause. The weird thing is that the code doesn't use any methods and the file I received had a .txt extension.
the file starts like that:
use Collection, File, Stream, String, System;
use Date;
include globals.routines.global_routines_generic;
include globals.routines.global_routines_mcc;
include globals.routines.global_classifier;
after that they declare a bunch of variables with the "var" clause and then a part of code looks like that:
File.createFolder(settings.path_files);
foreach(i, Folder in Folders) {
if (dlc.allfolders || String.contains(Folder, dlc.specific_folder)) {
Bestanden = File.iterateFiles(Folder.path, true);
stop_word_list = load_stop_words();
foreach(j, Bestand in Bestanden) {
if (rerun) {
if (!String.contains(Bestand, "ONBEKEND")) {
continue ;
}
}
writeAuditTrail (logfile, String.join(["Processing file " , Bestand]), 0, savelog);
folder_items = String.split(Bestand, "\\\\", false);
last_folder_name = folder_items[Collection.length(folder_items)-2];
dossier_tab = get_dossier_tab(folder_items[Collection.length(folder_items)-1], dlc);
possible_docs = dlc.HR_dossier_tabs[dossier_tab];
Does anyone have any idea what kind of language is that?
Thank you in advance
The code is closest to c++. It is definitely not java due to the fact that java does not have the foreach loop, the use keyword, and var. It is also probably not C# because of the library include syntax. It could be low level pseudo code but it is unlikely due to the syntax being so close to a C based language. enter link description here

In C# can you split a string into variables?

I recently came across a php code where a CSV string was split into two variables:
list($this->field_one, $this->field_two) = explode(",", $fields);
I turned this into:
string[] tmp = s_fields.Split(',');
field_one = tmp[0];
field_two = tmp[1];
Is there a C# equivalent without creating a temporary array?
Jon Skeet said the right thing. GC will do the thing, don't you worry.
But if you like the syntax so much (which is pretty considerable), you can use this, I guess.
public static class MyPhpStyleExtension
{
public void SplitInTwo(this string str, char splitBy, out string first, out string second)
{
var tempArray = str.Split(splitBy);
if (tempArray.length != 2) {
throw new NotSoPhpResultAsIExpectedException(tempArray.length);
}
first = tempArray[0];
second = tempArray[1];
}
}
I almost feel guilty by writing this code. Hope this will do the thing.
The answer to your quite narrow question is no. C# does not provide a 'multi-assignment' capability, so you cannot extract an arbitrary set of values from anything (such as Split()) and break them out into individual named variables.
There is a workaround for a specific number of variables, by writing a parameter with out arguments. See #vlad for an answer based on that.
But why would you want to? C# provides an impressive range of features that will allow you to take apart strings and deal them with the parts in a such a wide range of different ways that the lack of 'multi-assignment' should barely be noticed.
Parsing strings usually involves other operations such as dealing with formatting errors, trimming white space, case folding. There could be less than 2 strings, or more. Requirements could change over time. When you are ready for a more capable string parser, C# will be waiting.
You may use the following approach:
-Create a class that inherits from dynamic object.
-Create a local dictionary that will store your variables values in the inherited class.
-Override the TryGetMember and TrySetMember functions to get and set values from and into the dictionary.
-Now, you can split your string and put it in the dictionary, then access your variable like:
dynamicObject.var1

C++ string vs C# string, different running times. Why?

I was experimenting with C++ to observe the effects of variables' scope-bounded-declarations and usage in loops on the running time of the program, as follows:
for(int i=0; i<10000000 ; ++i){
string s = "HELLO THERE!";
}
and
string s;
for(int i=0; i<10000000 ; ++i){
s = "HELLO THERE!";
}
The first program run in ~1 second while the second one run in ~250 milliseconds, as expected. Trying built in types wouldn't cause a significant difference, so I stick with strings in both languages.
I was discussing this with a friend of mine and he said this wouldn't happen in C#. We tried and observed ourselves that this did not happen in C# as it turned out, scope-bounded declarations of strings won't affect running time of the program.
Why is this difference? Is that a bad optimization in C++ strings (I strongly doubt that tho) or something else?
Strings in C# are immutable, so the assignment can just copy over a reference. In C++, however, strings are mutable, so the entire contents of the string need to be copied over.
If you want to verify this hypothesis, try with a (significantly) longer string constant. Runtime in C++ should go up, but runtime in C# should remain the same.
Strings in C# are immutable.
C# uses references and the memory it's not copied!
in C# "HELLO THERE!" will be automatically assigned to a piece of memory and won't be copied each time
for example:
string a = "HELLO";
string b = a;
they are pointing to the same piece of memory, but in C++ no! the string will be the same but not in the same place, if you want to obtain the same reult you should use pointers (or smart pointers)
string *a = new string("hello");
string *b = a;

Is it possible to compile and execute new code at runtime in .NET?

Note: Mathematical expression evaluation is not the focus of this question. I want to compile and execute new code at runtime in .NET. That being said...
I would like to allow the user to enter any equation, like the following, into a text box:
x = x / 2 * 0.07914
x = x^2 / 5
And have that equation applied to incoming data points. The incoming data points are represented by x and each data point is processed by the user-specified equation. I did this years ago, but I didn't like the solution because it required parsing the text of the equation for every calculation:
float ApplyEquation (string equation, float dataPoint)
{
// parse the equation string and figure out how to do the math
// lots of messy code here...
}
When you're processing boatloads of data points, this introduces quite a bit of overhead. I would like to be able to translate the equation into a function, on the fly, so that it only has to be parsed once. It would look something like this:
FunctionPointer foo = ConvertEquationToCode(equation);
....
x = foo(x); // I could then apply the equation to my incoming data like this
Function ConvertEquationToCode would parse the equation and return a pointer to a function that applies the appropriate math.
The app would basically be writing new code at run time. Is this possible with .NET?
Yes! Using methods found in the Microsoft.CSharp, System.CodeDom.Compiler, and System.Reflection name spaces. Here is a simple console app that compiles a class ("SomeClass") with one method ("Add42") and then allows you to invoke that method. This is a bare-bones example that I formatted down to prevent scroll bars from appearing in the code display. It is just to demonstrate compiling and using new code at run time.
using Microsoft.CSharp;
using System;
using System.CodeDom.Compiler;
using System.Reflection;
namespace RuntimeCompilationTest {
class Program
{
static void Main(string[] args) {
string sourceCode = #"
public class SomeClass {
public int Add42 (int parameter) {
return parameter += 42;
}
}";
var compParms = new CompilerParameters{
GenerateExecutable = false,
GenerateInMemory = true
};
var csProvider = new CSharpCodeProvider();
CompilerResults compilerResults =
csProvider.CompileAssemblyFromSource(compParms, sourceCode);
object typeInstance =
compilerResults.CompiledAssembly.CreateInstance("SomeClass");
MethodInfo mi = typeInstance.GetType().GetMethod("Add42");
int methodOutput =
(int)mi.Invoke(typeInstance, new object[] { 1 });
Console.WriteLine(methodOutput);
Console.ReadLine();
}
}
}
You might try this: Calculator.Net
It will evaluate a math expression.
From the posting it will support the following:
MathEvaluator eval = new MathEvaluator();
//basic math
double result = eval.Evaluate("(2 + 1) * (1 + 2)");
//calling a function
result = eval.Evaluate("sqrt(4)");
//evaluate trigonometric
result = eval.Evaluate("cos(pi * 45 / 180.0)");
//convert inches to feet
result = eval.Evaluate("12 [in->ft]");
//use variable
result = eval.Evaluate("answer * 10");
//add variable
eval.Variables.Add("x", 10);
result = eval.Evaluate("x * 10");
Download Page
And is distributed under the BSD license.
Yes, definitely possible to have the user type C# into a text box, then compile that code and run it from within your app. We do that at my work to allow for custom business logic.
Here is an article (I haven't more than skimmed it) which should get you started:
http://www.c-sharpcorner.com/UploadFile/ChrisBlake/RunTimeCompiler12052005045037AM/RunTimeCompiler.aspx
You can also create a System.Xml.XPath.XPathNavigator from an empty, "dummy" XML stream,
and evaluate expressions using the XPath evaluator:
static object Evaluate ( string xp )
{
return _nav.Evaluate ( xp );
}
static readonly System.Xml.XPath.XPathNavigator _nav
= new System.Xml.XPath.XPathDocument (
new StringReader ( "<r/>" ) ).CreateNavigator ( );
If you want to register variables to use within this expression,
you can dynamically build XML that you can pass in the Evaluate overload
that takes a XPathNodeIterator.
<context>
<x>2.151</x>
<y>231.2</y>
</context>
You can then write expressions like "x / 2 * 0.07914" and then x
is the value of the node in your XML context.
Another good thing is, you will have access to all XPath core functions,
which includes mathematics and string manipulation methods, and more stuff.
If you want to take it further, you can even build your own XsltCustomContext(or ill post here on demand)
where you can resolve references to extension functions and variables:
object result = Evaluate ( "my:func(234) * $myvar" );
my:func is mapped to a C#/.NET method which takes a double or int as parameter.
myvar is registered as a variable within the XSLT context.
You can try looking at either CodeDom or Lambda Expression Trees. I think either one of those should allow you to accomplish this. Expression trees are probably the better way to go but also have a higher learning curve.
I've done this using CSharpCodeProvider by creating the boiler plate class and function stuff as a const string inside my generator class. Then I insert the user code into the boiler plate and compile.
It was fairly straightforward to do, but the danger to this approach is that the user entering the equation could enter just about anything which could be a security issue depending on your application.
If security is at all a concern, I would recommend using Lambda Expression Trees, but if not, using CSharpCodeProvider is a fairly robust option.
Have you seen http://ncalc.codeplex.com ?
It's extensible, fast (e.g. has its own cache) enables you to provide custom functions and varaibles at run time by handling EvaluateFunction/EvaluateParameter events. Example expressions it can parse:
Expression e = new Expression("Round(Pow(Pi, 2) + Pow([Pi2], 2) + X, 2)");
e.Parameters["Pi2"] = new Expression("Pi * Pi");
e.Parameters["X"] = 10;
e.EvaluateParameter += delegate(string name, ParameterArgs args)
{
if (name == "Pi")
args.Result = 3.14;
};
Debug.Assert(117.07 == e.Evaluate());
It also handles unicode & many data type natively. It comes with an antler file if you want to change the grammer. There is also a fork which supports MEF to load new functions.
You could start here and if you really want to get into it, Boo can be modified to meet your needs. You could also integrate LUA with .NET. Any three of these could be utilized within the body of a delegate for your ConvertEquationToCode.
Try Vici.Parser: download it here (free) , it's the most flexible expression parser/evaluator I've found so far.
Here a more modern library for simple expressions: System.Linq.Dynamic.Core.
It's compatible with .NET Standard/.NET Core, it's available through NuGet, and the source is available.
https://system-linq-dynamic-core.azurewebsites.net/html/de47654c-7ae4-9302-3061-ea6307706cb8.htm
https://github.com/StefH/System.Linq.Dynamic.Core
https://www.nuget.org/packages/System.Linq.Dynamic.Core/
This is a very lightweight and dynamic library.
I wrote a simple wrapper class for this library that let's me do things like this:
string sExpression = "(a == 0) ? 5 : 10";
ExpressionEvaluator<int> exec = new ExpressionEvaluator<int>(sExpression);
exec.AddParameter("a", 0);
int n0 = exec.Invoke();
Once the expression is compiled, you can simply update the parameter values and re-invoke the expression.
If all else fails, there are classes under the System.Reflection.Emit namespace which you can use to produce new assemblies, classes, and methods.
You could implement a postfix stack calculator. Basically what you have to do is convert the expression to postfix notation, and then simply iterate over the tokens in your postfix to calculate.
I would do a recursive function that doesn't write code but instead applies basic operators to portions of a string based on special characters found in that string.
If more than one special character is found, it breaks up the string and calls itself on those two portions.
you can use system.CodeDom to generate code and compile it on the fly
have a look here
I don't know if it's possible to implement your ConvertEquationToCode function, however, you can generate a data structure that represents the calculation you need to perform.
For example, you could build a tree whose leaf nodes represent the input for your calculation, whose non-leaf nodes represent intermediate results, and whose root node represents the whole calculation.
It has some advantages. For example, if you're doing what-if analysis and want to change the value of one input at a time, you can recalculate the results that depend on the value that you have changed, while retaining the results that don't.

Categories

Resources