示例#1
0
        static MongoDbDataStoreFactory()
        {
            var typeSerializer = new TypeSerialiser();

            BsonSerializer.RegisterSerializer(typeof(Type), typeSerializer);
            BsonSerializer.RegisterSerializer(Type.GetType("System.RuntimeType"), typeSerializer);

            IndexTypesByEntityType = new Dictionary <Type, IList <object> >();
            foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies())
            {
                var mongoIndexTypes = assembly
                                      .GetTypes()
                                      .Where
                                      (
                    type =>
                    (
                        // base is NOT an abstract index
                        (
                            type.BaseType != null &&
                            type.BaseType.IsGenericType &&
                            typeof(MongoDbIndex <>).IsAssignableFrom(type.BaseType.GetGenericTypeDefinition())
                        )
                        ||
                        // base is an abstract index
                        (
                            type.BaseType != null &&
                            type.BaseType.BaseType != null &&
                            type.BaseType.BaseType.IsGenericType &&
                            typeof(MongoDbIndex <>).IsAssignableFrom(type.BaseType.BaseType.GetGenericTypeDefinition())
                        )
                        ||
                        // a deeper inheritance model
                        (
                            type.BaseType != null &&
                            type.BaseType.BaseType != null &&
                            type.BaseType.BaseType.BaseType != null &&
                            type.BaseType.BaseType.BaseType.IsGenericType &&
                            typeof(MongoDbIndex <>).IsAssignableFrom(type.BaseType.BaseType.BaseType.GetGenericTypeDefinition())
                        )
                        ||
                        // an even deeper inheritance model
                        (
                            type.BaseType != null &&
                            type.BaseType.BaseType != null &&
                            type.BaseType.BaseType.BaseType != null &&
                            type.BaseType.BaseType.BaseType.BaseType != null &&
                            type.BaseType.BaseType.BaseType.BaseType.IsGenericType &&
                            typeof(MongoDbIndex <>).IsAssignableFrom(type.BaseType.BaseType.BaseType.BaseType.GetGenericTypeDefinition())
                        )
                    ) &&
                    !type.IsAbstract
                                      );
                foreach (Type mongoIndexType in mongoIndexTypes)
                {
                    Type genericType = mongoIndexType;
                    while (genericType != null && !genericType.IsGenericType)
                    {
                        genericType = genericType.BaseType;
                    }
                    genericType = genericType.GetGenericArguments().Single();

                    IList <object> indexTypes;
                    if (!IndexTypesByEntityType.TryGetValue(genericType, out indexTypes))
                    {
                        IndexTypesByEntityType.Add(genericType, indexTypes = new List <object>());
                    }
                    object mongoIndex = Activator.CreateInstance(mongoIndexType, true);
                    indexTypes.Add(mongoIndex);
                }
            }
        }
示例#2
0
 static EventStore()
 {
     BsonSerializer.RegisterSerializer(typeof(EventSourceVersion), new EventSourceVersionSerializer());
 }
        static SerializationHelper()
        {
            var decimalSerializer = new DecimalSerializer(BsonType.Decimal128, new RepresentationConverter(allowOverflow: false, allowTruncation: false));

            BsonSerializer.RegisterSerializer(decimalSerializer);
        }
 /// <summary>
 /// Loads serializers
 /// </summary>
 public void Load()
 {
     BsonSerializer.RegisterSerializer(new DecimalSerializer(BsonType.String));
 }
 static LocalDateTimeSerializerTests()
 {
     BsonSerializer.RegisterSerializer(new LocalDateTimeSerializer());
 }
示例#6
0
 /// <summary>
 /// Set database initializer
 /// </summary>
 public virtual void SetDatabaseInitializer()
 {
     BsonSerializer.RegisterSerializer(typeof(DateTime),
                                       new DateTimeSerializer(DateTimeKind.Utc));
 }
        protected override void Load(ContainerBuilder builder)
        {
            base.Load(builder);

            string cs = _configuration.GetSection("Settings:CADENA_CONEXION").Value;

            var mongoUrl = new MongoUrl(cs);

            /*
             * var ms = MongoClientSettings.FromConnectionString(cs);
             * ms.SslSettings = new SslSettings() { EnabledSslProtocols = SslProtocols.Tls12 };
             * ms.RetryWrites = false;
             * ms.ServerSelectionTimeout = new TimeSpan(0, 5, 0);
             * ms.WaitQueueTimeout = new TimeSpan(0, 5, 0);
             * ms.WaitQueueSize = 60000;
             */

            //builder.RegisterType<DataContext>().Named<IDataContext>("contextNoSql").WithParameter("settings", settings).InstancePerLifetimeScope();
            builder.RegisterType <DataContext>().Named <IDataContext>("contextNoSql").WithParameter("mongoUrl", mongoUrl).InstancePerLifetimeScope();

            /*
             * //-> Aplicacion
             * builder.RegisterAssemblyTypes(Assembly.Load(new AssemblyName("Minedu.AprendoEnCasaOffLine.Contenido.Core")))
             *  .Where(t => t.Name.EndsWith("Aplicacion", StringComparison.Ordinal) && t.GetTypeInfo().IsClass)
             *  .AsImplementedInterfaces();
             *
             * //-> Validacion
             * builder.RegisterAssemblyTypes(Assembly.Load(new AssemblyName("Minedu.AprendoEnCasaOffLine.Contenido.Core")))
             *  .Where(t => t.Name.EndsWith("Validacion", StringComparison.Ordinal) && t.GetTypeInfo().IsClass)
             *  .AsSelf();
             */
            //Base
            builder.RegisterType <CollectionContext>().As <ICollectionContext>().WithParameter((c, p) => true, (c, p) => p.ResolveNamed <IDataContext>("contextNoSql"));

            BsonSerializer.RegisterSerializer(typeof(DateTime), new BsonUtcDateTimeSerializer());

            //Repository

            /*
             * builder.RegisterAssemblyTypes(Assembly.Load(new AssemblyName("Minedu.AprendoEnCasaOffLine.Contenido.Core")))
             *  .Where(t => t.Name.EndsWith("Repositorio", StringComparison.Ordinal) && t.IsGenericType == false && t.IsClass == true && t.BaseType.Name.Contains("CustomBaseRepository"))
             *  .AsImplementedInterfaces()
             *  .WithParameter((c, p) => true, (c, p) => p.ResolveNamed<IDataContext>("contextNoSql"))
             *  .InstancePerLifetimeScope();
             */
            builder.RegisterGeneric(typeof(CollectionContext <>))
            .As(typeof(ICollectionContext <>))
            .WithParameter((c, p) => true, (c, p) => p.ResolveNamed <IDataContext>("contextNoSql"))
            .InstancePerDependency();

            builder.RegisterGeneric(typeof(BaseRepository <>))
            .As(typeof(IBaseRepository <>))
            .WithParameter((c, p) => true, (c, p) => p.ResolveNamed <IDataContext>("contextNoSql"))
            .InstancePerDependency();


            builder.RegisterGeneric(typeof(CustomBaseRepository <>))
            .As(typeof(ICustomBaseRepository <>))
            .WithParameter((c, p) => true, (c, p) => p.ResolveNamed <IDataContext>("contextNoSql"))
            .InstancePerDependency();
        }
 static B()
 {
     BsonSerializer.RegisterSerializer(typeof(IX), BsonClassMapSerializer.Instance);
 }
 static void AddSerializer <TType>() where TType : IMessage, new()
 {
     BsonSerializer.RegisterSerializer(typeof(TType),
                                       new ProtoBsonSerializer <TType>());
 }
示例#10
0
 static DatabaseProvider()
 {
     BsonSerializer.RegisterSerializer(typeof(Document), new JsonSerializerAdapter <Document>());
 }
示例#11
0
 static InstantSerializerTests()
 {
     BsonSerializer.RegisterSerializer(new InstantSerializer());
 }
示例#12
0
        private void MongoDBSettingHandler()
        {
            DateTimeSerializer dateTimeSerializer = new DateTimeSerializer(DateTimeKind.Local, BsonType.DateTime);

            BsonSerializer.RegisterSerializer(typeof(DateTime), dateTimeSerializer);
        }
示例#13
0
        /// <summary>The method called by the runtime to add services to the container.</summary>
        /// <param name="services">The service injection container.</param>
        public void ConfigureServices(IServiceCollection services)
        {
            // init basic services
            services
            .Configure <ApiClientsConfig>(this.Configuration.GetSection("ApiClients"))
            .Configure <BackgroundServicesConfig>(this.Configuration.GetSection("BackgroundServices"))
            .Configure <ModCompatibilityListConfig>(this.Configuration.GetSection("ModCompatibilityList"))
            .Configure <ModUpdateCheckConfig>(this.Configuration.GetSection("ModUpdateCheck"))
            .Configure <MongoDbConfig>(this.Configuration.GetSection("MongoDB"))
            .Configure <SiteConfig>(this.Configuration.GetSection("Site"))
            .Configure <RouteOptions>(options => options.ConstraintMap.Add("semanticVersion", typeof(VersionConstraint)))
            .AddLogging()
            .AddMemoryCache()
            .AddMvc()
            .ConfigureApplicationPartManager(manager => manager.FeatureProviders.Add(new InternalControllerFeatureProvider()))
            .AddJsonOptions(options =>
            {
                foreach (JsonConverter converter in new JsonHelper().JsonSettings.Converters)
                {
                    options.SerializerSettings.Converters.Add(converter);
                }

                options.SerializerSettings.Formatting        = Formatting.Indented;
                options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
            });
            MongoDbConfig mongoConfig = this.Configuration.GetSection("MongoDB").Get <MongoDbConfig>();

            // init background service
            {
                BackgroundServicesConfig config = this.Configuration.GetSection("BackgroundServices").Get <BackgroundServicesConfig>();
                if (config.Enabled)
                {
                    services.AddHostedService <BackgroundService>();
                }
            }

            // init MongoDB
            services.AddSingleton <MongoDbRunner>(serv => !mongoConfig.IsConfigured()
                ? MongoDbRunner.Start()
                : throw new InvalidOperationException("The MongoDB connection is configured, so the local development version should not be used.")
                                                  );
            services.AddSingleton <IMongoDatabase>(serv =>
            {
                // get connection string
                string connectionString = mongoConfig.IsConfigured()
                    ? mongoConfig.ConnectionString
                    : serv.GetRequiredService <MongoDbRunner>().ConnectionString;

                // get client
                BsonSerializer.RegisterSerializer(new UtcDateTimeOffsetSerializer());
                return(new MongoClient(connectionString).GetDatabase(mongoConfig.Database));
            });
            services.AddSingleton <IModCacheRepository>(serv => new ModCacheRepository(serv.GetRequiredService <IMongoDatabase>()));
            services.AddSingleton <IWikiCacheRepository>(serv => new WikiCacheRepository(serv.GetRequiredService <IMongoDatabase>()));

            // init Hangfire
            services
            .AddHangfire(config =>
            {
                config
                .SetDataCompatibilityLevel(CompatibilityLevel.Version_170)
                .UseSimpleAssemblyNameTypeSerializer()
                .UseRecommendedSerializerSettings();

                if (mongoConfig.IsConfigured())
                {
                    config.UseMongoStorage(mongoConfig.ConnectionString, $"{mongoConfig.Database}-hangfire", new MongoStorageOptions
                    {
                        MigrationOptions = new MongoMigrationOptions(MongoMigrationStrategy.Drop),
                        CheckConnection  = false    // error on startup takes down entire process
                    });
                }
                else
                {
                    config.UseMemoryStorage();
                }
            });

            // init API clients
            {
                ApiClientsConfig api       = this.Configuration.GetSection("ApiClients").Get <ApiClientsConfig>();
                string           version   = this.GetType().Assembly.GetName().Version.ToString(3);
                string           userAgent = string.Format(api.UserAgent, version);

                services.AddSingleton <IChucklefishClient>(new ChucklefishClient(
                                                               userAgent: userAgent,
                                                               baseUrl: api.ChucklefishBaseUrl,
                                                               modPageUrlFormat: api.ChucklefishModPageUrlFormat
                                                               ));
                services.AddSingleton <ICurseForgeClient>(new CurseForgeClient(
                                                              userAgent: userAgent,
                                                              apiUrl: api.CurseForgeBaseUrl
                                                              ));

                services.AddSingleton <IGitHubClient>(new GitHubClient(
                                                          baseUrl: api.GitHubBaseUrl,
                                                          userAgent: userAgent,
                                                          acceptHeader: api.GitHubAcceptHeader,
                                                          username: api.GitHubUsername,
                                                          password: api.GitHubPassword
                                                          ));

                services.AddSingleton <IModDropClient>(new ModDropClient(
                                                           userAgent: userAgent,
                                                           apiUrl: api.ModDropApiUrl,
                                                           modUrlFormat: api.ModDropModPageUrl
                                                           ));

                services.AddSingleton <INexusClient>(new NexusClient(
                                                         webUserAgent: userAgent,
                                                         webBaseUrl: api.NexusBaseUrl,
                                                         webModUrlFormat: api.NexusModUrlFormat,
                                                         webModScrapeUrlFormat: api.NexusModScrapeUrlFormat,
                                                         apiAppVersion: version,
                                                         apiKey: api.NexusApiKey
                                                         ));

                services.AddSingleton <IPastebinClient>(new PastebinClient(
                                                            baseUrl: api.PastebinBaseUrl,
                                                            userAgent: userAgent
                                                            ));
            }

            // init helpers
            services
            .AddSingleton <IGzipHelper>(new GzipHelper())
            .AddSingleton <IStorageProvider>(serv => new StorageProvider(
                                                 serv.GetRequiredService <IOptions <ApiClientsConfig> >(),
                                                 serv.GetRequiredService <IPastebinClient>(),
                                                 serv.GetRequiredService <IGzipHelper>()
                                                 ));
        }
示例#14
0
        /// <summary>The method called by the runtime to add services to the container.</summary>
        /// <param name="services">The service injection container.</param>
        public void ConfigureServices(IServiceCollection services)
        {
            // init basic services
            services
            .Configure <ApiClientsConfig>(this.Configuration.GetSection("ApiClients"))
            .Configure <BackgroundServicesConfig>(this.Configuration.GetSection("BackgroundServices"))
            .Configure <ModCompatibilityListConfig>(this.Configuration.GetSection("ModCompatibilityList"))
            .Configure <ModUpdateCheckConfig>(this.Configuration.GetSection("ModUpdateCheck"))
            .Configure <StorageConfig>(this.Configuration.GetSection("Storage"))
            .Configure <SiteConfig>(this.Configuration.GetSection("Site"))
            .Configure <RouteOptions>(options => options.ConstraintMap.Add("semanticVersion", typeof(VersionConstraint)))
            .AddLogging()
            .AddMemoryCache();
            StorageConfig storageConfig = this.Configuration.GetSection("Storage").Get <StorageConfig>();
            StorageMode   storageMode   = storageConfig.Mode;

            // init MVC
            services
            .AddControllers()
            .AddNewtonsoftJson(options => this.ConfigureJsonNet(options.SerializerSettings))
            .ConfigureApplicationPartManager(manager => manager.FeatureProviders.Add(new InternalControllerFeatureProvider()));
            services
            .AddRazorPages();

            // init storage
            switch (storageMode)
            {
            case StorageMode.InMemory:
                services.AddSingleton <IModCacheRepository>(new ModCacheMemoryRepository());
                services.AddSingleton <IWikiCacheRepository>(new WikiCacheMemoryRepository());
                break;

            case StorageMode.Mongo:
            case StorageMode.MongoInMemory:
            {
                // local MongoDB instance
                services.AddSingleton <MongoDbRunner>(_ => storageMode == StorageMode.MongoInMemory
                            ? MongoDbRunner.Start()
                            : throw new NotSupportedException($"The in-memory MongoDB runner isn't available in storage mode {storageMode}.")
                                                      );

                // MongoDB
                services.AddSingleton <IMongoDatabase>(serv =>
                    {
                        BsonSerializer.RegisterSerializer(new UtcDateTimeOffsetSerializer());
                        return(new MongoClient(this.GetMongoDbConnectionString(serv, storageConfig))
                               .GetDatabase(storageConfig.Database));
                    });

                // repositories
                services.AddSingleton <IModCacheRepository>(serv => new ModCacheMongoRepository(serv.GetRequiredService <IMongoDatabase>()));
                services.AddSingleton <IWikiCacheRepository>(serv => new WikiCacheMongoRepository(serv.GetRequiredService <IMongoDatabase>()));
            }
            break;

            default:
                throw new NotSupportedException($"Unhandled storage mode '{storageMode}'.");
            }

            // init Hangfire
            services
            .AddHangfire((serv, config) =>
            {
                config
                .SetDataCompatibilityLevel(CompatibilityLevel.Version_170)
                .UseSimpleAssemblyNameTypeSerializer()
                .UseRecommendedSerializerSettings();

                switch (storageMode)
                {
                case StorageMode.InMemory:
                    config.UseMemoryStorage();
                    break;

                case StorageMode.MongoInMemory:
                case StorageMode.Mongo:
                    string connectionString = this.GetMongoDbConnectionString(serv, storageConfig);
                    config.UseMongoStorage(MongoClientSettings.FromConnectionString(connectionString), $"{storageConfig.Database}-hangfire", new MongoStorageOptions
                    {
                        MigrationOptions = new MongoMigrationOptions(MongoMigrationStrategy.Drop),
                        CheckConnection  = false        // error on startup takes down entire process
                    });
                    break;
                }
            });

            // init background service
            {
                BackgroundServicesConfig config = this.Configuration.GetSection("BackgroundServices").Get <BackgroundServicesConfig>();
                if (config.Enabled)
                {
                    services.AddHostedService <BackgroundService>();
                }
            }

            // init API clients
            {
                ApiClientsConfig api       = this.Configuration.GetSection("ApiClients").Get <ApiClientsConfig>();
                string           version   = this.GetType().Assembly.GetName().Version.ToString(3);
                string           userAgent = string.Format(api.UserAgent, version);

                services.AddSingleton <IChucklefishClient>(new ChucklefishClient(
                                                               userAgent: userAgent,
                                                               baseUrl: api.ChucklefishBaseUrl,
                                                               modPageUrlFormat: api.ChucklefishModPageUrlFormat
                                                               ));

                services.AddSingleton <ICurseForgeClient>(new CurseForgeClient(
                                                              userAgent: userAgent,
                                                              apiUrl: api.CurseForgeBaseUrl
                                                              ));

                services.AddSingleton <IGitHubClient>(new GitHubClient(
                                                          baseUrl: api.GitHubBaseUrl,
                                                          userAgent: userAgent,
                                                          acceptHeader: api.GitHubAcceptHeader,
                                                          username: api.GitHubUsername,
                                                          password: api.GitHubPassword
                                                          ));

                services.AddSingleton <IModDropClient>(new ModDropClient(
                                                           userAgent: userAgent,
                                                           apiUrl: api.ModDropApiUrl,
                                                           modUrlFormat: api.ModDropModPageUrl
                                                           ));

                services.AddSingleton <INexusClient>(new NexusClient(
                                                         webUserAgent: userAgent,
                                                         webBaseUrl: api.NexusBaseUrl,
                                                         webModUrlFormat: api.NexusModUrlFormat,
                                                         webModScrapeUrlFormat: api.NexusModScrapeUrlFormat,
                                                         apiAppVersion: version,
                                                         apiKey: api.NexusApiKey
                                                         ));

                services.AddSingleton <IPastebinClient>(new PastebinClient(
                                                            baseUrl: api.PastebinBaseUrl,
                                                            userAgent: userAgent
                                                            ));
            }

            // init helpers
            services
            .AddSingleton <IGzipHelper>(new GzipHelper())
            .AddSingleton <IStorageProvider>(serv => new StorageProvider(
                                                 serv.GetRequiredService <IOptions <ApiClientsConfig> >(),
                                                 serv.GetRequiredService <IPastebinClient>(),
                                                 serv.GetRequiredService <IGzipHelper>()
                                                 ));
        }
 static MigrationRunner()
 {
     BsonSerializer.RegisterSerializer(typeof(MigrationVersion), new MigrationVersionSerializer());
 }
示例#16
0
 static Startup()
 {
     BsonSerializer.RegisterSerializer(new JTokenBsonSerializer());
     BsonSerializer.RegisterSerializer(new EnumSerializer <PermissionType>(BsonType.String));
 }
示例#17
0
 public void Provide(IBindingProviderBuilder builder)
 {
     builder.Bind <IKeyMaterialService>().To <PortalKeyMaterialService>();
     BsonSerializer.RegisterSerializer(new RsaSecurityKeySerializer());
 }
示例#18
0
        private static void InitClassMap()
        {
            BsonSerializer.RegisterSerializer(DateTimeSerializer.LocalInstance);

            if (!BsonClassMap.IsClassMapRegistered(typeof(BootstrapDict)))
            {
                BsonClassMap.RegisterClassMap <BootstrapDict>(md =>
                {
                    md.AutoMap();
                    md.IdMemberMap.SetSerializer(new StringSerializer(BsonType.ObjectId));
                    md.IdMemberMap.SetIgnoreIfDefault(true);
                });
            }
            if (!BsonClassMap.IsClassMapRegistered(typeof(DataAccess.User)))
            {
                BsonClassMap.RegisterClassMap <DataAccess.User>(md =>
                {
                    md.AutoMap();
                    md.IdMemberMap.SetSerializer(new StringSerializer(BsonType.ObjectId));
                    md.IdMemberMap.SetIgnoreIfDefault(true);
                    md.UnmapMember(user => user.Checked);
                    md.UnmapMember(user => user.Period);
                    md.UnmapMember(user => user.NewPassword);
                    md.UnmapMember(user => user.UserStatus);
                });
            }
            if (!BsonClassMap.IsClassMapRegistered(typeof(BootstrapMenu)))
            {
                BsonClassMap.RegisterClassMap <BootstrapMenu>(md =>
                {
                    md.AutoMap();
                    md.IdMemberMap.SetSerializer(new StringSerializer(BsonType.ObjectId));
                    md.IdMemberMap.SetIgnoreIfDefault(true);
                    md.UnmapMember(m => m.CategoryName);
                    md.UnmapMember(m => m.Active);
                    md.UnmapMember(m => m.ParentName);
                    md.UnmapMember(m => m.Menus);
                });
            }
            if (!BsonClassMap.IsClassMapRegistered(typeof(DataAccess.Group)))
            {
                BsonClassMap.RegisterClassMap <DataAccess.Group>(md =>
                {
                    md.AutoMap();
                    md.IdMemberMap.SetSerializer(new StringSerializer(BsonType.ObjectId));
                    md.IdMemberMap.SetIgnoreIfDefault(true);
                    md.UnmapMember(group => group.Checked);
                });
            }
            if (!BsonClassMap.IsClassMapRegistered(typeof(DataAccess.Role)))
            {
                BsonClassMap.RegisterClassMap <DataAccess.Role>(md =>
                {
                    md.AutoMap();
                    md.IdMemberMap.SetSerializer(new StringSerializer(BsonType.ObjectId));
                    md.IdMemberMap.SetIgnoreIfDefault(true);
                    md.UnmapMember(role => role.Checked);
                });
            }
            if (!BsonClassMap.IsClassMapRegistered(typeof(DataAccess.Exceptions)))
            {
                BsonClassMap.RegisterClassMap <DataAccess.Exceptions>(md =>
                {
                    md.AutoMap();
                    md.IdMemberMap.SetSerializer(new StringSerializer(BsonType.ObjectId));
                    md.IdMemberMap.SetIgnoreIfDefault(true);
                    md.UnmapMember(ex => ex.Period);
                });
            }
            if (!BsonClassMap.IsClassMapRegistered(typeof(DataAccess.Log)))
            {
                BsonClassMap.RegisterClassMap <DataAccess.Log>(md =>
                {
                    md.AutoMap();
                });
            }
            if (!BsonClassMap.IsClassMapRegistered(typeof(DataAccess.Trace)))
            {
                BsonClassMap.RegisterClassMap <DataAccess.Trace>(md =>
                {
                    md.AutoMap();
                    md.IdMemberMap.SetSerializer(new StringSerializer(BsonType.ObjectId));
                    md.IdMemberMap.SetIgnoreIfDefault(true);
                    md.AddKnownType(typeof(DataAccess.Log));
                });
            }
            if (!BsonClassMap.IsClassMapRegistered(typeof(DataAccess.LoginUser)))
            {
                BsonClassMap.RegisterClassMap <DataAccess.LoginUser>(md =>
                {
                    md.AutoMap();
                    md.IdMemberMap.SetSerializer(new StringSerializer(BsonType.ObjectId));
                    md.IdMemberMap.SetIgnoreIfDefault(true);
                });
            }
            if (!BsonClassMap.IsClassMapRegistered(typeof(DataAccess.ResetUser)))
            {
                BsonClassMap.RegisterClassMap <DataAccess.ResetUser>(md =>
                {
                    md.AutoMap();
                    md.IdMemberMap.SetSerializer(new StringSerializer(BsonType.ObjectId));
                    md.IdMemberMap.SetIgnoreIfDefault(true);
                });
            }
            if (!BsonClassMap.IsClassMapRegistered(typeof(RejectUser)))
            {
                BsonClassMap.RegisterClassMap <RejectUser>(md =>
                {
                    md.AutoMap();
                    md.IdMemberMap.SetSerializer(new StringSerializer(BsonType.ObjectId));
                    md.IdMemberMap.SetIgnoreIfDefault(true);
                });
            }
            if (!BsonClassMap.IsClassMapRegistered(typeof(DataAccess.Message)))
            {
                BsonClassMap.RegisterClassMap <DataAccess.Message>(md =>
                {
                    md.AutoMap();
                    md.IdMemberMap.SetSerializer(new StringSerializer(BsonType.ObjectId));
                    md.IdMemberMap.SetIgnoreIfDefault(true);
                    md.UnmapMember(t => t.LabelName);
                    md.UnmapMember(t => t.Period);
                    md.UnmapMember(t => t.FromIcon);
                    md.UnmapMember(t => t.FromDisplayName);
                });
            }
            if (!BsonClassMap.IsClassMapRegistered(typeof(DataAccess.Task)))
            {
                BsonClassMap.RegisterClassMap <DataAccess.Task>(md =>
                {
                    md.AutoMap();
                    md.IdMemberMap.SetSerializer(new StringSerializer(BsonType.ObjectId));
                    md.IdMemberMap.SetIgnoreIfDefault(true);
                    md.UnmapMember(t => t.AssignDisplayName);
                });
            }
        }
示例#19
0
        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;
            //    }
            //);
        }
示例#20
0
        static MongoDbAdapter()
        {
            BsonSerializer.RegisterSerializer(new VoucherSerializer());
            BsonSerializer.RegisterSerializer(new VoucherDetailSerializer());
            BsonSerializer.RegisterSerializer(new AssetSerializer());
            BsonSerializer.RegisterSerializer(new AssetItemSerializer());
            BsonSerializer.RegisterSerializer(new AmortizationSerializer());
            BsonSerializer.RegisterSerializer(new AmortItemSerializer());
            BsonSerializer.RegisterSerializer(new BalanceSerializer());
            BsonSerializer.RegisterSerializer(new ExchangeSerializer());

            BsonDocument MakeProject(BsonValue days, bool detail)
            {
                var proj = new BsonDocument
                {
                    ["_id"]  = false,
                    ["date"] = new BsonDocument
                    {
                        ["$switch"] = new BsonDocument
                        {
                            ["branches"] = new BsonArray
                            {
                                new BsonDocument
                                {
                                    ["case"] = new BsonDocument
                                    {
                                        ["$eq"] = new BsonArray
                                        {
                                            new BsonDocument
                                            {
                                                ["$type"] = "$date",
                                            },
                                            "missing",
                                        },
                                    },
                                    ["then"] = BsonNull.Value,
                                },
                            },
                            ["default"] = new BsonDocument
                            {
                                ["$subtract"] =
                                    new BsonArray
                                {
                                    "$date",
                                    new BsonDocument
                                    {
                                        ["$multiply"] =
                                            new BsonArray {
                                            days, 24 * 60 * 60 * 1000
                                        },
                                    },
                                },
                            },
                        },
                    },
                };

                if (detail)
                {
                    proj["detail"] = true;
                }
                return(proj);
            }

            var year = new BsonDocument
            {
                ["$subtract"] = new BsonArray {
                    new BsonDocument {
                        ["$dayOfYear"] = "$date"
                    }, 1
                },
            };
            var month = new BsonDocument
            {
                ["$subtract"] = new BsonArray {
                    new BsonDocument {
                        ["$dayOfMonth"] = "$date"
                    }, 1
                },
            };
            var week = new BsonDocument
            {
                ["$mod"] = new BsonArray
                {
                    new BsonDocument
                    {
                        ["$add"] = new BsonArray
                        {
                            new BsonDocument {
                                ["$dayOfWeek"] = "$date"
                            }, 5,
                        },
                    },
                    7,
                },
            };

            ProjectYear  = MakeProject(year, true);
            ProjectMonth = MakeProject(month, true);
            ProjectWeek  = MakeProject(week, true);

            ProjectNothingButYear  = MakeProject(year, false);
            ProjectNothingButMonth = MakeProject(month, false);
            ProjectNothingButWeek  = MakeProject(week, false);
        }
示例#21
0
 public static IKernel WithMongoEventsProvider(this IKernel kernel, string url, string database, string collection)
 {
     BsonSerializer.RegisterSerializer(typeof(decimal), new DecimalSerializer(BsonType.Decimal128));
     BsonSerializer.RegisterSerializer(typeof(decimal?), new NullableSerializer <decimal>(new DecimalSerializer(BsonType.Decimal128)));
     return(kernel.WithModule(new MongoEventsProviderModule(url, database, collection)));
 }
示例#22
0
 /// <summary>
 /// Set database initializer
 /// </summary>
 public virtual void SetDatabaseInitializer()
 {
     //BsonSerializer.RegisterSerializer<decimal>(new DecimalSerializer().WithRepresentation(BsonType.Double));
     BsonSerializer.RegisterSerializer(typeof(DateTime),
                                       new DateTimeSerializer(DateTimeKind.Utc));
 }
示例#23
0
        public void Configuration(IAppBuilder Builder)
        {
            ConfigureOAuth(Builder);

            var Configuration = new HttpConfiguration();
            var HTTPServer    = new HttpServer(Configuration);

            #region Custom Routing and WebAPI versionong
            Builder.UseWebApi(Configuration);

            // reporting api versions will return the headers "api-supported-versions" and "api-deprecated-versions"
            Configuration.AddApiVersioning(O => O.ReportApiVersions = true);



            Configuration.Routes.MapHttpRoute(
                "VersionedUrl",
                "api/{namespace}/{application}/v{apiVersion}/{module}/{controller}/{action}/{id}",
                defaults: new { id = RouteParameter.Optional },
                constraints: new { apiVersion = new ApiVersionRouteConstraint() });
            Configuration.Routes.MapHttpRoute(
                "DefaultApi",
                "api/{namespace}/{application}/v{apiVersion}/{module}/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional },
                constraints: new { apiVersion = new ApiVersionRouteConstraint() });
            Configuration.Routes.MapHttpRoute(
                "VersionedNoAppUrl",
                "api/{namespace}/v{apiVersion}/{module}/{controller}/{action}/{id}",
                defaults: new { id = RouteParameter.Optional },
                constraints: new { apiVersion = new ApiVersionRouteConstraint() });
            Configuration.Routes.MapHttpRoute(
                "DefaultApiNoApp",
                "api/{namespace}/v{apiVersion}/{module}/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional },
                constraints: new { apiVersion = new ApiVersionRouteConstraint() });
            Configuration.Routes.MapHttpRoute(
                "VersionedQueryString",
                "api/{namespace}/{application}/{module}/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional });
            Configuration.Routes.MapHttpRoute(
                "VersionedQueryStringWithAction",
                "api/{namespace}/{application}/{module}/{controller}/{action}/{id}",
                defaults: new { id = RouteParameter.Optional });



            Configuration.Services.Replace(typeof(IHttpControllerSelector), new NamespaceHttpControllerSelector(Configuration));
            #endregion

            #region Register DBContext, Service, Repository To Unity
            var Container = new UnityContainer();

            Container.RegisterType <RecDBMSSQLIDBFactory, RecDBMSSQLDBFactory>(new HierarchicalLifetimeManager());
            //Container.RegisterType<BookDBMongoDBIDBFactory, BookDBMongoDBDBFactory>(new HierarchicalLifetimeManager());


            //Container.RegisterType<BookDBOracleIDBFactory, BookDBOracleDBFactory>(new HierarchicalLifetimeManager());

            Container.RegisterTypes(
                AllClasses.FromAssemblies(typeof(RecDBRepository).Assembly)
                .Where(t => t.Name.EndsWith("Repository")),
                WithMappings.FromAllInterfaces);
            // Container.RegisterType<IRolesRepository, RolesRepository>(new InjectionConstructor("DeveloperCompetencyDBEntities"));

            Container.RegisterTypes(
                AllClasses.FromAssemblies(typeof(RecDBService).Assembly)
                .Where(t => t.Name.EndsWith("Service")),
                WithMappings.FromAllInterfaces);

            Configuration.DependencyResolver = new UnityResolver(Container);
            #endregion

            //MongoDB Datetime Converter
            BsonSerializer.RegisterSerializer(typeof(DateTime), DateTimeSerializer.UtcInstance);

            //Allow Cross Domain Access
            Builder.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
            Builder.UseWebApi(HTTPServer);
        }
示例#24
0
 static EventSubscriptions()
 {
     BsonSerializer.RegisterSerializer(typeof(MethodInfo), new MethodInfoSerializer());
     BsonSerializer.RegisterSerializer(typeof(Type), new TypeSerializer());
     BsonSerializer.RegisterSerializationProvider(new BsonSerializationProvider());
 }
示例#25
0
 static OffsetDateTimeSerializerTests()
 {
     BsonSerializer.RegisterSerializer(new OffsetDateTimeSerializer());
 }
示例#26
0
 public static void Init()
 {
     BsonSerializer.RegisterSerializer(new EnumSerializer <NumericType>(BsonType.String));
 }
示例#27
0
 public BaseMongoRepository()
 {
     this.MongoDbHandler = new MongoDbHandler <TEntity>();
     BsonSerializer.RegisterSerializer(typeof(DateTime), new DateTimeSerializer(DateTimeKind.Local));
 }
示例#28
0
 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);
 }
 public static void Init()
 {
     BsonSerializer.RegisterSerializer(typeof(MigrationVersion), new MigrationVersionSerializer());
 }
示例#30
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors();

            services.AddScoped <IMessage, Message>();

            var builder = services.BuildServiceProvider();

            AppSetting appSettings        = new AppSetting((IMessage)builder.GetRequiredService(typeof(IMessage)));
            var        appSettingsSection = Configuration.GetSection("Settings");

            appSettingsSection.Bind(appSettings);

            services.AddSingleton <MongoDBClient>(new MongoDBClient(appSettings.DBEndpoint, appSettings.DBName));

            services.AddSingleton <ISetting>(appSettings);

            BsonSerializer.RegisterSerializer(typeof(DateTime), DateTimeSerializer.LocalInstance);

            // jwt token authorize
            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(Encoding.ASCII.GetBytes(appSettings.ApplicationToken)),
                    ValidateIssuer           = false,
                    ValidateAudience         = false,
                    ClockSkew = TimeSpan.Zero
                };
            });

            services.AddControllers()
            .AddNewtonsoftJson(options => options.SerializerSettings.ContractResolver = new DefaultContractResolver());



            /// Add collections
            services.AddSingleton <IUserCollection, MongoUserCollection>();
            services.AddSingleton <IDeptReminderCollection, MongoDeptReminderCollection>();
            services.AddSingleton <ITransferCollection, MongoTransferCollection>();
            services.AddSingleton <ITransactionCollection, MongoTransactionCollection>();
            services.AddSingleton <ILinkingBankCollection, MongoLinkingBankCollection>();
            ///
            /// Add services
            services.AddSingleton <IContext, Context>();
            services.AddSingleton <IEmployeeService, EmployeeService>();
            services.AddSingleton <IUserService, UserService>();
            services.AddSingleton <IAccountService, AccountService>();
            services.AddSingleton <IDeptReminderService, DeptReminderService>();
            services.AddSingleton <ILinkingBankService, LinkingBankService>();
            services.AddTransient <IExternalBanking, ExternalBanking_BKTBank>();
            ///

            services.AddTransient <IEncrypt, Encrypt>();
        }