Exemplo n.º 1
0
        public override MethodBase BindToMethod(
            BindingFlags bindingAttr,
            MethodBase[] match,
            ref object[] args,
            ParameterModifier[] modifiers,
            CultureInfo culture,
            string[] names,
            out object state)
        {
            if (match == null)
            {
                throw new ArgumentNullException("match");
            }
            // Arguments are not being reordered.
            state = null;
            // Find a parameter match and return the first method with
            // parameters that match the request.
            foreach (MethodBase mb in match)
            {
                ParameterInfo[] parameters = mb.GetParameters();

                if (ParametersMatch(parameters, args))
                {
                    return mb;
                }
            }
            return null;
        }
        protected sealed override PropertyInfo GetPropertyImpl(string name, BindingFlags bindingAttr, Binder binder, Type returnType, Type[] types, ParameterModifier[] modifiers)
        {
            Debug.Assert(name != null);

            if (!OnlySearchRelatedBitsSet(bindingAttr))  // We don't yet have proper handling for BindingFlags not related to search so throw rather return a wrong result.
                throw new NotImplementedException();

            // GetPropertyImpl() is a funnel for two groups of api. We can distinguish by comparing "types" to null.
            if (types == null && returnType == null)
            {
                // Group #1: This group of api accept only a name and BindingFlags. The other parameters are hard-wired by the non-virtual api entrypoints. 
                Debug.Assert(binder == null);
                Debug.Assert(modifiers == null);
                return LowLevelTypeExtensions.GetProperty(this, name, bindingAttr);
            }
            else
            {
                if (!OnlySearchRelatedBitsSet(bindingAttr))  // We don't yet have proper handling for BindingFlags not related to search so throw rather return a wrong result.
                    throw new NotImplementedException();

                // Group #2: This group of api takes a set of parameter types, a return type (both cannot be null) and an optional binder. 
                if (binder == null)
                    binder = Type.DefaultBinder;
                PropertyInfo[] candidates = LowLevelTypeExtensions.GetProperties(this, name, bindingAttr);
                return binder.SelectProperty(bindingAttr, candidates, returnType, types, modifiers);
            }
        }
Exemplo n.º 3
0
 public static string ModifierToString(ParameterModifier variant)
 {
     var pair = ModifierMapping.FirstOrDefault(x => x.Value == variant);
     if (string.IsNullOrEmpty(pair.Key))
         throw new ArgumentException("Modifier is not supported in Visual Basic.");
     return pair.Key;
 }
Exemplo n.º 4
0
 public override sealed MethodBase BindToMethod(BindingFlags bindingAttr, MethodBase[] match, ref object[] args, ParameterModifier[] modifiers, CultureInfo culture, string[] names, out object state)
 {
     if (!((bindingAttr & ~SupportedBindingFlags) == 0) && modifiers == null && culture == null && names == null)
         throw new NotImplementedException();
     state = null;
     return LimitedBinder.BindToMethod(match, ref args);
 }
Exemplo n.º 5
0
        public override sealed MethodBase SelectMethod(BindingFlags bindingAttr, MethodBase[] match, Type[] types, ParameterModifier[] modifiers)
        {
            if (!((bindingAttr & ~SupportedBindingFlags) == 0) && modifiers == null)
                throw new NotImplementedException();

            return LimitedBinder.SelectMethod(match, types);
        }
Exemplo n.º 6
0
		/// <exception cref="BadSyntaxException">
		/// The <paramref name="name"/> or <paramref name="type"/> 
		/// does not fit to the syntax.
		/// </exception>
		protected Parameter(string name, string type, ParameterModifier modifier, string defaultValue)
		{
			Initializing = true;
			Name = name;
			Type = type;
			Modifier = modifier;
			DefaultValue = defaultValue;
			Initializing = false;
		}
Exemplo n.º 7
0
	bool GetArgsForCall (object [] originalArgs, out ParameterModifier parameterModifiers)
	{
		int countOfArgs = originalArgs.Length;
		if (countOfArgs == 0)
			return false;

		parameterModifiers = new ParameterModifier (countOfArgs);
		return true;
	}
Exemplo n.º 8
0
        public override sealed PropertyInfo SelectProperty(BindingFlags bindingAttr, PropertyInfo[] match, Type returnType, Type[] indexes, ParameterModifier[] modifiers)
        {
            if (!((bindingAttr & ~SupportedBindingFlags) == 0) && modifiers == null)
                throw new NotImplementedException();

            PropertyInfo[] memberArray = match.ToArray();

            if (memberArray.Length == 0)
                return null;

            return LimitedBinder.SelectProperty(memberArray, returnType, indexes);
        }
        protected sealed override ConstructorInfo GetConstructorImpl(BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers)
        {
            Debug.Assert(types != null);

            if (callConvention != CallingConventions.Any)
                throw new NotImplementedException();

            if (!OnlySearchRelatedBitsSet(bindingAttr))  // We don't yet have proper handling for BindingFlags not related to search so throw rather return a wrong result.
                throw new NotImplementedException();

            if (binder == null)
                binder = Type.DefaultBinder;
            ConstructorInfo[] candidates = GetConstructors(bindingAttr);
            return (ConstructorInfo)binder.SelectMethod(bindingAttr, candidates, types, modifiers);
        }
 PropertyInfo IReflect.GetProperty(string name, BindingFlags bindingAttr, Binder binder, Type returnType, Type[] types, ParameterModifier[] modifiers)
 {
     throw new NotImplementedException();
 }
Exemplo n.º 11
0
        private readonly InternalFlags _flags; // TODO_Serialize: round trip and test

        internal ParameterData(MetadataItemKinds declaringMemberKind, string name, TypeData type, ParameterModifier modifer, InternalFlags flags, object defaultValue)
        {
            _flags = flags;

            DeclaringMemberKind = declaringMemberKind;
            DefaultValue        = defaultValue;
            Modifer             = modifer;
            Name = name;
            Type = type;
        }
Exemplo n.º 12
0
		/// <summary>
		/// Allows to give parameter declaration group names.
		/// </summary>
		public static ParameterDeclaration NamedParameter(string groupName, AstType type, string name, ParameterModifier modifier = ParameterModifier.None)
		{
			return new NamedParameterDeclaration (groupName, type, name, modifier);
		}
        public override Object InvokeMember(
            String name, BindingFlags bindingFlags, Binder binder, Object target,
            Object[] providedArgs, ParameterModifier[] modifiers, CultureInfo culture, String[] namedParams)
        {
            const BindingFlags MemberBindingMask = (BindingFlags)0x000000FF;
            const BindingFlags InvocationMask = (BindingFlags)0x0000FF00;
            const BindingFlags BinderGetSetProperty = BindingFlags.GetProperty | BindingFlags.SetProperty;
            const BindingFlags BinderGetSetField = BindingFlags.GetField | BindingFlags.SetField;
            const BindingFlags BinderNonFieldGetSet = (BindingFlags)0x00FFF300;
            const BindingFlags BinderNonCreateInstance = BindingFlags.InvokeMethod | BinderGetSetField | BinderGetSetProperty;

            if (IsGenericParameter)
                throw new InvalidOperationException(SR.Arg_GenericParameter);

            #region Preconditions
            if ((bindingFlags & InvocationMask) == 0)
                // "Must specify binding flags describing the invoke operation required."
                throw new ArgumentException(SR.Arg_NoAccessSpec, nameof(bindingFlags));

            // Provide a default binding mask if none is provided 
            if ((bindingFlags & MemberBindingMask) == 0)
            {
                bindingFlags |= BindingFlags.Instance | BindingFlags.Public;

                if ((bindingFlags & BindingFlags.CreateInstance) == 0)
                    bindingFlags |= BindingFlags.Static;
            }

            // There must not be more named parameters than provided arguments
            if (namedParams != null)
            {
                if (providedArgs != null)
                {
                    if (namedParams.Length > providedArgs.Length)
                        // "Named parameter array can not be bigger than argument array."
                        throw new ArgumentException(SR.Arg_NamedParamTooBig, nameof(namedParams));
                }
                else
                {
                    if (namedParams.Length != 0)
                        // "Named parameter array can not be bigger than argument array."
                        throw new ArgumentException(SR.Arg_NamedParamTooBig, nameof(namedParams));
                }
            }
            #endregion

            #region COM Interop
            if (target != null && target.GetType().IsCOMObject)
                throw new PlatformNotSupportedException(SR.Arg_PlatformNotSupportedInvokeMemberCom);
            #endregion

            #region Check that any named paramters are not null
            if (namedParams != null && Array.IndexOf(namedParams, null) != -1)
                // "Named parameter value must not be null."
                throw new ArgumentException(SR.Arg_NamedParamNull, nameof(namedParams));
            #endregion

            int argCnt = (providedArgs != null) ? providedArgs.Length : 0;

            #region Get a Binder
            if (binder == null)
                binder = DefaultBinder;

            bool bDefaultBinder = (binder == DefaultBinder);
            #endregion

            #region Delegate to Activator.CreateInstance
            if ((bindingFlags & BindingFlags.CreateInstance) != 0)
            {
                if ((bindingFlags & BindingFlags.CreateInstance) != 0 && (bindingFlags & BinderNonCreateInstance) != 0)
                    // "Can not specify both CreateInstance and another access type."
                    throw new ArgumentException(SR.Arg_CreatInstAccess, nameof(bindingFlags));

                return Activator.CreateInstance(this, bindingFlags, binder, providedArgs, culture);
            }
            #endregion

            // PutDispProperty and\or PutRefDispProperty ==> SetProperty.
            if ((bindingFlags & (BindingFlags.PutDispProperty | BindingFlags.PutRefDispProperty)) != 0)
                bindingFlags |= BindingFlags.SetProperty;

            #region Name
            if (name == null)
                throw new ArgumentNullException(nameof(name));

            if (name.Length == 0 || name.Equals(@"[DISPID=0]"))
            {
                name = GetDefaultMemberName();

                if (name == null)
                {
                    // in InvokeMember we always pretend there is a default member if none is provided and we make it ToString
                    name = "ToString";
                }
            }
            #endregion

            #region GetField or SetField
            bool IsGetField = (bindingFlags & BindingFlags.GetField) != 0;
            bool IsSetField = (bindingFlags & BindingFlags.SetField) != 0;

            if (IsGetField || IsSetField)
            {
                #region Preconditions
                if (IsGetField)
                {
                    if (IsSetField)
                        // "Can not specify both Get and Set on a field."
                        throw new ArgumentException(SR.Arg_FldSetGet, nameof(bindingFlags));

                    if ((bindingFlags & BindingFlags.SetProperty) != 0)
                        // "Can not specify both GetField and SetProperty."
                        throw new ArgumentException(SR.Arg_FldGetPropSet, nameof(bindingFlags));
                }
                else
                {
                    Debug.Assert(IsSetField);

                    if (providedArgs == null)
                        throw new ArgumentNullException(nameof(providedArgs));

                    if ((bindingFlags & BindingFlags.GetProperty) != 0)
                        // "Can not specify both SetField and GetProperty."
                        throw new ArgumentException(SR.Arg_FldSetPropGet, nameof(bindingFlags));

                    if ((bindingFlags & BindingFlags.InvokeMethod) != 0)
                        // "Can not specify Set on a Field and Invoke on a method."
                        throw new ArgumentException(SR.Arg_FldSetInvoke, nameof(bindingFlags));
                }
                #endregion

                #region Lookup Field
                FieldInfo selFld = null;
                FieldInfo[] flds = GetMember(name, MemberTypes.Field, bindingFlags) as FieldInfo[];

                Debug.Assert(flds != null);

                if (flds.Length == 1)
                {
                    selFld = flds[0];
                }
                else if (flds.Length > 0)
                {
                    selFld = binder.BindToField(bindingFlags, flds, IsGetField ? Empty.Value : providedArgs[0], culture);
                }
                #endregion

                if (selFld != null)
                {
                    #region Invocation on a field
                    if (selFld.FieldType.IsArray || Object.ReferenceEquals(selFld.FieldType, CommonRuntimeTypes.Array))
                    {
                        #region Invocation of an array Field
                        int idxCnt;

                        if ((bindingFlags & BindingFlags.GetField) != 0)
                        {
                            idxCnt = argCnt;
                        }
                        else
                        {
                            idxCnt = argCnt - 1;
                        }

                        if (idxCnt > 0)
                        {
                            // Verify that all of the index values are ints
                            int[] idx = new int[idxCnt];
                            for (int i = 0; i < idxCnt; i++)
                            {
                                try
                                {
                                    idx[i] = ((IConvertible)providedArgs[i]).ToInt32(null);
                                }
                                catch (InvalidCastException)
                                {
                                    throw new ArgumentException(SR.Arg_IndexMustBeInt);
                                }
                            }

                            // Set or get the value...
                            Array a = (Array)selFld.GetValue(target);

                            // Set or get the value in the array
                            if ((bindingFlags & BindingFlags.GetField) != 0)
                            {
                                return a.GetValue(idx);
                            }
                            else
                            {
                                a.SetValue(providedArgs[idxCnt], idx);
                                return null;
                            }
                        }
                        #endregion
                    }

                    if (IsGetField)
                    {
                        #region Get the field value
                        if (argCnt != 0)
                            throw new ArgumentException(SR.Arg_FldGetArgErr, nameof(bindingFlags));

                        return selFld.GetValue(target);
                        #endregion
                    }
                    else
                    {
                        #region Set the field Value
                        if (argCnt != 1)
                            throw new ArgumentException(SR.Arg_FldSetArgErr, nameof(bindingFlags));

                        selFld.SetValue(target, providedArgs[0], bindingFlags, binder, culture);

                        return null;
                        #endregion
                    }
                    #endregion
                }

                if ((bindingFlags & BinderNonFieldGetSet) == 0)
                    throw new MissingFieldException(FullName, name);
            }
            #endregion                    

            #region Property PreConditions
            // @Legacy - This is RTM behavior
            bool isGetProperty = (bindingFlags & BindingFlags.GetProperty) != 0;
            bool isSetProperty = (bindingFlags & BindingFlags.SetProperty) != 0;

            if (isGetProperty || isSetProperty)
            {
                #region Preconditions
                if (isGetProperty)
                {
                    Debug.Assert(!IsSetField);

                    if (isSetProperty)
                        throw new ArgumentException(SR.Arg_PropSetGet, nameof(bindingFlags));
                }
                else
                {
                    Debug.Assert(isSetProperty);

                    Debug.Assert(!IsGetField);

                    if ((bindingFlags & BindingFlags.InvokeMethod) != 0)
                        throw new ArgumentException(SR.Arg_PropSetInvoke, nameof(bindingFlags));
                }
                #endregion
            }
            #endregion

            MethodInfo[] finalists = null;
            MethodInfo finalist = null;

            #region BindingFlags.InvokeMethod
            if ((bindingFlags & BindingFlags.InvokeMethod) != 0)
            {
                #region Lookup Methods
                MethodInfo[] semiFinalists = GetMember(name, MemberTypes.Method, bindingFlags) as MethodInfo[];
                LowLevelListWithIList<MethodInfo> results = null;

                for (int i = 0; i < semiFinalists.Length; i++)
                {
                    MethodInfo semiFinalist = semiFinalists[i];
                    Debug.Assert(semiFinalist != null);

                    if (!semiFinalist.QualifiesBasedOnParameterCount(bindingFlags, CallingConventions.Any, new Type[argCnt]))
                        continue;

                    if (finalist == null)
                    {
                        finalist = semiFinalist;
                    }
                    else
                    {
                        if (results == null)
                        {
                            results = new LowLevelListWithIList<MethodInfo>(semiFinalists.Length);
                            results.Add(finalist);
                        }

                        results.Add(semiFinalist);
                    }
                }

                if (results != null)
                {
                    Debug.Assert(results.Count > 1);
                    finalists = new MethodInfo[results.Count];
                    results.CopyTo(finalists, 0);
                }
                #endregion
            }
            #endregion

            Debug.Assert(finalists == null || finalist != null);

            #region BindingFlags.GetProperty or BindingFlags.SetProperty
            if (finalist == null && isGetProperty || isSetProperty)
            {
                #region Lookup Property
                PropertyInfo[] semiFinalists = GetMember(name, MemberTypes.Property, bindingFlags) as PropertyInfo[];
                LowLevelListWithIList<MethodInfo> results = null;

                for (int i = 0; i < semiFinalists.Length; i++)
                {
                    MethodInfo semiFinalist = null;

                    if (isSetProperty)
                    {
                        semiFinalist = semiFinalists[i].GetSetMethod(true);
                    }
                    else
                    {
                        semiFinalist = semiFinalists[i].GetGetMethod(true);
                    }

                    if (semiFinalist == null)
                        continue;

                    BindingFlags expectedBindingFlags = semiFinalist.IsPublic ? BindingFlags.Public : BindingFlags.NonPublic;
                    if ((bindingFlags & expectedBindingFlags) != expectedBindingFlags)
                        continue;

                    if (!semiFinalist.QualifiesBasedOnParameterCount(bindingFlags, CallingConventions.Any, new Type[argCnt]))
                        continue;

                    if (finalist == null)
                    {
                        finalist = semiFinalist;
                    }
                    else
                    {
                        if (results == null)
                        {
                            results = new LowLevelListWithIList<MethodInfo>(semiFinalists.Length);
                            results.Add(finalist);
                        }

                        results.Add(semiFinalist);
                    }
                }

                if (results != null)
                {
                    Debug.Assert(results.Count > 1);
                    finalists = new MethodInfo[results.Count];
                    results.CopyTo(finalists, 0);
                }
                #endregion            
            }
            #endregion

            if (finalist != null)
            {
                #region Invoke
                if (finalists == null &&
                    argCnt == 0 &&
                    finalist.GetParametersNoCopy().Length == 0 &&
                    (bindingFlags & BindingFlags.OptionalParamBinding) == 0)
                {
                    //if (useCache && argCnt == props[0].GetParameters().Length)
                    //    AddMethodToCache(name, bindingFlags, argCnt, providedArgs, props[0]);

                    return finalist.Invoke(target, bindingFlags, binder, providedArgs, culture);
                }

                if (finalists == null)
                    finalists = new MethodInfo[] { finalist };

                if (providedArgs == null)
                    providedArgs = Array.Empty<object>();

                Object state = null;


                MethodBase invokeMethod = null;

                try { invokeMethod = binder.BindToMethod(bindingFlags, finalists, ref providedArgs, modifiers, culture, namedParams, out state); }
                catch (MissingMethodException) { }

                if (invokeMethod == null)
                    throw new MissingMethodException(FullName, name);

                //if (useCache && argCnt == invokeMethod.GetParameters().Length)
                //    AddMethodToCache(name, bindingFlags, argCnt, providedArgs, invokeMethod);

                Object result = ((MethodInfo)invokeMethod).Invoke(target, bindingFlags, binder, providedArgs, culture);

                if (state != null)
                    binder.ReorderArgumentArray(ref providedArgs, state);

                return result;
                #endregion
            }

            throw new MissingMethodException(FullName, name);
        }
Exemplo n.º 14
0
 public AstArgument(AstIdentifier optionalName, ParameterModifier modifiers, AstExpression value)
 {
     OptionalName = optionalName;
     Modifier     = modifiers;
     Value        = value;
 }
Exemplo n.º 15
0
 private void AppendTextForIntValue( 
     int value, ParameterModifier modifier, string modifierAtt, StringBuilder sb)
 {
     switch (modifier)
     {
         case ParameterModifier.None:
             sb.Append(value);
             break;
         case ParameterModifier.d:
             sb.Append(_soundManager.GetTextForDays(value));
             break;
         case ParameterModifier.delim:
             sb.Append(value);
             sb.Append(modifierAtt);
             break;
         default:
             throw new Exception("Неподдерживаемый модификатор: " + modifier);
     }
 }
Exemplo n.º 16
0
 private void AddSoundForIntValue( 
     int value, ParameterModifier modifier, string modifierAtt, List<string> sounds)
 {
     switch (modifier)
     {
         case ParameterModifier.None:
             sounds.AddRange(_soundManager.GetSoundForNumber(value, false, NumberDeclension.None));
             break;
         case ParameterModifier.d:
             sounds.AddRange(_soundManager.GetSoundForDays(value));
             break;
         default:
             throw new Exception("Неподдерживаемый модификатор: " + modifier);
     }
 }
Exemplo n.º 17
0
 /// <exception cref="BadSyntaxException">
 /// The <paramref name="name"/> does not fit to the syntax.
 /// </exception>
 /// <exception cref="ReservedNameException">
 /// The parameter name is already exists.
 /// </exception>
 public abstract Parameter Add(string name, string type, ParameterModifier modifier, string defaultValue);
Exemplo n.º 18
0
 /// <exception cref="BadSyntaxException">
 /// The <paramref name="name"/> or <paramref name="type"/>
 /// does not fit to the syntax.
 /// </exception>
 internal CSharpParameter(string name, string type, ParameterModifier modifier)
     : base(name, type, modifier)
 {
 }
Exemplo n.º 19
0
 /// <exception cref="BadSyntaxException">
 /// The <paramref name="name"/> or <paramref name="type"/>
 /// does not fit to the syntax.
 /// </exception>
 internal CSharpParameter(string name, string type, ParameterModifier modifier, string defaultValue)
     : base(name, type, modifier, defaultValue)
 {
 }
Exemplo n.º 20
0
 internal static global::System.Runtime.InteropServices.HandleRef getCPtr(ParameterModifier obj)
 {
     return((obj == null) ? new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero) : obj.swigCPtr);
 }
Exemplo n.º 21
0
        CodeAction CreateFromStatements(RefactoringContext context, List <AstNode> statements)
        {
            if (!(statements [0].Parent is Statement))
            {
                return(null);
            }

            return(new CodeAction(context.TranslateString("Extract method"), script => {
                string methodName = "NewMethod";
                var method = new MethodDeclaration()
                {
                    ReturnType = new PrimitiveType("void"),
                    Name = methodName,
                    Body = new BlockStatement()
                };
                bool usesNonStaticMember = false;
                foreach (var node in statements)
                {
                    usesNonStaticMember |= StaticVisitor.UsesNotStaticMember(context, node);
                    if (node is Statement)
                    {
                        method.Body.Add((Statement)node.Clone());
                    }
                    else
                    {
                        method.Body.AddChildUnsafe(node.Clone(), node.Role);
                    }
                }
                if (!usesNonStaticMember)
                {
                    method.Modifiers |= Modifiers.Static;
                }

                var target = new IdentifierExpression(methodName);
                var invocation = new InvocationExpression(target);

                var usedVariables = VariableLookupVisitor.Analyze(context, statements);

                var inExtractedRegion = new VariableUsageAnalyzation(context, usedVariables);
                var lastStatement = statements [statements.Count - 1];

                var stmt = statements [0].GetParent <BlockStatement>();
                while (stmt.GetParent <BlockStatement> () != null)
                {
                    stmt = stmt.GetParent <BlockStatement>();
                }

                inExtractedRegion.SetAnalyzedRange(statements [0], lastStatement);
                stmt.AcceptVisitor(inExtractedRegion);

                var beforeExtractedRegion = new VariableUsageAnalyzation(context, usedVariables);
                beforeExtractedRegion.SetAnalyzedRange(statements [0].Parent, statements [0], true, false);
                stmt.AcceptVisitor(beforeExtractedRegion);

                var afterExtractedRegion = new VariableUsageAnalyzation(context, usedVariables);
                afterExtractedRegion.SetAnalyzedRange(lastStatement, stmt.Statements.Last(), false, true);
                stmt.AcceptVisitor(afterExtractedRegion);
                usedVariables.Sort((l, r) => l.Region.Begin.CompareTo(r.Region.Begin));

                IVariable generatedReturnVariable = null;
                foreach (var variable in usedVariables)
                {
                    if ((variable is IParameter) || beforeExtractedRegion.Has(variable) || !afterExtractedRegion.Has(variable))
                    {
                        continue;
                    }
                    generatedReturnVariable = variable;
                    method.ReturnType = context.CreateShortType(variable.Type);
                    method.Body.Add(new ReturnStatement(new IdentifierExpression(variable.Name)));
                    break;
                }

                foreach (var variable in usedVariables)
                {
                    if (!(variable is IParameter) && !beforeExtractedRegion.Has(variable) && !afterExtractedRegion.Has(variable))
                    {
                        continue;
                    }
                    if (variable == generatedReturnVariable)
                    {
                        continue;
                    }
                    Expression argumentExpression = new IdentifierExpression(variable.Name);

                    ParameterModifier mod = ParameterModifier.None;
                    if (inExtractedRegion.GetStatus(variable) == VariableState.Changed)
                    {
                        if (beforeExtractedRegion.GetStatus(variable) == VariableState.None)
                        {
                            mod = ParameterModifier.Out;
                            argumentExpression = new DirectionExpression(FieldDirection.Out, argumentExpression);
                        }
                        else
                        {
                            mod = ParameterModifier.Ref;
                            argumentExpression = new DirectionExpression(FieldDirection.Ref, argumentExpression);
                        }
                    }

                    method.Parameters.Add(new ParameterDeclaration(context.CreateShortType(variable.Type), variable.Name, mod));
                    invocation.Arguments.Add(argumentExpression);
                }
                script
                .InsertWithCursor(context.TranslateString("Extract method"), Script.InsertPosition.Before, method)
                .ContinueScript(delegate {
                    foreach (var node in statements.Skip(1))
                    {
                        if (node is NewLineNode)
                        {
                            continue;
                        }
                        script.Remove(node);
                    }
                    foreach (var variable in usedVariables)
                    {
                        if ((variable is IParameter) || beforeExtractedRegion.Has(variable) || !afterExtractedRegion.Has(variable))
                        {
                            continue;
                        }
                        if (variable == generatedReturnVariable)
                        {
                            continue;
                        }
                        script.InsertBefore(statements [0], new VariableDeclarationStatement(context.CreateShortType(variable.Type), variable.Name));
                    }
                    Statement invocationStatement;

                    if (generatedReturnVariable != null)
                    {
                        invocationStatement = new VariableDeclarationStatement(new SimpleType("var"), generatedReturnVariable.Name, invocation);
                    }
                    else
                    {
                        invocationStatement = invocation;
                    }
                    script.Replace(statements [0], invocationStatement);


                    script.Link(target, method.NameToken);
                });
            }, statements.First().StartLocation, statements.Last().EndLocation));
        }
Exemplo n.º 22
0
 /// <summary>Constructs an instance.</summary>
 /// <param name="name">The name of the parameter.</param>
 /// <param name="type">The type of the parameter.</param>
 /// <param name="modifier">The modifier of the parameter.</param>
 public CommandParameterInfo(string name, TypeInfo type, ParameterModifier modifier)
 {
     Name     = name;
     Type     = type;
     Modifier = modifier;
 }
Exemplo n.º 23
0
 public override object InvokeMember(string name, BindingFlags invokeAttr, Binder binder, object target, object[] args, ParameterModifier[] modifiers, CultureInfo culture, string[] namedParameters)
 {
     throw new NotImplementedException();
 }
Exemplo n.º 24
0
 protected override PropertyInfo GetPropertyImpl(string name, BindingFlags bindingAttr, Binder binder, Type returnType, Type[] types, ParameterModifier[] modifiers)
 {
     Debug.Assert(binder == null, "NYI");
     Debug.Assert(returnType == null, "NYI");
     Debug.Assert(types == null, "NYI");
     Debug.Assert(modifiers == null, "NYI");
     return new PropertyInfoImpl(Type.GetProperty(name, (System.Reflection.BindingFlags)bindingAttr, binder: null, returnType: null, types: new System.Type[0], modifiers: new System.Reflection.ParameterModifier[0]));
 }
Exemplo n.º 25
0
        public void DoDraggedEdge()
        {
            if (_sDragSourceSlot != null)
            {
                EventType typeForControl = Event.current.GetTypeForControl(0);
                if (typeForControl != EventType.Repaint)
                {
                    if (typeForControl == EventType.MouseDrag)
                    {
                        _sDropTarget = null;
                        DontDrawEdge = null;
                        Event.current.Use();
                    }
                }
                else
                {
                    Assembly unityEngineAssembly = Assembly.GetAssembly(typeof(UnityEngine.GUI));
                    Type     guiClipType         = unityEngineAssembly.GetType("UnityEngine.GUIClip", true);

                    FieldInfo propInfo = typeof(Slot).GetField(
                        "m_Position",
                        BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);

                    if (propInfo == null)
                    {
                        Debug.LogError("PropInfo m_Position is null!");
                    }
                    Rect position = (Rect)propInfo.GetValue(_sDragSourceSlot);

                    Vector2 end = Event.current.mousePosition;

                    if (_sDropTarget != null)
                    {
                        Rect position2 = (Rect)propInfo.GetValue(_sDropTarget);

                        object[]          endArgs = { new Vector2(position2.x, position2.y + 9f) };
                        ParameterModifier endP    = new ParameterModifier(1);
                        endP[0] = true;
                        ParameterModifier[] endMods     = { endP };
                        MethodInfo          endClipRect = guiClipType.GetMethod(
                            "Clip",
                            BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic |
                            BindingFlags.FlattenHierarchy,
                            Type.DefaultBinder,
                            new Type[] { typeof(Vector2) },
                            endMods);

                        end = (Vector2)endClipRect.Invoke(null, endArgs);
                    }

                    object[]          startArgs = { new Vector2(position.xMax, position.y + 9f) };
                    ParameterModifier startP    = new ParameterModifier(1);
                    startP[0] = true;
                    ParameterModifier[] startMods     = { startP };
                    MethodInfo          startClipRect = guiClipType.GetMethod(
                        "Clip",
                        BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic |
                        BindingFlags.FlattenHierarchy,
                        Type.DefaultBinder,
                        new Type[] { typeof(Vector2) },
                        startMods);

                    Vector2 start = (Vector2)startClipRect.Invoke(null, startArgs);

                    Color edgeColor = Color.white;
                    if (_sDragSourceSlot.dataType != null)
                    {
                        edgeColor = UdonGraphGUI.MapTypeToColor(_sDragSourceSlot.dataType);
                    }

                    DrawEdge(start, end, (Texture2D)Styles.selectedConnectionTexture.image, edgeColor, edgeStyle);
                }
            }
        }
Exemplo n.º 26
0
 private void AddSoundForTimeSpanValue( 
     TimeSpan value, ParameterModifier modifier, string modifierAtt, List<string> sounds)
 {
     switch (modifier)
     {
         case ParameterModifier.None:
             sounds.AddRange(_soundManager.GetSoundForHours(value.Hours));
             sounds.AddRange(_soundManager.GetSoundForMinutes(value.Minutes));
             break;
         case ParameterModifier.hhimmi:
             sounds.AddRange(_soundManager.GetSoundForHours(value.Hours, false, NumberDeclension.N_ti));
             sounds.AddRange(_soundManager.GetSoundForMinutes(value.Minutes, true, NumberDeclension.N_ti));
             break;
         case ParameterModifier.hhmm:
             if (value.Hours > 0)
                 sounds.AddRange(_soundManager.GetSoundForHours(value.Hours));
             sounds.AddRange(_soundManager.GetSoundForMinutes(value.Minutes));
             break;
         default:
             throw new Exception("Неподдерживаемый модификатор: " + modifier);
     }
 }
Exemplo n.º 27
0
 public ParameterInfo(Type parameterType, string argumentName)
 {
     Modifier      = ParameterModifier.None;
     ParameterType = parameterType;
     Name          = argumentName;
 }
Exemplo n.º 28
0
 private void ParseParameterArgument( 
     string arg, 
     out List<KeyValuePair<object, Type>> paramValues,  
     out ParameterModifier paramModifier, 
     out string paramModifierAtt)
 {
     const string INDEX_ALL = "IndexAll";
     const string INDEX_FROM = "IndexFrom";
     const string INDEX_TO = "IndexTo";
     const string MODIFIER = "Modifier";
     const string MODIFIER_ATT = "ModifierAtt";
     var regex = new ParseParameter();
     var match = regex.Match(arg);
     if (!match.Success)
         throw new Exception("Неправильный синтаксис параметра");
     paramValues = new List<KeyValuePair<object,Type>>();
     if (match.Groups[INDEX_ALL].Success)
     {
         for (int i = 0; i < Parameters.Length; i++)
             paramValues.Add(GetTypedParamValueAndType(i));
     }
     else
     {
         var paramIndexFrom = Convert.ToInt32(match.Groups[INDEX_FROM].Value);
         var paramIndexTo = paramIndexFrom;
         if (match.Groups[INDEX_TO].Success)
         {
             var paramIndexToValue = match.Groups[INDEX_TO].Value;
             paramIndexTo =
                 string.CompareOrdinal(paramIndexToValue, "*") == 0
                 ? Parameters.Length - 1
                 : Convert.ToInt32(paramIndexToValue);
         }
         if (paramIndexFrom > paramIndexTo || paramIndexTo >= Parameters.Length)
             throw new Exception("Некорректный диапазон индексов параметров");
         for (int i = paramIndexFrom; i <= paramIndexTo; i++)
             paramValues.Add(GetTypedParamValueAndType(i));
     }
     var modifierGroup = match.Groups[MODIFIER];
     if (modifierGroup.Success)
     {
         paramModifier = (ParameterModifier)Enum.Parse(typeof(ParameterModifier), modifierGroup.Value);
         var modifierAttGroup = match.Groups[MODIFIER_ATT];
         if (modifierAttGroup.Success)
             paramModifierAtt = modifierAttGroup.Value;
         else
             paramModifierAtt = null;
     }
     else
     {
         paramModifier = ParameterModifier.None;
         paramModifierAtt = null;
     }
 }
Exemplo n.º 29
0
 public Parameter(ParameterModifier modifier, TypeIdentifier type, Identifier identifier)
 {
     Modifier   = modifier;
     Type       = type;
     Identifier = identifier;
 }
Exemplo n.º 30
0
 /// <summary>
 /// 
 /// </summary>
 /// <param name="bindingAttr"></param>
 /// <param name="match"></param>
 /// <param name="returnType"></param>
 /// <param name="indexes"></param>
 /// <param name="modifiers"></param>
 /// <returns></returns>
 public override PropertyInfo SelectProperty(
     BindingFlags bindingAttr,
     PropertyInfo[] match,
     Type returnType,
     Type[] indexes,
     ParameterModifier[] modifiers
     )
 {
     if (match == null)
         throw new ArgumentNullException("match");
     for (int i = 0; i < match.Length; i++)
     {
         // Count the number of indexes that match.
         int count = 0;
         ParameterInfo[] parameters = match[i].GetIndexParameters();
         // Go on to the next property if the number of indexes do not match.
         if (indexes.Length != parameters.Length)
             continue;
         // Match each of the indexes that the user expects the property to have.
         for (int j = 0; j < indexes.Length; j++)
             // Determine whether the types specified by the user can be converted to index type.
             if (CanConvertFrom(indexes[j], parameters[j].ParameterType))
                 count += 1;
             else
                 break;
         // Determine whether the property has been found.
         if (count == indexes.Length)
             // Determine whether the return type can be converted to the properties type.
             if (CanConvertFrom(returnType, match[i].GetType()))
                 return match[i];
             else
                 continue;
     }
     return null;
 }
 public WriteMethodParameterModifier(ParameterModifier modifier)
 {
     Modifier = modifier;
 }
Exemplo n.º 32
0
Arquivo: test.cs Projeto: mono/gert
	public void foo (out ParameterModifier p)
	{
		p = new ParameterModifier (1);
		p [0] = true;
	}
 public ParameterDeclaration(AstType type, string name, ParameterModifier modifier = ParameterModifier.None)
 {
     Type = type;
     Name = name;
     ParameterModifier = modifier;
 }
Exemplo n.º 34
0
			public NamedParameterDeclaration(string groupName, AstType type, string name, ParameterModifier modifier = ParameterModifier.None) : base (type, name, modifier)
			{
				this.groupName = groupName;
			}
 public ParameterDeclaration(string name, ParameterModifier modifier = ParameterModifier.None)
 {
     Name = name;
     ParameterModifier = modifier;
 }
 MethodInfo IReflect.GetMethod(string name, BindingFlags bindingAttr, Binder binder, Type[] types, ParameterModifier[] modifiers)
 {
     throw new NotImplementedException();
 }
Exemplo n.º 37
0
        private void ParseParameterArgument(
            string arg,
            out List <KeyValuePair <object, Type> > paramValues,
            out ParameterModifier paramModifier,
            out string paramModifierAtt)
        {
            const string INDEX_ALL    = "IndexAll";
            const string INDEX_FROM   = "IndexFrom";
            const string INDEX_TO     = "IndexTo";
            const string MODIFIER     = "Modifier";
            const string MODIFIER_ATT = "ModifierAtt";
            var          regex        = new ParseParameter();
            var          match        = regex.Match(arg);

            if (!match.Success)
            {
                throw new Exception("Неправильный синтаксис параметра");
            }
            paramValues = new List <KeyValuePair <object, Type> >();
            if (match.Groups[INDEX_ALL].Success)
            {
                for (int i = 0; i < Parameters.Length; i++)
                {
                    paramValues.Add(GetTypedParamValueAndType(i));
                }
            }
            else
            {
                var paramIndexFrom = Convert.ToInt32(match.Groups[INDEX_FROM].Value);
                var paramIndexTo   = paramIndexFrom;
                if (match.Groups[INDEX_TO].Success)
                {
                    var paramIndexToValue = match.Groups[INDEX_TO].Value;
                    paramIndexTo =
                        string.CompareOrdinal(paramIndexToValue, "*") == 0
                        ? Parameters.Length - 1
                        : Convert.ToInt32(paramIndexToValue);
                }
                if (paramIndexFrom > paramIndexTo || paramIndexTo >= Parameters.Length)
                {
                    throw new Exception("Некорректный диапазон индексов параметров");
                }
                for (int i = paramIndexFrom; i <= paramIndexTo; i++)
                {
                    paramValues.Add(GetTypedParamValueAndType(i));
                }
            }
            var modifierGroup = match.Groups[MODIFIER];

            if (modifierGroup.Success)
            {
                paramModifier = (ParameterModifier)Enum.Parse(typeof(ParameterModifier), modifierGroup.Value);
                var modifierAttGroup = match.Groups[MODIFIER_ATT];
                if (modifierAttGroup.Success)
                {
                    paramModifierAtt = modifierAttGroup.Value;
                }
                else
                {
                    paramModifierAtt = null;
                }
            }
            else
            {
                paramModifier    = ParameterModifier.None;
                paramModifierAtt = null;
            }
        }
            object IReflect.InvokeMember(string name, BindingFlags invokeAttr, Binder binder, object target, object[] args, ParameterModifier[] modifiers, CultureInfo culture, string[] namedParameters)
            {
                object ret = null;
                // Check direct IDispatch call using a dispid (see http://msdn.microsoft.com/en-us/library/de3dhzwy.aspx)
                const string dispidToken = "[DISPID=";
                if (name.StartsWith(dispidToken))
                {
                    int dispid = int.Parse(name.Substring(dispidToken.Length, name.Length - dispidToken.Length - 1));
                    if (_dispidCache == null)
                    {
                        // WebBrowser has many properties, so we build a dispid cache on it
                        _dispidCache = new Dictionary<int, PropertyInfo>();
                        foreach (PropertyInfo pi in _host.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance))
                        {
                            if ((!pi.CanRead) || (pi.GetIndexParameters().Length > 0))
                                continue;

                            object[] atts = pi.GetCustomAttributes(typeof(DispIdAttribute), true);
                            if ((atts != null) && (atts.Length > 0))
                            {
                                DispIdAttribute da = (DispIdAttribute)atts[0];
                                _dispidCache[da.Value] = pi;
                            }
                        }
                    }

                    PropertyInfo property;
                    if (this._dispidCache.TryGetValue(dispid, out property))
                    {
                        ret = property.GetValue(this._host, null);
                    }
                }
                return ret;
            }
Exemplo n.º 39
0
        /// <summary>
        /// Intercept method calls
        /// </summary>
        /// <param name="myMessage">
        /// Contains information about the method being called
        /// </param>
        /// <returns>
        /// A <see cref="ReturnMessage"/>.
        /// </returns>
        public override IMessage Invoke(IMessage myMessage)
        {
            IMethodCallMessage callMessage = myMessage as IMethodCallMessage;

            if (null == callMessage)
            {
                Debug.WriteLine("Message type not implemented: " + myMessage.GetType().ToString());
                return(null);
            }

            MethodInfo method = callMessage.MethodBase as MethodInfo;

            if (null == method)
            {
                Debug.WriteLine("Unrecognized Invoke call: " + callMessage.MethodBase.ToString());
                return(null);
            }

            object returnValue = null;

            object[] outArgs      = null;
            int      outArgsCount = 0;

            string       methodName = method.Name;
            Type         returnType = method.ReturnType;
            BindingFlags flags      = BindingFlags.InvokeMethod;
            int          argCount   = callMessage.ArgCount;

            object invokeObject;
            Type   invokeType;
            Type   byValType;

            object[] args;
            object   arg;

            COMWrapper[] originalArgs;
            COMWrapper   wrapper;

            ParameterModifier[] argModifiers = null;
            ParameterInfo[]     parameters   = null;
            ParameterInfo       parameter;

            if ("Dispose" == methodName && 0 == argCount && typeof(void) == returnType)
            {
                this.Dispose();
            }
            else if ("ToString" == methodName && 0 == argCount && typeof(string) == returnType)
            {
                returnValue = this.ToString();
            }
            else if ("GetType" == methodName && 0 == argCount && typeof(System.Type) == returnType)
            {
                returnValue = this._InterceptType;
            }
            else if ("GetHashCode" == methodName && 0 == argCount && typeof(int) == returnType)
            {
                returnValue = this.GetHashCode();
            }
            else if ("Equals" == methodName && 1 == argCount && typeof(bool) == returnType)
            {
                returnValue = this.Equals(callMessage.Args[0]);
            }
            else if (1 == argCount && typeof(void) == returnType &&
                     (methodName.StartsWith("add_") || methodName.StartsWith("remove_")))
            {
                bool removeHandler = methodName.StartsWith("remove_");
                methodName = methodName.Substring(removeHandler ? 7 : 4);

                Delegate handler = callMessage.InArgs[0] as Delegate;
                if (null == handler)
                {
                    return(new ReturnMessage(new ArgumentNullException("handler"), callMessage));
                }

                try
                {
                    if (removeHandler)
                    {
                        RemoveEventHandler(methodName, handler);
                    }
                    else
                    {
                        AttachEventHandler(methodName, handler);
                    }
                }
                catch (Exception ex)
                {
                    return(new ReturnMessage(ex, callMessage));
                }
            }
            else
            {
                invokeObject = this._COMObject;
                invokeType   = this._COMType;

                if (methodName.StartsWith("get_"))
                {
                    // Property Get
                    methodName = methodName.Substring(4);
                    flags      = BindingFlags.GetProperty;
                    args       = callMessage.InArgs;
                }
                else if (methodName.StartsWith("set_"))
                {
                    // Property Set
                    methodName = methodName.Substring(4);
                    flags      = BindingFlags.SetProperty;
                    args       = callMessage.InArgs;
                }
                else
                {
                    args = callMessage.Args;
                    if (null != args && 0 != args.Length)
                    {
                        // Modifiers for ref / out parameters
                        argModifiers    = new ParameterModifier[1];
                        argModifiers[0] = new ParameterModifier(args.Length);

                        parameters = method.GetParameters();
                        for (int i = 0; i < parameters.Length; i++)
                        {
                            parameter = parameters[i];
                            if (parameter.IsOut || parameter.ParameterType.IsByRef)
                            {
                                argModifiers[0][i] = true;
                                outArgsCount++;
                            }
                        }

                        if (0 == outArgsCount)
                        {
                            argModifiers = null;
                        }
                    }
                }

                // Un-wrap wrapped COM objects before passing to the method
                if (null == args || 0 == args.Length)
                {
                    originalArgs = null;
                }
                else
                {
                    originalArgs = new COMWrapper[args.Length];
                    for (int i = 0; i < args.Length; i++)
                    {
                        if (null != args[i] && RemotingServices.IsTransparentProxy(args[i]))
                        {
                            wrapper = RemotingServices.GetRealProxy(args[i]) as COMWrapper;
                            if (null != wrapper)
                            {
                                originalArgs[i] = wrapper;
                                args[i]         = wrapper._COMObject;
                            }
                        }
                        else if (0 != outArgsCount && argModifiers[0][i])
                        {
                            byValType = GetByValType(parameters[i].ParameterType);
                            if (byValType.IsInterface)
                            {
                                // If we're passing a COM object by reference, and
                                // the parameter is null, we need to pass a
                                // DispatchWrapper to avoid a type mismatch exception.
                                if (null == args[i])
                                {
                                    args[i] = new DispatchWrapper(null);
                                }
                            }
                            else if (typeof(Decimal) == byValType)
                            {
                                // If we're passing a decimal value by reference,
                                // we need to pass a CurrencyWrapper to avoid a
                                // type mismatch exception.
                                // http://support.microsoft.com/?kbid=837378
                                args[i] = new CurrencyWrapper(args[i]);
                            }
                        }
                    }
                }

                try
                {
                    returnValue = invokeType.InvokeMember(methodName,
                                                          flags, null, invokeObject, args, argModifiers, null, null);
                }
                catch (Exception ex)
                {
                    return(new ReturnMessage(ex, callMessage));
                }

                // Handle enum and interface return types
                if (null != returnValue)
                {
                    if (returnType.IsInterface)
                    {
                        // Wrap the returned value in an intercepting COM wrapper
                        if (Marshal.IsComObject(returnValue))
                        {
                            returnValue = COMWrapper.Wrap(returnValue, returnType);
                        }
                    }
                    else if (returnType.IsEnum)
                    {
                        // Convert to proper Enum type
                        returnValue = Enum.Parse(returnType, returnValue.ToString());
                    }
                }

                // Handle out args
                if (0 != outArgsCount)
                {
                    outArgs = new object[args.Length];
                    for (int i = 0; i < parameters.Length; i++)
                    {
                        if (!argModifiers[0][i])
                        {
                            continue;
                        }

                        arg = args[i];
                        if (null == arg)
                        {
                            continue;
                        }

                        parameter = parameters[i];
                        wrapper   = null;

                        byValType = GetByValType(parameter.ParameterType);
                        if (typeof(Decimal) == byValType)
                        {
                            if (arg is CurrencyWrapper)
                            {
                                arg = ((CurrencyWrapper)arg).WrappedObject;
                            }
                        }
                        else if (byValType.IsEnum)
                        {
                            arg = Enum.Parse(byValType, arg.ToString());
                        }
                        else if (byValType.IsInterface)
                        {
                            if (Marshal.IsComObject(arg))
                            {
                                wrapper = originalArgs[i];
                                if (null != wrapper && wrapper._COMObject != arg)
                                {
                                    wrapper.Dispose();
                                    wrapper = null;
                                }

                                if (null == wrapper)
                                {
                                    wrapper = new COMWrapper(arg, byValType);
                                }
                                arg = wrapper.GetTransparentProxy();
                            }
                        }

                        outArgs[i] = arg;
                    }
                }
            }

            return(new ReturnMessage(returnValue,
                                     outArgs, outArgsCount,
                                     callMessage.LogicalCallContext,
                                     callMessage));
        }
Exemplo n.º 40
0
 protected override MethodInfo GetMethodImpl(string name, BindingFlags bindingAttr, Binder binder, System.Reflection.CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers)
 {
     throw new NotImplementedException();
 }
Exemplo n.º 41
0
 public MethodArgumentDescriptor(TypeDescriptor typeInformation, string argumentName, ParameterModifier modifier)
 {
     TypeInformation = typeInformation;
     ArgumentName    = argumentName;
     Modifier        = modifier;
 }
Exemplo n.º 42
0
 private void AddSoundForDateTimeValue( 
     DateTime value, ParameterModifier modifier, string modifierAtt, List<string> sounds)
 {
     switch (modifier)
     {
         case ParameterModifier.None:
             sounds.AddRange(_soundManager.GetSoundForHours(value.Hour));
             sounds.AddRange(_soundManager.GetSoundForMinutes(value.Minute));
             sounds.AddRange(_soundManager.GetSoundForDayInMonth(value.Day));
             sounds.Add(_soundManager.GetSoundForMonth(value.Month));
             sounds.AddRange(_soundManager.GetSoundForYear(value.Year));
             break;
         case ParameterModifier.hhmm:
             sounds.AddRange(_soundManager.GetSoundForHours(value.Hour));
             sounds.AddRange(_soundManager.GetSoundForMinutes(value.Minute));
             break;
         case ParameterModifier.hhimmi:
             sounds.AddRange(_soundManager.GetSoundForHours(value.Hour, false, NumberDeclension.N_ti));
             sounds.AddRange(_soundManager.GetSoundForMinutes(value.Minute, true, NumberDeclension.N_ti));
             break;
         case ParameterModifier.ddMMyyyy:
             sounds.AddRange(_soundManager.GetSoundForDayInMonth(value.Day));
             sounds.Add(_soundManager.GetSoundForMonth(value.Month));
             sounds.AddRange(_soundManager.GetSoundForYear(value.Year));
             break;
         default:
             throw new Exception("Неподдерживаемый модификатор: " + modifier);
     }
 }
Exemplo n.º 43
0
        /// <summary>
        /// Intercept method calls
        /// </summary>
        /// <param name="myMessage">
        /// Contains information about the method being called
        /// </param>
        /// <returns>
        /// A <see cref="ReturnMessage"/>.
        /// </returns>
        public override IMessage Invoke(IMessage myMessage)
        {
            IMethodCallMessage callMessage = myMessage as IMethodCallMessage;

            if (null == callMessage)
            {
                LOG.DebugFormat("Message type not implemented: {0}", myMessage.GetType().ToString());
                return(null);
            }

            MethodInfo method = callMessage.MethodBase as MethodInfo;

            if (null == method)
            {
                LOG.DebugFormat("Unrecognized Invoke call: {0}", callMessage.MethodBase.ToString());
                return(null);
            }

            object returnValue = null;

            object[] outArgs      = null;
            int      outArgsCount = 0;

            string       methodName = method.Name;
            Type         returnType = method.ReturnType;
            BindingFlags flags      = BindingFlags.InvokeMethod;
            int          argCount   = callMessage.ArgCount;

            object invokeObject;
            Type   invokeType;
            Type   byValType;

            object[] args;
            object   arg;

            COMWrapper[] originalArgs;
            COMWrapper   wrapper;

            ParameterModifier[] argModifiers = null;
            ParameterInfo[]     parameters   = null;
            ParameterInfo       parameter;

            if ("Dispose" == methodName && 0 == argCount && typeof(void) == returnType)
            {
                this.Dispose();
            }
            else if ("ToString" == methodName && 0 == argCount && typeof(string) == returnType)
            {
                returnValue = this.ToString();
            }
            else if ("GetType" == methodName && 0 == argCount && typeof(System.Type) == returnType)
            {
                returnValue = this._InterceptType;
            }
            else if ("GetHashCode" == methodName && 0 == argCount && typeof(int) == returnType)
            {
                returnValue = this.GetHashCode();
            }
            else if ("Equals" == methodName && 1 == argCount && typeof(bool) == returnType)
            {
                returnValue = this.Equals(callMessage.Args[0]);
            }
            else if (1 == argCount && typeof(void) == returnType && (methodName.StartsWith("add_") || methodName.StartsWith("remove_")))
            {
                bool removeHandler = methodName.StartsWith("remove_");
                methodName = methodName.Substring(removeHandler ? 7 : 4);

                Delegate handler = callMessage.InArgs[0] as Delegate;
                if (null == handler)
                {
                    return(new ReturnMessage(new ArgumentNullException("handler"), callMessage));
                }
            }
            else
            {
                invokeObject = this._COMObject;
                invokeType   = this._COMType;

                if (methodName.StartsWith("get_"))
                {
                    // Property Get
                    methodName = methodName.Substring(4);
                    flags      = BindingFlags.GetProperty;
                    args       = callMessage.InArgs;
                }
                else if (methodName.StartsWith("set_"))
                {
                    // Property Set
                    methodName = methodName.Substring(4);
                    flags      = BindingFlags.SetProperty;
                    args       = callMessage.InArgs;
                }
                else
                {
                    args = callMessage.Args;
                    if (null != args && 0 != args.Length)
                    {
                        // Modifiers for ref / out parameters
                        argModifiers    = new ParameterModifier[1];
                        argModifiers[0] = new ParameterModifier(args.Length);

                        parameters = method.GetParameters();
                        for (int i = 0; i < parameters.Length; i++)
                        {
                            parameter = parameters[i];
                            if (parameter.IsOut || parameter.ParameterType.IsByRef)
                            {
                                argModifiers[0][i] = true;
                                outArgsCount++;
                            }
                        }

                        if (0 == outArgsCount)
                        {
                            argModifiers = null;
                        }
                    }
                }

                // Un-wrap wrapped COM objects before passing to the method
                if (null == args || 0 == args.Length)
                {
                    originalArgs = null;
                }
                else
                {
                    originalArgs = new COMWrapper[args.Length];
                    for (int i = 0; i < args.Length; i++)
                    {
                        if (null != args[i] && RemotingServices.IsTransparentProxy(args[i]))
                        {
                            wrapper = RemotingServices.GetRealProxy(args[i]) as COMWrapper;
                            if (null != wrapper)
                            {
                                originalArgs[i] = wrapper;
                                args[i]         = wrapper._COMObject;
                            }
                        }
                        else if (0 != outArgsCount && argModifiers[0][i])
                        {
                            byValType = GetByValType(parameters[i].ParameterType);
                            if (byValType.IsInterface)
                            {
                                // If we're passing a COM object by reference, and
                                // the parameter is null, we need to pass a
                                // DispatchWrapper to avoid a type mismatch exception.
                                if (null == args[i])
                                {
                                    args[i] = new DispatchWrapper(null);
                                }
                            }
                            else if (typeof(Decimal) == byValType)
                            {
                                // If we're passing a decimal value by reference,
                                // we need to pass a CurrencyWrapper to avoid a
                                // type mismatch exception.
                                // http://support.microsoft.com/?kbid=837378
                                args[i] = new CurrencyWrapper(args[i]);
                            }
                        }
                    }
                }

                do
                {
                    try {
                        returnValue = invokeType.InvokeMember(methodName, flags, null, invokeObject, args, argModifiers, null, null);
                        break;
                    } catch (Exception ex) {
                        // Test for rejected
                        COMException comEx = ex as COMException;
                        if (comEx == null)
                        {
                            comEx = ex.InnerException as COMException;
                        }
                        if (comEx != null && (comEx.ErrorCode == RPC_E_CALL_REJECTED || comEx.ErrorCode == COMWrapper.RPC_E_FAIL))
                        {
                            string destinationName = _TargetName;
                            // Try to find a "catchy" name for the rejecting application
                            if (destinationName != null && destinationName.Contains("."))
                            {
                                destinationName = destinationName.Substring(0, destinationName.IndexOf("."));
                            }
                            if (destinationName == null)
                            {
                                destinationName = _InterceptType.FullName;
                            }
                            DialogResult result = MessageBox.Show(PluginUtils.Host.GreenshotForm, Language.GetFormattedString("com_rejected", destinationName), Language.GetString("com_rejected_title"), MessageBoxButtons.OKCancel, MessageBoxIcon.Exclamation);
                            if (result == DialogResult.OK)
                            {
                                continue;
                            }
                        }
                        // Not rejected OR pressed cancel
                        return(new ReturnMessage(ex, callMessage));
                    }
                } while (true);

                // Handle enum and interface return types
                if (null != returnValue)
                {
                    if (returnType.IsInterface)
                    {
                        // Wrap the returned value in an intercepting COM wrapper
                        if (Marshal.IsComObject(returnValue))
                        {
                            returnValue = COMWrapper.Wrap(returnValue, returnType, _TargetName);
                        }
                    }
                    else if (returnType.IsEnum)
                    {
                        // Convert to proper Enum type
                        returnValue = Enum.Parse(returnType, returnValue.ToString());
                    }
                }

                // Handle out args
                if (0 != outArgsCount)
                {
                    outArgs = new object[args.Length];
                    for (int i = 0; i < parameters.Length; i++)
                    {
                        if (!argModifiers[0][i])
                        {
                            continue;
                        }

                        arg = args[i];
                        if (null == arg)
                        {
                            continue;
                        }

                        parameter = parameters[i];
                        wrapper   = null;

                        byValType = GetByValType(parameter.ParameterType);
                        if (typeof(Decimal) == byValType)
                        {
                            if (arg is CurrencyWrapper)
                            {
                                arg = ((CurrencyWrapper)arg).WrappedObject;
                            }
                        }
                        else if (byValType.IsEnum)
                        {
                            arg = Enum.Parse(byValType, arg.ToString());
                        }
                        else if (byValType.IsInterface)
                        {
                            if (Marshal.IsComObject(arg))
                            {
                                wrapper = originalArgs[i];
                                if (null != wrapper && wrapper._COMObject != arg)
                                {
                                    wrapper.Dispose();
                                    wrapper = null;
                                }

                                if (null == wrapper)
                                {
                                    wrapper = new COMWrapper(arg, byValType, _TargetName);
                                }
                                arg = wrapper.GetTransparentProxy();
                            }
                        }
                        outArgs[i] = arg;
                    }
                }
            }

            return(new ReturnMessage(returnValue, outArgs, outArgsCount, callMessage.LogicalCallContext, callMessage));
        }
Exemplo n.º 44
0
 private void AddSoundForStringValue( 
     String value, ParameterModifier modifier, string modifierAtt, List<string> sounds)
 {
     if (string.IsNullOrEmpty(value))
         return;
     sounds.Add(value.Length == 1
                    ? _soundManager.GetSoundForLetter(value[0])
                    : _soundManager.SoundsDirPath + value);
 }
Exemplo n.º 45
0
 /// <summary>
 /// Calls the specified method by name and given argument types and values.
 /// </summary>
 /// <param name="name">The name of the method to call.</param>
 /// <param name="argTypes">The method argument types.</param>
 /// <param name="argModifiers">The argument type modifiers, such as out and ref.</param>
 /// <param name="argValues">The argument values to pass to the method.</param>
 /// <returns>The value returned by the specified method.</returns>
 public object CallMethod(string name, ICollection <Type> argTypes, ParameterModifier argModifiers, object[] argValues)
 {
     return(ProfilerInterceptor.GuardInternal(() => CallMethodInternal(name, argTypes, new[] { argModifiers }, argValues)));
 }
Exemplo n.º 46
0
 private void AppendTextForDateTimeValue( 
     DateTime value, ParameterModifier modifier, string modifierAtt, StringBuilder sb)
 {
     switch (modifier)
     {
         case ParameterModifier.None:
             sb.Append(value.ToString("HH:mm dd.MM.yyyy"));
             break;
         case ParameterModifier.hhmm:
             sb.Append(value.ToString("HH:mm"));
             break;
         case ParameterModifier.ddMMyyyy:
             sb.AppendFormat(value.ToString("dd.MM.yyyy"));
             break;
         default:
             throw new Exception("Неподдерживаемый модификатор: " + modifier);
     }
 }
Exemplo n.º 47
0
 public ParameterModifierLiteral(ParameterModifier modifier, TextSpan textSpan, FileNode fileNode)
     : base(textSpan, fileNode)
 {
     Modifier = modifier;
 }
Exemplo n.º 48
0
 private void AppendTextForTimeSpanValue( 
     TimeSpan value, ParameterModifier modifier, string modifierAtt, StringBuilder sb)
 {
     switch (modifier)
     {
         case ParameterModifier.None:
         case ParameterModifier.hhmm:
             sb.Append(string.Format("{0:00}:{1:00}", value.Hours, value.Minutes));
             break;
         default:
             throw new Exception("Неподдерживаемый модификатор: " + modifier);
     }
 }
Exemplo n.º 49
0
        static string TypeToStringInternal(IType t, bool includeNamespace, bool useBuiltinTypeNames = true, ParameterModifier parameterModifier = ParameterModifier.None)
        {
            TypeSystemAstBuilder builder = new TypeSystemAstBuilder();

            builder.AlwaysUseShortTypeNames   = !includeNamespace;
            builder.AlwaysUseBuiltinTypeNames = useBuiltinTypeNames;

            const ParameterModifier refInOutModifier = ParameterModifier.Ref | ParameterModifier.Out | ParameterModifier.In;

            AstType astType = builder.ConvertType(t);

            if ((parameterModifier & refInOutModifier) != 0 && astType is ComposedType ct && ct.HasRefSpecifier)
            {
                ct.HasRefSpecifier = false;
            }

            StringWriter w = new StringWriter();

            astType.AcceptVisitor(new CSharpOutputVisitor(w, TypeToStringFormattingOptions));
            string output = w.ToString();

            switch (parameterModifier)
            {
            case ParameterModifier.Ref:
                output = "ref " + output;
                break;

            case ParameterModifier.Out:
                output = "out " + output;
                break;

            case ParameterModifier.In:
                output = "in " + output;
                break;
            }

            return(output);
        }
Exemplo n.º 50
0
 /// <summary>
 /// 
 /// </summary>
 /// <param name="bindingAttr"></param>
 /// <param name="match"></param>
 /// <param name="types"></param>
 /// <param name="modifiers"></param>
 /// <returns></returns>
 public override MethodBase SelectMethod(
     BindingFlags bindingAttr,
     MethodBase[] match,
     Type[] types,
     ParameterModifier[] modifiers
     )
 {
     if (match == null)
         throw new ArgumentNullException("match");
     for (int i = 0; i < match.Length; i++)
     {
         // Count the number of parameters that match.
         int count = 0;
         ParameterInfo[] parameters = match[i].GetParameters();
         // Go on to the next method if the number of parameters do not match.
         if (types.Length != parameters.Length)
             continue;
         // Match each of the parameters that the user expects the method to have.
         for (int j = 0; j < types.Length; j++)
             // Determine whether the types specified by the user can be converted to parameter type.
             if (CanConvertFrom(types[j], parameters[j].ParameterType))
                 count += 1;
             else
                 break;
         // Determine whether the method has been found.
         if (count == types.Length)
             return match[i];
     }
     return null;
 }
Exemplo n.º 51
0
 public ArrayParameter(ParameterModifier modifier, TypeIdentifier type, Identifier identifier, IntLiteral size) : base(modifier, type, identifier, null)
 {
     Size = size;
 }
Exemplo n.º 52
0
		public void ChangeModifier(ParameterDeclaration param, ParameterModifier modifier)
		{
			var child = param.FirstChild;
			Func<AstNode, bool> pred = s => s.Role == ParameterDeclaration.RefModifierRole || s.Role == ParameterDeclaration.OutModifierRole || s.Role == ParameterDeclaration.ParamsModifierRole || s.Role == ParameterDeclaration.ThisModifierRole;
			if (!pred(child))
				child = child.GetNextSibling(pred); 

			int offset;
			int endOffset;

			if (child != null) {
				offset = GetCurrentOffset(child.StartLocation);
				endOffset = GetCurrentOffset(child.GetNextSibling (s => s.Role != Roles.NewLine && s.Role != Roles.Whitespace).StartLocation);
			} else {
				offset = endOffset = GetCurrentOffset(param.Type.StartLocation);
			}
			string modString;
			switch (modifier) {
				case ParameterModifier.None:
					modString = "";
					break;
				case ParameterModifier.Ref:
					modString = "ref ";
					break;
				case ParameterModifier.Out:
					modString = "out ";
					break;
				case ParameterModifier.Params:
					modString = "params ";
					break;
				case ParameterModifier.This:
					modString = "this ";
					break;
				default:
					throw new ArgumentOutOfRangeException();
			}
			Replace(offset, endOffset - offset, modString);
		}
 public void SetModifier(ParameterModifier modifier)
 {
     Assert.AreEqual(this.modifier, modifier);
 }