• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 223
  • Last Modified:

Can one pass in a file directly as an Arg to Command line app?

I can't use a path to go to an actual file that contains data I need. My hope is that I can pass the actual file itself into the Comand Line as an argument. What I would like to do is store that file into an Array in my Console app and then process.
Is there (hopefully) a way to do this?
Thank you Experts,
Wally
0
wally_davis
Asked:
wally_davis
  • 4
  • 3
1 Solution
 
Fernando SotoRetiredCommented:
Hi wally_davis;

If you mean you want to paste the text on the command line to run the program then if the file had no " or carrage returns and line feed where it would be one continus string most likely although size might be an issue. Such a string must be surrounded by " and each carrage returns and line feed would cause the line in the command window to execute. So the answer to your question is no.

Can you not create a copy of the file on the local file system from where the program is running from?

Fernando
0
 
wally_davisAuthor Commented:
Hi Fernando,
I'm close on this one. Here's what I have thanks to someone else helping me on this.
See code below. I'm getting an error in my SP when trying to create it that reads "Msg 156, Level 15, State 1, Procedure RunPingUtil, Line 5 Incorrect syntax near the keyword 'DECLARE'.".
Much appreciated,
Wally
--------- SP ------------
USE DMS
GO
 
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
CREATE Procedure RunPingUtil
 
DECLARE @Workstations varchar(max)
SET @Workstations = 'B001617259BA7,B001E371E21B2,B001422C95811';
								      -- Passing in Wkstn values'
DECLARE @CommandLine sysname
SET @CommandLine = 'C:\Test\ProofOfConcept.exe ''' + @Workstations + '''';
 
EXEC xp_cmdshell @CommandLine;
-------------- C# Code -------------------------
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);
                }
 
            }

Open in new window

0
 
wally_davisAuthor Commented:
Sorry, actually, I've tried adding Semicolons, commas, no commas, etc. everything but to no avail. I still get the "Incorrect syntax near the keyarod 'DECLARE'" Error.
0
Get expert help—faster!

Need expert help—fast? Use the Help Bell for personalized assistance getting answers to your important questions.

 
wally_davisAuthor Commented:
Fernando, I've made some modifications to this piece of code. I'm almost home free. However, now I'm getting "Method must have a return type" Error in the last line of codes "WaitForPool();" method.

I tried entering in return in the method like this but that still didn't work:
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; // I also tried return 0 but no go
        }
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;
 
            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);
                }
 
            }
 
                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();
        }
    }

Open in new window

0
 
Fernando SotoRetiredCommented:
Hi wally_davis;

The issue you are having with the error on the call to  WaitForPool(); at the end of the code is that the program statement in inserted at class level and not a program block as a Function / Subroutine such as Main. See code snippet below.

Fernando
// The call to the method WaitForPool() is outside of function / subroutine code block and is at class level
// Program statements can not appear at class level
 
        }  // This brace closes off the Main function   
        
        /* 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();
        
    }  // This brace closes off the class 
}      // This brace closes off the namespace
 
 
// In the below code I moved the curly brace } above the comment statement above to a position
// below the method call WaitForPool() which places the call at the end of the Main function.
 
            /* 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();                                                                          
                                                                                                    
        }  // This brace closes off the Main function                                                                                              
    }      // This brace closes off the class 
}          // This brace closes off the namespace

Open in new window

0
 
wally_davisAuthor Commented:
Nice catch. It's obvious I need to pay more attention of code when editing it. Your awesome, Thanks Fernando!
0
 
Fernando SotoRetiredCommented:
Not a problem, glad I was able to help.  ;=)
0

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

  • 4
  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now