예제 #1
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure <CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded    = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

            //service DI
            //services.AddDbContext<DatabaseContext>(options =>
            //options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection_sql_server")));

            services.AddDbContext <DatabaseContext>(options =>
                                                    options.UseSqlite(Configuration.GetConnectionString("DefaultConnection_sqlite")));

            // Create Database when Database not found (code first)
            var serviceProvider = services.BuildServiceProvider();

            DatabaseInit.INIT(serviceProvider);

            //Web Service
            services.AddTransient <ProductService>();

            //Acess Hosting
            services.TryAddSingleton <IHttpContextAccessor, HttpContextAccessor>();

            //Service Upload Image
            services.AddSingleton <UtilService>();
        }
예제 #2
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();

            services.AddDbContext <DatabaseContext>(x => x.UseSqlServer(Configuration["ConnectionString:sqlcon"]));

            var serviceProvider = services.BuildServiceProvider();

            DatabaseInit.INIT(serviceProvider);

            // Declare CORS
            services.AddCors(options =>
            {
                options.AddPolicy("AllowAll", builder =>
                {
                    builder.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod();
                });

                // options.AddPolicy("AllowSpecific", builder =>
                // {
                //     builder.WithOrigins("http://localhost:xxx","http://localhost:yyy")
                //            .AllowAnyHeader().AllowAnyMethod();
                // });
            });
            services.AddControllersWithViews()
            .AddNewtonsoftJson(options =>
                               options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
                               );
        }
예제 #3
0
        static void Main(string[] args)
        {
            var config = new ConfigurationBuilder()
                         .SetBasePath(new FileInfo(Assembly.GetEntryAssembly().Location).DirectoryName)
                         .AddJsonFile("appsettings.json", true)
                         .Build();

            var logBuild = new LoggerConfiguration()
                           .WriteTo.Console()
                           .WriteTo.RollingFile(Path.Combine("logs", "dotnet.log"), retainedFileCountLimit: 10, fileSizeLimitBytes: 1024 * 30)
                           .MinimumLevel.Verbose();

            Log.Logger = logBuild.CreateLogger();

            var webHost = BuildWebHost(config["server:port"]);

            if (args.Length > 0 && args[0] == "develop")
            {
                ServerInfo.DriverDirectoy      = args[1];
                ServerInfo.DriverPattern       = args[2];
                ServerInfo.IsInDevelopmentMode = true;
            }
            else
            {
                ServerInfo.DriverDirectoy = new FileInfo(Assembly.GetExecutingAssembly().Location).DirectoryName;
            }
            var logger = SystemLogger.Instance;

            logger.LogInformation($"Starting...Version {ServerInfo.GetServerVersion()}, Datetime {ServerInfo.StartupTime}. Running .NET Core Version {GetNetCoreVersion()}");

            var db = webHost.Services.GetRequiredService <AutomaticaContext>();

            DatabaseInit.EnusreDatabaseCreated(webHost.Services);

            var serverId = db.Settings.SingleOrDefault(a => a.ValueKey == "ServerUID");

            if (serverId == null)
            {
                var guid = Guid.NewGuid();
                db.Settings.Add(new Setting
                {
                    ValueKey  = "ServerUID",
                    Value     = guid,
                    Group     = "SERVER.SETTINGS",
                    IsVisible = false,
                    Type      = (long)PropertyTemplateType.Text
                });
                ServerInfo.ServerUid = guid;
                db.SaveChanges();
            }
            else
            {
                ServerInfo.ServerUid = new Guid(serverId.ValueText);
            }

            webHost.Services.GetService <DiscoveryService>();
            webHost.Run();

            logger.LogInformation("Stopped...");
        }
예제 #4
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseStaticFiles();
            app.UseCookiePolicy();

            using (DatabaseInit dbInit = new DatabaseInit())
            {
            }

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=User}/{action=login}/{id?}");
            });
        }
예제 #5
0
        public App()
        {
            InitializeComponent();


            AdminUser user = new AdminUser();

            user.UserName     = "******";
            user.PasswordHash = "b";
            user.UserName     = "******";
            user.DBName       = "testUserDb";

            AdminUser = user;
            LoginViewModel lvm = new LoginViewModel();

            DatabaseInit dbInit = new DatabaseInit();

            Student                    = null;
            Assessment                 = null;
            AssessmentSession          = null;
            CurrentAssessmentSessionId = 0;
            IsGroup                    = false;
            CurrentQuestionId          = 0;

            CurrentAssessmentQuestions = new List <AssessmentQuestion>();
            CurrentQuestions           = new List <Question>();

            MainPage = new NavigationPage(new AdminHome());
            //MainPage = new SingleTextTemplate(new SingleTextTemplateViewModel(nextQuestion, nextAssessmentQuestion));
        }
        /// <summary>
        /// 初始化处理
        /// </summary>
        internal static ValueTask Initalization(string _, ConnectEventArgs connectEvent)
        {
            Log.Info("AntiRain初始化", "与onebot客户端连接成功,初始化资源...");
            //初始化配置文件
            Log.Info("AntiRain初始化", $"初始化用户[{connectEvent.LoginUid}]的配置");
            if (!ConfigManager.UserConfigFileInit(connectEvent.LoginUid) ||
                !ConfigManager.TryGetUserConfig(connectEvent.LoginUid, out var userConfig))
            {
                Log.Fatal("AntiRain初始化", "无法获取用户配置文件");
                Environment.Exit(-1);
                return(ValueTask.CompletedTask);
            }

            //在控制台显示启用模块
            Log.Info("已启用的模块",
                     $"\n{userConfig.ModuleSwitch}");
            //显示代理信息
            if (userConfig.ModuleSwitch.Hso && !string.IsNullOrEmpty(userConfig.HsoConfig.PximyProxy))
            {
                Log.Debug("Hso Proxy", userConfig.HsoConfig.PximyProxy);
            }

            //初始化数据库
            DatabaseInit.UserDataInit(connectEvent);

            //初始化定时器线程
            if (userConfig.ModuleSwitch.Bili_Subscription)
            {
                SubscriptionTimer.TimerEventAdd(connectEvent);
            }

            return(ValueTask.CompletedTask);
        }
예제 #7
0
        /// <summary>
        /// 初始化处理
        /// </summary>
        internal static ValueTask Initalization(object sender, ConnectEventArgs connectEvent)
        {
            ConsoleLog.Info("AntiRain初始化", "与onebot客户端连接成功,初始化资源...");
            //初始化配置文件
            ConsoleLog.Info("AntiRain初始化", $"初始化用户[{connectEvent.LoginUid}]配置");
            Config config = new Config(connectEvent.LoginUid);

            config.UserConfigFileInit();
            config.LoadUserConfig(out UserConfig userConfig, false);


            //在控制台显示启用模块
            ConsoleLog.Info("已启用的模块",
                            $"\n{userConfig.ModuleSwitch}");
            //显示代理信息
            if (userConfig.ModuleSwitch.Hso && !string.IsNullOrEmpty(userConfig.HsoConfig.PximyProxy))
            {
                ConsoleLog.Debug("Hso Proxy", userConfig.HsoConfig.PximyProxy);
            }

            //初始化数据库
            DatabaseInit.Init(connectEvent);

            //初始化定时器线程
            if (userConfig.ModuleSwitch.Bili_Subscription)
            {
                ConsoleLog.Debug("Timer Init", $"flash span = {userConfig.SubscriptionConfig.FlashTime}");
                TimerEventParse.TimerAdd(connectEvent, userConfig.SubscriptionConfig.FlashTime);
            }

            return(ValueTask.CompletedTask);
        }
예제 #8
0
파일: Startup.cs 프로젝트: t6tg/APIdotnet
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
            services.AddDbContext <DatabaseContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection_sql_server")));
            var serviceProvider = services.BuildServiceProvider();

            DatabaseInit.INIT(serviceProvider);
        }
예제 #9
0
        public TruckModelRepositoryTests()
        {
            var          context = new TruckManagerContext(dbContextOptions);
            DatabaseInit db      = new DatabaseInit();

            db.Seed(context);

            repo = new TruckModelRepository(context);
        }
예제 #10
0
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);

            DatabaseInit.ResetIfDirty();
        }
예제 #11
0
파일: Program.cs 프로젝트: yesokie/DMSPSHN
 private static void LoadConfig()
 {
     ConfigurationHelper.Init();
     RedisConnection.Init(ConfigurationHelper.GetInteger("Redis:Db"), ConfigurationHelper.GetString("Redis:Host"), ConfigurationHelper.GetInteger("Redis:Port"), ConfigurationHelper.GetString("Redis:PassWd"));
     BsonSerializer.RegisterSerializer(typeof(DateTime), new MyMongoDBDateTimeSerializer());
     LogHelper.Init(ConfigurationHelper.GetString("Mongo:ConnectionString"), ConfigurationHelper.GetString("Mongo:DatabaseName"), ConfigurationHelper.GetBoolean("Mongo:IsReplicaSet"), ConfigurationHelper.GetString("Mongo:ReplicaSetName"));
     BaseProcs.Init(MongoConnect.GetHelper(ConfigurationHelper.GetString("Mongo:ConnectionString"), ConfigurationHelper.GetString("Mongo:DatabaseName"), 10, ConfigurationHelper.GetBoolean("Mongo:IsReplicaSet"), ConfigurationHelper.GetString("Mongo:ReplicaSetName"))).Wait();
     DatabaseInit.Init();
     //AccountProcs.Init(MongoConnect.GetHelper(ConfigurationHelper.GetString("AccountDb:ConnectionString"), ConfigurationHelper.GetString("AccountDb:DatabaseName"), 10, ConfigurationHelper.GetBoolean("AccountDb:IsReplicaSet"), ConfigurationHelper.GetString("AccountDb:ReplicaSetName"))).Wait();
     CultureInfo.CurrentCulture = new CultureInfo("vi-VN");
 }
예제 #12
0
        public static void ConfigDatabase(this IServiceCollection services, IConfiguration configuration)
        {
            // Connection Database SqlServar
            services.AddDbContext <Database.DatabaseContext>(option =>
                                                             option.UseSqlServer(configuration.GetConnectionString("DefaultConnection_sql_server")));

            // Check Database Ensure Created
            var serviceProvider = services.BuildServiceProvider();

            DatabaseInit.INIT(serviceProvider);
        }
 private void Awake()
 {
     if (instance == null)
     {
         instance = this as DatabaseInit;
         DontDestroyOnLoad(gameObject);
     }
     else if (instance != null)
     {
         Destroy(gameObject);
     }
 }
예제 #14
0
        public void Setup()
        {
            if (!DatabaseInit.DatabaseExists("BCAPIDatabase_Dev"))
            {
                DatabaseInit.CreateDatabase("BCAPIDatabase_Dev");
            }

            _transaction = new TransactionScope(TransactionScopeOption.Required,
                                                new TransactionOptions {
                IsolationLevel = IsolationLevel.ReadUncommitted, Timeout = new TimeSpan(0, 0, 10)
            });
        }
예제 #15
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                DatabaseInit.Seed(app);
            }

            app.UseAuthMiddleware();
            app.UseAuthentication();
            app.UseCors("AllowAll");
            app.UseMvc();
        }
예제 #16
0
        static async Task Main(string[] args)
        {
            Log.Logger = new LoggerConfiguration()
                         .Enrich.FromLogContext()
                         .WriteTo.Console()
                         .MinimumLevel.Verbose()
                         .CreateLogger();

            Log.Logger.Information("Starting Automatica.Core.CI database tool");

            var config = new ConfigurationBuilder()
                         .SetBasePath(new FileInfo(Assembly.GetEntryAssembly().Location).DirectoryName)
                         .AddJsonFile("appsettings.json", true)
                         .Build();

            var fi = new FileInfo(Assembly.GetEntryAssembly().Location);

            if (File.Exists(Path.Combine(fi.DirectoryName, DatabaseConstants.DatabaseInitName)))
            {
                File.Delete(Path.Combine(fi.DirectoryName, DatabaseConstants.DatabaseInitName));
            }

            var hostBuilder = new HostBuilder().ConfigureServices((hostContext, services) =>
            {
                var startup = new Startup(config);
                startup.ConfigureServices(services);
            }
                                                                  ).Build();


            string loadDirectory = "";

            if (args.Length > 0)
            {
                loadDirectory = args[0];
            }
            else
            {
                loadDirectory = fi.DirectoryName;
            }

            DatabaseInit.EnsureDatabaseCreated(hostBuilder.Services);

            var server = new CoreServer(hostBuilder.Services);
            await server.Load(loadDirectory, "*.dll");


            Console.WriteLine($"Done....");
            Environment.Exit(0);
        }
예제 #17
0
        public static void Main(string[] args)
        {
            Thread.CurrentThread.CurrentCulture = new CultureInfo(ConfigurationConstants.APP_CULTURE);
            IWebHostBuilder builder = CreateWebHostBuilder(args);
            IWebHost        host    = builder.Build();

            using IServiceScope scope = host.Services.CreateScope();
            System.IServiceProvider services = scope.ServiceProvider;
            DatabaseContext         context  = services.GetRequiredService <DatabaseContext>();

            DatabaseInit.Execute(context);

            host.Run();
        }
예제 #18
0
        public static void AppEnable(object sender, CQAppEnableEventArgs e)
        {
            try
            {
                //打开控制台
                //ConsoleLog.AllocConsole();
                Console.Title = @"SuiseiBot";

                //初始化配置文件
                Config config = new Config(e.CQApi.GetLoginQQ().Id);
                //数据库初始化
                ConsoleLog.Info("初始化", "SuiseiBot初始化");
                //设置Log等级
                ConsoleLog.SetLogLevel(config.LoadedConfig.LogLevel);
                //读取应用信息
                ConsoleLog.Debug("APP AuthCode(native plugin ID)", e.CQApi.AppInfo.AuthCode);
                //修改环境文件夹,初始化环境
                ConsoleLog.Debug("获取到环境路径", Directory.GetCurrentDirectory());
                Environment.SetEnvironmentVariable("Path", Directory.GetCurrentDirectory());
                //显示Log等级
                ConsoleLog.Debug("Log Level", config.LoadedConfig.LogLevel);
                //在控制台显示启用模块
                ConsoleLog.Info("已启用的模块",
                                $"\n{config.LoadedConfig.ModuleSwitch}");
                DatabaseInit.Init(e);

                //将关键词和帮助文本写入内存
                WholeMatchCmd.KeywordInit();
                PCRGuildCmd.PCRGuildCommandInit();
                GuildCommandHelp.InitHelpText();
                KeywordCmd.SpecialKeywordsInit(e.CQApi);

                //初始化定时器线程
                if (config.LoadedConfig.ModuleSwitch.Bili_Subscription || config.LoadedConfig.ModuleSwitch.PCR_Subscription)
                {
                    timer = new TimerInit(e.CQApi, config.LoadedConfig.SubscriptionConfig.FlashTime);
                }
                e.Handler = true;
            }
            catch (Exception exception)
            {
                ConsoleLog.Error("error", ConsoleLog.ErrorLogBuilder(exception));
            }
        }
예제 #19
0
        public static int Main(string[] args)
        {
            AppDomain.CurrentDomain.ProcessExit += MainDispose;

            try
            {
                Directory.CreateDirectory(DataPath);

                DbClient = DatabaseInit.ConnectDatabase(DbPath).GetAwaiter().GetResult();
            }
            catch (System.Exception exc)
            {
                Console.WriteLine(exc.Message);
                return(1);
            }

            CreateHostBuilder(args).Build().Run();

            return(0);
        }
예제 #20
0
        public void TestDatabaseInit()
        {
            if (File.Exists("automatica.core-test.db"))
            {
                File.Delete("automatica.core-test.db");
            }

            var mockConfSection = new Mock <IConfigurationSection>();

            mockConfSection.SetupGet(m => m[It.Is <string>(s => s == "AutomaticaDatabaseType")]).Returns("sqlite");
            mockConfSection.SetupGet(m => m[It.Is <string>(s => s == "AutomaticaDatabaseSqlite")]).Returns("Data Source=automatica.core-test.db");

            var mockConfiguration = new Mock <IConfiguration>();

            mockConfiguration.Setup(a => a.GetSection(It.Is <string>(s => s == "ConnectionStrings"))).Returns(mockConfSection.Object);


            var serviceProviderMock = new Mock <IServiceProvider>();

            serviceProviderMock.Setup(a => a.GetService(It.Is <Type>(s => s == typeof(IConfiguration)))).Returns(mockConfiguration.Object);
            serviceProviderMock.Setup(a => a.GetService(It.Is <Type>(s => s == typeof(AutomaticaContext)))).Returns(new AutomaticaContext(mockConfiguration.Object, true));
            serviceProviderMock.Setup(a => a.GetService(It.Is <Type>(s => s == typeof(IVisualisationFactory)))).Returns(new VisuTempInit());

            try
            {
                DatabaseInit.EnsureDatabaseCreated(serviceProviderMock.Object);
                Assert.True(true);
            }
            catch (Exception e)
            {
                Assert.True(false);
                Console.Error.WriteLine($"{e}");
            }
            finally
            {
                if (File.Exists("automatica.core-test.db"))
                {
                    File.Delete("automatica.core-test.db");
                }
            }
        }
예제 #21
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseHsts();
            }
            using (IServiceScope serviceScope = app.ApplicationServices.CreateScope())
            {
                MasterContext context = serviceScope.ServiceProvider.GetRequiredService <MasterContext>();
                context.Database.Migrate();
            }

            using (DatabaseInit database = new DatabaseInit())
            {
                database.InitializeDb();
            }
            app.UseHttpsRedirection();
            app.UseMvc();
        }
예제 #22
0
        public BaseControllerTest()
        {
            var tmpFolder = Path.Combine(Path.GetTempPath(), DatabaseFilePath);

            Directory.CreateDirectory(tmpFolder);

            var mockConfSection = new Mock <IConfigurationSection>();

            mockConfSection.SetupGet(m => m[It.Is <string>(s => s == "AutomaticaDatabaseType")]).Returns("sqlite");
            mockConfSection.SetupGet(m => m[It.Is <string>(s => s == "AutomaticaDatabaseSqlite")]).Returns($"Data Source={tmpFolder}/{DatabaseFilePath}.db");

            var mockConfiguration = new Mock <IConfiguration>();

            mockConfiguration.Setup(a => a.GetSection(It.Is <string>(s => s == "ConnectionStrings"))).Returns(mockConfSection.Object);

            var config = mockConfiguration.Object;

            Configuration = config;

            var services = new ServiceCollection();

            services.AddSingleton(config);
            services.AddAutomaticaCoreService(config, false);
            services.AddDbContext <AutomaticaContext>();
            services.AddSingleton <T>();

            services.AddAutomaticaPushServices(config, false);

            var hubClients  = new Mock <IHubClients>();
            var clientProxy = new Mock <IClientProxy>();

            hubClients.SetupGet(clients => clients.All).Returns(() => clientProxy.Object);
            hubClients.Setup(clients => clients.Group(It.IsAny <string>())).Returns(() => clientProxy.Object);

            var dataHubMoq = new Mock <IHubContext <DataHub> >();

            dataHubMoq.SetupGet(a => a.Clients).Returns(() => hubClients.Object);

            services.AddSingleton(dataHubMoq.Object);
            var telegramHubMoq = new Mock <IHubContext <TelegramHub> >();

            services.AddSingleton(telegramHubMoq.Object);

            services.AddSingleton <ILogger <NotifyDriverHandler> >(NullLogger <NotifyDriverHandler> .Instance);
            services.AddSingleton <ILogger <RuleEngineDispatcher> >(NullLogger <RuleEngineDispatcher> .Instance);
            services.AddSingleton <ILogger <LogicLoader> >(NullLogger <LogicLoader> .Instance);
            services.AddSingleton <ILogger <DriverLoader> >(NullLogger <DriverLoader> .Instance);
            services.AddSingleton <ILogger <PluginHandler> >(NullLogger <PluginHandler> .Instance);
            services.AddSingleton <ILogger <LearnMode> >(NullLogger <LearnMode> .Instance);
            services.AddSingleton <ILogger>(NullLogger.Instance);

            var mqttServerMock = new Mock <IMqttServer>();

            services.AddSingleton <IMqttServer>(mqttServerMock.Object);


            ServiceProvider = services.BuildServiceProvider();

            DatabaseInit.EnsureDatabaseCreated(ServiceProvider);

            Controller = ServiceProvider.GetRequiredService <T>();
        }
예제 #23
0
        public async Task ModulsAsync([Remainder] string args = null)
        {
            // Check if right Channel
            bool check = ReadChannelGeneralAdmin();

            if (!check)
            {
                return;
            }

            // If Mod Role not Set
            if (ModRoleID == 0)
            {
                await SendToGeneralChannelAdminAsync("Die Mod rolle wurde noch nicht gesetzt, bitte dem SeverAdministrator bescheid geben!");

                return;
            }

            if (args == null)
            {
                await SendToGeneralChannelAdminAsync(Context.User.Mention + " Du hast zu wenige Argumente angegeben. Bitte nutze den Befehl wie folgt:\n>>> `" +
                                                     Prefix + "edituser <UserID> <Counter_Streak> <Counter_Highest_Streak> <CounterAll> <Last_Date>` \n" +
                                                     "**BITTE BEACHTEN**: `<Last_Date>` **MUSS** im Format `DD.MM.YYYY` angegeben werden. Eine falsche Formation **WIRD** zu Fehlern bei den nächsten Zählungen führen!");

                return;
            }
            args = args.ToLower();
            string[] countArgs = args.Split(' ');

            // Check if to less or much Arguments
            if (countArgs.Length < 5)
            {
                await SendToGeneralChannelAdminAsync(Context.User.Mention + " Zu wenige Agumente!");
            }
            else if (countArgs.Length > 5)
            {
                await SendToGeneralChannelAdminAsync(Context.User.Mention + " Zu viele Agumente!");
            }
            else
            {
                // Check if Member has ModRole
                bool memberHasModRole = false;
                foreach (var item in Context.Guild.GetRole(ModRoleID).Members)
                {
                    if (item.Id == Context.User.Id)
                    {
                        memberHasModRole = true;
                    }
                }
                // User is Mod or Admin
                if (memberHasModRole || Context.Guild.GetUser(Context.User.Id).GuildPermissions.Administrator)
                {
                    var          db      = new DatabaseInit().connect();
                    TablesHeader dbTable = new TablesHeader(db);

                    var       table1337 = dbTable.Table1337;
                    Table1337 updateUser;
                    try
                    {
                        // Check if UserID is number
                        ulong userID = 0;
                        try
                        {
                            userID = Convert.ToUInt64(countArgs[0]);
                        }
                        catch (Exception)
                        {
                            await SendToGeneralChannelAdminAsync("<UserID> war keine Zahl!");

                            return;
                        }
                        // Get User from Database
                        updateUser = dbTable.Table1337.Single((item) => item.userid == userID);
                    }
                    catch (Exception)
                    {
                        await SendToGeneralChannelAdminAsync("Es wurde kein User mit der ID: " + countArgs[0] + " gefunden");

                        return;
                    }
                    // Check If args are Numbers
                    // <Counter_Streak>
                    try
                    {
                        updateUser.counter_streak = Convert.ToUInt32(countArgs[1]);
                    }
                    catch (Exception e)
                    {
                        await SendToGeneralChannelAdminAsync("Meow:\n" + e);
                        await SendToGeneralChannelAdminAsync("<Counter_Streak> war keine Positive Zahl!");

                        return;
                    }
                    // <Counter_Highest_Streak>
                    try
                    {
                        updateUser.counter_longest_streak = Convert.ToUInt32(countArgs[2]);
                    }
                    catch (Exception)
                    {
                        await SendToGeneralChannelAdminAsync("<Counter_Highest_Streak> war keine Positive Zahl!");

                        return;
                    }
                    try
                    {
                        updateUser.counter_all = Convert.ToUInt32(countArgs[3]);
                    }
                    catch (Exception)
                    {
                        await SendToGeneralChannelAdminAsync("<CounterAll> war keine Positive Zahl!");

                        return;
                    }

                    updateUser.date_last = countArgs[4];
                    dbTable.SubmitChanges();
                    db.Close();

                    await SendToGeneralChannelAdminAsync("User: "******" wurde erfolgreich Editiert\n" +
                                                         "Seine neuen Werte lauten wie Folgt:\n" +
                                                         ">>> Counter Streak: `" + countArgs[1] + "`\n" +
                                                         "Counter Longest Streak: `" + countArgs[2] + "`\n" +
                                                         "Counter Alltime: `" + countArgs[3] + "`\n" +
                                                         "Date Last: `" + countArgs[4] + "`");

                    LogMain("User: "******" wurde von " + Context.User.Username + " mit der ID " + Context.User.Id + " editiert.", LogLevel.Warning);
                }
                else
                {
                    await SendToGeneralChannelAdminAsync("Du hast keine Berechtigung. Du musst im besitz der `" + Context.Guild.GetRole(ModRoleID).Name + "` Rolle sein.");
                }
            }
        }
예제 #24
0
        static void Main(string[] args)
        {
            var config = new ConfigurationBuilder()
                         .SetBasePath(ServerInfo.GetConfigDirectory())
                         .AddJsonFile("appsettings.json", false)
                         .AddEnvironmentVariables()
                         .Build();

            var logBuild = LogConfiguration.ConfigureLogger();

            Log.Logger = logBuild.CreateLogger();

            foreach (DictionaryEntry env in Environment.GetEnvironmentVariables())
            {
                var envVar = $"{env.Key}={env.Value}";
                Log.Logger.Debug($"Using env variable: {envVar}");
            }

            var logger = SystemLogger.Instance;

            if (!File.Exists(Path.Combine(ServerInfo.GetConfigDirectory(), "appsettings.json")))
            {
                logger.LogError($"Could not find appsettings.json in {ServerInfo.GetConfigDirectory()}");
            }

            if (!String.IsNullOrEmpty(Environment.GetEnvironmentVariable("MQTT_LOG_VERBOSE")))
            {
                MqttNetGlobalLogger.LogMessagePublished += (s, e) =>
                {
                    var trace =
                        $"mqtt >> [{e.TraceMessage.ThreadId}] [{e.TraceMessage.Source}] [{e.TraceMessage.Level}]: {e.TraceMessage.Message}";
                    if (e.TraceMessage.Exception != null)
                    {
                        trace += Environment.NewLine + e.TraceMessage.Exception.ToString();
                    }

                    logger.LogDebug(trace);
                };
            }

            var webHost = BuildWebHost(config["server:port"]);

            if (args.Length > 0 && args[0] == "develop")
            {
                ServerInfo.PluginDirectory     = args[1];
                ServerInfo.PluginFilePattern   = args[2];
                ServerInfo.IsInDevelopmentMode = true;
            }
            else
            {
                var pluginDir = Environment.GetEnvironmentVariable("AUTOMATICA_PLUGIN_DIR");
                if (!String.IsNullOrEmpty(pluginDir))
                {
                    ServerInfo.PluginDirectory = pluginDir;
                }
                else
                {
                    ServerInfo.PluginDirectory = new FileInfo(Assembly.GetExecutingAssembly().Location).DirectoryName;
                }
            }

            logger.LogInformation($"Starting...Version {ServerInfo.GetServerVersion()}, Datetime {ServerInfo.StartupTime}. Running .NET Core Version {GetNetCoreVersion()}");

            var db = webHost.Services.GetRequiredService <AutomaticaContext>();

            DatabaseInit.EnsureDatabaseCreated(webHost.Services);



            var serverId = db.Settings.SingleOrDefault(a => a.ValueKey == "ServerUID");

            if (serverId == null)
            {
                var guid = Guid.NewGuid();
                db.Settings.Add(new Setting
                {
                    ValueKey  = "ServerUID",
                    Value     = guid,
                    Group     = "SERVER.SETTINGS",
                    IsVisible = false,
                    Type      = (long)PropertyTemplateType.Text
                });
                ServerInfo.ServerUid = guid;
                db.SaveChanges();
            }
            else
            {
                ServerInfo.ServerUid = new Guid(serverId.ValueText);
            }

            webHost.Services.GetService <DiscoveryService>();
            webHost.Run();

            logger.LogInformation("Stopped...");
        }
예제 #25
0
        /// <summary>
        /// This method creates initial Cart
        /// </summary>
        /// <returns></returns>
        public IActionResult InitCart()
        {
            int count = DatabaseInit.InitCart(_repository);

            return(Ok(count));
        }
예제 #26
0
        private async Task ShowUser(string args, ShowUserEnum su)
        {
            if (!ReadChannelGeneralAdmin())
            {
                return;
            }

            if (ModRoleID == 0)
            {
                await SendToGeneralChannelAdminAsync("Die Mod rolle wurde noch nicht gesetzt, bitte dem SeverAdministrator bescheid geben!");

                return;
            }

            if (args == null)
            {
                if (su == ShowUserEnum.Today)
                {
                    await SendToGeneralChannelAdminAsync(Context.User.Mention + " Du hast zu wenige Argumente angegeben. Bitte nutze den Befehl wie folgt:\n>>> `" +
                                                         Prefix + "showusertoday <UserID>`");
                }
                else if (su == ShowUserEnum.Yesterday)
                {
                    await SendToGeneralChannelAdminAsync(Context.User.Mention + " Du hast zu wenige Argumente angegeben. Bitte nutze den Befehl wie folgt:\n>>> `" +
                                                         Prefix + "showuseryesterday <UserID>`");
                }
                return;
            }
            args = args.ToLower();
            string[] countArgs = args.Split(' ');

            if (countArgs.Length > 1)
            {
                await SendToGeneralChannelAdminAsync(Context.User.Mention + " Zu viele Agumente!");
            }
            else
            {
                bool memberHasModRole = false;
                foreach (var item in Context.Guild.GetRole(ModRoleID).Members)
                {
                    if (item.Id == Context.User.Id)
                    {
                        memberHasModRole = true;
                    }
                }

                if (memberHasModRole || Context.Guild.GetUser(Context.User.Id).GuildPermissions.Administrator)
                {
                    var          db      = new DatabaseInit().connect();
                    TablesHeader dbTable = new TablesHeader(db);

                    Table1337   updateUserToday     = new Table1337();
                    Table1337_2 updateUserYesterday = new Table1337_2();

                    try
                    {
                        // Check if UserID is number
                        ulong userID = 0;
                        try
                        {
                            userID = Convert.ToUInt64(countArgs[0]);
                        }
                        catch (Exception)
                        {
                            await SendToGeneralChannelAdminAsync("<UserID> war keine Zahl!");

                            return;
                        }
                        // Get User from Database
                        if (su == ShowUserEnum.Today)
                        {
                            updateUserToday = dbTable.Table1337.Single((item) => item.userid == userID);
                        }
                        else if (su == ShowUserEnum.Yesterday)
                        {
                            updateUserYesterday = dbTable.Table1337_2.Single((item) => item.userid == userID);
                        }
                    }
                    catch (Exception)
                    {
                        await SendToGeneralChannelAdminAsync("Es wurde kein User mit der ID: " + countArgs[0] + " gefunden");

                        return;
                    }
                    if (su == ShowUserEnum.Today)
                    {
                        await SendToGeneralChannelAdminAsync("User Informationen\n" +
                                                             ">>> Name: `" + updateUserToday.username + "`\n" +
                                                             "ID: `" + updateUserToday.userid.ToString() + "`\n" +
                                                             "Counter Streak: `" + updateUserToday.counter_streak + "`\n" +
                                                             "Counter Longest Streak: `" + updateUserToday.counter_longest_streak + "`\n" +
                                                             "Counter All: `" + updateUserToday.counter_all + "`\n" +
                                                             "Date Begin: `" + updateUserToday.date_begin + "`\n" +
                                                             "Date Last: `" + updateUserToday.date_last + "`");
                    }
                    else if (su == ShowUserEnum.Yesterday)
                    {
                        await SendToGeneralChannelAdminAsync("User Informationen\n" +
                                                             ">>> Name: `" + updateUserYesterday.username + "`\n" +
                                                             "ID: `" + updateUserYesterday.userid.ToString() + "`\n" +
                                                             "Counter Streak: `" + updateUserYesterday.counter_streak + "`\n" +
                                                             "Counter Longest Streak: `" + updateUserYesterday.counter_longest_streak + "`\n" +
                                                             "Counter All: `" + updateUserYesterday.counter_all + "`\n" +
                                                             "Date Begin: `" + updateUserYesterday.date_begin + "`\n" +
                                                             "Date Last: `" + updateUserYesterday.date_last + "`");
                    }
                }
                else
                {
                    await SendToGeneralChannelAdminAsync("Du hast keine Berechtigung. Du musst im besitz der `" + Context.Guild.GetRole(ModRoleID).Name + "` Rolle sein.");
                }
            }
        }
        public static async Task Main()
        {
            //[Description(@"^谁是[\u4e00-\u9fa5]+$")] FindChara,//TODO 最后一个PCR功能(
            //修改控制台标题
            Console.Title = @"AntiRain";
            Log.Info("AntiRain初始化", "AntiRain初始化...");
            //初始化配置文件
            Log.Info("AntiRain初始化", "初始化服务器全局配置...");

            if (!ConfigManager.GlobalConfigFileInit() || !ConfigManager.TryGetGlobalConfig(out var globalConfig))
            {
                Log.Fatal("AntiRain初始化", "无法获取用户配置文件");
                Environment.Exit(-1);
                return;
            }

            Log.SetLogLevel(globalConfig.LogLevel);
            //显示Log等级
            Log.Debug("Log Level", globalConfig.LogLevel);

            //初始化资源数据库
            Log.Info("AntiRain初始化", "初始化资源...");
            DatabaseInit.GlobalDataInit();

            //检查是否开启角色数据下载
            //TODO 咕一段时间
            // if (globalConfig.ResourceConfig.UseCharaDatabase)
            // {
            //     //更新PCR角色数据库
            //     CharaParser charaParser = new CharaParser();
            //     if(!await charaParser.UpdateCharaNameByCloud()) Log.Error("AntiRain初始化","更新角色数据库失败");
            // }

            //初始化字符编码
            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);

            //指令匹配初始化
            Command.CommandAdapter.PCRGuildBattlecmdResourseInit();

            //启动机器人WebAPI服务器
            Log.Info("AntiRain初始化", "启动机器人WebAPI服务器...");
            ConsoleInterface = new ConsoleInterface(globalConfig.AntiRainAPILocation, globalConfig.AntiRainAPIPort);

            Log.Info("AntiRain初始化", "启动反向WS服务器...");
            //初始化服务器
            ISoraService server = SoraServiceFactory.CreateService(new ServerConfig
            {
                Host                     = globalConfig.Location,
                Port                     = globalConfig.Port,
                AccessToken              = globalConfig.AccessToken,
                UniversalPath            = globalConfig.UniversalPath,
                HeartBeatTimeOut         = TimeSpan.FromSeconds(globalConfig.HeartBeatTimeOut),
                ApiTimeOut               = TimeSpan.FromMilliseconds(globalConfig.OnebotApiTimeOut),
                SuperUsers               = globalConfig.SuperUsers,
                EnableSoraCommandManager = true
            });

            //服务器回调
            //初始化
            server.Event.OnClientConnect += InitalizationEvent.Initalization;
            //群聊事件
            server.Event.OnGroupMessage += GroupMessageEvent.GroupMessageParse;
            //私聊事件
            server.Event.OnPrivateMessage += PrivateMessageEvent.PrivateMessageParse;
            //群聊戳一戳
            server.Event.OnGroupPoke += GroupPokeEvent.GroupPokeEventParse;
            //关闭连接事件处理
            server.ConnManager.OnCloseConnectionAsync += SubscriptionTimer.DelTimerEvent;
            server.ConnManager.OnHeartBeatTimeOut     += SubscriptionTimer.DelTimerEvent;

            //启动服务器
            await server.StartService().RunCatch(BotUtils.BotCrash);

            await Task.Delay(-1);
        }
예제 #28
0
        public async Task MainAsync()
        {
            Console.OutputEncoding = System.Text.Encoding.Unicode;

            //Init for Log
            LogInit();
            // Init DB
            DatabaseInit db = new DatabaseInit();

            db.InitDB();

            // New Client
            // Load config.xml if doesn't exist create one. Both with exception handling.
            this._configXML = this.configClass.LoadConfigXML();

            this._client = new DiscordSocketClient(new DiscordSocketConfig
            {
                MessageCacheSize    = 200,
                LogLevel            = LogSeverity.Info,
                AlwaysDownloadUsers = true,
                LargeThreshold      = 250
            });

            // New CommandService
            this._commands = new CommandService(new CommandServiceConfig
            {
                // Config Here if needed
                LogLevel = LogSeverity.Info
            });

            // New CommandHandlingService
            this._cmdHandService = new CommandHandlingService(this._client, this._commands, this._configXML, this._devMode);

            // Add Own Features
            ListenFor1337 _listenFor1337 = new ListenFor1337(_client, _cmdHandService, _devMode);

            // New ServiceCollection
            this._services = new ServiceCollection()
                             .AddSingleton(this._client)
                             .AddSingleton(this._commands)
                             .AddSingleton(this._cmdHandService)
                             // Add More Services below if needed
                             .AddSingleton(_listenFor1337)
                             .BuildServiceProvider();

            // Init CommandHandlingService
            await _cmdHandService.InitializeAsync(_services);

            this._client.Log        += Log;
            this._client.UserJoined += UserJoined;


            if (this._configXML != null)
            {
                await _client.LoginAsync(TokenType.Bot, this.configClass.GetToken(_configXML));
            }
            else
            {
                CloseByInvalidToken();
            }
            await _client.StartAsync();

            // Block this task until the program is closed.
            await Task.Delay(-1);
        }
예제 #29
0
 public HomeController(DatabaseInit d)
 {
     data = d;
 }
예제 #30
0
        static async Task Main()
        {
            //修改控制台标题
            Console.Title = @"AntiRain";
            Log.Info("AntiRain初始化", "AntiRain初始化...");
            //初始化配置文件
            Log.Info("AntiRain初始化", "初始化服务器全局配置...");
            //全局文件初始化不需要uid,不使用构造函数重载
            ConfigManager configManager = new();

            configManager.GlobalConfigFileInit();
            configManager.LoadGlobalConfig(out var globalConfig, false);

            Log.SetLogLevel(globalConfig.LogLevel);
            //显示Log等级
            Log.Debug("Log Level", globalConfig.LogLevel);

            //初始化资源数据库
            Log.Info("AntiRain初始化", "初始化资源...");
            DatabaseInit.GlobalDataInit();

            //检查是否开启角色数据下载
            //TODO 咕一段时间
            // if (globalConfig.ResourceConfig.UseCharaDatabase)
            // {
            //     //更新PCR角色数据库
            //     CharaParser charaParser = new CharaParser();
            //     if(!await charaParser.UpdateCharaNameByCloud()) Log.Error("AntiRain初始化","更新角色数据库失败");
            // }

            //初始化字符编码
            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);

            //指令匹配初始化
            Command.CommandAdapter.KeywordResourseInit();
            Command.CommandAdapter.RegexResourseInit();
            Command.CommandAdapter.PCRGuildBattlecmdResourseInit();

            //启动机器人WebAPI服务器
            Log.Info("AntiRain初始化", "启动机器人WebAPI服务器...");
            ConsoleInterface = new ConsoleInterface(globalConfig.AntiRainAPILocation, globalConfig.AntiRainAPIPort);

            Log.Info("AntiRain初始化", "启动反向WS服务器...");
            //初始化服务器
            SoraWSServer server = new(new ServerConfig
            {
                Location = globalConfig.Location,
                Port = globalConfig.Port,
                AccessToken = globalConfig.AccessToken,
                UniversalPath = globalConfig.UniversalPath,
                ApiPath = globalConfig.ApiPath,
                EventPath = globalConfig.EventPath,
                HeartBeatTimeOut = globalConfig.HeartBeatTimeOut,
                ApiTimeOut = globalConfig.OnebotApiTimeOut
            });

            //服务器回调
            //初始化
            server.Event.OnClientConnect += InitalizationEvent.Initalization;
            //群聊事件
            server.Event.OnGroupMessage += GroupMessageEvent.GroupMessageParse;
            //私聊事件
            server.Event.OnPrivateMessage += PrivateMessageEvent.PrivateMessageParse;
            //群聊戳一戳
            server.Event.OnGroupPoke += GroupPokeEvent.GroupPokeEventParse;
            //关闭连接事件处理
            server.ConnManager.OnCloseConnectionAsync += TimerEventParse.StopTimer;
            server.ConnManager.OnHeartBeatTimeOut     += TimerEventParse.StopTimer;

            //启动服务器
            await server.StartServer().RunCatch(BotUtils.BotCrash);
        }