public ChangeOfCircsBuilder WithCompletedSections(bool markAsCompleted = true, bool excludeOptionalSections = false) { With(f => f.Consent, ConsentBuilder.NewValid()); With(f => f.UserId, "*****@*****.**"); With(f => f.ExistingApplicantDetails, ApplicantDetailsBuilder.NewValid(ad => ad.Address = AddressBuilder.NewValid("existing"))); With(f => f.ExistingPaymentDetails, PaymentDetailsBuilder.NewValid()); With(f => f.Options, OptionsBuilder.NewValid()); if (!excludeOptionalSections) { With(f => f.ApplicantDetails, ApplicantDetailsBuilder.NewValid()); With(f => f.ExpectedChildren, ExpectedChildrenBuilder.NewValid()); With(f => f.HealthProfessional, HealthProfessionalBuilder.NewValid()); With(f => f.PaymentDetails, PaymentDetailsBuilder.NewValid()); } With(f => f.Evidence, EvidenceBuilder.NewValid()); With(f => f.Declaration, DeclarationBuilder.NewValid()); With(f => f.Started, DomainRegistry.NowUtc() - TimeSpan.FromHours(24)); With(f => f.Completed, DomainRegistry.NowUtc()); VerifyConsistent(_instance); if (!markAsCompleted) { With(f => f.Completed, null); } return(this); }
public static async Task Main(string[] args) { var config = new ConfigurationBuilder() .AddEnvironmentVariables() .SetBasePath(PlatformServices.Default.Application.ApplicationBasePath) .AddJsonFile($"appsettings.{Environment.UserName}.json", true) .AddJsonFile("appsettings.Development.json", true) .AddJsonFile("appsettings.json") .Build(); var serviceProvider = BootstrapDependencyInjection(config); var hangfireOptions = serviceProvider.GetHangfireOptionsOrDefault(); var hangfireJobStorage = CreateRedisJobStorage(hangfireOptions); using (var server = CreateHangfireBackgroundJobServer(hangfireJobStorage, new HangfireActivator(serviceProvider))) { var smtpOptions = serviceProvider.GetSmtpOptionsOrDefault(); var backgroundJobClient = new BackgroundJobClient(hangfireJobStorage); var options = new OptionsBuilder() .ServerName(smtpOptions.HostName) .Port(smtpOptions.Port) .MessageStore(new RedisMinioMailStore(backgroundJobClient)) .Build(); var smtpServer = new SmtpServer.SmtpServer(options); await smtpServer.StartAsync(CancellationToken.None); server.SendStop(); } }
private NextSection AddOptions(NextSection current, Action <Options> mutator = null) { current.Section.Should().Be(Sections.Options); return(NextSection(current.Section, () => new AddOptions { FormId = current.Id, Options = OptionsBuilder.NewValid(mutator) }.Execute())); }
private async void Start_Click(object sender, EventArgs e) { EnableDisable(false); TimeSpan seconds = TimeSpan.FromSeconds(Decimal.ToDouble(timeout.Value)); LoggingMessageStore store = new LoggingMessageStore(); store.Message += Store_Message; ISmtpServerOptions options = new OptionsBuilder() .ServerName(serverName.Text) .Port(Decimal.ToInt32(port.Value)) .CommandWaitTimeout(seconds) .MessageStore(store) .Build(); smtpServer = new SmtpServer.SmtpServer(options); smtpServer.SessionCreated += OnSessionCreated; try { cancellationTokenSource = new CancellationTokenSource(); await smtpServer.StartAsync(cancellationTokenSource.Token) .ConfigureAwait(true); } catch (SocketException ex) { MessageBox.Show(this, ex.Message, this.Text); } catch (OperationCanceledException) { // nothing for user to do } EnableDisable(true); }
public static OptionsBuilder <TOptions> Bind <TOptions>(this OptionsBuilder <TOptions> optionsBuilder, IConfigurationSection section) where TOptions : class { return(optionsBuilder .Configure(section.Bind)); }
/// <summary> /// Limits the number of concurrent consumers /// </summary> /// <param name="builder">OptionsBuilder</param> /// <param name="limit">The consumer limit</param> public static void WithConsumerLimit(this OptionsBuilder builder, int limit) { builder._options.BusActions.Add((cfg, host, _) => { cfg.UseConcurrencyLimit(limit); }); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { //Auth Settings JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear(); //This is usually how to pass cookies but cant at because it requires windows and isnt supported on azure //services.AddDataProtection() // .PersistKeysToFileSystem(new System.IO.DirectoryInfo(@"c:\temp-keys")) // .ProtectKeysWithDpapi() // .SetApplicationName("SharedCookies"); services.AddAuthentication("Cookies") .AddCookie("Cookies", options => { options.Cookie.Name = ".AspNet.SharedCookie"; options.Cookie.Domain = ".azurewebsites.net"; }); //DB Connection var conn = Configuration.GetConnectionString("DBConnection"); services.AddDbContext <MSProductsDB>(options => options.UseSqlServer(conn, OptionsBuilder => { OptionsBuilder.EnableRetryOnFailure(3, TimeSpan.FromSeconds(10), null); })); //Because the auth service isnt implimented, use this to nullify all the auth code in the service services.AddMvc(options => options.Filters.Add(new AllowAnonymousFilter())).SetCompatibilityVersion(CompatibilityVersion.Version_2_2); }
public static void Run() { // this is important when dealing with a certificate that isnt valid ServicePointManager.ServerCertificateValidationCallback = IgnoreCertificateValidationFailureForTestingOnly; var cancellationTokenSource = new CancellationTokenSource(); var options = new OptionsBuilder() .ServerName("SmtpServer SampleApp") .Certificate(CreateCertificate()) .AllowUnsecureAuthentication(false) .UserAuthenticator(new SampleUserAuthenticator()) .Port(9025) .Build(); var server = new SmtpServer.SmtpServer(options); server.SessionCreated += OnSessionCreated; var serverTask = server.StartAsync(cancellationTokenSource.Token); SampleMailClient.Send(user: "******", password: "******"); cancellationTokenSource.Cancel(); serverTask.WaitWithoutException(); }
public void ValidateWithFluentValidation_CallValidateWithFluentValidation_ReturnThis() { var servicesMock = new Mock <IServiceCollection>(); var optionsBuilder = new OptionsBuilder <TestOptions>(servicesMock.Object, "name1"); optionsBuilder.ValidateWithFluentValidation().Should().BeSameAs(optionsBuilder); }
/// <summary> /// Create a running instance of a server. /// </summary> /// <param name="configuration">The configuration to apply to run the server.</param> /// <returns>A disposable instance which will close and release the server instance.</returns> SmtpServerDisposable CreateServer(Action <OptionsBuilder> configuration) { var options = new OptionsBuilder() .ServerName("localhost") .Port(9025) .MessageStore(MessageStore); configuration(options); var server = new SmtpServer(options.Build()); var smtpServerTask = server.StartAsync(CancellationTokenSource.Token); return(new SmtpServerDisposable(server, () => { CancellationTokenSource.Cancel(); try { smtpServerTask.Wait(); } catch (AggregateException e) { e.Handle(exception => exception is OperationCanceledException); } })); }
/// <summary> /// Specifies how many messages to prefetch from the bus /// </summary> /// <param name="builder">OptionsBuilder</param> /// <param name="count">The prefetch count</param> public static void WithPrefetchCount(this OptionsBuilder builder, ushort count) { builder._options.EndpointActions.Add(e => { e.PrefetchCount = count; }); }
private static void SetAppConfiguration(HostBuilderContext HostBuilderContext, IConfigurationBuilder ConfigurationBuilder) { var Directory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); ConfigurationBuilder.AddDatabaseConfigurations(OptionsBuilder => OptionsBuilder.UseSqlite($"Data Source={Directory}\\SecureDNS.sqlite;")); }
public static IServiceCollection AddScriptAPI(this IServiceCollection services, Action <OptionsBuilder> optionsBuilder) { var builder = new OptionsBuilder(); optionsBuilder(builder); var options = builder.Build(); services.AddSingleton <ScriptAPI.ServiceConfiguration.IOptions>(options); services.AddSingleton <ScriptAPIService>(); var procedures = Assembly.GetEntryAssembly().GetTypes() .Where(x => x.IsClass && !x.IsAbstract && typeof(IProcedure).IsAssignableFrom(x)) .ToArray(); foreach (var procedure in procedures) { services.AddTransient(procedure); } services.AddSingleton(new ProcedureMapping(procedures.Select(x => (Name: x.Name, Type: x)).ToArray())); services.AddSingleton <ProcedureLocator>(serviceProvider => (Type type) => serviceProvider.GetRequiredService(type)); services.AddSingleton(serviceProvider => new Host( serviceProvider.GetRequiredService <ProcedureLocator>(), serviceProvider.GetRequiredService <ProcedureMapping>()) ); services.TryAddSingleton <IHttpContextAccessor, HttpContextAccessor>(); return(services); }
//public static OptionsBuilder<TOptions> AddMySiteOptions // <TOptions>(this OptionsBuilder<TOptions> optionsBuilder, // Action<TOptions> configureAdminOptions) // where TOptions : SharePointSiteAuthorizationOptions => // optionsBuilder.AddNestedNamedOptions( // SharePointSiteAuthorizationOptions.MySiteOptionsName, // configureAdminOptions, // GetMySiteUrlFromSiteUrl // ); private static OptionsBuilder <TOptions> AddNestedNamedOptions <TOptions>(this OptionsBuilder <TOptions> optionsBuilder, string nestedOptionsName, Action <TOptions>?configureNestedOptions, Func <string, string> nestedSiteUrlTransform) where TOptions : SharePointSiteAuthorizationOptions { _ = optionsBuilder ?? throw new ArgumentNullException(nameof(optionsBuilder)); if (optionsBuilder.Name.Equals(nestedOptionsName, StringComparison.OrdinalIgnoreCase)) { throw new ArgumentException( message: "The nested options name must be different from the root options.", paramName: nameof(nestedOptionsName) ); } var nestedOptionsBuilder = optionsBuilder.Services .AddOptions <TOptions>(nestedOptionsName); nestedOptionsBuilder.Configure <IOptionsSnapshot <TOptions> >((nestedOptions, snapshot) => { var rootOptions = snapshot.Get(optionsBuilder.Name); nestedOptions.SiteUrl = nestedSiteUrlTransform(rootOptions.SiteUrl); }); if (configureNestedOptions is not null) { nestedOptionsBuilder.Configure(configureNestedOptions); } return(optionsBuilder); }
public static OptionsBuilder <TOptions> UseOptions <TOptions, TOptionsDep>( this OptionsBuilder <TOptions> optionsBuilder, Action <TOptions, TOptionsDep> configureOptions) where TOptionsDep : class where TOptions : class { return(optionsBuilder .Configure <IOptionsMonitor <TOptionsDep> >((options, dependency) => configureOptions(options, dependency.Get(optionsBuilder.Name)))); }
/// <summary> /// Builds command options. /// </summary> public static TCommand Options <TCommand>(this TCommand command, Action <IOptionsBuilder> optionsBuilder) where TCommand : CommandLineApplication { var builder = new OptionsBuilder(command); optionsBuilder(builder); builder.Build(); return(command); }
public static OptionsBuilder <TOptions> ConfigureSection <TOptions>(this OptionsBuilder <TOptions> builder) where TOptions : class { var section = typeof(TOptions).Name.Replace(Options, string.Empty); return(builder.Configure <IConfiguration>((options, configuration) => configuration.GetSection(section).Bind(options))); }
private static Options ParseOptions(string[] toolArgs) { var opts = new OptionsBuilder(Options.Defaults); var cli = new CommandLineUtilities(toolArgs); foreach (var opt in cli.Options) { switch (opt.Name.TrimEnd('-', '+')) { case ArgVerbose: case "v": opts.Verbose = CommandLineUtilities.ParseBooleanOption(opt); break; case ArgLogToStdOut: case "o": opts.LogToStdOut = CommandLineUtilities.ParseBooleanOption(opt); break; case "numKextConnections": case "c": Console.WriteLine($"*** WARNING *** option /{opt.Name} has no effect any longer"); break; case ArgReportQueueSizeMB: case "r": opts.ReportQueueSizeMB = CommandLineUtilities.ParseUInt32Option(opt, 1, 1024); break; case ArgEnableReportBatching: case "b": opts.EnableReportBatching = CommandLineUtilities.ParseBooleanOption(opt); break; case ArgEnableStatistics: case "s": opts.EnableTelemetry = CommandLineUtilities.ParseBooleanOption(opt); break; case ArgProcessTimeout: case "t": // Max is currently set to 4 hours and should suffice opts.ProcessTimeout = CommandLineUtilities.ParseInt32Option(opt, (int)s_defaultProcessTimeOut, (int)s_defaultProcessTimeOutMax); break; case ArgTrackDirectoryCreation: case "d": opts.TrackDirectoryCreation = CommandLineUtilities.ParseBooleanOption(opt); break; default: throw new InvalidArgumentException($"Unrecognized option {opt.Name}"); } } return(opts.Finish()); }
public SmtpServerTests() { _messageStore = new MockMessageStore(); _optionsBuilder = new OptionsBuilder() .ServerName("localhost") .Port(25) .MessageStore(_messageStore); }
public static void BindConfiguration_ThrowsForNullBuilder() { OptionsBuilder <FakeOptions> optionsBuilder = null !; Assert.Throws <ArgumentNullException>("optionsBuilder", () => { optionsBuilder.BindConfiguration("test"); }); }
protected internal virtual Request revokeAccessRequest( string user) { return(new Request(ArangoDBConstants .SYSTEM, RequestType.PUT, this.executor.createPath(ArangoDBConstants .PATH_API_USER, user, ArangoDBConstants.DATABASE, name)). setBody(this.executor.Serialize(OptionsBuilder.build(new UserAccessOptions (), ArangoDBConstants.NONE)))); }
public static OptionsBuilder <TOptions> AddAdminSiteOptions <TOptions>(this OptionsBuilder <TOptions> optionsBuilder, Action <TOptions>?configureAdminOptions = null) where TOptions : SharePointSiteAuthorizationOptions => optionsBuilder.AddNestedNamedOptions( SharePointSiteAuthorizationOptions.AdminSiteOptionsName, configureAdminOptions, GetAdminUrlFromSiteUrl );
public static void BindConfiguration_ReturnsSameBuilderInstance() { var services = new ServiceCollection(); var optionsBuilder = new OptionsBuilder <FakeOptions>(services, Options.DefaultName); var returnedBuilder = optionsBuilder.BindConfiguration("Test"); Assert.Same(optionsBuilder, returnedBuilder); }
static void Main(string[] args) { var cancellationTokenSource = new CancellationTokenSource(); var options = new OptionsBuilder() .ServerName("SmtpServer SampleApp") .Port(9025) .MessageStore(new ConsoleMessageStore()) .MailboxFilter(new ConsoleMailboxFilter()) .Build(); if (args == null || args.Length == 0) { var serverTask = RunServerAsync(options, cancellationTokenSource.Token); var clientTask1 = RunClientAsync("A", cancellationTokenSource.Token); var clientTask2 = RunClientAsync("B", cancellationTokenSource.Token); var clientTask3 = RunClientAsync("C", cancellationTokenSource.Token); Console.WriteLine("Press any key to continue"); Console.ReadKey(); cancellationTokenSource.Cancel(); serverTask.WaitWithoutException(); clientTask1.WaitWithoutException(); clientTask2.WaitWithoutException(); clientTask3.WaitWithoutException(); return; } if (args[0] == "server") { var serverTask = RunServerAsync(options, cancellationTokenSource.Token); Console.WriteLine("Press any key to continue"); Console.ReadKey(); cancellationTokenSource.Cancel(); serverTask.WaitWithoutException(); return; } if (args[0] == "client") { var clientTask = RunClientAsync(args[1], cancellationTokenSource.Token); Console.WriteLine("Press any key to continue"); Console.ReadKey(); cancellationTokenSource.Cancel(); clientTask.WaitWithoutException(); } }
public static OptionsBuilder <TOptions> ValidateEagerly <TOptions>(this OptionsBuilder <TOptions> optionsBuilder) where TOptions : class { if (optionsBuilder == null) { throw new ArgumentNullException(nameof(optionsBuilder)); } return(optionsBuilder.ValidateOnStart()); }
/// <summary> /// Registers a configuration instance which <typeparamref name="TOptions"/> will bind against. /// </summary> /// <typeparam name="TOptions">The options type to be configured.</typeparam> /// <param name="optionsBuilder">The options builder to add the services to.</param> /// <param name="config">The configuration being bound.</param> /// <param name="configureBinder">Used to configure the <see cref="BinderOptions"/>.</param> /// <returns>The <see cref="OptionsBuilder{TOptions}"/> so that additional calls can be chained.</returns> public static OptionsBuilder <TOptions> Bind <TOptions>(this OptionsBuilder <TOptions> optionsBuilder, IConfiguration config, Action <BinderOptions> configureBinder) where TOptions : class { if (optionsBuilder == null) { throw new ArgumentNullException(nameof(optionsBuilder)); } optionsBuilder.Services.Configure <TOptions>(optionsBuilder.Name, config, configureBinder); return(optionsBuilder); }
public static IServiceCollection AddDatabase(this IServiceCollection Services) { Services.AddEntityFrameworkSqlite(); var Directory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); Services.AddDbContext <DatabaseContext>(OptionsBuilder => OptionsBuilder.UseSqlite($"Data Source={Directory}\\SecureDNS.sqlite;")); return(Services); }
/// <summary>First layer of the bridge between IServiceCollectionExtensions /// and the recursive DataAnnotations validator.</summary> internal static OptionsBuilder <TOptions> RecursivelyValidateDataAnnotations <TOptions>( this OptionsBuilder <TOptions> optionsBuilder ) where TOptions : class { optionsBuilder.Services.AddSingleton <IValidateOptions <TOptions> >( new RecursiveDataAnnotationValidateOptions <TOptions>( optionsBuilder.Name )); return(optionsBuilder); }
public async Task Returns_A_WeatherForecast() { var opts = OptionsBuilder.OpenWeatherConfig(); var clientFactory = ClientBuilder.OpenWeatherClientFactory(OpenWeatherResponses.OkResponse); var sut = new OpenWeatherService(opts, clientFactory); var result = await sut.GetFiveDayForecastAsync("Chicago"); Assert.IsType <List <WeatherForecast> >(result); }
public static IServiceCollection AddKaspPanelOptions(this IServiceCollection services, Action <IOptionsBuilder> optionsAction) { var option = new OptionsBuilder(); optionsAction.Invoke(option); services.Configure <PanelOptions>(options => options.Options = option.Options); return(services); }