Ejemplo n.º 1
0
        protected virtual void RegisterConnectionsIfPresent(IServiceCollection services)
        {
            var queriesConnectionStringOrError = QueriesConnectionString.Create(Environment.GetEnvironmentVariable("DB")); //(Configuration["MelloDBConnString"]); //Configuration.QueriesConnectionString());

            if (queriesConnectionStringOrError.IsSuccess)
            {
                QueriesConnectionString = queriesConnectionStringOrError.Value;
                services.AddSingleton(QueriesConnectionString);
            }

            var commandsConnectionStringOrError = CommandsConnectionString.Create(Environment.GetEnvironmentVariable("DB")); //Configuration.CommandsConnectionString());

            if (commandsConnectionStringOrError.IsSuccess)
            {
                CommandsConnectionString = commandsConnectionStringOrError.Value;
                services.AddSingleton(CommandsConnectionString);
            }

            var computerVisionEndpointOrError = ComputerVisionEndpoint.Create("https://mello-image-recognition.cognitiveservices.azure.com/");//Environment.GetEnvironmentVariable("ComputerVisionEndpoint"));

            if (computerVisionEndpointOrError.IsSuccess)
            {
                ComputerVisionEndpoint = computerVisionEndpointOrError.Value;
                services.AddSingleton(ComputerVisionEndpoint);
            }

            var computerVisionKeyOrError = ComputerVisionKey.Create("");//Environment.GetEnvironmentVariable("ComputerVisionKey"));

            if (computerVisionKeyOrError.IsSuccess)
            {
                ComputerVisionKey = computerVisionKeyOrError.Value;
                services.AddSingleton(ComputerVisionKey);
            }
        }
Ejemplo n.º 2
0
 public Fingers10Context(CommandsConnectionString connectionString, ConsoleLogging consoleLogging, EventDispatcher eventDispatcher, IHttpContextAccessor httpContextAccessor)
 {
     _connectionString    = connectionString?.Value ?? throw new ArgumentNullException(nameof(connectionString));
     _useConsoleLogger    = consoleLogging?.Enable ?? throw new ArgumentNullException(nameof(consoleLogging));
     _eventDispatcher     = eventDispatcher;
     _httpContextAccessor = httpContextAccessor ?? throw new ArgumentNullException(nameof(httpContextAccessor));
 }
Ejemplo n.º 3
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();

            var config = new Config(3);
            var commandsConnectionString = new CommandsConnectionString(Configuration["ConnectionString"]);
            var queriesConnectionString  = new QueriesConnectionString(Configuration["QueriesConnectionString"]);

            services.AddSingleton(config);
            services.AddSingleton(commandsConnectionString);
            services.AddSingleton(queriesConnectionString);
            services.AddSingleton(new SessionFactory(commandsConnectionString));
            services.AddSingleton <Messages>();
            services.AddHandlers();
        }
Ejemplo n.º 4
0
        private static ISessionFactory BuildSessionFactory(CommandsConnectionString connectionString)
        {
            //FluentConfiguration configuration = Fluently.Configure()
            //    .Database(MsSqlConfiguration.MsSql2012.ConnectionString(connectionString.Value))
            //    .Mappings(m => m.FluentMappings
            //        .AddFromAssembly(Assembly.GetExecutingAssembly())
            //        .Conventions.Add(
            //            ForeignKey.EndsWith("ID"),
            //            ConventionBuilder.Property.When(criteria => criteria.Expect(x => x.Nullable, Is.Not.Set), x => x.Not.Nullable()))
            //        .Conventions.Add<OtherConversions>()
            //        .Conventions.Add<TableNameConvention>()
            //        .Conventions.Add<HiLoConvention>()
            //    );

            return(null);//configuration.BuildSessionFactory();
        }
Ejemplo n.º 5
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();

            var config = new Config(3); // in prod, get from appsettings.json.

            services.AddSingleton(config);
            var commandsConnectionString = new CommandsConnectionString(Configuration["CommandsConnectionString"]);
            var queriesConnectionString  = new QueriesConnectionString(Configuration["QueriesConnectionString"]);

            services.AddSingleton(commandsConnectionString);
            services.AddSingleton(queriesConnectionString);
            services.AddSingleton <SessionFactory>();

            services.AddSingleton <Messages>();
            services.AddHandlers();
        }
Ejemplo n.º 6
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();

            var connectionString = new CommandsConnectionString(Configuration["ConnectionString"]);

            services.AddSingleton(connectionString);
            var quriesConnectionString = new QueriesConnectionString(Configuration["QueriesConnectionString"]);

            services.AddSingleton(quriesConnectionString);

            services.AddSingleton <SessionFactory>();
            services.AddTransient <UnitOfWork>();
            services.AddSingleton <Messages>();

            services.AddHandlers();
        }
Ejemplo n.º 7
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            var commandsConnectionString = new CommandsConnectionString(Configuration.GetConnectionString("CommandConnectionString"));
            var queriesConnectionString  = new QueriesConnectionString(Configuration.GetConnectionString("QueriesConnectionString"));

            services.AddSingleton(commandsConnectionString);
            services.AddSingleton(queriesConnectionString);

            var mappingConfig = new MapperConfiguration(mc =>
            {
                mc.AddProfile(new MappingProfile());
            });

            services.AddSingleton(mappingConfig.CreateMapper());



            services.AddDbContext <StudentContext>(cfg =>
            {
                cfg.UseSqlServer(Configuration.GetConnectionString("CommandConnectionString"));
            });

            services.AddApiVersioning();
            services.AddSwaggerGen(options =>
            {
                options.SwaggerDoc("v1", new Info
                {
                    Title       = "Student Management System",
                    Version     = "v1",
                    Description = "API for Student Management System"
                });
            });

            services.AddScoped <IUnitOfWork, UnitOfWork>();
            services.AddTransient <IValidatorFactory, ServiceProviderValidatorFactory>();
            services
            .AddMvc()
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
            .AddFluentValidation(fv => fv.RegisterValidatorsFromAssemblyContaining <Startup>());

            services.AddMediatR(typeof(Startup).Assembly);
        }
Ejemplo n.º 8
0
        public static void Config(IServiceCollection services)
        {
            services.AddMediatR(Assembly.GetExecutingAssembly());

            services.AddDbContextFactory <ContentContext>(options =>
            {
                options.UseSqlServer(CommandsConnectionString.GetConnectionString());
            });


            services.AddScoped <PostController>();
            services.AddScoped <ContentContext>();
            services.AddScoped <IPostRepository, PostRepository>();
            //  services.AddScoped<IUnitOfWork,UnitOfWork>();
            services.AddScoped <IConnectionString, CommandsConnectionString>();
            var connectionString = CommandsConnectionString.GetConnectionString();

            services.AddSingleton(connectionString);
            services.AddScoped(typeof(IRequestHandler <CreatePostCommand, Result>), typeof(CreatePostCommandHandler));
            services.AddScoped(typeof(IPipelineBehavior <,>), typeof(TransactionBehavior <,>));
        }
Ejemplo n.º 9
0
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();

            var config = new Config(3); // Deserialize from appsettings.json
            var commandsConnectionString = new CommandsConnectionString(Configuration["ConnectionString"]);
            var queriesConnectionString  = new QueriesConnectionString(Configuration["QueriesConnectionString"]);

            var diBuilder = new ContainerBuilder();

            diBuilder.Populate(services);
            diBuilder.RegisterInstance(config);
            diBuilder.RegisterInstance(commandsConnectionString);
            diBuilder.RegisterInstance(queriesConnectionString);
            diBuilder.RegisterType <SessionFactory>().SingleInstance();
            diBuilder.RegisterType <Messages>().SingleInstance();
            diBuilder.AddMediatR(typeof(DisenrollCommand).Assembly);

            AutofacContainer = diBuilder.Build();
            return(new AutofacServiceProvider(AutofacContainer));
        }
Ejemplo n.º 10
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();

            var commandsConnectionString = new CommandsConnectionString(Configuration["ConnectionString"]);
            var queriesConnectionString  = new CommandsConnectionString(Configuration["QueriesConnectionString"]);

            services.AddSingleton(commandsConnectionString);
            services.AddSingleton(queriesConnectionString);
            services.AddSingleton(new SessionFactory(Configuration["ConnectionString"]));
            services.AddTransient <UnitOfWork>();
            services.AddTransient <ICommandHandler <EditPersonalInfoCommand> >(provider =>
                                                                               new DatabaseRetryDecorator <EditPersonalInfoCommand>(
                                                                                   new EditPersonalInfoCommandHandler(provider.GetService <SessionFactory>())));
            services.AddTransient <ICommandHandler <RegisterCommand>, RegisterCommandHandler>();
            services.AddTransient <ICommandHandler <UnregisterCommand>, UnregisterCommandHandler>();
            services.AddTransient <ICommandHandler <EnrollCommand>, EnrollComandHandler>();
            services.AddTransient <ICommandHandler <TransferEnrollmentCommand>, TransferEnrollmentCommandHandler>();
            services.AddTransient <ICommandHandler <DisenrollCommand>, DisenrollCommandHandler>();
            services.AddTransient <IQueryHandler <GetListQuery, List <StudentDto> >, GetListQueryHandler>();
            services.AddSingleton <Messages>();
            //services.AddHandlers();
        }
Ejemplo n.º 11
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info {
                    Title = "App API", Version = "v1"
                });
            });

            //Connection strings configurations
            var commandsConnectionString
                = new CommandsConnectionString(Configuration["CommandsConnectionString"]);
            var queriesConnectionString =
                new QueriesConnectionString(Configuration["QueriesConnectionString"]);

            services.AddSingleton(commandsConnectionString);
            services.AddSingleton(queriesConnectionString);

            //IoC + DI
            services.AddSingleton <Messages>();
            services.AddHandlers();

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
        }
Ejemplo n.º 12
0
 public SessionFactory(CommandsConnectionString connectionString)
 {
     _factory = BuildSessionFactory(connectionString);
 }
        /// <summary>
        /// This method gets called by the runtime. Use this method to add services to the container. For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        /// </summary>
        /// <param name="services"></param>
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddHttpCacheHeaders((expirationModelOptions) =>
            {
                expirationModelOptions.MaxAge        = 60;
                expirationModelOptions.CacheLocation = Marvin.Cache.Headers.CacheLocation.Private;
            },
                                         (validationModelOptions) =>
            {
                validationModelOptions.MustRevalidate = true;
            });

            services.AddResponseCaching();

            services.AddResponseCompression();

            services.AddControllers(options =>
            {
                //options.Filters.Add(new AuthorizeFilter());
                options.Filters.Add(new ProducesDefaultResponseTypeAttribute());
                options.Filters.Add(new ProducesResponseTypeAttribute(StatusCodes.Status400BadRequest));
                options.Filters.Add(new ProducesResponseTypeAttribute(StatusCodes.Status401Unauthorized));
                options.Filters.Add(new ProducesResponseTypeAttribute(StatusCodes.Status406NotAcceptable));
                options.Filters.Add(new ProducesResponseTypeAttribute(StatusCodes.Status500InternalServerError));

                options.ReturnHttpNotAcceptable = true;
                options.CacheProfiles.Add("240SecondsCacheProfile",
                                          new CacheProfile()
                {
                    Duration = 240
                });
                //options.InputFormatters.Insert(0, GetJsonPatchInputFormatter());
            })
            .AddNewtonsoftJson(setupAction =>
            {
                setupAction.SerializerSettings.ContractResolver =
                    new CamelCasePropertyNamesContractResolver();
            })
            //.AddJsonOptions(options =>
            //{
            //    options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
            //    options.JsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
            //})
            .AddXmlDataContractSerializerFormatters()
            .ConfigureApiBehaviorOptions(options =>
            {
                options.InvalidModelStateResponseFactory = context =>
                {
                    // create a problem details object
                    var problemDetailsFactory = context.HttpContext.RequestServices
                                                .GetRequiredService <ProblemDetailsFactory>();
                    var problemDetails = problemDetailsFactory.CreateValidationProblemDetails(
                        context.HttpContext,
                        context.ModelState);

                    // add additional info not added by default
                    problemDetails.Detail   = "See the errors field for details.";
                    problemDetails.Instance = context.HttpContext.Request.Path;

                    // find out which status code to use
                    var actionExecutingContext =
                        context as Microsoft.AspNetCore.Mvc.Filters.ActionExecutingContext;

                    // if there are modelstate errors & all keys were correctly
                    // found/parsed we're dealing with validation errors
                    //
                    // if the context couldn't be cast to an ActionExecutingContext
                    // because it's a ControllerContext, we're dealing with an issue
                    // that happened after the initial input was correctly parsed.
                    // This happens, for example, when manually validating an object inside
                    // of a controller action.  That means that by then all keys
                    // WERE correctly found and parsed.  In that case, we're
                    // thus also dealing with a validation error.
                    if (context.ModelState.ErrorCount > 0 &&
                        (context is ControllerContext ||
                         actionExecutingContext?.ActionArguments.Count == context.ActionDescriptor.Parameters.Count))
                    {
                        problemDetails.Type   = "https://enterprisearchitecture.com/modelvalidationproblem";
                        problemDetails.Status = StatusCodes.Status422UnprocessableEntity;
                        problemDetails.Title  = "One or more validation errors occurred.";

                        return(new UnprocessableEntityObjectResult(problemDetails)
                        {
                            ContentTypes = { "application/problem+json" }
                        });
                    }

                    // if one of the keys wasn't correctly found / couldn't be parsed
                    // we're dealing with null/unparsable input
                    problemDetails.Status = StatusCodes.Status400BadRequest;
                    problemDetails.Title  = "One or more errors on input occurred.";
                    return(new BadRequestObjectResult(problemDetails)
                    {
                        ContentTypes = { "application/problem+json" }
                    });
                };
            });

            services.Configure <MvcOptions>(config =>
            {
                var newtonsoftJsonOutputFormatter = config.OutputFormatters
                                                    .OfType <NewtonsoftJsonOutputFormatter>()?.FirstOrDefault();

                if (newtonsoftJsonOutputFormatter != null)
                {
                    newtonsoftJsonOutputFormatter.SupportedMediaTypes.Add("application/vnd.fingers10.hateoas+json");
                }
            });

            services.AddVersionedApiExplorer(options =>
            {
                options.GroupNameFormat = "'v'VV";
                //options.SubstituteApiVersionInUrl = true;
            });

            services.AddApiVersioning(options =>
            {
                options.AssumeDefaultVersionWhenUnspecified = true;
                options.DefaultApiVersion = new ApiVersion(1, 0);
                options.ReportApiVersions = true;
                options.ApiVersionReader  = new HeaderApiVersionReader("api-version");
                //options.ApiVersionReader = new MediaTypeApiVersionReader();
            });

            IApiVersionDescriptionProvider apiVersionDescriptionProvider = GetApiVersionDescriptionProvider(services);

            services.AddSwaggerGen(options =>
            {
                foreach (var description in apiVersionDescriptionProvider.ApiVersionDescriptions)
                {
                    options.SwaggerDoc(
                        $"EnterpriseArchitectureOpenAPISpecification{description.GroupName}",
                        new Microsoft.OpenApi.Models.OpenApiInfo
                    {
                        Title       = "EnterpriseArchitecture API",
                        Version     = description.ApiVersion.ToString(),
                        Description = "Through this API you can access architecture reference and knowledge",
                        Contact     = new Microsoft.OpenApi.Models.OpenApiContact
                        {
                            Email = "*****@*****.**",
                            Name  = "Abdul Rahman",
                            Url   = new Uri("https://www.linkedin.com/in/fingers10")
                        },
                        // Need to change the license in future
                        License = new Microsoft.OpenApi.Models.OpenApiLicense
                        {
                            Name = "MIT License",
                            Url  = new Uri("https://opensource.org/licenses/MIT")
                        },
                        //TermsOfService = new Uri("")
                    });
                }

                //options.AddSecurityDefinition("token", new OpenApiSecurityScheme
                //{
                //    Type = SecuritySchemeType.OpenIdConnect,
                //    OpenIdConnectUrl = new Uri(Configuration.GetValue<string>("IDP"))
                //});

                //options.AddSecurityRequirement(new OpenApiSecurityRequirement
                //{
                //    {
                //        new OpenApiSecurityScheme
                //        {
                //            Reference = new OpenApiReference {
                //                Type = ReferenceType.SecurityScheme,
                //                Id = "token" }
                //        }, Array.Empty<string>()
                //    }
                // });

                //options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme()
                //{
                //    Type = SecuritySchemeType.Http,
                //    Scheme = "Bearer",
                //    Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\""
                //});

                //options.AddSecurityRequirement(new OpenApiSecurityRequirement
                //{
                //    {
                //        new OpenApiSecurityScheme
                //        {
                //            Reference = new OpenApiReference {
                //                Type = ReferenceType.SecurityScheme,
                //                Id = "Bearer" }
                //        }, new List<string>() }
                //});

                options.DocInclusionPredicate((documentName, apiDescription) =>
                {
                    var actionApiVersionModel = apiDescription.ActionDescriptor
                                                .GetApiVersionModel(ApiVersionMapping.Explicit | ApiVersionMapping.Implicit);

                    if (actionApiVersionModel == null)
                    {
                        return(true);
                    }

                    if (actionApiVersionModel.DeclaredApiVersions.Count > 0)
                    {
                        return(actionApiVersionModel.DeclaredApiVersions.Any(v =>
                                                                             $"EnterpriseArchitectureOpenAPISpecificationv{v}" == documentName));
                    }

                    return(actionApiVersionModel.ImplementedApiVersions.Any(v =>
                                                                            $"EnterpriseArchitectureOpenAPISpecificationv{v}" == documentName));
                });

                options.OperationFilter <GetBookOperationFilter>();
                options.OperationFilter <CreateAuthorOperationFilter>();

                var xmlCommentsFile     = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
                var xmlCommentsFullPath = Path.Combine(AppContext.BaseDirectory, xmlCommentsFile);

                options.IncludeXmlComments(xmlCommentsFullPath);
            });

            services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());

            services.AddHttpContextAccessor();
            var config = new Config(Configuration.GetValue <int>("DatabaseConnectRetryAttempts"));

            services.AddSingleton(config);
            var consoleLogging = new ConsoleLogging(Configuration.GetValue <bool>("EnableConsoleLogging"));

            services.AddSingleton(consoleLogging);

            var commandsConnectionString = new CommandsConnectionString(Configuration["ConnectionString"]);
            var queriesConnectionString  = new QueriesConnectionString(Configuration["ConnectionString"]);

            services.AddSingleton(commandsConnectionString);
            services.AddSingleton(queriesConnectionString);

            services.AddTransient <IPropertyCheckerService, PropertyCheckerService>();
            services.AddTransient <IBus, Bus>();
            services.AddTransient <MessageBus>();
            services.AddTransient <EventDispatcher>();
            services.AddTransient <Messages>();
            services.AddTransient <Fingers10Context>();
            services.AddTransient <IAsyncRepository <Student>, StudentRepository>();
            services.AddTransient <IStudentReadonlyRepository, StudentReadonlyRepository>();
            services.AddTransient <IAuthorReadonlyRepository, AuthorReadonlyRepository>();
            services.AddTransient <IUnitOfWork, UnitOfWork>();
            services.AddHandlers();
        }
Ejemplo n.º 14
0
 public RegisterCommandStudentHandler(CommandsConnectionString connectionString)
 {
     _connectionString = connectionString;
 }