Search Results

Search found 97 results on 4 pages for 'processstartinfo'.

Page 4/4 | < Previous Page | 1 2 3 4 

  • Is there a buffer size attached to stdout?

    - by jameswelle
    I am trying to find some information on data limits related to stdout on Windows. I can't seem to find the information on MSDN. Is there a limit to how much data can be written to stdout? If so, what happens if the limit is reached? Is the data lost? If stdout is redirected (for example, by launching the process from .Net and using the ProcessStartInfo.RedirectStandardOutput property), does that have any effect on how much data can be written? As I read from the stdout stream in the calling process, does that affect the limitations? Are these limits related in any way to named pipes?

    Read the article

  • Running Services.msc as a different User C#

    - by Simon Mark Smith
    Hi, I have a requirement to create a simple windows forms application that allows an admin user to manage the Services on remote servers. We don't want to give the admins the usernames and passwords to the servers so these will be encrypted and stored in a database. My question is whether or not it is possible to spawn a Services.msc window when impersonating one of the users stored within the database? I have looked at the ProcessStartInfo class but because Services.msc is not an executable it does not seem to like executing this. Any ideas on a simple way of doing the actual impersonation and loading of Services.msc - say off a button click? Thanks

    Read the article

  • the problem of redirecting stdout in c#

    - by Mher
    Could you please explain why the shell redirection doesn't work with System.Diagnostics.Process class? I am trying to redirect the output streams to file with the following snippet: Process p = new Process(); p.StartInfo = new ProcessStartInfo(); p.StartInfo.FileName = "java.exe"; p.StartInfo.Arguments = @"> c:\Temp\test.log 2>&1"; p.StartInfo.UseShellExecute = true; p.Start(); The similar code works without problems with Python. Reading the output streams programmatically doesn't seem a preferable solution in my case because there will be a bunch of processes launched by my application.

    Read the article

  • StandardOutput.EndOfStream Hangs

    - by Ashton Halladay
    I'm starting a process within my C# application which runs a console application. I've redirected standard input and output, and am able to read a few lines via StandardOutput.ReadLine(). I'm convinced I have the ProcessStartInfo configured correctly. The console application, when started, outputs a few lines (ending with a "marker" line) and then waits for input. After receiving the input, it again outputs a few lines (ending again with a "marker" line), and so on. My intention is to read lines from it until I receive the "marker" line, at which point I know to send the appropriate input string. My problem is that, after several iterations, the program hangs. Pausing the debugger tends to place the hang within a call to StandardOutput.EndOfStream. This is the case in the following test code: while (!mProcess.StandardOutput.EndOfStream) // Program hangs here. { Console.WriteLine(mProcess.StandardOutput.ReadLine()); } When I'm testing for the "marker" line, I get the same kind of hang if I attempt to access StandardOutput.EndOfStream after reading the line: string line = ""; while (!isMarker(line)) { line = mProcess.StandardOutput.ReadLine(); } bool eos = mProcess.StandardOutput.EndOfStream; // Program hangs here. What might I be doing that causes this property to perform so horribly?

    Read the article

  • Process.CloseMainWindow() not working

    - by gehho
    I start the Windows On-Screen-Keyboard like that: s_onScreenKeyboard = new Process(); s_onScreenKeyboard.StartInfo = new ProcessStartInfo("osk.exe"); s_onScreenKeyboard.EnableRaisingEvents = true; s_onScreenKeyboard.Exited += new EventHandler(s_onScreenKeyboard_Exited); s_onScreenKeyboard.Start(); This works fine, but when I try to stop it using the following code, it does nothing: s_onScreenKeyboard.CloseMainWindow(); if (!s_onScreenKeyboard.HasExited) { if (!s_onScreenKeyboard.WaitForExit(1000)) { s_onScreenKeyboard.Close(); //s_onScreenKeyboard.Kill(); } } When uncommenting s_onScreenKeyboard.Kill(); it is closed, but the problem is that osk.exe obviously uses another process called "msswchx.exe" which is not closed if I simply kill the OSK process. This way, I would end up with hundreds of these processes which is not what I want. Another strange thing is that the CloseMainWindow() call worked at some time, but then it suddenly did not work anymore, and I do not remember what has changed. Any ideas? Background: I am implementing an On-Screen-Keyboard for my application because it should work with a touchscreen. It is important that the keyboard layout matches the layout which is configured in Windows since the application will be shipped to many different countries. Therefore, instead of implementing a custom keyboard control with approx. 537 keyboard layouts (exaggerating a little here...), I wanted to utilize the Windows built-in On-Screen-Keyboard which adapts to the selected keyboard layout automatically, saving a lot of work for me.

    Read the article

  • BCP task hangs while executing

    - by user350374
    Hey guys, We have a HPC node that runs some of our tasks in it. I have a task in my .net project that kicks the bcp utility on the HPC node and the output of the query that I have runs into 9 Mb. When the HPC node runs this task the output of the query is dumped into a file and then after it dumps around 5mb of data it suddenly stops dumping any more data and this happens all the time. (Please note this isnt any data issue as its not crashing on a particular row every time). this may or may not be of significance but I dump the data into a different server which has adequate permissions set. I have run the command with the same query directly on the hpc node and on other comps and it gives the right output. I'm running the bcp command as follows: var processInfo = new ProcessStartInfo("bcp.exe", argument) { RedirectStandardOutput = true, RedirectStandardError = true, CreateNoWindow = true, UseShellExecute = false }; var proc = new Process { StartInfo = processInfo, EnableRaisingEvents = true }; proc.Exited += new EventHandler(bcp_log); proc.Start(); proc.WaitForExit(); So my code actually waits for each bcp task to run before it goes ahead as I call it multiple times. FYI to remind you again it only fails when my o/p exceeds a certain no of bytes in this case approx 5mb. Any help is much appreciated.

    Read the article

  • Access problems with System.Diagnostics.Process in webservice

    - by Martin
    Hello everyone. I have problems with executing a process in a webservice method on a Windows Server 2003 machine. Here is the code: Dim target As String = "C:\dnscmd.exe" Dim fileInfo As System.IO.FileInfo = New System.IO.FileInfo(target) If Not fileInfo.Exists Then Throw New System.IO.FileNotFoundException("The requested file was not found: " + fileInfo.FullName) End If Dim startinfo As New System.Diagnostics.ProcessStartInfo("C:\dnscmd.exe") startinfo.UseShellExecute = False startinfo.Arguments = "\\MYCOMPUTER /recordadd mydomain.no " & dnsname & " CNAME myhost.mydomain.no" startinfo.UserName = "user1" Dim password As New SecureString() For Each c As Char In "secretpassword".ToCharArray() password.AppendChar(c) Next startinfo.Password = password Process.Start(startinfo) I know the process is being executed because i use processmonitor.exe on the server and it tells me that c:\dnscmd.exe is called with the right parameters Full command line value from procmon is: "C:\dnscmd.exe" \MYCOMPUTER /recordadd mydomain.no mysubdomain CNAME myhost.mydomain.no The user of the created process on the server is NT AUTHORITY\SYSTEM. BUT, the dns entry will not be added! Here is the weird thing: I KNOW the user (user1) I authenticate with has administrative rights (it's the same user I use to log on the machine with), but the user of the process in procmon says NT AUTHORITY\SYSTEM (which is not the user i use to authenticate). Weirdest: If i log on to the server, copy the command line value read from the procmon logging, and paste it in a command line window, it works! Reading procmon after this shows that user1 owns the dnscmd process. Why doesn't user1 become owner of the process started with system.diagnostics.process? Is the reason why the command doesn't work?

    Read the article

  • How to run White + SL4 UATs through TeamCity?

    - by Duncan Bayne
    After experiencing a series of unpleasant issues with TFS, including source code orruption and project management inflexibility, we (meaning the project team of which I'm a part) have decided to move from TFS 2010 to TeamCity + SVN + V1. I've managed to get our MSTest component and unit tests running as part of every build. However, our UATs are failing, and I was hoping for some advice from the TeamCity community as to best practices w.r.t. running web servers and interacting with the desktop. Each of our UAT fixtures starts a web server to host the site, like this: public static void StartWebServer() { var pathToSite = @"C:\projects\myproject\FrontEnd\MyProject.FrontEnd.Web"; var webServer = new Process { StartInfo = new ProcessStartInfo { Arguments = string.Format("/port:9150 /path:\"{0}\"", pathToSite), FileName = @"C:\Program Files (x86)\Common Files\microsoft shared\DevServer\10.0\WebDev.WebServer40.EXE" } }; webServer.Start(); } Needless to say, this doesn't work when running through TeamCity, as the pathToSite value is different each time. I'm hoping there is a way of determining the path into which the the code is checked out prior to building? That would allow me to point the web server at the right place. The other issue is that our UATs use White to drive the Silverlight UI through an instance of Internet Explorer: _browserWindow = InternetExplorer.Launch("http://localhost:9150/index.html#/Home", "Home - Windows Internet Explorer"); _document = _browserWindow.SilverlightDocument; I've ensured that the TeamCity service is granted the ability to interact with the desktop, and I've set the build agent machine up to log in automatically (an open session is a pre-requisite for White to work properly). Is that all I need to do or are there additional steps required?

    Read the article

  • Mercurial CLI is slow in C#?

    - by pATCheS
    I'm writing a utility in C# that will make managing multiple Mercurial repositories easier for the way my team is using it. However, it seems that there is always about a 300 to 400 millisecond delay before I get anything back from hg.exe. I'm using the code below to run hg.exe and hgtk.exe (TortoiseHg's GUI). The code currently includes a Stopwatch and some variables for timing purposes. The delay is roughly the same on multiple runs within the same session. I have also tried specifying the exact path of hg.exe, and got the same result. static string RunCommand(string executable, string path, string arguments) { var psi = new ProcessStartInfo() { FileName = executable, Arguments = arguments, WorkingDirectory = path, UseShellExecute = false, RedirectStandardError = true, RedirectStandardInput = true, RedirectStandardOutput = true, WindowStyle = ProcessWindowStyle.Maximized, CreateNoWindow = true }; var sbOut = new StringBuilder(); var sbErr = new StringBuilder(); var sw = new Stopwatch(); sw.Start(); var process = Process.Start(psi); TimeSpan firstRead = TimeSpan.Zero; process.OutputDataReceived += (s, e) => { if (firstRead == TimeSpan.Zero) { firstRead = sw.Elapsed; } sbOut.Append(e.Data); }; process.ErrorDataReceived += (s, e) => sbErr.Append(e.Data); process.BeginOutputReadLine(); process.BeginErrorReadLine(); var eventsStarted = sw.Elapsed; process.WaitForExit(); var processExited = sw.Elapsed; sw.Reset(); if (process.ExitCode != 0 || sbErr.Length > 0) { Error.Mercurial(process.ExitCode, sbOut.ToString(), sbErr.ToString()); } return sbOut.ToString(); } Any ideas on how I can speed things up? As it is, I'm going to have to do a lot of caching in addition to threading to keep the UI snappy.

    Read the article

  • How do I create an inheritable Semaphore in .NET?

    - by pauldoo
    I am trying to create a Win32 Semaphore object which is inheritable. This means that any child processes I launch may automatically have the right to act on the same Win32 object. My code currently looks as follows: Semaphore semaphore = new Semaphore(0, 10); Process process = Process.Start(pathToExecutable, arguments); But the semaphore object in this code cannot be used by the child process. The code I am writing is a port of come working C++. The old C++ code achieves this by the following: SECURITY_ATTRIBUTES security = {0}; security.nLength = sizeof(security); security.bInheritHandle = TRUE; HANDLE semaphore = CreateSemaphore(&security, 0, LONG_MAX, NULL); Then later when CreateProcess is called the bInheritHandles argument is set to TRUE. (In both the C# and C++ case I am using the same child process (which is C++). It takes the semaphore ID on command line, and uses the value directly in a call to ReleaseSemaphore.) I suspect I need to construct a special SemaphoreSecurity or ProcessStartInfo object, but I haven't figured it out yet.

    Read the article

  • Checking if a console application is still running using the Process class

    - by Ced
    I'm making an application that will monitor the state of another process and restart it when it stops responding, exits, or throws an error. However, I'm having trouble to make it reliably check if the process (Being a C++ Console window) has stopped responding. My code looks like this: public void monitorserver() { while (true) { server.StartInfo = new ProcessStartInfo(textbox_srcdsexe.Text, startstring); server.Start(); log("server started"); log("Monitor started."); while (server.Responding) { if (server.HasExited) { log("server exitted, Restarting."); break; } log("server is running: " + server.Responding.ToString()); Thread.Sleep(1000); } log("Server stopped responding, terminating.."); try { server.Kill(); } catch (Exception) { } } } The application I'm monitoring is Valve's Source Dedicated Server, running Garry's Mod, and I'm over stressing the physics engine to simulate it stopping responding. However, this never triggers the process class recognizing it as 'stopped responding'. I know there are ways to directly query the source server using their own protocol, but i'd like to keep it simple and universal (So that i can maybe use it for different applications in the future). Any help appreciated

    Read the article

  • Compile IL code at runtime using .NET 3.5 and C# from file

    - by nitefrog
    I would like to take a file that is an IL file, and at run time compile it back to an exe. Right now I can use process.start to fire off the command line with parameters (ilasm.exe) but I would like to automate this process from a C# service I will create. Is there a way to do this with reflection and reflection.emit? While this works: string rawText = File.ReadAllText(string.Format("c:\\temp\\{0}.il", Utility.GetAppSetting("baseName")), Encoding.ASCII); rawText = rawText.Replace("[--STRIP--]", guid); File.Delete(string.Format("c:\\temp\\{0}.il", Utility.GetAppSetting("baseName"))); File.WriteAllText(string.Format("c:\\temp\\{0}.il", Utility.GetAppSetting("baseName")),rawText, Encoding.ASCII); pi = new ProcessStartInfo(); pi.WindowStyle = ProcessWindowStyle.Hidden; pi.FileName = "\"" + ilasm + "\""; pi.Arguments = string.Format("c:\\temp\\{0}.il", Utility.GetAppSetting("baseName")); using(Process p = Process.Start(pi)) { p.WaitForExit(); } It is not ideal as I really would like this to be a streamlined process. I have seen examples of creating the IL at runtime, then saving, but I need to use the IL I already have in file form and compile it back to an exe. Thanks.

    Read the article

  • How-to diagnose and fix such "on-site" crash of dotnet application?

    - by Dmitriy Matveev
    Hello! I'm working on some application which has auto-update function. The implemented idea is simple as following: - There are some "starter" application which is installed to "Program Files/whatever/...". It's the application which is intended to be started by user. - Each time the "starter" application is executed it checks server for updates and downloads it to "%APPDATA%/some/...". And then it starts some application from that folder. Above approach is working on my development machine (running Vista) and on some other machines under XP, but under some different machine (running Windows 7) it isn't working. When "starter" executes the real application it crashes with some unknown problem (Signature = System.UnauthorizedAccess). When real application is executed manually from %APPDATA%/some/ folder then everything is working fine. I've tried to set same working directory in ProcessStartInfo, so "starter" will also execute real application in that folder, but this isn't helped me. How can I diagnose and/or fix that issue?

    Read the article

  • Cross Thread problem C#

    - by Frederik Witte
    Hello people - I got this code (lg_log is a listbox, and i want it to log the start_server.bat) Here is the code i got: public void bt_play_Click(object sender, EventArgs e) { lg_log.Items.Add("Starting Mineme server .."); string directory = Directory.GetCurrentDirectory(); var info = new ProcessStartInfo(directory + @"\start_base.bat") {UseShellExecute = false, RedirectStandardOutput = true, CreateNoWindow = true, WorkingDirectory = directory + @"\Servers\Base"}; var proc = new Process { StartInfo = info, EnableRaisingEvents = true }; proc.OutputDataReceived += (obj, args) => { if (args.Data != null) { lg_log.Items.Add(args.Data); } }; proc.Start(); proc.BeginOutputReadLine(); lg_log.Items.Add("Server is now running!"); proc.WaitForExit(); } When i run this, i'll get an error .. Anybody can help me? I'll rate the answer up! :D Edit: The error i get is this: System.InvalidOperationException Hope it helps :) The error comes at the lg_log.Items.Add(args.Data); code line

    Read the article

  • Execute files included in Resource folder

    - by Sumeet Pujari
    In WPF application where I have included some files in resources, I want to execute them on a button click. How do I specify a path in Process.Start(). private void button1_Click_2(object sender, RoutedEventArgs e) { Process.Start("test.txt"); } Or is there any other way? private void button1_Click_2(object sender, RoutedEventArgs e) { string path = System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + @"\test.txt"; if (File.Exists(path)) { Process.Start(new ProcessStartInfo(path)); } else { MessageBox.Show("No file found"+path); } I added a message box and it showed No files found. :( EDIT: I Tried to check the path after publishing and this what i got. No File Found With a Path - C:\Users\Administrator\AppData\Local\Apps\2.0... test.txt Before I published the Application I got a path which id No File Found at ..project..\bin\Debug\test.txt which is obvious since my Resource file not included there its Under a Resource Folder and not Debug when i add a test file in debug it open without any problem. Can someone Help throwing some light on this case. EDIT: I want to open a file from Resource directory @ C:\Users\Administrator\Documents\Visual Studio 2010\Projects\FastFix\FastFix\Resources Which would be included in my project when i am going to publish it is going to run as a standalone application without installation.

    Read the article

  • Kill process started with System.Diagnostic.Process.Start("FileName")

    - by PedroC88
    Hello; I am trying to create an app that will perform actions on specific times (much like the Windows Task Scheduler). I am currently using Process.Start() to lunch the file (or exe) required by the task. I am initiating a process by calling a file (an .mp3) and the process starts WMP (since it is the default application), so far so good. Now I wan't to kill that process. I know that it is normal behavior for the Process.Start(string, string) to return nothing (null in C#) in this case. So I am asking how can i close WMP when I called it through Process.Start(string, string)?? Edit: Please note that I am not opening WMP directly with Process.Start() and this is the line with which I run the process: VB: Me._procs.Add(Process.Start(Me._procInfo)) C#: this._procs.Add(Process.Start(this._procInfo)) _procInfo is a ProcessStartInfo instance. _procInfo.FileName is "C:\route\myFile.mp3". That is why WMP opens. In any case, all of the Start() methods, except for the instance-one which returns a boolean, return nothing (null in C#), because WMP is not the process that was directly created (please note that WMP is run and the song does play).

    Read the article

  • Programmatically use a server as the Build Server for multiple Project Collections

    Important: With this post you create an unsupported scenario by Microsoft. It will break your support for this server with Microsoft. So handle with care. I am the administrator an a TFS environment with a lot of Project Collections. In the supported configuration of Microsoft 2010 you need one Build Controller per Project Collection, and it is not supported to have multiple Build Controllers installed. Jim Lamb created a post how you can modify your system to change this behaviour. But since I have so many Project Collections, I automated this with the API of TFS. When you install a new build server via the UI, you do the following steps Register the build service (with this you hook the windows server into the build server environment) Add a new build controller Add a new build agent So in pseudo code, the code would look like foreach (projectCollection in GetAllProjectCollections) {       CreateNewWindowsService();       RegisterService();       AddNewController();       AddNewAgent(); } The following code fragements show you the most important parts of the method implementations. Attached is the full project. CreateNewWindowsService We create a new windows service with the SC command via the Diagnostics.Process class:             var pi = new ProcessStartInfo("sc.exe")                         {                             Arguments =                                 string.Format(                                     "create \"{0}\" start= auto binpath= \"C:\\Program Files\\Microsoft Team Foundation Server 2010\\Tools\\TfsBuildServiceHost.exe              /NamedInstance:{0}\" DisplayName= \"Visual Studio Team Foundation Build Service Host ({1})\"",                                     serviceHostName, tpcName)                         };            Process.Start(pi);             pi.Arguments = string.Format("failure {0} reset= 86400 actions= restart/60000", serviceHostName);            Process.Start(pi); RegisterService The trick in this method is that we set the NamedInstance static property. This property is Internal, so we need to set it through reflection. To get information on these you need nice Microsoft friends and the .Net reflector .             // Indicate which build service host instance we are using            typeof(BuildServiceHostUtilities).Assembly.GetType("Microsoft.TeamFoundation.Build.Config.BuildServiceHostProcess").InvokeMember("NamedInstance",              System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.SetProperty | System.Reflection.BindingFlags.Static, null, null, new object[] { serviceName });             // Create the build service host            serviceHost = buildServer.CreateBuildServiceHost(serviceName, endPoint);            serviceHost.Save();             // Register the build service host            BuildServiceHostUtilities.Register(serviceHost, user, password); AddNewController and AddNewAgent Once you have the BuildServerHost, the rest is pretty straightforward. There are methods on the BuildServerHost to modify the controllers and the agents                 controller = serviceHost.CreateBuildController(controllerName);                 agent = controller.ServiceHost.CreateBuildAgent(agentName, buildDirectory, controller);                controller.AddBuildAgent(agent); You have now seen the highlights of the application. If you need it and want to have sample information when you work in this area, download the app TFS2010_RegisterBuildServerToTPCs

    Read the article

  • Taking screenshot with Win32 API (C# pInvoke) not working in IIS

    - by Dillen Meijboom
    I want to take a screenshot of an external website. Currently my workflow is to start a Firefox instance with the specified URL and take a screenshot using PrintWindow in the Win32 API When I run this application in IISExpress it works fine but when I run the same application in IIS on a windows VPS it is not working (screenshot is blank). I don't know what I'm doing wrong? My code: using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Diagnostics; using System.Drawing; using System.Drawing.Imaging; using System.Linq; using System.Runtime.InteropServices; using System.Security; using System.Threading; using System.Web; namespace WebTools.Web { public class RemoteScreenshot { public static Bitmap TakeScreenshot(Process process) { // may need a process Refresh before return TakeScreenshot(process.MainWindowHandle); } public static Bitmap TakeScreenshot(IntPtr handle) { RECT rc = new RECT(); GetWindowRect(handle, ref rc); Bitmap bitmap = new Bitmap(rc.right - rc.left, rc.bottom - rc.top); using (Graphics graphics = Graphics.FromImage(bitmap)) { PrintWindow(handle, graphics.GetHdc(), 0); } return bitmap; } [DllImport("user32.dll")] private static extern bool GetWindowRect(IntPtr hWnd, ref RECT rect); [DllImport("user32.dll")] private static extern bool PrintWindow(IntPtr hWnd, IntPtr hDC, int flags); [StructLayout(LayoutKind.Sequential)] private struct RECT { public int left; public int top; public int right; public int bottom; } public static void Save(string url, string file, int timeout = 0) { Process.Start(new ProcessStartInfo("C:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe", url) { CreateNoWindow = false, WindowStyle = ProcessWindowStyle.Maximized }); Thread.Sleep(timeout); var bitmap = TakeScreenshot(Process.GetProcessesByName("firefox").First()); bitmap.Save(file, ImageFormat.Png); bitmap.Dispose(); Process.GetProcessesByName("firefox").First().Kill(); } } } EDIT: Running Firefox works fine because the AppPool is under another account that has the rights to execute firefox.

    Read the article

  • What common routines do you put in your Program.cs for C#

    - by Rick
    I'm interested in any common routine/procedures/methods that you might use in you Program.cs when creating a .NET project. For instance I commonly use the following code in my desktop applications to allow easy upgrades, single instance execution and friendly and simple reporting of uncaught system application errors. using System; using System.Diagnostics; using System.Threading; using System.Windows.Forms; namespace NameoftheAssembly { internal static class Program { /// <summary> /// The main entry point for the application. Modified to check for another running instance on the same computer and to catch and report any errors not explicitly checked for. /// </summary> [STAThread] private static void Main() { //for upgrading and installing newer versions string[] arguments = Environment.GetCommandLineArgs(); if (arguments.GetUpperBound(0) > 0) { foreach (string argument in arguments) { if (argument.Split('=')[0].ToLower().Equals("/u")) { string guid = argument.Split('=')[1]; string path = Environment.GetFolderPath(Environment.SpecialFolder.System); var si = new ProcessStartInfo(path + "\\msiexec.exe", "/x" + guid); Process.Start(si); Application.Exit(); } } //end of upgrade } else { bool onlyInstance = false; var mutex = new Mutex(true, Application.ProductName, out onlyInstance); if (!onlyInstance) { MessageBox.Show("Another copy of this running"); return; } AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; Application.ThreadException += ApplicationThreadException; Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } } private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) { try { var ex = (Exception) e.ExceptionObject; MessageBox.Show("Whoops! Please contact the developers with the following" + " information:\n\n" + ex.Message + ex.StackTrace, " Fatal Error", MessageBoxButtons.OK, MessageBoxIcon.Stop); } catch (Exception) { //do nothing - Another Exception! Wow not a good thing. } finally { Application.Exit(); } } public static void ApplicationThreadException(object sender, ThreadExceptionEventArgs e) { try { MessageBox.Show("Whoops! Please contact the developers with the following" + " information:\n\n" + e.Exception.Message + e.Exception.StackTrace, " Error", MessageBoxButtons.OK, MessageBoxIcon.Stop); } catch (Exception) { //do nothing - Another Exception! Wow not a good thing. } } } } I find these routines to be very helpful. What methods have you found helpful in Program.cs?

    Read the article

  • Unable to launch onscreen keyboard (osk.exe) from a 32-bit process on Win7 x64

    - by Steven Robbins
    90% of the time I am unable to launch osk.exe from a 32bit process on Win7 x64. Originally the code was just using: Process.Launch("osk.exe"); Which won't work on x64 because of the directory virtualization. Not a problem I thought, I'll just disable virtualization, launch the app, and enable it again, which I thought was the correct way to do things. I also added some code to bring the keyboard back up if it has been minimized (which works fine) - the code (in a sample WPF app) now looks as follows: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation;using System.Diagnostics; using System.Runtime.InteropServices; namespace KeyboardTest { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { [DllImport("kernel32.dll", SetLastError = true)] private static extern bool Wow64DisableWow64FsRedirection(ref IntPtr ptr); [DllImport("kernel32.dll", SetLastError = true)] public static extern bool Wow64RevertWow64FsRedirection(IntPtr ptr); private const UInt32 WM_SYSCOMMAND = 0x112; private const UInt32 SC_RESTORE = 0xf120; [DllImport("user32.dll", CharSet = CharSet.Auto)] static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, IntPtr lParam); private string OnScreenKeyboadApplication = "osk.exe"; public MainWindow() { InitializeComponent(); } private void KeyboardButton_Click(object sender, RoutedEventArgs e) { // Get the name of the On screen keyboard string processName = System.IO.Path.GetFileNameWithoutExtension(OnScreenKeyboadApplication); // Check whether the application is not running var query = from process in Process.GetProcesses() where process.ProcessName == processName select process; var keyboardProcess = query.FirstOrDefault(); // launch it if it doesn't exist if (keyboardProcess == null) { IntPtr ptr = new IntPtr(); ; bool sucessfullyDisabledWow64Redirect = false; // Disable x64 directory virtualization if we're on x64, // otherwise keyboard launch will fail. if (System.Environment.Is64BitOperatingSystem) { sucessfullyDisabledWow64Redirect = Wow64DisableWow64FsRedirection(ref ptr); } // osk.exe is in windows/system folder. So we can directky call it without path using (Process osk = new Process()) { osk.StartInfo.FileName = OnScreenKeyboadApplication; osk.Start(); osk.WaitForInputIdle(2000); } // Re-enable directory virtualisation if it was disabled. if (System.Environment.Is64BitOperatingSystem) if (sucessfullyDisabledWow64Redirect) Wow64RevertWow64FsRedirection(ptr); } else { // Bring keyboard to the front if it's already running var windowHandle = keyboardProcess.MainWindowHandle; SendMessage(windowHandle, WM_SYSCOMMAND, new IntPtr(SC_RESTORE), new IntPtr(0)); } } } } But this code, most of the time, throws the following exception on osk.Start(): The specified procedure could not be found at System.Diagnostics.Process.StartWithShellExecuteEx(ProcessStartInfo startInfo) I've tried putting long Thread.Sleep commands in around the osk.Start line, just to make sure it wasn't a race condition, but the same problem persists. Can anyone spot where I'm doing something wrong, or provide an alternative solution for this? It seems to work fine launching Notepad, it just won't play ball with the onscreen keyboard.

    Read the article

  • Node.js Adventure - Host Node.js on Windows Azure Worker Role

    - by Shaun
    In my previous post I demonstrated about how to develop and deploy a Node.js application on Windows Azure Web Site (a.k.a. WAWS). WAWS is a new feature in Windows Azure platform. Since it’s low-cost, and it provides IIS and IISNode components so that we can host our Node.js application though Git, FTP and WebMatrix without any configuration and component installation. But sometimes we need to use the Windows Azure Cloud Service (a.k.a. WACS) and host our Node.js on worker role. Below are some benefits of using worker role. - WAWS leverages IIS and IISNode to host Node.js application, which runs in x86 WOW mode. It reduces the performance comparing with x64 in some cases. - WACS worker role does not need IIS, hence there’s no restriction of IIS, such as 8000 concurrent requests limitation. - WACS provides more flexibility and controls to the developers. For example, we can RDP to the virtual machines of our worker role instances. - WACS provides the service configuration features which can be changed when the role is running. - WACS provides more scaling capability than WAWS. In WAWS we can have at most 3 reserved instances per web site while in WACS we can have up to 20 instances in a subscription. - Since when using WACS worker role we starts the node by ourselves in a process, we can control the input, output and error stream. We can also control the version of Node.js.   Run Node.js in Worker Role Node.js can be started by just having its execution file. This means in Windows Azure, we can have a worker role with the “node.exe” and the Node.js source files, then start it in Run method of the worker role entry class. Let’s create a new windows azure project in Visual Studio and add a new worker role. Since we need our worker role execute the “node.exe” with our application code we need to add the “node.exe” into our project. Right click on the worker role project and add an existing item. By default the Node.js will be installed in the “Program Files\nodejs” folder so we can navigate there and add the “node.exe”. Then we need to create the entry code of Node.js. In WAWS the entry file must be named “server.js”, which is because it’s hosted by IIS and IISNode and IISNode only accept “server.js”. But here as we control everything we can choose any files as the entry code. For example, I created a new JavaScript file named “index.js” in project root. Since we created a C# Windows Azure project we cannot create a JavaScript file from the context menu “Add new item”. We have to create a text file, and then rename it to JavaScript extension. After we added these two files we should set their “Copy to Output Directory” property to “Copy Always”, or “Copy if Newer”. Otherwise they will not be involved in the package when deployed. Let’s paste a very simple Node.js code in the “index.js” as below. As you can see I created a web server listening at port 12345. 1: var http = require("http"); 2: var port = 12345; 3:  4: http.createServer(function (req, res) { 5: res.writeHead(200, { "Content-Type": "text/plain" }); 6: res.end("Hello World\n"); 7: }).listen(port); 8:  9: console.log("Server running at port %d", port); Then we need to start “node.exe” with this file when our worker role was started. This can be done in its Run method. I found the Node.js and entry JavaScript file name, and then create a new process to run it. Our worker role will wait for the process to be exited. If everything is OK once our web server was opened the process will be there listening for incoming requests, and should not be terminated. The code in worker role would be like this. 1: public override void Run() 2: { 3: // This is a sample worker implementation. Replace with your logic. 4: Trace.WriteLine("NodejsHost entry point called", "Information"); 5:  6: // retrieve the node.exe and entry node.js source code file name. 7: var node = Environment.ExpandEnvironmentVariables(@"%RoleRoot%\approot\node.exe"); 8: var js = "index.js"; 9:  10: // prepare the process starting of node.exe 11: var info = new ProcessStartInfo(node, js) 12: { 13: CreateNoWindow = false, 14: ErrorDialog = true, 15: WindowStyle = ProcessWindowStyle.Normal, 16: UseShellExecute = false, 17: WorkingDirectory = Environment.ExpandEnvironmentVariables(@"%RoleRoot%\approot") 18: }; 19: Trace.WriteLine(string.Format("{0} {1}", node, js), "Information"); 20:  21: // start the node.exe with entry code and wait for exit 22: var process = Process.Start(info); 23: process.WaitForExit(); 24: } Then we can run it locally. In the computer emulator UI the worker role started and it executed the Node.js, then Node.js windows appeared. Open the browser to verify the website hosted by our worker role. Next let’s deploy it to azure. But we need some additional steps. First, we need to create an input endpoint. By default there’s no endpoint defined in a worker role. So we will open the role property window in Visual Studio, create a new input TCP endpoint to the port we want our website to use. In this case I will use 80. Even though we created a web server we should add a TCP endpoint of the worker role, since Node.js always listen on TCP instead of HTTP. And then changed the “index.js”, let our web server listen on 80. 1: var http = require("http"); 2: var port = 80; 3:  4: http.createServer(function (req, res) { 5: res.writeHead(200, { "Content-Type": "text/plain" }); 6: res.end("Hello World\n"); 7: }).listen(port); 8:  9: console.log("Server running at port %d", port); Then publish it to Windows Azure. And then in browser we can see our Node.js website was running on WACS worker role. We may encounter an error if we tried to run our Node.js website on 80 port at local emulator. This is because the compute emulator registered 80 and map the 80 endpoint to 81. But our Node.js cannot detect this operation. So when it tried to listen on 80 it will failed since 80 have been used.   Use NPM Modules When we are using WAWS to host Node.js, we can simply install modules we need, and then just publish or upload all files to WAWS. But if we are using WACS worker role, we have to do some extra steps to make the modules work. Assuming that we plan to use “express” in our application. Firstly of all we should download and install this module through NPM command. But after the install finished, they are just in the disk but not included in the worker role project. If we deploy the worker role right now the module will not be packaged and uploaded to azure. Hence we need to add them to the project. On solution explorer window click the “Show all files” button, select the “node_modules” folder and in the context menu select “Include In Project”. But that not enough. We also need to make all files in this module to “Copy always” or “Copy if newer”, so that they can be uploaded to azure with the “node.exe” and “index.js”. This is painful step since there might be many files in a module. So I created a small tool which can update a C# project file, make its all items as “Copy always”. The code is very simple. 1: static void Main(string[] args) 2: { 3: if (args.Length < 1) 4: { 5: Console.WriteLine("Usage: copyallalways [project file]"); 6: return; 7: } 8:  9: var proj = args[0]; 10: File.Copy(proj, string.Format("{0}.bak", proj)); 11:  12: var xml = new XmlDocument(); 13: xml.Load(proj); 14: var nsManager = new XmlNamespaceManager(xml.NameTable); 15: nsManager.AddNamespace("pf", "http://schemas.microsoft.com/developer/msbuild/2003"); 16:  17: // add the output setting to copy always 18: var contentNodes = xml.SelectNodes("//pf:Project/pf:ItemGroup/pf:Content", nsManager); 19: UpdateNodes(contentNodes, xml, nsManager); 20: var noneNodes = xml.SelectNodes("//pf:Project/pf:ItemGroup/pf:None", nsManager); 21: UpdateNodes(noneNodes, xml, nsManager); 22: xml.Save(proj); 23:  24: // remove the namespace attributes 25: var content = xml.InnerXml.Replace("<CopyToOutputDirectory xmlns=\"\">", "<CopyToOutputDirectory>"); 26: xml.LoadXml(content); 27: xml.Save(proj); 28: } 29:  30: static void UpdateNodes(XmlNodeList nodes, XmlDocument xml, XmlNamespaceManager nsManager) 31: { 32: foreach (XmlNode node in nodes) 33: { 34: var copyToOutputDirectoryNode = node.SelectSingleNode("pf:CopyToOutputDirectory", nsManager); 35: if (copyToOutputDirectoryNode == null) 36: { 37: var n = xml.CreateNode(XmlNodeType.Element, "CopyToOutputDirectory", null); 38: n.InnerText = "Always"; 39: node.AppendChild(n); 40: } 41: else 42: { 43: if (string.Compare(copyToOutputDirectoryNode.InnerText, "Always", true) != 0) 44: { 45: copyToOutputDirectoryNode.InnerText = "Always"; 46: } 47: } 48: } 49: } Please be careful when use this tool. I created only for demo so do not use it directly in a production environment. Unload the worker role project, execute this tool with the worker role project file name as the command line argument, it will set all items as “Copy always”. Then reload this worker role project. Now let’s change the “index.js” to use express. 1: var express = require("express"); 2: var app = express(); 3:  4: var port = 80; 5:  6: app.configure(function () { 7: }); 8:  9: app.get("/", function (req, res) { 10: res.send("Hello Node.js!"); 11: }); 12:  13: app.get("/User/:id", function (req, res) { 14: var id = req.params.id; 15: res.json({ 16: "id": id, 17: "name": "user " + id, 18: "company": "IGT" 19: }); 20: }); 21:  22: app.listen(port); Finally let’s publish it and have a look in browser.   Use Windows Azure SQL Database We can use Windows Azure SQL Database (a.k.a. WACD) from Node.js as well on worker role hosting. Since we can control the version of Node.js, here we can use x64 version of “node-sqlserver” now. This is better than if we host Node.js on WAWS since it only support x86. Just install the “node-sqlserver” module from NPM, copy the “sqlserver.node” from “Build\Release” folder to “Lib” folder. Include them in worker role project and run my tool to make them to “Copy always”. Finally update the “index.js” to use WASD. 1: var express = require("express"); 2: var sql = require("node-sqlserver"); 3:  4: var connectionString = "Driver={SQL Server Native Client 10.0};Server=tcp:{SERVER NAME}.database.windows.net,1433;Database={DATABASE NAME};Uid={LOGIN}@{SERVER NAME};Pwd={PASSWORD};Encrypt=yes;Connection Timeout=30;"; 5: var port = 80; 6:  7: var app = express(); 8:  9: app.configure(function () { 10: app.use(express.bodyParser()); 11: }); 12:  13: app.get("/", function (req, res) { 14: sql.open(connectionString, function (err, conn) { 15: if (err) { 16: console.log(err); 17: res.send(500, "Cannot open connection."); 18: } 19: else { 20: conn.queryRaw("SELECT * FROM [Resource]", function (err, results) { 21: if (err) { 22: console.log(err); 23: res.send(500, "Cannot retrieve records."); 24: } 25: else { 26: res.json(results); 27: } 28: }); 29: } 30: }); 31: }); 32:  33: app.get("/text/:key/:culture", function (req, res) { 34: sql.open(connectionString, function (err, conn) { 35: if (err) { 36: console.log(err); 37: res.send(500, "Cannot open connection."); 38: } 39: else { 40: var key = req.params.key; 41: var culture = req.params.culture; 42: var command = "SELECT * FROM [Resource] WHERE [Key] = '" + key + "' AND [Culture] = '" + culture + "'"; 43: conn.queryRaw(command, function (err, results) { 44: if (err) { 45: console.log(err); 46: res.send(500, "Cannot retrieve records."); 47: } 48: else { 49: res.json(results); 50: } 51: }); 52: } 53: }); 54: }); 55:  56: app.get("/sproc/:key/:culture", function (req, res) { 57: sql.open(connectionString, function (err, conn) { 58: if (err) { 59: console.log(err); 60: res.send(500, "Cannot open connection."); 61: } 62: else { 63: var key = req.params.key; 64: var culture = req.params.culture; 65: var command = "EXEC GetItem '" + key + "', '" + culture + "'"; 66: conn.queryRaw(command, function (err, results) { 67: if (err) { 68: console.log(err); 69: res.send(500, "Cannot retrieve records."); 70: } 71: else { 72: res.json(results); 73: } 74: }); 75: } 76: }); 77: }); 78:  79: app.post("/new", function (req, res) { 80: var key = req.body.key; 81: var culture = req.body.culture; 82: var val = req.body.val; 83:  84: sql.open(connectionString, function (err, conn) { 85: if (err) { 86: console.log(err); 87: res.send(500, "Cannot open connection."); 88: } 89: else { 90: var command = "INSERT INTO [Resource] VALUES ('" + key + "', '" + culture + "', N'" + val + "')"; 91: conn.queryRaw(command, function (err, results) { 92: if (err) { 93: console.log(err); 94: res.send(500, "Cannot retrieve records."); 95: } 96: else { 97: res.send(200, "Inserted Successful"); 98: } 99: }); 100: } 101: }); 102: }); 103:  104: app.listen(port); Publish to azure and now we can see our Node.js is working with WASD through x64 version “node-sqlserver”.   Summary In this post I demonstrated how to host our Node.js in Windows Azure Cloud Service worker role. By using worker role we can control the version of Node.js, as well as the entry code. And it’s possible to do some pre jobs before the Node.js application started. It also removed the IIS and IISNode limitation. I personally recommended to use worker role as our Node.js hosting. But there are some problem if you use the approach I mentioned here. The first one is, we need to set all JavaScript files and module files as “Copy always” or “Copy if newer” manually. The second one is, in this way we cannot retrieve the cloud service configuration information. For example, we defined the endpoint in worker role property but we also specified the listening port in Node.js hardcoded. It should be changed that our Node.js can retrieve the endpoint. But I can tell you it won’t be working here. In the next post I will describe another way to execute the “node.exe” and Node.js application, so that we can get the cloud service configuration in Node.js. I will also demonstrate how to use Windows Azure Storage from Node.js by using the Windows Azure Node.js SDK.   Hope this helps, Shaun All documents and related graphics, codes are provided "AS IS" without warranty of any kind. Copyright © Shaun Ziyan Xu. This work is licensed under the Creative Commons License.

    Read the article

  • Memory limit for running external executables within Asp.net

    - by itsbalur
    I am using WkhtmltoPdf in my C# web application running in .NET 4.0 to generate PDFs from HTML files. In general everything works fine except when the size of the HTML file is below 250KB. Once the HTML file size increases beyond that, the process which runs the wkhtmltopdf.exe gives an exception as below. On the Task Manager, I have seen that the Memory value for the wkhtmltopdf.exe process does not increase beyond a value of 40,096 K, which I believe is the reason why the process is abandoned in between. How can we configure such that the memory limit for external exes can be increased? Is there any other way of solving this issue? More info: When I run the conversion from the command line directly, the PDF is generated fine. So, its unlikely to be a problem with WkhtmlToPdf. The error is from localhost. I have tried the same on the DEV server, with the same result. Exception: > [Exception: Loading pages (1/6) [> > ] 0% [======> ] > 10% [======> ] 11% > [=======> ] 13% > [=========> ] 15% > [==========> ] 18% > [============> ] 20% > [=============> ] 22% > [==============> ] 24% > [===============> ] 26% > [=================> ] 29% > [==================> ] 31% > [===================> ] 33% > [=====================> ] 35% > [======================> ] 37% > [========================> ] 40% > [=========================> ] 42% > [==========================> ] 44% > [============================> ] 47% > [=============================> ] 49% > [==============================> ] 51% > [============================================================] 100% > Counting pages (2/6) > [============================================================] Object > 1 of 1 Resolving links (4/6) > [============================================================] Object > 1 of 1 Loading headers and footers (5/6) > Printing pages (6/6) [> > ] Preparing [=> > ] Page 1 of 49 [==> > ] Page 2 of 49 [===> > ] Page 3 of 49 [====> > ] Page 4 of 49 [======> > ] Page 5 of 49 [=======> > ] Page 6 of 49 [========> > ] Page 7 of 49 [=========> > ] Page 8 of 49 [==========> > ] Page 9 of 49 [============> > ] Page 10 of 49 [=============> > ] Page 11 of 49 [==============> > ] Page 12 of 49 [===============> > ] Page 13 of 49 [================> > ] Page 14 of 49 [==================> > ] Page 15 of 49 [===================> > ] Page 16 of 49 [====================> > ] Page 17 of 49 [=====================> > ] Page 18 of 49 [======================> > ] Page 19 of 49 [========================> > ] Page 20 of 49 [=========================> > ] Page 21 of 49 [==========================> > ] Page 22 of 49 [===========================> > ] Page 23 of 49 [============================> > ] Page 24 of 49 [==============================> > ] Page 25 of 49 [===============================> > ] Page 26 of 49 [=================================> > ] Page 27 of 49 [==================================> > ] Code that I use: var fileName = " - "; var wkhtmlDir = ConfigurationManager.AppSettings[Constants.AppSettings.ExportToPdfExecutablePath]; var wkhtml = ConfigurationManager.AppSettings[Constants.AppSettings.ExportToPdfExecutablePath] + "\\wkhtmltopdf.exe"; var p = new Process(); string switches = ""; switches += "--print-media-type "; switches += "--margin-top 10mm --margin-bottom 10mm --margin-right 5mm --margin-left 5mm "; switches += "--page-size A4 "; switches += "--disable-smart-shrinking "; var startInfo = new ProcessStartInfo { CreateNoWindow = true, FileName = wkhtml, Arguments = switches + " " + url + " " + fileName, UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardError = true, RedirectStandardInput=true, WorkingDirectory=wkhtmlDir }; p.StartInfo = startInfo; p.Start();

    Read the article

< Previous Page | 1 2 3 4