public void TestLookupIdGeneratorConventionWithTestClassB()
 {
     var convention = new LookupIdGeneratorConvention();
     var classMap = new BsonClassMap<TestClassB>();
     classMap.MapIdMember(x => x.GuidId);
     convention.PostProcess(classMap);
     Assert.IsNotNull(classMap.IdMemberMap.IdGenerator);
     Assert.IsInstanceOf<GuidGenerator>(classMap.IdMemberMap.IdGenerator);
 }
 public void TestMapField() {
     var classMap = new BsonClassMap<C>(cm => cm.MapField("f"));
     var memberMap = classMap.GetMemberMap("f");
     Assert.IsNotNull(memberMap);
     Assert.AreEqual("f", memberMap.ElementName);
     Assert.AreEqual("f", memberMap.MemberName);
 }
        public void TestDoesNotSetWhenNoIdExists()
        {
            var classMap = new BsonClassMap<TestClass>(cm =>
            { });

            Assert.DoesNotThrow(() => _subject.PostProcess(classMap));
        }
        public void TestIsReadOnlyPropertyOfAField()
        {
            var classMap = new BsonClassMap<TestClass>(cm => cm.AutoMap());
            var memberMap = classMap.GetMemberMap("Field");

            Assert.IsFalse(memberMap.IsReadOnly);
        }
        // public methods
        /// <summary>
        /// Applies a modification to the class map.
        /// </summary>
        /// <param name="classMap">The class map.</param>
        public void Apply(BsonClassMap classMap)
        {
            //使用插件机制处理序列化成员 james.wei 2015-05-26。
            foreach (var convention in _conventions.OfType<IClassMapConvention>())
            {
                convention.Apply(classMap);
            }

            foreach (var convention in _conventions.OfType<IMemberMapConvention>())
            {
                foreach (var memberMap in classMap.DeclaredMemberMaps)
                {
                    convention.Apply(memberMap);
                }
            }

            foreach (var convention in _conventions.OfType<ICreatorMapConvention>())
            {
                foreach (var creatorMap in classMap.CreatorMaps)
                {
                    convention.Apply(creatorMap);
                }
            }

            foreach (var convention in _conventions.OfType<IPostProcessingConvention>())
            {
                convention.PostProcess(classMap);
            }
        }
 public void TestNamedIdMemberConventionWithTestClassB()
 {
     var convention = new NamedIdMemberConvention("Id", "id", "_id");
     var classMap = new BsonClassMap<TestClassB>();
     convention.Apply(classMap);
     Assert.Null(classMap.IdMemberMap);
 }
        public void SetUp()
        {
            var stopwatch = new Stopwatch();
            _pack = new ConventionPack();
            _pack.AddRange(new IConvention[] 
            {
                new TrackingBeforeConvention(stopwatch) { Name = "1" },
                new TrackingMemberConvention(stopwatch) { Name = "3" },
                new TrackingAfterConvention(stopwatch) { Name = "5" },
                new TrackingMemberConvention(stopwatch) { Name = "4" },
                new TrackingAfterConvention(stopwatch) { Name = "6" },
                new TrackingBeforeConvention(stopwatch) { Name = "2" },
            });
            _subject = new ConventionRunner(_pack);

            var classMap = new BsonClassMap<TestClass>(cm =>
            {
                cm.MapMember(t => t.Prop1);
                cm.MapMember(t => t.Prop2);
            });

            stopwatch.Start();
            _subject.Apply(classMap);
            stopwatch.Stop();
        }
 public BsonMigrationSerializer(IBsonSerializer versionSerializer, IVersionDetectionStrategy versionDetectionStrategy, BsonClassMap classMap)
     : base(classMap)
 {
     _versionSerializer = versionSerializer;
     _versionDetectionStrategy = versionDetectionStrategy;
     _migrations = ExtractMigrations(classMap.ClassType);
 }
 public void TestMapIdField() {
     var classMap = new BsonClassMap<C>(cm => cm.MapIdField("f"));
     var idMemberMap = classMap.IdMemberMap;
     Assert.IsNotNull(idMemberMap);
     Assert.AreEqual("_id", idMemberMap.ElementName);
     Assert.AreEqual("f", idMemberMap.MemberName);
 }
        public void TestDoesNotSetWhenNoIdExists()
        {
            var classMap = new BsonClassMap<TestClass>(cm =>
            { });

            _subject.PostProcess(classMap);
        }
 /// <summary>
 /// Post process the class map.
 /// </summary>
 /// <param name="classMap">The class map to be processed.</param>
 public void PostProcess(BsonClassMap classMap)
 {
     if (typeof(IEntity).IsAssignableFrom(classMap.ClassType) && classMap.IdMemberMap != null)
     {
         classMap.IdMemberMap.SetIdGenerator(new GuidGenerator());
     }
 }
 // public methods
 /// <summary>
 /// Applies a modification to the class map.
 /// </summary>
 /// <param name="classMap">The class map.</param>
 public void Apply(BsonClassMap classMap)
 {
     foreach (var type in _knownTypes)
     {
         classMap.AddKnownType(type);
     }
 }
 public void TestNamedExtraElementsMemberConventionWithTestClassB()
 {
     var convention = new NamedExtraElementsMemberConvention("ExtraElements");
     var classMap = new BsonClassMap<TestClassB>();
     convention.Apply(classMap);
     Assert.IsNull(classMap.ExtraElementsMemberMap);
 }
 public void TestNoDefaultConstructorClassMapConventionWithTestClassA()
 {
     var convention = new ImmutableTypeClassMapConvention();
     var classMap = new BsonClassMap<TestClassA>();
     convention.Apply(classMap);
     Assert.False(classMap.HasCreatorMaps);
 }
 // constructors
 /// <summary>
 /// Initializes a new instance of the BsonMemberMap class.
 /// </summary>
 /// <param name="classMap">The class map this member map belongs to.</param>
 /// <param name="memberInfo">The member info.</param>
 public BsonMemberMap(BsonClassMap classMap, MemberInfo memberInfo)
 {
     _classMap = classMap;
     _memberInfo = memberInfo;
     _memberType = BsonClassMap.GetMemberInfoType(memberInfo);
     _defaultValue = GetDefaultValue(_memberType);
 }
示例#16
0
 static MongoTest()
 {
     BsonSerializer.RegisterIdGenerator(typeof(string), StringObjectIdGenerator.Instance);
     var map = new BsonClassMap<Person>();
     map.AutoMap();
     BsonClassMap.RegisterClassMap(map);
 }
示例#17
0
        public void TestSave()
        {
            var server = Configuration.TestServer;
            var database = Configuration.TestDatabase;
            var collection = Configuration.GetTestCollection<Foo>();

            var conventions = new ConventionPack();
            conventions.Add(new NamedIdMemberConvention(new[] { "FooId" }));
            ConventionRegistry.Register("test", conventions, t => t == typeof(Foo));

            var classMap = new BsonClassMap<Foo>(cm => cm.AutoMap());

            collection.RemoveAll();
            for (int i = 0; i < 10; i++)
            {
                var foo = new Foo
                {
                    FooId = ObjectId.Empty,
                    Name = string.Format("Foo-{0}", i),
                    Summary = string.Format("Summary for Foo-{0}", i)
                };
                collection.Save(foo);
                var count = collection.Count();
                Assert.AreEqual(i + 1, count);
            }
        }
示例#18
0
 public void Apply(BsonClassMap classMap)
 {
     if (classMap.ClassType.IsClass && typeof(ISaga).IsAssignableFrom(classMap.ClassType))
     {
         classMap.MapIdProperty(nameof(ISaga.CorrelationId));
     }
 }
示例#19
0
		public ContentSerializer(Type type, MongoDatabaseProvider database, IProxyFactory proxies)
		{
			this.database = database;
			classMap = BsonClassMap.LookupClassMap(type);
			serializer = new BsonClassMapSerializer(classMap);
			this.proxies = proxies;
		}
 public void TestNamedExtraElementsMemberConventionWithTestClassA()
 {
     var convention = new NamedExtraElementsMemberConvention("ExtraElements");
     var classMap = new BsonClassMap<TestClassA>();
     convention.Apply(classMap);
     Assert.IsNotNull(classMap.ExtraElementsMemberMap);
     Assert.AreEqual("ExtraElements", classMap.ExtraElementsMemberMap.MemberName);
 }
        public void TestMapsExtraElementsWhenFirstNameExists()
        {
            var classMap = new BsonClassMap<TestClass2>();

            _subject.Apply(classMap);

            Assert.IsNotNull(classMap.ExtraElementsMemberMap);
        }
        public void TestDoesNotMapExtraElementsWhenOneIsNotFound()
        {
            var classMap = new BsonClassMap<TestClass1>();

            _subject.Apply(classMap);

            Assert.Null(classMap.ExtraElementsMemberMap);
        }
        public void TestThrowsWithDuplicateExtraElements()
        {
            var convention = AttributeConventionPack.Instance;
            var classMap = new BsonClassMap<TestDuplicateExtraElements>();

            Assert.Throws<DuplicateBsonMemberMapAttributeException>(() =>
                new ConventionRunner(convention).Apply(classMap));
        }
示例#24
0
 public void RegisterClassIgnoreExtraFields(Type type)
 {
     BsonClassMap cm = new BsonClassMap(type);
     cm.AutoMap();
     //cm.SetIgnoreExtraElements(true); // Let's see if this is the default
     BsonClassMap.RegisterClassMap(cm);
     //BsonSerializer.RegisterDiscriminatorConvention(type, new ScalarDiscriminatorConvention("type"));
 }
        public void TestMapsIdWhenFirstNameExists()
        {
            var classMap = new BsonClassMap<TestClass2>();

            _subject.Apply(classMap);

            Assert.NotNull(classMap.IdMemberMap);
        }
 public void TestNoDefaultConstructorClassMapConventionWithTestClassC()
 {
     var convention = new ImmutableTypeClassMapConvention();
     var classMap = new BsonClassMap<TestClassC>();
     convention.Apply(classMap);
     Assert.True(classMap.HasCreatorMaps);
     Assert.Equal(1, classMap.CreatorMaps.Count());
 }
 public void TestNamedIdMemberConventionWithTestClassD()
 {
     var convention = new NamedIdMemberConvention("Id", "id", "_id");
     var classMap = new BsonClassMap<TestClassD>();
     convention.Apply(classMap);
     Assert.IsNotNull(classMap.IdMemberMap);
     Assert.AreEqual("_id", classMap.IdMemberMap.MemberName);
 }
        public void TestDoesNotMapExtraElementsWhenIsNotValidType()
        {
            var classMap = new BsonClassMap<TestClass5>();

            _subject.Apply(classMap);

            Assert.IsNull(classMap.ExtraElementsMemberMap);
        }
示例#29
0
        public void TestDoesNotMapIdWhenOneIsNotFound()
        {
            var classMap = new BsonClassMap<TestClass1>();

            _subject.Apply(classMap);

            Assert.IsNull(classMap.IdMemberMap);
        }
示例#30
0
        public void TestMapsIdWhenSecondNameExists()
        {
            var classMap = new BsonClassMap<TestClass3>();

            _subject.Apply(classMap);

            Assert.IsNotNull(classMap.IdMemberMap);
        }
 private static void RegisterClassMap()
 {
     if (classMapRegistered)
     {
         return;
     }
     BsonClassMap.RegisterClassMap <Error>(cm =>
     {
         cm.AutoMap();
         cm.MapIdMember(x => x.GUID);
         foreach (var prop in typeof(Error).GetMembers())
         {
             if (prop.CustomAttributes.Any(x => x.AttributeType == typeof(JsonIgnoreAttribute)))
             {
                 cm.UnmapMember(prop);
             }
         }
     });
     classMapRegistered = true;
 }
示例#32
0
        /// <summary>
        /// Adds a list of property mappings for given document type
        /// </summary>
        /// <param name="builder">The <see cref="AgileTea.Persistence.Mongo.IMongoDbBuilder"/> used for registration</param>
        /// <param name="mappings">List of mappings</param>
        /// <typeparam name="T">Document type</typeparam>
        /// <returns>The <see cref="AgileTea.Persistence.Mongo.IMongoDbBuilder"/> instance</returns>
        /// <exception cref="ArgumentNullException">Throws exception if the builder is null</exception>
        public static IMongoDbBuilder AddMappings <T>(this IMongoDbBuilder builder, params Action <BsonClassMap <T> >[] mappings)
            where T : class
        {
            if (builder == null)
            {
                throw new ArgumentNullException(nameof(builder));
            }

            BsonClassMap.RegisterClassMap <T>(map =>
            {
                map.AutoMap();
                map.SetIgnoreExtraElements(true);
                foreach (var mapping in mappings)
                {
                    mapping.Invoke(map);
                }
            });

            return(builder);
        }
示例#33
0
        public MongoServiceAccountDatabase()
        //string ConnectionString, string DatabaseName, string AccountName, string NetworkId, string ShardId = "Primary")
        {
            _config = Neo.Settings.Default.LyraNode;

            _DatabaseName = _config.Lyra.Database.DatabaseName;
            //_NetworkId = NetworkId;
            //_ShardId = ShardId;
            //_AccountName = AccountName;
            var ShardId = "Primary";

            _BlockCollectionName  = _config.Lyra.NetworkId + "-" + ShardId + "-" + ServiceAccount.SERVICE_ACCOUNT_NAME + "-blocks";
            _ParamsCollectionName = _config.Lyra.NetworkId + "-" + ShardId + "-" + ServiceAccount.SERVICE_ACCOUNT_NAME + "-params";

            BsonClassMap.RegisterClassMap <ConsolidationBlock>();
            BsonClassMap.RegisterClassMap <ServiceBlock>();

            _blocks = GetDatabase().GetCollection <Block>(_BlockCollectionName);
            _params = GetDatabase().GetCollection <AccountParam>(_ParamsCollectionName);
        }
示例#34
0
        private void Map()
        {
            BsonClassMap.RegisterClassMap <Entity>(cm =>
            {
                cm.MapIdProperty(c => c.Id);
            });

            BsonClassMap.RegisterClassMap <AggregateRoot>(cm =>
            {
                cm.MapProperty(c => c.Version).SetElementName("_version");
            });

            BsonClassMap.RegisterClassMap <School>(cm =>
            {
                cm.MapField("name").SetElementName("name");
                cm.MapField("manager").SetElementName("manager");
                cm.MapField("teachers").SetElementName("teachers");
                cm.MapField("parents").SetElementName("parents");
                cm.MapField("children").SetElementName("children");
            });

            BsonClassMap.RegisterClassMap <Teacher>(cm =>
            {
                cm.MapField("name").SetElementName("name");
            });

            BsonClassMap.RegisterClassMap <Parent>(cm =>
            {
                cm.MapField("name").SetElementName("name");
                cm.MapField("identification").SetElementName("identification");
                cm.MapField("birthDate").SetElementName("birthDate");
                cm.MapField("children").SetElementName("children");
            });

            BsonClassMap.RegisterClassMap <Child>(cm =>
            {
                cm.MapField("name").SetElementName("name");
                cm.MapField("birthDate").SetElementName("birthDate");
                cm.MapField("currentCustody").SetElementName("currentCustody");
            });
        }
        void RegisterClassMaps()
        {
            lock (ClassMapRegistrationLock)
            {
                if (BsonClassMap.IsClassMapRegistered(typeof(IdempotencyData)))
                {
                    _log.Debug("BSON class map for {type} already registered - not doing anything", typeof(IdempotencyData));
                    return;
                }

                _log.Debug("Registering BSON class maps for {type} and accompanying types", typeof(IdempotencyData));

                BsonClassMap.RegisterClassMap <IdempotencyData>(map =>
                {
                    map.MapCreator(obj => new IdempotencyData(obj.OutgoingMessages, obj.HandledMessageIds));
                    map.MapMember(obj => obj.HandledMessageIds);
                    map.MapMember(obj => obj.OutgoingMessages);
                });

                BsonClassMap.RegisterClassMap <OutgoingMessage>(map =>
                {
                    map.MapCreator(obj => new OutgoingMessage(obj.DestinationAddresses, obj.TransportMessage));
                    map.MapMember(obj => obj.DestinationAddresses);
                    map.MapMember(obj => obj.TransportMessage);
                });

                BsonClassMap.RegisterClassMap <OutgoingMessages>(map =>
                {
                    map.MapCreator(obj => new OutgoingMessages(obj.MessageId, obj.MessagesToSend));
                    map.MapMember(obj => obj.MessageId);
                    map.MapMember(obj => obj.MessagesToSend);
                });

                BsonClassMap.RegisterClassMap <TransportMessage>(map =>
                {
                    map.MapCreator(obj => new TransportMessage(obj.Headers, obj.Body));
                    map.MapMember(obj => obj.Headers);
                    map.MapMember(obj => obj.Body);
                });
            }
        }
示例#36
0
        static MongoHelper()
        {
            // 自动注册IgnoreExtraElements

            ConventionPack conventionPack = new ConventionPack {
                new IgnoreExtraElementsConvention(true)
            };

            ConventionRegistry.Register("IgnoreExtraElements", conventionPack, type => true);

#if SERVER
            BsonSerializer.RegisterSerializer(typeof(Vector3), new StructBsonSerialize <Vector3>());
            BsonSerializer.RegisterSerializer(typeof(Vector4), new StructBsonSerialize <Vector4>());
            BsonSerializer.RegisterSerializer(typeof(Quaternion), new StructBsonSerialize <Quaternion>());
#elif ROBOT
            BsonSerializer.RegisterSerializer(typeof(Quaternion), new StructBsonSerialize <Quaternion>());
            BsonSerializer.RegisterSerializer(typeof(Vector3), new StructBsonSerialize <Vector3>());
            BsonSerializer.RegisterSerializer(typeof(Vector4), new StructBsonSerialize <Vector4>());
#else
            BsonSerializer.RegisterSerializer(typeof(Vector4), new StructBsonSerialize <Vector4>());
            BsonSerializer.RegisterSerializer(typeof(Vector3), new StructBsonSerialize <Vector3>());
            BsonSerializer.RegisterSerializer(typeof(Vector2Int), new StructBsonSerialize <Vector2Int>());
#endif

            var types = Game.EventSystem.GetTypes();

            foreach (Type type in types)
            {
                if (!type.IsSubclassOf(typeof(Object)))
                {
                    continue;
                }

                if (type.IsGenericType)
                {
                    continue;
                }

                BsonClassMap.LookupClassMap(type);
            }
        }
示例#37
0
 protected override void RegisterTypes()
 {
     BsonClassMap.RegisterClassMap <TagReference>(map =>
     {
         map.SetIsRootClass(true);
         map.AddKnownType(typeof(Genre));
         map.AddKnownType(typeof(Year));
         map.AddKnownType(typeof(Title));
         map.AddKnownType(typeof(Artist));
         map.AddKnownType(typeof(Album));
         map.MapIdProperty(x => x.Id);
         map.MapProperty(x => x.Name);
     });
     BsonClassMap.RegisterClassMap <StorableTaggedFile>(map =>
     {
         map.UnmapProperty(f => f.Album);
         map.MapProperty(f => f.AlbumId);
         map.UnmapProperty(f => f.Artist);
         map.MapProperty(f => f.ArtistId);
         map.UnmapProperty(f => f.Genre);
         map.MapProperty(f => f.GenreId);
         map.UnmapProperty(f => f.Title);
         map.MapProperty(f => f.TitleId);
         map.UnmapProperty(f => f.Year);
         map.MapProperty(f => f.YearId);
         map.MapProperty(f => f.Comment);
         map.MapProperty(f => f.Filename);
         map.MapProperty(f => f.TrackNo);
         map.MapProperty(f => f.Duration);
         map.MapIdProperty(f => f.Id);
     });
     Container.RegisterType <IMongoWrapper, MongoWrapper>(new ContainerControlledLifetimeManager());
     Container.RegisterType(typeof(IDataAdapter <>), typeof(MongoDBAdapter <>), new PerResolveLifetimeManager());
     //var adapter = Container.Resolve<MongoDBAdapter<StorableTaggedFile>>();
     //var res =
     //    adapter.DistinctBy(f => f.AlbumId)
     //           .Select(f => f.LazyLoadReferences(Container.Resolve<IReferenceAdapters>()));
     //foreach (var item in res)
     //    Trace.WriteLine(item);
     //Trace.WriteLine("Done");
 }
示例#38
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            string host2    = "pc.mokhnatkin.org";
            string user     = "******";
            string password = "******";

            // Mongo
            services.AddSingleton <IMongoClient>(_ => new MongoClient());
            BsonClassMap.RegisterClassMap <Unit>();
            // Redis
            services.AddScoped <IRedisClientsManager>(_ => new RedisManagerPool());
            // Cassandra
            services.AddSingleton <ICluster>(_ =>
                                             Cluster.Builder()
                                             .AddContactPoint(host2)
                                             .WithPort(100)
                                             .WithCredentials(user, password)
                                             .Build());
            // Neo4j
            services.AddTransient <IGraphClient>(_ =>
            {
                var neo4JServersList = new[]
                {
                    new Uri($"http://{host2}:8000/db/data"),
                    new Uri($"http://{host2}:8001/db/data"),
                    new Uri($"http://{host2}:8002/db/data")
                };
                var clusterGraphClient = new GraphClientCluster(neo4JServersList, "neo4j", password);
                return(clusterGraphClient.GetActive());
            });
            // Add framework services.
            services.AddMvc();

            // Register the Swagger generator, defining one or more Swagger documents
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info {
                    Title = "Rest API", Version = "v1"
                });
            });
        }
示例#39
0
        static MongoHelper()
        {
            // 自动注册IgnoreExtraElements

            ConventionPack conventionPack = new ConventionPack {
                new IgnoreExtraElementsConvention(true)
            };

            ConventionRegistry.Register("IgnoreExtraElements", conventionPack, type => true);

            Type[] types = typeof(Game).Assembly.GetTypes();

            foreach (Type type in types)
            {
                if (!type.IsSubclassOf(typeof(Entity)))
                {
                    continue;
                }

                if (type.IsGenericType)
                {
                    continue;
                }

                try
                {
                    BsonClassMap.LookupClassMap(type);
                }
                catch (Exception e)
                {
                    Log.Error($"11111111111111111: {type.Name} {e}");
                }
            }
#if SERVER
            BsonSerializer.RegisterSerializer(typeof(Vector3), new StructBsonSerialize <Vector3>());
#else
            BsonSerializer.RegisterSerializer(typeof(Vector3), new StructBsonSerialize <Vector3>());
            BsonSerializer.RegisterSerializer(typeof(Vector4), new StructBsonSerialize <Vector4>());
            BsonSerializer.RegisterSerializer(typeof(Vector2Int), new StructBsonSerialize <Vector2Int>());
#endif
        }
示例#40
0
        internal void MaxWithUntypedProperty(IMongoFacadeTransaction tx, Maybe <object> max, Maybe <EventID> typedMax)
        {
            GIVEN["a ClassMap with custom serializer"] = () => BsonClassMap.RegisterClassMap <UntypedPropertyClass>(m => m
                                                                                                                    .MapIdField(x => x.ID)
                                                                                                                    .SetSerializer(EventIDSerializer.CastInstance));
            Given["a mongo collection"] = () => Env.DB.CreateCollectionAsync("test");

            USING["a transaction"] = () => {
                ITransaction t = DB.StartTransactionAsync().Result;
                tx = DB.UseTransaction(t);
                return(t);
            };

            When["calling Max on an empty collection"] = async() => max = await tx
                                                                          .GetCollection <UntypedPropertyClass>("test")
                                                                          .Max(x => x.ID);

            THEN["None<T> is returned"] = () => max.Should().Be(None <Object> .Value);

            And["a collection with a few items"] = () => tx
                                                   .GetCollection <UntypedPropertyClass>("test")
                                                   .InsertManyAsync(new uint[] { 1, 3, 7, 2 }.Select(x => new UntypedPropertyClass(id: x)));

            When["calling Max"] = async() => max = await tx
                                                   .GetCollection <UntypedPropertyClass>("test")
                                                   .Max(x => x.ID);

            THEN["the maximum value is returned"] = () => {
                max.Value.Should().BeOfType <EventID>();
                max.Value.As <EventID>().Serialize().Should().Be(7);
            };

            When["calling Max on a interface-typed collection"] = async() => typedMax = await tx
                                                                                        .GetCollection <UntypedPropertyClass>("test")
                                                                                        .Max <EventID>("_id");

            THEN["the maximum value is returned"] = () => {
                typedMax.Value.Should().BeOfType <EventID>();
                typedMax.Value.As <EventID>().Serialize().Should().Be(7);
            };
        }
示例#41
0
        private ResourceType BuildHierarchyForType(Type type, ResourceTypeKind kind)
        {
            var maps = new List <BsonClassMap>();

            var          baseClassMap       = BsonClassMap.LookupClassMap(type);
            ResourceType entityResourceType = null;

            while (baseClassMap != null && !_knownResourceTypes.TryGetValue(baseClassMap.ClassType, out entityResourceType))
            {
                maps.Add(baseClassMap);
                baseClassMap = baseClassMap.BaseClassMap;
                if (baseClassMap.ClassType == typeof(object))
                {
                    baseClassMap = null;
                }
            }

            if (entityResourceType != null)
            {
                if (entityResourceType.ResourceTypeKind == kind)
                {
                    if (maps.Count == 0)
                    {
                        return(entityResourceType);
                    }
                }
                else
                {
                    return(null);
                }
            }

            for (int i = maps.Count - 1; i >= 0; i--)
            {
                entityResourceType = CreateResourceType(maps[i].ClassType, kind, entityResourceType);
            }

            PopulateMetadataForTypes();

            return(entityResourceType);
        }
示例#42
0
        protected override void ApplicationStartup(ILifetimeScope container, IPipelines pipelines)
        {
            var databaseSettings    = container.Resolve <MongoDbSettings>();
            var databaseInitializer = container.Resolve <IDatabaseInitializer>();

            databaseInitializer.InitializeAsync();
            BsonClassMap.RegisterClassMap <RemarkGroup>(x =>
            {
                x.AutoMap();
                x.UnmapMember(m => m.Criteria);
                x.UnmapMember(m => m.Members);
                x.UnmapMember(m => m.MemberCriteria);
                x.UnmapMember(m => m.MemberRole);
            });
            BsonClassMap.RegisterClassMap <BasicRemark>(x =>
            {
                x.AutoMap();
                x.UnmapMember(m => m.Distance);
                x.UnmapMember(m => m.SmallPhotoUrl);
                x.UnmapMember(m => m.Photo);
            });
            var databaseSeeder = container.Resolve <IDatabaseSeeder>();

            databaseSeeder.SeedAsync();

            pipelines.BeforeRequest += (ctx) =>
            {
                FixNumberFormat(ctx);

                return(null);
            };
            pipelines.AfterRequest += (ctx) =>
            {
                ctx.Response.Headers.Add("Access-Control-Allow-Origin", "*");
                ctx.Response.Headers.Add("Access-Control-Allow-Methods", "POST,PUT,GET,OPTIONS,DELETE");
                ctx.Response.Headers.Add("Access-Control-Allow-Headers",
                                         "Authorization, Origin, X-Requested-With, Content-Type, Accept, X-Total-Count");
            };
            _exceptionHandler = container.Resolve <IExceptionHandler>();
            Logger.Information("Collectively.Services.Storage API has started.");
        }
示例#43
0
 static MongoResponseRepository()
 {
     #region Register ClassMap
     try
     {
         if (BsonClassMap.IsClassMapRegistered(typeof(ProgramBase)) == false)
         {
             BsonClassMap.RegisterClassMap <ProgramBase>();
         }
     }
     catch { }
     try
     {
         if (BsonClassMap.IsClassMapRegistered(typeof(MEResponse)) == false)
         {
             BsonClassMap.RegisterClassMap <MEResponse>();
         }
     }
     catch { }
     #endregion
 }
        public MongoEventStore(IMongoEventStoreSettings settings)
        {
            _connectionString = settings.MongoDbEventStoreConnectionString;
            _database         = settings.MongoDbEventStoreDatabase;

            BsonClassMap.RegisterClassMap <DomainEvent>();

            var assemblies            = AppDomain.CurrentDomain.GetAssemblies();
            var domainEventSubclasses = new List <Type>();

            foreach (var a in assemblies)
            {
                var types = a.GetTypes().Where(t => typeof(DomainEvent).IsAssignableFrom(t));
                domainEventSubclasses.AddRange(types);
            }

            foreach (var subclass in domainEventSubclasses)
            {
                BsonClassMap.LookupClassMap(subclass);
            }
        }
示例#45
0
            public void PostProcess(BsonClassMap classMap)
            {
                var idMemberMap = classMap.IdMemberMap;

                if (idMemberMap == null)
                {
                    return;
                }

                var representationOptions = idMemberMap.SerializationOptions as RepresentationSerializationOptions;

                if (idMemberMap.MemberType == typeof(string) && representationOptions != null && representationOptions.Representation == BsonType.ObjectId)
                {
                    idMemberMap.SetIdGenerator(StringObjectIdGenerator.Instance);
                }
                else
                {
                    var generator = _convention.GetIdGenerator(classMap.IdMemberMap.MemberInfo);
                    idMemberMap.SetIdGenerator(generator);
                }
            }
示例#46
0
        public static void Configure()
        {
            OneTimeRunner.Run(() =>
            {
                BsonClassMap.RegisterClassMap <IdentityUser>(map =>
                {
                    map.AutoMap();
                    map.ConfigureExtraProperties();
                });

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

                BsonClassMap.RegisterClassMap <IdentityClaimType>(map =>
                {
                    map.AutoMap();
                });
            });
        }
        public static bool TryConfigureExtraProperties(this BsonClassMap map)
        {
            if (!map.ClassType.IsAssignableTo <IHasExtraProperties>())
            {
                return(false);
            }

            var property = map.ClassType.GetProperty(
                nameof(IHasExtraProperties.ExtraProperties),
                BindingFlags.Public | BindingFlags.Instance | BindingFlags.GetProperty
                );

            if (property?.DeclaringType != map.ClassType)
            {
                return(false);
            }

            map.MapExtraElementsMember(property);

            return(true);
        }
示例#48
0
        private void MapClasses()
        {
            BsonClassMap.RegisterClassMap <Prodotto>(cm =>
            {
                cm.AutoMap();
                cm.MapIdMember(c => c.Id)
                .SetIdGenerator(StringObjectIdGenerator.Instance)
                .SetSerializer(new StringSerializer(BsonType.ObjectId));
                cm.SetIgnoreExtraElements(true);

                // Unmap property
                //cm.UnmapProperty(c => c.Lat);

                /// Map private field
                //cm.MapField("type");

                // change field map name
                //cm.GetMemberMap(c => c.InsertionTime)
                //  .SetElementName("ts");
            });
        }
        protected EntityCollectionDefinition(IMongoConnectionHandler connectionHandler)
        {
            if (connectionHandler == null)
            {
                throw new ArgumentNullException("connectionHandler");
            }

            Collection = connectionHandler.Database.GetCollection <T>(typeof(T).Name.ToLower() + "s");

            // setup serialization
            if (!BsonClassMap.IsClassMapRegistered(typeof(Entity)))
            {
                BsonClassMap.RegisterClassMap <Entity>(
                    cm =>
                {
                    cm.AutoMap();
                    cm.SetIdMember(cm.GetMemberMap(c => c.Id));
                    cm.IdMemberMap.SetIdGenerator(StringObjectIdGenerator.Instance);
                });
            }
        }
        // constructors
        /// <summary>
        /// Initializes a new instance of the BsonClassMapSerializer class.
        /// </summary>
        /// <param name="classMap">The class map.</param>
        public BsonClassMapSerializer(BsonClassMap classMap)
        {
            if (classMap == null)
            {
                throw new ArgumentNullException("classMap");
            }
            if (classMap.ClassType != typeof(TClass))
            {
                var message = string.Format("Must be a BsonClassMap for the type {0}.", typeof(TClass));
                throw new ArgumentException(message, "classMap");
            }
            if (!classMap.IsFrozen)
            {
                throw new ArgumentException("Class map is not frozen.", nameof(classMap));
            }

            _classMap = classMap;
#if NETSTANDARD1_5
            CheckForISupportInitializeInterface(out _beginInitMethodInfo, out _endInitMethodInfo);
#endif
        }
示例#51
0
        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);
            }
        }
示例#52
0
        protected override void Map(BsonClassMap <Role> map)
        {
            map.SetCollection("Roles");

            map.MapMember(x => x.Enabled)
            .SetIsRequired(true);

            map.MapMember(x => x.Description)
            .SetIsRequired(false);

            map.MapMember(x => x.Name)
            .SetIsRequired(true);

            map.MapListAsRefs(x => x.AccessList, "_authorizations", cm => cm
                              .SetIsRequired(true)
                              .SetElementName("AccessList")
                              );

            map.MapMember(x => x.Private)
            .SetIsRequired(true);
        }
示例#53
0
        private void MapClasses()
        {
            // Define que o mapping utilizara o padrão CamelCase.
            var conventionPack = new ConventionPack {
                new CamelCaseElementNameConvention()
            };

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

            // Se não tivermos nenhuma classe mapeada, para esse tipo, iremos mapear.
            if (!BsonClassMap.IsClassMapRegistered(typeof(Infected)))
            {
                BsonClassMap.RegisterClassMap <Infected>(i =>
                {
                    // Aqui podemos utilizar o MapField para definir configurações especificas
                    // o AutoMap efetua o mapeamento por convenção automaticamente.
                    i.AutoMap();
                    i.SetIgnoreExtraElements(true);
                });
            }
        }
示例#54
0
        public IBsonSerializer GetSerializer(Type type)
        {
            if (typeof(IEnumerable <ContentDetail>).IsAssignableFrom(type))
            {
                return(new ContentCollectionSerializer <ContentDetail>());
            }
            if (typeof(IEnumerable <DetailCollection>).IsAssignableFrom(type))
            {
                return(new ContentCollectionSerializer <DetailCollection>());
            }
            if (typeof(ContentItem).IsAssignableFrom(type))
            {
                return(new ContentSerializer(type, database, proxies));
            }
            if (typeof(DetailCollection) == type)
            {
                return(new BsonClassMapSerializer(BsonClassMap.LookupClassMap(type)));
            }

            return(null);
        }
示例#55
0
 // Driver is initialized late to give chance for custom conventions and class maps to be registered
 // StorageProvider Init() is called before any custom bootstrap provider
 private void EnsureDriverInitialized(IEnumerable <IMongoDriverBootstrap> bootstraps)
 {
     if (_isDriverInitialized)
     {
         return;
     }
     lock (DriverInitializationLock)
     {
         foreach (var bootstrap in bootstraps)
         {
             bootstrap.Init();
         }
         BsonSerializer.RegisterSerializationProvider(new OrleansSerializerProvider(_grainReferenceConverter));
         // Register class maps if they are not registered yet
         foreach (var grainStateType in _options.GrainAssemblies.SelectMany(a => a.GetGrainStateTypes()))
         {
             BsonClassMap.LookupClassMap(grainStateType);
         }
         _isDriverInitialized = true;
     }
 }
            public void Apply(BsonClassMap classMap)
            {
                if (classMap.ClassType.Namespace.Contains("AppStoreService.Core"))
                {
                    foreach (var map in classMap.DeclaredMemberMaps.Where(x => x != null))
                    {
                        if (map.MemberType == typeof(object) &&
                            (map.MemberName == "Id" || map.MemberName == "ObjectId"))
                        {
                            classMap.MapIdMember(map.MemberInfo);
                            map.SetIdGenerator(new ObjectIdGenerator());
                        }

                        if (map.MemberType.IsGenericParameter && map.MemberType.GetGenericTypeDefinition() ==
                            typeof(NullValueDictionary <,>))
                        {
                            classMap.MapExtraElementsMember(map.MemberInfo);
                        }
                    }
                }
            }
示例#57
0
        public static IServiceCollection AddInfrastructure(this IServiceCollection services)
        {
            BsonClassMap.RegisterClassMap <MemberAssignment>(cm =>
            {
                cm.AutoMap();
                cm.MapCreator(x => new MemberAssignment(x.User, x.Role));
            });

            BsonClassMap.RegisterClassMap <Assignment>(cm =>
            {
                cm.AutoMap();
                cm.MapCreator(x => new Assignment(
                                  x.Organization,
                                  x.IsDelegatedToCOA,
                                  x.Assignees));
            });

            return(services
                   .AddScoped <IReportScheduleRepository, ReportScheduleRepository>()
                   .AddTransient <IDateTimeService, DateTimeService>());
        }
示例#58
0
        public void Register()
        {
            SafeRegisterClassMap <PullRequestsReport>();
            SafeRegisterClassMap <AggregatedWorkitemsETAReport>();
            SafeRegisterClassMap <WorkItemsReport>();
            SafeRegisterClassMap <ReOpenedWorkItemsReport>();
            BsonClassMap.RegisterClassMap <WorkItem>(cm =>
            {
                cm.AutoMap();
                cm.MapMember(c => c.Fields).SetSerializer(new DictionaryInterfaceImplementerSerializer <Dictionary <string, string> >(DictionaryRepresentation.ArrayOfDocuments));
            });

            BsonClassMap.RegisterClassMap <WorkItemUpdateViewModel>(cm =>
            {
                cm.AutoMap();
                cm.MapMember(c => c.Fields).SetSerializer(new DictionaryInterfaceImplementerSerializer <Dictionary <string, WorkItemFieldUpdate> >(DictionaryRepresentation.ArrayOfDocuments));
            });

            BsonClassMap.RegisterClassMap <WorkItemFieldUpdate>();
            BsonClassMap.RegisterClassMap <PullRequestJobDetails>();
        }
示例#59
0
        // Forma mais organizada de realizar os Data Notations
        private void MapClasses()
        {
            //Cria uma convenção e regista, detalhando o formato
            var conventionPack = new ConventionPack {
                new CamelCaseElementNameConvention()
            };

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

            // Se não tiver nenhuma classe mapeada do tipo Infected.
            if (!BsonClassMap.IsClassMapRegistered(typeof(Infected)))
            {
                BsonClassMap.RegisterClassMap <Infected>(i =>
                {
                    // Evita rescrever todas as propriedades para exibição.
                    i.AutoMap();
                    // Evita bugs, caso aja acréscimo nas propriedades da classe Infected.
                    i.SetIgnoreExtraElements(true);
                });
            }
        }
示例#60
0
 static MongoErrorLog()
 {
     BsonSerializer.RegisterSerializer(typeof(NameValueCollection), NameValueCollectionSerializer.Instance);
     BsonClassMap.RegisterClassMap <Error>(cm =>
     {
         cm.MapProperty(c => c.ApplicationName);
         cm.MapProperty(c => c.HostName).SetElementName("host");
         cm.MapProperty(c => c.Type).SetElementName("type");
         cm.MapProperty(c => c.Source).SetElementName("source");
         cm.MapProperty(c => c.Message).SetElementName("message");
         cm.MapProperty(c => c.Detail).SetElementName("detail");
         cm.MapProperty(c => c.User).SetElementName("user");
         cm.MapProperty(c => c.Time).SetElementName("time");
         cm.MapProperty(c => c.StatusCode).SetElementName("statusCode");
         cm.MapProperty(c => c.WebHostHtmlMessage).SetElementName("webHostHtmlMessage");
         cm.MapField("_serverVariables").SetElementName("serverVariables");
         cm.MapField("_queryString").SetElementName("queryString");
         cm.MapField("_form").SetElementName("form");
         cm.MapField("_cookies").SetElementName("cookies");
     });
 }