public MongoContext() { string connectionString = ConfigurationManager.ConnectionStrings["MongoDb"].ConnectionString; var connection = new MongoUrlBuilder(connectionString); var client = new MongoClient(connectionString); _database = client.GetDatabase(connection.DatabaseName); List <BsonClassMap> mapps = BsonClassMap.GetRegisteredClassMaps().ToList(); if (mapps.All(m => m.GetType() != typeof(CategoryConfiguration))) { BsonClassMap.RegisterClassMap(new CategoryConfiguration()); } if (mapps.All(m => m.GetType() != typeof(SupplierConfiguration))) { BsonClassMap.RegisterClassMap(new SupplierConfiguration()); } if (mapps.All(m => m.GetType() != typeof(GameConfiguration))) { BsonClassMap.RegisterClassMap(new GameConfiguration()); } }
public void ConfigureCollection_SetDifferentSettingsToCollection_CollectionConfiguredSuccessfully() { // Arrange var mongoDatabaseBuilder = new MongoDatabaseBuilder(_mongoOptions); // Act mongoDatabaseBuilder.ConfigureCollection(new FooCollectionConfiguration()); MongoDbContextData result = mongoDatabaseBuilder.Build(); // Assert IMongoCollection <Foo> collection = result.GetCollection <Foo>(); IEnumerable <BsonClassMap> classMaps = BsonClassMap.GetRegisteredClassMaps(); Snapshot.Match(new { CollectionName = collection.CollectionNamespace.CollectionName, Settings = collection.Settings, Indexes = collection.Indexes.List().ToList(), ClassMaps = classMaps.Select(map => new { Name = map.Discriminator, IdMemberMap = new { map.IdMemberMap?.ElementName, map.IdMemberMap?.MemberName }, AllMemberMaps = map.AllMemberMaps.Select(amm => new { amm.ElementName, amm.MemberName }), IgnoreExtraElements = map.IgnoreExtraElements }) }); }
private void InitialiseClassMap() { MappingLock.EnterUpgradeableReadLock(); try { //For reasons unknown to me, you can't just call "BsonClassMap.LookupClassMap" as that "freezes" the class map //Instead, you must do the lookup and initial creation yourself. var classMaps = BsonClassMap.GetRegisteredClassMaps(); ClassMap = classMaps.Where(cm => cm.ClassType == EntityType).FirstOrDefault(); if (ClassMap == null) { MappingLock.EnterWriteLock(); try { ClassMap = new BsonClassMap(EntityType); ClassMap.AutoMap(); BsonClassMap.RegisterClassMap(ClassMap); foreach (var processor in DefaultMappingPack.Instance.Processors) { processor.ApplyMapping(EntityType, ClassMap); } } finally { MappingLock.ExitWriteLock(); } } } finally { MappingLock.ExitUpgradeableReadLock(); } }
/// <summary> Initializes a new instance of the MongoDbSagaRepository class. </summary> /// <exception cref="ArgumentNullException"> Thrown when one or more required arguments are null. </exception> /// <param name="database"> The database. </param> public MongoDbStateMachineSagaRepository(MongoDatabase database) : base(database) { if (Log == null) { Log = Logger.Get(typeof(MongoDbStateMachineSagaRepository <TSaga>).ToFriendlyName()); } BsonClassMap.RegisterClassMap <StateMachine <TSaga> >( cm => { cm.MapField("_currentState").SetSerializer(new StateSerializer <TSaga>()); cm.SetIsRootClass(true); }); BsonClassMap.RegisterClassMap <SagaStateMachine <TSaga> >(); if (BsonClassMap.IsClassMapRegistered(typeof(TSaga))) { var map = BsonClassMap.GetRegisteredClassMaps().First(c => c.ClassType == typeof(TSaga)).CastAs <BsonClassMap <TSaga> >(); map.UnmapProperty(s => s.Bus); } else { BsonClassMap.RegisterClassMap <TSaga>( cm => { cm.AutoMap(); cm.MapIdField(s => s.CorrelationId); cm.MapIdMember(s => s.CorrelationId); cm.MapIdProperty(s => s.CorrelationId); cm.UnmapProperty(s => s.Bus); }); } }
public void TestGetRegisteredClassMaps() { // this unit test can only be run once (per process) if (__firstTime) { Assert.IsFalse(BsonClassMap.IsClassMapRegistered(typeof(C))); Assert.IsFalse(BsonClassMap.IsClassMapRegistered(typeof(D))); var classMaps = BsonClassMap.GetRegisteredClassMaps(); var classMapTypes = classMaps.Select(x => x.ClassType).ToList(); Assert.IsFalse(classMapTypes.Contains(typeof(C))); Assert.IsFalse(classMapTypes.Contains(typeof(D))); BsonClassMap.RegisterClassMap <C>(cm => cm.AutoMap()); BsonClassMap.RegisterClassMap <D>(cm => cm.AutoMap()); Assert.IsTrue(BsonClassMap.IsClassMapRegistered(typeof(C))); Assert.IsTrue(BsonClassMap.IsClassMapRegistered(typeof(D))); classMaps = BsonClassMap.GetRegisteredClassMaps(); classMapTypes = classMaps.Select(x => x.ClassType).ToList(); Assert.IsTrue(classMapTypes.Contains(typeof(C))); Assert.IsTrue(classMapTypes.Contains(typeof(D))); __firstTime = false; } }
private void ConfigureBsonClassMaps() { var listOfClassMapsRegistered = BsonClassMap.GetRegisteredClassMaps(); listOfClassMapsRegistered = BsonClassMap.GetRegisteredClassMaps(); var testIntSequenceCollection = Client.GetDatabase(DefaultTestDatabaseName).GetCollection <IntSequenceCounterEntity>(DefaultTestCollectionForIntSequences); var intSequenceCounterRepository = new IntSequenceCounterRepository(testIntSequenceCollection); var intSequenceCounterGenerator = new IntSequenceCounterGenerator(intSequenceCounterRepository); BsonSerializer.RegisterIdGenerator(typeof(int), intSequenceCounterGenerator); var classMap = BsonClassMap.LookupClassMap(typeof(SampleEntityWithIntId)); /* * if (!BsonClassMap.IsClassMapRegistered(typeof(SampleEntityWithIntId))) * { * BsonClassMap.RegisterClassMap<SampleEntityWithIntId>(cm => * { * cm.AutoMap(); * cm.SetIsRootClass(true); * cm.SetIgnoreExtraElements(true); * cm.SetIdMember(cm.GetMemberMap(c => c.Id)); * cm.MapProperty(p => p.Id).SetIdGenerator(intSequenceCounterGenerator); * }); * } */ }
private static Type LookupType(Type nominalType, string typeHint) { Type type = Type.GetType(typeHint); if (type == null) { type = nominalType.Assembly .GetTypes() .FirstOrDefault(t => t.FullName?.EndsWith(typeHint) ?? false); } if (type == null) { type = TypeNameDiscriminator.GetActualType(typeHint); } if (type == null) { type = BsonClassMap .GetRegisteredClassMaps() .SelectMany(x => x.AllMemberMaps) .Where(x => x.MemberType.FullName?.EndsWith(typeHint) ?? false) .Select(x => x.MemberType) .FirstOrDefault(); } if (type != null) { return(type); } throw new InvalidOperationException($"Could not find type for {typeHint}"); }
static Dictionary <Type, BsonClassMap> GetClassMap() { var cm = BsonClassMap.GetRegisteredClassMaps().First(); var fi = typeof(BsonClassMap).GetField("__classMaps", BindingFlags.Static | BindingFlags.NonPublic); var classMaps = (Dictionary <Type, BsonClassMap>)fi.GetValue(cm); return(classMaps); }
public HeroService(MongoClient dbClient, IConfiguration config) { var dbName = config.GetValue <string>("HeroDatabaseName"); var collectionName = "hero"; _database = dbClient.GetDatabase(dbName); collection = _database.GetCollection <HeroDocument>(collectionName); var temp = BsonClassMap.GetRegisteredClassMaps(); }
public void ObjectIdGeneratorOnObjectIdProperty() { EntityMapping.AddMappingProcessor(new EntityIdProcessor()); EntityMapping.RegisterType(typeof(ObjectIdGeneratorTestModel)); var classMap = BsonClassMap.GetRegisteredClassMaps() .Where(cm => cm.ClassType == typeof(ObjectIdGeneratorTestModel)).FirstOrDefault(); Assert.AreEqual(typeof(ObjectIdGenerator), classMap.IdMemberMap.IdGenerator?.GetType()); }
public void ExplicitKeyOverridesImplicitId() { EntityMapping.AddMappingProcessor(new EntityIdProcessor()); EntityMapping.RegisterType(typeof(ExplicitKeyOverridesImplicitIdModel)); var classMap = BsonClassMap.GetRegisteredClassMaps() .Where(cm => cm.ClassType == typeof(ExplicitKeyOverridesImplicitIdModel)).FirstOrDefault(); Assert.AreEqual("ActualKey", classMap.IdMemberMap.MemberName); }
public void Replace <T>(string collectionName, string criteria, T data, bool insertIfNotFound) { var flags = UpdateFlags.None; if (insertIfNotFound) { flags |= UpdateFlags.Upsert; } BsonDocument deserialized; var stringData = data as string; if (stringData != null) { Exception exception; if (!AttemptDeserialize(data as string, out deserialized, out exception)) { throw new Exception("Invalid JSON format in 'Data'", exception); } Replace(collectionName, criteria, deserialized, insertIfNotFound); return; } RegisterClassForBSONSerialisation <T>(); MongoCollection <T> collection = Database.GetCollection <T>(collectionName); WriteConcernResult result; if (String.IsNullOrEmpty(criteria) && typeof(T) != typeof(BsonDocument)) { IEnumerable <BsonClassMap> maps = BsonClassMap.GetRegisteredClassMaps(); BsonMemberMap idMap = maps.First(v => v.ClassType == typeof(T)).IdMemberMap; if (idMap == null) { throw new MongoException( "Cannot perform mongo replace: no criteria specified and the object does not have an id field"); } var id = (string)idMap.Getter(data); if (String.IsNullOrEmpty(id)) { throw new MongoException("Cannot perform mongo replace: no criteria specified and the object's id field is not set"); } result = collection.Update(Query.EQ("_id", new ObjectId(id)), global::MongoDB.Driver.Builders.Update.Replace(data), flags); } else { result = collection.Update(new QueryDocument(ParseQuery(criteria)), global::MongoDB.Driver.Builders.Update.Replace(data), flags); } Log(string.Format("{0} items {1}.", result.DocumentsAffected, (result.DocumentsAffected == 0) || (result.UpdatedExisting) ? "replaced" : "inserted")); }
/// <inheritdoc /> public virtual IMongoCollection <T> GetCollection <T>() { var cm = BsonClassMap.GetRegisteredClassMaps().OfType <EntityMapClass <T> >().SingleOrDefault(); if (cm == null) { throw new Exception($"No registered EntityMapClass<T> found for type: {typeof(T).Name}"); } if (string.IsNullOrEmpty(cm.CollectionName)) { throw new Exception($"EntityMapClass<T> must call ToCollection method to specify mongo collection name. Type: {typeof(T).Name}"); } return(Db.GetCollection <T>(cm.CollectionName)); }
public void TestGetRegisteredClassMaps() { Assert.IsFalse(BsonClassMap.IsClassMapRegistered(typeof(C))); Assert.IsFalse(BsonClassMap.IsClassMapRegistered(typeof(D))); BsonClassMap.RegisterClassMap <C>(cm => cm.AutoMap()); BsonClassMap.RegisterClassMap <D>(cm => cm.AutoMap()); var classMaps = BsonClassMap.GetRegisteredClassMaps(); var classMapTypes = classMaps.Select(x => x.ClassType).ToList(); Assert.IsTrue(BsonClassMap.IsClassMapRegistered(typeof(C))); Assert.Contains(typeof(C), classMapTypes); Assert.Contains(typeof(D), classMapTypes); }
public static IEntityDefinition RegisterType(Type entityType) { if (IsRegistered(entityType)) { throw new ArgumentException("Type is already registered", nameof(entityType)); } var definition = new EntityDefinition { EntityType = entityType }; MappingLock.EnterUpgradeableReadLock(); try { //For reasons unknown to me, you can't just call "BsonClassMap.LookupClassMap" as that "freezes" the class map //Instead, you must do the lookup and initial creation yourself. var classMap = BsonClassMap.GetRegisteredClassMaps() .Where(cm => cm.ClassType == entityType).FirstOrDefault(); if (classMap == null) { MappingLock.EnterWriteLock(); try { classMap = new BsonClassMap(entityType); BsonClassMap.RegisterClassMap(classMap); classMap.AutoMap(); foreach (var processor in MappingProcessors) { processor.ApplyMapping(definition, classMap); } } finally { MappingLock.ExitWriteLock(); } } } finally { MappingLock.ExitUpgradeableReadLock(); } return(SetEntityDefinition(definition)); }
public Repository(IMongoDatabase db) { this.db = db; this.collection = db.GetCollection <TEntity>(ClassMappingExtensions.GetCollectionForType <TEntity>()); if (!BsonClassMap.IsClassMapRegistered(typeof(TEntity))) { throw new InvalidOperationException("Cannot create repository of unmapped class: " + typeof(TEntity).FullName); } this.map = BsonClassMap <TEntity> .GetRegisteredClassMaps().FirstOrDefault(); this.idMember = map?.IdMemberMap; }
public CategoryRepository(IMongoDatabase database) { _database = database; if (!BsonClassMap.GetRegisteredClassMaps().Any(x => x.ClassType == typeof(Category))) { BsonClassMap.RegisterClassMap <Category>(x => { x.AutoMap(); x.MapField("_childCategories"); x.MapField("_productIds"); }); } _collection = _database.GetCollection <Category>(_collectionName); }
public void ObeysIgnoreExtraElementsAttribute() { EntityMapping.AddMappingProcessor(new ExtraElementsProcessor()); EntityMapping.RegisterType(typeof(IgnoreExtraElementsModel)); var classMap = BsonClassMap.GetRegisteredClassMaps() .Where(cm => cm.ClassType == typeof(IgnoreExtraElementsModel)).FirstOrDefault(); Assert.IsTrue(classMap.IgnoreExtraElements); EntityMapping.RegisterType(typeof(ExtraElementsAttrModel)); classMap = BsonClassMap.GetRegisteredClassMaps() .Where(cm => cm.ClassType == typeof(ExtraElementsAttrModel)).FirstOrDefault(); Assert.IsFalse(classMap.IgnoreExtraElements); }
public void ObeysExtraElementsAttribute() { EntityMapping.AddMappingProcessor(new ExtraElementsProcessor()); EntityMapping.RegisterType(typeof(ExtraElementsAttrModel)); var classMap = BsonClassMap.GetRegisteredClassMaps() .Where(cm => cm.ClassType == typeof(ExtraElementsAttrModel)).FirstOrDefault(); Assert.AreEqual("AdditionalElements", classMap.ExtraElementsMemberMap.ElementName); EntityMapping.RegisterType(typeof(IgnoreExtraElementsModel)); classMap = BsonClassMap.GetRegisteredClassMaps() .Where(cm => cm.ClassType == typeof(IgnoreExtraElementsModel)).FirstOrDefault(); Assert.AreEqual(null, classMap.ExtraElementsMemberMap); }
public MongoDbAutomatonymousSagaRepository(MongoDatabase database, TStateMachine machine) : base(database) { if (Log == null) { Log = Logger.Get( typeof(MongoDbAutomatonymousSagaRepository <TStateMachineInstance, TStateMachine>) .ToFriendlyName()); } // BsonClassMap.RegisterClassMap<SagaStateMachineInstance>(); BsonClassMap <TStateMachineInstance> map; if (BsonClassMap.IsClassMapRegistered(typeof(TStateMachineInstance))) { map = (BsonClassMap <TStateMachineInstance>)BsonClassMap.GetRegisteredClassMaps() .First(c => c.ClassType == typeof(TStateMachineInstance)); } else { map = BsonClassMap.RegisterClassMap <TStateMachineInstance>( cm => { cm.AutoMap(); cm.MapIdField(s => s.CorrelationId); cm.MapIdMember(s => s.CorrelationId); cm.MapIdProperty(s => s.CorrelationId); cm.UnmapProperty(s => s.Bus); }); } map.UnmapProperty(s => s.Bus); var properties = typeof(TStateMachineInstance).GetProperties(); foreach (var propertyInfo in properties) { if (propertyInfo.PropertyType == typeof(State)) { map.MapProperty(propertyInfo.Name).SetSerializer(new StateSerializer <TStateMachine>(machine)); } else if (propertyInfo.PropertyType == typeof(CompositeEventStatus)) { map.MapProperty(propertyInfo.Name).SetSerializer(new CompositeEventStatusSerializer()); } } }
public void MapsNestedCollectionPropertyModel() { var processor = new NestedPropertyProcessor(); var classMap = new BsonClassMap <CollectionBaseModel>(); classMap.AutoMap(); var registeredClassMaps = BsonClassMap.GetRegisteredClassMaps(); Assert.IsFalse(registeredClassMaps.Any(m => m.ClassType == typeof(CollectionNestedModel))); processor.ApplyMapping(typeof(CollectionBaseModel), classMap); registeredClassMaps = BsonClassMap.GetRegisteredClassMaps(); Assert.IsTrue(registeredClassMaps.Any(m => m.ClassType == typeof(CollectionNestedModel))); }
private void RegisterMappings() { if (BsonClassMap.GetRegisteredClassMaps().Any()) { return; } BsonClassMap.RegisterClassMap <Entity>(cm => { cm.AutoMap(); cm.SetIsRootClass(true); cm.MapField("_tags") .SetElementName(nameof(Entity.Tags)); }); BsonClassMap.RegisterClassMap <Note>(); }
public void DiscoveredEntityClassMaps_AddedToMongo() { ContainerSetup .Arrange((TestTypeResolver config) => { config.UseDefaultSettingsConfig(); config.SetupValidMongoConsumingPlugin(); }) .Test( c => c.Build().Start(), (MappingModule module) => { var classMap = BsonClassMap.GetRegisteredClassMaps().FirstOrDefault(); classMap.Should().NotBeNull(); classMap.Should().BeOfType<MockEntityClassMap>(); }); }
private void RegisterClassMaps() { var registeredTypes = BsonClassMap.GetRegisteredClassMaps().Select(x => x.ClassType).ToList(); var commands = _commander.GetRegisteredCommands().Values; var registerClassMapMethod = typeof(BsonClassMap).GetMethod("RegisterClassMap", BindingFlags.Public | BindingFlags.Static, null, Type.EmptyTypes, new ParameterModifier[] { }); foreach (var commandType in commands) { if (registeredTypes.Contains(commandType)) { continue; } registerClassMapMethod.MakeGenericMethod(commandType) .Invoke(this, null); } }
public void AssureMappinsgAreInitialized() { if (BsonClassMap.GetRegisteredClassMaps().Any()) { return; } lock (_lock) { if (BsonClassMap.GetRegisteredClassMaps().Any()) { return; } foreach (var mapper in _mappers) { mapper.InitializeMapping(); } } }
public void TranslateToDomain <TEntity>(EntityEventSource <TEntity, long> domain, EntityEventSourceWrapper entity) where TEntity : IVersionableEntity <long>, new() { domain.Id = entity.Id; domain.State = entity.State; domain.Status = entity.Status; domain.ProcessingAt = entity.ProcessingAt; domain.ProcessingBy = entity.ProcessingBy; if (entity.SnapShot != null) { domain.SnapShot = (TEntity)BsonSerializer.Deserialize(entity.SnapShot, typeof(TEntity)); } foreach (var eventWrapper in entity.Events) { var registeredClassMaps = BsonClassMap.GetRegisteredClassMaps(); var bsonClassMap = registeredClassMaps.First(map => map.Discriminator == eventWrapper.Type); var @event = BsonSerializer.Deserialize(eventWrapper.Data, bsonClassMap.ClassType); domain.Events.Add((IDomainEvent <TEntity>)@event); } }
public void Verify_ability_to_map_with_attribute_interface_dictionary_representation() { var collection = db.GetCollection <TestClassWithHeadersAsInterfaceDictionaryMappedWithAttributes>("InterfaceDictionary"); var instance = new TestClassWithHeadersAsInterfaceDictionaryMappedWithAttributes() { Headers = new Dictionary <string, string>() { ["with.dot"] = "value", }, Property = "Property value" }; collection.InsertOne(instance); var mappingOfHeaders = BsonClassMap.GetRegisteredClassMaps() .Single(m => m.ClassType == typeof(TestClassWithHeadersAsInterfaceDictionaryMappedWithAttributes)) .AllMemberMaps .Single(mm => mm.MemberName == "Headers"); Console.WriteLine($"Mapping is {mappingOfHeaders.GetType()}"); }
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; } }
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 void Insert <T>(string collectionName, T data) { BsonDocument deserialized; var stringData = data as string; if (stringData != null) { Exception exception; if (!AttemptDeserialize(data as string, out deserialized, out exception)) { throw new Exception("Invalid JSON format in 'Data' property", exception); } Insert(collectionName, deserialized); return; } RegisterClassForBSONSerialisation <T>(); IEnumerable <BsonClassMap> maps = BsonClassMap.GetRegisteredClassMaps(); BsonClassMap map = maps.First(v => v.ClassType == typeof(T)); MongoCollection <T> collection = Database.GetCollection <T>(collectionName); var result = collection.Insert(data); Log(string.Format("{0} item(s) inserted.", result.DocumentsAffected)); }