public async Task If_no_campaign_is_currently_open__handler_returns_Maybe_None()
        {
            var sp = new ServiceProviderBuilder().BuildServiceProvider(ConfigureServices);

            using (var scope = sp.CreateScope())
            {
                var dbSession = scope.ServiceProvider.GetRequiredService <DbSessionProvider>();
                await dbSession.CreateSession().SaveAsync(new Campaign(
                                                              startDateTime: NodaTime.SystemClock.Instance.GetOffsetDateTime().Plus(NodaTime.Duration.FromDays(7)),
                                                              endDateTime: NodaTime.SystemClock.Instance.GetOffsetDateTime().Plus(NodaTime.Duration.FromDays(14)),
                                                              editionId: 1, name: "test"));
            }

            using (var scope = sp.CreateScope())
            {
                var mediator = scope.ServiceProvider.GetRequiredService <IMediator>();

                var query  = new GetCurrentCampaign.Query();
                var result = await mediator.Send(query);

                Assert.True(result.HasNoValue);
            }
        }
Esempio n. 2
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

            // Register the Swagger generator, defining 1 or more Swagger documents
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info {
                    Title = "Event Collector API", Version = "v1"
                });
            });

            ServiceProviderBuilder serviceProviderBuilder = new ServiceProviderBuilder();
            IServiceProvider       serviceProvider        = serviceProviderBuilder.Build(services);

            configuration.Bind(serviceProvider.GetRequiredService <IApplicationConfiguration>());

            IEventCollectorServerContext eventCollectorServerContext = serviceProvider.GetRequiredService <IEventCollectorServerContext>();

            eventCollectorServerContext.Configure();

            return(serviceProvider);
        }
Esempio n. 3
0
        public void IsValidInput_IsTrue_EvenIfDestinationDirIsNotEmpty()
        {
            // Arrange
            var dstDir = _testDir.CreateChildDir();

            File.WriteAllText(Path.Combine(dstDir, "bla.txt"), "bla");

            var serviceProvider = new ServiceProviderBuilder()
                                  .ConfigureScriptGenerationOptions(o =>
            {
                o.SourceDir      = _testDir.CreateChildDir();
                o.DestinationDir = dstDir;
            })
                                  .Build();
            var testConsole  = new TestConsole();
            var buildCommand = new BuildCommand();

            // Act
            var isValid = buildCommand.IsValidInput(serviceProvider, testConsole);

            // Assert
            Assert.True(isValid);
        }
            protected override void Test(IOrganizationService service)
            {
                var plugin = new TestPlugin(null, null);

                var serviceProvider = new ServiceProviderBuilder(
                    service,
                    new PluginExecutionContextBuilder()
                    .WithRegisteredEvent(20, "Update", "account")
                    .WithPrimaryEntityId(Ids.Account)
                    .WithTarget(Ids.Account)
                    .Build(),
                    new DebugLogger()).Build();


                var executionContext = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
                var target           = executionContext.InputParameters["Target"] as Entity;

                Assert.AreEqual(2, target.Attributes.Count);

                plugin.Execute(serviceProvider);

                // input parameter was changed
                Assert.AreEqual(3, target.Attributes.Count);

                serviceProvider = new ServiceProviderBuilder(
                    service,
                    new PluginExecutionContextBuilder()
                    .WithRegisteredEvent(40, "Update", "account")
                    .WithPrimaryEntityId(Ids.Account)
                    .WithTarget(Ids.Account)
                    .Build(),
                    new DebugLogger()).Build();

                executionContext = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));

                plugin.Execute(serviceProvider);
            }
Esempio n. 5
0
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        internal static void Main()
        {
            Log.Logger = new LoggerConfiguration()
                         .Enrich.FromLogContext()
                         .MinimumLevel.Debug()
                         .WriteTo.ColoredConsole()
                         .WriteTo.File(Path.Combine(
                                           Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData),
                                           "Proxy Port Router",
                                           "service.log"))
                         .CreateLogger();

            ServiceProviderBuilder.SetupBackendService(true);

            var rc = HostFactory.Run(
                x =>
            {
                x.UseSerilog();
                x.Service <Main>(
                    s =>
                {
                    s.ConstructUsing(f => new Main());
                    s.WhenStarted(tc => tc.Start());
                    s.WhenStopped(tc => tc.Stop());
                });
                x.RunAsLocalSystem();

                x.SetDescription("Service for hosting a proxy port router");
                x.SetDisplayName("Proxy Port Router");
                x.SetServiceName("ProxyPortRouterService");
            });

            // ReSharper disable once PossibleNullReferenceException
            var exitCode = (int)Convert.ChangeType(rc, rc.GetTypeCode());

            Environment.ExitCode = exitCode;
        }
Esempio n. 6
0
            protected override void Test(IOrganizationService service)
            {
                service = new OrganizationServiceBuilder(service)
                          .WithIdsDefaultedForCreate(
                    CreatedIds.Contact)
                          .Build();

                var plugin = new Sample.FieldEncryptionPlugin(null, null);

                plugin.Container.Implement <ICache>().Using <Fakes.FakeCacheProvider>().WithOverwrite();
                plugin.Container.Implement <ISecretProviderFactory>().Using <Fakes.FakeSecretProviderFactory <Fakes.FakeSecretProvider> >().WithOverwrite();


                var target = new Contact()
                {
                    Department = TestData.DecryptedValue
                };


                var executionContext = new PluginExecutionContextBuilder()
                                       .WithRegisteredEvent(20, "Create", Contact.EntityLogicalName)
                                       .WithInputParameter("Target", target)
                                       .Build();

                var serviceProvider = new ServiceProviderBuilder(
                    service,
                    executionContext,
                    new DebugLogger()).Build();

                plugin.Execute(serviceProvider);



                var contextTarget = executionContext.InputParameters["Target"] as Contact;

                Assert.AreEqual(TestData.EncryptedValue, contextTarget.Department);
            }
Esempio n. 7
0
        private IServiceProvider CreateServiceProvider(TestProgrammingPlatform generator, bool scriptOnly)
        {
            var sourceCodeFolder = Path.Combine(_testDirPath, "src");

            Directory.CreateDirectory(sourceCodeFolder);
            var outputFolder = Path.Combine(_testDirPath, "output");

            Directory.CreateDirectory(outputFolder);
            var servicesBuilder = new ServiceProviderBuilder()
                                  .ConfigureServices(services =>
            {
                // Add 'test' script generator here as we can control what the script output is rather
                // than depending on in-built script generators whose script could change overtime causing
                // this test to be difficult to manage.
                services.RemoveAll <IPlatformDetector>();
                services.TryAddEnumerable(
                    ServiceDescriptor.Singleton <IPlatformDetector>(
                        new TestPlatformDetectorUsingPlatformName(
                            detectedPlatformName: "test",
                            detectedPlatformVersion: "1.0.0")));
                services.RemoveAll <IProgrammingPlatform>();
                services.TryAddEnumerable(
                    ServiceDescriptor.Singleton <IProgrammingPlatform>(generator));
                services.AddSingleton <ITempDirectoryProvider>(
                    new TestTempDirectoryProvider(Path.Combine(_testDirPath, "temp")));
                var configuration = new ConfigurationBuilder().Build();
                services.AddSingleton <IConfiguration>(configuration);
            })
                                  .ConfigureScriptGenerationOptions(o =>
            {
                o.SourceDir      = sourceCodeFolder;
                o.DestinationDir = outputFolder;
                o.ScriptOnly     = scriptOnly;
            });

            return(servicesBuilder.Build());
        }
        public async Task get_all_clusters_returns_expected_body_with_clusters_available()
        {
            var serviceProviderBuilder = new ServiceProviderBuilder();
            var serviceProvider        = serviceProviderBuilder
                                         .WithServicesFromStartup()
                                         .WithInMemoryDb()
                                         .OverwriteService(typeof(IRestClient), new StubKafkaRestClient())
                                         .Build();
            var clusterController = new ClusterController(serviceProvider.GetService <IClusterRepository>());

            var clusterRepository = serviceProvider.GetService <IClusterRepository>();
            await clusterRepository.AddAsync("Dummy test cluster #1", "lkc-9999", true, Guid.Parse("1d569b07-75b4-4e2f-b067-6583401a09c8"));

            await clusterRepository.AddAsync("Dummy test cluster #2", "lkc-9998", true, Guid.Parse("b8c32078-9eec-4809-8f4e-5efbe509b78f"));

            var response = await clusterController.GetAll();

            var okResult = response as OkObjectResult;

            Assert.Equal(
                expected: "[{\"Name\":\"Dummy test cluster #1\",\"Description\":\"\",\"Enabled\":true,\"ClusterId\":\"lkc-9999\",\"DomainEvents\":[],\"Id\":\"1d569b07-75b4-4e2f-b067-6583401a09c8\"},{\"Name\":\"Dummy test cluster #2\",\"Description\":\"\",\"Enabled\":true,\"ClusterId\":\"lkc-9998\",\"DomainEvents\":[],\"Id\":\"b8c32078-9eec-4809-8f4e-5efbe509b78f\"}]",
                actual: JsonSerializer.Serialize(okResult.Value)
                );
        }
        public void RemovePhoneNumberFormatting_ContactHasFormatting_Should_RemoveFormatting()
        {
            //
            // Arrange
            //
            TestInitializer.InitializeTestSettings();
            var contact = new Contact { MobilePhone = "A-1-B-2-C-3" }; // Create Contact to use as target
            var plugin = new RemovePhoneNumberFormatting();
            var context = new PluginExecutionContextBuilder(). // Create Context Which is required by the service provider, which is required by the plugin
                WithRegisteredEvent(plugin.RegisteredEvents.First(e => e.EntityLogicalName == Contact.EntityLogicalName)). // Specifies the plugin event to use in the context
                WithTarget(contact).Build(); // Sets the Target
            var provider = new ServiceProviderBuilder().
                WithContext(context).Build();
            //
            // Act
            //
            plugin.Execute(provider); // Executes the Plugin

            //
            // Assert
            //

            Assert.AreEqual("123", contact.MobilePhone);
        }
Esempio n. 10
0
        public async Task CampaignsCannotOverlap()
        {
            var sp = new ServiceProviderBuilder().BuildServiceProvider(ConfigureServices);

            using (var scope = sp.CreateScope())
            {
                var engine  = sp.GetRequiredService <SharedKernel.ISzlemEngine>();
                var command = new Create.Command()
                {
                    Name          = "test",
                    StartDateTime = new NodaTime.LocalDateTime(2019, 09, 01, 12, 00, 00).InMainTimezone().ToOffsetDateTime(),
                    EndDateTime   = new NodaTime.LocalDateTime(2019, 10, 01, 12, 00, 00).InMainTimezone().ToOffsetDateTime(),
                    EditionID     = 1
                };

                var result = await engine.Execute(command);
            }

            using (var scope = sp.CreateScope())
            {
                var engine  = sp.GetRequiredService <SharedKernel.ISzlemEngine>();
                var command = new Create.Command()
                {
                    Name          = "test",
                    StartDateTime = new NodaTime.LocalDateTime(2019, 09, 01, 12, 00, 00).InMainTimezone().ToOffsetDateTime(),
                    EndDateTime   = new NodaTime.LocalDateTime(2019, 10, 01, 12, 00, 00).InMainTimezone().ToOffsetDateTime(),
                    EditionID     = 1
                };

                var result = await engine.Execute(command);

                Assert.False(result.IsSuccess);
                var error = Assert.IsType <Error.DomainError>(result.Error);
                Assert.Equal(Create.ErrorMessages.CampaignsCannotOverlap, error.Message);
            }
        }
Esempio n. 11
0
        public void IsValid_IsFalse_IfLanguageVersionSpecified_WithoutLanguageName()
        {
            // Arrange
            var serviceProvider = new ServiceProviderBuilder()
                                  .ConfigureScriptGenerationOptions(o =>
            {
                o.SourceDir       = _testDir.CreateChildDir();
                o.DestinationDir  = _testDir.CreateChildDir();
                o.PlatformName    = null;
                o.PlatformVersion = "1.0.0";
            })
                                  .Build();
            var testConsole  = new TestConsole();
            var buildCommand = new BuildCommand();

            // Act
            var isValid = buildCommand.IsValidInput(serviceProvider, testConsole);

            // Assert
            Assert.False(isValid);
            Assert.Contains(
                "Cannot use language version without specifying language name also.",
                testConsole.StdError);
        }
 public WeatherForecastTests()
 {
     this.services = ServiceProviderBuilder.GetServiceProvider(new string[] { "" });
     this.options  = services.GetRequiredService <IOptions <SecretsModel> >();
 }
Esempio n. 13
0
        public async Task Query_with_specified_CampaignId_returns_trainings_from_that_campaign()
        {
            var sp = new ServiceProviderBuilder().BuildServiceProvider(ConfigureServices);

            using (var scope = sp.CreateScope())
            {
                var dbSessionProvider = scope.ServiceProvider.GetRequiredService <DbSessionProvider>();
                var campaign          = new Campaign(
                    startDateTime: new NodaTime.LocalDateTime(2019, 09, 01, 12, 00).InMainTimezone().ToOffsetDateTime(),
                    endDateTime: new NodaTime.LocalDateTime(2019, 09, 30, 12, 00).InMainTimezone().ToOffsetDateTime(),
                    editionId: 1, name: "campaign");
                campaign.ScheduleTraining(new Training(
                                              "Papieska 1", "Wadowice",
                                              new NodaTime.LocalDateTime(2019, 10, 01, 12, 00).InMainTimezone().ToOffsetDateTime(),
                                              new NodaTime.LocalDateTime(2019, 10, 01, 16, 00).InMainTimezone().ToOffsetDateTime(),
                                              trainerID));
                campaign.ScheduleTraining(new Training(
                                              "Papieska 11", "Wadowice",
                                              new NodaTime.LocalDateTime(2019, 10, 02, 12, 00).InMainTimezone().ToOffsetDateTime(),
                                              new NodaTime.LocalDateTime(2019, 10, 02, 16, 00).InMainTimezone().ToOffsetDateTime(),
                                              trainerID));

                var campaign2 = new Campaign(
                    startDateTime: new NodaTime.LocalDateTime(2019, 10, 01, 12, 00).InMainTimezone().ToOffsetDateTime(),
                    endDateTime: new NodaTime.LocalDateTime(2019, 10, 30, 12, 00).InMainTimezone().ToOffsetDateTime(),
                    editionId: 1, name: "campaign2");
                campaign2.ScheduleTraining(new Training(
                                               "Papieska 2", "Wadowice",
                                               new NodaTime.LocalDateTime(2019, 11, 01, 12, 00).InMainTimezone().ToOffsetDateTime(),
                                               new NodaTime.LocalDateTime(2019, 11, 01, 16, 00).InMainTimezone().ToOffsetDateTime(),
                                               trainerID));
                campaign2.ScheduleTraining(new Training(
                                               "Papieska 22", "Wadowice",
                                               new NodaTime.LocalDateTime(2019, 11, 01, 12, 00).InMainTimezone().ToOffsetDateTime(),
                                               new NodaTime.LocalDateTime(2019, 11, 01, 16, 00).InMainTimezone().ToOffsetDateTime(),
                                               trainerID));

                var session = dbSessionProvider.CreateSession();
                await session.SaveAsync(campaign);

                Assert.Equal(1, campaign.Id);
                await session.SaveAsync(campaign2);

                Assert.Equal(2, campaign2.Id);
            }

            using (var scope = sp.CreateScope())
            {
                var mediator = scope.ServiceProvider.GetRequiredService <IMediator>();

                var results = await mediator.Send(new Recruitment.Trainings.Index.Query()
                {
                    CampaignIds = new[] { 1 }
                });

                Assert.Equal(2, results.Count);
                Assert.Collection(results,
                                  first => Assert.Equal("Papieska 1", first.Address),
                                  second => Assert.Equal("Papieska 11", second.Address)
                                  );
            }
        }
Esempio n. 14
0
 public DefaultClientAppContext()
 {
     ServiceProviderBuilder
     .ConfigureServices <ClientDependencyConfigurator>();
 }
Esempio n. 15
0
        private void Execute(GeneratorContext context)
        {
            try
            {
                var roots = new ServiceProviderBuilder(context).BuildRoots();

                foreach (var root in roots)
                {
                    var codeWriter = new CodeWriter();
                    codeWriter.UseNamespace("Jab");
                    using (codeWriter.Namespace($"{root.Type.ContainingNamespace.ToDisplayString()}"))
                    {
                        // TODO: implement infinite nesting
                        using CodeWriter.CodeWriterScope? parentTypeScope = root.Type.ContainingType is {} containingType?
                              codeWriter.Scope($"{SyntaxFacts.GetText(containingType.DeclaredAccessibility)} partial class {containingType.Name}") :
                              null;

                        codeWriter.Append($"{SyntaxFacts.GetText(root.Type.DeclaredAccessibility)} partial class {root.Type.Name}");
                        WriteInterfaces(codeWriter, root, false);
                        using (codeWriter.Scope())
                        {
                            WriteCacheLocations(root, codeWriter, onlyScoped: false);

                            foreach (var rootService in root.RootCallSites)
                            {
                                var rootServiceType = rootService.ServiceType;
                                using (rootService.IsMainImplementation ?
                                       codeWriter.Scope($"{rootServiceType} IServiceProvider<{rootServiceType}>.GetService()") :
                                       codeWriter.Scope($"private {rootServiceType} {GetResolutionServiceName(rootService)}()"))
                                {
                                    GenerateCallSiteWithCache(codeWriter,
                                                              "this",
                                                              rootService,
                                                              (w, v) => w.Line($"return {v};"));
                                }
                                codeWriter.Line();
                            }

                            WriteServiceProvider(codeWriter, root);
                            WriteDispose(codeWriter, root, onlyScoped: false);

                            using (codeWriter.Scope($"public Scope CreateScope()"))
                            {
                                codeWriter.Line($"return new Scope(this);");
                            }
                            codeWriter.Line();

                            if (root.KnownTypes.IServiceScopeFactoryType != null)
                            {
                                codeWriter.Line($"{root.KnownTypes.IServiceScopeType} {root.KnownTypes.IServiceScopeFactoryType}.CreateScope() => this.CreateScope();");
                                codeWriter.Line();
                            }

                            codeWriter.Append($"public partial class Scope");
                            WriteInterfaces(codeWriter, root, true);
                            using (codeWriter.Scope())
                            {
                                WriteCacheLocations(root, codeWriter, onlyScoped: true);
                                codeWriter.Line($"private {root.Type} _root;");
                                codeWriter.Line();

                                using (codeWriter.Scope($"public Scope({root.Type} root)"))
                                {
                                    codeWriter.Line($"_root = root;");
                                }
                                codeWriter.Line();

                                foreach (var rootService in root.RootCallSites)
                                {
                                    var rootServiceType = rootService.ServiceType;

                                    using (rootService.IsMainImplementation ?
                                           codeWriter.Scope($"{rootServiceType} IServiceProvider<{rootServiceType}>.GetService()") :
                                           codeWriter.Scope($"private {rootServiceType} {GetResolutionServiceName(rootService)}()"))
                                    {
                                        if (rootService.Lifetime == ServiceLifetime.Singleton)
                                        {
                                            codeWriter.Append($"return ");
                                            WriteResolutionCall(codeWriter, rootService, "_root");
                                            codeWriter.Line($";");
                                        }
                                        else
                                        {
                                            GenerateCallSiteWithCache(codeWriter,
                                                                      "_root",
                                                                      rootService,
                                                                      (w, v) => w.Line($"return {v};"));
                                        }
                                    }
                                    codeWriter.Line();
                                }

                                WriteServiceProvider(codeWriter, root);

                                if (root.KnownTypes.IServiceScopeType != null)
                                {
                                    codeWriter.Line($"{root.KnownTypes.IServiceProviderType} {root.KnownTypes.IServiceScopeType}.ServiceProvider => this;");
                                    codeWriter.Line();
                                }
                                WriteDispose(codeWriter, root, onlyScoped: true);
                            }
                        }
                    }
                    context.AddSource($"{root.Type.Name}.Generated.cs", codeWriter.ToString());
                }
            }
            catch (Exception e)
            {
                context.ReportDiagnostic(Diagnostic.Create(DiagnosticDescriptors.UnexpectedErrorDescriptor, Location.None, e.ToString()));
            }
        }
Esempio n. 16
0
        public static TestContext Get(Action <WindsorRegistrationOptions> configure = null, Func <IServiceProvider> serviceProviderFactory = null)
        {
            IServiceProvider serviceProvider = null;

            var serviceCollection = ServiceCollectionBuilder.New();

            var container = WindsorContainerBuilder.New(serviceCollection,
                                                        configure ?? (opts => opts.UseEntryAssembly(typeof(TestContextFactory).Assembly)),
                                                        serviceProviderFactory ?? (() => serviceProvider = ServiceProviderBuilder.New(serviceCollection)));

            var applicationBuilder = ApplicationBuilder.New(serviceProvider);

            return(new TestContext(serviceCollection, serviceProvider, applicationBuilder, container, container.RequireScope()));
        }
Esempio n. 17
0
        static void Main(string[] args)
        {
            var serviceProvider = ServiceProviderBuilder.GetInstance().GetServiceProvider();

            Console.ReadLine();
        }
        public async Task Querying_for_existing_enrollment_returns_that_enrollment_summary()
        {
            var sp = new ServiceProviderBuilder().BuildServiceProvider(ConfigureServices);

            using (var scope = sp.CreateScope())
            {
                var engine  = scope.ServiceProvider.GetRequiredService <ISzlemEngine>();
                var command = new SubmitRecruitmentForm.Command()
                {
                    FirstName   = "Andrzej",
                    LastName    = "Strzelba",
                    Email       = EmailAddress.Parse("*****@*****.**"),
                    PhoneNumber = Consts.FakePhoneNumber,
                    AboutMe     = "ala ma kota",
                    Region      = "Wolne Miasto Gdańsk",
                    PreferredLecturingCities = new[] { "Wadowice" },
                    PreferredTrainingIds     = new[] { 1, 2 },
                    GdprConsentGiven         = true
                };
                var result = await engine.Execute(command);

                Assert.True(result.IsSuccess);
            }

            using (var scope = sp.CreateScope())
            {
                var engine      = scope.ServiceProvider.GetRequiredService <ISzlemEngine>();
                var enrollments = await engine.Query(new GetSubmissions.Query());

                var result = await engine.Query(new GetEnrollmentDetails.QueryByEnrollmentId()
                {
                    EnrollmentID = enrollments.Single().Id
                });

                Assert.True(result.IsSuccess);
                var enrollment = result.Value;
                Assert.Equal(enrollments.Single().Id, enrollment.ID);
                Assert.Equal("Andrzej", enrollment.FirstName);
                Assert.Equal("Strzelba", enrollment.LastName);
                Assert.Equal(EmailAddress.Parse("*****@*****.**"), enrollment.Email);
                Assert.Equal(Consts.FakePhoneNumber, enrollment.PhoneNumber);
                Assert.Single(enrollment.PreferredLecturingCities, "Wadowice");

                Assert.Collection(enrollment.PreferredTrainings,
                                  first => {
                    Assert.Equal(1, first.ID);
                    Assert.Equal(trainerID, first.CoordinatorID);
                    Assert.Equal("Jan Paweł II", first.CoordinatorName);
                    Assert.Equal("Wadowice", first.City);
                },
                                  second => {
                    Assert.Equal(2, second.ID);
                    Assert.Equal(trainerID, second.CoordinatorID);
                    Assert.Equal("Jan Paweł II", second.CoordinatorName);
                    Assert.Equal("Wadowice", second.City);
                });

                enrollment.IsCurrentSubmission.Should().BeTrue();
                enrollment.IsOldSubmission.Should().BeFalse();
                enrollment.CanRecordTrainingResults.Should().BeFalse();
            }
        }