示例#1
0
    /// <summary>
    /// Performs an update of the mod loader.
    /// </summary>
    public async Task Update()
    {
        if (ApplicationInstanceTracker.GetAllProcesses(out var processes))
        {
            ActionWrappers.ExecuteWithApplicationDispatcher(() =>
            {
                // Accumulate list of processes.
                string allProcessString = $"\n{Resources.UpdateLoaderProcessList.Get()}:";
                foreach (var process in processes)
                {
                    allProcessString += $"\n({process.Id}) {process.ProcessName}";
                }

                Actions.DisplayMessagebox.Invoke(Resources.UpdateLoaderRunningTitle.Get(), Resources.UpdateLoaderRunningMessage.Get() + allProcessString, new Actions.DisplayMessageBoxParams()
                {
                    StartupLocation = Actions.WindowStartupLocation.CenterScreen
                });
            });
        }
        else
        {
            _manager.OnApplySelfUpdate += OnApplySelfUpdate;
            await _manager.PrepareUpdateAsync(_targetVersion, new Progress <double>(d => { Progress = d * 100; }));

            await _manager.StartUpdateAsync(_targetVersion, new OutOfProcessOptions()
            {
                Restart = true
            }, new UpdateOptions()
            {
                CleanupAfterUpdate = true
            });

            Environment.Exit(0);
        }
    }
示例#2
0
        private static void report_version_and_exit_if_requested(string[] args, ChocolateyConfiguration config)
        {
            if (args == null || args.Length == 0)
            {
                return;
            }

            var firstArg = args.FirstOrDefault();

            if (firstArg.is_equal_to("-v") || firstArg.is_equal_to("--version"))
            {
                "chocolatey".Log().Info(ChocolateyLoggers.Important, () => "{0}".format_with(config.Information.ChocolateyProductVersion));
                pause_execution_if_debug();
                Environment.Exit(0);
            }
        }
        /// <summary>
        /// Writes the given object (usually an exception) to disc so that it can be picked up by the CrashManager and send to Hockeyapp.
        /// </summary>
        /// <param name="exception">The object to write (usually an exception)</param>
        /// <param name="terminate">Flag that determines whether the process should be terminated after logging the exception</param>
        /// <remarks>This method controls exactly what is written to disc.  Its really a translation of the ExceptionHandler.saveException
        /// This method doesn't call any java if the exception object isn't a java class so it is safe to call when the mono runtime is no
        /// longer able to invoke JNI methods, for example in the case of a crash in the pure c# managed space.</remarks>
        public static void WriteTrace(object exception, bool terminate = true)
        {
            if (exception is Java.Lang.Exception)
            {
                ExceptionHandler.SaveNativeException(exception as Java.Lang.Exception, exception.ToString(), Java.Lang.Thread.CurrentThread(), _Listener);
            }
            else
            {
                ExceptionHandler.SaveManagedException(Java.Lang.Throwable.FromException(exception as Exception), Java.Lang.Thread.CurrentThread(), _Listener);
            }

            if (terminate)
            {
                Process.GetCurrentProcess().Kill();
                Environment.Exit(10);
            }
        }
示例#4
0
        public void warn_when_admin_needs_elevation(ChocolateyConfiguration config)
        {
            if (config.HelpRequested)
            {
                return;
            }

            var shouldWarn = (!config.Information.IsProcessElevated && config.Information.IsUserAdministrator) ||
                             (!config.Information.IsUserAdministrator && ApplicationParameters.InstallLocation.is_equal_to(ApplicationParameters.CommonAppDataChocolatey));

            if (shouldWarn)
            {
                this.Log().Warn(ChocolateyLoggers.Important, @"Chocolatey detected you are not running from an elevated command shell
 (cmd/powershell).");
            }

            // NOTE: blended options may not have been fully initialized yet
            var timeoutInSeconds = config.PromptForConfirmation ? 0 : 20;

            if (shouldWarn)
            {
                this.Log().Warn(ChocolateyLoggers.Important, @"
 You may experience errors - many functions/packages
 require admin rights. Only advanced users should run choco w/out an
 elevated shell. When you open the command shell, you should ensure 
 that you do so with ""Run as Administrator"" selected. If you are 
 attempting to use Chocolatey in a non-administrator setting, you
 must select a different location other than the default install
 location. See 
 https://chocolatey.org/install#non-administrative-install for details.
");
                var selection = InteractivePrompt.prompt_for_confirmation(@"
 Do you want to continue?", new[] { "yes", "no" },
                                                                          defaultChoice: null,
                                                                          requireAnswer: false,
                                                                          allowShortAnswer: true,
                                                                          shortPrompt: true,
                                                                          timeoutInSeconds: timeoutInSeconds
                                                                          );

                if (selection.is_equal_to("no"))
                {
                    Environment.Exit(-1);
                }
            }
        }
示例#5
0
        public static void Shutdown()
        {
            if (MooNetServer != null)
            {
                Logger.Warn("Shutting down MooNet-Server..");
                MooNetServer.Shutdown();
            }

            if (GameServer != null)
            {
                Logger.Warn("Shutting down Game-Server..");
                GameServer.Shutdown();
            }

            StopWebServices();
            Environment.Exit(0);
        }
示例#6
0
        public static void Shutdown()
        {
            if (MooNetServer != null)
            {
                Logger.Warn("Shutting down MooNet-Server..");
                MooNetServer.Shutdown();
            }

            if (GameServer != null)
            {
                Logger.Warn("Shutting down Game-Server..");
                GameServer.Shutdown();
            }

            // todo: stop webservices.

            Environment.Exit(0);
        }
示例#7
0
        async Task CreateConfiguration()
        {
            if (!Directory.Exists(configurationFolderPath))
            {
                var result = MessageBox.Show("Should a default config file be created?", "Question", MessageBoxButton.YesNo);

                if (result == MessageBoxResult.Yes)
                {
                    CreateConfigurationFolder();
                    await CreateConfigurationFile();

                    MessageBox.Show(
                        "A default configuration file has been created. Adjust the configuration file to your needs and restart your application.", "Information");
                    Process.Start(configurationFilePath);
                }

                Environment.Exit(-1);
            }
        }
示例#8
0
        protected override void Load(ContainerBuilder builder)
        {
            _options.Arrangement = _options.ArrangementWithMode();

            builder.Register <IPipelineLogger>(c => new NLogPipelineLogger(SlugifyTransform.Slugify(_options.Arrangement))).As <IPipelineLogger>().SingleInstance();
            builder.Register <IContext>(c => new PipelineContext(c.Resolve <IPipelineLogger>())).As <IContext>();

            // for now scheduler
            builder.Register(c => new RunTimeSchemaReader(c.Resolve <IContext>())).As <IRunTimeSchemaReader>();
            builder.Register <ISchemaHelper>(ctx => new SchemaHelper(ctx.Resolve <IContext>(), ctx.Resolve <IRunTimeSchemaReader>())).As <ISchemaHelper>();

            // for quartz scheduler
            builder.Register <ILoggerFactoryAdapter>(ctx => new QuartzLogAdaptor(ctx.Resolve <IContext>(), Scheduler.Quartz.Utility.ConvertLevel(ctx.Resolve <IContext>().LogLevel), true, true, false, "o")).As <ILoggerFactoryAdapter>();
            builder.Register(ctx => new QuartzJobFactory(_options, ctx.Resolve <IPipelineLogger>())).As <IJobFactory>().SingleInstance();

            builder.Register <IScheduler>((ctx, p) => {
                if (string.IsNullOrEmpty(_options.Schedule) || _options.Mode != null && _options.Mode.In("init", "check"))
                {
                    return(new NowScheduler(_options, ctx.Resolve <ISchemaHelper>(), ctx.Resolve <IPipelineLogger>()));
                }

                if (_options.Schedule == "internal")
                {
                    var process = ProcessFactory.Create(_options.Arrangement, new Dictionary <string, string>());
                    if (process.Errors().Any())
                    {
                        Console.Error.WriteLine("In order for an internal schedule to work, the arrangement passed in must be valid!");
                        foreach (var error in process.Errors())
                        {
                            Console.Error.WriteLine(error);
                        }
                        Environment.Exit(1);
                    }
                    return(new QuartzCronSchedulerViaInternalSchedule(_options, process.Schedule, ctx.Resolve <IJobFactory>(), ctx.Resolve <ILoggerFactoryAdapter>()));
                }

                return(new QuartzCronSchedulerViaCommandLine(_options, ctx.Resolve <IJobFactory>(), ctx.Resolve <ILoggerFactoryAdapter>()));
            }).As <IScheduler>();
        }
示例#9
0
        public static void ShowExceptionAndExit
        (
            Activity activity,
            Exception exception
        )
        {
            ExceptionClear();

            Context context = /*activity ??*/ Context;

            var dialogBuilder = new AlertDialog.Builder(context)
                                .SetTitle(Resource.String.ApplicationName)
                                .SetMessage(exception.GetAggregatedMessage())
                                .SetPositiveButton
                                (
                Resource.String.AlertCloseButton,

                delegate
            {
                Environment.Exit(-1);
            }
                                );

            //activity.RunOnUiThread
            //(
            //() =>
            //{
            Dialog exceptionDialog = dialogBuilder.Create();

            //if (activity == null)
            {
                exceptionDialog.Window.SetType(WindowManagerTypes.SystemAlert);
            }

            exceptionDialog.Show();
            //}
            //);
        }
示例#10
0
        public void warn_when_admin_needs_elevation(ChocolateyConfiguration config)
        {
            var shouldWarn = (!config.Information.IsProcessElevated && config.Information.IsUserAdministrator);

            if (shouldWarn)
            {
                this.Log().Warn(ChocolateyLoggers.Important, @"Chocolatey detected you are not running from an elevated command shell
 (cmd/powershell).");
            }

            // NOTE: blended options may not have been fully initialized yet
            if (!config.PromptForConfirmation)
            {
                return;
            }

            if (shouldWarn)
            {
                this.Log().Warn(ChocolateyLoggers.Important, @"
 You may experience errors - many functions/packages
 require admin rights. Only advanced users should run choco w/out an
 elevated shell. When you open the command shell, you should ensure 
 that you do so with ""Run as Administrator"" selected.
");
                var selection = InteractivePrompt.prompt_for_confirmation(@"
 Do you want to continue?", new[] { "yes", "no" },
                                                                          defaultChoice: null,
                                                                          requireAnswer: true,
                                                                          allowShortAnswer: true,
                                                                          shortPrompt: true
                                                                          );

                if (selection.is_equal_to("no"))
                {
                    Environment.Exit(-1);
                }
            }
        }
示例#11
0
        private static void ConfigureFlutnetRuntime()
        {
            try
            {
                //
                // Init the runtime using the application key (generated from the flutnet console)
                //
                FlutnetRuntime.Init("TRIAL-APP-KEY");

                //
                // Register the service on the flutnet runtime
                //
                FlutnetRuntime.RegisterPlatformService(new Service1(), "my_service");
                Initialized = true;
            }
            catch (Exception e)
            {
                if (CurrentActivity != null)
                {
                    AlertDialog.Builder builder = new AlertDialog.Builder(CurrentActivity);
                    builder.SetTitle("Fatal Error");
                    builder.SetMessage(e.Message);
                    builder.SetCancelable(false);
                    builder.SetPositiveButton("OK", (sender, args) =>
                    {
                        Process.KillProcess(Process.MyPid());
                        Environment.Exit(0);
                    });

                    AlertDialog dialog = builder.Create();
                    dialog.Show();
                }
                else
                {
                    throw;
                }
            }
        }
示例#12
0
        private static void CheckMemory(Process process, IPipelineLogger logger)
        {
            if (string.IsNullOrEmpty(process.MaxMemory))
            {
                return;
            }

            var context = new PipelineContext(logger, process);

            GC.Collect();
            GC.WaitForPendingFinalizers();

            var bytes = System.Diagnostics.Process.GetCurrentProcess().WorkingSet64.Bytes();

            if (bytes.Megabytes > MaxBytes.Megabytes)
            {
                if (MaxBytes.Megabytes > 0.0)
                {
                    context.Warn($"Process memory has increased from {MaxBytes.Megabytes:#.0} to {bytes.Megabytes:#.0}.");
                }
                MaxBytes = bytes;
            }

            var maxMemory = ByteSize.Parse(process.MaxMemory);

            if (maxMemory.CompareTo(bytes) < 0)
            {
                context.Error($"Process exceeded {maxMemory.Megabytes:#.0} Mb. Current memory is {bytes.Megabytes:#.0} Mb!");
                context.Error($"Process is exiting after running {RunCount} time{RunCount.Plural()}.");
                Environment.Exit(1);
            }
            else
            {
                context.Info($"Process is using {bytes.Megabytes:#.0} Mb of it's max {maxMemory.Megabytes:#.0} Mb allowed.");
                context.Info($"Process has run {RunCount} time{RunCount.Plural()}.");
            }
        }
示例#13
0
        private ICommand find_command(ChocolateyConfiguration config, Container container, bool isConsole, Action <ICommand> parseArgs)
        {
            if (string.IsNullOrWhiteSpace(config.CommandName))
            {
                if (isConsole)
                {
                    Environment.ExitCode = 1;
                }
                return(null);
            }

            var command = ApplicationManager.Instance.FindCommand(config.CommandName);

            if (parseArgs != null)
            {
                parseArgs.Invoke(command);
            }

            if (command.may_require_admin_access())
            {
                warn_when_admin_needs_elevation(config);
            }

            set_source_type(config);
            // guaranteed that all settings are set.
            EnvironmentSettings.set_environment_variables(config);

            this.Log().Debug(() => "Configuration: {0}".format_with(config.ToStringFull()));


            if (isConsole && (config.HelpRequested || config.UnsuccessfulParsing))
            {
                Environment.Exit(config.UnsuccessfulParsing? 1 : 0);
            }

            return(command);
        }
示例#14
0
        protected override void OnUpdateFrame(FrameEventArgs e)
        {
            //base.OnUpdateFrame(e);

            if (DualityApp.ExecContext == DualityApp.ExecutionContext.Terminated)
            {
                if (Build.VERSION.SdkInt >= BuildVersionCodes.Lollipop)
                {
                    (Context as Activity).FinishAndRemoveTask();
                }
                else
                {
                    (Context as Activity).Finish();
                }
                Environment.Exit(0);
                return;
            }

            DualityApp.Update();

#if ENABLE_TOUCH
            ControlScheme.UpdateTouchActions();
#endif
        }
示例#15
0
        private ICommand find_command(ChocolateyConfiguration config, Container container, bool isConsole, Action <ICommand> parseArgs)
        {
            var commands = container.GetAllInstances <ICommand>();
            var command  = commands.Where((c) =>
            {
                var attributes = c.GetType().GetCustomAttributes(typeof(CommandForAttribute), false);
                return(attributes.Cast <CommandForAttribute>().Any(attribute => attribute.CommandName.is_equal_to(config.CommandName)));
            }).FirstOrDefault();

            if (command == null)
            {
                //todo add a search among other location/extensions for the command
                if (!string.IsNullOrWhiteSpace(config.CommandName))
                {
                    throw new Exception("Could not find a command registered that meets '{0}'".format_with(config.CommandName));
                }

                if (isConsole)
                {
                    Environment.ExitCode = 1;
                }
            }
            else
            {
                if (command.may_require_admin_access())
                {
                    warn_when_admin_needs_elevation(config);
                }

                if (parseArgs != null)
                {
                    parseArgs.Invoke(command);
                }

                set_source_type(config);
                // guaranteed that all settings are set.
                EnvironmentSettings.set_environment_variables(config);

                this.Log().Debug(() => "Configuration: {0}".format_with(config.ToString()));


                if (isConsole && config.HelpRequested)
                {
#if DEBUG
                    Console.WriteLine("Press enter to continue...");
                    Console.ReadKey();
#endif
                    Environment.Exit(1);
                }

                var token = Assembly.GetExecutingAssembly().get_public_key_token();
                if (string.IsNullOrWhiteSpace(token) || !token.is_equal_to(ApplicationParameters.OfficialChocolateyPublicKey))
                {
                    if (!config.AllowUnofficialBuild)
                    {
                        throw new Exception(@"
Custom unofficial builds are not allowed by default.
 To override this behavior, explicitly set --allow-unofficial.
 See the help menu (choco -h) for options.");
                    }
                    else
                    {
                        this.Log().Warn(ChocolateyLoggers.Important, @"
Chocolatey is not an official build (bypassed with --allow-unofficial).
 If you are seeing this message and it is not expected, your system may 
 now be in a bad state. Only official builds are to be trusted.
"
                                        );
                    }
                }

                if (config.Noop)
                {
                    if (config.RegularOutput)
                    {
                        this.Log().Info("_ {0}:{1} - Noop Mode _".format_with(ApplicationParameters.Name, command.GetType().Name));
                    }

                    command.noop(config);
                    return(null);
                }
            }
            return(command);
        }
示例#16
0
文件: Program.cs 项目: Cubix651/choco
        // ReSharper disable InconsistentNaming
        private static void Main(string[] args)
        // ReSharper restore InconsistentNaming
        {
            try
            {
                add_assembly_resolver();

                string loggingLocation = ApplicationParameters.LoggingLocation;
                //no file system at this point
                if (!Directory.Exists(loggingLocation))
                {
                    Directory.CreateDirectory(loggingLocation);
                }

                Log4NetAppenderConfiguration.configure(loggingLocation);
                Bootstrap.initialize();
                Bootstrap.startup();
                var license   = License.validate_license();
                var container = SimpleInjectorContainer.Container;

                "LogFileOnly".Log().Info(() => "".PadRight(60, '='));

                var config     = container.GetInstance <ChocolateyConfiguration>();
                var fileSystem = container.GetInstance <IFileSystem>();

                var warnings = new List <string>();

                ConfigurationBuilder.set_up_configuration(
                    args,
                    config,
                    container,
                    license,
                    warning => { warnings.Add(warning); }
                    );
                Config.initialize_with(config);

                report_version_and_exit_if_requested(args, config);

                trap_exit_scenarios(config);

                warn_on_nuspec_or_nupkg_usage(args, config);

                if (config.RegularOutput)
                {
#if DEBUG
                    "chocolatey".Log().Info(ChocolateyLoggers.Important, () => "{0} v{1}{2} (DEBUG BUILD)".format_with(ApplicationParameters.Name, config.Information.ChocolateyProductVersion, license.is_licensed_version() ? " {0}".format_with(license.LicenseType) : string.Empty));
#else
                    if (config.Information.ChocolateyVersion == config.Information.ChocolateyProductVersion && args.Any())
                    {
                        "LogFileOnly".Log().Info(() => "{0} v{1}{2}".format_with(ApplicationParameters.Name, config.Information.ChocolateyProductVersion, license.is_licensed_version() ? " {0}".format_with(license.LicenseType) : string.Empty));
                    }
                    else
                    {
                        "chocolatey".Log().Info(ChocolateyLoggers.Important, () => "{0} v{1}{2}".format_with(ApplicationParameters.Name, config.Information.ChocolateyProductVersion, license.is_licensed_version() ? " {0}".format_with(license.LicenseType) : string.Empty));
                    }
#endif
                    if (args.Length == 0)
                    {
                        "chocolatley".Log().Info(ChocolateyLoggers.Important, () => "Please run 'choco -?' or 'choco <command> -?' for help menu.");
                    }
                }

                if (warnings.Count != 0 && config.RegularOutput)
                {
                    foreach (var warning in warnings.or_empty_list_if_null())
                    {
                        "chocolatey".Log().Warn(ChocolateyLoggers.Important, warning);
                    }
                }

                if (config.HelpRequested || config.UnsuccessfulParsing)
                {
                    pause_execution_if_debug();
                    Environment.Exit(config.UnsuccessfulParsing? 1 : 0);
                }

                Log4NetAppenderConfiguration.set_logging_level_debug_when_debug(config.Debug, excludeLoggerName: "{0}LoggingColoredConsoleAppender".format_with(ChocolateyLoggers.Verbose.to_string()));
                Log4NetAppenderConfiguration.set_verbose_logger_when_verbose(config.Verbose, config.Debug, "{0}LoggingColoredConsoleAppender".format_with(ChocolateyLoggers.Verbose.to_string()));
                Log4NetAppenderConfiguration.set_trace_logger_when_trace(config.Trace, "{0}LoggingColoredConsoleAppender".format_with(ChocolateyLoggers.Trace.to_string()));
                "chocolatey".Log().Debug(() => "{0} is running on {1} v {2}".format_with(ApplicationParameters.Name, config.Information.PlatformType, config.Information.PlatformVersion.to_string()));
                //"chocolatey".Log().Debug(() => "Command Line: {0}".format_with(Environment.CommandLine));

                remove_old_chocolatey_exe(fileSystem);

                AssemblyFileExtractor.extract_all_resources_to_relative_directory(fileSystem, Assembly.GetAssembly(typeof(Program)), ApplicationParameters.InstallLocation, new List <string>(), "chocolatey.console");
                //refactor - thank goodness this is temporary, cuz manifest resource streams are dumb
                IList <string> folders = new List <string>
                {
                    "helpers",
                    "functions",
                    "redirects",
                    "tools"
                };
                AssemblyFileExtractor.extract_all_resources_to_relative_directory(fileSystem, Assembly.GetAssembly(typeof(ChocolateyResourcesAssembly)), ApplicationParameters.InstallLocation, folders, ApplicationParameters.ChocolateyFileResources);

                var application = new ConsoleApplication();
                application.run(args, config, container);
            }
            catch (Exception ex)
            {
                if (ApplicationParameters.is_debug_mode_cli_primitive())
                {
                    "chocolatey".Log().Error(() => "{0} had an error occur:{1}{2}".format_with(
                                                 ApplicationParameters.Name,
                                                 Environment.NewLine,
                                                 ex.ToString()));
                }
                else
                {
                    "chocolatey".Log().Error(ChocolateyLoggers.Important, () => "{0}".format_with(ex.Message));
                }

                Environment.ExitCode = 1;
            }
            finally
            {
                "chocolatey".Log().Debug(() => "Exiting with {0}".format_with(Environment.ExitCode));
#if DEBUG
                "chocolatey".Log().Info(() => "Exiting with {0}".format_with(Environment.ExitCode));
#endif
                pause_execution_if_debug();
                Bootstrap.shutdown();
                Environment.Exit(Environment.ExitCode);
            }
        }
示例#17
0
 public static void Exit(int exitCode)
 {
     BeforeClose();
     Environment.Exit(exitCode);
 }
示例#18
0
        static void Main(string[] args)
        {
            var options = new Options();
            var modifed = new List <string>();

            if (args != null)
            {
                if (args.Length == 1 && !args[0].StartsWith("-"))
                {
                    modifed.Add("-f");
                    modifed.Add(args[0]);
                }
                else
                {
                    modifed.AddRange(args);
                }
            }

            if (!CommandLine.Parser.Default.ParseArguments(modifed.ToArray(), options))
            {
                Environment.ExitCode = Error;
                return;
            }

            var request = new Request(options.File)
            {
                Configuration = options.Configuration ?? "default.xml",
                Types         = options.Types,
                View          = options.Table,
                Provider      = options.Provider,
                Server        = options.Server,
                Database      = options.Database,
                Schema        = options.Schema,
                User          = options.User,
                Password      = options.Password,
                Port          = options.Port
            };

            if (!request.IsValid())
            {
                Console.Error.WriteLine(request.Message);
                Environment.Exit(Error);
            }

            try {
                using (var bootstrapper = new Bootstrapper(request)) {
                    var cfg = bootstrapper.Resolve <Cfg>();

                    if (cfg.Errors().Any())
                    {
                        foreach (var error in cfg.Errors())
                        {
                            Console.Error.WriteLine(error);
                            Environment.ExitCode = Error;
                        }
                    }
                    else
                    {
                        var response = bootstrapper.Resolve <Importer>().Import();
                        if (response.Records != 0)
                        {
                            return;
                        }
                        Console.Error.WriteLine("Did not import any records!");
                        Environment.ExitCode = Error;
                    }
                }
            } catch (Exception ex) {
                Console.Error.WriteLine(ex.Message);
                Environment.ExitCode = Error;
            }

            Environment.ExitCode = 0;
        }
示例#19
0
        /// <summary>
        /// Writes the given object (usually an exception) to disc so that it can be picked up by the CrashManager and send to Hockeyapp.
        /// </summary>
        /// <param name="exception">The object to write (usually an exception)</param>
        /// <param name="terminate">Flag that determines whether the process should be terminated after logging the exception</param>
        /// <remarks>This method controls exactly what is written to disc.  Its really a translation of the ExceptionHandler.saveException
        /// This method doesn't call any java if the exception object isn't a java class so it is safe to call when the mono runtime is no
        /// longer able to invoke JNI methods, for example in the case of a crash in the pure c# managed space.</remarks>
        public static void WriteTrace(object exception, bool terminate)
        {
            //if the exception came from java, then we should be able to invoke it
            if (exception is Java.Lang.Exception)
            {
                ExceptionHandler.SaveException(exception as Java.Lang.Exception, _Listener);
            }
            else
            {
                var date     = DateTime.Now;
                var filename = Guid.NewGuid().ToString();
                var path     = Path.Combine(_FilesPath, filename + ".stacktrace");
                Console.WriteLine("Writing unhandled exception to: {0}", path);
                try
                {
                    using (var f = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None))
                        using (var sw = new StreamWriter(f))
                        {
                            // Write the stacktrace to disk
                            sw.WriteLine("Package: {0}", _AppPackage);
                            sw.WriteLine("Version: {0}", _AppVersion);
                            if (_IncludeDeviceData)
                            {
                                sw.WriteLine("Android: {0}", _AndroidVersion);
                                sw.WriteLine("Manufacturer: {0}", _PhoneManufacturer);
                                sw.WriteLine("Model: {0}", _PhoneModel);
                            }
                            sw.WriteLine("Date: {0}", date);
                            sw.WriteLine();
                            //make sure there is something actually on disk
                            sw.Flush();
                            try
                            {
                                if (!(exception is Exception))
                                {
                                    sw.WriteLine(exception);
                                }
                                else
                                {
                                    while ((exception as AggregateException) != null)
                                    {
                                        exception = (exception as AggregateException).InnerException;
                                    }

                                    var e     = (Exception)exception;
                                    var trace = e.StackTrace;
                                    if (trace == null)
                                    {
                                        sw.WriteLine(e);
                                    }
                                    else
                                    {
                                        sw.WriteLine("{0}: {1}", e.GetType().FullName, e.Message);
                                        foreach (Match m in _StackTraceLine.Matches(trace))
                                        {
                                            var method = m.Groups[1].Value;
                                            if (AppNamespaces != null)
                                            {
                                                //use an application provided list of classes to determine which namespaces
                                                //should be mapped into the package name so hockey app can pick out the correct
                                                //top stacktrace line.  It unfortunately means you end up with an extra copy of
                                                //package name at the beginning of your c# crash traces
                                                foreach (var prefix in AppNamespaces)
                                                {
                                                    if (method.StartsWith(prefix, StringComparison.OrdinalIgnoreCase))
                                                    {
                                                        method = _AppPackage + "." + method;
                                                        break;
                                                    }
                                                }
                                            }
                                            else
                                            {
                                                //default to things that don't match mono/android/java, again, this forces an extra copy of
                                                //package name at the beginning of your c# crash traces
                                                if (!method.StartsWith("mono", StringComparison.OrdinalIgnoreCase) &&
                                                    !method.StartsWith("android", StringComparison.OrdinalIgnoreCase) &&
                                                    !method.StartsWith("system", StringComparison.OrdinalIgnoreCase) &&
                                                    !method.StartsWith("java", StringComparison.OrdinalIgnoreCase))
                                                {
                                                    method = _AppPackage + "." + method;
                                                }
                                            }
                                            //this forces the arguments part to look more like the file line number part that
                                            //android stack traces normally have
                                            var arguments = m.Groups[2].Value.Trim();
                                            arguments = arguments.Replace(' ', '_');
                                            arguments = arguments.Replace(',', '_');

                                            sw.WriteLine("\tat {0}({1}.args:1337)", method, arguments);
                                        }
                                    }
                                }
                            }
                            catch (Exception e)
                            {
                                // log something just in case something triggers the null refrence with the attached exception
                                // see https://bugzilla.xamarin.com/show_bug.cgi?id=10379
                                sw.WriteLine();
                                sw.WriteLine("Exception writing exception: {0}", e);
                                throw new Exception("Problem writing exception", e);
                            }
                            //make sure there is something actually on disk
                            sw.Flush();
                            if (_Listener != null)
                            {
                                try
                                {
                                    File.WriteAllText(Path.Combine(_FilesPath, filename + ".user"), ClipString(_Listener.UserID), Encoding.UTF8);
                                }
                                catch (Exception)
                                {
                                    if (_User != null)
                                    {
                                        sw.WriteLine();
                                        sw.WriteLine("UserId was cached");
                                        File.WriteAllText(Path.Combine(_FilesPath, filename + ".user"), ClipString(_User),
                                                          Encoding.UTF8);
                                    }
                                }
                                try
                                {
                                    File.WriteAllText(Path.Combine(_FilesPath, filename + ".contact"), ClipString(_Listener.Contact), Encoding.UTF8);
                                }
                                catch (Exception)
                                {
                                    if (_Contact != null)
                                    {
                                        sw.WriteLine();
                                        sw.WriteLine("Contact was cached");

                                        File.WriteAllText(Path.Combine(_FilesPath, filename + ".contact"), ClipString(_Contact), Encoding.UTF8);
                                    }
                                }
                                try
                                {
                                    File.WriteAllText(Path.Combine(_FilesPath, filename + ".description"), _Listener.Description, Encoding.UTF8);
                                }
                                catch (Exception)
                                {
                                    if (AllowCachedDescription && _Description != null)
                                    {
                                        sw.WriteLine();
                                        sw.WriteLine("Description was cached");
                                        File.WriteAllText(Path.Combine(_FilesPath, filename + ".description"), _Description, Encoding.UTF8);
                                    }
                                }
                            }
                        }
                }
                catch (Exception another)
                {
                    Console.WriteLine("Error saving exception stacktrace! {0}", another);
                }
            }

            if (terminate)
            {
                Process.GetCurrentProcess().Kill();
                Environment.Exit(10);
            }
        }
示例#20
0
        // ReSharper disable InconsistentNaming
        private static void Main(string[] args)
        // ReSharper restore InconsistentNaming
        {
            try
            {
                string loggingLocation = ApplicationParameters.LoggingLocation;
                //no file system at this point
                if (!Directory.Exists(loggingLocation))
                {
                    Directory.CreateDirectory(loggingLocation);
                }

                Log4NetAppenderConfiguration.configure(loggingLocation);
                Bootstrap.initialize();
                Bootstrap.startup();

                var license = LicenseValidation.validate();
                if (license.is_licensed_version())
                {
                    try
                    {
                        var licensedAssembly = Assembly.LoadFile(ApplicationParameters.LicensedAssemblyLocation);
                        license.AssemblyLoaded = true;
                        license.Assembly       = licensedAssembly;
                        license.Version        = VersionInformation.get_current_informational_version(licensedAssembly);
                        Type licensedComponent = licensedAssembly.GetType(ApplicationParameters.LicensedComponentRegistry, throwOnError: false, ignoreCase: true);
                        SimpleInjectorContainer.add_component_registry_class(licensedComponent);
                    }
                    catch (Exception ex)
                    {
                        "chocolatey".Log().Error(
                            @"Error when attempting to load chocolatey licensed assembly. Ensure
 that chocolatey.licensed.dll exists at 
 '{0}'.
 The error message itself may be helpful as well:{1} {2}".format_with(
                                ApplicationParameters.LicensedAssemblyLocation,
                                Environment.NewLine,
                                ex.Message
                                ));
                    }
                }
                var container = SimpleInjectorContainer.Container;

                var config     = container.GetInstance <ChocolateyConfiguration>();
                var fileSystem = container.GetInstance <IFileSystem>();

                var warnings = new List <string>();

                ConfigurationBuilder.set_up_configuration(
                    args,
                    config,
                    container,
                    license,
                    warning => { warnings.Add(warning); }
                    );
                Config.initialize_with(config);

                report_version_and_exit_if_requested(args, config);

                trap_exit_scenarios(config);

                if (config.RegularOutput)
                {
                    "logfile".Log().Info(() => "".PadRight(60, '='));
#if DEBUG
                    "chocolatey".Log().Info(ChocolateyLoggers.Important, () => "{0} v{1}{2} (DEBUG BUILD)".format_with(ApplicationParameters.Name, config.Information.ChocolateyProductVersion, license.is_licensed_version() ? " {0}".format_with(license.LicenseType) : string.Empty));
#else
                    if (config.Information.ChocolateyVersion == config.Information.ChocolateyProductVersion && args.Any())
                    {
                        "logfile".Log().Info(() => "{0} v{1}{2}".format_with(ApplicationParameters.Name, config.Information.ChocolateyProductVersion, license.is_licensed_version() ? " {0}".format_with(license.LicenseType) : string.Empty));
                    }
                    else
                    {
                        "chocolatey".Log().Info(ChocolateyLoggers.Important, () => "{0} v{1}{2}".format_with(ApplicationParameters.Name, config.Information.ChocolateyProductVersion, license.is_licensed_version() ? " {0}".format_with(license.LicenseType) : string.Empty));
                    }
#endif
                }

                if (warnings.Count != 0 && config.RegularOutput)
                {
                    foreach (var warning in warnings.or_empty_list_if_null())
                    {
                        "chocolatey".Log().Warn(ChocolateyLoggers.Important, warning);
                    }
                }

                if (config.HelpRequested)
                {
                    pause_execution_if_debug();
                    Environment.Exit(-1);
                }

                Log4NetAppenderConfiguration.set_logging_level_debug_when_debug(config.Debug, excludeLoggerName: "{0}LoggingColoredConsoleAppender".format_with(ChocolateyLoggers.Verbose.to_string()));
                Log4NetAppenderConfiguration.set_verbose_logger_when_verbose(config.Verbose, config.Debug, "{0}LoggingColoredConsoleAppender".format_with(ChocolateyLoggers.Verbose.to_string()));
                "chocolatey".Log().Debug(() => "{0} is running on {1} v {2}".format_with(ApplicationParameters.Name, config.Information.PlatformType, config.Information.PlatformVersion.to_string()));
                //"chocolatey".Log().Debug(() => "Command Line: {0}".format_with(Environment.CommandLine));

                remove_old_chocolatey_exe(fileSystem);

                //refactor - thank goodness this is temporary, cuz manifest resource streams are dumb
                IList <string> folders = new List <string>
                {
                    "helpers",
                    "functions",
                    "redirects",
                    "tools"
                };
                AssemblyFileExtractor.extract_all_resources_to_relative_directory(fileSystem, Assembly.GetAssembly(typeof(ChocolateyResourcesAssembly)), ApplicationParameters.InstallLocation, folders, ApplicationParameters.ChocolateyFileResources);

                var application = new ConsoleApplication();
                application.run(args, config, container);
            }
            catch (Exception ex)
            {
                var debug = false;
                // no access to the good stuff here, need to go a bit primitive in parsing args
                foreach (var arg in args.or_empty_list_if_null())
                {
                    if (arg.Contains("debug") || arg.is_equal_to("-d") || arg.is_equal_to("/d"))
                    {
                        debug = true;
                        break;
                    }
                }

                if (debug)
                {
                    "chocolatey".Log().Error(() => "{0} had an error occur:{1}{2}".format_with(
                                                 ApplicationParameters.Name,
                                                 Environment.NewLine,
                                                 ex.ToString()));
                }
                else
                {
                    "chocolatey".Log().Error(ChocolateyLoggers.Important, () => "{0}".format_with(ex.Message));
                }

                Environment.ExitCode = 1;
            }
            finally
            {
                "chocolatey".Log().Debug(() => "Exiting with {0}".format_with(Environment.ExitCode));
#if DEBUG
                "chocolatey".Log().Info(() => "Exiting with {0}".format_with(Environment.ExitCode));
#endif
                pause_execution_if_debug();
                Bootstrap.shutdown();

                Environment.Exit(Environment.ExitCode);
            }
        }
示例#21
0
        static void Main(string[] args)
        {
            // supply three parameters to make the sample work: the hostname of the XPCO Management Server and the username and password
            // of the account that will login to the system.

            if (args.Length != 3)
            {
                Console.WriteLine("You must supply exactly three parameters: Hostname of XPCO Management Server, username and password");
                Environment.Exit(1);
            }

            var uriBuilder = new UriBuilder(args[0]);
            var serverUri  = uriBuilder.Uri;
            var userName   = args[1];
            var password   = args[2];

            MultiEnvironment.InitializeUsingUserContext();

            // Remember to set the boolean parameter to true or false depending in whether the user is in AD.
            var userContext = MultiEnvironment.CreateSingleServerUserContext(userName, password, true, serverUri);

            bool loginSucceeded = MultiEnvironment.LoginUserContext(userContext);

            if (loginSucceeded == false)
            {
                Console.WriteLine("Failed to login to: " + serverUri);
                Console.WriteLine("");
                Console.WriteLine("Press any key");
                Console.ReadKey();
                Environment.Exit(1);
            }

            // Start new status sessions to an entire system with (possibly) multiple recording servers.
            var multiSession = new SystemStatusClient(userContext.Configuration.ServerFQID);

            // Register eventhandlers for the events we are interested in
            multiSession.EventFired             += EventFiredHandler;
            multiSession.ConnectionStateChanged += MultiSessionOnConnectionStateChanged;
            multiSession.ConfigurationChanged   += MultiSessionOnConfigurationChanged;
            multiSession.CameraStateChanged     += MultiSessionOnCameraStateChanged;
            //multiSession.SpeakerStateChanged += ...

            // Start the sessions
            multiSession.CreateAndStartSessions();

            var result = multiSession.GetAllStatusEventMessages();


            // Register for particular events. Feel free to add identifiers for other events.
            // IMPORTANT: The sessions must be started using the CreateAndStartSessions() method before you can subscribe to any events.
            multiSession.SetSubscribedEventsOnCreatedSessions(new HashSet <Guid>
            {
                KnownStatusEvents.MotionStarted,
                KnownStatusEvents.MotionStopped
            });

            // Subscribe to receive notification when the configuration has changed.
            multiSession.SubscribeToConfigurationChanges(true);

            // Subscribe to state changes on all devices of type camera.
            multiSession.AddSubscriptionsToDevicesOfKindOnCreatedSessions(Kind.Camera);

            Console.ReadKey();

            // Shut down all sessions nicely.
            multiSession.StopAndRemoveSessions();
        }
示例#22
0
 public void Exit(int exitCode)
 {
     Env.Exit(exitCode);
 }
示例#23
0
// ReSharper disable InconsistentNaming
        private static void Main(string[] args)
// ReSharper restore InconsistentNaming
        {
            try
            {
                string loggingLocation = ApplicationParameters.LoggingLocation;
                //no file system at this point
                if (!Directory.Exists(loggingLocation))
                {
                    Directory.CreateDirectory(loggingLocation);
                }

                Log4NetAppenderConfiguration.configure(loggingLocation);
                Bootstrap.initialize();
                Bootstrap.startup();

                var container  = SimpleInjectorContainer.Container;
                var config     = container.GetInstance <ChocolateyConfiguration>();
                var fileSystem = container.GetInstance <IFileSystem>();

                var warnings = new List <string>();

                ConfigurationBuilder.set_up_configuration(
                    args,
                    config,
                    fileSystem,
                    container.GetInstance <IXmlService>(),
                    warning => { warnings.Add(warning); }
                    );
                Config.initialize_with(config);

                report_version_and_exit_if_requested(args, config);

                trap_exit_scenarios(config);

                if (config.RegularOutput)
                {
                    "logfile".Log().Info(() => "".PadRight(60, '='));
#if DEBUG
                    "chocolatey".Log().Info(ChocolateyLoggers.Important, () => "{0} v{1} (DEBUG BUILD)".format_with(ApplicationParameters.Name, config.Information.ChocolateyProductVersion));
#else
                    "chocolatey".Log().Info(ChocolateyLoggers.Important, () => "{0} v{1}".format_with(ApplicationParameters.Name, config.Information.ChocolateyProductVersion));
#endif
                }


                if (warnings.Count != 0 && config.RegularOutput)
                {
                    foreach (var warning in warnings.or_empty_list_if_null())
                    {
                        "chocolatey".Log().Warn(ChocolateyLoggers.Important, warning);
                    }
                }

                if (config.HelpRequested)
                {
                    pause_execution_if_debug();
                    Environment.Exit(-1);
                }

                Log4NetAppenderConfiguration.set_verbose_logger_when_verbose(config.Verbose, ChocolateyLoggers.Verbose.to_string());
                Log4NetAppenderConfiguration.set_logging_level_debug_when_debug(config.Debug);
                "chocolatey".Log().Debug(() => "{0} is running on {1} v {2}".format_with(ApplicationParameters.Name, config.Information.PlatformType, config.Information.PlatformVersion.to_string()));
                //"chocolatey".Log().Debug(() => "Command Line: {0}".format_with(Environment.CommandLine));

                warn_when_admin_needs_elevation(config);
                remove_old_chocolatey_exe(fileSystem);

                LicenseValidation.validate(fileSystem);

                //refactor - thank goodness this is temporary, cuz manifest resource streams are dumb
                IList <string> folders = new List <string>
                {
                    "helpers",
                    "functions",
                    "redirects",
                    "tools"
                };
                AssemblyFileExtractor.extract_all_resources_to_relative_directory(fileSystem, Assembly.GetAssembly(typeof(ChocolateyResourcesAssembly)), ApplicationParameters.InstallLocation, folders, ApplicationParameters.ChocolateyFileResources);

                var application = new ConsoleApplication();
                application.run(args, config, container);
            }
            catch (Exception ex)
            {
                var debug = false;
                // no access to the good stuff here, need to go a bit primitive in parsing args
                foreach (var arg in args.or_empty_list_if_null())
                {
                    if (arg.Contains("debug") || arg.is_equal_to("-d") || arg.is_equal_to("/d"))
                    {
                        debug = true;
                        break;
                    }
                }

                if (debug)
                {
                    "chocolatey".Log().Error(() => "{0} had an error occur:{1}{2}".format_with(
                                                 ApplicationParameters.Name,
                                                 Environment.NewLine,
                                                 ex.ToString()));
                }
                else
                {
                    "chocolatey".Log().Error(ChocolateyLoggers.Important, () => "{0}".format_with(ex.Message));
                }

                Environment.ExitCode = 1;
            }
            finally
            {
                "chocolatey".Log().Debug(() => "Exiting with {0}".format_with(Environment.ExitCode));
#if DEBUG
                "chocolatey".Log().Info(() => "Exiting with {0}".format_with(Environment.ExitCode));
#endif
                pause_execution_if_debug();
                Bootstrap.shutdown();

                Environment.Exit(Environment.ExitCode);
            }
        }
示例#24
0
文件: Program.cs 项目: tapika/swupd
        // ReSharper disable InconsistentNaming
        private static void Main(string[] args)
        // ReSharper restore InconsistentNaming
        {
            try
            {
                Action failLogInit = () =>
                {
                    Log.InitializeWith <NLogLog>();
                    LogService.Instance.configure();
                };

                var config = Config.get_configuration_settings();
                if (new ChocolateyOptionSet().Parse(args, new ChocolateyStartupCommand(), config, failLogInit))
                {
                    Environment.Exit(config.UnsuccessfulParsing ? 1 : 0);
                }

                string loggingLocation = ApplicationParameters.LoggingLocation;
                if (!Directory.Exists(loggingLocation))
                {
                    Directory.CreateDirectory(loggingLocation);
                }

                LogService.Instance.configure(loggingLocation);
                Bootstrap.initialize();
                Bootstrap.startup();
                //LogService.Test();
                var container = SimpleInjectorContainer.Container;

                "LogFileOnly".Log().Info(() => "".PadRight(60, '='));

                var fileSystem = container.GetInstance <IFileSystem>();

                var warnings = new List <string>();

                if (!ConfigurationBuilder.set_up_configuration(
                        args,
                        config,
                        container,
                        warning => { warnings.Add(warning); }
                        ))
                {
                    Environment.Exit(config.UnsuccessfulParsing ? 1 : 0);
                }

                if (config.Features.LogWithoutColor)
                {
                    LogService.Instance.enableColors(false);
                }

                if (!string.IsNullOrWhiteSpace(config.AdditionalLogFileLocation))
                {
                    LogService.Instance.configureAdditionalLogFile(fileSystem.get_full_path(config.AdditionalLogFileLocation));
                }

                report_version_and_exit_if_requested(args, config);

                trap_exit_scenarios(config);

                warn_on_nuspec_or_nupkg_usage(args, config);

                if (config.RegularOutput)
                {
                    "chocolatey".Log().Info(ChocolateyLoggers.Important, () => "{0} v{1}".format_with(ApplicationParameters.Name, config.Information.ChocolateyProductVersion));
                    if (args.Length == 0)
                    {
                        "chocolatey".Log().Info(ChocolateyLoggers.Important, () => "Please run 'choco -?' or 'choco <command> -?' for help menu.");
                    }
                }

                if (warnings.Count != 0 && config.RegularOutput)
                {
                    foreach (var warning in warnings.or_empty_list_if_null())
                    {
                        "chocolatey".Log().Warn(ChocolateyLoggers.Important, warning);
                    }
                }

                if (config.HelpRequested || config.UnsuccessfulParsing)
                {
                    Environment.Exit(config.UnsuccessfulParsing ? 1 : 0);
                }

                LogService.Instance.adjustLogLevels(config.Debug, config.Verbose, config.Trace);
                "chocolatey".Log().Debug(() => "{0} is running on {1} v {2}".format_with(ApplicationParameters.Name, config.Information.PlatformType, config.Information.PlatformVersion.to_string()));
                //"chocolatey".Log().Debug(() => "Command Line: {0}".format_with(Environment.CommandLine));

                remove_old_chocolatey_exe(fileSystem);

                AssemblyFileExtractor.extract_all_resources_to_relative_directory(fileSystem, Assembly.GetAssembly(typeof(Program)), ApplicationParameters.InstallLocation, new List <string>(), "chocolatey.console", throwError: false);
                //refactor - thank goodness this is temporary, cuz manifest resource streams are dumb
                IList <string> folders = new List <string>
                {
                    "helpers",
                    "functions",
                    "redirects",
                    "tools"
                };
                AssemblyFileExtractor.extract_all_resources_to_relative_directory(fileSystem, Assembly.GetAssembly(typeof(ChocolateyResourcesAssembly)), ApplicationParameters.InstallLocation, folders, ApplicationParameters.ChocolateyFileResources, throwError: false);
                var application = new ConsoleApplication();
                application.run(args, config, container);
            }
            catch (Exception ex)
            {
                if (ApplicationParameters.is_debug_mode_cli_primitive())
                {
                    "chocolatey".Log().Error(() => "{0} had an error occur:{1}{2}".format_with(
                                                 ApplicationParameters.Name,
                                                 Environment.NewLine,
                                                 ex.ToString()));
                }
                else
                {
                    "chocolatey".Log().Error(ChocolateyLoggers.Important, () => "{0}".format_with(ex.Message));
                    "chocolatey".Log().Error(ChocolateyLoggers.LogFileOnly, () => "More Details: {0}".format_with(ex.ToString()));
                }

                if (Environment.ExitCode == 0)
                {
                    Environment.ExitCode = 1;
                }
            }
            finally
            {
                "chocolatey".Log().Debug(() => "Exiting with {0}".format_with(Environment.ExitCode));
#if DEBUG || RELWITHDEBINFO
                "chocolatey".Log().Info(() => "Exiting with {0}".format_with(Environment.ExitCode));
#endif
                Bootstrap.shutdown();
                Environment.Exit(Environment.ExitCode);
            }
        }