예제 #1
0
        public static WebHostBuilder UseProjectOf <TStartup>(this WebHostBuilder builder)
        {
            var startupAssembly = typeof(TStartup).GetTypeInfo().Assembly;
            var applicationName = startupAssembly.GetName().Name;
            var webRoot         = GetProjectDirectoryOf(startupAssembly);

            builder.ConfigureServices(services =>
            {
                var hostingEnvironment = new HostingEnvironment();
                hostingEnvironment.Initialize(
                    webRoot,
                    new WebHostOptions
                {
                    ApplicationName = applicationName,
                    Environment     = "Production"
                });
                services.AddSingleton <IHostingEnvironment>(hostingEnvironment);

                var manager = new ApplicationPartManager();
                manager.ApplicationParts.Add(new AssemblyPart(startupAssembly));
                services.AddSingleton(manager);
            });

            return(builder);
        }
예제 #2
0
        public Func <IServiceCollection, IServiceProvider> InitializeServices(Assembly startupAssembly, Func <IServiceCollection, IServiceProvider> buildServices)
        {
            var applicationName = startupAssembly.GetName().Name;
            var applicationRoot = GetApplicationRoot(applicationName);

#if DNX451
            AppDomain.CurrentDomain.SetData("APP_CONTEXT_BASE_DIRECTORY", applicationRoot);
#endif
            var applicationEnvironment = PlatformServices.Default.Application;

            var hostingEnvironment = new HostingEnvironment();
            hostingEnvironment.Initialize(applicationRoot, null);

            var assemblyProvider = new StaticAssemblyProvider();
            assemblyProvider.CandidateAssemblies.Add(startupAssembly);

            return(services =>
            {
                services.AddInstance <IApplicationEnvironment>(new TestApplicationEnvironment(applicationEnvironment, applicationName, applicationRoot));
                services.AddInstance <IHostingEnvironment>(hostingEnvironment);
                // Inject a custom assembly provider. Overrides AddMvc() because that uses TryAdd().
                services.AddInstance <IAssemblyProvider>(assemblyProvider);

                return buildServices(services);
            });
        }
예제 #3
0
        public FabricContainer(ServiceCollection services = null)
        {
            services = services ?? new ServiceCollection();

            this.RegisterInstance <IServiceScopeInitializer>(this);

//#if NETCORE20

            this.AsFabricContainer().BuildServiceProvider(services);
//#else
//            this.AsFabricContainer().WithAspNetCoreServiceProvider();
//#endif

            var _hostingEnvironment = new HostingEnvironment();
            var _config             = new ConfigurationBuilder()
                                      .AddEnvironmentVariables(prefix: "ASPNETCORE_")
                                      .Build();
            var _options = new WebHostOptions(_config, Assembly.GetEntryAssembly()?.GetName().Name)
            {
            };
            // Microsoft.AspNetCore.Hosting.Internal.HostingEnvironmentExtensions.Initialize

            var contentRootPath = ResolveContentRootPath(_options.ContentRootPath, AppContext.BaseDirectory);

            _hostingEnvironment.Initialize(contentRootPath, _options);
            this.RegisterInstance <IHostingEnvironment>(_hostingEnvironment);
        }
예제 #4
0
        public static WebHostBuilder UseProjectOf <TStartup>(this WebHostBuilder builder)
        {
            var libraryManager = DnxPlatformServices.Default.LibraryManager;

            var applicationName = typeof(TStartup).GetTypeInfo().Assembly.GetName().Name;
            var library         = libraryManager.GetLibrary(applicationName);
            var webRoot         = Path.GetDirectoryName(library.Path);

            var assemblyProvider = new StaticAssemblyProvider();

            assemblyProvider.CandidateAssemblies.Add(typeof(TStartup).Assembly);
            builder.ConfigureServices(services =>
            {
                var applicationEnvironment = new TestApplicationEnvironment(
                    PlatformServices.Default.Application,
                    applicationName,
                    webRoot);
                services.AddSingleton <IApplicationEnvironment>(applicationEnvironment);

                var hostingEnvironment = new HostingEnvironment();
                hostingEnvironment.Initialize(
                    webRoot,
                    new WebHostOptions
                {
                    Environment = "Production",
                },
                    configuration: null);
                services.AddSingleton <IHostingEnvironment>(hostingEnvironment);

                services.AddSingleton <IAssemblyProvider>(assemblyProvider);
            });

            return(builder);
        }
예제 #5
0
        private static IHostingEnvironment InitializeEnvironment()
        {
            IConfigurationRoot config = new ConfigurationBuilder().AddEnvironmentVariables("ASPNETCORE_").Build();
            var options = new WebHostOptions(config, GetApplicationName());
            var env     = new HostingEnvironment();

            env.Initialize(AppContext.BaseDirectory, options);
            return(env);
        }
        public void OverridesEnvironmentFromConfig()
        {
            var env = new HostingEnvironment();
            env.EnvironmentName = "SomeName";

            env.Initialize("DummyApplication", Path.GetFullPath("."), new WebHostOptions(){ Environment = "NewName" });

            Assert.Equal("NewName", env.EnvironmentName);
        }
        public void DefaultsToNullFileProvider()
        {
            var env = new HostingEnvironment();

            env.Initialize("DummyApplication", Path.GetFullPath(Path.Combine("testroot", "wwwroot")), new WebHostOptions());

            Assert.Equal(Path.GetFullPath(Path.Combine("testroot", "wwwroot")), env.ContentRootPath);
            Assert.Null(env.WebRootPath);
            Assert.IsAssignableFrom<PhysicalFileProvider>(env.ContentRootFileProvider);
            Assert.IsAssignableFrom<NullFileProvider>(env.WebRootFileProvider);
        }
        public void SetsFullPathToWwwroot()
        {
            var env = new HostingEnvironment();

            env.Initialize("DummyApplication", Path.GetFullPath("."), new WebHostOptions(){ WebRoot = "testroot" });

            Assert.Equal(Path.GetFullPath("."), env.ContentRootPath);
            Assert.Equal(Path.GetFullPath("testroot"), env.WebRootPath);
            Assert.IsAssignableFrom<PhysicalFileProvider>(env.ContentRootFileProvider);
            Assert.IsAssignableFrom<PhysicalFileProvider>(env.WebRootFileProvider);
        }
예제 #9
0
        public void DefaultsToNullFileProvider()
        {
            IWebHostEnvironment env = new HostingEnvironment();

            env.Initialize(Path.GetFullPath(Path.Combine("testroot", "wwwroot")), CreateWebHostOptions());

            Assert.Equal(Path.GetFullPath(Path.Combine("testroot", "wwwroot")), env.ContentRootPath);
            Assert.Null(env.WebRootPath);
            Assert.IsAssignableFrom <PhysicalFileProvider>(env.ContentRootFileProvider);
            Assert.IsAssignableFrom <NullFileProvider>(env.WebRootFileProvider);
        }
예제 #10
0
        public void DefaultsToWwwrootSubdir()
        {
            var env = new HostingEnvironment();

            env.Initialize("DummyApplication", Path.GetFullPath("testroot"), new WebHostOptions());

            Assert.Equal(Path.GetFullPath("testroot"), env.ContentRootPath);
            Assert.Equal(Path.GetFullPath(Path.Combine("testroot", "wwwroot")), env.WebRootPath);
            Assert.IsAssignableFrom <PhysicalFileProvider>(env.ContentRootFileProvider);
            Assert.IsAssignableFrom <PhysicalFileProvider>(env.WebRootFileProvider);
        }
예제 #11
0
        private IHostingEnvironment CreateHostingEnvironment()
        {
            var hostingEnvironment = new HostingEnvironment();

            var appEnvironment = PlatformServices.Default.Application;

            var applicationName = typeof(Startup).GetTypeInfo().Assembly.GetName().Name;

            hostingEnvironment.Initialize(applicationName, appEnvironment.ApplicationBasePath, new WebHostOptions());

            return(hostingEnvironment);
        }
예제 #12
0
        private static IHostingEnvironment GetHostingEnvironment(Func <string> contentRootPath)
        {
            var hostingEnvironment = new HostingEnvironment();

            var webHostOptions = new WebHostOptions();

            hostingEnvironment.Initialize("Template", contentRootPath(), webHostOptions);

            hostingEnvironment.EnvironmentName = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");

            return(hostingEnvironment);
        }
        public void OverridesEnvironmentFromConfig()
        {
            IWebHostEnvironment env = new HostingEnvironment();

            env.EnvironmentName = "SomeName";

            env.Initialize(Path.GetFullPath("."), new WebHostOptions()
            {
                Environment = "NewName"
            });

            Assert.Equal("NewName", env.EnvironmentName);
        }
        public void SetsFullPathToWwwroot()
        {
            IWebHostEnvironment env = new HostingEnvironment();

            env.Initialize(Path.GetFullPath("."), new WebHostOptions()
            {
                WebRoot = "testroot"
            });

            Assert.Equal(Path.GetFullPath("."), env.ContentRootPath);
            Assert.Equal(Path.GetFullPath("testroot"), env.WebRootPath);
            Assert.IsAssignableFrom <PhysicalFileProvider>(env.ContentRootFileProvider);
            Assert.IsAssignableFrom <PhysicalFileProvider>(env.WebRootFileProvider);
        }
        public void OverridesEnvironmentFromConfig()
        {
            var env = new HostingEnvironment()
            {
                EnvironmentName = "SomeName"
            };

            env.Initialize("DummyApplication", new HostOptions()
            {
                Environment = "NewName"
            });

            Assert.Equal("NewName", env.EnvironmentName);
        }
예제 #16
0
 static Bootstrap()
 {
     ServiceLogManager.SetProvider(() => new Log4NetServiceLog("Dagent"));
     ServiceLocatorManager.SetProvider(() => new UnityServiceLocator()) // new MicroServiceLocator())
     .Register(r =>
     {
         ConfigurationManagerEx.GetSection <HostingSection>("hosting").Configure(r);
         var appSection = ConfigurationManagerEx.GetSection <AppSection>("appSection").Configure(r);
         if (appSection.Log4Net)
         {
             XmlConfigurator.Configure();
         }
         HostingEnvironment.Initialize();
     });
     var o = ServiceLocatorManager.Current;
 }
예제 #17
0
        private static void AddTestServices(
            IServiceCollection services,
            string applicationWebSiteName,
            string applicationPath,
            Action <IServiceCollection> configureServices)
        {
            applicationPath = applicationPath ?? WebsitesDirectoryPath;

            // Get current IApplicationEnvironment; likely added by the host.
            var provider            = services.BuildServiceProvider();
            var originalEnvironment = provider.GetRequiredService <IApplicationEnvironment>();

            // When an application executes in a regular context, the application base path points to the root
            // directory where the application is located, for example MvcSample.Web. However, when executing
            // an application as part of a test, the ApplicationBasePath of the IApplicationEnvironment points
            // to the root folder of the test project.
            // To compensate for this, we need to calculate the original path and override the application
            // environment value so that components like the view engine work properly in the context of the
            // test.
            var applicationBasePath = CalculateApplicationBasePath(
                originalEnvironment,
                applicationWebSiteName,
                applicationPath);
            var environment = new TestApplicationEnvironment(
                originalEnvironment,
                applicationWebSiteName,
                applicationBasePath);

            services.AddInstance <IApplicationEnvironment>(environment);
            var hostingEnvironment = new HostingEnvironment();

            hostingEnvironment.Initialize(applicationBasePath, config: null);
            services.AddInstance <IHostingEnvironment>(hostingEnvironment);

            // Injecting a custom assembly provider. Overrides AddMvc() because that uses TryAdd().
            var assemblyProvider = CreateAssemblyProvider(applicationWebSiteName);

            services.AddInstance(assemblyProvider);

            // Avoid using pooled memory, we don't have a guarantee that our services will get disposed.
            services.AddInstance <IHttpResponseStreamWriterFactory>(new TestHttpResponseStreamWriterFactory());

            if (configureServices != null)
            {
                configureServices(services);
            }
        }
예제 #18
0
    public void OverridesEnvironmentFromConfig()
    {
        IWebHostEnvironment env = new HostingEnvironment();

        env.EnvironmentName = "SomeName";

        var webHostOptions = CreateWebHostOptions(
            new ConfigurationBuilder()
            .AddInMemoryCollection(new Dictionary <string, string>()
        {
            [WebHostDefaults.EnvironmentKey] = "NewName"
        }).Build());

        env.Initialize(Path.GetFullPath("."), webHostOptions);

        Assert.Equal("NewName", env.EnvironmentName);
    }
예제 #19
0
    public void SetsFullPathToWwwroot()
    {
        IWebHostEnvironment env = new HostingEnvironment();

        var webHostOptions = CreateWebHostOptions(
            new ConfigurationBuilder()
            .AddInMemoryCollection(new Dictionary <string, string>()
        {
            [WebHostDefaults.WebRootKey] = "testroot"
        }).Build());

        env.Initialize(Path.GetFullPath("."), webHostOptions);

        Assert.Equal(Path.GetFullPath("."), env.ContentRootPath);
        Assert.Equal(Path.GetFullPath("testroot"), env.WebRootPath);
        Assert.IsAssignableFrom <PhysicalFileProvider>(env.ContentRootFileProvider);
        Assert.IsAssignableFrom <PhysicalFileProvider>(env.WebRootFileProvider);
    }
예제 #20
0
        IHostingEnvironment GetModuleHostingEnvironment()
        {
            var moduleAssemblyName = ModuleStartupType.GetTypeInfo().Assembly.GetName().Name;
            var moduleEnv          = new HostingEnvironment();
            var contentRootPath    = Path.Combine(PlatformServices.Default.Application.ApplicationBasePath, "Modules", moduleAssemblyName);

            if (!Directory.Exists(contentRootPath))
            {
                Directory.CreateDirectory(contentRootPath);
            }
            moduleEnv.Initialize(
                applicationName: moduleAssemblyName,
                contentRootPath: contentRootPath,
                options: new WebHostOptions()
            {
                Environment = _env.EnvironmentName
            });
            return(moduleEnv);
        }
예제 #21
0
        public static IHostBuilder AddKestrelApp(this IHostBuilder builder, Action <IApplicationBuilder> appBuilder)
        {
            builder.ConfigureServices(services =>
            {
                var sp = services.BuildServiceProvider();

                var appLifetime = ActivatorUtilities.CreateInstance <ApplicationLifetime>(sp);
                services.AddSingleton <Microsoft.AspNetCore.Hosting.IApplicationLifetime>(appLifetime);
                services.AddSingleton <Microsoft.Extensions.Hosting.IApplicationLifetime>(appLifetime);

                var hostOptions = new WebHostOptions(sp.GetRequiredService <IConfiguration>(), Assembly.GetEntryAssembly()?.GetName().Name);

                var commonHosting = new HostingEnvironment();
                commonHosting.Initialize(sp.GetRequiredService <Microsoft.Extensions.Hosting.IHostingEnvironment>(), hostOptions);
                services.AddSingleton <Microsoft.AspNetCore.Hosting.IHostingEnvironment>(commonHosting);
                services.AddSingleton <Microsoft.Extensions.Hosting.IHostingEnvironment>(commonHosting);

                var listener = new DiagnosticListener("Microsoft.AspNetCore");
                services.AddSingleton <DiagnosticListener>(listener);
                services.AddSingleton <DiagnosticSource>(listener);

                services.AddTransient <IServiceProviderFactory <IServiceCollection>, DefaultServiceProviderFactory>();

                services.AddSingleton <ObjectPoolProvider, DefaultObjectPoolProvider>();

                services.AddTransient <IApplicationBuilderFactory, ApplicationBuilderFactory>();
                services.AddTransient <IHttpContextFactory, HttpContextFactory>();
                services.AddScoped <IMiddlewareFactory, MiddlewareFactory>();
                services.AddTransient <IStartupFilter, AutoRequestServicesStartupFilter>();

                services.TryAddSingleton <ITransportFactory, LibuvTransportFactory>();

                services.AddTransient <IConfigureOptions <KestrelServerOptions>, KestrelServerOptionsSetup>();
                services.AddSingleton <IServer, KestrelServer>();

                services.AddSingleton(provider => ConstructWebHost(provider, hostOptions, appBuilder));
                services.AddSingleton <IHostedService, HttpHostedService>();
            });

            return(builder);
        }
예제 #22
0
        private Func <IServiceCollection, IServiceProvider> InitializeServices(
            Assembly startupAssembly,
            Func <IServiceCollection, IServiceProvider> buildServices)
        {
            var applicationServices = CallContextServiceLocator.Locator.ServiceProvider;
            var libraryManager      = applicationServices.GetRequiredService <ILibraryManager>();

            // When an application executes in a regular context, the application base path points to the root
            // directory where the application is located, for example .../samples/MvcSample.Web. However, when
            // executing an application as part of a test, the ApplicationBasePath of the IApplicationEnvironment
            // points to the root folder of the test project.
            // To compensate, we need to calculate the correct project path and override the application
            // environment value so that components like the view engine work properly in the context of the test.
            var applicationName = startupAssembly.GetName().Name;
            var library         = libraryManager.GetLibrary(applicationName);
            var applicationRoot = Path.GetDirectoryName(library.Path);

            var applicationEnvironment = applicationServices.GetRequiredService <IApplicationEnvironment>();

            return((services) =>
            {
                services.AddInstance <IApplicationEnvironment>(
                    new TestApplicationEnvironment(applicationEnvironment, applicationName, applicationRoot));

                var hostingEnvironment = new HostingEnvironment();
                hostingEnvironment.Initialize(applicationRoot, null);
                services.AddInstance <IHostingEnvironment>(hostingEnvironment);

                // Inject a custom assembly provider. Overrides AddMvc() because that uses TryAdd().
                var assemblyProvider = new StaticAssemblyProvider();
                assemblyProvider.CandidateAssemblies.Add(startupAssembly);
                services.AddInstance <IAssemblyProvider>(assemblyProvider);

                AddAdditionalServices(services);

                return buildServices(services);
            });
        }
예제 #23
0
        public static void Main(string[] args)
        {
            PlatformServices        ps      = PlatformServices.Default;
            IApplicationEnvironment env     = ps.Application;
            IConfigurationBuilder   builder = new ConfigurationBuilder()
                                              .AddEnvironmentVariables()
                                              .SetBasePath(env.ApplicationBasePath);

            IHostingEnvironment hostingEnv = new HostingEnvironment();

            hostingEnv.Initialize(env.ApplicationBasePath, builder.Build());
            if (hostingEnv.IsDevelopment())
            {
                Console.WriteLine("Loading from UserSecret store");
                builder.AddUserSecrets();
            }
            else
            {
                Console.WriteLine("Loading from jsons directory");
                builder.AddJsonFile(@"..\..\..\..\..\..\MechHisui-jsons\secrets.json");
            }

            IConfiguration config = builder.Build();

            var client = new DiscordClient(conf =>
            {
                conf.AppName    = "MechHisui";
                conf.AppVersion = "0.3.0";
                conf.LogLevel   = LogSeverity.Info;
                //conf.UseLargeThreshold = true;
            });

            //client.Disconnected += (s, e) => Environment.Exit(0);
            Console.CancelKeyPress += async(s, e) => await RegisterCommands.Disconnect(client, config);

            //Display all log messages in the console
            client.Log.Message += (s, e) => Console.WriteLine($"{DateTime.Now} - [{e.Severity}] {e.Source}: {e.Message} {e.Exception}");

            //Add a ModuleService and CommandService
            client.AddService(new ModuleService());
            client.UsingCommands(conf =>
            {
                conf.AllowMentionPrefix = true;
                conf.HelpMode           = HelpMode.Public;
                conf.PrefixChar         = '.';
            });

            //register commands
            client.RegisterAddChannelCommand(config);
            client.RegisterDeleteCommand(config);
            client.RegisterDisconnectCommand(config);
            if (!Debugger.IsAttached)
            {
                client.RegisterEvalCommand(config);
            }
            //client.RegisterImageCommand(config);
            client.RegisterInfoCommand(config);
            client.RegisterKnownChannelsCommand(config);
            client.RegisterLearnCommand(config);
            client.RegisterPickCommand(config);
            //client.RegisterRecordingCommand(config);
            client.RegisterResetCommand(config);
            client.RegisterRollCommand(config);
            client.RegisterThemeCommand(config);
            client.RegisterWhereCommand(config);
            client.RegisterXmasCommand(config);

            client.RegisterAPCommand(config);
            client.RegisterDailyCommand(config);
            client.RegisterEventCommand(config);
            client.RegisterFriendsCommand(config);
            client.RegisterLoginBonusCommand(config);
            client.RegisterStatsCommands(config);
            client.RegisterQuartzCommand(config);
            client.RegisterZoukenCommand(config);

            client.RegisterHisuiBetsCommands(config);

            client.RegisterSecretHitler(config);

            client.RegisterTriviaCommand(config);

            Responses.InitResponses(config);

            int lastcode = 0;

            if (args.Length > 0 && Int32.TryParse(args[0], out lastcode) && lastcode != 0)
            {
                Console.WriteLine($"Last exit code was {lastcode}");
            }

            client.MessageUpdated += async(s, e) =>
            {
                if (!(await e.Channel.DownloadMessages(10, e.Before.Id, Relative.After)).Any(m => m.IsAuthor))
                {
                    var msgReceived = typeof(DiscordClient).GetMethod("OnMessageReceived", BindingFlags.NonPublic | BindingFlags.Instance);
                    msgReceived.Invoke(s, new object[] { e.After });
                    //client.OnMessageReceived(e.After);
                }
            };

            try
            {
                //Convert our sync method to an async one and block the Main function until the bot disconnects
                client.ExecuteAndWait(async() =>
                {
                    //Connect to the Discord server using our email and password
                    await client.Connect(config["Email"], config["Password"]);
                    Console.WriteLine($"Logged in as {client.CurrentUser.Name}");
                    Console.WriteLine($"MH v. 0.3.0");

                    //Use a channel whitelist
                    client.GetService <ModuleService>().Add(
                        new ChannelWhitelistModule(
                            Helpers.ConvertStringArrayToULongArray(
                                //config["API_testing"]
                                //config["LTT_general"],
                                //config["LTT_testing"],
                                config["FGO_playground"],
                                config["FGO_Hgames"],
                                config["FGO_events"],
                                config["FGO_general"]
                                )
                            ),
                        nameof(ChannelWhitelistModule),
                        ModuleFilter.ChannelWhitelist
                        );

                    if (!client.Servers.Any())
                    {
                        Console.WriteLine("Not a member of any server");
                    }
                    else
                    {
                        foreach (var prChannel in client.PrivateChannels)
                        {
                            if (prChannel.Id == UInt64.Parse(config["PrivChat"]))
                            {
                                client.MessageReceived += (new Responder(prChannel, client).Respond);
                            }
                        }
                        foreach (var channel in Helpers.IterateChannels(client.Servers, printServerNames: true, printChannelNames: true))
                        {
                            if (!channel.IsPrivate && Helpers.IsWhilested(channel, client))
                            {
                                //Console.CancelKeyPress += async (s, e) => await client.SendMessage(channel, config["Goodbye"]);
                                client.MessageReceived += (new Responder(channel, client).Respond);
                                if (channel.Id != UInt64.Parse(config["API_testing"]))
                                {
                                    if (Debugger.IsAttached)
                                    {
                                        // await channel.SendMessage("MechHisui started in debug mode. Not all commands will be available.");
                                    }
                                    else if (lastcode != -1 && channel.Id != UInt64.Parse(config["FGO_events"]))
                                    {
                                        await channel.SendMessage(config["Hello"]);
                                    }
                                }
                            }
                        }
                        if (!Debugger.IsAttached)
                        {
                            client.AddNewHisuiBetsUsers(config);
                        }
                        Console.WriteLine($"Started up at {DateTime.Now}.");
                    }
                });
            }
            catch (Exception ex)
            {
                File.AppendAllText(Path.Combine(config["Logs"], "crashlogs.txt"), $"{DateTime.Now} - {ex.Message}\n{ex.StackTrace}\n");
                Environment.Exit(-1);
            }
        }
예제 #24
0
        public static void Main(string[] args)
        {
            PlatformServices        ps  = PlatformServices.Default;
            IApplicationEnvironment env = ps.Application;
            //Console.WriteLine($"Base: {env.ApplicationBasePath}");

            IConfigurationBuilder builder = new ConfigurationBuilder()
                                            .AddEnvironmentVariables()
                                            .SetBasePath(env.ApplicationBasePath);

            IHostingEnvironment hostingEnv = new HostingEnvironment();

            hostingEnv.Initialize(env.ApplicationBasePath, builder.Build());
            if (hostingEnv.IsDevelopment())
            {
                Console.WriteLine("Loading from UserSecret store");
                builder.AddUserSecrets();
            }
            else
            {
                Console.WriteLine("Loading from jsons directory");
                builder.AddJsonFile(@"..\..\..\..\GudakoBot-jsons\secrets.json");
            }

            IConfiguration config = builder.Build();

            ulong owner  = UInt64.Parse(config["Owner"]);
            ulong fgogen = UInt64.Parse(config["FGO_general"]);

            Console.WriteLine("Loading chat lines...");
            LoadLines(config);
            Console.WriteLine($"Loaded {Randomlines.Count()} lines.");

            var client = new DiscordClient(conf =>
            {
                conf.AppName    = "GudakoBot";
                conf.CacheToken = true;
                conf.LogLevel   = /*Debugger.IsAttached ? LogSeverity.Verbose :*/ LogSeverity.Warning;
                //conf.UseLargeThreshold = true;
            });

            //Display all log messages in the console
            client.Log.Message     += (s, e) => Console.WriteLine($"[{e.Severity}] {e.Source}: {e.Message}");
            client.MessageReceived += (s, e) =>
            {
                if (e.Message.User.Id == owner && e.Message.Text == "-new")
                {
                    Console.WriteLine($"{DateTime.Now}: Reloading lines");
                    LoadLines(config);
                    e.Channel.SendMessage(Randomlines.Last());
                    timer.Change(TimeSpan.FromMinutes(30), TimeSpan.FromMinutes(30));
                }
            };


            client.ExecuteAndWait(async() =>
            {
                //Connect to the Discord server using our email and password
                await client.Connect(config["Email"], config["Password"]);
                //client.Token = (await client.Send(new LoginRequest { Email = config["Email"], Password = config["Password"] })).Token;
                Console.WriteLine($"Logged in as {client.CurrentUser.Name}");
                Console.WriteLine($"Started up at {DateTime.Now}.");

                var rng = new Random();
                timer   = new Timer(async s =>
                {
                    var channel = client.GetChannel(fgogen);
                    if (channel == null)
                    {
                        Console.WriteLine($"Channel was null. Waiting for next interval.");
                    }
                    else
                    {
                        Console.WriteLine($"{DateTime.Now}: Sending message.");
                        Randomlines = Randomlines.Shuffle();
                        await channel.SendMessage(Randomlines.ElementAt(rng.Next(maxValue: Randomlines.Count())));
                    }
                },
                                    null,
                                    TimeSpan.FromMinutes(10),
                                    TimeSpan.FromMinutes(30));
            });
        }
예제 #25
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="services"></param>
        /// <param name="logDirectory">log file path
        /// <para>e.g. .Logs or wwwroor/logs or C:/wwwroot/logs</para>
        /// </param>
        public static void AddFileLog(this IServiceCollection services, string logDirectory = ".Logs")
        {
            if (!services.Any(x => x.ImplementationType == typeof(LOG.LoggerFactory)))
            {
                LOG.LoggerFactory.ServiceCollection = services;
                if (string.IsNullOrEmpty(logDirectory))
                {
                    logDirectory = ".Logs";
                }
                services.AddHttpContextAccessor();
                Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
                Console.OutputEncoding = System.Text.Encoding.UTF8;
                var _config = services.FirstOrDefault(x => x.ServiceType == typeof(IConfiguration))?.ImplementationInstance as IConfiguration;
                if (_config == null)
                {
                    _config = new ConfigurationBuilder()
                              .AddEnvironmentVariables("ASPNETCORE_")
                              .SetBasePath(AppContext.BaseDirectory)
                              .Build();
                    _config[WebHostDefaults.ContentRootKey] = AppContext.BaseDirectory;
                    services.AddSingleton(_config);
                }
                if (string.IsNullOrEmpty(_config[WebHostDefaults.ContentRootKey]))
                {
                    _config[WebHostDefaults.ContentRootKey] = AppContext.BaseDirectory;
                }

                IHostingEnvironment environment = (IHostingEnvironment)services.FirstOrDefault(x => x.ServiceType == typeof(IHostingEnvironment))
                                                  ?.ImplementationInstance;
                if (environment == null)
                {
                    WebHostOptions options = new WebHostOptions(_config, Assembly.GetEntryAssembly().GetName().Name);
                    environment = new HostingEnvironment();
                    environment.Initialize(AppContext.BaseDirectory, options);
                    services.TryAddSingleton <IHostingEnvironment>(environment);
                }
                if (string.IsNullOrEmpty(environment.WebRootPath))
                {
                    var _contentPath = _config[WebHostDefaults.ContentRootKey];
                    var binIndex     = _contentPath.LastIndexOf("\\bin\\");
                    if (binIndex > -1)
                    {
                        var contentPath = _contentPath.Substring(0, binIndex);
                        if (contentPath.IndexOf(environment.ApplicationName) > -1)
                        {
                            _config[WebHostDefaults.ContentRootKey] = contentPath;
                            environment.ContentRootPath             = contentPath;
                            environment.WebRootPath = System.IO.Path.Combine(contentPath, "wwwroot");
                        }
                    }
                    else
                    {
                        environment.WebRootPath = System.IO.Path.Combine(_config["ContentRoot"], "wwwroot");
                    }
                }
                if (Path.IsPathRooted(logDirectory))
                {
                    LoggerSettings.LogDirectory = logDirectory;
                }
                else
                {
                    LoggerSettings.LogDirectory = Path.Combine(_config["ContentRoot"], logDirectory);
                }
                if (!Directory.Exists(LoggerSettings.LogDirectory))
                {
                    Directory.CreateDirectory(LoggerSettings.LogDirectory);
                }
                var path = Path.Combine(LoggerSettings.LogDirectory, LoggerSettings.LogJsonFileName);
                if (!File.Exists(path))
                {
                    File.AppendAllText(path, LoggerSettings.LoggingJsonContent);
                }
                ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
                configurationBuilder
                .SetBasePath(environment.ContentRootPath)
                .AddJsonFile(path, true, true);
                var configuration = configurationBuilder.Build();
                services.RemoveAll <ILoggerProviderConfigurationFactory>();
                services.RemoveAll(typeof(ILoggerProviderConfiguration <>));


                var type = typeof(ILoggerProviderConfigurationFactory).Assembly.DefinedTypes
                           .SingleOrDefault(t => t.Name == "LoggingConfiguration");
                services.RemoveAll(type);

                services.AddLogging(x =>
                {
                    x.AddConfiguration(configuration);
                    if (!x.Services.Any(t => t.ServiceType == typeof(ILoggerProvider)))
                    {
                        x.AddConsole();
                    }
                    x.Services.RemoveAll <IConfigureOptions <Logging.LoggerFilterOptions> >();
                    x.Services.AddSingleton <IConfigureOptions <Logging.LoggerFilterOptions> >(new LOG.LoggerFilterConfigureOptions(configuration));
                });
                services.Replace(ServiceDescriptor.Singleton <ILoggerFactory, LOG.LoggerFactory>());
            }
        }
예제 #26
0
        private static async Task RunAsync(string[] args, CancellationToken token)
        {
            args[2] = args[2].Replace("^>", ">").Replace("^<", "<");;



            var builder = new ConfigurationBuilder()
                          .SetBasePath(Directory.GetCurrentDirectory())
                          .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                          .AddEnvironmentVariables();
            var config = builder.Build();


            var _options       = new WebHostOptions(config);
            var appEnvironment = PlatformServices.Default.Application;

            var applicationName = _options.ApplicationName ?? appEnvironment.ApplicationName;

            var environment = new HostingEnvironment();

            environment.Initialize(applicationName, Directory.GetCurrentDirectory(), _options);


            var url      = "http://localhost:5000";
            var basePath = environment.IsProduction() ?
                           environment.ContentRootPath
                   : Path.Combine(environment.ContentRootPath, "artifacts", "app");


            using (var host = new WebHostBuilder()
                              .UseKestrel()
                              .UseConfiguration(config)
                              .UseUrls(url)
                              .UseWebRoot(basePath)
                              .UseContentRoot(Directory.GetCurrentDirectory())
                              .ConfigureLogging(l => l.AddConsole(config.GetSection("Logging")))
                              .ConfigureServices(ConfigureServices)
                              .Configure(app =>
            {
                // to do - wire in our HTTP endpoints

                app.UseStaticFiles();
                app.UseWebPages();
            })
                              .Build())
            {
                host.Start();// (token); //.Run(token);


                var result = await RequireJS.RunAsync <object, string>(host.Services.GetService <INodeServices>(), basePath.Replace("\\", "/"), "AppInsightsQueryReporter", url, new
                {
                    appId  = args[0],
                    appKey = args[1],
                    query  = args[2]
                });

                Console.WriteLine(result.ToString());



                //   await Task.Delay(Timeout.Infinite, token);
            }
        }