Solved

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

Posted on 2009-04-01
7
210 Views
Last Modified: 2013-12-17
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
Comment
Question by:wally_davis
  • 4
  • 3
7 Comments
 
LVL 62

Expert Comment

by:Fernando Soto
Comment Utility
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
 

Author Comment

by:wally_davis
Comment Utility
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
 

Author Comment

by:wally_davis
Comment Utility
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
Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

 

Author Comment

by:wally_davis
Comment Utility
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
 
LVL 62

Accepted Solution

by:
Fernando Soto earned 500 total points
Comment Utility
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
 

Author Closing Comment

by:wally_davis
Comment Utility
Nice catch. It's obvious I need to pay more attention of code when editing it. Your awesome, Thanks Fernando!
0
 
LVL 62

Expert Comment

by:Fernando Soto
Comment Utility
Not a problem, glad I was able to help.  ;=)
0

Featured Post

How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

Join & Write a Comment

This article describes relatively difficult and non-obvious issues that are likely to arise when creating COM class in Visual Studio and deploying it by professional MSI-authoring tools. It is assumed that the reader is already familiar with the cla…
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
It is a freely distributed piece of software for such tasks as photo retouching, image composition and image authoring. It works on many operating systems, in many languages.
Excel styles will make formatting consistent and let you apply and change formatting faster. In this tutorial, you'll learn how to use Excel's built-in styles, how to modify styles, and how to create your own. You'll also learn how to use your custo…

771 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now