How do I use command line arguments in my C# console app? - c#

I am writing a url shortener app and I would like to also create a console app with C# to push the URLs to a WCF service which I have also created.
WCF app will shorten the url on this URI;
http://example.com/shorten/http://exaple.com
so what I want is just that.
My console exe file will be sitting inside c:\dev folder and on Windows command line, I would like to do this;
c:\dev>myapp -throw http://example.com
with this method I would like to talk to that service. there is no problem on talking part. But the problem is how can I supply this -throw thing on the command line and get a response and put that response on the command line and supply a method to copy that to the clipboard. Am I asking too much here? :S I don't know.
Could you direct me somewhere that I can find information on that or could u please give me an example code of this?
Thanks.
EDIT :
I have tried the following code;
class Program {
static void Main(string[] args) {
if (args[0] == "-throw") {
System.Windows.Forms.Clipboard.SetDataObject(args[1]);
Console.WriteLine(args[1] + " has been added to clipboard !");
Console.ReadLine();
}
}
}
and I received the following error;
C:\Apps\ArgsTry\ArgsTry\bin\Debug>ArgsTry
-throw man
Unhandled Exception:
System.Threading.ThreadStateException:
Current thread must be set to single
thread apartment (STA) mode before OLE
calls can be made. Ensur e that your
Main function has STAThreadAttribute
marked on it. at
System.Windows.Forms.Clipboard.SetDataObject(Object
data, Boolean copy, In t32 retryTimes,
Int32 retryDelay) at
System.Windows.Forms.Clipboard.SetDataObject(Object
data) at
ArgsTry.Program.Main(String[] args) in
c:\apps\ArgsTry\ArgsTry\Program.cs:
line 14
C:\Apps\ArgsTry\ArgsTry\bin\Debug>

Passing arguments to a console application is easy:
using System;
public class CommandLine
{
public static void Main(string[] args)
{
for(int i = 0; i < args.Length; i++)
{
if( args[i] == "-throw" )
{
// call http client args[i+1] for URL
}
}
}
}
As for the clipboard, see:
http://msdn.microsoft.com/en-us/library/system.windows.forms.clipboard.aspx

See the args below, you can use it to read all the values passed when you run your exe file.
static void Main(string[] args) {

Related

Embedded Nancy not listening

I read a couple of related questions which had an issue with accessing nency from a remote computer. However, I am unable to access nancy from my own pc.
Here is my code:
class Program
{
static void Main(string[] args)
{
HostConfiguration hostConfigs = new HostConfiguration();
//hostConfigs.RewriteLocalhost = true;
hostConfigs.UrlReservations.CreateAutomatically = true;
using (var host = new NancyHost(hostConfigs, new Uri("http://localhost:1234")))
{
host.Start();
Console.WriteLine("Running on http://+:1234");
Console.WriteLine(host.ToString());
}
Console.ReadKey();
}
}
public class HelloModule : NancyModule
{
public HelloModule()
{
Get["/"] = parameters => Response.AsJson("Success");
Get["/nancy"] = parameters => Response.AsJson("Success");
}
}
}
I am administrator on my PC and I do not get any exception. If I type http://localhost:1234 or http://127.0.0.1:1234 to my browser (with /nancy and without) I would expect a response. However, I do net get any reponse. Further, in the list produced with netstat -ano I do not see any process listing on port 1234. I downloaded the latest version of nancy via nuget.
Do you have any idea?
The following line should work as expected:
var host = new NancyHost(hostConfigs, new Uri("http://localhost:1234"))
But what happens with a using statement, is that anything specified between ( and ) (simply put) is disposed after the closing brace (}) of the same using statement. So what is actually happening is, the host gets created, is started, and is disposed right after it printed some lines to the console.
Simply put, move the ReadKey call inside the using statement. There it will wait until a key is pressed, and the host will be disposed after that event has occurred.

How to re-start a console application if it crashes?

I have created a console application in C#. How can I program this application so that it will re-start itself after a crash?
If I understand your question correctly, you want to attempt to re-start a console app in the event of a crash. In C# console-apps the method defined as the entry point (usually static void main) is the root of the call stacks in the app. You essentially would need to call that method recursively. You will want to make sure that the app eventually fails if it is in some unintended or unrecoverable state.
For example in the main class:
static int retryCount;
const int numberOfRetries = 3;
static void Main(string[] args)
{
try
{
var theApp = new MyApplicationType(args);
theApp.StartMyAppLogic();
}
catch (ExpectedExceptionType expectThisTypeOfException)
{
thisMethodHandlesExceptions(expectThisTypeOfException);
}
catch (AnotherExpectedExceptionType alsoExpectThisTypeOfException)
{
thisMethodHandlesExceptions(alsoExpectThisTypeOfException);
}
catch (Exception unexpectedException)
{
if(retryCount < numberOfRetries)
{
retryCount++;
Main(args);
}
else
{
throw;
}
}
}
You can use a watchdog to process your monitor and restart it if crashed:
see: What's the best way to watchdog a desktop application?
You can use a windows service instead and set it's recovery options as indicated here: https://serverfault.com/questions/48600/how-can-i-automatically-restart-a-windows-service-if-it-crashes
You can use a scheduled task in task manager to start your application periodically , and set it to only start if previous run has ended:
https://support.microsoft.com/en-us/kb/323527
You could try something like this:
static void Main(string[] args)
{
try
{
// Application code goes here
}
catch (Exception)
{
var applicationPath = System.Reflection.Assembly.GetExecutingAssembly().Location;
Process.Start(applicationPath);
Environment.Exit(Environment.ExitCode);
}
}
Basically, wrap all the code in a try/catch, and if any exceptions occur, the program will retrieve the .exe location with System.Reflection.Assembly.GetExecutingAssembly().Location; and then call Process.Start to run the application again.
You should control your console app from another application (watchdog, sheduler, procmon, servman, ...).
E.g. you can create your console app as a service and control it from service manager.

C# Console application read/writes on standard IO doesn't works

Have C# Console application which read/writes on standard input and output.
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Console application");
while(true)
{
int input = Console.Read();
Console.WriteLine(input.ToString());
}
}
}
I have other native application which launch above console application and read/writes with help of pipe communication.
C# console application writes are read successfully in external application and also initial writes from external application works fine and then it loops to read from the C# console application.
After that writes from external application on the pipe doesn't work.
Absurd thing is problem is happening on some of the operating system and few it is working fine.
C# Console application compile with .NET Framework 4 / Client Profile.
Known issue from MS :
http://support.microsoft.com/en-us/kb/2675468
Please check the KB for more details along with sample provided.
Try
static void Main(string[] args)
{
Console.SetIn(new StreamReader(Console.OpenStandardInput()));
while (Console.In.Peek() != -1)
{
string input = Console.In.ReadLine();
Console.WriteLine(input);
}
}
Does it work that way?
EDIT: I have updated my answer.
Sample usage/output:
dir /B | ConsoleApplication1.exe
produces:
ConsoleApplication1.exe
ConsoleApplication1.exe.config
ConsoleApplication1.pdb
ConsoleApplication1.vshost.exe
ConsoleApplication1.vshost.exe.config
ConsoleApplication1.vshost.exe.manifest
When I try your original code, it ends up spamming -1 constantly.
You can also try:
while (true)
{
int input = Console.Read();
if (input != -1) { // -1 = no input
Console.WriteLine(input.ToString());
}
}
Now it handles every character separately.

Program won't recognize command line arguments [duplicate]

This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
How to get command line from a ClickOnce application?
I was working on a console application and manually added the string[] args inside of Main() after I had already done a bunch of other work. Is that all I have to do to accept command line arguments? Or do I need to configure something elsewhere also? I keep doing Console.WriteLine("{0}",args.Length) and get zero no matter what I send after the exe..
class Program
{
static void Main(string[] args)
{
Console.WriteLine("{0}", args.Length);
}
}
then I run ...\setup.exe yes no maybe and get 0 for length. What more do I need to do?
MORE INFO:
I tried to break after setting command line arguments in the properties page and I get the following error.:
I am thinking that someone's comment about ClickOnce deployment is my problem. How can I deploy in VS2010 to allow this?
MORE INFO:
I disabled "ClickOnce security settings" under Properties -> Security and was able to debug successfully, but when I click on Publish, it automatically turns this setting back on.. How do I prevent that?
This example:
using System;
namespace ConsoleApplication1
{
internal class Program
{
private static void Main(string[] args)
{
Console.WriteLine("Number of command line parameters = {0}", args.Length);
for (int i = 0; i < args.Length; i++)
{
Console.WriteLine("Arg[{0}] = [{1}]", i, args[i]);
}
}
}
}
When executed as ConsoleApplication1.exe a b c will output:
Number of command line parameters = 3
Arg[0] = [a]
Arg[1] = [b]
Arg[2] = [c]
See Command Line Parameters Tutorial
Update: this code
class Program
{
static void Main(string[] args)
{
Console.WriteLine("{0}", args.Length);
}
}
When executed as ConsoleApplication1.exe a b c outputs
3
Above all, make sure you're executing the correct .exe.
Perhaps you can do something like this in a for loop to check what the values if any of the command arguments are
public class CountCommandLineArgs
{
public static void Main(string[] args)
{
Console.WriteLine("Number of command line parameters = {0}",
args.Length);
foreach(string s in args)
{
Console.WriteLine(s);
}
}
}

How Might I Convert This C# Code In To Batch File Code?

I have read that Win32 will not allow remote invocation of a process that is interactive and I suspect a Console Application is considered to be interactive by Windows and so instead, if I could convert the following code in to a batch file then I am hoping I can remotely run the batch file on the server computer from a client. Feel free to correct this logic if I'm wrong.
The code is:
namespace PRIMEWebFlyControl
{
class Program
{
// name of the process we will retrieve a handle to
private const string PROCESS_NAME = "PRIMEPipeLine";
private static Process ProgramHandle;
private static string command;
static void Main(string[] args)
{
//Console.WriteLine("This program has been launched remotely!");
TextReader tr = new StreamReader("C:\\inetpub\\wwwroot\\PRIMEWeb\\Executables\\FlyCommand.txt");
command = tr.ReadLine();
tr.Close();
ExecuteCommand();
}
[DllImport("user32.dll")]
static extern bool SetForegroundWindow(IntPtr handle);
private static void ExecuteCommand() {
if (AssignProcessHandle()) {
IntPtr p = ProgramHandle.MainWindowHandle;
SetForegroundWindow(p);
SendKeys.SendWait(command + "~"); // "~" is equivalent to pressing Enter
}
}
private static bool AssignProcessHandle()
{
// ask the system for all processes that match the name we are looking for
Process[] matchingProcesses = Process.GetProcessesByName(PROCESS_NAME);
// if none are returned then we haven't found the program so return false;
if (matchingProcesses.Length == 0) return false;
// else, set our reference to the running program
ProgramHandle = matchingProcesses[0];
// return true to indicate we have assigned the ref sucessfully
return true;
}
}
}
As you will notice the code contains method calls of Windows library methods like SetForegroundWindow() and as I am unfamiliar with batch files, I wondered how the same thing might be achieved.
Many thanks
If I understand well, you are looking for a command line that will execute a bunch of commands that exist inside a text file named (C:\inetpub\wwwroot\PRIMEWeb\Executables\FlyCommand.txt)
Here is what you need to do:
cmd < C:\inetpub\wwwroot\PRIMEWeb\Executables\FlyCommand.txt
In case the path contains spaces, use the following command:
cmd < "C:\inetpub\wwwroot\PRIMEWeb\Executables\FlyCommand.txt"

Categories