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();
        }
Beispiel #2
0
        /// <summary>
        /// Método que crea la session factory
        /// </summary>
        public ISessionFactory SessionFactory()
        {
            try
            {
                //Siempre que no la hayamos creado antes
                if (_sessionFactory == null)
                {
                    var cfg = new NHibernate.Cfg.Configuration();
                    cfg.Configure();

                    var mapper = new ModelMapper();

                    //Especifico uno por unos los mapeos de las entidades
                    //mapper.AddMappings(typeof(BE.AfiliadoDatos).Assembly.GetTypes());
                    mapper.AddMapping <MapAfiBeneficiariosOspep>();
                    mapper.AddMapping <MapTest>();
                    mapper.AddMapping <MapAuditoriaWS>();
                    mapper.AddMapping <MapAfiBeneficiarios>();

                    var mapping = mapper.CompileMappingForAllExplicitlyAddedEntities();

                    cfg.AddMapping(mapping);

                    _sessionFactory = cfg.BuildSessionFactory();
                }
                return(_sessionFactory);
            }
            catch (Exception e)
            {
                return(null);
            }
        }
        static void Main(string[] args)
        {
            SqlServerTypes.Utilities.LoadNativeAssemblies(AppDomain.CurrentDomain.BaseDirectory);

            var mapper = new ConventionModelMapper();

            mapper.Class<SomeAreaClass>(c =>
            {
                c.Property(x => x.Area, m =>
                {
                    m.Type<MsSql2008GeographyType>();
                    m.NotNullable(true);
                });
            });

            var cfg = new Configuration()

                .DataBaseIntegration(db =>
                {
                    db.ConnectionString = "YourConnectionString";
                    db.Dialect<MsSql2012GeographyDialect>();
                });

            cfg
                .AddMapping(mapper.CompileMappingForAllExplicitlyAddedEntities());

            cfg
                .AddAuxiliaryDatabaseObject(new SpatialAuxiliaryDatabaseObject(cfg));

            new SchemaExport(cfg).Execute(false, true, false);
        }
Beispiel #4
0
        public static void Initialize()
        {
            NhibernateConfiguration = new Configuration();
            NhibernateConfiguration.Properties[NHibernate.Cfg.Environment.CollectionTypeFactoryClass] = typeof(Net4CollectionTypeFactory).AssemblyQualifiedName;
            NhibernateConfiguration.Configure();

            // Mapping by Mapping XML-Files
            foreach (var xmlMappingAssembly in GetXmlMappingAssemblies())
            {
                NhibernateConfiguration.AddAssembly(xmlMappingAssembly);
            }

            // Mapping by Code
            var modelMapper = new ModelMapper();

            foreach (var modelAssembly in GetModelAssemblies())
            {
                modelMapper.AddMappings(modelAssembly.GetExportedTypes());
                NhibernateConfiguration.AddAssembly(modelAssembly);
            }
            if (GetModelAssemblies().Any())
            {
                HbmMapping domainMapping = modelMapper.CompileMappingForAllExplicitlyAddedEntities();
                NhibernateConfiguration.AddMapping(domainMapping);
            }


            SessionFactory = NhibernateConfiguration.BuildSessionFactory();
        }
 private static void InitializeSessionFactory()
 {
     if (sessionFactory == null)
     {
         lock (mutex)
         {
             if (sessionFactory == null)
             {
                 configuration = new Configuration();
                 configuration.DataBaseIntegration(db =>
                 {
                     db.ConnectionString = connectionString;
                     db.Dialect<MsSql2008Dialect>();
                     db.Driver<SqlClientDriver>();
                     db.Timeout = 20;
                     db.LogFormattedSql = Config.LogSql;
                     db.LogSqlInConsole = Config.LogSql;
                 });
                 var modelMapper = new ModelMapper();
                 modelMapper.AddMappings(ExportedTypes);
                 var mappingDocument = modelMapper.CompileMappingForAllExplicitlyAddedEntities();
                 configuration.AddMapping(mappingDocument);
                 sessionFactory = configuration.BuildSessionFactory();
             }
         }
     }
 }
Beispiel #6
0
        public void TestMethod1()
        {
            var config = new NH.Configuration().Configure();

            var mapper = new ModelMapper();

            mapper.AddMappings(typeof(SessionFactory).Assembly.GetTypes());
            config.AddMapping(mapper.CompileMappingForAllExplicitlyAddedEntities());
            SchemaUpdate su = new SchemaUpdate(config);

            //se.Execute(false, false, true);
            su.Execute(true, true);

            var factory = config.BuildSessionFactory();

            using (var session = factory.OpenSession())
            {
                using (var tran = session.BeginTransaction())
                {
                    session.Save(new Brand {
                        Name = "Brand 2", UtcCreationDate = DateTime.UtcNow, UtcUpdateDate = DateTime.UtcNow
                    });
                    tran.Commit();
                }
            }

            factory.Dispose();
        }
Beispiel #7
0
        public void CreateSqlSchema()
        {
            var sqlBuilder = new SqlConnectionStringBuilder();
              sqlBuilder.DataSource = "(local)";
              sqlBuilder.InitialCatalog = "nservicebus";
              sqlBuilder.IntegratedSecurity = true;

              var cfg = new Configuration()

            .DataBaseIntegration(x =>
                               {
                                 x.Dialect<MsSql2008Dialect>();
                                 x.ConnectionString = sqlBuilder.ConnectionString;
                               });

              var mapper = new ModelMapper();
              mapper.AddMappings(typeof(NHibernate.Config.SubscriptionMap).Assembly.GetExportedTypes());
              HbmMapping faultMappings = mapper.CompileMappingForAllExplicitlyAddedEntities();

              cfg.AddMapping(faultMappings);

              File.WriteAllText("schema.sql", "");

              new SchemaExport(cfg).Create(x => File.AppendAllText("schema.sql", x), true);

              subscriptionStorageSessionProvider = new SubscriptionStorageSessionProvider(cfg.BuildSessionFactory());

              storage = new SubscriptionStorage(subscriptionStorageSessionProvider);
        }
Beispiel #8
0
        static NHibernateHelper()
        {
            NHibernate.Cfg.Configuration cfg = null;

#if HIBERNATE_CFG_CODE
            cfg = new NHibernate.Cfg.Configuration()
                  .DataBaseIntegration(db =>
            {
                db.ConnectionString = ConfigurationManager.
                                      ConnectionStrings[Constants.DB_CONNECTION_STRING_NAME].
                                      ConnectionString;
                db.Dialect <MsSql2008Dialect>();
                db.Driver <NHibernate.Driver.SqlClientDriver>();
                db.ConnectionProvider <NHibernate.Connection.DriverConnectionProvider>();
            });
#else
            cfg = new NHibernate.Cfg.Configuration().Configure();
#endif

#if HIBERNATE_MAP_CODE
            var mapper = new ModelMapper();
            mapper.AddMappings(Assembly.GetExecutingAssembly().GetExportedTypes());
            HbmMapping mapping = mapper.CompileMappingForAllExplicitlyAddedEntities();
            cfg.AddMapping(mapping);
#else
            // Автоматический маппинг всей сборки, содержащей типы сущностей
            configuration.AddAssembly(typeof(< type_name >).Assembly);
#endif

            new SchemaUpdate(cfg).Execute(true, true);
            sessionFactory = cfg.BuildSessionFactory();
        }
 public static ISessionFactory AppDomainFactory()
 {
     if (_appDomainFactory == null)
     {
         lock (_synRoot3)
         {
             if (_appDomainFactory == null)
             {
                 var createSchema = false;
                 var configuration = new Configuration()
                     .DataBaseIntegration(d =>
                     {
                         d.ConnectionStringName = Constants.APP_DB;
                         d.Dialect<MsSql2012Dialect>();
                         //d.Dialect<Oracle10gDialect>();
                         d.SchemaAction = SchemaAutoAction.Validate;
                     })
                     .Proxy(p => p.ProxyFactoryFactory<DefaultProxyFactoryFactory>())
                     .CurrentSessionContext<LazySessionContext>()
                     .SetProperty(NHibernate.Cfg.Environment.Hbm2ddlKeyWords, "none")
                     .SetProperty(NHibernate.Cfg.Environment.Hbm2ddlAuto, (createSchema == true) ? SchemaAutoAction.Update.ToString() : SchemaAutoAction.Validate.ToString());
                 configuration.AddMapping(GetAppMappings());
                 configuration.BuildMapping();
                 if (File.Exists(Util.GetFullPath(System.Configuration.ConfigurationManager.AppSettings[Constants.HIBERNATE_CONFIG_KEY])))
                     configuration.Configure(Util.GetFullPath(System.Configuration.ConfigurationManager.AppSettings[Constants.HIBERNATE_CONFIG_KEY]));
                 if (File.Exists(Util.GetFullPath(System.Configuration.ConfigurationManager.AppSettings[Constants.HIBERNATE_CONFIG_KEY_App])))
                     configuration.Configure(Util.GetFullPath(System.Configuration.ConfigurationManager.AppSettings[Constants.HIBERNATE_CONFIG_KEY_App]));
                 //new NHibernate.Tool.hbm2ddl.SchemaExport(configuration).SetOutputFile(@"c:\temp\MyDDL.sql").Execute(true /*script*/, true /*export to db*/, false /*just drop*/);
                 _appDomainFactory = configuration.BuildSessionFactory();
             }
         }
     }
     return _appDomainFactory;
 }
Beispiel #10
0
        public static void Initialize()
        {
            NhibernateConfiguration = new Configuration().Configure();

            // Mapping by Mapping XML-Files
            foreach (var xmlMappingAssembly in GetXmlMappingAssemblies())
            {
                NhibernateConfiguration.AddAssembly(xmlMappingAssembly);
            }

            // Mapping by Code
            var modelMapper = new ModelMapper();

            foreach (var modelAssembly in GetModelAssemblies())
            {
                modelMapper.AddMappings(modelAssembly.GetExportedTypes());
                NhibernateConfiguration.AddAssembly(modelAssembly);
            }
            if (GetModelAssemblies().Any())
            {
                HbmMapping domainMapping = modelMapper.CompileMappingForAllExplicitlyAddedEntities();
                NhibernateConfiguration.AddMapping(domainMapping);
            }

            SessionFactory = NhibernateConfiguration.BuildSessionFactory();
        }
 private static Configuration GetConfiguration()
 {
     var config = new Configuration();
     config.Configure();
     config.AddMapping(GetMappings());
     return config;
 }
        /// <summary>
        /// Configures the storage with the user supplied persistence configuration
        /// Azure tables are created if requested by the user
        /// </summary>
        /// <param name="config"></param>
        /// <param name="connectionString"></param>
        /// <param name="createSchema"></param>
        /// <returns></returns>
        public static Configure AzureSubcriptionStorage(this Configure config,
            string connectionString,
            bool createSchema,
            string tableName)
        {
            var cfg = new Configuration()
            .DataBaseIntegration(x =>
                                   {
                                     x.ConnectionString = connectionString;
                                     x.ConnectionProvider<TableStorageConnectionProvider>();
                                     x.Dialect<TableStorageDialect>();
                                     x.Driver<TableStorageDriver>();
                                   });

               SubscriptionMap.TableName = tableName;

              var mapper = new ModelMapper();
              mapper.AddMappings(Assembly.GetExecutingAssembly().GetExportedTypes());
              var faultMappings = mapper.CompileMappingForAllExplicitlyAddedEntities();

              cfg.AddMapping(faultMappings);

              if (createSchema)
              {
            new SchemaExport(cfg).Execute(true, true, false);
              }

              var sessionSource = new SubscriptionStorageSessionProvider(cfg.BuildSessionFactory());

            config.Configurer.RegisterSingleton<ISubscriptionStorageSessionProvider>(sessionSource);

            config.Configurer.ConfigureComponent<SubscriptionStorage>(DependencyLifecycle.InstancePerCall);

            return config;
        }
Beispiel #13
0
        static SessionFactory()
        {
            var connectionString = @"Data Source=.\sqlexpress2014;Initial Catalog=BlogDatabase;Integrated Security=True";

            var configuration = new Configuration();
            configuration.DataBaseIntegration(
                x =>
                {
                    x.ConnectionString = connectionString;
                    x.Driver<SqlClientDriver>();
                    x.Dialect<MsSql2012Dialect>();
                });
            configuration.SetProperty(Environment.UseQueryCache, "true");
            configuration.SetProperty(Environment.UseSecondLevelCache, "true");
            configuration.SetProperty(Environment.CacheProvider, typeof(SysCacheProvider).AssemblyQualifiedName);
            var mapper = new ModelMapper();
            mapper.AddMappings(Assembly.GetExecutingAssembly().GetExportedTypes());

            mapper.BeforeMapBag += (modelInspector, member1, propertyCustomizer) =>
            {
                propertyCustomizer.Inverse(true);
                propertyCustomizer.Cascade(Cascade.All | Cascade.DeleteOrphans);
            };
            mapper.BeforeMapManyToOne +=
                (modelInspector, member1, propertyCustomizer) => { propertyCustomizer.NotNullable(true); };
            mapper.BeforeMapProperty += (inspector, member, customizer) => customizer.NotNullable(true);
            var mapping = mapper.CompileMappingForAllExplicitlyAddedEntities();
            configuration.AddMapping(mapping);
            sessionFactory = configuration.BuildSessionFactory();
        }
Beispiel #14
0
		public void SpecifiedForeignKeyNameInByCodeMappingIsUsedInGeneratedSchema()
		{
			var mapper = new ModelMapper();

			// Generates a schema in which a Person record cannot be created unless an Employee
			// with the same primary key value already exists. The Constrained property of the
			// one-to-one mapping is required to create the foreign key constraint on the Person
			// table, and the optional ForeignKey property is used to name it; otherwise a
			// generated name is used

			mapper.Class<Person>(rc =>
			{
				rc.Id(x => x.Id, map => map.Generator(Generators.Foreign<Employee>(p => p.Person)));
				rc.Property(x => x.Name);
				rc.OneToOne(x => x.Employee, map =>
				{
					map.Constrained(true);
					map.ForeignKey(ForeignKeyName);
				});
			});

			mapper.Class<Employee>(rc =>
			{
				rc.Id(x => x.Id);
				rc.OneToOne(x => x.Person, map => { });
			});

			var script = new StringBuilder();
			var cfg = new Configuration();
			cfg.AddMapping(mapper.CompileMappingForAllExplicitlyAddedEntities());

			new SchemaExport(cfg).Execute(s => script.AppendLine(s), false, false);
			script.ToString().Should().Contain(string.Format("constraint {0}", ForeignKeyName));
		}
        /// <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();
        }
        public static void GenerateSchema()
        {
            Configuration cfg = new Configuration();

            //cfg.SetProperty("nhibernate.envers.default_schema", "audit");

            cfg.AddAuxiliaryDatabaseObject(new SpatialAuxiliaryDatabaseObject(cfg));

            var mapper = new ModelMapper();
            mapper.AddMappings(Assembly.GetExecutingAssembly().GetExportedTypes());

            HbmMapping mapping = mapper.CompileMappingForAllExplicitlyAddedEntities();
            cfg.AddMapping(mapping);

            cfg.AddAssembly(typeof(Model).Assembly);

            //cfg.IntegrateWithEnvers();

            cfg.Configure();

            new NHibernate.Tool.hbm2ddl.SchemaExport(cfg)
                .SetDelimiter(";")
                //.SetOutputFile("schema.sql")
                .Execute(false, true, false);
        }
        private ISessionFactory BuildSessionFactory()
        {
            var mapper = new ModelMapper();
            var configuration = new Configuration();

            mapper.AddMappings(Assembly.GetExecutingAssembly().GetExportedTypes());

            configuration.DataBaseIntegration(c =>
            {
                c.ConnectionString = _connectionString;
                c.IsolationLevel = IsolationLevel.ReadCommitted;
                c.Driver<Sql2008ClientDriver>();
                c.Dialect<MsSql2008Dialect>();
                c.BatchSize = 50;
                c.Timeout = 30;

            #if DEBUG
                c.LogSqlInConsole = true;
                c.LogFormattedSql = true;
                c.AutoCommentSql = true;
            #endif
            });

            #if DEBUG
            configuration.SessionFactory().GenerateStatistics();
            #endif

            configuration.AddMapping(mapper.CompileMappingForAllExplicitlyAddedEntities());
            var sessionFactory = configuration.BuildSessionFactory();

            return sessionFactory;
        }
        public static void NHibernateConfiguration(TestContext context)
        {
            log4net.Config.XmlConfigurator.Configure();

            Configuration = new Configuration();
            // lendo o arquivo hibernate.cfg.xml
            Configuration.Configure();

            FilterDefinition filterDef = new FilterDefinition(
                "Empresa","EMPRESA = :EMPRESA",
                new Dictionary<string, IType>() {{"EMPRESA", NHibernateUtil.Int32}}, false);
            Configuration.AddFilterDefinition(filterDef);
            filterDef = new FilterDefinition(
                "Ativa", "ATIVO = 'Y'",
                new Dictionary<string, IType>(), false);
            Configuration.AddFilterDefinition(filterDef);

            // Mapeamento por código
            var mapper = new ModelMapper();
            mapper.AddMappings(Assembly.GetExecutingAssembly().GetExportedTypes());
            HbmMapping mapping = mapper.CompileMappingForAllExplicitlyAddedEntities();
            Configuration.AddMapping(mapping);

            // Gerar o XML a partir do mapeamento de codigo.
            //var mappingXMl = mapping.AsString();

            // Mapeamento por arquivo, in resource.
            Configuration.AddAssembly(Assembly.GetExecutingAssembly());

            // Gerando o SessionFactory
            SessionFactory = Configuration.BuildSessionFactory();
        }
Beispiel #19
0
        private Configuration BuildSQLiteConfiguration()
        {
            var config = new Configuration();

            config.DataBaseIntegration(x =>
            {
                x.Driver <SQLite20Driver>();
                x.Dialect <CustomSQLiteDialect>();
                x.ConnectionProvider <DriverConnectionProvider>();
                x.KeywordsAutoImport = Hbm2DDLKeyWords.AutoQuote;
                x.ConnectionString   = BuildSqlitePath();
                x.Timeout            = 255;
                x.BatchSize          = 100;
                x.LogFormattedSql    = true;
                x.LogSqlInConsole    = true;
                x.AutoCommentSql     = false;
            });

            var mapper = new ModelMapper();

            mapper.AddMappings(typeof(DevContainer).Assembly.GetExportedTypes());

            var domainMapping = mapper.CompileMappingForAllExplicitlyAddedEntities();

            if (domainMapping.Items != null)
            {
                config.AddMapping(domainMapping);
            }

            return(config);
        }
Beispiel #20
0
        private ISessionFactory BuildProjectsSessionFactory()
        {
            // register nhibernate
            var file = "deal.cat";
            if (ChiffrageWPF.Properties.Settings.Default.DealsRecentPath != null && ChiffrageWPF.Properties.Settings.Default.DealsRecentPath.Count > 0)
            {
                file = ChiffrageWPF.Properties.Settings.Default.DealsRecentPath[ChiffrageWPF.Properties.Settings.Default.DealsRecentPath.Count - 1];
            }

            var dealConfiguration = new Configuration()
            .Proxy(p => p.ProxyFactoryFactory<NHibernate.Bytecode.DefaultProxyFactoryFactory>())
            .DataBaseIntegration(d =>
            {
                d.ConnectionString = string.Format("Data Source={0};Version=3;", file);
                d.Dialect<SQLiteDialect>();
                d.SchemaAction = SchemaAutoAction.Update;
            });
            var dealMapper = new ModelMapper();

            dealMapper.AddMappings(typeof(DealRepository).Assembly.GetTypes());

            HbmMapping dealMapping = dealMapper.CompileMappingForAllExplicitlyAddedEntities();
            dealConfiguration.AddMapping(dealMapping);

            return dealConfiguration.BuildSessionFactory();
        }
		protected override void Mapping(Configuration config)
		{
			var mapper = new ModelMapper();
			mapper.Class<Software>(map =>
			{
				map.Id(s => s.Id, o => o.Generator(Generators.GuidComb));
				map.Property(s => s.Name, o =>
				{
					o.NotNullable(true);
					o.Unique(true);
				});
			});

			mapper.Class<AssignedSoftware>(map =>
			{
				map.Id(s => s.Key, o => o.Generator(Generators.Assigned));
				map.Property(s => s.Name, o =>
				{
					o.NotNullable(true);
					o.Unique(true);
				});
			});

			var mapping = mapper.CompileMappingForAllExplicitlyAddedEntities();
			config.AddMapping(mapping);
			config.DataBaseIntegration(db => db.LogSqlInConsole = true);
		}
        static void Main(string[] args)
        {
            #region NHibernate
            var hibernateConfig = new Configuration();
            hibernateConfig.DataBaseIntegration(x =>
            {
                x.ConnectionStringName = "NServiceBus/Persistence";
                x.Dialect <MsSql2012Dialect>();
            });
            var mapper = new ModelMapper();
            mapper.AddMapping <OrderMap>();
            hibernateConfig.AddMapping(mapper.CompileMappingForAllExplicitlyAddedEntities());
            SessionFactory = hibernateConfig.BuildSessionFactory();
            #endregion

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

            #region ReceiverConfiguration
            var busConfig = new BusConfiguration();
            busConfig.UseTransport <SqlServerTransport>().UseSpecificConnectionInformation(
                EndpointConnectionInfo.For("sender")
                .UseConnectionString(@"Data Source=.\SQLEXPRESS;Initial Catalog=sender;Integrated Security=True"));

            busConfig.UsePersistence <NHibernatePersistence>();
            busConfig.EnableOutbox();
            #endregion

            using (Bus.Create(busConfig).Start())
            {
                Console.WriteLine("Press <enter> to exit");
                Console.ReadLine();
            }
        }
Beispiel #23
0
        public void TestConnection()
        {
            var cfg = new Configuration()
                    .DataBaseIntegration(db =>
                    {
                        db.ConnectionString = "Server=127.0.0.1;Database=troyanda;Uid=postgres;Pwd=qwerty;";
                        db.Dialect<PostgreSQL94Dialect>();
                        db.SchemaAction = SchemaAutoAction.Validate;
                    });

            var types = typeof (Cars).Assembly.GetExportedTypes();
            /* Add the mapping we defined: */
            var mapper = new ModelMapper();
            mapper.AddMappings(types);

            var mapping = mapper.CompileMappingForAllExplicitlyAddedEntities();

            cfg.AddMapping(mapping);

            /* Create a session and execute a query: */
            using (ISessionFactory factory = cfg.BuildSessionFactory())
            using (ISession session = factory.OpenSession())
            using (ITransaction tx = session.BeginTransaction())
            {
                var car = session.Get<Cars>((long)1);

                var worker = new WorkerServices(cfg, session);

                var result = worker.GetItemsPresenterForEntity(typeof (Sector));
                //session.Save()

                tx.Commit();
            }
        }
        public static Configuration BuildConfiguration(string connStr)
        {
            var cfg = new Configuration();

            // See http://fabiomaulo.blogspot.com/2009/07/nhibernate-configuration-through.html
            cfg.DataBaseIntegration(db => {
                db.Driver<SqlClientDriver>();
                db.Dialect<MsSql2012Dialect>();
                db.ConnectionString = connStr; // db.ConnectionStringName = "ConnStr";
                db.HqlToSqlSubstitutions = "true 1, false 0, yes 'Y', no 'N'";

                // See http://geekswithblogs.net/lszk/archive/2011/07/12/showing-a-sql-generated-by-nhibernate-on-the-vs-build-in.aspx
                //db.LogSqlInConsole = true; // Remove if using Log4Net
                //db.LogFormattedSql = true;
                //db.AutoCommentSql = true;

                db.SchemaAction = SchemaAutoAction.Validate; // This correspond to "hbm2ddl.validate", see http://nhforge.org/blogs/nhibernate/archive/2008/11/23/nhibernate-hbm2ddl.aspx
            });

            var mapper = new ModelMapper();
            mapper.Class<Parent>(map => {
                map.Id(x => x.Id, m => {
                    m.Generator(Generators.GuidComb);
                    m.UnsavedValue(Guid.Empty);
                });
                map.Version(x => x.RowVersion, m => m.UnsavedValue(0));
                map.Property(x => x.Description);
            });
            cfg.AddMapping(mapper.CompileMappingForAllExplicitlyAddedEntities());
            return cfg;
        }
Beispiel #25
0
    static async Task AsyncMain()
    {
        Console.Title = "Samples.SQLNHibernateOutbox.Receiver";
        #region NHibernate

        var hibernateConfig = new Configuration();
        hibernateConfig.DataBaseIntegration(x =>
        {
            x.ConnectionString = @"Data Source=.\SqlExpress;Database=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;Database=nservicebus;Integrated Security=True");

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

        endpointConfiguration.EnableOutbox();

        #endregion

        #region RetriesConfiguration

        endpointConfiguration.Recoverability()
        .Immediate(immediate => immediate.NumberOfRetries(0))
        .Delayed(delayed => delayed.NumberOfRetries(0));

        #endregion

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

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

        try
        {
            Console.WriteLine("Press any key to exit");
            Console.ReadKey();
        }
        finally
        {
            await endpointInstance.Stop()
            .ConfigureAwait(false);
        }
    }
Beispiel #26
0
        static SessionFactory()
        {
            mapper.AddMappings(typeof(SessionFactory).Assembly.GetTypes());

            configuraion.Configure();

            configuraion.AddMapping(mapper.CompileMappingForAllExplicitlyAddedEntities());
        }
 public static void MapAll(Configuration cfg, Assembly a)
 {
     var mapper = new ModelMapper();
     mapper.AddMappings(a.GetExportedTypes());
     var domainMapping =
       mapper.CompileMappingForAllExplicitlyAddedEntities();
     cfg.AddMapping(domainMapping);
 }
        private static void ConfigureMappings(Configuration configuration)
        {
            var mapper = new ModelMapper();

            mapper.AddMappings(Assembly.GetAssembly(typeof(UserMapping)).GetTypes());

            configuration.AddMapping(mapper.CompileMappingForAllExplicitlyAddedEntities());
        }
    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);
        }
    }
Beispiel #30
0
    static async Task AsyncMain()
    {
        Console.Title = "Samples.SQLNHibernateOutbox.Receiver";
        #region NHibernate

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

        #endregion

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

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

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

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

        endpointConfiguration.EnableOutbox();

        #endregion

        #region RetriesConfiguration

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

        #endregion

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

        IEndpointInstance endpoint = await Endpoint.Start(endpointConfiguration);

        try
        {
            Console.WriteLine("Press any key to exit");
            Console.ReadKey();
        }
        finally
        {
            await endpoint.Stop();
        }
    }
 protected override void PostProcessMappings(Configuration config)
 {
     if (_hbmMappings != null)
     {
         foreach (HbmMapping hbmMapping in _hbmMappings)
         {
             config.AddMapping(hbmMapping);
         }
     }
 }
        public static Configuration AddConfigurationMappings(this Configuration configuration)
        {
            configuration.AddMapping(GetMappingFor(typeof(ClientMapper),
                                                   typeof(ApiResourceMapper),
                                                   typeof(ApiResourceScopeMapper),
                                                   typeof(IdentityResourceMapper)
                                                   ));

            return(configuration);
        }
		static void Main(String[] args)
		{
			var cfg = new Configuration();
			cfg.DataBaseIntegration(x =>
				{
					x.Dialect<MsSql2008Dialect>();
					x.Driver<Sql2008ClientDriver>();
					x.ConnectionString = @"Data Source=(local)\SQLEXPRESS; Initial Catalog=NHibernate; Integrated Security=SSPI";
					x.SchemaAction = SchemaAutoAction.Update;
				})
				.SetProperty(NHibernate.Cfg.Environment.UseProxyValidator, Boolean.FalseString);

			var model = new ConventionModelMapper();
			model.BeforeMapClass += (a, b, c) => { c.Lazy(false); c.Id(x => x.Generator(Generators.Identity)); };

			var mappings = model.CompileMappingFor(new Type[] { typeof(Xpto) });

			cfg.AddMapping(mappings);

			using (var sessionFactory = cfg.BuildSessionFactory())
			{
				var validation = sessionFactory
					.FluentlyValidate()
					.Entity<Xpto>(x => x.Name != "aa", "Name is empty");

				using (var session = sessionFactory.OpenSession())
				using (var tx = session.BeginTransaction())
				{
					var x = new Xpto();

					try
					{
						session.Save(x);
						session.Flush();
					}
					catch
					{
						//expected
					}

					x.Name = "aa";

					//disable all validations
					//sessionFactory.DisableFluentValidation();
					
					//disable validations over the Xpto class
					//validation.Clear<Xpto>();

					//session.Save(new Xpto());
					session.Flush();
					//should work
				}
			}
		}
Beispiel #34
0
        static void AddConventionalMapping(Configuration cfg)
        {
            var modelMapper = new ConventionModelMapper();
            modelMapper.IsEntity((x, y) => x.IsClass == true && x.IsSealed == false && x.Namespace == typeof(Program).Namespace);
            modelMapper.BeforeMapClass += (x, y, z) => { z.Id(a => a.Generator(Generators.Identity)); z.Lazy(true); };
            modelMapper.BeforeMapManyToOne += (x, y, z) => { z.Lazy(LazyRelation.Proxy); z.NotNullable(true); };

            var mappings = modelMapper.CompileMappingFor(typeof(Program).Assembly.GetTypes().Where(x => x.IsPublic && x.IsSealed == false));

            cfg.AddMapping(mappings);
        }
Beispiel #35
0
        private void LoadClassMappings(Configuration configuration)
        {
            var mapper = new ModelMapper();

            mapper.AddMappings(GetClassMappings());
            HbmMapping mapping = mapper.CompileMappingForAllExplicitlyAddedEntities();

            configuration.AddMapping(mapping);

            logger.WriteLine(mapping.AsString());
        }
        private static Configuration CreatConfiguration()
        {
            ModelMapper mapper = GetMapper();
            HbmMapping mapping = mapper.CompileMappingForAllExplicitlyAddedEntities();

            var configuration = new Configuration();
            configuration.SetProperty(Environment.Dialect, "NHibernate.Dialect.MsSql2012Dialect");
            configuration.SetProperty(Environment.ConnectionString, @"Data Source=.\sqlexpress;Initial Catalog=OrdersDatabase;Integrated Security=True");
            configuration.AddMapping(mapping);

            return configuration;
        }
        static void Execute()
        {
            //Mapper
            var mapper = new ModelMapper();
            MapVisualFeed(mapper);
            MapVideoFeed(mapper);
            MapPlaylistAssignment(mapper);
            var mapping = mapper.CompileMappingForAllExplicitlyAddedEntities();

            //Configuration
            var configuration = new Configuration();
            configuration.DataBaseIntegration(x =>
            {
                x.Dialect<MsSql2008Dialect>();
                x.Driver<Sql2008ClientDriver>();
                x.AutoCommentSql = true;
                x.SchemaAction = SchemaAutoAction.Validate;
                x.KeywordsAutoImport = Hbm2DDLKeyWords.AutoQuote;
                x.ConnectionString = "Data Source=localhost;Initial Catalog=Test;Integrated Security=true";
                x.PrepareCommands = false;
                x.BatchSize = short.MaxValue;
            });
            configuration.AddMapping(mapping);

            //Export Schema
            new SchemaExport(configuration).Drop(false, true);
            new SchemaExport(configuration).Create(false, true);

            //Session Factory
            var sf = configuration.BuildSessionFactory();

            //Insert
            using (var session = sf.OpenSession())
            {
                var video = new VideoFeed();
                var playlist = new PlaylistAssignment() { VideoFeed = video };

                video.PlaylistAssignments = new Iesi.Collections.Generic.HashedSet<PlaylistAssignment>();
                video.PlaylistAssignments.Add(playlist);

                session.Save(video);
                session.Flush();
            }

            //Query
            using (var session = sf.OpenSession())
            {
                var videos = session.QueryOver<VideoFeed>().List();
                var playlists = videos.SelectMany(x => x.PlaylistAssignments);
            }
        }
Beispiel #38
0
        /// <summary>
        /// Get a configuration using settings in web.config and map entities in this assembly
        /// </summary>
        /// <returns></returns>
        public static Configuration GetConfiguration()
        {
            Configuration cfg = new Configuration();

            ModelMapper mapper = new ModelMapper();
            mapper.AddMappings(Assembly.GetExecutingAssembly().GetExportedTypes());

            HbmMapping domainMapping =
              mapper.CompileMappingForAllExplicitlyAddedEntities();
            cfg.AddMapping(domainMapping);
            cfg.Configure();

            return cfg;
        }
Beispiel #39
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();
        }
Beispiel #40
0
        public void Start()
        {
            _host = WebApp.Start <Startup>(Endpoint);

            Console.WriteLine();
            Console.WriteLine("Hangfire Server started.");
            Console.WriteLine("Dashboard is available at {0}/hangfire", Endpoint);
            Console.WriteLine();

            var config = new NHibernate.Cfg.Configuration();

            config.DataBaseIntegration(db =>
            {
                db.Dialect <MsSql2008Dialect>();
                db.ConnectionStringName = "DataContext";
            });

            var mapper = new ModelMapper();

            mapper.AddMapping <ApplicationMap>();
            mapper.AddMapping <EnviromentMap>();
            mapper.AddMapping <DeployTaskMap>();
            mapper.AddMapping <ParameterMap>();
            mapper.AddMapping <DeploymentMap>();
            mapper.AddMapping <ApplicationAdministratorsMap>();
            mapper.AddMapping <AllowedGroupMap>();
            mapper.AddMapping <AllowedUserMap>();
            mapper.AddMapping <LogEntryMap>();
            mapper.AddMapping <MailTaskMap>();
            mapper.AddMapping <LocalScriptTaskMap>();
            mapper.AddMapping <RemoteScriptTaskMap>();
            mapper.AddMapping <DatabaseTaskMap>();
            mapper.AddMapping <AgentMap>();
            mapper.AddMapping <ApplicationGroupMap>();
            mapper.AddMapping <DeploymentTaskMap>();
            mapper.AddMapping <TaskTemplateMap>();
            mapper.AddMapping <TaskTemplateVersionMap>();
            mapper.AddMapping <TaskTemplateParameterMap>();
            mapper.AddMapping <TemplatedTaskMap>();
            mapper.AddMapping <TemplatedTaskParameterMap>();
            mapper.AddMapping <MaintenanceTaskMap>();
            mapper.AddMapping <MaintenanceLogEntryMap>();

            config.AddMapping(mapper.CompileMappingForAllExplicitlyAddedEntities());

            DeployJob.Store         = config.BuildSessionFactory();
            LogsCompactionJob.Store = DeployJob.Store;
            MaintenanceJob.Store    = DeployJob.Store;
            HealthCheckJob.Store    = DeployJob.Store;
        }
        NHibernate.Cfg.Configuration CreateConfiguration()
        {
            ModelMapper mapper = CreateModelMapper();

            HbmMapping domainMapping = mapper.CompileMappingForAllExplicitlyAddedEntities();

            var configuration = new NHibernate.Cfg.Configuration();

            configuration = ApplyDatabaseIntegration(configuration);

            configuration.AddMapping(domainMapping);

            return(configuration);
        }
        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;
        }
        public static void Configure()
        {
            var config = new Configuration(); //crate a configuration object.

            //configure connection string
            config.Configure();
            //add our mappings
            var mapper = new ModelMapper();
            mapper.AddMapping<UserMap>();

            config.AddMapping(mapper.CompileMappingForAllExplicitlyAddedEntities());

            //create session factory
            _sessionFactory = config.BuildSessionFactory();
        }
        public void ApplyTo(Configuration configuration)
        {
            var mapper = new ModelMapper();
            mapper.Class<Node>(node =>
            {
                node.Id(x => x.Id, map =>
                {
                    map.Column("NodeId");
                    map.Generator(Generators.GuidComb);
                });
                node.Property(x => x.Name, map =>
                {
                    map.Length(50);
                    map.Column("NodeName");
                });
                node.Bag(x => x.Connections, bag =>
                {
                    bag.Key(key =>
                    {
                        key.Column("StartNodeId");
                        key.ForeignKey("FK_RelatedNode_Node_StartNodeId");
                    });
                    bag.Table("Connection");
                    bag.Cascade(Cascade.All.Include(Cascade.Remove));
                    bag.Fetch(CollectionFetchMode.Subselect);
                });
            });

            mapper.Component<Connection>(connection =>
            {
                connection.Parent(x => x.Start);
                connection.ManyToOne(x => x.End, manyToOne =>
                {
                    manyToOne.Column("EndNodeId");
                    manyToOne.ForeignKey("FK_RelatedNode_Node_EndNodeId");
                    manyToOne.Cascade(Cascade.Persist);
                    manyToOne.NotNullable(true);
                });
                connection.Component(x => x.Quality, c => {});
            });

            mapper.Component<ConnectionQuality>(connectionQuality =>
            {
                connectionQuality.Property(x => x.UploadMbps);
                connectionQuality.Property(x => x.DownloadMbps);
            });
            configuration.AddMapping(mapper.CompileMappingForAllExplicitAddedEntities());
        }
Beispiel #45
0
        private static Configuration BuildDatabaseConfiguration()
        {
            var config = new Configuration().Configure();

            var mapper = new ModelMapper();

            mapper.AddMappings(Assembly.GetExecutingAssembly().GetExportedTypes());

            var domainMapping = mapper.CompileMappingForAllExplicitlyAddedEntities();

            if (domainMapping.Items != null)
            {
                config.AddMapping(domainMapping);
            }

            return(config);
        }
Beispiel #46
0
        private bool Conexao()
        {
            //Cria a configuração com o NH

            var config = new NHibernate.Cfg.Configuration();

            try
            {
                //Integração com o banco de dados
                config.DataBaseIntegration(c => {
                    //Dialeto do banco
                    c.Dialect <NHibernate.Dialect.MySQLDialect>();
                    //String de conexão
                    c.ConnectionString = StringConexao;
                    //Driver de conexão com o banco
                    c.Driver <NHibernate.Driver.MySqlDataDriver>();
                    //Provedor de conexão do MySQL
                    c.ConnectionProvider <NHibernate.Connection.DriverConnectionProvider>();
                    //Gera Log dos  comenados exercutados no console
                    c.LogSqlInConsole = true;
                    //Cria o schema do banco de dados sempre que a configuration for utilizada
                    c.SchemaAction = SchemaAutoAction.Update;
                });

                //Realiza o mapeamento das classes
                var maps = this.Mapeamento();
                config.AddMapping(maps);

                if (HttpContext.Current == null)
                {
                    config.CurrentSessionContext <ThreadStaticSessionContext>();
                }
                else
                {
                    config.CurrentSessionContext <WebSessionContext>();
                }

                this.SessionFactory = config.BuildSessionFactory();

                return(true);
            }
            catch
            {
                throw;
            }
        }
        private static ISessionFactory ConfigureSessionFactory()
        {
            var cfg = new Configuration()
                      .DataBaseIntegration(db =>
            {
                db.ConnectionString = GetConnectionString();
                db.Driver <MySqlDataDriver>();
                db.Dialect <MySQLDialect>();
            });
            var mapper = new ModelMapper();

            mapper.AddMappings(Assembly.GetExecutingAssembly().GetExportedTypes());
            var mapping = mapper.CompileMappingForAllExplicitlyAddedEntities();

            cfg.AddMapping(mapping);
            new SchemaUpdate(cfg).Execute(true, true);
            return(cfg.BuildSessionFactory());
        }
Beispiel #48
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            var configuration = new NHibernate.Cfg.Configuration();

            configuration.DataBaseIntegration(c =>
            {
                c.Driver <NHibernate.Driver.NpgsqlDriver>();
                c.Dialect <NHibernate.Dialect.PostgreSQL83Dialect>();

                var connectionString = System.Environment.GetEnvironmentVariable("CONNECTION_STRING");
                Console.WriteLine("Given ConnectionString:" + connectionString);
                c.ConnectionString = connectionString;
                c.LogFormattedSql  = true;
                c.LogSqlInConsole  = true;
            });

            var mapper = new NHibernate.Mapping.ByCode.ModelMapper();

            mapper.AddMapping <PatientMapping>();
            mapper.AddMapping <ObservationMapping>();

            var mapping = mapper.CompileMappingForAllExplicitlyAddedEntities();

            configuration.AddMapping(mapping);

            services.AddSingleton <ICentralConfiguration>(new CentralConfiguration());
            services.AddSingleton <IObservationTransformer>(new ObservationTransformer());

            // add NHibernate services;
            services.AddHibernate(configuration);

            services.AddControllers();

            services.AddCors(options =>
            {
                options.AddPolicy("CorsPolicy",
                                  builder => builder
                                  .AllowAnyMethod()
                                  .AllowCredentials()
                                  .SetIsOriginAllowed((host) => true)
                                  .AllowAnyHeader());
            });
        }
Beispiel #49
0
    static void Main()
    {
        Console.Title = "Samples.SQLNHibernateOutbox.Receiver";
        #region NHibernate

        Configuration hibernateConfig = new Configuration();
        hibernateConfig.DataBaseIntegration(x =>
        {
            x.ConnectionStringName = "NServiceBus/Persistence";
            x.Dialect <MsSql2012Dialect>();
        });
        ModelMapper mapper = new ModelMapper();
        mapper.AddMapping <OrderMap>();
        hibernateConfig.AddMapping(mapper.CompileMappingForAllExplicitlyAddedEntities());

        #endregion

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

        BusConfiguration busConfiguration = new BusConfiguration();
        busConfiguration.UseSerialization <JsonSerializer>();
        busConfiguration.EndpointName("Samples.SQLNHibernateOutbox.Receiver");
        #region ReceiverConfiguration

        busConfiguration.UseTransport <SqlServerTransport>();

        busConfiguration.UsePersistence <NHibernatePersistence>()
        .RegisterManagedSessionInTheContainer()
        .UseConfiguration(hibernateConfig);

        busConfiguration.EnableOutbox();

        #endregion

        busConfiguration.DisableFeature <SecondLevelRetries>();

        using (Bus.Create(busConfiguration).Start())
        {
            Console.WriteLine("Press any key to exit");
            Console.ReadKey();
        }
    }
Beispiel #50
0
        public static NHibernate.Cfg.Configuration ConfigureEntities(this NHibernate.Cfg.Configuration configuration)
        {
            var modelMapper = new ModelMapper();

            modelMapper.
            AddMappings(
                Assembly.
                GetExecutingAssembly().
                GetExportedTypes().
                Where(t => t.Name.EndsWith("Mapping"))
                );

            configuration.
            AddMapping(
                modelMapper.
                CompileMappingForAllExplicitlyAddedEntities()
                );

            return(configuration);
        }
        public static Configuration RecuperaConfiguracao()
        {
            Configuration cfg    = new Configuration();
            var           mapper = new ModelMapper();

            mapper.AddMappings(Assembly.GetExecutingAssembly().GetExportedTypes());

            string conn = ConfigurationManager.ConnectionStrings["Conexao"].ConnectionString;

            cfg.DataBaseIntegration(c =>
            {
                c.ConnectionProvider <DriverConnectionProvider>();
                c.Dialect <MsSql2012Dialect>();
                c.Driver <SqlClientDriver>();
                c.ConnectionString = conn;
                c.SchemaAction     = SchemaAutoAction.Update;
            });
            cfg.AddMapping(mapper.CompileMappingForAllExplicitlyAddedEntities());
            return(cfg);
        }
Beispiel #52
0
    static void Main()
    {
        #region NHibernate

        Configuration hibernateConfig = new Configuration();
        hibernateConfig.DataBaseIntegration(x =>
        {
            x.ConnectionStringName = "NServiceBus/Persistence";
            x.Dialect <MsSql2012Dialect>();
        });
        ModelMapper mapper = new ModelMapper();
        mapper.AddMapping <OrderMap>();
        hibernateConfig.AddMapping(mapper.CompileMappingForAllExplicitlyAddedEntities());

        #endregion

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

        #region ReceiverConfiguration

        BusConfiguration busConfiguration = new BusConfiguration();
        busConfiguration.UseTransport <SqlServerTransport>()
        .UseSpecificConnectionInformation(
            EndpointConnectionInfo.For("sender")
            .UseConnectionString(@"Data Source=.\SQLEXPRESS;Initial Catalog=sender;Integrated Security=True"));

        busConfiguration.UsePersistence <NHibernatePersistence>()
        .RegisterManagedSessionInTheContainer()
        .UseConfiguration(hibernateConfig);
        busConfiguration.EnableOutbox();

        #endregion

        busConfiguration.DisableFeature <SecondLevelRetries>();

        using (Bus.Create(busConfiguration).Start())
        {
            Console.WriteLine("Press any key to exit");
            Console.ReadKey();
        }
    }
        private static NHConfig.Configuration BuildConfiguration()
        {
            var configuration = new NHConfig.Configuration();

            configuration
            .SetProperty(NHConfig.Environment.ConnectionDriver, typeof(SQLite20Driver).AssemblyQualifiedName)
            .SetProperty(NHConfig.Environment.Dialect, typeof(SQLiteDialect).AssemblyQualifiedName)
            .SetProperty(NHConfig.Environment.QuerySubstitutions, QuerySubstitutions)
            .SetProperty(NHConfig.Environment.CurrentSessionContextClass, typeof(ThreadStaticSessionContext).AssemblyQualifiedName)
            .SetProperty(NHConfig.Environment.ProxyFactoryFactoryClass, typeof(DefaultProxyFactoryFactory).AssemblyQualifiedName)
            .SetProperty(NHConfig.Environment.Isolation, IsolationLevel.ReadCommitted.ToString())
            .SetProperty(NHConfig.Environment.ConnectionString, InMemoryConnectionString);

            var mappings = BuildMappings();

            configuration.AddMapping(mappings);

            OptimizePerformance(configuration);

            return(configuration);
        }
Beispiel #54
0
        /// <summary>
        /// Configures the storage with the user supplied persistence configuration.
        /// Database schema is updated if requested by the user.
        /// </summary>
        /// <param name="config">The configuration object.</param>
        /// <param name="configuration">The <see cref="Configuration"/> object.</param>
        /// <param name="autoUpdateSchema"><value>true</value> to auto update schema<./param>
        /// <returns>The configuration object</returns>
        public static Configure UseNHibernateTimeoutPersister(this Configure config,
                                                              Configuration configuration,
                                                              bool autoUpdateSchema)
        {
            var mapper = new ModelMapper();

            mapper.AddMappings(Assembly.GetExecutingAssembly().GetExportedTypes());
            HbmMapping faultMappings = mapper.CompileMappingForAllExplicitlyAddedEntities();

            configuration.AddMapping(faultMappings);

            if (autoUpdateSchema)
            {
                new SchemaUpdate(configuration).Execute(false, true);
            }

            config.Configurer.ConfigureComponent <TimeoutStorage>(DependencyLifecycle.SingleInstance)
            .ConfigureProperty(p => p.SessionFactory, configuration.BuildSessionFactory());

            return(config);
        }
        public NHibernate.Cfg.Configuration Configure()
        {
            var config = new NHibernate.Cfg.Configuration();

            config.SetProperty(Environment.ReleaseConnections, "on_close")
            .SetProperty(Environment.Dialect, typeof(NHibernate.Spatial.Dialect.MsSql2008GeographyDialect).AssemblyQualifiedName)
            .SetProperty(Environment.ConnectionDriver, typeof(NHibernate.Driver.SqlClientDriver).AssemblyQualifiedName);

            var modelMapper = new ModelMapper(new ModelInspector());

            modelMapper.AddMappings(typeof(ModelInspector).Assembly.GetExportedTypes());

            var mapping = modelMapper.CompileMappingForAllExplicitlyAddedEntities();

            config.AddMapping(mapping);

            config.SetListener(NHibernate.Event.ListenerType.PostUpdate, new FullTextIndexEventListener());
            config.SetListener(NHibernate.Event.ListenerType.PostInsert, new FullTextIndexEventListener());
            config.SetListener(NHibernate.Event.ListenerType.PostDelete, new FullTextIndexEventListener());

            return(config);
        }
        static void CreateDatabase()
        {
            var configuration = new NHibernate.Cfg.Configuration();
            var _mapper       = new CustomModelMapper();

            configuration.DataBaseIntegration((x) =>
            {
                x.ConnectionString = @"Data Source=localhost;Initial Catalog=EnversBug;Persist Security Info=True;User ID=sa;Password=sa2008~";
                x.Dialect <MsSql2012Dialect>();
            });

            var types = typeof(Entity <>)
                        .Assembly
                        .GetTypes()
                        .Where(t => !t.IsInterface && !t.IsGenericType)
            ;

            _mapper.AddMappings(types);

            configuration.AddMapping(_mapper.CompileMappingFor(types));

            configuration.SetEnversProperty(ConfigurationKey.AuditTableSuffix, "_A");
            configuration.SetEnversProperty(ConfigurationKey.StoreDataAtDelete, true);
            configuration.SetEnversProperty(ConfigurationKey.RevisionOnCollectionChange, false);

            var enversConf = new NHibernate.Envers.Configuration.Fluent.FluentConfiguration();

            enversConf.Audit(types);

            configuration.IntegrateWithEnvers(enversConf);


            var exporter = new SchemaExport(configuration);

            exporter.Execute(true, true, false);

            _sessionFactory = configuration.BuildSessionFactory();
        }
        /// <summary>
        /// Configures the storage with the user supplied persistence configuration
        /// DB schema is updated if requested by the user
        /// </summary>
        /// <param name="config"></param>
        /// <param name="nhibernateProperties"></param>
        /// <param name="autoUpdateSchema"></param>
        /// <returns></returns>
        public static Configure DBSubcriptionStorage(this Configure config,
                                                     Configuration configuration,
                                                     bool autoUpdateSchema)
        {
            var mapper = new ModelMapper();

            mapper.AddMappings(Assembly.GetExecutingAssembly().GetExportedTypes());
            HbmMapping faultMappings = mapper.CompileMappingForAllExplicitlyAddedEntities();

            configuration.AddMapping(faultMappings);

            if (autoUpdateSchema)
            {
                new SchemaUpdate(configuration).Execute(false, true);
            }

            var sessionSource = new SubscriptionStorageSessionProvider(configuration.BuildSessionFactory());

            config.Configurer.RegisterSingleton <ISubscriptionStorageSessionProvider>(sessionSource);
            config.Configurer.ConfigureComponent <SubscriptionStorage>(DependencyLifecycle.InstancePerCall);

            return(config);
        }
        /// <summary>
        /// Registers the OpenIddict entity mappings in the NHibernate
        /// configuration using the specified entities and the specified key type.
        /// </summary>
        /// <param name="configuration">The NHibernate configuration builder.</param>
        /// <returns>The <see cref="Configuration"/>.</returns>
        public static Configuration UseOpenIddict <TApplication, TAuthorization, TScope, TToken, TKey>([NotNull] this Configuration configuration)
            where TApplication : OpenIddictApplication <TKey, TAuthorization, TToken>
            where TAuthorization : OpenIddictAuthorization <TKey, TApplication, TToken>
            where TScope : OpenIddictScope <TKey>
            where TToken : OpenIddictToken <TKey, TApplication, TAuthorization>
            where TKey : IEquatable <TKey>
        {
            if (configuration == null)
            {
                throw new ArgumentNullException(nameof(configuration));
            }

            var mapper = new ModelMapper();

            mapper.AddMapping <OpenIddictApplicationMapping <TApplication, TAuthorization, TToken, TKey> >();
            mapper.AddMapping <OpenIddictAuthorizationMapping <TAuthorization, TApplication, TToken, TKey> >();
            mapper.AddMapping <OpenIddictScopeMapping <TScope, TKey> >();
            mapper.AddMapping <OpenIddictTokenMapping <TToken, TApplication, TAuthorization, TKey> >();

            configuration.AddMapping(mapper.CompileMappingForAllExplicitlyAddedEntities());

            return(configuration);
        }
Beispiel #59
0
        private static Configuration buildConfig(ReadModelConnectionString connectionString)
        {
            var cfg = new Configuration().DataBaseIntegration(
                db =>
            {
                db.ConnectionString = (String)connectionString;
                db.Dialect <MySQLDialect>();
            });

            /* Add the mapping we defined: */
            var mapper = new ModelMapper();

            mapper.AddMappings(
                Assembly.GetExecutingAssembly()
                .GetTypes()
                .Where <Type>(g => g.FullName.EndsWith("Map") || g.IsSubclassOf(typeof(ClassMapping))));

            HbmMapping mapping = mapper.CompileMappingForAllExplicitlyAddedEntities();

            cfg.AddMapping(mapping);

            return(cfg);
        }
        static void Main(string[] args)
        {
            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 busConfig = new BusConfiguration();
            busConfig.UseTransport <SqlServerTransport>().DefaultSchema("receiver")
            .UseSpecificConnectionInformation(endpoint =>
            {
                var schema = endpoint.Split(new[] { '.' }, StringSplitOptions.RemoveEmptyEntries)[0].ToLowerInvariant();
                return(ConnectionInfo.Create().UseSchema(schema));
            });
            busConfig.UsePersistence <NHibernatePersistence>().UseConfiguration(hibernateConfig);
            #endregion

            using (Bus.Create(busConfig).Start())
            {
                Console.WriteLine("Press <enter> to exit");
                Console.ReadLine();
            }
        }