Example #1
1
		public static void main(String[] args)
		{
			try
			{
				Configuration cfg = new Configuration();

				bool script = true;
				// If true then execute db updates, otherwise just generate and display updates
				bool doUpdate = true;
				//String propFile = null;

				for (int i = 0; i < args.Length; i++)
				{
					if (args[i].StartsWith("--"))
					{
						if (args[i].Equals("--quiet"))
						{
							script = false;
						}
						else if (args[i].StartsWith("--properties="))
						{
							throw new NotSupportedException("No properties file for .NET, use app.config instead");
							//propFile = args[i].Substring( 13 );
						}
						else if (args[i].StartsWith("--config="))
						{
							cfg.Configure(args[i].Substring(9));
						}
						else if (args[i].StartsWith("--text"))
						{
							doUpdate = false;
						}
						else if (args[i].StartsWith("--naming="))
						{
							cfg.SetNamingStrategy(
								(INamingStrategy) Activator.CreateInstance(ReflectHelper.ClassForName(args[i].Substring(9)))
								);
						}
					}
					else
					{
						cfg.AddFile(args[i]);
					}
				}

				/* NH: No props file for .NET
				 * if ( propFile != null ) {
					Hashtable props = new Hashtable();
					props.putAll( cfg.Properties );
					props.load( new FileInputStream( propFile ) );
					cfg.SetProperties( props );
				}*/

				new SchemaUpdate(cfg).Execute(script, doUpdate);
			}
			catch (Exception e)
			{
				log.Error("Error running schema update", e);
				Console.WriteLine(e);
			}
		}
Example #2
0
		public static void Main(string[] args)
		{
			try
			{
				var cfg = new Configuration();

				//string propFile = null;

				for (int i = 0; i < args.Length; i++)
				{
					if (args[i].StartsWith("--"))
					{
						//if (args[i].StartsWith("--properties="))
						//{
						//  propFile = args[i].Substring(13);
						//}
						//else 
						if (args[i].StartsWith("--config="))
						{
							cfg.Configure(args[i].Substring(9));
						}
						else if (args[i].StartsWith("--naming="))
						{
							cfg.SetNamingStrategy(
								(INamingStrategy)
								Cfg.Environment.BytecodeProvider.ObjectsFactory.CreateInstance(ReflectHelper.ClassForName(args[i].Substring(9))));
						}
					}
					else
					{
						cfg.AddFile(args[i]);
					}
				}
				/* NH: No props file for .NET
				if ( propFile != null ) {
					Properties props = new Properties();
					props.putAll( cfg.getProperties() );
					props.load( new FileInputStream( propFile ) );
					cfg.setProperties( props );
				}
				*/
				new SchemaValidator(cfg).Validate();
			}
			catch (Exception e)
			{
				log.Error("Error running schema update", e);
				Console.WriteLine(e);
			}
		}
Example #3
0
        public EasyWorshipReader(string easyWorshipSongPath)
        {
            var initialConfiguration = new Configuration();
            initialConfiguration.SetNamingStrategy(new ParadoxNamingStrategy());

            var fluentConfiguration =
                Fluently.Configure(initialConfiguration)
                    .Database(JetDriverConfiguration.Standard.ConnectionString(
                        $"Provider=Microsoft.Jet.OLEDB.4.0;Data Source={easyWorshipSongPath};Extended Properties=\"Paradox 5.x;CharacterSet=65001;\"")
                        .Dialect<JetDialect>()
                        .Driver<OleDbDriver>())
                    .Mappings(m => m.FluentMappings.AddFromAssemblyOf<MainForm>());

            _sessionSource = new SessionSource(fluentConfiguration);
        }
Example #4
0
        public static void ConfigureAutoMapping()
        {
            NHibernate.Cfg.Configuration config = new NHibernate.Cfg.Configuration();
            config.SetNamingStrategy(DefaultNamingStrategy.Instance);

            FluentNHibernate.Cfg.FluentConfiguration fConfig = FluentNHibernate.Cfg.Fluently.Configure(config);
            var sessionFactory = Fluently.Configure(config)
                                 .Database(MsSqlConfiguration.MsSql2012.ConnectionString(new Action <ConnectionStringBuilder>(GenerateConnStr)))
                                 .ExposeConfiguration(BuildSchema)
                                 .Mappings(m =>
                                           m.AutoMappings
                                           .Add(AutoMap.AssemblyOf <Product>()))
                                 .BuildSessionFactory();

            var k = sessionFactory.OpenSession();
        }
        public static void RunSync()
        {
            IPersistenceConfigurer configurer = MsSqlConfiguration.MsSql2012.ConnectionString(Engine.ConnectionString)
                                                .FormatSql()
                                                .ShowSql();

            //  IPersistenceConfigurer configurer = MySQLConfiguration.Standard.ConnectionString(Engine.ConnectionString)
            //.FormatSql()
            //.ShowSql();
            NHibernate.Cfg.Configuration configuration = new NHibernate.Cfg.Configuration();
            configuration.SetNamingStrategy(NHibernate.Cfg.LowerImprovedNamingStrategy.Instance);
            Fluently.Configure(configuration)
            .Database(
                configurer
                )
            .Mappings(c => c.FluentMappings.AddFromAssembly(typeof(Account).Assembly))
            .ExposeConfiguration(cfg => new SchemaUpdate(cfg).Execute(true, true))
            .BuildSessionFactory();
        }
        public static void InitMapping(Configuration cfg)
        {
            var mapper = new ModelMapper();

            mapper.AddMapping <DealVariantMap>();
            mapper.AddMapping <DistrictMap>();
            mapper.AddMapping <OwnershipMap>();
            mapper.AddMapping <SewageMap>();
            mapper.AddMapping <WaterSupplyMap>();
            mapper.AddMapping <LayoutMap>();
            mapper.AddMapping <MaterialMap>();
            mapper.AddMapping <RealtorMap>();
            mapper.AddMapping <StreetMap>();
            mapper.AddMapping <TerraceMap>();
            mapper.AddMapping <ToiletTypeMap>();
            mapper.AddMapping <FloorLevelMap>();
            mapper.AddMapping <RealtorAgencyMap>();
            mapper.AddMapping <ConditionMap>();
            mapper.AddMapping <DestinationMap>();

            mapper.AddMapping <RealEstateMap>();
            mapper.AddMapping <PlotMap>();
            mapper.AddMapping <BuildingMap>();
            mapper.AddMapping <ResidenceMap>();
            mapper.AddMapping <ApartmentMap>();
            mapper.AddMapping <FlatMap>();
            mapper.AddMapping <HouseMap>();
            mapper.AddMapping <RoomMap>();

            mapper.BeforeMapClass     += AutoMapper_BeforeMapClass;
            mapper.BeforeMapManyToOne += AutoMapper_BeforeMapManyToOne;
            mapper.BeforeMapBag       += BeforeBag;

            cfg.SetNamingStrategy(new PostgresNamingStrategy());

            cfg.AddMapping(mapper.CompileMappingForAllExplicitlyAddedEntities());
        }
Example #7
0
        /// <summary>
        /// Initialize the SessionFactory for the given or the
        /// default location.
        /// </summary>
        public virtual void AfterPropertiesSet()
        {
            // Create Configuration instance.
            Configuration config = NewConfiguration();

            if (this.dbProvider != null)
            {
                config.SetProperty(Environment.ConnectionString, dbProvider.ConnectionString);
                config.SetProperty(Environment.ConnectionProvider, typeof(DbProviderWrapper).AssemblyQualifiedName);
                configTimeDbProvider = this.dbProvider;
            }

            if (ExposeTransactionAwareSessionFactory)
            {
                // Set ICurrentSessionContext implementation,
                // providing the Spring-managed ISession s current Session.
                // Can be overridden by a custom value for the corresponding Hibernate property
                // config.SetProperty(Environment.CurrentSessionContextClass, typeof(SpringSessionContext).AssemblyQualifiedName);
                config.SetProperty(Environment.CurrentSessionContextClass, typeof(WcfOperationSessionContext).AssemblyQualifiedName);
            }

            if (this.entityInterceptor != null)
            {
                // Set given entity interceptor at SessionFactory level.
                config.SetInterceptor(this.entityInterceptor);
            }

            if (this.namingStrategy != null)
            {
                // Pass given naming strategy to Hibernate Configuration.
                config.SetNamingStrategy(this.namingStrategy);
            }



            if (this.filterDefinitions != null)
            {
                // Register specified NHibernate FilterDefinitions.
                for (int i = 0; i < this.filterDefinitions.Length; i++)
                {
                    config.AddFilterDefinition(this.filterDefinitions[i]);
                }
            }

            if (this.hibernateProperties != null)
            {
                if (config.GetProperty(Environment.ConnectionProvider) != null &&
                    hibernateProperties.Contains(Environment.ConnectionProvider))
                {
                    #region Logging
                    if (log.IsInfoEnabled)
                    {
                        log.Info("Overriding use of Spring's Hibernate Connection Provider with [" +
                                 hibernateProperties[Environment.ConnectionProvider] + "]");
                    }
                    #endregion
                    config.Properties.Remove(Environment.ConnectionProvider);
                }

                Dictionary <string, string> genericHibernateProperties = new Dictionary <string, string>();
                foreach (DictionaryEntry entry in hibernateProperties)
                {
                    genericHibernateProperties.Add((string)entry.Key, (string)entry.Value);
                }
                config.AddProperties(genericHibernateProperties);
            }
            if (this.mappingAssemblies != null)
            {
                foreach (string assemblyName in mappingAssemblies)
                {
                    config.AddAssembly(assemblyName);
                }
            }

            if (this.mappingResources != null)
            {
                IResourceLoader loader = this.ResourceLoader;
                if (loader == null)
                {
                    loader = this.applicationContext;
                }
                foreach (string resourceName in mappingResources)
                {
                    config.AddInputStream(loader.GetResource(resourceName).InputStream);
                }
            }

            if (configFilenames != null)
            {
                foreach (string configFilename in configFilenames)
                {
                    config.Configure(configFilename);
                }
            }

            if (this.eventListeners != null)
            {
                // Register specified NHibernate event listeners.
                foreach (DictionaryEntry entry in eventListeners)
                {
                    ListenerType listenerType;
                    try
                    {
                        listenerType = (ListenerType)Enum.Parse(typeof(ListenerType), (string)entry.Key);
                    }
                    catch
                    {
                        throw new ArgumentException(string.Format("Unable to parse string '{0}' as valid {1}", entry.Key, typeof(ListenerType)));
                    }

                    object listenerObject = entry.Value;
                    if (listenerObject is ICollection)
                    {
                        ICollection    listeners        = (ICollection)listenerObject;
                        EventListeners listenerRegistry = config.EventListeners;

                        // create the array and check that types are valid at the same time
                        ArrayList items         = new ArrayList(listeners);
                        object[]  listenerArray = (object[])items.ToArray(listenerRegistry.GetListenerClassFor(listenerType));
                        config.SetListeners(listenerType, listenerArray);
                    }
                    else
                    {
                        config.SetListener(listenerType, listenerObject);
                    }
                }
            }

            // Perform custom post-processing in subclasses.
            PostProcessConfiguration(config);

            // Build SessionFactory instance.
            log.Info("Building new Hibernate SessionFactory");
            this.configuration  = config;
            this.sessionFactory = NewSessionFactory(config);

            AfterSessionFactoryCreation();

            // set config time DB provider back to null
            configTimeDbProvider = null;
        }
Example #8
0
        /// <summary>
        /// Initialize the SessionFactory for the given or the
        /// default location.
        /// </summary>
        public virtual void AfterPropertiesSet()
        {
            // Create Configuration instance.
            Configuration config = NewConfiguration();

            if (this.dbProvider != null)
            {
                config.SetProperty(Environment.ConnectionString, dbProvider.ConnectionString);
                config.SetProperty(Environment.ConnectionProvider, typeof(DbProviderWrapper).AssemblyQualifiedName);
                configTimeDbProvider = this.dbProvider;
            }

            if (ExposeTransactionAwareSessionFactory)
            {
                // Set ICurrentSessionContext implementation,
                // providing the Spring-managed ISession s current Session.
                // Can be overridden by a custom value for the corresponding Hibernate property
                config.SetProperty(Environment.CurrentSessionContextClass, typeof(SpringSessionContext).AssemblyQualifiedName);
            }

            if (this.entityInterceptor != null)
            {
                // Set given entity interceptor at SessionFactory level.
                config.SetInterceptor(this.entityInterceptor);
            }

            if (this.namingStrategy != null)
            {
                // Pass given naming strategy to Hibernate Configuration.
                config.SetNamingStrategy(this.namingStrategy);
            }

#if NH_2_1
            if (this.typeDefinitions != null)
            {
                // Register specified Hibernate type definitions.
                IDictionary <string, string> typedProperties = new  Dictionary <string, string>();
                foreach (DictionaryEntry entry in hibernateProperties)
                {
                    typedProperties.Add((string)entry.Key, (string)entry.Value);
                }

                Dialect  dialect  = Dialect.GetDialect(typedProperties);
                Mappings mappings = config.CreateMappings(dialect);
                for (int i = 0; i < this.typeDefinitions.Length; i++)
                {
                    IObjectDefinition           typeDef       = this.typeDefinitions[i];
                    Dictionary <string, string> typedParamMap = new Dictionary <string, string>();
                    foreach (DictionaryEntry entry in typeDef.PropertyValues)
                    {
                        typedParamMap.Add((string)entry.Key, (string)entry.Value);
                    }
                    mappings.AddTypeDef(typeDef.ObjectTypeName, typeDef.ObjectTypeName, typedParamMap);
                }
            }
#endif

            if (this.filterDefinitions != null)
            {
                // Register specified NHibernate FilterDefinitions.
                for (int i = 0; i < this.filterDefinitions.Length; i++)
                {
                    config.AddFilterDefinition(this.filterDefinitions[i]);
                }
            }

#if NH_2_1
            // check whether proxy factory has been initialized
            if (config.GetProperty(Environment.ProxyFactoryFactoryClass) == null &&
                (hibernateProperties == null || !hibernateProperties.Contains(Environment.ProxyFactoryFactoryClass)))
            {
                // nothing set by user, lets use Spring.NET's proxy factory factory
                #region Logging
                if (log.IsInfoEnabled)
                {
                    log.Info("Setting proxy factory to Spring provided one as user did not specify any");
                }
                #endregion
                config.Properties.Add(
                    Environment.ProxyFactoryFactoryClass, typeof(Bytecode.ProxyFactoryFactory).AssemblyQualifiedName);
            }
#endif

            if (this.hibernateProperties != null)
            {
                if (config.GetProperty(Environment.ConnectionProvider) != null &&
                    hibernateProperties.Contains(Environment.ConnectionProvider))
                {
                    #region Logging
                    if (log.IsInfoEnabled)
                    {
                        log.Info("Overriding use of Spring's Hibernate Connection Provider with [" +
                                 hibernateProperties[Environment.ConnectionProvider] + "]");
                    }
                    #endregion
                    config.Properties.Remove(Environment.ConnectionProvider);
                }

                Dictionary <string, string> genericHibernateProperties = new Dictionary <string, string>();
                foreach (DictionaryEntry entry in hibernateProperties)
                {
                    genericHibernateProperties.Add((string)entry.Key, (string)entry.Value);
                }
                config.AddProperties(genericHibernateProperties);
            }
            if (this.mappingAssemblies != null)
            {
                foreach (string assemblyName in mappingAssemblies)
                {
                    config.AddAssembly(assemblyName);
                }
            }

            if (this.mappingResources != null)
            {
                IResourceLoader loader = this.ResourceLoader;
                if (loader == null)
                {
                    loader = this.applicationContext;
                }
                foreach (string resourceName in mappingResources)
                {
                    config.AddInputStream(loader.GetResource(resourceName).InputStream);
                }
            }

            if (configFilenames != null)
            {
                foreach (string configFilename in configFilenames)
                {
                    config.Configure(configFilename);
                }
            }

#if NH_2_1
            // Tell Hibernate to eagerly compile the mappings that we registered,
            // for availability of the mapping information in further processing.
            PostProcessMappings(config);
            config.BuildMappings();

            if (this.entityCacheStrategies != null)
            {
                // Register cache strategies for mapped entities.
                foreach (string className in this.entityCacheStrategies.Keys)
                {
                    String[] strategyAndRegion = StringUtils.CommaDelimitedListToStringArray(this.entityCacheStrategies.GetProperty(className));
                    if (strategyAndRegion.Length > 1)
                    {
                        config.SetCacheConcurrencyStrategy(className, strategyAndRegion[0], strategyAndRegion[1]);
                    }
                    else if (strategyAndRegion.Length > 0)
                    {
                        config.SetCacheConcurrencyStrategy(className, strategyAndRegion[0]);
                    }
                }
            }

            if (this.collectionCacheStrategies != null)
            {
                // Register cache strategies for mapped collections.
                foreach (string collRole in collectionCacheStrategies.Keys)
                {
                    string[] strategyAndRegion = StringUtils.CommaDelimitedListToStringArray(this.collectionCacheStrategies.GetProperty(collRole));
                    if (strategyAndRegion.Length > 1)
                    {
                        throw new Exception("Collection cache concurrency strategy region definition not supported yet");
                        //config.SetCollectionCacheConcurrencyStrategy(collRole, strategyAndRegion[0], strategyAndRegion[1]);
                    }
                    else if (strategyAndRegion.Length > 0)
                    {
                        config.SetCollectionCacheConcurrencyStrategy(collRole, strategyAndRegion[0]);
                    }
                }
            }
#endif

            if (this.eventListeners != null)
            {
                // Register specified NHibernate event listeners.
                foreach (DictionaryEntry entry in eventListeners)
                {
                    ListenerType listenerType;
                    try
                    {
                        listenerType = (ListenerType)Enum.Parse(typeof(ListenerType), (string)entry.Key);
                    }
                    catch
                    {
                        throw new ArgumentException(string.Format("Unable to parse string '{0}' as valid {1}", entry.Key, typeof(ListenerType)));
                    }

                    object listenerObject = entry.Value;
                    if (listenerObject is ICollection)
                    {
                        ICollection    listeners        = (ICollection)listenerObject;
                        EventListeners listenerRegistry = config.EventListeners;

                        // create the array and check that types are valid at the same time
                        ArrayList items         = new ArrayList(listeners);
                        object[]  listenerArray = (object[])items.ToArray(listenerRegistry.GetListenerClassFor(listenerType));
                        config.SetListeners(listenerType, listenerArray);
                    }
                    else
                    {
                        config.SetListener(listenerType, listenerObject);
                    }
                }
            }

            // Perform custom post-processing in subclasses.
            PostProcessConfiguration(config);

#if NH_2_1
            if (BytecodeProvider != null)
            {
                // set custom IBytecodeProvider
                Environment.BytecodeProvider = BytecodeProvider;
            }
            else
            {
                // use Spring's as default
                // Environment.BytecodeProvider = new Bytecode.BytecodeProvider(this.applicationContext);
            }
#endif

            // Build SessionFactory instance.
            log.Info("Building new Hibernate SessionFactory");
            this.configuration  = config;
            this.sessionFactory = NewSessionFactory(config);

            AfterSessionFactoryCreation();

            // set config time DB provider back to null
            configTimeDbProvider = null;
        }
        /// <summary>
        /// Main NHibernate configuration method.
        /// It configures NHibernate in an opinionated way, with an option to override various small NHibernate settings by overriding
        /// other virtual methods.
        /// This method can be overridden to completely customize NHibernate configuration.
        /// </summary>
        /// <param name="shouldMapDtos">See the constructor</param>
        /// <param name="configurationFileName">See the constructor</param>
        /// <param name="connectionString">See the constructor</param>
        /// <param name="sessionFactory">NHibernate session factory</param>
        /// <param name="configuration">NHibernate configuration</param>
        protected virtual void ConfigureNhibernate(
            bool shouldMapDtos,
            string configurationFileName,
            string connectionString,
            out ISessionFactory sessionFactory,
            out Configuration configuration
            )
        {
            configuration = new Configuration();
            if (string.IsNullOrWhiteSpace(configurationFileName))
            {
                configuration.Configure();
            }
            else
            {
                configuration.Configure(configurationFileName);
            }

            var assembliesToMap = GetAssembliesToMap();
            var isTypeDto       = GetIsTypeDtoFunc();

            var autoPersistenceModel = AutoMap.Assemblies(
                GetAutomappingConfiguration(shouldMapDtos, isTypeDto),
                assembliesToMap
                );

            GetIncludeBaseTypes().Each(x => autoPersistenceModel.IncludeBase(x));
            GetIgnoreBaseTypes().Each(x => autoPersistenceModel.IgnoreBase(x));
            assembliesToMap.Each(x => autoPersistenceModel.UseOverridesFromAssembly(x));

            _configureConventions();

            configuration.SetNamingStrategy(GetNamingStrategy());

            var fluentConfiguration = Fluently.Configure(configuration)
                                      .Mappings(x =>
            {
                var mappingsContainer            = x.AutoMappings.Add(autoPersistenceModel);
                var exportNhibernateMappingsPath = GetExportNhibernateMappingsPath();
                if (!string.IsNullOrWhiteSpace(exportNhibernateMappingsPath))
                {
                    mappingsContainer.ExportTo(exportNhibernateMappingsPath);
                }
            });

            if (!string.IsNullOrWhiteSpace(connectionString))
            {
                configuration.SetProperty(Environment.ConnectionString, connectionString);
            }

            AdditionalConfiguration(configuration);

            sessionFactory = fluentConfiguration.BuildSessionFactory();

            void _configureConventions()
            {
                if (ShouldUseDefaultConventions())
                {
                    DisableLazyLoadForDtosConvention.Initialize(isTypeDto);
                    HasManyConvention.Initialize(
                        GetCollectionCascadeInstanceAction(),
                        GetBackingFieldNameFromPropertyNameFunc(),
                        GetCollectionInstanceAccessAction()
                        );
                    PrimaryKeyConvention.Initialize(GetIdentityHiLoMaxLo());

                    var disabledConventions = GetDisabledConventions();
                    var conventionTypes     = Assembly.GetExecutingAssembly().GetTypes()
                                              .Where(type => typeof(IConvention).IsAssignableFrom(type) &&
                                                     !type.IsInterface &&
                                                     !disabledConventions.Contains(type))
                                              .ToList();

                    conventionTypes.Each(conventionType => autoPersistenceModel.Conventions.Add(conventionType));
                }

                GetAssembliesWithAdditionalConventions().Each(assembly => autoPersistenceModel.Conventions.AddAssembly(assembly));
                GetAdditionalConventions().Each(conventionType => autoPersistenceModel.Conventions.Add(conventionType));
            }
        }
        public Configuration BuildConfiguration()
        {
            var mapper = new ConventionModelMapper();

            CollectMappingContributorsAndApply(mapper);

            AR.RaiseOnMapperCreated(mapper, this);

            var mapping = mapper.CompileMappingForAllExplicitlyAddedEntities();
            mapping.autoimport = Source.AutoImport;
            mapping.defaultlazy = Source.Lazy;

            if (Source.Debug) {
                try {
                    File.WriteAllText(
                        Path.Combine(
                            AppDomain.CurrentDomain.BaseDirectory,
                            Name + "mapping.hbm.xml"

                        ), mapping.AsString()
                    );
                } catch { /* just bail out */ }
            }

            AR.RaiseOnHbmMappingCreated(mapping, this);

            var cfg = new Configuration();

            if (Source.NamingStrategyImplementation != null)
                cfg.SetNamingStrategy((INamingStrategy) Activator.CreateInstance(Source.NamingStrategyImplementation));

            foreach(var key in Properties.AllKeys)
            {
                cfg.Properties[key] = Properties[key];
            }

            CollectAllContributorsAndRegister(cfg);

            cfg.AddMapping(mapping);

            AR.RaiseOnConfigurationCreated(cfg, this);

            return cfg;
        }