Tl:dr - How can I reference CasperJS and PhantomJS from the C# project folder?
I've got working code that runs a CasperJS script from a C# project when I manually unzip the binaries for CasperJS and PhantomJS to the C: drive. (See here for a simple guide and working code below labelled WORKING Code:)
As there is no installation needed I thought it would be easy enough to move these to the C# project folder instead \tools\casperjs and \tools\phantomjs. Also, I need to update the PATH variable in code using p.StartInfo.EnvironmentVariables["PATH"] = EnvPath;
All of the combination of paths I attempt I keep getting the following error "Fatal: [Errno 2] No such file or directory; did you install phantomjs?"
All of the files have definitely been included in the file path. Am I missing something obvious?
NON WORKING Code: [filepaths \tools\casperjs, \tools\phantomjs & C:\Python34]
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Casper
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string Cpath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
//;C:\phantomjs;C:\casperjs\batchbin
FileInfo csp1 = new FileInfo(Cpath + #"\tools\casperjs\n1k0-casperjs-4f105a9\bin\casperjs");
FileInfo csp2 = new FileInfo(Cpath + #"\tools\casperjs\batchbin");
FileInfo pht = new FileInfo(Cpath + #"\tools\phantomjs");
string EnvPath = string.Format(";{0};{1}", pht, csp2);
DirectoryInfo dir = csp1.Directory;
FileInfo path = new FileInfo(#"C:\Python34\python.exe");
string arg = String.Format("casperjs TESTcasper.js");
ExecutePythonScript(dir, path, arg, EnvPath);
}
private static void ExecutePythonScript(DirectoryInfo workingDir, FileInfo pythonPath, string casperArguments, string EnvPath)
{
var p = new Process();
p.StartInfo.EnvironmentVariables["PATH"] = EnvPath;
p.StartInfo.WorkingDirectory = workingDir.FullName;
p.StartInfo.FileName = pythonPath.FullName;
p.StartInfo.Arguments = casperArguments;
p.StartInfo.UseShellExecute = false;
p.StartInfo.CreateNoWindow = true;
p.StartInfo.RedirectStandardError = true;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.RedirectStandardOutput = true;
p.ErrorDataReceived += (s, e) =>
{
if (!string.IsNullOrEmpty(e.Data))
MessageBox.Show("e> " + e.Data);
};
p.OutputDataReceived += (s, e) =>
{
if (!string.IsNullOrEmpty(e.Data))
MessageBox.Show("->" + e.Data);
};
p.Start();
p.BeginOutputReadLine();
p.BeginErrorReadLine();
p.WaitForExit();
p.Close();
}
}
}
WORKING Code: [filepaths C:\casperjs, C:\phantomjs & C:\Python34]
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Casper
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
//
FileInfo info = new FileInfo(#"C:\casperjs\n1k0-casperjs-4f105a9\bin\casperjs");
DirectoryInfo dir = info.Directory;
FileInfo path = new FileInfo(#"C:\Python34\python.exe");
string arg = #"casperjs TESTcasper.js";
ExecutePythonScript(dir, path, arg);
}
private static void ExecutePythonScript(DirectoryInfo workingDir, FileInfo pythonPath, string casperArguments)
{
var p = new Process();
p.StartInfo.WorkingDirectory = workingDir.FullName;
p.StartInfo.FileName = pythonPath.FullName;
p.StartInfo.Arguments = casperArguments;
p.StartInfo.UseShellExecute = false;
p.StartInfo.CreateNoWindow = true;
p.StartInfo.RedirectStandardError = true;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.RedirectStandardOutput = true;
p.ErrorDataReceived += (s, e) =>
{
if (!string.IsNullOrEmpty(e.Data))
MessageBox.Show("e> " + e.Data);
};
p.OutputDataReceived += (s, e) =>
{
if (!string.IsNullOrEmpty(e.Data))
MessageBox.Show("->" + e.Data);
};
p.Start();
p.BeginOutputReadLine();
p.BeginErrorReadLine();
p.WaitForExit();
p.Close();
}
}
}
TESTcasper.js
var casper = require('casper').create();
casper.start('http://casperjs.org/', function() {
this.echo(this.getTitle());
});
casper.thenOpen('http://phantomjs.org', function() {
this.echo(this.getTitle());
});
casper.run();
Got it working. Just make sure ALL required assets are properly copied over. I missed the file package.json in the filepath C:\casperjs\n1k0-casperjs-4f105a9
This now works for me
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Casper
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string Cpath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
//;C:\phantomjs;C:\casperjs\batchbin
FileInfo csp1 = new FileInfo(Cpath + #"\tools\casperjs\n1k0-casperjs-4f105a9\bin\casperjs");
FileInfo csp2 = new FileInfo(Cpath + #"\tools\casperjs\n1k0-casperjs-4f105a9\batchbin");
FileInfo pht = new FileInfo(Cpath + #"\tools\phantomjs\phantomjs-1.9.7-windows\");
string EnvPath = string.Format(";{0};{1}", pht, csp2);
DirectoryInfo dir = csp1.Directory;
FileInfo path = new FileInfo(#"C:\Python34\python.exe");
string arg = String.Format("casperjs OSTESTcasper.js");
ExecutePythonScript(dir, path, arg, EnvPath);
}
private static void ExecutePythonScript(DirectoryInfo workingDir, FileInfo pythonPath, string casperArguments, string EnvPath)
{
var p = new Process();
p.StartInfo.EnvironmentVariables["PATH"] = EnvPath;
p.StartInfo.WorkingDirectory = workingDir.FullName;
p.StartInfo.FileName = pythonPath.FullName;
p.StartInfo.Arguments = casperArguments;
p.StartInfo.UseShellExecute = false;
p.StartInfo.CreateNoWindow = true;
p.StartInfo.RedirectStandardError = true;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.RedirectStandardOutput = true;
p.ErrorDataReceived += (s, e) =>
{
if (!string.IsNullOrEmpty(e.Data))
MessageBox.Show("e> " + e.Data);
};
p.OutputDataReceived += (s, e) =>
{
if (!string.IsNullOrEmpty(e.Data))
MessageBox.Show("->" + e.Data);
};
p.Start();
p.BeginOutputReadLine();
p.BeginErrorReadLine();
p.WaitForExit();
p.Close();
}
}
}
Related
When i run this application i get an message that DeviceApplication.CAB installation was unsuccessfull .
I checked inside the windows directory and i found that wceload.exe is available.
I have placed the cab inside the directory where the present exe is running .
Any idea how to do this ??
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.IO;
namespace DeviceApplication3
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public void displayMesage() {
LaunchInstaller("DeviceApplication.cab");
}
private static bool LaunchInstaller(string cabFile)
{
// Info on WceLoad.exe
//http://msdn.microsoft.com/en-us/library/bb158700.aspx
const string installerExe = "\\windows\\wceload.exe";
const string processOptions = "";
try
{
ProcessStartInfo processInfo = new ProcessStartInfo();
processInfo.FileName = installerExe;
processInfo.Arguments = processOptions + " \"" + cabFile + "\"";
Process process = Process.Start(processInfo);
if (process != null)
{
process.WaitForExit();
}
return InstallationSuccessCheck(cabFile);
}
catch (Exception e)
{
MessageBox.Show("Sorry, for some reason this installation failed.\n" + e.Message);
Console.WriteLine(e);
throw;
}
}
private static bool InstallationSuccessCheck(string cabFile)
{
if (File.Exists(cabFile))
{
MessageBox.Show("Something in the install went wrong. Please contact support.");
return false;
}
return true;
}
}
}
Answering my own question ,
Its because of the path i gave in the process ,
ProcessStartInfo psi = new ProcessStartInfo(#"Windows\wceload.exe", "/nodelete \"Program Files\\DeviceApplication3\\DeviceApplication.CAB\"");
Process proc = Process.Start(psi);
So I created an URL protocol to run an application with the command arguments.
Here is my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using Microsoft.Win32;
using System.Diagnostics;
namespace iw4Protocol
{
class Program
{
static void Main(string[] args)
{
RegistryKey key = Registry.ClassesRoot.OpenSubKey("gameProtocol");
if (key == null)
{
string iw4FullPath = Directory.GetCurrentDirectory();
gameProtocol protocol = new gameProtocol();
protocol.RegisterProtocol(gameFullPath);
}
else
{
RegistryKey gamepathkey = Registry.ClassesRoot.OpenSubKey("gameProtocol");
string gamepath = gamepathkey.GetValue("gamepath").ToString();
Environment.SetEnvironmentVariable("path",gamepath);
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = #"test.exe";
startInfo.Arguments = Environment.CommandLine;
Process.Start(startInfo);
}
}
}
}
The problem is that the program need some files to get launched but it can't load them because the path isn't 'set'.
How I can set this path to launch all these needed files (like /cd command)?
If you want to set the PATH environment variable and use it in your process, add it to the Environment variables but you have to set UseShellExecute to false in that case:
ProcessStartInfo startInfo = new ProcessStartInfo();
// set environment
startInfo.UseShellExecute = false;
startInfo.EnvironmentVariables["PATH"] += ";" + gamepath;
// you might need more Environment vars, you're on your own here...
// start the exe
startInfo.FileName = #"test.exe";
startInfo.Arguments = Environment.CommandLine;
// added for debugging
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError = true;
var p = new Process();
p.StartInfo = startInfo;
using(var sw = new StreamWriter(File.Create("c:\\temp\\debug.txt"))) // make sure C:\temp exist
{
p.OutputDataReceived += (sender, pargs) => sw.WriteLine(pargs.Data);
p.ErrorDataReceived += (sender, pargs) => sw.WriteLine(pargs.Data);
p.Start();
p.BeginOutputReadLine();
p.BeginErrorReadLine();
p.WaitForExit();
}
I am making a C# Windows application for printing a PDF.
When I open the application, it only opens the Acrobat Reader window and no more printing. Is there anything I have missed in the function of Print()?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using Microsoft.Win32;
namespace PrintDocumentsApplication
{
public partial class PrintForm : Form
{
public PrintForm()
{
InitializeComponent();
}
private void printPdfButton_Click(object sender, EventArgs e)
{
String File = #"C:\Documents and Settings\larasasasrylo\Desktop\QRCODE_DEMO\test.pdf";
String Printer = "\\vhssadasdasoftaweafs\\HP Color LaserJet 5550 PCL 6";
Print(File, Printer);
}
public static bool Print(string file, string printer)
{
try
{
Process.Start(
Registry.LocalMachine.OpenSubKey(
#"SOFTWARE\Microsoft\Windows\CurrentVersion" +
#"\App Paths\AcroRd32.exe").GetValue("").ToString(),
string.Format("/h /t \"{0}\" \"{1}\"", file, printer));
return true;
}
catch { }
return false;
}
}
}
you try this
Process process = new Process();
process.StartInfo.FileName = pathToPdfOrDocFile;
process.UseShellExecute = true;
process.StartInfo.Verb = "printto";
process.StartInfo.Arguments = "\"" + printerName + "\"";
process.Start();
process.WaitForInputIdle();
process.Kill();
From my previous question here I was writing a program that executes A number of files through CMD.
Here is my Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Windows.Forms;
using System.Diagnostics;
namespace Convert
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
}
private void BtnSelect_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog Open = new OpenFileDialog();
Open.Filter = "RIFF/RIFX (*.Wav)|*.wav";
Open.CheckFileExists = true;
Open.Multiselect = true;
Open.ShowDialog();
LstFile.Items.Clear();
foreach (string file in Open.FileNames)
{
LstFile.Items.Add(file);
}
}
private void button1_Click(object sender, RoutedEventArgs e)
{
LstFile.Items.Clear();
}
private void BtnConvert_Click(object sender, RoutedEventArgs e)
{ Process p = new Process();
p.StartInfo.FileName = "cmd";
p.StartInfo.UseShellExecute = false;
foreach (string fn in LstFile.Items)
{
string fil = "\"";
string gn = fil + fn + fil;
p.Start();
p.StartInfo.Arguments = gn;
}
}
}
}
i used
string fil = "\"";
string gn = fil + fn + fil;
to provide quotation marks around the full file name in case the filename has spaces.
My problem is that my program Opens CMD Put does not pass any arguments in it.I checked if the filnames(list) are working and they are fine.Looking at the examples this is the way to do it,but obviously something is wrong
set
StartInfo.Arguements
BEFORE you start the process, and I'd suggest making a new process class for each process that you start.
example:
foreach (string fn in LstFile.Items)
{
string fil = "\"";
string gn = fil + fn + fil;
Process p = new Process();
p.StartInfo.FileName = "cmd";
p.StartInfo.UseShellExecute = false;
p.StartInfo.Arguments = gn;
//You can do other stuff with p.StartInfo such as redirecting the output
p.Start();
// i'd suggest adding p to a list or calling p.WaitForExit();,
//depending on your needs.
}
If you're trying to call cmd commands, make your arguements
"/c \"what i would type into the command Line\""
This is an example of what I did quick. It opens a text document in notepad
Process p = new Process();
p.StartInfo.FileName = "cmd";
p.StartInfo.UseShellExecute = false;
p.StartInfo.Arguments = "/c \"New Text Document.txt\"";
p.Start();
p.WaitForExit();
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.Security;
namespace SampleProject
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
String input = textBox1.Text;
try
{
Process ps = new Process();
ps.StartInfo.FileName = #"\\199.63.55.163\d$\hello.bat";
ps.StartInfo.Arguments = input;
ps.StartInfo.CreateNoWindow = false;
String domain = ps.StartInfo.Domain;
ps.StartInfo.RedirectStandardOutput = true;
ps.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
ps.StartInfo.WorkingDirectory = #"d:\praveen";
ps.StartInfo.UserName = "Raj";
ps.StartInfo.Domain = "domain";
ps.StartInfo.Password = Encrypt("Hello123");
ps.StartInfo.UseShellExecute = false;
ps.Start();
ps.WaitForExit();
MessageBox.Show(ps.StandardOutput.ReadToEnd());
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void label1_Click(object sender, EventArgs e)
{
}
public static SecureString Encrypt(String pwd)
{
SecureString ss = new SecureString();
for (int i = 0; i < pwd.Length; i++)
{
ss.AppendChar(pwd[i]);
}
return ss;
}
}
}
It's a shot in the dark, but I think that you can't read the processes standard output once it has exited.
Also you have to redirect it - take a look at this documentation: http://msdn.microsoft.com/en-us/library/system.diagnostics.process.standardoutput.aspx
Duplicate of .NET Process Start Process Error using credentials (The handle is invalid) ? You need to assign RedirectStandardInput, RedirectStandardOutput, RedirectStandardError