Ejemplo n.º 1
0
        /// <summary>
        /// Maps the specified arguments to parameters.
        /// </summary>
        /// <param name="arguments">The arguments.</param>
        /// <param name="parameters">The parameters.</param>
        /// <returns></returns>
        public MappingResult Map(IEnumerable <KeyValuePair <string, object> > arguments, IEnumerable <ArgumentInfo> parameters)
        {
            // Prepare
            var result = new MappingResult();

            if (arguments == null)
            {
                arguments = new List <KeyValuePair <string, object> >();
            }
            if (parameters == null)
            {
                parameters = new List <ArgumentInfo>();
            }

            // Map
            var mapped         = parameters.GroupJoin(arguments.DefaultIfEmpty(), x => x.Name, x => x.Key, (x, y) => new Tuple <ArgumentInfo, object>(x, y.ToList().FirstOrDefault().Value)).ToList();
            var missing        = mapped.Where(x => x.Item1.DefaultValue == null && x.Item2 == null).ToList();
            var defaultMissing = mapped.Where(x => x.Item1.DefaultValue != null && x.Item2 == null).ToList();

            result.MissingDefaultArguments = defaultMissing.Select(x => x.Item1).ToList();

            // Has missing
            if (missing.Any())
            {
                result.State            = ResultState.MissingArguments;
                result.MissingArguments = missing.Select(x => x.Item1).ToList();
                return(result);
            }

            // Result
            result.State           = ResultState.Success;
            result.ResultArguments = mapped.Select(x => DataCastUtil.Convert(x.Item2?.ToString() ?? x.Item1.DefaultValue?.ToString(), x.Item1.Type)).ToList();
            return(result);
        }
Ejemplo n.º 2
0
        protected override ISourceInfo ResolveSourceValue(MappingMemberInfo memberInfo)
        {
            var sourceValue = memberInfo.SourceInstance;

            var srcPropMap =
                memberInfo.Attributes.FirstOrDefault(x => x is MapSourcePropertyAttribute) as MapSourcePropertyAttribute;
            object        propValue = null;
            MappingResult result    = MappingResult.NotResolved;

            if (srcPropMap.Name != null && srcPropMap.Path != null)
            {
                throw new PropertyMappingException(memberInfo.Type.FullName, memberInfo.Name,
                                                   "Either Name or Path in the MapSourcePropertyAttribute should be set.");
            }


            if (!string.IsNullOrWhiteSpace(srcPropMap.Name))
            {
                return(GetPropertyByName(memberInfo, srcPropMap, sourceValue));
            }
            if (!string.IsNullOrWhiteSpace(srcPropMap.Path))
            {
                return(GetProperyByPath(srcPropMap, sourceValue));
            }
            return(null);
        }
        /// <summary>
        /// Emit the constuctor code.
        /// </summary>
        void EmitConstructor(TypeBuilder type, MappingResult result)
        {
            ConstructorBuilder constructor =
                type.DefineConstructor(MethodAttributes.Public |
                                       MethodAttributes.HideBySig |
                                       MethodAttributes.SpecialName |
                                       MethodAttributes.RTSpecialName,
                                       CallingConventions.Standard, Type.EmptyTypes);

            // Calls the constructor of the base class DataReaderMapper
            ConstructorInfo data_reader_mapper_ctor = typeof(DataReaderMapper <T>)
                                                      .GetConstructor(
                BindingFlags.Public |
                BindingFlags.NonPublic |
                BindingFlags.Instance,
                null, Type.EmptyTypes, null);
            ILGenerator il = constructor.GetILGenerator();

            il.Emit(OpCodes.Ldarg_0);                       // load "this" pointer
            il.Emit(OpCodes.Call, data_reader_mapper_ctor); // call default ctor

            // Create the array that will store the column ordinals.
            result.OrdinalsField = type
                                   .DefineField("ordinals_", typeof(int[]), FieldAttributes.Private);

            result.LoaderField = typeof(DataReaderMapper <T>)
                                 .GetField("loader_", BindingFlags.Public |
                                           BindingFlags.NonPublic |
                                           BindingFlags.Instance);

            // return from the constructor
            il.Emit(OpCodes.Ret);
        }
Ejemplo n.º 4
0
 public TenantContext(TTenant tenant, ResolutionResult resolutionResult, MappingResult mappingResult, ResolutionType resolvedType)
 {
     Tenant           = tenant;
     ResolutionResult = resolutionResult;
     MappingResult    = mappingResult;
     ResolutionType   = resolvedType;
 }
        OrdinalMap[] EmitOrdinals(ILGenerator il, MappingResult result)
        {
            ValueMap[]   fields           = result.ValueMappings;
            OrdinalMap[] ordinals_mapping = new OrdinalMap[fields.Length];

            if (fields.Length > 0)
            {
                MethodInfo get_ordinal_method =
                    Dynamics_.GetDataReaderMethod("GetOrdinal");

                il.Emit(OpCodes.Ldarg_0);
                il.Emit(OpCodes.Ldc_I4, fields.Length);
                il.Emit(OpCodes.Newarr, typeof(int));
                il.Emit(OpCodes.Stfld, result.OrdinalsField);

                for (int i = 0, j = fields.Length; i < j; i++)
                {
                    il.Emit(OpCodes.Ldarg_0);
                    il.Emit(OpCodes.Ldfld, result.OrdinalsField);
                    il.Emit(OpCodes.Ldc_I4, i);
                    il.Emit(OpCodes.Ldarg_1);
                    il.Emit(OpCodes.Ldstr, fields[i].Key);
                    il.Emit(OpCodes.Callvirt, get_ordinal_method);
                    il.Emit(OpCodes.Stelem_I4);

                    ordinals_mapping[i] =
                        new OrdinalMap(i, fields[i].Value, fields[i].RawType)
                    {
                        Conversor = fields[i].Conversor
                    };
                }
            }
            return(ordinals_mapping);
        }
        private void LogError(string message, ODM2ConverterSourceLocation location)
        {
            var resultLevel = ResultLevel.ERROR;
            var result      = new MappingResult(resultLevel, message, location);

            _iResults.Add(result);
        }
Ejemplo n.º 7
0
        protected void Configure(PatcheetahConfig config)
        {
            config.EnableNestedPatching();
            config.EnableAttributes();
            config.SetPrePatchProcessingFunction(context =>
            {
                if (context.NewValue is int age && age == 0)
                {
                    return(18);
                }

                return(context.NewValue);
            });
            config
            .ConfigureEntity <User>()
            .UseMapping(x => x.Username, x =>
            {
                if (x == "convertme")
                {
                    return(MappingResult.MapTo($"{x}_1"));
                }

                return(MappingResult.Skip(x));
            })
            // .Required(x => x.LastSeenFrom) -> we don't need this anymore. Instead of method setup, we'll install it from attribute
            // .IgnoreOnPatching(x => x.Username) -> Same situation, let's install it from attribute
            .SetKey(x => x.Username);     // Set login as key but replace it by id from attributes
        }
Ejemplo n.º 8
0
        public static void WriteJson(this MappingResult value, Utf8JsonWriter writer)
        {
            switch (value)
            {
            case MappingResult.NotParsable: JsonSerializer.Serialize(writer, "notParsable"); break;

            case MappingResult.Success: JsonSerializer.Serialize(writer, "success"); break;

            case MappingResult.TitleNotFound: JsonSerializer.Serialize(writer, "titleNotFound"); break;
            }
        }
Ejemplo n.º 9
0
        private static MappingResult FindProp(Dictionary <string, MappingResult> map, string propName)
        {
            MappingResult retVal = null;

            foreach (string name in map.Keys)
            {
                if (name.Equals(propName, StringComparison.InvariantCultureIgnoreCase))
                {
                    retVal = map[name];
                    break;
                }
            }

            return(retVal);
        }
Ejemplo n.º 10
0
        private static void RegisterMapProp <T>(string entityName, MappingResult iCalName)
        {
            List <Dictionary <string, MappingResult> > map;

            if (!_mappingDef.TryGetValue(typeof(T), out map))
            {
                map = new List <Dictionary <string, MappingResult> >();
                map.Add(new Dictionary <string, MappingResult>());
                map.Add(new Dictionary <string, MappingResult>());
                _mappingDef.Add(typeof(T), map);
            }
            Dictionary <string, MappingResult> entity2iCal = map[0];
            Dictionary <string, MappingResult> iCal2Entity = map[1];

            entity2iCal.Add(entityName, iCalName);
            iCal2Entity.Add(iCalName.Name, new MappingResult(entityName, iCalName.ValueType));
        }
        void GetMappings(PropertyInfo[] properties, MappingResult result)
        {
            List <ValueMap> value_mappings =
                new List <ValueMap>(properties.Length);
            List <ConstantMap> const_mappings =
                new List <ConstantMap>(properties.Length);

            for (int i = 0, j = properties.Length; i < j; i++)
            {
                PropertyInfo property = properties[i];
                ITypeMap     mapping;

                // If a custom  map was not defined, maps to the name of the property
                // if auto map is enabled, ignoring if not.
                if (!mappings_.TryGetValue(property.Name, out mapping))
                {
                    mapping = auto_map_
            ? (ITypeMap) new StringTypeMap(property.Name)
            : new IgnoreMapType(property.Name);
                }

                if (mapping.MapType == TypeMapType.Ignore || IsReferenceType(property))
                {
                    mapping = new IgnoreMapType(GetDefaultValue(property.PropertyType));
                    const_mappings.Add(new ConstantMap(mapping, property));
                }
                else if (mapping.MapType == TypeMapType.String)
                {
                    var map = mapping as StringTypeMap;
                    value_mappings.Add(
                        new ValueMap((string)map.Value, property, map.RawType)
                    {
                        Conversor = map.Conversor
                    });
                }
                else
                {
                    const_mappings.Add(new ConstantMap(mapping, property));
                }
            }
            result.ValueMappings    = value_mappings.ToArray();
            result.ConstantMappings = const_mappings.ToArray();
        }
        /// <summary>
        /// Generates the dynamic type for <typeparamref source="T"/>.
        /// </summary>
        /// <returns>
        /// The dynamic type for <typeparamref source="T"/>.
        /// </returns>
        /// <remarks>
        /// The type is dynamically created and added to the current
        /// <see cref="AppDomain"/>.
        /// </remarks>
        Type MakeDynamicType(string dynamic_type_name)
        {
            TypeBuilder builder;

            try {
                builder = Dynamics_.ModuleBuilder.DefineType(
                    dynamic_type_name,
                    TypeAttributes.Public |
                    TypeAttributes.Class |
                    TypeAttributes.AutoClass |
                    TypeAttributes.AutoLayout,
                    typeof(DataReaderMapper <T>),
                    new Type[] {
                    typeof(IDataReaderMapper <T>)
                });
            } catch (ArgumentException) {
                // Check if the type was created by another thread.
                Type type = Dynamics_.ModuleBuilder.GetType(dynamic_type_name);
                if (type == null)
                {
                    throw;
                }
                return(type);
            }

            PropertyInfo[] properties = GetProperties();

            MappingResult result = new MappingResult();

            // Get the mappings for the properties that return value types.
            GetMappings(properties, result);

            EmitConstructor(builder, result);
            EmitGetOrdinals(builder, result);
            //EmitConversors(builder, result);
            EmitNewT(builder);
            EmitMapMethod(builder, result);

            OnPreCreateType(builder);

            return(builder.CreateType());
        }
Ejemplo n.º 13
0
        public MappingResult <MappedPart> MapItem(LddPart source)
        {
            var result = new MappingResult <MappedPart>();
            var mapped = new MappedPart();

            var itemDetails = GetPart(source);

            if (itemDetails == null)
            {
                result.WasSuccessful = false;
                result.Message       = string.Format("Unable to locate part mapping.");
                return(result);
            }

            mapped.ItemId = itemDetails.ItemId;

            var colorId = GetColorId(source);

            if (!colorId.HasValue)
            {
                result.WasSuccessful = false;
                result.Message       = string.Format("Unable to locate color mapping.");
                return(result);
            }

            mapped.ColorId = colorId.Value;

            if (!string.IsNullOrWhiteSpace(source.Decoration) && source.Decoration != "0")
            {
                result.WasSuccessful = false;
                result.Message       = string.Format("Decorated elements are not currently supported.");
                return(result);
            }

            result.Mapped        = mapped;
            result.WasSuccessful = true;

            return(result);
        }
Ejemplo n.º 14
0
        public void Setup()
        {
            ParseMovieTitle();

            _pass1 = new Mock <IDecisionEngineSpecification>();
            _pass2 = new Mock <IDecisionEngineSpecification>();
            _pass3 = new Mock <IDecisionEngineSpecification>();

            _fail1 = new Mock <IDecisionEngineSpecification>();
            _fail2 = new Mock <IDecisionEngineSpecification>();
            _fail3 = new Mock <IDecisionEngineSpecification>();

            _pass1.Setup(c => c.IsSatisfiedBy(It.IsAny <RemoteMovie>(), null)).Returns(Decision.Accept);
            _pass2.Setup(c => c.IsSatisfiedBy(It.IsAny <RemoteMovie>(), null)).Returns(Decision.Accept);
            _pass3.Setup(c => c.IsSatisfiedBy(It.IsAny <RemoteMovie>(), null)).Returns(Decision.Accept);

            _fail1.Setup(c => c.IsSatisfiedBy(It.IsAny <RemoteMovie>(), null)).Returns(Decision.Reject("fail1"));
            _fail2.Setup(c => c.IsSatisfiedBy(It.IsAny <RemoteMovie>(), null)).Returns(Decision.Reject("fail2"));
            _fail3.Setup(c => c.IsSatisfiedBy(It.IsAny <RemoteMovie>(), null)).Returns(Decision.Reject("fail3"));

            _reports = new List <ReleaseInfo> {
                new ReleaseInfo {
                    Title = "Trolls.2016.720p.WEB-DL.DD5.1.H264-FGT"
                }
            };
            _remoteEpisode = new RemoteMovie
            {
                Movie           = new Movie(),
                ParsedMovieInfo = new ParsedMovieInfo()
            };

            _mappingResult = new MappingResult {
                Movie = new Movie(), MappingResultType = MappingResultType.Success
            };
            _mappingResult.RemoteMovie = _remoteEpisode;

            Mocker.GetMock <IParsingService>()
            .Setup(c => c.Map(It.IsAny <ParsedMovieInfo>(), It.IsAny <string>(), It.IsAny <SearchCriteriaBase>())).Returns(_mappingResult);
        }
 private TenantMapResult(MappingResult mappingResult)
 {
     MappingResult = mappingResult;
     Value         = default;
     ErrorMessage  = "";
 }
Ejemplo n.º 16
0
        public async Task Invoke(HttpContext httpContext, ITenantResolverService tenantResolverService, ITenantMapperService <TTenantMapping> tenantMapperService,
                                 ITenantInfoService <TTenant> tenantInfoService)
        {
            TenantContext <TTenant> _tenantContext = null;

            TenantResolveResult _tenantResolveResult          = null;
            TenantMapResult <TTenantMapping> _tenantMapResult = null;

            TTenant        _tenant        = default;
            TTenantMapping _tenantMapping = default;

            ResolutionResult _resolutionResult = ResolutionResult.NotFound;
            MappingResult    _mappingResult    = MappingResult.NotFound;
            ResolutionType   _resolutionType   = ResolutionType.Nothing;

            string _tenantResolvedData = "";

            _tenantResolveResult = await tenantResolverService.ResolveTenantAsync(httpContext);

            _resolutionResult = _tenantResolveResult.ResolutionResult;

            switch (_resolutionResult)
            {
            case ResolutionResult.Success:

                _resolutionType     = _tenantResolveResult.ResolutionType;
                _tenantResolvedData = _tenantResolveResult.Value;

                switch (_resolutionType)
                {
                case ResolutionType.TenantId:
                    _mappingResult = MappingResult.NotApply;
                    break;

                case ResolutionType.TenantName:
                    _mappingResult = MappingResult.Success;
                    break;
                }

                break;

            case ResolutionResult.NotApply:

                _mappingResult      = MappingResult.NotApply;
                _tenantResolvedData = "";
                break;

            case ResolutionResult.NotFound:

                _mappingResult      = MappingResult.NotFound;
                _tenantResolvedData = "";
                break;

            case ResolutionResult.Error:

                _mappingResult      = MappingResult.Error;
                _tenantResolvedData = "";
                break;
            }

            if (_resolutionResult == ResolutionResult.Success)
            {
                if (_mappingResult != MappingResult.NotApply) //if applies mapping call mapping service
                {
                    _tenantMapResult = await tenantMapperService.MapTenantAsync(_tenantResolveResult.Value);

                    _mappingResult = _tenantMapResult.MappingResult;

                    switch (_mappingResult)
                    {
                    case MappingResult.Success:

                        _tenantMapping      = _tenantMapResult.Value;
                        _tenantResolvedData = _tenantMapping.TenantId;

                        break;

                    case MappingResult.NotFound:

                        _tenantResolvedData = "";
                        _resolutionResult   = ResolutionResult.NotFound;
                        _resolutionType     = ResolutionType.Nothing;

                        break;

                    case MappingResult.Error:

                        _tenantResolvedData = "";
                        _resolutionResult   = ResolutionResult.Error;
                        _resolutionType     = ResolutionType.Nothing;

                        break;
                    }
                }

                //at this point it must be the id
                if (!string.IsNullOrWhiteSpace(_tenantResolvedData))
                {
                    _tenant = await tenantInfoService.GetTenantInfoAsync(_tenantResolvedData);
                }
            }

            _tenantContext = new TenantContext <TTenant>(_tenant, _resolutionResult, _mappingResult, _resolutionType);

            httpContext.SetTenantContext(_tenantContext);

            await _next(httpContext);
        }
Ejemplo n.º 17
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="offset">Offset</param>
 /// <param name="mapping">Mapping flags</param>
 public ILFrameIP(uint offset, MappingResult mapping)
 {
     this.offset = offset;
     this.mapping = mapping;
 }
Ejemplo n.º 18
0
        private IEnumerable <DownloadDecision> GetMovieDecisions(List <ReleaseInfo> reports, SearchCriteriaBase searchCriteria = null)
        {
            if (reports.Any())
            {
                _logger.ProgressInfo("Processing {0} releases", reports.Count);
            }

            else
            {
                _logger.ProgressInfo("No results found");
            }

            var reportNumber = 1;

            foreach (var report in reports)
            {
                DownloadDecision decision = null;
                _logger.ProgressTrace("Processing release {0}/{1}", reportNumber, reports.Count);

                try
                {
                    var parsedMovieInfo = _parsingService.ParseMovieInfo(report.Title, new List <object> {
                        report
                    });

                    MappingResult result = null;

                    if (parsedMovieInfo == null || parsedMovieInfo.MovieTitle.IsNullOrWhiteSpace())
                    {
                        _logger.Debug("{0} could not be parsed :(.", report.Title);
                        parsedMovieInfo = new ParsedMovieInfo
                        {
                            MovieTitle = report.Title,
                            Year       = 1290,
                            Languages  = new List <Language> {
                                Language.Unknown
                            },
                            Quality = new QualityModel(),
                        };

                        if (_configService.ParsingLeniency == ParsingLeniencyType.MappingLenient)
                        {
                            result = _parsingService.Map(parsedMovieInfo, report.ImdbId.ToString(), searchCriteria);
                        }

                        if (result == null || result.MappingResultType != MappingResultType.SuccessLenientMapping)
                        {
                            result = new MappingResult {
                                MappingResultType = MappingResultType.NotParsable
                            };
                            result.Movie = null; //To ensure we have a remote movie, else null exception on next line!
                            result.RemoteMovie.ParsedMovieInfo = parsedMovieInfo;
                        }
                        else
                        {
                            //Enhance Parsed Movie Info!
                            result.RemoteMovie.ParsedMovieInfo = Parser.Parser.ParseMinimalMovieTitle(parsedMovieInfo.MovieTitle,
                                                                                                      result.RemoteMovie.Movie.Title, parsedMovieInfo.Year);
                        }
                    }
                    else
                    {
                        result = _parsingService.Map(parsedMovieInfo, report.ImdbId.ToString(), searchCriteria);
                    }

                    result.ReleaseName = report.Title;
                    var remoteMovie = result.RemoteMovie;

                    remoteMovie.Release       = report;
                    remoteMovie.MappingResult = result.MappingResultType;

                    if (result.MappingResultType != MappingResultType.Success && result.MappingResultType != MappingResultType.SuccessLenientMapping)
                    {
                        var rejection = result.ToRejection();
                        decision = new DownloadDecision(remoteMovie, rejection);
                    }
                    else
                    {
                        if (parsedMovieInfo.Quality.HardcodedSubs.IsNotNullOrWhiteSpace())
                        {
                            //remoteMovie.DownloadAllowed = true;
                            if (_configService.AllowHardcodedSubs)
                            {
                                decision = GetDecisionForReport(remoteMovie, searchCriteria);
                            }
                            else
                            {
                                var whitelisted = _configService.WhitelistedHardcodedSubs.Split(',');
                                _logger.Debug("Testing: {0}", whitelisted);
                                if (whitelisted != null && whitelisted.Any(t => (parsedMovieInfo.Quality.HardcodedSubs.ToLower().Contains(t.ToLower()) && t.IsNotNullOrWhiteSpace())))
                                {
                                    decision = GetDecisionForReport(remoteMovie, searchCriteria);
                                }
                                else
                                {
                                    decision = new DownloadDecision(remoteMovie, new Rejection("Hardcoded subs found: " + parsedMovieInfo.Quality.HardcodedSubs));
                                }
                            }
                        }
                        else
                        {
                            //remoteMovie.DownloadAllowed = true;
                            decision = GetDecisionForReport(remoteMovie, searchCriteria);
                        }
                    }
                }
                catch (Exception e)
                {
                    _logger.Error(e, "Couldn't process release.");

                    var remoteMovie = new RemoteMovie {
                        Release = report
                    };
                    decision = new DownloadDecision(remoteMovie, new Rejection("Unexpected error processing release"));
                }

                reportNumber++;

                if (decision != null)
                {
                    if (decision.Rejections.Any())
                    {
                        _logger.Debug("Release rejected for the following reasons: {0}", string.Join(", ", decision.Rejections));
                    }

                    else
                    {
                        _logger.Debug("Release accepted");
                    }

                    yield return(decision);
                }
            }
        }
        void EmitGetOrdinals(TypeBuilder type, MappingResult result)
        {
            MethodBuilder builder = type
                                    .DefineMethod("GetOrdinals",
                                                  MethodAttributes.Assembly | MethodAttributes.HideBySig |
                                                  MethodAttributes.Virtual, typeof(void),
                                                  new Type[] { typeof(IDataReader) });

            ILGenerator il = builder.GetILGenerator();

            // If there is nothing to be mapped, map nothing.
            if (result.ValueMappings.Length == 0)
            {
                // Create an empty array to prevent the NoResultException to be throw
                // by the Map method.
                il.Emit(OpCodes.Ldarg_0);
                il.Emit(OpCodes.Ldc_I4_0);
                il.Emit(OpCodes.Newarr, typeof(int));
                il.Emit(OpCodes.Stfld, result.OrdinalsField);

                result.OrdinalsMapping = new OrdinalMap[0];
            }
            else
            {
                // check if the ordinals is not already got.
                il.Emit(OpCodes.Ldarg_0);
                il.Emit(OpCodes.Ldfld, result.OrdinalsField);
                il.Emit(OpCodes.Ldnull);
                il.Emit(OpCodes.Ceq);

                Label label = il.DefineLabel();
                il.Emit(OpCodes.Brtrue_S, label);
                il.Emit(OpCodes.Ret);
                il.MarkLabel(label);

                // get the columns ordinals, using a try/catch block to prevent a
                // InvalidOperationException to be throw when no recordset is returned.
                il.BeginExceptionBlock();

                result.OrdinalsMapping = EmitOrdinals(il, result);

                //il.Emit(OpCodes.Leave, exit_try_label);
                il.BeginCatchBlock(typeof(InvalidOperationException));

                // remove the exception from the stack
                il.Emit(OpCodes.Pop);

                // set [ordinals_] to null
                il.Emit(OpCodes.Ldarg_0);
                il.Emit(OpCodes.Ldnull);
                il.Emit(OpCodes.Stfld, result.OrdinalsField);
                il.EndExceptionBlock();
            }

            /*MethodInfo method_info =
             *  typeof (DataReaderMapper<T>).GetMethod("Initialize",
             *    BindingFlags.NonPublic | BindingFlags.Public |
             *      BindingFlags.Instance,
             *    null, new Type[] {typeof (IDataReader)}, null);*/

            il.Emit(OpCodes.Ret);
        }
        void EmitMapMethod(TypeBuilder type, MappingResult result)
        {
            MethodBuilder builder = type
                                    .DefineMethod("MapInternal",
                                                  MethodAttributes.Public | MethodAttributes.HideBySig |
                                                  MethodAttributes.Virtual, typeof(T),
                                                  new Type[] { typeof(IDataReader) });

            // define that the method is allowed to acess non-public members.

            /*Type permission = typeof(ReflectionPermissionAttribute);
             * ConstructorInfo ctor =
             * permission
             *  .GetConstructor(new[] { typeof(SecurityAction) });
             * PropertyInfo access = permission.GetProperty("Flags");
             * var reflection_permission_attribute =
             * new CustomAttributeBuilder(ctor, new object[] { SecurityAction.Demand },
             *  new[] { access },
             *  new object[] {
             *    ReflectionPermissionFlag.MemberAccess |
             *      ReflectionPermissionFlag.RestrictedMemberAccess
             *  });
             *
             * builder.SetCustomAttribute(reflection_permission_attribute);*/
            ILGenerator il = builder.GetILGenerator();

            // Create a new instance of the T using the associated class loader and
            // stores in a local variable.
            il.DeclareLocal(type_t_);
            MethodInfo callable = typeof(CallableDelegate <T>).GetMethod("Invoke");

            il.Emit(OpCodes.Ldarg_0);
            il.Emit(OpCodes.Ldfld, result.LoaderField);
            il.Emit(OpCodes.Callvirt, callable);
            il.Emit(OpCodes.Stloc_0);

            // Set the value of the properties of the newly created T object.
            OrdinalMap[] fields = result.OrdinalsMapping;
            for (int i = 0, j = fields.Length; i < j; i++)
            {
                OrdinalMap   field    = fields[i];
                int          ordinal  = field.Key;
                PropertyInfo property = field.Value;

                MethodInfo get_x_method =
                    Dynamics_.GetDataReaderMethod(
                        Dynamics_.GetDataReaderMethodName(field.RawType ??
                                                          property.PropertyType), data_reader_type_);

                // Get the set method of the current property. If the property does
                // not have a set method ignores it.
                MethodInfo set_x_property = property.GetSetMethod(true);
                if (set_x_property == null)
                {
                    throw new ArgumentException(
                              "The property {0} does not have a set method.".Fmt(property.Name));
                }

                // loaded the "data transfer object"
                il.Emit(OpCodes.Ldloc_0);

                // if the conversor method is defined we need to load the
                // "this" pointer onto the stack before the data reader, so we can
                // chain the conversion method call after the value is retrieved
                // from the data reader.
                MethodInfo conversor = null;
                if (field.Conversor != null)
                {
                    conversor = (field.Conversor.Body as MethodCallExpression).Method;
                    if (!conversor.IsStatic || !conversor.IsPublic)
                    {
                        throw new ArgumentException(
                                  "The \"conversor\" method of the property {0} is not static or public"
                                  .Fmt(property.Name));
                    }
                }

                // loads the data reader
                il.Emit(OpCodes.Ldarg_1);

                // load the ordinals_ array
                il.Emit(OpCodes.Ldarg_0);
                il.Emit(OpCodes.Ldfld, result.OrdinalsField);

                // load the element of the array at |ordinal| position
                EmitLoad(il, ordinal);
                il.Emit(OpCodes.Ldelem_I4);

                // call the "get...(int i)" method of the datareader
                //   -> i will be equals to the element loaded from the
                //      array at positiom "ordinal"
                il.Emit(OpCodes.Callvirt, get_x_method);

                // the stack now contains the returned value of "get...(int i)"
                // method.

                // convert the result of get method and...
                if (conversor != null)
                {
                    il.Emit(OpCodes.Call, conversor);
                }

                // store it on the loaded field.
                il.Emit(OpCodes.Callvirt, set_x_property);
            }

            ConstantMap[] constant_maps = result.ConstantMappings;
            for (int i = 0, j = constant_maps.Length; i < j; i++)
            {
                ITypeMap     map      = constant_maps[i].Key;
                PropertyInfo property = constant_maps[i].Value;
                if (map.MapType != TypeMapType.Ignore)
                {
                    // Get the set method of the current property. If the property does
                    // not have a set method ignores it.
                    MethodInfo set_x_property = property.GetSetMethod(true);
                    if (set_x_property == null)
                    {
                        continue;
                    }

                    il.Emit(OpCodes.Ldloc_0);
                    EmitLoad(il, map);
                    il.Emit(OpCodes.Callvirt, set_x_property);
                }
            }

            // load the local T and return.
            il.Emit(OpCodes.Ldloc_0);
            il.Emit(OpCodes.Ret);
        }
Ejemplo n.º 21
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="offset">Offset</param>
 /// <param name="mapping">Mapping flags</param>
 public ILFrameIP(uint offset, MappingResult mapping)
 {
     this.Offset  = offset;
     this.Mapping = mapping;
 }
Ejemplo n.º 22
0
		/// <summary>
		/// Constructor
		/// </summary>
		/// <param name="offset">Offset</param>
		/// <param name="mapping">Mapping flags</param>
		public ILFrameIP(uint offset, MappingResult mapping) {
			Offset = offset;
			Mapping = mapping;
		}
Ejemplo n.º 23
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="offset">Offset</param>
 /// <param name="mapping">Mapping flags</param>
 public ILFrameIP(uint offset, MappingResult mapping)
 {
     Offset  = offset;
     Mapping = mapping;
 }