Solved

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

Posted on 2009-04-01
7
214 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 63

Expert Comment

by:Fernando Soto
ID: 24044454
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
ID: 24044826
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
ID: 24044835
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
Space-Age Communications Transitions to DevOps

ViaSat, a global provider of satellite and wireless communications, securely connects businesses, governments, and organizations to the Internet. Learn how ViaSat’s Network Solutions Engineer, drove the transition from a traditional network support to a DevOps-centric model.

 

Author Comment

by:wally_davis
ID: 24045209
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 63

Accepted Solution

by:
Fernando Soto earned 500 total points
ID: 24046509
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
ID: 31565556
Nice catch. It's obvious I need to pay more attention of code when editing it. Your awesome, Thanks Fernando!
0
 
LVL 63

Expert Comment

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

Featured Post

How Do You Stack Up Against Your Peers?

With today’s modern enterprise so dependent on digital infrastructures, the impact of major incidents has increased dramatically. Grab the report now to gain insight into how your organization ranks against your peers and learn best-in-class strategies to resolve incidents.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

IP addresses can be stored in a database in any of several ways.  These ways may vary based on the volume of the data.  I was dealing with quite a large amount of data for user authentication purpose, and needed a way to minimize the storage.   …
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…
In an interesting question (https://www.experts-exchange.com/questions/29008360/) here at Experts Exchange, a member asked how to split a single image into multiple images. The primary usage for this is to place many photographs on a flatbed scanner…

733 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