コード例 #1
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);
        }
コード例 #2
0
ファイル: SessionHelper.cs プロジェクト: gobixm/learn
 private static HbmMapping GetMappings()
 {
     var mapper = new ModelMapper();
     mapper.AddMappings(typeof(SessionHelper).Assembly.GetExportedTypes());
     HbmMapping mapping = mapper.CompileMappingForAllExplicitlyAddedEntities();
     return mapping;
 }
コード例 #3
0
ファイル: Fixture.cs プロジェクト: owerkop/nhibernate-core
		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));
		}
コード例 #4
0
        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;
        }
コード例 #5
0
        private static void InitNHibernate()
        {
            lock (LockObject)
            {
                if (_sessionFactory == null)
                {
                    // Создание NHibernate-конфигурации приложения на основании описаний из web.config.
                    // После этого вызова, в том числе, из сборки будут извлечены настройки маппинга, 
                    // заданные в xml-файлах.
                    var configure = new Configuration().Configure();

                    // Настройка маппинга, созданного при помощи mapping-by-code
                    var mapper = new ModelMapper();
                    mapper.AddMappings(new List<Type>
                    {
                        // Перечень классов, описывающих маппинг
                        typeof (DocumentTypeMap),
                        typeof (DocumentMap),
                        typeof (DocumentWithVersionMap),
                    });
                    // Добавление маппинга, созданного при помощи mapping-by-code, 
                    // в NHibernate-конфигурацию приложения
                    configure.AddDeserializedMapping(mapper.CompileMappingForAllExplicitlyAddedEntities(), null);
                    //configure.LinqToHqlGeneratorsRegistry<CompareValuesGeneratorsRegistry>();
                    //configure.LinqToHqlGeneratorsRegistry<InGeneratorRegistry>();
                    configure.DataBaseIntegration(x =>
                    {
                        x.LogSqlInConsole = true;
                        x.LogFormattedSql = true;
                    });

                    _sessionFactory = configure.BuildSessionFactory();
                }
            }
        }
コード例 #6
0
        /// <summary>
        /// Creates session factory
        /// </summary>
        /// <param name="configurationReader">configuration reader</param>
        /// <returns></returns>
        private static ISessionFactory CreateSessionFactory(IConfigurationReader configurationReader)
        {
            var configuration = new NHibernate.Cfg.Configuration();
            configuration.SessionFactoryName("Jumblocks Blog");

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

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

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

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

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

            return configuration.BuildSessionFactory();
        }
コード例 #7
0
        public static void AddNHibernateSessionFactory(this IServiceCollection services)
        {
            // By default NHibernate looks for hibernate.cfg.xml
            // otherwise for Web it will fallback to web.config
            // we got one under wwwroot/web.config
            Configuration config = new Configuration();
            config.Configure();

            // Auto load entity mapping class
            ModelMapper mapper = new ModelMapper();
            mapper.AddMappings(Assembly.GetAssembly(typeof(Employee)).GetExportedTypes());

            HbmMapping mapping = mapper.CompileMappingForAllExplicitlyAddedEntities();
            config.AddDeserializedMapping(mapping, "NHibernate.Mapping");

            SchemaMetadataUpdater.QuoteTableAndColumns(config);

            // Drop & Recreate database schema
            new SchemaExport(config).Drop(false, true);
            new SchemaExport(config).Create(false, true);

            // Register services
            services.AddSingleton<ISessionFactory>(provider => config.BuildSessionFactory());
            services.AddTransient<ISession>(provider => services.BuildServiceProvider().GetService<ISessionFactory>().OpenSession());
        }
コード例 #8
0
		public void ComponentMappingJustOnceDemo()
		{
			var mapper = new ModelMapper();
			mapper.Component<Name>(comp =>
			{
				comp.Property(name => name.First);
				comp.Property(name => name.Last);
			});
			mapper.Component<Address>(comp =>
			{
				comp.Property(address => address.CivicNumber);
				comp.Property(address => address.Street);
			});
			mapper.Class<Person1>(cm =>
			{
				cm.Id(person => person.Id, map => map.Generator(Generators.HighLow));
				cm.Property(person => person.Test);
				cm.Component(person => person.Name, comp => { });
				cm.Component(person => person.Address, comp => { });
			});

			var hbmMapping = mapper.CompileMappingForAllExplicitlyAddedEntities();

			var hbmClass = hbmMapping.RootClasses[0];

			var hbmComponents = hbmClass.Properties.OfType<HbmComponent>();
			hbmComponents.Should().Have.Count.EqualTo(2);
			hbmComponents.Select(x => x.Name).Should().Have.SameValuesAs("Name","Address");
		} 
コード例 #9
0
		public void MapClassWithIdAndProperty()
		{
			var mapper = new ModelMapper();
			mapper.Class<MyClass>(ca =>
			{
				ca.Id("id", map =>
				{
					map.Column("MyClassId");
					map.Generator(Generators.HighLow, gmap => gmap.Params(new { max_low = 100 }));
				});
				ca.Version("version", map => { });
				ca.Property("something", map => map.Length(150));
			});
			var hbmMapping = mapper.CompileMappingFor(new[] { typeof(MyClass) });
			var hbmClass = hbmMapping.RootClasses[0];
			hbmClass.Should().Not.Be.Null();
			var hbmId = hbmClass.Id;
			hbmId.Should().Not.Be.Null();
			hbmId.name.Should().Be("id");
			hbmId.access.Should().Be("field");
			var hbmGenerator = hbmId.generator;
			hbmGenerator.Should().Not.Be.Null();
			[email protected]().Be("hilo");
			hbmGenerator.param[0].name.Should().Be("max_low");
			hbmGenerator.param[0].GetText().Should().Be("100");
			var hbmVersion = hbmClass.Version;
			hbmVersion.name.Should().Be("version");
			var hbmProperty = hbmClass.Properties.OfType<HbmProperty>().Single();
			hbmProperty.name.Should().Be("something");
			hbmProperty.access.Should().Be("field");
			hbmProperty.length.Should().Be("150");
		}
コード例 #10
0
 static Configuration AddLoquaciousMappings(Configuration nhConfiguration)
 {
     ModelMapper mapper = new ModelMapper();
     mapper.AddMappings(typeof(OrderSagaDataLoquacious).Assembly.GetTypes());
     nhConfiguration.AddMapping(mapper.CompileMappingForAllExplicitlyAddedEntities());
     return nhConfiguration;
 }
コード例 #11
0
        void ApplyMappings(Configuration config)
        {
            var mapper = new ModelMapper();
            mapper.AddMapping<OutboxEntityMap>();

            config.AddMapping(mapper.CompileMappingForAllExplicitlyAddedEntities());
        }
コード例 #12
0
        private static ModelMapper GetMapper()
        {
            var mapper = new ModelMapper();
            mapper.AddMappings(Assembly.GetExecutingAssembly().GetExportedTypes());

            return mapper;
        }
コード例 #13
0
ファイル: Fixture.cs プロジェクト: marchlud/nhibernate-core
		protected override HbmMapping GetMappings()
		{
			var mapper = new ModelMapper();
			mapper.Class<Order>(rc =>
				{
					rc.Table("Orders");
					rc.Id(x => x.Id, m => m.Generator(Generators.GuidComb));
					rc.Property(x => x.Name);
					rc.Set(x => x.OrderLines, m =>
						{
							m.Inverse(true);
							m.Key(k =>
								{
									k.Column("OrderId");
									k.NotNullable(true);
								});
							m.Cascade(Mapping.ByCode.Cascade.All.Include(Mapping.ByCode.Cascade.DeleteOrphans));
							m.Access(Accessor.NoSetter);
						}, m => m.OneToMany());
				});
			mapper.Class<OrderLine>(rc =>
				{
					rc.Table("OrderLines");
					rc.Id(x => x.Id, m => m.Generator(Generators.GuidComb));
					rc.Property(x => x.Name);
					rc.ManyToOne(x => x.Order, m => m.Column("OrderId"));
				});

			return mapper.CompileMappingForAllExplicitlyAddedEntities();
		}
コード例 #14
0
ファイル: Mapper.cs プロジェクト: horsdal/Restbucks-on-Nancy
        private static void Customize(ModelMapper mapper)
        {
            mapper.Class<EntityBase>(map =>
                               {
                                 map.Id(e => e.Id, id => id.Generator(Generators.HighLow));
                                 map.Version(e => e.Version, d => { });
                               });
              mapper.Class<Product>(map => map.Set(p => p.Customizations,
                                           set => set.Cascade(Cascade.All),
                                           rel => rel.ManyToMany()));

              mapper.Class<Customization>(map => map.Set(p => p.PossibleValues,
                                                 set => set.Cascade(Cascade.All),
                                                 rel => rel.Element()));

              mapper.Class<Order>(map =>
                          {
                            map.Set(p => p.Items, set =>
                                                  {
                                                    set.Cascade(Cascade.All);
                                                    set.Inverse(true);
                                                  });
                            map.ManyToOne(o => o.Payment, o => o.Cascade(Cascade.All));
                          });
        }
コード例 #15
0
        protected override void PostProcessConfiguration(global::NHibernate.Cfg.Configuration config)
        {
            base.PostProcessConfiguration(config);

            if (FluentNhibernateMappingAssemblies != null)
            {
                // add any class mappings in the listed assemblies:
                var mapper = new ModelMapper();

                foreach (var asm in FluentNhibernateMappingAssemblies.Select(Assembly.Load))
                {
                    mapper.AddMappings(asm.GetTypes());
                }

                foreach (var mapping in mapper.CompileMappingForEachExplicitlyAddedEntity())
                {
                    config.AddMapping(mapping);
                }

                foreach (string assemblyName in FluentNhibernateMappingAssemblies)
                {
                    config.AddMappingsFromAssembly(Assembly.Load(assemblyName));
                }
            }
        }
コード例 #16
0
		protected override HbmMapping GetMappings()
		{
			var mapper = new ModelMapper();
			mapper.Class<Document>(rc =>
			{
				rc.Id(x => x.Id, idMapper => idMapper.Generator(Generators.Identity));
				rc.ManyToOne(x => x.Blob, m =>
					{
						m.Cascade(Mapping.ByCode.Cascade.All);
					});
				rc.Property(x => x.Name);
			});
			
			mapper.Class<Blob>(map =>
				{
					map.Id(x => x.Id, idMapper => idMapper.Generator(Generators.Identity));
					map.Property(x => x.Bytes, y =>
						{
							y.Column(x =>
							{
								x.SqlType("varbinary(max)");
								x.Length(int.MaxValue);
							});
							y.Lazy(true);
						});
				});

			return mapper.CompileMappingForAllExplicitlyAddedEntities();
		}
        /// <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;
        }
コード例 #18
0
		protected override HbmMapping GetMappings()
		{
			var mapper = new ModelMapper();

			mapper.Class<Employee>(mc =>
			{
				mc.Id(x => x.Id, map =>
				{
					map.Generator(Generators.Identity);
					map.Column("Id");
				});
				mc.ManyToOne<EmployeeInfo>(x => x.Info, map =>
				{
					map.Column("Info_id");
					map.Unique(true);
					map.Cascade(Mapping.ByCode.Cascade.All | Mapping.ByCode.Cascade.DeleteOrphans);

				});
			});

			mapper.Class<EmployeeInfo>(cm =>
			{
				cm.Id(x => x.Id, m =>
				{
					m.Generator(Generators.Identity);
					m.Column("Id");
				});
				cm.OneToOne<Employee>(x => x.EmployeeDetails, map =>
				{
					map.PropertyReference(x => x.Info);
				});
			});

			return mapper.CompileMappingForAllExplicitlyAddedEntities();
		}
コード例 #19
0
		protected override HbmMapping GetMappings()
		{
			var mapper = new ModelMapper();
			mapper.Class<Parent>(rc =>
			{
				rc.Id(x => x.Id, m => m.Generator(Generators.GuidComb));
				rc.Property(x => x.Name);
				rc.List(x => x.Children,
					m =>
					{
						m.Lazy(CollectionLazy.Extra);
						m.Cascade(Mapping.ByCode.Cascade.All | Mapping.ByCode.Cascade.DeleteOrphans);
						m.Inverse(true);
					},
					relation => relation.OneToMany());
			});
			mapper.Class<Child>(rc =>
			{
				rc.Id(x => x.Id, m => m.Generator(Generators.GuidComb));
				rc.Property(x => x.Name);
				rc.ManyToOne(x => x.Parent);
			});

			return mapper.CompileMappingForAllExplicitlyAddedEntities();
		}
コード例 #20
0
		public void TestMapElementElement()
		{
			var mapper = new ModelMapper();

			mapper.Class<ClassWithMapElementElement>(
				c =>
				{
					c.Lazy(false);
					c.Id(id => id.Id, id => id.Generator(Generators.Identity));

					c.Map(
						m => m.Map,
						col =>
						{
							col.Table("element_element");
							col.Key(k => k.Column("id"));
						},
						key => key.Element(e => e.Column("key")),
						element => element.Element(e => e.Column("element")));
				});

			var mappings = mapper.CompileMappingForAllExplicitlyAddedEntities();
			var hbmClass = mappings.RootClasses.FirstOrDefault(c => c.Name == typeof (ClassWithMapElementElement).Name);
			var hbmMap = hbmClass.Properties.OfType<HbmMap>().SingleOrDefault();

			Assert.That(hbmMap, Is.Not.Null);
			Assert.That(hbmMap.Item, Is.TypeOf<HbmMapKey>());
			Assert.That(hbmMap.Item1, Is.TypeOf<HbmElement>());
		}
コード例 #21
0
ファイル: Fixture.cs プロジェクト: owerkop/nhibernate-core
		private HbmMapping GetMappings()
		{
			var mapper = new ModelMapper();
			mapper.Class<User>(rt =>
			                   {
			                   	rt.Id(x => x.Id, map => map.Generator(Generators.Guid));
			                   	rt.Property(x => x.Name);
													rt.Set(x => x.Roles, map =>
																							 {
																								 map.Table("UsersToRoles");
																								 map.Inverse(true);
																								 map.Key(km => km.Column("UserId"));
																							 }, rel => rel.ManyToMany(mm =>
																							                          {
																																					mm.Column("RoleId");
																							                          	mm.ForeignKey("FK_RoleInUser");
																							                          }));
			                   });
			mapper.Class<Role>(rt =>
			                   {
			                   	rt.Id(x => x.Id, map => map.Generator(Generators.Guid));
			                   	rt.Property(x => x.Name);
			                   	rt.Set(x => x.Users, map =>
			                   	                     {
			                   	                     	map.Table("UsersToRoles");
																								map.Key(km => km.Column("RoleId"));
																							 }, rel => rel.ManyToMany(mm =>
																							                          {
																																					mm.Column("UserId");
																							                          	mm.ForeignKey("FK_UserInRole");
																							                          }));
			                   });
			var mappings = mapper.CompileMappingForAllExplicitlyAddedEntities();
			return mappings;
		}
コード例 #22
0
        ModelMapper CreateModelMapper()
        {
            var mapper = new ModelMapper();

            mapper.AfterMapClass += (inspector, type, customizer) =>
                {
                    // make sure that sagas are assigned for the Id, or bad things happen
                    if (typeof(ISaga).IsAssignableFrom(type))
                        customizer.Id(m => m.Generator(Generators.Assigned));
                };

            mapper.AfterMapProperty += (inspector, member, customizer) =>
                {
                    Type memberType = member.LocalMember.GetPropertyOrFieldType();

                    if (memberType.IsGenericType
                        && typeof(Nullable<>).IsAssignableFrom(memberType.GetGenericTypeDefinition()))
                    {
                        customizer.NotNullable(false);
                    }
                    else if (!typeof(string).IsAssignableFrom(memberType))
                    {
                        customizer.NotNullable(true);
                    }
                };

            mapper.AddMappings(_mappedTypes);

            return mapper;
        }
コード例 #23
0
ファイル: NhibernateCfg.cs プロジェクト: chenbojian/cbjany
 public static HbmMapping GetMapping()
 {
     var modelMapper = new ModelMapper();
     modelMapper.AddMappings(Assembly.GetAssembly(typeof(PeopleMap)).GetExportedTypes());
     HbmMapping mapping = modelMapper.CompileMappingForAllExplicitlyAddedEntities();
     return mapping;
 }
コード例 #24
0
        public void Setup()
        {
            var mapper = new ModelMapper();
            mapper.AddMapping<OutboxEntityMap>();

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

            configuration.AddMapping(mapper.CompileMappingForAllExplicitlyAddedEntities());

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

            SessionFactory = configuration.BuildSessionFactory();

            Session = SessionFactory.OpenSession();

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

        }
コード例 #25
0
        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();
        }
コード例 #26
0
ファイル: SessionFactory.cs プロジェクト: Nerielle/Learning
        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();
        }
コード例 #27
0
		private HbmMapping GetMappings()
		{
			var mapper = new ModelMapper();

			mapper.BeforeMapClass += (mi, t, map) => map.Id(x => x.Generator(Generators.GuidComb));

			mapper.Class<Parent>(rc =>
			{
				rc.Id(p => p.Id);
				rc.Property(p => p.ParentCode, m => m.Unique(true));
				rc.Property(p => p.Name);
				rc.Bag(p => p.Children, m =>
				{
					m.Key(km => { km.Column(cm => cm.Name("ParentParentCode")); km.PropertyRef(pg => pg.ParentCode); });
					m.Inverse(true);
					m.Cascade(Mapping.ByCode.Cascade.Persist);
				}, rel => rel.OneToMany());
			});

			mapper.Class<Child>(rc =>
			{
				rc.Id(p => p.Id);
				rc.Property(p => p.Name);
				rc.ManyToOne<Parent>(p => p.Parent, m => { m.Column("ParentParentCode"); m.PropertyRef("ParentCode"); });
			});

			return mapper.CompileMappingForAllExplicitlyAddedEntities();
		}
コード例 #28
0
		public void ShouldProperlyMapComponentWhenMappingOnlyPartOfItInSomePlaces()
		{
			var mapper = new ModelMapper();
			mapper.Class<ClassWithComponents>(cm =>
			{
				cm.Component(x => x.Component1, c =>
				{
					c.Property(x => x.PropertyOne, p => p.Column("OnePropertyOne"));
				});

				cm.Component(x => x.Component2, c =>
				{
					c.Property(x => x.PropertyOne, p => p.Column("TwoPropertyOne"));
					c.Property(x => x.PropertyTwo, p => p.Column("TwoPropertyTwo"));
				});
			});

			//Compile, and get the component property in which we mapped only one inner property
			var mappings = mapper.CompileMappingForAllExplicitlyAddedEntities();

			var component1PropertyMapping = (HbmComponent)mappings.RootClasses[0].Properties.Single(x => x.Name == "Component1");

			//There should be only one inner property in the mapping of this component
			// Note: take a look at how CURRENTLY the test fails with 1 expected vs 2, instead of vs 3. 
			//       This means that the "PropertyThree" property of the component that was never mapped, is not taken into account (which is fine).
			Assert.That(component1PropertyMapping.Items.Length, Is.EqualTo(1));
		}
 private static void AddFromConfig(ModelMapper modelMapper, IList<Assembly> assemblies)
 {
    for (int i = 0; i < assemblies.Count; ++i)
    {
       modelMapper.AddMappings(assemblies[i].GetTypes());
    }
 }
コード例 #30
0
ファイル: Fixture.cs プロジェクト: Ruhollah/nhibernate-core
		protected override HbmMapping GetMappings()
		{
			// The impl/mapping of the bidirectional one-to-many sucks but was provided as is
			var mapper = new ModelMapper();
			mapper.BeforeMapClass += (i, t, cm) => cm.Id(map =>
																									 {
																										 map.Column((t.Name + "Id").ToUpperInvariant());
																										 map.Generator(Generators.HighLow, g => g.Params(new { max_lo = "1000" }));
																									 });
			mapper.Class<Customer>(ca =>
			{
				ca.Lazy(false);
				ca.Id(x => x.Id, m => { });
				ca.NaturalId(x => x.Property(c => c.Name, p => p.NotNullable(true)));
				ca.Property(x => x.Address, p => p.Lazy(true));
				ca.Set(c => c.Orders, c =>
				{
					c.Key(x => x.Column("CUSTOMERID"));
					c.Inverse(true);
					c.Cascade(Mapping.ByCode.Cascade.All);
				}, c => c.OneToMany());
			});
			mapper.Class<Order>(cm =>
			                    {
														cm.Id(x => x.Id, m => { });
														cm.Property(x => x.Date);
														cm.ManyToOne(x => x.Customer, map => map.Column("CUSTOMERID"));
			                    });
			return mapper.CompileMappingForAllExplicitlyAddedEntities();
		}
コード例 #31
0
 public List <CourseModel> DeleteCourse([FromBody] int id)
 {
     return(ModelMapper.MapToCourseModels(SQLService.DeleteCourse(id)));
 }
コード例 #32
0
    static async Task AsyncMain()
    {
        Console.Title = "Samples.MultiTenant.Receiver";

        var sharedDatabaseConfiguration = CreateBasicNHibernateConfig();

        var tenantDatabasesConfiguration = CreateBasicNHibernateConfig();
        var mapper = new ModelMapper();

        mapper.AddMapping <OrderMap>();
        tenantDatabasesConfiguration.AddMapping(mapper.CompileMappingForAllExplicitlyAddedEntities());

        var endpointConfiguration = new EndpointConfiguration("Samples.MultiTenant.Receiver");

        endpointConfiguration.LimitMessageProcessingConcurrencyTo(1);
        endpointConfiguration.SendFailedMessagesTo("error");
        var transport = endpointConfiguration.UseTransport <MsmqTransport>();
        var routing   = transport.Routing();

        routing.RegisterPublisher(
            eventType: typeof(OrderSubmitted),
            publisherEndpoint: "Samples.MultiTenant.Sender");

        #region ReceiverConfiguration

        var persistence = endpointConfiguration.UsePersistence <NHibernatePersistence>();
        persistence.UseConfiguration(tenantDatabasesConfiguration);
        persistence.UseSubscriptionStorageConfiguration(sharedDatabaseConfiguration);
        persistence.UseTimeoutStorageConfiguration(sharedDatabaseConfiguration);
        persistence.DisableSchemaUpdate();

        endpointConfiguration.EnableOutbox();

        var settings = endpointConfiguration.GetSettings();
        settings.Set("NHibernate.Timeouts.AutoUpdateSchema", true);
        settings.Set("NHibernate.Subscriptions.AutoUpdateSchema", true);

        #endregion

        ReplaceOpenSqlConnection(endpointConfiguration);

        RegisterPropagateTenantIdBehavior(endpointConfiguration);


        var startableEndpoint = await Endpoint.Create(endpointConfiguration)
                                .ConfigureAwait(false);

        #region CreateSchema

        CreateSchema(tenantDatabasesConfiguration, "A");
        CreateSchema(tenantDatabasesConfiguration, "B");

        #endregion

        var endpointInstance = await startableEndpoint.Start()
                               .ConfigureAwait(false);

        Console.WriteLine("Press any key to exit");
        Console.ReadKey();
        if (endpointInstance != null)
        {
            await endpointInstance.Stop()
            .ConfigureAwait(false);
        }
    }
コード例 #33
0
        public ApplicationObject PreviousTasks(long id, string userId)
        {
            try
            {
                using (var db = new ImportPermitEntities())
                {
                    //get the id of the userprofile table
                    var registeredGuys = db.AspNetUsers.Find(userId);
                    var profileId      = registeredGuys.UserProfile.Id;

                    //get the employee id on employee desk table
                    var employeeDesk = db.EmployeeDesks.Where(e => e.EmployeeId == profileId).ToList();
                    if (employeeDesk.Any())
                    {
                        var employeeId = employeeDesk[0].Id;

                        var myApplication =
                            db.Applications.Find(id);


                        if (myApplication == null)
                        {
                            return(new ApplicationObject());
                        }

                        var app          = myApplication;
                        var importObject = ModelMapper.Map <Application, ApplicationObject>(app);
                        if (importObject == null || importObject.Id < 1)
                        {
                            return(new ApplicationObject());
                        }

                        importObject.ProcessingHistoryObjects = new List <ProcessingHistoryObject>();



                        var history = (from h in db.ProcessingHistories where h.EmployeeId.Equals(employeeId)


                                       select new ProcessingHistoryObject()
                        {
                            AssignedTime = h.AssignedTime,

                            DueTime = h.DueTime,
                            FinishedTime = h.FinishedTime,
                            Remarks = h.Remarks,
                            OutComeCode = h.OutComeCode
                        }).ToList();
                        if (history.Any())
                        {
                            foreach (var item in history)
                            {
                                item.AssignedTimeStr           = item.AssignedTime.ToString();
                                item.DueTimeStr                = item.DueTime.ToString();
                                item.ActualDeliveryDateTimeStr = item.FinishedTime.ToString();

                                importObject.ProcessingHistoryObjects.Add(item);
                            }
                            return(importObject);
                        }

                        return(new ApplicationObject());
                    }

                    return(new ApplicationObject());
                }
            }
            catch (Exception ex)
            {
                ErrorLogger.LoggError(ex.StackTrace, ex.Source, ex.Message);
                return(new ApplicationObject());
            }
        }
コード例 #34
0
        public RecertificationObject GetRecertification(long historyId)
        {
            try
            {
                using (var db = new ImportPermitEntities())
                {
                    var history = db.RecertificationHistories.Find(historyId);

                    var docs = new List <DocumentObject>();

                    var recertifications =
                        db.Recertifications.Where(m => m.Id == history.RecertificationId)

                        .ToList();

                    if (!recertifications.Any())
                    {
                        return(new RecertificationObject());
                    }

                    var app          = recertifications[0];
                    var importObject = ModelMapper.Map <Recertification, RecertificationObject>(app);
                    if (importObject == null || importObject.Id < 1)
                    {
                        return(new RecertificationObject());
                    }

                    //get the importer Id
                    var importerId = app.Notification.ImporterId;

                    //get the required docs
                    var requiredDocs =
                        db.ImportRequirements.Where(r => r.ImportStageId == (int)AppStage.Recertification).ToList();
                    if (requiredDocs.Any())
                    {
                        foreach (var item in requiredDocs)
                        {
                            var doc       = new DocumentObject();
                            var docEntity =
                                db.Documents.Where(
                                    d => d.DocumentTypeId == item.DocumentTypeId && d.ImporterId == importerId)
                                .ToList();
                            if (docEntity.Any())
                            {
                                doc.DocumentTypeName = docEntity[0].DocumentType.Name;
                                doc.DateUploadedStr  = docEntity[0].DateUploaded.ToString("dd/MM/yyyy");
                                doc.DocumentPath     = docEntity[0].DocumentPath;

                                docs.Add(doc);
                            }
                        }

                        importObject.DocumentObjects = docs;
                    }


                    importObject.ReferenceCode = app.Notification.Invoice.ReferenceCode;

                    return(importObject);
                }
            }
            catch (Exception ex)
            {
                ErrorLogger.LoggError(ex.StackTrace, ex.Source, ex.Message);
                return(new RecertificationObject());
            }
        }
コード例 #35
0
        public NotificationObject GetNotification(long historyId)
        {
            try
            {
                using (var db = new ImportPermitEntities())
                {
                    var history = db.NotificationHistories.Find(historyId);


                    var myApplications =
                        db.Notifications.Where(m => m.Id == history.NotificationId)
                        .Include("Importer")
                        .Include("Permit")
                        .Include("Product")
                        .ToList();
                    if (!myApplications.Any())
                    {
                        return(new NotificationObject());
                    }

                    var app          = myApplications[0];
                    var importObject = ModelMapper.Map <Notification, NotificationObject>(app);
                    if (importObject == null || importObject.Id < 1)
                    {
                        return(new NotificationObject());
                    }

                    importObject.DateCreatedStr         = app.DateCreated.ToString("dd/MM/yyyy");
                    importObject.StatusStr              = Enum.GetName(typeof(NotificationStatusEnum), app.Status);
                    importObject.ArrivalDateStr         = importObject.ArrivalDate.ToString("dd/MM/yyyy");
                    importObject.QuantityOnVesselStr    = importObject.QuantityOnVessel.ToString();
                    importObject.AmountDueStr           = importObject.AmountDue.ToString();
                    importObject.DischargeDateStr       = importObject.DischargeDate.ToString("dd/MM/yyyy");
                    importObject.QuantityToDischargeStr = importObject.QuantityToDischarge.ToString();

                    importObject.DepotName = app.Depot.Name;

                    importObject.ReferenceCode = app.Invoice.ReferenceCode;

                    importObject.NotificationDocumentObjects = new List <NotificationDocumentObject>();
                    importObject.ProductObject = new ProductObject();
                    importObject.NotificationInspectionObjects = new List <NotificationInspectionObject>();



                    var product = (from p in db.Products
                                   where p.ProductId == importObject.ProductId


                                   select new ProductObject()
                    {
                        ProductId = p.ProductId,
                        Code = p.Code,
                        Name = p.Name
                    }).ToList();
                    if (product.Any())
                    {
                        importObject.ProductObject = product[0];
                    }



                    var inspection = (from i in db.NotificationInspections
                                      where i.NotificationId == importObject.Id


                                      select new NotificationInspectionObject()
                    {
                        InspectionDate = i.InspectionDate,
                        InspectorComment = i.InspectorComment
                    }


                                      ).ToList();
                    if (inspection.Any())
                    {
                        foreach (var item in inspection)
                        {
                            if (item.InspectionDate != null)
                            {
                                item.InspectionDateStr = item.InspectionDate.Value.ToString("dd/MM/yyyy");
                            }

                            importObject.NotificationInspectionObjects.Add(item);
                            importObject.IsReportSubmitted = true;
                        }
                    }



                    var doc = (from ad in app.NotificationDocuments
                               join d in db.Documents on ad.DocumentId equals d.DocumentId

                               select new NotificationDocumentObject()
                    {
                        DocumentTypeName = d.DocumentType.Name,
                        DateUploaded = d.DateUploaded,
                        DocumentPathStr = d.DocumentPath
                    }).ToList();
                    if (doc.Any())
                    {
                        foreach (var item in doc)
                        {
                            item.DateUploadedStr = item.DateUploaded.ToString("dd/MM/yyyy");
                            item.DocumentPathStr = item.DocumentPathStr.Replace("~", "").Replace("/", "\\");
                            importObject.NotificationDocumentObjects.Add(item);
                        }
                    }



                    return(importObject);
                }
            }
            catch (Exception ex)
            {
                ErrorLogger.LoggError(ex.StackTrace, ex.Source, ex.Message);
                return(new NotificationObject());
            }
        }
コード例 #36
0
        public ApplicationObject GetApplication(long historyId)
        {
            try
            {
                using (var db = new ImportPermitEntities())
                {
                    var track = db.ProcessingHistories.Find(historyId);

                    var myApplications =
                        db.Applications.Where(m => m.Id == track.ApplicationId)
                        .Include("Importer")
                        .Include("ApplicationItems")
                        .Include("ApplicationDocuments")
                        .Include("NotificationBankers")
                        .ToList();
                    if (!myApplications.Any())
                    {
                        return(new ApplicationObject());
                    }

                    var app          = myApplications[0];
                    var importObject = ModelMapper.Map <Application, ApplicationObject>(app);
                    if (importObject == null || importObject.Id < 1)
                    {
                        return(new ApplicationObject());
                    }

                    importObject.ReferenceCode       = app.Invoice.ReferenceCode;
                    importObject.DateAppliedStr      = app.DateApplied.ToString("dd/MM/yyyy");
                    importObject.StatusStr           = Enum.GetName(typeof(AppStatus), app.ApplicationStatusCode);
                    importObject.LastModifiedStr     = importObject.LastModified.ToString("dd/MM/yyyy");
                    importObject.ImporterStr         = app.Importer.Name;
                    importObject.ApplicationTypeName = app.ApplicationType.Name;


                    importObject.ApplicationItemObjects     = new List <ApplicationItemObject>();
                    importObject.ApplicationDocumentObjects = new List <ApplicationDocumentObject>();
                    importObject.StandardRequirementObjects = new List <StandardRequirementObject>();

                    var permApp = db.PermitApplications.Where(p => p.ApplicationId == app.Id).ToList();

                    if (permApp.Any())
                    {
                        var permId = permApp[0].PermitId;
                        var perm   = db.Permits.Where(m => m.Id == permId).ToList();
                        if (perm.Any())
                        {
                            importObject.PermitStr = perm[0].PermitValue;
                        }
                        else if (!perm.Any())
                        {
                            importObject.PermitStr = "Nil";
                        }
                    }



                    app.ApplicationItems.ToList().ForEach(u =>
                    {
                        var im = ModelMapper.Map <ApplicationItem, ApplicationItemObject>(u);
                        if (im != null && im.ApplicationId > 0)
                        {
                            im.ProductObject = (from pr in db.Products.Where(x => x.ProductId == im.ProductId)
                                                select new ProductObject
                            {
                                ProductId = pr.ProductId,
                                Code = pr.Code,
                                Name = pr.Name,
                                Availability = pr.Availability
                            }).ToList()[0];

                            var appCountries = db.ApplicationCountries.Where(a => a.ApplicationItemId == im.Id).Include("Country").ToList();
                            var depotList    = db.ThroughPuts.Where(a => a.ApplicationItemId == im.Id).Include("Depot").ToList();
                            if (appCountries.Any() && depotList.Any())
                            {
                                im.CountryOfOriginName = "";
                                appCountries.ForEach(c =>
                                {
                                    if (string.IsNullOrEmpty(im.CountryOfOriginName))
                                    {
                                        im.CountryOfOriginName = c.Country.Name;
                                    }
                                    else
                                    {
                                        im.CountryOfOriginName += ", " + c.Country.Name;
                                    }
                                });

                                im.DischargeDepotName = "";
                                depotList.ForEach(d =>
                                {
                                    if (string.IsNullOrEmpty(im.DischargeDepotName))
                                    {
                                        im.DischargeDepotName = d.Depot.Name;
                                    }
                                    else
                                    {
                                        im.DischargeDepotName += ", " + d.Depot.Name;
                                    }
                                });
                            }
                            importObject.ApplicationItemObjects.Add(im);
                        }
                    });


                    var doc = (from ad in app.ApplicationDocuments
                               join d in db.Documents on ad.DocumentId equals d.DocumentId

                               select new ApplicationDocumentObject
                    {
                        DocumentTypeName = d.DocumentType.Name,
                        DateUploaded = d.DateUploaded,
                        DocumentPathStr = d.DocumentPath
                    }).ToList();
                    if (doc.Any())
                    {
                        foreach (var item in doc)
                        {
                            item.DateUploadedStr = item.DateUploaded.ToString("dd/MM/yyyy");
                            item.DocumentPathStr = item.DocumentPathStr.Replace("~", "").Replace("/", "\\");
                            importObject.ApplicationDocumentObjects.Add(item);
                        }
                    }

                    importObject.StandardRequirementObjects = new List <StandardRequirementObject>();

                    var doc2 = db.StandardRequirements.Where(s => s.ImporterId == importObject.ImporterId).Include("StandardRequirementType").ToList();

                    if (doc2.Any())
                    {
                        foreach (var standardObj in doc2.Select(item => new StandardRequirementObject
                        {
                            DocumentPath = item.DocumentPath.Replace("~", "").Replace("/", "\\"),
                            DateStr = item.LastUpdated.ToString("dd/MM/yyyy"),
                            StandardRequirementTypeName = item.StandardRequirementType.Name
                        }))
                        {
                            importObject.StandardRequirementObjects.Add(standardObj);
                        }
                    }



                    return(importObject);
                }
            }
            catch (Exception ex)
            {
                ErrorLogger.LoggError(ex.StackTrace, ex.Source, ex.Message);
                return(new ApplicationObject());
            }
        }
コード例 #37
0
 public StudentTeamService(ITeamService teamService, QueryExecutor queryExecutor, ModelMapper modelMapper, SqlCommands sqlCommands, IMapper autoMapper, IHttpContextAccessor httpContextAccessor, HttpClientService httpClientService)
 {
     this._queryExecutor       = queryExecutor;
     this._modelMapper         = modelMapper;
     this._sqlCommands         = sqlCommands;
     this._autoMapper          = autoMapper;
     this._httpContextAccessor = httpContextAccessor;
     this._httpClientService   = httpClientService;
     this._teamService         = teamService;
 }
コード例 #38
0
        protected override HbmMapping GetMappings()
        {
            var mapper = new ModelMapper();

            mapper.Class <EntityEager>(
                rc =>
            {
                rc.Lazy(false);
                rc.Id(x => x.Id, m => m.Generator(Generators.GuidComb));
                rc.Version(ep => ep.Version, vm => { });
                rc.Property(x => x.Name);
                MapList(rc, p => p.ChildrenList, CollectionFetchMode.Join);
            });

            MapSimpleChild <EntityEagerChild>(
                mapper,
                rc => { rc.Lazy(false); });

            mapper.Class <EntityComplex>(
                rc =>
            {
                rc.Id(x => x.Id, m => m.Generator(Generators.GuidComb));

                rc.Version(ep => ep.Version, vm => { });

                rc.Property(x => x.Name);

                rc.Property(ep => ep.LazyProp, m =>
                {
                    m.Lazy(true);
                    m.FetchGroup("LazyGroup");
                });
                rc.Property(ep => ep.LazyProp2, m =>
                {
                    m.Lazy(true);
                    m.FetchGroup("LazyGroup2");
                });

                rc.ManyToOne(
                    ep => ep.Child1,
                    m =>
                {
                    m.Column("Child1Id");
                    m.ForeignKey("none");
                });
                rc.ManyToOne(
                    ep => ep.Child2,
                    m =>
                {
                    m.Column("Child2Id");
                    m.ForeignKey("none");
                });
                rc.ManyToOne(ep => ep.SameTypeChild, m =>
                {
                    m.Column("SameTypeChildId");
                    m.ForeignKey("none");
                });
                MapList(rc, ep => ep.ChildrenList, mapper: m => m.OrderBy("OrderIdx desc"));
                MapList(rc, ep => ep.ChildrenListEmpty);
            });

            MapSimpleChild(
                mapper,
                default(EntitySimpleChild),
                c => c.Children,
                rc =>
            {
                rc.Property(sc => sc.LazyProp, mp => mp.Lazy(true));
                rc.Property(sc => sc.OrderIdx);
            });
            MapSimpleChild(mapper, default(Level2Child), c => c.Children);
            MapSimpleChild <Level3Child>(mapper);

            return(mapper.CompileMappingForAllExplicitlyAddedEntities());
        }
コード例 #39
0
 public UserInfoController(PTAuthenticationDbContext _dbContext, UserManager <PTUserEntity> _userManager)
 {
     dbContext   = _dbContext;
     userManager = _userManager;
     modelMapper = new ModelMapper(dbContext);
 }
コード例 #40
0
 private static void MapSimpleChild <TChild>(ModelMapper mapper, Action <IClassMapper <TChild> > action = null) where TChild : BaseChild
 {
     MapSimpleChild <TChild, object>(mapper, default(TChild), null, action);
 }
コード例 #41
0
ファイル: MqttPlugin.cs プロジェクト: mazaxaka/thinking-home
 public override void InitDbModel(ModelMapper mapper)
 {
     mapper.Class <ReceivedData>(cfg => cfg.Table("Mqtt_ReceivedData"));
 }
コード例 #42
0
    static async Task AsyncMain()
    {
        Console.Title = "Samples.MultiTenant.Receiver";

        var sharedDatabaseConfiguration = CreateBasicNHibernateConfig();

        var tenantDatabasesConfiguration = CreateBasicNHibernateConfig();
        var mapper = new ModelMapper();

        mapper.AddMapping <OrderMap>();
        tenantDatabasesConfiguration.AddMapping(mapper.CompileMappingForAllExplicitlyAddedEntities());

        var endpointConfiguration = new EndpointConfiguration("Samples.MultiTenant.Receiver");

        endpointConfiguration.UseSerialization <JsonSerializer>();
        endpointConfiguration.LimitMessageProcessingConcurrencyTo(1);
        endpointConfiguration.SendFailedMessagesTo("error");

        #region ReceiverConfiguration

        var persistence = endpointConfiguration.UsePersistence <NHibernatePersistence>();
        persistence.UseConfiguration(tenantDatabasesConfiguration);
        persistence.UseSubscriptionStorageConfiguration(sharedDatabaseConfiguration);
        persistence.UseTimeoutStorageConfiguration(sharedDatabaseConfiguration);
        persistence.DisableSchemaUpdate();

        endpointConfiguration.EnableOutbox();

        var settingsHolder = endpointConfiguration.GetSettings();
        settingsHolder.Set("NHibernate.Timeouts.AutoUpdateSchema", true);
        settingsHolder.Set("NHibernate.Subscriptions.AutoUpdateSchema", true);

        #endregion

        #region ReplaceOpenSqlConnection

        endpointConfiguration.Pipeline.Register <ExtractTenantConnectionStringBehavior.Registration>();

        #endregion

        #region RegisterPropagateTenantIdBehavior

        endpointConfiguration.Pipeline.Register <PropagateOutgoingTenantIdBehavior.Registration>();
        endpointConfiguration.Pipeline.Register <PropagateIncomingTenantIdBehavior.Registration>();

        #endregion


        var startableEndpoint = await Endpoint.Create(endpointConfiguration)
                                .ConfigureAwait(false);

        IEndpointInstance endpointInstance = null;

        #region CreateSchema

        CreateSchema(tenantDatabasesConfiguration, "A");
        CreateSchema(tenantDatabasesConfiguration, "B");

        #endregion

        try
        {
            endpointInstance = await startableEndpoint.Start()
                               .ConfigureAwait(false);

            Console.WriteLine("Press any key to exit");
            Console.ReadKey();
        }
        finally
        {
            if (endpointInstance != null)
            {
                await endpointInstance.Stop()
                .ConfigureAwait(false);
            }
        }
    }
コード例 #43
0
        public void Configure()
        {
            if (Configured)
            {
                return;
            }
            lock (this)
            {
                if (Configured)
                {
                    return;
                }
                OnConfiguring();
                Configuration = new Configuration().DataBaseIntegration(
                    x =>
                {
#if DEBUG
                    x.LogSqlInConsole = true;
                    x.LogFormattedSql = true;
#endif
                });

                //var filePath = ConfigFile;
                //filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, filePath);
                //var cfg = Configuration.Configure(filePath);

                var cfg = Configuration.SetProperties(_parameters);
                Console.WriteLine("NhRepositoryConfiguration Parameters");
                _parameters.ToList().ForEach(x => Console.WriteLine("{0}:{1}", x.Key, x.Value));
                Action <IEnumerable <string> > funcCreateInitialScripts =
                    scriptFileNames =>
                {
                    if (!scriptFileNames.Any())
                    {
                        return;
                    }
                    var scriptBuilder = new StringBuilder();
                    scriptFileNames
                    .ToList().ForEach(
                        scriptFile =>
                    {
                        using (var streamReader = new StreamReader(scriptFile, Encoding.GetEncoding("iso-8859-9")))
                        {
                            scriptBuilder.AppendLine(streamReader.ReadToEnd());
                        }
                    }
                        );
                    cfg.AddAuxiliaryDatabaseObject(new SimpleAuxiliaryDatabaseObject(scriptBuilder.ToString(), null));
                };

                Action <IEnumerable <string> > actCodeMappings =
                    assemblyFileNames =>
                {
                    var modelMapper = new ModelMapper();
                    assemblyFileNames.ToList().ForEach(
                        assebmlyFile => modelMapper.AddMappings(Assembly.Load(assebmlyFile).GetExportedTypes()));

                    var mp = modelMapper.CompileMappingForAllExplicitlyAddedEntities();
                    // For Duplicate mapping
                    mp.autoimport = false;
                    cfg.AddDeserializedMapping(mp, null);
                };

                Action <IEnumerable <string> > actXmlMappings = assemblyFileNames => assemblyFileNames.ToList().ForEach(
                    assebmlyFile => cfg.AddAssembly(assebmlyFile));

                if (_databaseConfiguration.AllowInstall)
                {
                    funcCreateInitialScripts(_databaseConfiguration.GetScriptFiles());
                }

                var codeMappings = _databaseConfiguration.GetMappings(MappingType.Code);

                if (codeMappings.Any())
                {
                    actCodeMappings(codeMappings);
                }

                var xmlMappings = _databaseConfiguration.GetMappings(MappingType.Xml);
                if (xmlMappings.Any())
                {
                    actXmlMappings(xmlMappings);
                }

                SchemaMetadataUpdater.QuoteTableAndColumns(cfg);

                if (_databaseConfiguration.AllowInstall)
                {
                    new SchemaExport(cfg).SetOutputFile(_databaseConfiguration.ScriptFilePath).Create(false, true);
                }
                Configured = true;

                OnConfigured();
            }
        }
コード例 #44
0
 public MaterialService(HttpClientService httpClientService, IHttpContextAccessor httpContextAccessor, ISectionService sectionService, QueryExecutor queryExecutor, ModelMapper modelMapper, IMapper autoMapper, SqlCommands sqlCommands)
 {
     this._queryExecutor       = queryExecutor;
     this._modelMapper         = modelMapper;
     this._autoMapper          = autoMapper;
     this._sqlCommands         = sqlCommands;
     this._httpClientService   = httpClientService;
     this._httpContextAccessor = httpContextAccessor;
     this._sectionService      = sectionService;
 }
コード例 #45
0
ファイル: SetPropertyCommand.cs プロジェクト: you8/vvvv-sdk
 public static void SetByCommand(this IEditableProperty property, object newValue, ModelMapper mapper)
 {
     if (mapper.CanMap <ICommandHistory>())
     {
         property.SetByCommand(newValue, mapper.Map <ICommandHistory>());
     }
 }
コード例 #46
0
        protected override HbmMapping GetMappings()
        {
            var mapper = new ModelMapper();

            mapper.Class <EntityComplex>(
                rc =>
            {
                rc.Id(x => x.Id, m => m.Generator(Generators.GuidComb));

                rc.Version(ep => ep.Version, vm => { });

                rc.Property(x => x.Name);

                rc.Property(ep => ep.LazyProp, m => m.Lazy(true));

                rc.ManyToOne(ep => ep.Child1, m => m.Column("Child1Id"));
                rc.ManyToOne(ep => ep.Child2, m => m.Column("Child2Id"));
                rc.ManyToOne(ep => ep.SameTypeChild, m => m.Column("SameTypeChildId"));

                rc.Bag(
                    ep => ep.ChildrenList,
                    m =>
                {
                    m.Cascade(Mapping.ByCode.Cascade.All);
                    m.Inverse(true);
                },
                    a => a.OneToMany());
            });

            mapper.Class <EntitySimpleChild>(
                rc =>
            {
                rc.Id(x => x.Id, m => m.Generator(Generators.GuidComb));
                rc.Property(x => x.Name);
            });

            mapper.Class <EntityWithCompositeId>(
                rc =>
            {
                rc.ComponentAsId(
                    e => e.Key,
                    ekm =>
                {
                    ekm.Property(ek => ek.Id1);
                    ekm.Property(ek => ek.Id2);
                });

                rc.Property(e => e.Name);
            });

            mapper.Class <EntityWithCompositeId>(
                rc =>
            {
                rc.ComponentAsId(
                    e => e.Key,
                    ekm =>
                {
                    ekm.Property(ek => ek.Id1);
                    ekm.Property(ek => ek.Id2);
                });

                rc.Property(e => e.Name);
            });

            mapper.Class <EntityWithNoAssociation>(
                rc =>
            {
                rc.Id(e => e.Id, m => m.Generator(Generators.GuidComb));

                rc.Property(e => e.Complex1Id);
                rc.Property(e => e.Complex2Id);
                rc.Property(e => e.Simple1Id);
                rc.Property(e => e.Simple2Id);
                rc.Property(e => e.Composite1Key1);
                rc.Property(e => e.Composite1Key2);
                rc.Property(e => e.CustomEntityNameId);
            });

            mapper.Class <EntityCustomEntityName>(
                rc =>
            {
                rc.EntityName(customEntityName);

                rc.Id(e => e.Id, m => m.Generator(Generators.GuidComb));
                rc.Property(e => e.Name);
            });

            return(mapper.CompileMappingForAllExplicitlyAddedEntities());
        }
コード例 #47
0
 public ActionResult Details(Guid id, int page = 1)
 {
     ViewBag.Page = page;
     return(View(ModelMapper.Map <Project, ProjectView>(GetEntity <Project>(id))));
 }
コード例 #48
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();
                    var appconfig = ConfigurationManager.AppSettings;
                    switch (appconfig["Ambiente"])
                    {
                    case "Test":
                        cfg.Configure("D:/Desarrollo/C#/Desarm/WebApi/bin/Conexion/test.cfg.xml");
                        break;

                    case "TestDatacenterRemoto":
                        cfg.Configure("D:/Desarrollo/C#/Desarm/WebApi/bin/Conexion/testdatacenter.cfg.xml");
                        break;

                    case "Produccion":
                        cfg.Configure("/inetpub/wwwroot/Desarm/bin/Conexion/produccion.cfg.xml");
                        break;

                    case "TestDatacenter":
                        cfg.Configure("/inetpub/wwwroot/DesarmTest/bin/Conexion/testdatacenter.cfg.xml");
                        break;
                    }

                    var mapper = new ModelMapper();

                    //Especifico uno por unos los mapeos de las entidades
                    mapper.AddMapping <MapMarcas>();
                    mapper.AddMapping <MapModelos>();
                    mapper.AddMapping <MapVehiculosTipo>();
                    mapper.AddMapping <MapArticulos>();
                    mapper.AddMapping <MapTiposCombustible>();
                    mapper.AddMapping <MapLocalidades>();
                    mapper.AddMapping <MapProvincias>();
                    mapper.AddMapping <MapPedidosWeb>();
                    mapper.AddMapping <MapPedidosWeDetalle>();
                    mapper.AddMapping <MapPedidosWebFormasPago>();
                    mapper.AddMapping <MapPersonasWeb>();
                    mapper.AddMapping <MapPersonas>();
                    mapper.AddMapping <MapEmpleados>();
                    mapper.AddMapping <MapCanalesVenta>();
                    mapper.AddMapping <MapFormasPago>();
                    mapper.AddMapping <MapCanalesVentaForPag>();
                    mapper.AddMapping <MapPedidosWebArchivos>();
                    mapper.AddMapping <MapArticulosAsociados>();
                    mapper.AddMapping <MapPedidosWebTarjetasCupones>();
                    mapper.AddMapping <MapTarjetasEmisor>();
                    mapper.AddMapping <MapTarjetasEntidades>();
                    mapper.AddMapping <MapTarjetasPlanes>();
                    mapper.AddMapping <MapTarjetasPlanesEmisor>();
                    mapper.AddMapping <MapPersonasConsulta>();
                    mapper.AddMapping <MapDanios>();
                    mapper.AddMapping <MapDaniosFotos>();
                    mapper.AddMapping <MapDaniosSecuencias>();
                    mapper.AddMapping <MapBloqueos>();

                    var mapping = mapper.CompileMappingForAllExplicitlyAddedEntities();

                    cfg.AddMapping(mapping);

                    _sessionFactory = cfg.BuildSessionFactory();
                }
                return(_sessionFactory);
            }
            catch (Exception e)
            {
                throw e;
            }
        }
コード例 #49
0
 public DefaultContextMenuProvider(ModelMapper mapper, ILogger logger)
 {
     FMapper = mapper;
     FLogger = logger;
 }
コード例 #50
0
 public ActionResult Edit(Guid id)
 {
     return(View(ModelMapper.Map <Project, ProjectView>(GetEntity <Project>(id))));
 }
コード例 #51
0
 public BaseBackendController(DbContext _dbContext)
     : base(_dbContext)
 {
     dbContext   = _dbContext;
     modelMapper = new ModelMapper(dbContext);
 }
コード例 #52
0
 public static void WithMappings(this ModelMapper mapper, Configuration configuration)
 {
     mapper.AddMappings(typeof(CustomerMap).Assembly.GetTypes());
     configuration.AddMapping(mapper.CompileMappingForAllExplicitlyAddedEntities());
 }
コード例 #53
0
        protected override HbmMapping GetMappings()
        {
            var mapper = new ModelMapper();

            return(mapper.CompileMappingForAllExplicitlyAddedEntities());
        }
コード例 #54
0
        public override ISessionFactory GetSessionFactory()
        {
            if (_sessionFactory == null)
            {
                lock (_locker)
                {
                    if (_sessionFactory == null)
                    {
                        var config = new Configuration();

                        config.Mappings(map =>
                        {
                            map.DefaultCatalog = _database;
                            map.DefaultSchema  = "dbo";
                        });

                        config.DataBaseIntegration(db =>
                        {
                            db.LogFormattedSql  = false;
                            db.LogSqlInConsole  = false;
                            db.ConnectionString = _connectionString;
                            db.Timeout          = 10;
                            db.Dialect <MsSql2005Dialect>();
                            db.Driver <SqlClientDriver>();
                            db.IsolationLevel = IsolationLevel.ReadCommitted;
                            db.ConnectionProvider <DriverConnectionProvider>();
                        });

                        config.Cache(cache =>
                        {
                            cache.DefaultExpiration = 600;
                            cache.UseQueryCache     = true;
                            cache.Provider <NCacheProvider>();
                            cache.QueryCacheFactory <NCacheQueryCacheFactory>();
                        });



                        config.Properties.Add("cache.use_sliding_expiration", "true");

                        var mapper = new ModelMapper();
                        mapper.AddMappings(
                            Assembly.GetAssembly(
                                typeof(CustomersMap))
                            .GetExportedTypes());
                        var mapping =
                            mapper.CompileMappingForAllExplicitlyAddedEntities();

                        config.AddMapping(mapping);
                        config.AddAuxiliaryDatabaseObject(
                            new ServiceBrokerSettings());
                        config.AddAuxiliaryDatabaseObject(
                            new CustomerCountryByID_SP());
                        config.AddAuxiliaryDatabaseObject(
                            new CustomerContactNameAndPhoneByID_SP());
                        config.AddAuxiliaryDatabaseObject(
                            new SQLProductPollingDependencyTrigger());
                        config.AddAuxiliaryDatabaseObject(
                            new SQLEmployeePollingDependencyTrigger());

                        var schemaExport = new SchemaExport(config);
                        schemaExport.Create(true, true);

                        _sessionFactory = config.BuildSessionFactory();
                    }
                }
            }

            return(_sessionFactory);
        }
コード例 #55
0
 /// <summary>
 /// Creates a new query hack
 /// </summary>
 public ConceptQueryHack(ModelMapper mapper)
 {
     this.m_mapper = mapper;
 }
コード例 #56
0
    static void Main()
    {
        Console.Title = "Samples.MultiTenant.Receiver";

        Configuration hibernateConfig = CreateBasicNHibernateConfig();
        ModelMapper   mapper          = new ModelMapper();

        mapper.AddMapping <OrderMap>();
        hibernateConfig.AddMapping(mapper.CompileMappingForAllExplicitlyAddedEntities());

        BusConfiguration busConfiguration = new BusConfiguration();

        busConfiguration.UseSerialization <JsonSerializer>();
        busConfiguration.EndpointName("Samples.MultiTenant.Receiver");

        #region ReceiverConfiguration

        busConfiguration.UsePersistence <NHibernatePersistence>()
        .RegisterManagedSessionInTheContainer()
        .UseConfiguration(hibernateConfig)
        .UseSubscriptionStorageConfiguration(CreateBasicNHibernateConfig())
        .UseTimeoutStorageConfiguration(CreateBasicNHibernateConfig())
        .DisableSchemaUpdate();

        busConfiguration.EnableOutbox();

        SettingsHolder settingsHolder = busConfiguration.GetSettings();
        settingsHolder.Set("NHibernate.Timeouts.AutoUpdateSchema", true);
        settingsHolder.Set("NHibernate.Subscriptions.AutoUpdateSchema", true);

        #endregion

        #region ReplaceOpenSqlConnection

        busConfiguration.Pipeline.Replace("OpenSqlConnection", typeof(MultiTenantOpenSqlConnectionBehavior));

        #endregion

        #region RegisterPropagateTenantIdBehavior

        busConfiguration.Pipeline.Register <PropagateTenantIdBehavior.Registration>();

        #endregion

        busConfiguration.DisableFeature <SecondLevelRetries>();

        #region CreateSchema

        IStartableBus startableBus = Bus.Create(busConfiguration);

        CreateSchema(hibernateConfig, "A");
        CreateSchema(hibernateConfig, "B");

        #endregion

        #region CapturePipelineExecutor

        PipelineExecutor = ((UnicastBus)startableBus).Builder.Build <PipelineExecutor>();

        #endregion

        using (startableBus.Start())
        {
            Console.WriteLine("Press any key to exit");
            Console.ReadKey();
        }
    }
コード例 #57
0
        protected override HbmMapping GetMappings()
        {
            var mapper = new ModelMapper();

            mapper.Class <Client>(rc =>
            {
                rc.Id(x => x.Id, m => m.Generator(Generators.GuidComb));
                rc.Property(x => x.Name);
            });
            mapper.JoinedSubclass <CorporateClient>(rc =>
            {
                rc.Property(x => x.CorporateId);
            });
            mapper.Class <Project>(rc =>
            {
                rc.Id(x => x.Id, m => m.Generator(Generators.GuidComb));
                rc.Property(x => x.Name);
                rc.Property(x => x.EmailPref, m => m.Type <EnumType <EmailPref> >());
                rc.ManyToOne(x => x.Client, m => m.Column("ClientId"));
                rc.ManyToOne(x => x.BillingClient, m => m.Column("BillingClientId"));
                rc.ManyToOne(x => x.CorporateClient, m => m.Column("CorporateClientId"));
                rc.Set(x => x.Issues,
                       m =>
                {
                    m.Key(k => k.Column(c => c.Name("ProjectId")));
                },
                       rel => rel.OneToMany());
            });
            mapper.Class <Issue>(rc =>
            {
                rc.Id(x => x.Id, m => m.Generator(Generators.GuidComb));
                rc.Property(x => x.Name);
                rc.ManyToOne(x => x.Project, m => m.Column("ProjectId"));
                rc.ManyToOne(x => x.Client, m => m.Column("ClientId"));
            });
            mapper.Class <Invoice>(rc =>
            {
                rc.Id(x => x.Id, m => m.Generator(Generators.GuidComb));
                rc.Property(x => x.InvoiceNumber);
                rc.Property(x => x.Amount);
                rc.Property(x => x.SpecialAmount);
                rc.Property(x => x.Paid);
                rc.ManyToOne(x => x.Project, m => m.Column("ProjectId"));
                rc.ManyToOne(x => x.Issue, m => m.Column("IssueId"));
            });
            mapper.Class <Employee>(rc =>
            {
                rc.Id(x => x.Id, m => m.Generator(Generators.GuidComb));
                rc.Property(x => x.Name);
                rc.Property(x => x.ReviewAsPrimary);
                rc.Set(x => x.Projects,
                       m =>
                {
                    m.Table("EmployeesToProjects");
                    m.Cascade(Mapping.ByCode.Cascade.All | Mapping.ByCode.Cascade.DeleteOrphans);
                    m.Key(k => k.Column(c => c.Name("EmployeeId")));
                },
                       rel => rel.ManyToMany(m => m.Column("ProjectId")));
                rc.Set(x => x.WorkIssues,
                       m =>
                {
                    m.Table("EmployeesToWorkIssues");
                    m.Cascade(Mapping.ByCode.Cascade.All | Mapping.ByCode.Cascade.DeleteOrphans);
                    m.Key(k => k.Column(c => c.Name("EmployeeId")));
                },
                       rel => rel.ManyToMany(m => m.Column("IssueId")));
                rc.Set(x => x.ReviewIssues,
                       m =>
                {
                    m.Table("EmployeesToReviewIssues");
                    m.Cascade(Mapping.ByCode.Cascade.All | Mapping.ByCode.Cascade.DeleteOrphans);
                    m.Key(k => k.Column(c => c.Name("EmployeeId")));
                },
                       rel => rel.ManyToMany(m => m.Column("IssueId")));
            });

            return(mapper.CompileMappingForAllExplicitlyAddedEntities());
        }
コード例 #58
0
 public AssignedAirportToAirlineMappManager()
 {
     _AssignedAirportToAirlineMappStore = new AssignedAirportToAirlineMappDataStoreStrategy();
     mapper     = new ModelMapper <SITA_MultiProject16.Repository.AssignedAirportToAirlineMapp, Entities.AssignedAirportToAirlineMapp>();
     listMapper = new ModelMapper <IList <SITA_MultiProject16.Repository.AssignedAirportToAirlineMapp>, IList <Entities.AssignedAirportToAirlineMapp> >();
 }
コード例 #59
0
ファイル: Mapping.cs プロジェクト: AndersBjrn/Receptdatabas
 public NHibernateMapper()
 {
     _modelMapper = new ModelMapper();
 }
コード例 #60
0
 public IActionResult InsertNewSectorEmpresa([FromBody] SectorDTO body, int idEmpresa)
 {
     try{
         Console.WriteLine("[InsertNewSectorEmpresa] -> request: " + body.ToString());
         // se valida param y body de request
         if (body == null || body.Nombre == null || idEmpresa == 0)
         {
             Console.WriteLine("[InsertNewSectorEmpresa] -> falta sector o idEmpresa en request");
             RestResponse responseErr = RestUtils.GenerateResponseErrorWith(
                 new ResponseError(
                     RestUtils.RESPONSE_BADREQUEST_CODE,
                     "Falta sector o idEmpresa en request"
                     )
                 );
             responseErr.Header.Message = RestUtils.RESPONSE_BADREQUEST_MSG;
             return(BadRequest(responseErr));
         }
         // se realiza insersion
         int result = empresasService.AddNewSectorInEmpresa(
             idEmpresa,
             ModelMapper.Map(body)
             );
         // se valida resultado de operacion
         if (result == 0)
         {
             Console.WriteLine("[InsertNewSectorEmpresa] -> operacion fallida");
             RestResponse responseErr = RestUtils.GenerateResponseErrorWith(
                 new ResponseError(
                     RestUtils.RESPONSE_INTERNAL_ERROR_MSG,
                     "Operacion fallida, no se completo proceso"
                     )
                 );
             responseErr.Header.Message = RestUtils.RESPONSE_ERROR_CODE;
             return(StatusCode(
                        StatusCodes.Status500InternalServerError,
                        responseErr
                        ));
         }
         else if (result == -99)
         {
             Console.WriteLine("[InsertNewSectorEmpresa] -> operacion fallida");
             RestResponse responseErr = RestUtils.GenerateResponseErrorWith(
                 new ResponseError(
                     RestUtils.RESPONSE_NOTFOUND_MSG,
                     "Operacion fallida, no se pudo insertar sector porque no hay empresa asociada al id" + idEmpresa
                     )
                 );
             responseErr.Header.Message = RestUtils.RESPONSE_ERROR_CODE;
             return(NotFound(responseErr));
         }
         body.EmpresaId = idEmpresa;
         body.SectorId  = result;
         Console.WriteLine("[InsertNewSectorEmpresa] -> operacion exitosa");
         return(StatusCode(
                    StatusCodes.Status201Created,
                    RestUtils.GenerateResponseOkWithData(body)
                    ));
     } catch (Exception exception) {
         Console.WriteLine("[InsertNewSectorEmpresa] -> " + RestUtils.RESPONSE_INTERNAL_ERROR_MSG);
         RestResponse response = RestUtils.GenerateResponseErrorWith(
             new ResponseError(
                 exception.Message,
                 exception.GetType().ToString()
                 )
             );
         response.Header.Message = RestUtils.RESPONSE_INTERNAL_ERROR_MSG;
         return(StatusCode(
                    StatusCodes.Status500InternalServerError,
                    response
                    ));
     }
 }