Ejemplo n.º 1
0
        private static IHighlightJSService GetOrCreateHighlightJSService()
        {
            if (_highlightJSService == null || _services != null)
            {
                lock (_createLock)
                {
                    if (_highlightJSService == null || _services != null)
                    {
                        // Dispose of service provider
                        _serviceProvider?.Dispose();

                        // Create new service provider
                        (_services ?? (_services = new ServiceCollection())).AddHighlightJS();
                        _serviceProvider    = _services.BuildServiceProvider();
                        _highlightJSService = _serviceProvider.GetRequiredService <IHighlightJSService>();

                        // Only set to null after new _highlightJSService is initialized, otherwise another thread might skip the lock and try to use the old _highlightJSService
                        _services = null;
                    }
                }
            }

            // HighlightJSService already exists and no configuration pending
            return(_highlightJSService);
        }
Ejemplo n.º 2
0
        public void Setup()
        {
            var services = new ServiceCollection();

            services.AddBeeBus(typeof(BasicMessage).Assembly);
            _serviceProvider?.Dispose();
            _serviceProvider = services.BuildServiceProvider(false);
        }
Ejemplo n.º 3
0
        static void Main(string[] args)
        {
            ServiceProvider serviceProvider = null;

            try
            {
                var configuration = new ConfigurationBuilder()
                                    .AddJsonFile("settings.json")
                                    .Build();

                var services = new ServiceCollection();

                services.AddLogging(logging => { logging.AddConsole(); });
                services.AddOptions();
                services.AddHttpClient();
                services.AddSingleton(configuration.Get <Settings>());
                services.AddSingleton <ColoredBtcClITool>();

                serviceProvider = services.BuildServiceProvider();

                serviceProvider.GetRequiredService <ColoredBtcClITool>().Execute(args);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"args: {string.Join(", ", args)}. {ex}");
            }
            finally
            {
                serviceProvider?.Dispose();
            }
        }
Ejemplo n.º 4
0
 void IDisposable.Dispose()
 {
     ServiceContainer.ServiceProviderOverride = null;
     _serviceProvider?.Dispose();
     _serviceProvider = null;
     JsiiTypeAttributeBase.Reset();
 }
Ejemplo n.º 5
0
        public void TearDown()
        {
            serviceScope?.Dispose();
            serviceProvider?.Dispose();

            File.Delete(databaseFileName);
        }
Ejemplo n.º 6
0
 public void Dispose()
 {
     using IDbConnection db = new SqlConnection(ConnectionString);
     db.Execute(@"DELETE FROM [dbo].[Pet]
                 DELETE FROM [dbo].[User]");
     ServiceProvider?.Dispose();
 }
Ejemplo n.º 7
0
        public void AddBewitValidation_WithMyPayload_ShouldAddBewitTokenValidatorForMyPayload()
        {
            //Arrange
            const string secret   = "112";
            var          services = new ServiceCollection();

            //Act
            services.AddBewitValidation(new BewitOptions
            {
                Secret = secret
            }, b => b.AddPayload <Foo>());

            //Assert
            ServiceProvider serviceProvider = null;

            try
            {
                serviceProvider = services.BuildServiceProvider();
                IBewitTokenValidator <Foo> bewitTokenGenerator =
                    serviceProvider.GetService <IBewitTokenValidator <Foo> >();
                bewitTokenGenerator.Should().NotBeNull();
                bewitTokenGenerator.Should()
                .BeOfType <BewitTokenValidator <Foo> >();
            }
            finally
            {
                serviceProvider?.Dispose();
            }
        }
Ejemplo n.º 8
0
        public void AddBewitValidation_WithPersistance_ShouldAddPersistedBewitTokenGenerator()
        {
            //Arrange
            const string secret   = "112";
            var          services = new ServiceCollection();

            //Act
            services.AddSingleton <INonceRepository>(new Mock <INonceRepository>().Object);
            services.AddBewitValidation(new BewitOptions
            {
                Secret = secret
            },
                                        builder =>
            {
                builder.AddPayload <Foo>();
            });

            //Assert
            ServiceProvider serviceProvider = null;

            try
            {
                serviceProvider = services.BuildServiceProvider();
                IBewitTokenValidator <Foo> bewitTokenGenerator =
                    serviceProvider.GetService <IBewitTokenValidator <Foo> >();
                bewitTokenGenerator.Should().NotBeNull();
                bewitTokenGenerator.Should()
                .BeOfType <BewitTokenValidator <Foo> >();
            }
            finally
            {
                serviceProvider?.Dispose();
            }
        }
Ejemplo n.º 9
0
        public void AddBewitValidation_WithValidConfiguration_ShouldAddBewitTokenValidatorForMyPayload()
        {
            //Arrange
            var services      = new ServiceCollection();
            var configuration = new ConfigurationBuilder()
                                .AddInMemoryCollection(new[]
            {
                new KeyValuePair <string, string>("Bewit:Secret", "123")
            })
                                .Build();

            //Act
            services.AddBewitValidation(configuration, b => b.AddPayload <Foo>());

            //Assert
            ServiceProvider serviceProvider = null;

            try
            {
                serviceProvider = services.BuildServiceProvider();
                IBewitTokenValidator <Foo> bewitTokenGenerator =
                    serviceProvider.GetService <IBewitTokenValidator <Foo> >();
                bewitTokenGenerator.Should().NotBeNull();
                bewitTokenGenerator.Should()
                .BeOfType <BewitTokenValidator <Foo> >();
            }
            finally
            {
                serviceProvider?.Dispose();
            }
        }
Ejemplo n.º 10
0
        ////////////////////////////////////////////////////////////////////////////////////////////////////
        /// <summary>   Main entry-point for this application. </summary>
        ///
        /// <param name="args"> An array of command-line argument strings. </param>
        ////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma warning disable IDE0060 // Remove unused parameter
        private static void Main(string[] args)
#pragma warning restore IDE0060 // Remove unused parameter
        {
            //Note that I still do not know if I need this line.  I adopted it when I was
            // trying to find out how to start a WinUI desktop application from a Main method like this.
            // I found that Scott Jones from Microsoft had this call in his example.  So far I have not
            // needed it, but I am leaving it here as a reminder of random stuff to try when I have some
            // problem that has sucked my brain clean of any solutions.
            //WinRT.ComWrappersSupport.InitializeComWrappers();

            //In WPF it is easier to know when the application is exiting.  This is a solid way to
            // be notified for any required cleanup.
            AppDomain.CurrentDomain.ProcessExit += CurrentDomain_ProcessExit;

            //If you are new to WinUI, coming from WPF like me, you will probably be a bit confused how this
            // initializer works.  Merely declaring an instance of an Application is all that is required.
            // I could have placed all of this logic in "Main" itself, so be aware that you can just use
            // a simple lambda if you wish.
            Microsoft.UI.Xaml.Application.Start(ApplicationInitializationCallback);

            //Assure all services that implement IDisposable get a chance to run their dispose logic.
            ServiceProvider?.Dispose();

            //Not really needed, but I tend to do things like this out of good habit, plus some
            // testing scenarios can cause abnormal control flow.
            ServiceProvider = null;
            Current         = null;
        }
Ejemplo n.º 11
0
 protected virtual void Dispose(bool disposing)
 {
     if (disposing)
     {
         _provider?.Dispose();
     }
 }
Ejemplo n.º 12
0
        private async Task <int> ExecuteAsync(
            CommandLineApplication cmd)
        {
            int             resultCode;
            ServiceProvider serviceProvider = null;

            try
            {
                if (Options.ShowHelp || !Options.Validate())
                {
                    cmd.ShowHelp();
                }
                else
                {
                    serviceProvider = ConfigureServices().BuildServiceProvider();

                    await serviceProvider
                    .GetService <TStrategy>()
                    .ExecuteAsync();
                }

                resultCode = 0;
            }
            catch (Exception e)
            {
                _log.Critical(e, "Execution burning failed.");

                resultCode = 1;
            }

            serviceProvider?.Dispose();

            return(resultCode);
        }
Ejemplo n.º 13
0
        private static int Main(string[] args)
        {
            int             resultCode;
            ServiceProvider serviceProvider = null;

            try
            {
                serviceProvider = ConfigureServices().BuildServiceProvider();

                var rootCommand = serviceProvider.GetService <IRootCommand>();
                var app         = rootCommand.Configure();

                resultCode = app.Execute(args);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);

                resultCode = 1;
            }

            serviceProvider?.Dispose();

            return(resultCode);
        }
        public async Task TestAbstractReturn()
        {
            var queues = new List <IQueue>()
            {
                new Config.Queue(Q1),
                new Config.Queue(Q2),
                new Config.Queue(Q3),
                new Config.Queue(Q4)
            };

            ServiceProvider provider = null;

            try
            {
                provider = await CreateAndStartServices(null, queues, typeof(Listener));

                var template = provider.GetRabbitTemplate();
                var reply    = template.ConvertSendAndReceive <Three>("EnableRabbitReturnTypesTests.2", "3");
                Assert.NotNull(reply);
                var reply2 = template.ConvertSendAndReceive <Four>("EnableRabbitReturnTypesTests.2", "4");
                Assert.NotNull(reply2);
            }
            catch (Exception)
            {
            }
            finally
            {
                var admin = provider.GetRabbitAdmin();
                admin.DeleteQueue(Q1);
                admin.DeleteQueue(Q2);
                admin.DeleteQueue(Q3);
                admin.DeleteQueue(Q4);
                provider?.Dispose();
            }
        }
Ejemplo n.º 15
0
        public async Task TearDown()
        {
            serviceScope?.Dispose();
            serviceProvider?.Dispose();

            await DropDatabaseAsync()
            .ConfigureAwait(false);
        }
Ejemplo n.º 16
0
        public void TestCleanup()
        {
            _servicesCollection.Clear();
            _servicesCollection = null;

            _serviceProvider?.Dispose();
            _serviceProvider = null;
        }
Ejemplo n.º 17
0
        public void TearDown()
        {
            unitOfWork?.Dispose();
            serviceScope?.Dispose();
            serviceProvider?.Dispose();

            DropDatabase();
        }
Ejemplo n.º 18
0
        protected virtual void Dispose(bool disposing)
        {
            if (disposing)
            {
                _serviceProvider?.Dispose();
            }

            _serviceProvider = null;
        }
Ejemplo n.º 19
0
 /// <summary>
 /// Dispose all created objects.
 /// </summary>
 public void Dispose()
 {
     scope?.Dispose();
     serviceProvider?.Dispose();
     foreach (var o in createdObjects.Values.Select(i => i as IDisposable).Where(i => i != null))
     {
         o.Dispose();
     }
 }
Ejemplo n.º 20
0
        /// <summary>
        /// Entry point for the program.
        /// </summary>
        /// <param name="args">Arguments passed to the program, if any.</param>
        /// <returns>A <see cref="Task" /> representing program progress.</returns>
        public static async Task Main(string[] args)
        {
            ServiceProvider provider = null;
            ILogger         log      = null;

            try
            {
                var configuration = BuildConfiguration(args);

                var services = new ServiceCollection();

                services.AddLogging(
                    builder =>
                {
                    var logger = new LoggerConfiguration().ReadFrom.Configuration(configuration).CreateLogger();
                    Log.Logger = logger;
                    builder.AddSerilog(logger, true);
                });

                services.AddCshrixServices(configuration, "ClientConfiguration");

                services.AddTransient <Bot>();

                provider = services.BuildServiceProvider();

                log = provider.GetRequiredService <ILoggerFactory>().CreateLogger("MAIN");

                var bot = provider.GetRequiredService <Bot>();

                await bot.TestAsync();

                Console.WriteLine("Press <ENTER> to exit");
                Console.ReadLine();

                log.LogInformation("<ENTER> pressed, disposing service provider and exiting");
                provider.Dispose();
            }
            catch (Exception ex)
            {
                if (log == null)
                {
                    Console.WriteLine($"Unhandled exception {ex.GetType()} in main: {ex.Message}");
                    Console.WriteLine(ex.StackTrace);
                }
                else
                {
                    log.LogCritical(ex, "Unhandled exception in main");
                }

                throw;
            }
            finally
            {
                provider?.Dispose();
            }
        }
    protected virtual void Dispose(bool disposing)
    {
        if (!disposing)
        {
            return;
        }

        ServiceProvider?.Dispose();
        ServiceProvider = null;
    }
Ejemplo n.º 22
0
        public void Dispose()
        {
            ServiceProvider?.Dispose();
            ((IDisposable)CommandService)?.Dispose();
            CancellationTokenSource?.Dispose();

            foreach (var task in TasksToAwait)
            {
                task.Dispose();
            }
        }
 public void TearDown()
 {
     ServiceScope?.Dispose();
     ServiceProvider?.Dispose();
     if (_temporaryDatabase != null)
     {
         var connString = _temporaryDatabase.ConnectionString;
         _temporaryDatabase = null;
         FbDatabase.DropDatabase(connString);
     }
 }
Ejemplo n.º 24
0
 /// <summary>
 /// Disposes underlying service provider.
 /// </summary>
 /// <param name="disposing"></param>
 protected virtual void Dispose(bool disposing)
 {
     if (_disposed)
     {
         return;
     }
     if (disposing)
     {
         _serviceProvider?.Dispose();
     }
     _disposed = true;
 }
        private static ServiceProvider GetOrCreateServiceProvider()
        {
            if (_serviceProvider == null || _services != null)
            {
                lock (_createLock)
                {
                    if (_serviceProvider == null || _services != null)
                    {
                        // Dispose of service provider
                        _serviceProvider?.Dispose();

                        // Create new service provider
                        (_services ?? (_services = new ServiceCollection())).AddFlexiBlocks();
                        _serviceProvider = _services.BuildServiceProvider();
                        _services        = null;
                    }
                }
            }

            return(_serviceProvider);
        }
 public void Dispose()
 {
     if (codeDomProvider != null)
     {
         codeDomProvider.Dispose();
         codeDomProvider = null;
     }
     if (serviceProvider != null)
     {
         serviceProvider.Dispose();
         serviceProvider = null;
     }
 }
        static void Main(string[] args)
        {
            SetupDI();

            var onboardingClient = ServiceProvider.GetService <IOnboardingClient>();

            var v = onboardingClient.GetProcesses();

            Console.WriteLine(v.Result);
            Console.ReadLine();

            ServiceProvider.Dispose();
        }
Ejemplo n.º 28
0
        public void Dispose()
        {
            CheckDisposed();

            _services?.Clear();
            _services = null;

            _queue = null;

            _provider?.Dispose();
            _provider = null;

            _disposed = true;
        }
Ejemplo n.º 29
0
        private void Dispose(bool disposing)
        {
            if (disposing)
            {
                var _dbContext = GetService <DbContext>();

                if (_dbContext != null)
                {
                    _dbContext.Dispose();
                }

                serviceProvider.Dispose();
            }
        }
 protected virtual void Dispose(bool disposing)
 {
     if (!_disposed)
     {
         if (disposing)
         {
             if (serviceProvider != null)
             {
                 serviceProvider.Dispose();
             }
         }
     }
     _disposed = true;
 }
Ejemplo n.º 31
0
        private static bool ProcessCommandLine(Dictionary<string, string> pArgs)
        {
            if (pArgs.ContainsKey("-assistant"))
            {
                Assistant.Main(pArgs);

                return true;
            }

            if (pArgs.ContainsKey("-e"))
            {
                try
                {
                    ExtendedCmd.Run(pArgs);
                }
                catch (Exception ex)
                {
                    PhUtils.ShowException("Unable to complete the operation", ex);
                }

                return true;
            }

            if (pArgs.ContainsKey("-installkph"))
            {
                try
                {
                    using (ServiceManagerHandle scm = new ServiceManagerHandle(ScManagerAccess.CreateService))
                    {
                        using (ServiceHandle shandle = scm.CreateService(
                            "KProcessHacker2",
                            "KProcessHacker2",
                            ServiceType.KernelDriver,
                            ServiceStartType.SystemStart,
                            ServiceErrorControl.Ignore,
                            Application.StartupPath + "\\kprocesshacker.sys",
                            null,
                            null,
                            null
                            ))
                        {
                            shandle.Start();
                        }
                    }
                }
                catch (WindowsException ex)
                {
                    // Need to pass status back.
                    Environment.Exit((int)ex.ErrorCode);
                }

                return true;
            }

            if (pArgs.ContainsKey("-uninstallkph"))
            {
                try
                {
                    using (ServiceHandle shandle = new ServiceHandle("KProcessHacker2", ServiceAccess.Stop | (ServiceAccess)StandardRights.Delete))
                    {
                        try { shandle.Control(ServiceControl.Stop); }
                        catch { }

                        shandle.Delete();
                    }
                }
                catch (WindowsException ex)
                {
                    // Need to pass status back.
                    Environment.Exit((int)ex.ErrorCode);
                }

                return true;
            }

            if (pArgs.ContainsKey("-ip"))
                InspectPid = int.Parse(pArgs["-ip"]);

            if (pArgs.ContainsKey("-pw"))
            {
                int pid = int.Parse(pArgs["-pw"]);

                PrimaryProviderThread = new ProviderThread(Settings.Instance.RefreshInterval);
                SecondaryProviderThread = new ProviderThread(Settings.Instance.RefreshInterval);

                ProcessProvider = new ProcessSystemProvider();
                ServiceProvider = new ServiceProvider();
                PrimaryProviderThread.Add(ProcessProvider);
                PrimaryProviderThread.Add(ServiceProvider);
                ProcessProvider.Boost();
                ServiceProvider.Boost();
                ProcessProvider.Enabled = true;
                ServiceProvider.Enabled = true;

                Win32.LoadLibrary(Settings.Instance.DbgHelpPath);

                if (!ProcessProvider.Dictionary.ContainsKey(pid))
                {
                    PhUtils.ShowError("The process (PID " + pid.ToString() + ") does not exist.");
                    Environment.Exit(0);
                    return true;
                }

                ProcessWindow pw = new ProcessWindow(ProcessProvider.Dictionary[pid]);

                Application.Run(pw);

                PrimaryProviderThread.Dispose();
                ProcessProvider.Dispose();
                ServiceProvider.Dispose();

                Environment.Exit(0);

                return true;
            }

            if (pArgs.ContainsKey("-pt"))
            {
                int pid = int.Parse(pArgs["-pt"]);

                try
                {
                    using (var phandle = new ProcessHandle(pid, Program.MinProcessQueryRights))
                        Application.Run(new TokenWindow(phandle));
                }
                catch (Exception ex)
                {
                    PhUtils.ShowException("Unable to show token properties", ex);
                }

                return true;
            }

            if (pArgs.ContainsKey("-o"))
            {
                OptionsWindow options = new OptionsWindow(true)
                {
                    StartPosition = FormStartPosition.CenterScreen
                };
                IWin32Window window;

                if (pArgs.ContainsKey("-hwnd"))
                    window = new WindowFromHandle(new IntPtr(int.Parse(pArgs["-hwnd"])));
                else
                    window = new WindowFromHandle(IntPtr.Zero);

                if (pArgs.ContainsKey("-rect"))
                {
                    Rectangle rect = Utils.GetRectangle(pArgs["-rect"]);

                    options.Location = new Point(rect.X + 20, rect.Y + 20);
                    options.StartPosition = FormStartPosition.Manual;
                }

                options.SelectedTab = options.TabPages["tabAdvanced"];
                options.ShowDialog(window);

                return true;
            }

            if (pArgs.ContainsKey(string.Empty))
                if (pArgs[string.Empty].Replace("\"", string.Empty).Trim().EndsWith("taskmgr.exe", StringComparison.OrdinalIgnoreCase))
                    StartVisible = true;

            if (pArgs.ContainsKey("-m"))
                StartHidden = true;
            if (pArgs.ContainsKey("-v"))
                StartVisible = true;

            if (pArgs.ContainsKey("-a"))
            {
                try { Unhook(); }
                catch { }
                try { NProcessHacker.KphHookInit(); }
                catch { }
            }

            if (pArgs.ContainsKey("-t"))
            {
                if (pArgs["-t"] == "0")
                    SelectTab = "Processes";
                else if (pArgs["-t"] == "1")
                    SelectTab = "Services";
                else if (pArgs["-t"] == "2")
                    SelectTab = "Network";
            }

            return false;
        }