Example #1
0
        private static string GetMapping(ParameterMapping mapping, bool filterRequired = false)
        {
            string inputPath = mapping.InputParameter.Name;

            if (mapping.InputParameterProperty != null)
            {
                inputPath += "." + CodeNamer.Instance.CamelCase(mapping.InputParameterProperty) + "()";
            }
            if (filterRequired && !mapping.InputParameter.IsRequired)
            {
                inputPath = "null";
            }

            string outputPath = "";

            if (mapping.OutputParameterProperty != null)
            {
                outputPath += ".with" + CodeNamer.Instance.PascalCase(mapping.OutputParameterProperty);
                return(string.Format(CultureInfo.InvariantCulture, "{0}({1})", outputPath, inputPath));
            }
            else
            {
                return(string.Format(CultureInfo.InvariantCulture, "{0} = {1}", outputPath, inputPath));
            }
        }
Example #2
0
        private static ParameterMapping ReadParameterMapping(XmlReader reader)
        {
            System.Diagnostics.Debug.Assert(reader.NodeType == XmlNodeType.Element);
            if (!IsInNamespace(reader) || reader.LocalName != XmlMappingConstant.Parameter)
            {
                throw Error.UnexpectedElement(XmlMappingConstant.Parameter, String.Format(System.Globalization.CultureInfo.InvariantCulture, "{0}{1}{2}", reader.Prefix, String.IsNullOrEmpty(reader.Prefix) ? "" : "/", reader.LocalName));
            }

            ValidateAttributes(reader, new[] {
                XmlMappingConstant.Name,
                XmlMappingConstant.DbType,
                XmlMappingConstant.Parameter,
                XmlMappingConstant.Direction
            });

            ParameterMapping pm = new ParameterMapping();

            pm.Name          = RequiredAttribute(reader, XmlMappingConstant.Name);
            pm.ParameterName = RequiredAttribute(reader, XmlMappingConstant.Parameter);
            pm.DbType        = OptionalAttribute(reader, XmlMappingConstant.DbType);
            pm.XmlDirection  = OptionalAttribute(reader, XmlMappingConstant.Direction);

            AssertEmptyElement(reader);

            return(pm);
        }
Example #3
0
        /// <exception cref="System.TypeLoadException" />
        /// <exception cref="System.MemberAccessException" />
        /// <exception cref="System.Reflection.TargetInvocationException" />
        private void LoadFunctions(XmlElement root)
        {
            var        list = root.GetElementsByTagName("function");
            XmlNode    node = null;
            XmlElement e    = null;

            for (int i = 0, n = list.Count; i < n; i++)
            {
                node = list.Item(i);
                if (node.NodeType == XmlNodeType.Element)
                {
                    e = (XmlElement)node;
                    var name = e.GetAttribute("name");
                    if (functions.ContainsKey(name))
                    {
                        throw new ConfigException("rule function " + name + " duplicated!");
                    }
                    var clazz    = e.GetAttribute("class");
                    var function = CreateFunction(name, clazz);

                    ParameterMapping.Mapping(function, ConfigUtil.LoadElements(e));

                    functions[name] = function;
                }
            }
        }
 private void AddSimpleHiddenMapping(ParameterMapping mapping, ParameterInfo info, bool prohibitNull)
 {
     mapping.AddBuilder(new SimpleArgBuilder(info, info.ParameterType, mapping.ArgIndex, false, false));
     mapping.AddParameter(new ParameterWrapper(info, info.ParameterType, null,
                                               ParameterBindingFlags.IsHidden | (prohibitNull ? ParameterBindingFlags.ProhibitNull : 0)
                                               ));
 }
Example #5
0
        /// <summary>
        /// Create a factory generator.
        /// </summary>
        /// <param name="service">The service that will be activated in
        /// order to create the products of the factory.</param>
        /// <param name="delegateType">The delegate to provide as a factory.</param>
        /// <param name="parameterMapping">The parameter mapping mode to use.</param>
        public FactoryGenerator(Type delegateType, Service service, ParameterMapping parameterMapping)
        {
            if (service == null)
            {
                throw new ArgumentNullException("service");
            }
            Enforce.ArgumentTypeIsFunction(delegateType);

            _generator = CreateGenerator((activatorContextParam, resolveParameterArray) =>
            {
                // c, service, [new Parameter(name, (object)dps)]*
                var resolveParams = new[] {
                    activatorContextParam,
                    Expression.Constant(service, typeof(Service)),
                    Expression.NewArrayInit(typeof(Parameter), resolveParameterArray)
                };

                // c.Resolve(...)
                return(Expression.Call(
                           ReflectionExtensions.GetMethod <IComponentContext>(cc => cc.ResolveService(default(Service), default(Parameter[]))),
                           resolveParams));
            },
                                         delegateType,
                                         GetParameterMapping(delegateType, parameterMapping));
        }
Example #6
0
        internal static IEnumerable <Parameter> GetParameterCollection <TDelegate>(this ParameterMapping mapping, params object[] param)
        {
            IEnumerable <Parameter> parameterCollection;

            switch (mapping)
            {
            case ParameterMapping.ByType:
                parameterCollection = param.Select(x => (Parameter) new TypedParameter(x.GetType(), x));
                break;

            case ParameterMapping.ByName:
            {
                var parameterInfo = typeof(TDelegate).GetMethods().First().GetParameters();
                parameterCollection = new List <Parameter>();
                for (var i = 0; i < param.Length; i++)
                {
                    ((IList <Parameter>)parameterCollection).Add(new NamedParameter(parameterInfo[i].Name, param[i]));
                }
            }
            break;

            case ParameterMapping.ByPosition:
                parameterCollection = new List <Parameter>();
                for (var i = 0; i < param.Length; i++)
                {
                    ((IList <Parameter>)parameterCollection).Add(new PositionalParameter(i, param[i]));
                }
                break;

            default:
                throw new NotSupportedException("Parameter mapping not supported");
            }

            return(parameterCollection);
        }
        private static string GetMapping(ParameterMapping mapping, bool filterRequired = false)
        {
            string inputPath = mapping.InputParameter.Name;

            if (mapping.InputParameterProperty != null)
            {
                inputPath += "." + CodeNamer.Instance.CamelCase(mapping.InputParameterProperty) + "()";
            }
            if (filterRequired && !mapping.InputParameter.IsRequired)
            {
                inputPath = "nil";
            }

            var outputPath = "";

            if (mapping.OutputParameterProperty != null)
            {
                outputPath += "." + mapping.OutputParameterProperty;
                return($"{outputPath} = {inputPath}");
            }
            else
            {
                return($"{outputPath} = {inputPath}");
            }
        }
            public override IReadOnlyCollection <ParameterMapping> ProvideParameterMapping(System.Reflection.MethodInfo methodInfo)
            {
                List <ParameterMapping> mapping = new List <ParameterMapping>();

                var email = methodInfo.GetParameters()[0];

                var from = new ParameterMapping("from");

                mapping.Add(from);
                from.AddSource(email, (EmailChange e) => e.From);

                var to = new ParameterMapping("to");

                to.AddSource(email, (EmailChange e) => e.To);
                mapping.Add(to);

                var when = new ParameterMapping("when");

                when.AddSource(email, (EmailChange e) => e.When);
                mapping.Add(when);

                var domain = new ParameterMapping("domain");

                domain.AddSource(email, (EmailChange e) => e.GetDomain());
                mapping.Add(domain);

                return(mapping.AsReadOnly());
            }
Example #9
0
        protected override BitArray MapSpecialParameters(ParameterMapping /*!*/ mapping)
        {
            var      infos   = mapping.Overload.Parameters;
            BitArray special = base.MapSpecialParameters(mapping);

            if (infos.Count > 0)
            {
                bool normalSeen = false;
                for (int i = 0; i < infos.Count; i++)
                {
                    bool isSpecial = false;
                    if (infos[i].ParameterType.IsSubclassOf(typeof(SiteLocalStorage)))
                    {
                        mapping.AddBuilder(new SiteLocalStorageBuilder(infos[i]));
                        isSpecial = true;
                    }
                    else if (infos[i].ParameterType == typeof(CodeContext) && !normalSeen)
                    {
                        mapping.AddBuilder(new ContextArgBuilder(infos[i]));
                        isSpecial = true;
                    }
                    else
                    {
                        normalSeen = true;
                    }

                    if (isSpecial)
                    {
                        (special = special ?? new BitArray(infos.Count))[i] = true;
                    }
                }
            }

            return(special);
        }
Example #10
0
 private static ParameterMapping GetParameterMapping(Type delegateType, ParameterMapping configuredParameterMapping)
 {
     if (configuredParameterMapping == ParameterMapping.Adaptive)
     {
         return(DelegateTypeIsFunc(delegateType) ? ParameterMapping.ByType : ParameterMapping.ByName);
     }
     return(configuredParameterMapping);
 }
Example #11
0
 internal static ParameterMapping ResolveParameterMapping(this ParameterMapping configuredParameterMapping, Type delegateType)
 {
     if (configuredParameterMapping == ParameterMapping.Adaptive)
     {
         return(delegateType.Name.StartsWith("Func`") ? ParameterMapping.ByType : ParameterMapping.ByName);
     }
     return(configuredParameterMapping);
 }
Example #12
0
 static ParameterMapping GetParameterMapping(Type delegateType, ParameterMapping configuredParameterMapping)
 {
     if (configuredParameterMapping == ParameterMapping.Adaptive)
     {
         return(delegateType.Name.StartsWith("Func`") ? ParameterMapping.ByType : ParameterMapping.ByName);
     }
     return(configuredParameterMapping);
 }
Example #13
0
 public Wp7FactoryGenerator(Type delegateType, Service service, ParameterMapping parameterMapping)
 {
     if (service == null)
     {
         throw new ArgumentNullException("service");
     }
     Enforce.ArgumentTypeIsFunction(delegateType);
     this.CreateGenerator(service, delegateType, parameterMapping);
 }
            public override IReadOnlyCollection <ParameterMapping> ProvideParameterMapping(MethodInfo methodInfo)
            {
                List <ParameterMapping> mappings = base.ProvideParameterMapping(methodInfo).ToList();

                var mapping = new ParameterMapping("context");

                mapping.AddContext("context", () => GetContext());
                mappings.Add(mapping);

                return(mappings.AsReadOnly());
            }
            public override IReadOnlyCollection <ParameterMapping> ProvideParameterMapping(System.Reflection.MethodInfo methodInfo)
            {
                var mappings = new List <ParameterMapping>();
                var mapping  = new ParameterMapping("data");

                mappings.Add(mapping);

                // return a mapping with an empty source

                return(mappings.AsReadOnly());
            }
 private static ParameterMapping GetParameterMapping(Type delegateType, ParameterMapping configuredParameterMapping)
 {
     if (configuredParameterMapping != ParameterMapping.Adaptive)
     {
         return(configuredParameterMapping);
     }
     if (!delegateType.Name.StartsWith("Func`"))
     {
         return(ParameterMapping.ByName);
     }
     return(ParameterMapping.ByType);
 }
        /// <summary>
        /// Create a factory generator.
        /// </summary>
        /// <param name="service">The service that will be activated in
        /// order to create the products of the factory.</param>
        /// <param name="delegateType">The delegate to provide as a factory.</param>
        /// <param name="parameterMapping">The parameter mapping mode to use.</param>
        public FactoryGenerator(Type delegateType, Service service, ParameterMapping parameterMapping)
        {
            if (service == null)
            {
                throw new ArgumentNullException("service");
            }
            Enforce.ArgumentTypeIsFunction(delegateType);

            _service          = service;
            _delegateType     = delegateType;
            _parameterMapping = GetParameterMapping(delegateType, parameterMapping);
        }
 private void ApplyMappings()
 {
     ParameterMapping.UpdateMappings(
         _document,
         Command.TargetComponent,
         _erasedMappings,
         _newMappings,
         _ruleName,
         _ruleOptionsForm.FireDep,
         _ruleOptionsForm.DontRunAuto,
         _ruleOptionsForm.UpdateWhenDone);
 }
            public override IReadOnlyCollection <ParameterMapping> ProvideParameterMapping(System.Reflection.MethodInfo methodInfo)
            {
                List <ParameterMapping> mapping = new List <ParameterMapping>();

                var email = methodInfo.GetParameters()[0];

                var from = new ParameterMapping("from");

                mapping.Add(from);
                from.AddSource(email, (OtherClass o) => o.AMethodNotShared());

                return(mapping.AsReadOnly());
            }
Example #20
0
        private void CreateGenerator(object service, Type delegateType, ParameterMapping parameterMapping)
        {
            Type        trailingItem = delegateType.FunctionReturnType();
            MethodInfo  method       = delegateType.GetMethod("Invoke");
            List <Type> args         = (from x in method.GetParameters() select x.ParameterType).Append <Type>(trailingItem).Append <Type>(delegateType).ToList <Type>();
            MethodInfo  info2        = DelegateActivators.FirstOrDefault <MethodInfo>(x => x.GetGenericArguments().Count <Type>() == args.Count <Type>());

            if (info2 != null)
            {
                MethodInfo creator = info2.MakeGenericMethod(args.ToArray());
                this._generator = (a0, a1) => (Delegate)creator.Invoke(null, new object[] { a0, service, parameterMapping.ResolveParameterMapping(delegateType) });
            }
        }
        /// <summary>
        /// Adds a mapping to the list of mappings
        /// </summary>
        /// <param name="mappings">The list of parameter mappings.</param>
        /// <param name="parameterInfo">The parameter being evaluated.</param>
        /// <param name="parameterName">The name of the parameter.</param>
        /// <param name="alias">The alias to use to output the parameter.</param>
        /// <param name="converter">An optional expression to use to convert the parameter.</param>
        private static void AddMapping(List <ParameterMapping> mappings, ParameterInfo parameterInfo, string parameterName, string alias, LambdaExpression converter)
        {
            // find the mapping that matches the name or create a new mapping
            var mapping = mappings.FirstOrDefault(p => String.Compare(p.Name, parameterName, StringComparison.OrdinalIgnoreCase) == 0);

            if (mapping == null)
            {
                mapping = new ParameterMapping(parameterName);
                mappings.Add(mapping);
            }

            mapping.AddSource(parameterInfo, alias, converter);
        }
            public override IReadOnlyCollection <ParameterMapping> ProvideParameterMapping(System.Reflection.MethodInfo methodInfo)
            {
                var mappings = new List <ParameterMapping>();
                var mapping  = new ParameterMapping("data");

                mappings.Add(mapping);
                foreach (var p in methodInfo.GetParameters().Reverse())
                {
                    mapping.AddSource(p);
                }

                return(mappings.AsReadOnly());
            }
Example #23
0
        protected internal override BitArray MapSpecialParameters(ParameterMapping mapping) {
            //  CallType        call-site   m static                  m instance         m operator/extension
            //  implicit inst.  T.m(a,b)    Ast.Call(null, [a, b])    Ast.Call(a, [b])   Ast.Call(null, [a, b])   
            //  none            a.m(b)      Ast.Call(null, [b])       Ast.Call(a, [b])   Ast.Call(null, [a, b])

            if (!mapping.Overload.IsStatic) {
                var type = mapping.Overload.DeclaringType;
                var flags = ParameterBindingFlags.ProhibitNull | (_callType == CallTypes.ImplicitInstance ? ParameterBindingFlags.IsHidden : 0);

                mapping.AddParameter(new ParameterWrapper(null, type, null, flags));
                mapping.AddInstanceBuilder(new InstanceBuilder(mapping.ArgIndex));
            }

            return null;
        }
Example #24
0
            /// <summary>
            /// Creates a new rebuilder that works on the given scope.
            /// </summary>
            /// <param name="parameterMapping">
            /// The target value of every parameter.
            /// </param>
            /// <param name="scope">The used scope.</param>
            /// <param name="methodMapping">The method mapping.</param>
            /// <returns>The created rebuilder.</returns>
            public IRRebuilder CreateRebuilder(
                ParameterMapping parameterMapping,
                Scope scope,
                MethodMapping methodMapping)
            {
                this.Assert(parameterMapping.Method == scope.Method);
                this.Assert(scope != null);
                this.Assert(scope.Method != Method);

                return(new IRRebuilder(
                           this,
                           parameterMapping,
                           scope,
                           methodMapping));
            }
        public FactoryGenerator(Type delegateType, Service service, ParameterMapping parameterMapping)
        {
            Func <Expression, Expression[], Expression> makeResolveCall = null;

            if (service == null)
            {
                throw new ArgumentNullException("service");
            }
            Enforce.ArgumentTypeIsFunction(delegateType);
            if (makeResolveCall == null)
            {
                makeResolveCall = (activatorContextParam, resolveParameterArray) => Expression.Call(ReflectionExtensions.GetMethod <IComponentContext>((Expression <Action <IComponentContext> >)(cc => cc.ResolveService(null, ((Parameter[])null)))), new Expression[] { activatorContextParam, Expression.Constant(service, typeof(Service)), Expression.NewArrayInit(typeof(Parameter), resolveParameterArray) });
            }
            this._generator = CreateGenerator(makeResolveCall, delegateType, GetParameterMapping(delegateType, parameterMapping));
        }
Example #26
0
            /// <summary>
            /// Creates a new rebuilder that works on the given scope.
            /// </summary>
            /// <param name="parameterMapping">The target value of every parameter.</param>
            /// <param name="scope">The used scope.</param>
            /// <param name="methodMapping">The method mapping.</param>
            /// <returns>The created rebuilder.</returns>
            public IRRebuilder CreateRebuilder(
                ParameterMapping parameterMapping,
                Scope scope,
                MethodMapping methodMapping)
            {
                Debug.Assert(parameterMapping.Method == scope.Method, "Invalid parameter mapping");
                Debug.Assert(scope != null, "Invalid scope");
                Debug.Assert(scope.Method != Method, "Cannot rebuild a function into itself");

                return(new IRRebuilder(
                           this,
                           parameterMapping,
                           scope,
                           methodMapping));
            }
Example #27
0
        /// <exception cref="System.MemberAccessException" />
        /// <exception cref="System.Reflection.TargetInvocationException" />
        private void LoadSystem(XmlElement root)
        {
            var list = root.GetElementsByTagName("system");

            for (int i = 0, n = list.Count; i < n; i++)
            {
                var node = list.Item(i);
                if (node.NodeType != XmlNodeType.Element)
                {
                    continue;
                }

                var props = ConfigUtil.LoadElements((XmlElement)node);
                ParameterMapping.Mapping(System, props);
            }
        }
Example #28
0
        private static ParameterMapping ReadParameterMapping(XmlReader reader)
        {
            if (!IsInNamespace(reader) || (reader.LocalName != "Parameter"))
            {
                throw Error.UnexpectedElement("Parameter", string.Format(CultureInfo.InvariantCulture, "{0}{1}{2}", new object[] { reader.Prefix, string.IsNullOrEmpty(reader.Prefix) ? "" : "/", reader.LocalName }));
            }
            ValidateAttributes(reader, new string[] { "Name", "DbType", "Parameter", "Direction" });
            ParameterMapping mapping = new ParameterMapping();

            mapping.Name          = RequiredAttribute(reader, "Name");
            mapping.ParameterName = RequiredAttribute(reader, "Parameter");
            mapping.DbType        = OptionalAttribute(reader, "DbType");
            mapping.XmlDirection  = OptionalAttribute(reader, "Direction");
            AssertEmptyElement(reader);
            return(mapping);
        }
Example #29
0
        /// <summary>
        /// 从JObject中读取需要的字符串,适用于Route,Query和Form Body,但不适用于JSON模板
        /// </summary>
        /// <param name="requestJson"></param>
        /// <param name="mapping"></param>
        /// <returns></returns>
        public static string ReadMappingValueString(JObject requestJson, ParameterMapping mapping)
        {
            string valueString;

            if (mapping.MappingType == MappingType.Constant)
            {
                valueString = ReadConstantValueString(mapping.ClientPath);
            }
            else if (mapping.MappingType == MappingType.Path)
            {
                valueString = ReadJsonValueString(requestJson, mapping.ClientPath, out var notFound);
            }
            else
            {
                throw new Exception("不支持的参数映射形式");
            }
            return(System.Web.HttpUtility.UrlEncode(valueString));
        }
Example #30
0
        private static string GetMapping(ParameterMapping mapping)
        {
            string inputPath = mapping.InputParameter.Name;

            if (mapping.InputParameterProperty != null)
            {
                inputPath += ".get" + CodeNamer.PascalCase(mapping.InputParameterProperty) + "()";
            }

            string outputPath = "";

            if (mapping.OutputParameterProperty != null)
            {
                outputPath += ".set" + CodeNamer.PascalCase(mapping.OutputParameterProperty);
                return(string.Format(CultureInfo.InvariantCulture, "{0}({1})", outputPath, inputPath));
            }
            else
            {
                return(string.Format(CultureInfo.InvariantCulture, "{0} = {1}", outputPath, inputPath));
            }
        }
Example #31
0
		/// <summary>
		/// Emits a method to complement an interface method. The complement method will have a suffix such as _Completed,
		/// and will take one parameter.
		/// </summary>
		/// <param name="invocationContext">The InvocationContext for this call.</param>
		/// <param name="suffix">The suffix to use on the method.</param>
		/// <param name="parameterType">The type of the parameter of the method.</param>
		/// <param name="parameterName">The name of the parameter of the method.</param>
		/// <param name="beginMethod">The begin method for this interface call.</param>
		/// <param name="eventId">The next available event ID.</param>
		/// <param name="autoKeyword">The auto-keyword to use if enabled.</param>
		/// <param name="faultedMethod">A faulted method to call or null if no other faulted method is available.</param>
		/// <returns>The MethodBuilder for the method.</returns>
		private MethodBuilder EmitMethodComplementImpl(InvocationContext invocationContext, string suffix, Type parameterType, string parameterName, MethodInfo beginMethod, ref int eventId, EventKeywords autoKeyword, MethodBuilder faultedMethod)
		{
			var interfaceMethod = invocationContext.MethodInfo;

			// if there is a NonEvent attribute, then no need to emit this method
			if (interfaceMethod.GetCustomAttribute<NonEventAttribute>() != null)
				return null;

			// if the method ends in _Completed, then don't emit another one
			if (interfaceMethod.Name.EndsWith(suffix, StringComparison.OrdinalIgnoreCase))
				return null;

			var methodName = beginMethod.Name + suffix;

			// if the interface already has a _Completed method with the same parameter, don't emit a new one
			var parameterTypes = parameterType == typeof(void) ? Type.EmptyTypes : new Type[] { parameterType };
			if (interfaceMethod.DeclaringType.GetMethod(methodName, parameterTypes) != null)
				return null;

			// create a single parameter for the return value, and a context parameter if its supported
			var parameterMappings = new List<ParameterMapping>();
			if (parameterType != typeof(void))
			{
				var mapping = new ParameterMapping(parameterName);
				mapping.AddSource(new ParameterDefinition(parameterName, 0, parameterType));
				parameterMappings.Add(mapping);
			}

			if (SupportsContext(invocationContext))
				parameterMappings.Add(new ParameterMapping(Context));

			// determine if this is a non-event or an event
			// if an event, but there is no event attribute, just add one to the last event id
			EventAttribute startEventAttribute = interfaceMethod.GetCustomAttribute<EventAttribute>() ?? new EventAttribute(eventId);
			EventAttribute eventAttribute = _eventAttributeProvider.CopyEventAttribute(startEventAttribute, invocationContext, eventId);
			eventId = Math.Max(eventId, eventAttribute.EventId + 1);
			if (eventAttribute.Keywords == EventKeywords.None)
				eventAttribute.Keywords = autoKeyword;

			// define the internal method
			MethodBuilder m = _typeBuilder.DefineMethod(methodName, MethodAttributes.Public, typeof(void), parameterMappings.Select(p => p.CleanTargetType).ToArray());
			if (parameterMappings.Any())
				m.DefineParameter(1, ParameterAttributes.None, parameterMappings[0].Name);
			m.SetCustomAttribute(EventAttributeHelper.ConvertEventAttributeToAttributeBuilder(eventAttribute));

			// if we have a return type, then we need to implement two methods
			if (parameterTypes.Length == 1)
			{
				EmitCallWriteEvent(invocationContext, m, eventAttribute, parameterMappings);

				// emit an overloaded wrapper method that calls the method when it's enabled
				// note this is a non-event so EventSource doesn't try to log it
				MethodBuilder im = _typeBuilder.DefineMethod(methodName, MethodAttributes.Public);
				ProxyHelper.CopyGenericSignature(interfaceMethod, im);
				im.SetReturnType(parameterTypes[0]);
				im.SetParameters(parameterTypes);

				// mark the method as a non-event
				im.SetCustomAttribute(EventAttributeHelper.CreateNonEventAttribute());

				// put the return value on the stack so we can return the value as a passthrough
				im.GetILGenerator().Emit(OpCodes.Ldarg_1);

				if (EmitIsEnabled(im, eventAttribute))
				{
					EmitTaskCompletion(im, parameterType, faultedMethod);
					EmitDirectProxy(invocationContext, im, m, parameterMappings);
				}

				return im;
			}
			else
			{
				// the method does not have a return value
				// so create the internal method that calls WriteEvent
				ProxyHelper.EmitDefaultValue(m.GetILGenerator(), m.ReturnType);
				if (EmitIsEnabled(m, eventAttribute))
					EmitCallWriteEvent(invocationContext, m, eventAttribute, parameterMappings);

				return m;
			}
		}
Example #32
0
        /// <summary>
        /// Called by the MaterialReader
        /// </summary>
        /// <param name="reader"></param>
        public void deserialize(BinaryReader reader)
        {
            int texCount = reader.ReadInt32();
            for (int i = 0; i < texCount; ++i)
            {
                TextureNames[i] = reader.ReadString();
            }

            m_effectName = reader.ReadString();
            m_technique = reader.ReadString();

            int paramCount = reader.ReadInt32();
            for (int i = 0; i < paramCount; ++i)
            {
                ParameterMapping param = new ParameterMapping();
                param.deserialize(reader);
                m_parameterMapping.Add(param);
            }
        }
            public override IReadOnlyCollection<ParameterMapping> ProvideParameterMapping(System.Reflection.MethodInfo methodInfo)
            {
                var mappings = new List<ParameterMapping>();
                var mapping = new ParameterMapping("data");
                mappings.Add(mapping);
                foreach (var p in methodInfo.GetParameters().Reverse())
                    mapping.AddSource(p);

                return mappings.AsReadOnly();
            }
            public override IReadOnlyCollection<ParameterMapping> ProvideParameterMapping(System.Reflection.MethodInfo methodInfo)
            {
                var mappings = new List<ParameterMapping>();
                var mapping = new ParameterMapping("data");
                mappings.Add(mapping);

                // return a mapping with an empty source

                return mappings.AsReadOnly();
            }
            public override IReadOnlyCollection<ParameterMapping> ProvideParameterMapping(MethodInfo methodInfo)
            {
                List<ParameterMapping> mappings = base.ProvideParameterMapping(methodInfo).ToList();

                var mapping = new ParameterMapping("context");
                mapping.AddContext("context", () => GetContext());
                mappings.Add(mapping);

                return mappings.AsReadOnly();
            }
Example #36
0
        /// <summary>
        /// Emits the code needed to properly push an object on the stack,
        /// serializing the value if necessary.
        /// </summary>
        /// <param name="typeBuilder">The TypeBuilder for the method being built.</param>
        /// <param name="methodBuilder">The method currently being built.</param>
        /// <param name="invocationContext">The invocation context for this call.</param>
        /// <param name="invocationContexts">A list of invocation contexts that will be appended to.</param>
        /// <param name="invocationContextsField">The static field containing the array of invocation contexts at runtime.</param>
        /// <param name="parameterMapping">The mapping of source parameters to destination parameters.</param>
        /// <param name="serializationProvider">The serialization provider for the current interface.</param>
        /// <param name="serializationProviderField">
        /// The field on the current object that contains the serialization provider at runtime.
        /// This method assume the current object is stored in arg.0.
        /// </param>
        internal static void EmitSerializeValue(
			TypeBuilder typeBuilder,
			MethodBuilder methodBuilder,
			InvocationContext invocationContext,
			List<InvocationContext> invocationContexts,
			FieldBuilder invocationContextsField,
			ParameterMapping parameterMapping,
			TraceSerializationProvider serializationProvider,
			FieldBuilder serializationProviderField)
        {
            var sourceCount = parameterMapping.Sources.Count();
            if (sourceCount == 0)
                return;

            if (sourceCount == 1)
            {
                var parameter = parameterMapping.Sources.First();

                EmitSerializeValue(
                    typeBuilder,
                    methodBuilder,
                    invocationContext,
                    invocationContexts,
                    invocationContextsField,
                    parameter.Position,
                    parameter.SourceType,
                    parameterMapping.CleanTargetType,
                    parameter.Converter,
                    serializationProvider,
                    serializationProviderField);
                return;
            }

            var il = methodBuilder.GetILGenerator();

            // use the serializer to serialize the objects
            var context = new TraceSerializationContext(invocationContext.SpecifyType(InvocationContextTypes.BundleParameters), -1);
            context.EventLevel = serializationProvider.GetEventLevelForContext(context);

            if (context.EventLevel != null)
            {
                // get the object serializer from the this pointer
                il.Emit(OpCodes.Ldsfld, serializationProviderField);

                // create a new dictionary strings and values
                il.Emit(OpCodes.Newobj, typeof(Dictionary<string, string>).GetConstructor(Type.EmptyTypes));

                foreach (var parameter in parameterMapping.Sources)
                {
                    il.Emit(OpCodes.Dup);
                    il.Emit(OpCodes.Ldstr, parameter.Alias);

                    EmitSerializeValue(
                        typeBuilder,
                        methodBuilder,
                        invocationContext,
                        invocationContexts,
                        invocationContextsField,
                        parameter.Position,
                        parameter.SourceType,
                        parameterMapping.CleanTargetType,
                        parameter.Converter,
                        serializationProvider,
                        serializationProviderField);

                    var method = typeof(Dictionary<string, string>).GetMethod("Add");
                    il.Emit(OpCodes.Call, method);
                }

                // get the invocation context from the array on the provider
                il.Emit(OpCodes.Ldsfld, invocationContextsField);
                il.Emit(OpCodes.Ldc_I4, invocationContexts.Count);
                il.Emit(OpCodes.Ldelem, typeof(TraceSerializationContext));
                invocationContexts.Add(context);

                il.Emit(OpCodes.Callvirt, typeof(TraceSerializationProvider).GetMethod("ProvideSerialization", BindingFlags.Instance | BindingFlags.Public));
            }
            else
                il.Emit(OpCodes.Ldnull);
        }
            public override IReadOnlyCollection<ParameterMapping> ProvideParameterMapping(System.Reflection.MethodInfo methodInfo)
            {
                List<ParameterMapping> mapping = new List<ParameterMapping>();

                var email = methodInfo.GetParameters()[0];

                var from = new ParameterMapping("from");
                mapping.Add(from);
                from.AddSource(email, (OtherClass o) => o.AMethodNotShared());

                return mapping.AsReadOnly();
            }
            public override IReadOnlyCollection<ParameterMapping> ProvideParameterMapping(System.Reflection.MethodInfo methodInfo)
            {
                List<ParameterMapping> mapping = new List<ParameterMapping>();

                var email = methodInfo.GetParameters()[0];

                var from = new ParameterMapping("from");
                mapping.Add(from);
                from.AddSource(email, (EmailChange e) => e.From);

                var to = new ParameterMapping("to");
                to.AddSource(email, (EmailChange e) => e.To);
                mapping.Add(to);

                var when = new ParameterMapping("when");
                when.AddSource(email, (EmailChange e) => e.When);
                mapping.Add(when);

                var domain = new ParameterMapping("domain");
                domain.AddSource(email, (EmailChange e) => e.GetDomain());
                mapping.Add(domain);

                return mapping.AsReadOnly();
            }