コード例 #1
0
        public void TestSave()
        {
            var server     = Configuration.TestServer;
            var database   = Configuration.TestDatabase;
            var collection = Configuration.GetTestCollection <Foo>();

            var conventions = new ConventionProfile()
                              .SetIdMemberConvention(new NamedIdMemberConvention("_id"));

            BsonClassMap.RegisterConventions(conventions, t => t == typeof(Foo));

            collection.RemoveAll();
            for (int i = 0; i < 10; i++)
            {
                var foo = new Foo
                {
                    _id     = ObjectId.Empty,
                    Name    = string.Format("Foo-{0}", i),
                    Summary = string.Format("Summary for Foo-{0}", i)
                };
                collection.Save(foo, SafeMode.True);
                var count = collection.Count();
                Assert.AreEqual(i + 1, count);
            }
        }
コード例 #2
0
        public void TestSave()
        {
            var server     = MongoServer.Create("mongodb://localhost/?safe=true");
            var database   = server["onlinetests"];
            var collection = database.GetCollection <Foo>("csharp77");

            var conventions = new ConventionProfile()
                              .SetIdMemberConvention(new NamedIdMemberConvention("_id"));

            BsonClassMap.RegisterConventions(conventions, t => t == typeof(Foo));

            collection.RemoveAll();
            for (int i = 0; i < 10; i++)
            {
                var foo = new Foo
                {
                    _id     = ObjectId.Empty,
                    Name    = string.Format("Foo-{0}", i),
                    Summary = string.Format("Summary for Foo-{0}", i)
                };
                collection.Save(foo, SafeMode.True);
                var count = collection.Count();
                Assert.AreEqual(i + 1, count);
            }
        }
コード例 #3
0
ファイル: EmailScheduler.cs プロジェクト: Lietuva2/LT2
        /// <summary>
        /// Main entry of the program.
        /// </summary>
        public static void Main()
        {
            MongoObjectIdGenerator.Register();
            MongoObjectIdSerializer.Register();

            BsonClassMap.RegisterConventions(new ConventionProfile().SetSerializationOptionsConvention(new LocalDateTimeSerializationConvention()), c => true);

            IKernel kernel = new StandardKernel();

            NinjectBindings.RegisterServices(kernel);
            ServiceLocator.Resolver = kernel.GetService;

            kernel.Bind <EmailScheduler>().ToSelf();
            kernel.Bind <IBus>().To <NullBus>();
            //kernel.Load(Assembly.GetExecutingAssembly());

            var sheduller = kernel.Get <EmailScheduler>();

#if DEBUG
            sheduller.OnStart(null);
            Console.ReadKey();
#else
            try
            {
                System.ServiceProcess.ServiceBase.Run(sheduller);
            }
            catch (Exception e)
            {
                Log.Information(String.Format("Starting service failed: {0}.", e));
            }
#endif
        }
コード例 #4
0
        private static void InitializeSerialization()
        {
            var conventions = new ConventionProfile();

            conventions.SetDefaultValueConvention(new EmptyGuidDefaultValueConvention());
            conventions.SetSerializeDefaultValueConvention(new NeverSerializeDefaultValueConvention());
            BsonClassMap.RegisterConventions(conventions, type => type.FullName.StartsWith("MongoDB.BsonUnitTests.Jira.CSharp310Tests"));
        }
コード例 #5
0
        public virtual void Init()
        {
            var profile = new ConventionProfile();

            profile.SetMemberFinderConvention(new LoggingMemberFinderConvention());
            BsonClassMap.RegisterClassMap(new ExceptionMap());
            BsonClassMap.RegisterClassMap(new LocationInformationMap());
            BsonClassMap.RegisterConventions(profile, t => true);
        }
コード例 #6
0
        static MongoDbSagaPersister()
        {
            ElementNameConventions = new SagaDataElementNameConvention();

            var conventionProfile = new ConventionProfile()
                                    .SetElementNameConvention(ElementNameConventions);

            BsonClassMap.RegisterConventions(conventionProfile, t => typeof(ISagaData).IsAssignableFrom(t));
        }
コード例 #7
0
        private static void InitializeSerialization()
        {
            var conventions = new ConventionProfile();

            conventions.SetDefaultValueConvention(new EmptyGuidDefaultValueConvention());
#pragma warning disable 618 // SetSerializeDefaultValueConvention and NeverSerializeDefaultValueConvention are obsolete
            conventions.SetSerializeDefaultValueConvention(new NeverSerializeDefaultValueConvention());
#pragma warning restore 618
            BsonClassMap.RegisterConventions(conventions, type => type.FullName.StartsWith("MongoDB.BsonUnitTests.Jira.CSharp310Tests", StringComparison.Ordinal));
        }
        /// <summary>
        /// Initializes the driver after it has been instantiated.
        /// </summary>
        /// <param name="cxInfo">the serialized connection properties.</param>
        /// <param name="context">The driver object</param>
        /// <param name="executionManager">The current Query Execution Manager for this query</param>
        public override void InitializeContext(IConnectionInfo cxInfo, object context, QueryExecutionManager executionManager)
        {
            base.InitializeContext(cxInfo, context, executionManager);

            //since the type is generated dynamically we can only access it by reflection
            ConnectionProperties props = propsSerializer.Deserialize(cxInfo.DriverData);

            PropertyInfo pinf = context.GetType().GetProperty("SqlTabWriter", BindingFlags.Instance | BindingFlags.Public);

            pinf.SetValue(context, executionManager.SqlTranslationWriter, null);

            if (props.InitializationQuery != null)
            {
                MethodInfo customInitialize = context.GetType().GetMethod("DoCustomInit", new[] { typeof(ConnectionProperties) });
                customInitialize.Invoke(context, new object[] { props });
            }

            MethodInfo init = context.GetType().GetMethod("InitCollections", BindingFlags.Instance | BindingFlags.Public);

            init.Invoke(context, new object[] { });



            if (!mSerializersAlreadyRegistered && props.CustomSerializers != null)
            {
                List <Assembly> assemblies =
                    props.AssemblyLocations.Select(LoadAssemblySafely).ToList();

                foreach (var pair in props.CustomSerializers)
                {
                    var type       = assemblies.Select(a => a.GetType(pair.Key)).FirstOrDefault(x => x != null);
                    var serializer = assemblies.Select(a => a.GetType(pair.Value)).FirstOrDefault(x => x != null);
                    if (type == null || serializer == null)
                    {
                        return;
                    }
                    //throw new Exception(string.Format("Unable to initialize custom serializer {0} for type {1}", pair.Value, pair.Key));

                    BsonSerializer.RegisterSerializer(type, (IBsonSerializer)Activator.CreateInstance(serializer));
                }

                mSerializersAlreadyRegistered = true;
            }

            if (props.AdditionalOptions.BlanketIgnoreExtraElements)
            {
                var conventions = new ConventionProfile();
                conventions.SetIgnoreExtraElementsConvention(new AlwaysIgnoreExtraElementsConvention());

                BsonClassMap.RegisterConventions(conventions, t => true);
            }

            //set as default
            MongoDB.Bson.IO.JsonWriterSettings.Defaults.Indent = true;
        }
コード例 #9
0
        static MongoDbSagaPersister()
        {
            RebusLoggerFactory.Changed += f => log = f.GetCurrentClassLogger();
            var namingConvention = new SagaDataElementNameConvention();

            RevisionMemberName     = namingConvention.RevisionMemberName;
            ElementNameConventions = namingConvention;
            var conventionProfile = new ConventionProfile()
                                    .SetElementNameConvention(ElementNameConventions);

            BsonClassMap.RegisterConventions(conventionProfile, t => typeof(ISagaData).IsAssignableFrom(t));
        }
コード例 #10
0
    private static MongoRead RegisterMongoDb()
    {
        var readServer = MongoServer.Create(connectionString);
        var read       = new MongoRead(readServer);

        var myConventions = new ConventionProfile();

        myConventions.SetIdMemberConvention(new NoDefaultPropertyIdConvention());
        BsonClassMap.RegisterConventions(myConventions, t => true);

        return(read);
    }
コード例 #11
0
 public LogEntryMongoDataService()
 {
     lock (this)
     {
         if (!BsonClassMap.IsClassMapRegistered(typeof(LogEntry)))
         {
             var noIdConventions = new ConventionProfile();
             noIdConventions.SetIdMemberConvention(new NamedIdMemberConvention()); // no names
             BsonClassMap.RegisterConventions(noIdConventions, t => t == typeof(LogEntry));
             BsonClassMap.RegisterClassMap <LogEntry>(cm => cm.AutoMap());
         }
     }
 }
コード例 #12
0
        public void TestMappingUsesBsonSerializationOptionsConventionDoesNotMatchWrongProperty()
        {
            var profile = new ConventionProfile()
                          .SetSerializationOptionsConvention(new TypeRepresentationSerializationOptionsConvention(typeof(ObjectId), BsonType.JavaScriptWithScope));

            BsonClassMap.RegisterConventions(profile, t => t == typeof(A));

            var classMap = BsonClassMap.LookupClassMap(typeof(A));

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

            Assert.IsNull(options);
        }
コード例 #13
0
        private IQueryable GetQueryableCollection(string connectionString, Dictionary <string, Type> providerTypes, string collectionName)
        {
            var collectionType = CreateDynamicTypeForCollection(collectionName, providerTypes);

            var conventions = new ConventionProfile();

            conventions.SetIdMemberConvention(new NamedIdMemberConvention(MongoMetadata.MappedObjectIdName));
            conventions.SetIgnoreExtraElementsConvention(new AlwaysIgnoreExtraElementsConvention());
            BsonClassMap.RegisterConventions(conventions, t => t == collectionType);

            return(InterceptingProvider.Intercept(
                       new MongoQueryableResource(connectionString, collectionName, collectionType),
                       new ResultExpressionVisitor()));
        }
コード例 #14
0
        public void TestConventionProfileStillUsesDefaults()
        {
#pragma warning disable 618
            var conventions = new ConventionProfile();
            conventions.SetElementNameConvention(new CamelCaseElementNameConvention());
            BsonClassMap.RegisterConventions(conventions, t => t == typeof(A));
#pragma warning restore 618
            var classMap = new BsonClassMap <A>();
            classMap.AutoMap();

            var memberMap = classMap.GetMemberMap(x => x.S);

            Assert.IsNotNull(memberMap);
        }
コード例 #15
0
        public void TestMappingWithAMatchingSerializationOptionsConventionDoesNotOverrideAttribute()
        {
            var profile = new ConventionProfile()
                          .SetSerializationOptionsConvention(new TypeRepresentationSerializationOptionsConvention(typeof(ObjectId), BsonType.JavaScriptWithScope));

            BsonClassMap.RegisterConventions(profile, t => t == typeof(B));

            var classMap = BsonClassMap.LookupClassMap(typeof(B));

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

            Assert.IsInstanceOf <RepresentationSerializationOptions>(options);
            Assert.AreEqual(BsonType.ObjectId, ((RepresentationSerializationOptions)options).Representation);
        }
コード例 #16
0
        public RepositorioMongo()
        {
            var url    = new MongoUrl(GetMongoDbConnectionString());
            var client = new MongoClient(url);
            var server = client.GetServer();

            database   = server.GetDatabase(url.DatabaseName);
            Collection = database.GetCollection <T>(typeof(T).Name.ToLower());

            //Ajuda no migration, se tiver campo a mais no banco ele ignora
            var conventions = new ConventionProfile();

            conventions.SetIgnoreExtraElementsConvention(new AlwaysIgnoreExtraElementsConvention());
            BsonClassMap.RegisterConventions(conventions, (type) => true);
        }
コード例 #17
0
        public Repositorio()
        {
            var connectionString = new MongoConnectionStringBuilder(ConfigurationManager.ConnectionStrings["AeeBanco"].ConnectionString);

            server     = MongoServer.Create(connectionString);
            db         = server.GetDatabase(connectionString.DatabaseName);
            Collection = db.GetCollection <T>(typeof(T).Name.ToLower());

            //Corrige a hora no sevidor do banco
            DateTimeSerializationOptions.Defaults = new DateTimeSerializationOptions(DateTimeKind.Utc, BsonType.Document);

            var minhaConvensao = new ConventionProfile();

            minhaConvensao.SetIgnoreExtraElementsConvention(new AlwaysIgnoreExtraElementsConvention());
            BsonClassMap.RegisterConventions(minhaConvensao, (type) => true);
        }
コード例 #18
0
        public void AfterPropertiesSet()
        {
            var defaultProfile = ConventionProfile.GetDefault();

            _profile = new ConventionProfile();
            _filter  = new ConventionFilterHelper(IncludeFilters, ExcludeFilters);

            _profile.SetDefaultValueConvention(DefaultValueConvention ?? defaultProfile.DefaultValueConvention);
            _profile.SetElementNameConvention(ElementNameConvention ?? defaultProfile.ElementNameConvention);
            _profile.SetExtraElementsMemberConvention(ExtraElementsMemberConvention ?? defaultProfile.ExtraElementsMemberConvention);
            _profile.SetIdGeneratorConvention(IdGeneratorConvention ?? defaultProfile.IdGeneratorConvention);
            _profile.SetIdMemberConvention(IdMemberConvention ?? defaultProfile.IdMemberConvention);
            _profile.SetIgnoreExtraElementsConvention(IgnoreExtraElementsConvention ?? defaultProfile.IgnoreExtraElementsConvention);
            _profile.SetIgnoreIfDefaultConvention(IgnoreIfDefaultConvention ?? defaultProfile.IgnoreIfDefaultConvention);
            _profile.SetIgnoreIfNullConvention(IgnoreIfNullConvention ?? defaultProfile.IgnoreIfNullConvention);
            _profile.SetMemberFinderConvention(MemberFinderConvention ?? defaultProfile.MemberFinderConvention);
            _profile.SetSerializationOptionsConvention(SerializationOptionsConvention ?? defaultProfile.SerializationOptionsConvention);

            BsonClassMap.RegisterConventions(_profile, _filter.Filter);
        }
コード例 #19
0
        protected void Application_Start()
        {
            // MiniProfilerEF6.Initialize();

            Logger = Log4NetLogger.Configure();
            Logger.Information("App is starting");

            AreaRegistration.RegisterAllAreas();

            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);

            //RouteDebug.RouteDebugger.RewriteRoutesForTesting(RouteTable.Routes);

            DefaultModelBinder.ResourceClassKey = "ErrorMessages";

            ModelMetadataProviders.Current = new CustomModelMetadataProvider();

            MongoObjectIdGenerator.Register();
            MongoObjectIdSerializer.Register();
            BsonClassMap.RegisterConventions(new ConventionProfile().SetSerializationOptionsConvention(new LocalDateTimeSerializationConvention()), c => true);

            var kernel = new Ninject.Web.Common.Bootstrapper().Kernel;

            ServiceLocator.Resolver = kernel.GetService;

            BundleConfig.RegisterBundles(BundleTable.Bundles);

            ViewEngines.Engines.Clear();
            ViewEngines.Engines.Add(new LocalizedRazorViewEngine());
            ViewEngines.Engines.Add(new LocalizedWebFormViewEngine());

            //GlobalFilters.Filters.Add(new StackExchange.Profiling.Data..Profiling.MVCHelpers.ProfilingActionFilter());

            var chatService = ServiceLocator.Resolve <ChatService>();

            chatService.ClearClients();
        }
コード例 #20
0
        private void Register(IDefinitionProvider[] definitionProviders, IProxyFactory proxies)
        {
            if (isRegistered)
            {
                return;
            }
            isRegistered = true;

            var conventions = new ConventionProfile();

            conventions.SetIgnoreIfNullConvention(new AlwaysIgnoreIfNullConvention());
            conventions.SetMemberFinderConvention(new IgnoreUnderscoreMemberFinderConvention());

            BsonClassMap.RegisterConventions(conventions, t => true);

            BsonSerializer.RegisterSerializationProvider(new ContentSerializationProvider(this, proxies));

            BsonClassMap.RegisterClassMap <AuthorizedRole>(cm =>
            {
                cm.AutoMap();
                cm.UnmapProperty(cd => cd.ID);
                cm.UnmapField(cd => cd.EnclosingItem);
            });
            BsonClassMap.RegisterClassMap <ContentDetail>(cm =>
            {
                cm.AutoMap();
                cm.UnmapProperty(cd => cd.ID);
                cm.UnmapProperty(cd => cd.EnclosingCollection);
                cm.UnmapProperty(cd => cd.EnclosingItem);
                cm.UnmapProperty(cd => cd.Value);
                cm.MapProperty(cd => cd.LinkedItem).SetSerializer(new ContentRelationSerializer(this));
                cm.UnmapProperty(cd => cd.LinkValue);
                cm.GetMemberMap(cd => cd.DateTimeValue).SetSerializationOptions(new DateTimeSerializationOptions(DateTimeKind.Local));
            });
            BsonClassMap.RegisterClassMap <DetailCollection>(cm =>
            {
                cm.AutoMap();
                cm.UnmapProperty(dc => dc.ID);
                cm.UnmapProperty(dc => dc.EnclosingItem);
            });
            BsonClassMap.RegisterClassMap <Relation <ContentItem> >(cm =>
            {
                cm.MapProperty(r => r.ID);
                cm.MapProperty(r => r.ValueAccessor).SetSerializer(new RelationValueAccessorSerializer <ContentItem>(this));
            });
            BsonClassMap.RegisterClassMap <ContentRelation>(cm =>
            {
            });
            BsonClassMap.RegisterClassMap <ContentVersion>(cm =>
            {
                cm.AutoMap();
                cm.MapIdProperty(cv => cv.ID).SetIdGenerator(new IntIdGenerator());
                cm.GetMemberMap(cv => cv.Published).SetSerializationOptions(new DateTimeSerializationOptions(DateTimeKind.Local));
                cm.GetMemberMap(cv => cv.Saved).SetSerializationOptions(new DateTimeSerializationOptions(DateTimeKind.Local));
                cm.GetMemberMap(cv => cv.FuturePublish).SetSerializationOptions(new DateTimeSerializationOptions(DateTimeKind.Local));
                cm.GetMemberMap(cv => cv.Expired).SetSerializationOptions(new DateTimeSerializationOptions(DateTimeKind.Local));
            });
            BsonClassMap.RegisterClassMap <ContentItem>(cm =>
            {
                cm.AutoMap();
                cm.MapIdProperty(ci => ci.ID).SetIdGenerator(new IntIdGenerator());
                cm.UnmapProperty(ci => ci.Children);
                cm.GetMemberMap(ci => ci.Parent).SetSerializer(new ContentItemReferenceSerializer(this));
                cm.UnmapProperty(ci => ci.VersionOf);
                cm.GetMemberMap(ci => ci.Created).SetSerializationOptions(new DateTimeSerializationOptions(DateTimeKind.Local));
                cm.GetMemberMap(ci => ci.Updated).SetSerializationOptions(new DateTimeSerializationOptions(DateTimeKind.Local));
                cm.GetMemberMap(ci => ci.Published).SetSerializationOptions(new DateTimeSerializationOptions(DateTimeKind.Local));
                cm.GetMemberMap(ci => ci.Expires).SetSerializationOptions(new DateTimeSerializationOptions(DateTimeKind.Local));
                cm.SetIsRootClass(isRootClass: true);
            });

            var definitions = definitionProviders.SelectMany(dp => dp.GetDefinitions()).ToList();

            foreach (var definition in definitions)
            {
                var factoryType = typeof(ContentClassMapFactory <>).MakeGenericType(definition.ItemType);
                var factory     = (ContentClassMapFactory)Activator.CreateInstance(factoryType, proxies, this, services);
                BsonClassMap.RegisterClassMap(factory.Create(definition, definitions));
            }
        }
コード例 #21
0
        public void SetUp()
        {
#pragma warning disable 618 // Obsoleted by lots of things related to legacy convention support
            BsonClassMap.RegisterConventions(ConventionProfile.GetDefault(), t => t == typeof(A) || t == typeof(B));
#pragma warning restore 618
        }