wally_davis
asked on
Pass a filename to a Console app
I want to pass in a file called "data.txt" to a console application as an argument.
Which class do you use? Environment , Process or ProcessStartInfo and could some give me an example of how to write that code to pass it in?
I want to be able to get that text passed in and then store it in an Array and add each workstation to "nodeList.Add(node)". See code below.
I would be most grateful,
Thanks,
Wally
Which class do you use? Environment , Process or ProcessStartInfo and could some give me an example of how to write that code to pass it in?
I want to be able to get that text passed in and then store it in an Array and add each workstation to "nodeList.Add(node)". See code below.
I would be most grateful,
Thanks,
Wally
List<Program> nodeList = new List<Program>();
List<string> workstations;
if (args.Length > 0)
{
// Load command line arg into List<string> collection
// assuming comma-seperated values
workstations = new List<string>(args[0].Split(new char[] { ',' }));
foreach (string wkstn in workstations)
{
Program node = new Program();
node.NodeToPing = wkstn;
nodeList.Add(node);
}
}
ASKER
No, actually, not start an Application, but, pass in a txt file that would contain say "20" workstation names. So, I want to pass in a txt file to be used within the Consol application.
You can't pass an actual file. You would need to pass the contents of the file, or a path to the file and let the app open it itself.
ASKER
Ok, lets see if I can explain this better. Instead of having the filename coded into the Console application,
I would like to run the Console application, call it "ProofOfConcept.exe". What I would like to do is have a "-f" switch (-f stands for filename) and then the name of the file to it.
So, If I want to pass in "data.txt" file, I would like the program to work like this:
ProofOfConcept -f data.txt.
Hopefully that makes more sense.
I would like to run the Console application, call it "ProofOfConcept.exe". What I would like to do is have a "-f" switch (-f stands for filename) and then the name of the file to it.
So, If I want to pass in "data.txt" file, I would like the program to work like this:
ProofOfConcept -f data.txt.
Hopefully that makes more sense.
ASKER
I've been searching Microsofts website and there are no really good examples out there unless I'm just overlooking them.
Try this:
static void Main(string[] args)
{
int idx = Array.IndexOf(args, "-f");
string filename = "";
if (idx != -1)
{
filename = args[idx + 1];
}
}
ASKER
ok, Carl, The code ran but it didn't send the three workstations to the database with ping results I was expecting. My data.txt file contains these three workstations (no commas in the text file): C001617259BA7, C001E371E21B2 and C001422C95811. Think I'm going to need a little more help sorting it out. Here's what I have for code below. Its around 200 lines and if pasted into Word/Landscape, its pretty straightforward. Thanks.
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.NetworkInformation;
using System.Data.SqlClient;
using System.Diagnostics;
namespace ProofOfConcept
{
class Program
{
// This is not used at the moment... but may be...
static void UpdateDatabase(Object database)
{
}
// The threadpool's threads call this with the argument "new "String( node.NodesToPing)"
// that is passed to QueueUserWorkItem and so, each computer is pinged quickly in the
// PingWorkstations() method when added to the threadpool.
static void PingWorkstations(Object threadContext)
{
String computer = (String)threadContext;
// PingThreadContext pc = (PingThreadContext)threadContext;
string status = "";
string epAddress = "";
SqlConnection conn = new SqlConnection(SettingsManager.ConnectionString);
SqlCommand sqlCmd = new SqlCommand("usp_PingStatus", conn);
sqlCmd.CommandType = System.Data.CommandType.StoredProcedure;
try
{
// Verify host is in DNS first
IPHostEntry IPHost = Dns.GetHostEntry(computer);
// Ping the workstation, get status and update DB
foreach (IPAddress address in IPHost.AddressList)
{
Ping p = new Ping();
try
{
// Based on the Ping Status will determine which
// case to process.
PingReply pr = p.Send(computer);
switch (pr.Status)
{
case IPStatus.Success:
sqlCmd.Parameters.AddWithValue("Status", "Reachable");
sqlCmd.Parameters.AddWithValue("Endpoint", computer);
sqlCmd.Parameters.AddWithValue("IPAddress", (address != null) ? address.ToString() :
IPAddress.None.ToString());
sqlCmd.Parameters.AddWithValue("DTStamp", DateTime.Now);
status = "Reachable";
epAddress = (address != null) ? address.ToString() : IPAddress.None.ToString();
//Console.WriteLine(computer + " - Sweet");
break;
case IPStatus.TimedOut:
sqlCmd.Parameters.AddWithValue("Status", "Timed Out");
sqlCmd.Parameters.AddWithValue("Endpoint", computer);
sqlCmd.Parameters.AddWithValue("IPAddress", (address != null) ? address.ToString() :
IPAddress.None.ToString());
sqlCmd.Parameters.AddWithValue("DTStamp", DateTime.Now);
status = "Timed Out";
epAddress = (address != null) ? address.ToString() : IPAddress.None.ToString();
//Console.WriteLine(computer + " - Timedout");
break;
case IPStatus.DestinationHostUnreachable:
sqlCmd.Parameters.AddWithValue("Status", "Host Unreachable");
sqlCmd.Parameters.AddWithValue("Endpoint", computer);
sqlCmd.Parameters.AddWithValue("IPAddress", (address != null) ? address.ToString() :
IPAddress.None.ToString());
sqlCmd.Parameters.AddWithValue("DTStamp", DateTime.Now);
status = "Host Unreachable";
epAddress = (address != null) ? address.ToString() : IPAddress.None.ToString();
//Console.WriteLine(computer + " - Timedout");
break;
case IPStatus.DestinationNetworkUnreachable:
sqlCmd.Parameters.AddWithValue("Status", "Network Unreachable");
sqlCmd.Parameters.AddWithValue("Endpoint", computer);
sqlCmd.Parameters.AddWithValue("IPAddress", (address != null) ? address.ToString() :
IPAddress.None.ToString());
sqlCmd.Parameters.AddWithValue("DTStamp", DateTime.Now);
status = "Network Unreachable";
epAddress = (address != null) ? address.ToString() : IPAddress.None.ToString();
break;
case IPStatus.Unknown:
sqlCmd.Parameters.AddWithValue("Status", "unknown");
sqlCmd.Parameters.AddWithValue("Endpoint", computer);
sqlCmd.Parameters.AddWithValue("IPAddress", "NA");
sqlCmd.Parameters.AddWithValue("DTStamp", DateTime.Now);
status = "unknown";
epAddress = "NA";
break;
}
}
catch (Exception ex)
{
Console.WriteLine("Error occurred: " + ex.Message);
}
//Open a DB connection.... SEND THE DATA CLOSE IT
try
{
// Lets add the data to the DB
conn.Open();
sqlCmd.ExecuteNonQuery();
Console.WriteLine("EP Status : {0} \nEP Name: {1} \nEP Address: {2}\n", status, computer, address );
}
catch
{
}
finally
{
conn.Close();
}
}
}
// If no DNS Record exists then update
// Endpoint information in nodes table
catch
{
sqlCmd.Parameters.AddWithValue("Status", "No DNS Record");
sqlCmd.Parameters.AddWithValue("Endpoint", computer);
sqlCmd.Parameters.AddWithValue("IPAddress", "NA");
sqlCmd.Parameters.AddWithValue("DTStamp", DateTime.Now);
status = "No DNS Record";
epAddress = "NA";
conn.Open();
sqlCmd.ExecuteNonQuery();
Console.WriteLine("EP Status : {0} \nEP Name: {1} \nEP Address: {2}\n", status, computer, epAddress);
conn.Close();
}
}
/* When availThreads = maxThreads the
* entire ThreadPool has completed being
* processed and a Sleep of 1 second before
* the next ThreadPool starts processing
*/
static void WaitForPool()
{
int maxThreads = 0;
int placeHolder = 0;
int availThreads = 0;
while (true)
{
System.Threading.ThreadPool.GetMaxThreads(out maxThreads, out placeHolder);
System.Threading.ThreadPool.GetAvailableThreads(out availThreads, out placeHolder);
if (availThreads == maxThreads) break;
System.Threading.Thread.Sleep( 1000 );
}
return ;
}
/* ----------------------------- Main () Program entry ------------------------------ */
// This is the Collection List property
// that will hold each workstation value
// that will eventually get pinged.
public string nodeToPing;
public string NodeToPing
{
get { return nodeToPing; }
set { nodeToPing = value; }
}
static void Main(string[] args)
{
// Do Database Query Here.....
// This will hold the entire workstation
// list that is pulled from the Nodes table
List<Program> nodeList = new List<Program>();
List<string> workstations;
int idx = Array.IndexOf(args, "-f");
string filename = "";
if (idx != 1)
{
filename = args[idx + 1];
}
if (args.Length > 0)
{
// Load command line arg into List<string> collection
// assuming comma-seperated values
workstations = new List<string>(filename.Split(','));
foreach (string wkstn in workstations)
{
Program node = new Program();
node.NodeToPing = wkstn;
nodeList.Add(node);
}
}
if (nodeList.Count > 0)
{
// parameters( max # of worker threads in thread
// pool and max # asynchronous IO threads in pool)
System.Threading.ThreadPool.SetMaxThreads(65, 10);
System.Threading.ThreadPool.SetMinThreads(65, 10);
/* For each computer in the computer list,
* each computer to be pinged by the PingWorkstations()
* method gets passed to the QueueUserWorkItem to be
* processed by the threadpool thread.
* Each workstation to be pinged gets added to the pool
* and processed quickly.
*/
foreach (Program node in nodeList)
{
System.Threading.ThreadPool.QueueUserWorkItem(new System.Threading.WaitCallback(PingWorkstations), node.NodeToPing );
}
}
/* This little baby is the "ShamWow" it waits till all those threads in the threadpool
* are done... and you will say "Wow" everytime.
* It's made in Germany, lol. This method processes and completes each threadpool before
* moving onto the next threadpool.
*/
WaitForPool();
}
}
}
ASKER
I retyped in the Command Prompt "ProofOfConcept.exe -f c:\data.txt and still no data was updated in DB.
Your not actually reading the file. You are passing a file name to the app but just trying to split it as if it were a comma-seperated list, like in your previous posting.
ASKER
Ok, looks like I overlooked that part. So, since I've passed the filename in, can I open it and read the data in?
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = "WINWORD.EXE";
startInfo.Arguments = f;
Process.Start(startInfo);