Executing .R file in C# using R.net in visual studio - c#

I have a .r file which fetches data from database, performs some calculation and write back to a new table in database.
I am trying to execute the .r file from C# using visual studio 2010.
The C# code is mentioned below.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using RDotNet;
using RDotNet.Devices;
using RDotNet.Internals;
namespace EmbeddAssembly
{
class Program
{
static void Main(string[] args)
{
string rhome = System.Environment.GetEnvironmentVariable("R_HOME");
if (string.IsNullOrEmpty(rhome))
rhome = #"C:\Program Files\R\R-2.14.1";
System.Environment.SetEnvironmentVariable("R_HOME", rhome);
System.Environment.SetEnvironmentVariable("PATH", System.Environment.GetEnvironmentVariable("PATH") + ";" + rhome + #"binx64");
// Set the folder in which R.dll locates.
//REngine.SetDllDirectory(#"C:Program FilesRR-2.12.0bini386″);
REngine.SetDllDirectory(#"C:\Program Files\R\R-2.14.1\bin\x64");
// REngine e = REngine.CreateInstance("test", new[] { "" });
using (REngine engine = REngine.CreateInstance("RDotNet", new[] { "-q" })) // quiet mode
{
foreach (string path in engine.EagerEvaluate(".libPaths()").AsCharacter())
{
Console.WriteLine(path);
}
engine.Evaluate(".libPaths(C:\\Program Files\\R\\R-2.14.1\\library)");
engine.Evaluate("source(C:\\Users\\..\\Documents\\Visual Studio 2010\\Projects\\EmbeddAssembly\\multi.r)");
Console.ReadLine();
}
}
}
}
I am not getting any error but it is not calling the .r file.
The code in r file works fine because I am able to retrive data and write into the table. However on calling that from C# it is not performing any action.

You are missing character delimitors around arguments to the R functions called. Also, avoid using backslashes when passing strings to R.NET's Evaluate. You may need to end up having quadruple backslashes (or even more if using regular expressions) to get things to work.
You should use something like:
engine.Evaluate(".libPaths('C:/Program Files/R/R-2.14.1/library')");
engine.Evaluate("source('C:/Users/Documents/Visual Studio 2010/Projects/EmbeddAssembly/multi.r')");
It seems you are using a very old version of R.NET; I strongly advise you to use R.NET.Community on NuGet. I know there is an R.NET nuget feed still up too, but this appears not maintained anymore. Also, FYI, R.NET latest reference documentation is now on a GitHub page

Related

what reference I need to add in C# to get LaunchPadApi?

I try to connect to the API (Using C#) that client provided, but it is using LaunchPadApi() I am not sure what assembly I need to add to get this, these are 2 references that were added:
using IO.Swagger.Api;
using IO.Swagger.Client;
I was able to find using IO.Swagger.Client; but I am not able to find using IO.Swagger.Api;
This is a sample code I am not sure how I can get LaunchPadApi defined so "responsePost" method is not recognized as well,
using System;
using System.Diagnostics;
using IO.Swagger.Api;
using IO.Swagger.Client;
using IO.Swagger.Model;
public class responsePostExample
{
public void main()
{
var apiInstance = new LaunchPadApi();
....
try
{
apiInstance.responsePost(body, xAPIKey);
}
....
Install Launchpad in your nuget package manager for the project
Add using Launchpad; to the top of your file

setup ironpython: Module not found

I'm using Ironpython for the first time to Import a Python Script to C#. I get the error "No module named numpy", but I don't know why. I read that I have to add my path of my modules to my python script. This is my python script:
import numpy as np
import sys
sys.path.append(r"C:\Users\abc\CSharp\PythonScriptExecution1\packages\IronPython.2.7.9\lib")
sys.path.append(r"C:\Users\abc\PycharmProjects\untitled3\venv\Lib")
sum = np.sum([0.5, 1.5])
print(sum)
The second path is the path which is also used as project interpreter in Pycharm for the python.exe.
My C# code is this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PythonScriptExecution2
{
class Program
{
static void Main(string[] args)
{
Microsoft.Scripting.Hosting.ScriptEngine pythonEngine =
IronPython.Hosting.Python.CreateEngine();
// We execute this script from Visual Studio
// so the program will be executed from bin\Debug or bin\Release
Microsoft.Scripting.Hosting.ScriptSource pythonScript =
pythonEngine.CreateScriptSourceFromFile("C:/Users/abc/PycharmProjects/untitled3/test.py");
pythonScript.Execute();
}
}
}
Running the Python script in Pycharm works fine, but importing it to C# results in the error mentioned above. Can someone help me how to set the right paths?
edit: If it doesn't work, does anyone know any other way to run a python script with C#?
Related to How to add modules to Iron Python?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PythonScriptExecution2
{
class Program
{
static void Main(string[] args)
{
Microsoft.Scripting.Hosting.ScriptEngine eEngine =
IronPython.Hosting.Python.CreateEngine();
// We execute this script from Visual Studio
// so the program will be executed from bin\Debug or bin\Release
Microsoft.Scripting.Hosting.ScriptSource pythonScript =
ICollection<string> searchPaths = engine.GetSearchPaths();
searchPaths.Add(#"C:\Users\abc\CSharp\PythonScriptExecution1\packages\IronPython.2.7.9\lib");
searchPaths.Add(#"C:\Users\abc\PycharmProjects\untitled3\venv\Lib");
engine.SetSearchPaths(searchPaths);
engine.CreateScriptSourceFromFile("C:/Users/abc/PycharmProjects/untitled3/test.py");
pythonScript.Execute();
}
}
}

Issues with Intellisense and class library

I am using Visual Studio 2013. I am trying to start unit testing by using this tutorial.
I have added a class library and a reference to MVC. However, the Intellisense/Autocompletion is not working properly within my class library. Currently, this is all the code I have in my test class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NUnit.Framework;
using System.Web.Mvc;
using System.Web;
using Application_Portal;
using Application_Portal.Controllers;
namespace ApplicationPortalTests
{
[TestFixture]
public class HomeControllerTest
{
HomeController home = new HomeController();
}
}
The Intellisense does not seem to recognize the home variable (no suggested properties, etc.) Typing home.Index() gives the following error:
ApplicationPortalTests.HomeControllerTest.home' is a 'field' but is used like a 'type'
Furthermore, it does not even seem to recognize "var" (as in var result = ...). Instead, when I type var and hit space, it autocompletes it as EnvironmentVariableTarget.
I have tried cleaning and rebuilding the project, and closing and reopening Visual Studio, but with no success.
What might the issue be? I appreciate any advice.
You have declared your variable inside the class. If you want to use this variable, it must be within the context of a member. For instance:
[Test]
public void test_my_index_page()
{
var result = home.index();
}

webservice with exceldna and c#

I am using a Java webservice. I'm consuming it with an Excel function which I made using c# and excel-dna. The problem is that everytime I call the function add I get (#valeur).
This my c# code source:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ExcelDna.Integration;
using System.Diagnostics;
using System.ServiceModel;
using System.ServiceModel.Channels;
namespace MyLibrary
{
public class Class1
{
[ExcelFunction(Description = "adds two terms")]
public static int add(int a, int b)
{
ServiceReference1.ServerImplClient client =
new ServiceReference1.ServerImplClient();
return client.addition(a, b);
}
}
}
Service Reference has been included and the dna and xll files also.
Approach debugging this step by step.
To debug an Excel DNA method from Visual Studio, you need to:
bring up your Excel; make sure that the XLL that is loaded is the one in the bin directory
in Visual studio "attach" to the excel process (tools->attach to process or Ctrl-Alt-p)
put a breakpoint at the start of your function (if the correct XLL is loaded the breakpoint will be a filled circle; if it isn't then the loaded XLL is a different one)
If you then make a call to your function and it doesn't hit the breakpoint, you may be passing in the wrong parameter types (side note: all numeric values in Excel are doubles - you can always have object parameters and check the arguments in your function).
If it does hit your function then you can step through your client code in the normal way.

C# DLL using DllExport: No entry point when called in VBA

To avoid requiring a Dll be registered for all users of a spreadsheet, I'm trying to use late binding so that users do not need to add a reference to the Dll.
I've created the Dll in C# with Visual Studio, and even though I've included "using RGiesecke.DllExport;" and used DllExport on a function to return an object containing the functions I need to access in VBA, I still get the error "Run-time error '453': Can't Find DLL entry point CreateDotNetObject in C:\temp\MyFunctions.dll."
The DLL code is as follows:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.TeamFoundation.WorkItemTracking.Client;
using System.Data;
using System.Text.RegularExpressions;
using Microsoft.TeamFoundation.Client;
using System.Runtime.InteropServices;
using System.ComponentModel;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
using System.Collections;
using System.Collections.ObjectModel;
using System.Threading;
using Microsoft.TeamFoundation.Framework.Client;
using Microsoft.TeamFoundation.Framework;
using Microsoft.TeamFoundation.Common;
using Microsoft.VisualBasic;
using System.Diagnostics;
using RGiesecke.DllExport;
namespace MyFunctions
{
public interface IMyFunctions
{
string GetWorkItemLinkList(string WIIDs);
}
[CLSCompliant(true), ComVisible(true), ClassInterface(ClassInterfaceType.AutoDual)]
public class MyFunctions : IMyFunctions
{
TfsConfigurationServer server;
WorkItemStore store;
private void TFSconnect()
{
//Code to connect
}
[CLSCompliant(true), ComVisible(true), Description("GetWorkItemLink func")]
public string GetWorkItemLink(int WIID)
{
TFSconnect();
//Code to build return string "message"
return message;
}
[CLSCompliant(true), ComVisible(true), Description("GetWorkItemLinkList func")]
public string GetWorkItemLinkList(string WIIDs)
{
TFSconnect();
//Code to build return string "returnStr"
return returnStr;
}
}
static class UnmanagedExports
{
[DllExport]
[return: MarshalAs(UnmanagedType.IDispatch)]
static Object CreateDotNetObject()
{
return new MyFunctions();
}
}
}
and the declaration in VBA is as follows:
Private Declare Function CreateDotNetObject Lib "c:\temp\MyFunctions.dll" () As Object
But when I try to instantiate an object, I get the error I mentioned above.
Sub test()
Dim o As Object
Set o = CreateDotNetObject()
End Sub
This is my first time attempting to use custom dll functions in Excel without adding a reference in the VBA. The functions do work if I add a reference (early binding), but the DLL is not going to be propogated to everyone who uses the spreadsheet, and I need it to not crash when they run normal functions.
EDIT: Additional info. I just noticed that in addition to the DLL, when I build the solution in Visual Studio I also get an " Object FileLibrary" and an "Exports Library File". When I register the DLL is there anything I should be doing with either the .exp or .lib?
Thanks,
Mike
I was building the solution with the Platform Target in the class library properties set to "Any PC", which apparently does not allow exports. When I switch it to "x86" it totally works.

Categories

Resources