Пример #1
1
        public static void Initialize(TestContext context)
        {
            var cfg = new Configuration();
            cfg.DataBaseIntegration(x => {
                x.ConnectionString = "Server=localhost;Database=test;Uid=root;Pwd=kmn23po;";
                x.Driver<MySqlDataDriver>();
                x.Dialect<MySQLDialect>();
                x.LogSqlInConsole = true;
                x.BatchSize = 30;
            });

            var mapper = new ModelMapper();
            mapper.AddMapping<ParentMap>();
            mapper.AddMapping<ParentWithGuidMap>();
            mapper.AddMapping<ChildMap>();

            cfg.AddMapping(mapper.CompileMappingForAllExplicitlyAddedEntities());

            sessionFactory = cfg.BuildSessionFactory();

            var schemaUpdate = new SchemaUpdate(cfg);
            schemaUpdate.Execute(false, true);

            InsertData();
        }
Пример #2
0
		protected override HbmMapping GetMappings()
		{
			var mapper = new ModelMapper();
			mapper.AddMapping<PersonMapper>();
			mapper.AddMapping<CachedPersonMapper>();

			return mapper.CompileMappingForAllExplicitlyAddedEntities();
		}
Пример #3
0
 public void CompiledMappings_ShouldNotDependOnAddedOrdering_AddedBy_AddMapping()
 {
     var mapper = new ModelMapper();
     mapper.AddMapping<EntityMapping>();
     mapper.AddMapping<DerivedClassMapping>();
     mapper.AddMapping<BaseClassMapping>();
     var config = TestConfigurationHelper.GetDefaultConfiguration();
     Assert.DoesNotThrow(() => config.AddMapping(mapper.CompileMappingForAllExplicitlyAddedEntities()));
 }
Пример #4
0
        private static HbmMapping GetMappings()
        {
            var mapper = new ModelMapper();

            mapper.AddMapping<BlogPostMapping>();
            mapper.AddMapping<CommentMapping>();

            HbmMapping mapping = mapper.CompileMappingFor(new[] { typeof(BlogPost), typeof(Comment) });

            return mapping;
        }
		private IEnumerable<HbmMapping> CreateMapper()
		{
			var mapper = new ModelMapper();

			mapper.AddMapping<XmlAsStringEntityMap>();
			mapper.AddMapping<XmlEntityMap>();
			mapper.AddMapping<BinaryEntityMap>();
			mapper.AddMapping<ProtobufEntityMap>();
			mapper.AddMapping<JsonEntityMap>();
			return mapper.CompileMappingForEachExplicitlyAddedEntity();
		}
Пример #6
0
        public void ExportSchema()
        {
            // Inicio do Setup do NH
            var config = new Configuration();

            config.DataBaseIntegration(
                db =>
                {
                    db.Dialect<MsSql2008Dialect>();
                    db.ConnectionStringName = "DefaultNH";
                    db.SchemaAction = SchemaAutoAction.Recreate;
                });

            ModelMapper modelMapper = new ModelMapper();

            modelMapper.AddMapping<ProdutoNHMap>();
            modelMapper.AddMapping<DepartamentoNHMap>();

            config.AddDeserializedMapping(modelMapper.CompileMappingForAllExplicitlyAddedEntities(), "Domain");

            ISessionFactory sessionFactory = config.BuildSessionFactory();

            // Fim do Setup do NH - Isso deve ficar no start da app (Global.asax por exemplo)

            using (var session = sessionFactory.OpenSession())
            {
                // Criteria API
                // HQL
                // Linq

                var produtosAcima1000 = session.QueryOver<Produto>().List();

                foreach (var produto in produtosAcima1000)
                {
                    Console.WriteLine(produto);
                }
            }

            using (var session = sessionFactory.OpenSession())
            {
                var produto = new Produto();

                produto.Nome = "Teste #1";
                produto.Preco = 90;
                produto.Quantidade = 123;
                produto.Ativo = true;

                session.Save(produto);
                session.Flush();
            }
        }
 public static ISessionFactory CreateSessionFactory()
 {
     var configuration = new Configuration();
     configuration.Configure();
     var mapper = new ModelMapper();
     mapper.AddMapping<FileMapping>();
     mapper.AddMapping<CinemaMapping>();
     mapper.AddMapping<LanguageMapping>();
     mapper.AddMapping<CompanyMapping>();
     configuration.AddDeserializedMapping(mapper.CompileMappingForAllExplicitlyAddedEntities(), null);
     var factory = configuration.BuildSessionFactory();
     new SchemaUpdate(configuration).Execute(false, true);
     return factory;
 }
Пример #8
0
        public static void Configure()
        {
            var config = new Configuration().Configure();

            var mapper = new ModelMapper();
            mapper.AddMapping<UserMap>();
            mapper.AddMapping<RoleMap>();
            mapper.AddMapping<PostMap>();
            mapper.AddMapping<TagMap>();

            config.AddMapping(mapper.CompileMappingForAllExplicitlyAddedEntities());

            _sessionFactory = config.BuildSessionFactory();
        }
Пример #9
0
        /// <summary>
        /// Creates session factory
        /// </summary>
        /// <param name="configurationReader">configuration reader</param>
        /// <returns></returns>
        private static ISessionFactory CreateSessionFactory(IConfigurationReader configurationReader)
        {
            var configuration = new NHibernate.Cfg.Configuration();
            configuration.SessionFactoryName("Jumblocks Blog");

            configuration.DataBaseIntegration(db =>
            {
                db.Dialect<MsSql2008FixedDialect>();
                db.IsolationLevel = IsolationLevel.ReadCommitted;
                db.ConnectionString = configurationReader.ConnectionStrings["BlogDb"].ConnectionString;
                db.BatchSize = 100;

                //for testing
                db.LogFormattedSql = true;
                db.LogSqlInConsole = true;
                db.AutoCommentSql = true;
            });

            var mapper = new ModelMapper();
            mapper.AddMapping<BlogPostMap>();
            mapper.AddMapping<BlogUserMap>();
            mapper.AddMapping<ImageReferenceMap>();
            mapper.AddMapping<TagMap>();
            mapper.AddMapping<SeriesMap>();

            mapper.AddMapping<UserMap>();
            mapper.AddMapping<RoleMap>();
            mapper.AddMapping<OperationMap>();

            configuration.AddMapping(mapper.CompileMappingForAllExplicitlyAddedEntities());
            configuration.CurrentSessionContext<WebSessionContext>();

            return configuration.BuildSessionFactory();
        }
        void ApplyMappings(Configuration config)
        {
            var mapper = new ModelMapper();
            mapper.AddMapping<OutboxEntityMap>();

            config.AddMapping(mapper.CompileMappingForAllExplicitlyAddedEntities());
        }
        public void Setup()
        {
            var mapper = new ModelMapper();
            mapper.AddMapping<OutboxEntityMap>();

            var configuration = new global::NHibernate.Cfg.Configuration()
                .AddProperties(new Dictionary<string, string>
                {
                    { "dialect", dialect },
                    { global::NHibernate.Cfg.Environment.ConnectionString,connectionString }
                });

            configuration.AddMapping(mapper.CompileMappingForAllExplicitlyAddedEntities());

            new SchemaUpdate(configuration).Execute(false, true);

            SessionFactory = configuration.BuildSessionFactory();

            Session = SessionFactory.OpenSession();

            persister = new OutboxPersister
            {
                StorageSessionProvider = new FakeSessionProvider(SessionFactory, Session),
                EndpointName = "TestEndpoint"
            };

        }
Пример #12
0
        public static HbmMapping LoadMappingFrom(params Assembly[] assemblies)
        {
            Require.NotNull(assemblies, "assemblies");

            var baseTypes = new Type[] {
                typeof(ClassMapping<>),
                typeof(JoinedSubclassMapping<>),
                typeof(UnionSubclassMapping<>),
                typeof(SubclassMapping<>)
            };

            var mapper = new ModelMapper();

            foreach (var asm in assemblies)
            {
                foreach (var type in asm.GetTypes())
                {
                    if (!type.IsClass || type.IsAbstract || type.IsInterface || !type.BaseType.IsGenericType) continue;

                    if (!baseTypes.Contains(type.BaseType.GetGenericTypeDefinition())) continue;

                    mapper.AddMapping(type);
                }
            }

            var mapping = mapper.CompileMappingForAllExplicitlyAddedEntities();
            mapping.autoimport = false;

            return mapping;
        }
Пример #13
0
    static async Task AsyncMain()
    {
        Console.Title = "Samples.SqlNHibernate.Receiver";
        Configuration hibernateConfig = new Configuration();
        hibernateConfig.DataBaseIntegration(x =>
        {
            x.ConnectionStringName = "NServiceBus/Persistence";
            x.Dialect<MsSql2012Dialect>();
        });

        #region NHibernate

        hibernateConfig.SetProperty("default_schema", "receiver");

        #endregion

        ModelMapper mapper = new ModelMapper();
        mapper.AddMapping<OrderMap>();
        hibernateConfig.AddMapping(mapper.CompileMappingForAllExplicitlyAddedEntities());

        new SchemaExport(hibernateConfig).Execute(false, true, false);

        #region ReceiverConfiguration

        EndpointConfiguration endpointConfiguration = new EndpointConfiguration("Samples.SqlNHibernate.Receiver");
        endpointConfiguration.SendFailedMessagesTo("error");
        endpointConfiguration.AuditProcessedMessagesTo("audit");
        endpointConfiguration.EnableInstallers();
        endpointConfiguration.UseTransport<SqlServerTransport>()
            .DefaultSchema("receiver")
            .UseSpecificSchema(e =>
            {
                if (e == "error" || e == "audit")
                {
                    return "dbo";
                }
                if (e == "Samples.SqlNHibernate.Sender")
                {
                    return "sender";
                }
                return null;
            });

        endpointConfiguration.UsePersistence<NHibernatePersistence>()
            .UseConfiguration(hibernateConfig);

        #endregion

        IEndpointInstance endpoint = await Endpoint.Start(endpointConfiguration);
        try
        {
            Console.WriteLine("Press any key to exit");
            Console.ReadKey();
        }
        finally
        {
            await endpoint.Stop();
        }
    }
Пример #14
0
        public static void Configure()
        {
            var config = new Configuration();
            // if Migrator mapping generator does not connect to the database just add "charset:utf8" to the end of the connection string.
            var mapper = new ModelMapper();

            mapper.AddMapping <UsersMap>();
            mapper.AddMapping <RolesMap>();
            mapper.AddMapping <StockMap>();
            mapper.AddMapping <SalesMap>();

            config.AddMapping(mapper.CompileMappingForAllExplicitlyAddedEntities());

            config.Configure();

            _sessionFactory = config.BuildSessionFactory();
        }
Пример #15
0
        public static void Configure()
        {
            var config = new Configuration();

            config.Configure();

            var mapper = new ModelMapper();

            mapper.AddMapping <UserMap>();
            mapper.AddMapping <RoleMap>();
            mapper.AddMapping <PostMap>();
            mapper.AddMapping <TagMap>();

            config.AddMapping(mapper.CompileMappingForAllExplicitlyAddedEntities());

            _sessionFactory = config.BuildSessionFactory();
        }
Пример #16
0
        public SessionProvider()
        {
            var configuration = new Configuration();

            configuration.Configure();
            var modelMapper = new ModelMapper();

            modelMapper.AddMapping <UserMap>();
            modelMapper.AddMapping <ArtistMap>();
            modelMapper.AddMapping <SongMap>();
            modelMapper.AddMapping <GenreMap>();
            configuration.AddDeserializedMapping(modelMapper.CompileMappingForAllExplicitlyAddedEntities(), null);

            _factory = configuration.BuildSessionFactory();

            new SchemaUpdate(configuration).Execute(false, true);
        }
        private HbmMapping CreateMappings()
        {
            ModelMapper mapper = new ModelMapper();

            mapper.AddMapping(typeof(PessoaMap));

            return(mapper.CompileMappingForAllExplicitlyAddedEntities());
        }
        void ApplyMappings(Configuration config)
        {
            var mapper = new ModelMapper();

            mapper.AddMapping <OutboxEntityMap>();

            config.AddMapping(mapper.CompileMappingForAllExplicitlyAddedEntities());
        }
Пример #19
0
        public static void Configure()
        {
            var config = new Configuration();

            //configure the connection string
            config.Configure();
            //add our mapping
            var mapper = new ModelMapper();

            mapper.AddMapping <UserMap>();
            mapper.AddMapping <RoleMap>();

            config.AddMapping(mapper.CompileMappingForAllExplicitlyAddedEntities());
            // create session factory

            _sessionFactory = config.BuildSessionFactory();
        }
        protected override void Configure(Configuration configuration)
        {
            configuration.DataBaseIntegration(db =>
            {
                db.Dialect <MsSql2012Dialect>();
                db.ConnectionString = _sqlFixture.Container.GetConnectionString("TestDatabase");
                db.BatchSize        = 100;
            });

            var mapper = new ModelMapper();

            mapper.AddMapping <CustomerMapping>();
            mapper.AddMapping <OrderMapping>();
            HbmMapping mapping = mapper.CompileMappingForAllExplicitlyAddedEntities();

            configuration.AddMapping(mapping);
        }
Пример #21
0
        public static void Conf()
        {
            var conf = new Configuration();

            conf.Configure();
            var maper = new ModelMapper();

            maper.AddMapping <ContextMap>();
            maper.AddMapping <MenuMap>();
            maper.AddMapping <ProductMap>();
            maper.AddMapping <OrderMap>();
            maper.AddMapping <OrderProductMap>();

            conf.AddMapping(maper.CompileMappingForAllExplicitlyAddedEntities());

            _sessionFactory = conf.BuildSessionFactory();
        }
Пример #22
0
        public void Can_Generate_Blogger_Tables_XmlMapping()
        {
            // Arrange
            var result = "";
            var mapper = new ModelMapper();

            mapper.AddMapping <BloggerMap>();
            mapper.AddMapping <BloggerDataMap>();

            // Act
            var mapping = mapper.CompileMappingForAllExplicitlyAddedEntities();

            result = mapping.AsString();

            // Assert
            Assert.NotEqual("", result);
        }
Пример #23
0
        public ProgrammaticDatabaseConfiguration()
        {
            var config = new Configuration()
                         .SetProperty(Environment.ReleaseConnections, "on_close")
                         .SetProperty(Environment.Dialect, typeof(SQLiteDialect).AssemblyQualifiedName)
                         .SetProperty(Environment.ConnectionDriver, typeof(SQLite20Driver).AssemblyQualifiedName)
                         .SetProperty(Environment.ConnectionString, "data source=:memory:")
                         .SetProperty(Environment.ShowSql, "true")
                         .SetProperty(Environment.FormatSql, "true");

            var modelMapper = new ModelMapper();

            modelMapper.AddMapping <EmployeeMappings>();
            modelMapper.AddMapping <AddressMappings>();
            modelMapper.AddMapping <BenefitMappings>();
            modelMapper.AddMapping <LeaveMappings>();
            modelMapper.AddMapping <SkillsEnhancementAllowanceMappings>();
            modelMapper.AddMapping <SeasonTicketLoanMappings>();
            modelMapper.AddMapping <CommunityMappings>();

            config.AddMapping(modelMapper.CompileMappingForAllExplicitlyAddedEntities());

            sessionFactory = config.BuildSessionFactory();
            session        = sessionFactory.OpenSession();
            using (var tx = session.BeginTransaction())
            {
                new SchemaExport(config).Execute(true, true, false, session.Connection, Console.Out);
                tx.Commit();
            }
            session.Clear();
        }
        public DatabaseConfigurationForSqlServer()
        {
            var config = new Configuration()
                         .SetProperty(Environment.ReleaseConnections, "on_close")
                         .SetProperty(Environment.Dialect, typeof(MsSql2012Dialect).AssemblyQualifiedName)
                         .SetProperty(Environment.ConnectionDriver, typeof(SqlClientDriver).AssemblyQualifiedName)
                         .SetProperty(Environment.ConnectionString, @"Server=LAPTOP-SUHAS\SQLEXPRESS;Database=EmployeeBenefits;Trusted_Connection=True;")
                         .SetProperty(Environment.ShowSql, "true")
                         .SetProperty(Environment.FormatSql, "true");

            var modelMapper = new ModelMapper();

            modelMapper.AddMapping <EmployeeMappings>();
            modelMapper.AddMapping <AddressMappings>();
            modelMapper.AddMapping <BenefitMappings>();
            modelMapper.AddMapping <LeaveMappings>();
            modelMapper.AddMapping <SkillsEnhancementAllowanceMappings>();
            modelMapper.AddMapping <SeasonTicketLoanMappings>();
            modelMapper.AddMapping <CommunityMappings>();

            config.AddMapping(modelMapper.CompileMappingForAllExplicitlyAddedEntities());

            sessionFactory = config.BuildSessionFactory();
            //using (var session = sessionFactory.OpenSession())
            //{
            //    new SchemaExport(config).Execute(true, true, false, session.Connection, Console.Out);
            //}
        }
        private SessionFactoryProvider()
        {
            var allEntities = new[] {
                typeof(IdentityUser),
                typeof(ApplicationUser),
                typeof(IdentityRole),
                typeof(IdentityUserClaim),
                typeof(IdentityUserToken),
                typeof(IdentityUserLogin),
                typeof(Foo)
            };

            var mapper = new ModelMapper();

            mapper.AddMapping <ApplicationUserMap>();
            mapper.AddMapping <IdentityUserMap>();
            mapper.AddMapping <IdentityRoleMap>();
            mapper.AddMapping <IdentityUserClaimMap>();
            mapper.AddMapping <IdentityUserTokenMap>();
            mapper.AddMapping <IdentityUserLoginMap>();
            mapper.AddMapping <FooMap>();

            var mapping = mapper.CompileMappingForEach(allEntities);

            this._configuration = new Configuration();
            this._configuration.Configure("sqlite-nhibernate-config.xml");
            foreach (var map in mapping)
            {
                Console.WriteLine(map.AsString());
                this._configuration.AddDeserializedMapping(map, null);
            }
            this.SessionFactory = this._configuration.BuildSessionFactory();
        }
Пример #26
0
        private static HbmMapping GetMappings()
        {
            //This is dynamic way!!
            //var mapper = new ModelMapper();
            //mapper.AddMappings(Assembly.GetExecutingAssembly().GetExportedTypes());
            //HbmMapping mapping = mapper.CompileMappingForAllExplicitlyAddedEntities();

            ModelMapper mapper = new ModelMapper();

            mapper.AddMapping <SupplierMap>();
            mapper.AddMapping <UserMap>();
            mapper.AddMapping <MaterialMap>();
            //mapper.AddMapping<CustomerMap>();
            //mapper.AddMapping<>
            HbmMapping mapping = mapper.CompileMappingFor(new[] { typeof(Supplier), typeof(User), typeof(Material) });

            return(mapping);
        }
        public NHMigrationDemoConfig()
        {
            this.DataBaseIntegration(db =>
            {
                db.ConnectionString = "Data Source=(local);initial catalog=NHMigrationDemo;Integrated Security=SSPI";
                db.Dialect<MsSql2012Dialect>();
                db.BatchSize = 150;
                db.KeywordsAutoImport = Hbm2DDLKeyWords.AutoQuote;
                db.LogFormattedSql = true;
            });
            var mapper = new ModelMapper();
            mapper.AddMapping(new CatMapping());
            mapper.AddMapping(new DogMapping());
            this.AddMapping(mapper.CompileMappingForAllExplicitlyAddedEntities());

            this.UseTableBasedMigrations("NHMigrationDemoConfig");
            this.RegisterAllMigrationsFrom(GetType().Assembly);
        }
Пример #28
0
    static async Task AsyncMain()
    {
        Console.Title = "Samples.SQLNHibernateOutbox.Receiver";
        #region NHibernate

        var hibernateConfig = new Configuration();
        hibernateConfig.DataBaseIntegration(x =>
        {
            x.ConnectionString = @"Data Source=.\SQLEXPRESS;Initial Catalog=nservicebus;Integrated Security=True";
            x.Dialect <MsSql2012Dialect>();
        });
        var mapper = new ModelMapper();
        mapper.AddMapping <OrderMap>();
        hibernateConfig.AddMapping(mapper.CompileMappingForAllExplicitlyAddedEntities());

        #endregion

        new SchemaExport(hibernateConfig).Execute(false, true, false);

        var endpointConfiguration = new EndpointConfiguration("Samples.SQLNHibernateOutbox.Receiver");
        endpointConfiguration.UseSerialization <JsonSerializer>();
        #region ReceiverConfiguration

        var transport = endpointConfiguration.UseTransport <SqlServerTransport>();
        transport.ConnectionString(@"Data Source=.\SQLEXPRESS;Initial Catalog=nservicebus;Integrated Security=True");

        var persistence = endpointConfiguration.UsePersistence <NHibernatePersistence>();
        persistence.UseConfiguration(hibernateConfig);

        endpointConfiguration.EnableOutbox();

        #endregion

        #region RetriesConfiguration

        endpointConfiguration.DisableFeature <FirstLevelRetries>();
        endpointConfiguration.DisableFeature <SecondLevelRetries>();

        #endregion

        endpointConfiguration.SendFailedMessagesTo("error");
        endpointConfiguration.AuditProcessedMessagesTo("audit");

        var endpointInstance = await Endpoint.Start(endpointConfiguration)
                               .ConfigureAwait(false);

        try
        {
            Console.WriteLine("Press any key to exit");
            Console.ReadKey();
        }
        finally
        {
            await endpointInstance.Stop()
            .ConfigureAwait(false);
        }
    }
Пример #29
0
        public static void Configure()
        {
            var config = new Configuration();

            config.Configure();

            var mapper = new ModelMapper();

            mapper.AddMapping <KullaniciMap>();
            mapper.AddMapping <UrunlerMap>();
            mapper.AddMapping <KategoriMap>();
            mapper.AddMapping <MesajMap>();


            config.AddMapping(mapper.CompileMappingForAllExplicitlyAddedEntities());

            _sessionFactory = config.BuildSessionFactory();
        }
Пример #30
0
 public static ModelMapper ClassMapHiLo <TEntity>(this ModelMapper mapper, Action <IClassMapper <TEntity> > mapaction) where TEntity : BaseHiLoModel <TEntity>
 {
     mapper.AddMapping(new ClassMapping <TEntity>());
     mapper.Class <TEntity>(map => {
         map.IdHilo();
         mapaction(map);
     });
     return(mapper);
 }
Пример #31
0
    static async Task AsyncMain()
    {
        Console.Title = "Samples.SqlNHibernate.Receiver";
        var hibernateConfig = new Configuration();

        hibernateConfig.DataBaseIntegration(x =>
        {
            x.ConnectionStringName = "NServiceBus/Persistence";
            x.Dialect <MsSql2012Dialect>();
        });

        #region NHibernate

        hibernateConfig.SetProperty("default_schema", "receiver");

        #endregion

        var mapper = new ModelMapper();
        mapper.AddMapping <OrderMap>();
        hibernateConfig.AddMapping(mapper.CompileMappingForAllExplicitlyAddedEntities());

        new SchemaExport(hibernateConfig).Execute(false, true, false);

        #region ReceiverConfiguration

        var endpointConfiguration = new EndpointConfiguration("Samples.SqlNHibernate.Receiver");
        endpointConfiguration.SendFailedMessagesTo("error");
        endpointConfiguration.AuditProcessedMessagesTo("audit");
        endpointConfiguration.EnableInstallers();
        var transport = endpointConfiguration.UseTransport <SqlServerTransport>();
        transport.DefaultSchema("receiver");
        transport.UseSpecificSchema(e =>
        {
            if (e == "error" || e == "audit")
            {
                return("dbo");
            }
            if (e == "Samples.SqlNHibernate.Sender")
            {
                return("sender");
            }
            return(null);
        });

        var persistence = endpointConfiguration.UsePersistence <NHibernatePersistence>();
        persistence.UseConfiguration(hibernateConfig);

        #endregion

        var endpointInstance = await Endpoint.Start(endpointConfiguration)
                               .ConfigureAwait(false);

        Console.WriteLine("Press any key to exit");
        Console.ReadKey();
        await endpointInstance.Stop()
        .ConfigureAwait(false);
    }
Пример #32
0
 public static ModelMapper ClassMapGuid <TEntity>(this ModelMapper mapper, Action <IClassMapper <TEntity> > mapaction) where TEntity : BaseGuidModel <TEntity>
 {
     mapper.AddMapping(new ClassMapping <TEntity>());
     mapper.Class <TEntity>(map => {
         map.IdGuidComb();
         mapaction(map);
     });
     return(mapper);
 }
Пример #33
0
        /// <summary>
        /// Adds T mapping to <param name="configuration">Configuration</param>.
        /// </summary>
        /// <typeparam name="T">The mapping class.</typeparam>
        /// <param name="configuration">The existing <see cref="Configuration"/>.</param>
        public static void AddMappings <T>(Configuration configuration) where T : IConformistHoldersProvider, new()
        {
            var mapper = new ModelMapper();

            mapper.AddMapping <T>();
            var mappings = mapper.CompileMappingForAllExplicitlyAddedEntities();

            configuration.AddMapping(mappings);
        }
Пример #34
0
    static async Task AsyncMain()
    {
        Console.Title = "Samples.SqlNHibernate.Receiver";
        var connection      = @"Data Source=.\SqlExpress;Database=NsbSamplesSqlNHibernate;Integrated Security=True; Max Pool Size=100";
        var hibernateConfig = new Configuration();

        hibernateConfig.DataBaseIntegration(x =>
        {
            x.ConnectionString = connection;
            x.Dialect <MsSql2012Dialect>();
        });

        #region NHibernate

        hibernateConfig.SetProperty("default_schema", "receiver");

        #endregion

        SqlHelper.CreateSchema(connection, "receiver");
        var mapper = new ModelMapper();
        mapper.AddMapping <OrderMap>();
        hibernateConfig.AddMapping(mapper.CompileMappingForAllExplicitlyAddedEntities());

        new SchemaExport(hibernateConfig).Execute(false, true, false);

        #region ReceiverConfiguration

        var endpointConfiguration = new EndpointConfiguration("Samples.SqlNHibernate.Receiver");
        endpointConfiguration.SendFailedMessagesTo("error");
        endpointConfiguration.AuditProcessedMessagesTo("audit");
        endpointConfiguration.EnableInstallers();
        var transport = endpointConfiguration.UseTransport <SqlServerTransport>();
        transport.ConnectionString(connection);
        transport.DefaultSchema("receiver");
        transport.UseSchemaForQueue("error", "dbo");
        transport.UseSchemaForQueue("audit", "dbo");
        transport.UseSchemaForQueue("Samples.SqlNHibernate.Sender", "sender");

        transport.Transactions(TransportTransactionMode.SendsAtomicWithReceive);

        var routing = transport.Routing();
        routing.RouteToEndpoint(typeof(OrderAccepted), "Samples.SqlNHibernate.Sender");
        routing.RegisterPublisher(typeof(OrderSubmitted).Assembly, "Samples.SqlNHibernate.Sender");

        var persistence = endpointConfiguration.UsePersistence <NHibernatePersistence>();
        persistence.UseConfiguration(hibernateConfig);

        #endregion

        var endpointInstance = await Endpoint.Start(endpointConfiguration)
                               .ConfigureAwait(false);

        Console.WriteLine("Press any key to exit");
        Console.ReadKey();
        await endpointInstance.Stop()
        .ConfigureAwait(false);
    }
Пример #35
0
        protected override void Configure(NHibernate.Cfg.Configuration protoConfig)
        {
            protoConfig.Properties[NHibernate.Cfg.Environment.ShowSql] = "True";

            var mapper = new ModelMapper();

            mapper.AddMapping <PersonMap>();
            protoConfig.AddMapping(mapper.CompileMappingForAllExplicitlyAddedEntities());
        }
        public void WhenRegisterClassMappingThroughTypeThenMapTheClass()
        {
            var mapper = new ModelMapper();

            mapper.AddMapping(typeof(MyClassMap));
            var hbmMapping = mapper.CompileMappingFor(new[] { typeof(MyClass) });

            ModelIsWellFormed(hbmMapping);
        }
        public void WhenRegisterClassMappingThroughTypeThenGetMapping()
        {
            var mapper = new ModelMapper();

            mapper.AddMapping(typeof(MyClassMap));
            var hbmMapping = mapper.CompileMappingForAllExplicitlyAddedEntities();

            ModelIsWellFormed(hbmMapping);
        }
Пример #38
0
        protected static HbmMapping GetMappings()
        {
            //There is a dynamic way to do this, but for simplicity I chose to hard code
            var mapper = new ModelMapper();

            mapper.AddMapping<UsersMap>();
            var mapping = mapper.CompileMappingFor(new[] { typeof(Users) });
            return mapping;
        }
Пример #39
0
        public static void Configure()//APP Level - Only Once //bu sadece bir kez app startda çağırılıyor.
        {
            var config = new Configuration();

            config.Configure();
            //select  connection string

            var mapper = new ModelMapper();

            mapper.AddMapping <UserMap>();
            mapper.AddMapping <RoleMap>();
            mapper.AddMapping <TagMap>();
            mapper.AddMapping <PostMap>();
            config.AddMapping(mapper.CompileMappingForAllExplicitlyAddedEntities());
            //add mapping
            _sessionFactory = config.BuildSessionFactory();
            //create session factory
        }
Пример #40
0
        public static void Configure()
        {
            var config = new Configuration();

            // Configure the connection string
            config.Configure();

            // Add out mappings
            var mapper = new ModelMapper();
            mapper.AddMapping<UserMap>();
            mapper.AddMapping<RoleMap>();
            mapper.AddMapping<TagMap>();
            mapper.AddMapping<PostMap>();
            config.AddMapping(mapper.CompileMappingForAllExplicitlyAddedEntities());

            // create session factory
            _sessionFactory = config.BuildSessionFactory();
        }
Пример #41
0
    static async Task AsyncMain()
    {
        Console.Title = "Samples.SQLNHibernateOutbox.Receiver";
        #region NHibernate

        var hibernateConfig = new Configuration();
        hibernateConfig.DataBaseIntegration(x =>
        {
            x.ConnectionString = @"Data Source=.\SQLEXPRESS;Initial Catalog=nservicebus;Integrated Security=True";
            x.Dialect<MsSql2012Dialect>();
        });
        var mapper = new ModelMapper();
        mapper.AddMapping<OrderMap>();
        hibernateConfig.AddMapping(mapper.CompileMappingForAllExplicitlyAddedEntities());

        #endregion

        new SchemaExport(hibernateConfig).Execute(false, true, false);

        var endpointConfiguration = new EndpointConfiguration("Samples.SQLNHibernateOutbox.Receiver");
        endpointConfiguration.UseSerialization<JsonSerializer>();
        #region ReceiverConfiguration

        var transport = endpointConfiguration.UseTransport<SqlServerTransport>();
        transport.ConnectionString(@"Data Source=.\SQLEXPRESS;Initial Catalog=nservicebus;Integrated Security=True");

        var persistence = endpointConfiguration.UsePersistence<NHibernatePersistence>();
        persistence.UseConfiguration(hibernateConfig);

        endpointConfiguration.EnableOutbox();

        #endregion

        #region RetriesConfiguration

        endpointConfiguration.DisableFeature<FirstLevelRetries>();
        endpointConfiguration.DisableFeature<SecondLevelRetries>();

        #endregion

        endpointConfiguration.SendFailedMessagesTo("error");
        endpointConfiguration.AuditProcessedMessagesTo("audit");

        var endpointInstance = await Endpoint.Start(endpointConfiguration)
            .ConfigureAwait(false);
        try
        {
            Console.WriteLine("Press any key to exit");
            Console.ReadKey();
        }
        finally
        {
            await endpointInstance.Stop()
                .ConfigureAwait(false);
        }
    }
Пример #42
0
        public static ISessionFactory GetOrCreateSessionFactory()
        {
            if (_sessionFactory != null)
            {
                return(_sessionFactory);
            }

            var cfg = new Configuration();

            // настройка подключения к БД
            cfg.DataBaseIntegration(d =>
            {
                // диалект контролирует синтаксис sql-запросов
                d.Dialect <NHibernate.Dialect.PostgreSQLDialect>();

                // драйвер отвечает за отправку и прием данных
                d.Driver <NHibernate.Driver.NpgsqlDriver>();

                d.ConnectionString = "Server=localhost;Port=5432;Database=library;User ID=postgres;Password=123";
                d.LogSqlInConsole  = true;
            });

            var oldListenets = cfg.EventListeners.FlushEventListeners.ToList();

            oldListenets.Add(new FlushEventListener());

            cfg.EventListeners.FlushEventListeners = oldListenets.ToArray();

            // указываем маппинги сущностей
            var modelMapper = new ModelMapper();

            Assembly.Load("EntitiesAndMaps");
            var mapTypes = AppDomain.CurrentDomain.GetAssemblies()
                           .SelectMany(a => a.GetExportedTypes())
                           .Where(type => type.IsClass)
                           .Where(type => type.BaseType != null)
                           .Where(type => type.BaseType.IsGenericType)
                           .Where(type => typeof(ClassMapping <>) == type.BaseType.GetGenericTypeDefinition())
                           .ToArray();

            foreach (var mapType in mapTypes)
            {
                modelMapper.AddMapping(mapType);
            }

            cfg.AddMapping(modelMapper.CompileMappingForAllExplicitlyAddedEntities());

            modelMapper.CompileMappingForEachExplicitlyAddedEntity().WriteAllXmlMapping();

            // создаем объект ISessionFactory, хранящий в себе настройки, в единственном экземпляре
            // этот объект не содержит подключения к БД
            var sessionFactory = cfg.BuildSessionFactory();

            _sessionFactory = sessionFactory;
            return(_sessionFactory);
        }
Пример #43
0
        public static void Configure()
        {
            //configure database using nhibernate
            var config = new Configuration();

            //configure the connection string
            //picks up settings from webconfig as default behavior
            config.Configure();

            //add mappings for Nhibernate
            var mapper = new ModelMapper();
            mapper.AddMapping<GuestMap>();
            mapper.AddMapping<RoleMap>();

            config.AddMapping(mapper.CompileMappingForAllExplicitlyAddedEntities());

            //create session factory
            _sessionFactory = config.BuildSessionFactory();
        }
Пример #44
0
        public static void Configure()
        {
            var config = new Configuration();

            //configure the connection string
            config.Configure(); //automatically look at Web.config

            //add our mappings
            var mapper = new ModelMapper();

            mapper.AddMapping <UserMap>();
            mapper.AddMapping <RoleMap>();
            mapper.AddMapping <TagMap>();
            mapper.AddMapping <PostMap>();
            config.AddMapping(mapper.CompileMappingForAllExplicitlyAddedEntities());

            //create session factory, will be used in OpenSession & CloseSession below
            _sessionFactory = config.BuildSessionFactory();
        }
Пример #45
0
        protected override void Configure(Configuration configuration)
        {
            var root = TestHelper
                       .GetIConfigurationRoot();

            var nhibernate = root
                             .GetSection("nhibernate");

            nhibernate
            .Bind(configuration.Properties);

            var mapper = new ModelMapper();

            mapper.AddMapping <CustomerMapping>();
            mapper.AddMapping <OrderMapping>();
            var mapping = mapper.CompileMappingForAllExplicitlyAddedEntities();

            configuration.AddMapping(mapping);
        }
Пример #46
0
        public void CanGenerateParentMapXml()
        {
            var modelMapper = new ModelMapper();
            modelMapper.AddMapping<ParentMap>();

            var hbmMapping = modelMapper.CompileMappingForAllExplicitlyAddedEntities();
            XmlSerializer xmlSerializer = new XmlSerializer(hbmMapping.GetType());

            xmlSerializer.Serialize(Console.Out, hbmMapping);
        }
Пример #47
0
        public NHMigrationDemoConfig()
        {
            this.DataBaseIntegration(db =>
            {
                db.ConnectionString = "Data Source=(local);initial catalog=NHMigrationDemo;Integrated Security=SSPI";
                db.Dialect <MsSql2012Dialect>();
                db.BatchSize          = 150;
                db.KeywordsAutoImport = Hbm2DDLKeyWords.AutoQuote;
                db.LogFormattedSql    = true;
            });
            var mapper = new ModelMapper();

            mapper.AddMapping(new CatMapping());
            mapper.AddMapping(new DogMapping());
            this.AddMapping(mapper.CompileMappingForAllExplicitlyAddedEntities());

            this.UseTableBasedMigrations("NHMigrationDemoConfig");
            this.RegisterAllMigrationsFrom(GetType().Assembly);
        }
        public void CanGenerateXmlMapping()
        {
            var mapper = new ModelMapper();
            mapper.AddMapping<PersonMap>();

            var mapping = mapper.CompileMappingForAllExplicitlyAddedEntities();
            var xmlSerializer = new XmlSerializer(mapping.GetType());

            xmlSerializer.Serialize(Console.Out, mapping);
        }
Пример #49
0
        private void AddMapping(KeyValuePair <MappedType, MappingStrategy> obj)
        {
            var holdersProvider = this.Invoke("GetConformistHoldersProvider", new[] { obj.Key.Source }, obj);

            holdersProvider =
                new TypeAnnotationsMapper()
                .Invoke("Map", new[] { obj.Key.Source }, new[] { obj.Key, holdersProvider });

            modelMapper.AddMapping((IConformistHoldersProvider)holdersProvider);
        }
        private static HbmMapping GetMappingsLameWay()
        {
            var mapper = new ModelMapper();

            mapper.AddMapping <FundProductMap>();

            var mapping = mapper.CompileMappingFor(new[] { typeof(FundProduct) });

            return(mapping);
        }
Пример #51
0
        private static HbmMapping GetMappings()
        {
            ModelMapper mapper = new ModelMapper();
            mapper.AddMapping<UserMap>();
            mapper.AddMapping<BlogMap>();
            mapper.AddMapping<BlogRecordMap>();
            mapper.AddMapping<CommentMap>();
            mapper.AddMapping<RatingMap>();

            HbmMapping mapping = mapper.CompileMappingFor(new[]
            {
                typeof(User),
                typeof(Blog),
                typeof(BlogRecord),
                typeof(Comment),
                typeof(Rating)
            });

            return mapping;
        }
		/// <summary>
		/// Get Mappings for NHibernate
		/// </summary>
		/// <returns>The Mappings</returns>
		protected static HbmMapping GetMappings()
		{
			ModelMapper modelMapper = new ModelMapper();

			modelMapper.AddMapping<TestsuiteMap>();
			modelMapper.AddMapping<TestsystemMap>();
			modelMapper.AddMapping<ResultMap>();
			modelMapper.AddMapping<BrowserMap>();
			modelMapper.AddMapping<LanguageMap>();
			modelMapper.AddMapping<TestcaseMap>();
			modelMapper.AddMapping<ErrorMap>();
			modelMapper.AddMapping<TesterMap>();
			modelMapper.AddMapping<HistoryResultMap>();
			modelMapper.AddMapping<TestJobMap>();

			HbmMapping hbmMapping = modelMapper.CompileMappingFor(new[] { typeof(Testsuite), typeof(Testsystem),
				typeof(Result), typeof(Browser), typeof(Language),  typeof(Testcase),  typeof(Error), typeof(Tester),
				typeof(TestJob),typeof(HistoryResult)});
			return hbmMapping;
		}
Пример #53
0
    static void Main()
    {
        Console.Title = "Samples.SqlNHibernate.Receiver";
        Configuration hibernateConfig = new Configuration();
        hibernateConfig.DataBaseIntegration(x =>
        {
            x.ConnectionStringName = "NServiceBus/Persistence";
            x.Dialect<MsSql2012Dialect>();
        });

        #region NHibernate

        hibernateConfig.SetProperty("default_schema", "receiver");

        #endregion

        ModelMapper mapper = new ModelMapper();
        mapper.AddMapping<OrderMap>();
        hibernateConfig.AddMapping(mapper.CompileMappingForAllExplicitlyAddedEntities());

        new SchemaExport(hibernateConfig).Execute(false, true, false);

        BusConfiguration busConfiguration = new BusConfiguration();
        busConfiguration.EndpointName("Samples.SqlNHibernate.Receiver");
        busConfiguration.EnableInstallers();

        #region ReceiverConfiguration

        busConfiguration.UseTransport<SqlServerTransport>()
            .DefaultSchema("receiver")
            .UseSpecificConnectionInformation(endpoint =>
            {
                if (endpoint == "error" || endpoint == "audit")
                {
                    return ConnectionInfo.Create().UseSchema("dbo");
                }
                if (endpoint == "Samples.SqlNHibernate.Sender")
                {
                    return ConnectionInfo.Create().UseSchema("sender");
                }
                return null;
            });
        busConfiguration.UsePersistence<NHibernatePersistence>()
            .UseConfiguration(hibernateConfig)
            .RegisterManagedSessionInTheContainer();
        #endregion

        using (Bus.Create(busConfiguration).Start())
        {
            Console.WriteLine("Press any key to exit");
            Console.ReadKey();
        }
    }
        public DatabaseSessionProvider()
        {
            var configuration = new Configuration();
            configuration.Configure();
            var modelMapper = new ModelMapper();
            modelMapper.AddMapping<UserMap>();
            modelMapper.AddMapping<ProjectMap>();
            modelMapper.AddMapping<EventMap>();
            modelMapper.AddMapping<DeliveryMap>();
            modelMapper.AddMapping<MailValidationRequestMap>();
            modelMapper.AddMapping<ProjectMembershipMap>();
            modelMapper.AddMapping<NotificationSettingMap>();
            modelMapper.AddMapping<OrderMap>();
            modelMapper.AddMapping<NotificationEmailMapping>();
            modelMapper.AddMapping<PasswordChangeRequestMap>();
            configuration.AddDeserializedMapping(modelMapper.CompileMappingForAllExplicitlyAddedEntities(), null);

            _factory = configuration.BuildSessionFactory();

            new SchemaUpdate(configuration).Execute(false, true);
        }
        public void Fixture()
        {
            var mapper = new ModelMapper();
            mapper.AddMapping<ProductMap>();
            mapper.AddMapping<OrderMap>();
            mapper.AddMapping<OrderDetailMap>();
            
            var mapping = mapper.CompileMappingForAllExplicitlyAddedEntities();
            
            var config = new Configuration();
            config.AddDeserializedMapping(mapping, "ProductMap");
            config.Configure();
            
            //create the database
            new NHibernate.Tool.hbm2ddl.SchemaExport(config).Execute(true, true, false);

            var factory = config.BuildSessionFactory();
            var session = factory.OpenSession();

            var product = new Product();
            product.ProductName = "Test";
            product.Description = string.Join("",Enumerable.Repeat("1", 8000).ToArray());
            product.Image = new byte[8000];
            product.Price = 10.9999m;

            var order = new Order();
            order.OrderDate = DateTime.UtcNow;
            order.Freight = 1.22m;
            order.Details = new List<OrderDetail>() { new OrderDetail() { Product = product, Quantity = 2 } };

            session.Save(product);
            session.Save(order);
            session.Flush();

            var loaded = session.Get<Order>(order.Id);
            Assert.AreEqual(order, loaded);
            Assert.AreEqual(1.22m, order.Freight);
            session.Close();
        }
        public void CanCorrectlyMapIdentityUser()
        {
            var mapper = new ModelMapper();
            mapper.AddMapping<IdentityUserMap>();
            mapper.AddMapping<IdentityRoleMap>();
            mapper.AddMapping<IdentityUserClaimMap>();
            mapper.AddMapping<IdentityUserLoginMap>();

            var mapping = mapper.CompileMappingForAllExplicitlyAddedEntities();

            var configuration = new Configuration();
            configuration.Configure("sqlite-nhibernate-config.xml");
            configuration.AddDeserializedMapping(mapping, null);

            var factory = configuration.BuildSessionFactory();
            var session = factory.OpenSession();
            BuildSchema(configuration);

            new PersistenceSpecification<IdentityUser>(session)
                .CheckProperty(c => c.UserName, "John")
                .VerifyTheMappings();
        }
Пример #57
0
 public static HbmMapping GetAllMapper()
 {
     var mapper = new ModelMapper();
     mapper.AddMapping(typeof(UserEntityMap));
     mapper.AddMapping(typeof(AdminEntityMap));
     mapper.AddMapping(typeof(FileEntityMap));
     mapper.AddMapping(typeof(ImageEntityMap));
     mapper.AddMapping(typeof(VideoEntityMap));
     mapper.AddMapping(typeof(MessageEntityMap));
     mapper.AddMapping(typeof(CommentEntityMap));
     return mapper.CompileMappingForAllExplicitlyAddedEntities();
 }
Пример #58
0
    static void Main()
    {
        Configuration hibernateConfig = new Configuration();
        hibernateConfig.DataBaseIntegration(x =>
        {
            x.ConnectionStringName = "NServiceBus/Persistence";
            x.Dialect<MsSql2012Dialect>();
        });

        #region NHibernate

        hibernateConfig.SetProperty("default_schema", "receiver");

        #endregion

        ModelMapper mapper = new ModelMapper();
        mapper.AddMapping<OrderMap>();
        hibernateConfig.AddMapping(mapper.CompileMappingForAllExplicitlyAddedEntities());

        new SchemaExport(hibernateConfig).Execute(false, true, false);

        #region ReceiverConfiguration

        BusConfiguration busConfiguration = new BusConfiguration();
        busConfiguration.UseTransport<SqlServerTransport>()
            .DefaultSchema("receiver")
            .UseSpecificConnectionInformation(endpoint =>
            {
                if (endpoint == "error")
                {
                    return ConnectionInfo.Create().UseSchema("dbo");
                }
                if (endpoint == "audit")
                {
                    return ConnectionInfo.Create().UseSchema("dbo");
                }
                string schema = endpoint.Split(new[] { '.' }, StringSplitOptions.RemoveEmptyEntries)[0].ToLowerInvariant();
                return ConnectionInfo.Create().UseSchema(schema);
            });
        busConfiguration.UsePersistence<NHibernatePersistence>()
            .UseConfiguration(hibernateConfig)
            .RegisterManagedSessionInTheContainer();
        #endregion

        using (Bus.Create(busConfiguration).Start())
        {
            Console.WriteLine("Press <enter> to exit");
            Console.ReadLine();
        }
    }
Пример #59
0
        protected virtual Configuration Configure()
        {
            var config = new Configuration();
            config.Properties.Clear();

            Customize(config);

            var mapper = new ModelMapper();
            mapper.AddMapping(typeof(UserMapping));

            var mapping = mapper.CompileMappingForAllExplicitlyAddedEntities();
            config.AddMapping(mapping);

            return config;
        }
Пример #60
0
        protected void OnFixtureSetUp()
        {
            Configuration c = new Configuration().Proxy(
                p => p.ProxyFactoryFactory<NHibernate.Bytecode.DefaultProxyFactoryFactory>())
                .DataBaseIntegration(d =>
                {
                    d.Dialect<MsSql2008Dialect>();
                    d.ConnectionString = "Server=localhost;Initial Catalog=Tasks;user=jbpmUser;password=7bpmXus3r";
                    d.LogSqlInConsole = true;

                });
            c.SetProperty("current_session_context_class", "thread_static");
            ModelMapper mapper = new ModelMapper();
            mapper.AddMapping(typeof(TaskEntityMap));
            c.AddMapping(mapper.CompileMappingForAllExplicitlyAddedEntities());
            SchemaExport = new SchemaExport(c);
            SessionFactory = c.BuildSessionFactory();
        }