Catching a vbscript error from c# (the vbscriot executed from c#) - c#

i'm trying to execute vbscript from c#, the vbscript runs always succesfully despite of the fact that i don't have permissions to run this script.
the code:
//nswp is the User's password
foreach (char c in uspw)
{
password.AppendChar(c);
}
Process scriptProc = new Process();
scriptProc.StartInfo.RedirectStandardOutput = true;
scriptProc.StartInfo.RedirectStandardError = true;
scriptProc.StartInfo.Domain = "moia.gov.il";
scriptProc.StartInfo.ErrorDialog = true;
scriptProc.StartInfo.UserName = Globals.CURRENT_USER.user_name;
scriptProc.StartInfo.Password = password;
scriptProc.StartInfo.UseShellExecute = false;
scriptProc.StartInfo.FileName = #"cscript";
scriptProc.StartInfo.Arguments = "//B //Nologo " + pathSave;
scriptProc.Start();
scriptProc.WaitForExit();
scriptProc.Close();
When i'm executing this vbscript manually (by double click on the file icon) i get a permissions error, as i should.
How can i catch this error in c# and throw exception respectively.

You don't have a lot of options when using a different process like you do here. This is about it:
scriptProc.WaitForExit();
if (scriptProc.ExitCode != 0) throw new Exception("Script failed");
You can get rich error info by executing the script in-process by using the COM scripting host. That could be overkill, hard to tell.

Related

How do i execute an external exe using a specific user

Im making an application which needs to monitor the filesystem using FileSystemWatcher, to detect how an installation affects the filesystem.
To get rid of noise i want to filter the events that are created by their creating user, and that code is working with the //BUILTIN //Administrator user, which is used by default when doing an installation. But still there are quite a bit of noise. Then i got the idea of creating a specific user that i can use for running the installation file, and filter on that specific user, and thereby getting rid of allmost all the noise.
this is my code for the process creation and start
private void executeInnoInstaller(string path, string fileName)
{
// Use ProcessStartInfo class
ProcessStartInfo installerProces = new ProcessStartInfo();
installerProces.CreateNoWindow = true;
installerProces.UseShellExecute = false;
installerProces.FileName = path + "\"" + fileName + "\"";
installerProces.WindowStyle = ProcessWindowStyle.Normal;
installerProces.UserName = "test";
System.Security.SecureString encPassword = new System.Security.SecureString();
foreach (System.Char c in "test")
{
encPassword.AppendChar(c);
}
encPassword.MakeReadOnly();
installerProces.Password = encPassword;
try
{
// Start the process with the info we specified.
// Call WaitForExit and then the using statement will close.
using (Process exeProcess = Process.Start(installerProces))
{
exeProcess.WaitForExit();
//int exitCode = exeProcess.ExitCode;
}
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
this code exits with a access denied.
OS=Windows
Ive already tried to run the installer.exe from the OS filehandler with SHIFT - Rightclick using the specified user, and it works.
VisualStudio is run as administrator.
Ive tried to run the build project exe file as administrator, but it does not work.
Without the user credentials, the code works and uses the //BUILTIN //Administrator account
Does anybody have any idea ?
Thank you beforehand for your time and effort.
This code works if i turn down the UAC securitylevel to the lowest.

Python code execution through .net web application : getting error "No module named pyodbc"

I am trying to Execute python script from my .Net Web Application. For this I have installed Python from nuget package manager. But I am getting following errors during execution:
I have attempted following code chunks for getting resolution but I am not able to execute it successfully.
Below is the Python Scrip to Insert a record in SQL Server database:
import pyodbc
conn = pyodbc.connect('DRIVER={SQL Server Native Client
11.0};SERVER=*****\SQLEXPRESS;DATABASE=TestDB;UID=sa;PWD=****')
cur = conn.cursor()
cur.execute("Insert into Results([EmailID],[Journey]) VALUES (?,?)", 55,
"JourneyName")
conn.commit()
Print("Success")
Below is the C# Code to execute above python file.
public string run_cmd(string strPath) //this must not be async
{
try
{
ProcessStartInfo start = new ProcessStartInfo();
start.FileName = #"C:\Anaconda\python.exe";
start.Arguments = string.Format("C:\\Users\\261866\\TestPYCode.py");
start.UseShellExecute = false;
start.CreateNoWindow = true;
start.RedirectStandardOutput = true;
start.RedirectStandardError = true;
using (Process process = Process.Start(start))
{
using (StreamReader reader = process.StandardOutput)
{
string stderr = process.StandardError.ReadToEnd();
string result = reader.ReadToEnd();
return result;
}
}
}
catch (Exception ex)
{
return ex.Message;
}
return "run till end";
}
As I have executed above c# code I am getting below Error:
Traceback (most recent call last):"C:\Users\261866\TestPYCode.py"
import pyodbc Module Not Found Error: No module named 'pyodbc'
Error: No module named 'pyodbc'
The problem might be the source from where comes pyodbc. If your pyodbc comes from a .whl file then probably you have to install it using pip.
Here is the Microsoft's documentation says how to configure development environment for pyodbc.
Did you try it?
And here you've got ODBC Driver for SQL Server on Windows where you can download it and install.

System.Diagnostics.Process can't start process

I'm creating a service on VS2010, using .net framework 4.0 Client Profile. The target machine is Windows Server 2003 64 bits. This service move some files and then executes a process with System.Diagnostics.Process. The trouble is that, even if the taskmanager shows a process as starting, the executable never do whats was made for. Example code:
private void imprimir(string nombreImpresora, int copias, string nombreArchivo)
{
try
{
string copiasSumatra = "1,";
for (int i = 1; i < copias; i++)
{
copiasSumatra += "1,";
}
string path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
string comando = String.Format("-print-to \"{0}\" \"{1}\" -print-settings \"{2}odd,fit\" -silent", nombreImpresora, nombreArchivo, copiasSumatra);
string filename = '"' + Path.Combine(path, "SumatraPDF.exe") + '"';
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo.WorkingDirectory = path;
proc.StartInfo.FileName = filename;
proc.StartInfo.Arguments = comando;
proc.StartInfo.RedirectStandardError = false;
proc.StartInfo.RedirectStandardOutput = false;
proc.StartInfo.UseShellExecute = true;
proc.StartInfo.ErrorDialog = false;
proc.Start();
proc.WaitForExit();
lc.writeToLog("Instruction executed. Exit code: " + proc.ExitCode);
}
catch (Exception ex)
{
lc.writeToLog(ex.Message + " " + ex.StackTrace);
}
}
If I execute it on my dev machine (windows 8 pro) or in another test server (Windows Server 2003 32 bits) it makes whats expected. If I run it on the WS2003 64 bit server it does nothing.
I've debugged lots of times to see if it produces some error that I'm missing, but nothing happens. The "lc.writeToLog" method prints text to a file. I've used it to log every single line of the execution, but no error is thrown. Using that method I've concluded that it passes the "proc.WaitForExit()" instruction, so I think it's going to do what I've programmed, but nothing happens.
I have runned the same instruction but passing it a user, password and domain and the result was the same. Also tryed to capture standard error and output but it contained nothing.
What could be the trouble?
It was a server related issue. After deploying the application onto the production server the issue has disapeared.

app crashes with ProcessStartInfo arguments

I am trying to run a process called "prog.exe" with the arguments "blah $00" (sort of a code) but whatever I try fails.
string file = "blah $00";
string result = string.Empty;
ProcessStartInfo P = new ProcessStartInfo(#"""" + "prog.exe" + #"""");
P.Arguments = #"""" + file + #"""";
P.CreateNoWindow = true;
P.UseShellExecute = false;
P.RedirectStandardOutput = true;
Process.Start(P);
using (Process process = Process.Start(P))
{
using (StreamReader str = process.StandardOutput)
result = str.ReadToEnd();
}
MessageBox.Show(result);
When this code is executed, my program just crashes and I am forced to close it using the Task Manager.
I am not sure what's wrong with my code (am I not setting the arguments correctly?), so any help would be appreciated.
Run your process with given argument from console and see what happens. If result is something you expect, just remove double quotes and this should resolve your problem.
I don't think your program crashes. It just waits for "prog.exe" to finish! I bet, that your program continues running as soon as you are done working with prog.exe and close it - and make sure in task manager that it really is gone.

How to Integrate C++ compiler in Visual Studio 2008

Can someone help me with this issue?
I currently working on my project for final year of my honors degree. And we are developing a application to evaluate programming assignments of student ( for 1st year student level)
I just want to know how to integrate C++ compiler using C# code to compile C++ code.
In our case we are loading a student C++ code into text area, then with a click on button we want to compile the code. And if there any compilation errors it will be displayed on text area nearby. (Interface is attached herewith.)
And finally it able to execute the code if there aren't any compilation errors. And results will be displayed in console.
We were able to do this with a C#(C# code will be loaded to text area intead of C++ code) code using inbuilt compiler. But still not able to do for C# code.
Can anyone suggest a method to do this? It is possible to integrate external compiler to VS C# code? If possible how to achieve it?
Very grateful if anyone will contributing to solve this matter?
This is code for Build button which we proceed with C# code compiling
CodeDomProvider codeProvider = CodeDomProvider.CreateProvider("csharp");
string Output = "Out.exe";
Button ButtonObject = (Button)sender;
rtbresult.Text = "";
System.CodeDom.Compiler.CompilerParameters parameters = new CompilerParameters();
//Make sure we generate an EXE, not a DLL
parameters.GenerateExecutable = true;
parameters.OutputAssembly = Output;
CompilerResults results = codeProvider.CompileAssemblyFromSource(parameters, rtbcode.Text);
if (results.Errors.Count > 0)
{
rtbresult.ForeColor = Color.Red;
foreach (CompilerError CompErr in results.Errors)
{
rtbresult.Text = rtbresult.Text +
"Line number " + CompErr.Line +
", Error Number: " + CompErr.ErrorNumber +
", '" + CompErr.ErrorText + ";" +
Environment.NewLine + Environment.NewLine;
}
}
else
{
//Successful Compile
rtbresult.ForeColor = Color.Blue;
rtbresult.Text = "Success!";
//If we clicked run then launch our EXE
if (ButtonObject.Text == "Run") Process.Start(Output); // Run button
}
there is unfortunately no default implementation for CodeDom for C++, you can always define your own if you want to use the same code as the above to compile C++.
Or you can call cl.exe directly, In both cases you would have to manually invoke cl.exe
http://msdn.microsoft.com/en-us/library/19z1t1wy(v=VS.71).aspx
It shouldn't that hard. write the code to a temporary file, call cl.exe pipe any output to a window you want (or not) and the end, check if a exe has been produced, if it has compilation succeeded and you can run the exe, if not it failed and the error should be in the log you created earlier.
It's less structured than above but it's by far the easiest way.
-- more detailed
the following code assumes your environment vars are properly set. http://msdn.microsoft.com/en-us/library/f2ccy3wt(VS.80).aspx
class CL
{
private const string clexe = #"cl.exe";
private const string exe = "Test.exe", file = "test.cpp";
private string args;
public CL(String[] args)
{
this.args = String.Join(" ", args);
this.args += (args.Length > 0 ? " " : "") + "/Fe" + exe + " " + file;
}
public Boolean Compile(String content, ref string errors)
{
//remove any old copies
if (File.Exists(exe))
File.Delete(exe);
if(File.Exists(file))
File.Delete(file);
File.WriteAllText(file, content);
Process proc = new Process();
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.RedirectStandardError = true;
proc.StartInfo.FileName = clexe;
proc.StartInfo.Arguments = this.args;
proc.StartInfo.CreateNoWindow = true;
proc.Start();
//errors += proc.StandardError.ReadToEnd();
errors += proc.StandardOutput.ReadToEnd();
proc.WaitForExit();
bool success = File.Exists(exe);
return success;
}
}
this will compile the code given to it, but it's just a sample, everytime compilation succeeds there will be a file "Test.exe" which you can run. when it fails the "errors" variable will contain the error message.
hope this helps,
for more information on running processes, take a look at http://www.codeproject.com/KB/cs/ProcessStartDemo.aspx

Categories

Resources