Executing Process not working - c#

The situation:
I want to modify the folder quotas on my FileServer through a process executing dirquota.exe
The Problem:
The Process being executed gives no result at all
So Far:
I've redirected the process and arguments being executed on my FileServer to take a closer look what's happening exactly on the serverside.
The executed process gave no exception and everything went just fine, it seemed..
When looking at the current folder quota's on my FileServer nothing has changed..I decided to copy paste my arguments in a CMD.exe on the server, then it all went fine...
I cannot figure why it is not working on my FileServer, probably somthing simple but I need some help here
Important Info:
I'm installing a Windows Service on my FileServer and calling the Method through SOUPUI (This is all working fine).
The installed service is running as a Domain admin and has all the required rights to perform these actions
The Class
public class Quota
{
public string FolderLocation;
public int SizeInMB;
public string FileServerName;
}
The Method
public string SetFolderQuota(Quota quota)
{
Process QuotaProcess = new Process();
QuotaProcess.StartInfo.RedirectStandardOutput = false;
QuotaProcess.StartInfo.FileName = #"cmd.exe";
QuotaProcess.StartInfo.UseShellExecute = true;
QuotaProcess.StartInfo.Arguments = "/C " + "dirquota Quota Add /PATH:" + '"' + quota.FolderLocation + '"' + " /Limit:" + quota.SizeInMB + "mb" + " /remote:" + quota.FileServerName;
try
{
QuotaProcess.Start();
}
catch(Exception Ex)
{
return Ex.Message;
}
return "Correctly Executed: " + QuotaProcess.StartInfo.FileName + QuotaProcess.StartInfo.Arguments;
}

Found The Problem
dirquota.exe is redirected using Windows-on Windows 64-bit redirection. What's happening is that my launch request (from a 32-bit process) is being redirected to %windir%\SysWOW64\dirquota.exe. Since there's no 32-bit version of this particular executable on 64-bit installs, the launch fails. To bypass this process and allow my 32-bit process to access the native (64-bit) path, I have to reference %windir%\sysnative instead
The Code
public string SetFolderQuota(Quota quota)
{
string FileLocation = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows),#"sysnative\dirquota.exe");
Process QuotaProcess = new Process();
QuotaProcess.StartInfo.RedirectStandardOutput = false;
QuotaProcess.StartInfo.FileName = FileLocation;
QuotaProcess.StartInfo.UseShellExecute = true;
QuotaProcess.StartInfo.Arguments = " Quota Add /PATH:" + '"' + quota.FolderLocation + '"' + " /Limit:" + quota.SizeInMB + "mb" + " /remote:" + quota.FileServerName;
try
{
QuotaProcess.Start();
}
catch(Exception Ex)
{
return Ex.Message + Environment.NewLine + "FileLocation: " + FileLocation;
}
return "Correctly Executed: " + QuotaProcess.StartInfo.FileName + QuotaProcess.StartInfo.Arguments;
}

Best if you can redirect the output of Process to a log file and see what is the actual exception..
ProcessStartInfo process = new ProcessStartInfo
{
CreateNoWindow = false,
UseShellExecute = false,
RedirectStandardOutput = true,
FileName = #"cmd.exe",
Arguments = "/C " + "dirquota Quota Add /PATH:" + '"' + quota.FolderLocation + '"' + " /Limit:" + quota.SizeInMB + "mb" + " /remote:" + quota.FileServerName
};
Process p = Process.Start(process);
string output = p.StandardOutput.ReadToEnd();
Log the value of output to get the exact exception caused by execution of this command

Related

SQL CLR calling Process.Start hangs or fails

I have checked and there are many posts similar but I cannot solve this. This is a SQL CLR proc to run an exe that parses PDF files. I can run same code as myself in console app. Permissions are not an issue. I am dumping to event log and the ProcessStartInfo is full formed. UseShellExecute - I am not certain. I have also created a .bat file to execute the code - run it manually - it runs fine. Via this CLR program ? Hangs or runs right away but does nothing. At wits end. My goal was to create the CLR using the Nuget from itext but I had a real hard time installing. SQL CLR doesnt support it but I tried anyway.
Thanks in advance.
[Microsoft.SqlServer.Server.SqlProcedure]
public static void PDFToCSVViaExe_CLR()
{
ProcessStartInfo startInfo = new ProcessStartInfo();
string args = #"\\app\Systems\Universal";
args = " \"" + args + "\"" + " \"" + "*" + "\"" + " \"" + "LVM" + "\"";
startInfo.CreateNoWindow = false;
startInfo.UseShellExecute = true;
startInfo.FileName = "c:\\SqlCLR\\PDFRipper\\PDFToCSV.exe";
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
startInfo.Arguments = args;
EventLog.WriteEntry(".NET Runtime", startInfo.FileName.ToString()+" " + args, EventLogEntryType.Warning, 1000);
string folder = "C:\\SqlCLR\\PDFRipper\\LVM.bat";
try
{
//using (new ImpersonationNamespace.Impersonation("domain", "user", "password"))
{
EventLog.WriteEntry(".NET Runtime", System.Security.Principal.WindowsIdentity.GetCurrent().Name + " OR " + Environment.UserName, EventLogEntryType.Warning, 1000);
folder = System.IO.Path.GetDirectoryName(folder);
if (!Directory.Exists(folder))
{
throw (new Exception("Directory does not exist for " + folder));
}
else
{ EventLog.WriteEntry(".NET Runtime", folder + " exists.", EventLogEntryType.Warning, 1000); }
// Start the process with the info we specified.
// Call WaitForExit and then the using statement will close.
using (Process exeProcess = Process.Start(startInfo))
{
exeProcess.WaitForExit();
}
}
}
catch (Exception ex)
{
using (EventLog EventLog = new EventLog("Application"))
{
EventLog.Source = "Application";
//eventLog.WriteEntry(ex.Message);
EventLog.WriteEntry(".NET Runtime", ex.Message + "Trace" + ex.StackTrace, EventLogEntryType.Warning, 1000);
//eventLog.WriteEntry(".NET Runtime", ex.Message, EventLogEntryType.Warning, 1000);
}
}

StackOverflow in WCF caused by R.Net

Good Day,
i am trying to write an R code in .net to run as a WCF function. this function is suppose to import a csv file to MSSQL using R using .net code.
I am getting a stackoverflow error when i try to reference the odbc library over wcf, however if i try to run the function using debug instance it passes that point.
public string R_to_MSSQL_Server(string data, string Server, string Database,string Tablename)
{
StartupParameter rinit = new StartupParameter();
rinit.Quiet = true;
rinit.RHome = #"C:\Program Files\R\R-3.4.4\";
rinit.Home = #"C:\R";
REngine.SetEnvironmentVariables();
REngine engine = REngine.GetInstance(null, true, rinit);
StringBuilder Data = new StringBuilder();
Data.Append(data);
string filepath = Path.Combine(Path.GetTempPath(), "RTable.csv");
//"UID= Tester;" +
//"PWD= rstudioapi::askForPassword(\"password\"); " +
try
{
UploadCSV(Data);
filepath = PathCleaning(filepath);
engine.Evaluate("Data <- read.csv(file<- '" + filepath + "', heade= TRUE, sep=',')");
engine.Evaluate("Table <- data.frame(Data)");
engine.Evaluate("connectionString <- ' " +
"driver={SQL Server}; " +
"server= "+ Server + "; " +
"database=" + Database + ";" +
"UID= Tester;" +
"PWD= rstudioapi::askForPassword(\"password\"); " +
"'");
engine.Evaluate("library(odbc)");
engine.Evaluate("library(healthcareai)");
engine.Evaluate("con<- DBI::dbConnect(odbc::odbc(),.connection_string=connectionString)");
engine.Evaluate("DBI::dbwriteTable(conn=con," + Tablename + " , Table)");
return "Completed successfully";
}
catch( Exception x)
{
return "Fail to complete" + x;
}
}
the error when i run it through WCF hits at "engine.evaluate("library(odbc)");"
This is where its being called by another machine accessing it through wcf.
static void Main(string[] args)
{
MainServiceClient client = new MainServiceClient();
string tablename = "Test Table";
string Table = "";
string Pkey ="Name";
Table=File.ReadAllText(#"\\lonvmfs02\Home\kr.williams\TestTable2.csv");
string query = client.R_to_MSSQL_Server(Table, "stage04", "CWDataSets", "Tester");
this is the error thats being thrown inside the WCF Machine ( W3wp debugging ).
System.StackOverflowException
HResult=0x800703E9
Source=
StackTrace:
this is all the exception details give.
how do it increase the size of the stack / get around this problem?
Thanks

running a exe file from web api on iis server not working

I want to execute an exe file on to The Web API as and when user request comes. It is working perfectly but when I am hosting web API to server the exe file is not executed when user request comes. What to do for executing the exe file from web API on IIS server?
Here is the process starting code:
public static void Start(long campaign_id, long contact_id, string startDate, string endDate, string user)
{
try
{
//WindowStyle = ProcessWindowStyle.Hidden;
startInfo.FileName = "cmd.exe";
startInfo.WorkingDirectory = #"C:\";
startInfo.Arguments = "/c sparkclr-submit --master " + ConfigurationManager.AppSettings["SparkMaster"] + " --driver-class-path " + AppDomain.CurrentDomain.BaseDirectory + "Engine\\mysql.jar " + "--exe CmAnalyticsEngine.exe " + AppDomain.CurrentDomain.BaseDirectory + "Engine " + campaign_id + " " + contact_id + " " + startDate + " " + endDate + " " + user;
process.StartInfo = startInfo;
process.Start();
}
catch (Exception e)
{
LogWritter.WriteErrorLog(e);
}
}
How are you starting the exe? You have any error logs?
You can try using the verb runas in Process.Start to execute the exe file as an Administrator.
ProcessStartInfo proc = new ProcessStartInfo();
proc.WindowStyle = ProcessWindowStyle.Normal;
proc.FileName = myExePath;
proc.CreateNoWindow = false;
proc.UseShellExecute = false;
proc.Verb = "runas"; //this is how you pass this verb

Run batch file remotely as administrator using psexec in C#

I have a .bat file on the remote machine. when i run manually cmd as admin, executed psexec works correctly. But in C#, i stuck somewhere. I would like to run this .bat file as administrator in C# code. Here is my code. Could someone help me, please?
public void CopyAtoBFolder()
{
int waitForExit = 1000 * 300;
string localDestinationFolderPath = #"D:\Tool\";
string call = localDestinationFolderPath + "CopyAtoBFolder.bat";
Process process = new Process();
process.StartInfo.FileName = this.path + #"\PsExec.exe";
process.StartInfo.Arguments = "-accepteula " + localDestinationFolderPath + #" \\" + ip + " -i -u " + username + " -p " + password + " " + call;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.UseShellExecute = false;
process.Start();
process.BeginOutputReadLine();
var ended = process.WaitForExit(waitForExit);
if (!ended)
{
throw new TifPcbaException("Process timed out.");
}
int resultReturnCode = process.ExitCode;
if (resultReturnCode != 0)
{
throw new TifPcbaException("PSExec return code " + resultReturnCode + " shows an error calling " + call + Environment.NewLine);
}
}
And here is the error.
PSExec return code 6 shows an error calling D:\Tool\CopyAtoBFolder.bat
Add a app.manifest in your project and change the following line in app.manifest file:
<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
This would force your application to run as admin

PDF generation using HTML Doc Software in asp.net

I am converting a website from 1.1 framework to 4.0. The website has functionality to Generate Pdf of the content entered in TextEditor. this website has used "HTMLDoc Software" to convert content to pdf using the below code:
string url, pdfFile, exeFile;
string response = "";
url = GetWebUrl() + "/PDFSpeechDetails.aspx?ArticleId=" + ValueOfQueryString;
pdfFile = HttpContext.Current.Request.PhysicalApplicationPath + "pdfs\\articles\\" + ValueOfQueryString + ".pdf";
exeFile = HttpContext.Current.Request.PhysicalApplicationPath + "html2pdf\\htmldoc.exe";
response = gPDF.ShowPDF(url, pdfFile, exeFile);
and ShowPDF Method is:
public string ShowPDF(string url, string pdfFile, string exeFile)
{
try
{
Process p = new Process();
p.StartInfo.FileName = exeFile;
pdfFile = "\"" + pdfFile + "\"";
string args = " --webpage -f " + pdfFile + " " + url;
p.StartInfo.Arguments = args;
p.Start();
p.WaitForExit();
return "1";
}
catch (Exception ex)
{
return (ex.ToString());
}
}
What the above code is doing:(as the previous developer used)
I have placed a folder named HTML2PDf has an exe file. i am just passing it to argument and running this exe file.
This code is working fine on my local machine as well as on server(I took remote of the server and checked there.), but when i tried to generate the PDF from Outer world means using website's domain name, it does not work. I am not getting any clue why it is not working.
please help me how can i make it working on website.

Categories

Resources