public static CimInstance CreateRequestGuid()
        {
            Guid guid = System.Guid.NewGuid();

            // Converts a Guid to 2 64 bit variables.
            byte[] guidBytes = guid.ToByteArray();
            UInt64 low       = 0;
            UInt64 high      = 0;

            for (int i = (guidBytes.Length / 2) - 1; i >= 0; i--)
            {
                if (i < 7)
                {
                    low  = low << 8;
                    high = high << 8;
                }
                low  |= guidBytes[i];
                high |= guidBytes[i + 8];
            }

            // Converts the Guid to the MSFT_ServerManagerRequestGuid CIM class
            CimInstance guidInstance = new CimInstance("MSFT_ServerManagerRequestGuid", "root\\Microsoft\\Windows\\ServerManager");

            guidInstance.CimInstanceProperties.Add(CimProperty.Create("HighHalf", high, CimType.UInt64, CimFlags.None));
            guidInstance.CimInstanceProperties.Add(CimProperty.Create("LowHalf", low, CimType.UInt64, CimFlags.None));

            return(guidInstance);
        }
Esempio n. 2
0
        public void TestWhen()
        {
            var currentProcess = Process.GetCurrentProcess();
            var cimInstance    = new CimInstance("Win32_Process", "root/cimv2");

            cimInstance.CimInstanceProperties.Add(CimProperty.Create("ProcessId", currentProcess.Id, CimFlags.None));
            cimInstance.CimInstanceProperties.Add(CimProperty.Create("Name", currentProcess.ProcessName, CimFlags.None));
            cimInstance.CimInstanceProperties.Add(CimProperty.Create("HandleCount", currentProcess.HandleCount, CimFlags.None));
            cimInstance.CimInstanceProperties.Add(CimProperty.Create("WorkingSetSize", currentProcess.WorkingSet64, CimFlags.None));
            cimInstance.CimInstanceProperties.Add(CimProperty.Create("VirtualSize", currentProcess.VirtualMemorySize64, CimFlags.None));

            var properties = new [] { "ProcessId", "Name", "HandleCount", "WorkingSetSize", "VirtualSize" };
            var result     = Format(cimInstance);

            Assert.Equal(7, result.Length);
            var fmt = "{0,-" + properties.Max(prop => prop.Length) + "} : {1}";

            Assert.Equal("", result[0]);
            Assert.Equal(string.Format(fmt, "ProcessId", currentProcess.Id), result[1]);
            Assert.Equal(string.Format(fmt, "Name", currentProcess.ProcessName), result[2]);
            Assert.Equal(string.Format(fmt, "HandleCount", currentProcess.HandleCount), result[3]);
            Assert.Equal(string.Format(fmt, "WorkingSetSize", currentProcess.WorkingSet64), result[4]);
            Assert.Equal(string.Format(fmt, "VirtualSize", currentProcess.VirtualMemorySize64), result[5]);
            Assert.Equal("", result[6]);
        }
        /// <summary>
        /// <para>
        /// Create <see cref="CimInstance"/> with given properties.
        /// </para>
        /// </summary>
        /// <param name="className"></param>
        /// <param name="key"></param>
        /// <param name="properties"></param>
        /// <param name="cmdlet"></param>
        /// <returns></returns>
        /// <exception cref="ArgumentNullException">See CimProperty.Create.</exception>
        /// <exception cref="ArgumentException">CimProperty.Create.</exception>
        private CimInstance CreateCimInstance(
            string className,
            string cimNamespace,
            IEnumerable <string> key,
            IDictionary properties,
            NewCimInstanceCommand cmdlet)
        {
            CimInstance cimInstance = new(className, cimNamespace);

            if (properties == null)
            {
                return(cimInstance);
            }

            List <string> keys = new();

            if (key != null)
            {
                foreach (string keyName in key)
                {
                    keys.Add(keyName);
                }
            }

            IDictionaryEnumerator enumerator = properties.GetEnumerator();

            while (enumerator.MoveNext())
            {
                CimFlags flag         = CimFlags.None;
                string   propertyName = enumerator.Key.ToString().Trim();
                if (keys.Contains(propertyName, StringComparer.OrdinalIgnoreCase))
                {
                    flag = CimFlags.Key;
                }

                object propertyValue = GetBaseObject(enumerator.Value);

                DebugHelper.WriteLog("Create and add new property to ciminstance: name = {0}; value = {1}; flags = {2}", 5, propertyName, propertyValue, flag);

                PSReference cimReference = propertyValue as PSReference;
                if (cimReference != null)
                {
                    CimProperty newProperty = CimProperty.Create(propertyName, GetBaseObject(cimReference.Value), CimType.Reference, flag);
                    cimInstance.CimInstanceProperties.Add(newProperty);
                }
                else
                {
                    CimProperty newProperty = CimProperty.Create(
                        propertyName,
                        propertyValue,
                        flag);
                    cimInstance.CimInstanceProperties.Add(newProperty);
                }
            }

            return(cimInstance);
        }
Esempio n. 4
0
        static void ReadFile(CimSession session, string file)
        {
            // https://twitter.com/mattifestation/status/1220713684756049921
            CimInstance baseInstance = new CimInstance("PS_ModuleFile");

            baseInstance.CimInstanceProperties.Add(CimProperty.Create("InstanceID", file, CimFlags.Key));
            CimInstance modifiedInstance = session.GetInstance("ROOT/Microsoft/Windows/Powershellv3", baseInstance);

            System.Byte[] fileBytes = (byte[])modifiedInstance.CimInstanceProperties["FileData"].Value;
            Console.WriteLine(Encoding.UTF8.GetString(fileBytes, 0, fileBytes.Length));
        }
Esempio n. 5
0
        private CimInstance CreateCimInstance(string className, string cimNamespace, IEnumerable <string> key, IDictionary properties, NewCimInstanceCommand cmdlet)
        {
            CimInstance cimInstance = new CimInstance(className, cimNamespace);

            if (properties != null)
            {
                List <string> strs = new List <string>();
                if (key != null)
                {
                    foreach (string str in key)
                    {
                        strs.Add(str);
                    }
                }
                IDictionaryEnumerator enumerator = properties.GetEnumerator();
                while (enumerator.MoveNext())
                {
                    CimFlags cimFlag = CimFlags.None;
                    string   str1    = enumerator.Key.ToString().Trim();
                    if (strs.Contains <string>(str1, StringComparer.OrdinalIgnoreCase))
                    {
                        cimFlag = CimFlags.Key;
                    }
                    object   baseObject = base.GetBaseObject(enumerator.Value);
                    object[] objArray   = new object[3];
                    objArray[0] = str1;
                    objArray[1] = baseObject;
                    objArray[2] = cimFlag;
                    DebugHelper.WriteLog("Create and add new property to ciminstance: name = {0}; value = {1}; flags = {2}", 5, objArray);
                    PSReference pSReference = baseObject as PSReference;
                    if (pSReference == null)
                    {
                        CimProperty cimProperty = CimProperty.Create(str1, baseObject, cimFlag);
                        cimInstance.CimInstanceProperties.Add(cimProperty);
                    }
                    else
                    {
                        CimProperty cimProperty1 = CimProperty.Create(str1, base.GetBaseObject(pSReference.Value), CimType.Reference, cimFlag);
                        cimInstance.CimInstanceProperties.Add(cimProperty1);
                    }
                }
                return(cimInstance);
            }
            else
            {
                return(cimInstance);
            }
        }
        internal static CimInstance GetInstanceCore(CimSession cimSession, string cimNamespace, string cimClassName)
        {
            CimInstance getInstance = new CimInstance(cimClassName);
            Dictionary <string, object> propertyValues = GetKeyValues(cimSession, cimNamespace, cimClassName);

            if (propertyValues == null || propertyValues.Count == 0)
            {
                return(getInstance);
            }

            foreach (var property in propertyValues)
            {
                getInstance.CimInstanceProperties.Add(CimProperty.Create(property.Key, property.Value, CimFlags.Key));
            }

            return(getInstance);
        }
 internal void ModifyLocalCimInstance(CimInstance cimInstance)
 {
     foreach (MethodParameter methodParameter in this.GetMethodInputParameters())
     {
         CimValueConverter.AssertIntrinsicCimType(methodParameter.ParameterType);
         CimProperty propertyBeingModified = cimInstance.CimInstanceProperties[methodParameter.Name];
         if (propertyBeingModified != null)
         {
             propertyBeingModified.Value = methodParameter.Value;
         }
         else
         {
             CimProperty propertyBeingAdded = CimProperty.Create(
                 methodParameter.Name,
                 methodParameter.Value,
                 CimValueConverter.GetCimTypeEnum(methodParameter.ParameterType),
                 CimFlags.None);
             cimInstance.CimInstanceProperties.Add(propertyBeingAdded);
         }
     }
 }
Esempio n. 8
0
        public static void CreateSnapshot()
        {
            const string hvNamespace = @"root\virtualization\v2";

            var sessionOptions = new DComSessionOptions
            {
                Timeout = TimeSpan.FromSeconds(30)
            };

            var cimSession = CimSession.Create("localhost", sessionOptions);

            // Get an instance of the VM to snapshot
            var vm = cimSession.QueryInstances(hvNamespace, "WQL", $"SELECT * FROM CIM_ComputerSystem WHERE ElementName = 'MyTestVM'").First();

            // Get the instance of Msvm_VirtualSystemSnapshotService. There is only one.
            var vmSnapshotService = cimSession.EnumerateInstances(hvNamespace, "Msvm_VirtualSystemSnapshotService").First();

            // Set the snapshot parameters by creating a Msvm_VirtualSystemSnapshotSettingData
            var snapshotSettings = new CimInstance("Msvm_VirtualSystemSnapshotSettingData");

            snapshotSettings.CimInstanceProperties.Add(CimProperty.Create("ConsistencyLevel", 1, CimType.UInt8, CimFlags.ReadOnly));
            snapshotSettings.CimInstanceProperties.Add(CimProperty.Create("IgnoreNonSnapshottableDisks", true, CimFlags.ReadOnly));

            // Put all of these things into a CimMethodParametersCollection.
            // Note; no need to specify the "Out" parameters. They will be returned by the call to InvokeMethod.
            var methodParameters = new CimMethodParametersCollection
            {
                CimMethodParameter.Create("AffectedSystem", vm, CimType.Reference, CimFlags.In),
                CimMethodParameter.Create("SnapshotSettings", snapshotSettings.ToString(), CimType.String, CimFlags.In),
                CimMethodParameter.Create("SnapshotType", 2, CimType.UInt16, CimFlags.In),
            };

            cimSession.InvokeMethod(hvNamespace, vmSnapshotService, "CreateSnapshot", methodParameters);

            Console.WriteLine($"Snapshot created!");
        }
Esempio n. 9
0
        /// <summary>
        /// <para>
        /// Set the properties value to be modified to the given
        /// <see cref="CimInstance"/>
        /// </para>
        /// </summary>
        /// <param name="properties"></param>
        /// <param name="cimInstance"></param>
        /// <param name="terminationMessage"></param>
        /// <returns></returns>
        private bool SetProperty(IDictionary properties, ref CimInstance cimInstance, ref Exception exception)
        {
            DebugHelper.WriteLogEx();
            if (properties.Count == 0)
            {
                // simply ignore if empty properties was provided
                return(true);
            }
            IDictionaryEnumerator enumerator = properties.GetEnumerator();

            while (enumerator.MoveNext())
            {
                object value = GetBaseObject(enumerator.Value);
                string key   = enumerator.Key.ToString();
                DebugHelper.WriteLog("Input property name '{0}' with value '{1}'", 1, key, value);

                try
                {
                    CimProperty property = cimInstance.CimInstanceProperties[key];
                    // modify existing property value if found
                    if (property != null)
                    {
                        if ((property.Flags & CimFlags.ReadOnly) == CimFlags.ReadOnly)
                        {
                            // can not modify ReadOnly property
                            exception = new CimException(String.Format(CultureInfo.CurrentUICulture,
                                                                       Strings.CouldNotModifyReadonlyProperty, key, cimInstance));
                            return(false);
                        }
                        // allow modify the key property value as long as it is not readonly,
                        // then the modified ciminstance is stand for a different CimInstance
                        DebugHelper.WriteLog("Set property name '{0}' has old value '{1}'", 4, key, property.Value);
                        property.Value = value;
                    }
                    else // For dynamic instance, it is valid to add a new property
                    {
                        CimProperty newProperty;
                        if (value == null)
                        {
                            newProperty = CimProperty.Create(
                                key,
                                value,
                                CimType.String,
                                CimFlags.Property);
                        }
                        else
                        {
                            CimType referenceType   = CimType.Unknown;
                            object  referenceObject = GetReferenceOrReferenceArrayObject(value, ref referenceType);
                            if (referenceObject != null)
                            {
                                newProperty = CimProperty.Create(
                                    key,
                                    referenceObject,
                                    referenceType,
                                    CimFlags.Property);
                            }
                            else
                            {
                                newProperty = CimProperty.Create(
                                    key,
                                    value,
                                    CimFlags.Property);
                            }
                        }
                        try
                        {
                            cimInstance.CimInstanceProperties.Add(newProperty);
                        }
                        catch (CimException e)
                        {
                            if (e.NativeErrorCode == NativeErrorCode.Failed)
                            {
                                string errorMessage = String.Format(CultureInfo.CurrentUICulture,
                                                                    Strings.UnableToAddPropertyToInstance,
                                                                    newProperty.Name,
                                                                    cimInstance);
                                exception = new CimException(errorMessage, e);
                            }
                            else
                            {
                                exception = e;
                            }
                            return(false);
                        }
                        DebugHelper.WriteLog("Add non-key property name '{0}' with value '{1}'.", 3, key, value);
                    }
                }
                catch (Exception e)
                {
                    DebugHelper.WriteLog("Exception {0}", 4, e);
                    exception = e;
                    return(false);
                }
            }
            return(true);
        }
        private void HandleComplexTypePSObject
        (
            object source,
            string property,
            int depth,
            out CimInstance result
        )
        {
            List <CimInstance> listOfCimInstancesProperties = null;

            Dbg.Assert(source != null, "caller should validate the parameter");
            PSObject mshSource = PSObject.AsPSObject(source);

            // Figure out what kind of object we are dealing with
            bool isErrorRecord         = false;
            bool isInformationalRecord = false;
            bool isEnum     = false;
            bool isPSObject = false;

            //TODO, insivara : To be implemented
            //bool isCimInstance = false;

            if (!mshSource.immediateBaseObjectIsEmpty)
            {
                ErrorRecord errorRecord = mshSource.ImmediateBaseObject as ErrorRecord;
                if (errorRecord == null)
                {
                    InformationalRecord informationalRecord = mshSource.ImmediateBaseObject as InformationalRecord;
                    if (informationalRecord == null)
                    {
                        isEnum     = mshSource.ImmediateBaseObject is Enum;
                        isPSObject = mshSource.ImmediateBaseObject is PSObject;
                    }
                    else
                    {
                        informationalRecord.ToPSObjectForRemoting(mshSource);
                        isInformationalRecord = true;
                    }
                }
                else
                {
                    errorRecord.ToPSObjectForRemoting(mshSource);
                    isErrorRecord = true;
                }
            }

            bool writeToString = true;

            if (mshSource.ToStringFromDeserialization == null)
            // continue to write ToString from deserialized objects, but...
            {
                if (mshSource.immediateBaseObjectIsEmpty) // ... don't write ToString for property bags
                {
                    writeToString = false;
                }
            }

            // This will create a CimInstance for PS_Object and populate the typenames.
            result = CreateCimInstanceForPSObject(cimClassName: "PS_Object",
                                                  psObj: mshSource,
                                                  writeToString: writeToString);

            PSMemberInfoInternalCollection <PSPropertyInfo> specificPropertiesToSerialize =
                SerializationUtilities.GetSpecificPropertiesToSerialize(mshSource, AllPropertiesCollection, _typeTable);

            if (isEnum)
            {
                CimInstance enumCimInstance = CreateCimInstanceForEnum(mshSource, depth, property != null);
                CimProperty p = CimProperty.Create("Value", enumCimInstance,
                                                   Microsoft.Management.Infrastructure.CimType.Reference,
                                                   Microsoft.Management.Infrastructure.CimFlags.Property);
                result.CimInstanceProperties.Add(p);
            }
            else if (isPSObject)
            {
                CimInstance psObjectCimInstance;
                CreateCimInstanceForOneObject(mshSource.ImmediateBaseObject, property, depth, out psObjectCimInstance);
                CimProperty valueProperty = CimProperty.Create("Value", psObjectCimInstance,
                                                               Microsoft.Management.Infrastructure.CimType.Reference,
                                                               Microsoft.Management.Infrastructure.CimFlags.Property);
                result.CimInstanceProperties.Add(valueProperty);
            }
            else if (isErrorRecord || isInformationalRecord)
            {
                // nothing to do
            }
            else
            {
                CreateCimInstanceForPSObjectProperties(mshSource, depth, specificPropertiesToSerialize, out listOfCimInstancesProperties);
            }

            //TODO, insivara : Implement serialization of CimInstance
            //if (isCimInstance)
            //{
            //    CimInstance cimInstance = mshSource.ImmediateBaseObject as CimInstance;
            //    PrepareCimInstanceForSerialization(mshSource, cimInstance);
            //}

            //TODO, insivara : ExtendedProperties implementation will be done in a subsequent checkin
            //SerializeExtendedProperties(mshSource, depth, specificPropertiesToSerialize, out listOfCimInstancesExtendedProperties);

            if (listOfCimInstancesProperties != null && listOfCimInstancesProperties.Count > 0)
            {
                CimInstance[] referenceArray = listOfCimInstancesProperties.ToArray();
                CimProperty   properties     = CimProperty.Create("Properties", referenceArray,
                                                                  Microsoft.Management.Infrastructure.CimType.ReferenceArray,
                                                                  Microsoft.Management.Infrastructure.CimFlags.Property);
                result.CimInstanceProperties.Add(properties);
            }
        }
        private bool HandleKnownContainerTypes
        (
            object source,
            string property,
            int depth,
            out CimInstance result
        )
        {
            Dbg.Assert(source != null, "caller should validate the parameter");

            result = CreateNullCimInstance();
            ContainerType ct         = ContainerType.None;
            PSObject      mshSource  = source as PSObject;
            IEnumerable   enumerable = null;
            IDictionary   dictionary = null;

            //If passed in object is PSObject with no baseobject, return false.
            if (mshSource != null && mshSource.immediateBaseObjectIsEmpty)
            {
                return(false);
            }

            //Check if source (or baseobject in mshSource) is known container type
            SerializationUtilities.GetKnownContainerTypeInfo(mshSource != null ? mshSource.ImmediateBaseObject : source, out ct,
                                                             out dictionary, out enumerable);

            if (ct == ContainerType.None)
            {
                return(false);
            }

            result = CreateCimInstanceForPSObject(cimClassName: "PS_Object",
                                                  psObj: mshSource ?? PSObject.AsPSObject(source),
                                                  writeToString: false);

            List <CimInstance> listOfCimInstances = null;

            switch (ct)
            {
            case ContainerType.Dictionary:
                WriteDictionary(dictionary, depth, out listOfCimInstances);
                break;

            case ContainerType.Stack:
                WriteEnumerable(enumerable, property, depth, out listOfCimInstances);
                break;

            case ContainerType.Queue:
                WriteEnumerable(enumerable, property, depth, out listOfCimInstances);
                break;

            case ContainerType.List:
                WriteEnumerable(enumerable, property, depth, out listOfCimInstances);
                break;

            case ContainerType.Enumerable:
                WriteEnumerable(enumerable, property, depth, out listOfCimInstances);
                break;

            default:
                Dbg.Assert(false, "All containers should be handled in the switch");
                break;
            }

            CimInstance[] instanceArray = listOfCimInstances.ToArray();
            CimProperty   valueProperty = CimProperty.Create("Value", instanceArray, Microsoft.Management.Infrastructure.CimType.InstanceArray, CimFlags.Property);

            result.CimInstanceProperties.Add(valueProperty);
            return(true);
        }
Esempio n. 12
0
        private bool SetProperty(IDictionary properties, ref CimInstance cimInstance, ref Exception exception)
        {
            CimProperty cimProperty;
            bool        flag;

            DebugHelper.WriteLogEx();
            if (properties.Count != 0)
            {
                IDictionaryEnumerator enumerator = properties.GetEnumerator();
                while (enumerator.MoveNext())
                {
                    object   baseObject = base.GetBaseObject(enumerator.Value);
                    string   str        = enumerator.Key.ToString();
                    object[] objArray   = new object[2];
                    objArray[0] = str;
                    objArray[1] = baseObject;
                    DebugHelper.WriteLog("Input property name '{0}' with value '{1}'", 1, objArray);
                    try
                    {
                        CimProperty item = cimInstance.CimInstanceProperties[str];
                        if (item == null)
                        {
                            if (baseObject != null)
                            {
                                CimType cimType = CimType.Unknown;
                                object  referenceOrReferenceArrayObject = base.GetReferenceOrReferenceArrayObject(baseObject, ref cimType);
                                if (referenceOrReferenceArrayObject == null)
                                {
                                    cimProperty = CimProperty.Create(str, baseObject, (CimFlags)((long)4));
                                }
                                else
                                {
                                    cimProperty = CimProperty.Create(str, referenceOrReferenceArrayObject, cimType, (CimFlags)((long)4));
                                }
                            }
                            else
                            {
                                cimProperty = CimProperty.Create(str, baseObject, CimType.String, (CimFlags)((long)4));
                            }
                            try
                            {
                                cimInstance.CimInstanceProperties.Add(cimProperty);
                            }
                            catch (CimException cimException1)
                            {
                                CimException cimException = cimException1;
                                if (cimException.NativeErrorCode != NativeErrorCode.Failed)
                                {
                                    exception = cimException;
                                }
                                else
                                {
                                    object[] name = new object[2];
                                    name[0] = cimProperty.Name;
                                    name[1] = cimInstance;
                                    string str1 = string.Format(CultureInfo.CurrentUICulture, Strings.UnableToAddPropertyToInstance, name);
                                    exception = new CimException(str1, cimException);
                                }
                                flag = false;
                                return(flag);
                            }
                            object[] objArray1 = new object[2];
                            objArray1[0] = str;
                            objArray1[1] = baseObject;
                            DebugHelper.WriteLog("Add non-key property name '{0}' with value '{1}'.", 3, objArray1);
                        }
                        else
                        {
                            if ((item.Flags & CimFlags.ReadOnly) != CimFlags.ReadOnly)
                            {
                                object[] value = new object[2];
                                value[0] = str;
                                value[1] = item.Value;
                                DebugHelper.WriteLog("Set property name '{0}' has old value '{1}'", 4, value);
                                item.Value = baseObject;
                            }
                            else
                            {
                                object[] objArray2 = new object[2];
                                objArray2[0] = str;
                                objArray2[1] = cimInstance;
                                exception    = new CimException(string.Format(CultureInfo.CurrentUICulture, Strings.CouldNotModifyReadonlyProperty, objArray2));
                                flag         = false;
                                return(flag);
                            }
                        }
                        continue;
                    }
                    catch (Exception exception2)
                    {
                        Exception exception1 = exception2;
                        object[]  objArray3  = new object[1];
                        objArray3[0] = exception1;
                        DebugHelper.WriteLog("Exception {0}", 4, objArray3);
                        exception = exception1;
                        flag      = false;
                    }
                    return(flag);
                }
                return(true);
            }
            else
            {
                return(true);
            }
        }