I need to interface R to some C# application. I installed rscproxy_1.3 and R_Scilab_DCOM3.0-1B5 added COM references to the STATCONNECTORCLNTLib, StatConnectorCommonLib and STATCONNECTORSRVLib but I still cannot get it working.
When I run following test program:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
//COM references
using STATCONNECTORCLNTLib;
using StatConnectorCommonLib;
using STATCONNECTORSRVLib;
namespace R_TESTING
{
class Program
{
static void Main(string[] args)
{
StatConnector sc1 = new STATCONNECTORSRVLib.StatConnectorClass();
sc1.Init("R");
}
}
}
I get this exception:
Unhandled Exception: System.Runtime.InteropServices.COMException: Exception from HRESULT: 0x80040013
at STATCONNECTORSRVLib.StatConnectorClass.Init(String bstrConnectorName)
Thanks in advance.
UPDATE:
Ok, still no luck.
I will try to explain what I did so far.
Installed R-2.12.2-win.exe from
rproject to the C:\Program
Files\R\R-2.12.2
Downloaded rscproxy_1.3-1.zip and
copy/pasted it to the C:\Program
Files\R\R-2.12.2\library
Installed R_Scilab_DCOM3.0-1B5.exe to
the C:\Program Files (x86)\R\(D)COM
Server
With Scilab comes a basic test. I tried to run it but I got following error:
Loading StatConnector Server... Done
Initializing R...Function call failed
Code: -2147221485 Text: installation
problem: unable to load connector
Releasing StatConnector Server...Done
Than I looked in the PATH/System Variables and found no path/R_HOME/R_USER info. Also, I couldn't find anything R related in the registry.
I guess I am doing something terribly wrong, so I desperately need help from you guys.
You can have a look at R.NET, for another approach...
Ok, I solved it finally.
The problem is that R (D)Com doesn't work with current version of R. I installed 2.11.1 and it worked out of box.
Thanks a lot.
Use R.NET (I installed mine from NuGet) and the following code in a new C# console app (which was copied with minor changes from http://rdotnet.codeplex.com/).
It will work when pointed at the 32-bit version of R v2.11.1, but it will not work when pointed at the 64-bit version of R v2.11.1 (as noted in the code below).
When I installed NuGet, it automatically added references to the current project: RDotNet (RDotNet.dll) and RDotNet.NativeLIbrary (RDotNet.NativeLibrary.dll). You'll need these references in any new project.
Works under VS2012 (untested under VS2010, but will probably work).
Works when compiled for both "x32" and "All CPU" (under "Build..Configuration Manager" in VS2012).
// Call R from .NET. Advantage is that everything is in process.
// Tested on VS2012, will probably work on VS2010.
using System;
using System.IO;
using System.Linq;
using RDotNet;
class Program
{
static void Main(string[] args)
{
// Set the folder in which R.dll locates.
var envPath = Environment.GetEnvironmentVariable("PATH");
var rBinPath = #"C:\Program Files (x86)\R\R-2.11.1\bin";
//var rBinPath = #"C:\Program Files\R\R-2.11.1-x64\bin"; // Doesn't work ("DLL was not found.")
Environment.SetEnvironmentVariable("PATH", envPath + Path.PathSeparator + rBinPath);
using (REngine engine = REngine.CreateInstance("RDotNet"))
{
// Initializes settings.
engine.Initialize();
// .NET Framework array to R vector.
NumericVector group1 = engine.CreateNumericVector(new double[] { 30.02, 29.99, 30.11, 29.97, 30.01, 29.99 });
engine.SetSymbol("group1", group1);
// Direct parsing from R script.
NumericVector group2 = engine.Evaluate("group2 <- c(29.89, 29.93, 29.72, 29.98, 30.02, 29.98)").AsNumeric();
// Test difference of mean and get the P-value.
GenericVector testResult = engine.Evaluate("t.test(group1, group2)").AsList();
double p = testResult["p.value"].AsNumeric().First();
Console.WriteLine("Group1: [{0}]", string.Join(", ", group1));
Console.WriteLine("Group2: [{0}]", string.Join(", ", group2));
Console.WriteLine("P-value = {0:0.000}", p);
}
}
}
From here:
I think I just remembered how to solve the 80040013 exception. I think it had to do with the fact that my
install of the R files did not include a rscproxy.dll. Somewhere along the way, R changed from using a dll
named (I think) proxy.dll and started using one called rscproxy.dll. You have to find and download
rscproxy.dll to the R\bin folder.
If that doesn't work, check your environment variables to be sure they R_HOME and R_USER values are
pointing to the R\bin folder. Make sure the R (D)Com objects are properly registered with Windows.
Here is how to call a custom R Function from an Rdata file ( not just a built-in R function).
Actually this is what worked for me.
To get StatConnectorClass working, I had to open up the properties for StatConnectorsRVLib and set 'Embed Interop Types' to False.
using StatConnectorCommonLib;
using STATCONNECTORSRVLib;
using STATCONNECTORCLNTLib;
StatConnectorClass rConn = new StatConnectorClass();
try
{
rConn.Init("R"); // here is where we initialize R
Response.Write("Initialized." + "<br />"); Response.Flush();
Response.Write("1" + "<br />"); Response.Flush();
string path = #"C:SOMEPATH\Black-Scholes.RData";
rConn.SetSymbol("path", path);
Response.Write("2" + "<br />"); Response.Flush();
rConn.Evaluate("load(path)");
Response.Write("3" + "<br />"); Response.Flush();
Int16 entry = 27;
rConn.SetSymbol("n1", entry);
Response.Write("6" + "<br />"); Response.Flush();
rConn.Evaluate("x1<-samplefn(n1)" );
Response.Write("Entered : " + entry.ToString() + "<br/> ");
Object o = rConn.GetSymbol("x1");
Response.Write("Ans:" + o.ToString() + "<br />"); Response.Flush();
rConn.Close();
}
catch (Exception ex)
{
Response.Write("Error: " + ex.Message );//+ " xx " + rConn.GetErrorText());
rConn.Close();
}
Hope this helps!
Problem:
Loading StatConnector Server... Done Initializing R...Function call
failed Code: -2147221485 Text: installation problem: unable to load
connector Releasing StatConnector Server...Done
Solution: [By the way, I have R, RStudio, Revolution R in my PC]
1. Install the necessary programs and packages:
For performing exponential smoothing in Eviews (7.2), ExpSmooth add-ins is necessary.
For the ExpSmooth add-ins to properly work, the program R, and the packages forecast and rscproxy must be installed; and statconnDCOM must be installed.
2. Put the files and folders to the correct BIN and LIBRARY locations:
Copy-paste the file rscproxy.dll to the C:\Program Files\R\R-2.15.3\bin and C:\Revolution\R-Enterprise-6.1\R-2.14.2\bin folders.
Put the rscproxy folder in rscproxy_2.0-5.zip file to the C:\Revolution\R-Enterprise-6.1\R-2.14.2\library and C:\Program Files\R\R-2.15.3\library folders.
3. Additional info:
I did not make any changes to environment variables to overcome the problem in question.
I had set some environment variables for the first time when I installed R and Revolution R like that (this setting is irrelavant with the context here):
System variables - Path:
C:\Rtools\bin;C:\Program Files\R\R-3.0.2\bin\i386;C:\Rtools\gcc-4.6.3\bin;
(I offer you to set the R version that you installed and use).
Run Server 01 – Basic Test that existed upon installing statconnDCOM: Start - statconn – DCOM - “Server 01 – Basic Test”.
Press to R.
statconnDCOM worked.
Related
I'm trying to get status data of my processor on the local machine. I found several tutorials online, but no one of them covers the error I'm getting.
This is my code:
UpdateVisitor visitor = new UpdateVisitor();
Computer computer = new Computer();
computer.Open();
computer.CPUEnabled = true;
computer.Accept(visitor);
It throws an Exception when calling computer.Open() and this is the exception message:
What am i doing wrong? If i can provide some more detail, please let me know.
I'm referencing the library in a .NET Standard 2.0 project.
Solved the problem by referencing the library in a .NET Framework 4.7.1 project, instead that in a .NET Standard 2.0 project. I post this answer just to warn other people trying to achieve this that this library is not fully compatible with .NET Standard code.
I stole this WMI Answer from this question: C# CPU and GPU Temp.
Just install System.Management and start VS in Admin mode, and you can access the sensors.
using System;
using System.Diagnostics;
using System.Management;
class Program
{
static void Main(string[] args)
{
Double CPUtprt = 0;
System.Management.ManagementObjectSearcher mos = new System.Management.ManagementObjectSearcher(#"root\WMI", "Select * From MSAcpi_ThermalZoneTemperature");
foreach (System.Management.ManagementObject mo in mos.Get())
{
CPUtprt = Convert.ToDouble(Convert.ToDouble(mo.GetPropertyValue("CurrentTemperature").ToString()) - 2732) / 10;
Console.WriteLine("CPU temp : " + CPUtprt.ToString() + " °C");
}
}
}
I was trying to combine a Python code with C#, to use all those cool libraries like Speech Recognition inside my C# application.
I made two different projects one for python (IronPython) where I've included the module I need (Speech Recognition) through the python environment in VS2017 and the other one is just a console application where I want to call this app.
I thought the point was to change the searchPaths of Ironpython and afterwards it'll work.
Maybe I'm doing something wrong or maybe it just shouldn't work anyway?
C# Code Main.cs:
using IronPython.Hosting;
using System.Collections.Generic;
private static void Main(string[] args)
{
//Using Iron python
var engine = IronPython.Hosting.Python.CreateEngine();
System.Console.WriteLine("Search paths:");
ICollection<string> searchPaths = engine.GetSearchPaths();
foreach (string path in searchPaths)
{
System.Console.WriteLine(path);
}
System.Console.WriteLine();
searchPaths.Add("..\\..");
///Trying to add a searchPath for the place with the module I need
searchPaths.Add(#"C:\Program Files (x86)\Microsoft Visual
Studio\Shared\Anaconda3_64\Lib\site-packages");
engine.SetSearchPaths(searchPaths);
var res = engine.CreateScriptSourceFromFile(
#"D:\Python\Projects\TestSpeechRecognition
\TestForNETinPython\TestForNETinPython.py"
);
engine.ImportModule("speech_recognition");
var result = res.Execute();
}
Python code
import speech_recognition as sr
r = sr.Recognizer()
with sr.Microphone() as source:
print ("Hello: ")
audio = r.listen(source)
try:
print ("I said: " + r.recognize_google(audio))
except sr.UnknownValueError:
print ("Cant't rec")
except sr.RequestError as e:
print ("Can't connect: (0)".format(e))
Exception:
Unhandled Exception:
IronPython.Runtime.Exceptions.ImportException: no module named speech_recognition
at IronPython.Hosting.PythonService.ImportModule(ScriptEngine engine, String name)
at IronPython.Hosting.Python.ImportModule(ScriptEngine engine, String moduleName)
at Test.Program.Main(String[] args) in D:\Python\Projects\TestSpeechRecognition\Test\Program.cs:line 26
I even read some literature about creating the modules like this one http://www.needfulsoftware.com/IronPython/IronPythonCS2 or this one it's for pythonnet and a little bit creepy, but I guess it may be useful (NoteBook).
Hope someone can use it to solve the problem.
I am trying to create a "Hello World" example in R Language using R.Net version 1.5.5 (loaded from NuGet). Unfortunately, none of the online samples that I have seen work.
THIS IS WHAT I HAVE DONE:
Installed Microsoft R Open 3.2.4, the enhanced R distribution
Installed R Tools for Visual Studio (R version 3.2.4 (2016-03-16))
Created an R Project & tested a simple script
Created an MVC application & referenced R.Net version 1.5.5 from NuGet
MY PROBLEM:
All of the online examples I have seen must be using an earlier version because I cannot create an instance of the REngine for the LIFE of me! In fact, I keep getting:
Dll was not found
...yet C:\Program Files\Microsoft\MRO\R-3.2.4\bin\x64\r.dll does indeed exist.
Q: How do I create an instance of the REngine using R.Net version 1.5.5?
MY CODE LOOKS LIKE:
class Program
{
#region <Methods>
static void Main(string[] args)
{
SetupPath(); // current process, soon to be deprecated
using (REngine engine = REngine.CreateInstance("RDotNet"))
{
engine.Initialize(); // required since v1.5
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();
}
public static void SetupPath()
{
var oldPath = System.Environment.GetEnvironmentVariable("PATH");
var rPath = #"C:\Program Files\Microsoft\MRO\R-3.2.4\bin\x64";
if (!Directory.Exists(rPath))
throw new DirectoryNotFoundException(string.Format(" R.dll not found in : {0}", rPath));
var newPath = string.Format("{0}{1}{2}", rPath, System.IO.Path.PathSeparator, oldPath);
System.Environment.SetEnvironmentVariable("PATH", newPath);
}
#endregion
}
I hate to answer my own question, but here it is...
The Microsoft R Open 3.2.4 enhanced R distribution installs x64 files. As such, running under ANY CPU will cause a failure because it will choose x86 (by default).
Under
Project Properties -> Build: in the "General" section
Choose x64 as your Platform Target
I was wondering if there is an online tool that can convert c# code to powershell cmdlet code. I have following code that i need to have it powershell. I dont have visual studio to turn this into an exe or dll. any help or ideas would be great.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
namespace CopyUsersBetweenGroupsInSharepointByRR
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("This tool will copy the users from one group to another group");
Console.WriteLine("Please enter the URL of the site where your groups are available");
String siteUrl = Console.ReadLine();
using (SPSite site = new SPSite(siteUrl))
{
try
{
SPWeb web = site.OpenWeb();
Console.WriteLine("Please enter the name of the source group");
String sourceGroupName = Console.ReadLine();
Console.WriteLine("Please enter the name of the destination group");
String destinationGroupName = Console.ReadLine();
SPGroup sourceGroup = web.Groups[sourceGroupName];
SPGroup destinationGroup = web.Groups[destinationGroupName];
SPUserCollection sourceUsers = sourceGroup.Users;
SPUserInfo[] sourceUserInfoArray = new SPUserInfo[sourceUsers.Count];
for (int i = 0; i < sourceUsers.Count; i++)
{
sourceUserInfoArray[i] = new SPUserInfo();
sourceUserInfoArray[i].LoginName = sourceUsers[i].LoginName;
sourceUserInfoArray[i].Name = sourceUsers[i].Name;
}
destinationGroup.Users.AddCollection(sourceUserInfoArray);
destinationGroup.Update();
web.Update();
Console.WriteLine("Operation Completed Successfully");
Console.ReadLine();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
Console.ReadLine();
}
}
}
}
}
It's comments like those above that are turning people away from SO in droves. The OP's question was unambiguous and displayed genuine need.
There are several ways to achieve this. Rewriting your entire C# code repository is not one of them.
As already discussed, as of PS 2 you are able to either run C# (or most any other language) inline, or refer to well-formed external file. I've had mixed success with this and I don't believe it's what the OP was really after.
If you genuinely want to convert code (particularly compiled assemblies) then a decompiler like Reflector is able to do this and - with the PowerShell addon - is also able to convert it on-the-fly.
http://blog.lekman.com/2011/10/converting-c-to-powershell.html
If you want your input and output to take place within the PS console then you'd still have to perform some obvious re-writes. But this method has proved incredibly useful to me.
The fastest way to do it is to write the PowerShell code yourself.
Below is how the code will look in PowerShell, i would say that most C# developers should be able to grasp the concepts of converting C# code to PowerShell in a very short time.
Functions can be a little odd at the beginning, since the usual PS syntax is
myFunction Parameter1 Parameter2
Also you really should install PowerShell 3.0 and use the Windows PowerShell ISE tool to develop the code.
Anyways it should not take you more than 1-2 hours to get your C# code running along in PowerShell.
[System.Reflection.Assembly]::LoadWithPartialName(”Microsoft.SharePoint”)
Write-Host "This tool will copy the users from one group to another group"
Write-Host "Please enter the URL of the site where your groups are available"
[string] $siteUrl = [Console]::ReadLine()
$site = new-object Microsoft.SharePoint.SPSite($siteUrl)
try
{
$web = $site.OpenWeb()
Write-Host "Please enter the name of the source group"
[string] $sourceGroupName = [Console]::ReadLine()
Write-Host "Please enter the name of the destination group"
[string] $destinationGroupName = [Console]::ReadLine()
$sourceUsers = $web.Groups[$sourceGroupName]
(and so on)
}
catch
{
Write-Error ("Failed to copy sharepoint users." + $_)
}
I doubt there is anything remotely like that, however Visual Studio is not required to compile c# code. You could compile an exe without VS. The compiler (csc.exe) and msbuild are included as part of framework. They are located in C:\Windows\Microsoft.NET\Framework\{version}.
If you really want to call this from powershell, have a look at the Add-Type cmdlet. You provide it the source code and it will compile the source on the fly, then load the assembly into your session.
Not sure about online tools, but download the free Visual Studio Express & follow this tutorial should have you creating a cmdlet in no time
We have the following code in wizard to add existing project to a new solution:
//generating files
if (dte.Solution.Projects.Count < 1) // Solution is empty or doesn't exist
{
dte.Solution.Create(oneFolderHigher(Params.OutputDir, solutionName),
solutionFileName(solutionName));
}
// adding created project to solution
dte.Solution.AddFromFile(Path.Combine(Params.ProjectRootFolder,
Params.ProjectName + ".csproj"));
It works just fine under MS Visual Studio 2010, but fails under 2012 (I experimented with second parameter):
System.Runtime.InteropServices.COMException (0x80004004): Operation aborted (Exception from HRESULT: 0x80004004 (E_ABORT))
at EnvDTE.SolutionClass.AddFromFile(String FileName, Boolean Exclusive)
at Wizard.Generator.NewProjectGenerator.Generate(Action`1 logMessage)
at Wizard.Forms.WizardForm.Finish()
After this error I'm adding the new project to the solution manually and everything works OK. But we can not just say, "Sorry, we can not add newly generated project for you so please add it by yourself."
MSDN proposes:
You can use the LaunchWizard method rather than AddFromFile to execute a wizard if you want to suppress its UI during execution. LaunchWizard has a parameter that allows you to disable the UI.
But this method requires some wizard file, so it can not be a solution.
Could someone help?
Wizard is running from "New -> Project" menu.
Here the workaround for the issue (proposed by my boss):
Before adding the project to solution, project file should be converted to
VS2012 format.
But code is little ugly:
using (StreamReader sr = new StreamReader(newFile))
using (StreamWriter sw = new StreamWriter(projectFile, false, Encoding.UTF8))
{
while (sr.Peek() >= 0)
{
string s = sr.ReadLine();
if (s.Contains("<Project ToolsVersion=\"4.0\""))
{
s = s + Environment.NewLine + importProject;
}
... and so on
Maybe someone knows the way to do it awesome? I mean converting. I'll let the question to be unanswered some time. Waiting for your comments.