예제 #1
0
        public static Task Main(string[] args)
        {
            var options = new MainOptions
            {
                CommandLineArguments           = args,
                FirstLoggingInformationMessage = "~~ Sample Hosted Services Application ~~",
                LogAssemblyInformation         = true,
                LastLoggingInformationMessage  = "-- Sample Hosted Services Application has ended/terminated --",
                ConfigureCustomServices        = new Action <HostBuilderContext, IServiceCollection>((hostContext, services) =>
                {
                    services.AddHostedService <HostedService1>();
                    services.AddHostedService <HostedService2>();
                }),
                CustomPreHostRunAsyncAction = new Action <IHost>(host =>
                {
                    using (var scope = host.Services.CreateScope())
                    {
                        var services = scope.ServiceProvider;
                        var logger   = services.GetRequiredService <ILogger <Program> >();
                        logger.LogInformation($"Inside the {nameof(MainOptions.CustomPreHostRunAsyncAction)} method - before hosts all start. Woot!");
                    }
                })
            };


            return(SimpleHosting.Program.Main <Program>(options));
        }
예제 #2
0
        private void ContentDialog_PrimaryButtonClick(ContentDialog sender, ContentDialogButtonClickEventArgs args)
        {
            List <ulong> users   = new List <ulong>();
            List <ulong> ignores = new List <ulong>();

            if (usersBox.Text.Split(',').Length != 0 && usersBox.Text != "")
            {
                foreach (string user in usersBox.Text.Split(','))
                {
                    users.Add(Convert.ToUInt64(user));
                }
            }

            if (ignoreBox.Text.Split(',').Length != 0 && ignoreBox.Text != "")
            {
                foreach (string ignore in ignoreBox.Text.Split(','))
                {
                    ignores.Add(Convert.ToUInt64(ignore));
                }
            }

            MO = new MainOptions()
            {
                Ignores = ignores,
                Users   = users,
                Timeout = toBox.Text == "" ? 0 : Convert.ToInt32(toBox.Text)
            };
        }
예제 #3
0
        /// <summary>
        /// Initializes the components needed by the application.
        /// </summary>
        /// <returns>if true, we can launch application</returns>
        private static bool Start()
        {
            //Lecture des préférences
            try {
                options = MainOptions.Load();
            } catch (Exception e) {
                //90% of chance to get a InvalidOperationException containing the XML related exception in InnerException property
                if (e.InnerException != null)
                {
                    e = e.InnerException;
                }
                //
                DialogResult result = MessageBox.Show(
                    String.Format(
                        "Fichier de préférence : {0}\n\nErreur : {1}\n\nSi vous venez de modifier manuellement votre fichier, cliquez sur NON, repérez votre erreur et corrigez-la avant de relancer Sycorax.\n\nSouhaitez-vous EFFACER ce fichier et le REMPLACER PAR UNE VERSION PAR DEFAUT ?\n\nSi vous cliquez sur OUI, l'ancien fichier de préférence sera détruit, le nouveau fichier de préférences contiendra les options par défaut.\nAttention, cette opération est irréversible et toutes vos préférences (par exemple, la liste de vos dossiers) seront perdues.\n\nSi vous cliquez sur NON, il vous sera alors loisible d'éditer manuellement le fichier de préférence pour corriger l'erreur. Notre support technique se fera un plaisir de vous y aider, le cas échéant.\n\nSi vous n'arrivez pas à prendre une décision, nous vous recommandons de cliquer sur NON et de déplacer votre fichier sur le bureau avant de relancer Sycorax.\nVous pourrez ainsi par la suite effectuer toutes les modifications nécessaires, par exemple recopier votre liste de dossiers depuis l'ancien fichier vers le nouveau.",
                        MainOptions.DefaultOptionsFile, e.Message
                        ),
                    "[IMPORTANT] Votre fichier de préférence est corrompu.",
                    MessageBoxButtons.YesNo, MessageBoxIcon.Stop, MessageBoxDefaultButton.Button2
                    );
                if (result == DialogResult.Yes)
                {
                    options = MainOptions.CreateNewOptionsFile(MainOptions.DefaultOptionsFile);
                }
                else
                {
                    return(false);
                }
            }

            return(true);
        }
예제 #4
0
        /// <summary>
        /// When implemented in a derived class, <see cref="M:System.ServiceProcess.ServiceBase.OnCustomCommand(System.Int32)"></see> executes when the Service Control Manager (SCM) passes a custom command to the service. Specifies actions to take when a command with the specified parameter value occurs.
        /// </summary>
        /// <param name="command">
        ///     The command message sent to the service :
        ///         1) Rehash des préférences et redémarrage de la surveillance.
        ///         2) Réinitialisation de la connexion databaseUpdate
        ///         3) 1 + 2
        /// </param>
        protected override void OnCustomCommand(int command)
        {
            switch (command)
            {
            case 3:
                //1 + 2
                options = MainOptions.Load();
                goto case 2;
            //Tiens, ça faisait bien une bonne dizaine
            //d'années que je n'avais plus goto :p ^^

            case 2:
                //Réinitialisation de la connexion databaseUpdate
                databaseUpdate.Dispose();
                databaseUpdate = new DatabaseUpdate(options.ConnectionString);
                StopSurveillance();
                StartSurveillance();
                break;

            case 1:
                //Rehash des préférences et redémarrage de la surveillance.
                options = MainOptions.Load();
                StopSurveillance();
                StartSurveillance();
                break;

            default:
                throw new ArgumentException("Commande inconnue : " + command.ToString());
            }
        }
예제 #5
0
 public MainOptionsWindow(MainOptions options = null)
 {
     this.InitializeComponent();
     if (options != null)
     {
         AddOptions(options);
     }
 }
예제 #6
0
 public FileOptions(MainViewModel vm)
 {
     options              = vm.Options;
     options.OnVisUpdate += (a) => {
         OnPropertyChanged("IsVisible");
     };
     Foreground = Brushes.Red;
 }
예제 #7
0
 /// <summary>
 /// Start this service.
 /// </summary>
 protected override void OnStart(string[] args)
 {
     //Lecture des préférences
     options = MainOptions.Load();
     //Initialisation de la base de données et de sa classe de mise à jour
     databaseUpdate = new DatabaseUpdate(options.ConnectionString);
     //Lancement de la surveillance des dossiers
     StartSurveillance();
 }
예제 #8
0
 public void AddOptions(MainOptions options)
 {
     if (MO == null)
     {
         toBox.Text     = options.Timeout.ToString();
         usersBox.Text  = string.Join(",", options.Users);
         ignoreBox.Text = string.Join(",", options.Ignores);
     }
 }
예제 #9
0
        public async Task GivenAValidRequest_Get_ReturnsAnHttpStatus200OK(MainOptions <Startup> mainOptions)
        {
            _factory.MainOptions = mainOptions;

            var client = _factory.CreateClient();

            // Act.
            var result = await client.GetAsync("/WeatherForecast");

            // Assert.
            result.StatusCode.ShouldBe(System.Net.HttpStatusCode.OK);
        }
예제 #10
0
        public static Task Main(string[] args)
        {
            var options = new MainOptions
            {
                CommandLineArguments           = args,
                FirstLoggingInformationMessage = "~~ Test Web Api ~~",
                LogAssemblyInformation         = true,
                LastLoggingInformationMessage  = "-- Test Web Api has ended/terminated --"
            };

            return(Homely.AspNetCore.Hosting.CoreApp.Program.Main <Startup>(options));
        }
예제 #11
0
        public override Task RefreshAsync()
        {
            mainOptions = settingsManager.Get <MainOptions>(MainOptions.Key);

            TxtVersion.Text = version.ToString();

            CboThemeBase.ItemsSource  = ThemeManager.Current.BaseColors;
            CboThemeColor.ItemsSource = ThemeManager.Current.ColorSchemes;

            CboThemeBase.SelectedItem  = ThemeManager.Current.DetectTheme()?.BaseColorScheme;
            CboThemeColor.SelectedItem = ThemeManager.Current.DetectTheme()?.ColorScheme;
            return(base.RefreshAsync());
        }
예제 #12
0
        public PgSettings(
            Version version,
            SettingsManager settingsManager,
            PageNavigator pageNavigator
            )
        {
            InitializeComponent();

            this.version         = version;
            this.settingsManager = settingsManager;
            this.pageNavigator   = pageNavigator;
            mainOptions          = settingsManager.Get <MainOptions>(MainOptions.Key);
        }
예제 #13
0
        public static Task Main(string[] args)
        {
            var options = new MainOptions <Startup>
            {
                CommandLineArguments           = args,
                FirstLoggingInformationMessage = "~~ Sample Web Application ~~",
                LogAssemblyInformation         = true,
                LastLoggingInformationMessage  = "-- Sample Web Application has ended/terminated --",
                StartupActivation = new System.Func <WebHostBuilderContext, ILogger, Startup>((context, logger) => new Startup(context.Configuration, logger))
            };

            return(SimpleHosting.Program.Main(options));
        }
예제 #14
0
파일: Program.cs 프로젝트: windygu/sycorax
        /// <summary>
        /// Thread principal
        /// </summary>
        static public void Do()
        {
            try {
                //Lecture des préférences
                Console.WriteLine("[*] Loading options ...");
                options = MainOptions.Load();

                //Initialisation de la base de données et de sa classe de mise à jour
                Console.WriteLine("[*] Initializing database connection and update facilities ...");
                databaseUpdate = new DatabaseUpdate(options.ConnectionString);

                //Lancement d'une surveillance pour chaque dossier repris dans l'option FoldersToWatch
                Console.WriteLine("[*] Initializing folders watch ...");

                //Let's check if we've folders to watch
                //  CLI is very useful to test if DatabaseUpdate initialization is OK,
                //  it's why we don't test options.FoldersToWatch.Length before !
                if (options.FoldersToWatch.Length == 0)
                {
                    //Nothing to do
                    Console.WriteLine("    ( no folder to watch, exiting )");
                    databaseUpdate.Dispose();
                    return;
                }
                watchers = new SurveillanceDossiers[options.FoldersToWatch.Length];
                for (int i = 0; i < options.FoldersToWatch.Length; i++)
                {
                    watchers[i]        = new SurveillanceDossiers(options.FoldersToWatch[i], databaseUpdate, options.DeleteTunesIfOrphan, options.IndexSubdirectories);
                    watchers[i].Error += new EventHandler <ExceptionEventArgs>(Program_Error);
                    Console.WriteLine("    ° " + options.FoldersToWatch[i]);
                }

                Console.WriteLine("______________________________________________________________________");
                Console.WriteLine();

                //Oki, manage events
                databaseUpdate.LogEntry += new EventHandler <TimestampMessageEventArgs>(databaseUpdate_LogEntry);
            } catch (Exception e) {
                //Options XML deserialize InnerException
                if (e.InnerException != null)
                {
                    e = e.InnerException;
                }
                Console.WriteLine(e.Message);
                if (options != null && options.DebugMode)
                {
                    Console.WriteLine(e.StackTrace);
                }
            }
        }
예제 #15
0
 public CommandSender(IHandlerResolver handlerResolver,
     IEventPublisher eventPublisher,
     IObjectFactory objectFactory,
     IStoreProvider storeProvider,
     IValidationService validationService,
     IOptions<MainOptions> mainOptions,
     IOptions<ValidationOptions> validationOptions)
 {
     _handlerResolver = handlerResolver;
     _eventPublisher = eventPublisher;
     _objectFactory = objectFactory;
     _storeProvider = storeProvider;
     _validationService = validationService;
     _mainOptions = mainOptions.Value;
     _validationOptions = validationOptions?.Value ?? new ValidationOptions();
 }
예제 #16
0
		static void Main(string[] args)
		{
			AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve);

			MainOptions opts = new MainOptions();
			opts.ProcessArgs(args);

			if (args.Length == 0 || args[0].StartsWith("-"))
			{
				ShowUsage();
			}

			Console.WriteLine("Processing {0} {1}", args[0], opts.verbose);

			IGenerator generator = null;

			if (args[0] == "controller")
			{
				generator = new NewController();
			}
			else if (args[0] == "project")
			{
				generator = new NewProject();
			}
			else
			{
				Console.Error.WriteLine("Not supported");
				return;
			}

			Configure(generator, args);

			string workingDir = AppDomain.CurrentDomain.BaseDirectory;
			string templateDir = @"C:\dev\DotNet\castle\svn\trunk\MonoRail\NewGenerator\GeneratorTemplates\";

			GeneratorContext context = new GeneratorContext(workingDir, templateDir);

			ITemplateEngine engine = new NVelocityTemplateEngine(templateDir);

			if (engine is ISupportInitialize)
			{
				((ISupportInitialize)engine).BeginInit();
			}

			generator.Generate(context, new DefaultGeneratorService(context, engine));
		}
예제 #17
0
        public MainWindow(
            SettingsManager settingsManager,
            PageNavigator pageNavigator)
        {
            InitializeComponent();
            this.settingsManager = settingsManager;
            MainOptions mainOptions = settingsManager.GetMainOptions();

            Top         = mainOptions.Appearance.WindowPosition.Top;
            Left        = mainOptions.Appearance.WindowPosition.Left;
            Width       = mainOptions.Appearance.WindowPosition.Width;
            Height      = mainOptions.Appearance.WindowPosition.Height;
            WindowState = (WindowState)mainOptions.Appearance.WindowPosition.WindowsState;

            PageNavigator = pageNavigator;

            Loaded += OnLoaded;
        }
예제 #18
0
 public FileOptions(MainOptions options)
 {
     this.options = options;
 }
예제 #19
0
 public CommandDocumentFactory(IOptions <MainOptions> mainOptions)
 {
     _mainOptions = mainOptions.Value;
 }
예제 #20
0
        private void Cancel()
        {
            mainOptions = settingsManager.Get <MainOptions>(MainOptions.Key);

            ThemeManager.Current.ChangeTheme(App.Current, mainOptions.Appearance.Theme);
        }
예제 #21
0
 public FileObject(MainOptions options)
 {
 }
예제 #22
0
        public void ConfigureServices(IServiceCollection services)
        {
            // Configuration
            services.AddOptions <MoodleLtiOptions>().Bind(_configuration.GetSection(nameof(MoodleLtiOptions)));
            _mainOptions = _configuration.GetSection(nameof(MainOptions)).Get <MainOptions>();
            services.AddOptions <MainOptions>().Bind(_configuration.GetSection(nameof(MainOptions)));
            var dbOptions = _configuration.GetSection(nameof(CtfDbOptions)).Get <CtfDbOptions>();

            // Moodle connection
            services.AddHttpClient();
            services.AddMoodleLtiApi();
            services.AddMoodleGradebook();

            // Database
            services.AddDbContextPool <CtfDbContext>(options =>
            {
                options.UseMySql($"Server={dbOptions.Server};Database={dbOptions.Database};User={dbOptions.User};Password={dbOptions.Password};", _ =>
                {
                });
                if (_environment.IsDevelopment())
                {
                    options.UseLoggerFactory(_debugLoggerFactory)
                    .EnableSensitiveDataLogging();
                }
            });

            // Localization
            services.AddLocalization(options => options.ResourcesPath = "Resources");

            // Entity/Model mapping
            services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());

            // Memory cache
            services.AddMemoryCache();

            // Model/database services
            services.AddScoped <IUserService, UserService>();
            services.AddScoped <ISlotService, SlotService>();
            services.AddScoped <ILabService, LabService>();
            services.AddScoped <IExerciseService, ExerciseService>();
            services.AddScoped <IFlagService, FlagService>();
            services.AddScoped <ILabExecutionService, LabExecutionService>();
            services.AddScoped <IScoreboardService, ScoreboardService>();

            // Markdown parser
            services.AddSingleton <IMarkdownService, MarkdownService>();

            // Configuration service
            services.AddScoped <IConfigurationService, ConfigurationService>();

            // Export/sync services
            services.AddScoped <IMoodleService, MoodleService>();
            services.AddScoped <ICsvService, CsvService>();

            // Change name of antiforgery cookie
            services.AddAntiforgery(options =>
            {
                options.Cookie.Name     = "ctf4e.antiforgery";
                options.Cookie.SameSite = SameSiteMode.Lax;
            });

            // Authentication
            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(options =>
            {
                options.Cookie.Name      = "ctf4e.session";
                options.LoginPath        = "/auth";
                options.LogoutPath       = "/auth/logout";
                options.AccessDeniedPath = "/auth";
            });
            services.AddAuthorization(options =>
            {
                options.AddPolicy(AuthenticationStrings.PolicyIsGroupMember, policy => policy.RequireClaim(AuthenticationStrings.ClaimIsGroupMember, true.ToString()));
                options.AddPolicy(AuthenticationStrings.PolicyIsAdmin, policy => policy.RequireClaim(AuthenticationStrings.ClaimIsAdmin, true.ToString()));
                options.AddPolicy(AuthenticationStrings.PolicyIsPrivileged, policy => policy.RequireAssertion(context =>
                {
                    return(context.User.Claims.Any(c => c.Type == AuthenticationStrings.ClaimIsAdmin && c.Value == true.ToString()) ||
                           context.User.Claims.Any(c => c.Type == AuthenticationStrings.ClaimIsTutor && c.Value == true.ToString()));
                }));
            });

            // Use MVC
            var mvcBuilder = services.AddControllersWithViews(_ =>
            {
            }).AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix);

            // Development tools
            if (_mainOptions.DevelopmentMode)
            {
                // Add MiniProfiler
                services.AddMiniProfiler(options =>
                {
                    // Put profiler results to dev route
                    options.RouteBasePath = "/dev/profiler";
예제 #23
0
 public CommandEntityFactory(IOptions <MainOptions> mainOptions)
 {
     _mainOptions = mainOptions.Value;
 }
예제 #24
0
    public void ConfigureServices(IServiceCollection services)
    {
        // Configuration
        services.AddOptions <MoodleLtiOptions>().Bind(_configuration.GetSection(nameof(MoodleLtiOptions)));
        _mainOptions = _configuration.GetSection(nameof(MainOptions)).Get <MainOptions>();
        services.AddOptions <MainOptions>().Bind(_configuration.GetSection(nameof(MainOptions)));
        var dbOptions = _configuration.GetSection(nameof(CtfDbOptions)).Get <CtfDbOptions>();

        // Key persistence
        if (_mainOptions.SecretsDirectory != null)
        {
            services.AddDataProtection()
            .PersistKeysToFileSystem(new DirectoryInfo(_mainOptions.SecretsDirectory));
        }

        // Moodle connection
        services.AddHttpClient();
        services.AddMoodleLtiApi();
        services.AddMoodleGradebook();

        // Database
        services.AddDbContextPool <CtfDbContext>(options =>
        {
            options.UseMySql($"Server={dbOptions.Server};Database={dbOptions.Database};User={dbOptions.User};Password={dbOptions.Password};",
                             ServerVersion.Parse("10.5.8-mariadb"), mysqlOptions => mysqlOptions.EnableRetryOnFailure(3));
            if (_environment.IsDevelopment())
            {
                options.UseLoggerFactory(_debugLoggerFactory)
                .EnableSensitiveDataLogging();
            }
        });

        // Localization
        services.AddLocalization(options => options.ResourcesPath = "Resources");

        // Entity/Model mapping
        services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());

        // Memory cache
        services.AddMemoryCache();

        // Model/database services
        services.AddScoped <IUserService, UserService>();
        services.AddScoped <ISlotService, SlotService>();
        services.AddScoped <ILabService, LabService>();
        services.AddScoped <IExerciseService, ExerciseService>();
        services.AddScoped <IFlagService, FlagService>();
        services.AddScoped <ILabExecutionService, LabExecutionService>();
        services.AddScoped <IScoreboardService, ScoreboardService>();

        // Markdown parser
        services.AddSingleton <IMarkdownService, MarkdownService>();

        // Configuration service
        services.AddScoped <IConfigurationService, ConfigurationService>();

        // Export/sync services
        services.AddScoped <IMoodleService, MoodleService>();
        services.AddScoped <ICsvService, CsvService>();
        services.AddScoped <IDumpService, DumpService>();

        // Rate limiting
        services.AddSingleton <ILoginRateLimiter, LoginRateLimiter>();

        // Forward headers when used behind a proxy
        services.Configure <ForwardedHeadersOptions>(options =>
        {
            options.ForwardedHeaders = ForwardedHeaders.XForwardedProto;
        });

        // Change name of antiforgery cookie
        services.AddAntiforgery(options =>
        {
            options.Cookie.Name     = "ctf4e.antiforgery";
            options.Cookie.SameSite = SameSiteMode.Lax;
        });

        // Authentication
        services.AddAuthentication(options =>
        {
            options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        }).AddCookie(options =>
        {
            options.Cookie.Name      = "ctf4e.session";
            options.LoginPath        = "/auth";
            options.LogoutPath       = "/auth/logout";
            options.AccessDeniedPath = "/auth";
        });

        // Authorization
        services.AddSingleton <IAuthorizationHandler, UserPrivilegeHandler>();
        services.AddSingleton <IAuthorizationPolicyProvider, UserPrivilegePolicyProvider>();

        // Use MVC
        var mvcBuilder = services.AddControllersWithViews(_ =>
        {
        }).AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix);

        // Development tools
        if (_mainOptions.DevelopmentMode)
        {
            // Add MiniProfiler
            services.AddMiniProfiler(options =>
            {
                // Put profiler results to dev route
                options.RouteBasePath = "/dev/profiler";