internal static string GetMemberName(MemberInfo member)
        {
            // This works for all sorts of things: Type, MethodInfo, PropertyInfo, FieldInfo
            Object [] rg = member.GetCustomAttributes(typeof(ManagedNameAttribute), false);
            if (rg.Length > 0)
            {
                // bug#69115 - if null or empty string are passed, we just ignore this attribute
                ManagedNameAttribute attr = (ManagedNameAttribute)rg[0];
                if (attr.name != null && attr.name.Length != 0)
                {
                    return(attr.name);
                }
            }

            return(member.Name);
        }
        private static void InitializeInstance(Object o)
        {
            Type            type      = o.GetType();
            string          className = ManagedNameAttribute.GetClassName(type);
            SchemaNaming    naming    = InstrumentedAttribute.GetSchemaNaming(type.Assembly);
            ManagementClass theClass  = new ManagementClass(naming.NamespaceName + ":" + className);

            foreach (FieldInfo field in type.GetFields())
            {
                Object val = theClass.Properties[ManagedNameAttribute.GetFieldName(field)].Value;
                if (null != val)
                {
                    field.SetValue(o, val);
                }
            }
        }
Beispiel #3
0
        internal static string GetBaseClassName(Type type)
        {
            InstrumentationClassAttribute attribute = InstrumentationClassAttribute.GetAttribute(type);
            string managedBaseClassName             = attribute.ManagedBaseClassName;

            if (managedBaseClassName == null)
            {
                InstrumentationClassAttribute instrumentationClassAttribute = InstrumentationClassAttribute.GetAttribute(type.BaseType);
                if (instrumentationClassAttribute == null)
                {
                    InstrumentationType instrumentationType = attribute.InstrumentationType;
                    switch (instrumentationType)
                    {
                    case InstrumentationType.Instance:
                    {
                        return(null);
                    }

                    case InstrumentationType.Event:
                    {
                        return("__ExtrinsicEvent");
                    }

                    case InstrumentationType.Abstract:
                    {
                        return(null);
                    }
                    }
                }
                return(ManagedNameAttribute.GetMemberName(type.BaseType));
            }
            else
            {
                return(managedBaseClassName);
            }
        }
        public SchemaMapping(Type type, SchemaNaming naming, Hashtable mapTypeToConverterClassName)
        {
            codeClassName = (string)mapTypeToConverterClassName[type];
            classType     = type;

            bool hasGenericEmbeddedObject = false;

            string baseClassName = ManagedNameAttribute.GetBaseClassName(type);

            className           = ManagedNameAttribute.GetMemberName(type);
            instrumentationType = InstrumentationClassAttribute.GetAttribute(type).InstrumentationType;

            classPath = naming.NamespaceName + ":" + className;

            if (null == baseClassName)
            {
                newClass = new ManagementClass(naming.NamespaceName, "", null);
                newClass.SystemProperties ["__CLASS"].Value = className;
            }
            else
            {
                ManagementClass baseClass = new ManagementClass(naming.NamespaceName + ":" + baseClassName);
                if (instrumentationType == InstrumentationType.Instance)
                {
                    bool baseAbstract = false;
                    try
                    {
                        QualifierData o = baseClass.Qualifiers["abstract"];
                        if (o.Value is bool)
                        {
                            baseAbstract = (bool)o.Value;
                        }
                    }
                    catch (ManagementException e)
                    {
                        if (e.ErrorCode != ManagementStatus.NotFound)
                        {
                            throw;
                        }
                    }
                    if (!baseAbstract)
                    {
                        throw new Exception(RC.GetString("CLASSINST_EXCEPT"));
                    }
                }

                newClass = baseClass.Derive(className);
            }


            // Create the converter class
            CodeWriter codeClass = code.AddChild("public class " + codeClassName + " : IWmiConverter");

            // Create code block for one line Members
            CodeWriter codeOneLineMembers = codeClass.AddChild(new CodeWriter());

            codeOneLineMembers.Line("static ManagementClass managementClass = new ManagementClass(@\"" + classPath + "\");");
            codeOneLineMembers.Line("static IntPtr classWbemObjectIP;");
            codeOneLineMembers.Line("static Guid iidIWbemObjectAccess = new Guid(\"49353C9A-516B-11D1-AEA6-00C04FB68820\");");
            codeOneLineMembers.Line("internal ManagementObject instance = managementClass.CreateInstance();");
            codeOneLineMembers.Line("object reflectionInfoTempObj = null ; ");
            codeOneLineMembers.Line("FieldInfo reflectionIWbemClassObjectField = null ; ");
            codeOneLineMembers.Line("IntPtr emptyWbemObject = IntPtr.Zero ; ");

            //
            // Reuters VSQFE#: 750	[marioh] see comments above
            // Used as a temporary pointer to the newly created instance that we create to avoid re-using the same
            // object causing unbound memory usage in IWbemClassObject implementation.
            codeOneLineMembers.Line("IntPtr theClone = IntPtr.Zero;");
            codeOneLineMembers.Line("public static ManagementObject emptyInstance = managementClass.CreateInstance();");

            // TODO: Make these non-public
            codeOneLineMembers.Line("public IntPtr instWbemObjectAccessIP;");

            // Create static constructor to initialize handles
            CodeWriter codeCCTOR = codeClass.AddChild("static " + codeClassName + "()");

            codeCCTOR.Line("classWbemObjectIP = (IntPtr)managementClass;");
            codeCCTOR.Line("IntPtr wbemObjectAccessIP;");
            codeCCTOR.Line("Marshal.QueryInterface(classWbemObjectIP, ref iidIWbemObjectAccess, out wbemObjectAccessIP);");
            codeCCTOR.Line("int cimType;");

            // Create constructor
            CodeWriter codeCTOR = codeClass.AddChild("public " + codeClassName + "()");

            codeCTOR.Line("IntPtr wbemObjectIP = (IntPtr)instance;");
            codeCTOR.Line("Marshal.QueryInterface(wbemObjectIP, ref iidIWbemObjectAccess, out instWbemObjectAccessIP);");

            //
            // Reuters VSQFE#: 750	[marioh]
            // In the CCTOR we set things up only once:
            //  1. We get the IWbemClassObjectFreeThreaded object '_wbemObject' from the ManagementObject instance
            //  2. We then get the actual IntPtr to the underlying WMI object
            //  3. Finally, the simple cast to IntPtr from the ManagementObject instance
            // These fields will be used later during the ToWMI call.
            codeCTOR.Line("FieldInfo tempField = instance.GetType().GetField ( \"_wbemObject\", BindingFlags.Instance | BindingFlags.NonPublic );");
            codeCTOR.Line("if ( tempField == null )");
            codeCTOR.Line("{");
            codeCTOR.Line("   tempField = instance.GetType().GetField ( \"wbemObject\", BindingFlags.Instance | BindingFlags.NonPublic ) ;");
            codeCTOR.Line("}");

            codeCTOR.Line("reflectionInfoTempObj = tempField.GetValue (instance) ;");
            codeCTOR.Line("reflectionIWbemClassObjectField = reflectionInfoTempObj.GetType().GetField (\"pWbemClassObject\", BindingFlags.Instance | BindingFlags.NonPublic );");
            codeCTOR.Line("emptyWbemObject = (IntPtr) emptyInstance;");

            // Create destructor that will be called at process cleanup
            CodeWriter codeDTOR = codeClass.AddChild("~" + codeClassName + "()");

            codeDTOR.AddChild("if(instWbemObjectAccessIP != IntPtr.Zero)").Line("Marshal.Release(instWbemObjectAccessIP);");

            // Create method to convert from managed code to WMI
            CodeWriter codeToWMI = codeClass.AddChild("public void ToWMI(object obj)");

            //
            // Reuters VSQFE#: 750	[marioh] see comments above
            // Ensure the release of the WbemObjectAccess interface pointer.
            codeToWMI.Line("if(instWbemObjectAccessIP != IntPtr.Zero)");
            codeToWMI.Line("{");
            codeToWMI.Line("    Marshal.Release(instWbemObjectAccessIP);");
            codeToWMI.Line("    instWbemObjectAccessIP = IntPtr.Zero;");
            codeToWMI.Line("}");

            codeToWMI.Line("if(theClone != IntPtr.Zero)");
            codeToWMI.Line("{");
            codeToWMI.Line("    Marshal.Release(theClone);");
            codeToWMI.Line("    theClone = IntPtr.Zero;");
            codeToWMI.Line("}");

            codeToWMI.Line("IWOA.Clone_f(12, emptyWbemObject, out theClone) ;");
            codeToWMI.Line("Marshal.QueryInterface(theClone, ref iidIWbemObjectAccess, out instWbemObjectAccessIP) ;");
            codeToWMI.Line("reflectionIWbemClassObjectField.SetValue ( reflectionInfoTempObj, theClone ) ;");

            codeToWMI.Line(String.Format("{0} instNET = ({0})obj;", type.FullName.Replace('+', '.')));             // bug#92918 - watch for nested classes

            // Explicit cast to IntPtr
            CodeWriter codeIntPtrCast = codeClass.AddChild("public static explicit operator IntPtr(" + codeClassName + " obj)");

            codeIntPtrCast.Line("return obj.instWbemObjectAccessIP;");

            // Add GetInstance
            codeOneLineMembers.Line("public ManagementObject GetInstance() {return instance;}");

            PropertyDataCollection props = newClass.Properties;

            // type specific info
            switch (instrumentationType)
            {
            case InstrumentationType.Event:
                break;

            case InstrumentationType.Instance:
                props.Add("ProcessId", CimType.String, false);
                props.Add("InstanceId", CimType.String, false);
                props["ProcessId"].Qualifiers.Add("key", true);
                props["InstanceId"].Qualifiers.Add("key", true);
                newClass.Qualifiers.Add("dynamic", true, false, false, false, true);
                newClass.Qualifiers.Add("provider", naming.DecoupledProviderInstanceName, false, false, false, true);
                break;

            case InstrumentationType.Abstract:
                newClass.Qualifiers.Add("abstract", true, false, false, false, true);
                break;

            default:
                break;
            }

            int  propCount    = 0;
            bool needsNullObj = false;

            foreach (MemberInfo field in type.GetMembers())
            {
                if (!(field is FieldInfo || field is PropertyInfo))
                {
                    continue;
                }

                if (field.GetCustomAttributes(typeof(IgnoreMemberAttribute), false).Length > 0)
                {
                    continue;
                }

                if (field is FieldInfo)
                {
                    FieldInfo fi = field as FieldInfo;

                    // We ignore statics
                    if (fi.IsStatic)
                    {
                        ThrowUnsupportedMember(field);
                    }
                }
                else if (field is PropertyInfo)
                {
                    PropertyInfo pi = field as PropertyInfo;
                    // We must have a 'get' property accessor
                    if (!pi.CanRead)
                    {
                        ThrowUnsupportedMember(field);
                    }

                    // We ignore static properties
                    MethodInfo mi = pi.GetGetMethod();
                    if (null == mi || mi.IsStatic)
                    {
                        ThrowUnsupportedMember(field);
                    }

                    // We don't support parameters on properties
                    if (mi.GetParameters().Length > 0)
                    {
                        ThrowUnsupportedMember(field);
                    }
                }

                String propName = ManagedNameAttribute.GetMemberName(field);


#if SUPPORTS_ALTERNATE_WMI_PROPERTY_TYPE
                Type t2 = ManagedTypeAttribute.GetManagedType(field);
#else
                Type t2;
                if (field is FieldInfo)
                {
                    t2 = (field as FieldInfo).FieldType;
                }
                else
                {
                    t2 = (field as PropertyInfo).PropertyType;
                }
#endif
                bool isArray = false;
                if (t2.IsArray)
                {
                    // We only support one dimensional arrays in this version
                    if (t2.GetArrayRank() != 1)
                    {
                        ThrowUnsupportedMember(field);
                    }

                    isArray = true;
                    t2      = t2.GetElementType();
                }

                string embeddedTypeName      = null;
                string embeddedConverterName = null;
                if (mapTypeToConverterClassName.Contains(t2))
                {
                    embeddedConverterName = (string)mapTypeToConverterClassName[t2];
                    embeddedTypeName      = ManagedNameAttribute.GetMemberName(t2);
                }

                bool isGenericEmbeddedObject = false;
                if (t2 == typeof(object))
                {
                    isGenericEmbeddedObject = true;
                    if (hasGenericEmbeddedObject == false)
                    {
                        hasGenericEmbeddedObject = true;
                        // Add map
                        codeOneLineMembers.Line("static Hashtable mapTypeToConverter = new Hashtable();");
                        foreach (DictionaryEntry entry in mapTypeToConverterClassName)
                        {
                            codeCCTOR.Line(String.Format("mapTypeToConverter[typeof({0})] = typeof({1});", ((Type)entry.Key).FullName.Replace('+', '.'), (string)entry.Value)); // bug#92918 - watch for nested classes
                        }
                    }
                }

                string propFieldName   = "prop_" + (propCount);
                string handleFieldName = "handle_" + (propCount++);

                // Add handle for field, which is static accross all instances
                codeOneLineMembers.Line("static int " + handleFieldName + ";");
                codeCCTOR.Line(String.Format("IWOA.GetPropertyHandle_f27(27, wbemObjectAccessIP, \"{0}\", out cimType, out {1});", propName, handleFieldName));

                // Add PropertyData for field, which is specific to each instance
                codeOneLineMembers.Line("PropertyData " + propFieldName + ";");
                codeCTOR.Line(String.Format("{0} = instance.Properties[\"{1}\"];", propFieldName, propName));

                if (isGenericEmbeddedObject)
                {
                    CodeWriter codeNotNull = codeToWMI.AddChild(String.Format("if(instNET.{0} != null)", field.Name));
                    CodeWriter codeElse    = codeToWMI.AddChild("else");
                    codeElse.Line(String.Format("{0}.Value = null;", propFieldName));
                    if (isArray)
                    {
                        codeNotNull.Line(String.Format("int len = instNET.{0}.Length;", field.Name));
                        codeNotNull.Line("ManagementObject[] embeddedObjects = new ManagementObject[len];");
                        codeNotNull.Line("IWmiConverter[] embeddedConverters = new IWmiConverter[len];");

                        CodeWriter codeForLoop = codeNotNull.AddChild("for(int i=0;i<len;i++)");

                        CodeWriter codeFoundType = codeForLoop.AddChild(String.Format("if((instNET.{0}[i] != null) && mapTypeToConverter.Contains(instNET.{0}[i].GetType()))", field.Name));
                        codeFoundType.Line(String.Format("Type type = (Type)mapTypeToConverter[instNET.{0}[i].GetType()];", field.Name));
                        codeFoundType.Line("embeddedConverters[i] = (IWmiConverter)Activator.CreateInstance(type);");
                        codeFoundType.Line(String.Format("embeddedConverters[i].ToWMI(instNET.{0}[i]);", field.Name));
                        codeFoundType.Line("embeddedObjects[i] = embeddedConverters[i].GetInstance();");

                        codeForLoop.AddChild("else").Line(String.Format("embeddedObjects[i] = SafeAssign.GetManagementObject(instNET.{0}[i]);", field.Name));

                        codeNotNull.Line(String.Format("{0}.Value = embeddedObjects;", propFieldName));
                    }
                    else
                    {
                        CodeWriter codeFoundType = codeNotNull.AddChild(String.Format("if(mapTypeToConverter.Contains(instNET.{0}.GetType()))", field.Name));
                        codeFoundType.Line(String.Format("Type type = (Type)mapTypeToConverter[instNET.{0}.GetType()];", field.Name));
                        codeFoundType.Line("IWmiConverter converter = (IWmiConverter)Activator.CreateInstance(type);");
                        codeFoundType.Line(String.Format("converter.ToWMI(instNET.{0});", field.Name));
                        codeFoundType.Line(String.Format("{0}.Value = converter.GetInstance();", propFieldName));

                        codeNotNull.AddChild("else").Line(String.Format("{0}.Value = SafeAssign.GetInstance(instNET.{1});", propFieldName, field.Name));
                    }
                }
                else if (embeddedTypeName != null)
                {
                    // If this is an embedded struct, it cannot be null
                    CodeWriter codeNotNull;
                    if (t2.IsValueType)
                    {
                        codeNotNull = codeToWMI;
                    }
                    else
                    {
                        codeNotNull = codeToWMI.AddChild(String.Format("if(instNET.{0} != null)", field.Name));
                        CodeWriter codeElse = codeToWMI.AddChild("else");
                        codeElse.Line(String.Format("{0}.Value = null;", propFieldName));
                    }

                    if (isArray)
                    {
                        codeNotNull.Line(String.Format("int len = instNET.{0}.Length;", field.Name));
                        codeNotNull.Line("ManagementObject[] embeddedObjects = new ManagementObject[len];");
                        codeNotNull.Line(String.Format("{0}[] embeddedConverters = new {0}[len];", embeddedConverterName));

                        CodeWriter codeForLoop = codeNotNull.AddChild("for(int i=0;i<len;i++)");
                        codeForLoop.Line(String.Format("embeddedConverters[i] = new {0}();", embeddedConverterName));

                        // If this is a struct array, the elements are never null
                        if (t2.IsValueType)
                        {
                            codeForLoop.Line(String.Format("embeddedConverters[i].ToWMI(instNET.{0}[i]);", field.Name));
                        }
                        else
                        {
                            CodeWriter codeArrayElementNotNull = codeForLoop.AddChild(String.Format("if(instNET.{0}[i] != null)", field.Name));
                            codeArrayElementNotNull.Line(String.Format("embeddedConverters[i].ToWMI(instNET.{0}[i]);", field.Name));
                        }
                        codeForLoop.Line("embeddedObjects[i] = embeddedConverters[i].instance;");

                        codeNotNull.Line(String.Format("{0}.Value = embeddedObjects;", propFieldName));
                    }
                    else
                    {
                        // We cannot create an instance of 'embeddedConverterName' because it may be the
                        // same type as we are defining (in other words, a cyclic loop, such as class XXX
                        // having an instance of an XXX as a member).  To prevent an infinite loop of constructing
                        // converter classes, we create a 'lazy' variable that is initialized to NULL, and the first
                        // time it is used, we set it to a 'new embeddedConverterName'.
                        codeOneLineMembers.Line(String.Format("{0} lazy_embeddedConverter_{1} = null;", embeddedConverterName, propFieldName));
                        CodeWriter codeConverterProp = codeClass.AddChild(String.Format("{0} embeddedConverter_{1}", embeddedConverterName, propFieldName));
                        CodeWriter codeGet           = codeConverterProp.AddChild("get");
                        CodeWriter codeIf            = codeGet.AddChild(String.Format("if(null == lazy_embeddedConverter_{0})", propFieldName));
                        codeIf.Line(String.Format("lazy_embeddedConverter_{0} = new {1}();", propFieldName, embeddedConverterName));
                        codeGet.Line(String.Format("return lazy_embeddedConverter_{0};", propFieldName));

                        codeNotNull.Line(String.Format("embeddedConverter_{0}.ToWMI(instNET.{1});", propFieldName, field.Name));
                        codeNotNull.Line(String.Format("{0}.Value = embeddedConverter_{0}.instance;", propFieldName));
                    }
                }
                else if (!isArray)
                {
                    if (t2 == typeof(Byte) || t2 == typeof(SByte))
                    {
                        codeToWMI.Line(String.Format("IWOA.WritePropertyValue_f28(28, instWbemObjectAccessIP, {0}, 1, ref instNET.{1});", handleFieldName, field.Name));
                    }
                    else if (t2 == typeof(Int16) || t2 == typeof(UInt16) || t2 == typeof(Char))
                    {
                        codeToWMI.Line(String.Format("IWOA.WritePropertyValue_f28(28, instWbemObjectAccessIP, {0}, 2, ref instNET.{1});", handleFieldName, field.Name));
                    }
                    else if (t2 == typeof(UInt32) || t2 == typeof(Int32) || t2 == typeof(Single))
                    {
                        codeToWMI.Line(String.Format("IWOA.WriteDWORD_f31(31, instWbemObjectAccessIP, {0}, instNET.{1});", handleFieldName, field.Name));
                    }
                    else if (t2 == typeof(UInt64) || t2 == typeof(Int64) || t2 == typeof(Double))
                    {
                        codeToWMI.Line(String.Format("IWOA.WriteQWORD_f33(33, instWbemObjectAccessIP, {0}, instNET.{1});", handleFieldName, field.Name));
                    }
                    else if (t2 == typeof(Boolean))
                    {
                        // TODO: Fix this to use IWOA
//                        codeToWMI.Line(String.Format("{0}.Value = instNET.{1};", propFieldName, field.Name));
                        codeToWMI.Line(String.Format("if(instNET.{0})", field.Name));
                        codeToWMI.Line(String.Format("    IWOA.WritePropertyValue_f28(28, instWbemObjectAccessIP, {0}, 2, ref SafeAssign.boolTrue);", handleFieldName));
                        codeToWMI.Line("else");
                        codeToWMI.Line(String.Format("    IWOA.WritePropertyValue_f28(28, instWbemObjectAccessIP, {0}, 2, ref SafeAssign.boolFalse);", handleFieldName));
                    }
                    else if (t2 == typeof(String))
                    {
                        CodeWriter codeQuickString = codeToWMI.AddChild(String.Format("if(null != instNET.{0})", field.Name));
                        codeQuickString.Line(String.Format("IWOA.WritePropertyValue_f28(28, instWbemObjectAccessIP, {0}, (instNET.{1}.Length+1)*2, instNET.{1});", handleFieldName, field.Name));
                        //                        codeToWMI.AddChild("else").Line(String.Format("{0}.Value = instNET.{1};", propFieldName, field.Name));
                        codeToWMI.AddChild("else").Line(String.Format("IWOA.Put_f5(5, instWbemObjectAccessIP, \"{0}\", 0, ref nullObj, 8);", propName));
                        if (needsNullObj == false)
                        {
                            needsNullObj = true;

                            // Bug#111623 - This line used to say 'nullObj = null;'  When nullObj was passed
                            // to IWOA.Put, this did NOT set the value of a string variable to NULL.  The correct
                            // thing to do was to pass a reference to DBNull.Value to IWOA.Put instead.
                            codeOneLineMembers.Line("object nullObj = DBNull.Value;");
                        }
                    }
                    else if (t2 == typeof(DateTime) || t2 == typeof(TimeSpan))
                    {
                        codeToWMI.Line(String.Format("IWOA.WritePropertyValue_f28(28, instWbemObjectAccessIP, {0}, 52, SafeAssign.WMITimeToString(instNET.{1}));", handleFieldName, field.Name));
                        //                        codeToWMI.Line(String.Format("{0}.Value = SafeAssign.DateTimeToString(instNET.{1});", propFieldName, field.Name));
                    }
                    else
                    {
                        codeToWMI.Line(String.Format("{0}.Value = instNET.{1};", propFieldName, field.Name));
                    }
                }
                else
                {
                    // We have an array type
                    if (t2 == typeof(DateTime) || t2 == typeof(TimeSpan))
                    {
                        codeToWMI.AddChild(String.Format("if(null == instNET.{0})", field.Name)).Line(String.Format("{0}.Value = null;", propFieldName));
                        codeToWMI.AddChild("else").Line(String.Format("{0}.Value = SafeAssign.WMITimeArrayToStringArray(instNET.{1});", propFieldName, field.Name));
                    }
                    else
                    {
                        // This handles arrays of all primative types
                        codeToWMI.Line(String.Format("{0}.Value = instNET.{1};", propFieldName, field.Name));
                    }
                }


                CimType cimtype = CimType.String;

                if (field.DeclaringType != type)
                {
                    continue;
                }


#if REQUIRES_EXPLICIT_DECLARATION_OF_INHERITED_PROPERTIES
                if (InheritedPropertyAttribute.GetAttribute(field) != null)
                {
                    continue;
                }
#else
                // See if this field already exists on the WMI class
                // In other words, is it inherited from a base class
                // TODO: Make this more efficient
                //  - If we have a null base class name, all property names
                //    should be new
                //  - We could get all base class property names into a
                //    hashtable, and look them up from there
                bool propertyExists = true;
                try
                {
                    PropertyData prop = newClass.Properties[propName];
                    // HACK for bug#96863 - The above line used to throw a
                    // not found exception.  This was changed with a recent
                    // checkin.  If this functionality is not reverted, the
                    // following statement should force the necessary 'not
                    // found' exception that we are looking for.
                    CimType cimType = prop.Type;

                    // Make sure that if the property exists, it is inherited
                    // If it is local, they probably named two properties with
                    // the same name
                    if (prop.IsLocal)
                    {
                        throw new ArgumentException(String.Format(RC.GetString("MEMBERCONFLILCT_EXCEPT"), field.Name), field.Name);
                    }
                }
                catch (ManagementException e)
                {
                    if (e.ErrorCode != ManagementStatus.NotFound)
                    {
                        throw;
                    }
                    else
                    {
                        propertyExists = false;
                    }
                }
                if (propertyExists)
                {
                    continue;
                }
#endif


                if (embeddedTypeName != null)
                {
                    cimtype = CimType.Object;
                }
                else if (isGenericEmbeddedObject)
                {
                    cimtype = CimType.Object;
                }
                else if (t2 == typeof(ManagementObject))
                {
                    cimtype = CimType.Object;
                }
                else if (t2 == typeof(SByte))
                {
                    cimtype = CimType.SInt8;
                }
                else if (t2 == typeof(Byte))
                {
                    cimtype = CimType.UInt8;
                }
                else if (t2 == typeof(Int16))
                {
                    cimtype = CimType.SInt16;
                }
                else if (t2 == typeof(UInt16))
                {
                    cimtype = CimType.UInt16;
                }
                else if (t2 == typeof(Int32))
                {
                    cimtype = CimType.SInt32;
                }
                else if (t2 == typeof(UInt32))
                {
                    cimtype = CimType.UInt32;
                }
                else if (t2 == typeof(Int64))
                {
                    cimtype = CimType.SInt64;
                }
                else if (t2 == typeof(UInt64))
                {
                    cimtype = CimType.UInt64;
                }
                else if (t2 == typeof(Single))
                {
                    cimtype = CimType.Real32;
                }
                else if (t2 == typeof(Double))
                {
                    cimtype = CimType.Real64;
                }
                else if (t2 == typeof(Boolean))
                {
                    cimtype = CimType.Boolean;
                }
                else if (t2 == typeof(String))
                {
                    cimtype = CimType.String;
                }
                else if (t2 == typeof(Char))
                {
                    cimtype = CimType.Char16;
                }
                else if (t2 == typeof(DateTime))
                {
                    cimtype = CimType.DateTime;
                }
                else if (t2 == typeof(TimeSpan))
                {
                    cimtype = CimType.DateTime;
                }
                else
                {
                    ThrowUnsupportedMember(field);
                }
// HACK: The following line cause a strange System.InvalidProgramException when run through InstallUtil
//				throw new Exception("Unsupported type for event member - " + t2.Name);


//              TODO: if(t2 == typeof(Decimal))

#if SUPPORTS_WMI_DEFAULT_VAULES
                Object defaultValue = ManagedDefaultValueAttribute.GetManagedDefaultValue(field);

                // TODO: Is it safe to make this one line?
                if (null == defaultValue)
                {
                    props.Add(propName, cimtype, false);
                }
                else
                {
                    props.Add(propName, defaultValue, cimtype);
                }
#else
                try
                {
                    props.Add(propName, cimtype, isArray);
                }
                catch (ManagementException e)
                {
                    ThrowUnsupportedMember(field, e);
                }
#endif

                // Must at 'interval' SubType on TimeSpans
                if (t2 == typeof(TimeSpan))
                {
                    PropertyData prop = props[propName];
                    prop.Qualifiers.Add("SubType", "interval", false, true, true, true);
                }

                if (embeddedTypeName != null)
                {
                    PropertyData prop = props[propName];
                    prop.Qualifiers["CIMTYPE"].Value = "object:" + embeddedTypeName;
                }
            }
            codeCCTOR.Line("Marshal.Release(wbemObjectAccessIP);");
//            codeToWMI.Line("Console.WriteLine(instance.GetText(TextFormat.Mof));");
        }
Beispiel #5
0
        int IWbemServices_Old.CreateInstanceEnumAsync_([In][MarshalAs(UnmanagedType.BStr)]  string strFilter,
                                                       [In] Int32 lFlags,
                                                       [In][MarshalAs(UnmanagedType.Interface)]  IWbemContext pCtx,
                                                       [In][MarshalAs(UnmanagedType.Interface)]  IWbemObjectSink pResponseHandler)
        {
            try
            {
                // Make sure we do not let a shutdown kill this thread
                preventShutdownLock.AcquireReaderLock(-1);

                // If we are already shutting down, don't do anything
                if (shutdownInProgress != 0)
                {
                    return(0);
                }

                // If batching takes longer than 1/10 of a second, we want to stop
                // and flush the batch
                uint timeLimitForBatchFlush = (uint)Environment.TickCount + 100;

                // Find the managed type that is being requested by this call
                Type managedType = null;
                foreach (Type type in instrumentedAssembly.mapTypeToConverter.Keys)
                {
                    if (0 == String.Compare(ManagedNameAttribute.GetMemberName(type), strFilter, StringComparison.Ordinal))
                    {
                        managedType = type;
                        break;
                    }
                }

                // If we do not support the requested type, just exit
                if (null == managedType)
                {
                    return(0);
                }

                // size for batching
                int batchSize = 64;

                // Array of IWbemClassObject IntPtrs for batching
                IntPtr[] objs      = new IntPtr[batchSize];
                IntPtr[] objsClone = new IntPtr[batchSize];

                // Array of converter methods for batching
                ConvertToWMI[] funcs = new ConvertToWMI[batchSize];

                // Array of IWbemClassObjectFreeThreaded instances for batching
                IWbemClassObjectFreeThreaded[] insts = new IWbemClassObjectFreeThreaded[batchSize];

                // IWbemObjectAccess handle for 'InstanceId'
                int handleInstanceId = 0;

                // Current number of objects in batch
                int count = 0;

                // The process identity string
                Object processIdentity = Instrumentation.ProcessIdentity;

                // Walk all published instances
                try
                {
                    // Don't let anyone add entries to the dictionary while we are enumerating it.
                    // Other people can read from the dictionary
                    InstrumentedAssembly.readerWriterLock.AcquireReaderLock(-1);
                    foreach (DictionaryEntry entry in InstrumentedAssembly.mapIDToPublishedObject)
                    {
                        // If the process is going away, stop indicating more instances
                        if (shutdownInProgress != 0)
                        {
                            return(0);
                        }

                        // Is this object the type requested by this query?
                        if (managedType != entry.Value.GetType())
                        {
                            continue;
                        }

                        // Initialize this batch entry if necessary.  Each element of the batch arrays
                        // are initialized 'just in time'.  If we have less than batchSize entries total
                        // (or it takes too long to batch), we do not unnecessarily allocate the batch entry
                        if (funcs[count] == null)
                        {
                            Object converter = Activator.CreateInstance((Type)instrumentedAssembly.mapTypeToConverter[managedType]);
                            funcs[count] = (ConvertToWMI)Delegate.CreateDelegate(typeof(ConvertToWMI), converter, "ToWMI");

                            //
                            // Reuters VSQFE#: 750    [marioh]
                            // In order for the instance data batching logic to work properly, we HAVE TO convert the .NET
                            // objects to WMI objects before we update the batching pointers since the ToWMI method in the generated
                            // code will Spawn new instances.
                            //
                            lock (entry.Value)
                                funcs[count](entry.Value);

                            objs[count] = (IntPtr)converter.GetType().GetField("instWbemObjectAccessIP").GetValue(converter);
                            Marshal.AddRef(objs[count]);
                            insts[count] = new IWbemClassObjectFreeThreaded(objs[count]);
                            insts[count].Put_("ProcessId", 0, ref processIdentity, 0);

                            int cimType;
                            if (count == 0)
                            {
                                WmiNetUtilsHelper.GetPropertyHandle_f27(27, insts[count], "InstanceId", out cimType, out handleInstanceId);
                            }
                        }
                        else
                        {
                            //
                            // Reuters VSQFE#: 750    [marioh]
                            // If we end up re-using an existing delegate from the batch array, we still have to convert
                            // the .NET to WMI objects and update the instance pointers.
                            //

                            // Copy the managed instance information into the IWbemClassObject'
                            // We're using a batch, therefore we have to convert them.
                            lock (entry.Value)
                                funcs[count](entry.Value);

                            objs[count] = (IntPtr)funcs[count].Target.GetType().GetField("instWbemObjectAccessIP").GetValue(funcs[count].Target);

                            //
                            // We have to AddRef the interface pointer due to the IWbemClassObjectFreeThreaded not addreffing
                            // but releasing in the destructor. Great huh?
                            //
                            Marshal.AddRef(objs[count]);
                            insts[count] = new IWbemClassObjectFreeThreaded(objs[count]);
                            insts[count].Put_("ProcessId", 0, ref processIdentity, 0);

                            int cimType;
                            if (count == 0)
                            {
                                WmiNetUtilsHelper.GetPropertyHandle_f27(27, insts[count], "InstanceId", out cimType, out handleInstanceId);
                            }
                        }

                        // We have an instance to publish.  Store the instance ID in 'InstanceId'
                        string instanceId = (string)entry.Key;
                        WmiNetUtilsHelper.WritePropertyValue_f28(28, insts[count], handleInstanceId, (instanceId.Length + 1) * 2, instanceId);

                        //                        // Copy the managed instance information into the IWbemClassObject'
                        //                        lock(entry.Value)
                        //                            funcs[count](entry.Value);

                        // Increment the batch counter
                        count++;

                        // If we've reached batchSize, or if we've gone longer than 1/10th second since
                        // an Indicate, flush the batch
                        if (count == batchSize || ((uint)Environment.TickCount) >= timeLimitForBatchFlush)
                        {
                            // Do the Indicate to WMI
                            // NOTE: On WinXP, we cannot control whether the implementation of
                            // Indicate will immediately send the objects to WMI, or if it will
                            // batch them.  If it batches them, we cannot reuse them in a future
                            // call to Indicate, or change them in any way after the call to
                            // Indicate.  Because of this, we will always 'Clone' the objects
                            // just before calling Indicate.  The performance is negligable, even
                            // on Windows 2000, which can handle about 200,000 Clones per second
                            // on a 1 GHz machine.
                            for (int i = 0; i < count; i++)
                            {
                                WmiNetUtilsHelper.Clone_f(12, objs[i], out objsClone[i]);
                            }
                            int hr = pResponseHandler.Indicate_(count, objsClone);
                            for (int i = 0; i < count; i++)
                            {
                                Marshal.Release(objsClone[i]);
                            }

                            // If hr is not S_OK, we stop the enumeration.  This can happen if the
                            // client cancels the call.
                            if (hr != 0)
                            {
                                return(0);
                            }

                            // Reset the batch counter
                            count = 0;

                            // Reset the time limit for another 1/10th second in the future
                            timeLimitForBatchFlush = (uint)Environment.TickCount + 100;
                        }
                    }
                }
                finally
                {
                    InstrumentedAssembly.readerWriterLock.ReleaseReaderLock();
                }
                if (count > 0)
                {
                    // NOTE: On WinXP, we cannot control whether the implementation of
                    // Indicate will immediately send the objects to WMI, or if it will
                    // batch them.  If it batches them, we cannot reuse them in a future
                    // call to Indicate, or change them in any way after the call to
                    // Indicate.  Because of this, we will always 'Clone' the objects
                    // just before calling Indicate.  The performance is negligable, even
                    // on Windows 2000, which can handle about 200,000 Clones per second
                    // on a 1 GHz machine.
                    for (int i = 0; i < count; i++)
                    {
                        WmiNetUtilsHelper.Clone_f(12, objs[i], out objsClone[i]);
                    }
                    pResponseHandler.Indicate_(count, objsClone);
                    for (int i = 0; i < count; i++)
                    {
                        Marshal.Release(objsClone[i]);
                    }
                }
            }
            finally
            {
                pResponseHandler.SetStatus_(0, 0, null, IntPtr.Zero);
                Marshal.ReleaseComObject(pResponseHandler);
                preventShutdownLock.ReleaseReaderLock();
            }
            return(0);
        }
            public TypeInfo(EventSource source, SchemaNaming naming, Type t)
            {
                this.toWMI = (ConvertFuncToWMI)InstrumentedAssembly.mapTypeToToWMIFunc[t];
                this.toNET = (ConvertFuncToNET)InstrumentedAssembly.mapTypeToToNETFunc[t];
                this.t     = t;
                isSTA      = Thread.CurrentThread.ApartmentState == ApartmentState.STA;
                ManagementClass eventClass = new ManagementClass(naming.NamespaceName + ":" + ManagedNameAttribute.GetMemberName(t));
                PropertyInfo    prop       = typeof(ManagementBaseObject).GetProperty("WmiObject", BindingFlags.Instance | BindingFlags.NonPublic);

                ManagementObject evt = eventClass.CreateInstance();

                obj         = (IWbemClassObject_DoNotMarshal)prop.GetValue(evt, null);
                this.source = source;


                SetBatchSize(batchSize);

                IWbemClassObject_DoNotMarshal obj2;

                obj.Clone_(out obj2);
                xoa1[0] = (IWbemObjectAccess)obj2;
                oa1test = new ClassObjectArray(xoa1);

                writeDWORD1 = new WriteDWORD(xoa1[0].WriteDWORD_);
                writeQWORD1 = new WriteQWORD(xoa1[0].WriteQWORD_);

#if xxx
                string             code       = CodeSpit.Spit(t, xoa1[0]);
                CSharpCodeProvider provider   = new CSharpCodeProvider();
                ICodeCompiler      compiler   = provider.CreateCompiler();
                CompilerParameters parameters = new CompilerParameters();
                parameters.GenerateInMemory = true;

                parameters.ReferencedAssemblies.Add(t.Assembly.Location);
                parameters.ReferencedAssemblies.Add(typeof(WriteDWORD).Assembly.Location);
                parameters.ReferencedAssemblies.Add(typeof(Event).Assembly.Location);
                CompilerResults results = compiler.CompileAssemblyFromSource(parameters, code);
                foreach (CompilerError err in results.Errors)
                {
                    Console.WriteLine(err.ToString());
                }
                Type dynType = results.CompiledAssembly.GetType("Hack");

                MethodInfo doit = dynType.GetMethod("Func");

                managedToIWbem = (ManagedToIWbem)Delegate.CreateDelegate(typeof(ManagedToIWbem), doit);
#endif
            }
Beispiel #7
0
        int System.Management.IWbemServices_Old.CreateInstanceEnumAsync_(string strFilter, int lFlags, IWbemContext pCtx, IWbemObjectSink pResponseHandler)
        {
            Type type = null;
            int  num;

            try
            {
                EventSource.preventShutdownLock.AcquireReaderLock(-1);
                if (EventSource.shutdownInProgress == 0)
                {
                    int tickCount = Environment.TickCount + 100;
                    foreach (Type key in this.instrumentedAssembly.mapTypeToConverter.Keys)
                    {
                        if (string.Compare(ManagedNameAttribute.GetMemberName(key), strFilter, StringComparison.Ordinal) != 0)
                        {
                            continue;
                        }
                        type = key;
                        break;
                    }
                    if (null != type)
                    {
                        int            num1              = 64;
                        IntPtr[]       value             = new IntPtr[num1];
                        IntPtr[]       intPtrArray       = new IntPtr[num1];
                        ConvertToWMI[] convertToWMIArray = new ConvertToWMI[num1];
                        IWbemClassObjectFreeThreaded[] wbemClassObjectFreeThreaded = new IWbemClassObjectFreeThreaded[num1];
                        int    num2            = 0;
                        int    V_8             = 0;
                        object processIdentity = Instrumentation.ProcessIdentity;
                        try
                        {
                            InstrumentedAssembly.readerWriterLock.AcquireReaderLock(-1);
                            foreach (DictionaryEntry dictionaryEntry in InstrumentedAssembly.mapIDToPublishedObject)
                            {
                                if (EventSource.shutdownInProgress == 0)
                                {
                                    if (type != dictionaryEntry.Value.GetType())
                                    {
                                        continue;
                                    }
                                    if (convertToWMIArray[num2] != null)
                                    {
                                        lock (dictionaryEntry.Value)
                                        {
                                            convertToWMIArray[num2](dictionaryEntry.Value);
                                        }
                                        value[num2] = (IntPtr)convertToWMIArray[num2].Target.GetType().GetField("instWbemObjectAccessIP").GetValue(convertToWMIArray[num2].Target);
                                        Marshal.AddRef(value[num2]);
                                        wbemClassObjectFreeThreaded[num2] = new IWbemClassObjectFreeThreaded(value[num2]);
                                        wbemClassObjectFreeThreaded[num2].Put_("ProcessId", 0, ref processIdentity, 0);
                                        if (num2 == 0)
                                        {
                                            int V_15;
                                            WmiNetUtilsHelper.GetPropertyHandle_f27(27, wbemClassObjectFreeThreaded[num2], "InstanceId", out V_15, out V_8);
                                        }
                                    }
                                    else
                                    {
                                        object obj = Activator.CreateInstance((Type)this.instrumentedAssembly.mapTypeToConverter[type]);
                                        convertToWMIArray[num2] = (ConvertToWMI)Delegate.CreateDelegate(typeof(ConvertToWMI), obj, "ToWMI");
                                        lock (dictionaryEntry.Value)
                                        {
                                            convertToWMIArray[num2](dictionaryEntry.Value);
                                        }
                                        value[num2] = (IntPtr)obj.GetType().GetField("instWbemObjectAccessIP").GetValue(obj);
                                        Marshal.AddRef(value[num2]);
                                        wbemClassObjectFreeThreaded[num2] = new IWbemClassObjectFreeThreaded(value[num2]);
                                        wbemClassObjectFreeThreaded[num2].Put_("ProcessId", 0, ref processIdentity, 0);
                                        if (num2 == 0)
                                        {
                                            int V_13;
                                            WmiNetUtilsHelper.GetPropertyHandle_f27(27, wbemClassObjectFreeThreaded[num2], "InstanceId", out V_13, out V_8);
                                        }
                                    }
                                    string str = (string)dictionaryEntry.Key;
                                    WmiNetUtilsHelper.WritePropertyValue_f28(28, wbemClassObjectFreeThreaded[num2], V_8, (str.Length + 1) * 2, str);
                                    num2++;
                                    if (num2 != num1 && Environment.TickCount < tickCount)
                                    {
                                        continue;
                                    }
                                    for (int i = 0; i < num2; i++)
                                    {
                                        WmiNetUtilsHelper.Clone_f(12, value[i], out intPtrArray[i]);
                                    }
                                    int num3 = pResponseHandler.Indicate_(num2, intPtrArray);
                                    for (int j = 0; j < num2; j++)
                                    {
                                        Marshal.Release(intPtrArray[j]);
                                    }
                                    if (num3 == 0)
                                    {
                                        num2      = 0;
                                        tickCount = Environment.TickCount + 100;
                                    }
                                    else
                                    {
                                        num = 0;
                                        return(num);
                                    }
                                }
                                else
                                {
                                    num = 0;
                                    return(num);
                                }
                            }
                        }
                        finally
                        {
                            InstrumentedAssembly.readerWriterLock.ReleaseReaderLock();
                        }
                        if (num2 > 0)
                        {
                            for (int k = 0; k < num2; k++)
                            {
                                WmiNetUtilsHelper.Clone_f(12, value[k], out intPtrArray[k]);
                            }
                            pResponseHandler.Indicate_(num2, intPtrArray);
                            for (int l = 0; l < num2; l++)
                            {
                                Marshal.Release(intPtrArray[l]);
                            }
                        }
                        return(0);
                    }
                    else
                    {
                        num = 0;
                    }
                }
                else
                {
                    num = 0;
                }
            }
            finally
            {
                pResponseHandler.SetStatus_(0, 0, null, IntPtr.Zero);
                Marshal.ReleaseComObject(pResponseHandler);
                EventSource.preventShutdownLock.ReleaseReaderLock();
            }
            return(num);
        }
Beispiel #8
0
 int IWbemServices_Old.CreateInstanceEnumAsync_([In, MarshalAs(UnmanagedType.BStr)] string strFilter, [In] int lFlags, [In, MarshalAs(UnmanagedType.Interface)] IWbemContext pCtx, [In, MarshalAs(UnmanagedType.Interface)] IWbemObjectSink pResponseHandler)
 {
     try
     {
         preventShutdownLock.AcquireReaderLock(-1);
         if (shutdownInProgress != 0)
         {
             return(0);
         }
         uint num  = (uint)(Environment.TickCount + 100);
         Type type = null;
         foreach (Type type2 in this.instrumentedAssembly.mapTypeToConverter.Keys)
         {
             if (string.Compare(ManagedNameAttribute.GetMemberName(type2), strFilter, StringComparison.Ordinal) == 0)
             {
                 type = type2;
                 break;
             }
         }
         if (null == type)
         {
             return(0);
         }
         int            num2       = 0x40;
         IntPtr[]       ptrArray   = new IntPtr[num2];
         IntPtr[]       apObjArray = new IntPtr[num2];
         ConvertToWMI[] owmiArray  = new ConvertToWMI[num2];
         IWbemClassObjectFreeThreaded[] threadedArray = new IWbemClassObjectFreeThreaded[num2];
         int    plHandle        = 0;
         int    index           = 0;
         object processIdentity = System.Management.Instrumentation.Instrumentation.ProcessIdentity;
         try
         {
             InstrumentedAssembly.readerWriterLock.AcquireReaderLock(-1);
             foreach (DictionaryEntry entry in InstrumentedAssembly.mapIDToPublishedObject)
             {
                 if (shutdownInProgress != 0)
                 {
                     return(0);
                 }
                 if (type == entry.Value.GetType())
                 {
                     if (owmiArray[index] == null)
                     {
                         object target = Activator.CreateInstance((Type)this.instrumentedAssembly.mapTypeToConverter[type]);
                         owmiArray[index] = (ConvertToWMI)Delegate.CreateDelegate(typeof(ConvertToWMI), target, "ToWMI");
                         lock (entry.Value)
                         {
                             owmiArray[index](entry.Value);
                         }
                         ptrArray[index] = (IntPtr)target.GetType().GetField("instWbemObjectAccessIP").GetValue(target);
                         Marshal.AddRef(ptrArray[index]);
                         threadedArray[index] = new IWbemClassObjectFreeThreaded(ptrArray[index]);
                         threadedArray[index].Put_("ProcessId", 0, ref processIdentity, 0);
                         if (index == 0)
                         {
                             int num5;
                             WmiNetUtilsHelper.GetPropertyHandle_f27(0x1b, (IntPtr)threadedArray[index], "InstanceId", out num5, out plHandle);
                         }
                     }
                     else
                     {
                         lock (entry.Value)
                         {
                             owmiArray[index](entry.Value);
                         }
                         ptrArray[index] = (IntPtr)owmiArray[index].Target.GetType().GetField("instWbemObjectAccessIP").GetValue(owmiArray[index].Target);
                         Marshal.AddRef(ptrArray[index]);
                         threadedArray[index] = new IWbemClassObjectFreeThreaded(ptrArray[index]);
                         threadedArray[index].Put_("ProcessId", 0, ref processIdentity, 0);
                         if (index == 0)
                         {
                             int num6;
                             WmiNetUtilsHelper.GetPropertyHandle_f27(0x1b, (IntPtr)threadedArray[index], "InstanceId", out num6, out plHandle);
                         }
                     }
                     string key = (string)entry.Key;
                     WmiNetUtilsHelper.WritePropertyValue_f28(0x1c, (IntPtr)threadedArray[index], plHandle, (key.Length + 1) * 2, key);
                     index++;
                     if ((index == num2) || (Environment.TickCount >= num))
                     {
                         for (int i = 0; i < index; i++)
                         {
                             WmiNetUtilsHelper.Clone_f(12, ptrArray[i], out apObjArray[i]);
                         }
                         int num8 = pResponseHandler.Indicate_(index, apObjArray);
                         for (int j = 0; j < index; j++)
                         {
                             Marshal.Release(apObjArray[j]);
                         }
                         if (num8 != 0)
                         {
                             return(0);
                         }
                         index = 0;
                         num   = (uint)(Environment.TickCount + 100);
                     }
                 }
             }
         }
         finally
         {
             InstrumentedAssembly.readerWriterLock.ReleaseReaderLock();
         }
         if (index > 0)
         {
             for (int k = 0; k < index; k++)
             {
                 WmiNetUtilsHelper.Clone_f(12, ptrArray[k], out apObjArray[k]);
             }
             pResponseHandler.Indicate_(index, apObjArray);
             for (int m = 0; m < index; m++)
             {
                 Marshal.Release(apObjArray[m]);
             }
         }
     }
     finally
     {
         pResponseHandler.SetStatus_(0, 0, null, IntPtr.Zero);
         Marshal.ReleaseComObject(pResponseHandler);
         preventShutdownLock.ReleaseReaderLock();
     }
     return(0);
 }
        public SchemaMapping(Type type, SchemaNaming naming, Hashtable mapTypeToConverterClassName)
        {
            this.codeClassName = (string)mapTypeToConverterClassName[type];
            this.classType     = type;
            bool   flag          = false;
            string baseClassName = ManagedNameAttribute.GetBaseClassName(type);

            this.className           = ManagedNameAttribute.GetMemberName(type);
            this.instrumentationType = InstrumentationClassAttribute.GetAttribute(type).InstrumentationType;
            this.classPath           = naming.NamespaceName + ":" + this.className;
            if (baseClassName == null)
            {
                this.newClass = new ManagementClass(naming.NamespaceName, "", null);
                this.newClass.SystemProperties["__CLASS"].Value = this.className;
            }
            else
            {
                ManagementClass class2 = new ManagementClass(naming.NamespaceName + ":" + baseClassName);
                if (this.instrumentationType == System.Management.Instrumentation.InstrumentationType.Instance)
                {
                    bool flag2 = false;
                    try
                    {
                        QualifierData data = class2.Qualifiers["abstract"];
                        if (data.Value is bool)
                        {
                            flag2 = (bool)data.Value;
                        }
                    }
                    catch (ManagementException exception)
                    {
                        if (exception.ErrorCode != ManagementStatus.NotFound)
                        {
                            throw;
                        }
                    }
                    if (!flag2)
                    {
                        throw new Exception(RC.GetString("CLASSINST_EXCEPT"));
                    }
                }
                this.newClass = class2.Derive(this.className);
            }
            CodeWriter writer  = this.code.AddChild("public class " + this.codeClassName + " : IWmiConverter");
            CodeWriter writer2 = writer.AddChild(new CodeWriter());

            writer2.Line("static ManagementClass managementClass = new ManagementClass(@\"" + this.classPath + "\");");
            writer2.Line("static IntPtr classWbemObjectIP;");
            writer2.Line("static Guid iidIWbemObjectAccess = new Guid(\"49353C9A-516B-11D1-AEA6-00C04FB68820\");");
            writer2.Line("internal ManagementObject instance = managementClass.CreateInstance();");
            writer2.Line("object reflectionInfoTempObj = null ; ");
            writer2.Line("FieldInfo reflectionIWbemClassObjectField = null ; ");
            writer2.Line("IntPtr emptyWbemObject = IntPtr.Zero ; ");
            writer2.Line("IntPtr originalObject = IntPtr.Zero ; ");
            writer2.Line("bool toWmiCalled = false ; ");
            writer2.Line("IntPtr theClone = IntPtr.Zero;");
            writer2.Line("public static ManagementObject emptyInstance = managementClass.CreateInstance();");
            writer2.Line("public IntPtr instWbemObjectAccessIP;");
            CodeWriter writer3 = writer.AddChild("static " + this.codeClassName + "()");

            writer3.Line("classWbemObjectIP = (IntPtr)managementClass;");
            writer3.Line("IntPtr wbemObjectAccessIP;");
            writer3.Line("Marshal.QueryInterface(classWbemObjectIP, ref iidIWbemObjectAccess, out wbemObjectAccessIP);");
            writer3.Line("int cimType;");
            CodeWriter writer4 = writer.AddChild("public " + this.codeClassName + "()");

            writer4.Line("IntPtr wbemObjectIP = (IntPtr)instance;");
            writer4.Line("originalObject = (IntPtr)instance;");
            writer4.Line("Marshal.QueryInterface(wbemObjectIP, ref iidIWbemObjectAccess, out instWbemObjectAccessIP);");
            writer4.Line("FieldInfo tempField = instance.GetType().GetField ( \"_wbemObject\", BindingFlags.Instance | BindingFlags.NonPublic );");
            writer4.Line("if ( tempField == null )");
            writer4.Line("{");
            writer4.Line("   tempField = instance.GetType().GetField ( \"wbemObject\", BindingFlags.Instance | BindingFlags.NonPublic ) ;");
            writer4.Line("}");
            writer4.Line("reflectionInfoTempObj = tempField.GetValue (instance) ;");
            writer4.Line("reflectionIWbemClassObjectField = reflectionInfoTempObj.GetType().GetField (\"pWbemClassObject\", BindingFlags.Instance | BindingFlags.NonPublic );");
            writer4.Line("emptyWbemObject = (IntPtr) emptyInstance;");
            CodeWriter writer5 = writer.AddChild("~" + this.codeClassName + "()");

            writer5.AddChild("if(instWbemObjectAccessIP != IntPtr.Zero)").Line("Marshal.Release(instWbemObjectAccessIP);");
            writer5.Line("if ( toWmiCalled == true )");
            writer5.Line("{");
            writer5.Line("\tMarshal.Release (originalObject);");
            writer5.Line("}");
            CodeWriter writer6 = writer.AddChild("public void ToWMI(object obj)");

            writer6.Line("toWmiCalled = true ;");
            writer6.Line("if(instWbemObjectAccessIP != IntPtr.Zero)");
            writer6.Line("{");
            writer6.Line("    Marshal.Release(instWbemObjectAccessIP);");
            writer6.Line("    instWbemObjectAccessIP = IntPtr.Zero;");
            writer6.Line("}");
            writer6.Line("if(theClone != IntPtr.Zero)");
            writer6.Line("{");
            writer6.Line("    Marshal.Release(theClone);");
            writer6.Line("    theClone = IntPtr.Zero;");
            writer6.Line("}");
            writer6.Line("IWOA.Clone_f(12, emptyWbemObject, out theClone) ;");
            writer6.Line("Marshal.QueryInterface(theClone, ref iidIWbemObjectAccess, out instWbemObjectAccessIP) ;");
            writer6.Line("reflectionIWbemClassObjectField.SetValue ( reflectionInfoTempObj, theClone ) ;");
            writer6.Line(string.Format("{0} instNET = ({0})obj;", type.FullName.Replace('+', '.')));
            writer.AddChild("public static explicit operator IntPtr(" + this.codeClassName + " obj)").Line("return obj.instWbemObjectAccessIP;");
            writer2.Line("public ManagementObject GetInstance() {return instance;}");
            PropertyDataCollection properties = this.newClass.Properties;

            switch (this.instrumentationType)
            {
            case System.Management.Instrumentation.InstrumentationType.Instance:
                properties.Add("ProcessId", CimType.String, false);
                properties.Add("InstanceId", CimType.String, false);
                properties["ProcessId"].Qualifiers.Add("key", true);
                properties["InstanceId"].Qualifiers.Add("key", true);
                this.newClass.Qualifiers.Add("dynamic", true, false, false, false, true);
                this.newClass.Qualifiers.Add("provider", naming.DecoupledProviderInstanceName, false, false, false, true);
                break;

            case System.Management.Instrumentation.InstrumentationType.Abstract:
                this.newClass.Qualifiers.Add("abstract", true, false, false, false, true);
                break;
            }
            int  num   = 0;
            bool flag3 = false;

            foreach (MemberInfo info in type.GetMembers())
            {
                if (((info is FieldInfo) || (info is PropertyInfo)) && (info.GetCustomAttributes(typeof(IgnoreMemberAttribute), false).Length <= 0))
                {
                    Type fieldType;
                    if (info is FieldInfo)
                    {
                        FieldInfo info2 = info as FieldInfo;
                        if (info2.IsStatic)
                        {
                            ThrowUnsupportedMember(info);
                        }
                    }
                    else if (info is PropertyInfo)
                    {
                        PropertyInfo info3 = info as PropertyInfo;
                        if (!info3.CanRead)
                        {
                            ThrowUnsupportedMember(info);
                        }
                        MethodInfo getMethod = info3.GetGetMethod();
                        if ((null == getMethod) || getMethod.IsStatic)
                        {
                            ThrowUnsupportedMember(info);
                        }
                        if (getMethod.GetParameters().Length > 0)
                        {
                            ThrowUnsupportedMember(info);
                        }
                    }
                    string memberName = ManagedNameAttribute.GetMemberName(info);
                    if (info is FieldInfo)
                    {
                        fieldType = (info as FieldInfo).FieldType;
                    }
                    else
                    {
                        fieldType = (info as PropertyInfo).PropertyType;
                    }
                    bool isArray = false;
                    if (fieldType.IsArray)
                    {
                        if (fieldType.GetArrayRank() != 1)
                        {
                            ThrowUnsupportedMember(info);
                        }
                        isArray   = true;
                        fieldType = fieldType.GetElementType();
                    }
                    string str3 = null;
                    string str4 = null;
                    if (mapTypeToConverterClassName.Contains(fieldType))
                    {
                        str4 = (string)mapTypeToConverterClassName[fieldType];
                        str3 = ManagedNameAttribute.GetMemberName(fieldType);
                    }
                    bool flag5 = false;
                    if (fieldType == typeof(object))
                    {
                        flag5 = true;
                        if (!flag)
                        {
                            flag = true;
                            writer2.Line("static Hashtable mapTypeToConverter = new Hashtable();");
                            foreach (DictionaryEntry entry in mapTypeToConverterClassName)
                            {
                                string introduced55 = ((Type)entry.Key).FullName.Replace('+', '.');
                                writer3.Line(string.Format("mapTypeToConverter[typeof({0})] = typeof({1});", introduced55, (string)entry.Value));
                            }
                        }
                    }
                    string str5 = "prop_" + num;
                    string str6 = "handle_" + num++;
                    writer2.Line("static int " + str6 + ";");
                    writer3.Line(string.Format("IWOA.GetPropertyHandle_f27(27, wbemObjectAccessIP, \"{0}\", out cimType, out {1});", memberName, str6));
                    writer2.Line("PropertyData " + str5 + ";");
                    writer4.Line(string.Format("{0} = instance.Properties[\"{1}\"];", str5, memberName));
                    if (flag5)
                    {
                        CodeWriter writer8 = writer6.AddChild(string.Format("if(instNET.{0} != null)", info.Name));
                        writer6.AddChild("else").Line(string.Format("{0}.Value = null;", str5));
                        if (isArray)
                        {
                            writer8.Line(string.Format("int len = instNET.{0}.Length;", info.Name));
                            writer8.Line("ManagementObject[] embeddedObjects = new ManagementObject[len];");
                            writer8.Line("IWmiConverter[] embeddedConverters = new IWmiConverter[len];");
                            CodeWriter writer10 = writer8.AddChild("for(int i=0;i<len;i++)");
                            CodeWriter writer11 = writer10.AddChild(string.Format("if((instNET.{0}[i] != null) && mapTypeToConverter.Contains(instNET.{0}[i].GetType()))", info.Name));
                            writer11.Line(string.Format("Type type = (Type)mapTypeToConverter[instNET.{0}[i].GetType()];", info.Name));
                            writer11.Line("embeddedConverters[i] = (IWmiConverter)Activator.CreateInstance(type);");
                            writer11.Line(string.Format("embeddedConverters[i].ToWMI(instNET.{0}[i]);", info.Name));
                            writer11.Line("embeddedObjects[i] = embeddedConverters[i].GetInstance();");
                            writer10.AddChild("else").Line(string.Format("embeddedObjects[i] = SafeAssign.GetManagementObject(instNET.{0}[i]);", info.Name));
                            writer8.Line(string.Format("{0}.Value = embeddedObjects;", str5));
                        }
                        else
                        {
                            CodeWriter writer12 = writer8.AddChild(string.Format("if(mapTypeToConverter.Contains(instNET.{0}.GetType()))", info.Name));
                            writer12.Line(string.Format("Type type = (Type)mapTypeToConverter[instNET.{0}.GetType()];", info.Name));
                            writer12.Line("IWmiConverter converter = (IWmiConverter)Activator.CreateInstance(type);");
                            writer12.Line(string.Format("converter.ToWMI(instNET.{0});", info.Name));
                            writer12.Line(string.Format("{0}.Value = converter.GetInstance();", str5));
                            writer8.AddChild("else").Line(string.Format("{0}.Value = SafeAssign.GetInstance(instNET.{1});", str5, info.Name));
                        }
                    }
                    else if (str3 != null)
                    {
                        CodeWriter writer13;
                        if (fieldType.IsValueType)
                        {
                            writer13 = writer6;
                        }
                        else
                        {
                            writer13 = writer6.AddChild(string.Format("if(instNET.{0} != null)", info.Name));
                            writer6.AddChild("else").Line(string.Format("{0}.Value = null;", str5));
                        }
                        if (isArray)
                        {
                            writer13.Line(string.Format("int len = instNET.{0}.Length;", info.Name));
                            writer13.Line("ManagementObject[] embeddedObjects = new ManagementObject[len];");
                            writer13.Line(string.Format("{0}[] embeddedConverters = new {0}[len];", str4));
                            CodeWriter writer15 = writer13.AddChild("for(int i=0;i<len;i++)");
                            writer15.Line(string.Format("embeddedConverters[i] = new {0}();", str4));
                            if (fieldType.IsValueType)
                            {
                                writer15.Line(string.Format("embeddedConverters[i].ToWMI(instNET.{0}[i]);", info.Name));
                            }
                            else
                            {
                                writer15.AddChild(string.Format("if(instNET.{0}[i] != null)", info.Name)).Line(string.Format("embeddedConverters[i].ToWMI(instNET.{0}[i]);", info.Name));
                            }
                            writer15.Line("embeddedObjects[i] = embeddedConverters[i].instance;");
                            writer13.Line(string.Format("{0}.Value = embeddedObjects;", str5));
                        }
                        else
                        {
                            writer2.Line(string.Format("{0} lazy_embeddedConverter_{1} = null;", str4, str5));
                            CodeWriter writer18 = writer.AddChild(string.Format("{0} embeddedConverter_{1}", str4, str5)).AddChild("get");
                            writer18.AddChild(string.Format("if(null == lazy_embeddedConverter_{0})", str5)).Line(string.Format("lazy_embeddedConverter_{0} = new {1}();", str5, str4));
                            writer18.Line(string.Format("return lazy_embeddedConverter_{0};", str5));
                            writer13.Line(string.Format("embeddedConverter_{0}.ToWMI(instNET.{1});", str5, info.Name));
                            writer13.Line(string.Format("{0}.Value = embeddedConverter_{0}.instance;", str5));
                        }
                    }
                    else if (!isArray)
                    {
                        if ((fieldType == typeof(byte)) || (fieldType == typeof(sbyte)))
                        {
                            writer6.Line(string.Format("{0} instNET_{1} = instNET.{1} ;", fieldType, info.Name));
                            writer6.Line(string.Format("IWOA.WritePropertyValue_f28(28, instWbemObjectAccessIP, {0}, 1, ref instNET_{1});", str6, info.Name));
                        }
                        else if (((fieldType == typeof(short)) || (fieldType == typeof(ushort))) || (fieldType == typeof(char)))
                        {
                            writer6.Line(string.Format("{0} instNET_{1} = instNET.{1} ;", fieldType, info.Name));
                            writer6.Line(string.Format("IWOA.WritePropertyValue_f28(28, instWbemObjectAccessIP, {0}, 2, ref instNET_{1});", str6, info.Name));
                        }
                        else if (((fieldType == typeof(uint)) || (fieldType == typeof(int))) || (fieldType == typeof(float)))
                        {
                            writer6.Line(string.Format("IWOA.WriteDWORD_f31(31, instWbemObjectAccessIP, {0}, instNET.{1});", str6, info.Name));
                        }
                        else if (((fieldType == typeof(ulong)) || (fieldType == typeof(long))) || (fieldType == typeof(double)))
                        {
                            writer6.Line(string.Format("IWOA.WriteQWORD_f33(33, instWbemObjectAccessIP, {0}, instNET.{1});", str6, info.Name));
                        }
                        else if (fieldType == typeof(bool))
                        {
                            writer6.Line(string.Format("if(instNET.{0})", info.Name));
                            writer6.Line(string.Format("    IWOA.WritePropertyValue_f28(28, instWbemObjectAccessIP, {0}, 2, ref SafeAssign.boolTrue);", str6));
                            writer6.Line("else");
                            writer6.Line(string.Format("    IWOA.WritePropertyValue_f28(28, instWbemObjectAccessIP, {0}, 2, ref SafeAssign.boolFalse);", str6));
                        }
                        else if (fieldType == typeof(string))
                        {
                            writer6.AddChild(string.Format("if(null != instNET.{0})", info.Name)).Line(string.Format("IWOA.WritePropertyValue_f28(28, instWbemObjectAccessIP, {0}, (instNET.{1}.Length+1)*2, instNET.{1});", str6, info.Name));
                            writer6.AddChild("else").Line(string.Format("IWOA.Put_f5(5, instWbemObjectAccessIP, \"{0}\", 0, ref nullObj, 8);", memberName));
                            if (!flag3)
                            {
                                flag3 = true;
                                writer2.Line("object nullObj = DBNull.Value;");
                            }
                        }
                        else if ((fieldType == typeof(DateTime)) || (fieldType == typeof(TimeSpan)))
                        {
                            writer6.Line(string.Format("IWOA.WritePropertyValue_f28(28, instWbemObjectAccessIP, {0}, 52, SafeAssign.WMITimeToString(instNET.{1}));", str6, info.Name));
                        }
                        else
                        {
                            writer6.Line(string.Format("{0}.Value = instNET.{1};", str5, info.Name));
                        }
                    }
                    else if ((fieldType == typeof(DateTime)) || (fieldType == typeof(TimeSpan)))
                    {
                        writer6.AddChild(string.Format("if(null == instNET.{0})", info.Name)).Line(string.Format("{0}.Value = null;", str5));
                        writer6.AddChild("else").Line(string.Format("{0}.Value = SafeAssign.WMITimeArrayToStringArray(instNET.{1});", str5, info.Name));
                    }
                    else
                    {
                        writer6.Line(string.Format("{0}.Value = instNET.{1};", str5, info.Name));
                    }
                    CimType propertyType = CimType.String;
                    if (info.DeclaringType == type)
                    {
                        bool flag6 = true;
                        try
                        {
                            PropertyData data2 = this.newClass.Properties[memberName];
                            CimType      type1 = data2.Type;
                            if (data2.IsLocal)
                            {
                                throw new ArgumentException(string.Format(RC.GetString("MEMBERCONFLILCT_EXCEPT"), info.Name), info.Name);
                            }
                        }
                        catch (ManagementException exception2)
                        {
                            if (exception2.ErrorCode != ManagementStatus.NotFound)
                            {
                                throw;
                            }
                            flag6 = false;
                        }
                        if (!flag6)
                        {
                            if (str3 != null)
                            {
                                propertyType = CimType.Object;
                            }
                            else if (flag5)
                            {
                                propertyType = CimType.Object;
                            }
                            else if (fieldType == typeof(ManagementObject))
                            {
                                propertyType = CimType.Object;
                            }
                            else if (fieldType == typeof(sbyte))
                            {
                                propertyType = CimType.SInt8;
                            }
                            else if (fieldType == typeof(byte))
                            {
                                propertyType = CimType.UInt8;
                            }
                            else if (fieldType == typeof(short))
                            {
                                propertyType = CimType.SInt16;
                            }
                            else if (fieldType == typeof(ushort))
                            {
                                propertyType = CimType.UInt16;
                            }
                            else if (fieldType == typeof(int))
                            {
                                propertyType = CimType.SInt32;
                            }
                            else if (fieldType == typeof(uint))
                            {
                                propertyType = CimType.UInt32;
                            }
                            else if (fieldType == typeof(long))
                            {
                                propertyType = CimType.SInt64;
                            }
                            else if (fieldType == typeof(ulong))
                            {
                                propertyType = CimType.UInt64;
                            }
                            else if (fieldType == typeof(float))
                            {
                                propertyType = CimType.Real32;
                            }
                            else if (fieldType == typeof(double))
                            {
                                propertyType = CimType.Real64;
                            }
                            else if (fieldType == typeof(bool))
                            {
                                propertyType = CimType.Boolean;
                            }
                            else if (fieldType == typeof(string))
                            {
                                propertyType = CimType.String;
                            }
                            else if (fieldType == typeof(char))
                            {
                                propertyType = CimType.Char16;
                            }
                            else if (fieldType == typeof(DateTime))
                            {
                                propertyType = CimType.DateTime;
                            }
                            else if (fieldType == typeof(TimeSpan))
                            {
                                propertyType = CimType.DateTime;
                            }
                            else
                            {
                                ThrowUnsupportedMember(info);
                            }
                            try
                            {
                                properties.Add(memberName, propertyType, isArray);
                            }
                            catch (ManagementException exception3)
                            {
                                ThrowUnsupportedMember(info, exception3);
                            }
                            if (fieldType == typeof(TimeSpan))
                            {
                                PropertyData data3 = properties[memberName];
                                data3.Qualifiers.Add("SubType", "interval", false, true, true, true);
                            }
                            if (str3 != null)
                            {
                                PropertyData data4 = properties[memberName];
                                data4.Qualifiers["CIMTYPE"].Value = "object:" + str3;
                            }
                        }
                    }
                }
            }
            writer3.Line("Marshal.Release(wbemObjectAccessIP);");
        }
Beispiel #10
0
        public SchemaMapping(Type type, SchemaNaming naming)
        {
            classType = type;

            string baseClassName = ManagedNameAttribute.GetBaseClassName(type);

            className           = ManagedNameAttribute.GetMemberName(type);
            instrumentationType = InstrumentationClassAttribute.GetAttribute(type).InstrumentationType;

            classPath = naming.NamespaceName + ":" + className;

            if (null == baseClassName)
            {
                newClass = new ManagementClass(naming.NamespaceName, "", null);
                newClass.SystemProperties ["__CLASS"].Value = className;
            }
            else
            {
                ManagementClass baseClass = new ManagementClass(naming.NamespaceName + ":" + baseClassName);
                newClass = baseClass.Derive(className);
            }

            PropertyDataCollection props = newClass.Properties;

            // type specific info
            switch (instrumentationType)
            {
            case InstrumentationType.Event:
                break;

            case InstrumentationType.Instance:
                props.Add("ProcessId", CimType.String, false);
                props.Add("InstanceId", CimType.String, false);
                props["ProcessId"].Qualifiers.Add("key", true);
                props["InstanceId"].Qualifiers.Add("key", true);
                newClass.Qualifiers.Add("dynamic", true, false, false, false, true);
                newClass.Qualifiers.Add("provider", naming.DecoupledProviderInstanceName, false, false, false, true);
                break;

            case InstrumentationType.Abstract:
                newClass.Qualifiers.Add("abstract", true, false, false, false, true);
                break;

            default:
                break;
            }

            foreach (MemberInfo field in type.GetFields())
            {
                if (!(field is FieldInfo || field is PropertyInfo))
                {
                    continue;
                }

                if (field.DeclaringType != type)
                {
                    continue;
                }

                if (field.GetCustomAttributes(typeof(IgnoreMemberAttribute), false).Length > 0)
                {
                    continue;
                }

                String propName = ManagedNameAttribute.GetMemberName(field);


#if REQUIRES_EXPLICIT_DECLARATION_OF_INHERITED_PROPERTIES
                if (InheritedPropertyAttribute.GetAttribute(field) != null)
                {
                    continue;
                }
#else
                // See if this field already exists on the WMI class
                // In other words, is it inherited from a base class
                // TODO: Make this more efficient
                //  - If we have a null base class name, all property names
                //    should be new
                //  - We could get all base class property names into a
                //    hashtable, and look them up from there
                bool propertyExists = true;
                try
                {
                    PropertyData prop = newClass.Properties[propName];
                }
                catch (ManagementException e)
                {
                    if (e.ErrorCode != ManagementStatus.NotFound)
                    {
                        throw e;
                    }
                    else
                    {
                        propertyExists = false;
                    }
                }
                if (propertyExists)
                {
                    continue;
                }
#endif

#if SUPPORTS_ALTERNATE_WMI_PROPERTY_TYPE
                Type t2 = ManagedTypeAttribute.GetManagedType(field);
#else
                Type t2;
                if (field is FieldInfo)
                {
                    t2 = (field as FieldInfo).FieldType;
                }
                else
                {
                    t2 = (field as PropertyInfo).PropertyType;
                }
#endif

                CimType cimtype = CimType.String;

                if (t2 == typeof(SByte))
                {
                    cimtype = CimType.SInt8;
                }
                else if (t2 == typeof(Byte))
                {
                    cimtype = CimType.UInt8;
                }
                else if (t2 == typeof(Int16))
                {
                    cimtype = CimType.SInt16;
                }
                else if (t2 == typeof(UInt16))
                {
                    cimtype = CimType.UInt16;
                }
                else if (t2 == typeof(Int32))
                {
                    cimtype = CimType.SInt32;
                }
                else if (t2 == typeof(UInt32))
                {
                    cimtype = CimType.UInt32;
                }
                else if (t2 == typeof(Int64))
                {
                    cimtype = CimType.SInt64;
                }
                else if (t2 == typeof(UInt64))
                {
                    cimtype = CimType.UInt64;
                }
                else if (t2 == typeof(Single))
                {
                    cimtype = CimType.Real32;
                }
                else if (t2 == typeof(Double))
                {
                    cimtype = CimType.Real64;
                }
                else if (t2 == typeof(Boolean))
                {
                    cimtype = CimType.Boolean;
                }
                else if (t2 == typeof(String))
                {
                    cimtype = CimType.String;
                }
                else if (t2 == typeof(Char))
                {
                    cimtype = CimType.Char16;
                }
                else if (t2 == typeof(DateTime))
                {
                    cimtype = CimType.DateTime;
                }
                else if (t2 == typeof(TimeSpan))
                {
                    cimtype = CimType.DateTime;
                }
                else
                {
                    throw new Exception(String.Format("Unsupported type for event member - {0}", t2.Name));
                }
// HACK: The following line cause a strange System.InvalidProgramException when run through InstallUtil
//				throw new Exception("Unsupported type for event member - " + t2.Name);


//              TODO: if(t2 == typeof(Decimal))

#if SUPPORTS_WMI_DEFAULT_VAULES
                Object defaultValue = ManagedDefaultValueAttribute.GetManagedDefaultValue(field);

                // TODO: Is it safe to make this one line?
                if (null == defaultValue)
                {
                    props.Add(propName, cimtype, false);
                }
                else
                {
                    props.Add(propName, defaultValue, cimtype);
                }
#else
                props.Add(propName, cimtype, false);
#endif

                // Must at 'interval' SubType on TimeSpans
                if (t2 == typeof(TimeSpan))
                {
                    PropertyData prop = props[propName];
                    prop.Qualifiers.Add("SubType", "interval", false, true, true, true);
                }
            }
        }