C# not connecting to R using RDotNet - c#

I am trying to interface C# to R using RDotNet.
The following code is wants R to calculate the sum of two numbers and C# to get the result back and display it in the command window.
using System;
using RDotNet;
namespace rcon
{
class Program
{
static void Main(string[] args)
{
string dllPath = #"C:\Program Files\R\R-3.1.0\bin\i386";
REngine.SetDllDirectory(dllPath);
REngine.CreateInstance("RDotNet");
//REngine engine = REngine.GetInstanceFromID("RDotNet");
using (REngine engine = REngine.GetInstanceFromID("RDotNet"))
{
var x = engine.Evaluate("x <- 1 + 2");
Console.WriteLine(x);
}
}
}
}
but when I try to send the command to R and get back the calue in x I got an error:
"InvalidOperationException was unhandled"
"Operation is not valid due to the current state of the object."
If I explore the object "engine" I see that IsRunning=false.
Can this be the problem? And how can I fix this in order to be able to interface to R?

It looks like you have outdated version of R.NET.
From R.NET project documentation
R.NET 1.5.10 and subsequent versions include significant changes
notably to alleviate two stumbling blocks often dealt with by users:
paths to the R shared library, and preventing multiple engine
initializations.
You can update your R.NET using NuGet manager from Visual Studio. See the same documentation page for detals.
Here is code sample from the same documentatin page - note that initialization of REngine is significantly simpler now (as now Rengine looks at the Registry settings set up by the R installer):
REngine.SetEnvironmentVariables(); // <-- May be omitted; the next line would call it.
REngine engine = REngine.GetInstance();
// A somewhat contrived but customary Hello World:
CharacterVector charVec = engine.CreateCharacterVector(new[] { "Hello, R world!, .NET speaking" });
engine.SetSymbol("greetings", charVec);
engine.Evaluate("str(greetings)"); // print out in the console
string[] a = engine.Evaluate("'Hi there .NET, from the R engine'").AsCharacter().ToArray();
Console.WriteLine("R answered: '{0}'", a[0]);
Console.WriteLine("Press any key to exit the program");
Console.ReadKey();
engine.Dispose();

Related

Quantum Program The name 'BellTest' does not exist in the current context

This is my first Q# program and i'm following this getting started link.https://learn.microsoft.com/en-us/quantum/quantum-writeaquantumprogram?view=qsharp-preview
Error is
The name 'BellTest' does not exist in the current context
but its defined in the Bell.cs
I followed the steps and when building its having errors. I'm not sure how to import the operations from .qs file to driver c# file as this error looks like it can't find that operation.
Any help is really appreciated
Here is the code
Driver.cs
using Microsoft.Quantum.Simulation.Core;
using Microsoft.Quantum.Simulation.Simulators;
namespace Quantum.Bell
{
class Driver
{
static void Main(string[] args)
{
using (var sim = new QuantumSimulator())
{
// Try initial values
Result[] initials = new Result[] { Result.Zero, Result.One };
foreach (Result initial in initials)
{
var res = BellTest.Run(sim, 1000, initial).Result;
var (numZeros, numOnes) = res;
System.Console.WriteLine(
$"Init:{initial,-4} 0s={numZeros,-4} 1s={numOnes,-4}");
}
}
System.Console.WriteLine("Press any key to continue...");
System.Console.ReadKey();
}
}
}
Bell.qs
namespace Quantum.Bell
{
open Microsoft.Quantum.Primitive;
open Microsoft.Quantum.Canon;
operation Set (desired:Result,q1:Qubit) : ()
{
body
{
let current = M(q1);
if (desired != current)
{
X(q1);
}
}
}
operation BellTest (count : Int, initial: Result) : (Int,Int)
{
body
{
mutable numOnes = 0;
using (qubits = Qubit[1])
{
for (test in 1..count)
{
Set (initial, qubits[0]);
let res = M (qubits[0]);
// Count the number of ones we saw:
if (res == One)
{
set numOnes = numOnes + 1;
}
}
Set(Zero, qubits[0]);
}
// Return number of times we saw a |0> and number of times we saw a |1>
return (count-numOnes, numOnes);
}
}
}
I also got the same error, but I was able to do it by pressing the F5 key.
Perhaps the Visual Studio editor is not yet fully support to the .qs file.
Namespace sharing does not seem to be working properly between .cs file and .qs file.
I was able to execute using your code in my development environment.
--
IDE: Visual Studio Community 2017 (Version 15.5.2)
Dev Kit: Microsoft Quantum Development Kit (0 and 1)
I engage the same problem in microsoft.quantum.development.kit/0.3.1811.203-preview version.
The BellTest operation cannot recognised by VSC Pic of VSCode
What I do is,
save all but keep VSCode open
go to directory and delete anything in bin/ obj/ by /bin/rm -rf bin obj
dotnet run
you go back to check VSCode, the BellTest recognised by VSC now.

How can I export my c# code logic (if-else-loops) in to text files (e.g XML) and later import it back and run?

I have these requirements coming from client every week for some new logic or verification. For which I have to code new logic (basically some if-else and loops) and launch a new build for him. I want to avoid it by simply coding my logic in visual studio then writing a utility to export it to XML or something and send it to client via e-mail. He just have to place this file in some appropriate folder and the application will behave considering this logic.
Please suggest some solutions. My platform is C# Asp.Net.
Thanks
Using .NET 4.6 and the NuGetPackage Microsoft.CodeAnalysis.Scripting you could implement a scripting engine to run your c# code residing in a textfile without building an assembly.
Install NuGet Package:
Install-Package Microsoft.CodeAnalysis.Scripting.CSharp
Implement TestClass with some basic C#-Code-Content:
class Program
{
static void Main(string[] args)
{
TestScript();
}
private static async void TestScript()
{
// Code snippet: a class with one string-property.
string codeContent = #" using System;
public class ScriptedClass
{
public string HelloWorld { get; set; }
public ScriptedClass()
{
HelloWorld = ""Hello Roslyn!"";
}
}
new ScriptedClass().HelloWorld";
// Instanciate CSharpScriptEngine
var engine = new CSharpScriptEngine();
// Execute code and return string property (HelloWorld)
var scriptingState = await engine.ExecuteAsync(codeContent);
// Print return value from CSharpScript
Console.WriteLine("Returned from CSharpScript: {0}", scriptingState.ReturnValue);
Console.WriteLine("Press any key to continue.");
Console.ReadKey();
}
}
Implement a ScriptingEngine:
internal sealed class CSharpScriptEngine
{
public async Task<ScriptState<object>> ExecuteAsync(string codeContent)
{
// Add references from calling assembly
ScriptOptions options = ScriptOptions.Default.AddReferences(Assembly.GetExecutingAssembly());
// Run codeContent with given options
return await CSharpScript.RunAsync(codeContent, options);
}
}
Read ScriptCode from textfile:
So basically you could read some csharpcode from a textfile of your choice and run them on the fly:
private static async void TestScript()
{
// Read in script file
string codeContent = File.ReadAllText(#"C:\Temp\CSharpScriptTest.cs");
var engine = new CSharpScriptEngine();
// Run script
var scriptingState = await engine.ExecuteAsync(codeContent);
Console.WriteLine("Returned from CSharpScript: {0}", scriptingState.ReturnValue);
Console.WriteLine("Press any key to continue.");
Console.ReadKey();
}
In case you are wondering how all of this works under the hood, Roslyn will create a so called submission from your script code. A submission is an in memory assembly containing the types generated around your script code, which can be identified among the assemblies in the current AppDomain by a ℛ prefix in the name.
The precise implementation details are not important here (though, for example, scriptcs heavily relies on understanding in detail how Roslyn works to provide its extra features), but it's important to know that submissions can be chained together. When they are chained, variables, methods or classes defined in an earlier submission are available to use in subsequent submissions, creating a feature of a C# REPL (read-evaluate-print loop).
C# and Visual Basic - Use Roslyn to Write a Live Code Analyzer for Your API
Hope it helps

OpenALPR crash - Attempted to read or write protected memory

I have a C# program that has been crashing after a variable amount of time. I've tracked it down to OpenALPR and have now duplicated the problem in a test program.
I basically ask to get the plates from an image in a while loop. It fails after a bunch of iterations. Failed after Iterations : 179, 221, 516, 429, 295, 150
Program output:
...
Iter (219) No Plates Found in image 71197e9d829d4d429e74a71c983380dc_09032015
134103267.jpg
Config file location provided via API
LBP Time: 0.005ms.
Total Time to process image: 1.916ms.
Iter (220) No Plates Found in image 71197e9d829d4d429e74a71c983380dc_09032015
134103267.jpg
Config file location provided via API
LBP Time: 0.003ms.
Total Time to process image: 4.071ms.
Iter (221) No Plates Found in image 71197e9d829d4d429e74a71c983380dc_09032015
134103267.jpg
Config file location provided via API
Failure message:
Unhandled Exception:
Unhandled Exception: System.AccessViolationException: Attempted to read or write
protected memory. This is often an indication that other memory is corrupt.
at openalprnet.AlprNet.Dispose(Boolean )
System.AccessViolationException: Attempted to read or write protected memory. Th
is is often an indication that other memory is corrupt.
at alpr.Alpr.{ctor}(Alpr* , basic_string<char\,std::char_traits<char>\,std::a
llocator<char> >* , basic_string<char\,std::char_traits<char>\,std::allocator<ch
ar> >* , basic_string<char\,std::char_traits<char>\,std::allocator<char> >* )
at openalprnet.AlprNet..ctor(String country, String configFile, String runtim
eDir)
at AlprTest.Program.Main(String[] args) in C:\Users\foo\Desktop\c#LPR\A
lprTest\Program.cs:line 25
One time, I also got part of another error message(not sure if its related or not) : Unable to load regex: ######. Although the error above is pointing to the CTOR, I have, in my normal application, had it fail during the recognize call. I've also seen (not sure how accurate these stack traces are) it in openalprnet.AlprNet.Dispose(Boolean) which was called from alpr.Alpr.{ctor}(...
My test program :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using openalprnet;
namespace AlprTest
{
class Program
{
static void Main(string[] args)
{
string chipPath = "71197e9d829d4d429e74a71c983380dc_09032015134103267.jpg";
string confPath = Path.GetFullPath(".\\openalpr.conf");
string runtimeDirPath = Path.GetFullPath(".\\runtime_data");
int i = 0;
while (true)
{
++i;
try
{
// Look at target velocity and pick a conf file to use.
//
AlprNet alpr = new AlprNet("us", confPath, runtimeDirPath);
if (!alpr.isLoaded())
{
return;
}
// Optionally apply pattern matching for a particular region
alpr.DefaultRegion = "va"; // was md
alpr.DetectRegion = true;
AlprResultsNet results = alpr.recognize(chipPath);
if (results.plates.Count < 1)
{
Console.WriteLine(" Iter ({1}) No Plates Found in image {0}", chipPath, i);
}
else
{
int j = 0;
foreach (var result in results.plates)
{
Console.WriteLine("Plate {0}: {1} result(s)", ++j, result.topNPlates.Count);
Console.WriteLine(" Processing Time: {0} msec(s)", result.processing_time_ms);
foreach (var plate in result.topNPlates)
{
Console.WriteLine(" - {0}\t Confidence: {1}\tMatches Template: {2}", plate.characters,
plate.overall_confidence, plate.matches_template);
}
}
}
}
catch (Exception ex)
{
Console.WriteLine("Exception caught in LPR processing. Ex={0}", ex);
return;
}
}
}
}
}
The program depends on the openalpr distribution and corresponding opencv dlls. openalpr-net.dll, liblept170.dll, opencv_core248.dll, opencv_features2d248.dll, opencv_ffmpeg248.dll, opencv_flann248.dll, opencv_highgui248.dll, opencv_imgproc248.dll, opencv_objdetect248.dll, opencv_video248.dll. It also uses a runtime_data directory (which I simply copied from the sample app) which seems to contain training data and such.
So, obviously, I'm using C#. I'm using Visual Studio 2010 and .NET 4.0
I'm assuming that I'm using OpenALPR wrong and that there is, in fact, nothing wrong with it. This would seem to be a pretty basic function. Aside from fixing it... why does this crash my program and how can I catch this and recover? You notice my try-catch totally fails to catch it and it crashes the whole application.
EDIT :
While running the test app, it starts with like 2gig of memory, but it just grows and grows and grows. It crashed with 7.7 gig after 147 loops.
EDIT EDIT :
Added in call to Dispose after each iteration and now the program sits pretty steady at 50-75 megs of memory.
Turns out the problem was the Dispose.
Need to Dispose of the object. Better yet, don't dispose of the object and re-use it. So long as the config doesn't change you can reuse the object. Sadly, the prewarp is in the config so you likely won't be able to reuse the object. Call Dispose before the object leaves scope.
try
{
// Look at target velocity and pick a conf file to use.
//
AlprNet alpr = new AlprNet("us", confPath, runtimeDirPath);
if (!alpr.isLoaded())
{
return;
}
// Optionally apply pattern matching for a particular region
alpr.DefaultRegion = "va"; // was md
alpr.DetectRegion = true;
AlprResultsNet results = alpr.recognize(chipPath);
...
alpr.Dispose(); // Dispose of the object so it can clean up
}

How to release COM handle in .NET

I am using the following code under ASP.NET 4.0 framework to obtain the version of MSI file from a web app:
string strVersion = "";
try
{
Type InstallerType;
WindowsInstaller.Installer installer;
InstallerType = Type.GetTypeFromProgID("WindowsInstaller.Installer");
installer = (WindowsInstaller.Installer)Activator.CreateInstance(InstallerType);
WindowsInstaller.Database db = installer.OpenDatabase(strMSIFilePath, 0);
WindowsInstaller.View dv = db.OpenView("SELECT `Value` FROM `Property` WHERE `Property`='ProductVersion'");
WindowsInstaller.Record record = null;
dv.Execute(record);
record = dv.Fetch();
strVersion = record.get_StringData(1).ToString();
dv.Close();
//db.Commit();
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(dv);
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(db);
}
catch
{
//Failed
strVersion = "";
}
It works fine except that when the code finishes running it holds an internal MSI file handle so when I try to move or rename the MSI file I get the error that the file is still in use. This continues until I actually navigate away from the ASPX page that calls the method above.
My question is, I obviously didn't close some handle or object in the code above. But what could that be?
PS. I'm testing it in a development IDE from VS2010.
EDIT: Edited the code like it should be after Adriano's suggestion. Thanks!
The COM object has not been released (it should be auto-released when it goes out of scope but in .NET this doesn't work really well). Because it does not implement the IDisposable interface you can't call its Dispose() method and you can't use it inside an using statement. You have to explicitly call Marshal.FinalReleaseComObject. For example:
try
{
// Your stuffs
}
finally
{
dv.Close();
Marshal.FinalReleaseComObject(dv);
Marshal.FinalReleaseComObject(db);
}
Moreover note that you do not really need a call to the Commit() method because you didn't make any change but just a query.
FWIW, you should be using Windows Installer XML (WiX) Deployment Tools Foundation (DTF). It's an FOSS project from Microsoft that can be found on CodePlex. It has MSI interop libraries with classes that are very similar to the COM classes but implement IDisosable and use P/Invoke instead of COM behind the scenes. There is even support for Linq to MSI if you want. And the full source code is available.
DTF is the gold standard for MSI interop in a .NET world. Here are two examples:
using System;
using System.Linq;
using Microsoft.Deployment.WindowsInstaller;
using Microsoft.Deployment.WindowsInstaller.Linq;
namespace ConsoleApplication3
{
class Program
{
const string DATABASE_PATH = #"C:\FOO..MSI";
const string SQL_SELECT_PRODUCTVERSION = "SELECT `Value` FROM `Property` WHERE `Property`='ProductVersion'";
static void Main(string[] args)
{
using (Database database = new Database(DATABASE_PATH, DatabaseOpenMode.ReadOnly))
{
Console.WriteLine(database.ExecuteScalar(SQL_SELECT_PRODUCTVERSION).ToString());
}
using (QDatabase database = new QDatabase(DATABASE_PATH, DatabaseOpenMode.ReadOnly))
{
var results = from property in database.Properties where property.Property == "ProductVersion" select property.Value;
Console.WriteLine(results.AsEnumerable<string>().First());
}
}
}
}
try to Dispose the Objects.
dv.Dispose();
db.Dispose();

string contain math expression [duplicate]

I would like to do the equivalent of:
object result = Eval("1 + 3");
string now = Eval("System.DateTime.Now().ToString()") as string
Following Biri s link, I got this snippet (modified to remove obsolete method ICodeCompiler.CreateCompiler():
private object Eval(string sExpression)
{
CSharpCodeProvider c = new CSharpCodeProvider();
CompilerParameters cp = new CompilerParameters();
cp.ReferencedAssemblies.Add("system.dll");
cp.CompilerOptions = "/t:library";
cp.GenerateInMemory = true;
StringBuilder sb = new StringBuilder("");
sb.Append("using System;\n");
sb.Append("namespace CSCodeEvaler{ \n");
sb.Append("public class CSCodeEvaler{ \n");
sb.Append("public object EvalCode(){\n");
sb.Append("return " + sExpression + "; \n");
sb.Append("} \n");
sb.Append("} \n");
sb.Append("}\n");
CompilerResults cr = c.CompileAssemblyFromSource(cp, sb.ToString());
if (cr.Errors.Count > 0)
{
throw new InvalidExpressionException(
string.Format("Error ({0}) evaluating: {1}",
cr.Errors[0].ErrorText, sExpression));
}
System.Reflection.Assembly a = cr.CompiledAssembly;
object o = a.CreateInstance("CSCodeEvaler.CSCodeEvaler");
Type t = o.GetType();
MethodInfo mi = t.GetMethod("EvalCode");
object s = mi.Invoke(o, null);
return s;
}
Old topic, but considering this is one of the first threads showing up when googling, here is an updated solution.
You can use Roslyn's new Scripting API to evaluate expressions.
If you are using NuGet, just add a dependency to Microsoft.CodeAnalysis.CSharp.Scripting.
To evaluate the examples you provided, it is as simple as:
var result = CSharpScript.EvaluateAsync("1 + 3").Result;
This obviously does not make use of the scripting engine's async capabilities.
You can also specify the evaluated result type as you intended:
var now = CSharpScript.EvaluateAsync<string>("System.DateTime.Now.ToString()").Result;
To evaluate more advanced code snippets, pass parameters, provide references, namespaces and whatnot, check the wiki linked above.
I have written an open source project, Dynamic Expresso, that can convert text expression written using a C# syntax into delegates (or expression tree). Text expressions are parsed and transformed into Expression Trees without using compilation or reflection.
You can write something like:
var interpreter = new Interpreter();
var result = interpreter.Eval("8 / 2 + 2");
or
var interpreter = new Interpreter()
.SetVariable("service", new ServiceExample());
string expression = "x > 4 ? service.aMethod() : service.AnotherMethod()";
Lambda parsedExpression = interpreter.Parse(expression,
new Parameter("x", typeof(int)));
parsedExpression.Invoke(5);
My work is based on Scott Gu article http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx .
If you specifically want to call into code and assemblies in your own project I would advocate using the C# CodeDom CodeProvider.
Here is a list of the most popular approaches that I am aware of for evaluating string expressions dynamically in C#.
Microsoft Solutions
C# CodeDom CodeProvider:
See How LINQ used to work and this CodeProject article
Roslyn:
See this article on Rosly Emit API and this StackOverflow answer
DataTable.Compute:
See this answer on StackOverflow
Webbrowser.Document.InvokeScript
See this StackOverflow question
DataBinder.Eval
ScriptControl
See this answer on StackOverflow and this question
Executing PowerShell:
See this CodeProject article
Non-Microsoft solutions (not that there is anything wrong with that)
Expression evaluation libraries:
Flee
DynamicExpresso
NCalc
CodingSeb.ExpressionEvaluator
Eval-Expression.NET
Javascript interpreter
Jint
To execute real C#
CS-Script
Roll your own a language building toolkit like:
Irony
Jigsaw
using System;
using Microsoft.JScript;
using Microsoft.JScript.Vsa;
using Convert = Microsoft.JScript.Convert;
namespace System
{
public class MathEvaluator : INeedEngine
{
private VsaEngine vsaEngine;
public virtual String Evaluate(string expr)
{
var engine = (INeedEngine)this;
var result = Eval.JScriptEvaluate(expr, engine.GetEngine());
return Convert.ToString(result, true);
}
VsaEngine INeedEngine.GetEngine()
{
vsaEngine = vsaEngine ?? VsaEngine.CreateEngineWithType(this.GetType().TypeHandle);
return vsaEngine;
}
void INeedEngine.SetEngine(VsaEngine engine)
{
vsaEngine = engine;
}
}
}
What are the performance implications of doing this?
We use a system based on something like the above mentioned, where each C# script is compiled to an in-memory assembly and executed in a separate AppDomain. There's no caching system yet, so the scripts are recompiled every time they run. I've done some simple testing and a very simple "Hello World" script compiles in about 0.7 seconds on my machine, including loading the script from disk. 0.7 seconds is fine for a scripting system, but might be too slow for responding to user input, in that case a dedicated parser/compiler like Flee might be better.
using System;
public class Test
{
static public void DoStuff( Scripting.IJob Job)
{
Console.WriteLine( "Heps" );
}
}
I have just written a similar library (Matheval) in pure C#.
It allows evaluating string and number expression like excel fomular.
using System;
using org.matheval;
public class Program
{
public static void Main()
{
Expression expression = new Expression("IF(time>8, (HOUR_SALARY*8) + (HOUR_SALARY*1.25*(time-8)), HOUR_SALARY*time)");
//bind variable
expression.Bind("HOUR_SALARY", 10);
expression.Bind("time", 9);
//eval
Decimal salary = expression.Eval<Decimal>();
Console.WriteLine(salary);
}
}
Looks like there is also a way of doing it using RegEx and XPathNavigator to evaluate the expression. I did not have the chance to test it yet but I kind of liked it because it did not require to compile code at runtime or use libraries that could not be available.
http://www.webtips.co.in/c/evaluate-function-in-c-net-as-eval-function-in-javascript.aspx
I'll try it and tell later if it worked. I also intend to try it in Silverlight, but it is too late and I'm almost asleep to do it now.
While C# doesn't have any support for an Eval method natively, I have a C# eval program that does allow for evaluating C# code. It provides for evaluating C# code at runtime and supports many C# statements. In fact, this code is usable within any .NET project, however, it is limited to using C# syntax. Have a look at my website, http://csharp-eval.com, for additional details.
There is a nice piece of code here
https://www.c-sharpcorner.com/article/codedom-calculator-evaluating-c-sharp-math-expressions-dynamica/
Download this and make it a class library which may be referenced in your project. This seems to be pretty fast and simple
Perhaps this could help !

Categories

Resources