I am looking for resources that have examples for creating a Console Application. I am past the "Hello World" stage but am stumped at the point where I need to run an application. I have the string that I need to run that I pulled from the batch file that I am trying to automate in a C# app. I need help with knowing which classes and namespaces have the functionality I need to run it.
Edit: Sorry for the poorly asked question. I'll rewrite it.
I am trying to create a console application that will replace a batch file that I have partially written. Some of the data and file manipulations that I need to do are more complex than can easily be done in a batch file. So far I am reading, writing, and manipulating the files just fine. I am having difficulty when trying figure out how to run a command to execute an application on the server with the proper arguments being passed in.
Update: a coworker gave me the following code snippit which is exactly what I needed to move forward. I am sorry the question was worded so badly.
public static string MyDOSMethod()
{
ProcessStartInfo si = new ProcessStartInfo("cmd.exe");
si.RedirectStandardInput = true;
si.RedirectStandardOutput = true;
si.UseShellExecute = false;
Process p = Process.Start(si);
p.StandardInput.WriteLine(#"cd \windows\system32");
p.StandardInput.WriteLine("exit");
try
{
return p.StandardOutput.ReadToEnd();
}
catch (Exception e)
{
return e.Message;
}
}
The question is not perfectly clear, what I understood is "I need to start an application from my console application; what class can I use?"
My answer is: you should have a look at the static method Process.Start (and in general at the class Process of namespace System.Diagnostics).
Have a look at this tutorial, it will guide you through the usage of Process.Start and ProcessStartInfo (which runs a process and gives you feedback)
I recommend this introduction to C# if your new to programming.
http://www.csharp-station.com/Tutorial.aspx
In order to compile you need a compiler and a GUI to edit code in is also nice :o) Here you can use the free version of Visual Studio:
http://www.microsoft.com/express/
In Visual Studio just click new select console application and i think you will get a "default application" like Hello World that you can run and build.
Related
I'm not sure if what I was to do is possible. I'm not a C# guru but I manage to make a living. Over the years I've written and accumulated dozens of console apps that perform otherwise tedious tasks. Everything from cleaning junk data from SQL Server databases, changing filenames in a defined directory, creating zip archives and sending emails.
Most of the apps are built on .Net Framework 4.7. What I'm wondering is if there is a way I can combine all of these apps into a single console application? I would want it to have some sort of menu of available commands as well as descriptive help section for each command and its arguments.
Can I do this? Any tutorials come to mind? Thanks!
You can right click the Solution in the Solution Explorer in VS and add a project, then in your main call them based on conditions like:
using (var process1 = new Process())
{
process1.StartInfo.FileName = #"..\..\..\ConsoleApp1.exe";
process1.Start();
}
using (var process2 = new Process())
{
process2.StartInfo.FileName = #"..\..\..\ConsoleApp2.exe";
process2.Start();
}
Console.WriteLine("We Just ran two console apps inside of a console app ;)");
Console.ReadKey();
why don't you use parallel and multi-tasking instead of run multi-app?
You can run multi-task.
For my current project, I need to compare two build versions of a program and generate a report showing which files have changed. My own idea was to run through each file using the file system, comparing dates modified. It was suggested, however, that I instead find the changelists stored in Source Depot and compare that way.
Being unfamiliar with Source Depot, I was able to find two relevant commands - "changes" and "changelist". However, the documentation is very vague about explaining how to use the SD commands, and typing something like "sd changes 1249191" results in errors like "must create client 'MGURL' to access local files". The other problem is that even if I had that aspect working, making a call with "System.Diagnostics.Process.Start" would most likely only print info to the console and not return any data to me from within C#.
I think what I really need is a library similar to the Microsoft.TeamFoundation for TFS. However, I've found little to no info online about Source Depot at all, let alone a way to interface with it through C#. Anyone have any insights? Have you done something like this before?
Check out the internal toolbox website for Source Depot utilities. There should also be a internal email alias for Source Depot questions like this...
The solution I found was two-fold, and this was partly due to my own research into the tool and partly from a colleague's suggestion.
Firstly, upon re-examining the sd command list, I found I wasn't looking at the right commands to get the info back that I wanted.
Secondly, there is no way to directly interact with source depot, but I can redirect the console's output back to me by using RedirectStandardOuput:
Process process = new Process();
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.FileName = "sd.exe";
process.StartInfo.Arguments = string.Format("describe {0}", newChangelist);
process.Start();
// read strings from process.StandardOutput here
process.WaitForExit();
From a C# MVC controller action, is it possible to execute a gulp task and if so how would I go about doing this?
In my C# app, I'm trying to check if a given string (submitted in a form) is valid sass.
There are a couple of C# CSS parsers but I can't find one that can handle sass (*.scss).
In my projects I use a gulp task that compiles sass and reports any errors so I was wondering if there was a way I could utilize this to do the validation in my C# app i.e. add the text input from my C# app to a .scss file, get the gulp task to try and compile it, if it passes without errors then I know the sass is valid.
Maybe I'm barking up the wrong tree here but any help would be much appreciated.
Ok. There's a few things here (in your question) that a scaring the absolute crap out of me but I think the easiest summary of it is this :-
Given an ASP.NET MVC Controller, how can I call -another- .exe
process?
So assuming you still want to do this, ignoring security vun's and stuff (I'll just roll with you, here...) I think you need to run a new AppDomain and then in that app domain run your exe. If the exe fails, you can then capture the error message also.
Updated as per comments
Random code taken from first'ish google result:
try
{
//Create a new appdoamin for execute my exe in a isolated way.
AppDomain sandBox = AppDomain.CreateDomain("sandBox");
try
{
//Exe executing with arguments
sandBox.ExecuteAssembly(".exe file name with path");
}
finally
{
AppDomain.Unload(sandBox);//destry created appdomain and memory is released.
}
}
catch (Exception ex)//Any exception that generate from executable can handle
{
//Logger.log(ex.Message);
}
so here, you would run the gulp.exe and pass in your command line args, include the sass content (content saved to a file?).
Now, if the .exe isn't a .NET assembly, then you might need to use the Process method...
something like this.. (pseudo code)
Process app = new Process();
app.StartInfo.FileName = #"D:/Path to /My/Program to be run.exe";
app.Start();
Again - not testing, but this should be enough to get you started...
Do note -> running a Process requires serious security permissions on the server, so generally hosted servers (like Azure Websites Site etc) lock all this down to protected themselves. If you own the server, then go nuts.
Final Note:
I've never seen or used Node.
I've never seen or used gulp.
If I try to open Notepad from a .NET console application it works fine.
I'm doing it as follows:
var p = new Process
{
StartInfo =
{
FileName = "c:\windows\system32\notepad.exe";
}
};
p.Start();
When I try to open the application I actually want to open, nothing happens. If I open that application by hand I see a Java process being created, which means it's a Java application packaged as an exe file.
Any ideas on how to open Java exe apps through .NET?
Thanks in advance
There shouldn't be much of a difference between a regular EXE and an "exified" Java application. Have you tried adjusting the working directory? Maybe there's some unzipping going on.
Lets say you had an application named "HelloWorld". Then from a command prompt (and from your code) you would launch it with:
java HelloWorld
Now this would assume that java is in your path. Which is a bad assumption. So you would be better off either having logic to populate the path to java, or to hardcode it.
I don't ever recommend hardcoding a path if you plan to pass this software around. It's never a sure thing...
Currently running this code to open Business Vision (an application written by someone else that i don't have access to the code of):
ProcessStartInfo myProcessStartInfo = new ProcessStartInfo(BusinessVisionPath);
myProcessStartInfo.UseShellExecute = false;
myProcessStartInfo.RedirectStandardOutput = true;
myProcess.StartInfo = myProcessStartInfo;
myProcess.Start();
StreamReader myStreamReader = myProcess.StandardOutput;
Boolean done = false;
while (done == false)
{
int s = myStreamReader.Read();
Console.WriteLine(s);
if (s == -1)
{
done = true;
Process IProcess = new Process();
ProcessStartInfo IProcessStartInfo = new ProcessStartInfo(QuickPrinterPath);
IProcessStartInfo.WindowStyle = ProcessWindowStyle.Maximized;
IProcess.StartInfo = IProcessStartInfo;
IProcess.Start();
}
}
myProcess.Close();
Console.ReadLine();
Anyways,
this code currently opens my printer program when BusinessVision closes.
Questions:
How (if possible) can i open my program when a certain message box pops up within BV ("Are you sure you want to print an invoice"?)
Is it possible to get any data from the application ? like raw data that i can parse through as it runs or something?
You might want to look into Microsoft's UI Automation. It allows you to read data from the windows of other applications, and interact with other applications' UI programmatically. I used this a couple years ago to automate a bunch of tests on an old VB6 app we had. My code would find the main window of the application, then drill down to the menus/controls/etc that I was interested in. From there I could automate clicks and keystrokes, and then scrape the text/data I wanted from the labels in various windows. I could then pull the data into my .NET app and do what I wanted with it.
In your case you would need some always-running app (such as a Windows service) to constantly monitor the BV program and detect when the message box appears, and then react accordingly by launching your program.
It takes a fair amount of work to understand and get working, but it's very powerful. There are free apps out there that will make it easier to browse the visual hierarchy of windows and see what kind of information is available. Check out Microsoft's UISpy:
http://msdn.microsoft.com/en-us/library/ms727247.aspx
Here are some other links to get you started:
http://en.wikipedia.org/wiki/Microsoft_UI_Automation
http://msdn.microsoft.com/en-us/library/ms747327.aspx
You can try to use one of the approved way to access data.
In the case of Sage BusinessVision there is:
Data import and export as csv availlable manualy from the application.
Direct acces to the Pervasive database, documentation availlable in the help section of the application in a file called BusinessVision Database Structure Reference.chm
API availlable to Sage partners.
1 is the most simple way and nothing is automatic.
2 is more challenging but will give you acces to the underlying data live.
3 requires that you pay and that you meet requirement by Sage.
If you combine 2. and some UI automation you could build some trigger on certain UI events and bring foward new windows filled with data from the database.
Note that UI automation will be extremly fragile to new version of the application and will certainly need to be reworked every time.
You could, although I'm not sure I'd recommend it, Enumerate top level windows, and check if one of them matches the pop-up box.
Except for files or database entries that the application creates, not that I am aware of, unless you want to get into Binary Patching of the application.
If the target is a .NET exe, perhaps the developers were sloppy and exposed their classes and methods publicly. In that case, load the exe as if it were a DLL dependency for your application and call their methods directly.
You could always try a decompiler :)
dotPeek