Beispiel #1
0
        private static void SetupSerialisationAndMapping()
        {
            if (BsonClassMap.GetRegisteredClassMaps().FirstOrDefault(p => p.ClassType == typeof(T)) == null)
            {
                BsonClassMap.RegisterClassMap <T>(cm =>
                {
                    cm.AutoMap();
                    cm.SetIgnoreExtraElements(true);
                    cm.SetIdMember(cm.GetMemberMap(c => c._recordId));
                });
            }

            var usedTypes = GetContainingTypes(typeof(T));

            foreach (var type in usedTypes)
            {
                var existing = BsonClassMap.GetRegisteredClassMaps().FirstOrDefault(p => p.ClassType == type);
                if (existing == null)
                {
                    var bsonMap = new BsonClassMap(type);
                    bsonMap.AutoMap();
                    bsonMap.SetIgnoreExtraElements(true);
                    BsonClassMap.RegisterClassMap(bsonMap);
                }
            }

            try
            {
                BsonSerializer.RegisterSerializer(typeof(UInt64), new UInt64Serializer(BsonType.Int64, new RepresentationConverter(true, false)));
                BsonSerializer.RegisterSerializer(typeof(UInt32), new UInt32Serializer(BsonType.Int64, new RepresentationConverter(true, false)));
                BsonSerializer.RegisterSerializer(DateTimeSerializer.LocalInstance);
                BsonSerializer.RegisterSerializer(typeof(float), new FloatTruncationSerializer());
            }
            catch (BsonSerializationException)
            {
                // swallow;
            }
        }
Beispiel #2
0
        public InventoryManager()
        {
            _activeInvsBeingManaged = new Dictionary <Client, KeyValuePair <IStorage, IStorage> >();

            #region Inventory Items

            BsonClassMap.RegisterClassMap <BagItem>();
            BsonClassMap.RegisterClassMap <Phone>();
            BsonClassMap.RegisterClassMap <Money>();
            BsonClassMap.RegisterClassMap <EngineParts>();
            BsonClassMap.RegisterClassMap <SprayPaint>();
            BsonClassMap.RegisterClassMap <Fish>();
            BsonClassMap.RegisterClassMap <RopeItem>();
            BsonClassMap.RegisterClassMap <RagsItem>();
            BsonClassMap.RegisterClassMap <SprunkItem>();
            BsonClassMap.RegisterClassMap <CheckItem>();
            BsonClassMap.RegisterClassMap <HuntingTag>();
            BsonClassMap.RegisterClassMap <AnimalItem>();
            BsonClassMap.RegisterClassMap <AmmoItem>();
            BsonClassMap.RegisterClassMap <ScubaItem>();
            BsonClassMap.RegisterClassMap <SupplyItem>();
            BsonClassMap.RegisterClassMap <IdentificationItem>();
            BsonClassMap.RegisterClassMap <DrivingLicenseItem>();
            BsonClassMap.RegisterClassMap <FishingRod>();
            BsonClassMap.RegisterClassMap <Cocaine>();
            BsonClassMap.RegisterClassMap <Heroin>();
            BsonClassMap.RegisterClassMap <Speed>();
            BsonClassMap.RegisterClassMap <Weed>();
            BsonClassMap.RegisterClassMap <Meth>();
            BsonClassMap.RegisterClassMap <Crowbar>();
            BsonClassMap.RegisterClassMap <WeaponCase>();
            BsonClassMap.RegisterClassMap <Weapon>();

            #endregion

            Event.OnClientEventTrigger     += API_onClientEventTrigger;
            CharacterMenu.OnCharacterLogin += CharacterMenu_OnCharacterLogin;
        }
Beispiel #3
0
        public DataContext(AppSettings settings)
        {
            var client = new MongoClient(settings.Db.ConnectionString);

            BsonClassMap.RegisterClassMap <User>(cm =>
            {
                cm.AutoMap();
                cm.MapIdMember(c => c.Id)
                .SetIdGenerator(StringObjectIdGenerator.Instance)
                .SetSerializer(new StringSerializer(BsonType.ObjectId));
            });

            BsonClassMap.RegisterClassMap <Alert>(cm =>
            {
                cm.AutoMap();
                cm.MapIdMember(c => c.Id)
                .SetIdGenerator(StringObjectIdGenerator.Instance)
                .SetSerializer(new StringSerializer(BsonType.ObjectId));
            });

            BsonClassMap.RegisterClassMap <Asic>(cm =>
            {
                cm.AutoMap();
                cm.MapIdMember(c => c.Id)
                .SetIdGenerator(StringObjectIdGenerator.Instance)
                .SetSerializer(new StringSerializer(BsonType.ObjectId));
            });

            BsonClassMap.RegisterClassMap <HardwareCost>(cm =>
            {
                cm.AutoMap();
                cm.MapIdMember(c => c.Id)
                .SetIdGenerator(StringObjectIdGenerator.Instance)
                .SetSerializer(new StringSerializer(BsonType.ObjectId));
            });

            _database = client.GetDatabase(settings.Db.DatabaseName);
        }
Beispiel #4
0
        public static void RegisterClassMaps()
        {
            BsonClassMap.RegisterClassMap <WorkflowMetadata>(cm => WorkflowsClassMap.Register(cm));
            BsonClassMap.RegisterClassMap <Workflow>(seq => WorkflowsClassMap.Register(seq));
            BsonClassMap.RegisterClassMap <WorkflowTemplate>(seq => WorkflowTemplatesClassMap.Register(seq));
            BsonClassMap.RegisterClassMap <StepTemplate>(cm => StepTemplatesClassMap.Register(cm));
            BsonClassMap.RegisterClassMap <Journal>(je => JournalsClassMap.Register(je));
            BsonClassMap.RegisterClassMap <Step>(cm => StepsClassMap.Register(cm));
            BsonClassMap.RegisterClassMap <StepLog>(cm => StepLogsClassMap.Register(cm));
            BsonClassMap.RegisterClassMap <User>(u => UsersClassMap.Register(u));
            BsonClassMap.RegisterClassMap <GlobalValue>(gv => GlobalValuesClassMap.Register(gv));
            BsonClassMap.RegisterClassMap <TrackedEntity>(gv => TrackedEntitiesClassMap.Register(gv));
            BsonClassMap.RegisterClassMap <Condition>(gv => ConditionsClassMap.Register(gv));
            BsonClassMap.RegisterClassMap <LogEntry>();
            BsonClassMap.RegisterClassMap <NodeInformation>();
            BsonClassMap.RegisterClassMap <Index>();
            BsonClassMap.RegisterClassMap <BaseTask>();
            BsonClassMap.RegisterClassMap <Lock>();
            BsonClassMap.RegisterClassMap <LogicBlockLock>();
            BsonClassMap.RegisterClassMap <BaseCommand>(gv => BaseCommandsClassMap.Register(gv));
            BsonClassMap.RegisterClassMap <NodeStorage <CindiClusterState> >(gv => NodeStorageClassMap.Register(gv));
            BsonClassMap.RegisterClassMap <Update>(gv => UpdateClassMap.Register(gv));
            BsonClassMap.RegisterClassMap <ShardMetadata>(lsm => LocalShardMetaDataClassMap.Register(lsm));
            BsonClassMap.RegisterClassMap <CindiClusterState>(cs => CindiClusterStateClassMap.Register(cs));
            BsonClassMap.RegisterClassMap <ShardWriteOperation>(cs => ShardOperationClassMap.Register(cs));
            BsonClassMap.RegisterClassMap <BaseState>(cs => BaseStateClassMap.Register(cs));
            BsonClassMap.RegisterClassMap <JournalEntry>(cs => JournalEntriesClassMap.Register(cs));
            BsonClassMap.RegisterClassMap <Domain.Entities.Metrics.Metric>(cs => MetricsClassMap.Register(cs));
            BsonClassMap.RegisterClassMap <MetricTick>(cs => MetricTickClassMap.Register(cs));
            BsonClassMap.RegisterClassMap <BotKey>(cs => BotKeyClassMap.Register(cs));
            BsonClassMap.RegisterClassMap <ExecutionTemplate>(cs => ExecutionTemplateClassMap.Register(cs));
            BsonClassMap.RegisterClassMap <ExecutionSchedule>(cs => ExecutionScheduleClassMap.Register(cs));
            //BsonSerializer.RegisterSerializer(typeof(Update), new UpdateSerializer());

            /*BsonSerializer.RegisterSerializer(typeof(BaseCommand), new BaseCommandSerializer());
             * BsonSerializer.RegisterSerializer(typeof(NodeStorage), new NodeStorageSerializer());
             * BsonSerializer.RegisterSerializer(typeof(Update), new UpdateSerializer());*/
        }
Beispiel #5
0
        public void ApplyReplaceArray(string path, object value, bool isArray)
        {
            var converter = Helper.GetConverter();
            var doc       = new JsonPatchDocument <UserEntity>();

            BsonClassMap.RegisterClassMap <UserEntity>();
            doc.Operations.Add(new Operation <UserEntity>
            {
                from  = string.Empty,
                op    = "replace",
                path  = path,
                value = isArray ? JArray.Parse((string)value) : value
            });
            var result = converter.Convert <UserEntity, UserEntity>(doc);

            using (var coll = Helper.GetCollection <UserEntity>())
            {
                var filtered = Builders <UserEntity> .Filter.And(result.Filters);

                var updates = Builders <UserEntity> .Update.Combine(result.Updates);

                coll.Collection.InsertOne(new UserEntity {
                    Id = Guid.NewGuid(), Dogs = new []
                    {
                        new Dog {
                            Name = "Don"
                        }
                    }
                });
                var updateResult = coll.Collection.UpdateOne(filtered, updates);
                Assert.True(updateResult.ModifiedCount > 0);
                var entities = coll.Collection.Find("{}").ToList();
                Assert.True(entities.Any());
                Assert.NotNull(entities[0].Dogs);
                Assert.True(entities[0].Dogs.Any());
                Assert.True(entities[0].Dogs[0].Name != "Don");
            }
        }
Beispiel #6
0
        private void LoadDataFromDB()
        {
            // Create server settings to pass connection string, timeout, etc.
            MongoServerSettings settings = new MongoServerSettings();

            settings.Server = new MongoServerAddress("localhost", 27017);
            //// Create server object to communicate with our server
            MongoServer server = new MongoServer(settings);

            if (!BsonClassMap.IsClassMapRegistered(typeof(IPerson)))
            {
                BsonClassMap.RegisterClassMap <IPerson>(cm =>
                {
                    cm.AutoMap();
                    cm.SetIdMember(cm.GetMemberMap(c => c.registrationNumber));
                }
                                                        );
                // Console.WriteLine("Registering Class");
            }

            if (!BsonClassMap.IsClassMapRegistered(typeof(SourceAFIS.Simple.Fingerprint)))
            {
                BsonClassMap.RegisterClassMap <SourceAFIS.Simple.Fingerprint>(cm =>
                {
                    cm.MapProperty <byte[, ]>(c => c.Image);
                    cm.MapProperty <byte[]>(c => c.Template);
                    cm.UnmapField(c => c.AsBitmap);
                    cm.MapProperty <byte[]>(c => c.AsImageData);
                    cm.MapProperty <byte[]>(c => c.AsIsoTemplate);
                    cm.UnmapField(c => c.AsXmlTemplate);
                }
                                                                              );
            }

            var database = server.GetDatabase("AfisDB");

            dbrecords = database.GetCollection <IPerson>("IPerson");
        }
        private static bool Map()
        {
            if (BsonClassMap.IsClassMapRegistered(typeof(Entity)))
            {
                return(false);
            }

            try
            {
                BsonClassMap.RegisterClassMap <Entity>(cm =>
                {
                    cm.SetIsRootClass(true);
                    cm.MapIdProperty(x => x.Id);
                });

                BsonClassMap.RegisterClassMap <WorkflowDefinition>(cm =>
                {
                    cm.MapProperty(p => p.Variables).SetSerializer(VariablesSerializer.Instance);
                    cm.AutoMap();
                });

                BsonClassMap.RegisterClassMap <WorkflowInstance>(cm =>
                {
                    cm.MapProperty(p => p.Variables).SetSerializer(VariablesSerializer.Instance);
                    cm.AutoMap();
                });

                BsonClassMap.RegisterClassMap <Bookmark>(cm => cm.AutoMap());
                BsonClassMap.RegisterClassMap <WorkflowExecutionLogRecord>(cm => cm.AutoMap());
                BsonClassMap.RegisterClassMap <WorkflowOutputReference>(cm => cm.AutoMap());
            }
            catch (Exception)
            {
                return(false);
            }

            return(true);
        }
Beispiel #8
0
        /// <summary>
        /// Register MongoDB mappings
        /// </summary>
        public static void RegisterMongoDBMappings()
        {
            //BsonSerializer.RegisterSerializer(new DecimalSerializer(BsonType.Decimal128));
            //BsonSerializer.RegisterSerializer(typeof(double?), new NullableSerializer<double>(new DecimalSerializer(BsonType.Decimal128)));
            BsonSerializer.RegisterSerializer(typeof(DateTime), new BsonUtcDateTimeSerializer());

            BsonSerializer.RegisterSerializer(typeof(Dictionary <int, int>),
                                              new DictionaryInterfaceImplementerSerializer <Dictionary <int, int> >(DictionaryRepresentation.ArrayOfArrays));

            //global set an equivalent of [BsonIgnoreExtraElements] for every Domain Model
            var cp = new ConventionPack {
                new IgnoreExtraElementsConvention(true)
            };

            ConventionRegistry.Register("ApplicationConventions", cp, t => true);


            BsonClassMap.RegisterClassMap <Media.Download>(cm =>
            {
                cm.AutoMap();
                cm.UnmapMember(m => m.DownloadBinary);
            });
        }
Beispiel #9
0
        public static void Configure()
        {
            OneTimeRunner.Run(() =>
            {
                BsonClassMap.RegisterClassMap <IdentityUser>(map =>
                {
                    map.AutoMap();
                    map.ConfigureExtraProperties();
                });

                BsonClassMap.RegisterClassMap <IdentityRole>(map =>
                {
                    map.AutoMap();
                    map.ConfigureExtraProperties();
                });

                BsonClassMap.RegisterClassMap <IdentityClaimType>(map =>
                {
                    map.AutoMap();
                    map.ConfigureExtraProperties();
                });
            });
        }
Beispiel #10
0
        private void MapClasses()
        {
            // Vamos criar uma convenção para que o mongo trabalhe com CamelCase
            var conventionPack = new ConventionPack {
                new CamelCaseElementNameConvention()
            };

            ConventionRegistry.Register("camelCase", conventionPack, t => true);

            // E caso não tenhamos nada mapeado,
            if (!BsonClassMap.IsClassMapRegistered(typeof(Infectado)))
            {
                BsonClassMap.RegisterClassMap <Infectado>(i =>
                {
                    /*
                     *  Aqui, vamos mapear no banco, com o mesmo nome e tipo da classe que fizemos.
                     */
                    i.AutoMap();
                    // Para caso você apartir de hoje tenha uma nova coluna no documento, e o banco não estranhe...
                    i.SetIgnoreExtraElements(true);
                });
            }
        }
 /// <summary>
 /// Configure Classes to ignore Extra Elements (e.g. _Id) when deserializing
 /// As we are using "IdentityServer4.Models" we cannot add something like "[BsonIgnore]"
 /// </summary>
 private static void ConfigureMongoDriver2IgnoreExtraElements()
 {
     BsonClassMap.RegisterClassMap <Client>(cm =>
     {
         cm.AutoMap();
         cm.SetIgnoreExtraElements(true);
     });
     BsonClassMap.RegisterClassMap <IdentityResource>(cm =>
     {
         cm.AutoMap();
         cm.SetIgnoreExtraElements(true);
     });
     BsonClassMap.RegisterClassMap <ApiResource>(cm =>
     {
         cm.AutoMap();
         cm.SetIgnoreExtraElements(true);
     });
     BsonClassMap.RegisterClassMap <PersistedGrant>(cm =>
     {
         cm.AutoMap();
         cm.SetIgnoreExtraElements(true);
     });
 }
Beispiel #12
0
        public void Map()
        {
            BsonClassMap.RegisterClassMap <Base>(map =>
            {
                map.AutoMap();
                map.GetMemberMap(x => x.CreatedOn).SetSerializer(new DateTimeSerializer(DateTimeKind.Utc));
                map.IdMemberMap.SetIdGenerator(StringObjectIdGenerator.Instance).SetSerializer(new StringSerializer(BsonType.ObjectId));
                map.MapExtraElementsMember(x => x.ExtraElement);
            });
            BsonClassMap.RegisterClassMap <Application>(map =>
            {
                map.AutoMap();
            });

            var pack = new ConventionPack();

            pack.Add(new CamelCaseElementNameConvention());

            ConventionRegistry.Register(
                "My Custom Conventions",
                pack,
                t => t.FullName.StartsWith("MyNamespace."));
        }
Beispiel #13
0
        public DbContext(
            string connectionString,
            string database,
            ILogger <DbContext> logger)
        {
            _logger = logger;

            _logger.LogInformation("Connection to {@mongoUrl} at {@database}", connectionString, database);

            var mongoUrl = new MongoUrl(connectionString);

            Client   = new MongoClient(mongoUrl);
            Database = Client.GetDatabase(database);

            if (!BsonClassMap.IsClassMapRegistered(typeof(ShortUrl)))
            {
                BsonClassMap.RegisterClassMap <ShortUrl>(cm =>
                {
                    cm.MapIdProperty(c => c.Id);
                    cm.MapProperty(c => c.FullUrl);
                });
            }
        }
Beispiel #14
0
        public static void Setup()
        {
            BsonClassMap.RegisterClassMap <ServiceType>(cm =>
            {
                cm.AutoMap();
                cm.SetIsRootClass(true);
            });
            BsonClassMap.RegisterClassMap <ServiceType.DeliveryType>();
            BsonClassMap.RegisterClassMap <ServiceType.InRestaurantType>();
            BsonClassMap.RegisterClassMap <ServiceType.TakeOutType>();

            BsonClassMap.RegisterClassMap <Pizza>(cm =>
            {
                cm.AutoMap();
                cm.GetMemberMap(c => c.Toppings).SetElementName("Topping");
            });

            BsonClassMap.RegisterClassMap <Order>(cm =>
            {
                cm.AutoMap();
                cm.SetIgnoreExtraElements(true);
            });
        }
        private static void DefineClassMaps()
        {
            if (!BsonClassMap.IsClassMapRegistered(typeof(Project)))
            {
                BsonClassMap.RegisterClassMap <Project>(p =>
                {
                    p.AutoMap();

                    // explict version
                    p.MapProperty(c => c.Id)
                    .SetIdGenerator(StringObjectIdGenerator.Instance)
                    .SetSerializer(new StringSerializer(BsonType.ObjectId));

                    // short version
                    //p.IdMemberMap.SetSerializer(new StringSerializer(BsonType.ObjectId));

                    p.GetMemberMap(c => c.StartDate).SetSerializer(new DateTimeSerializer(true));
                    p.GetMemberMap(c => c.EndDate).SetSerializer(new DateTimeSerializer(true));

                    p.UnmapMember(c => c.Fee);
                });
            }
        }
Beispiel #16
0
        public static IRepository BuildMongoDbRepository(string url, bool reload = true)
        {
            var mongoUrl = new MongoUrl(url);
            var db       = new MongoClient(mongoUrl).GetServer();

            if (reload)
            {
                if (db.DatabaseExists(mongoUrl.DatabaseName))
                {
                    db.DropDatabase(mongoUrl.DatabaseName);
                }
            }

            if (!BsonClassMap.IsClassMapRegistered(typeof(IncEntityBase)))
            {
                BsonClassMap.RegisterClassMap <IncEntityBase>(map => map.UnmapProperty(r => r.Id));
            }
            var session = new MongoDatabaseDisposable(db.GetDatabase(mongoUrl.DatabaseName));
            var buildMongoDbRepository = new MongoDbRepository(/*Pleasure.MockStrictAsObject<IMongoDbSessionFactory>(mock => mock.Setup(r => r.GetCurrent()).Returns(session))*/);

            buildMongoDbRepository.SetProvider(session);
            return(buildMongoDbRepository);
        }
Beispiel #17
0
        public static void AddMongoDb(this IServiceCollection services, Action <MongoSettings> settingsAction)
        {
            services.AddScoped <IMongoClient, MongoClient>();
            services.AddScoped <IMongoContext, MongoDbContext>();
            services.AddScoped <IUnitOfWork, UnitOfWork>();

            var mongoSettings = new MongoSettings();

            settingsAction(mongoSettings);
            services.AddSingleton(mongoSettings);

            if (BsonClassMap.IsClassMapRegistered(typeof(DomainEntity)))
            {
                return;
            }

            BsonClassMap.RegisterClassMap <DomainEntity>(cm =>
            {
                cm.AutoMap();
                cm.SetIsRootClass(true);
                cm.UnmapMember(x => x.ValidationResult);
            });
        }
 public virtual void RegisterClass()
 {
     m_Wheels    = new Wheel[1];
     m_Wheels[0] = new Wheel(0);
     m_Wheels[0].RegisterClass();
     m_PowerSource.RegisterClass();
     m_OwnerDetailes = new VehicleOwner();
     m_OwnerDetailes.RegisterClass();
     if (!BsonClassMap.IsClassMapRegistered(typeof(Vehicle)))
     {
         BsonClassMap.RegisterClassMap <Vehicle>(cm =>
         {
             cm.SetIdMember(cm.MapField(c => c.r_LicensePlateNumber).SetElementName("LicensePlateNumber"));
             cm.MapField(c => c.m_ModelName).SetElementName("ModelName");
             cm.MapField(c => c.m_OwnerDetailes).SetElementName("OwnerDetailes");
             cm.MapField(c => c.m_PercentageOfEnergy).SetElementName("PercentageOfEnergy");
             cm.MapField(c => c.m_PowerSource).SetElementName("PowerSource");
             cm.MapField(c => c.m_Status).SetElementName("Status").SetSerializer(new EnumSerializer <eRepairStatus>(BsonType.String));
             cm.MapField(c => c.m_Wheels).SetElementName("Wheels");
             cm.MapField(c => c.m_TimeOfEnteringToGarage).SetElementName("TimeOfEnteringToGarage");
         });
     }
 }
Beispiel #19
0
        static MongoDBDataStorageProvider()
        {
            ConventionPack pack = new ConventionPack
            {
                new EnumRepresentationConvention(BsonType.String)
            };

            ConventionRegistry.Register("EnumStringConvention", pack, t => true);

            pack = new ConventionPack
            {
                new IgnoreIfNullConvention(true)
            };
            ConventionRegistry.Register("IgnoreNull", pack, t => true);

            BsonClassMap.RegisterClassMap <AuditEvent>(cm =>
            {
                cm.AutoMap();
                cm.MapExtraElementsField(c => c.CustomFields);
            });

            BsonSerializer.RegisterSerializer(typeof(FieldValueChange), new FieldValueChangeSerializer());
        }
Beispiel #20
0
 public DocumentTypeBuilder <T> Map(Action <BsonClassMap <T> > bsonClassMapAction)
 {
     try
     {
         if (!BsonClassMap.IsClassMapRegistered(typeof(T)))
         {
             BsonClassMap.RegisterClassMap <T>(bsonClassMapAction);
         }
         return(this);
     }
     catch (ArgumentException ex)
     {
         if (ex.Message.Contains("An item with the same key has already been added"))
         {
             return(this);
         }
         throw;
     }
     catch (Exception)
     {
         throw;
     }
 }
Beispiel #21
0
        static MongoStorage()
        {
            // We will register all our Dto classes with the default conventions.
            // By doing this, we can safely use strings for referencing class
            // property names with risking to have a mismatch with any convention
            // used by bson serializer.
            var conventionPack = new ConventionPack();

            conventionPack.Append(DefaultConventionPack.Instance);
            conventionPack.Append(AttributeConventionPack.Instance);
            var conventionRunner = new ConventionRunner(conventionPack);

            var assembly  = typeof(MongoStorage).GetTypeInfo().Assembly;
            var classMaps = assembly.DefinedTypes
                            .Where(t => t.IsClass && !t.IsAbstract && !t.IsGenericType && t.Namespace == "Hangfire.Mongo.Dto")
                            .Select(t => new BsonClassMap(t.AsType()));

            foreach (var classMap in classMaps)
            {
                conventionRunner.Apply(classMap);
                BsonClassMap.RegisterClassMap(classMap);
            }
        }
        public static void ProductMap()
        {
            if (!BsonClassMap.IsClassMapRegistered(typeof(Product)))
            {
                BsonClassMap.RegisterClassMap <Product>(map =>
                {
                    map.MapIdProperty(x => x.ProductId)
                    .SetIdGenerator(MongoDBInt32IdGenerator.Instance)
                    .SetSerializer(new StringSerializer(BsonType.String));

                    map.MapProperty(x => x.ProductId);
                    map.MapProperty(x => x.ProductName);
                    map.MapProperty(x => x.SupplierId);
                    map.MapProperty(x => x.CategoryId);
                    map.MapProperty(x => x.QuantityPerUnit);
                    map.MapProperty(x => x.UnitPrice);
                    map.MapProperty(x => x.UnitsInStock);
                    map.MapProperty(x => x.UnitsOnOrder);
                    map.MapProperty(x => x.ReorderLevel);
                    map.MapProperty(x => x.Discontinued);
                });
            }
        }
Beispiel #23
0
        private void InitMappings()
        {
            BsonClassMap.RegisterClassMap <WeatherReport>(cm =>
            {
                cm.MapMember(c => c.DraughtDays);
                cm.MapMember(c => c.MaxIntensityDay);
                cm.MapMember(c => c.MaxRainIntensity);
                cm.MapMember(c => c.RainDays);
                cm.MapMember(c => c.OptimumDays);
            });

            BsonClassMap.RegisterClassMap <Weather>(cm =>
            {
                cm.MapMember(c => c.Type).SetSerializer(new EnumSerializer <Weather.WeatherType>(BsonType.String));
                cm.MapMember(c => c.RainIntensity);
            });

            BsonClassMap.RegisterClassMap <DayReport>(cm =>
            {
                cm.MapMember(c => c.Day);
                cm.MapMember(c => c.Weather);
            });
        }
 public static IServiceCollection AddMongoDB(this IServiceCollection services, string connectionString)
 {
     services.AddSingleton <IMongoDatabase>(x =>
     {
         BsonDefaults.GuidRepresentation = GuidRepresentation.Standard;
         BsonClassMap.RegisterClassMap <Enumeration>(cm =>
         {
             cm.SetIsRootClass(true);
             cm.MapMember(m => m.Id);
             cm.MapMember(m => m.Name);
         });
         BsonClassMap.RegisterClassMap <SeatState>(cm =>
         {
             cm.MapCreator(c => new SeatState(c.Id, c.Name));
         });
         var client   = new MongoClient(connectionString);
         var database = client.GetDatabase("CqrsMovie_Seats_ReadModel"); //Best to inject a class with all parameter and not being coupled like this
         return(database);
     });
     services.AddScoped <IPersister, Persister>();
     services.AddSingleton <IEventStorePositionRepository>(x => new EventStorePositionRepository(x.GetService <ILogger <EventStorePositionRepository> >(), connectionString));
     return(services);
 }
Beispiel #25
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            BsonClassMap.RegisterClassMap <Blog>(x =>
            {
                x.AutoMap();
                x.SetIgnoreExtraElements(true);
                x.MapIdMember(y => y.Id);
            });

            BsonClassMap.RegisterClassMap <Post>(x =>
            {
                x.AutoMap();
                x.SetIgnoreExtraElements(true);
            });

            BsonClassMap.RegisterClassMap <Author>(x =>
            {
                x.AutoMap();
                x.SetIgnoreExtraElements(true);
            });

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        }
Beispiel #26
0
        public static void RegisterAll()
        {
            BsonClassMap.RegisterClassMap <Shape>(c =>
            {
                c.SetDiscriminatorIsRequired(true);
                c.SetIsRootClass(true);
                c.AddKnownType(typeof(Cuboid));
            });

            BsonSerializer.RegisterSerializer(new SlotSerializer());
            BsonSerializer.RegisterSerializer(new DependencyObjectStateSerializer());
            BsonSerializer.RegisterSerializer(new BlockChunkPosSerializer());
            BsonSerializer.RegisterSerializer(new BlockWorldPosSerializer());
            BsonSerializer.RegisterSerializer(new ChunkWorldPosSerializer());
            BsonSerializer.RegisterSerializer(new BlockSectionPosSerializer());
            BsonSerializer.RegisterSerializer(new EntityWorldPosSerializer());
            BsonSerializer.RegisterSerializer(new EntityChunkPosSerializer());
            BsonSerializer.RegisterSerializer(new Point3dSerializer());
            BsonSerializer.RegisterSerializer(new SizeSerializer());
            BsonSerializer.RegisterSerializer(new ChunkColumnCompactStorageSerializer());
            BsonSerializer.RegisterSerializer(new ChunkSectionCompactStorageSerializer());
            BsonSerializer.RegisterSerializer(new GameModeSerializer());
        }
Beispiel #27
0
        private void RegisterIdGenerator()
        {
            BsonSerializer.RegisterIdGenerator(typeof(string), StringObjectIdGenerator.Instance);
            BsonSerializer.RegisterSerializer(typeof(DateTime), DateTimeStringSerializer.Instance);

            BsonClassMap.RegisterClassMap <NodeBase>(entity =>
            {
                entity.AutoMap();
                //entity.UnmapProperty(c => c.ChangeSetId);
                entity.UnmapProperty(c => c.Srid);
                entity.UnmapProperty(c => c.User);
                entity.UnmapProperty(c => c.UserId);
                entity.UnmapProperty(c => c.Visible);
                //entity.UnmapProperty(c => c.TimeStamp);
            });

            BsonClassMap.RegisterClassMap <Node>(entity =>
            {
                entity.AutoMap();
                entity.UnmapProperty(c => c.Latitude);
                entity.UnmapProperty(c => c.Longtitude);
            });
        }
Beispiel #28
0
        private static void Map()
        {
            if (BsonClassMap.GetRegisteredClassMaps().Any())
            {
                return;
            }

            foreach (var type in TyperConfigurarion.Typers)
            {
                var map = new BsonClassMap(type);
                map.AutoMap();
                map.SetIsRootClass(true);

                //map.
                //map.IdMemberMap.SetIdGenerator(BsonObjectIdGenerator.Instance);
                //map.IdMemberMap.SetIdGenerator()
                BsonClassMap.RegisterClassMap(map);

                //type.Assembly.GetTypes()
                //    .Where(type => featureType.IsAssignableFrom(type)).ToList()
                //    .ForEach(type => cm.AddKnownType(type));
            }
        }
        public MongoResponseCache(string connectionString)
        {
            BsonSerializer.RegisterDiscriminatorConvention(typeof(Response), new TypeDiscriminatorConvention());

            BsonClassMap.RegisterClassMap <Response>(cm =>
            {
                cm.AutoMap();
                cm.MapProperty(x => x.Type).SetRepresentation(BsonType.String);
            });

            BsonClassMap.RegisterClassMap <Error>();
            BsonClassMap.RegisterClassMap <Link>();
            BsonClassMap.RegisterClassMap <Photo>();
            BsonClassMap.RegisterClassMap <Rich>();
            BsonClassMap.RegisterClassMap <Video>();

            var url      = MongoUrl.Create(connectionString);
            var client   = new MongoClient(url);
            var server   = client.GetServer();
            var database = server.GetDatabase(url.DatabaseName);

            _collection = database.GetCollection <MongoCacheItem>("embedly");
        }
        public MongoDbContextModel Build()
        {
            lock (SyncObj)
            {
                var entityModels = _entityModelBuilders
                                   .Select(x => x.Value)
                                   .Cast <IMongoEntityModel>()
                                   .ToImmutableDictionary(x => x.EntityType, x => x);

                var baseClasses = new List <Type>();

                foreach (var entityModel in entityModels.Values)
                {
                    var map = entityModel.As <IHasBsonClassMap>().GetMap();
                    if (!BsonClassMap.IsClassMapRegistered(map.ClassType))
                    {
                        BsonClassMap.RegisterClassMap(map);
                    }

                    baseClasses.AddRange(entityModel.EntityType.GetBaseClasses(includeObject: false));
                }

                baseClasses = baseClasses.Distinct().ToList();

                foreach (var baseClass in baseClasses)
                {
                    if (!BsonClassMap.IsClassMapRegistered(baseClass))
                    {
                        var map = new BsonClassMap(baseClass);
                        map.ConfigurePlusConventions();
                        BsonClassMap.RegisterClassMap(map);
                    }
                }

                return(new MongoDbContextModel(entityModels));
            }
        }