Esempio n. 1
0
        // 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
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();

            MongoDbPersistence.Configure();

            // Add framework services.
            services.AddSwaggerGen(options =>
            {
                //options.DescribeAllEnumsAsStrings();
                options.SwaggerDoc("v1", new Microsoft.OpenApi.Models.OpenApiInfo
                {
                    Title          = "TestOnContainers - User HTTP API",
                    Version        = "v1",
                    Description    = "The User Microservice HTTP API. This is a Data-Driven/CRUD microservice sample",
                    TermsOfService = new Uri("https://example.com/terms")
                });
            });

            services.Configure <UserSettings>(Configuration);

            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();
            services.AddTransient <IUsersService, UsersService>();
            services.AddTransient <IUsersRepository, UsersRepository>();

            services.AddTransient <IQuestionsService, QuestionsService>();
            services.AddTransient <IQuestionsRepository, QuestionsRepository>();

            services.AddScoped <IMongoContext, MongoContext>();
        }
Esempio n. 2
0
        public static DomainActorSystem Build(string actorSystemName, string journalConnectionString, string snapshotStoreConnectionString)
        {
            var configStr     = $@"
akka {{
    persistence {{
        publish-plugin-commands = on
        journal {{
            plugin = ""akka.persistence.journal.mongodb""
            mongodb {{
                class = ""Akka.Persistence.MongoDb.Journal.MongoDbJournal, Akka.Persistence.MongoDb""
                connection-string = ""{journalConnectionString}""
                collection = ""EventJournal""
                metadata-collection = ""Metadata""
                auto-initialize = on
            }}
        }}
        snapshot-store {{
	        mongodb {{
		        class = ""Akka.Persistence.MongoDb.Snapshot.MongoDbSnapshotStore, Akka.Persistence.MongoDb""
		        connection-string = ""{snapshotStoreConnectionString}""
		        auto-initialize = on
		        collection = ""SnapshotStore""
	        }}
        }}
    }}
}}
";
            var configuration = ConfigurationFactory.ParseString(configStr);
            var actorSystem   = ActorSystem.Create(actorSystemName, configuration);

            MongoDbPersistence.Get(actorSystem);

            return(new DomainActorSystem(actorSystemName, actorSystem));
        }
Esempio n. 3
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseHttpsRedirection();

            app.UseSwagger();

            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "Poll API V1");
            });

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });

            MongoDbPersistence.Configure();
        }
Esempio n. 4
0
        public MongoDbSnapshotStore()
        {
            _settings = MongoDbPersistence.Get(Context.System).SnapshotStoreSettings;

            var serialization = Context.System.Serialization;

            switch (_settings.StoredAs)
            {
            case StoredAsType.Binary:
                _serialize = o =>
                {
                    var serializer = serialization.FindSerializerFor(o);
                    return(new SerializationResult(serializer.ToBinary(o), serializer));
                };
                _deserialize = (type, serialized, manifest, serializerId) =>
                {
                    if (serializerId.HasValue)
                    {
                        return(serialization.Deserialize((byte[])serialized, serializerId.Value, manifest));
                    }
                    var deserializer = serialization.FindSerializerForType(type);
                    return(deserializer.FromBinary((byte[])serialized, type));
                };
                break;

            default:
                _serialize   = o => new SerializationResult(o, null);
                _deserialize = (type, serialized, manifest, serializerId) => serialized;
                break;
            }
        }
Esempio n. 5
0
        public void Mongo_SnapshotStoreSettingsSettings_must_have_default_values()
        {
            var mongoPersistence = MongoDbPersistence.Get(Sys);

            mongoPersistence.SnapshotStoreSettings.ConnectionString.Should().Be(string.Empty);
            mongoPersistence.SnapshotStoreSettings.AutoInitialize.Should().BeFalse();
            mongoPersistence.SnapshotStoreSettings.Collection.Should().Be("SnapshotStore");
        }
Esempio n. 6
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0);

            // Configure the persistence in another layer
            MongoDbPersistence.Configure();

            RegisterServices(services);
        }
Esempio n. 7
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            MongoDbPersistence.Configure();

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
            services.AddScoped <IMongoContext, MongoContext>();
            services.AddScoped <IUnitOfWork, UnitOfWork>();
            services.AddScoped <IProductRepository, ProductRepository>();
        }
Esempio n. 8
0
        public void Mongo_JournalSettings_must_have_default_values()
        {
            var mongoPersistence = MongoDbPersistence.Get(Sys);

            mongoPersistence.JournalSettings.ConnectionString.Should().Be(string.Empty);
            mongoPersistence.JournalSettings.AutoInitialize.Should().BeFalse();
            mongoPersistence.JournalSettings.Collection.Should().Be("EventJournal");
            mongoPersistence.JournalSettings.MetadataCollection.Should().Be("Metadata");
        }
Esempio n. 9
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddScoped <IMongoContext, MongoContext>();
            services.AddScoped <IUnitOfWork, MongoDbUnitOfWork>();
            services.AddScoped(typeof(IRepository <>), typeof(MongoDbRepository <>));
            services.AddScoped(typeof(ICustomMongoRepository <>), typeof(CustomCollectionNameMongoDbRepository <>));
            // Custom-named collections that we do  not want to use the class name as the collection name
            services.AddScoped <IMongoCollectionName <EuDocumentEntity>, EuDocumentsCollection>();

            // MongoDb Configuration
            MongoDbPersistence.Configure();

            //services.AddNewtonsoftJson(options => options.UseMemberCasing()); ;

            services.AddScoped <RegulationManager>();
            services.AddScoped <EuDocumentsManager>();

            services.AddCors(options =>
            {
                options.AddPolicy(MyAllowSpecificOrigins,
                                  builder =>
                {
                    builder.WithOrigins("http://localhost:4200/");
                    builder.WithOrigins("https://dev-complai.eu.auth0.com");
                });
            });


            ConfigureAuthentication(services);


            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info {
                    Title = "COMPLAI API", Version = "v1"
                });
                c.AddSecurityDefinition(CookieAuthenticationDefaults.AuthenticationScheme, new ApiKeyScheme()
                {
                    Type        = "apiKey",
                    Description = CookieAuthenticationDefaults.AuthenticationScheme,
                    In          = CookieAuthenticationDefaults.AuthenticationScheme,
                    Name        = CookieAuthenticationDefaults.AuthenticationScheme
                });

                // Include XML comments in swagger documentation
                var filePath = Path.Combine(System.AppContext.BaseDirectory, "ComplAI.API.xml");
                c.IncludeXmlComments(filePath);
            });

            services.AddMvc();
        }
Esempio n. 10
0
        // This method gets called by the runtime. Use this method to add services to the container.

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc(options => options.Filters.Add(new ApiExceptionFilter())).SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info
                {
                    Version        = "v1",
                    Title          = "API Net Core",
                    Description    = "My ASP.NET Core Web API",
                    TermsOfService = "None",
                    Contact        = new Contact()
                    {
                        Name = "Enrique Inca Q.", Email = "*****@*****.**", Url = ""
                    }
                });
            });
            services.AddCors();
            MongoDbPersistence.Configure();
            AutoMapperConfiguracion.Configure();
            RegisterServices(services);

            // configure strongly typed settings objects
            var appSettingsSection = Configuration.GetSection("AppSettings");

            services.Configure <Settings>(appSettingsSection);

            // configure jwt authentication
            var settings = appSettingsSection.Get <Settings>();
            var key      = Encoding.ASCII.GetBytes(settings.Secret);

            services.AddAuthentication(x =>
            {
                x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(x =>
            {
                x.RequireHttpsMetadata      = false;
                x.SaveToken                 = true;
                x.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = new SymmetricSecurityKey(key),
                    ValidateIssuer           = false,
                    ValidateAudience         = false
                };
            });
        }
Esempio n. 11
0
        public void InstallServices(IServiceCollection services, IConfiguration configuration)
        {
            // Config Entity Framework
            string migrationsAssembly = "Pso.Infra.Data.EfCore";

            services.AddDbContext <PsoDbContext>((sp, options) =>
                                                 options.UseNpgsql(configuration.GetConnectionString("DefaultConnection"),
                                                                   b => b.MigrationsAssembly(migrationsAssembly)));

            services.Configure <PsoDbMongoDatabaseSettings>(configuration.GetSection("MongoConnection"));
            services.AddScoped <DbContext, PsoDbContext>();
            services.AddScoped <PsoDbContext>();
            services.AddScoped <MongoDataContext>();

            //Configure MongoDb
            MongoDbPersistence.Configure();
        }
Esempio n. 12
0
        public static void Start()
        {
            var config = ConfigurationFactory.ParseString(@"
                akka.persistence {
                    journal {
                        plugin = ""akka.persistence.journal.mongodb""
                        mongodb {
                            connection-string = ""mongodb://127.0.0.1:27017/example""
                        }
                    }
                }");

            ExampleSystem = ActorSystem.Create("ExampleSystem", config);

            MongoDbPersistence.Get(ExampleSystem);

            ExampleActor = ExampleSystem.ActorOf <ExampleActor>();
        }
Esempio n. 13
0
 // This method gets called by the runtime. Use this method to add services to the container.
 public void ConfigureServices(IServiceCollection services)
 {
     //services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
     services.AddControllers();
     // Configure the persistence in another layer
     MongoDbPersistence.Configure();
     services.AddSwaggerGen(s =>
     {
         s.SwaggerDoc("v1",
                      new OpenApiInfo
         {
             Version     = "v1",
             Title       = "Workiom Code Test",
             Description = "Workiom Code Test"
         });
     });
     RegisterServices(services);
 }
        public MongoDbJournal()
        {
            _settings = MongoDbPersistence.Get(Context.System).JournalSettings;

            var serialization = Context.System.Serialization;

            switch (_settings.StoredAs)
            {
            case StoredAsType.Binary:
                _serialize = representation =>
                {
                    var serializer = serialization.FindSerializerFor(representation);
                    return(new SerializationResult(serializer.ToBinary(representation), serializer));
                };
                _deserialize = (type, serialized, manifest, serializerId) =>
                {
                    if (serializerId.HasValue)
                    {
                        /*
                         * Backwards compat: check to see if manifest is populated before using it.
                         * Otherwise, fall back to using the stored type data instead.
                         * Per: https://github.com/AkkaNetContrib/Akka.Persistence.MongoDB/issues/57
                         */
                        if (string.IsNullOrEmpty(manifest))
                        {
                            return(serialization.Deserialize((byte[])serialized, serializerId.Value, type));
                        }
                        return(serialization.Deserialize((byte[])serialized, serializerId.Value, manifest));
                    }

                    var deserializer = serialization.FindSerializerForType(type);
                    return(deserializer.FromBinary((byte[])serialized, type));
                };
                break;

            default:
                _serialize   = representation => new SerializationResult(representation, null);
                _deserialize = (type, serialized, manifest, serializerId) => serialized;
                break;
            }
        }
Esempio n. 15
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();

            services.AddSingleton(typeof(IMongoContext <>), typeof(MongoContext <>));
            services.AddScoped(typeof(IRepository <>), typeof(BaseRepository <>));
            services.AddScoped(typeof(IUserRepository), typeof(UserRepository));
            services.AddScoped <BudgetService, BudgetService>();
            services.AddScoped <UserService, UserService>();


            services.Configure <Settings>(options =>
            {
                options.ConnectionString
                    = Configuration.GetSection("MongoConnection:ConnectionString").Value;
                options.Database
                    = Configuration.GetSection("MongoConnection:Database").Value;
            });

            MongoDbPersistence.Configure();
        }
Esempio n. 16
0
 // This method gets called by the runtime. Use this method to add services to the container.
 public void ConfigureServices(IServiceCollection services)
 {
     services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
     // Configure the persistence in another layer
     MongoDbPersistence.Configure();
     services.AddSwaggerGen(s =>
     {
         s.SwaggerDoc("v1", new Info
         {
             Version     = "v1",
             Title       = "MongoDB Repository Pattern and Unit of Work - Example",
             Description = "Swagger surface",
             Contact     = new Contact {
                 Name = "Bruno Brito", Email = "*****@*****.**", Url = "http://www.brunobrito.net.br"
             },
             License = new License {
                 Name = "MIT", Url = "https://github.com/brunohbrito/MongoDB-RepositoryUoWPatterns/blob/master/LICENSE"
             },
         });
     });
     RegisterServices(services);
 }
Esempio n. 17
0
 // This method gets called by the runtime. Use this method to add services to the container.
 public void ConfigureServices(IServiceCollection services)
 {
     services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
     // Configure the persistence in another layer
     MongoDbPersistence.Configure();
     services.AddSwaggerGen(s =>
     {
         s.SwaggerDoc("v1", new Info
         {
             Version     = "v1",
             Title       = "MongoDB Repository",
             Description = "Swagger",
             Contact     = new Contact {
                 Name = "", Email = "", Url = ""
             },
             License = new License {
                 Name = "", Url = ""
             },
         });
     });
     RegisterServices(services);
 }
Esempio n. 18
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers()
            .SetCompatibilityVersion(CompatibilityVersion.Version_3_0)
            .AddJsonOptions(opt =>
            {
                var serializerOptions = opt.JsonSerializerOptions;
                serializerOptions.IgnoreNullValues         = true;
                serializerOptions.IgnoreReadOnlyProperties = false;
                serializerOptions.WriteIndented            = true;
            });

            // Configure the persistence in another layer
            MongoDbPersistence.Configure();

            services.AddSwaggerGen(s =>
            {
                s.SwaggerDoc("v1", new OpenApiInfo
                {
                    Version     = "v1",
                    Title       = "MongoDB Repository Pattern and Unit of Work - Example",
                    Description = "Swagger surface",
                    Contact     = new OpenApiContact
                    {
                        Name  = "Bruno Brito",
                        Email = "*****@*****.**",
                        Url   = new Uri("http://www.brunobrito.net.br")
                    },
                    License = new OpenApiLicense
                    {
                        Name = "MIT",
                        Url  = new Uri("https://github.com/brunohbrito/MongoDB-RepositoryUoWPatterns/blob/master/LICENSE")
                    }
                });
            });

            RegisterServices(services);
        }
Esempio n. 19
0
        static void Main(string[] args)
        {
            MongoDbPersistence.Configure();

            ConnectionOptions options = new ConnectionOptions
            {
                Url      = "mongodb://127.0.0.1:27017/?connectTimeoutMS=10000&socketTimeoutMS=10000",
                Database = "test-db"
            };

            MongoDbContext mongoDbContext = new MongoDbContext(options);

            var facetRepository   = new FacetRepository(mongoDbContext);
            var productRepository = new ProductRepository(mongoDbContext);

            var insertedEntity = productRepository.Insert(new Product
            {
                Name     = "Product-Test-1",
                TenantId = "Tenant-Test"
            });

            Console.WriteLine("Hello World!");
        }
        public MongoDbSnapshotStore()
        {
            _settings = MongoDbPersistence.Get(Context.System).SnapshotStoreSettings;

            _serialization = Context.System.Serialization;
        }
 public MongoDbJournal()
 {
     _settings = MongoDbPersistence.Get(Context.System).JournalSettings;
 }
Esempio n. 22
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure <CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded    = context => true;
                options.MinimumSameSitePolicy = Microsoft.AspNetCore.Http.SameSiteMode.None;
                options.ConsentCookie.Name    = "LuduStack.Consent";
            });

            MongoDbPersistence.Configure();

            services.AddIdentityMongoDbProvider <ApplicationUser, Role>(options =>
            {
                options.Password.RequireDigit           = false;
                options.Password.RequiredLength         = 4;
                options.Password.RequireNonAlphanumeric = false;
                options.Password.RequireUppercase       = false;
                options.Password.RequireLowercase       = false;
            }, options =>
            {
                options.ConnectionString = Configuration["MongoSettings:Connection"];
                options.DatabaseName     = Configuration["MongoSettings:DatabaseName"];
            })
            .AddDefaultTokenProviders();

            SetupAuthentication(services);

            services.AddAutoMapperSetup();

            services.AddSession(opt =>
            {
                opt.Cookie.Name        = ".LuduStack.Session";
                opt.Cookie.IsEssential = true;
            });

            services.AddResponseCompression();

            services.AddRouting(options =>
            {
                options.LowercaseUrls       = true;
                options.AppendTrailingSlash = true;
            });

            services.AddLocalization();

            services.AddControllersWithViews(options =>
            {
                options.ModelBinderProviders.Insert(0, new InvariantDecimalModelBinderProvider());
                options.CacheProfiles.Add("Default",
                                          new CacheProfile()
                {
                    Duration     = 2592000,
                    VaryByHeader = HeaderNames.ETag
                });
                options.CacheProfiles.Add("Short",
                                          new CacheProfile()
                {
                    Duration     = 86400,
                    VaryByHeader = HeaderNames.ETag
                });
                options.CacheProfiles.Add("Never",
                                          new CacheProfile()
                {
                    Location = ResponseCacheLocation.None,
                    NoStore  = true
                });
            })
            .AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix)
            .AddDataAnnotationsLocalization(options =>
            {
                options.DataAnnotationLocalizerProvider = (type, factory) =>
                                                          factory.Create(typeof(SharedResources));
            });

            services.AddMemoryCache();

            services.AddProgressiveWebApp(new PwaOptions {
                EnableCspNonce = false
            });

            services.AddTransient <ICookieMgrService, CookieMgrService>();

            services.Configure <ConfigOptions>(myOptions =>
            {
                myOptions.FacebookAppId    = Configuration["Authentication:Facebook:AppId"];
                myOptions.ReCaptchaSiteKey = Configuration["ReCaptcha:SiteKey"];
            });

            services.AddMediatR(Assembly.GetExecutingAssembly(), typeof(SendNotificationRequestHandler).GetTypeInfo().Assembly, typeof(DeleteCourseCommandHandler).GetTypeInfo().Assembly);

            // .NET Native DI Abstraction
            RegisterServices(services);
        }
Esempio n. 23
0
 public MongoDbSnapshotStore()
 {
     _settings = MongoDbPersistence.Get(Context.System).SnapshotStoreSettings;
 }
Esempio n. 24
0
        public MongoDbJournal()
        {
            _settings = MongoDbPersistence.Get(Context.System).JournalSettings;

            _serialization = Context.System.Serialization;
        }
Esempio n. 25
0
 static GameLoanContext()
 {
     MongoDbPersistence.Configure();
 }
Esempio n. 26
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="services"></param>
        public void Load(IServiceCollection services)
        {
            var applicationAssembly = AppDomain.CurrentDomain.Load("Basket.Application");
            var startupAssembly     = typeof(Startup).Assembly;

            services.AddMediatR(applicationAssembly, startupAssembly);

            services.AddTransient(typeof(IPipelineBehavior <,>), typeof(ValidationPipelineBehavior <,>));

            services.AddControllers(options => { options.EnableEndpointRouting = false; })
            .AddJsonOptions(opt =>
            {
                opt.JsonSerializerOptions.PropertyNamingPolicy        = JsonNamingPolicy.CamelCase;
                opt.JsonSerializerOptions.PropertyNameCaseInsensitive = true;
                opt.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter(JsonNamingPolicy.CamelCase));
            }).AddFluentValidation(opt =>
            {
                opt.RegisterValidatorsFromAssemblyContaining <Startup>();
                opt.ImplicitlyValidateChildProperties = true;
            }).AddMvcOptions(opt =>
            {
                opt.ModelMetadataDetailsProviders.Clear();
                opt.ModelValidatorProviders.Clear();
            });

            services.AddHttpContextAccessor();
            services.AddHttpClient();

            services.AddValidatorsFromAssemblies(new[] { applicationAssembly, startupAssembly });

            services.AddAutoMapper(typeof(AutoMapperProfile).GetTypeInfo().Assembly);

            services.AddScoped <IPaginationUriService>(sp =>
            {
                var httpContextAccessor = sp.GetRequiredService <IHttpContextAccessor>();
                return(new PaginationUriManager(httpContextAccessor));
            });

            services.AddSingleton <IMapperAdapter, AutoMapperAdapter>();
            services.AddScoped <ICacheService, RedisCacheManager>();
            services.AddTransient <IResponseLocalized, ResponseLocalized>();
            services.AddTransient <IProductStockProvider, ProductStockProvider>();

            services.AddScoped <IBasketCardRepository, BasketCardRepository>();

            #region DataAccess

            services.AddSingleton(typeof(MongoDbPersistence));

            const string mSc = "MongoSerializationConventions";
            var          mongoConventionPack = new ConventionPack
            {
                new EnumRepresentationConvention(BsonType.String),
                new CamelCaseElementNameConvention(),
                new NamedIdMemberConvention("Id", "id", "_id"),
                new IgnoreExtraElementsConvention(true),
                new IgnoreIfDefaultConvention(false),
                new StringObjectIdIdGeneratorConvention(), // should be before LookupIdGeneratorConvention ,
            };
            ConventionRegistry.Register(mSc, mongoConventionPack, t => true);

            MongoDbPersistence.Configure();
            services.AddScoped <IMongoDbConnector, MongoDbConnector>();

            #endregion
        }