Example #1
0
 /// <summary>
 /// Adds class URI to the current entity's list
 /// </summary>
 public void Visit(IClassMapping classMapping)
 {
     if (!classMapping.IsInherited)
     {
         _currentClasses.Add(classMapping);
     }
 }
Example #2
0
        public void ShouldWorkWithStringConstraint()
        {
            PropertyInfo lpi = typeof(KnownRules).GetProperty("StrProp", membersBindingFlags);

            var v = new ValidationDef <KnownRules>();
            var expectedMessage = "The StrProp is too long {Max}";

            v.Define(x => x.StrProp).MaxLength(10).WithMessage(expectedMessage).And.NotNullable().And.NotEmpty();
            IClassMapping cm = ((IMappingSource)v).GetMapping();

            var mAttrs = cm.GetMemberAttributes(lpi);

            Assert.That(mAttrs.Count(), Is.EqualTo(3));
            var lengthAttribute = mAttrs.OfType <LengthAttribute>().FirstOrDefault();

            Assert.That(lengthAttribute, Is.Not.Null);
            Assert.That(lengthAttribute.Max, Is.EqualTo(10));
            Assert.That(lengthAttribute.Message, Is.EqualTo(expectedMessage));
            Assert.That(mAttrs.OfType <NotNullAttribute>().FirstOrDefault(), Is.Not.Null);
            Assert.That(mAttrs.OfType <NotEmptyAttribute>().FirstOrDefault(), Is.Not.Null);

            v = new ValidationDef <KnownRules>();
            v.Define(x => x.StrProp).NotNullable().And.IsEmail();
            cm     = ((IMappingSource)v).GetMapping();
            mAttrs = cm.GetMemberAttributes(lpi);
            Assert.That(mAttrs.OfType <EmailAttribute>().FirstOrDefault(), Is.Not.Null);
            Assert.That(mAttrs.OfType <NotNullAttribute>().FirstOrDefault(), Is.Not.Null);
        }
Example #3
0
        /// <summary>
        /// Creates a <c>HAL</c> resource using the specified state.
        /// </summary>
        /// <typeparam name="T">The source type.</typeparam>
        /// <param name="state">The state.</param>
        /// <param name="mappingConfiguration">The mapping configuration.</param>
        /// <returns>A <c>HAL</c> resource.</returns>
        public Resource <T> Create <T>(T state, IClassMapping mappingConfiguration)
        {
            var h = new Resource <T>(state);

            this.BuildLinks(h, mappingConfiguration);
            this.BuildEmbeddedResources(h);

            return(h);
        }
Example #4
0
        public void ShouldWorkWithGuid()
        {
            PropertyInfo lpi = typeof(KnownRules).GetProperty("GuidProp", membersBindingFlags);
            var          v   = new ValidationDef <KnownRules>();

            v.Define(x => x.GuidProp).NotEmpty();
            IClassMapping cm = ((IMappingSource)v).GetMapping();

            cm.GetMemberAttributes(lpi).Select(x => x.GetType()).Single().Should().Be.EqualTo <NotNullNotEmptyAttribute>();
        }
Example #5
0
 public UsersController(
     AlohaContext alohaContext,
     ISecurityService securityService,
     IClassMapping <User, UserDto> userToUserDtoMapping,
     IClassMapping <UserDto, User> userDtoToUserMapping)
 {
     this.alohaContext         = alohaContext;
     this.securityService      = securityService;
     this.userToUserDtoMapping = userToUserDtoMapping;
     this.userDtoToUserMapping = userDtoToUserMapping;
 }
Example #6
0
 public WorkstationsController(
     AlohaContext dbContext,
     IClassMapping <Workstation, WorkstationDto> workstationToWorkstationDtoMapping,
     IClassMapping <WorkstationDto, Workstation> workstationDtoToWorkstationMapping,
     IEntityUpdater <Workstation> workstationUpdater)
 {
     this.dbContext = dbContext;
     this.workstationToWorkstationDtoMapping = workstationToWorkstationDtoMapping;
     this.workstationDtoToWorkstationMapping = workstationDtoToWorkstationMapping;
     this.workstationUpdater = workstationUpdater;
 }
Example #7
0
        public void Loquacious()
        {
            var v = new ValidationDef <KnownRules>();

            v.Define(x => x.StrProp).IsNumeric();
            IClassMapping cm  = ((IMappingSource)v).GetMapping();
            PropertyInfo  lpi = typeof(KnownRules).GetProperty("StrProp");

            Assert.That(cm.GetMemberAttributes(lpi).Count(), Is.EqualTo(1));
            Assert.That(cm.GetMemberAttributes(lpi).First(), Is.InstanceOf <IsNumericAttribute>());
        }
Example #8
0
 public WorkersController(
     AlohaContext alohaContext,
     IClassMapping <Worker, WorkerDto> workerToWorkerDtoMapping,
     IClassMapping <WorkerDto, Worker> workerDtoToWorkerMapping,
     IEntityUpdater <Worker> workerUpdater,
     ISecurityService securityService)
 {
     this.alohaContext             = alohaContext;
     this.workerToWorkerDtoMapping = workerToWorkerDtoMapping;
     this.workerDtoToWorkerMapping = workerDtoToWorkerMapping;
     this.workerUpdater            = workerUpdater;
     this.securityService          = securityService;
 }
Example #9
0
 public FloorsController(
     AlohaContext dbContext,
     IClassMapping <Floor, FloorDto> floorToFloorDtoMapping,
     IClassMapping <FloorDto, Floor> floorDtoToFloorMapping,
     IClassMapping <Workstation, WorkstationDto> workstationToWorkstationDtoMapping,
     IEntityUpdater <Floor> floorUpdater)
 {
     this.dbContext = dbContext;
     this.floorToFloorDtoMapping             = floorToFloorDtoMapping;
     this.floorDtoToFloorMapping             = floorDtoToFloorMapping;
     this.workstationToWorkstationDtoMapping = workstationToWorkstationDtoMapping;
     this.floorUpdater = floorUpdater;
 }
Example #10
0
 public OfficesController(
     AlohaContext dbContext,
     IClassMapping <Office, OfficeDto> officeToOfficeDtoMapping,
     IClassMapping <OfficeDto, Office> officeDtoToOfficeMapping,
     IClassMapping <Floor, FloorDto> floorToFloorDtoMapping,
     IEntityUpdater <Office> officeUpdater)
 {
     this.dbContext = dbContext;
     this.officeToOfficeDtoMapping = officeToOfficeDtoMapping;
     this.officeDtoToOfficeMapping = officeDtoToOfficeMapping;
     this.floorToFloorDtoMapping   = floorToFloorDtoMapping;
     this.officeUpdater            = officeUpdater;
 }
 public void AddClassExternalDefinition(IClassMapping definition)
 {
     System.Type type = definition.EntityType;
     log.Debug("Adding external definition for " + type.FullName);
     try
     {
         definitions.Add(type, definition);
     }
     catch (ArgumentException)
     {
         log.Warn(string.Format(duplicationWarnMessageTemplate, type.AssemblyQualifiedName));
     }
 }
 public void AddClassExternalDefinition(IClassMapping definition)
 {
     System.Type type = definition.EntityType;
     log.Debug("Adding external definition for " + type.FullName);
     try
     {
         definitions.Add(type, definition);
     }
     catch (ArgumentException)
     {
         log.Warn(string.Format(duplicationWarnMessageTemplate, type.AssemblyQualifiedName));
     }
 }
        public void ShouldWorkCodiceFiscaleExtensions()
        {
            var          v = new ValidationDef <Cliente>();
            const string expectedMessage = "Codice fiscale non valido";

            v.Define(x => x.CodiceFiscale).IsCodiceFiscale().WithMessage(expectedMessage);
            IClassMapping cm = ((IMappingSource)v).GetMapping();
            PropertyInfo  pi = typeof(Cliente).GetProperty("CodiceFiscale", membersBindingFlags);

            Assert.That(cm.GetMemberAttributes(pi).Count(), Is.EqualTo(1));
            CodiceFiscaleAttribute first = cm.GetMemberAttributes(pi).OfType <CodiceFiscaleAttribute>().FirstOrDefault();

            Assert.That(first, Is.Not.Null);
            Assert.That(first.Message, Is.EqualTo(expectedMessage));
        }
        public IClassMapping GetClassMapping(System.Type clazz, ValidatorMode mode)
        {
            IClassMapping externalDefinition;
            IClassMapping result = null;

            switch (mode)
            {
            case ValidatorMode.UseAttribute:
                break;

            case ValidatorMode.UseExternal:
                result = GetExternalDefinitionFor(clazz);
                if (result == null)
                {
                    log.Warn(string.Format("External definition not foud for class {0} in ValidatorMode.UseExternal mode.", clazz.FullName));
                    return(null);                            // <<<<<===
                }
                break;

            case ValidatorMode.OverrideAttributeWithExternal:
                externalDefinition = GetExternalDefinitionFor(clazz);
                if (externalDefinition != null)
                {
                    log.Debug("XmlOverAttribute applied for " + clazz.FullName);
                    result = new XmlOverAttributeClassMapping(externalDefinition);
                }
                break;

            case ValidatorMode.OverrideExternalWithAttribute:
                externalDefinition = GetExternalDefinitionFor(clazz);
                if (externalDefinition != null)
                {
                    log.Debug("AttributeOverXml applied for " + clazz.FullName);
                    result = new AttributeOverXmlClassMapping(externalDefinition);
                }
                break;
            }
            if (result != null)
            {
                return(result);
            }
            else
            {
                log.Debug("Reflection applied for " + clazz.FullName);
                return(new ReflectionClassMapping(clazz));
            }
        }
Example #15
0
        public void ShouldAddPropertiesValidators()
        {
            var v = new ValidationDef <KnownRules>();

            v.Define(x => x.DtProp).IsInThePast();
            IClassMapping cm  = ((IMappingSource)v).GetMapping();
            PropertyInfo  lpi = typeof(KnownRules).GetProperty("DtProp", membersBindingFlags);

            Assert.That(cm.GetMemberAttributes(lpi).Count(), Is.EqualTo(1));
            Assert.That(cm.GetMemberAttributes(lpi).First(), Is.InstanceOf <PastAttribute>());

            var kv = new KnownRulesSimpleValidationDef();

            cm = ((IMappingSource)kv).GetMapping();
            Assert.That(cm.GetMemberAttributes(lpi).Count(), Is.EqualTo(1));
            Assert.That(cm.GetMemberAttributes(lpi).First(), Is.InstanceOf <PastAttribute>());
        }
Example #16
0
        public void ShouldAssignRuleArgsOptions()
        {
            PropertyInfo lpi      = typeof(KnownRules).GetProperty("DtProp", membersBindingFlags);
            var          v        = new ValidationDef <KnownRules>();
            string       expected = "{validator.past}";

            v.Define(x => x.DtProp).IsInThePast();
            IClassMapping cm = ((IMappingSource)v).GetMapping();

            Assert.That(cm.GetMemberAttributes(lpi).OfType <PastAttribute>().First().Message, Is.EqualTo(expected));

            v        = new ValidationDef <KnownRules>();
            expected = "The date is in the past.";
            v.Define(x => x.DtProp).IsInThePast().WithMessage(expected);
            cm = ((IMappingSource)v).GetMapping();
            Assert.That(cm.GetMemberAttributes(lpi).OfType <PastAttribute>().First().Message, Is.EqualTo(expected));
        }
Example #17
0
        public void ShouldWorkWithCollectionConstraints()
        {
            PropertyInfo lpi = typeof(KnownRules).GetProperty("ArrProp", membersBindingFlags);
            var          v   = new ValidationDef <KnownRules>();

            v.Define(x => x.ArrProp).SizeBetween(1, 9);
            IClassMapping cm     = ((IMappingSource)v).GetMapping();
            var           mAttrs = cm.GetMemberAttributes(lpi);

            Assert.That(mAttrs.Count(), Is.EqualTo(1));

            v = new ValidationDef <KnownRules>();
            v.Define(x => x.ArrProp).NotNullable().And.SizeBetween(1, 9);
            cm     = ((IMappingSource)v).GetMapping();
            mAttrs = cm.GetMemberAttributes(lpi);
            Assert.That(mAttrs.Count(), Is.EqualTo(2));
        }
Example #18
0
 public GraphService(
     WinContext winContext,
     IClassMapping <Graph, GraphDto> graphToGraphDtoMapping,
     IClassMapping <GraphDto, Graph> graphDtoToGraphMapping,
     IEntityUpdater <Graph> graphUpdater,
     IClassMapping <Concept, ConceptDto> conceptToConceptDtoMapping,
     IClassMapping <ConceptDto, Concept> conceptDtoToConceptMapping,
     IEntityUpdater <Concept> conceptUpdater
     )
 {
     this.winContext                 = winContext;
     this.graphToGraphDtoMapping     = graphToGraphDtoMapping;
     this.graphDtoToGraphMapping     = graphDtoToGraphMapping;
     this.graphUpdater               = graphUpdater;
     this.conceptToConceptDtoMapping = conceptToConceptDtoMapping;
     this.conceptDtoToConceptMapping = conceptDtoToConceptMapping;
     this.conceptUpdater             = conceptUpdater;
 }
Example #19
0
        /// <summary>
        /// Builds the resource links from the state.
        /// </summary>
        /// <typeparam name="T">The source type.</typeparam>
        /// <param name="resource">The resource.</param>
        /// <param name="mappingConfiguration">The mapping configuration.</param>
        /// <exception cref="System.UriFormatException">Invalid URI: The current request url is not valid.</exception>
        private void BuildLinks <T>(Resource <T> resource, IClassMapping mappingConfiguration)
        {
            var l = new KeyedCollection <Link>();

            if (mappingConfiguration != null)
            {
                foreach (var map in mappingConfiguration.LinkResolvers)
                {
                    Uri v;

                    if (map.Value.Resolve(resource, out v))
                    {
                        l.Add(new Link(map.Key, v));
                    }
                }

                resource.Links = l;
            }
        }
 protected void MixMembersWith(HashSet <MemberInfo> lmembers, IClassMapping mapping)
 {
     foreach (MemberInfo info in mapping.GetMembers())
     {
         lmembers.Add(info);
         IEnumerable <Attribute> mas = mapping.GetMemberAttributes(info);
         if (mas != null)
         {
             List <Attribute> attrs;
             if (!membersAttributesDictionary.TryGetValue(info, out attrs))
             {
                 membersAttributesDictionary[info] = new List <Attribute>(mas);
             }
             else
             {
                 CombineAttribute(mas, attrs);
                 membersAttributesDictionary[info] = attrs;
             }
         }
     }
 }
 protected void MixMembersWith(HashSet<MemberInfo> lmembers, IClassMapping mapping)
 {
     foreach (MemberInfo info in mapping.GetMembers())
     {
         lmembers.Add(info);
         IEnumerable<Attribute> mas = mapping.GetMemberAttributes(info);
         if (mas != null)
         {
             List<Attribute> attrs;
             if (!membersAttributesDictionary.TryGetValue(info, out attrs))
             {
                 membersAttributesDictionary[info] = new List<Attribute>(mas);
             }
             else
             {
                 CombineAttribute(mas, attrs);
                 membersAttributesDictionary[info] = attrs;
             }
         }
     }
 }
        public void ShouldWorkPartitaIvaExtensions()
        {
            const string expectedMessage = "Partita IVA non valida";
            var          v = new ValidationDef <Cliente>();

            v.Define(x => x.Piva).NotNullable().And.IsPartitaIva().WithMessage(expectedMessage);
            PropertyInfo  pi = typeof(Cliente).GetProperty("Piva", membersBindingFlags);
            IClassMapping cm = ((IMappingSource)v).GetMapping();

            Assert.That(cm.GetMemberAttributes(pi).Count(), Is.EqualTo(2));
            PartitaIvaAttribute pa = cm.GetMemberAttributes(pi).OfType <PartitaIvaAttribute>().FirstOrDefault();

            Assert.That(pa, Is.Not.Null);
            Assert.That(pa.Message, Is.EqualTo(expectedMessage));

            pi = typeof(Cliente).GetProperty("NumPiva", membersBindingFlags);
            v  = new ValidationDef <Cliente>();
            v.Define(x => x.NumPiva).IsPartitaIva().WithMessage(expectedMessage);
            cm = ((IMappingSource)v).GetMapping();
            Assert.That(cm.GetMemberAttributes(pi).Count(), Is.EqualTo(1));
            pa = cm.GetMemberAttributes(pi).OfType <PartitaIvaAttribute>().FirstOrDefault();
            Assert.That(pa, Is.Not.Null);
        }
 protected virtual void InitializeMembers(HashSet<MemberInfo> lmembers, IClassMapping baseMap, IClassMapping alternativeMap)
 {
     MixMembersWith(lmembers, baseMap);
     MixMembersWith(lmembers, alternativeMap);
 }
 protected virtual void InitializeClassAttributes(IClassMapping baseMap, IClassMapping alternativeMap)
 {
     classAttributes = new List<Attribute>();
     CombineAttribute(baseMap.GetClassAttributes(), classAttributes);
     CombineAttribute(alternativeMap.GetClassAttributes(), classAttributes);
 }
Example #25
0
 /// <inheritdoc />
 public void Visit(IClassMapping classMapping)
 {
 }
 public AttributeOverXmlClassMapping(IClassMapping externalDef)
 {
     xmlcm = externalDef;
     rcm = new ReflectionClassMapping(xmlcm.EntityType);
     clazz = xmlcm.EntityType;
 }
 /// <summary>
 /// Adds class URI to the current entity's list
 /// </summary>
 public void Visit(IClassMapping classMapping)
 {
     if (!classMapping.IsInherited)
     {
         _currentClasses.Add(classMapping);
     }
 }
Example #28
0
        /// <summary>
        /// Initialize the <see cref="ClassValidator"/> type.
        /// </summary>
        /// <param name="clazz"></param>
        /// <param name="nestedClassValidators"></param>
        private void InitValidator(System.Type clazz, IDictionary <System.Type, IClassValidator> nestedClassValidators)
        {
            entityValidators    = new List <ValidatorDef>();
            membersToValidate   = new List <Member>();
            childGetters        = new List <MemberInfo>();
            defaultInterpolator = new DefaultMessageInterpolatorAggregator();
            defaultInterpolator.Initialize(messageBundle, defaultMessageBundle, culture);

            //build the class hierarchy to look for members in
            nestedClassValidators.Add(clazz, this);
            HashSet <System.Type> classes = new HashSet <System.Type>();

            AddSuperClassesAndInterfaces(clazz, classes);

            // Create the IClassMapping for each class of the validator
            var classesMaps = new List <IClassMapping>(classes.Count);

            foreach (System.Type type in classes)
            {
                IClassMapping mapping = factory.ClassMappingFactory.GetClassMapping(type, validatorMode);
                if (mapping != null)
                {
                    classesMaps.Add(mapping);
                }
                else
                {
                    log.Warn("Validator not found in mode " + validatorMode + " for class " + clazz.AssemblyQualifiedName);
                }
            }

            //Check on all selected classes
            foreach (IClassMapping map in classesMaps)
            {
                foreach (Attribute classAttribute in map.GetClassAttributes())
                {
                    ValidateClassAtribute(classAttribute);
                }

                foreach (MemberInfo member in map.GetMembers())
                {
                    var memberAttributes = map.GetMemberAttributes(member);
                    CreateMemberAttributes(member, memberAttributes);
                    CreateChildValidator(member, memberAttributes);

                    foreach (Attribute memberAttribute in memberAttributes)
                    {
                        IValidator propertyValidator = CreateOrGetValidator(memberAttribute);

                        if (propertyValidator != null)
                        {
                            var tagable = memberAttribute as ITagableRule;
                            membersToValidate.Add(new Member
                            {
                                ValidatorDef =
                                    new ValidatorDef(propertyValidator, tagable != null ? tagable.TagCollection : null),
                                Getter = member
                            });
                        }
                    }
                }
            }
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="ValueResolverMapping{T}" /> class.
 /// </summary>
 /// <param name="classMapping">The class mapping.</param>
 /// <param name="key">The key.</param>
 public ValueResolverMapping(IClassMapping classMapping, string key)
 {
     this.classMapping = classMapping;
     this.key          = key;
 }
Example #30
0
 public EntityFieldInterceptor(IClassMapping classMapping)
 {
     this.classMapping = classMapping;
     this.entityProxyObject = new ProxyEntityObject();
 }
Example #31
0
 /// <summary>
 /// Initializes a new instance of the <see cref="LinkMapping"/> class.
 /// </summary>
 /// <param name="classMapping">The class mapping.</param>
 /// <param name="relation">The relation.</param>
 public LinkMapping(IClassMapping classMapping, string relation)
 {
     this.classMapping = classMapping;
     this.relation     = relation;
 }
Example #32
0
        private IList <object> ReadSection(Type type, StatementData dataContainer, string section,
                                           IClassMapping classMapping)
        {
            IDictionary <string, string> fieldMapper = classMapping.FieldMappings;

            var tradeSections = dataContainer.GetSectionsByName(section);

            if (tradeSections == null || !tradeSections.Any())
            {
                return(null);
            }

            IList <object> res = new List <object>();

            foreach (var tradeSection in tradeSections)
            {
                Dictionary <string, int> fieldToIndex = new Dictionary <string, int>();

                var lineIdx = 0;
                tradeSection.Lines.ForEach(tr =>
                {
                    if (tr.LineType != LineType.Data)
                    {
                        return;
                    }

                    var entity = Activator.CreateInstance(type);
                    res.Add(entity);

                    foreach (var field in fieldMapper.Keys)
                    {
                        if (!fieldToIndex.ContainsKey(field))
                        {
                            var idx             = tradeSection.Headers.IndexOf(field);
                            fieldToIndex[field] = idx;
                        }

                        var val   = "";
                        var index = fieldToIndex[field];
                        if (index >= 0)
                        {
                            val = tr.Fields[index];
                        }
                        else
                        {
                            continue;
                        }

                        if (string.IsNullOrEmpty(val))
                        {
                            continue;
                        }

                        var propertyName = fieldMapper[field];
                        var propInfo     = type.GetProperty(propertyName);
                        if (propInfo.PropertyType == typeof(string))
                        {
                            propInfo.SetValue(entity, val);
                        }
                        else
                        {
                            if (val.CanChangeType(propInfo.PropertyType))
                            {
                                object convertedValue = Convert.ChangeType(val, propInfo.PropertyType, CultureInfo.InvariantCulture);
                                propInfo.SetValue(entity, convertedValue);
                            }
                            else
                            {
                                throw new TaxCalcException($"line: {lineIdx} - field {field} value cannot be set from {val}");
                            }
                        }
                    }
                    lineIdx++;
                });
            }

            res = classMapping.Filter != null?res?.Where(classMapping.Filter.Compile()).ToList() : res;

            return(res);
        }
Example #33
0
        private IList <T> ReadSection <T>(StatementData dataContainer, string section, IClassMapping classMapping) where T : new()
        {
            var list = ReadSection(typeof(T), dataContainer, section, classMapping);

            return(list?.Select(x => (T)x).ToList());
        }
 protected virtual void InitializeMembers(HashSet <MemberInfo> lmembers, IClassMapping baseMap, IClassMapping alternativeMap)
 {
     MixMembersWith(lmembers, baseMap);
     MixMembersWith(lmembers, alternativeMap);
 }
 protected virtual void InitializeClassAttributes(IClassMapping baseMap, IClassMapping alternativeMap)
 {
     classAttributes = new List <Attribute>();
     CombineAttribute(baseMap.GetClassAttributes(), classAttributes);
     CombineAttribute(alternativeMap.GetClassAttributes(), classAttributes);
 }
 public XmlOverAttributeClassMapping(IClassMapping externalDef)
 {
     xmlcm = externalDef;
     rcm   = new ReflectionClassMapping(xmlcm.EntityType);
     clazz = xmlcm.EntityType;
 }