Exemple #1
1
 public void Set()
 {
     var pack = new ConventionPack {new CamelCaseElementNameConvention()};
     ConventionRegistry.Register(
        "My Custom Conventions",
        pack,
        t => t.FullName.StartsWith("Foodie."));
 }
        public void TestSave()
        {
            var server = LegacyTestConfiguration.Server;
            var database = LegacyTestConfiguration.Database;
            var collection = LegacyTestConfiguration.GetCollection<Foo>();

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

            BsonClassMap.RegisterClassMap<Foo>();

            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);
            }
        }
Exemple #3
0
        static void Poco(string[] args)
        {
            var conventionPack = new ConventionPack();
            conventionPack.Add(new CamelCaseElementNameConvention());
            ConventionRegistry.Register("camelCase", conventionPack, t => true);

            BsonClassMap.RegisterClassMap<Person>(cm =>
            {
                cm.AutoMap();
                cm.MapMember(x => x.Name).SetElementName("name");
            });

            var person = new Person
            {
                Name = "Jones",
                Age = 30,
                Colors = new List<string> { "red", "blue" },
                Pets = new List<Pet> { new Pet { Name = "Fluffy", Type = "Pig" } },
                ExtraElements = new BsonDocument("anotherName", "anotherValue")
            };

            using (var writer = new JsonWriter(Console.Out))
            {
                BsonSerializer.Serialize(writer, person);
            }
        }
Exemple #4
0
 private static void InitializeSerialization()
 {
     var conventions = new ConventionPack();
     conventions.Add(new EmptyGuidDefaultValueConvention());
     conventions.Add(new IgnoreIfDefaultConvention(true));
     ConventionRegistry.Register("CSharp310", conventions, type => type.FullName.StartsWith("MongoDB.Bson.Tests.Jira.CSharp310Tests", StringComparison.Ordinal));
 }
Exemple #5
0
        // constructors
        static LeadsDatabase()
        {
            // register the conventions
            var pack = new ConventionPack { new EnumRepresentationConvention(BsonType.String) };

            ConventionRegistry.Register("conventions", pack, t => true);
        }
        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();
        }
        //private static bool _usePBSerializationProvider_v2 = true;

        //public static bool UsePBSerializationProvider_v2 { get { return _usePBSerializationProvider_v2; } set { _usePBSerializationProvider_v2 = value; } }

        // set mongo serialization options : save enum as string
        public static void SetDefaultMongoSerializationOptions()
        {
            // enum as string, ATTENTION vérifier d'abord 
            ConventionPack conventions = new ConventionPack();
            conventions.Add(new EnumRepresentationConvention(BsonType.String));
            ConventionRegistry.Register("PB_EnumRepresentationConvention", conventions, t => true);
        }
        public static void RegisterConventions()
        {
            var pack = new ConventionPack
            {
                new EnumRepresentationConvention(BsonType.String)
            };

            ConventionRegistry.Register("EnumStringConvention", pack, t => true);
        }
 private IMongoDatabase ConnectDB()
 {
     var mongoSection = Configuration.GetSection("MongoDB");
     var client = new MongoClient(mongoSection.GetSection("ConnectionString").Value);
     var pack = new ConventionPack();
     pack.Add(new CamelCaseElementNameConvention());
     ConventionRegistry.Register("camel case", pack, t => true);
     return client.GetDatabase(mongoSection.GetSection("Database").Value);           
 }
Exemple #10
0
        private void ConfigureConvention()
        {
            var pack = new ConventionPack();
            pack.Add(new CamelCaseElementNameConvention());

            ConventionRegistry.Register("camelCaseConvention",
                pack,
                x => x.FullName.StartsWith("medis.Api.Models"));
        }
        private static void RegisterConventionsImpl()
        {
            var pack = new ConventionPack
            {
                new CamelCaseElementNameConvention(),
                new IgnoreIfNullConvention(false)
            };

            ConventionRegistry.Register("all", pack, type => true);
        }
        // constructors
        static AssetViewDatabase()
        {
            // register the conventions
            var pack = new ConventionPack
                            {
                                new CamelCaseElementNameConvention(),
                                new EnumRepresentationConvention(BsonType.String)
                            };

            ConventionRegistry.Register("conventions", pack, t => true);
        }
        public DistrictsRepository(IMongoClient client, string database)
        {
            // todo: move this out to IOC config
            var cp = new ConventionPack();
            cp.Add(new CamelCaseElementNameConvention());
            ConventionRegistry.Register("camel case", cp, x => true);

            _client = client;
            _db = _client.GetDatabase(database);
            _collection = _db.GetCollection<District>("districts");
        }
        public void TestMappingUsesMemberSerializationOptionsConventionDoesNotMatchWrongProperty()
        {
            var pack = new ConventionPack();
            pack.Add(new MemberSerializationOptionsConvention(typeof(ObjectId), new RepresentationSerializationOptions(BsonType.JavaScriptWithScope)));
            ConventionRegistry.Register("test", pack, t => t == typeof(A));

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

            var options = classMap.GetMemberMap("NoMatch").SerializationOptions;
            Assert.IsNull(options);
        }
        public void TestMappingUsesMemberDefaultValueConventionDoesNotMatchWrongProperty()
        {
            var pack = new ConventionPack();
            pack.Add(new MemberDefaultValueConvention(typeof(int), 1));
            ConventionRegistry.Register("test", pack, t => t == typeof(A));

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

            var defaultValue = classMap.GetMemberMap("NoMatch").DefaultValue;
            Assert.Equal(0L, defaultValue);
        }
        /// <summary>
        /// Sets MongoDb global Conventions
        /// 
        /// This method should be called only once on startup
        /// </summary>
        /// <param name="conventions"></param>
        public virtual void SetConventions(IEnumerable<IConvention> conventions = null)
        {
            // Map global convention to all serialization
            var pack = new ConventionPack();
            pack.Add(new IgnoreExtraElementsConvention(true));

            if (conventions != null)
                pack.AddRange(conventions);

            ConventionRegistry.Register("ApplicationConventions", pack, t => true);
        }
Exemple #17
0
 public async Task InstallDatabase()
 {
     var mongoConventions = new ConventionPack();
     mongoConventions.Add(new CamelCaseElementNameConvention());
     mongoConventions.Add(new IgnoreExtraElementsConvention(true));
     mongoConventions.Add(new StringEnumConvention());
     ConventionRegistry.Register("camel case", mongoConventions, t => true);
     BsonDefaults.GuidRepresentation = GuidRepresentation.Standard;
     var mongoClient = new MongoClient(_connectionString);
     var database = mongoClient.GetDatabase(_databaseName);
     await RunMigrations(database);
 }
        public void TestMappingUsesMemberDefaultValueConvention()
        {
            var pack = new ConventionPack();
            pack.Add(new MemberDefaultValueConvention(typeof(int), 1));
            ConventionRegistry.Register("test", pack, t => t == typeof(A));

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

            var defaultValue = classMap.GetMemberMap("Match").DefaultValue;
            Assert.IsInstanceOf<int>(defaultValue);
            Assert.AreEqual(1, defaultValue);
        }
        public void TestMappingUsesMemberSerializationOptionsConventionDoesNotOverrideAttribute()
        {
            var pack = new ConventionPack();
            pack.Add(new MemberSerializationOptionsConvention(typeof(ObjectId), new RepresentationSerializationOptions(BsonType.JavaScriptWithScope)));
            ConventionRegistry.Register("test", pack, t => t == typeof(B));

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

            var options = classMap.GetMemberMap("Match").SerializationOptions;
            Assert.IsInstanceOf<RepresentationSerializationOptions>(options);
            Assert.AreEqual(BsonType.ObjectId, ((RepresentationSerializationOptions)options).Representation);
        }
        public void TestMappingUsesMemberDefaultValueConventionDoesNotOverrideAttribute()
        {
            var pack = new ConventionPack();
            pack.Add(new MemberDefaultValueConvention(typeof(int), 1));
            ConventionRegistry.Register("test", pack, t => t == typeof(B));

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

            var defaultValue = classMap.GetMemberMap("Match").DefaultValue;
            Assert.IsType<int>(defaultValue);
            Assert.Equal(2, defaultValue);
        }
Exemple #21
0
        public IMongoDatabaseBuilder RegisterDefaultConventionPack()
        {
            var conventionPack = new ConventionPack
            {
                new EnumRepresentationConvention(BsonType.String),
                new ImmutableConvention(),
                new IgnoreExtraElementsConvention(true)
            };

            RegisterConventionPack("Default", conventionPack, t => true);

            return(this);
        }
Exemple #22
0
        public MongoEventStore(IConfiguration configuration, IMongoClient mongoClient)
        {
            _databaseName = configuration["Mongo:DatabaseName"] ?? "EventStore";

            var conventionPack = new ConventionPack
            {
                new MapReadOnlyPropertiesConvention()
            };

            ConventionRegistry.Register("Conventions", conventionPack, _ => true);

            _mongoClient = mongoClient;
        }
 public Startup(IHostingEnvironment env, IApplicationEnvironment appEnv)
 {
     // configuration
     var builder = new ConfigurationBuilder(appEnv.ApplicationBasePath)
         .AddJsonFile("config.json")
         .AddJsonFile($"config.{env.EnvironmentName}.json", optional: true);
     builder.AddEnvironmentVariables();
     Configuration = builder.Build();
     // MongoDB objects attributes naming conventions
     var conventionPack = new ConventionPack();
     conventionPack.Add(new CamelCaseElementNameConvention());
     ConventionRegistry.Register("CamelCase", conventionPack, t => true);
 }
        static AbstractRepository()
        {
            var pack = new ConventionPack();
            var ignoreIfNull = new IgnoreIfNullConvention(true);
            pack.Add(ignoreIfNull);
            ConventionRegistry.Register("ignoreNulls", pack, t => true);

            Migrations.CreatePointsOfInterest();
            Migrations.CreateUsers();
            Migrations.EnsureGeospacialIndex();
            Migrations.EnsureUniqueEmailIndex();
            Migrations.CreateLocationTypes();
        }
        public void TestMappingUsesMemberDefaultValueConventionDoesNotMatchWrongProperty()
        {
            var pack = new ConventionPack();

            pack.Add(new MemberDefaultValueConvention(typeof(int), 1));
            ConventionRegistry.Register("test", pack, t => t == typeof(A));

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

            var defaultValue = classMap.GetMemberMap("NoMatch").DefaultValue;

            Assert.AreEqual(0, defaultValue);
        }
Exemple #26
0
        private static void SetupConventions()
        {
            if (isConventionSetup)
            {
                return;
            }
            var enumConventionPack = new ConventionPack {
                new EnumRepresentationConvention(BsonType.String)
            };

            ConventionRegistry.Register("EnumSerializationConvention", enumConventionPack, t => t.IsEnum);
            isConventionSetup = true;
        }
    public MongoDbService(MongoClientSettings settings, string databaseName)
    {
        ConventionPack conventionPack = new ConventionPack {
            new CamelCaseElementNameConvention()
        };

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

        MongoClient    client   = new MongoClient(settings);
        IMongoDatabase database = client.GetDatabase(databaseName);

        users = new UserCollection(database.GetCollection <UserModel>("users"));
    }
Exemple #28
0
        public static void Init()
        {
            var pack = new ConventionPack();

            pack.Add(new CamelCaseElementNameConvention());

            ConventionRegistry.Register("CamelCase", pack, t => t.FullName.StartsWith("MongoDB.Migrations.Tool.Entity."));
            BsonClassMap.RegisterClassMap <Book>(cm =>
            {
                cm.AutoMap();
                cm.SetIgnoreExtraElements(true);
            });
        }
        public void TestMappingUsesMemberSerializationOptionsConventionDoesNotMatchWrongProperty()
        {
            var pack = new ConventionPack();

            pack.Add(new MemberSerializationOptionsConvention(typeof(ObjectId), new RepresentationSerializationOptions(BsonType.JavaScriptWithScope)));
            ConventionRegistry.Register("test", pack, t => t == typeof(A));

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

            var options = classMap.GetMemberMap("NoMatch").SerializationOptions;

            Assert.IsNull(options);
        }
        private void RegisterConventions()
        {
            var pack = new ConventionPack();

            pack.Add(new EnumRepresentationConvention(BsonType.Int32));
            pack.Add(new IgnoreIfNullConvention(true));
            pack.Add(new IgnoreIfDefaultConvention(false));

            Assembly entitiesAssembly = typeof(Post).GetTypeInfo().Assembly;

            ConventionRegistry.Register("MongoDbSpecs pack", pack,
                                        t => t.GetTypeInfo().Assembly == entitiesAssembly);
        }
Exemple #31
0
        public void Setup()
        {
            var camelCaseConvention = new ConventionPack {
                new CamelCaseElementNameConvention()
            };

            ConventionRegistry.Register("CamelCase", camelCaseConvention, type => true);

            var client = new MongoClient(Constants.MongoDbConnectionUri());

            _moviesCollection   = client.GetDatabase("sample_mflix").GetCollection <Movie>("movies");
            _commentsCollection = client.GetDatabase("sample_mflix").GetCollection <Comment>("comments");
        }
        static ArticlesContext()
        {
            // Conventions
            var managedTypes = new HashSet <Type> {
                typeof(Article)
            };

            var conventions = new ConventionPack();

            conventions.Add(new GuidRepresentationConvention(BsonType.String));

            ConventionRegistry.Register("ManagedTypeConventions", conventions, managedTypes.Contains);
        }
 /// <summary>
 /// Registers the MongoDB Bson serialization conventions.
 /// </summary>
 /// <param name="autoGenerateID">A <see cref="Boolean"/> value which indicates whether
 /// the ID value should be automatically generated when a new document is inserting.</param>
 /// <param name="localDateTime">A <see cref="Boolean"/> value which indicates whether
 /// the local date/time should be used when serializing/deserializing <see cref="DateTime"/> values.</param>
 /// <param name="additionConventions">Additional conventions that needs to be registered.</param>
 public static void RegisterConventions(bool autoGenerateID, bool localDateTime, IEnumerable<IConvention> additionConventions)
 {
     var conventionPack = new ConventionPack();
     conventionPack.Add(new NamedIdMemberConvention("id", "Id", "ID", "iD"));
     if (autoGenerateID)
         conventionPack.Add(new GuidIDGeneratorConvention());
     if (localDateTime)
         conventionPack.Add(new UseLocalDateTimeConvention());
     if (additionConventions != null)
         conventionPack.AddRange(additionConventions);
     
     ConventionRegistry.Register("DefaultConvention", conventionPack, t => true);
 }
        public CommentsRepository(IMongoClient mongoClient)
        {
            var camelCaseConvention = new ConventionPack {
                new CamelCaseElementNameConvention()
            };

            ConventionRegistry.Register("CamelCase", camelCaseConvention, type => true);

            _commentsCollection = mongoClient.GetDatabase("sample_mflix").GetCollection <Comment>("comments");
            _moviesRepository   = new MoviesRepository(mongoClient);

            _userRepository = new UsersRepository(mongoClient);
        }
Exemple #35
0
        private void AddFilters(HttpConfiguration config)
        {
            config.Filters.Add(new ModelValidationFilterAttribute());

            config.Formatters.JsonFormatter.SerializerSettings.ContractResolver =
                new CamelCasePropertyNamesContractResolver();

            var pack = new ConventionPack {
                new CamelCaseElementNameConvention()
            };

            ConventionRegistry.Register("camelCaseFields", pack, t => true);
        }
Exemple #36
0
        public MysteryMongoDb()
        {
            //we apply our conventions

            //enums shall became string
            var pack = new ConventionPack  {
                new EnumRepresentationConvention(BsonType.String),
                new IgnoreExtraElementsConvention(ignoreExtraElements: true),
            };

            ConventionRegistry.Register("MysteryConvetions", pack, t => true);
            BsonSerializer.RegisterSerializer(typeof(DateTime), DateTimeSerializer.LocalInstance);
        }
        /// <summary>
        /// Instala os mapeamentos dos modelos para o MongoDB
        /// </summary>
        public static void Install()
        {
            // Define como Camel Case o nome das chaves de cada registro no banco de dados
            ConventionPack conventionPack = new ConventionPack {
                new CamelCaseElementNameConvention()
            };

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

            AuctionMap.Configure();
            AuctionResponsibleUserMap.Configure();
            UserMap.Configure();
        }
        public static Bootstrapper UseMongoDbAsMainRepository(this Bootstrapper bootstrapper, MongoDbOptions options)
        {
            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }

            var service = new MongoDbDALBootstrapperService
            {
                BootstrappAction = (ctx) =>
                {
                    if (BsonSerializer.SerializerRegistry.GetSerializer <Type>() == null)
                    {
                        BsonSerializer.RegisterSerializer(typeof(Type), new TypeSerializer());
                    }
                    if (BsonSerializer.SerializerRegistry.GetSerializer <Guid>() == null)
                    {
                        BsonSerializer.RegisterSerializer(typeof(Guid), new GuidSerializer());
                    }
                    MongoDbContext.DatabaseName = options.DatabaseName;
                    MongoDbContext.MongoClient  = new MongoDB.Driver.MongoClient(options.Url);

                    var pack = new ConventionPack();
                    pack.Add(new IgnoreExtraElementsConvention(true));
                    ConventionRegistry.Register("CQELight conventions", pack, _ => true);

                    if (ctx.IsServiceRegistered(BootstrapperServiceType.IoC))
                    {
                        bootstrapper.AddIoCRegistration(new TypeRegistration <MongoDataReaderAdapter>(true));
                        bootstrapper.AddIoCRegistration(new TypeRegistration <MongoDataWriterAdapter>(true));

                        var entities = ReflectionTools.GetAllTypes()
                                       .Where(t => typeof(IPersistableEntity).IsAssignableFrom(t)).ToList();
                        foreach (var item in entities)
                        {
                            var mongoRepoType      = typeof(MongoRepository <>).MakeGenericType(item);
                            var dataReaderRepoType = typeof(IDataReaderRepository <>).MakeGenericType(item);
                            var databaseRepoType   = typeof(IDatabaseRepository <>).MakeGenericType(item);
                            var dataUpdateRepoType = typeof(IDataUpdateRepository <>).MakeGenericType(item);

                            bootstrapper
                            .AddIoCRegistration(new FactoryRegistration(() => mongoRepoType.CreateInstance(),
                                                                        mongoRepoType, dataUpdateRepoType, databaseRepoType, dataReaderRepoType));
                        }
                    }
                }
            };

            bootstrapper.AddService(service);
            return(bootstrapper);
        }
        // public static methods
        /// <summary>
        /// Looks up the effective set of conventions that apply to a type.
        /// </summary>
        /// <param name="type">The type.</param>
        /// <returns>The conventions for that type.</returns>
        public static IConventionPack Lookup(Type type)
        {
            if (type == null)
            {
                throw new ArgumentNullException("type");
            }

            lock (__lock)
            {
                var pack = new ConventionPack();

                // append any attribute packs (usually just one) at the end so attributes are processed last
                var attributePacks = new List<IConventionPack>();
#pragma warning disable 618 //obsoleted by ConventionProfile
                ConventionProfile conventionProfile = null;
#pragma warning restore 618
                foreach (var container in __conventionPacks)
                {
                    if (container.Filter(type))
                    {
#pragma warning disable 618 //obsoleted by ConventionProfile
                        if (container.Pack is ConventionProfile)
                        {
                            conventionProfile = container.Pack as ConventionProfile;
                        }
#pragma warning restore 618

                        if (container.Name == "__attributes__")
                        {
                            attributePacks.Add(container.Pack);
                        }
                        else
                        {
                            pack.Append(container.Pack);
                        }
                    }
                }
                if (conventionProfile != null)
                {
                    // already includes the default attribute convention pack
                    return conventionProfile; 
                }

                foreach (var attributePack in attributePacks)
                {
                    pack.Append(attributePack);
                }

                return pack;
            }
        }
        static MongoEventStoreTests()
        {
            var pack = new ConventionPack
            {
                new CamelCaseElementNameConvention(),
                new IgnoreExtraElementsConvention(true)
            };

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

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

            BsonDefaults.GuidRepresentation = GuidRepresentation.Standard;
        }
Exemple #41
0
        static void Setup()
        {
            var camelCaseConvention = new ConventionPack {
                new CamelCaseElementNameConvention()
            };

            ConventionRegistry.Register("CamelCase", camelCaseConvention, type => true);

            var mongoUri       = mongoConnectionString;
            var mflixClient    = new MongoClient(mongoUri);
            var moviesDatabase = mflixClient.GetDatabase("sample_mflix");

            _moviesCollection = moviesDatabase.GetCollection <Movie>("movies");
        }
        protected virtual void RegisterConventions()
        {
            var pack = new ConventionPack();

            pack.Add(new EnumRepresentationConvention(BsonType.Int32));
            pack.Add(new IgnoreIfNullConvention(true));
            pack.Add(new IgnoreIfDefaultConvention(false));

            Assembly thisAssembly = typeof(IdentityMongoDbContext <>).GetTypeInfo().Assembly;

            ConventionRegistry.Register("Identity custom pack",
                                        pack,
                                        t => t.GetTypeInfo().Assembly == thisAssembly);
        }
Exemple #43
0
        public async Task InstallDatabase()
        {
            var mongoConventions = new ConventionPack();

            mongoConventions.Add(new CamelCaseElementNameConvention());
            mongoConventions.Add(new IgnoreExtraElementsConvention(true));
            mongoConventions.Add(new StringEnumConvention());
            ConventionRegistry.Register("camel case", mongoConventions, t => true);
            BsonDefaults.GuidRepresentation = GuidRepresentation.Standard;
            var mongoClient = new MongoClient(_connectionString);
            var database    = mongoClient.GetDatabase(_databaseName);

            await RunMigrations(database);
        }
        public static void Init()
        {
            var pack = new ConventionPack
            {
                new CamelCaseElementNameConvention()
            };

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

            EntityMapperInitializer.Init();
        }
        private static void Register()
        {
            var conventionPack = new ConventionPack {
                new IgnoreExtraElementsConvention(true)
            };

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

            if (!_isRegistered)
            {
                BsonSerializer.RegisterSerializer(typeof(DateTime), new UtcDateTimeSerializer());
                _isRegistered = true;
            }
        }
        public void TestMappingUsesMemberSerializationOptionsConventionDoesNotOverrideAttribute()
        {
            var pack = new ConventionPack();

            pack.Add(new MemberSerializationOptionsConvention(typeof(ObjectId), new RepresentationSerializationOptions(BsonType.JavaScriptWithScope)));
            ConventionRegistry.Register("test", pack, t => t == typeof(B));

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

            var options = classMap.GetMemberMap("Match").SerializationOptions;

            Assert.IsInstanceOf <RepresentationSerializationOptions>(options);
            Assert.AreEqual(BsonType.ObjectId, ((RepresentationSerializationOptions)options).Representation);
        }
        public void Init()
        {
            var user     = EnvironmentConstants.MONGO_DB_USER.GetAsMandatoryEnvironmentVariable();
            var password = EnvironmentConstants.MONGO_DB_PASSWORD.GetAsMandatoryEnvironmentVariable();

            _client   = new MongoClient($"mongodb://{user}:{password}@mongo");
            _database = _client.GetDatabase("propertyCrawler");

            var pack = new ConventionPack {
                new IgnoreExtraElementsConvention(true)
            };

            ConventionRegistry.Register("My Solution Conventions", pack, t => true);
        }
Exemple #48
0
        public IMongoDatabase GetDatabase()
        {
            var url      = new MongoUrl(_configuration.GetConnectionString("Mongo"));
            var client   = new MongoClient(url);
            var database = client.GetDatabase("HumanResources");

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

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

            return(database);
        }
Exemple #49
0
        public void Setup()
        {
            var camelCaseConvention = new ConventionPack {
                new CamelCaseElementNameConvention()
            };

            ConventionRegistry.Register("CamelCase", camelCaseConvention, type => true);

            var client = new MongoClient(Constants.MongoDbConnectionUri());

            _theatersCollection = client.GetDatabase("sample_mflix").GetCollection <Theater>("theaters");

            AddTestTheaters();
        }
Exemple #50
0
        public void TestMappingUsesMemberDefaultValueConventionDoesNotOverrideAttribute()
        {
            var pack = new ConventionPack();

            pack.Add(new MemberDefaultValueConvention(typeof(int), 1));
            ConventionRegistry.Register("test", pack, t => t == typeof(B));

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

            var defaultValue = classMap.GetMemberMap("Match").DefaultValue;

            Assert.IsType <int>(defaultValue);
            Assert.Equal(2, defaultValue);
        }
Exemple #51
0
        /// <summary>
        /// Sets MongoDb global Conventions
        ///
        /// This method should be called only once on startup
        /// </summary>
        /// <param name="conventions"></param>
        public virtual void SetConventions(IEnumerable <IConvention> conventions = null)
        {
            // Map global convention to all serialization
            var pack = new ConventionPack();

            pack.Add(new IgnoreExtraElementsConvention(true));

            if (conventions != null)
            {
                pack.AddRange(conventions);
            }

            ConventionRegistry.Register("ApplicationConventions", pack, t => true);
        }
Exemple #52
0
        public static void ForType <T>(string idPropName)
        {
            var t = typeof(T);

            lock (_done)
            {
                if (_done.Add(t))
                {
                    var cp = new ConventionPack();
                    cp.AddClassMapConvention(t.Name + "ids", bcm => bcm.MapIdProperty(idPropName));
                    ConventionRegistry.Register(t.Name + "idsPack", cp, type => type == t);
                }
            }
        }
Exemple #53
0
        public static IServiceCollection WithMongo(this IServiceCollection services, IConfiguration configuration)
        {
            services.Configure <MongoSettings>(configuration.GetSection("MongoSettings"));

            var pack = new ConventionPack {
                new IgnoreExtraElementsConvention(true)
            };

            ConventionRegistry.Register("My Solution Conventions", pack, t => true);

            BaseModelConfiguration.Configure();

            return(services);
        }
Exemple #54
0
        static CSharp648Tests()
        {
            // suppressing the _id by registering the class map manually
            BsonClassMap.RegisterClassMap<U2>(cm =>
            {
                cm.AutoMap();
                cm.SetIdMember(null);
            });

            // suppressing the _id by using the NoIdMemberConvention
            var pack = new ConventionPack();
            pack.Add(new NoIdMemberConvention());
            ConventionRegistry.Register("U3noid", pack, t => t == typeof(U3));
        }
Exemple #55
0
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            GlobalConfiguration.Configure(WebApiConfig.Register);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            var pack = new ConventionPack()
            {
                new EnumRepresentationConvention(BsonType.String)
            };

            ConventionRegistry.Register("EnumStringConvention", pack, t => true);
        }
        internal void RegisterMongoDbConventions()
        {
            var appConventions = new ConventionPack
            {
                new IgnoreExtraElementsConvention(true),
                new EnumRepresentationConvention(BsonType.String),
                new NamedIdMemberConvention("Id"),
            };

            BsonClassMap.RegisterClassMap<EventMetadata>();
            ConventionRegistry.Register("Core", appConventions, type => true);

            BsonSerializer.RegisterSerializer(typeof(DateTime), new DateTimeSerializer(new DateTimeSerializationOptions(DateTimeKind.Utc)));
            BsonSerializer.RegisterSerializer(typeof(DateTime?), new NullableSerializer<DateTime>());
        }
        private void InitializeDatabase(string connectionString)
        {
            // Specify, that null values should be ignored by BsonSerializer
            var p = new ConventionPack
            {
                new IgnoreIfNullConvention(true),
                new IgnoreExtraElementsConvention(true)
            };
            ConventionRegistry.Register("all", p, t => true);

            var urlBuilder = new MongoUrlBuilder(connectionString);
            dbPrefix = urlBuilder.DatabaseName;
            if (string.IsNullOrWhiteSpace(dbPrefix))
                throw new ArgumentException("Connection string must include database name prefix. E.g. mongodb://mongodb01/staging");
            mongoClient = new MongoClient(connectionString);
            mongoServer = mongoClient.GetServer();
        }
        static async Task classBarmoloMetodusConventionPack()
        {
            var conventionPack = new ConventionPack();
            conventionPack.Add(new CamelCaseElementNameConvention());
            ConventionRegistry.Register("camelCase", conventionPack, t => true);           

            var person = new Person
            {
                Name = "Jones",
                Age = 34,
                //Colors = new List<string> { "red", "green" },
                //Pets = new List<Pet> { new Pet { Name = "Fluffy", Type = "Pig" } },
                //ExtraElements = new BsonDocument("anotherName", "anotherValue")
            };

            using (var writer = new JsonWriter(Console.Out))
            {
                BsonSerializer.Serialize(writer, person);
            }
        }
        public MongoContext()
        {
            var pack = new ConventionPack()
            {
                new CamelCaseElementNameConvention(),
                new EnumRepresentationConvention(BsonType.String)
            };

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

            var mongoUrlBuilder = new MongoUrlBuilder(ConfigurationManager.ConnectionStrings["AuthContext"].ConnectionString);

            var mongoClient = new MongoClient(mongoUrlBuilder.ToMongoUrl());
            var server = mongoClient.GetServer();

            Database = server.GetDatabase(mongoUrlBuilder.DatabaseName);

            userCollection = Database.GetCollection<User>("users");
            roleCollection = Database.GetCollection<Role>("roles");
            clientCollection = Database.GetCollection<Client>("clients");
            refreshTokenCollection = Database.GetCollection<RefreshToken>("refreshTokens");
        }
        protected BaseTest()
        {
            //  http://stackoverflow.com/questions/19521626/mongodb-convention-packs
            ConventionPack conventionPack = new ConventionPack { new CamelCaseElementNameConvention() };
            ConventionRegistry.Register("camelCase", conventionPack, x => true);

            string connectionString = String.Format("mongodb://{0}:{1}", MongoServerAddress, MongoServerPort);
            var mongoClient = new MongoClient(connectionString);

            BlogContext = new BlogContext(mongoClient);
            Task blogContextResetDataTask = BlogContext.ResetData();

            SchoolContext = new SchoolContext(mongoClient);
            Task schoolContextResetDataTask = SchoolContext.ResetData();

            TestContext = new TestContext(mongoClient);
            Task testContextResetDataTask = TestContext.ResetData();

            testContextResetDataTask.Wait();
            blogContextResetDataTask.Wait();
            schoolContextResetDataTask.Wait();
        }