示例#1
0
        internal object ConvertBackWithConverter(
            CBORObject cbor,
            Type type)
        {
            ConverterInfo convinfo = null;

            if (this.converters.ContainsKey(type))
            {
                convinfo = this.converters[type];
            }
            else
            {
                return(null);
            }
            if (convinfo == null)
            {
                return(null);
            }
            if (convinfo.FromObject == null)
            {
                return(null);
            }
            return(PropertyMap.InvokeOneArgumentMethod(
                       convinfo.FromObject,
                       convinfo.Converter,
                       cbor));
        }
示例#2
0
            public int OleDragEnter(IntPtr pDataObj, int grfKeyState, long pt, ref int pdwEffect)
            {
                object     nativeDataObject = Marshal.GetObjectForIUnknown(pDataObj);
                DataObject dataObject       = new DataObject(nativeDataObject);

                this.converterInfo = this.converter.CanConvertToHtml(dataObject);
                if (this.converterInfo == ConverterInfo.Yes)
                {
                    this.currentDataObj = new DataObject(DataFormats.Html, String.Empty);

                    IntPtr pUnk = Marshal.GetIUnknownForObject(this.currentDataObj);

                    // Get the IOleDataObject interface for the object
                    Guid guid = new Guid("0000010E-0000-0000-C000-000000000046");
                    Marshal.QueryInterface(pUnk, ref guid, out this.currentDataObjPtr);
                    Marshal.Release(pUnk);

                    return(this.originalDropTarget.OleDragEnter(this.currentDataObjPtr, grfKeyState, pt, ref pdwEffect));
                }
                else if (this.converterInfo == ConverterInfo.No)
                {
                    // ignore this drag/drop
                    pdwEffect = 0;
                }
                else if (this.converterInfo == ConverterInfo.Unknown)
                {
                    // If the converter doesn't know anything about this data object, just use the original data object
                    return(this.originalDropTarget.OleDragEnter(pDataObj, grfKeyState, pt, ref pdwEffect));
                }
                else
                {
                    Debug.Fail("Unknown ConverterInfo value!");
                }
                return(NativeMethods.S_OK);
            }
示例#3
0
        private object[] GetParametersUsingCompiledDelgates(RpcJsonReader reader, ConverterInfo converter, JsonSerializer serializer)
        {
            if (reader.Read())
            {
                if (reader.TokenType == JsonToken.StartArray)
                {
                    reader.Read();

                    var deserializer = converter.ParameterArrayDeserializer ??
                                       (converter.ParameterArrayDeserializer =
                                            _parameterArrayDeserializerBuilder.BuildDeserializer(converter.ExposedMethod));

                    return(deserializer(reader.Context, reader, serializer));
                }

                if (reader.TokenType == JsonToken.StartObject)
                {
                    reader.Read();

                    var deserializer = converter.NamedParamsDeserializer ??
                                       (converter.NamedParamsDeserializer =
                                            _namedParameterDeserializerBuilder.BuildDeserializer(converter.ExposedMethod));

                    return(deserializer(reader.Context, reader, serializer));
                }

                if (reader.TokenType == JsonToken.Null)
                {
                    return(new object[0]);
                }
            }

            throw new Exception("Could not read parameters");
        }
示例#4
0
        /// <summary>Registers an object that converts objects of a given type
        /// to CBOR objects (called a CBOR converter).</summary>
        /// <param name='type'>A Type object specifying the type that the
        /// converter converts to CBOR objects.</param>
        /// <param name='converter'>The parameter <paramref name='converter'/>
        /// is an ICBORConverter object.</param>
        /// <typeparam name='T'>Must be the same as the "type"
        /// parameter.</typeparam>
        /// <returns>This object.</returns>
        /// <exception cref='ArgumentNullException'>The parameter <paramref
        /// name='type'/> or <paramref name='converter'/> is null.</exception>
        /// <exception cref='ArgumentException'>Converter doesn't contain a
        /// proper ToCBORObject method".</exception>
        public CBORTypeMapper AddConverter <T>(
            Type type,
            ICBORConverter <T> converter)
        {
            if (type == null)
            {
                throw new ArgumentNullException(nameof(type));
            }
            if (converter == null)
            {
                throw new ArgumentNullException(nameof(converter));
            }
            var ci = new ConverterInfo();

            ci.Converter = converter;
            ci.ToObject  = PropertyMap.FindOneArgumentMethod(
                converter,
                "ToCBORObject",
                type);
            if (ci.ToObject == null)
            {
                throw new ArgumentException(
                          "Converter doesn't contain a proper ToCBORObject method");
            }
            ci.FromObject = PropertyMap.FindOneArgumentMethod(
                converter,
                "FromCBORObject",
                typeof(CBORObject));
            this.converters[type] = ci;
            return(this);
        }
示例#5
0
        public CollectionAssociation(Expression <Func <TSource, IEnumerable <TSourceItem> > > source, Expression <Func <TTarget, IEnumerable <TTargetItem> > > target, Expression <Func <TSourceItem, TTargetItem> > converter)
            : base(source, target)
        {
            Contract.Assert(converter != null);

            TargetConverter = new ConverterInfo(converter);
        }
示例#6
0
        private readonly TypeInfo m_typeInfo; // Corresponding type info

        #endregion Fields

        #region Constructors

        public ConvEnumExternal(ConverterInfo info, TypeInfo typeInfo, Type managedType)
        {
            m_typeInfo = typeInfo;
            m_managedType = managedType;

            info.AddToSymbolTable(typeInfo, ConvType.Enum, this);
            info.RegisterType(managedType, this);
        }
示例#7
0
        private readonly TypeInfo m_typeInfo; // Corresponding type info

        #endregion Fields

        #region Constructors

        public ConvCoClassExternal(ConverterInfo info, TypeInfo typeInfo, Type managedType, ConverterAssemblyInfo converterAssemblyInfo)
        {
            m_typeInfo = typeInfo;
            m_managedType = managedType;

            info.RegisterType(managedType, this);

            TypeInfo defaultTypeInfo = ConvCommon.GetDefaultInterface(ConvCommon.GetAlias(typeInfo));
            if (defaultTypeInfo != null)
                m_defaultInterface = info.GetTypeRef(ConvType.Interface, defaultTypeInfo) as IConvInterface;
        }
示例#8
0
 internal CBORObject ConvertWithConverter(object obj) {
   Object type = obj.GetType();
   ConverterInfo convinfo = null;
   if (this.converters.ContainsKey(type)) {
     convinfo = this.converters[type];
   } else {
     return null;
   }
   return (convinfo == null) ? null :
     PropertyMap.CallToObject(convinfo, obj);
 }
示例#9
0
 /// <summary>
 /// Add a converter to this PatternLayout
 /// </summary>
 /// <param name="converterInfo">the converter info</param>
 /// <remarks>
 /// <para>
 /// This version of the method is used by the configurator.
 /// Programmatic users should use the alternative <see cref="M:AddConverter(string,Type)" /> method.
 /// </para>
 /// </remarks>
 public void AddConverter(ConverterInfo converterInfo)
 {
     if (converterInfo == null)
     {
         throw new ArgumentNullException("converterInfo");
     }
     if (!CompatibilityExtensions.IsAssignableFrom(typeof(PatternConverter), converterInfo.Type))
     {
         throw new ArgumentException("The converter type specified [" + converterInfo.Type + "] must be a subclass of log4net.Util.PatternConverter", "converterInfo");
     }
     m_instanceRulesRegistry[converterInfo.Name] = converterInfo;
 }
示例#10
0
        public PropertyToPropertyWithConversionAssociation(
            Expression <Func <TSource, TSourceProperty> > source,
            Expression <Func <TSourceProperty, TTargetProperty> > sourceConverter,
            Expression <Func <TTarget, TTargetProperty> > target,
            Expression <Func <TTargetProperty, TSourceProperty> > targetConverter
            ) : base(source, target)
        {
            Contract.Assert(sourceConverter != null);
            Contract.Assert(targetConverter != null);

            SourceConverter = new ConverterInfo(sourceConverter);
            TargetConverter = new ConverterInfo(targetConverter);
        }
        /// <summary>
        /// Add a converter to this PatternLayout
        /// </summary>
        /// <param name="converterInfo">the converter info</param>
        /// <remarks>
        /// <para>
        /// This version of the method is used by the configurator.
        /// Programmatic users should use the alternative <see cref="M:AddConverter(string,Type)"/> method.
        /// </para>
        /// </remarks>
        public void AddConverter(ConverterInfo converterInfo)
        {
            if (converterInfo == null)
            {
                throw new ArgumentNullException("converterInfo");
            }

            if (!typeof(PatternConverter).IsAssignableFrom(converterInfo.Type))
            {
                throw new ArgumentException("The converter type specified [" + converterInfo.Type + "] must be a subclass of Mammothcode.Public.Core.Util.PatternConverter", "converterInfo");
            }
            m_instanceRulesRegistry[converterInfo.Name] = converterInfo;
        }
示例#12
0
        /// <summary>
        /// Fetch our own <see cref="PatternConverter"/> SerializingConverter.
        /// </summary>
        /// <param name="info">description of the PatternConverter</param>
        /// <returns>pattern converter set up</returns>
        /// <remarks>
        /// <para>
        /// Please note that properties are only supported with log4net 1.2.11 and above.
        /// </para>
        /// </remarks>
        protected virtual PatternConverter CreateSerializingConverter(ConverterInfo info)
        {
            var conv = info.Type == null ? null : Activator.CreateInstance(info.Type) as PatternConverter;

            if (conv == null)
            {
                conv = new JsonPatternConverter();
            }

            conv.Properties = info.Properties;

            return(conv);
        }
示例#13
0
 internal object ConvertBackWithConverter(
   CBORObject cbor,
   Type type) {
   ConverterInfo convinfo = null;
   if (this.converters.ContainsKey(type)) {
     convinfo = this.converters[type];
   } else {
     return null;
   }
   if (convinfo == null) {
     return null;
   }
   return (convinfo.FromObject == null) ? null :
     PropertyMap.CallFromObject(convinfo, cbor);
 }
示例#14
0
        protected override PatternParser CreatePatternParser(string pattern)
        {
            var parser = base.CreatePatternParser(pattern);

            foreach (DictionaryEntry entry in SGlobalRulesRegistry)
            {
                var info = new ConverterInfo
                {
                    Name = (string)entry.Key,
                    Type = (Type)entry.Value
                };
                parser.PatternConverters[entry.Key] = info;
            }

            return(parser);
        }
示例#15
0
        /// <summary>
        /// Add a converter to this PatternLayout
        /// </summary>
        /// <param name="name">the name of the conversion pattern for this converter</param>
        /// <param name="type">the type of the converter</param>
        /// <remarks>
        /// <para>
        /// Add a named pattern converter to this instance. This
        /// converter will be used in the formatting of the event.
        /// This method must be called before <see cref="M:log4net.Layout.PatternLayout.ActivateOptions" />.
        /// </para>
        /// <para>
        /// The <paramref name="type" /> specified must extend the
        /// <see cref="T:log4net.Util.PatternConverter" /> type.
        /// </para>
        /// </remarks>
        public void AddConverter(string name, Type type)
        {
            if (name == null)
            {
                throw new ArgumentNullException("name");
            }
            if ((object)type == null)
            {
                throw new ArgumentNullException("type");
            }
            ConverterInfo converterInfo = new ConverterInfo();

            converterInfo.Name = name;
            converterInfo.Type = type;
            AddConverter(converterInfo);
        }
示例#16
0
            public int OleDragLeave()
            {
                this.converterInfo = ConverterInfo.No;

                if (this.currentDataObj != null)
                {
                    this.currentDataObj = null;
                    Marshal.Release(this.currentDataObjPtr);
                    this.currentDataObjPtr = IntPtr.Zero;

                    return(this.originalDropTarget.OleDragLeave());
                }

                // If the DataObject was never set (meaning we cancelled the drag/drop), don't pass on the DragLeave since
                // we never passed in the DragEnter
                return(NativeMethods.S_OK);
            }
示例#17
0
        public void AddConverter(string name, Type type)
        {
            if (name == null)
            {
                throw new ArgumentNullException("name");
            }
            if (type == null)
            {
                throw new ArgumentNullException("type");
            }
            ConverterInfo converterInfo = new ConverterInfo {
                Name = name,
                Type = type
            };

            this.AddConverter(converterInfo);
        }
示例#18
0
        /// <summary>
        /// 对Hashtable中的值进行转换
        /// </summary>
        /// <param name="pattern"></param>
        /// <returns></returns>
        virtual protected PatternParser CreatePatternParser(string pattern)
        {
            PatternParser patternParser = new PatternParser(pattern);

            foreach (DictionaryEntry entry in s_globalRulesRegistry)
            {
                ConverterInfo converterInfo = new ConverterInfo();
                converterInfo.Name = (string)entry.Key;
                converterInfo.Type = (Type)entry.Value;
                patternParser.PatternConverters[entry.Key] = converterInfo;
            }
            foreach (DictionaryEntry entry in m_instanceRulesRegistry)
            {
                patternParser.PatternConverters[entry.Key] = entry.Value;
            }
            return(patternParser);
        }
示例#19
0
        private readonly TypeInfo m_typeInfo; // Corresponding type info

        #endregion Fields

        #region Constructors

        public ConvClassInterfaceExternal(ConverterInfo info, TypeInfo typeInfo, Type managedType, ConverterAssemblyInfo converterAssemblyInfo)
        {
            m_typeInfo = typeInfo;
            m_managedType = managedType;

            info.RegisterType(managedType, this);

            //
            // Associate the default interface with the class interface
            //
            TypeInfo defaultInterfaceTypeInfo;
            if (converterAssemblyInfo.ClassInterfaceMap.GetExclusiveDefaultInterfaceForCoclass(typeInfo, out defaultInterfaceTypeInfo))
            {
                var convInterface = info.GetTypeRef(ConvType.Interface, defaultInterfaceTypeInfo) as IConvInterface;
                convInterface.AssociateWithExclusiveClassInterface(this);
            }
        }
示例#20
0
        protected virtual PatternParser CreatePatternParser(string pattern)
        {
            PatternParser         parser     = new PatternParser(pattern);
            IDictionaryEnumerator enumerator = s_globalRulesRegistry.GetEnumerator();

            try
            {
                while (enumerator.MoveNext())
                {
                    DictionaryEntry current = (DictionaryEntry)enumerator.Current;
                    ConverterInfo   info    = new ConverterInfo {
                        Name = (string)current.Key,
                        Type = (Type)current.Value
                    };
                    parser.PatternConverters[current.Key] = info;
                }
            }
            finally
            {
                IDisposable disposable = enumerator as IDisposable;
                if (disposable != null)
                {
                    disposable.Dispose();
                }
            }
            IDictionaryEnumerator enumerator2 = this.m_instanceRulesRegistry.GetEnumerator();

            try
            {
                while (enumerator2.MoveNext())
                {
                    DictionaryEntry current = (DictionaryEntry)enumerator2.Current;
                    parser.PatternConverters[current.Key] = current.Value;
                }
            }
            finally
            {
                IDisposable disposable2 = enumerator2 as IDisposable;
                if (disposable2 != null)
                {
                    disposable2.Dispose();
                }
            }
            return(parser);
        }
        private JToken GetJObjectMultiBinding (ConverterInfo conv, string afterExpr)
        {
            if (afterExpr.StartsWith(","))
                afterExpr = afterExpr.Substring(1).Trim();
            string strMultiBinding = string.Format("{{MultiBinding {0}}}", afterExpr);

            JObject xmlMultiBinding = GetJObjectFromMarkupExt(strMultiBinding);
            {
                xmlMultiBinding.Add(pnConverter, FormatGeneratedConverterReference(conv.Name));
                xmlMultiBinding.Add(pnContent, new JArray());
                {
                    var content = (JArray)xmlMultiBinding[pnContent];
                    foreach (string strSubBinding in conv.SubBindings)
                        content.Add(GetJObjectFromMarkupExt(strSubBinding));
                }
            }
            return xmlMultiBinding;
        }
示例#22
0
        public static void RegisterGlobalTypeConverter(Type type, ITypeConverter typeConverter, EngineType engineType)
        {
            Dictionary <Type, ConverterInfo> globalConverterInfos = engineType switch
            {
                EngineType.MySQL => _mysqlGlobalConverterInfos,
                EngineType.SQLite => _sqliteGlobalConverterInfos,
                _ => throw new NotSupportedException(),
            };

            ConverterInfo converterInfo = new ConverterInfo
            {
                DbType        = typeConverter.DbType,
                Statement     = typeConverter.Statement,
                TypeConverter = typeConverter
            };

            globalConverterInfos[type] = converterInfo;
        }
示例#23
0
        private bool m_useDefaultMarshal; // Whether we marshal by default or marshal by UnmanagedType

        #endregion Fields

        #region Constructors

        public TypeConverter(ConverterInfo info, TypeInfo type, TypeDesc desc, ConversionType conversionType)
        {
            m_info = info;
            m_typeInfo = type;
            m_typeDesc = desc;
            m_conversionType = conversionType;

            m_paramDesc = null;
            m_attribute = null;
            m_conversionLoss = false;
            m_convertedType = null;
            m_nativeIndirections = 0;
            m_convertingNewEnumMember = false;

            ResetUnmanagedType();

            // Do the conversion
            _Convert();
        }
示例#24
0
        private PatternParser CreatePatternParser(string pattern)
        {
            PatternParser patternParser = new PatternParser(pattern);

            // Add all the builtin patterns
            foreach (DictionaryEntry entry in s_globalRulesRegistry)
            {
                ConverterInfo converterInfo = new ConverterInfo();
                converterInfo.Name = (string)entry.Key;
                converterInfo.Type = (Type)entry.Value;
                patternParser.PatternConverters.Add(entry.Key, converterInfo);
            }
            // Add the instance patterns
            foreach (DictionaryEntry entry in m_instanceRulesRegistry)
            {
                patternParser.PatternConverters[entry.Key] = entry.Value;
            }

            return(patternParser);
        }
示例#25
0
        /// <summary>
        /// Create an instance from a <see cref="ConverterInfo"/>, instantiating it's <see cref="PatternConverter"/>.
        /// </summary>
        /// <remarks>
        /// Properties["option"] (a <see cref="String"/>) can be used to set an option on the converter instance.
        /// </remarks>
        /// <remarks>
        /// Properties are only supported in log4net 1.2.11 and later.
        /// </remarks>
        /// <param name="info"></param>
        public RawCallLayout(ConverterInfo info)
        {
            Name = info.Name;

            var conv = (PatternConverter)Activator.CreateInstance(info.Type);

            conv.Properties = info.Properties;

            if (info.Properties.Contains("option"))
            {
                conv.Option = Convert.ToString(info.Properties["option"]);
            }

            if (conv is IOptionHandler)
            {
                ((IOptionHandler)conv).ActivateOptions();
            }

            m_getter = (e) => Format(conv, e);
            m_info   = info;
        }
示例#26
0
        /// <summary>
        /// Create the pattern parser instance
        /// </summary>
        /// <param name="pattern">the pattern to parse</param>
        /// <returns>The <see cref="PatternParser"/> that will format the event</returns>
        /// <remarks>
        /// <para>
        /// Creates the <see cref="PatternParser"/> used to parse the conversion string. Sets the
        /// global and instance rules on the <see cref="PatternParser"/>.
        /// </para>
        /// </remarks>
        virtual protected PatternParser CreatePatternParser(string pattern)
        {
            PatternParser patternParser = new PatternParser(pattern);

            // Add all the builtin patterns
            foreach (DictionaryEntry entry in s_globalRulesRegistry)
            {
                ConverterInfo converterInfo = new ConverterInfo
                {
                    Name = (string)entry.Key,
                    Type = (Type)entry.Value
                };
                patternParser.PatternConverters[entry.Key] = converterInfo;
            }
            // Add the instance patterns
            foreach (DictionaryEntry entry in m_instanceRulesRegistry)
            {
                patternParser.PatternConverters[entry.Key] = entry.Value;
            }

            return(patternParser);
        }
示例#27
0
        internal CBORObject ConvertWithConverter(object obj)
        {
            Object        type     = obj.GetType();
            ConverterInfo convinfo = null;

            if (this.converters.ContainsKey(type))
            {
                convinfo = this.converters[type];
            }
            else
            {
                return(null);
            }
            if (convinfo == null)
            {
                return(null);
            }
            return((CBORObject)PropertyMap.InvokeOneArgumentMethod(
                       convinfo.ToObject,
                       convinfo.Converter,
                       obj));
        }
示例#28
0
            public int OleDrop(IntPtr pDataObj, int grfKeyState, long pt, ref int pdwEffect)
            {
                int hr = NativeMethods.S_OK;

                if (this.converterInfo == ConverterInfo.Yes)
                {
                    object     nativeDataObject = Marshal.GetObjectForIUnknown(pDataObj);
                    DataObject dataObject       = new DataObject(nativeDataObject);

                    bool mapped = this.converter.ConvertToHtml(dataObject, this.currentDataObj);
                    if (mapped)
                    {
                        IntPtr pUnk = Marshal.GetIUnknownForObject(this.currentDataObj);

                        // Get the IOleDataObject interface for the object
                        Guid guid = new Guid("0000010E-0000-0000-C000-000000000046");
                        Marshal.QueryInterface(pUnk, ref guid, out this.currentDataObjPtr);

                        hr = this.originalDropTarget.OleDrop(this.currentDataObjPtr, grfKeyState, pt, ref pdwEffect);

                        this.currentDataObj    = null;
                        this.currentDataObjPtr = IntPtr.Zero;
                        Marshal.Release(this.currentDataObjPtr);
                    }
                    else
                    {
                        pdwEffect = 0;
                    }
                }
                else if (this.converterInfo == ConverterInfo.Unknown)
                {
                    hr = this.originalDropTarget.OleDrop(pDataObj, grfKeyState, pt, ref pdwEffect);
                }

                this.converterInfo = ConverterInfo.No;

                return(hr);
            }
示例#29
0
        private ConverterInfo GetConverter(string urlPath, string method)
        {
            var exposedMethod = _cacheManager.GetExposedMethodInformation(urlPath, method);

            if (exposedMethod == null)
            {
                return(null);
            }

            var converter = (ConverterInfo)exposedMethod.GetSerializerData(_serializerId);

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

            converter = new ConverterInfo {
                ExposedMethod = exposedMethod
            };

            exposedMethod.SetSerializerData(_serializerId, converter);

            return(converter);
        }
示例#30
0
        private void Init(ConverterInfo info, TypeBuilder typeBuilder, bool emitDispId, TypeInfo type, TypeAttr attr, bool bCoClass, bool bSource, TypeInfo implementingInterface)
        {
            m_typeStack = new Stack<TypeInfo>();

            m_attrStack = new Stack<TypeAttr>();
            PushType(type, attr);

            m_info = info;
            m_typeBuilder = typeBuilder;
            m_emitDispId = emitDispId;
            m_bCoClass = bCoClass;
            m_propertyInfo = new PropertyInfo(this);
            m_bSource = bSource;
            IsConversionLoss = false;
            IsDefaultInterface = false;
            m_currentSlot = 0;
            m_currentImplementingInterface = implementingInterface;
        }
示例#31
0
		/// <summary>
		/// Add a converter to this PatternLayout
		/// </summary>
		/// <param name="name">the name of the conversion pattern for this converter</param>
		/// <param name="type">the type of the converter</param>
		/// <remarks>
		/// <para>
		/// Add a named pattern converter to this instance. This
		/// converter will be used in the formatting of the event.
		/// This method must be called before <see cref="ActivateOptions"/>.
		/// </para>
		/// <para>
		/// The <paramref name="type"/> specified must extend the 
		/// <see cref="PatternConverter"/> type.
		/// </para>
		/// </remarks>
		public void AddConverter(string name, Type type) {
			if (name == null)
				throw new ArgumentNullException("name");
			if (type == null)
				throw new ArgumentNullException("type");

			ConverterInfo converterInfo = new ConverterInfo();
			converterInfo.Name = name;
			converterInfo.Type = type;

			AddConverter(converterInfo);
		}
示例#32
0
 Converter GetConverterInstance(ConverterInfo info) =>
 _converterCache[info.ConverterId] ??= (Converter)Activator.CreateInstance(info.ConverterType) !;
示例#33
0
        /// <summary>
        /// Override the dispid if Guid_DispIdOverride is present
        /// </summary>
        /// <param name="index">The index of the func/var, not the disp id</param>
        /// <returns>Whether we have Guid_DispIdOverride or not</returns>
        public static bool GetOverrideDispId(ConverterInfo info, TypeInfo typeInfo, int index, InterfaceMemberType memberType, ref int dispid, bool isSet)
        {
            bool hasOverride = false;
            object data;

            if (memberType == InterfaceMemberType.Method)
                data = typeInfo.GetFuncCustData(index, CustomAttributeGuids.GUID_DispIdOverride);
            else
            {
                Debug.Assert(memberType == InterfaceMemberType.Variable);
                data = typeInfo.GetVarCustData(index, CustomAttributeGuids.GUID_DispIdOverride);
            }

            if (data is short)
            {
                dispid = (short)data;
                hasOverride = true;
            }
            else if (data is int)
            {
                dispid = (int)data;
                hasOverride = true;
            }
            else if (data != null)
            {
                // We only emit Wrn_NonIntegralCustomAttributeType when we set the id
                if (isSet)
                {
                    //
                    // Emit Wrn_NonIntegralCustomAttributeType warning
                    //
                    info.ReportEvent(
                        WarningCode.Wrn_NonIntegralCustomAttributeType,
                        Resource.FormatString("Wrn_NonIntegralCustomAttributeType", "{" + CustomAttributeGuids.GUID_DispIdOverride.ToString().ToUpper() + "}", typeInfo.GetDocumentation(dispid)));
                }
            }

            return hasOverride;
        }
示例#34
0
        /// <summary>
        /// Check for optional arguments
        /// </summary>
        public static void CheckForOptionalArguments(ConverterInfo info, FuncDesc func, out int varArg, out int firstOptArg, out int lastOptArg)
        {
            int numOfParams = func.cParams;
            varArg = firstOptArg = lastOptArg = numOfParams + 1;

            if (func.cParamsOpt == -1)
            {
                //
                // [vararg] scenario
                //

                // For propput/propputref, the last parameter will be the value to be set
                bool skipPropPutArg = false;
                if ((func.invkind & (TypeLibTypes.Interop.INVOKEKIND.INVOKE_PROPERTYPUT | TypeLibTypes.Interop.INVOKEKIND.INVOKE_PROPERTYPUTREF)) != 0)
                    skipPropPutArg = true;

                // vararg will be the last argument except for lcid arguments & retval arguments
                for (int target = numOfParams - 1; target >= 0; --target)
                {
                    // skip lcid/retval
                    ParamDesc paramDesc = func.GetElemDesc(target).paramdesc;
                    if (IsRetVal(info, paramDesc, func) || paramDesc.IsLCID)
                        continue;

                    // skip for property
                    if (skipPropPutArg)
                    {
                        skipPropPutArg = false;
                        continue;
                    }

                    varArg = target;
                    break;
                }

                Debug.Assert(varArg < numOfParams);
            }
            else if (func.cParamsOpt > 0)
            {
                //
                // [optional] scenario
                //
                int countOfOptionals = func.cParamsOpt;
                firstOptArg = 0;

                // find the first optional arg
                for (int target = func.cParams - 1; target >= 0; --target)
                {
                    // The count of optional params does not include any lcid params, nor does
                    // it include the return value, so skip those.
                    ParamDesc param = func.GetElemDesc(target).paramdesc;
                    if (!(param.IsRetval || param.IsRetval))
                    {
                        if (--countOfOptionals == 0)
                        {
                            firstOptArg = target;
                            break;
                        }
                    }
                }

                lastOptArg = firstOptArg + func.cParamsOpt;
            }
        }
示例#35
0
 public InterfaceInfo(ConverterInfo info, TypeBuilder typeBuilder, bool supportsDispatch, TypeInfo type, TypeAttr attr, bool bCoClass, bool bSource, TypeInfo implementingInterface)
 {
     Init(info, typeBuilder, supportsDispatch, type, attr, bCoClass, bSource, implementingInterface);
 }
示例#36
0
        public static bool HasNewEnumMember(ConverterInfo info, TypeInfo typeInfo, string fullName)
        {
            bool hasNewEnumMember = false;
            bool hasDuplicateNewEnumMember = false;
            int firstNewEnum = -1;

            using (TypeAttr attr = typeInfo.GetTypeAttr())
            {
                if (attr.IsDispatch ||
                    (attr.IsInterface && ConvCommon.IsDerivedFromIDispatch(typeInfo)))
                {
                    // Check to see if the interface has a function with a DISPID of DISPID_NEWENUM.
                    for (int i = 0; i < attr.cFuncs; ++i)
                    {
                        using(FuncDesc func = typeInfo.GetFuncDesc(i))
                        {
                            if (IsNewEnumFunc(info, typeInfo, func, i))
                            {
                                if (!hasNewEnumMember)
                                    firstNewEnum = func.memid;

                                if (hasNewEnumMember)
                                    hasDuplicateNewEnumMember = true;

                                // The interface has a function with a DISPID of DISPID_NEWENUM.
                                hasNewEnumMember = true;
                            }
                        }
                    }

                    // Check to see if the interface as a property with a DISPID of DISPID_NEWENUM.
                    for (int i = 0; i < attr.cVars; ++i)
                    {
                        using (VarDesc varDesc = typeInfo.GetVarDesc(i))
                        {
                            if (IsNewEnumDispatchProperty(info, typeInfo, varDesc, i))
                            {
                                if (!hasNewEnumMember)
                                    firstNewEnum = varDesc.memid;

                                if (hasNewEnumMember)
                                    hasDuplicateNewEnumMember = true;

                                // The interface has a property with a DISPID of DISPID_NEWENUM.
                                hasNewEnumMember = true;
                            }
                        }
                    }

                    // Check to see if the ForceIEnumerable custom value exists on the type
                    if (HasForceIEnumerableCustomAttribute(typeInfo))
                        hasNewEnumMember = true;

                    if (hasDuplicateNewEnumMember)
                    {
                        info.ReportEvent(
                            WarningCode.Wrn_MultiNewEnum,
                            Resource.FormatString("Wrn_MultiNewEnum", fullName, typeInfo.GetDocumentation(firstNewEnum)));
                    }
                }
                else
                {
                    // Check to see if the ForceIEnumerable custom value exists on the type
                    //  If it does, spit out a warning.
                    if (HasForceIEnumerableCustomAttribute(typeInfo))
                    {
                        string msg = Resource.FormatString(
                            "Wrn_IEnumCustomAttributeOnIUnknown",
                            CustomAttributeGuids.GUID_ForceIEnumerable.ToString().ToUpper(),
                            typeInfo.GetDocumentation());

                        info.ReportEvent(WarningCode.Wrn_IEnumCustomAttributeOnIUnknown, msg);
                    }
                }
            }

            return hasNewEnumMember;
        }
示例#37
0
            public int OleDragLeave()
            {
                this.converterInfo = ConverterInfo.No;

                if (this.currentDataObj != null)
                {
                    this.currentDataObj = null;
                    Marshal.Release(this.currentDataObjPtr);
                    this.currentDataObjPtr = IntPtr.Zero;

                    return this.originalDropTarget.OleDragLeave();
                }

                // If the DataObject was never set (meaning we cancelled the drag/drop), don't pass on the DragLeave since
                // we never passed in the DragEnter
                return NativeMethods.S_OK;
            }
示例#38
0
            public int OleDrop(IntPtr pDataObj, int grfKeyState, long pt, ref int pdwEffect)
            {
                int hr = NativeMethods.S_OK;
                if (this.converterInfo == ConverterInfo.Yes)
                {
                    object nativeDataObject = Marshal.GetObjectForIUnknown(pDataObj);
                    DataObject dataObject = new DataObject(nativeDataObject);

                    bool mapped = this.converter.ConvertToHtml(dataObject, this.currentDataObj);
                    if (mapped)
                    {
                        IntPtr pUnk = Marshal.GetIUnknownForObject(this.currentDataObj);

                        // Get the IOleDataObject interface for the object
                        Guid guid = new Guid("0000010E-0000-0000-C000-000000000046");
                        Marshal.QueryInterface(pUnk, ref guid, out this.currentDataObjPtr);

                        hr = this.originalDropTarget.OleDrop(this.currentDataObjPtr, grfKeyState, pt, ref pdwEffect);

                        this.currentDataObj = null;
                        this.currentDataObjPtr = IntPtr.Zero;
                        Marshal.Release(this.currentDataObjPtr);

                    }
                    else
                    {
                        pdwEffect = 0;
                    }
                }
                else if (this.converterInfo == ConverterInfo.Unknown)
                {
                    hr = this.originalDropTarget.OleDrop(pDataObj, grfKeyState, pt, ref pdwEffect);
                }

                this.converterInfo = ConverterInfo.No;

                return hr;
            }
示例#39
0
            public int OleDragEnter(IntPtr pDataObj, int grfKeyState, long pt, ref int pdwEffect)
            {
                object nativeDataObject = Marshal.GetObjectForIUnknown(pDataObj);
                DataObject dataObject = new DataObject(nativeDataObject);

                this.converterInfo = this.converter.CanConvertToHtml(dataObject);
                if (this.converterInfo == ConverterInfo.Yes)
                {
                    this.currentDataObj = new DataObject(DataFormats.Html, String.Empty);

                    IntPtr pUnk = Marshal.GetIUnknownForObject(this.currentDataObj);

                    // Get the IOleDataObject interface for the object
                    Guid guid = new Guid("0000010E-0000-0000-C000-000000000046");
                    Marshal.QueryInterface(pUnk, ref guid, out this.currentDataObjPtr);
                    Marshal.Release(pUnk);

                    return this.originalDropTarget.OleDragEnter(this.currentDataObjPtr, grfKeyState, pt, ref pdwEffect);
                }
                else if (this.converterInfo == ConverterInfo.No)
                {
                    // ignore this drag/drop
                    pdwEffect = 0;
                }
                else if (this.converterInfo == ConverterInfo.Unknown)
                {
                    // If the converter doesn't know anything about this data object, just use the original data object
                    return this.originalDropTarget.OleDragEnter(pDataObj, grfKeyState, pt, ref pdwEffect);
                }
                else
                {
                    Debug.Fail("Unknown ConverterInfo value!");
                }
                return NativeMethods.S_OK;
            }
 public void AddConverter(ConverterInfo converterInfo)
 {
     m_converters.Add(converterInfo);
 }
示例#41
0
        private IConvInterface m_convSourceInterface; // IConvInterface for the default source interface

        #endregion Fields

        #region Constructors

        public ConvClassInterfaceLocal(
            ConverterInfo info,
            TypeInfo coclassTypeInfo,
            TypeInfo defaultInterfaceTypeInfo,
            TypeInfo defaultSourceInterfaceTypeInfo,
            bool isExclusive)
        {
            m_info = info;
            m_coclassTypeInfo = coclassTypeInfo;
            m_defaultInterfaceTypeInfo = defaultInterfaceTypeInfo;
            m_defaultSourceInterfaceTypeInfo = defaultSourceInterfaceTypeInfo;
            m_isExclusive = isExclusive;

            DefineType(info, m_coclassTypeInfo, false);
        }
示例#42
0
        /// <summary>
        /// Used in the customized type conversion
        /// </summary>
        /// <param name="type"></param>
        public TypeConverter(Type type, CustomAttributeBuilder attribute, ParameterAttributes parameterAttributesOverride)
        {
            m_info = null;
            m_typeDesc = null;
            m_typeInfo = null;
            m_paramDesc = null;
            m_attribute = attribute;
            m_conversionLoss = false;
            m_convertedType = type;
            m_nativeIndirections = 0;

            m_parameterAttributesOverride = parameterAttributesOverride;

            ResetUnmanagedType();
        }
示例#43
0
        private IConvInterface m_defaultInterface; // The default interface

        #endregion Fields

        #region Constructors

        public ConvCoClassLocal(ConverterInfo info, TypeInfo type)
        {
            DefineType(info, type, true);
        }
示例#44
0
        /// <summary>
        /// Wrapper for a already converted type
        /// </summary>
        /// <param name="type"></param>
        public TypeConverter(Type type)
        {
            m_info = null;
            m_typeDesc = null;
            m_typeInfo = null;
            m_paramDesc = null;
            m_attribute = null;
            m_conversionLoss = false;
            m_convertedType = type;
            m_nativeIndirections = 0;

            ResetUnmanagedType();
        }
示例#45
0
        private static DataTemplate GetCellTemplate(IColumnItem column, ConverterInfo converterInfo, GridViewDataControl grid)
        {
            string accessDenied = null;

            if ((string)grid.Tag == "SearchGrid")
                accessDenied = string.Format(
                    CultureInfo.InvariantCulture,
                    @"AccessDeniedPropertyList=""{{{{Binding Path={0}, Converter={{{{StaticResource StringToHashSetConverter}}}}}}}}""",
                    Constants.AccessDeniedPropertiesName);

            if ((string)grid.Tag == "SingleCrGrid")
                accessDenied = string.Format(
                    CultureInfo.InvariantCulture,
                    @"SingleCrAccessDeniedList=""{{{{Binding Path={0}, Converter={{{{StaticResource StringToHashSetConverter}}}}}}}}""",
                    Constants.AccessDeniedPropertiesName);

            if ((string)grid.Tag == "MultipleCrGrid")
                accessDenied = string.Format(
                    CultureInfo.InvariantCulture,
                    @"MultiCrAccessDeniedList=""{{{{Binding Path={0}, Converter={{{{StaticResource StringToHashSetConverter}}}}}}}}""",
                    Constants.AccessDeniedPropertiesName);

            var hightlightBehavior = string.Format(CultureInfo.InvariantCulture, 
@"
    <i:Interaction.Behaviors>
        <Behaviors:HightlightBehavior HighlightBrush=""Red""
                                      HighlightFontWeight=""Bold""
                                      HightlightText=""{{{{Binding RelativeSource={{{{RelativeSource AncestorType=UserControl}}}}, Path=DataContext.FilterString}}}}""
                                      {0}
                                      ColumnName=""{1}""
                                      Text=""{{0}}"" />
        <Behaviors:{2} Text=""{{0}}"" />
        </i:Interaction.Behaviors>", accessDenied, column.ColumnName, typeof(HighlightRichTextBehavior).Name);

            var prop = column.Property;
            var stringFormat = string.Empty;

            var numericAttribute =
                (NumericAttribute)
                (from d in prop.GetCustomAttributes(typeof(NumericAttribute), false) select d).FirstOrDefault();

            if (numericAttribute != null)
            {
                switch (numericAttribute.NumericType)
                {
                    case NumericTypes.Numeric:
                        stringFormat = string.Format(CultureInfo.InvariantCulture, "StringFormat=N{0}", numericAttribute.NumberOfDigits);
                        break;

                    case NumericTypes.Currency:
                        stringFormat = string.Format(CultureInfo.InvariantCulture, "StringFormat=C{0}", numericAttribute.NumberOfDigits);
                        break;

                    case NumericTypes.Percentage:
                        stringFormat = string.Format(CultureInfo.InvariantCulture, "StringFormat=P{0}", numericAttribute.NumberOfDigits);
                        break;
                }
            }

            var converter = converterInfo.ConverterString;

            var binding =
                string.Format(CultureInfo.InvariantCulture, "{{Binding {1}{0}{2}{3}}}",
                              prop.Name,
                              string.IsNullOrWhiteSpace(column.Prefix) ? string.Empty : string.Format(CultureInfo.InvariantCulture, "{0}.", column.Prefix),
                              string.IsNullOrWhiteSpace(converter) ? string.Empty : string.Format(CultureInfo.InvariantCulture, ", {0}", converter),
                              string.IsNullOrWhiteSpace(stringFormat) ? string.Empty : string.Format(CultureInfo.InvariantCulture, ", {0}", stringFormat));

            var behavior = string.Format(CultureInfo.InvariantCulture, hightlightBehavior, binding);
            var templateText = string.Format(CultureInfo.InvariantCulture, @"
<DataTemplate
    xmlns=""http://schemas.microsoft.com/client/2007""
    xmlns:i=""http://schemas.microsoft.com/expression/2010/interactivity""
    xmlns:Behaviors=""clr-namespace:Cebos.Common.Behaviors;assembly=Cebos.Veyron.Common.SL"">
     <TextBlock>
        {0}
     </TextBlock>
</DataTemplate>", behavior);
            var itemTemplate = XamlReader.Load(templateText);
            return (DataTemplate)itemTemplate;
        }
        private ConverterInfo AddComplexBindingConverter (MatchCollection mSubs, string strBinding, int termPos)
        {
            var sbExpr = new StringBuilder(mSubs[0].Result("$`"));
            var conv = new ConverterInfo {
                Name = string.Format(CultureInfo.InvariantCulture, "_jaml_{0}Converter", ClassName),
                SubBindings = new List<string>(),
            };
            for (int i = 0; i < mSubs.Count; ++i) {
                string strBetween = GetStringBetweenCaptures(mSubs[i], i + 1 < mSubs.Count ? mSubs[i + 1] : null,
                    strBinding, termPos);
                sbExpr.AppendFormat(CultureInfo.InvariantCulture, "(values[{0}]){1}", i, strBetween);
                string strSub = mSubs[i].Groups["SubBinding"].Value;
                conv.SubBindings.Add(
                    FormatScalarPropertyValue(FormatSimpleBindingValue(strSub) ?? strSub));
            }
            conv.Expression = sbExpr.ToString().Trim();

            EnsureConverterNameUnique(conv);
            Converters.Add(conv);
            return conv;
        }
示例#47
0
		/// <summary>
		/// Add a converter to this PatternLayout
		/// </summary>
		/// <param name="converterInfo">the converter info</param>
		/// <remarks>
		/// <para>
		/// This version of the method is used by the configurator.
		/// Programmatic users should use the alternative <see cref="AddConverter(string,Type)"/> method.
		/// </para>
		/// </remarks>
		public void AddConverter(ConverterInfo converterInfo) {
			if (converterInfo == null)
				throw new ArgumentNullException("converterInfo");

			if (!typeof(PatternConverter).IsAssignableFrom(converterInfo.Type)) {
				throw new ArgumentException("The converter type specified [" + converterInfo.Type + "] must be a subclass of GodLesZ.Library.Logging.Util.PatternConverter", "converterInfo");
			}
			m_instanceRulesRegistry[converterInfo.Name] = converterInfo;
		}
示例#48
0
 public static void HandleAlias(ConverterInfo info, TypeInfo typeInfo, TypeDesc typeDesc, FieldBuilder builder)
 {
     string aliasName = GetAliasName(info, typeInfo, typeDesc);
     if (aliasName != null)
         builder.SetCustomAttribute(CustomAttributeHelper.GetBuilderForComAliasName(aliasName));
 }
        private JToken GetJTokenComplexBindingFromConverter (ConverterInfo conv, string strBinding, int termPos)
        {
            string afterExpr = strBinding.Substring(termPos);
            if (afterExpr.StartsWith(StrExpressionPostfix))
                afterExpr = afterExpr.Substring(StrExpressionPostfix.Length);
            afterExpr = afterExpr.Trim();

            if (conv.IsSingle) {
                string binding = conv.SubBindings[0].Trim();
                return string.Format(CultureInfo.InvariantCulture, "{0}, Converter={1}{2}}}",
                    binding.Substring(0, binding.Length - 1), // trim last '}'
                    FormatGeneratedConverterReference(conv.Name),
                    afterExpr);
            }
            else {
                return GetJObjectMultiBinding(conv, afterExpr);
            }
        }
示例#50
0
 public ConvEnumLocal(ConverterInfo info, TypeInfo type)
 {
     DefineType(info, type, true);
 }
 private void EnsureConverterNameUnique (ConverterInfo conv)
 {
     string name = conv.Name;
     int num = 1;
     while (Converters.Any(c => c.Name == conv.Name))
         conv.Name = name + num++;
 }
示例#52
0
 public void AddConverter(ConverterInfo converterInfo)
 {
     AddConverter(converterInfo.Name, converterInfo.Type);
 }
示例#53
0
 public InterfaceInfo(ConverterInfo info, TypeBuilder typeBuilder, bool supportsDispatch, TypeInfo type, TypeAttr attr, bool bCoClass)
 {
     Init(info, typeBuilder, supportsDispatch, type, attr, bCoClass, false, null);
 }
示例#54
0
        /// <summary>
        /// Common code shared by struct, enum, and union type creation 
        /// </summary>
        public static TypeBuilder DefineTypeHelper(ConverterInfo info, TypeInfo typeInfo, TypeInfo nonAliasedTypeInfo, TypeAttributes attributes, Type typeParent, ConvType convType)
        {
            using (TypeAttr typeAttr = nonAliasedTypeInfo.GetTypeAttr())
            {
                string name = info.GetUniqueManagedName(typeInfo, convType);

                TypeBuilder typeBuilder = info.ModuleBuilder.DefineType(name, attributes, typeParent);

                DefineGuid(typeInfo, nonAliasedTypeInfo, typeBuilder);

                // We only emit TypeLibType attribute for class/interface, according to MSDN
                // typeBuilder.SetCustomAttribute(CustomAttributeHelper.GetBuilderForTypeLibType((TypeLibTypeFlags)attr.wTypeFlags));

                return typeBuilder;
            }
        }
示例#55
0
        public AssemblyBuilder DoProcess(
            Object typeLib,
            string asmFilename,
            TypeLibImporterFlags flags,
            ITypeLibImporterNotifySink notifySink,
            byte[] publicKey,
            StrongNameKeyPair keyPair,
            string asmNamespace,
            Version asmVersion,
            bool isVersion2,
            bool isPreserveSig,
            string ruleSetFileName)
        {
            m_resolver = notifySink;

            TypeLib tlb = new TypeLib((TypeLibTypes.Interop.ITypeLib)typeLib);

            if (asmNamespace == null)
            {
                asmNamespace = tlb.GetDocumentation();

                string fileName = System.IO.Path.GetFileNameWithoutExtension(asmFilename);
                if (fileName != asmNamespace)
                    asmNamespace = fileName;

                //
                // Support for GUID_ManagedName (for namespace)
                //
                string customManagedNamespace = tlb.GetCustData(CustomAttributeGuids.GUID_ManagedName) as string;
                if (customManagedNamespace != null)
                {
                    customManagedNamespace = customManagedNamespace.Trim();
                    if (customManagedNamespace.ToUpper().EndsWith(".DLL"))
                        customManagedNamespace = customManagedNamespace.Substring(0, customManagedNamespace.Length - 4);
                    else if (customManagedNamespace.ToUpper().EndsWith(".EXE"))
                        customManagedNamespace = customManagedNamespace.Substring(0, customManagedNamespace.Length - 4);

                    asmNamespace = customManagedNamespace;
                }
            }

            //
            // Check for GUID_ExportedFromComPlus
            //
            object value = tlb.GetCustData(CustomAttributeGuids.GUID_ExportedFromComPlus);
            if (value != null)
            {
                // Make this a critical failure, instead of returning null which will be ignored.
                throw new TlbImpGeneralException(Resource.FormatString("Err_CircularImport", asmNamespace), ErrorCode.Err_CircularImport);
            }

            string strModuleName = asmFilename;

            if (asmFilename.Contains("\\"))
            {
                int nIndex;
                for (nIndex = strModuleName.Length; strModuleName[nIndex - 1] != '\\'; --nIndex) ;
                strModuleName = strModuleName.Substring(nIndex);
            }

            // If the version information was not specified, then retrieve it from the typelib.
            if (asmVersion == null)
            {
                using (TypeLibAttr attr = tlb.GetLibAttr())
                {
                    asmVersion = new Version(attr.wMajorVerNum, attr.wMinorVerNum, 0, 0);
                }
            }

            // Assembly name should not have .DLL
            // while module name must contain the .DLL
            string strAsmName = String.Copy(strModuleName);
            if (strAsmName.EndsWith(".DLL", StringComparison.InvariantCultureIgnoreCase))
                strAsmName = strAsmName.Substring(0, strAsmName.Length - 4);

            AssemblyName assemblyName = new AssemblyName();
            assemblyName.Name = strAsmName;
            assemblyName.SetPublicKey(publicKey);
            assemblyName.Version = asmVersion;
            assemblyName.KeyPair = keyPair;

            m_assemblyBuilder = CreateAssemblyBuilder(assemblyName, tlb, flags);

            m_moduleBuilder = CreateModuleBuilder(m_assemblyBuilder, strModuleName);

            // Add a listener for the reflection load only resolve events.
            AppDomain currentDomain = Thread.GetDomain();
            ResolveEventHandler asmResolveHandler = ReflectionOnlyResolveAsmEvent;
            currentDomain.ReflectionOnlyAssemblyResolve += asmResolveHandler;

            ConverterSettings settings;
            settings.m_isGenerateClassInterfaces = true;
            settings.m_namespace = asmNamespace;
            settings.m_flags = flags;
            settings.m_isVersion2 = isVersion2;
            settings.m_isPreserveSig = isPreserveSig;
            RuleEngine.InitRuleEngine(new TlbImpActionManager(),
                                      new TlbImpCategoryManager(),
                                      new TlbImpConditionManager(),
                                      new TlbImpOperatorManager());
            if (ruleSetFileName != null)
            {
                try
                {
                    RuleFileParser parser = new RuleFileParser(ruleSetFileName);
                    settings.m_ruleSet = parser.Parse();
                }
                catch (Exception ex)
                {
                    Output.WriteWarning(Resource.FormatString("Wrn_LoadRuleFileFailed",
                                                              ruleSetFileName, ex.Message),
                                        WarningCode.Wrn_LoadRuleFileFailed);
                    settings.m_ruleSet = null;
                }
            }
            else
            {
                settings.m_ruleSet = null;
            }

            m_converterInfo = new ConverterInfo(m_moduleBuilder, tlb, m_resolver, settings);

            //
            // Generate class interfaces
            // NOTE:
            // We have to create class interface ahead of time because of the need to convert default interfaces to
            // class interfafces. However, this creates another problem that the event interface is always named first
            // before the other interfaces, because we need to create the type builder for the event interface first
            // so that we can create a class interface that implement it. But in the previous version of TlbImp,
            // it doesn't have to do that because it can directly create a typeref with the class interface name,
            // without actually creating anything like the TypeBuilder. The result is that the name would be different
            // with interop assemblies generated by old tlbimp in this case.
            // Given the nature of reflection API, this cannot be easily workarounded unless we switch to metadata APIs.
            // I believe this is acceptable because this only happens when:
            // 1. People decide to migrate newer .NET framework
            // 2. The event interface name conflicts with a normal interface
            //
            // In this case the problem can be easily fixed with a global refactoring, so I wouldn't worry about that
            //
            if (m_converterInfo.GenerateClassInterfaces)
            {
                CreateClassInterfaces();
            }

            //
            // Generate the remaining types except coclass
            // Because during creating coclass, we require every type, including all the referenced type to be created
            // This is a restriction of reflection API that when you override a method in parent interface, the method info
            // is needed so the type must be already created and loaded
            //
            var coclassList = new List<TypeInfo>();
            int nCount = tlb.GetTypeInfoCount();
            for (int n = 0; n < nCount; ++n)
            {
                try
                {
                    TypeInfo type = tlb.GetTypeInfo(n);
                    string strType = type.GetDocumentation();

                    using (TypeAttr attr = type.GetTypeAttr())
                    {
                        TypeLibTypes.Interop.TYPEKIND kind = attr.typekind;
                        TypeInfo typeToProcess;
                        TypeAttr attrToProcess;
                        if (kind == TypeLibTypes.Interop.TYPEKIND.TKIND_ALIAS)
                        {
                            ConvCommon.ResolveAlias(type, attr.tdescAlias, out typeToProcess, out attrToProcess);
                            if (attrToProcess.typekind == TypeLibTypes.Interop.TYPEKIND.TKIND_ALIAS)
                            {
                                continue;
                            }
                            else
                            {
                                // We need to duplicate the definition of the user defined type in the name of the alias
                                kind = attrToProcess.typekind;
                                typeToProcess = type;
                                attrToProcess = attr;
                            }
                        }
                        else
                        {
                            typeToProcess = type;
                            attrToProcess = attr;
                        }

                        switch (kind)
                        {
                            // Process coclass later because of reflection API requirements
                            case TypeLibTypes.Interop.TYPEKIND.TKIND_COCLASS:
                                coclassList.Add(typeToProcess);
                                break;

                            case TypeLibTypes.Interop.TYPEKIND.TKIND_ENUM:
                                m_converterInfo.GetEnum(typeToProcess, attrToProcess);
                                break;

                            case TypeLibTypes.Interop.TYPEKIND.TKIND_DISPATCH:
                            case TypeLibTypes.Interop.TYPEKIND.TKIND_INTERFACE:
                                m_converterInfo.GetInterface(typeToProcess, attrToProcess);
                                break;

                            case TypeLibTypes.Interop.TYPEKIND.TKIND_MODULE:
                                m_converterInfo.GetModule(typeToProcess, attrToProcess);
                                break;

                            case TypeLibTypes.Interop.TYPEKIND.TKIND_RECORD:
                                m_converterInfo.GetStruct(typeToProcess, attrToProcess);
                                break;
                            case TypeLibTypes.Interop.TYPEKIND.TKIND_UNION:
                                m_converterInfo.GetUnion(typeToProcess, attrToProcess);
                                break;
                        }

                        m_converterInfo.ReportEvent(
                            MessageCode.Msg_TypeInfoImported,
                            Resource.FormatString("Msg_TypeInfoImported", typeToProcess.GetDocumentation()));
                    }
                }
                catch (ReflectionTypeLoadException)
                {
                    throw; // Fatal failure. Throw
                }
                catch (TlbImpResolveRefFailWrapperException)
                {
                    throw; // Fatal failure. Throw
                }
                catch (TlbImpGeneralException)
                {
                    throw; // Fatal failure. Throw
                }
                catch (TypeLoadException)
                {
                    throw; // TypeLoadException is critical. Throw.
                }
                catch (Exception)
                {
                }
            }

            // Process coclass after processing all the other types
            foreach (TypeInfo type in coclassList)
            {
                using (TypeAttr attr = type.GetTypeAttr())
                {
                    try
                    {
                        m_converterInfo.GetCoClass(type, attr);
                    }
                    catch (ReflectionTypeLoadException)
                    {
                        throw; // Fatal failure. Throw
                    }
                    catch (TlbImpResolveRefFailWrapperException)
                    {
                        throw; // Fatal failure. Throw
                    }
                    catch (TlbImpGeneralException)
                    {
                        throw; // Fatal failure. Throw
                    }
                    catch (TypeLoadException)
                    {
                        throw; // TypeLoadException is critical. Throw.
                    }
                    catch (Exception)
                    {
                    }
                }
            }

            //
            // Build an array of EventItfInfo & generate event provider / event sink helpers
            //

            var eventAdapterGenerator = new Event.TCEAdapterGenerator();
            var eventItfList = new List<Event.EventItfInfo>();

            foreach (IConvBase symbol in m_converterInfo.GetAllConvBase)
            {
                var convInterface = symbol as IConvInterface;
                if (convInterface != null)
                {
                    if (convInterface.EventInterface != null)
                    {
                        Debug.Assert(convInterface.EventInterface is ConvEventInterfaceLocal);
                        var local = convInterface.EventInterface as ConvEventInterfaceLocal;

                        Type eventInterfaceType = convInterface.EventInterface.ManagedType;

                        // Build EventItfInfo and add to the list
                        Type sourceInterfaceType = convInterface.ManagedType;
                        string sourceInterfaceName = sourceInterfaceType.FullName;
                        Event.EventItfInfo eventItfInfo = new Event.EventItfInfo(
                            eventInterfaceType.FullName,
                            sourceInterfaceName,
                            local.EventProviderName,
                            eventInterfaceType,
                            convInterface.ManagedType);
                        eventItfList.Add(eventItfInfo);
                    }
                }
            }

            eventAdapterGenerator.Process(m_moduleBuilder, eventItfList);

            return m_assemblyBuilder;
        }
示例#56
0
        /// <summary>
        /// Create local class interfaces
        /// </summary>
        public void CreateLocalClassInterfaces(ConverterInfo converterInfo)
        {
            // Walk the candidate list and generate class interfaces
            // Note: We need to create the class interface in two phases because
            // during creation of class interface, we'll need to create interface & event interface, which
            // could have parameters resolve back to coclass which requires certain class interface
            // So split into two stages so that when we are doing creation all necessary information are inplace
            var convClassInterfaceLocals = new List<ConvClassInterfaceLocal>();

            //
            // Phase 1 : Create ConvClassInterfaceLocal instances and associate interface with class interfaces
            //
            foreach (DefaultInterfaceInfo info in m_defaultInterfaceInfoList)
            {
                try
                {
                    ConvClassInterfaceLocal local = new ConvClassInterfaceLocal(
                        converterInfo,
                        info.coclass,
                        info.defaultInterface,
                        info.defaultSourceInterface,
                        info.isExclusive);
                    convClassInterfaceLocals.Add(local);
                }
                catch (ReflectionTypeLoadException)
                {
                    throw; // Fatal failure. Throw
                }
                catch (TlbImpResolveRefFailWrapperException)
                {
                    throw; // Fatal failure. Throw
                }
                catch (TlbImpGeneralException)
                {
                    throw; // Fatal failure. Throw
                }
                catch (TypeLoadException)
                {
                    throw; // TypeLoadException is critical. Throw.
                }
                catch (Exception)
                {
                }
            }

            //
            // Phase 2 : Create the class interface
            //
            foreach (ConvClassInterfaceLocal local in convClassInterfaceLocals)
            {
                try
                {
                    local.Create();
                }
                catch (ReflectionTypeLoadException)
                {
                    throw; // Fatal failure. Throw
                }
                catch (TlbImpResolveRefFailWrapperException)
                {
                    throw; // Fatal failure. Throw
                }
                catch (TlbImpGeneralException)
                {
                    throw; // Fatal failure. Throw
                }
                catch (TypeLoadException)
                {
                    throw; // TypeLoadException is critical. Throw.
                }
                catch (Exception)
                {
                }
            }
        }
示例#57
0
		/// <summary>
		/// Create the pattern parser instance
		/// </summary>
		/// <param name="pattern">the pattern to parse</param>
		/// <returns>The <see cref="PatternParser"/> that will format the event</returns>
		/// <remarks>
		/// <para>
		/// Creates the <see cref="PatternParser"/> used to parse the conversion string. Sets the
		/// global and instance rules on the <see cref="PatternParser"/>.
		/// </para>
		/// </remarks>
		virtual protected PatternParser CreatePatternParser(string pattern) {
			PatternParser patternParser = new PatternParser(pattern);

			// Add all the builtin patterns
			foreach (DictionaryEntry entry in s_globalRulesRegistry) {
				ConverterInfo converterInfo = new ConverterInfo();
				converterInfo.Name = (string)entry.Key;
				converterInfo.Type = (Type)entry.Value;
				patternParser.PatternConverters[entry.Key] = converterInfo;
			}
			// Add the instance patterns
			foreach (DictionaryEntry entry in m_instanceRulesRegistry) {
				patternParser.PatternConverters[entry.Key] = entry.Value;
			}

			return patternParser;
		}