public static string GetTokenString(MappingContext<QueryTokenEntity> ctx)
 {
     return ctx.Inputs.Keys
         .OrderBy(k => int.Parse(k.After("ddlTokens_")))
         .Select(k => ctx.Inputs[k])
         .TakeWhile(k => k.HasText())
         .ToString(".");
 }
Esempio n. 2
0
        public static void FromContext(this ModelStateDictionary modelState, MappingContext context)
        {
            modelState.Clear();

            if (context.GlobalErrors.Count > 0)
                foreach (var p in context.GlobalErrors)
                    foreach (var v in p.Value)
                        modelState.AddModelError(p.Key, v, context.GlobalInputs.TryGetC(p.Key));
        }
Esempio n. 3
0
        public static byte[] GetNewPassword(MappingContext<byte[]> ctx, string newPasswordKey, string newPasswordBisKey)
        {
            string newPassword = ctx.Parent.Inputs[newPasswordKey];
            if (string.IsNullOrEmpty(newPassword))
                return ctx.ParentNone(newPasswordKey, AuthMessage.PasswordMustHaveAValue.NiceToString());

            string newPasswordBis = ctx.Parent.Inputs[newPasswordBisKey];
            if (string.IsNullOrEmpty(newPasswordBis))
                return ctx.ParentNone(newPasswordBisKey, AuthMessage.YouMustRepeatTheNewPassword.NiceToString());

            if (newPassword != newPasswordBis)
                return ctx.ParentNone(newPasswordBisKey, AuthMessage.TheSpecifiedPasswordsDontMatch.NiceToString());

            return Security.EncodePassword(newPassword);
        }
Esempio n. 4
0
        /// <summary>
        /// Creates the target object.
        /// </summary>
        /// <param name="from">The value from which the mapping is executed.</param>
        /// <param name="targetType">The target type.</param>
        /// <param name="context">The context.</param>
        /// <returns>The target object.</returns>
        /// <exception cref="T:System.ArgumentNullException">The <paramref name="from" />
        /// or <paramref name="targetType" /> is null.</exception>
        public virtual object CreateTargetObject(object from, Type targetType, MappingContext context)
        {
            Error.ArgumentNullException_IfNull(from, "from");
            Error.ArgumentNullException_IfNull(targetType, "targetType");

            if (ReflectionHelper.IsAssignable(typeof(Array), targetType))
            {
                int size = from.GetType().IsArray ? ((Array)from).Length : ((IEnumerable)from).Cast<object>().Count<object>();

                return ReflectionHelper.CreateArray(targetType.GetElementType(), size);
            }
            else
            {
                if (ReflectionHelper.IsComplexEnumerable(targetType))
                {
                    return ReflectionHelper.CreateList(targetType.GetGenericArguments()[0]);
                }
                else
                {
                    return Activator.CreateInstance(targetType);
                }
            }
        }
 protected override void OnBuildMap(MappingContext mappingContext)
 {
 }
 protected override void Set(ref object instance, object value, MappingContext context)
 {
     ((IDictionary<string, object>)instance)[PropertyName] = value;
 }
Esempio n. 7
0
 public MappingDataService(MappingContext db, IMapper mapper)
 {
     _db     = db;
     _mapper = mapper;
 }
Esempio n. 8
0
        /// <summary>
        /// Wrapper to call the MappingContext
        /// </summary>
        /// <param name="dataRecord"></param>
        /// <param name="columnIndex"></param>
        /// <param name="mappingContext"></param>
        /// <returns></returns>
        protected virtual string GetAsString(IDataRecord dataRecord, int columnIndex, MappingContext mappingContext)
        {
            var value = dataRecord.GetAsString(columnIndex);

            mappingContext.OnGetAsString(dataRecord, ref value, null, columnIndex); // return type null here, expression can be a little more complex than a known type
            // TODO: see if we keep this type
            return(value);
        }
        public IEnumerable <SyntaxNode> GenerateImplementation(IMethodSymbol methodSymbol, SyntaxGenerator generator,
                                                               SemanticModel semanticModel, MappingContext mappingContext)
        {
            var mappingEngine = new MappingEngine(semanticModel, generator);
            var source        = methodSymbol.Parameters[0];
            var sourceFinder  = new ObjectMembersMappingSourceFinder(source.Type, generator.IdentifierName(source.Name), generator);
            var targets       = MappingTargetHelper.GetFieldsThaCanBeSetPrivately(methodSymbol.ContainingType, mappingContext);

            return(mappingEngine.MapUsingSimpleAssignment(targets, new SingleSourceMatcher(sourceFinder), mappingContext));
        }
Esempio n. 10
0
        internal SyntaxNode GetDefaultExpression(ITypeSymbol type, MappingContext mappingContext, MappingPath mappingPath)
        {
            if (mappingPath.AddToMapped(type) == false)
            {
                return(syntaxGenerator.DefaultExpression(type)
                       .WithTrailingTrivia(SyntaxFactory.Comment(" /* Stop recursive mapping */")));
            }

            if (SymbolHelper.IsNullable(type, out var underlyingType))
            {
                type = underlyingType;
            }


            if (type.TypeKind == TypeKind.Enum && type is INamedTypeSymbol namedTypeSymbol)
            {
                var enumOptions = namedTypeSymbol.MemberNames.Where(x => x != "value__" && x != ".ctor").OrderBy(x => x).ToList();
                if (enumOptions.Count > 0)
                {
                    return(syntaxGenerator.MemberAccessExpression(syntaxGenerator.IdentifierName(namedTypeSymbol.Name), syntaxGenerator.IdentifierName(enumOptions[0])));
                }
                return(syntaxGenerator.DefaultExpression(type));
            }

            if (type.SpecialType == SpecialType.None)
            {
                var objectCreationExpression = (ObjectCreationExpressionSyntax)syntaxGenerator.ObjectCreationExpression(type);


                if (MappingHelper.IsCollection(type))
                {
                    var isReadonlyCollection = ObjectHelper.IsReadonlyCollection(type);

                    if (type is IArrayTypeSymbol)
                    {
                        objectCreationExpression = SyntaxFactory.ObjectCreationExpression((TypeSyntax)syntaxGenerator.TypeExpression(type));
                    }
                    else if (type.TypeKind == TypeKind.Interface || isReadonlyCollection)
                    {
                        var namedType = type as INamedTypeSymbol;
                        if (namedType.IsGenericType)
                        {
                            var typeArgumentListSyntax = SyntaxFactory.TypeArgumentList(SyntaxFactory.SeparatedList(namedType.TypeArguments.Select(x => syntaxGenerator.TypeExpression(x))));
                            var newType = SyntaxFactory.GenericName(SyntaxFactory.Identifier("List"), typeArgumentListSyntax);
                            objectCreationExpression = SyntaxFactory.ObjectCreationExpression(newType, SyntaxFactory.ArgumentList(), default(InitializerExpressionSyntax));
                        }
                        else
                        {
                            var newType = SyntaxFactory.ParseTypeName("ArrayList");
                            objectCreationExpression = SyntaxFactory.ObjectCreationExpression(newType, SyntaxFactory.ArgumentList(), default(InitializerExpressionSyntax));
                        }
                    }
                    var subType = MappingHelper.GetElementType(type);
                    var initializationBlockExpressions = new SeparatedSyntaxList <ExpressionSyntax>();
                    var subTypeDefault = (ExpressionSyntax)GetDefaultExpression(subType, mappingContext, mappingPath.Clone());
                    if (subTypeDefault != null)
                    {
                        initializationBlockExpressions = initializationBlockExpressions.Add(subTypeDefault);
                    }

                    var initializerExpressionSyntax = SyntaxFactory.InitializerExpression(SyntaxKind.ObjectInitializerExpression, initializationBlockExpressions).FixInitializerExpressionFormatting(objectCreationExpression);
                    return(objectCreationExpression
                           .WithInitializer(initializerExpressionSyntax)
                           .WrapInReadonlyCollectionIfNecessary(isReadonlyCollection, syntaxGenerator));
                }

                {
                    var nt = type as INamedTypeSymbol;

                    if (nt == null)
                    {
                        var genericTypeConstraints = type.UnwrapGeneric().ToList();
                        if (genericTypeConstraints.Any() == false)
                        {
                            return(GetDefaultForUnknown(type, SyntaxFactory.ParseTypeName("object")));
                        }
                        nt = genericTypeConstraints.FirstOrDefault(x => x.TypeKind == TypeKind.Class) as INamedTypeSymbol ??
                             genericTypeConstraints.FirstOrDefault(x => x.TypeKind == TypeKind.Interface) as INamedTypeSymbol;
                    }

                    if (nt == null)
                    {
                        return(GetDefaultForUnknownType(type));
                    }

                    if (nt.TypeKind == TypeKind.Interface)
                    {
                        var implementations     = SymbolFinder.FindImplementationsAsync(type, this._document.Project.Solution).Result;
                        var firstImplementation = implementations.FirstOrDefault();
                        if (firstImplementation is INamedTypeSymbol == false)
                        {
                            return(GetDefaultForUnknownType(type));
                        }

                        nt = firstImplementation as INamedTypeSymbol;
                        objectCreationExpression = (ObjectCreationExpressionSyntax)syntaxGenerator.ObjectCreationExpression(nt);
                    }
                    else if (nt.TypeKind == TypeKind.Class && nt.IsAbstract)
                    {
                        var randomDerived = SymbolFinder.FindDerivedClassesAsync(nt, this._document.Project.Solution).Result
                                            .FirstOrDefault(x => x.IsAbstract == false);

                        if (randomDerived != null)
                        {
                            nt = randomDerived;
                            objectCreationExpression = (ObjectCreationExpressionSyntax)syntaxGenerator.ObjectCreationExpression(nt);
                        }
                    }

                    var publicConstructors    = nt.Constructors.Where(x => mappingContext.AccessibilityHelper.IsSymbolAccessible(x, nt)).ToList();
                    var hasDefaultConstructor = publicConstructors.Any(x => x.Parameters.Length == 0);
                    if (hasDefaultConstructor == false && publicConstructors.Count > 0)
                    {
                        var randomConstructor    = publicConstructors.First();
                        var constructorArguments = randomConstructor.Parameters.Select(p => GetDefaultExpression(p.Type, mappingContext, mappingPath.Clone())).ToList();
                        objectCreationExpression = (ObjectCreationExpressionSyntax)syntaxGenerator.ObjectCreationExpression(nt, constructorArguments);
                    }

                    var fields      = MappingTargetHelper.GetFieldsThaCanBeSetPublicly(nt, mappingContext);
                    var assignments = fields.Select(x =>
                    {
                        var identifier = (ExpressionSyntax)(SyntaxFactory.IdentifierName(x.Name));
                        return((ExpressionSyntax)syntaxGenerator.AssignmentStatement(identifier, this.FindMappingSource(x.Type, mappingContext, mappingPath.Clone()).Expression));
                    }).ToList();

                    if (assignments.Count == 0)
                    {
                        return(objectCreationExpression);
                    }
                    var initializerExpressionSyntax = SyntaxFactory.InitializerExpression(SyntaxKind.ObjectInitializerExpression, new SeparatedSyntaxList <ExpressionSyntax>().AddRange(assignments)).FixInitializerExpressionFormatting(objectCreationExpression);
                    return(objectCreationExpression.WithInitializer(initializerExpressionSyntax));
                }
            }


            return(GetDefaultForSpecialType(type));
        }
Esempio n. 11
0
 public ModelContext(MappingContext mappingContext, object initialContext)
 {
     MappingContext = mappingContext;
     Context        = initialContext;
 }
Esempio n. 12
0
        private static MatchedParameterList FindParametersMatch(ArgumentListSyntax invalidArgumentList,
                                                                IEnumerable <ImmutableArray <IParameterSymbol> > overloadParameterSets, SemanticModel semanticModel,
                                                                SyntaxGenerator syntaxGenerator, MappingContext mappingContext)
        {
            var sourceFinder    = CreateSourceFinderBasedOnInvalidArgument(invalidArgumentList, semanticModel, syntaxGenerator);
            var parametersMatch = MethodHelper.FindBestParametersMatch(sourceFinder, overloadParameterSets, mappingContext);

            return(parametersMatch);
        }
        public async Task <IReadOnlyList <MappingMatch> > MatchAll(IReadOnlyCollection <IObjectField> targets, SyntaxGenerator syntaxGenerator, MappingContext mappingContext, SyntaxNode globalTargetAccessor = null)
        {
            var results = new List <MappingMatch>(targets.Count);

            foreach (var target in targets)
            {
                results.Add(new MappingMatch
                {
                    Source = await sourceFinder.FindMappingSource(target.Name, target.Type, mappingContext).ConfigureAwait(false),
                    Target = CreateTargetElement(globalTargetAccessor, target, syntaxGenerator)
                });
            }

            return(results.Where(x => x.Source != null).ToList());
        }
Esempio n. 14
0
        public async override Task <DataPage <D> > ExecuteQuery <D, D1>(ICRUDRepository repo, MappingContext context, object query)
        {
            var            cQuery      = query as IWebQueryProvider;
            DataPage <DTO> pRes        = null;
            bool           hasGrouping = false;

            if (repo is IWebQueryable)
            {
                pRes        = await(repo as IWebQueryable).ExecuteQuery <DTO, DTOEXT>(cQuery);
                hasGrouping = pRes != null && pRes.Data != null && pRes.Data.Count > 0 && pRes.Data.First() is DTOEXT;
            }
            else
            {
                QueryDescription <DTO> qd = null;
                if (cQuery != null)
                {
                    qd = cQuery.Parse <DTO>();
                }

                if (qd == null)
                {
                    pRes = await
                           repo.GetPage <DTO>(null, null, 1, int.MaxValue, null);
                }
                else
                {
                    var grouping = qd.GetGrouping <DTOEXT>();
                    if (grouping == null)
                    {
                        pRes = await
                               repo.GetPage <DTO>(qd.GetFilterExpression(), qd.GetSorting(), (int)qd.Page, (int)qd.Take);
                    }
                    else
                    {
                        pRes = await
                               repo.GetPageExtended <DTO, DTOEXT>(qd.GetFilterExpression(), qd.GetSorting <DTOEXT>(), (int)qd.Page, (int)qd.Take, grouping);

                        hasGrouping = true;
                    }
                }
            }
            if (pRes == null)
            {
                return(null);
            }
            var res = new DataPage <D>()
            {
                ItemsPerPage = pRes.ItemsPerPage,
                Page         = pRes.Page,
                TotalCount   = pRes.TotalCount,
                TotalPages   = pRes.TotalPages
            };

            if (hasGrouping)
            {
                res.Data = pRes.Data.Select(m => m == null ? default(DTOEXT) : (DTOEXT)m).MapIEnumerable <DTOEXT>(context).To <D1>().Select(m => m == null ? default(D) : (D)m).ToList();
            }
            else
            {
                res.Data = pRes.Data.MapIEnumerable <DTO>(context).To <D>().ToList();
            }
            return(res);
        }
Esempio n. 15
0
 public GeneratedListMappingSource(MappingContext mappingContext, EmitHelper emitHelper, ILogger log)
 {
     _visitor          = new FluentMappingProviderBuilder(log);
     _emitHelper       = emitHelper;
     _ontologyProvider = mappingContext.OntologyProvider;
 }
 public MappingModelBuilder(MappingContext mappingContext)
 {
     _mappingContext = mappingContext;
 }
        public IEnumerable <SyntaxNode> GenerateImplementation(IMethodSymbol methodSymbol, SyntaxGenerator generator,
                                                               SemanticModel semanticModel, MappingContext mappingContext)
        {
            var mappingEngine = new MappingEngine(semanticModel, generator);
            var targetType    = methodSymbol.ReturnType;
            var sourceFinder  = new LocalScopeMappingSourceFinder(semanticModel, methodSymbol);
            var objectCreationExpressionSyntax = (ObjectCreationExpressionSyntax)generator.ObjectCreationExpression(targetType.StripNullability());
            var newExpression = mappingEngine.AddInitializerWithMapping(objectCreationExpressionSyntax, new SingleSourceMatcher(sourceFinder), targetType, mappingContext);

            return(new[] { generator.ReturnStatement(newExpression).WithAdditionalAnnotations(Formatter.Annotation) });
        }
Esempio n. 18
0
 public MappingElement FindMappingSource(string targetName, ITypeSymbol targetType, MappingContext mappingContext)
 {
     return(FindMappingSource(targetType, mappingContext, new MappingPath()));
 }
Esempio n. 19
0
        private static QTable ConvertToQTable <T>(IEnumerable <T> dataModels, Dictionary <string, PropertyInfo> propertiesDict, MappingContext cxt)
        {
            var rowCount = dataModels.Count();

            var columns         = propertiesDict.Keys.ToArray();
            var propertiesArray = propertiesDict.Values.ToArray();

            var data = new object[propertiesDict.Count];

            for (int i = 0; i < data.Length; ++i)
            {
                data[i] = Array.CreateInstance(ToQType(propertiesArray[i].PropertyType), rowCount);
            }

            int rowIndex = 0;
            var result   = new QTable(columns, data);

            foreach (var dataModel in dataModels)
            {
                for (int propIndex = 0; propIndex < propertiesArray.Length; propIndex++)
                {
                    var propInfo       = propertiesArray[propIndex];
                    var dataModelValue = cxt.TypeAccessor[dataModel, propInfo.Name];
                    ((Array)data.GetValue(propIndex)).SetValue(ToQObject(dataModelValue, propInfo), rowIndex);
                }

                rowIndex++;
            }
            return(result);
        }
        public async Task <MappingElement> FindMappingSource(string targetName, AnnotatedType targetType, MappingContext mappingContext)
        {
            foreach (var sourceFinder in sourceFinders)
            {
                var mappingElement = await sourceFinder.FindMappingSource(targetName, targetType, mappingContext).ConfigureAwait(false);

                if (mappingElement != null)
                {
                    return(mappingElement);
                }
            }

            return(null);
        }
 public MatWarehouseController(MappingContext context) : base()
 {
     this.context = context;
 }
        public async Task <IReadOnlyList <SyntaxNode> > GenerateImplementation(IMethodSymbol methodSymbol, SyntaxGenerator generator,
                                                                               SemanticModel semanticModel, MappingContext mappingContext)
        {
            var mappingEngine   = new MappingEngine(semanticModel, generator);
            var destinationType = new AnnotatedType(methodSymbol.ReturnType);
            var sourceType      = new AnnotatedType(methodSymbol.ContainingType);
            var newExpression   = await mappingEngine.MapExpression((ExpressionSyntax)generator.ThisExpression(), sourceType, destinationType, mappingContext).ConfigureAwait(false);

            return(new[] { generator.ReturnStatement(newExpression).WithAdditionalAnnotations(Formatter.Annotation) });
        }
Esempio n. 23
0
 public static MatchedParameterList FindBestParametersMatch(IMappingSourceFinder mappingSourceFinder,
                                                            IEnumerable <ImmutableArray <IParameterSymbol> > overloadParameterSets, MappingContext mappingContext)
 {
     return(overloadParameterSets.Select(x => FindArgumentsMatch(x, mappingSourceFinder, mappingContext))
            .Where(x => x.HasAnyMatch())
            .OrderByDescending(x => x.IsCompletlyMatched())
            .ThenByDescending(x => x.MatchedCount)
            .FirstOrDefault());
 }
Esempio n. 24
0
        protected virtual object GetAsObject(IDataRecord dataRecord, int columnIndex, MappingContext mappingContext)
        {
            var value = dataRecord.GetAsObject(columnIndex);

            mappingContext.OnGetAsObject(dataRecord, ref value, null, columnIndex);
            return(value);
        }
Esempio n. 25
0
        private static MatchedParameterList FindArgumentsMatch(ImmutableArray <IParameterSymbol> parameters,
                                                               IMappingSourceFinder mappingSourceFinder, MappingContext mappingContext)
        {
            var matchedArgumentList = new MatchedParameterList();

            foreach (var parameter in parameters)
            {
                var mappingSource = mappingSourceFinder.FindMappingSource(parameter.Name, parameter.Type, mappingContext);
                matchedArgumentList.AddMatch(parameter, mappingSource);
            }
            return(matchedArgumentList);
        }
 public DataListController(MappingContext db, IMapper mapper)
 {
     _service = new MappingDataService(db, mapper);
 }
 public void RebuildMappings(MappingContext mappingContext)
 {
 }
 public override object Create(IDataRecord record, MappingContext context)
 {
     return new ExpandoObject();
 }
        public async Task <IReadOnlyList <SyntaxNode> > GenerateImplementation(IMethodSymbol methodSymbol, SyntaxGenerator generator,
                                                                               SemanticModel semanticModel, MappingContext mappingContext)
        {
            foreach (var implementor in implementors)
            {
                var result = await implementor.GenerateImplementation(methodSymbol, generator, semanticModel, mappingContext).ConfigureAwait(false);

                if (result.Count > 0)
                {
                    return(result);
                }
            }

            return(Array.Empty <SyntaxNode>());
        }
Esempio n. 30
0
 protected override void OnBuildMap(MappingContext mappingContext)
 {
     mappingContext.Map<Person>()
         .ToTable("people");
     mappingContext.Map<Person>()
         .Member(person => person.Id)
         .HasName("id")
         .IsPrimaryKey();
     mappingContext.Map<Person>()
         .Member(person => person.FirstName)
         .HasName("first_name")
         .IsNotNull();
 }
Esempio n. 31
0
 public MatUnitController(MappingContext context) : base()
 {
     this.context = context;
 }
 public GenericRepository(MappingContext context)
 {
     this.context = context;
     entities     = context.Set <T>();
 }
Esempio n. 33
0
        public async Task <IReadOnlyList <SyntaxNode> > GenerateImplementation(IMethodSymbol methodSymbol, SyntaxGenerator generator,
                                                                               SemanticModel semanticModel, MappingContext mappingContext)
        {
            var mappingEngine       = new MappingEngine(semanticModel, generator);
            var source              = methodSymbol.Parameters[0];
            var sourceFinder        = new ObjectMembersMappingSourceFinder(new AnnotatedType(source.Type), generator.IdentifierName(source.Name));
            var mappingTargetHelper = new MappingTargetHelper();
            var targets             = mappingTargetHelper.GetFieldsThaCanBeSetPrivately(methodSymbol.ContainingType, mappingContext);

            return(await mappingEngine.MapUsingSimpleAssignment(targets, new SingleSourceMatcher(sourceFinder), mappingContext).ConfigureAwait(false));
        }