private void RegisterConventions() => ConventionRegistry.Register("Conventions", new MongoConventions(), x => true);
/// <summary> /// Register MongoDB mappings /// </summary> /// <param name="config">Config</param> public static void RegisterMongoDBMappings(GrandConfig config) { BsonSerializer.RegisterSerializer(typeof(decimal), new DecimalSerializer(BsonType.Decimal128)); BsonSerializer.RegisterSerializer(typeof(decimal?), new NullableSerializer <decimal>(new DecimalSerializer(BsonType.Decimal128))); BsonSerializer.RegisterSerializer(typeof(DateTime), new BsonUtcDateTimeSerializer()); //global set an equivalent of [BsonIgnoreExtraElements] for every Domain Model var cp = new ConventionPack(); cp.Add(new IgnoreExtraElementsConvention(true)); ConventionRegistry.Register("ApplicationConventions", cp, t => true); BsonClassMap.RegisterClassMap <Product>(cm => { cm.AutoMap(); //ignore these Fields, an equivalent of [BsonIgnore] cm.UnmapMember(c => c.ProductType); cm.UnmapMember(c => c.IntervalUnitType); cm.UnmapMember(c => c.BackorderMode); cm.UnmapMember(c => c.DownloadActivationType); cm.UnmapMember(c => c.GiftCardType); cm.UnmapMember(c => c.LowStockActivity); cm.UnmapMember(c => c.ManageInventoryMethod); cm.UnmapMember(c => c.RecurringCyclePeriod); }); BsonClassMap.RegisterClassMap <ProductAttributeCombination>(cm => { cm.AutoMap(); cm.UnmapMember(c => c.ProductId); }); BsonClassMap.RegisterClassMap <ProductAttributeMapping>(cm => { cm.AutoMap(); cm.UnmapMember(c => c.ProductId); cm.UnmapMember(c => c.AttributeControlType); }); BsonClassMap.RegisterClassMap <ProductAttributeValue>(cm => { cm.AutoMap(); cm.UnmapMember(c => c.ProductAttributeMappingId); cm.UnmapMember(c => c.ProductId); cm.UnmapMember(c => c.AttributeValueType); }); BsonClassMap.RegisterClassMap <ProductCategory>(cm => { cm.AutoMap(); cm.UnmapMember(c => c.ProductId); }); BsonClassMap.RegisterClassMap <ProductManufacturer>(cm => { cm.AutoMap(); cm.UnmapMember(c => c.ProductId); }); BsonClassMap.RegisterClassMap <ProductPicture>(cm => { cm.AutoMap(); cm.UnmapMember(c => c.ProductId); }); BsonClassMap.RegisterClassMap <ProductSpecificationAttribute>(cm => { cm.AutoMap(); cm.UnmapMember(c => c.ProductId); cm.UnmapMember(c => c.AttributeType); }); BsonClassMap.RegisterClassMap <ProductTag>(cm => { cm.AutoMap(); cm.UnmapMember(c => c.ProductId); }); BsonClassMap.RegisterClassMap <ProductWarehouseInventory>(cm => { cm.AutoMap(); cm.UnmapMember(c => c.ProductId); }); BsonClassMap.RegisterClassMap <RelatedProduct>(cm => { cm.AutoMap(); cm.UnmapMember(c => c.ProductId1); }); BsonClassMap.RegisterClassMap <BundleProduct>(cm => { cm.AutoMap(); cm.UnmapMember(c => c.ProductBundleId); }); BsonClassMap.RegisterClassMap <TierPrice>(cm => { cm.AutoMap(); cm.UnmapMember(c => c.ProductId); }); BsonClassMap.RegisterClassMap <Address>(cm => { cm.AutoMap(); cm.UnmapMember(c => c.CustomerId); }); BsonClassMap.RegisterClassMap <Customer>(cm => { cm.AutoMap(); cm.UnmapMember(c => c.PasswordFormat); }); BsonClassMap.RegisterClassMap <ShoppingCartItem>(cm => { cm.AutoMap(); cm.UnmapMember(c => c.ShoppingCartType); }); BsonClassMap.RegisterClassMap <CustomerAction>(cm => { cm.AutoMap(); cm.UnmapMember(c => c.Condition); cm.UnmapMember(c => c.ReactionType); }); BsonClassMap.RegisterClassMap <CustomerAction.ActionCondition>(cm => { cm.AutoMap(); cm.UnmapMember(c => c.CustomerActionConditionType); cm.UnmapMember(c => c.Condition); }); BsonClassMap.RegisterClassMap <CustomerAttribute>(cm => { cm.AutoMap(); cm.UnmapMember(c => c.AttributeControlType); }); BsonClassMap.RegisterClassMap <CustomerHistoryPassword>(cm => { cm.AutoMap(); cm.UnmapMember(c => c.PasswordFormat); }); BsonClassMap.RegisterClassMap <CustomerReminder>(cm => { cm.AutoMap(); cm.UnmapMember(c => c.Condition); cm.UnmapMember(c => c.ReminderRule); }); BsonClassMap.RegisterClassMap <CustomerReminder.ReminderCondition>(cm => { cm.AutoMap(); cm.UnmapMember(c => c.ConditionType); cm.UnmapMember(c => c.Condition); }); BsonClassMap.RegisterClassMap <CustomerReminderHistory>(cm => { cm.AutoMap(); cm.UnmapMember(c => c.ReminderRule); cm.UnmapMember(c => c.HistoryStatus); }); BsonClassMap.RegisterClassMap <CustomerRole>(cm => { cm.AutoMap(); cm.UnmapMember(c => c.CustomerId); }); BsonClassMap.RegisterClassMap <Discount>(cm => { cm.AutoMap(); cm.UnmapMember(c => c.DiscountType); cm.UnmapMember(c => c.DiscountLimitation); }); BsonClassMap.RegisterClassMap <ForumTopic>(cm => { cm.AutoMap(); cm.UnmapMember(c => c.ForumTopicType); }); BsonClassMap.RegisterClassMap <Log>(cm => { cm.AutoMap(); cm.UnmapMember(c => c.LogLevel); }); BsonClassMap.RegisterClassMap <Download>(cm => { cm.AutoMap(); cm.UnmapMember(c => c.DownloadBinary); }); BsonClassMap.RegisterClassMap <Campaign>(cm => { cm.AutoMap(); cm.UnmapMember(c => c.CustomerHasOrdersCondition); cm.UnmapMember(c => c.CustomerHasShoppingCartCondition); }); BsonClassMap.RegisterClassMap <EmailAccount>(cm => { cm.AutoMap(); cm.UnmapMember(c => c.FriendlyName); }); BsonClassMap.RegisterClassMap <InteractiveForm.FormAttribute>(cm => { cm.AutoMap(); cm.UnmapMember(c => c.AttributeControlType); }); BsonClassMap.RegisterClassMap <MessageTemplate>(cm => { cm.AutoMap(); cm.UnmapMember(c => c.DelayPeriod); }); BsonClassMap.RegisterClassMap <QueuedEmail>(cm => { cm.AutoMap(); cm.UnmapMember(c => c.Priority); }); BsonClassMap.RegisterClassMap <CheckoutAttribute>(cm => { cm.AutoMap(); cm.UnmapMember(c => c.AttributeControlType); }); BsonClassMap.RegisterClassMap <GiftCard>(cm => { cm.AutoMap(); cm.UnmapMember(c => c.GiftCardType); }); BsonClassMap.RegisterClassMap <Order>(cm => { cm.AutoMap(); cm.UnmapMember(c => c.OrderStatus); cm.UnmapMember(c => c.PaymentStatus); cm.UnmapMember(c => c.ShippingStatus); cm.UnmapMember(c => c.CustomerTaxDisplayType); cm.UnmapMember(c => c.TaxRatesDictionary); }); BsonClassMap.RegisterClassMap <ShipmentItem>(cm => { cm.AutoMap(); cm.UnmapMember(c => c.ShipmentId); }); BsonClassMap.RegisterClassMap <VendorNote>(cm => { cm.AutoMap(); cm.UnmapMember(c => c.VendorId); }); BsonClassMap.RegisterClassMap <Currency>(cm => { cm.AutoMap(); cm.UnmapMember(c => c.RoundingType); }); }
public static async Task Main(string[] args) { try { const string collectionName = "TestCollection"; string connectionString = Environment.GetEnvironmentVariable("CUSTOMCONNSTR_MongoDB"); //string connectionString = "mongodb://*****:*****@localhost:27017"; ConventionRegistry.Register("Conventions", new MongoDbConventions(), _ => true); MongoClient mongoClient = new MongoClient(connectionString); IMongoDatabase database = mongoClient.GetDatabase("TestDB"); // Put a break point here and F10. // --> Drop: Collection. database.DropCollection(collectionName); IStudentRepository repository = new StudentRepository(database, collectionName); // --> Seed. await repository.InsertAsync(Student.GenerateStudents(100)); Student student = Student.GenerateStudent(); ReplaceOneResult updateOrInsertResult = await repository.UpdateOrInsertAsync(student, true); // updateOrInsertResult.UpsertedId.AsString // It has a value, in case of insert. student = await repository.GetAsync(student.Id); DeleteResult deleteResult = await repository.DeleteAsync(student.Id); bool exists = await repository.ExistsAsync(s => s.Id == student.Id); IEnumerable <Student> physicists = await repository.FindAsync(s => s.Subjects.Contains("Physics")); // ModifiedCount has to be 0. UpdateResult updateResult = await repository.AddSubjectAsync(physicists.First().Id, "Physics"); updateResult = await repository.RemoveSubjectAsync(physicists.First().Id, "Physics"); long count = await repository.CountAsync(s => s.Subjects.Contains("Physics")); // --> Paged query. PageQuery <Student> pageQuery = PageQuery <Student> .Create(page : 1, pageSize : 20) .Filter(s => s.Age >= 18 && s.Age <= 65) .Sort(sb => sb.Ascending(s => s.Age).Ascending(s => s.Name)); PageResult <Student> studentPageResult = null; do { studentPageResult = await repository.BrowseAsync(pageQuery); // if (studentPageResult.IsNotEmpty) studentPageResult.Items pageQuery.Page++; } while (studentPageResult.HasNextPage); // --> Paged query with projection. PageQuery <Student, StudentDto> pageQueryProjection = PageQuery <Student, StudentDto> .Create(page : 1, pageSize : 20) .Filter(s => s.Age >= 18 && s.Age <= 65) .Sort(sb => sb.Descending("$natural")) // https://docs.mongodb.com/manual/reference/glossary/#term-natural-order .Project(s => new StudentDto { Id = s.Id, Name = s.Name, SubjectCount = s.Subjects.Count() }); PageResult <StudentDto> studentDtoPageResult = null; do { studentDtoPageResult = await repository.BrowseAsync(pageQueryProjection); pageQueryProjection.Page++; } while (studentDtoPageResult.HasNextPage); deleteResult = await repository.DeleteAsync(s => s.Age < 5); } catch (Exception ex) { // MongoException // Do something... Console.WriteLine(ex.Message); } }
public IServiceProvider ConfigureServices(IServiceCollection services) { services.AddOptions(); services.AddHealthChecks(); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Latest).AddControllersAsServices() .AddJsonOptions( options => { options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; options.SerializerSettings.Formatting = Formatting.Indented; options.SerializerSettings.ContractResolver = new DefaultContractResolver(); options.SerializerSettings.NullValueHandling = NullValueHandling.Include; }) .AddMvcOptions(options => options.Filters.Add <ModelValidationAttribute>()); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new Info { Title = ApplicationConfiguration.Api.Name, Version = ApplicationConfiguration.Api.Version }); c.AddSecurityDefinition("Bearer", new ApiKeyScheme { Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"", Name = "Authorization", In = "header", Type = "apiKey" }); c.AddSecurityRequirement(new Dictionary <string, IEnumerable <string> > { { "Bearer", Enumerable.Empty <string>() } }); }); services.AddHeaderPropagation(options => { options.HeaderNames.Add("Authorization"); options.HeaderNames.Add("x-request-id"); options.HeaderNames.Add("x-b3-traceid"); options.HeaderNames.Add("x-b3-spanid"); options.HeaderNames.Add("x-b3-parentspanid"); options.HeaderNames.Add("x-b3-sampled"); options.HeaderNames.Add("x-b3-flags"); options.HeaderNames.Add("x-ot-span-context"); }); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Latest).AddControllersAsServices() .AddJsonOptions(options => { options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore; options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; options.SerializerSettings.PreserveReferencesHandling = PreserveReferencesHandling.None; options.SerializerSettings.Formatting = Formatting.Indented; options.SerializerSettings.ContractResolver = new DefaultContractResolver(); }); ConventionRegistry.Remove("__defaults__"); var conventionPack = new ConventionPack { new StringObjectIdIdGeneratorConvention(), new CamelCaseElementNameConvention() }; BsonSerializer.RegisterSerializer(new GuidSerializer().WithRepresentation(BsonType.String)); services.Configure <HttpHandlerDiagnosticOptions>(options => { options.IgnorePatterns.Add(x => !x.RequestUri.IsLoopback); }); services.AddLogging(); services.AddHttpClient(); services.Configure <HttpHandlerDiagnosticOptions>(options => { options.IgnorePatterns.Add(x => !x.RequestUri.IsLoopback); }); var containerBuilder = new ContainerBuilder(); containerBuilder.RegisterServices(); containerBuilder.RegisterRepositories(); containerBuilder.Populate(services); var container = containerBuilder.Build(); return(new AutofacServiceProvider(container)); }
// 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 = SameSiteMode.None; }); services.Configure <AppSettings>(Configuration.GetSection("AppSettings")); services.Configure <MongoDbSettings>(Configuration.GetSection("MongoDb")); // services.Configure<Auth0Settings>(Configuration.GetSection("Auth0")); // var auth0Settings = Configuration.GetSection("Auth0"); // Add authentication services services.AddAuthentication(options => { options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme; options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme; options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme; }) .AddCookie() .AddOpenIdConnect("Auth0", options => { // Set the authority to your Auth0 domain options.Authority = $"https://{Configuration["Auth0:Domain"]}"; // Configure the Auth0 Client ID and Client Secret options.ClientId = Configuration["Auth0:ClientId"]; options.ClientSecret = Configuration["Auth0:ClientSecret"]; // Set response type to code options.ResponseType = "code"; // Configure the scope options.Scope.Clear(); options.Scope.Add("openid email profile"); options.TokenValidationParameters = new TokenValidationParameters { NameClaimType = "name", }; // Set the callback path, so Auth0 will call back to http://localhost:3000/signin-auth0 // Also ensure that you have added the URL as an Allowed Callback URL in your Auth0 dashboard options.CallbackPath = new PathString("/signin-auth0"); // Configure the Claims Issuer to be Auth0 options.ClaimsIssuer = "Auth0"; // Saves tokens to the AuthenticationProperties options.SaveTokens = true; options.Events = new OpenIdConnectEvents { // handle the logout redirection OnRedirectToIdentityProviderForSignOut = (context) => { var logoutUri = $"https://{Configuration["Auth0:Domain"]}/v2/logout?client_id={Configuration["Auth0:ClientId"]}"; var postLogoutUri = context.Properties.RedirectUri; if (!string.IsNullOrEmpty(postLogoutUri)) { if (postLogoutUri.StartsWith("/")) { // transform to absolute var request = context.Request; postLogoutUri = request.Scheme + "://" + request.Host + request.PathBase + postLogoutUri; } logoutUri += $"&returnTo={Uri.EscapeDataString(postLogoutUri)}"; } context.Response.Redirect(logoutUri); context.HandleResponse(); return(Task.CompletedTask); } }; }); services.AddMvc() .SetCompatibilityVersion(CompatibilityVersion.Version_2_1); // services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) // .AddCookie(options => // { // options.AccessDeniedPath = "/Common/AccessDenied"; // options.LoginPath = "/account/login"; // }); services.AddAuthorization(options => { options.AddPolicy("GraphQL", policy => policy.Requirements.Add(new NoOpRequirement())); }); services.AddSingleton <IDependencyResolver>(s => new FuncDependencyResolver(s.GetRequiredService)); services.AddSingleton <AccrualFrequencyEnum>(); services.AddSingleton <EndingEnum>(); services.AddSingleton <AccrualActionEnum>(); services.AddSingleton <AccrualGraphType>(); services.AddSingleton <AirportGraphType>(); services.AddSingleton <HealthCheckGraphType>(); services.AddSingleton <RoleGraphType>(); services.AddSingleton <UserGraphType>(); services.AddSingleton <AccrualActionRecordInputType>(); services.AddSingleton <AccrualActionRecordGraphType>(); services.AddSingleton <AccrualRowGraphType>(); services.AddSingleton <AccrualInputType>(); services.AddSingleton <AirportInputType>(); services.AddSingleton <ISchema, AppSchema>(); services.AddSingleton <AccrualService>(); services.AddSingleton <AppQuery>(); services.AddSingleton <AppMutation>(); services.AddSingleton <IAirportRepository, AirportRepository>(); services.AddSingleton <IDashboardRepository, MongoDashboardRepository>(); services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>(); services.AddSingleton <IAuthorizationHandler, NoOpHandler>(); services.AddSingleton <IUserRepository, MongoUserRepository>(); services.AddScoped <IRoleRepository, MongoRoleRepository>(); services.AddGraphQL(_ => { _.EnableMetrics = true; _.ExposeExceptions = true; }); //.AddUserContextBuilder(httpContext => new GraphQLUserContext { User = httpContext.User }); // services.AddSingleton<IUserStore<MongoIdentityUser>>(provider => // { // var database = provider.GetService<IMongoDatabase>(); // return new MongoUserStore<MongoIdentityUser>(database); // }); // Console.WriteLine("printing config vars"); // foreach(var kvp in Configuration.GetChildren()) // { // Console.WriteLine($"{kvp.Key}|{kvp.Value}"); // } services.AddSingleton <IMongoDatabase>(provider => { var pack = new ConventionPack { new CamelCaseElementNameConvention() }; ConventionRegistry.Register("camelcase", pack, t => true); var options = provider.GetService <IOptions <MongoDbSettings> >(); var client = new MongoClient(options.Value.ConnectionString); var database = client.GetDatabase(options.Value.DatabaseName); return(database); }); // services.AddScoped<MongoRoleRepository>(provider => // { // var database = provider.GetService<IMongoDatabase>(); // var repository = new MongoRoleRepository(database); // // return repository; // }); services.AddSingleton <IRoleRepository, MongoRoleRepository>(); services.AddSingleton <IMigrationRepository, MongoMigrationRepository>(); services.AddSingleton <IMigrationDiscoverService, DefaultMigrationDiscoverService>(); services.AddSingleton <IDotNetProvider, DefaultDotNetProvider>(); services.AddSingleton <IMigrationService, MongoMigrationService>(); }
public MongoHelper(DatabaseConnection connection) { #region Init ConventionRegistry.Register(typeof(IgnoreExtraElementsConvention).Name, new ConventionPack { new IgnoreExtraElementsConvention(true) }, t => true); ConventionRegistry.Register("EnumStringConvention", new ConventionPack { new EnumRepresentationConvention(BsonType.String) }, t => true); if (!BsonClassMap.IsClassMapRegistered(typeof(GifSection))) { BsonClassMap.RegisterClassMap <GifSection>(); } if (!BsonClassMap.IsClassMapRegistered(typeof(TextSection))) { BsonClassMap.RegisterClassMap <TextSection>(); } if (!BsonClassMap.IsClassMapRegistered(typeof(ImageSection))) { BsonClassMap.RegisterClassMap <ImageSection>(); } if (!BsonClassMap.IsClassMapRegistered(typeof(AudioSection))) { BsonClassMap.RegisterClassMap <AudioSection>(); } if (!BsonClassMap.IsClassMapRegistered(typeof(VideoSection))) { BsonClassMap.RegisterClassMap <VideoSection>(); } if (!BsonClassMap.IsClassMapRegistered(typeof(EmbeddedHtmlSection))) { BsonClassMap.RegisterClassMap <EmbeddedHtmlSection>(); } if (!BsonClassMap.IsClassMapRegistered(typeof(CarouselSection))) { BsonClassMap.RegisterClassMap <CarouselSection>(); } if (!BsonClassMap.IsClassMapRegistered(typeof(NodeContent))) { BsonClassMap.RegisterClassMap <NodeContent>(); } if (!BsonClassMap.IsClassMapRegistered(typeof(SectionContent))) { BsonClassMap.RegisterClassMap <SectionContent>(); } if (!BsonClassMap.IsClassMapRegistered(typeof(TextSectionContent))) { BsonClassMap.RegisterClassMap <TextSectionContent>(); } if (!BsonClassMap.IsClassMapRegistered(typeof(TitleCaptionSectionContent))) { BsonClassMap.RegisterClassMap <TitleCaptionSectionContent>(); } if (!BsonClassMap.IsClassMapRegistered(typeof(ImageSectionContent))) { BsonClassMap.RegisterClassMap <ImageSectionContent>(); } if (!BsonClassMap.IsClassMapRegistered(typeof(GraphSectionContent))) { BsonClassMap.RegisterClassMap <GraphSectionContent>(); } if (!BsonClassMap.IsClassMapRegistered(typeof(ButtonContent))) { BsonClassMap.RegisterClassMap <ButtonContent>(); } if (!BsonClassMap.IsClassMapRegistered(typeof(PrintOTPSection))) { BsonClassMap.RegisterClassMap <PrintOTPSection>(); } if (!BsonClassMap.IsClassMapRegistered(typeof(CarouselButtonContent))) { BsonClassMap.RegisterClassMap <CarouselButtonContent>(); } if (!BsonClassMap.IsClassMapRegistered(typeof(CarouselItemContent))) { BsonClassMap.RegisterClassMap <CarouselItemContent>(); } #endregion _connection = connection; }
// this method gets called by the runtime. use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddCors(); services.AddMemoryCache(); services .AddRouting(options => { options.LowercaseUrls = true; }) .AddControllersWithViews(options => { var authorizationPolicy = new AuthorizationPolicyBuilder(new[] { JwtBearerDefaults.AuthenticationScheme }) .RequireAuthenticatedUser() .Build(); options.Filters.Add(new AuthorizeFilter(authorizationPolicy)); options.Filters.Add(new CustomModelStateFilter()); }) .AddFluentValidation(options => { ValidatorOptions.CascadeMode = CascadeMode.StopOnFirstFailure; options.RegisterValidatorsFromAssemblyContaining <Startup>(); }) .AddNewtonsoftJson(options => { options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); }); #region MONGODB CONFIGURATION var conventionPack = new ConventionPack { new CamelCaseElementNameConvention() }; ConventionRegistry.Register("CamelCase", conventionPack, t => true); #endregion #region SERVICES services.AddScoped <EmailService>(); services.AddScoped <MongoDbService>(); #endregion #region IDENTITY services .AddIdentityMongoDbProvider <ApplicationUser, ApplicationRole>(options => { options.User.RequireUniqueEmail = false; options.User.AllowedUserNameCharacters = null; options.Password.RequireDigit = false; options.Password.RequiredLength = 8; options.Password.RequireNonAlphanumeric = false; options.Password.RequireLowercase = true; options.Password.RequireUppercase = false; options.Lockout.AllowedForNewUsers = true; options.Lockout.MaxFailedAccessAttempts = 5; }, mongoIdentityOptions => { mongoIdentityOptions.ConnectionString = _configuration.GetConnectionString("DefaultConnection"); mongoIdentityOptions.MigrationCollection = Collections.Migrations; mongoIdentityOptions.UsersCollection = Collections.Users; mongoIdentityOptions.RolesCollection = Collections.Roles; }) .AddDefaultTokenProviders(); #endregion #region AUTHENTICATION services .AddAuthentication(options => { options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }) .AddJwtBearer(options => { var secret = _configuration.GetSection("JwtSettings:Secret").Value; options.TokenValidationParameters = new TokenValidationParameters() { ValidAudience = _configuration.GetSection("JwtSettings:ValidAudience").Value, ValidateAudience = _configuration.GetSection("JwtSettings:ValidateAudience").Get <bool>(), ValidIssuer = _configuration.GetSection("JwtSettings:ValidIssuer").Value, ValidateIssuer = _configuration.GetSection("JwtSettings:ValidateIssuer").Get <bool>(), ValidateIssuerSigningKey = true, ValidateLifetime = true, ClockSkew = TimeSpan.Zero, IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(secret)) }; options.Events = new JwtBearerEvents { OnAuthenticationFailed = context => { if (context.Exception.GetType() == typeof(SecurityTokenExpiredException)) { context.Response.Headers.Add("Token-Expired", bool.TrueString); } return(Task.CompletedTask); } }; }); #endregion #region SWAGGER CONFIGURATION services.AddSwaggerGen(options => { options.SwaggerDoc("v1", new OpenApiInfo { Title = "API", Version = "v1" }); options.AddSecurityDefinition("JwtAuth", new OpenApiSecurityScheme() { Name = "Bearer", BearerFormat = "JWT", Scheme = "bearer", Description = "Specify the authorization token.", In = ParameterLocation.Header, Type = SecuritySchemeType.Http, }); options.AddSecurityRequirement(new OpenApiSecurityRequirement() { { new OpenApiSecurityScheme() { Reference = new OpenApiReference() { Id = "JwtAuth", Type = ReferenceType.SecurityScheme } }, new string[] { } } }); }); #endregion // in production, the vue files will be served from this directory services.AddSpaStaticFiles(configuration => { configuration.RootPath = "ClientApp/dist"; }); }
private static void RegiserConvensions() { ConventionRegistry.Register("ToDoAPIConvensions", new MongoConvensions(), x => true); }
private void RegisterConventions() { ConventionRegistry.Register("NetCoreMicroConventions", new MongoConvention(), x => true); }
private static void RegisterConventions() { ConventionRegistry.Register("MyMindConventions", new MongoConventions(), x => true); }
private void Application_Startup(object sender, StartupEventArgs e) { #region Initialize Mongo Parser Maps ConventionRegistry.Register(typeof(IgnoreExtraElementsConvention).Name, new ConventionPack { new IgnoreExtraElementsConvention(true) }, t => true); ConventionRegistry.Register("EnumStringConvention", new ConventionPack { new EnumRepresentationConvention(BsonType.String) }, t => true); if (!BsonClassMap.IsClassMapRegistered(typeof(GifSection))) { BsonClassMap.RegisterClassMap <GifSection>(); } if (!BsonClassMap.IsClassMapRegistered(typeof(TextSection))) { BsonClassMap.RegisterClassMap <TextSection>(); } if (!BsonClassMap.IsClassMapRegistered(typeof(ImageSection))) { BsonClassMap.RegisterClassMap <ImageSection>(); } if (!BsonClassMap.IsClassMapRegistered(typeof(AudioSection))) { BsonClassMap.RegisterClassMap <AudioSection>(); } if (!BsonClassMap.IsClassMapRegistered(typeof(VideoSection))) { BsonClassMap.RegisterClassMap <VideoSection>(); } if (!BsonClassMap.IsClassMapRegistered(typeof(EmbeddedHtmlSection))) { BsonClassMap.RegisterClassMap <EmbeddedHtmlSection>(); } if (!BsonClassMap.IsClassMapRegistered(typeof(CarouselSection))) { BsonClassMap.RegisterClassMap <CarouselSection>(); } if (!BsonClassMap.IsClassMapRegistered(typeof(NodeContent))) { BsonClassMap.RegisterClassMap <NodeContent>(); } if (!BsonClassMap.IsClassMapRegistered(typeof(SectionContent))) { BsonClassMap.RegisterClassMap <SectionContent>(); } if (!BsonClassMap.IsClassMapRegistered(typeof(TextSectionContent))) { BsonClassMap.RegisterClassMap <TextSectionContent>(); } if (!BsonClassMap.IsClassMapRegistered(typeof(TitleCaptionSectionContent))) { BsonClassMap.RegisterClassMap <TitleCaptionSectionContent>(); } if (!BsonClassMap.IsClassMapRegistered(typeof(GraphSectionContent))) { BsonClassMap.RegisterClassMap <GraphSectionContent>(); } if (!BsonClassMap.IsClassMapRegistered(typeof(ButtonContent))) { BsonClassMap.RegisterClassMap <ButtonContent>(); } if (!BsonClassMap.IsClassMapRegistered(typeof(PrintOTPSection))) { BsonClassMap.RegisterClassMap <PrintOTPSection>(); } if (!BsonClassMap.IsClassMapRegistered(typeof(CarouselButtonContent))) { BsonClassMap.RegisterClassMap <CarouselButtonContent>(); } if (!BsonClassMap.IsClassMapRegistered(typeof(CarouselItemContent))) { BsonClassMap.RegisterClassMap <CarouselItemContent>(); } #endregion #region This applies the default font FrameworkElement.StyleProperty.OverrideMetadata(typeof(Window), new FrameworkPropertyMetadata { DefaultValue = FindResource(typeof(Window)) }); #endregion }
public static void CRUD() { var exp = ExpressionMapper.MapExp <StudentVm, Student>(); #region 连接Mongodb var client = new MongoClient("mongodb://localhost:27017"); var database = client.GetDatabase("school"); #endregion #region 约束 驼峰命名法 var pack = new ConventionPack(); pack.Add(new CamelCaseElementNameConvention()); ConventionRegistry.Register("CamelCaseElementNameConvention", pack, t => true); #endregion #region 1.插入数据 var collection = database.GetCollection <Student>("student"); if (collection.CountDocuments(a => true) == 0) { collection.InsertOne(new Student() { Age = 27, Name = "zhangsan", Address = "河南", Birthday = DateTime.Parse("1992-06-17 12:35:12"), Hobbies = new[] { "阅读", "跑步", }, Courses = new List <Course>() { new Course() { Name = "计算机理论", Count = 30 }, new Course() { Name = "操作系统", Count = 35 } } }); collection.InsertOne(new Student() { Age = 23, Name = "lisi", Address = "北京", Birthday = DateTime.Parse("1996-05-17 14:40:08"), Hobbies = new[] { "游戏", "睡觉", "代码" }, Courses = new List <Course>() { new Course() { Name = "c#语言基础", Count = 30 }, new Course() { Name = "编译原理", Count = 35 } } }); var bulkList = new List <Student>() { new Student() { Age = 26, Name = "wangwu", Address = "河北", Birthday = DateTime.Parse("1993-08-17 16:40:08"), Hobbies = new[] { "睡觉" }, Courses = new List <Course>() { new Course() { Name = "网络编程", Count = 30 }, new Course() { Name = "操作系统", Count = 35 } } }, new Student() { Age = 29, Name = "wangwu", Address = "南京", Birthday = DateTime.Parse("1990-05-17 14:40:08"), Hobbies = new[] { "游戏", "睡觉", "代码", "逛街" }, Courses = new List <Course>() { new Course() { Name = "网络编程", Count = 30 }, new Course() { Name = "操作系统", Count = 35 } } } }; collection.InsertMany(bulkList); } #endregion Console.WriteLine(); #region 2.过滤器(Filter) Console.WriteLine("==============过滤=============="); //空过滤器匹配全部 FilterDefinition <BsonDocument> filter0 = Builders <BsonDocument> .Filter.Empty; //一般匹配 FilterDefinition <BsonDocument> filter1 = "{name:'zhangsan'}"; FilterDefinition <BsonDocument> filter2 = new BsonDocument("name", "zhangsan"); var builder3 = Builders <BsonDocument> .Filter; var filter3 = builder3.Eq("name", "zhangsan") & builder3.Gt("age", 10); var builder4 = Builders <Student> .Filter; var filter4 = (builder4.Eq("name", "zhangsan") & builder4.Gt(a => a.Age, 10)) | builder4.Gt(a => a.Birthday, DateTime.Parse("1990-01-01")); var query21 = database.GetCollection <BsonDocument>("student").Find(filter1); var json21 = query21.ToString(); var student21 = query21.FirstOrDefault(); Console.WriteLine(json21); var query22 = database.GetCollection <BsonDocument>("student").Find(filter2); var json22 = query22.ToString(); var student22 = query22.FirstOrDefault(); Console.WriteLine(json22); var query23 = database.GetCollection <BsonDocument>("student").Find(filter3); var json23 = query23.ToString(); var student23 = query23.FirstOrDefault(); Console.WriteLine(json23); var query24 = database.GetCollection <Student>("student").Find(filter4); var json24 = query24.ToString(); var student24 = query24.FirstOrDefault(); Console.WriteLine(json24); //数组匹配 var builder5 = Builders <BsonDocument> .Filter; var filter25 = builder5.AnyEq("courses.name", "操作系统"); var query25 = database.GetCollection <BsonDocument>("student").Find(filter25); var json25 = query25.ToString(); var student25 = database.GetCollection <BsonDocument>("student").Find(filter25).ToList(); Console.WriteLine(json25); var builder6 = Builders <Student> .Filter; var filter26 = builder6.ElemMatch(a => a.Courses, a => a.Name == "操作系统"); var query26 = database.GetCollection <Student>("student").Find(filter26); var json26 = query26.ToString(); var student26 = database.GetCollection <Student>("student").Find(filter26).ToList(); Console.WriteLine(json26); var builder7 = Builders <Student> .Filter; var filter27 = builder7.ElemMatch(a => a.Courses, a => a.Name == "操作系统") & builder7.ElemMatch(a => a.Courses, a => a.Count > 30); var query27 = database.GetCollection <Student>("student").Find(filter27); var json27 = query27.ToString(); var student27 = database.GetCollection <Student>("student").Find(filter27).ToList(); Console.WriteLine(json27); var builder8 = Builders <Student> .Filter; var filter28 = builder8.ElemMatch(a => a.Courses, a => a.Name == "操作系统") | builder8.ElemMatch(a => a.Courses, a => a.Count > 30); var query28 = database.GetCollection <Student>("student").Find(filter28); var json28 = query28.ToString(); var student28 = database.GetCollection <Student>("student").Find(filter28).ToList(); Console.WriteLine(json28); var builder9 = Builders <Student> .Filter; var filter29 = builder9.SizeGte(a => a.Hobbies, 4); var query29 = database.GetCollection <Student>("student").Find(filter29); var json29 = query29.ToString(); var student29 = database.GetCollection <Student>("student").Find(filter29).ToList(); Console.WriteLine(json29); var builder10 = Builders <Student> .Filter; var filter210 = builder10.In(a => a.Name, new[] { "zhangsan", "wangwu" }); var query210 = database.GetCollection <Student>("student").Find(filter210); var json210 = query210.ToString(); var student210 = database.GetCollection <Student>("student").Find(filter210).ToList(); Console.WriteLine(json210); var builder11 = Builders <Student> .Filter; var filter211 = builder11.AnyEq(a => a.Hobbies, "睡觉"); var query211 = database.GetCollection <Student>("student").Find(filter211); var json211 = query211.ToString(); var student211 = database.GetCollection <Student>("student").Find(filter211).ToList(); Console.WriteLine(json211); var builder12 = Builders <Student> .Filter; var filter212 = builder12.Regex(a => a.Name, "ng"); var query212 = database.GetCollection <Student>("student").Find(filter212); var json212 = query212.ToString(); var student212 = database.GetCollection <Student>("student").Find(filter212).ToList(); Console.WriteLine(json212); var indexes = database.GetCollection <Student>("student").Indexes; var indexKey = Builders <Student> .IndexKeys.Text(a => a.Name); var model = new CreateIndexModel <Student>(indexKey); indexes.CreateOne(model); var list = indexes.List().ToList(); var builder13 = Builders <Student> .Filter; var filter213 = builder13.Text("zhangsan"); var query213 = database.GetCollection <Student>("student").Find(filter213); var json213 = query213.ToString(); var student213 = database.GetCollection <Student>("student").Find(filter213).ToList(); Console.WriteLine(json213); Console.WriteLine("==============过滤=============="); #endregion Console.WriteLine(); #region 3.投影(Projections) Console.WriteLine("==============投影=============="); ProjectionDefinition <BsonDocument> projection1 = "{age:1}"; ProjectionDefinition <BsonDocument> projection2 = new BsonDocument("age", 1); var json31 = projection1.RenderToBsonDocument(); var students31 = database.GetCollection <BsonDocument>("student").Find(a => true).Project(projection1).ToList(); Console.WriteLine(json31); var projection3 = Builders <Student> .Projection.Include(a => a.Age).Include(a => a.Name); var projection4 = Builders <Student> .Projection.Exclude(a => a.Id).Exclude(a => a.Courses); var projection5 = Builders <Student> .Projection.Exclude(a => a.Id); var query33 = database.GetCollection <Student>("student").Find(a => true).Project <Student>(projection3); var json33 = query33.ToString(); var students33 = query33.ToList(); Console.WriteLine(json33); var query34 = database.GetCollection <Student>("student").Find(a => true).Project <Student>(projection4); var json34 = query34.ToString(); var students34 = query34.ToList(); Console.WriteLine(json34); var query35 = database.GetCollection <Student>("student").Find(a => true).Project <Student>(projection5); var json35 = query35.ToString(); var students35 = query35.ToList(); Console.WriteLine(json35); var projection6 = Builders <Student> .Projection.Expression(a => new StudentVm() { Age = a.Age, Id = a.Id, Name = a.Name }); var query36 = database.GetCollection <Student>("student").Find(a => true).Project(projection6); var json36 = query36.ToString(); var students36 = query36.ToList(); Console.WriteLine(json36); var students37 = database.GetCollection <Student>("student").Find(a => true).Project(a => new StudentVm { Age = a.Age, Id = a.Id, Name = a.Name }).ToList(); var query38 = database.GetCollection <Student>("student").Find(a => true).Project(a => new { a.Age, a.Id, a.Name }); var json38 = query38.ToString(); var students38 = query38.ToList(); Console.WriteLine(json38); var query39 = database.GetCollection <Student>("student").Find(a => true).Project(a => new { AgeAndName = a.Name + "," + a.Age.ToString() }); var json39 = query39.ToString(); var students39 = query39.ToList(); Console.WriteLine(json39); //自动投影 根据StudentVm中的属性自动生成 var query310 = database.GetCollection <Student>("student").Find(a => true).Project(ExpressionMapper.MapExp <Student, StudentVm>()); var json310 = query310.ToString(); var listss = query310.ToList(); Console.WriteLine($"自动投影:{json310}"); Console.WriteLine("==============投影=============="); #endregion Console.WriteLine(); #region 4.排序(Sort) Console.WriteLine("==============排序=============="); SortDefinition <BsonDocument> sort1 = "{ age: 1 }"; SortDefinition <BsonDocument> sort2 = Builders <BsonDocument> .Sort.Ascending("_id").Descending("age"); SortDefinition <Student> sort3 = Builders <Student> .Sort.Ascending(a => a.Id).Descending(a => a.Age); var query41 = database.GetCollection <Student>("student").Find(new BsonDocument()).Sort(sort3); var json41 = query41.ToString(); var student41 = query41.ToList(); Console.WriteLine(json41); Console.WriteLine("==============排序=============="); #endregion Console.WriteLine(); #region 5.更新(Update) Console.WriteLine("==============更新=============="); UpdateDefinition <BsonDocument> update1 = "{ $set: { age: 25 } }"; UpdateDefinition <BsonDocument> update2 = new BsonDocument("$set", new BsonDocument("age", 1)); //数组更新添加 var updateBuilder = Builders <Student> .Update; UpdateDefinition <Student> update3 = updateBuilder .Set(a => a.Name, "修改名称") .Set(a => a.Age, 25) .Push(a => a.Hobbies, "购物") .PushEach(a => a.Courses, new List <Course>() { new Course() { Name = "马克思主义理论基础", Count = 10, }, new Course() { Name = "毛泽东思想概论", Count = 10, } }) .CurrentDate(a => a.Birthday, UpdateDefinitionCurrentDateType.Date); var json53 = update3.RenderToBsonDocument(); var student53 = collection.UpdateOne(a => a.Name == "zhangsan", update3); Console.WriteLine(json53); //数组更新移除 UpdateDefinition <Student> update4 = updateBuilder .Set(a => a.Name, "zhangsan") .Inc(a => a.Age, 100) .Pull(a => a.Hobbies, "购物") .PullFilter(a => a.Courses, a => a.Name == "毛泽东思想概论"); var json54 = update4.RenderToBsonDocument(); var student54 = collection.UpdateOne(a => a.Name == "修改名称", update4); Console.WriteLine(json54); //匹配数组中得某个元素,并更新这个元素的相关字段 UpdateDefinition <Student> update5 = updateBuilder .Set(a => a.Courses[-1].Name, "ssss"); var json55 = update5.RenderToBsonDocument(); var student55 = collection.UpdateOne(a => a.Courses.Any(b => b.Name == "马克思主义理论基础"), update5); Console.WriteLine(json55); UpdateDefinition <Student> update6 = updateBuilder .Mul(a => a.Age, 12); var op = new FindOneAndUpdateOptions <Student>() { IsUpsert = true, ReturnDocument = ReturnDocument.After }; var student56 = collection.FindOneAndUpdate <Student>(a => a.Age > 26, update6, op); var update7 = updateBuilder .PopFirst(a => a.Hobbies) .PopLast(a => a.Courses); var json57 = update7.RenderToBsonDocument(); var student57 = collection.UpdateOne(a => a.Name == "zhangsan", update7); Console.WriteLine(json57); var update8 = updateBuilder .SetOnInsert(a => a.Name, "ssss"); var json58 = update8.RenderToBsonDocument(); var student58 = collection.UpdateOne(a => a.Name == "ls", update8, new UpdateOptions() { IsUpsert = true }); Console.WriteLine(json58); var update9 = updateBuilder .Rename(a => a.Address, "homeAddress"); var json59 = update9.RenderToBsonDocument(); var student59 = collection.UpdateOne(a => a.Name == "wangwu", update9); Console.WriteLine(json59); var update10 = updateBuilder .Set(a => a.Name, "**"); var json510 = update10.RenderToBsonDocument(); var student510 = collection.UpdateMany(a => a.Age > 20, update10); Console.WriteLine(json510); //根据条件动态更新 var update11 = updateBuilder .Set(a => a.Name, "**"); if (true) { update11 = update11.Set(a => a.Age, 12); } var json511 = update11.RenderToBsonDocument(); Console.WriteLine(json511); Console.WriteLine("==============更新=============="); #endregion Console.WriteLine(); #region 6.聚合(Aggregation) Console.WriteLine("==============聚合=============="); var pipeline1 = new BsonDocument[] { new BsonDocument { { "$sort", new BsonDocument("_id", 1) } }, new BsonDocument { { "$group", new BsonDocument { { "_id", "$age" }, { "min", new BsonDocument { { "$min", "$age" } } } } } } }; var student61 = collection.Aggregate <BsonDocument>(pipeline1).ToListAsync(); var agg = collection.Aggregate(); var gg = agg .Match(a => a.Age > 10) .Project(a => new { a.Age, a.Name }) .Group(key => key.Age, g => new { age = g.Key, count = g.Count(), max = g.Max(a => a.Age), min = g.Min(a => a.Age), avg = g.Average(a => a.Age) }); var json62 = gg.ToString(); var student62 = gg.ToList(); Console.WriteLine(json62); Console.WriteLine("==============聚合=============="); #endregion Console.WriteLine(); #region 7.删除数据 var student71 = collection.DeleteOne(a => a.Age > 100); var student72 = collection.DeleteMany(a => a.Age > 100); var op7 = new FindOneAndDeleteOptions <Student>() { }; var student73 = collection.FindOneAndDelete <Student>(a => a.Age > 100, op7); #endregion Console.WriteLine(); #region 8.快速使用 Console.WriteLine("==============快速使用=============="); var student80 = collection.Find(a => true).FirstOrDefault(); var students81 = collection.Find(a => true).ToList(); var students82 = collection.Find(a => true).Skip(80).Limit(20).ToList(); var long83 = collection.Find(a => true).CountDocuments(); var bool84 = collection.Find(a => true).Any(); var students85 = collection.Find(a => true).SortBy(a => a.Id).SortByDescending(a => a.Age).ToList(); var queryable = collection.AsQueryable(); var queryable86 = queryable.Where(a => a.Age > 20).Select(a => new { a.Age, a.Name }) .GroupBy(a => a.Age) .Select(g => new { g.Key, Max = g.Max(a => a.Age), Min = g.Min(a => a.Age), Avg = g.Average(a => a.Age), Name = g.First().Name, Count = g.Count(), }); var json86 = queryable86.ToString(); Console.WriteLine(json86); Console.WriteLine("==============快速使用=============="); #endregion #region 9.执行命令 //批量更新不同的值 var dic = new Dictionary <string, object>() { { "update", "students" }, { "updates", new List <BsonDocument>() } }; //循环生成不同的更新命令 for (int i = 0; i < 10; i++) { ((List <BsonDocument>)dic["updates"]).Add(new BsonDocument() { { "q", new BsonDocument("age", i * 5) }, { "u", new BsonDocument("$set", new BsonDocument() { { "age", i + 2 }, { "name", i + "-" } } ) }, }); } var result = database.RunCommand <BsonDocument>(new BsonDocument(dic)); #endregion //批量操作 #region 10.批量操作 var write = new UpdateOneModel <Student>(filter211, update10); collection.BulkWrite(new List <UpdateOneModel <Student> >() { write }); #endregion #region 11.DbContext封装 var students = SchoolDbContext.Students.Find(a => true); using (var session = SchoolDbContext.MongoClient.StartSession()) { session.StartTransaction(); SchoolDbContext.Students.Find(session, a => true); session.CommitTransaction(); } #endregion #region 12.测试 WriteConcern writeConcern = new WriteConcern(); var update12 = Builders <Student> .Update.Set(a => a.Age, 25); var result12 = database.GetCollection <Student>("student22").UpdateOne(a => a.Name == "ss", update12); #endregion #region 13.聚合2 var p1 = PipelineStageDefinitionBuilder.Match <Student>(a => a.Name == "**"); var student101 = collection.Aggregate().AppendStage(p1).ToList(); #endregion #region 13.连接 //参看:https://stackoverflow.com/questions/50530363/aggregate-lookup-with-c-sharp Console.WriteLine("==============连接查询=============="); var studentQuery = database.GetCollection <Student>("student").AsQueryable(); var classroomQuery = database.GetCollection <ClassRoom>("classroom").AsQueryable(); //使用集合的方式来解决左连接 var student102 = from s in studentQuery.Where(a => a.Name == "**") join c in classroomQuery on s.classroomid equals c.Id into joined select new { s.Name, s.Age, classname = joined }; var query102 = student102.ToString(); Console.WriteLine(query102); var result102 = student102.ToList(); //database.GetCollection<Student>("student").Aggregate() // .Lookup().ToList(); #endregion #region 14 动态生成根据id查找 var result141 = collection.FindById("5d8894a114294d2acc82ecd6").Result; #endregion }
static void Main(string[] args) { try { string dbName = "test"; string collectionName = "users"; // Adding convention ConventionPack conventionPack = new ConventionPack { new CamelCaseElementNameConvention() }; ConventionRegistry.Register("camelCase", conventionPack, t => true); TestRepository repository = new TestRepository(); // Get databases names Console.WriteLine("Databases:"); foreach (string s in repository.GetDatabaseNames().Result) { Console.WriteLine(s); } Console.WriteLine(); // Get collections names Console.WriteLine("Collections in database {0}:", dbName); foreach (string s in repository.GetCollectionsNames(dbName).Result) { Console.WriteLine(s); } Console.WriteLine(); // Objects mapping BsonClassMap.RegisterClassMap <Person>(cm => { cm.AutoMap(); }); // Adding documents Person p = new Person { Name = "Andrew", Surname = "Li", Age = 52, Company = new Company { Name = "Google" } }; repository.AddDocument(dbName, collectionName, p); // Find docs Console.WriteLine("Find docs in {0}:", dbName); foreach (string s in repository.FindDocs <BsonDocument>(dbName, collectionName).Result) { Console.WriteLine(s); } Console.WriteLine(); } catch (Exception e) { Console.WriteLine(e); } Console.ReadKey(); }
/// <summary> /// Configure middlewares. /// </summary> /// <param name="services">The services.</param> protected override void CustomConfigureServices(IServiceCollection services) { ConventionRegistry .Register( "Ignore extra elements", new ConventionPack { new IgnoreExtraElementsConvention(true), }, type => true); services.AddServiceBus <SecurityBusRegistry>(); services .AddIdentityServer(options => { options.IssuerUri = "https://devkit.security/"; options.Events.RaiseErrorEvents = true; options.Events.RaiseInformationEvents = true; options.Events.RaiseFailureEvents = true; options.Events.RaiseSuccessEvents = true; }) .AddCustomStores() .AddCustomValidators() .AddDeveloperSigningCredential(); services .AddIdentityMongoDbProvider <UserAccount, UserRole>( identityOptions => { identityOptions.Password.RequiredLength = 6; identityOptions.Password.RequireLowercase = true; identityOptions.Password.RequireUppercase = true; identityOptions.Password.RequireNonAlphanumeric = true; identityOptions.Password.RequireDigit = true; }, mongoIdentityOptions => { var connectionString = services.BuildServiceProvider().GetRequiredService <RepositoryOptions>().ConnectionString; mongoIdentityOptions.ConnectionString = connectionString; }); services .AddAuthentication() .AddGoogle(options => { // register your IdentityServer with Google at https://console.developers.google.com // enable the Google+ API // set the redirect URI to http://localhost:5000/signin-google options.ClientId = Environment.GetEnvironmentVariable("GOOGLE_CLIENT_ID"); options.ClientSecret = Environment.GetEnvironmentVariable("GOOGLE_SECRET"); }) .AddFacebook(options => { options.SignInScheme = IdentityServerConstants.ExternalCookieAuthenticationScheme; options.ClientId = Environment.GetEnvironmentVariable("FACEBOOK_CLIENT_ID"); options.ClientSecret = Environment.GetEnvironmentVariable("FACEBOOK_SECRET"); }); services.AddSeedData <SecuritySeeder>(); }
public static void RegisterConvetions() { ConventionRegistry.Register("MemoTimeConventions", new MongoConvention(), x => true); _initialized = true; }
private static void RegisterConventions() { ConventionRegistry.Register("ExaminoConventions", new MongoConvention(), x => true); _initialized = true; }
private void RegisterConventions() { ConventionRegistry.Register("WardenConventions", new MongoConvention(), x => true); _initialized = true; }
protected override void Load(ContainerBuilder builder) { base.Load(builder); MapAllEvents(); ConventionRegistry.Register("MyConventions", new MyConventions(), _ => true); builder.Register <IMongoClient>(c => { var ctx = c.Resolve <IComponentContext>(); var options = ctx.Resolve <IOptions <MongoDbSettings> >(); MongoClientSettings settings = MongoClientSettings.FromUrl(new MongoUrl(options.Value.ConnectionString)); settings.SslSettings = new SslSettings() { EnabledSslProtocols = SslProtocols.Tls12 }; return(new MongoClient(settings)); }) .SingleInstance(); builder.Register <IMongoDatabase>(c => { var ctx = c.Resolve <IComponentContext>(); var options = ctx.Resolve <IOptions <MongoDbSettings> >(); var client = ctx.Resolve <IMongoClient>(); var db = client.GetDatabase(options.Value.Database); if (seedDatabase) { db.SeedDatabase(); } return(db); }); assemblies .SelectMany(x => x.GetTypes()) .Where(x => typeof(Aggregate).IsAssignableFrom(x)) .ToList() .ForEach(x => { var storeType = typeof(AggregateStore <>).MakeGenericType(x); builder.RegisterType(storeType).AsImplementedInterfaces(); }); assemblies .SelectMany(x => x.GetTypes()) .SelectMany(x => x.GetInterfaces()) .Where(x => typeof(IQuery).IsAssignableFrom(x)) .SelectMany(x => x.GetGenericArguments()) .Select(x => typeof(IEnumerable).IsAssignableFrom(x) ? x.GetGenericArguments().First() : x) .Distinct() .ToList() .ForEach(x => { var storeType = typeof(QueryableStore <>).MakeGenericType(x); builder.RegisterType(storeType).AsImplementedInterfaces(); }); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddCors(options => { options.AddPolicy(AllowSpecificOrigins, builder => { builder.WithOrigins(Configuration["CORS"]) .AllowAnyHeader() .AllowAnyMethod(); }); }); services.AddControllers() .AddNewtonsoftJson( options => options.UseMemberCasing()); services.Configure <HistorySettings>(Configuration); //Compression services.AddResponseCompression(options => { options.Providers.Add <BrotliCompressionProvider>(); }); services.Configure <BrotliCompressionProviderOptions>(options => { options.Level = CompressionLevel.Fastest; }); services.AddScoped <IRecordsService, RecordsService>(); services.AddScoped <IRecordEventsService, RecordEventsService>(); services.AddScoped <IRecordRepository, RecordRepository>(); // Register the Swagger generator, defining one or more Swagger documents services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" }); }); // Para Utilizar los modelos comenzando con mayuscula para MondoDB var conventionPack = new ConventionPack { new CamelCaseElementNameConvention() }; ConventionRegistry.Register("camelCase", conventionPack, t => true); // Consumer dependencies should be scoped //services.AddScoped<SomeConsumerDependency>(); // local function to create the bus // IBusControl CreateBus(IServiceProvider serviceProvider) // { // return Bus.Factory.CreateUsingRabbitMq(cfg => // { // cfg.Host(Configuration["RABBITMQ_URI"]); // cfg.ClearMessageDeserializers(); // cfg.UseRawJsonSerializer(); // cfg.ReceiveEndpoint("history-service", ep => // { // ep.PrefetchCount = 16; // ep.ConfigureConsumer<RecordCreatedIntegrationEventHandler>(serviceProvider); // }); // }); // } // // local function to configure consumers // void ConfigureMassTransit(IServiceCollectionConfigurator configurator) // { // configurator.AddConsumer<RecordCreatedIntegrationEventHandler>(); // } // configures MassTransit to integrate with the built-in dependency injection // services.AddMassTransit(CreateBus, ConfigureMassTransit); services.AddDistributedRedisCache(option => { option.Configuration = Configuration["redis:connection"]; option.ConfigurationOptions.Password = Configuration["redis:password"]; option.InstanceName = "master"; }); services.AddScoped <IRedisClient>(s => new RedisClient(Configuration["redis:connection"], int.Parse(Configuration["redis:port"]), password: Configuration["redis:password"])); }
static void Main(string[] args) { Console.WriteLine("Hello World!"); var settings = MongoClientSettings.FromConnectionString(ConnectionString); IMongoClient client = new MongoClient(settings); client.DropDatabase(DatabaseName); // Set up MongoDB conventions var pack = new ConventionPack { new EnumRepresentationConvention(BsonType.String) }; ConventionRegistry.Register("EnumStringConvention", pack, t => true); string json = File.ReadAllText("../SmartDeliveries/src/SmartDeliveries/Validation.js"); var document = new BsonDocument(); document.AddRange(BsonDocument.Parse(json)); Debug.WriteLine(document.ToJson()); var database = client.GetDatabase(DatabaseName); database.CreateCollection(CollectionName, new CreateCollectionOptions <BsonDocument> { ValidationAction = DocumentValidationAction.Error, ValidationLevel = DocumentValidationLevel.Strict, Validator = document }); ISalesOrderService salesOrderService = new SalesOrderService(new MongoClient(settings)); // PB1 Add a new sales order to the system. string orderId = Guid.NewGuid().ToString(); salesOrderService.AddSalesOrder(new AddSalesOrderRequest { OrderId = orderId, CreatedAt = DateTime.Now }); string fulfillmentId = Guid.NewGuid().ToString(); // PB2 salesOrderService.AddFulFillment(new SalesOrderFulfillmentRequest { OrderId = orderId, FulfillmentId = fulfillmentId, Date = DateTime.Now, LineItems = new System.Collections.Generic.List <SalesOrderFulfillmentRequest.FulfillmentLineItem> { new SalesOrderFulfillmentRequest.FulfillmentLineItem { ProductId = 1, Quantity = 5 } } }); salesOrderService.AddFulFillmentSafe(new SalesOrderFulfillmentRequest { OrderId = orderId, FulfillmentId = fulfillmentId, Date = DateTime.Now, LineItems = new System.Collections.Generic.List <SalesOrderFulfillmentRequest.FulfillmentLineItem> { new SalesOrderFulfillmentRequest.FulfillmentLineItem { ProductId = 1, Quantity = 5 } } }); salesOrderService.CloseExpiredOrders(new CloseExpiredOrdersRequest { ExpiryDate = ThreeMonthsAgo }); }
public static IServiceCollection AddMongoDataAccess(this IServiceCollection services, IConfiguration configuration) { IConfigurationSection dataAccessConfig = configuration.GetSection("DataAccess"); string connectionString = dataAccessConfig.GetValue <string>("ConnectionString", "mongodb://localhost:27017"); string jobDatabase = dataAccessConfig.GetValue <string>("JobDatabase", "jobs"); services.AddHangfire(x => x.UseMongoStorage(connectionString, jobDatabase, new MongoStorageOptions { MigrationOptions = new MongoMigrationOptions { Strategy = MongoMigrationStrategy.Migrate } })); BsonSerializer.RegisterDiscriminatorConvention(typeof(Project), new HierarchicalDiscriminatorConvention("appName")); BsonSerializer.RegisterDiscriminatorConvention(typeof(LexConfig), new HierarchicalDiscriminatorConvention("type")); BsonSerializer.RegisterDiscriminatorConvention(typeof(LexViewFieldConfig), new HierarchicalDiscriminatorConvention("type")); BsonSerializer.RegisterDiscriminatorConvention(typeof(LexTask), new HierarchicalDiscriminatorConvention("type")); var globalPack = new ConventionPack { new CamelCaseElementNameConvention(), new ObjectRefConvention() }; ConventionRegistry.Register("Global", globalPack, t => true); var paratextProjectPack = new ConventionPack { new NoIdMemberConvention() }; ConventionRegistry.Register("ParatextProject", paratextProjectPack, t => t == typeof(ParatextProject)); RegisterClass <EntityBase>(cm => { cm.MapIdProperty(e => e.Id) .SetIdGenerator(StringObjectIdGenerator.Instance) .SetSerializer(new StringSerializer(BsonType.ObjectId)); }); RegisterClass <LexConfig>(cm => { cm.MapMember(lc => lc.HideIfEmpty).SetSerializer(new EmptyStringBooleanSerializer()); }); RegisterClass <LexConfigFieldList>(cm => cm.SetDiscriminator(LexConfig.FieldList)); RegisterClass <LexConfigOptionList>(cm => cm.SetDiscriminator(LexConfig.OptionList)); RegisterClass <LexConfigMultiOptionList>(cm => cm.SetDiscriminator(LexConfig.MultiOptionList)); RegisterClass <LexConfigMultiText>(cm => cm.SetDiscriminator(LexConfig.MultiText)); RegisterClass <LexConfigPictures>(cm => cm.SetDiscriminator(LexConfig.Pictures)); RegisterClass <LexConfigMultiParagraph>(cm => cm.SetDiscriminator(LexConfig.MultiParagraph)); RegisterClass <LexViewFieldConfig>(cm => cm.SetDiscriminator("basic")); RegisterClass <LexViewMultiTextFieldConfig>(cm => cm.SetDiscriminator("multitext")); RegisterClass <LexTask>(cm => cm.SetDiscriminator("")); RegisterClass <LexTaskDashboard>(cm => cm.SetDiscriminator(LexTask.Dashboard)); RegisterClass <LexTaskSemdom>(cm => cm.SetDiscriminator(LexTask.Semdom)); RegisterClass <LexAuthorInfo>(cm => { cm.MapMember(a => a.ModifiedByUserRef) .SetSerializer(new StringSerializer(BsonType.ObjectId)); cm.MapMember(a => a.CreatedByUserRef) .SetSerializer(new StringSerializer(BsonType.ObjectId)); }); RegisterClass <LexSense>(cm => { cm.UnmapMember(s => s.CustomFields); cm.UnmapMember(s => s.AuthorInfo); cm.UnmapMember(s => s.ReversalEntries); }); services.AddSingleton <IMongoClient>(sp => new MongoClient(connectionString)); services.AddMongoRepository <SendReceiveJob>("send_receive"); services.AddMongoRepository <User>("users", cm => { cm.MapMember(u => u.SiteRole).SetSerializer( new DictionaryInterfaceImplementerSerializer <Dictionary <string, string> >( DictionaryRepresentation.Document, new SiteDomainSerializer(), new StringSerializer())); cm.MapMember(u => u.Projects) .SetSerializer(new EnumerableInterfaceImplementerSerializer <List <string>, string>( new StringSerializer(BsonType.ObjectId))); }); services.AddMongoRepository <Project>("projects"); services.AddMongoRepository <LexProject>("projects", cm => cm.SetDiscriminator("lexicon")); services.AddMongoRepository <TranslateProject>("projects", cm => cm.SetDiscriminator("translate")); services.AddMongoProjectRepositoryFactory <TranslateDocumentSet>("translate"); services.AddMongoProjectRepositoryFactory <LexEntry>("lexicon", cm => { cm.UnmapMember(e => e.Environments); cm.UnmapMember(e => e.MorphologyType); }); return(services); }
public static void Register(MappingConvention mapping) { ConventionRegistry.Register("MappingConvention", new ConventionPack { mapping }, _ => true); }
private void RegisterConventions() { ConventionRegistry.Register("ActioConventions", new MongoConvention(), x => true); }
/// <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 }
private void RegisterConventions() { ConventionRegistry.Register("MushroomCloudConvention", new MongoConvention(), x => true); }
public void ConfigureServices(IServiceCollection services) { services.AddControllers(); #region MongoDB var conventionPack = new ConventionPack { new CamelCaseElementNameConvention() }; ConventionRegistry.Register( "camelCase", conventionPack, t => true ); //BsonClassMap.RegisterClassMap<SRecipe>( // x => new RecipeMapper().SetupBsonMapping(x) //); BsonClassMap.RegisterClassMap <JsonLdObject>( x => new JsonLdObjectMapper().SetupBsonMapping(x) ); BsonClassMap.RegisterClassMap <Thing>( x => new ThingMapper().SetupBsonMapping(x) ); BsonSerializer.RegisterSerializationProvider( new ValuesSerializerProvider() ); BsonSerializer.RegisterGenericSerializerDefinition( typeof(OneOrMany <>), typeof(OneOrManySerializer <>) ); MongoDbHelper.Default .MapInterfaceToDefaultImplementation <IAggregateRating>() .MapInterfaceToDefaultImplementation <IClaimReview>() .MapInterfaceToDefaultImplementation <IClip>() .MapInterfaceToDefaultImplementation <ICreativeWork>() .MapInterfaceToDefaultImplementation <IDemand>() .MapInterfaceToDefaultImplementation <IHowTo>() .MapInterfaceToDefaultImplementation <IHowToSection>() .MapInterfaceToDefaultImplementation <IHowToDirection>() .MapInterfaceToDefaultImplementation <IHowToItem>() .MapInterfaceToDefaultImplementation <IHowToStep>() .MapInterfaceToDefaultImplementation <IHowToSupply>() .MapInterfaceToDefaultImplementation <IHowToTip>() .MapInterfaceToDefaultImplementation <IHowToTool>() .MapInterfaceToDefaultImplementation <IIntangible>() .MapInterfaceToDefaultImplementation <IImageGallery>() .MapInterfaceToDefaultImplementation <IImageObject>() .MapInterfaceToDefaultImplementation <IItemList>() .MapInterfaceToDefaultImplementation <IMonetaryAmount>() .MapInterfaceToDefaultImplementation <INutritionInformation>() .MapInterfaceToDefaultImplementation <IOrganization>() .MapInterfaceToDefaultImplementation <IPerson>() .MapInterfaceToDefaultImplementation <IPublicationEvent>() .MapInterfaceToDefaultImplementation <IQuantitativeValue>() .MapInterfaceToDefaultImplementation <IRating>() .MapInterfaceToDefaultImplementation <IRecipe>() .MapInterfaceToDefaultImplementation <IReview>() .MapInterfaceToDefaultImplementation <IReviewAction>() .MapInterfaceToDefaultImplementation <IStructuredValue>() .MapInterfaceToDefaultImplementation <IThing, Thing>(x => x.Name) .MapInterfaceToDefaultImplementation <IVideoObject>(); //BsonSerializer.RegisterSerializer( // typeof(IThing), // new ThingSerializer() //); BsonSerializer.RegisterSerializer( typeof(TimeSpan), new TimeSpanSerializer() ); BsonSerializer.RegisterSerializer( typeof(JsonLdContext), new JsonLdContextSerializer() ); BsonSerializer.RegisterGenericSerializerDefinition( typeof(Values <,>), typeof(ValuesSerializer <,>) ); BsonSerializer.RegisterGenericSerializerDefinition( typeof(Values <, ,>), typeof(ValuesSerializer <, ,>) ); BsonSerializer.RegisterGenericSerializerDefinition( typeof(Values <, , ,>), typeof(ValuesSerializer <, , ,>) ); BsonSerializer.RegisterGenericSerializerDefinition( typeof(Values <, , , , , ,>), typeof(ValuesSerializer <, , , , , ,>) ); //BsonSerializer.RegisterDiscriminatorConvention( // typeof(Values<,>), // new SchemaValuesConvention() //); //BsonSerializer.RegisterDiscriminatorConvention( // typeof(Values<,,>), // new SchemaValuesConvention() //); //BsonSerializer.RegisterDiscriminatorConvention( // typeof(Values<,,,>), // new SchemaValuesConvention() //); //BsonSerializer.RegisterDiscriminatorConvention( // typeof(Values<,,,,,,>), // new SchemaValuesConvention() //); services .AddMongoDb( Configuration.GetConnectionString("RecipeDb"), Configuration.GetValue <string>("DatabaseName") ); #endregion //services.AddGraphQL( // sp => // { // var schema = SchemaBuilder.New() // //.EnableRelaySupport() // .AddType<ThingTypeDescriptor>() // .AddServices(sp) // //.AddObjectType<OneOrManyTypeDescriptor>() // //.Use(next => context => // //{ // // return Task.CompletedTask; // //}) // //.AddObjectType<ThingTypeDescriptor>() // .AddObjectType<SchemaOrgTypeDescriptor<SRecipe>>() // //.AddObjectType<RecipeTypeDescriptor>() // .AddQueryType(d => d.Name(QueryConstants.QueryTypeName)) // //.AddType<RecipeQueryType>() // .AddType<HelloWorldQueryType>() // .Create(); // return schema; // } //); }
private void RegisterConventions() { BsonSerializer.RegisterSerializer(typeof(decimal), new DecimalSerializer(BsonType.Decimal128)); BsonSerializer.RegisterSerializer(typeof(decimal?), new NullableSerializer <decimal>(new DecimalSerializer(BsonType.Decimal128))); ConventionRegistry.Register("Conventions", new MongoDbConventions(), x => true); }
private void RegisterConventions() { ConventionRegistry.Register("CollectivelyConventions", new MongoConvention(), x => true); _initialized = true; }
static MongoHelper() { ConventionRegistry.Register(typeof(IgnoreExtraElementsConvention).Name, new ConventionPack { new IgnoreExtraElementsConvention(true) }, t => true); }
private static void RegisterConventions() { ConventionRegistry.Register("PassengerConventions", new MongoConvention(), x => true); }