c# - Run a R Script from asp.net application and get the output from r -
i need run r script stored in folder asp.net application , show output of r script in web page.
below code of default.aspx.cs file
using rdotnet; using system; using system.collections.generic; using system.io; using system.linq; using system.web; using system.web.ui; using system.web.ui.webcontrols; public partial class _default : system.web.ui.page { protected void page_load(object sender, eventargs e) { } private static double evaluateexpression(rengine engine, string expression) { var expressionvector = engine.createcharactervector(new[] { expression }); engine.setsymbol("expr", expressionvector); // wrong -- need parse expression before evaluation //var result = engine.evaluate("eval(expr)"); // right way this!!! var result = engine.evaluate("eval(parse(text=expr))"); var ret = result.asnumeric().first(); return ret; } public static void setuppath(string rversion = "r-3.2.1") { var oldpath = system.environment.getenvironmentvariable("path"); var rpath = system.environment.is64bitprocess ? string.format(@"c:\program files\r\{0}\bin\x64", rversion) : string.format(@"c:\program files\r\{0}\bin\i386", rversion); 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); } protected void button1_click(object sender, eventargs e) { setuppath(); rengine.setenvironmentvariables(); rengine engine = rengine.getinstance(); // rengine requires explicit initialization. // can set parameters. engine.initialize(); string path = server.mappath("~/r script/rscript.r"); engine.evaluate("source('" + path + "')"); label1.text = evaluateexpression(engine, "c").tostring(); } }
the rscript.r script file has below simple coding
c<-sum(1,2,3,4)
the operation such way have button , when click button, r script in folder needs executed , result value needs displayed in label have in web page. have file rscript.r in web applications folder , getting pulled correctly.
when click on button code gets executed , web application throwing error
attempted read or write protected memory. indication other memory corrupt.
i tried google out not helpful. there way execute r file directly asp.net web application , output of executed file.
can me out?
i used rscriptrunner , solution got fixed. created class file rscriptrunner , called function in button click event.
rscriptrunner can execute r script using rscript.exe in commandline mode.
however not able output result r code.
Comments
Post a Comment