I have mvc project and R project under same solution, I want to run mvc first display it on browser then send some arguments to script.R in R project then run R project and refreshing mvc based on results of R project
Currently I can execute Script.r and the results saved as html then I run mvc and html results from R are displayed on the browser.
I need to make it automatically.
My code is like this code https://1drv.ms/u/s!Ar6hTIP_Ln58h6JtpQQ3yt3JjIsIFg
Controller code
using WebApplication1.Infrastructure;
public ActionResult Index()
{
RScript.Run("HeatMap", 1997);
RScript.Run("HeatMap", 1998);
return View();
}
Rscript class code
public static class RScript
{
public static bool Run(string filename, int year = 0)
{
var rCodeFilePath = $"C:\\Users\\COMNET\\source\\repos\\Test\\RProject1\\RProject1\\{filename}.R";
if (year != 0)
rCodeFilePath = $"{rCodeFilePath} {year}";
var rScriptExecutablePath = #"C:\Program Files\R\R-3.4.3\bin\x64\Rscript.exe";
var result = string.Empty;
try
{
var info = new ProcessStartInfo
{
FileName = rScriptExecutablePath,
WorkingDirectory =
Path.GetDirectoryName(rScriptExecutablePath),
Arguments = rCodeFilePath,
RedirectStandardInput = false,
RedirectStandardOutput = true,
UseShellExecute = false,
CreateNoWindow = true
};
using (var proc = new Process())
{
proc.StartInfo = info;
proc.Start();
proc.Close();
}
return true;
}
catch (Exception ex)
{
//return false;
throw new Exception("R Script failed: " + result, ex);
}
}
}
R script code
library(RODBC)
library(ggplot2)
args <- commandArgs(TRUE)
cn <- odbcConnect('', uid = '', pwd = '')
view <- ifelse(args[1] == 1998, 'vwR1TranValuebyCountryCategoty98', 'vwR1TranValuebyCountryCategoty97')
qtyNatCat <- sqlFetch(cn, view)
odbcClose(cn)
q <- ggplot(qtyNatCat, aes(x = Category, y = Country, fill = TransValue))
q <- q + geomtile()
q <- q + geomraster()
q <- q + scalefillgradient(low = "#c00000", high = "#00c000", na.value = "white")
q <- q + xlab('') + ylab('')
q <- q + theme(axis.text.x = elementtext(angle = 10, hjust = 1, vjust = 1))
q <- q + labs(fill = "Qty\nper\nTran")
wd <- getwd()
imagedir <- paste("C:\\Users\\COMNET\\Downloads\\net to the power of r\\NorthwindDashboard\\NorthwindDashboard\\Content\\html\\", sep = "")
setwd(imagedir)
filename <- ifelse(args[1] == 1998, 'heatmap98.png', 'heatmap97.png')
if (file.exists(filename))
file.remove(filename)
ggsave(q, file = filename, width = 9, height = 4)
setwd(wd)
Related
I have an API that automatically pulls new order details from my Woocommerce store into a Google Sheet. It seems to be working however, it has failed to pull the first 7 orders into my google sheet. It has all of the orders after the first 7. How do I get it to pull the first 7 orders into the sheet?
Here is my Google App Script:
function start_sync() {
// Followed instructions at https://github.com/mithunmanohar/woocommerce-orders-google-sheets-integration
var sheet_name = "OrderDetails"
update_order_5_min(sheet_name)
}
function update_order_5_min(sheet_name) {
var ck = "ck_ed82fae51e5bafce28dde95224db9c9c4bd36dba";
var cs = "cs_9a16fd7b641769a65412f336de3e7a928f7e153c";
var website = "https://www.funtrackdayz.com";
var now = new Date();
var website_t ="240";
var min = website_t * 60
now.setMinutes(now.getMinutes() - min);
var n = now.toISOString();
var surl = website + "/wc-api/v3/orders?consumer_key=" + ck + "&consumer_secret=" + cs + "&status=processing&filter[created_at_min]=" + n //"&after=2016-10-27T10:10:10Z"
// var surl = website + "/wc-api/v3/orders?consumer_key=" + ck + "&consumer_secret=" + cs + "&status=processing"
// &filter[created_at_min]=" + n //"&after=2016-10-27T10:10:10Z"
var url = surl
var options = {
"method": "GET",
"Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
"muteHttpExceptions": true,
};
var result = UrlFetchApp.fetch(url, options);
if (result.getResponseCode() == 200) {
var params = JSON.parse(result.getContentText());
}
var doc = SpreadsheetApp.getActiveSpreadsheet();
var temp = doc.getSheetByName(sheet_name);
var consumption = {}
//"orders"
arrayLength = params["orders"].length
for (var i = 0; i < arrayLength; i++) {
var container = [];
a = container.push(params["orders"][i]["billing_address"]["first_name"]);
a = container.push(params["orders"][i]["billing_address"]["last_name"]);
a = container.push(params["orders"][i]["billing_address"]["address_1"] + ", " + params["orders"][i]["billing_address"]["address_2"]);
a = container.push("");
a = container.push(params["orders"][i]["billing_address"]["city"]);
a = container.push(params["orders"][i]["billing_address"]["state"]);
a = container.push(params["orders"][i]["billing_address"]["postcode"]);
a = container.push(params["orders"][i]["billing_address"]["phone"]);
a = container.push(params["orders"][i]["billing_address"]["email"]);
a = container.push(params["orders"][i]["total"]); //price
a = container.push(params["orders"][i]["payment_details"]["method_id"]);
c = params["orders"][i]["line_items"].length;
items = "";
skus="";
for (var k = 0; k < c; k++) {
item = params["orders"][i]["line_items"][k]["name"];
qty = params["orders"][i]["line_items"][k]["quantity"];
sku = params["orders"][i]["line_items"][k]["sku"];
meta = ""
try {
meta = params["orders"][i]["line_items"][k]["meta"][0]["value"];
meta = " - " + meta
} catch (err) {
meta = ""
}
item_f = qty + " x " + item + meta
items = items + item_f + ",\n"
skus = skus + ",\n"
}
a = container.push(items)
a = container.push(sku)
// a = container.push(params["orders"][i]["total_line_items_quantity"]); // Quantity
a = container.push(params["orders"][i]["order_number"]); //
a = container.push(params["orders"][i]["note"])
a = container.push(params["orders"][i]["created_at"]);
var doc = SpreadsheetApp.getActiveSpreadsheet();
var temp = doc.getSheetByName(sheet_name);
temp.appendRow(container);
removeDuplicates(sheet_name)
}
}
function removeDuplicates(sheet_name) {
var doc = SpreadsheetApp.getActiveSpreadsheet();
var sheet = doc.getSheetByName(sheet_name);
var data = sheet.getDataRange().getValues();
var newData = new Array();
for (i in data) {
var row = data[i];
var duplicate = false;
for (j in newData) {
if (row.join() == newData[j].join()) {
duplicate = true;
}
}
if (!duplicate) {
newData.push(row);
}
}
sheet.clearContents();
sheet.getRange(1, 1, newData.length, newData[0].length).setValues(newData);
}
I need to make a function which call Oracle R Enterprise ore.corr function and output result as a data.frame.
My R code here:
f_sts_corelation =
function(dat, target_col="",corr_type="spearman",group_by="")
{
v_target_col = gsub("\n","",target_col, fixed = TRUE);
v_target_col_list = "";
library("gdata");
for (s_name in strsplit(v_target_col,",")[[1]])
{
n_pos = regexpr(".",s_name,fixed = TRUE);
if (n_pos > 0)
{
s_name = substring(s_name,n_pos+1);
}
s_name = gsub("\"","",s_name, fixed = TRUE);
if (is.numeric(dat[,trim(s_name)]))
{
if (nchar(v_target_col_list)== 0)
{
v_target_col_list = trim(s_name)
}
else
{
v_target_col_list =paste(v_target_col_list,",",trim(s_name))
}
}
}
ore.data = ore.push(dat)
v_id = c()
v_group=c()
v_row = c()
v_col = c()
v_statistic = c()
v_pvalue = c()
v_df = c()
#group_by = ""
s_group_by = trim(gsub("\n","",group_by, fixed = TRUE));
if (nchar(s_group_by) > 0)
{
n_pos = regexpr(".",s_group_by,fixed = TRUE);
if (n_pos > 0)
{
s_group_by = substring(s_group_by,n_pos+1);
}
s_group_by = trim(gsub("\"","",s_group_by, fixed = TRUE));
ore.corr.res = ore.corr(ore.data,var = v_target_col_list, group.by = s_group_by)
for (i in 1:length(ore.corr.res))
{
if (i == 1)
{
v_group = rep(names(ore.corr.res[i]),length(ore.corr.res[[i]]$ROW))
v_row = as.vector(ore.corr.res[[i]]$ROW)
v_col = as.vector(ore.corr.res[[i]]$COL)
v_statistic = as.vector(ore.corr.res[[i]][,3])
v_pvalue = as.vector(ore.corr.res[[i]][,4])
v_df = as.vector(ore.corr.res[[i]][,5])
}
else
{
v_group = c(v_group,rep(names(ore.corr.res[i]),length(ore.corr.res[[i]]$ROW)))
v_row = c(v_row,as.vector(ore.corr.res[[i]]$ROW))
v_col = c(v_col,as.vector(ore.corr.res[[i]]$COL))
v_statistic = c(v_statistic,as.vector(ore.corr.res[[i]][,3]))
v_pvalue = c(v_pvalue,as.vector(ore.corr.res[[i]][,4]))
v_df = c(v_df,as.vector(ore.corr.res[[i]][,5]))
}
}
}
else if(nchar(s_group_by) == 0)
{
ore.corr.res = ore.corr(ore.data,var = v_target_col_list)
v_group = rep(" ",length(ore.corr.res$ROW))
v_row = as.vector(ore.corr.res$ROW)
v_col = as.vector(ore.corr.res$COL)
v_statistic = as.vector(ore.corr.res[,3])
v_pvalue = as.vector(ore.corr.res[,4])
v_df = as.vector(ore.corr.res[,5])
}
df_res = data.frame(Group_by = v_group,
Row = v_row,
Col = v_col,
Statistic = v_statistic,
P_Value = v_pvalue,
DF = v_df)
}
After that, I run the function by following script:
dat = iris;
corr_type="spearman";
V_target_col= '"IRIS_N$10002"."Sepal.Length",
"IRIS_N$10002"."Sepal.Width",
"IRIS_N$10002"."Petal.Width",
"IRIS_N$10002"."Petal.Length"';
group_by =
'
"IRIS_N$10002"."Species"
'
df_result = f_sts_corelation(dat,target_col = target_col, group_by = group_by)
But following error happen.
Error: ORE object has no unique key
I have tried to run each R command inside my function step by step and I sure that the Error happen from the last R command:
df_res = data.frame(Group_by = v_group,
Row = v_row,
Col = v_col,
Statistic = v_statistic,
P_Value = v_pvalue,
DF = v_df)
I don't know how to avoid this error.
I have a project that read an excel file and write into some data later on download this file. I have created this project in ASP.NET.
I can read excel file and write into something then I save it as different name.In my local computer this code work properly and I do not have any error in these code.But When I publish this project I did not get any error but my project did not give me any result of as I wanted. How can I solve this problem?
public static void ReadExistingExcel()
{
#region excelformac
// var fileName = "SOF46501-firmaadi-08062015.xltx";
string path = HttpContext.Current.Server.MapPath("~/File/SOF46501-firmaadi-08062015.xltx");
// path = "D:\\SOF46501-firmaadi-08062015.xltx";
oXL = new Microsoft.Office.Interop.Excel.Application();
oXL.Visible = true;
oXL.DisplayAlerts = false;
mWorkBook = oXL.Workbooks.Open(path, 0, false, 5, "", "", false, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "", true, false, 0, true, false, false);
//Get all the sheets in the workbook
mWorkSheets = mWorkBook.Worksheets;
//Get the allready exists sheet
mWSheet1 = (Microsoft.Office.Interop.Excel.Worksheet)mWorkSheets.get_Item("Standart USD");
Microsoft.Office.Interop.Excel.Range range = mWSheet1.UsedRange;
#endregion
int sofNo = 0, sofNo2 = 0;
ProductBUS productBUS = new ProductBUS();
List<UrunCikisVO> uruncikisVO = new List<UrunCikisVO>();
uruncikisVO = productBUS.GetProduct();
sofNo = productBUS.SofNo();
sofNo2 = sofNo + 1;
if (productBUS.SofUpdate(sofNo2))
{
}
int j = 0;
for (int i = 0; i < uruncikisVO.Count; i++)
{
if (i % 10 == 0)
{
j = 0;
sofNo = productBUS.SofNo();
sofNo2 = sofNo + 1;
if (productBUS.SofUpdate(sofNo2))
{
}
}
else
{
j++;
}
mWSheet1.Cells[i + 8, 2] = uruncikisVO[i].UrunKodu;
mWSheet1.Cells[i + 8, 4] = uruncikisVO[i].UrunTanimi;
mWSheet1.Cells[i + 8, 5] = uruncikisVO[i].Adet;
mWSheet1.Cells[i + 8, 6] = uruncikisVO[i].BirimFiyat;
mWSheet1.Cells[i + 8, 7] = uruncikisVO[i].ToplamFiyat;
mWSheet1.Cells[2, 3] = sofNo;
mWSheet1.Cells[3, 3] = uruncikisVO[0].SiparisTarihi;
mWSheet1.Cells[4, 3] = uruncikisVO[0].ResmiAdi;
mWSheet1.Cells[5, 3] = uruncikisVO[0].phone;
mWSheet1.Cells[6, 7] = uruncikisVO[0].ParaBirim;
mWSheet1.Cells[20, 4] = uruncikisVO[0].MüsteriTemsilcisi;
mWSheet1.Cells[21, 4] = uruncikisVO[0].Notlar;
mWSheet1.Cells[22, 4] = uruncikisVO[0].SiparisTarihi + "/" + uruncikisVO[0].OdemeSekli;
mWSheet1.Cells[23, 4] = uruncikisVO[0].TeslimatTarihi;
mWSheet1.Cells[24, 4] = uruncikisVO[0].VergiDairesi + " / " + uruncikisVO[0].VergiNo;
mWSheet1.Cells[25, 4] = uruncikisVO[0].ResmiAdi;
mWSheet1.Cells[26, 4] = uruncikisVO[0].FirmaAdresi;
}
#region excelsave_Close
mWorkBook.SaveAs("D:\\SOF" + sofNo + "-" + uruncikisVO[0].ResmiAdi + "-" + DateTime.Now.ToShortDateString() + ".xls", Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookDefault, Type.Missing, Type.Missing, false, false, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
mWorkBook.Close(Type.Missing, Type.Missing, Type.Missing);
mWSheet1 = null;
mWorkBook = null;
oXL.Quit();
GC.WaitForPendingFinalizers();
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
#endregion
}
It might actually be the version of Microsoft used on Local vs on Production. I'd suggest you look into something like EPPlus http://epplus.codeplex.com/. This will give you the flex of using the right DLL both locally and on production.
More references
Create/Read/Edit Advance Excel 2007/2010 Report in C#.Net using EPPlus
Writing Excel Files using EPPLus
Import/Export Data from Excel Files (.xlsx) to DataGridView or Vice Versa Using EPPlus
and check this answer as well
Reading Excel spreasheet using EPPlus
I have written the following code to export data to excel.
This code works fine on local,but when we deploy this code on Server (UAT),it doesn't work.
If we restart server, it works for a while but again after a while it fails.
Code:
public void ExportToExcelFunction(string FlName, DataTable mydt, string DispColName, string BindCols)
{
Excel.Application xlObj = new Excel.Application();
object oMissing = System.Reflection.Missing.Value;
xlObj.Visible = false;
//vinod
string filepath = Server.MapPath("Export");
string strFlName = filepath + "\\Master.xlsx";
Excel.Workbook xlWB = xlObj.Workbooks.Open(strFlName, 0, true, 5, "", "", false, Excel.XlPlatform.xlWindows, "", true, true, 0, true);
Excel.Worksheet xlSheet = (Excel.Worksheet)xlWB.ActiveSheet;
int cols = mydt.Columns.Count;
int rows = mydt.Rows.Count;
//Added for export to excel
try
{
//For Column
string[] strCols = DispColName.Split(',');
for (int i = 1; i <= strCols.Length; i++)
{
if (strCols[i - 1].Length > 0 && strCols[i - 1] != null)
xlSheet.Cells[1, i] = Convert.ToString(strCols[i - 1]);
}
// for Row
string[] strColBind = BindCols.Split(',');
for (int r = 0; r < rows; r++)
{
for (int c = 0; c < strColBind.Length; c++)
{
xlSheet.Cells[r + 2, c + 1] = mydt.Rows[r][strColBind[c]];
}
}
}
catch (Exception ex)
{
}
String newFlName = "\\" + DateTime.Now.Ticks.ToString() + "_" + FlName + ".xls";
xlWB.SaveAs(filepath + newFlName, Excel.XlFileFormat.xlWorkbookNormal, "", "", false, false, Excel.XlSaveAsAccessMode.xlExclusive, true, false, "", true);
xlWB.Close(true, oMissing, oMissing);
xlObj.Quit();
System.IO.FileInfo file = new System.IO.FileInfo(#"" + filepath + newFlName + "");
Response.Clear();
Response.ClearHeaders();
Response.ClearContent();
Response.AppendHeader("Content-Disposition", "attachment; filename = " + FlName + ".xls");
Response.AppendHeader("Content-Length", file.Length.ToString());
Response.ContentType = "application/download";
Response.WriteFile(file.FullName);
Response.Flush();
Response.Close();
Response.End();
}
Two things you should know.
The first, is that your code appears to be using Excel Interop Services, thus it requires Excel to be installed on the server.
The second thing is that using Excel Interop Services on the server side is not supported by Microsoft, for a number of good reasons.
Instead, I suggest using an alternative library such as EPPlus or Open Office XML SDK, both of which run on the server side just fine.
I'm trying to research the routed direction using google maps for asp.net control. Here is my Code.
GoogleMapForASPNet1.GoogleMapObject.APIKey = ConfigurationManager.AppSettings["GoogleAPIKey"];
GoogleMapForASPNet1.GoogleMapObject.Width = "1100px";
GoogleMapForASPNet1.GoogleMapObject.Height = "600px";
GoogleMapForASPNet1.GoogleMapObject.ZoomLevel = 10;
GoogleMapForASPNet1.GoogleMapObject.CenterPoint = new GooglePoint("1", 1.352083, 103.819836);
GoogleMapForASPNet1.GoogleMapObject.ShowTraffic = true;
int count=0;
bool flag = false;
GoogleMapForASPNet1.GoogleMapObject.Points.Clear();
foreach (var gitem in tblG)
{
foreach (var item in tblDT)
{
if (item.Latitude==gitem.Latitude && item.Longitude==gitem.Longitude && flag!=true)
{
count += 1;
GooglePoint GP1 = new GooglePoint();
GP1.ID = "GP" + count.ToString();
GP1.Latitude = Convert.ToDouble(gitem.Latitude);//latitude;
GP1.Longitude = Convert.ToDouble(gitem.Longitude);
GP1.InfoHTML = " Name:<b>" + Name + "</b></br>Point:<b>" + "GP" + count.ToString() + "</b></br>Time:<b>" + gitem.CDate.ToString() + "</b></br>";//stime;
GoogleMapForASPNet1.GoogleMapObject.Points.Add(GP1);
string address = gitem.Latitude + "," + gitem.Longitude;
GoogleMapForASPNet1.GoogleMapObject.Directions.Addresses.Add(address);
flag = true;
}
}
flag = false;
}
I want it as Routed Direction is only between start and End point.
But I got result look like driving Direction. I don't want to get that result. How to fix that problem?