Example #1
0
        public void Start(string[] args)
        {
            string userInput = null;
            Arguments arguments = new Arguments(string.Join(" ", args));

            if (arguments.Exists("server"))
            {
                // Override default settings with user provided input. 
                m_clientHelper.PersistSettings = false;
                m_remotingClient.PersistSettings = false;
                if (arguments.Exists("server"))
                    m_remotingClient.ConnectionString = string.Format("Server={0}", arguments["server"]);
            }

            // Connect to service and send commands. 
            m_clientHelper.Connect();
            while (m_clientHelper.Enabled &&
                   string.Compare(userInput, "Exit", true) != 0)
            {
                // Wait for a command from the user. 
                userInput = Console.ReadLine();
                // Write a blank line to the console.
                Console.WriteLine();

                if (!string.IsNullOrEmpty(userInput))
                {
                    // The user typed in a command and didn't just hit <ENTER>. 
                    switch (userInput.ToUpper())
                    {
                        case "CLS":
                            // User wants to clear the console window. 
                            Console.Clear();
                            break;
                        case "EXIT":
                            // User wants to exit the telnet session with the service. 
                            if (m_telnetActive)
                            {
                                userInput = string.Empty;
                                m_clientHelper.SendRequest("Telnet -disconnect");
                            }
                            break;
                        default:
                            // User wants to send a request to the service. 
                            m_clientHelper.SendRequest(userInput);
                            if (string.Compare(userInput, "Help", true) == 0)
                                DisplayHelp();

                            break;
                    }
                }
            }
        }
        static int Main(string[] arguments)
        {
            Arguments splitArguments=null;
            try
            {
                 splitArguments = new Arguments(arguments);
                ExceptionFunctions.ForceVerbose = splitArguments.Exists(Arguments.DefaultArgumentPrefix + "verbose");
                string operation = splitArguments.String(Arguments.OperationArgument, true);

                AdapterFunctions.RunOperation(operation, splitArguments);
                return 0;
            } catch (Exception error)
            {
                string message = string.Empty
                    + Arguments.ErrorArgument + " " + ExceptionFunctions.Write(error, !ExceptionFunctions.ForceVerbose) + Environment.NewLine
                    + "Arguments: " + string.Join(" ", arguments) + Environment.NewLine;
                //if (ExceptionFunctions.ForceVerbose)
                //{
                //    message += ProcessFunctions.WriteProcessHeritage() + Environment.NewLine;
                //    message += ProcessFunctions.WriteSystemVariables() + Environment.NewLine;
                //}
                Console.Write(message);
                if (ExceptionFunctions.ForceVerbose)
                {
                    SwishFunctions.MessageTextBox(message, false);
                }
                return -1;
            }
        }
        static int Main(string[] arguments)
        {
            try
            {
                Arguments splitArguments = new Arguments(arguments);
                ExceptionFunctions.ForceVerbose = splitArguments.Exists(Arguments.DefaultArgumentPrefix + "verbose");
                string inputFileName = FileFunctions.AdjustFileName(splitArguments.String(Arguments.InputArgument, true));
                string variable = splitArguments.String(Arguments.DefaultArgumentPrefix + "variable", true);
                string operation = splitArguments.String(Arguments.DefaultArgumentPrefix + "operation", false);

                if (string.IsNullOrWhiteSpace(operation))
                {
                    operation = "mean";
                }

                CollapseOpperation operationCode = (CollapseOpperation)Enum.Parse(typeof(CollapseOpperation), operation, true);

                double result = AdapterFunctions.Collapse(inputFileName, variable, operationCode);

                Console.Write(result.ToString());
                return 0;
            } catch (Exception error)
            {
                string message = Arguments.ErrorArgument + " " + ExceptionFunctions.Write(error, !ExceptionFunctions.ForceVerbose);
                //if (ExceptionFunctions.ForceVerbose)
                //{
                //    message += ProcessFunctions.WriteProcessHeritage();
                //    message += ProcessFunctions.WriteSystemVariables();
                //}
                Console.Write(message);
                if (ExceptionFunctions.ForceVerbose)
                {
                    SwishFunctions.MessageTextBox(message, false);
                }
                return -1;
            }
        }
Example #4
0
        /// <summary>
        /// Handles service start event.
        /// </summary>
        /// <param name="args">Service start arguments.</param>
        public virtual void Start(string[] args)
        {
            string userInput = null;
            Arguments arguments = new Arguments(string.Join(" ", args));

            if (arguments.Exists("OrderedArg1") && arguments.Exists("restart"))
            {
                string serviceName = arguments["OrderedArg1"];

                if (Common.IsPosixEnvironment)
                {
                    string serviceCommand = FilePath.GetAbsolutePath(serviceName);

                    try
                    {
                        Command.Execute(serviceCommand, "stop");
                    }
                    catch (Exception ex)
                    {
                        WriteLine("Failed to stop the {0} daemon: {1}\r\n", serviceName, ex.Message);
                    }

                    try
                    {
                        Command.Execute(serviceCommand, "start");
                    }
                    catch (Exception ex)
                    {
                        WriteLine("Failed to restart the {0} daemon: {1}\r\n", serviceName, ex.Message);
                    }
                }
                else
                {
                    // Attempt to access service controller for the specified Windows service
                    ServiceController serviceController = ServiceController.GetServices().SingleOrDefault(svc => string.Compare(svc.ServiceName, serviceName, StringComparison.OrdinalIgnoreCase) == 0);

                    if (serviceController != null)
                    {
                        try
                        {
                            if (serviceController.Status == ServiceControllerStatus.Running)
                            {
                                WriteLine("Attempting to stop the {0} Windows service...", serviceName);

                                serviceController.Stop();

                                // Can't wait forever for service to stop, so we time-out after 20 seconds
                                serviceController.WaitForStatus(ServiceControllerStatus.Stopped, TimeSpan.FromSeconds(20.0D));

                                if (serviceController.Status == ServiceControllerStatus.Stopped)
                                    WriteLine("Successfully stopped the {0} Windows service.", serviceName);
                                else
                                    WriteLine("Failed to stop the {0} Windows service after trying for 20 seconds...", serviceName);

                                // Add an extra line for visual separation of service termination status
                                WriteLine("");
                            }
                        }
                        catch (Exception ex)
                        {
                            WriteLine("Failed to stop the {0} Windows service: {1}\r\n", serviceName, ex.Message);
                        }
                    }

                    // If the service failed to stop or it is installed as stand-alone debug application, we try to forcibly stop any remaining running instances
                    try
                    {
                        Process[] instances = Process.GetProcessesByName(serviceName);

                        if (instances.Length > 0)
                        {
                            int total = 0;
                            WriteLine("Attempting to stop running instances of the {0}...", serviceName);

                            // Terminate all instances of service running on the local computer
                            foreach (Process process in instances)
                            {
                                process.Kill();
                                total++;
                            }

                            if (total > 0)
                                WriteLine("Stopped {0} {1} instance{2}.", total, serviceName, total > 1 ? "s" : "");

                            // Add an extra line for visual separation of process termination status
                            WriteLine("");
                        }
                    }
                    catch (Exception ex)
                    {
                        WriteLine("Failed to terminate running instances of the {0}: {1}\r\n", serviceName, ex.Message);
                    }

                    // Attempt to restart Windows service...
                    if (serviceController != null)
                    {
                        try
                        {
                            // Refresh state in case service process was forcibly stopped
                            serviceController.Refresh();

                            if (serviceController.Status != ServiceControllerStatus.Running)
                                serviceController.Start();
                        }
                        catch (Exception ex)
                        {
                            WriteLine("Failed to restart the {0} Windows service: {1}\r\n", serviceName, ex.Message);
                        }
                    }
                }
            }
            else
            {
                if (arguments.Exists("server"))
                {
                    // Override default settings with user provided input. 
                    m_clientHelper.PersistSettings = false;
                    m_remotingClient.PersistSettings = false;
                    m_remotingClient.ConnectionString = string.Format("Server={0}", arguments["server"]);
                }

                long lastConnectAttempt = 0;

                // Connect to service and send commands.
                while (!string.Equals(userInput, "Exit", StringComparison.OrdinalIgnoreCase))
                {
                    try
                    {
                        // Do not reattempt connection too quickly
                        while (DateTime.UtcNow.Ticks - lastConnectAttempt < Ticks.PerSecond)
                            Thread.Sleep(200);

                        lastConnectAttempt = DateTime.UtcNow.Ticks;

                        if (!m_authenticationFailure)
                        {
                            // If there has been no authentication
                            // failure, connect normally
                            Connect();
                        }
                        else
                        {
                            UserInfo userInfo;
                            StringBuilder username = new StringBuilder();
                            StringBuilder password = new StringBuilder();

                            // If there has been an authentication failure,
                            // prompt the user for new credentials
                            PromptForCredentials(username, password);

                            try
                            {
                                // Attempt to set network credentials used when attempting AD authentication
                                userInfo = new UserInfo(username.ToString());
                                userInfo.Initialize();
                                SetNetworkCredential(new NetworkCredential(userInfo.LoginID, password.ToString()));
                            }
                            catch
                            {
                                // Even if this fails, we can still pass along user credentials
                            }

                            Connect(username.ToString(), password.ToString());
                        }

                        while (m_authenticated && m_clientHelper.Enabled && !string.Equals(userInput, "Exit", StringComparison.OrdinalIgnoreCase))
                        {
                            // Wait for a command from the user. 
                            userInput = System.Console.ReadLine();

                            // Write a blank line to the console.
                            WriteLine();

                            if (!string.IsNullOrWhiteSpace(userInput))
                            {
                                // The user typed in a command and didn't just hit <ENTER>. 
                                switch (userInput.ToUpper())
                                {
                                    case "CLS":
                                        // User wants to clear the console window. 
                                        System.Console.Clear();
                                        break;

                                    case "EXIT":
                                        // User wants to exit the telnet session with the service. 
                                        if (m_telnetActive)
                                        {
                                            userInput = string.Empty;
                                            m_clientHelper.SendRequest("Telnet -disconnect");
                                        }

                                        break;

                                    case "LOGIN":
                                        m_authenticated = false;
                                        m_authenticationFailure = true;
                                        break;

                                    default:
                                        // User wants to send a request to the service. 
                                        m_clientHelper.SendRequest(userInput);

                                        if (string.Compare(userInput, "Help", StringComparison.OrdinalIgnoreCase) == 0)
                                            DisplayHelp();

                                        break;
                                }
                            }
                        }

                        m_clientHelper.Disconnect();
                    }
                    catch (Exception)
                    {
                        // Errors during the outer connection loop
                        // should simply force an attempt to reconnect
                        m_clientHelper.Disconnect();
                    }
                }
            }
        }
Example #5
0
        /// <summary>
        /// Handles service start event.
        /// </summary>
        /// <param name="args">Service start arguments.</param>
        public virtual void Start(string[] args)
        {
            string userInput = null;
            Arguments arguments = new Arguments(string.Join(" ", args));

            if (arguments.Exists("OrderedArg1") && arguments.Exists("restart"))
            {
                string serviceName = arguments["OrderedArg1"];

                // Attempt to access service controller for the specified Windows service
                ServiceController serviceController = ServiceController.GetServices().SingleOrDefault(svc => string.Compare(svc.ServiceName, serviceName, true) == 0);

                if (serviceController != null)
                {
                    try
                    {
                        if (serviceController.Status == ServiceControllerStatus.Running)
                        {
                            Console.WriteLine("Attempting to stop the {0} Windows service...", serviceName);

                            serviceController.Stop();

                            // Can't wait forever for service to stop, so we time-out after 20 seconds
                            serviceController.WaitForStatus(ServiceControllerStatus.Stopped, TimeSpan.FromSeconds(20.0D));

                            if (serviceController.Status == ServiceControllerStatus.Stopped)
                                Console.WriteLine("Successfully stopped the {0} Windows service.", serviceName);
                            else
                                Console.WriteLine("Failed to stop the {0} Windows service after trying for 20 seconds...", serviceName);

                            // Add an extra line for visual separation of service termination status
                            Console.WriteLine("");
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Failed to stop the {0} Windows service: {1}\r\n", serviceName, ex.Message);
                    }
                }

                // If the service failed to stop or it is installed as stand-alone debug application, we try to forcibly stop any remaining running instances
                try
                {
                    Process[] instances = Process.GetProcessesByName(serviceName);

                    if (instances.Length > 0)
                    {
                        int total = 0;
                        Console.WriteLine("Attempting to stop running instances of the {0}...", serviceName);

                        // Terminate all instances of service running on the local computer
                        foreach (Process process in instances)
                        {
                            process.Kill();
                            total++;
                        }

                        if (total > 0)
                            Console.WriteLine(string.Format("Stopped {0} {1} instance{2}.", total, serviceName, total > 1 ? "s" : ""));

                        // Add an extra line for visual separation of process termination status
                        Console.WriteLine("");
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Failed to terminate running instances of the {0}: {1}\r\n", serviceName, ex.Message);
                }

                // Attempt to restart Windows service...
                if (serviceController != null)
                {
                    try
                    {
                        // Refresh state in case service process was forcibly stopped
                        serviceController.Refresh();

                        if (serviceController.Status != ServiceControllerStatus.Running)
                            serviceController.Start();
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Failed to restart the {0} Windows service: {1}\r\n", serviceName, ex.Message);
                    }
                }
            }
            else
            {
                if (arguments.Exists("server"))
                {
                    // Override default settings with user provided input. 
                    m_clientHelper.PersistSettings = false;
                    m_remotingClient.PersistSettings = false;
                    m_remotingClient.ConnectionString = string.Format("Server={0}", arguments["server"]);
                }

                // Connect to service and send commands. 
                while (!m_clientHelper.Enabled)
                {
                    m_authenticationWaitHandle.WaitOne();
                    m_clientHelper.Connect();

                    while (m_clientHelper.Enabled && string.Compare(userInput, "Exit", true) != 0)
                    {
                        m_innerLoopActive = true;

                        // Wait for a command from the user. 
                        userInput = System.Console.ReadLine();

                        // Write a blank line to the console.
                        System.Console.WriteLine();

                        if (!string.IsNullOrWhiteSpace(userInput))
                        {
                            // The user typed in a command and didn't just hit <ENTER>. 
                            switch (userInput.ToUpper())
                            {
                                case "CLS":
                                    // User wants to clear the console window. 
                                    System.Console.Clear();
                                    break;
                                case "EXIT":
                                    // User wants to exit the telnet session with the service. 
                                    if (m_telnetActive)
                                    {
                                        userInput = string.Empty;
                                        m_clientHelper.SendRequest("Telnet -disconnect");
                                    }
                                    break;
                                default:
                                    // User wants to send a request to the service. 
                                    m_clientHelper.SendRequest(userInput);
                                    if (string.Compare(userInput, "Help", true) == 0)
                                        DisplayHelp();

                                    break;
                            }
                        }
                    }

                    m_innerLoopActive = false;
                }
            }
        }
        public void Start()
        {
            string userInput = null;
            string[] args = Arguments.ToArgs(Environment.CommandLine);
            Arguments arguments = new Arguments(string.Join(" ", args.Where(arg => !arg.StartsWith("--filter=", StringComparison.OrdinalIgnoreCase))));

            if (arguments.Exists("server"))
            {
                // Override default settings with user provided input.
                m_clientHelper.PersistSettings = false;
                m_remotingClient.PersistSettings = false;
                if (arguments.Exists("server"))
                    m_remotingClient.ConnectionString = string.Format("Server={0}", arguments["server"]);
            }

            // Set the status message filter from command line args before connecting to the service
            m_clientHelper.StatusMessageFilter = Enumerable.Range(0, args.Length)
                .Where(index => args[index].StartsWith("--filter=", StringComparison.OrdinalIgnoreCase))
                .Select(index => Regex.Replace(args[index], "^--filter=", "", RegexOptions.IgnoreCase))
                .FirstOrDefault() ?? ClientHelper.DefaultStatusMessageFilter;

            // Connect to service and send commands.
            m_clientHelper.Connect();
            while (m_clientHelper.Enabled &&
                   string.Compare(userInput, "Exit", true) != 0)
            {
                // Wait for a command from the user.
                userInput = Console.ReadLine();
                // Write a blank line to the console.
                Console.WriteLine();

                if (!string.IsNullOrEmpty(userInput))
                {
                    // The user typed in a command and didn't just hit <ENTER>.
                    switch (userInput.ToUpper())
                    {
                        case "CLS":
                            // User wants to clear the console window.
                            Console.Clear();
                            break;
                        case "EXIT":
                            // User wants to exit the telnet session with the service.
                            if (m_telnetActive)
                            {
                                userInput = string.Empty;
                                m_clientHelper.SendRequest("Telnet -disconnect");
                            }
                            break;
                        default:
                            // User wants to send a request to the service.
                            m_clientHelper.SendRequest(userInput);
                            if (string.Compare(userInput, "Help", true) == 0)
                                DisplayHelp();

                            break;
                    }
                }
            }
        }
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        static void Main()
        {
            if (!s_singleInstanceMutex.WaitOne(0, true))
                Environment.Exit(1);

            bool runAsService;
            bool runAsApplication;

            Arguments args = new Arguments(Environment.CommandLine, true);

            if (args.Count == 0)
            {
#if DEBUG
                runAsService = false;
                runAsApplication = true;
#else
                runAsService = true;
                runAsApplication = false;
#endif
            }
            else
            {
                runAsService = args.Exists("RunAsService");
                runAsApplication = args.Exists("RunAsApplication");

                if (!runAsService && !runAsApplication && !args.Exists("RunAsConsole"))
                {
                    MessageBox.Show("Invalid argument. If specified, argument must be one of: -RunAsService, -RunAsApplication or -RunAsConsole.");
                    Environment.Exit(1);
                }
            }

            if (runAsService)
            {
                // Run as Windows Service.
                ServiceBase.Run(new ServiceBase[] { Host });
            }
            else if (runAsApplication)
            {
                // Run as Windows Application.
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new DebugHost(Host));
            }
            else
            {
                string shellHostedServiceName = Host.ServiceName + "Shell.exe";
                string shellHostedServiceFileName = FilePath.GetAbsolutePath(shellHostedServiceName);
                string shellHostedServiceConfigFileName = FilePath.GetAbsolutePath(shellHostedServiceName + ".config");
                string serviceConfigFileName = FilePath.GetAbsolutePath(Host.ServiceName + ".exe.config");

                try
                {
                    File.Copy(serviceConfigFileName, shellHostedServiceConfigFileName, true);
#if MONO
                    Process hostedServiceSession = Process.Start("mono", shellHostedServiceFileName);
#else
                    Process hostedServiceSession = Process.Start(shellHostedServiceFileName);
#endif
                    if ((object)hostedServiceSession != null)
                    {
                        hostedServiceSession.WaitForExit();

                        try
                        {
                            File.Copy(shellHostedServiceConfigFileName, serviceConfigFileName, true);
                        }
                        catch
                        {
                            // Do not report exception if config file could not be updated
                        }

                        Environment.Exit(hostedServiceSession.ExitCode);
                    }
                    else
                    {
                        MessageBox.Show($"Failed to start \"{Host.ServiceName}\" as a shell hosted service.");
                        Environment.Exit(1);
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"Failed to start \"{Host.ServiceName}\" as a shell hosted service: {ex.Message}");
                    Environment.Exit(1);
                }
            }
        }
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        static void Main()
        {
            ServiceHost host = new ServiceHost();

            bool runAsService;
            bool runAsApplication;

            Arguments args = new Arguments(Environment.CommandLine, true);

            if (args.Count > 1)
            {
                MessageBox.Show("Too many arguments. If specified, argument must be one of: -RunAsService, -RunAsApplication or -RunAsConsole.");
                Environment.Exit(1);
            }

            if (args.Count == 0)
            {
            #if DEBUG
                runAsService = false;
                runAsApplication = true;
            #else
                runAsService = true;
                runAsApplication = false;
            #endif
            }
            else
            {
                runAsService = args.Exists("RunAsService");
                runAsApplication = args.Exists("RunAsApplication");

                if (!runAsService && !runAsApplication && !args.Exists("RunAsConsole"))
                {
                    MessageBox.Show("Invalid argument. If specified, argument must be one of: -RunAsService, -RunAsApplication or -RunAsConsole.");
                    Environment.Exit(1);
                }
            }

            if (runAsService)
            {
                // Run as Windows Service.
                ServiceBase.Run(new ServiceBase[] { host });
            }
            else if (runAsApplication)
            {
                // Run as Windows Application.
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new DebugHost(host));
            }
            else
            {
                string hostedServiceSessionName = host.ServiceName + "Shell.exe";
                Process hostedServiceSession = Process.Start(hostedServiceSessionName);

                if ((object)hostedServiceSession != null)
                {
                    hostedServiceSession.WaitForExit();
                    Environment.Exit(hostedServiceSession.ExitCode);
                }
                else
                {
                    MessageBox.Show(string.Format("Failed to start \"{0}\" with a hosted service.", hostedServiceSessionName));
                    Environment.Exit(1);
                }
            }
        }
        public static void RunOperation(string operation, Arguments splitArguments)
        {
            switch (operation)
            {
            case FormatOperation:
                {
                    string inputFileName = FileFunctions.AdjustFileName(splitArguments.String(Arguments.InputArgument, true));
                    string outputFileName = splitArguments.OutputFileName();
                    List<string> variableNames = splitArguments.StringList(Arguments.DefaultArgumentPrefix + "variables", true, true);
                    string format = splitArguments.String(Arguments.DefaultArgumentPrefix + "format", true);
                    Format(inputFileName, outputFileName, variableNames, format);
                    Console.Write(outputFileName);
                }
                break;

            case CompressOperation:
                {
                    string inputFileName = FileFunctions.AdjustFileName(splitArguments.String(Arguments.InputArgument, true));
                    string outputFileName = splitArguments.OutputFileName();
                    Compress(inputFileName, outputFileName);
                    Console.Write(outputFileName);
                }
                break;

            case FileNameOperation:
                {
                    string inputFileName = FileFunctions.AdjustFileName(splitArguments.String(Arguments.InputArgument, true));
                    string fileName = Path.GetFileName(inputFileName);
                    Console.Write(fileName);
                }
                break;

            case FileNameWithoutExtensionOperation:
                {
                    string inputFileName = FileFunctions.AdjustFileName(splitArguments.String(Arguments.InputArgument, true));
                    string fileName = Path.GetFileNameWithoutExtension(inputFileName);
                    Console.Write(fileName);
                }
                break;

            case GenerateOperation:
                {
                    string inputFileName = FileFunctions.AdjustFileName(splitArguments.String(Arguments.InputArgument, true));
                    string outputFileName = splitArguments.OutputFileName();
                    string variableName = splitArguments.String(Arguments.DefaultArgumentPrefix + "variable", true);
                    string expression = splitArguments.String(Arguments.DefaultArgumentPrefix + "expression", true);
                    string type = splitArguments.String(Arguments.DefaultArgumentPrefix + "type", false);
                    Generate(inputFileName, outputFileName, variableName, type, expression);
                    Console.Write(outputFileName);
                }
                break;

            case PasswordOperation:
                {
                    string prompt = splitArguments.String(Arguments.DefaultArgumentPrefix + "prompt", false);
                    bool requireEntry = splitArguments.Bool(Arguments.DefaultArgumentPrefix + "ignoreCache", false);
                    string password = Password(prompt, requireEntry);
                    Console.Write(password);
                }
                break;

            case TransposeOperation:
                {
                    string inputFileName = FileFunctions.AdjustFileName(splitArguments.String(Arguments.InputArgument, true));
                    string outputFileName = splitArguments.OutputFileName();
                    Transpose(inputFileName, outputFileName);
                    Console.Write(outputFileName);
                }
                break;

            case SortOperation:
                {
                    string inputFileName = FileFunctions.AdjustFileName(splitArguments.String(Arguments.InputArgument, true));
                    List<string> variableNames = splitArguments.StringList(Arguments.DefaultArgumentPrefix + "variables", true, true);
                    string outputFileName = splitArguments.OutputFileName();
                    outputFileName = Sort(inputFileName, variableNames, outputFileName);
                    Console.Write(outputFileName);
                }
                break;

            case SelectCloumnsOperation:
                {
                    string inputFileName = FileFunctions.AdjustFileName(splitArguments.String(Arguments.InputArgument, true));
                    List<string> variableNames = splitArguments.StringList(Arguments.DefaultArgumentPrefix + "variables", true, true);
                    string outputFileName = splitArguments.OutputFileName();
                    SelectColumns(inputFileName, outputFileName, variableNames);
                    Console.Write(outputFileName);
                }
                break;

            case SelectRecordsOperation:
                {
                    string inputFileName = FileFunctions.AdjustFileName(splitArguments.String(Arguments.InputArgument, true));
                    string expression = splitArguments.String(Arguments.DefaultArgumentPrefix + "expression", true);
                    string outputFileName = splitArguments.OutputFileName();
                    Select(inputFileName, outputFileName, expression);
                    Console.Write(outputFileName);
                }
                break;

            case SaveOperation:
                {
                    string inputFileName = FileFunctions.AdjustFileName(splitArguments.String(Arguments.InputArgument, true));
                    string outputFileName = splitArguments.OutputFileName();
                    SaveFile(inputFileName, outputFileName);
                    Console.Write(outputFileName);
                }
                break;

            case MergeOperation:
                {
                    string input1FileName = FileFunctions.AdjustFileName(splitArguments.String(Arguments.InputArgument + "1", true));
                    string input2FileName = FileFunctions.AdjustFileName(splitArguments.String(Arguments.InputArgument + "2", true));
                    List<string> variableNames = splitArguments.StringList(Arguments.DefaultArgumentPrefix + "variables", true, true);
                    string outputFileName = splitArguments.OutputFileName();
                    List<MergeRecordResult> keep = splitArguments.EnumList<MergeRecordResult>(Arguments.DefaultArgumentPrefix + "keep", false, false);

                    string keepMergeString = FileFunctions.AdjustFileName(splitArguments.String(Arguments.DefaultArgumentPrefix + "keepMerge", false));
                    bool keepMerge;
                    if (!string.IsNullOrWhiteSpace(keepMergeString))
                    {
                        keepMerge = bool.Parse(keepMergeString.ToLower());
                    } else
                    {
                        keepMerge = false;
                    }

                    Merge(input1FileName, input2FileName, variableNames, outputFileName, keepMerge, keep);
                    Console.Write(outputFileName);
                }
                break;

            case DoScriptOperation:
                {
                    string inputFileName = FileFunctions.AdjustFileName(splitArguments.String(Arguments.DefaultArgumentPrefix + "filename", true));
                    string log = StataFunctions.RunScript(inputFileName, false);
                    Console.Write(log);
                }
                break;

            case CommandOperation:
                {
                    string inputFileName = FileFunctions.AdjustFileName(splitArguments.String(Arguments.InputArgument, true));
                    string command = splitArguments.String(Arguments.DefaultArgumentPrefix + "command", true);
                    string outputFileName = splitArguments.OutputFileName();
                    StataCommand(inputFileName, outputFileName, command);
                    Console.Write(outputFileName);
                }
                break;

            case AppendOperation:
                {
                    string input1FileName = FileFunctions.AdjustFileName(splitArguments.String(Arguments.InputArgument + "1", true));
                    string input2FileName = FileFunctions.AdjustFileName(splitArguments.String(Arguments.InputArgument + "2", true));
                    string outputFileName = splitArguments.OutputFileName();
                    outputFileName = Append(input1FileName, input2FileName, outputFileName);
                    Console.Write(outputFileName);
                }
                break;

            case RemoveColumnsOperation:
                {
                    string inputFileName = FileFunctions.AdjustFileName(splitArguments.String(Arguments.InputArgument, true));
                    List<string> variableNames = splitArguments.StringList(Arguments.DefaultArgumentPrefix + "variables", true, true);
                    string outputFileName = splitArguments.OutputFileName();
                    RemoveColumns(inputFileName, outputFileName, variableNames);
                    Console.Write(outputFileName);
                }
                break;

            case DisplayOperation:
                {
                    string inputFileName = FileFunctions.AdjustFileName(splitArguments.String(Arguments.InputArgument, true));
                    Display(inputFileName);
                }
                break;

            case DisplayClientOperation:
                {
                    string inputFileName = FileFunctions.AdjustFileName(splitArguments.String(Arguments.InputArgument, true));
                    DisplayClient(inputFileName);
                }
                break;

            case TestOperation:
                {
                    bool silent = splitArguments.Exists(Arguments.DefaultArgumentPrefix + "silent");

                    List<string> lines = new List<string>();
                    lines.Add("Arguments: " + splitArguments.ArgumentString);
                    lines.Add("Startup path: " + Application.StartupPath);
                    lines.Add("Working directory: " + Environment.CurrentDirectory);

                    if (ProcessFunctions.KeplerProcess != null)
                    {
                        lines.Add("Keper process:");
                        lines.Add(ProcessFunctions.WriteProcessInformation(ProcessFunctions.KeplerProcess));
                    } else
                    {
                        lines.Add("Keper process: Not found");
                    }

                    lines.Add("Current process heritage: ");

                    lines.AddRange(ProcessFunctions.WriteProcessHeritage().Split(new string[] { Environment.NewLine }, StringSplitOptions.None));
                    lines.AddRange(ProcessFunctions.WriteSystemVariables().Split(new string[] { Environment.NewLine }, StringSplitOptions.None));
                    if (!silent)
                    {
                        SwishFunctions.MessageTextBox("Test display", lines, false);
                    }
                    Console.Write(string.Join(Environment.NewLine, lines));
                }
                break;

            case TemporaryFileNameOperation:
                {
                    string fileName = FileFunctions.TempoaryOutputFileName(string.Empty);
                    if (FileFunctions.FileExists(fileName))
                    {
                        File.Delete(fileName);
                    }
                    Console.Write(fileName);
                }
                break;

            case ReplaceOperation:
                {
                    string inputFileName = FileFunctions.AdjustFileName(splitArguments.String(Arguments.InputArgument, true));
                    string outputFileName = splitArguments.OutputFileName();
                    string condition = splitArguments.String(Arguments.DefaultArgumentPrefix + "condition", true);
                    string value = splitArguments.String(Arguments.DefaultArgumentPrefix + "value", true);
                    Replace(inputFileName, outputFileName, condition, value);
                    Console.Write(outputFileName);
                }
                break;

            default:
                throw new Exception("Unknown operation \"" + operation + "\"");
            }
        }