public IContent Mock(Guid id) { var content = Substitute.For<IContent>(); var propertyDataCollection = new PropertyDataCollection(); content.Property.Returns(propertyDataCollection); foreach (var pair in properties) { var property = Substitute.For<PropertyData>(); property.Name = pair.Key; property.Value.Returns(pair.Value); propertyDataCollection.Add(property); } content.ContentGuid.Returns(id); return content; }
static void BuildDotNetCoreProcessList(string processName) { try { SelectQuery query = new SelectQuery(@"SELECT * FROM Win32_Process where Name = '" + processName + "'"); using (ManagementObjectSearcher getQueryResults = new ManagementObjectSearcher(query)) { //execute the query ManagementObjectCollection processes = getQueryResults.Get(); if (processes.Count > 0) { foreach (ManagementObject process in processes) { process.Get(); PropertyDataCollection processProperties = process.Properties; ProcessDetails pd = new ProcessDetails { processName = processName, processId = Convert.ToInt32(processProperties["ProcessID"].Value), parentProcessId = Convert.ToInt32(processProperties["ParentProcessID"].Value) }; Process procToGetBitness = Process.GetProcessById(pd.processId); string userDomain = procToGetBitness.StartInfo.EnvironmentVariables["USERDOMAIN"]; string userName = procToGetBitness.StartInfo.EnvironmentVariables["USERNAME"]; string fullUserName = userDomain + "\\" + userName; pd.fullUserName = fullUserName; string procArc; try { if (CheckProcessBitness(procToGetBitness)) { procArc = "x86"; } else { procArc = "AMD64"; } } catch (Exception) { procArc = "Unknown"; } pd.processorArchitecture = procArc; try { string appPoolName = AppPoolProcessList[pd.parentProcessId]; pd.appPoolName = appPoolName; ProcessList.Add(pd); } catch (Exception) { // } } } } } catch (Exception ex) { Console.WriteLine("Error occured while executing the query: {0}", ex.Message); } }
public override object SaveData(PropertyDataCollection properties) { return(LongString); }
static void Main(string[] args) { while (true) { bool valid; int input; do { valid = true; Console.Write("1) Disk Data \n2) Object Management List \n3) Head Layer \n4) Boot Device \n5) List of all services \n6) Exit program \nInput:"); if (!int.TryParse(Console.ReadLine(), out input) || input < 1 || input > 6) { Console.WriteLine("Invalid input"); Console.ReadKey(); Console.Clear(); valid = false; } } while (valid == false); Console.Clear(); switch (input) { case 1: foreach (ManagementObject managementObject in ObjectManager.DiskMetadata()) { Console.WriteLine("Disk Name : " + managementObject["Name"].ToString()); Console.WriteLine("FreeSpace: " + managementObject["FreeSpace"].ToString()); Console.WriteLine("Disk Size: " + managementObject["Size"].ToString()); Console.WriteLine("---------------------------------------------------"); } Console.Write("Hard disk serial: " + ObjectManager.HardDiskSerialNumber()); break; case 2: foreach (ManagementObject obj in ObjectManager.ManagementObjectsList().Get()) { var usage = obj["PercentProcessorTime"]; var name = obj["Name"]; Console.WriteLine("CPU"); Console.WriteLine(name + " : " + usage + "\n"); } break; case 3: foreach (ManagementObject result in ObjectManager.HeadLayer()) { Console.WriteLine("Total Visible Memory: {0}KB", result["TotalVisibleMemorySize"]); Console.WriteLine("Free Physical Memory: {0}KB", result["FreePhysicalMemory"]); Console.WriteLine("Total Virtual Memory: {0}KB", result["TotalVirtualMemorySize"]); Console.WriteLine("Free Virtual Memory: {0}KB", result["FreeVirtualMemory"]); } foreach (ManagementObject result in ObjectManager.ObjectQueryList()) { Console.WriteLine("User:\t{0}", result["RegisteredUser"]); Console.WriteLine("Org.:\t{0}", result["Organization"]); Console.WriteLine("O/S :\t{0}", result["Name"]); } break; case 4: //enumerate the collection. foreach (ManagementObject m in ObjectManager.MOCBootDevice()) { // access properties of the WMI object Console.WriteLine("BootDevice : {0}", m["BootDevice"]); } break; case 5: Console.WriteLine("process søgning"); ManagementObjectCollection objectCollection = ObjectManager.LISTAllServices(); Console.WriteLine("There are {0} Windows services: ", objectCollection.Count); foreach (ManagementObject windowsService in objectCollection) { PropertyDataCollection serviceProperties = windowsService.Properties; foreach (PropertyData serviceProperty in serviceProperties) { if (serviceProperty.Value != null) { Console.WriteLine("Windows service property name: {0}", serviceProperty.Name); Console.WriteLine("Windows service property value: {0}", serviceProperty.Value); } } Console.WriteLine("---------------------------------------"); } break; case 6: Environment.Exit(0); break; default: Console.WriteLine("Something went wrong"); break; } Console.WriteLine("\n\nPress any key to go back..."); Console.ReadKey(); Console.Clear(); } } //S**t main
static void Main(string[] args) { Console.SetWindowSize(Console.LargestWindowWidth - 5, Console.LargestWindowHeight - 1); PropertyDataCollection properties = null; System.Management.ManagementObjectSearcher mox = null; System.Management.ManagementObjectCollection mok = null; int repeatTimes = 0; try { //define scope (namespace) System.Management.ManagementScope x = new System.Management.ManagementScope("root\\WMI"); //define query System.Management.SelectQuery q = new System.Management.SelectQuery("WMIACPI_IO"); //output current brightness mox = new System.Management.ManagementObjectSearcher(x, q); mok = mox.Get(); while (true) { using (ManagementObjectCollection.ManagementObjectEnumerator enumerator = mox.Get().GetEnumerator()) { if (enumerator.MoveNext()) { ManagementObject managementObject = (ManagementObject)enumerator.Current; ConsoleKeyInfo ckey = Console.ReadKey(); if (ckey.Key == ConsoleKey.C) { break; } if (ckey.Key == ConsoleKey.F) { managementObject.SetPropertyValue("Active", false); } else { if (ckey.Key == ConsoleKey.T) { managementObject.SetPropertyValue("Active", true); } else { Console.WriteLine((bool)managementObject["Active"]); } } managementObject.Put(); } } } while (true) { System.Threading.Thread.Sleep(200); mok = mox.Get(); foreach (System.Management.ManagementObject o in mok) { properties = o.Properties; //o.InvokeMethod("WmiSetBrightness", new Object[] { UInt32.MaxValue, targetBrightness }); //note the reversed order - won't work otherwise! break; //only work on the first object } //Console.WriteLine(properties["IOBytes"].Value); PropertyData ioBytes = properties["IOBytes"]; byte[] bytes = ioBytes.Value as byte[]; //bytes[83] = 100; //lastBytes = bytes; //((byte[])ioBytes.Value)[83] = 4; //((byte[])ioBytes.Value)[84] = 100; int place = -1; if (!isTheSame(bytes, out place)) { if (++repeatTimes >= 10) { repeatTimes = 0; Console.Clear(); } string message = "PLACE: " + place + "\r\n" + BitConverter.ToString(bytes); Console.WriteLine(message); } } } catch (Exception ex) { Console.WriteLine(ex.StackTrace); Console.WriteLine(ex.Message); Console.WriteLine(ex.Source); } finally { if (mox != null) { mox.Dispose(); } if (mok != null) { mok.Dispose(); } } }
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 ; "); codeOneLineMembers.Line("IntPtr originalObject = IntPtr.Zero ; "); codeOneLineMembers.Line("bool toWmiCalled = false ; "); // // 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();"); // 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("originalObject = (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);"); // [marioh] Make sure we release the initial instance so that we dont leak codeDTOR.Line("if ( toWmiCalled == true )"); codeDTOR.Line("{"); codeDTOR.Line(" Marshal.Release (originalObject);"); codeDTOR.Line("}"); // 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("toWmiCalled = true ;"); 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('+', '.'))); // // 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)); // } } } 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)) { // // [PS#128409, marioh] CS0206 Compile error occured when instrumentated types contains public properties of type SByte, Int16, and UInt16 // Properties can not be passed as ref and therefore we store the property value in a tmp local variable before calling WritePropertyValue. // codeToWMI.Line(String.Format("{0} instNET_{1} = instNET.{1} ;", t2, field.Name)); 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)) { // // [PS#128409, marioh] CS0206 Compile error occured when instrumentated types contains public properties of type SByte, Int16, and UInt16 // Properties can not be passed as ref and therefore we store the property value in a tmp local variable before calling WritePropertyValue. // codeToWMI.Line(String.Format("{0} instNET_{1} = instNET.{1} ;", t2, field.Name)); 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)) { // 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; // 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 // bool propertyExists = true; try { PropertyData prop = newClass.Properties[propName]; // HACK 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); // #if SUPPORTS_WMI_DEFAULT_VAULES Object defaultValue = ManagedDefaultValueAttribute.GetManagedDefaultValue(field); // 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));"); }
/// <summary> /// Perform collection task specific processing. /// </summary> /// /// <param name="taskId">Database assigned task Id.</param> /// <param name="cleId">Database Id of owning Collection Engine.</param> /// <param name="elementId">Database Id of element being collected.</param> /// <param name="databaseTimestamp">Database relatvie task dispatch timestamp.</param> /// <param name="localTimestamp">Local task dispatch timestamp.</param> /// <param name="attributes">Map of attribute names to Id for attributes being collected.</param> /// <param name="scriptParameters">Collection script specific parameters (name/value pairs).</param> /// <param name="connection">Connection script results (null if this script does not /// require a remote host connection).</param> /// <param name="tftpDispatcher">Dispatcher for TFTP transfer requests.</param> /// <returns>Collection results.</returns> public CollectionScriptResults ExecuteTask(long taskId, long cleId, long elementId, long databaseTimestamp, long localTimestamp, IDictionary <string, string> attributes, IDictionary <string, string> scriptParameters, IDictionary <string, object> connection, string tftpPath, string tftpPath_login, string tftpPath_password, ITftpDispatcher tftpDispatcher) { m_taskId = taskId.ToString(); m_cleId = cleId; m_elementId = elementId; m_databaseTimestamp = databaseTimestamp; m_localTimestamp = localTimestamp; m_attributes = attributes; m_scriptParameters = scriptParameters; m_tftpDispatcher = tftpDispatcher; m_connection = connection; m_executionTimer = Stopwatch.StartNew(); ManagementScope cimvScope = null; ManagementScope defaultScope = null; ManagementScope iisScope = null; ResultCodes resultCode = ResultCodes.RC_SUCCESS; Lib.Logger.TraceEvent(TraceEventType.Start, 0, "Task Id {0}: Collection script MicrosoftIISwebSiteConfigInfoScript.", m_taskId); try { if (null == connection) { resultCode = ResultCodes.RC_NULL_CONNECTION_OBJECT; Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Connection object passed to MicrosoftIISwebSiteConfigInfoScript is null.", m_taskId); } else if (!connection.ContainsKey(@"cimv2")) { resultCode = ResultCodes.RC_NULL_CONNECTION_OBJECT; Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Management scope for CIMV namespace is not present in connection object.", m_taskId); } else if (!connection.ContainsKey(@"default")) { resultCode = ResultCodes.RC_NULL_CONNECTION_OBJECT; Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Management scope for Default namespace is not present in connection object.", m_taskId); } else { cimvScope = connection[@"cimv2"] as ManagementScope; iisScope = connection[@"iis"] as ManagementScope; if (!cimvScope.IsConnected) { resultCode = ResultCodes.RC_WMI_CONNECTION_FAILED; Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Connection to CIMV2 namespace failed", m_taskId); } else if (!iisScope.IsConnected) { resultCode = ResultCodes.RC_WMI_CONNECTION_FAILED; Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Connection to IIS namespace failed", m_taskId); } StringBuilder WebSitesConfig = new StringBuilder(); Lib.Logger.TraceEvent(TraceEventType.Verbose, 0, "Task Id {0}: Attempting to connect to MicrosoftIISV2 namespace", m_taskId); /**** Collect IIS website configuration info ****/ //get IIS setting System.Management.ObjectQuery oQuery = new System.Management.ObjectQuery("SELECT * FROM IISWebServerSetting"); //Execute the query ManagementObjectSearcher oSearcher = new ManagementObjectSearcher(iisScope, oQuery); Lib.Logger.TraceEvent(TraceEventType.Verbose, 0, "Task Id {0}: Query IISWebServerSetting object.", m_taskId); //Get the results ManagementObjectCollection oReturnCollection = oSearcher.Get(); Dictionary <string, string> dic = new Dictionary <string, string>(); Dictionary <string, Dictionary <string, string> > dic1 = new Dictionary <string, Dictionary <string, string> >(); /* * The ServerAutoStart property indicates if the server instance should start automatically when the service is started. * This property is reset automatically when a server instance is stopped or restarted, to maintain state across service restarts. For example, if a server is stopped, the value of this property is set to false so that if the service is stopped and restarted, the server will remain stopped. Likewise, if a server is started, this property is set to true, allowing the server to remain running whenever the service is running. */ foreach (ManagementObject oReturn in oReturnCollection) { Dictionary <string, string> dic0 = new Dictionary <string, string>(); //Servercomment is shown as Description in IIS Manager dic0.Add("ServerComment", oReturn["ServerComment"].ToString()); dic0.Add("ServerAutoStart", oReturn["ServerAutoStart"].ToString()); // ServerBindings[] array of ServerBinding // The ServerBindings property specifies a string that IIS uses to determine which network endpoints are used by the server instance. The string format is IP:Port:Hostname. ManagementBaseObject[] ServerBindings = (ManagementBaseObject[])oReturn["ServerBindings"]; String serverBinding = null; for (int i = 0; i < ServerBindings.Length; i++) { PropertyDataCollection pc = ServerBindings[i].Properties; String ip = null; String port = null; String hostname = null; foreach (PropertyData property in pc) { if (property.Name.Equals("Hostname")) { hostname = (string)property.Value; } if (property.Name.Equals("IP")) { ip = (string)property.Value; } if (property.Name.Equals("Port")) { port = (string)property.Value; } } if (serverBinding == null) { serverBinding = ip + ":" + port + ":" + hostname; } else { serverBinding += "<BDNA,2>" + ip + ":" + port + ":" + hostname; } } //SecureBindings[] array of SecureBinding //The SecureBindings property specifies a string that is used by IIS to determine which secure network endpoints are used by the server instance. The string format is IP: Port. ManagementBaseObject[] SecureBindings = (ManagementBaseObject[])oReturn["SecureBindings"]; String SecureBinding = null; for (int i = 0; i < SecureBindings.Length; i++) { PropertyDataCollection pc = SecureBindings[i].Properties; String ip = null; String port = null; String hostname = null; foreach (PropertyData property in pc) { if (property.Name.Equals("Hostname")) { hostname = (string)property.Value; } if (property.Name.Equals("IP")) { ip = (string)property.Value; } if (property.Name.Equals("Port")) { port = (string)property.Value; } } if (SecureBinding == null) { SecureBinding = ip + ":" + port + ":" + hostname; } else { SecureBinding += "<BDNA,2>" + ip + ":" + port + ":" + hostname; } } dic0.Add("ServerBindings", serverBinding); dic0.Add("SecureBindings", SecureBinding); dic1.Add(oReturn["Name"].ToString(), dic0); dic.Add(oReturn["Name"].ToString(), oReturn["ServerComment"].ToString()); } ///// ##### RR NEW DEBUG Oct18 //// ************** #3 Find IIS Filter information: ***************** System.Management.ObjectQuery filterQuery = new System.Management.ObjectQuery("SELECT * FROM IIsFilterSetting"); //Execute the query ManagementObjectSearcher filter = new ManagementObjectSearcher(iisScope, filterQuery); //Get the results ManagementObjectCollection ReturnFilter = filter.Get(); Dictionary <string, string> dicFilter = new Dictionary <string, string>(); //loop through found info foreach (ManagementObject oReturn in ReturnFilter) { String name = oReturn["Name"].ToString(); String filterPath = oReturn["FilterPath"].ToString(); if (filterPath.Contains("iisWASPlugin_http.dll")) { foreach (String s in dic.Keys) { if (name.StartsWith(s + "/Filters") || name.StartsWith(s + "/filters") || name.StartsWith(s + "/FILTERS")) { dicFilter.Add(s, filterPath); } } } } /***** Find directory Path for web sites *****/ /** comment out following code because on some Windows 2003 server following WQL is not returning all records * /* * System.Management.ObjectQuery pathQuery = new System.Management.ObjectQuery("SELECT Path, name, ScriptMaps FROM IIsWebVirtualDirSetting"); * * //Execute the query * ManagementObjectSearcher path = new ManagementObjectSearcher(Scope, pathQuery); * * Lib.Logger.TraceEvent(TraceEventType.Verbose, * 0, * "Task Id {0}: Query IIsWebVirtualDirSetting object.", * m_taskId); * * //Get the results * ManagementObjectCollection ReturnPath = path.Get(); */ Dictionary <string, string> dicPath = new Dictionary <string, string>(); Dictionary <string, string> dicScriptProcessor = new Dictionary <string, string>(); foreach (String d_key in dic.Keys) { //String sql = "SELECT * FROM IIsWebVirtualDirSetting where name = '" + d_key + "/ROOT'"; String sql = "SELECT Path, name, ScriptMaps FROM IIsWebVirtualDirSetting where name = '" + d_key + "/ROOT'"; System.Management.ObjectQuery pathQuery = new System.Management.ObjectQuery(sql); //Execute the query ManagementObjectSearcher path = new ManagementObjectSearcher(iisScope, pathQuery); Lib.Logger.TraceEvent(TraceEventType.Verbose, 0, "Task Id {0}: Query IIsWebVirtualDirSetting object.", m_taskId); //Get the results ManagementObjectCollection ReturnPath = path.Get(); //loop through found info foreach (ManagementObject oReturn in ReturnPath) { String name = (String)oReturn["name"]; String Path = (String)oReturn["Path"]; //// RR NEW String iisproxyPath_ScriptProcessor = null; ManagementBaseObject[] scriptMaps = (ManagementBaseObject[])oReturn["ScriptMaps"]; for (int i = 0; i < scriptMaps.Length; i++) { PropertyDataCollection pc = scriptMaps[i].Properties; foreach (PropertyData property in pc) { if (property.Name.Equals("ScriptProcessor") && property.Value.ToString().Contains("iisproxy.dll")) { iisproxyPath_ScriptProcessor = (String)property.Value; break; } } } //// RR NEW END foreach (String s in dic.Keys) { if (name.Equals(s + "/ROOT") || name.Equals(s + "/root")) { dicPath.Add(s, Path); dicScriptProcessor.Add(s, iisproxyPath_ScriptProcessor); } } } } foreach (String s in dic1.Keys) { WebSitesConfig.Append("Name=").Append(s).Append("<BDNA,1>"); WebSitesConfig.Append("Desc=").Append(dic1[s]["ServerComment"]).Append("<BDNA,1>"); WebSitesConfig.Append("ServerBindings=").Append(dic1[s]["ServerBindings"]).Append("<BDNA,1>"); WebSitesConfig.Append("SecureBindings=").Append(dic1[s]["SecureBindings"]).Append("<BDNA,1>"); WebSitesConfig.Append("ServerAutoStart=").Append(dic1[s]["ServerAutoStart"]).Append("<BDNA,1>"); if (dicPath.ContainsKey(s)) { WebSitesConfig.Append("Local Path=").Append(dicPath[s]).Append("<BDNA,1>"); } if (dicScriptProcessor.ContainsKey(s)) { WebSitesConfig.Append("iisproxyPath_ScriptProcessor=").Append(dicScriptProcessor[s]).Append("<BDNA,1>"); } if (dicFilter.ContainsKey(s)) { WebSitesConfig.Append("iisWASPlugin_http_dll_Path=").Append(dicFilter[s]).Append("<BDNA,1>"); } WebSitesConfig.Append("<BDNA,>"); } // RR DEBUG ONLY: //Console.WriteLine("\nWebSitesConfigInfo=" + WebSitesConfig); this.BuildDataRow(@"websiteDetail", WebSitesConfig); } } catch (Exception ex) { if (ResultCodes.RC_SUCCESS == resultCode) { Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Unhandled exception in MicrosoftIISwebSiteConfigInfoScript. Elapsed time {1}.\n{2}Result code changed to RC_PROCESSING_EXECEPTION.", m_taskId, m_executionTimer.Elapsed.ToString(), ex.ToString()); resultCode = ResultCodes.RC_PROCESSING_EXCEPTION; } else { Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Unhandled exception in MicrosoftIISwebSiteConfigInfoScript. Elapsed time {1}.\n{2}", m_taskId, m_executionTimer.Elapsed.ToString(), ex.ToString()); } } Lib.Logger.TraceEvent(TraceEventType.Stop, 0, "Task Id {0}: Collection script MicrosoftIISWebSiteConfigScript. Elapsed time {1}. Result code {2}.", m_taskId, m_executionTimer.Elapsed.ToString(), resultCode.ToString()); return(new CollectionScriptResults (resultCode, 0, null, null, null, false, m_dataRow.ToString())); }
public static void HWInfo() { //Code from Daniel T. Holtzclaw's "DeviceRegister" application. string save_to = ""; save_to = Path.Combine(Application.StartupPath) + "//HWinfo.txt"; if (File.Exists(save_to)) { File.Delete(save_to); } // Will overwrite. using (FileStream fs = File.Open(save_to, FileMode.Create)) { StreamWriter write_stream = new StreamWriter(fs); //Logical Disks = "Win32_LogicalDisk" //Processes = "Win32_Process" //Processors = "Win32_Processor" //Graphics = "Win32_DisplayConfiguration" //??? = "Win32_Account" //??? = "Win32_AllocatedResource" //??? = "Win32_BootConfiguration" //??? = "Win32_ClassCOMApplicationClasses" //CONSULT: https://msdn.microsoft.com/en-us/library/dn792258%28v=vs.85%29.aspx //Logical Disks //CPU's ManagementObjectCollection cpu_collection = new ManagementClass(new ManagementPath("Win32_Processor")).GetInstances(); //Graphics ManagementObjectCollection gpu_collection = new ManagementClass(new ManagementPath("Win32_DisplayConfiguration")).GetInstances(); //Graphics take two ManagementObjectCollection gpu_controller = new ManagementClass(new ManagementPath("Win32_VideoController")).GetInstances(); int count = 0; write_stream.WriteLine("\n\n\nPROCESS-----------------------------------------"); count = 0; foreach (ManagementObject obj in cpu_collection) { PropertyDataCollection prop_collection = obj.Properties; write_stream.WriteLine("Processor: " + count++); foreach (PropertyData data in prop_collection) { if (data != null) { //if (data.Value != null) // { //if (!String.IsNullOrEmpty(data.Value.ToString())) write_stream.WriteLine(" " + data.Name + ": " + data.Value); //} } } write_stream.WriteLine(); } write_stream.WriteLine("\n\n\nGRAPHICS-----------------------------------------"); count = 0; foreach (ManagementObject obj in gpu_collection) { PropertyDataCollection prop_collection = obj.Properties; write_stream.WriteLine("GPU: " + count++); foreach (PropertyData data in prop_collection) { if (data != null) { //if (data.Value != null) //{ //if (!String.IsNullOrEmpty(data.Value.ToString())) write_stream.WriteLine(" " + data.Name + ": " + data.Value); //} } } write_stream.WriteLine(); } write_stream.WriteLine("\n\n\nGRAPHICS Controller----------------------------------"); count = 0; foreach (ManagementObject obj in gpu_controller) { PropertyDataCollection prop_collection = obj.Properties; write_stream.WriteLine("GPU: " + count++); foreach (PropertyData data in prop_collection) { if (data != null) { //if (data.Value != null) //{ //if (!String.IsNullOrEmpty(data.Value.ToString())) write_stream.WriteLine(" " + data.Name + ": " + data.Value); //} } } write_stream.WriteLine(); } write_stream.Close(); cpu_collection.Dispose(); gpu_collection.Dispose(); } }
public override object SaveData(PropertyDataCollection properties) { //return a string object so that EPi can save it to database return LongString; }
private void GetComputerInfo_NoNulls(string WMIClass) { ManagementClass mc = new ManagementClass(WMIClass); ManagementObjectCollection MOC = mc.GetInstances(); int count = 0; //MOC has a chance of success in assignment but failure on Count call. try { count = MOC.Count; } catch { count = -1; } if (count > 0) { foreach (ManagementObject MO in MOC) { List <string> ComputerInfo = new List <string>(); ComputerInfo.Add(WMIClass); PropertyDataCollection pdlist = MO.Properties; foreach (PropertyData pd in pdlist) { string temp = ""; if (pd.Value is string[]) { string[] strArray = ((string[])pd.Value); temp = pd.Name + ": "; for (int i = 0; i < strArray.Length && i < int.MaxValue; i++) { ComputerInfo.Add(temp + strArray[i]); } } else { if (pd.Name.Contains("VariableValue")) { temp = pd.Name + ": "; if (pd.Value != null) { string[] splitString = pd.Value.ToString().Split(';'); foreach (string split in splitString) { ComputerInfo.Add(temp + split); } } } else if ((pd.Name.Contains("GroupComponent") || (pd.Name.Contains("PartComponent")))) { temp = pd.Name + ": "; if (pd.Value != null) { ComputerInfo.Add(temp + pd.Value); string[] splitString = pd.Value.ToString().Split(','); if (splitString.Count() > 1) { for (int i = 0; i < splitString.Length && i < int.MaxValue; i++) { if (i != 0) { ComputerInfo.Add(temp + splitString[i]); } } } else { splitString = pd.Value.ToString().Split(':'); for (int i = 0; i < splitString.Length && i < int.MaxValue; i++) { if (i != 0) { ComputerInfo.Add("Win32 Relationship: " + splitString[i]); } } } } } else if ((pd.Name.Contains("SameElement")) || (pd.Name.Contains("SystemElement"))) { temp = pd.Name + ": "; if (pd.Value != null) { ComputerInfo.Add(temp + pd.Value); string[] splitString = pd.Value.ToString().Split(':'); ComputerInfo.Add("Root: " + splitString[0]); splitString = pd.Value.ToString().Split(':'); for (int i = 0; i < splitString.Length && i < int.MaxValue; i++) { if (i != 0) { ComputerInfo.Add("Win32 Relationship: " + splitString[i]); string deviceid = (splitString[i].Split('.'))[1]; deviceid = deviceid.Replace("DeviceID=", ""); ComputerInfo.Add("Device: " + deviceid); } } } } else { temp = pd.Name + ": "; if (pd.Value != null) { temp += pd.Value.ToString(); ComputerInfo.Add(temp); } } } } DataLists.Add(ComputerInfo); } } }
/// <summary> /// Update properties table /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private async void UpdateProperties(object sender, EventArgs e) { if (listBox.SelectedItem == null) { MessageBox.Show(@"No class select", WmiBrowserMain.Name, MessageBoxButtons.OK, MessageBoxIcon.Information); return; } try { // revert in finally block Cursor = Cursors.WaitCursor; listBox.Enabled = false; menuFileCancel.Enabled = contextMenuCancel.Enabled = true; NameToDescription.Clear(); listView.Items.Clear(); listView.Groups.Clear(); textBoxPropertyDesc.Text = null; const string qDescription = "Description"; groupBox3.Text = $@"Class properties: {listBox.Text}"; string className = _wmiClassCollection[listBox.Text].Name; _cts = new CancellationTokenSource(); await Task.Run(() => { ManagementClass processClass = new ManagementClass(className) { Options = { UseAmendedQualifiers = true } }; PropertyDataCollection properties = processClass.Properties; ManagementObjectSearcher searcher = new ManagementObjectSearcher($"SELECT * FROM {className}") { Scope = _scope, }; foreach (var o in searcher.Get()) { var mo = (ManagementObject)o; _cts.Token.ThrowIfCancellationRequested(); ListViewGroup moGroup = new ListViewGroup(mo.Path.RelativePath); Invoke(new Action(() => { listView.Groups.Add(moGroup); })); // fill rows foreach (PropertyData p in properties) { _cts.Token.ThrowIfCancellationRequested(); // Property name string pName = p.Name; // Property value string pValue = default(string); string pCimType = CimTypeToString[p.Type]; if (p.IsArray) { // Array pCimType += "[]"; var array = mo[pName] as Array; if (array != null) { foreach (var a in array) { pValue += $"{a}, "; } } else { pValue = $"{mo[pName]}"; } } else { switch (p.Type) { // Not array case CimType.None: break; case CimType.DateTime: // convert DateTime to handy format string value = mo[pName]?.ToString(); if (false == string.IsNullOrEmpty(value)) { pValue = ManagementDateTimeConverter.ToDateTime(value).ToString(CultureInfo.CurrentCulture); } break; default: pValue = $"{mo[pName]}"; break; } } // Property description foreach (QualifierData q in p.Qualifiers) { _cts.Token.ThrowIfCancellationRequested(); if (q.Name.Equals(qDescription)) { string pDescription = processClass.GetPropertyQualifierValue(pName, qDescription)?.ToString(); NameToDescription[pName] = pDescription?.Replace("\n", Nl); break; } } ListViewItem pItem = new ListViewItem(new[] { pName, pCimType, pValue }) { Group = moGroup }; if ((listView.Items.Count & 1) == 1) { pItem.BackColor = System.Drawing.Color.LightGray; } Invoke(new Action(() => { listView.Items.Add(pItem); })); } } }, _cts.Token); } catch (OperationCanceledException ex) { MessageBox.Show(ex.Message, WmiBrowserMain.Name, MessageBoxButtons.OK, MessageBoxIcon.Information); } finally { menuFileCancel.Enabled = contextMenuCancel.Enabled = false; listBox.Enabled = true; Cursor = Cursors.Default; } }
public BoostingData() { Property = new PropertyDataCollection(); }
private void CopyProperties(IContentData content, PropertyDataCollection properties) { foreach (var property in properties) { // continue if the property isn't languagespecific or a metadata property if (!content.Property[property.Name].IsLanguageSpecific || content.Property[property.Name].IsMetaData) { continue; } // if it is a block, recursively copy the property values if (property.Value is IContentData) { CopyProperties(content.Property[property.Name].Value as IContentData, (property.Value as IContentData).Property); } else { // copy the property value content.Property[property.Name].Value = property.Value; } } }
public override object SaveData(PropertyDataCollection properties) { return(JsonConvert.SerializeObject(Value, _serializerSettings)); }
static void Main(string[] args) { // Display help information if (args.Length > 0) { if (args[0] == "/?") { Console.WriteLine(); Console.WriteLine(); Console.WriteLine("The correct usage of this sample is \"EnumRL.exe [RLName]\""); Console.WriteLine("Where [RLname] is the name of a particular receive location to enumerate."); Console.WriteLine("If receive location name contains spaces make sure to put it in quotes"); Console.WriteLine(); Console.WriteLine("Example #1 Enumerate all the receive locations."); Console.WriteLine(" EnumRL"); Console.WriteLine(); Console.WriteLine("Example#2 enumerate just the \"My Receive Location #3\" receive location."); Console.WriteLine(" EnumRL \"My Receive Location #3\" "); Console.WriteLine(); Console.WriteLine(); Console.WriteLine("To get help use enumRL.exe /?"); return; } } try { //Create the WMI search object. ManagementObjectSearcher Searcher = new ManagementObjectSearcher(); // create the scope node so we can set the WMI root node correctly. ManagementScope Scope = new ManagementScope("root\\MicrosoftBizTalkServer"); Searcher.Scope = Scope; // Build a Query to enumerate the MSBTS_ReceiveLocation instances if an argument // is supplied use it to select only the matching RL. SelectQuery Query = new SelectQuery(); if (args.Length == 0) { Query.QueryString = "SELECT * FROM MSBTS_ReceiveLocation"; } else { Query.QueryString = "SELECT * FROM MSBTS_ReceiveLocation WHERE Name = '" + args[0] + "'"; } // Set the query for the searcher. Searcher.Query = Query; // Execute the query and determine if any results were obtained. ManagementObjectCollection QueryCol = Searcher.Get(); // Use a bool to tell if we enter the for loop // below because Count property is not supported bool ReceiveLocationFound = false; // Enumerate all properties. foreach (ManagementBaseObject envVar in QueryCol) { // There is at least one Receive Location ReceiveLocationFound = true; Console.WriteLine("**************************************************"); Console.WriteLine("Receive Location: {0}", envVar["Name"]); Console.WriteLine("**************************************************"); PropertyDataCollection envVarProperties = envVar.Properties; Console.WriteLine("Output in the form of: Property: {Value}"); foreach (PropertyData envVarProperty in envVarProperties) { Console.WriteLine(envVarProperty.Name + ":\t" + envVarProperty.Value); } } if (!ReceiveLocationFound) { Console.WriteLine("No receive locations found matching the specified name."); } } catch (Exception excep) { Console.WriteLine(excep.ToString()); } Console.WriteLine("\r\n\r\nPress Enter to continue..."); Console.Read(); }
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);"); }
public TestClassD() { Property = new PropertyDataCollection(); }
static void Main(string[] args) { ManagementScope scope = new ManagementScope("\\\\.\\ROOT\\Microsoft\\Windows\\Storage"); ObjectQuery query = new ObjectQuery("SELECT * FROM MSFT_Volume"); ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query); ManagementObjectCollection queryCollection = searcher.Get(); foreach (ManagementObject m in queryCollection) { try { ManagementBaseObject inParams = m.GetMethodParameters("Optimize"); //PropertyDataCollection systemPropertyData = inParams.SystemProperties; //foreach(PropertyData data in systemPropertyData) //{ // Console.WriteLine("{0}: {1}", data.Name, data.Value); //} //PropertyDataCollection propertyData = inParams.Properties; //foreach (PropertyData data in propertyData) //{ // Console.WriteLine("{0}: {1}", data.Name, data.Value); //} PropertyDataCollection properties = inParams.Properties; List <string> propertyNames = new List <string>(); foreach (PropertyData property in properties) { propertyNames.Add(property.Name); } if (propertyNames.Contains("ReTrim")) { Console.WriteLine("Optimize contains retrim"); inParams.SetPropertyValue("ReTrim", true); ManagementBaseObject outParams = m.InvokeMethod("Optimize", inParams, null); Console.WriteLine("ReturnValue: {0}", outParams["ReturnValue"]); if (Convert.ToInt32(outParams["ReturnValue"]) == 0) { Console.WriteLine("Trimming of drive {0} complete", m["DriveLetter"]); } else { PropertyDataCollection outParamsProperties = outParams.Properties; foreach (PropertyData property in outParamsProperties) { if (property.Name.Equals("ExtendedStatus")) { Console.WriteLine("---Extended status---"); ManagementBaseObject extendedStatus = (ManagementBaseObject)property.Value; PropertyDataCollection systemPropertyData = extendedStatus.Properties; foreach (PropertyData data in systemPropertyData) { Console.WriteLine("{0}: {1}", data.Name, data.Value); } } } Console.WriteLine("Can't perform trim on this. FileSystemLabel: {0}", m["FileSystemLabel"]); Console.WriteLine("Trimming of drive: {0} unsuccessful", m["DriveLetter"]); } } else { Console.WriteLine("ReTrim property does not exist"); } } catch (Exception ex) { Console.WriteLine("Can't trim this.{0}", ex); } Console.WriteLine(); } Console.ReadKey(); }
private AdapterEntity SwitchInterfaceProperties(PropertyDataCollection networkAdapterProperties) { AdapterEntity adapterEntity = new AdapterEntity(); foreach (PropertyData networkAdapterProperty in networkAdapterProperties) { switch (networkAdapterProperty.Name) { case "IPAddress": foreach (string ipAddress in (string[])networkAdapterProperty.Value) { adapterEntity.IpAddress = ipAddress; break; } break; case "IPSubnet": foreach (string netMask in (string[])networkAdapterProperty.Value) { adapterEntity.NetMask = netMask; break; } break; case "DefaultIPGateway": if ((string[])networkAdapterProperty.Value != null) { foreach (string defaultIPGateway in (string[])networkAdapterProperty.Value) { adapterEntity.DefaultIpGateway = defaultIPGateway; break; } } else { adapterEntity.DefaultIpGateway = ""; } break; case "SettingID": adapterEntity.UUID = (string)networkAdapterProperty.Value; break; case "DHCPEnabled": if (networkAdapterProperty.Value != null) { adapterEntity.IsDhcpEnabled = (bool)networkAdapterProperty.Value; } else { adapterEntity.IsDhcpEnabled = false; } break; case "DNSServerSearchOrder": if ((string[])networkAdapterProperty.Value != null) { adapterEntity.DNS = (string[])networkAdapterProperty.Value; } else { adapterEntity.DNS = new string[] { "", "" } }; break; default: break; } } return(adapterEntity); }
public override object SaveData(PropertyDataCollection properties) { return(this.SerializeValue(this._value)); }
public override object SaveData(PropertyDataCollection properties) { //Use PropertyXhtmlString to save the string value and do link mapping this.LongString = ConvertImageCollectionToXhtml(this._value); return base.SaveData(properties); }
/// <summary> /// Returns the localised text name of the BUILTIN\Users group. This varies by locale so has to be derived on the users system. /// </summary> /// <returns>Localised name of the BUILTIN\Users group</returns> /// <remarks>This uses the WMI features and is pretty obscure - sorry, it was the only way I could find to do this! Peter</remarks> protected static string GetBuiltInGroup(string DomainSID, string GroupSID) { ManagementObjectSearcher Searcher = default(ManagementObjectSearcher); string Group = "Unknown"; // Initialise to some values string Name = "Unknown"; PropertyDataCollection p = default(PropertyDataCollection); //LogMessage("", "Start: " + DomainSID + " " + GroupSID); try { //Searcher = new ManagementObjectSearcher(new ManagementScope("\\\\localhost\\root\\cimv2"), new WqlObjectQuery("Select * From Win32_Account "), null); Searcher = new ManagementObjectSearcher(new ManagementScope("\\\\localhost\\root\\cimv2"), new WqlObjectQuery("Select * From Win32_Account Where SID = '" + DomainSID + "'"), null); //new WqlObjectQuery("Select * From Win32_Account Where SID = 'S-1-5-32'"), null); //new WqlObjectQuery("Select * From Win32_Account"), null); //LogMessage("GetBuiltInGroup", "Found " + Searcher.Get().Count + " entries"); int count = 0; foreach (ManagementBaseObject wmiClass in Searcher.Get()) { count += 1; p = wmiClass.Properties; foreach (PropertyData pr in p) { if (pr.Name == "Name") { Group = pr.Value.ToString(); //LogMessage("GetBuiltInGroup Name " + count, pr.Name + " = " + pr.Value.ToString()); } } } Searcher.Dispose(); } catch (Exception ex) { LogMessage("GetBuiltInUsers 1", ex.ToString()); } try { Searcher = new ManagementObjectSearcher(new ManagementScope("\\\\localhost\\root\\cimv2"), new WqlObjectQuery("Select * From Win32_Group Where SID = '" + GroupSID + "'"), null); foreach (ManagementBaseObject wmiClass in Searcher.Get()) { p = wmiClass.Properties; foreach (PropertyData pr in p) { if (pr.Name == "Name") { Name = pr.Value.ToString(); } } } Searcher.Dispose(); } catch (Exception ex) { LogMessage("GetBuiltInUsers 2", ex.ToString()); } // LogMessage("GetBuiltInUsers", "Returning: " + Group + "\\" + Name); return(Group + "\\" + Name); }
public override object SaveData(PropertyDataCollection properties) { return(SerializationHelper.SerializeObject(Value)); }
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); } } }
public DataTable GetSchemaTable() { PropertyDataCollection properties = null; if (_firstObject == null) { var moveNext = _enumerator.MoveNext(); _firstRead = true; if (moveNext) { _firstObject = _enumerator.Current; properties = _firstObject.Properties; } else { var query = _command.CommandText; var index = 0; var fromFound = false; string className = null; while (true) { var wordStart = QueryTextBox.NextWordStart(query, index); var wordEnd = QueryTextBox.WordEnd(query, wordStart); var word = query.Substring(wordStart, wordEnd - wordStart + 1); if (fromFound) { className = word; break; } else { if (word.ToLower() == "from") { fromFound = true; } index = wordEnd + 1; } } query = $"SELECT * FROM meta_class WHERE __this ISA '{className}'"; var objectQuery = new ObjectQuery(query); var searcher = new ManagementObjectSearcher(_command.Connection.Scope, objectQuery); var objects = searcher.Get(); var enumerator2 = objects.GetEnumerator(); enumerator2.MoveNext(); properties = enumerator2.Current.Properties; } } var schemaTable = new DataTable(); schemaTable.Columns.Add("ColumnName", typeof(string)); schemaTable.Columns.Add("ColumnSize", typeof(int)); schemaTable.Columns.Add("DataType", typeof(Type)); schemaTable.Columns.Add("ProviderType", typeof(int)); schemaTable.Columns.Add("ProviderTypeStr", typeof(string)); schemaTable.Columns.Add("NumericPrecision", typeof(int)); schemaTable.Columns.Add("NumericScale", typeof(int)); schemaTable.Columns.Add("IsArray", typeof(bool)); var values = new object[8]; foreach (var propertyData in properties) { var cimType = propertyData.Type; Type dataType; int size; switch (cimType) { case CimType.Boolean: dataType = typeof(bool); size = 1; break; case CimType.DateTime: dataType = typeof(DateTime); size = 8; break; case CimType.UInt8: dataType = typeof(byte); size = 1; break; case CimType.UInt16: dataType = typeof(ushort); size = 2; break; case CimType.UInt32: dataType = typeof(uint); size = 4; break; case CimType.UInt64: dataType = typeof(ulong); size = 8; break; case CimType.String: dataType = typeof(string); size = 0; break; default: dataType = typeof(object); size = 0; break; } int providerType; string providerTypeStr; if (propertyData.IsArray) { providerType = (int)cimType | 0x1000; var typeName = dataType.FullName + "[]"; dataType = Type.GetType(typeName); providerTypeStr = cimType.ToString() + "[]"; } else { providerType = (int)cimType; providerTypeStr = cimType.ToString(); } values[0] = propertyData.Name; values[1] = size; values[2] = dataType; values[3] = providerType; values[4] = providerTypeStr; values[7] = propertyData.IsArray; schemaTable.Rows.Add(values); } FieldCount = schemaTable.Rows.Count; return(schemaTable); }
public Partition(Drive ADrive, PropertyDataCollection AProperties) { Index = Int32.Parse(AProperties["Index"].Value.ToString()); _Drive = ADrive; }
public override object SaveData(PropertyDataCollection properties) { return this.SerializeValue(this._value); }
public Drive(PropertyDataCollection AProperties) { Index = Int32.Parse(AProperties["Index"].Value.ToString()); Caption = AProperties["Caption"].Value.ToString(); Signature = AProperties["Signature"].Value.ToString(); }
public override object SaveData(PropertyDataCollection properties) { return LongString; }
private void SetSlideBarStatus(int a, int b) // I just write this in a single function to control instead of using SBarHook. { if (a != 1) { return; } PropertyDataCollection properties = null; System.Management.ManagementObjectSearcher mox = null; System.Management.ManagementObjectCollection mok = null; try { //define scope (namespace) System.Management.ManagementScope x = new System.Management.ManagementScope("root\\WMI"); //define query System.Management.SelectQuery q = new System.Management.SelectQuery("WMIACPI_IO"); //output current brightness mox = new System.Management.ManagementObjectSearcher(x, q); mok = mox.Get(); while (true) { mok = mox.Get(); foreach (System.Management.ManagementObject o in mok) { byte[] curBytes = o.Properties["IOBytes"].Value as byte[]; if (b == 32 || b == 33) { curBytes[84] = (byte)(b % 2); } if (b == 0 || b == 1) { curBytes[83] = (byte)(b % 2); } //curBytes[85] = 1; //curBytes[66] = 4; o.SetPropertyValue("IOBytes", curBytes); o.Put(); break; //only work on the first object } //Console.WriteLine(properties["IOBytes"].Value); PropertyData ioBytes = properties["IOBytes"]; byte[] bytes = ioBytes.Value as byte[]; //bytes[83] = 100; //lastBytes = bytes; //((byte[])ioBytes.Value)[83] = 4; //((byte[])ioBytes.Value)[84] = 100; //int place = -1; //if (!isTheSame(bytes, out place)) //{ // Console.WriteLine("PLACE: " + place); // Console.WriteLine(BitConverter.ToString(bytes)); //} //if (bytes[83] < 3) break; } } catch (Exception ex) { Console.WriteLine(ex.StackTrace); Console.WriteLine(ex.Message); Console.WriteLine(ex.Source); } finally { if (mox != null) { mox.Dispose(); } if (mok != null) { mok.Dispose(); } } }