Ejemplo n.º 1
0
        public override async Task Stop()
        {
            using (new DiagnosticTimer($"Test TearDown for {instanceName}"))
            {
                await bootstrapper.Stop().ConfigureAwait(false);

                HttpClient.Dispose();
                Handler.Dispose();
            }

            bootstrapper = null;
            Bus          = null;
            HttpClient   = null;
            Handler      = null;
        }
Ejemplo n.º 2
0
        public BusInstance Start(bool isRunningAcceptanceTests = false)
        {
            var logger = LogManager.GetLogger(typeof(Bootstrapper));

            if (!isRunningAcceptanceTests)
            {
                var startOptions = new StartOptions(settings.RootUrl);

                WebApp = Microsoft.Owin.Hosting.WebApp.Start(startOptions, b => Startup.Configuration(b));
            }

            bus = NServiceBusFactory.CreateAndStart(settings, container, onCriticalError, documentStore, configuration, isRunningAcceptanceTests);

            logger.InfoFormat("Api is now accepting requests on {0}", settings.ApiUrl);

            return(bus);
        }
Ejemplo n.º 3
0
        async Task InitializeServiceControl(ScenarioContext context)
        {
            var instancePort    = FindAvailablePort(33333);
            var maintenancePort = FindAvailablePort(instancePort + 1);

            ConfigurationManager.AppSettings.Set("ServiceControl/TransportType", transportToUse.TypeName);

            var settings = new Settings(instanceName)
            {
                Port = instancePort,
                DatabaseMaintenancePort = maintenancePort,
                DbPath = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()),
                ForwardErrorMessages         = false,
                TransportCustomizationType   = transportToUse.TypeName,
                TransportConnectionString    = transportToUse.ConnectionString,
                ProcessRetryBatchesFrequency = TimeSpan.FromSeconds(2),
                MaximumConcurrencyLevel      = 2,
                HttpDefaultConnectionLimit   = int.MaxValue,
                RunInMemory = true,
                OnMessage   = (id, headers, body, @continue) =>
                {
                    var log = LogManager.GetLogger <ServiceControlComponentRunner>();
                    headers.TryGetValue(Headers.MessageId, out var originalMessageId);
                    log.Debug($"OnMessage for message '{id}'({originalMessageId ?? string.Empty}).");

                    //Do not filter out CC, SA and HB messages as they can't be stamped
                    if (headers.TryGetValue(Headers.EnclosedMessageTypes, out var messageTypes) &&
                        messageTypes.StartsWith("ServiceControl."))
                    {
                        return(@continue());
                    }

                    //Do not filter out subscribe messages as they can't be stamped
                    if (headers.TryGetValue(Headers.MessageIntent, out var intent) &&
                        intent == MessageIntentEnum.Subscribe.ToString())
                    {
                        return(@continue());
                    }

                    var currentSession = context.TestRunId.ToString();
                    if (!headers.TryGetValue("SC.SessionID", out var session) || session != currentSession)
                    {
                        log.Debug($"Discarding message '{id}'({originalMessageId ?? string.Empty}) because it's session id is '{session}' instead of '{currentSession}'.");
                        return(Task.FromResult(0));
                    }

                    return(@continue());
                }
            };

            setSettings(settings);
            Settings = settings;
            var configuration = new EndpointConfiguration(instanceName);

            configuration.EnableInstallers();

            configuration.GetSettings().Set("SC.ScenarioContext", context);
            configuration.GetSettings().Set(context);

            // This is a hack to ensure ServiceControl picks the correct type for the messages that come from plugins otherwise we pick the type from the plugins assembly and that is not the type we want, we need to pick the type from ServiceControl assembly.
            // This is needed because we no longer use the AppDomain separation.
            configuration.RegisterComponents(r => { configuration.GetSettings().Set("SC.ConfigureComponent", r); });

            configuration.RegisterComponents(r =>
            {
                r.RegisterSingleton(context.GetType(), context);
                r.RegisterSingleton(typeof(ScenarioContext), context);
            });

            configuration.Pipeline.Register <TraceIncomingBehavior.Registration>();
            configuration.Pipeline.Register <TraceOutgoingBehavior.Registration>();
            configuration.Pipeline.Register(new StampDispatchBehavior(context), "Stamps outgoing messages with session ID");
            configuration.Pipeline.Register(new DiscardMessagesBehavior(context), "Discards messages based on session ID");

            configuration.AssemblyScanner().ExcludeAssemblies(typeof(ServiceControlComponentRunner).Assembly.GetName().Name);

            customConfiguration(configuration);

            using (new DiagnosticTimer($"Initializing Bootstrapper for {instanceName}"))
            {
                var logPath = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
                Directory.CreateDirectory(logPath);

                var loggingSettings = new LoggingSettings(settings.ServiceName, logPath: logPath);
                bootstrapper = new Bootstrapper(ctx =>
                {
                    var logitem = new ScenarioContext.LogItem
                    {
                        Endpoint   = settings.ServiceName,
                        Level      = LogLevel.Fatal,
                        LoggerName = $"{settings.ServiceName}.CriticalError",
                        Message    = $"{ctx.Error}{Environment.NewLine}{ctx.Exception}"
                    };
                    context.Logs.Enqueue(logitem);
                    ctx.Stop().GetAwaiter().GetResult();
                }, settings, configuration, loggingSettings, builder => { builder.RegisterType <FailedErrorsModule>().As <INancyModule>(); });
                bootstrapper.HttpClientFactory = HttpClientFactory;
            }

            using (new DiagnosticTimer($"Initializing AppBuilder for {instanceName}"))
            {
                StaticConfiguration.DisableErrorTraces = false;
                var app = new AppBuilder();
                bootstrapper.Startup.Configuration(app);
                var appFunc = app.Build();

                Handler = new OwinHttpMessageHandler(appFunc)
                {
                    UseCookies        = false,
                    AllowAutoRedirect = false
                };
                var httpClient = new HttpClient(Handler);
                httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                HttpClient = httpClient;
            }

            using (new DiagnosticTimer($"Creating and starting Bus for {instanceName}"))
            {
                Bus = await bootstrapper.Start(true).ConfigureAwait(false);
            }
        }
Ejemplo n.º 4
0
        /// <summary>
        /// This method gets called by the runtime. Use this method to add services to the container
        /// </summary>
        /// <param name="services"></param>
        public void ConfigureServices(IServiceCollection services)
        {
            services
            .AddDbContext <MentifiContext>(options =>
                                           options.UseSqlServer(Configuration.GetConnectionString("Hub3cConnection"))).AddUnitOfWork <MentifiContext>();

            services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme)
            .AddIdentityServerAuthentication(options =>
            {
                options.Authority            = Configuration["AuthUrl"];
                options.RequireHttpsMetadata = false;
            });

            services.AddScoped <IDeserializer, JsonDeserializer>();
            services.AddScoped <IUserProfileService, UserProfileService>();
            services.AddScoped <IApiClient, ApiClient>();
            services.AddScoped <IConnectionService, ConnectionService>();
            services.AddScoped <ILookupService, LookupService>();
            services.AddScoped <ISystemUserDeviceService, SystemUserDeviceService>();
            services.AddScoped <IHub3cFirebaseApi, Hub3CFirebaseApi>();
            services.AddScoped <IDashboardService, DashboardService>();
            services.AddScoped <INotificationService, NotificationService>();
            services.AddScoped <IEmailApi, EmailApi>();
            services.AddScoped <IBulletinService, BulletinService>();
            services.AddScoped <IDocumentService, DocumentService>();
            services.AddScoped <IBusInstance, BusInstance>();
            services.AddScoped <IGoalService, GoalService>();
            services.AddScoped <IGoalProgressService, GoalProgressService>();
            services.AddScoped <ITaskService, TaskService>();
            services.AddScoped <IMessageBoardService, MessageBoardService>();
            services.AddScoped <IMessageService, MessageService>();
            services.AddScoped <IProjectService, ProjectService>();
            services.AddScoped <IProjectTeamService, ProjectTeamService>();
            services.AddScoped <IAdminInvitationService, AdminInvitationService>();
            services.AddScoped <IInvitationLinkService, InvitationLinkService>();
            services.AddScoped <IExperienceService, ExperienceService>();
            services.AddScoped <IInformalExperienceService, InformalExperienceService>();
            services.AddScoped <ISubjectExperienceService, SubjectExperienceService>();
            services.AddScoped <ISubjectPreferenceService, SubjectPreferenceService>();
            services.AddScoped <IAdditionalActivityService, AdditionalActivityService>();
            services.AddScoped <IUserAddressService, UserAddressService>();
            services.AddScoped <IEducationService, EducationService>();

            var mongoOpt = Configuration.GetSection("MongoDbConfig");

            services.AddSingleton <IMongoClient>(new MongoClient(mongoOpt.GetSection("Host").Value));
            services.AddSingleton <IMongoRepository <Resource>, MongoRepository <Resource> >();

            // For Rabbit Subscriber
            var rabbitUsername = Configuration.GetSection("MessagingConfig")["RabbitUsername"];
            var rabbitPassword = Configuration.GetSection("MessagingConfig")["RabbitPassword"];
            var rabbitHost     = Configuration.GetSection("MessagingConfig")["RabbitServer"];
            var rabbitVHost    = Configuration.GetSection("MessagingConfig")["RabbitVHost"];

            var subscriber  = new RabbitSubscriber(rabbitUsername, rabbitPassword, rabbitHost, rabbitVHost);
            var rabbitBus   = new RabbitBus(rabbitHost, rabbitUsername, rabbitPassword, rabbitVHost);
            var busInstance = new BusInstance(rabbitBus);

            services.AddSingleton(subscriber);
            services.AddSingleton(rabbitBus);
            services.AddSingleton(busInstance);
            services.AddMvc(op =>
            {
                op.Filters.Add(new ValidateModelStateAttribute());
            });

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

                c.DocInclusionPredicate((version, apiDesc) =>
                {
                    var versions = apiDesc.ControllerAttributes()
                                   .OfType <ApiVersionAttribute>()
                                   .SelectMany(attr => attr.Versions);

                    var values = apiDesc.RelativePath
                                 .Split('/');
                    values[1]            = version;
                    apiDesc.RelativePath = string.Join("/", values);

                    var versionParameter = apiDesc.ParameterDescriptions
                                           .SingleOrDefault(p => p.Name == "version");

                    if (versionParameter != null)
                    {
                        apiDesc.ParameterDescriptions.Remove(versionParameter);
                    }

                    //return true;

                    return(versions.Any(v => $"v{v.ToString()}" == version));
                });
                c.AddSecurityDefinition("Bearer",
                                        new ApiKeyScheme
                {
                    In          = "header",
                    Description = "Please insert JWT with Bearer into field",
                    Name        = "Authorization",
                    Type        = "apiKey",
                });

                c.IncludeXmlComments(GetXmlCommentsPath());
                c.DescribeAllEnumsAsStrings();
                c.DescribeAllParametersInCamelCase();
            });
            services.AddCors();
            services.AddApiVersioning(
                o =>
            {
                o.AssumeDefaultVersionWhenUnspecified = true;
                o.DefaultApiVersion = new ApiVersion(new DateTime(2018, 2, 6), 1, 0);
            });
        }