Пример #1
0
        static void Main(string[] args)
        {
            var options = new Options();
            var parser  = new CommandLine.Parser(with => with.HelpWriter = Console.Error);

            if (parser.ParseArgumentsStrict(args, options, () => { Environment.Exit(-2); }))
            {
                options.BoundaryCheck();

                if (string.IsNullOrEmpty(options.InputFile) && string.IsNullOrEmpty(options.InputFileList))
                {
                    Console.WriteLine("Neither input file nor input file list is specified");
                    Environment.Exit(-2);
                }

                if (!string.IsNullOrEmpty(options.InputFile) && !string.IsNullOrEmpty(options.InputFileList))
                {
                    Console.WriteLine("Both input file and input file list are specified");
                    Environment.Exit(-2);
                }

                int returnValue = Run(options);

                if (returnValue != 0)
                {
                    Environment.Exit(returnValue);
                }
            }
        }
Пример #2
0
        public void Parse_strict_bad_input_fails_and_exits_with_verbs_when_get_usage_is_defined()
        {
            string invokedVerb         = null;
            object invokedVerbInstance = null;

            var options    = new OptionsWithVerbs();
            var testWriter = new StringWriter();

            ReflectionHelper.AssemblyFromWhichToPullInformation = Assembly.GetExecutingAssembly();
            var parser = new CommandLine.Parser(with => with.HelpWriter = testWriter);
            var result = parser.ParseArgumentsStrict(new string[] { "bad", "input" }, options,
                                                     (verb, subOptions) =>
            {
                invokedVerb         = verb;
                invokedVerbInstance = subOptions;
            },
                                                     () => Console.WriteLine("fake fail"));

            result.Should().BeFalse();

            var helpText = testWriter.ToString();

            Console.WriteLine(helpText);
            var lines = helpText.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);

            // Did we really produced all help?
            lines.Should().HaveCount(n => n == 1);
            // Verify just significant output
            lines[0].Trim().Should().Be("verbs help index");

            invokedVerb.Should().Be("bad");
            invokedVerbInstance.Should().BeNull();
        }
Пример #3
0
    static void Main(string[] args)
    {
      // Parse command line options
      var mpOptions = new CommandLineOptions();
      var parser = new CommandLine.Parser(with => with.HelpWriter = Console.Out);
      parser.ParseArgumentsStrict(args, mpOptions, () => Environment.Exit(1));

      List<string> products = new List<string>
      {
        "MediaPortal Setup TV", // Legacy folders for TVE3 support
        "MediaPortal TV Server", // Legacy folders for TVE3 support
        "MP2-Client",
        "MP2-Server",
        "MP2-ClientLauncher",
        "MP2-ServiceMonitor"
      };

      string dataPath = !string.IsNullOrEmpty(mpOptions.DataDirectory) ?
        mpOptions.DataDirectory :
        Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData);

      string outputPath = !string.IsNullOrEmpty(mpOptions.OutputDirectory) ?
        mpOptions.OutputDirectory :
        Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "MediaPortal2-Logs");

      try
      {
        CollectLogFiles(dataPath, outputPath, products);
      }
      catch (Exception ex)
      {
        Console.WriteLine("Exception while collecting log files: {0}", ex);
      }
    }
Пример #4
0
        /// <summary>
        /// 应用程序入口
        /// </summary>
        /// <param name="args">命令行参数</param>
        static void Main(string[] args)
        {
            System.DateTime startTime = System.DateTime.Now;

            //-- 分析命令行参数
            var options = new Options();
            var parser = new CommandLine.Parser(with => with.HelpWriter = Console.Error);

            if (parser.ParseArgumentsStrict(args, options, () => Environment.Exit(-1)))
            {
                //-- 执行导出操作
                try
                {
                    Run(options);
                }
                catch (Exception exp)
                {
                    Console.WriteLine("Error: " + exp.Message);
                }
            }

            //-- 程序计时
            System.DateTime endTime = System.DateTime.Now;
            System.TimeSpan dur = endTime - startTime;
            Console.WriteLine(
                string.Format("[{0}]:\t转换完成[{1}毫秒].",
                Path.GetFileName(options.ExcelPath),
                dur.Milliseconds)
                );
        }
Пример #5
0
        static void Main(string[] args)
        {
            Thread.CurrentThread.Name = "Main";

            // Parse command line options
            var mpOptions = new CommandLineOptions();
            var parser    = new CommandLine.Parser(with => with.HelpWriter = Console.Out);

            parser.ParseArgumentsStrict(args, mpOptions, () => Environment.Exit(1));

            if (String.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable("wix")))
            {
                Console.Write("WiX environment variable could not be found. Please reinstall WiX.");
                Environment.Exit(2);
            }

            if (!CreateTransforms(mpOptions))
            {
                Environment.Exit(3);
            }

            if (!MergeTransforms(mpOptions))
            {
                Environment.Exit(4);
            }
        }
Пример #6
0
        static void Main(string[] args)
        {
            // Parse command line options
            var mpOptions = new CommandLineOptions();
            var parser    = new CommandLine.Parser(with => with.HelpWriter = Console.Out);

            parser.ParseArgumentsStrict(args, mpOptions, () => Environment.Exit(1));

            List <string> products = new List <string>
            {
                "MediaPortal Setup TV",  // Legacy folders for TVE3 support
                "MediaPortal TV Server", // Legacy folders for TVE3 support
                "MP2-Client",
                "MP2-Server",
                "MP2-ClientLauncher",
                "MP2-ServiceMonitor"
            };

            string dataPath = !string.IsNullOrEmpty(mpOptions.DataDirectory) ?
                              mpOptions.DataDirectory :
                              Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData);

            string outputPath = !string.IsNullOrEmpty(mpOptions.OutputDirectory) ?
                                mpOptions.OutputDirectory :
                                Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "MediaPortal2-Logs");

            try
            {
                CollectLogFiles(dataPath, outputPath, products);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception while collecting log files: {0}", ex);
            }
        }
Пример #7
0
        /// <summary>
        /// 应用程序入口
        /// </summary>
        /// <param name="args">命令行参数</param>
        static void Main(string[] args)
        {
            System.DateTime startTime = System.DateTime.Now;

            //-- 分析命令行参数
            var options = new Options();
            var parser  = new CommandLine.Parser(with => with.HelpWriter = Console.Error);

            if (parser.ParseArgumentsStrict(args, options, () => Environment.Exit(-1)))
            {
                //-- 执行导出操作
                try
                {
                    Run(options);
                }
                catch (Exception exp)
                {
                    Console.WriteLine("Error: " + exp.Message);
                }
            }

            //-- 程序计时
            System.DateTime endTime = System.DateTime.Now;
            System.TimeSpan dur     = endTime - startTime;
            Console.WriteLine(
                string.Format("[{0}]:\t转换完成[{1}毫秒].",
                              Path.GetFileName(options.ExcelPath),
                              dur.Milliseconds)
                );
        }
Пример #8
0
        public static void Main(string[] args)
        {
            options = new Options();

            CommandLine.Parser parser = new CommandLine.Parser(with => with.HelpWriter = Console.Error);

            parser.ParseArgumentsStrict(args, options, () => Environment.Exit(-2));

            if (options.AccessKey == null || options.SecretKey == null)
            {
                Console.WriteLine(options.GetUsage());
                Environment.Exit(-2);
            }

            try
            {
                // ListVolumes(); // got for testing connectivity

                CheckForScheduledSnapshots();

                CheckForExpiredSnapshots();
            }
            catch (Exception err)
            {
                Console.WriteLine("Error from " + err.Source + ": " + err.Message);
                Environment.Exit(-2);
            }

            Environment.Exit(0);
        }
Пример #9
0
        static void Main(string[] args)
        {
            try
            {
                var options = new Options();

                if (args.Length == 0)
                {
                    Console.WriteLine(options.GetUsage());
                    Environment.Exit(0);
                }

                var parser = new CommandLine.Parser(with => with.HelpWriter = Console.Error);

                if (parser.ParseArgumentsStrict(args, options, () => Environment.Exit(1)))
                {
                    Command(options);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("{" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "}");
                Console.WriteLine(ex);
            }

            Environment.Exit(0);
        }
Пример #10
0
        public void Parse_strict_bad_input_fails_and_exits_with_verbs()
        {
            string invokedVerb         = null;
            object invokedVerbInstance = null;

            var options    = new OptionsWithVerbsNoHelp();
            var testWriter = new StringWriter();

            ReflectionHelper.AssemblyFromWhichToPullInformation = Assembly.GetExecutingAssembly();
            var parser = new CommandLine.Parser(with => with.HelpWriter = testWriter);
            var result = parser.ParseArgumentsStrict(new string[] { "bad", "input" }, options,
                                                     (verb, subOptions) =>
            {
                invokedVerb         = verb;
                invokedVerbInstance = subOptions;
            },
                                                     () => Console.WriteLine("fake fail"));

            result.Should().BeFalse();

            var helpText = testWriter.ToString();

            Console.WriteLine(helpText);
            var lines = helpText.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);

            // Did we really produced all help?
            lines.Should().HaveCount(n => n == 8);
            // Verify just significant output
            lines[5].Trim().Should().Be("add       Add file contents to the index.");
            lines[6].Trim().Should().Be("commit    Record changes to the repository.");
            lines[7].Trim().Should().Be("clone     Clone a repository into a new directory.");

            invokedVerb.Should().Be("bad");
            invokedVerbInstance.Should().BeNull();
        }
Пример #11
0
        static void Main(string[] args)
        {
            // Parse command line options
            var options = new SkinCloneArguments();
            var parser  = new CommandLine.Parser(with => with.HelpWriter = Console.Out);

            parser.ParseArgumentsStrict(args, options, () => Environment.Exit(1));

            SkinCloner.Process(options);
        }
Пример #12
0
        static void Main(string[] args)
        {
            var options = new Options();
            var parser  = new CommandLine.Parser(with => with.HelpWriter = Console.Error);

            if (parser.ParseArgumentsStrict(args, options, () => { Environment.Exit(-2); }))
            {
                options.BoundaryCheck();

                Run(options);
            }
        }
Пример #13
0
        static void Main(string[] args)
        {
            Thread.CurrentThread.Name = "Main";

            // Parse command line options
            var mpOptions = new CommandLineOptions();
            var parser    = new CommandLine.Parser(with => with.HelpWriter = Console.Out);

            parser.ParseArgumentsStrict(args, mpOptions, () => Environment.Exit(1));

            targetDir = mpOptions.TargetDir;

            // always run verification first
            if (!Verify())
            {
                Environment.Exit(2);
            }

            if (mpOptions.Verify)
            {
                Environment.Exit(0);
            }

            if (mpOptions.ToCache)
            {
                UpdateTransifexConfig();
                CopyToCache();
            }

            if (mpOptions.Push)
            {
                ExecutePush();
            }

            if (mpOptions.Pull)
            {
                ExecutePull();
                WritePullMarkerFile();
            }

            if (mpOptions.Fix)
            {
                DeleteEmptyFiles();
                FixEncodings();
            }

            if (mpOptions.FromCache)
            {
                CopyFromCache();
            }
        }
Пример #14
0
    /// <summary>
    /// The main entry point for the MP2 server application.
    /// </summary>
    public static void Main(params string[] args)
    {
      // Parse command line options
      var mpOptions = new CommandLineOptions();
      var parser = new CommandLine.Parser(with => with.HelpWriter = Console.Out);
      parser.ParseArgumentsStrict(args, mpOptions, () => Environment.Exit(1));

      if (mpOptions.RunAsConsoleApp)
        new ApplicationLauncher(mpOptions.DataDirectory).RunAsConsole();
      else
      {
        ServiceBase[] servicesToRun = new ServiceBase[] { new WindowsService() };
        ServiceBase.Run(servicesToRun);
      }
    }
Пример #15
0
        static void Main(string[] args)
        {
            var options = new Options();

            options.Import = false;
            options.Export = false;



            var parser = new CommandLine.Parser(with => with.HelpWriter = Console.Error);

            if (parser.ParseArgumentsStrict(args, options, () => Environment.Exit(-2)))
            {
                Run(options);
            }
        }
Пример #16
0
        static void Main(string[] args)
        {
            // direct the output to the console.
            OsmSharp.Tools.Output.OutputStreamHost.RegisterOutputStream(
                new ConsoleOutputStream());

            // check for command line options.
            var options = new Options();
            var parser = new CommandLine.Parser(with => with.HelpWriter = Console.Error);

            if (parser.ParseArgumentsStrict(args, options, () => Environment.Exit(-2)))
            {
                // parsing was successfull.
                OperationProcessor.Settings["pbf_file"] = options.File;
            }

            // initializes the processor(s).
            var processors = new List<IProcessor>();
            processors.Add(OperationProcessor.GetInstance());

            // start all the processor(s).
            foreach (IProcessor processor in processors)
            {
                processor.Start();
            }

            // get the hostname.
            string hostname = options.Hostname;
            if (string.IsNullOrWhiteSpace(hostname))
            {
                hostname = ConfigurationManager.AppSettings["hostname"];
            }
            if (string.IsNullOrWhiteSpace(hostname))
            {
                throw new ArgumentOutOfRangeException("hostname", "Hostname not configure! use -h or --host");
            }
            OsmSharp.Tools.Output.OutputStreamHost.WriteLine("Service will listen to: {0}",
                hostname);

            // start the self-hosting.
            var host = new AppHost();
            host.Init();
            host.Start(hostname);

            OsmSharp.Tools.Output.OutputStreamHost.WriteLine("OsmDataService started.");
            Console.ReadLine();
        }
Пример #17
0
        /// <summary>
        /// The main entry point for the MP2 server application.
        /// </summary>
        public static void Main(params string[] args)
        {
            // Parse command line options
            var mpOptions = new CommandLineOptions();
            var parser    = new CommandLine.Parser(with => with.HelpWriter = Console.Out);

            parser.ParseArgumentsStrict(args, mpOptions, () => Environment.Exit(1));

            if (mpOptions.RunAsConsoleApp)
            {
                new ApplicationLauncher(mpOptions.DataDirectory).RunAsConsole();
            }
            else
            {
                ServiceBase[] servicesToRun = new ServiceBase[] { new WindowsService() };
                ServiceBase.Run(servicesToRun);
            }
        }
Пример #18
0
        public void Parse_strict_bad_input_fails_and_exits_when_get_usage_is_defined()
        {
            var options = new SimpleOptionsForStrict();
            var testWriter = new StringWriter();

            ReflectionHelper.AssemblyFromWhichToPullInformation = Assembly.GetExecutingAssembly();
            var parser = new CommandLine.Parser(with => with.HelpWriter = testWriter);
            var result = parser.ParseArgumentsStrict(new string[] { "--bad", "--input" }, options,
                () => Console.WriteLine("fake fail"));

            result.Should().BeFalse();

            var helpText = testWriter.ToString();
            Console.WriteLine(helpText);
            var lines = helpText.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
            // Did we really called user help method?
            lines.Should().HaveCount(n => n == 1);
            // Verify just significant output
            lines[0].Trim().Should().Be("SimpleOptionsForStrict (user defined)");
        }
Пример #19
0
        static void Main(string[] args)
        {
            if (args.Length <= 0)
            {
                //-- GUI MODE ----------------------------------------------------------
                Console.WriteLine("Launch excel2json GUI Mode...");
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new GUI.MainForm());
            }
            else
            {
                //-- COMMAND LINE MODE -------------------------------------------------

                //-- 分析命令行参数
                var options = new Options();
                var parser  = new CommandLine.Parser(with => with.HelpWriter = Console.Error);

                if (parser.ParseArgumentsStrict(args, options, () => Environment.Exit(-1)))
                {
                    //-- 执行导出操作
                    try
                    {
                        DateTime startTime = DateTime.Now;
                        Run(options);
                        //-- 程序计时
                        DateTime endTime = DateTime.Now;
                        TimeSpan dur     = endTime - startTime;
                        Console.WriteLine(
                            string.Format("[{0}]:\tConversion complete in [{1}ms].",
                                          Path.GetFileName(options.excelPath),
                                          dur.TotalMilliseconds)
                            );
                    }
                    catch (Exception exp)
                    {
                        Console.WriteLine("Error: " + exp.Message);
                    }
                }
            }// end of else
        }
Пример #20
0
    static void Main(string[] args)
    {
      Thread.CurrentThread.Name = "Main";

      // Parse command line options
      var mpOptions = new CommandLineOptions();
      var parser = new CommandLine.Parser(with => with.HelpWriter = Console.Out);
      parser.ParseArgumentsStrict(args, mpOptions, () => Environment.Exit(1));

      if (String.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable("wix")))
      {
        Console.Write("WiX environment variable could not be found. Please reinstall WiX.");
        Environment.Exit(2);
      }

      if (!CreateTransforms(mpOptions))
        Environment.Exit(3);

      if (!MergeTransforms(mpOptions))
        Environment.Exit(4);
    }
Пример #21
0
        static int Main(string[] args)
        {
            var options = new Options();
            var parser  = new CommandLine.Parser(with => with.HelpWriter = Console.Error);

            if (parser.ParseArgumentsStrict(args, options, () => Environment.Exit(-2)))
            {
                if (options.type == "COMMI")
                {
                    dhqh_commition dhqh = new dhqh_commition();
                    dhqh.run();
                    return(0);
                }
            }

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Main());

            return(0);
        }
Пример #22
0
        /// <summary>
        /// 命令行模式
        /// </summary>
        /// <param name="args"></param>
        private static void ConsoleMode(string[] args)
        {
            DateTime   startTime = DateTime.Now;
            OptionCmmd options   = new OptionCmmd();

            CommandLine.Parser parser = new CommandLine.Parser((with) => {
                with.HelpWriter = Console.Error;
            });

            if (parser.ParseArgumentsStrict(args, options, () => Environment.Exit(-1)))
            {
                try {
                    OptionsForm optionForm = new OptionsForm();
                    optionForm.XlsxSrcPath = options.InputPath;
                    optionForm.XlsxDstPath = options.OutputPath;

                    optionForm.SetExportType(ExportType.cs);
                    optionForm.SetExportType(ExportType.txt);
                    DataMemory.SetOptionForm(optionForm);

                    ExprotCallbackArgv argv = new ExprotCallbackArgv();
                    argv.OnProgressChanged = (int progress) => {
                        //Console.WriteLine(string.Format("Export progress {0}", progress));
                    };
                    argv.OnRunChanged      = (string message) => {
                        Console.WriteLine(string.Format("Export message {0}", message));
                    };

                    Facade.BeforeExporterOptionForm();
                    Facade.RunXlsxForm(argv);
                    Facade.AfterExporterOptionForm();
                } catch (Exception ex) {
                    Console.WriteLine("Error: " + ex.Message);
                }
            }
            TimeSpan expend = DateTime.Now - startTime;

            Console.WriteLine(string.Format("Expend time [{0} millisecond].", expend.Milliseconds));
        }
Пример #23
0
        public void Parse_strict_bad_input_fails_and_exits_when_get_usage_is_defined()
        {
            var options    = new SimpleOptionsForStrict();
            var testWriter = new StringWriter();

            ReflectionHelper.AssemblyFromWhichToPullInformation = Assembly.GetExecutingAssembly();
            var parser = new CommandLine.Parser(with => with.HelpWriter = testWriter);
            var result = parser.ParseArgumentsStrict(new string[] { "--bad", "--input" }, options,
                                                     () => Console.WriteLine("fake fail"));

            result.Should().BeFalse();

            var helpText = testWriter.ToString();

            Console.WriteLine(helpText);
            var lines = helpText.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);

            // Did we really called user help method?
            lines.Should().HaveCount(n => n == 1);
            // Verify just significant output
            lines[0].Trim().Should().Be("SimpleOptionsForStrict (user defined)");
        }
Пример #24
0
        public void Parse_strict_bad_input_fails_and_exits()
        {
            var options = new SimpleOptions();
            var testWriter = new StringWriter();

            ReflectionHelper.AssemblyFromWhichToPullInformation = Assembly.GetExecutingAssembly();
            var parser = new CommandLine.Parser(with => with.HelpWriter = testWriter);
            var result = parser.ParseArgumentsStrict(new string[] {"--bad", "--input"}, options,
                () => Console.WriteLine("fake fail"));

            result.Should().BeFalse();

            var helpText = testWriter.ToString();
            Console.WriteLine(helpText);
            var lines = helpText.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
            // Did we really produced all help?
            lines.Should().HaveCount(n => n == 8);
            // Verify just significant output
            lines[5].Trim().Should().Be("-s, --string");
            lines[6].Trim().Should().Be("-i");
            lines[7].Trim().Should().Be("--switch");
        }
Пример #25
0
        public void Parse_strict_bad_input_fails_and_exits()
        {
            var options    = new SimpleOptions();
            var testWriter = new StringWriter();

            ReflectionHelper.AssemblyFromWhichToPullInformation = Assembly.GetExecutingAssembly();
            var parser = new CommandLine.Parser(with => with.HelpWriter = testWriter);
            var result = parser.ParseArgumentsStrict(new string[] { "--bad", "--input" }, options,
                                                     () => Console.WriteLine("fake fail"));

            result.Should().BeFalse();

            var helpText = testWriter.ToString();

            Console.WriteLine(helpText);
            var lines = helpText.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);

            // Did we really produced all help?
            lines.Should().HaveCount(n => n == 8);
            // Verify just significant output
            lines[5].Trim().Should().Be("-s, --string");
            lines[6].Trim().Should().Be("-i");
            lines[7].Trim().Should().Be("--switch");
        }
Пример #26
0
    static void Main(string[] args)
    {
      Thread.CurrentThread.Name = "Main";

      // Parse command line options
      var mpOptions = new CommandLineOptions();
      var parser = new CommandLine.Parser(with => with.HelpWriter = Console.Out);
      parser.ParseArgumentsStrict(args, mpOptions, () => Environment.Exit(1));

      targetDir = mpOptions.TargetDir;

      // always run verification first
      if (!Verify())
        Environment.Exit(2);

      if (mpOptions.Verify)
        Environment.Exit(0);

      if (mpOptions.ToCache)
      {
        UpdateTransifexConfig();
        CopyToCache();
      }

      if (mpOptions.Push)
        ExecutePush();

      if (mpOptions.Pull)
        ExecutePull();

      if (mpOptions.Fix)
        FixEncodings();

      if (mpOptions.FromCache)
        CopyFromCache();
    }
Пример #27
0
        static void Main(string[] args)
        {
            var cmd    = new GenArgs();
            var parser = new CommandLine.Parser(with => with.HelpWriter = Console.Error);

            if (parser.ParseArgumentsStrict(args, cmd, () =>
            {
                Console.ReadLine();
                Environment.FailFast("Failed");
            }))
            {
                if (File.Exists(cmd.ResxFilePath))
                {
                    Run(cmd);
                }
                else
                {
                    Console.WriteLine($"RESX file {cmd.ResxFilePath} does not eixst");
                }
            }

            //Console.WriteLine("Press <ENTER> to quit");
            //Console.ReadLine();
        }
Пример #28
0
        static void Main(string[] args)
        {
            var cmd = new GenArgs();
            var parser = new CommandLine.Parser(with => with.HelpWriter = Console.Error);

            if (parser.ParseArgumentsStrict(args, cmd, () =>
            {
                Console.ReadLine();
                Environment.FailFast("Failed");
            }))
            {
                if (File.Exists(cmd.ResxFilePath))
                {
                    Run(cmd);
                }
                else
                {
                    Console.WriteLine($"RESX file {cmd.ResxFilePath} does not eixst");
                }
            }

            Console.WriteLine("Press <ENTER> to quit");
            Console.ReadLine();
        }
Пример #29
0
        /// <summary>
        /// The main entry point for the MP2-ClientLauncher application.
        /// </summary>
        private static void Main(params string[] args)
        {
            Thread.CurrentThread.Name = "Main";

            // Parse command line options
            var mpOptions = new CommandLineOptions();
            var parser    = new CommandLine.Parser(with => with.HelpWriter = Console.Out);

            parser.ParseArgumentsStrict(args, mpOptions, () => Environment.Exit(1));

            // Check if another instance is already running
            if (SingleInstanceHelper.IsAlreadyRunning(MUTEX_ID, out _mutex))
            {
                _mutex = null;
                // Stop current instance
                Console.Out.WriteLine("Application already running.");
                Environment.Exit(2);
            }

#if !DEBUG
            string logPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData),
                                          @"Team MediaPortal", "MP2-Client", "Log");
#endif

            //// todo: Make sure we're properly handling exceptions
            //DispatcherUnhandledException += OnUnhandledException;
            //AppDomain.CurrentDomain.UnhandledException += LauncherExceptionHandling.CurrentDomain_UnhandledException;

            // Start core services
            ILogger logger = null;
            try
            {
                // Check if user wants to override the default Application Data location.
                ApplicationCore.RegisterVitalCoreServices(mpOptions.DataDirectory);

                logger = ServiceRegistration.Get <ILogger>();

#if !DEBUG
                logPath = ServiceRegistration.Get <IPathManager>().GetPath("<LOG>");
#endif
            }
            catch (Exception e)
            {
                if (logger != null)
                {
                    logger.Critical("Error starting application", e);
                }

                ApplicationCore.DisposeCoreServices();

                throw;
            }

            // Start application
            logger.Info("Starting application");

            try
            {
                if (TerminateProcess("ehtray"))
                {
                    logger.Info("Terminating running instance(s) of ehtray.exe");
                }

                Remote.Transceivers.AddRange(GetTransceiverList());
                Remote.Click         += OnClick;
                Device.DeviceArrival += OnDeviceArrival;
                Device.DeviceRemoval += OnDeviceRemoval;

                if (!mpOptions.NoIcon)
                {
                    InitTrayIcon();
                }

                Application.Run();
            }
            catch (Exception e)
            {
                logger.Critical("Error executing application", e);
            }

            logger.Info("Exiting...");



            // Release mutex for single instance
            if (_mutex != null)
            {
                _mutex.ReleaseMutex();
            }

            Application.Exit();
        }
Пример #30
0
    /// <summary>
    /// The main entry point for the MP2-ClientLauncher application.
    /// </summary>
    private static void Main(params string[] args)
    {
      Thread.CurrentThread.Name = "Main";

      // Parse command line options
      var mpOptions = new CommandLineOptions();
      var parser = new CommandLine.Parser(with => with.HelpWriter = Console.Out);
      parser.ParseArgumentsStrict(args, mpOptions, () => Environment.Exit(1));

      // Check if another instance is already running
      if (SingleInstanceHelper.IsAlreadyRunning(MUTEX_ID, out _mutex))
      {
        _mutex = null;
        // Stop current instance
        Console.Out.WriteLine("Application already running.");
        Environment.Exit(2);
      }

#if !DEBUG
      string logPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData),
                                    @"Team MediaPortal", "MP2-Client", "Log");
#endif

      //// todo: Make sure we're properly handling exceptions
      //DispatcherUnhandledException += OnUnhandledException;
      //AppDomain.CurrentDomain.UnhandledException += LauncherExceptionHandling.CurrentDomain_UnhandledException;

      // Start core services
      ILogger logger = null;
      try
      {
        // Check if user wants to override the default Application Data location.
        ApplicationCore.RegisterVitalCoreServices(mpOptions.DataDirectory);

        logger = ServiceRegistration.Get<ILogger>();

#if !DEBUG
        logPath = ServiceRegistration.Get<IPathManager>().GetPath("<LOG>");
#endif
      }
      catch (Exception e)
      {
        if (logger != null)
          logger.Critical("Error starting application", e);

        ApplicationCore.DisposeCoreServices();

        throw;
      }

      // Start application
      logger.Info("Starting application");

      try
      {
        if (TerminateProcess("ehtray"))
          logger.Info("Terminating running instance(s) of ehtray.exe");

        Remote.Transceivers.AddRange(GetTransceiverList());
        Remote.Click += OnClick;
        Device.DeviceArrival += OnDeviceArrival;
        Device.DeviceRemoval += OnDeviceRemoval;

        if (!mpOptions.NoIcon)
          InitTrayIcon();

        Application.Run();
      }
      catch (Exception e)
      {
        logger.Critical("Error executing application", e);
      }

      logger.Info("Exiting...");



      // Release mutex for single instance
      if (_mutex != null)
        _mutex.ReleaseMutex();

      Application.Exit();
    }
Пример #31
0
        /// <summary>
        /// The entry point of the program, where the program control starts and ends.
        /// </summary>
        /// <param name="args">The command-line arguments.</param>
        public static void Main(string[] args)
        {
            using (var parser = new CommandLine.Parser(with => with.HelpWriter = Console.Error))
            {
                if (parser.ParseArgumentsStrict(args, _options, () => Environment.Exit(-1)))
                {
                    // Set logging level (default = INFO).
                    if (_options.VerboseLevel != null)
                    {
                        VerboseLevel logLevel;

                        if (Enum.TryParse <VerboseLevel>(_options.VerboseLevel, ignoreCase: true, result: out logLevel))
                        {
                            Log.LogLevel = logLevel;
                        }
                        else
                        {
                            Log.LogLevel = VerboseLevel.INFO;
                        }
                    }

                    // Delete & re-create output directory.
                    if (Directory.Exists(_options.OutputDirectory))
                    {
                        Directory.Delete(_options.OutputDirectory, recursive: true);
                    }

                    Directory.CreateDirectory(_options.OutputDirectory);

                    // Load plugins.
                    Dictionary <PluginType, IPlugin> plugins = GetPlugins(_options.ConfigFile);

                    var xmlDoc       = XmlUtils.LoadXmlDocument(_options.ConfigFile);
                    var defaultsNode = GetDefaultsXmlNode(xmlDoc);
                    var platforms    = GetPlatforms(xmlDoc, defaultsNode);

                    // Execute Reader plugin.
                    var readerPlugin = plugins[PluginType.TestReader] as IReaderPlugin;
                    readerPlugin.TestInputFile = _options.TestFile;
                    readerPlugin.Execute();

                    // Add all tests to queue.
                    var testQueue = new TestQueue();

                    foreach (var test in readerPlugin.Tests)
                    {
                        testQueue.EnqueueTestToRun(test);
                    }

                    // Execute Setup plugin.

                    // Execute Test Executor plugin.
                    var executorPlugin = plugins[PluginType.TestExecutor] as IExecutorPlugin;
                    executorPlugin.Options   = _options;
                    executorPlugin.TestQueue = testQueue;
                    ExecuteTests(executorPlugin, platforms);

                    // Execute Cleanup plugin.

                    // Execute Reporter plugin.
                    var reporterPlugin = plugins[PluginType.TestReporter] as IReporterPlugin;
                    reporterPlugin.TestQueue = testQueue;
                    reporterPlugin.Execute();
                }
            }
        }
Пример #32
0
    /// <summary>
    /// The main entry point for the MP2 client application.
    /// </summary>
    private static void Main(params string[] args)
    {
      Thread.CurrentThread.Name = "Main";

      // Parse command line options
      var mpOptions = new CommandLineOptions();
      var parser = new CommandLine.Parser(with => with.HelpWriter = Console.Out);
      parser.ParseArgumentsStrict(args, mpOptions, () => Environment.Exit(1));

      // Check if another instance is already running
      if (SingleInstanceHelper.IsAlreadyRunning(MUTEX_ID, out _mutex))
      {
        _mutex = null;
        // Set focus on previously running app
        SingleInstanceHelper.SwitchToCurrentInstance(SingleInstanceHelper.SHOW_MP2_CLIENT_MESSAGE);
        // Stop current instance
        Console.Out.WriteLine("Application already running.");
        Environment.Exit(2);
      }

#if !DEBUG
      string logPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), @"Team MediaPortal\MP2-Client\Log");
#endif

      Application.ThreadException += LauncherExceptionHandling.Application_ThreadException;
      AppDomain.CurrentDomain.UnhandledException += LauncherExceptionHandling.CurrentDomain_UnhandledException;

      SystemStateService systemStateService = new SystemStateService();
      ServiceRegistration.Set<ISystemStateService>(systemStateService);
      systemStateService.SwitchSystemState(SystemState.Initializing, false);

      try
      {
#if !DEBUG
        SplashScreen splashScreen = null;
#endif
        ILogger logger = null;
        try
        {
          // Check if user wants to override the default Application Data location.
          ApplicationCore.RegisterVitalCoreServices(mpOptions.DataDirectory);

#if !DEBUG
          splashScreen = CreateSplashScreen();
          splashScreen.ShowSplashScreen();
#endif

          ApplicationCore.RegisterCoreServices();

          logger = ServiceRegistration.Get<ILogger>();

#if !DEBUG
          IPathManager pathManager = ServiceRegistration.Get<IPathManager>();
          logPath = pathManager.GetPath("<LOG>");
#endif

          UiExtension.RegisterUiServices();
        }
        catch (Exception e)
        {
          if (logger != null)
            logger.Critical("Error starting application", e);
          systemStateService.SwitchSystemState(SystemState.ShuttingDown, true);
          ServiceRegistration.IsShuttingDown = true;

          UiExtension.DisposeUiServices();
          ApplicationCore.DisposeCoreServices();

          throw;
        }

        // Start the core
        logger.Debug("ApplicationLauncher: Starting application");

        try
        {
          IPluginManager pluginManager = ServiceRegistration.Get<IPluginManager>();
          pluginManager.Initialize();
          pluginManager.Startup(false);
          ApplicationCore.StartCoreServices();

          ISkinEngine skinEngine = ServiceRegistration.Get<ISkinEngine>();
          IWorkflowManager workflowManager = ServiceRegistration.Get<IWorkflowManager>();
          IMediaAccessor mediaAccessor = ServiceRegistration.Get<IMediaAccessor>();
          ILocalSharesManagement localSharesManagement = ServiceRegistration.Get<ILocalSharesManagement>();

          // We have to handle some dependencies here in the start order:
          // 1) After all plugins are loaded, the SkinEngine can initialize (=load all skin resources)
          // 2) After the skin resources are loaded, the workflow manager can initialize (=load its states and actions)
          // 3) Before the main window is shown, the splash screen should be hidden
          // 4) After the workflow states and actions are loaded, the main window can be shown
          // 5) After the skinengine triggers the first workflow state/startup screen, the default shortcuts can be registered
          mediaAccessor.Initialize(); // Independent from other services
          localSharesManagement.Initialize(); // After media accessor was initialized
          skinEngine.Initialize(); // 1)
          workflowManager.Initialize(); // 2)

#if !DEBUG
          splashScreen.CloseSplashScreen(); // 3)
#endif

          skinEngine.Startup(); // 4)
          UiExtension.Startup(); // 5)

          ApplicationCore.RegisterDefaultMediaItemAspectTypes(); // To be done after UI services are running

          systemStateService.SwitchSystemState(SystemState.Running, true);

          if (mpOptions.AutoStart)
            StartFocusKeeper();

          Application.Run();

          systemStateService.SwitchSystemState(SystemState.ShuttingDown, true);
          ServiceRegistration.IsShuttingDown = true; // Block ServiceRegistration from trying to load new services in shutdown phase

          // 1) Stop UI extensions (Releases all active players, must be done before shutting down SE)
          // 2) Shutdown SkinEngine (Closes all screens, uninstalls background manager, stops render thread)
          // 3) Shutdown WorkflowManager (Disposes all models)
          // 4) Shutdown ImporterWorker
          // 5) Shutdown PluginManager (Shuts down all plugins)
          // 6) Remove all services
          UiExtension.StopUiServices();
          skinEngine.Shutdown();
          workflowManager.Shutdown();
          ServiceRegistration.Get<IImporterWorker>().Shutdown();
          pluginManager.Shutdown();
          mediaAccessor.Shutdown();
          localSharesManagement.Shutdown();
          ApplicationCore.StopCoreServices();
        }
        catch (Exception e)
        {
          logger.Critical("Error executing application", e);
          systemStateService.SwitchSystemState(SystemState.ShuttingDown, true);
          ServiceRegistration.IsShuttingDown = true;
        }
        finally
        {
          UiExtension.DisposeUiServices();
          ApplicationCore.DisposeCoreServices();

          systemStateService.SwitchSystemState(SystemState.Ending, false);
        }
      }
      catch (Exception ex)
      {
#if DEBUG
        ConsoleLogger log = new ConsoleLogger(LogLevel.All, false);
        log.Error(ex);
#else
        UiCrashLogger crash = new UiCrashLogger(logPath);
        crash.CreateLog(ex);
#endif
        systemStateService.SwitchSystemState(SystemState.Ending, false);

        // Release mutex for single instance
        if (_mutex != null)
          _mutex.ReleaseMutex();

        Application.Exit();
      }
    }
Пример #33
0
        private static bool AcceptArguments(string[] args, ref ParsedArguments parsedArgs, out string errorMessage, out IList <string> warningMessages)
        {
            errorMessage    = string.Empty;
            warningMessages = new List <string>();

            var converterOptions = new CmdConverterOptions();

            using (var parser = new CmdParser(parsingSettings => { parsingSettings.IgnoreUnknownArguments = false; }))
            {
                if (!parser.ParseArgumentsStrict(args, converterOptions, () =>
                {
                    if (!IsHelpArgumentOnly(args))
                    {
                        Logger.LogError(NewLine + "Incorrect command line arguments." + NewLine);
                    }
                }))
                {
                    errorMessage = converterOptions.GetUsage();
                    return(IsHelpArgumentOnly(args));
                }
            }

            if (converterOptions.PlogPaths.Count == 0)
            {
                errorMessage = string.Format("No input target was specified.{0}{1}{2}", NewLine, NewLine, converterOptions.GetUsage());
                return(false);
            }

            foreach (var plogPath in converterOptions.PlogPaths)
            {
                if (!File.Exists(plogPath))
                {
                    errorMessage = string.Format("File '{0}' does not exist.{1}", plogPath, NewLine);
                    return(false);
                }

                parsedArgs.RenderInfo.Logs.Add(plogPath);
            }

            parsedArgs.RenderInfo.OutputDir = converterOptions.OutputPath ?? DefaultOutputFolder;

            if (!Directory.Exists(parsedArgs.RenderInfo.OutputDir))
            {
                errorMessage = string.Format("Output directory '{0}' does not exist.{1}", converterOptions.OutputPath, NewLine);
                return(false);
            }

            // Output directory represents a root drive
            string outputDirRoot = Path.GetPathRoot(parsedArgs.RenderInfo.OutputDir);

            if (outputDirRoot.Equals(parsedArgs.RenderInfo.OutputDir, StringComparison.InvariantCultureIgnoreCase) &&
                !outputDirRoot.EndsWith(Path.DirectorySeparatorChar.ToString()))
            {
                parsedArgs.RenderInfo.OutputDir += Path.DirectorySeparatorChar;
            }

            parsedArgs.RenderInfo.SrcRoot = converterOptions.SrcRoot;

            // Getting a map for levels by the analyzer type
            IDictionary <AnalyzerType, ISet <uint> > analyzerLevelFilterMap = new Dictionary <AnalyzerType, ISet <uint> >();

            if (converterOptions.AnalyzerLevelFilter != null && converterOptions.AnalyzerLevelFilter.Count > 0 &&
                !Utils.TryParseLevelFilters(converterOptions.AnalyzerLevelFilter, analyzerLevelFilterMap,
                                            out errorMessage))
            {
                return(false);
            }

            parsedArgs.LevelMap = analyzerLevelFilterMap;

            // Getting render types
            ISet <LogRenderType> renderTypes = new HashSet <LogRenderType>();

            if (converterOptions.PlogRenderTypes != null &&
                converterOptions.PlogRenderTypes.Count > 0 &&
                !Utils.TryParseEnumValues <LogRenderType>(converterOptions.PlogRenderTypes, renderTypes,
                                                          out errorMessage))
            {
                return(false);
            }

            // Gettings error code mappings
            ISet <ErrorCodeMapping> errorCodeMappings = new HashSet <ErrorCodeMapping>();

            if (converterOptions.ErrorCodeMapping != null &&
                converterOptions.ErrorCodeMapping.Count > 0 &&
                !Utils.TryParseEnumValues <ErrorCodeMapping>(converterOptions.ErrorCodeMapping, errorCodeMappings,
                                                             out errorMessage))
            {
                return(false);
            }

            if (parsedArgs.LevelMap.Any())
            {
                if (errorCodeMappings.Contains(ErrorCodeMapping.MISRA) && !parsedArgs.LevelMap.Any(item => item.Key == AnalyzerType.MISRA))
                {
                    warningMessages.Add(string.Format("MISRA mapping is specified, but MISRA rules group is not enabled. Check the '-{0}' flag.", CmdConverterOptions.AnalyzerLevelFilter_ShortName));
                }

                if (errorCodeMappings.Contains(ErrorCodeMapping.OWASP) && !parsedArgs.LevelMap.Any(item => item.Key == AnalyzerType.OWASP))
                {
                    warningMessages.Add(string.Format("OWASP mapping is specified, but OWASP rules group is not enabled. Check the '-{0}' flag.", CmdConverterOptions.AnalyzerLevelFilter_ShortName));
                }

                if (errorCodeMappings.Contains(ErrorCodeMapping.AUTOSAR) && !parsedArgs.LevelMap.Any(item => item.Key == AnalyzerType.AUTOSAR))
                {
                    warningMessages.Add(string.Format("AUTOSAR mapping is specified, but AUTOSAR rules group is not enabled. Check the '-{0}' flag.", CmdConverterOptions.AnalyzerLevelFilter_ShortName));
                }
            }

            // Check if provided outputNameTemplate is a valid file name
            if (!string.IsNullOrWhiteSpace(converterOptions.OutputNameTemplate) && !Utils.IsValidFilename(converterOptions.OutputNameTemplate))
            {
                errorMessage = String.Format("Template \"{0}\" is not a valid file name.{1}", converterOptions.OutputNameTemplate, NewLine);
                return(false);
            }

            // Check if settings path is exists
            if (!String.IsNullOrWhiteSpace(converterOptions.SettingsPath) && !File.Exists(converterOptions.SettingsPath))
            {
                errorMessage = string.Format("Settings file '{0}' does not exist.", converterOptions.SettingsPath);
                return(false);
            }

            parsedArgs.RenderTypes        = renderTypes;
            parsedArgs.ErrorCodeMappings  = errorCodeMappings;
            parsedArgs.DisabledErrorCodes = converterOptions.DisabledErrorCodes;
            parsedArgs.SettingsPath       = converterOptions.SettingsPath;
            parsedArgs.OutputNameTemplate = converterOptions.OutputNameTemplate;
            parsedArgs.IndicateWarnings   = converterOptions.IndicateWarnings;

            errorMessage = string.Empty;
            return(true);
        }
Пример #34
0
        /// <summary>
        /// Either shows the application's main window or inits the application in the system tray.
        /// </summary>
        private void OnStartup(object sender, StartupEventArgs args)
        {
            Thread.CurrentThread.Name = "Main";
            Thread.CurrentThread.SetApartmentState(ApartmentState.STA);

            // Parse command line options
            var mpOptions = new CommandLineOptions();
            var parser    = new CommandLine.Parser(with => with.HelpWriter = Console.Out);

            parser.ParseArgumentsStrict(args.Args, mpOptions, () => Environment.Exit(1));

            // Check if another instance is already running
            // If new instance was created by UacHelper previous one, assume that previous one is already closed.
            if (SingleInstanceHelper.IsAlreadyRunning(MUTEX_ID, out _mutex))
            {
                _mutex = null;
                // Set focus on previously running app
                SingleInstanceHelper.SwitchToCurrentInstance(SingleInstanceHelper.SHOW_MP2_SERVICEMONITOR_MESSAGE);
                // Stop current instance
                Console.Out.WriteLine("Application already running.");
                Environment.Exit(2);
            }

            // Make sure we're properly handling exceptions
            DispatcherUnhandledException += OnUnhandledException;
            AppDomain.CurrentDomain.UnhandledException += LauncherExceptionHandling.CurrentDomain_UnhandledException;

            var systemStateService = new SystemStateService();

            ServiceRegistration.Set <ISystemStateService>(systemStateService);
            systemStateService.SwitchSystemState(SystemState.Initializing, false);

#if !DEBUG
            string logPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), @"Team MediaPortal\MP2-ServiceMonitor\Log");
#endif

            try
            {
                ILogger logger = null;
                try
                {
                    ApplicationCore.RegisterVitalCoreServices(true);
                    ApplicationCore.RegisterCoreServices();
                    logger = ServiceRegistration.Get <ILogger>();

                    logger.Debug("Starting Localization");
                    Localization localization = new Localization();
                    ServiceRegistration.Set <ILocalization>(localization);
                    localization.Startup();

                    //ApplicationCore.StartCoreServices();

                    logger.Debug("UiExtension: Registering ISystemResolver service");
                    ServiceRegistration.Set <ISystemResolver>(new SystemResolver());

                    logger.Debug("UiExtension: Registering IServerConnectionManager service");
                    ServiceRegistration.Set <IServerConnectionManager>(new ServerConnectionManager());

#if !DEBUG
                    logPath = ServiceRegistration.Get <IPathManager>().GetPath("<LOG>");
#endif
                }
                catch (Exception e)
                {
                    if (logger != null)
                    {
                        logger.Critical("Error starting application", e);
                    }

                    systemStateService.SwitchSystemState(SystemState.ShuttingDown, true);
                    ServiceRegistration.IsShuttingDown = true;

                    ApplicationCore.DisposeCoreServices();

                    throw;
                }

                InitIpc();

                var appController = new AppController();
                ServiceRegistration.Set <IAppController>(appController);

                // Start the application
                logger.Debug("Starting application");
                try
                {
                    ServiceRegistration.Get <IServerConnectionManager>().Startup();
                    appController.StartUp(mpOptions);
                }
                catch (Exception e)
                {
                    logger.Critical("Error executing application", e);
                    systemStateService.SwitchSystemState(SystemState.ShuttingDown, true);
                    ServiceRegistration.IsShuttingDown = true;
                }
            }
            catch (Exception ex)
            {
#if DEBUG
                var log = new ConsoleLogger(LogLevel.All, false);
                log.Error(ex);
#else
                ServerCrashLogger crash = new ServerCrashLogger(logPath);
                crash.CreateLog(ex);
#endif
                systemStateService.SwitchSystemState(SystemState.Ending, false);
                Current.Shutdown();
            }
        }
Пример #35
0
        private static bool AcceptArguments(string[] args, ref ParsedArguments parsedArgs, out string errorMessage)
        {
            var converterOptions = new CmdConverterOptions();
            var parser           = new CmdParser(parsingSettings =>
            {
                parsingSettings.HelpWriter             = Console.Error;
                parsingSettings.IgnoreUnknownArguments = false;
            });

            if (!parser.ParseArgumentsStrict(args, converterOptions))
            {
                errorMessage = converterOptions.GetUsage();
                return(false);
            }

            if (!File.Exists(converterOptions.PlogPath))
            {
                errorMessage = string.Format("File '{0}' does not exist{1}{2}", converterOptions.PlogPath, NewLine,
                                             converterOptions.GetUsage());
                return(false);
            }

            Reporter.Instance.Header       = converterOptions.Header;
            Reporter.Instance.Server       = converterOptions.Server;
            Reporter.Instance.Port         = converterOptions.Port;
            Reporter.Instance.SmtpUser     = converterOptions.SmtpUser;
            Reporter.Instance.SmtpPassword = converterOptions.SmtpPassword;
            Reporter.Instance.FromAddress  = converterOptions.FromAddress;
            Reporter.Instance.SendEmail    = converterOptions.SendEmail;
            SvnInfo.Instance.AutoEmail     = converterOptions.AutoEmail;
            SvnInfo.Instance.EmailList     = converterOptions.EmailList;

            parsedArgs.RenderInfo.Plog      = converterOptions.PlogPath;
            parsedArgs.RenderInfo.OutputDir = converterOptions.OutputPath ?? DefaultOutputFolder;

            if (!Directory.Exists(parsedArgs.RenderInfo.OutputDir))
            {
                errorMessage = string.Format("Output directory '{0}' does not exist{1}{2}", converterOptions.OutputPath,
                                             NewLine, converterOptions.GetUsage());
                return(false);
            }

            parsedArgs.RenderInfo.SrcRoot = converterOptions.SrcRoot;

            // Getting a map for levels by the analyzer type
            IDictionary <AnalyzerType, ISet <uint> > analyzerLevelFilterMap = new Dictionary <AnalyzerType, ISet <uint> >();

            if (converterOptions.AnalyzerLevelFilter != null && converterOptions.AnalyzerLevelFilter.Count > 0 &&
                !Utils.TryParseLevelFilters(converterOptions.AnalyzerLevelFilter, analyzerLevelFilterMap,
                                            out errorMessage))
            {
                return(false);
            }

            parsedArgs.LevelMap = analyzerLevelFilterMap;

            // Getting render types
            ISet <RenderType> renderTypes = new HashSet <RenderType>();

            if (converterOptions.PlogRenderTypes != null && converterOptions.PlogRenderTypes.Count > 0 &&
                !Utils.TryParseRenderFilter(converterOptions.PlogRenderTypes, renderTypes, out errorMessage))
            {
                return(false);
            }

            parsedArgs.RenderTypes        = renderTypes;
            parsedArgs.DisabledErrorCodes = converterOptions.DisabledErrorCodes;

            errorMessage = string.Empty;
            return(true);
        }
Пример #36
0
        public void Parse_strict_bad_input_fails_and_exits_with_verbs_when_get_usage_is_defined()
        {
            string invokedVerb = null;
            object invokedVerbInstance = null;

            var options = new OptionsWithVerbs();
            var testWriter = new StringWriter();

            ReflectionHelper.AssemblyFromWhichToPullInformation = Assembly.GetExecutingAssembly();
            var parser = new CommandLine.Parser(with => with.HelpWriter = testWriter);
            var result = parser.ParseArgumentsStrict(new string[] { "bad", "input" }, options,
                (verb, subOptions) =>
                {
                    invokedVerb = verb;
                    invokedVerbInstance = subOptions;
                },
                () => Console.WriteLine("fake fail"));

            result.Should().BeFalse();

            var helpText = testWriter.ToString();
            Console.WriteLine(helpText);
            var lines = helpText.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
            // Did we really produced all help?
            lines.Should().HaveCount(n => n == 1);
            // Verify just significant output
            lines[0].Trim().Should().Be("verbs help index");

            invokedVerb.Should().Be("bad");
            invokedVerbInstance.Should().BeNull();
        }
Пример #37
0
        public static void Main(string[] args)
        {
            options = new Options();

            CommandLine.Parser parser = new CommandLine.Parser(with => with.HelpWriter = Console.Error);

            parser.ParseArgumentsStrict(args, options, () => Environment.Exit(-2));

            if (options.AccessKey == null || options.SecretKey == null)
            {
                Console.WriteLine(options.GetUsage());
                Environment.Exit(-2);
            }

            try
            {

                // ListVolumes(); // got for testing connectivity

                CheckForScheduledSnapshots();

                CheckForExpiredSnapshots();

            }
            catch (Exception err)
            {
                Console.WriteLine("Error from " + err.Source + ": " + err.Message);
                Environment.Exit(-2);
            }

            Environment.Exit(0);
        }
Пример #38
0
        /// <summary>
        /// 应用程序入口
        /// </summary>
        /// <param name="args">命令行参数</param>
        static void Main(string[] args)
        {
            System.DateTime startTime = System.DateTime.Now;

            //-- 分析命令行参数
            var parser  = new CommandLine.Parser(with => with.HelpWriter = Console.Error);
            var options = new Options();

            if (parser.ParseArgumentsStrict(args, options, () => Environment.Exit(-1)))
            {
                if (options.SourcePath != null)
                {
                    if (!Directory.Exists(ConfigurationManager.AppSettings["DataPointTestCaseJsonFilePath"].ToString()))
                    {
                        Directory.CreateDirectory(ConfigurationManager.AppSettings["DataPointTestCaseJsonFilePath"].ToString());
                    }
                    if (!Directory.Exists(ConfigurationManager.AppSettings["DataPointTestCaseJavaFilePath"].ToString()))
                    {
                        Directory.CreateDirectory(ConfigurationManager.AppSettings["DataPointTestCaseJavaFilePath"].ToString());
                    }

                    FileInfo[] filist = new DirectoryInfo(options.SourcePath).GetFiles("*.xlsx");
                    if (filist.Length > 0)
                    {
                        foreach (FileInfo item in filist)
                        {
                            var DataPoint = item.Name.Replace(item.Extension, "");
                            options.ExcelPath  = item.FullName;
                            options.HeaderRows = 3;
                            options.JsonPath   = Path.Combine(ConfigurationManager.AppSettings["DataPointTestCaseJsonFilePath"].ToString(), DataPoint + ".json");
                            options.JavaPath   = Path.Combine(ConfigurationManager.AppSettings["DataPointTestCaseJavaFilePath"].ToString(), DataPoint + ".java");
                            try
                            {
                                Run(options);
                            }
                            catch (Exception exp)
                            {
                                Console.WriteLine("Error: " + exp.Message);
                            }
                        }
                    }
                    else
                    {
                        Console.WriteLine("Error: Don't find the TestCase Excel file.");
                    }
                }
                else
                {
                    //-- 执行导出操作
                    try
                    {
                        Run(options);
                    }
                    catch (Exception exp)
                    {
                        Console.WriteLine("Error: " + exp.Message);
                    }
                }
            }

            //-- 程序计时
            System.DateTime endTime = System.DateTime.Now;
            System.TimeSpan dur     = endTime - startTime;
            Console.WriteLine(
                string.Format("[{0}]:\t转换完成[{1}毫秒].",
                              Path.GetFileName(options.ExcelPath),
                              dur.Milliseconds)
                );
        }
Пример #39
0
        /// <summary>
        /// The main entry point for the MP2 client application.
        /// </summary>
        private static void Main(params string[] args)
        {
            Thread.CurrentThread.Name = "Main";

            // Parse command line options
            var mpOptions = new CommandLineOptions();
            var parser    = new CommandLine.Parser(with => with.HelpWriter = Console.Out);

            parser.ParseArgumentsStrict(args, mpOptions, () => Environment.Exit(1));

            // Check if another instance is already running
            if (SingleInstanceHelper.IsAlreadyRunning(MUTEX_ID, out _mutex))
            {
                _mutex = null;
                // Set focus on previously running app
                SingleInstanceHelper.SwitchToCurrentInstance(SingleInstanceHelper.SHOW_MP2_CLIENT_MESSAGE);
                // Stop current instance
                Console.Out.WriteLine("Application already running.");
                Environment.Exit(2);
            }

#if !DEBUG
            string logPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), @"Team MediaPortal\MP2-Client\Log");
#endif

            Application.ThreadException += LauncherExceptionHandling.Application_ThreadException;
            AppDomain.CurrentDomain.UnhandledException += LauncherExceptionHandling.CurrentDomain_UnhandledException;
            TaskScheduler.UnobservedTaskException      += LauncherExceptionHandling.TaskScheduler_UnobservedTaskException;

            SystemStateService systemStateService = new SystemStateService();
            ServiceRegistration.Set <ISystemStateService>(systemStateService);
            systemStateService.SwitchSystemState(SystemState.Initializing, false);

            try
            {
#if !DEBUG
                SplashScreen splashScreen = null;
#endif
                ILogger logger = null;
                try
                {
                    // Check if user wants to override the default Application Data location.
                    ApplicationCore.RegisterVitalCoreServices(true, mpOptions.DataDirectory);

#if !DEBUG
                    splashScreen = CreateSplashScreen();
                    splashScreen.ShowSplashScreen();
#endif

                    ApplicationCore.RegisterCoreServices();

                    logger = ServiceRegistration.Get <ILogger>();

#if !DEBUG
                    IPathManager pathManager = ServiceRegistration.Get <IPathManager>();
                    logPath = pathManager.GetPath("<LOG>");
#endif

                    UiExtension.RegisterUiServices();
                }
                catch (Exception e)
                {
                    if (logger != null)
                    {
                        logger.Critical("Error starting application", e);
                    }
                    systemStateService.SwitchSystemState(SystemState.ShuttingDown, true);
                    ServiceRegistration.IsShuttingDown = true;

                    UiExtension.DisposeUiServices();
                    ApplicationCore.DisposeCoreServices();

                    throw;
                }

                // Start the core
                logger.Debug("ApplicationLauncher: Starting application");

                try
                {
                    IPluginManager pluginManager = ServiceRegistration.Get <IPluginManager>();
                    pluginManager.Initialize();
                    pluginManager.Startup(false);
                    ApplicationCore.StartCoreServices();

                    ISkinEngine            skinEngine            = ServiceRegistration.Get <ISkinEngine>();
                    IWorkflowManager       workflowManager       = ServiceRegistration.Get <IWorkflowManager>();
                    IMediaAccessor         mediaAccessor         = ServiceRegistration.Get <IMediaAccessor>();
                    ILocalSharesManagement localSharesManagement = ServiceRegistration.Get <ILocalSharesManagement>();

                    // We have to handle some dependencies here in the start order:
                    // 1) After all plugins are loaded, the SkinEngine can initialize (=load all skin resources)
                    // 2) After the skin resources are loaded, the workflow manager can initialize (=load its states and actions)
                    // 3) Before the main window is shown, the splash screen should be hidden
                    // 4) After the workflow states and actions are loaded, the main window can be shown
                    // 5) After the skinengine triggers the first workflow state/startup screen, the default shortcuts can be registered
                    mediaAccessor.Initialize();         // Independent from other services
                    localSharesManagement.Initialize(); // After media accessor was initialized
                    skinEngine.Initialize();            // 1)
                    workflowManager.Initialize();       // 2)

#if !DEBUG
                    splashScreen.CloseSplashScreen(); // 3)
#endif

                    skinEngine.Startup();                                         // 4)
                    UiExtension.Startup();                                        // 5)

                    ApplicationCore.RegisterDefaultMediaItemAspectTypes().Wait(); // To be done after UI services are running

                    _ipcServer = new IpcServer("Client");
                    _ipcServer.CustomShutdownCallback = () =>
                    {
                        ServiceRegistration.Get <IScreenControl>().Shutdown();
                        return(true);
                    };
                    try
                    {
                        _ipcServer.Open();
                    }
                    catch (Exception ipcEx)
                    {
                        logger.Error(ipcEx);
                    }
                    systemStateService.SwitchSystemState(SystemState.Running, true);

                    if (mpOptions.AutoStart)
                    {
                        StartFocusKeeper();
                    }

                    Application.Run();
                    systemStateService.SwitchSystemState(SystemState.ShuttingDown, true);
                    ServiceRegistration.IsShuttingDown = true; // Block ServiceRegistration from trying to load new services in shutdown phase

                    // 1) Stop UI extensions (Releases all active players, must be done before shutting down SE)
                    // 2) Shutdown SkinEngine (Closes all screens, uninstalls background manager, stops render thread)
                    // 3) Shutdown WorkflowManager (Disposes all models)
                    // 4) Shutdown ImporterWorker
                    // 5) Shutdown PluginManager (Shuts down all plugins)
                    // 6) Remove all services
                    UiExtension.StopUiServices();
                    skinEngine.Shutdown();
                    workflowManager.Shutdown();
                    ServiceRegistration.Get <IImporterWorker>().Shutdown();
                    pluginManager.Shutdown();
                    mediaAccessor.Shutdown();
                    localSharesManagement.Shutdown();
                    ApplicationCore.StopCoreServices();
                }
                catch (Exception e)
                {
                    logger.Critical("Error executing application", e);
                    systemStateService.SwitchSystemState(SystemState.ShuttingDown, true);
                    ServiceRegistration.IsShuttingDown = true;
                }
                finally
                {
                    if (_ipcServer != null)
                    {
                        _ipcServer.Close();
                    }
                    UiExtension.DisposeUiServices();
                    ApplicationCore.DisposeCoreServices();

                    systemStateService.SwitchSystemState(SystemState.Ending, false);
                }
            }
            catch (Exception ex)
            {
#if DEBUG
                ConsoleLogger log = new ConsoleLogger(LogLevel.All, false);
                log.Error(ex);
#else
                UiCrashLogger crash = new UiCrashLogger(logPath);
                crash.CreateLog(ex);
#endif
                systemStateService.SwitchSystemState(SystemState.Ending, false);

                // Release mutex for single instance
                if (_mutex != null)
                {
                    _mutex.ReleaseMutex();
                }

                Application.Exit();
            }
        }
Пример #40
0
    /// <summary>
    /// Either shows the application's main window or inits the application in the system tray.
    /// </summary>
    private void OnStartup(object sender, StartupEventArgs args)
    {
      Thread.CurrentThread.Name = "Main";
      Thread.CurrentThread.SetApartmentState(ApartmentState.STA);

      // Parse command line options
      var mpOptions = new CommandLineOptions();
      var parser = new CommandLine.Parser(with => with.HelpWriter = Console.Out);
      parser.ParseArgumentsStrict(args.Args, mpOptions, () => Environment.Exit(1));

      // Check if another instance is already running
      // If new instance was created by UacHelper previous one, assume that previous one is already closed.
      if (SingleInstanceHelper.IsAlreadyRunning(MUTEX_ID, out _mutex))
      {
        _mutex = null;
        // Set focus on previously running app
        SingleInstanceHelper.SwitchToCurrentInstance(SingleInstanceHelper.SHOW_MP2_SERVICEMONITOR_MESSAGE );
        // Stop current instance
        Console.Out.WriteLine("Application already running.");
        Environment.Exit(2);
      }

      // Make sure we're properly handling exceptions
      DispatcherUnhandledException += OnUnhandledException;
      AppDomain.CurrentDomain.UnhandledException += LauncherExceptionHandling.CurrentDomain_UnhandledException;

      var systemStateService = new SystemStateService();
      ServiceRegistration.Set<ISystemStateService>(systemStateService);
      systemStateService.SwitchSystemState(SystemState.Initializing, false);

#if !DEBUG
      string logPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), @"Team MediaPortal\MP2-ServiceMonitor\Log");
#endif

      try
      {
        ILogger logger = null;
        try
        {
          ApplicationCore.RegisterVitalCoreServices();
          ApplicationCore.RegisterCoreServices();
          logger = ServiceRegistration.Get<ILogger>();

          logger.Debug("Starting Localization");
          Localization localization = new Localization();
          ServiceRegistration.Set<ILocalization>(localization);
          localization.Startup();

          //ApplicationCore.StartCoreServices();

          logger.Debug("UiExtension: Registering ISystemResolver service");
          ServiceRegistration.Set<ISystemResolver>(new SystemResolver());

          logger.Debug("UiExtension: Registering IServerConnectionManager service");
          ServiceRegistration.Set<IServerConnectionManager>(new ServerConnectionManager());

#if !DEBUG
          logPath = ServiceRegistration.Get<IPathManager>().GetPath("<LOG>");
#endif
        }
        catch (Exception e)
        {
          if (logger != null)
            logger.Critical("Error starting application", e);

          systemStateService.SwitchSystemState(SystemState.ShuttingDown, true);
          ServiceRegistration.IsShuttingDown = true;

          ApplicationCore.DisposeCoreServices();

          throw;
        }

        var appController = new AppController();
        ServiceRegistration.Set<IAppController>(appController);

        // Start the application
        logger.Debug("Starting application");
        try
        {
          ServiceRegistration.Get<IServerConnectionManager>().Startup();
          appController.StartUp(mpOptions);
        }
        catch (Exception e)
        {
          logger.Critical("Error executing application", e);
          systemStateService.SwitchSystemState(SystemState.ShuttingDown, true);
          ServiceRegistration.IsShuttingDown = true;
        }
      }
      catch (Exception ex)
      {
#if DEBUG
        var log = new ConsoleLogger(LogLevel.All, false);
        log.Error(ex);
#else
        ServerCrashLogger crash = new ServerCrashLogger(logPath);
        crash.CreateLog(ex);
#endif
        systemStateService.SwitchSystemState(SystemState.Ending, false);
        Current.Shutdown();
      }
    }
Пример #41
0
        public virtual int InitGame(string[] args)
        {
            var options = new Options();
            var parser  = new CommandLine.Parser(with => with.HelpWriter = Console.Error);

            if (parser.ParseArgumentsStrict(args, options, HandleInputError))
            {
                if (options.ModPaths == null &&
                    options.Blueprints == null &&
#if SE
                    options.IngameScripts == null &&
#endif
                    options.Scenarios == null &&
                    options.Worlds == null &&
                    options.Collections == null)
                {
                    if (!options.ClearSteamCloud && !options.ListDLCs)
                    {
                        Console.WriteLine(CommandLine.Text.HelpText.AutoBuild(options).ToString());
                        return(Cleanup(1));
                    }
                }

                // If a "0" or "none" was specified for DLC, that means remove them all.
                if (options.DLCs?.Length > 0 &&
                    (options.DLCs.Contains("0") || options.DLCs.Contains("none", StringComparer.InvariantCultureIgnoreCase)))
                {
                    options.DLCs = new string[0];
                }

                // If a 0 was specified for dependencies, that means remove them all.
                if (options.Dependencies?.Length > 0 && options.Dependencies.Contains((ulong)0))
                {
                    options.Dependencies = new ulong[0];
                }

                // SE requires -appdata, but the commandline dll requires --appdata, so fix it
                for (var idx = 0; idx < args.Length; idx++)
                {
                    if (string.Compare(args[idx], "--appdata", StringComparison.InvariantCultureIgnoreCase) == 0)
                    {
                        args[idx] = "-appdata";
                    }
                }

                m_useModIO = options.ModIO;
                try
                {
                    // Initialize game code
                    InitSandbox(args);
                }
                catch (Exception ex)
                {
                    ex.Log("ERROR: An exception occurred intializing game libraries: ");
                    return(Cleanup(2));
                }

                if (!SteamAPI.IsSteamRunning())
                {
                    MySandboxGame.Log.WriteLineAndConsole("ERROR: * Steam not detected. Is Steam running and not as Admin? *");
                    MySandboxGame.Log.WriteLineAndConsole("* Only compile testing is available. *");
                    MySandboxGame.Log.WriteLineAndConsole("");

                    if (options.Download)
                    {
                        return(Cleanup(3));
                    }

                    options.Upload = false;
                }

                MySandboxGame.Log.WriteLineAndConsole($"{AppName} {Assembly.GetExecutingAssembly().GetName().Version}");

                ProgramBase.CheckForUpdate(MySandboxGame.Log.WriteLineAndConsole);

                MySandboxGame.Log.WriteLineToConsole(string.Empty);
                MySandboxGame.Log.WriteLineAndConsole($"Log file: {MySandboxGame.Log.GetFilePath()}");
                MySandboxGame.Log.WriteLineToConsole(string.Empty);

                // Make sure file paths are properly rooted based on the user's current directory at launch
                MySandboxGame.Log.WriteLineAndConsole($"Relative root: {LaunchDirectory}");

#if SE
                ParameterInfo[] parameters;
                if (options.Compile)
                {
                    // Init ModAPI
                    var initmethod = typeof(MySandboxGame).GetMethod("InitModAPI", BindingFlags.Instance | BindingFlags.NonPublic);
                    MyDebug.AssertRelease(initmethod != null);

                    if (initmethod != null)
                    {
                        parameters = initmethod.GetParameters();
                        MyDebug.AssertRelease(parameters.Count() == 0);

                        if (!(parameters.Count() == 0))
                        {
                            initmethod = null;
                        }
                    }

                    if (initmethod != null)
                    {
                        initmethod.Invoke(m_game, null);
                    }
                    else
                    {
                        MySandboxGame.Log.WriteLineAndConsole(string.Format(Constants.ERROR_Reflection, "InitModAPI"));
                    }
                }
#endif
                ReplaceMethods();

                System.Threading.Tasks.Task <bool> Task;

                if (options.Download)
                {
                    Task = DownloadMods(options);
                }
                else if (options.ClearSteamCloud)
                {
                    Task = ClearSteamCloud(options.DeleteSteamCloudFiles, options.Force);
                }
                else if (options.ListDLCs)
                {
                    Task = System.Threading.Tasks.Task <bool> .Factory.StartNew(() => { ListDLCs(); return(true); });
                }
                else
                {
                    Task = UploadMods(options);
                }

                try
                {
                    // Wait for file transfers to finish (separate thread)
                    while (!Task.Wait(100))
                    {
                        MyGameService.Update();
                    }
                }
                catch (AggregateException ex)
                {
                    MyDebug.AssertRelease(Task.IsFaulted);
                    MyDebug.AssertRelease(ex.InnerException != null);
                    ex.InnerException.Log();
                    return(Cleanup(4));
                }
                catch (Exception ex)
                {
                    ex.Log();
                    return(Cleanup(5));
                }

                // If the task reported any error, return exit code
                if (!Task.Result)
                {
                    return(Cleanup(-1));
                }
            }

            return(Cleanup());
        }
Пример #42
0
        const uint AppId_ME = 333950;      // TODO

        static int Main(string[] args)
        {
            var options = new Options();
            var parser  = new CommandLine.Parser(with => with.HelpWriter = Console.Error);

            if (parser.ParseArgumentsStrict(args, options, () => Environment.Exit(1)))
            {
                // Steam API doesn't initialize correctly if it can't find steam_appid.txt
                if (!File.Exists("steam_appid.txt"))
                {
                    Directory.SetCurrentDirectory(Path.GetDirectoryName(typeof(VRage.FastResourceLock).Assembly.Location) + "\\..");
                }

                if (options.ModPaths == null &&
                    options.Blueprints == null &&
                    options.IngameScripts == null &&
                    options.Scenarios == null &&
                    options.Worlds == null)
                {
                    System.Console.WriteLine(CommandLine.Text.HelpText.AutoBuild(options).ToString());
                    return(1);
                }

                try
                {
                    // Initialize game code
                    InitSandbox(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "SpaceEngineers"));
                }
                catch (Exception ex)
                {
                    MySandboxGame.Log.WriteLineAndConsole(string.Format("An exception occurred intializing game libraries: {0}", ex.Message));
                    MySandboxGame.Log.WriteLineAndConsole(ex.StackTrace);
                    return(2);
                }

                if (MySteam.API == null)
                {
                    MySandboxGame.Log.WriteLineAndConsole("* Steam not detected. Is Steam UAC elevated? *");
                    MySandboxGame.Log.WriteLineAndConsole("* Only compile testing is available. *");
                    MySandboxGame.Log.WriteLineAndConsole("");

                    if (options.Download)
                    {
                        return(3);
                    }

                    options.Upload = false;
                }

                MySandboxGame.Log.WriteLineAndConsole(string.Format("SEWT {0}", Assembly.GetExecutingAssembly().GetName().Version));

                ParameterInfo[] parameters;
                if (options.Compile)
                {
                    // Init ModAPI
                    var initmethod = typeof(MySandboxGame).GetMethod("InitModAPI", BindingFlags.Instance | BindingFlags.NonPublic);
                    MyDebug.AssertDebug(initmethod != null);

                    if (initmethod != null)
                    {
                        parameters = initmethod.GetParameters();
                        MyDebug.AssertDebug(parameters.Count() == 0);

                        if (!(parameters.Count() == 0))
                        {
                            initmethod = null;
                        }
                    }

                    if (initmethod != null)
                    {
                        initmethod.Invoke(m_spacegame, null);
                    }
                    else
                    {
                        MySandboxGame.Log.WriteLineAndConsole(string.Format(Constants.ERROR_Reflection, "InitModAPI"));
                    }
                }

                // Keen's code for WriteAndShareFileBlocking has a UI dependency
                // This method need to be replaced with a custom one, which removes the unnecessary UI code.
                var methodtoreplace = typeof(MySteamWorkshop).GetMethod("WriteAndShareFileBlocking", BindingFlags.Static | BindingFlags.NonPublic);
                var methodtoinject  = typeof(InjectedMethod).GetMethod("WriteAndShareFileBlocking", BindingFlags.Static | BindingFlags.NonPublic);

                MyDebug.AssertDebug(methodtoreplace != null);
                if (methodtoreplace != null)
                {
                    parameters = methodtoreplace.GetParameters();
                    MyDebug.AssertDebug(parameters.Count() == 1);
                    MyDebug.AssertDebug(parameters[0].ParameterType == typeof(string));

                    if (!(parameters.Count() == 1 && parameters[0].ParameterType == typeof(string)))
                    {
                        methodtoreplace = null;
                    }
                }

                if (methodtoreplace != null && methodtoinject != null)
                {
                    MethodUtil.ReplaceMethod(methodtoreplace, methodtoinject);
                }
                else
                {
                    MySandboxGame.Log.WriteLineAndConsole(string.Format(Constants.ERROR_Reflection, "WriteAndShareFileBlocking"));
                }

                System.Threading.Tasks.Task <bool> Task;

                if (options.Download)
                {
                    Task = DownloadMods(options);
                }
                else
                {
                    Task = UploadMods(options);
                }

                try
                {
                    // Wait for file transfers to finish (separate thread)
                    while (!Task.Wait(500))
                    {
                        if (MySteam.API != null)
                        {
                            MySteam.API.RunCallbacks();
                        }
                    }
                }
                catch (AggregateException ex)
                {
                    MyDebug.AssertDebug(Task.IsFaulted);
                    MyDebug.AssertDebug(ex.InnerException != null);
                    var exception = ex.InnerException;
                    MySandboxGame.Log.WriteLineAndConsole("An exception occurred: " + exception.Message);
                    MySandboxGame.Log.WriteLineAndConsole(exception.StackTrace);
                    return(4);
                }

                // If the task reported any error, return exit code
                if (!Task.Result)
                {
                    return(-1);
                }

                // Cleanup
                CleanupSandbox();
            }
            return(0);
        }
Пример #43
0
        public void Parse_strict_bad_input_fails_and_exits_with_verbs()
        {
            string invokedVerb = null;
            object invokedVerbInstance = null;

            var options = new OptionsWithVerbsNoHelp();
            var testWriter = new StringWriter();

            ReflectionHelper.AssemblyFromWhichToPullInformation = Assembly.GetExecutingAssembly();
            var parser = new CommandLine.Parser(with => with.HelpWriter = testWriter);
            var result = parser.ParseArgumentsStrict(new string[] { "bad", "input" }, options,
                (verb, subOptions) =>
                {
                    invokedVerb = verb;
                    invokedVerbInstance = subOptions;
                },
                () => Console.WriteLine("fake fail"));

            result.Should().BeFalse();

            var helpText = testWriter.ToString();
            Console.WriteLine(helpText);
            var lines = helpText.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
            // Did we really produced all help?
            lines.Should().HaveCount(n => n == 8);
            // Verify just significant output
            lines[5].Trim().Should().Be("add       Add file contents to the index.");
            lines[6].Trim().Should().Be("commit    Record changes to the repository.");
            lines[7].Trim().Should().Be("clone     Clone a repository into a new directory.");

            invokedVerb.Should().Be("bad");
            invokedVerbInstance.Should().BeNull();
        }