Please give me a working code for achieving the time synchronization using w32tm.exe in C#.net. I already tried. Code shown below.
System.Diagnostics.Process p;
string output;
p = new System.Diagnostics.Process();
p.StartInfo = procStartInfo;
p.StartInfo.FileName = "w32tm";
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.Arguments = " /resync /computer:xxxxx977";
p.Start();
p.WaitForExit();
output = p.StandardOutput.ReadLine().ToString();
MessageBox.Show(output);
But i am getting the following error
The specified module could not be found. (0x8007007E).
and my requirement also wants to redirect the standardoutput for the success message.
you can try following C# code to enable date time sync from NTP server.
by the way i guess which is /resync command number so that i wouldn't have to launch that dirty external process
/// <summary>Synchronizes the date time to ntp server using w32time service</summary>
/// <returns><c>true</c> if [command succeed]; otherwise, <c>false</c>.</returns>
public static bool SyncDateTime()
{
try
{
ServiceController serviceController = new ServiceController("w32time");
if (serviceController.Status != ServiceControllerStatus.Running)
{
serviceController.Start();
}
Logger.TraceInformation("w32time service is running");
Process processTime = new Process();
processTime.StartInfo.FileName = "w32tm";
processTime.StartInfo.Arguments = "/resync";
processTime.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
processTime.Start();
processTime.WaitForExit();
Logger.TraceInformation("w32time service has sync local dateTime from NTP server");
return true;
}
catch (Exception exception)
{
Logger.LogError("unable to sync date time from NTP server", exception);
return false;
}
}
detailled explanation :
windows have a service, called w32time, which can sync time on your computer, first i check that the service is running, using ServiceController class, then, because i don't know which is the resync command number so that i can use ServiceController launch command method, i use a ProcessStart to launch a dos command on that services : w32tm /resync
The error is occurring when the .Net runtime JITs the method you're about to step into, because it couldn't find one of the types used by the method.
What exactly does the method that you can't step into do, and what types / methods does it use?
Refer this Link
So check whether any item you tried to load is in the folder or not.
Related
I am currently working on a C# Program which needs to call a local PHP script and write its output to a file. The problem is, that I need to be able to stop the execution of the script.
First, I tried to call cmd.exe and let cmd write the output to the file which worked fine. But I found out, that killing the cmd process does not stop the php cli.
So I tried to call php directly, redirect its output and write it from the C# code to a file. But here the problem seems to be, that the php cli does not terminate when the script is done. process.WaitForExit() does not return, even when I am sure that the script has been fully executed.
I cannot set a timeout to the WaitForExit(), because depending on the arguments, the script may take 3 minutes or eg. 10 hours.
I do not want to kill just a random php cli, there may be others currently running.
What is the best way to call a local php script from C#, writing its output to a file and beeing able to stop the execution?
Here is my current code:
// Create the process
var process = new System.Diagnostics.Process();
process.EnableRaisingEvents = true;
process.StartInfo.UseShellExecute = false;
process.StartInfo.FileName = "php.exe";
// CreateExportScriptArgument returns something like "file.php arg1 arg2 ..."
process.StartInfo.Arguments = CreateExportScriptArgument(code, this.content, this.options);
process.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
process.StartInfo.RedirectStandardOutput = true;
// Start the process or cancel, if the process should not run
if (!this.isRunning) { return; }
this.currentProcess = process;
process.Start();
// Get the output
var output = process.StandardOutput;
// Wait for the process to finish
process.WaitForExit();
this.currentProcess = null;
To kill the process I am using:
// Mark as not running to prevent starting new
this.isRunning = false;
// Kill the process
if (this.currentProcess != null)
{
this.currentProcess.Kill();
}
Thanks for reading!
EDIT
That the cli does not return seems to be not reproducible. When I test a different script (without arguments) it works, probably its the script or the passing of the arguments.
Running my script from cmd works just fine, so the script should not be the problem
EDIT 2
When disabling RedirectStandardOutput, the cli quits. could it be, that I need to read the output, before the process finishes? Or does the process wait, when some kind of buffer is full?
EDIT 3: Problem solved
Thanks to VolkerK, I / we found a solution. The problem was, that WaitForExit() did not get called, when the output is not read (probably due to a full buffer in the standard output). My script wrote much output.
What works for me:
process.Start();
// Get the output
var output = process.StandardOutput;
// Read the input and write to file, live to avoid reading / writing to much at once
using (var file = new StreamWriter("path\\file", false, new UTF8Encoding()))
{
// Read each line
while (!process.HasExited)
{
file.WriteLine(output.ReadLine());
}
// Read the rest
file.Write(output.ReadToEnd());
// flush to file
file.Flush();
}
Since the problem was that the output buffer was full and therefore the php process stalled while waiting to send its output, asynchronously reading the output in the c# program is the solution.
class Program {
protected static /* yeah, yeah, it's only an example */ StringBuilder output;
static void Main(string[] args)
{
// Create the process
var process = new System.Diagnostics.Process();
process.EnableRaisingEvents = true;
process.StartInfo.UseShellExecute = false;
process.StartInfo.FileName = "php.exe";
process.StartInfo.Arguments = "-f path\\test.php mu b 0 0 pgsql://user:pass#x.x.x.x:5432/nominatim";
process.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
process.StartInfo.RedirectStandardOutput = true;
output = new StringBuilder();
process.OutputDataReceived += process_OutputDataReceived;
// Start the process
process.Start();
process.BeginOutputReadLine();
// Wait for the process to finish
process.WaitForExit();
Console.WriteLine("test");
// <-- do something with Program.output here -->
Console.ReadKey();
}
static void process_OutputDataReceived(object sender, System.Diagnostics.DataReceivedEventArgs e)
{
if (!String.IsNullOrEmpty(e.Data)) {
// edit: oops the new-line/carriage-return characters are not "in" e.Data.....
// this _might_ be a problem depending on the actual output.
output.Append(e.Data);
output.Append(Environment.NewLine);
}
}
}
see also: https://msdn.microsoft.com/en-us/library/system.diagnostics.process.beginoutputreadline%28v=vs.110%29.aspx
I came across this question, which looked like it would resolve what I'm trying to do, and I'm trying to use similar code where a Process() object is created and the "sc" command is called from code.
static void SetRecoveryOptions(string serviceName)
{
int exitCode;
using (var process = new Process())
{
var startInfo = process.StartInfo;
startInfo.FileName = "sc";
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
// tell Windows that the service should restart if it fails
startInfo.Arguments = string.Format("failure \"{0}\" reset= 0 actions= restart/60000", serviceName);
process.Start();
process.WaitForExit();
exitCode = process.ExitCode;
}
if (exitCode != 0)
throw new InvalidOperationException();
}
I've tried calling that code from a few locations (such as the committed event handler for the service installer, OnStart of the service itself, etc) but every time I get an exception as soon as the Process() object is created. The exception is: "operation is not allowed due to the current state of the object".
Any ideas what I'm missing here?
guy, I used this code snippet, I execute multiple SSIS packages, when the first one finished, it takes a so long time to execute the another one, but I run the script command line on the CMD, it execute quickly. So I think it's the problem of code, do you know why? This is my code below:
SSISHelper.ExecuteSSISPackage("/F \"C:\\Users\\v-nashi\\Documents\\visual studio 2010\\projects\\ImportExcel\\ImportExcel\\LYO_DailyLogin.dtsx\"");
SSISHelper.ExecuteSSISPackage("/F \"C:\\Users\\v-nashi\\Documents\\visual studio 2010\\projects\\ImportExcel\\ImportExcel\\LYO_COSMOS_Activities.dtsx\"");
/// <summary>
/// Excuete SQL Server Integration Services packages with parameter.
/// </summary>
/// <param name="para">parameter</param>
/// <returns>bool</returns>
public static bool ExecutePackage(string parameter)
{
if (File.Exists(DTExec_Path) == false)
throw new Exception("The file DTExec.exe is not found, or the file is not exist.");
Process process = new Process();
process.StartInfo.FileName = DTExec_Path;
process.StartInfo.Arguments = parameter;
// True if the shell should be used when starting the process; false if the process should be created directly
// from the executable file.
process.StartInfo.UseShellExecute = true;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = true;
Console.WriteLine("{0} {1}", DTExec_Path, parameter);
process.Start();
process.WaitForExit();
string[] results = process.StandardOutput.ReadToEnd().Split('\n');
foreach (string item in results)
{
if (item.Contains("DTExec: The package execution returned DTSER_SUCCESS (0)."))
return true;
}
return false;
}
I just want to run the SSIS package programmatically, or the better way?
Another way can be like this.
Microsoft.SqlServer.Dts.Runtime.Application app = new Microsoft.SqlServer.Dts.Runtime.Application();
string packagePath = "Path of your SSIS package";
Package package = app.LoadPackage(packagePath, null);
//Assign your variables here.
Variables vars = package.Variables;
vars["FileName"].Value = variables.FileName;
Microsoft.SqlServer.Dts.Runtime.DTSExecResult results = package.Execute();
if (results == DTSExecResult.Success)
{
//Do what u want after success.
}
For this U have to use this Microsoft.SqlServer.ManagedDTS library from microsoft. Try to find it in GAC or Something else site.
This is for single SSIS service in same way U can execute multiple one by one.
Does any one knows how we can find
When active directory was last backed up using C#?
according to my knowledge when we run this command
repadmin /showbackup
its will shows us full detail. I tried to get value of dsa signature using C#, but even that value does not make much sense, and will help us to get correct information of.
Like from which domain controller backup was initiated and on when?
Anyone knows how to get this last backup detail of active directory using C#?
Thanks in advance
I have found many times that not all may be done with WMI, The below code should run the requisite command to show the information you requested and then redirect it to standard out.
System.Diagnostics.ProcessStartInfo PSI =
new System.Diagnostics.ProcessStartInfo("cmd", "/c " + "Repadmin.exe /showbackup");
PSI.RedirectStandardOutput = true;
PSI.UseShellExecute = false;
PSI.CreateNoWindow = true;
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo = PSI;
proc.Start();
string result = proc.StandardOutput.ReadToEnd();
Console.WriteLine(result);
}
catch (Exception e)
{
Messagebox.Show(e.InnerException);
}
}
Let me be clear:
- I have Java.exe in my path environment variable
- So if I want to run a "selenium-server" I will do :
1. Start cmd.exe
Microsoft Windows [Version 5.2.3790]
(C) Copyright 1985-2003 Microsoft Corp.
C:\Documents and Settings\cnguyen>
2. Then:
C:\Documents and Settings\cnguyen>cd C:\Selenium RC 0.9.2\selenium-server-0.9.2
3. Next, I'm in the directory that I want so I run:
C:\Documents and Settings\cnguyen>cd C:\Selenium RC 0.9.2\selenium-server-0.9.2
C:\Selenium RC 0.9.2\selenium-server-0.9.2>java -jar selenium-server.jar
09:26:18.586 INFO - Java: Sun Microsystems Inc. 16.3-b01
09:26:18.586 INFO - OS: Windows 2003 5.2 x86
09:26:18.586 INFO - v0.9.2 [2006], with Core v0.8.3 [1879]
09:26:18.633 INFO - Version Jetty/5.1.x
09:26:18.633 INFO - Started HttpContext[/selenium-server/driver,/selenium-server
/driver]
09:26:18.633 INFO - Started HttpContext[/selenium-server,/selenium-server]
09:26:18.633 INFO - Started HttpContext[/,/]
09:26:18.648 INFO - Started SocketListener on 0.0.0.0:4444
09:26:18.648 INFO - Started org.mortbay.jetty.Server#16a55fa
And here is what I got so far, it compiled but not showing anything :(
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
namespace SeleniumProcessExample
{
public class SeleniumProcess
{
private Process pro;
public SeleniumProcess()
{
pro = new Process();
Directory.SetCurrentDirectory( #"C:\Selenium RC 0.9.2\selenium-server-0.9.2" );
pro.StartInfo.FileName = "java";
pro.StartInfo.Arguments = " -jar selenium-server.jar";
pro.StartInfo.RedirectStandardOutput = true;
pro.StartInfo.RedirectStandardError = true;
pro.StartInfo.UseShellExecute = false;
pro.Start();
string strOutput = pro.StandardOutput.ReadToEnd();
string strError = pro.StandardError.ReadToEnd();
Console.WriteLine( strOutput );
Console.WriteLine( strError );
Console.Out.Flush();
pro.CloseMainWindow();
}
}
}
EDIT: if you intent is to hide the
selenium-server output window, you're
going to have to make some
asynchronous calls. I can go into the
details if this is indeed your intent.
I would love to see this. Would you mind showing me how to do this? Thanks a lot for your suggestion ;)
This works for me...
/// <summary>
/// Creates new process to run and executable file, and return the output
/// </summary>
/// <param name="program">The name of the executable to run</param>
/// <param name="arguments">Any parameters that are required by the executable</param>
/// <param name="silent">Determines whether or not we output execution details</param>
/// <param name="workingDirectory">The directory to run the application process from</param>
/// <param name="standardErr">The standard error from the executable. String.Empty if none returned.</param>
/// <param name="standardOut">The standard output from the executable. String.Empty if none returned, or silent = true</param>
/// <returns>The application's exit code.</returns>
public static int Execute(string program, string arguments, bool silent, string workingDirectory, out string standardOut, out string standardErr)
{
standardErr = String.Empty;
standardOut = String.Empty;
//sometimes it is not advisable to output the arguments e.g. passwords etc
if (!silent)
{
Console.WriteLine(program + " " + arguments);
}
Process proc = Process.GetCurrentProcess();
if (!string.IsNullOrEmpty(workingDirectory))
{
//execute from the specific working directory if specified
proc.StartInfo.WorkingDirectory = workingDirectory;
}
proc.EnableRaisingEvents = true;
proc.StartInfo.FileName = program;
proc.StartInfo.Arguments = arguments;
proc.StartInfo.CreateNoWindow = true;
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.RedirectStandardError = true;
proc.Start();
proc.WaitForExit();
//only display the console output if not operating silently
if (!silent)
{
if (proc.StandardOutput != null)
{
standardOut = proc.StandardOutput.ReadToEnd();
Console.WriteLine(standardOut);
}
}
if (proc.StandardError != null)
{
standardErr = proc.StandardError.ReadToEnd();
Console.WriteLine(standardErr);
}
proc.StandardOutput.Close();
proc.StandardError.Close();
return proc.ExitCode;
}
Your pro.StandardOutput.ReadToEnd() call will block until the executable terminates. Since you're starting a server that will launch and wait for output, you'll never get anything.
If you just want to see the output of the server, set UseShellExecute to true and RedirectStandardOutput and RedirectStandardError to false. (or just delete those three lines) This will cause a new console window to open and show the output from selenium-server.
EDIT: if you intent is to hide the selenium-server output window, you're going to have to make some asynchronous calls. I can go into the details if this is indeed your intent.
I would start by changing the code for the process to this to see if it starts java.exe
pro = new Process();
pro.StartInfo.FileName = #"C:\Selenium RC 0.9.2\selenium-server-0.9.2\java.exe";
pro.StartInfo.Arguments = " -jar selenium-server.jar";
pro.StartInfo.RedirectStandardOutput = true;
pro.StartInfo.RedirectStandardError = true;
pro.StartInfo.UseShellExecute = false;
pro.Start();
Chances are that your program is blocking on the call to pro.StandardOutput.ReadToEnd(). Consider using the non-blocking BeginOutputReadLine() method (more at http://msdn.microsoft.com/en-us/library/system.diagnostics.process.beginoutputreadline.aspx and http://msdn.microsoft.com/en-us/library/system.diagnostics.process.standardoutput.aspx).
class LaunchJava
{
private static Process myProcessProcess;
private static StreamWriter myProcessStandardInput;
private static Thread thist = Thread.CurrentThread;
public static void DoJava()
{
// Initialize the process and its StartInfo properties.
// The sort command is a console application that
// reads and sorts text input.
myProcess= new Process();
myProcess.StartInfo.Arguments = "-jar selenium-server.jar";
myProcess.StartInfo.FileName = #"C:\Documents and Settings\cnguyen\java.exe";
// Set UseShellExecute to false for redirection.
myProcess.StartInfo.UseShellExecute = false;
// Redirect the standard output of the sort command.
// This stream is read asynchronously using an event handler.
myProcess.StartInfo.RedirectStandardOutput = true;
myProcessOutput = new StringBuilder("");
// Set our event handler to asynchronously read the sort output.
myProcess.OutputDataReceived += new DataReceivedEventHandler(myProcessOutputHandler);
// Redirect standard input as well. This stream
// is used synchronously.
myProcess.StartInfo.RedirectStandardInput = true;
Console.WriteLine("Start.");
// Start the process.
myProcess.Start();
// Use a stream writer to synchronously write the sort input.
myProcessStandardInput = myProcess.StandardInput;
// Start the asynchronous read of the sort output stream.
myProcess.BeginOutputReadLine();
// Wait for the process to end on its own.
// as an alternative issue some kind of quit command in myProcessOutputHandler
myProcess.WaitForExit();
// End the input stream to the sort command.
myProcessInput.Close();
myProcessProcess.Close();
}
private static void myProcessOutputHandler(object sendingProcess, DataReceivedEventArgs Output)
{
// do interactive work here if needed...
if (!String.IsNullOrEmpty(Output.Data))
{ myProcess.StandardInput.BaseStream.Write(bytee,0,bytee.GetLength);
}
}