public void ExecuteCustomDelegatedApplier()
        {
            var orm = new Mock<IDomainInspector>();
            orm.Setup(m => m.IsEntity(It.IsAny<Type>())).Returns(true);
            orm.Setup(m => m.IsRootEntity(It.IsAny<Type>())).Returns(true);
            orm.Setup(m => m.IsTablePerClass(It.IsAny<Type>())).Returns(true);
            orm.Setup(m => m.IsPersistentId(It.Is<MemberInfo>(mi => mi.Name == "Id"))).Returns(true);
            orm.Setup(m => m.IsPersistentProperty(It.Is<MemberInfo>(mi => mi.Name != "Id"))).Returns(true);

            var mapper = new Mapper(orm.Object);
            mapper.AddPropertyPattern(mi => mi.GetPropertyOrFieldType() == typeof(DateTime) && (mi.Name.StartsWith("Date") || mi.Name.EndsWith("Date")),
                                      pm => pm.Type(NHibernateUtil.Date));
            var mapping = mapper.CompileMappingFor(new[] {typeof (MyClass)});

            var hbmClass = mapping.RootClasses.Single();

            var hbmProp = (HbmProperty) hbmClass.Properties.First(p => p.Name == "Date");
            hbmProp.Type.name.Should().Be.EqualTo("Date");

            hbmProp = (HbmProperty)hbmClass.Properties.First(p => p.Name == "DateOfMeeting");
            hbmProp.Type.name.Should().Be.EqualTo("Date");

            hbmProp = (HbmProperty)hbmClass.Properties.First(p => p.Name == "MeetingDate");
            hbmProp.Type.name.Should().Be.EqualTo("Date");

            hbmProp = (HbmProperty)hbmClass.Properties.First(p => p.Name == "StartAt");
            hbmProp.Type.Should().Be.Null();
        }
예제 #2
0
 public void ShouldMapColumnsToExpectedTypeBasedOnSpecifiedFieldOrder()
 {
     var mapper = new Mapper<SpecifiedOrderTargetType>(new ErrorCollector());
     var target = mapper.Map(new[] {"4", "hello"});
     Assert.Equal("hello", target.AString);
     Assert.Equal(4, target.AnInt);
 }
        public void Exchange()
        {
            var mapper = new Mapper<int>();
            const int Input_A = 21;
            const int Input_B = 42;
            int result;
            bool isNew;

            mapper.Set(0, Input_A, out isNew);
            Assert.IsTrue(isNew);
            Assert.IsTrue(mapper.TryGet(0, out result));
            Assert.AreEqual(Input_A, result);

            Assert.IsFalse(mapper.Exchange(0, Input_B, out result));
            Assert.AreEqual(Input_A, result);
            Assert.IsTrue(mapper.TryGet(0, out result));
            Assert.AreEqual(Input_B, result);

            Assert.IsTrue(mapper.Exchange(1, Input_A, out result));
            Assert.AreEqual(default(int), result);
            Assert.IsTrue(mapper.TryGet(1, out result));
            Assert.AreEqual(Input_A, result);

            Assert.AreEqual(2, mapper.Count);
        }
        public void ParseAndSave()
        {
            var file = httpContext.Request.Files[0];

            IEnumerable<ISupplier> list = null;

            Dictionary<string, Dictionary<string, int>> ConversionDictionary = null;

            switch (model.Supplier)
            {
                case "Igal":
                    list = csvParser.Parse<Igal>(file.InputStream);
                    ConversionDictionary = Igal.ConversionDictionary;
                    break;
                case "IgalGIA":
                    list = csvParser.Parse<IgalGIA>(file.InputStream);
                    ConversionDictionary = IgalGIA.ConversionDictionary;
                    break;
            }

            list = list.Distinct().ToList();

            var mapper = new Mapper<INV_DIAMONDS_INVENTORY>(ConversionDictionary);
            mapper.SetPricePolicy(PricePolicy.Calibrate);
            mapper.OurPriceCalibration((decimal)1.07);

            var dblist = list.Select(mapper.Map).ToList();

            var db = new DatabasePersistence();
            db.AddSupplierDiamondList(dblist);
            db.SaveOrUpdate();
        }
        public void ComposingPatternsAppliersPacksUsingInflector()
        {
            // In this example I'll use the same domain, but composing others packs, changing the strategy for the hierarchy

            var orm = new ObjectRelationalMapper();

            // The follow line show how compose patterns-appliers-packs and patterns-appliers
            IPatternsAppliersHolder patternsAppliers =
                (new SafePropertyAccessorPack())
                    .Merge(new OneToOneRelationPack(orm))
                    .Merge(new BidirectionalManyToManyRelationPack(orm))
                    .Merge(new BidirectionalOneToManyRelationPack(orm))
                    .Merge(new DiscriminatorValueAsClassNamePack(orm))
                    .Merge(new CoolColumnsNamingPack(orm))
                    .Merge(new TablePerClassPack())
                    .Merge(new PluralizedTablesPack(orm, new EnglishInflector()))
                    .Merge(new ListIndexAsPropertyPosColumnNameApplier())
                    .Merge(new DatePropertyByNameApplier())
                    .Merge(new MsSQL2008DateTimeApplier());

            // Instancing the Mapper using the result of Merge
            var mapper = new Mapper(orm, patternsAppliers);

            // Note: I'm declaring the strategy only for the base entity
            orm.TablePerClass<Animal>();

            // Note : I have to create mappings for the whole domain
            var mapping = mapper.CompileMappingFor(typeof(Animal).Assembly.GetTypes().Where(t => t.Namespace == typeof(Animal).Namespace));
            Console.Write(mapping.AsString());
        }
 public SqlProvider()
     : base(PROVIDER_NAME)
 {
     m_mapper = new Mapper(this);
     m_builder = new CommandBuilder(this);
     m_executor = new CommandExecutor();
 }
        public void Map_WhenInvoked_ShouldMapArrayMember()
        {
            // Arrange
            var mapper = new Mapper<SArr, DArr>()
                .Map((arr, i) => arr.Src[i].Name, (arr, i) => arr.Dst[i].Name)
                .Map((arr, i) => arr.Src[i].Id, (arr, i) => arr.Dst[i].Id);

            var src = fixture.Create<SArr>();

            // Act
            var dst = mapper.Map(src);

            // Assert
            Assert.NotNull(dst.Dst);
            Assert.Equal(dst.Dst.Length, src.Src.Length);

            for (var i = 0; i < dst.Dst.Length; i++)
            {
                var srcElm = src.Src[i];
                var dstElm = dst.Dst[i];

                Assert.NotNull(dstElm);
                Assert.Equal(srcElm.Name, dstElm.Name);
                Assert.Equal(srcElm.Id, dstElm.Id);
            }
        }
        public void ComposingPatternsAppliersPacks()
        {
            // In this example I will compose various packs to customize the mapping.
            // The result is the same of ConfOrm.UsageExamples.Packs.SimpleDemo but this time using patterns-appliers-packs composition (instead its short-cut CoolPatternsAppliersHolder).
            // To play with patterns-appliers-packs-composition you need a more complex domain; adding and removing packs you can see
            // how change your mapping.

            // What is a patterns-appliers-pack:
            // It is an implementation of IPatternsAppliersHolder focused in a specific concern;
            // for example CoolTablesAndColumnsNamingPack is focused to set columns and table names.

            var orm = new ObjectRelationalMapper();

            // The follow line show how compose patterns-appliers-packs and patterns-appliers
            IPatternsAppliersHolder patternsAppliers =
                (new SafePropertyAccessorPack())
                    .Merge(new OneToOneRelationPack(orm))
                    .Merge(new BidirectionalManyToManyRelationPack(orm))
                    .Merge(new BidirectionalOneToManyRelationPack(orm))
                    .Merge(new DiscriminatorValueAsClassNamePack(orm))
                    .Merge(new CoolTablesAndColumnsNamingPack(orm))
                    .Merge(new TablePerClassPack())
                    .Merge(new DatePropertyByNameApplier())
                    .Merge(new MsSQL2008DateTimeApplier());

            // Instancing the Mapper using the result of Merge
            var mapper = new Mapper(orm, patternsAppliers);

            // Note: I'm declaring the strategy only for the base entity
            orm.TablePerClassHierarchy<Animal>();

            // Note : I have to create mappings for the whole domain
            var mapping = mapper.CompileMappingFor(typeof(Animal).Assembly.GetTypes().Where(t => t.Namespace == typeof(Animal).Namespace));
            Console.Write(mapping.AsString());
        }
예제 #9
0
        public void Map_ShouldMapReportNumber()
        {
            //Arrange
            var mapper = new Mapper<INV_DIAMONDS_INVENTORY>(Igal.ConversionDictionary);
            var igalDiamond = new Igal()
            {
                Clarity = "SI2",
                Culet = "",
                Color = "H",
                Cut = "VG",
                DepthPresentage = (decimal)4.25,
                InventoryCode = "12345",
                Fluorescence = "MB",
                Girdle = "",
                Length = (decimal)3.5,
                Polish = "G",
                Price = 9999,
                Report = "EGL IL",
                ReportURL = "",
                Shape = "BR",
                Symmetry = "EX",
                Table = (decimal)54.5,
                Weight = (decimal)2.41,
                Width = (decimal)6.35,
                ReportNumber = "123"

            };
            //Act
            var inv_entry = mapper.Map(igalDiamond);
            //Assert
            inv_entry.report_number.Should().Be("123");
        }
예제 #10
0
 public virtual IMapper BuildMapper()
 {
     if (mapper != null)
     {
         // log
         Settings.InfoLog.Invoke(MethodBase.GetCurrentMethod().Name + " Invoked more than once. Returning cached instance! Make sure you do not call this method multiple times.");
     }
     else
     {
         var mapperLocal = new Mapper(Settings.MappingStrategyBuilder = Settings.MappingStrategyBuilder ?? BuildMappingStrategyBuilder(),
                                      Settings.MappingCompiler = Settings.MappingCompiler ?? BuildMappingCompiler(),
                                      Settings.TypeMatchers = Settings.TypeMatchers ?? BuildTypeMatchers());
         var mappings = new List<MappingInfo>();
         var bag = new MappingBag(mappings);
         foreach (var catalog in catalogs)
         {
             catalog.Collect(bag);
         }
         mappings.Sort();
         foreach (var mapping in mappings)
         {
             mapperLocal.RegisterMapping(mapping);
         }
         mapper = mapperLocal;
     }
     return mapper;
 }
예제 #11
0
        public static HbmMapping GetMapings(ObjectRelationalMapper orm)
        {

            domainEntities =
                typeof(Entity).Assembly.GetTypes()
                    .Where(t => typeof(Entity).IsAssignableFrom(t) && !t.IsGenericType)
                    .ToList();
            orm.Cascade<Claim, CPS.Domain.Action>(CascadeOn.None);
            orm.Cascade<Branch, Claim>(CascadeOn.None);
            orm.Cascade<Domain.Action,Document>(CascadeOn.All);

            orm.Component<Address>();
            orm.Component<Incident>();
            orm.Component<ContactInfo>();

            var patterns = new SafePropertyAccessorPack().Merge(new OneToOneRelationPack(orm))
                .Merge(new BidirectionalManyToManyRelationPack(orm))
                .Merge(new BidirectionalOneToManyRelationPack(orm))
                .Merge(new DiscriminatorValueAsClassNamePack(orm))
                .Merge(new CoolColumnsNamingPack(orm))
                .Merge(new TablePerClassPack())
                .Merge(new ListIndexAsPropertyPosColumnNameApplier())
                .Merge(new PluralizedTablesPack(orm, new EnglishInflector()))
                .Merge(new MsSQL2008DateTimeApplier());


            var mapper = new Mapper(orm, patterns);

            var mapping = mapper.CompileMappingFor(domainEntities);
            Debug.WriteLine(mapping.AsString());
            return mapping;
        }
예제 #12
0
 private static HbmMapping GetMapping()
 {
     var orm = new ObjectRelationalMapper();
     var mapper = new Mapper(orm,
     new CoolPatternsAppliersHolder(orm));
     orm.TablePerClassHierarchy<Product>();
     orm.TablePerClass<ActorRole>();
     orm.Patterns.PoidStrategies.Add(
     new GuidOptimizedPoidPattern());
     orm.VersionProperty<Entity>(x => x.Version);
     orm.NaturalId<Product>(p => p.Name);
     orm.Cascade<Movie, ActorRole>(
     Cascade.All | Cascade.DeleteOrphans);
     mapper.AddPropertyPattern(mi =>
     mi.GetPropertyOrFieldType() == typeof(Decimal) &&
     mi.Name.Contains("Price"),
     pm => pm.Type(NHibernateUtil.Currency));
     mapper.AddPropertyPattern(mi =>
     orm.IsRootEntity(mi.DeclaringType) &&
     !"Description".Equals(mi.Name),
     pm => pm.NotNullable(true));
     mapper.Subclass<Movie>(cm =>
     cm.List(movie => movie.Actors,
     colm => colm.Index(
     lim => lim.Column("ActorIndex")), m => { }));
     var domainClasses = typeof(Entity).Assembly.GetTypes()
     .Where(t => typeof(Entity).IsAssignableFrom(t));
     return mapper.CompileMappingFor(domainClasses);
 }
예제 #13
0
        public void CqlClient_Timestamp()
        {
            var config = new MappingConfiguration()
                .Define(new Map<Song>().PartitionKey(s => s.Id).TableName("song_insert"));

            //Use linq to create the table
            var table = new Table<Song>(_session, config);
            table.CreateIfNotExists();
            var mapper = new Mapper(_session, config);
            var song = new Song
            {
                Id = Guid.NewGuid(),
                Artist = "The Who",
                Title = "Substitute",
                ReleaseDate = DateTimeOffset.UtcNow
            };
            //Set timestamp to 1 day ago
            var timestamp = DateTimeOffset.Now.Subtract(TimeSpan.FromDays(1));
            mapper.Insert(song, true, CqlQueryOptions.New().SetTimestamp(timestamp));

            //query for timestamp in a column of the record
            var cqlLowerCasePartitionKey = "SELECT WRITETIME (Artist) AS timestamp FROM " + table.Name + " WHERE Id = " + song.Id + ";";
            var rows = _session.Execute(cqlLowerCasePartitionKey).GetRows().ToList();
            Assert.AreEqual(1, rows.Count);

            var creationTimestamp = rows[0].GetValue<long>("timestamp");
            Assert.NotNull(creationTimestamp);
            //Timestamp retrieved is in macroseconds. Converting it to milliseconds
            Assert.AreEqual(TypeSerializer.SinceUnixEpoch(timestamp).Ticks / 10, rows[0].GetValue<object>("timestamp"));
        }
예제 #14
0
 public Import(ILocalhost localhost, IGenerator generator)
 {
     this.localhost = localhost;
     this.generator = generator;
     mapper = new Mapper<Key, Key>();
     interactions = new List<Interaction>();
 }
예제 #15
0
    public void TransposeRegroupsPerTargetRepositoryAndBranch()
    {
        var m = new Mapper()
            .Add(new Parts("o1/r1", TreeEntryTargetType.Blob, "b1", "a"),
                new Parts("o1/r2", TreeEntryTargetType.Blob, "b1", "a"),
                new Parts("o1/r2", TreeEntryTargetType.Blob, "b1", "b"),
                new Parts("o1/r3", TreeEntryTargetType.Blob, "b1", "a"))
            .Add(new Parts("o1/r1", TreeEntryTargetType.Tree, "b1", "t1"),
                new Parts("o1/r2", TreeEntryTargetType.Tree, "b1", "t"))
            .Add(new Parts("o2/r4", TreeEntryTargetType.Tree, "b3", "t3"),
                new Parts("o1/r3", TreeEntryTargetType.Tree, "b1", "sub/t"),
                new Parts("o1/r2", TreeEntryTargetType.Tree, "b1", "t2"))
            .Add(new Parts("o1/r1", TreeEntryTargetType.Tree, "b1", "t2"),
                new Parts("o1/r2", TreeEntryTargetType.Tree, "b2", "t"),
                new Parts("o1/r3", TreeEntryTargetType.Tree, "b1", "t"));

        var t = m.Transpose();

        var orbs = t.Keys.ToList();
        orbs.Sort(StringComparer.Ordinal);

        Assert.AreEqual(new[]
        {
            "o1/r2/b1",
            "o1/r2/b2",
            "o1/r3/b1"
        }, orbs.ToArray());
    }
예제 #16
0
        public void DefiningAndCustomizingVersionThroughBaseImplementation()
        {
            // In this example I'll show how you can work with Version and how ConfORM understands OOP

            var orm = new ObjectRelationalMapper();
            var mapper = new Mapper(orm, new CoolPatternsAppliersHolder(orm));

            // In this case I will use the definition of table-to-class strategy class by class
            orm.TablePerClass<CurrencyDefinition>();
            orm.TablePerClass<Company>();
            orm.TablePerClass<Customer>();
            orm.TablePerClass<Provider>();

            // Defining relations
            orm.OneToOne<Company, Customer>();
            orm.OneToOne<Company, Provider>();

            // In the follow line I'm defining which is the property used as Version for all classes inherited from VersionedEntity
            orm.VersionProperty<VersionedEntity>(ve=> ve.Version);

            // In the follow line I'm customizing the column-name for the property used as Version for all classes inherited from VersionedEntity....
            // Note : VersionedEntity is not an entity, it is only a base class.
            mapper.Class<VersionedEntity>(cm => cm.Version(ve => ve.Version, vm => vm.Column("Revision")));

            // In the follow line I'm customizing the column-name for the property used as Version only for the class Provider
            // Note : You can move the follow line before the previous and the result does not change, this is because ConfORM can understand
            // which is a base customization and which is the specific customization.
            mapper.Class<Provider>(cm => cm.Version(ve => ve.Version, vm => vm.Column("IncrementalVersion")));

            // Note : I have to create mappings for the whole domain; Entity and VersionedEntity are excluded from de mapping because out-side
            // root-entities hierarchy (root-entities are : CurrencyDefinition, Company, Customer, Provider)
            var mapping = mapper.CompileMappingFor(typeof(Entity).Assembly.GetTypes().Where(t => t.Namespace == typeof(Entity).Namespace));
            Console.Write(mapping.AsString());
        }
        public void WhenCustomizeNestedComponentParentAccessThroughCollectionThenApplyCustomizationToMappingForCompositeElement()
        {
            Mock<IDomainInspector> orm = GetMockedDomainInspector();

            var domainInspector = orm.Object;
            var mapper = new Mapper(domainInspector);

            mapper.Class<MyClass>(
                ca =>
                ca.Bag(mycomponent => mycomponent.Components, x => { },
                       cer =>
                       cer.Component(
                       	c =>
                       	c.Component(mycomponent => mycomponent.Component,
                       	            ce => ce.Parent(mync => mync.Parent, pa => pa.Access(Accessor.Field))))));

            HbmMapping mapping = mapper.CompileMappingFor(new[] { typeof(MyClass) });

            HbmClass rc = mapping.RootClasses.First(r => r.Name.Contains("MyClass"));
            var hbmBag = (HbmBag)rc.Properties.First(p => p.Name == "Components");
            var hbmCompositeElement = (HbmCompositeElement)hbmBag.ElementRelationship;
            var hbmNestedCompositeElement = (HbmNestedCompositeElement)hbmCompositeElement.Properties.First(p => p.Name == "Component");
            hbmNestedCompositeElement.Parent.name.Should().Be("Parent");
            hbmNestedCompositeElement.Parent.access.Should().Be("field.camelcase-underscore");
        }
 private void CustomizeRelations(Mapper mapper)
 {
     /* TODO: add IDomainInspector.IsOptionalOneToMany to avoid auto OnDelete.Cascade and soft-Cascade actions.
         IsOptionalOneToMany may come in place using Declared.Explicit in the ORM */
     mapper.Class<User>(cm =>
     {
         cm.Id(u => u.Id, im => im.Generator(Generators.Foreign<User>(u => u.Human)));
         cm.OneToOne(u => u.Human, otom => otom.Constrained(true));
     });
     mapper.Class<Human>(cm => cm.Bag(human => human.Pets, bagm =>
     {
         bagm.Cascade(Cascade.None);
         bagm.Key(km => km.OnDelete(OnDeleteAction.NoAction));
     }, cer => { }));
     mapper.Class<Zoo>(cm =>
     {
         cm.Map(zoo => zoo.Mammals, mapm =>
         {
             mapm.Cascade(Cascade.None);
             mapm.Key(km => km.OnDelete(OnDeleteAction.NoAction));
             mapm.Inverse(false);
         }, x=> { }, cer => { });
         cm.Map(zoo => zoo.Animals, mapm =>
         {
             mapm.Cascade(Cascade.None);
             mapm.Key(km => km.OnDelete(OnDeleteAction.NoAction));
         }, x => { }, cer => { });
     });
 }
예제 #19
0
        public void ComposingPatternsAppliersPacks()
        {
            // Thanks to Lorenzo Vegetti to provide the domain of this example.
            // This example refers to a little-domain, interesting from the point of view of mapping with ConfORM.
            // Here you can see how apply general convetion, how and when compose patterns-appliers-packs and patterns-appliers,
            // how ConfORM can apply different mapping depending on the type of enum (see the difference on CostOptions) and so on...
            // You don't have to organize the mapping all in one class, as in this example, and you don't have to use the IModuleMapping...
            // You can organize the mapping as you feel more confortable for your application; in some case a class is enough, in other cases would
            // be better the separation per module/concern, you are not closed in "mapping per class" box.

            var orm = new ObjectRelationalMapper();

            // With the follow line I'm adding the pattern for the POID strategy ("native" instead the default "High-Low")
            orm.Patterns.PoidStrategies.Add(new NativePoidPattern());

            // composition of patterns-appliers-packs and patterns-appliers for Lorenzo's domain
            // Note: for bidirectional-one-to-many association Lorenzo is not interested in the default cascade behavior,
            // implemented in the BidirectionalOneToManyRelationPack, because he is using a sort of soft-delete in his base class VersionModelBase.
            // He can implements a custom pack of patterns-appliers to manage the situation when classes does not inherits from VersionModelBase by the way
            // he don't want the cascade atall, so the BidirectionalOneToManyInverseApplier will be enough
            IPatternsAppliersHolder patternsAppliers =
                (new SafePropertyAccessorPack())
                    .Merge(new OneToOneRelationPack(orm))
                    .Merge(new BidirectionalManyToManyRelationPack(orm))
                    .Merge(new DiscriminatorValueAsClassNamePack(orm))
                    .Merge(new CoolColumnsNamingPack(orm))
                    .Merge(new TablePerClassPack())
                    .Merge(new PluralizedTablesPack(orm, new EnglishInflector()))
                    .Merge(new ListIndexAsPropertyPosColumnNameApplier())
                    .Merge(new BidirectionalOneToManyInverseApplier(orm))
                    .Merge(new EnumAsStringPack())
                    .Merge(new DatePropertyByNameApplier())
                    .Merge(new MsSQL2008DateTimeApplier());

            // Instancing the Mapper using the result of Merge
            var mapper = new Mapper(orm, patternsAppliers);

            // Setting the version property using the base class
            orm.VersionProperty<VersionModelBase>(v => v.Version);

            // Note: I'm declaring the strategy only for the base entity
            orm.TablePerClassHierarchy<Cost>();
            orm.TablePerClass<EditionQuotation>();
            orm.TablePerClass<ProductQuotation>();
            orm.TablePerClass<Quotation>();

            AppliesGeneralConventions(mapper);

            // EditionQuotation.PrintCost don't use lazy-loading
            mapper.Customize<EditionQuotation>(map => map.ManyToOne(eq => eq.PrintCost, m2o => m2o.Lazy(LazyRelation.NoLazy)));

            // Customizes some others DDL's stuff outside conventions
            CustomizeColumns(mapper);

            // Note : I have to create mappings for the whole domain
            HbmMapping mapping =
                mapper.CompileMappingFor(
                    typeof (GenericModelBase<>).Assembly.GetTypes().Where(t => t.Namespace == typeof (GenericModelBase<>).Namespace));
            Console.Write(mapping.AsString());
        }
예제 #20
0
 public StripeService(string apiKey = null)
 {
     ApiKey = apiKey;
     Mapper = new Mapper();
     Requestor = new Requestor(Mapper);
     ParameterBuilder = new ParameterBuilder();
 }
예제 #21
0
 public void BoolPropertyTrueStringIsParsedAsTrue()
 {
     string input = "<TestClass BoolProp=\"true\" /> ";
     var mapper = new Mapper<TestClass>(input);
     TestClass result = mapper.ParseNext();
     Assert.IsTrue(result.BoolProp);
 }
예제 #22
0
 public void BoolPropertyZeroIsParsedAsFalse()
 {
     string input = "<TestClass BoolProp=\"0\" /> ";
     var mapper = new Mapper<TestClass>(input);
     TestClass result = mapper.ParseNext();
     Assert.IsFalse(result.BoolProp);
 }
        public void CallCustomizerOnCompositeElementsProperties()
        {
            Mock<IDomainInspector> orm = GetMockedDomainInspector();
            var mapper = new Mapper(orm.Object);
            bool simplePropertyCalled = false;
            bool manyToOneCalled = false;
            bool reSimplePropertyCalled = false;
            bool reManyToOneCalled = false;

            mapper.Customize<MyComponent>(x =>
            {
                x.Property(mc => mc.Simple, pm => simplePropertyCalled = true);
                x.ManyToOne(mc => mc.ManyToOne, pm => manyToOneCalled = true);
            });
            mapper.Customize<MyNestedComponent>(x =>
            {
                x.Property(mc => mc.ReSimple, pm => reSimplePropertyCalled = true);
                x.ManyToOne(mc => mc.ReManyToOne, pm => reManyToOneCalled = true);
            });

            mapper.CompileMappingFor(new[] { typeof(MyClass) });
            simplePropertyCalled.Should().Be.True();
            manyToOneCalled.Should().Be.True();
            reSimplePropertyCalled.Should().Be.True();
            reManyToOneCalled.Should().Be.True();
        }
예제 #24
0
		/// <summary>
		/// Adds a mapper for the specified token
		/// </summary>
		public void Add(string token, Mapper mapper)
		{
			if(token==null) throw new ArgumentNullException("token is null");
			if(mapper==null) throw new ArgumentNullException("mapper is null");
			
			m_Mappers[token]=mapper;
		}
예제 #25
0
        public HbmMapping CreateMapping()
        {
            var orm = new ObjectRelationalMapper();

            //主键生成策略(自增)
            orm.Patterns.PoidStrategies.Add(new NativePoidPattern());
            var entities = new[]
            {
                typeof(User),
                typeof(PlusMaterial),
                typeof(StockIn),
                typeof(StockInDetail),
                typeof(StockOut),
                typeof(StockOutDetail),
            };
            orm.TablePerClass(entities);

            //关系映射
            orm.ManyToOne<StockInDetail, StockIn>();
            orm.ManyToOne<StockOutDetail, StockOut>();

            //数据库命名规则
            var mapper = new Mapper(orm, new CoolPatternsAppliersHolder(orm));
            orm.TablePerClass(entities);
            var hc = mapper.CompileMappingFor(Assembly.Load("PMMS.Entities").GetTypes());
            return hc;
        }
        public void WhenCustomizedAndSpecifiedThenSetDifferentConfigurationForSameComponent()
        {
            Mock<IDomainInspector> orm = GetMockedDomainInspector();

            var domainInspector = orm.Object;
            var mapper = new Mapper(domainInspector);
            mapper.Customize<Name>(name =>
                {
                    name.Property(np => np.First, pm => pm.Length(20));
                    name.Property(np => np.Last, pm => pm.Length(35));
                });

            mapper.Class<Person>(c =>
                {
                    c.Component(p => p.RealName, cname => cname.Property(cnp => cnp.Last, pm => pm.Length(50)));
                    c.Component(p => p.Aka, cname => cname.Property(cnp => cnp.First, pm => pm.Length(50)));
                });

            HbmMapping mapping = mapper.CompileMappingFor(new[] { typeof(Person) });

            HbmClass rc = mapping.RootClasses.First(r => r.Name.Contains("Person"));
            var hbmRealName = (HbmComponent)rc.Properties.First(p => p.Name == "RealName");
            var hbmAka = (HbmComponent)rc.Properties.First(p => p.Name == "Aka");
            hbmRealName.Properties.OfType<HbmProperty>().Select(p => p.length).Should().Have.SameValuesAs("20", "50");
            hbmAka.Properties.OfType<HbmProperty>().Select(p => p.length).Should().Have.SameValuesAs("50", "35");
        }
        public void MapCollection_WhenConversionFailed_ShouldCorrectlyAddIndexToPathes()
        {
            // Arrange
            var mapper = new Mapper<AContainer, BContainer>()
                .Map((e, i) => e.Data[i].Name, (container, i) => container.Set[i].Numeric);

            var left = fixture.CreateMany<AContainer>(15).ToList();

            left.ForEach(e => e.Data.ForEach(d => d.Name = "124"));

            left[11].Data[2] = new A { Name = "Error" };

            // Throws
            try
            {
                mapper.MapCollection(left);
                Assert.True(false);
            }
            catch (ConversionException ex)
            {
                Assert.Equal(1, ex.Errors.Length);
                var error = ex.Errors[0];

                Assert.Equal("[11].Data[2].Name", error.SourcePath);
                Assert.Equal("[11].Set[2].Numeric", error.DestinationPath);
                Assert.NotEmpty(error.ErrorMessage);
                Assert.Equal("Error", error.SourceValue);
            }
        }
예제 #28
0
        public PocoMapperTests(ITestOutputHelper x)
        {
            x.Logger();
            LogManager.OutputToTrace();
            _sut = Setup.MapperFactory().CreateMapper<MapperPost>("1") as Mapper<MapperPost>;

        }
예제 #29
0
파일: DBInit.cs 프로젝트: GunioRobot/vlko
        /// <summary>
        /// Initializes the mappings.
        /// </summary>
        /// <param name="config">The configuration.</param>
        public static void InitMappings(Configuration config)
        {
            var orm = new ObjectRelationalMapper();

            var mapper = new Mapper(orm);

            mapper.AddPropertyPattern(mi => mi.GetPropertyOrFieldType() == typeof(string) && !mi.Name.EndsWith("Text"), pm => pm.Length(50));
            mapper.AddPropertyPattern(mi => mi.GetPropertyOrFieldType() == typeof(string) && mi.Name.EndsWith("Text"), pm => pm.Type(NHibernateUtil.StringClob));

            orm.Patterns.PoidStrategies.Add(new AssignedPoidPattern());

            foreach (var componentDbInit in IoC.ResolveAllInstances<IComponentDbInit>())
            {
                componentDbInit.InitMappings(orm, mapper);
            }

            // compile the mapping for the specified entities
            HbmMapping mappingDocument = mapper.CompileMappingFor(ListOfModelTypes());

            // inject the mapping in NHibernate
            config.AddDeserializedMapping(mappingDocument, "Domain");
            // fix up the schema
            SchemaMetadataUpdater.QuoteTableAndColumns(config);

            SessionFactory.SessionFactoryInstance = config.BuildSessionFactory();
        }
 public void WhenCircularReferenceShouldNotMatch()
 {
     var orm = GetMockedDomainInspector();
     var mapper = new Mapper(orm.Object);
     var mappings = mapper.CompileMappingFor(new[] { typeof(Person) });
     var hbmPersonFriends = mappings.RootClasses.First(rc => rc.Name.Contains("Person")).Properties.OfType<HbmBag>().Single();
     hbmPersonFriends.Table.Should().Be.Null();
 }
예제 #31
0
 protected override void BecauseOf()
 {
     Result = Mapper.MapToJsonModel(ValidDateAsString, Rates);
 }
예제 #32
0
 public async Task <List <ContentDTO> > GetAsync() => (await ContentRepository.All()).Select(x => Mapper.Map <ContentDTO>(x)).ToList();
예제 #33
0
 public IList<InvoiceInfoDto> GetAllMissions()
 {
     var task = _InvoiceRepository.GetAll().OrderByDescending(t => t.Id).ToList();
     return Mapper.Map<List<InvoiceInfoDto>>(task);
 }
        /// <summary>
        /// Add Payment - Async
        /// </summary>
        /// <param name="paymentViewModel">New PaymentViewModel</param>
        /// <returns>Added Payment</returns>
        public async Task <PaymentViewModel> AddPaymentViewModelAsync(PaymentViewModel paymentViewModel)
        {
            using (IDbContextTransaction transaction = await UnitOfWork.BeginTransactionAsync())
            {
                try
                {
                    // need change
                    // Here we need to check the payment referenece from their api

                    string username = HttpContextAccessor.HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value;

                    User user = await UnitOfWork.UserRepository.GetUserByUsernameAsync(username);

                    if (user == null)
                    {
                        throw new Exception("Invalid user or user not found.");
                    }

                    PaymentMethod paymentMethod = await UnitOfWork.PaymentMethodRepository.GetPaymentMethodByCodeAsync(paymentViewModel.PaymentMethodCode);

                    if (paymentMethod == null)
                    {
                        throw new Exception("Invalid payment method code.");
                    }

                    Payment payment = Mapper.Map <PaymentViewModel, Payment>(paymentViewModel);

                    // Set Payment's missing parts
                    payment.UserId          = user.Id;
                    payment.PaymentMethodId = paymentMethod.Id;

                    await UnitOfWork.PaymentRepository.AddPaymentAsync(payment);

                    //Update user's loyalty points
                    user.LoyaltyPoints += payment.EarnedLoyaltyPoints;

                    string message = $"{ ((user.Gender == Gender.Male) ? "Mr" : "Miss/ Mrs") }. { user.FirstName }, you payed Rs.{ string.Format("{0:0.00}", payment.Amount) } successfully by { paymentMethod.Name } on { payment.PayedDateTime }";

                    SentEmail sentEmail = new SentEmail()
                    {
                        Subject = "Payment success",
                        Message = message,
                        Payment = payment,
                        UserId  = user.Id
                    };
                    //Do what ever thing in here to send email
                    await UnitOfWork.SentEmailRepository.AddSentEmailAsync(sentEmail);

                    SentMessage sentMessage = new SentMessage()
                    {
                        Message = message,
                        Payment = payment,
                        UserId  = user.Id
                    };
                    //Do what ever thing in here to send sms
                    await UnitOfWork.SentMessageRepository.AddSentMessageAsync(sentMessage);

                    await UnitOfWork.CompleteAsync();

                    transaction.Commit();

                    payment.PaymentMethod = paymentMethod;

                    // Create new Payment ViewModel
                    PaymentViewModel addedPaymentViewModel = Mapper.Map <Payment, PaymentViewModel>(payment);
                    addedPaymentViewModel.PaymentMethodCode = paymentMethod.Code;

                    return(addedPaymentViewModel);
                }
                catch
                {
                    transaction.Rollback();
                    throw;
                }
            }
        }
예제 #35
0
        public async Task <ContentDTO> GetAsync(int id)
        {
            var content = await ContentRepository.Read(id);

            return(Mapper.Map <ContentDTO>(content));
        }
예제 #36
0
 public DepartmentDto GetDtoByID(int id)
 {
     return Mapper.Map<DepartmentDto>(_departmentRepository.GetEntityByID(id));
 }
예제 #37
0
 public void AddDto(DepartmentDto dto)
 {
     _departmentRepository.AddEntity(Mapper.Map<Department>(dto));
 }
예제 #38
0
 protected override void Because_of()
 {
     _source = new Source {Name = "jon", Value = "value", Foo = "bar"};
     _dest = new Destination();
     _dest = Mapper.Map<Source, Destination>(_source);
 }
예제 #39
0
 protected override void Because_of()
 {
     _source = new Source {MyName = "jon"};
     _dest = Mapper.Map<Source, Destination>(_source);
 }
예제 #40
0
 protected override void Because_of()
 {
     _dest = Mapper.Map<Source, Dest>(new Source());
 }
예제 #41
0
 public void Should_propagate_exception()
 {
     new Action(()=>Mapper.Map<Destination>(new Source())).ShouldThrow<AutoMapperMappingException>(e=>e.InnerException.ShouldEqual(_ex));
 }
예제 #42
0
 protected override void Because_of()
 {
     var source = new Source { Value = "a1" };
     _dest = Mapper.Map<Source, Dest>(source);
 }
예제 #43
0
 protected override void Because_of()
 {
     _destination = Mapper.Map<Destination>(new Source { ObjectValue = new InnerSource { IntValue = 15 } });
 }
예제 #44
0
 protected override void Because_of()
 {
     _result = Mapper.Map<Source, Destination>(new Source { Value = 5 });
 }
예제 #45
0
 // GET: Account
 public ActionResult Index()
 {
     var userModelView = Mapper.Map<IEnumerable<User>, IEnumerable<UserViewModel>>(_userAppService.GetAll());
     _userAppService.Save();
     return View(userModelView);
 }
예제 #46
0
 protected override void Because_of()
 {
     _result = Mapper.Map(new Source { Value = 5 }, _result);
 }
예제 #47
0
 public List<DepartmentDto> GetAllDtos()
 {
     return Mapper.Map<List<DepartmentDto>>(_departmentRepository.GetAllEntities());
 }
예제 #48
0
        public override async Task<dynamic> HandleAsync(Commands.AddProductPhoto command)
        {
            Result result;
            // validate the command
            if (string.IsNullOrWhiteSpace(command.Medium))
            {
                result= new Result(false, command.Medium, "Orta Boy Resim Adı gereklidir.", true, null);
                return await Task.FromResult(result);
            }
            if (command.Medium.Length > 200)
            {
                result=new Result(false, command.Medium, "Orta Boy Resim Adı 200 karakterden uzun olamaz.", true,null);
                return await Task.FromResult(result);
            }
            if (string.IsNullOrWhiteSpace(command.Small))
            {
                result= new Result(false, command.Small, "Küçük Boy Resim Adı gereklidir.", true,null);
                return await Task.FromResult(result);
            }
            if (command.Small.Length > 200)
            {
                result=new Result(false, command.Small, "Küçük Boy Resim Adı 200 karakterden uzun olamaz.", true,null);
                return await Task.FromResult(result);
            }
            if (string.IsNullOrWhiteSpace(command.Large))
            {
                result= new Result(false, command.Large, "Büyük Boy Resim Adı gereklidir.", true,null);
                return await Task.FromResult(result);
            }
            if (command.Large.Length > 200)
            {
                result= new Result(false, command.Large, "Büyük Boy Resim Adı 200 karakterden uzun olamaz.", true,null);
                return await Task.FromResult(result);
            }
            if (string.IsNullOrWhiteSpace(command.Alt))
            {
                result= new Result(false, command.Alt, "Açıklama gereklidir.", true,null);
                return await Task.FromResult(result);
            }
            if (command.Alt.Length > 4000)
            {
                result= new Result(false, command.Alt, "Açıklama 4000 karakterden uzun olamaz.", true,null);
                return await Task.FromResult(result);
            }
            if (string.IsNullOrWhiteSpace(command.ProductId))
            {
                result= new Result(false, command.ProductId, "ÜrünId gereklidir.", true,null);
                return await Task.FromResult(result);
            }


            // map command to the model
            var model = Mapper.Map<ProductPhoto>(command);

            // mark the model to insert
            productphotoRepository.Insert(model);

            // save changes to database
            await unitOfWork.SaveChangesAsync();

            // return the result
            result = new Result(true,model.Id, "Ürün resmi başarıyla eklendi.", true, 1);

            return await Task.FromResult(result);
        }
예제 #49
0
 public void UpdateDto(DepartmentDto dto)
 {
     _departmentRepository.UpdateEntity(Mapper.Map<Department>(dto));
 }
예제 #50
0
        public ActionResult Edit(int id)
        {
            var bannerViewModel = Mapper.Map <Banner, BannerViewModel>(_bannerService.GetById(id));

            return(View(bannerViewModel));
        }
 /// <summary>
 /// Get Payment By User Id - Async
 /// </summary>
 /// <param name="userId">User Id</param>
 /// <returns>IEnumerable of PaymentViewModel</returns>
 public async Task <IEnumerable <PaymentViewModel> > GetPaymentViewModelsByUserIdAsync(int userId)
 {
     return(Mapper.Map <IEnumerable <Payment>, IEnumerable <PaymentViewModel> >(await UnitOfWork.PaymentRepository.GetPaymentByUserIdAsync(userId)));
 }
예제 #52
0
 protected override void Because_of()
 {
     _destination = Mapper.Map<Destination>(new Source { ObjectValue = new object() });
 }
예제 #53
0
        public async Task <IEnumerable <PublisherViewModel> > GetPublishers()
        {
            var publishers = await _publisherService.GetAll();

            return(Mapper.Map <IEnumerable <Publisher>, IEnumerable <PublisherViewModel> >(publishers));
        }
 /// <summary>
 /// Get Payment By Id - Async
 /// </summary>
 /// <param name="id">Payment Id</param>
 /// <returns>PaymentViewModel</returns>
 public async Task <PaymentViewModel> GetPaymentViewModelByIdAsync(int id)
 {
     return(Mapper.Map <Payment, PaymentViewModel>(await UnitOfWork.PaymentRepository.GetPaymentByIdAsync(id)));
 }
예제 #55
0
 public StudentViewModel GetById(Guid id)
 {
     return(Mapper.Map <StudentViewModel>(_studentRepository.GetById(id)));
 }
예제 #56
0
        public void BuildMappings()
        {
            Mapper.CreateMap <Common.Models.Matters.Matter, MatterViewModel>()
            .ForMember(dst => dst.IsStub, opt => opt.UseValue(false))
            .ForMember(dst => dst.Created, opt => opt.MapFrom(src => src.Created))
            .ForMember(dst => dst.Modified, opt => opt.MapFrom(src => src.Modified))
            .ForMember(dst => dst.Disabled, opt => opt.MapFrom(src => src.Disabled))
            .ForMember(dst => dst.CreatedBy, opt => opt.ResolveUsing(db =>
            {
                return(new ViewModels.Account.UsersViewModel()
                {
                    PId = db.CreatedBy.PId,
                    IsStub = true
                });
            }))
            .ForMember(dst => dst.ModifiedBy, opt => opt.ResolveUsing(db =>
            {
                return(new ViewModels.Account.UsersViewModel()
                {
                    PId = db.ModifiedBy.PId,
                    IsStub = true
                });
            }))
            .ForMember(dst => dst.DisabledBy, opt => opt.ResolveUsing(db =>
            {
                if (db.DisabledBy == null || !db.DisabledBy.PId.HasValue)
                {
                    return(null);
                }
                return(new ViewModels.Account.UsersViewModel()
                {
                    PId = db.DisabledBy.PId.Value,
                    IsStub = true
                });
            }))
            .ForMember(dst => dst.Id, opt => opt.MapFrom(src => src.Id))
            .ForMember(dst => dst.Parent, opt => opt.ResolveUsing(db =>
            {
                if (!db.ParentId.HasValue)
                {
                    return(null);
                }
                return(new ViewModels.Matters.MatterViewModel()
                {
                    Id = db.ParentId.Value,
                    IsStub = true
                });
            }))
            .ForMember(dst => dst.MatterType, opt => opt.ResolveUsing(db =>
            {
                if (db.MatterType == null || !db.MatterType.Id.HasValue)
                {
                    return(null);
                }
                return(new ViewModels.Matters.MatterTypeViewModel()
                {
                    Id = db.MatterType.Id.Value,
                    IsStub = true
                });
            }))
            .ForMember(dst => dst.Title, opt => opt.MapFrom(src => src.Title))
            .ForMember(dst => dst.Synopsis, opt => opt.MapFrom(src => src.Synopsis))
            .ForMember(dst => dst.Active, opt => opt.MapFrom(src => src.Active))
            .ForMember(dst => dst.Jurisdiction, opt => opt.MapFrom(src => src.Jurisdiction))
            .ForMember(dst => dst.CaseNumber, opt => opt.MapFrom(src => src.CaseNumber))
            .ForMember(dst => dst.LeadAttorney, opt => opt.ResolveUsing(db =>
            {
                if (db.LeadAttorney == null || !db.LeadAttorney.Id.HasValue)
                {
                    return(null);
                }
                return(new ViewModels.Contacts.ContactViewModel()
                {
                    Id = db.LeadAttorney.Id.Value,
                    IsStub = true
                });
            }))
            .ForMember(dst => dst.BillTo, opt => opt.ResolveUsing(db =>
            {
                if (db.BillTo == null || !db.BillTo.Id.HasValue)
                {
                    return(null);
                }
                return(new ViewModels.Contacts.ContactViewModel()
                {
                    Id = db.BillTo.Id.Value,
                    IsStub = true
                });
            }))
            .ForMember(dst => dst.DefaultBillingRate, opt => opt.ResolveUsing(db =>
            {
                if (db.DefaultBillingRate == null || !db.DefaultBillingRate.Id.HasValue)
                {
                    return(null);
                }
                return(new ViewModels.Billing.BillingRateViewModel()
                {
                    Id = db.DefaultBillingRate.Id.Value,
                    IsStub = true
                });
            }))
            .ForMember(dst => dst.BillingGroup, opt => opt.ResolveUsing(db =>
            {
                if (db.BillingGroup == null || !db.BillingGroup.Id.HasValue)
                {
                    return(null);
                }
                return(new ViewModels.Billing.BillingGroupViewModel()
                {
                    Id = db.BillingGroup.Id.Value,
                    IsStub = true
                });
            }))
            .ForMember(dst => dst.OverrideMatterRateWithEmployeeRate, opt => opt.MapFrom(src => src.OverrideMatterRateWithEmployeeRate))
            .ForMember(dst => dst.Clients, opt => opt.Ignore())
            .ForMember(dst => dst.Tasks, opt => opt.Ignore())
            .ForMember(dst => dst.Notes, opt => opt.Ignore())
            .ForMember(dst => dst.TaskNotes, opt => opt.Ignore())
            .ForMember(dst => dst.MinimumCharge, opt => opt.MapFrom(src => src.MinimumCharge))
            .ForMember(dst => dst.EstimatedCharge, opt => opt.MapFrom(src => src.EstimatedCharge))
            .ForMember(dst => dst.MaximumCharge, opt => opt.MapFrom(src => src.MaximumCharge))
            .ForMember(dst => dst.NonbillableTime, opt => opt.Ignore())
            .ForMember(dst => dst.Fees, opt => opt.Ignore())
            .ForMember(dst => dst.Expenses, opt => opt.Ignore())
            .ForMember(dst => dst.TimeBilled, opt => opt.Ignore())
            .ForMember(dst => dst.MoneyBilled, opt => opt.Ignore())
            .ForMember(dst => dst.TimeBillable, opt => opt.Ignore())
            .ForMember(dst => dst.MoneyBillable, opt => opt.Ignore())
            .ForMember(dst => dst.TotalValue, opt => opt.Ignore())
            .ForMember(dst => dst.EffectiveHourlyRate, opt => opt.Ignore());

            Mapper.CreateMap <MatterViewModel, Common.Models.Matters.Matter>()
            .ForMember(dst => dst.Created, opt => opt.MapFrom(src => src.Created))
            .ForMember(dst => dst.Modified, opt => opt.MapFrom(src => src.Modified))
            .ForMember(dst => dst.Disabled, opt => opt.MapFrom(src => src.Disabled))
            .ForMember(dst => dst.CreatedBy, opt => opt.ResolveUsing(x =>
            {
                if (x.CreatedBy == null || !x.CreatedBy.PId.HasValue)
                {
                    return(null);
                }
                return(new ViewModels.Account.UsersViewModel()
                {
                    PId = x.CreatedBy.PId,
                    IsStub = true
                });
            }))
            .ForMember(dst => dst.ModifiedBy, opt => opt.ResolveUsing(x =>
            {
                if (x.CreatedBy == null || !x.CreatedBy.PId.HasValue)
                {
                    return(null);
                }
                return(new ViewModels.Account.UsersViewModel()
                {
                    PId = x.ModifiedBy.PId,
                    IsStub = true
                });
            }))
            .ForMember(dst => dst.DisabledBy, opt => opt.ResolveUsing(x =>
            {
                if (x.DisabledBy == null || !x.DisabledBy.PId.HasValue)
                {
                    return(null);
                }
                return(new ViewModels.Account.UsersViewModel()
                {
                    PId = x.DisabledBy.PId.Value,
                    IsStub = true
                });
            }))
            .ForMember(dst => dst.Id, opt => opt.MapFrom(src => src.Id))
            .ForMember(dst => dst.ParentId, opt => opt.ResolveUsing(model =>
            {
                if (model.Parent == null || !model.Parent.Id.HasValue)
                {
                    return(null);
                }
                return(model.Parent.Id.Value);
            }))
            .ForMember(dst => dst.MatterType, opt => opt.ResolveUsing(x =>
            {
                if (x.MatterType == null || !x.MatterType.Id.HasValue)
                {
                    return(null);
                }
                return(new ViewModels.Matters.MatterTypeViewModel()
                {
                    Id = x.MatterType.Id.Value,
                    IsStub = true
                });
            }))
            .ForMember(dst => dst.Title, opt => opt.MapFrom(src => src.Title))
            .ForMember(dst => dst.Synopsis, opt => opt.MapFrom(src => src.Synopsis))
            .ForMember(dst => dst.Active, opt => opt.MapFrom(src => src.Active))
            .ForMember(dst => dst.Jurisdiction, opt => opt.MapFrom(src => src.Jurisdiction))
            .ForMember(dst => dst.CaseNumber, opt => opt.MapFrom(src => src.CaseNumber))
            .ForMember(dst => dst.LeadAttorney, opt => opt.ResolveUsing(x =>
            {
                if (x.LeadAttorney == null || !x.LeadAttorney.Id.HasValue)
                {
                    return(null);
                }
                return(new ViewModels.Contacts.ContactViewModel()
                {
                    Id = x.LeadAttorney.Id.Value,
                    IsStub = true
                });
            }))
            .ForMember(dst => dst.BillTo, opt => opt.ResolveUsing(x =>
            {
                if (x.BillTo == null || !x.BillTo.Id.HasValue)
                {
                    return(null);
                }
                return(new ViewModels.Contacts.ContactViewModel()
                {
                    Id = x.BillTo.Id.Value,
                    IsStub = true
                });
            }))
            .ForMember(dst => dst.DefaultBillingRate, opt => opt.ResolveUsing(x =>
            {
                if (x.DefaultBillingRate == null || !x.DefaultBillingRate.Id.HasValue)
                {
                    return(null);
                }
                return(new ViewModels.Billing.BillingRateViewModel()
                {
                    Id = x.DefaultBillingRate.Id.Value,
                    IsStub = true
                });
            }))
            .ForMember(dst => dst.BillingGroup, opt => opt.ResolveUsing(x =>
            {
                if (x.BillingGroup == null || !x.BillingGroup.Id.HasValue)
                {
                    return(null);
                }
                return(new ViewModels.Billing.BillingGroupViewModel()
                {
                    Id = x.BillingGroup.Id.Value,
                    IsStub = true
                });
            }))
            .ForMember(dst => dst.OverrideMatterRateWithEmployeeRate, opt => opt.MapFrom(src => src.OverrideMatterRateWithEmployeeRate))
            .ForMember(dst => dst.MinimumCharge, opt => opt.MapFrom(src => src.MinimumCharge))
            .ForMember(dst => dst.EstimatedCharge, opt => opt.MapFrom(src => src.EstimatedCharge))
            .ForMember(dst => dst.MaximumCharge, opt => opt.MapFrom(src => src.MaximumCharge));
        }
예제 #57
0
 protected override void Because_of()
 {
     _destination = Mapper.Map<Destination>(new Source());
 }
        public ActionResult Post(CarpetSkuSettingsViewModel vm)
        {
            CarpetSkuSettings pt = AutoMapper.Mapper.Map<CarpetSkuSettingsViewModel, CarpetSkuSettings>(vm);


            if (ModelState.IsValid)
            {

                if (vm.CarpetSkuSettingsId <= 0)
                {
                    pt.CreatedDate = DateTime.Now;
                    pt.ModifiedDate = DateTime.Now;
                    pt.CreatedBy = User.Identity.Name;
                    pt.ModifiedBy = User.Identity.Name;
                    pt.ObjectState = Model.ObjectState.Added;
                    _CarpetSkuSettingsService.Create(pt);

                    try
                    {
                        _unitOfWork.Save();
                    }

                    catch (Exception ex)
                    {
                        string message = _exception.HandleException(ex);
                        ModelState.AddModelError("", message);
                        PrepareViewBag(vm);
                        return View("Create", vm);
                    }

                    int DocTypeId = new DocumentTypeService(_unitOfWork).Find(MasterDocTypeConstants.Carpet).DocumentTypeId;

                    LogActivity.LogActivityDetail(LogVm.Map(new ActiivtyLogViewModel
                    {
                        DocId = pt.CarpetSkuSettingsId,
                        DocTypeId = DocTypeId,
                        ActivityType = (int)ActivityTypeContants.SettingsAdded,
                    }));



                    return RedirectToAction("Index", "CarpetMaster", new { id = 0 }).Success("Data saved successfully");
                }
                else
                {
                    List<LogTypeViewModel> LogList = new List<LogTypeViewModel>();

                    CarpetSkuSettings temp = _CarpetSkuSettingsService.Find(pt.CarpetSkuSettingsId);

                    CarpetSkuSettings ExRec = Mapper.Map<CarpetSkuSettings>(temp);

                    temp.isVisibleProductDesign = vm.isVisibleProductDesign;
                    temp.isVisibleProductStyle = vm.isVisibleProductStyle;
                    temp.isVisibleProductManufacturer = vm.isVisibleProductManufacturer;
                    temp.isVisibleProductDesignPattern = vm.isVisibleProductDesignPattern;
                    temp.isVisibleContent = vm.isVisibleContent;
                    temp.isVisibleOriginCountry = vm.isVisibleOriginCountry;
                    temp.isVisibleInvoiceGroup = vm.isVisibleInvoiceGroup;
                    temp.isVisibleDrawbackTarrif = vm.isVisibleDrawbackTarrif;
                    temp.isVisibleStandardCost = vm.isVisibleStandardCost;
                    temp.isVisibleStandardWeight = vm.isVisibleStandardWeight;
                    temp.isVisibleGrossWeight = vm.isVisibleGrossWeight;
                    temp.isVisibleSupplierDetail = vm.isVisibleSupplierDetail;
                    temp.isVisibleSample = vm.isVisibleSample;
                    temp.isVisibleCounterNo = vm.isVisibleCounterNo;
                    temp.isVisibleTags = vm.isVisibleTags;
                    temp.isVisibleDivision = vm.isVisibleDivision;
                    temp.isVisibleColour = vm.isVisibleColour;
                    temp.isVisibleProductionRemark = vm.isVisibleProductionRemark;
                    temp.ProductDesignId = pt.ProductDesignId;
                    temp.OriginCountryId = pt.OriginCountryId;
                    temp.UnitConversions = pt.UnitConversions;
                    temp.PerimeterSizeTypeId = pt.PerimeterSizeTypeId;
                    temp.isVisibleCBM = pt.isVisibleCBM;
                    temp.isVisibleMapScale = pt.isVisibleMapScale;
                    temp.isVisibleTraceType = pt.isVisibleTraceType;
                    temp.isVisibleMapType = pt.isVisibleMapType;
                    temp.isVisibleStencilSize = pt.isVisibleStencilSize;
                    temp.isVisibleSalesTaxProductCode = pt.isVisibleSalesTaxProductCode;
                    temp.SalesTaxProductCodeCaption = pt.SalesTaxProductCodeCaption;
                    temp.ModifiedDate = DateTime.Now;
                    temp.ModifiedBy = User.Identity.Name;
                    temp.ObjectState = Model.ObjectState.Modified;
                    _CarpetSkuSettingsService.Update(temp);

                    LogList.Add(new LogTypeViewModel
                    {
                        ExObj = ExRec,
                        Obj = temp,
                    });

                    XElement Modifications = new ModificationsCheckService().CheckChanges(LogList);

                    try
                    {
                        _unitOfWork.Save();
                    }

                    catch (Exception ex)
                    {
                        string message = _exception.HandleException(ex);
                        ModelState.AddModelError("", message);
                        PrepareViewBag(vm);
                        return View("Create", pt);
                    }

                    int DocTypeId = new DocumentTypeService(_unitOfWork).Find(MasterDocTypeConstants.Carpet).DocumentTypeId;

                    LogActivity.LogActivityDetail(LogVm.Map(new ActiivtyLogViewModel
                    {
                        DocId = temp.CarpetSkuSettingsId,
                        ActivityType = (int)ActivityTypeContants.SettingsModified,
                        DocTypeId = DocTypeId,
                        xEModifications = Modifications,
                    }));

                    return RedirectToAction("Index", "CarpetMaster", new { id = 0 }).Success("Data saved successfully");

                }

            }
            PrepareViewBag(vm);
            return View("Create", vm);
        }
예제 #59
0
 protected override void Because_of()
 {
     var model = new ModelObject {Value = 42, Value2fff = 42, Value3 = 42, Value4 = 42, Value5 = 42};
     _result = Mapper.Map<ModelObject, ModelDto>(model);
 }
예제 #60
0
 public IEnumerable <StudentViewModel> GetAll()
 {
     return(Mapper.Map <IEnumerable <StudentViewModel> >(_studentRepository.GetAll()));
 }