/// <summary>
        /// </summary>
        /// <param name="baseObject"></param>
        /// <param name="propertyName"></param>
        /// <returns></returns>
        public override PSAdaptedProperty GetProperty(object baseObject, string propertyName)
        {
            if (propertyName == null)
            {
                throw new PSArgumentNullException("propertyName");
            }

            // baseObject should never be null
            CimInstance cimInstance = baseObject as CimInstance;

            if (cimInstance == null)
            {
                string msg = string.Format(CultureInfo.InvariantCulture,
                                           CimInstanceTypeAdapterResources.BaseObjectNotCimInstance,
                                           "baseObject",
                                           typeof(CimInstance).ToString());
                throw new PSInvalidOperationException(msg);
            }

            CimProperty cimProperty = cimInstance.CimInstanceProperties[propertyName];

            if (cimProperty != null)
            {
                PSAdaptedProperty prop = GetCimPropertyAdapter(cimProperty, baseObject, propertyName);
                return(prop);
            }

            if (propertyName.Equals(RemotingConstants.ComputerNameNoteProperty, StringComparison.OrdinalIgnoreCase))
            {
                PSAdaptedProperty prop = GetPSComputerNameAdapter(cimInstance);
                return(prop);
            }

            return(null);
        }
        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);
        }
示例#3
0
            public bool IsMatch(CimInstance o)
            {
                if (o is null)
                {
                    return(false);
                }

                CimProperty propertyInfo = o.CimInstanceProperties[PropertyName];

                if (propertyInfo is null)
                {
                    return(false);
                }

                object actualPropertyValue = propertyInfo.Value;

                if (CimTypedExpectedPropertyValue is null)
                {
                    HadMatch = HadMatch || (actualPropertyValue is null);
                    return(actualPropertyValue is null);
                }

                CimValueConverter.AssertIntrinsicCimValue(actualPropertyValue);
                CimValueConverter.AssertIntrinsicCimValue(CimTypedExpectedPropertyValue);

                actualPropertyValue = ConvertActualValueToExpectedType(actualPropertyValue, CimTypedExpectedPropertyValue);
                Dbg.Assert(IsSameType(actualPropertyValue, CimTypedExpectedPropertyValue), "Types of actual vs expected property value should always match");

                bool isMatch = this.IsMatchingValue(actualPropertyValue);

                HadMatch = HadMatch || isMatch;
                return(isMatch);
            }
示例#4
0
        /// <summary>
        /// </summary>
        /// <param name="adaptedProperty"></param>
        /// <returns></returns>
        public override bool IsSettable(PSAdaptedProperty adaptedProperty)
        {
            /* I was explicitly asked to only use MI_FLAG_READONLY for now
             * // based on DSP0004, version 2.6.0, section "5.5.3.55 Write" (pages 89-90, lines 3056-3061)
             * bool writeQualifierValue = this.GetPropertyQualifierValue(adaptedProperty, "Write", defaultValue: false);
             * return writeQualifierValue;
             */

            if (adaptedProperty == null)
            {
                return(false);
            }

            CimProperty cimProperty = adaptedProperty.Tag as CimProperty;

            if (cimProperty == null)
            {
                return(false);
            }

            bool isReadOnly = (CimFlags.ReadOnly == (cimProperty.Flags & CimFlags.ReadOnly));
            bool isSettable = !isReadOnly;

            return(isSettable);
        }
示例#5
0
        internal static ErrorCategory ConvertCimErrorToErrorCategory(CimInstance cimError)
        {
            ErrorCategory errorCategory = ErrorCategory.NotSpecified;

            if (cimError != null)
            {
                CimProperty item = cimError.CimInstanceProperties["Error_Category"];
                if (item != null)
                {
                    if (LanguagePrimitives.TryConvertTo <ErrorCategory>(item.Value, CultureInfo.InvariantCulture, out errorCategory))
                    {
                        return(errorCategory);
                    }
                    else
                    {
                        return(ErrorCategory.NotSpecified);
                    }
                }
                else
                {
                    return(ErrorCategory.NotSpecified);
                }
            }
            else
            {
                return(ErrorCategory.NotSpecified);
            }
        }
示例#6
0
        public override void SetPropertyValue(PSAdaptedProperty adaptedProperty, object value)
        {
            if (adaptedProperty == null)
            {
                throw new ArgumentNullException("adaptedProperty");
            }
            if (!this.IsSettable(adaptedProperty))
            {
                throw new SetValueException("ReadOnlyCIMProperty", null, CimInstanceTypeAdapterResources.ReadOnlyCIMProperty, new object[] { adaptedProperty.Name });
            }
            CimProperty tag  = adaptedProperty.Tag as CimProperty;
            object      obj2 = value;

            if (obj2 != null)
            {
                Type    dotNetType;
                CimType cimType = tag.CimType;
                if (cimType == CimType.DateTime)
                {
                    dotNetType = typeof(object);
                }
                else if (cimType == CimType.DateTimeArray)
                {
                    dotNetType = typeof(object[]);
                }
                else
                {
                    dotNetType = CimConverter.GetDotNetType(tag.CimType);
                }
                obj2 = Adapter.PropertySetAndMethodArgumentConvertTo(value, dotNetType, CultureInfo.InvariantCulture);
            }
            tag.Value = obj2;
        }
示例#7
0
 private static PSAdaptedProperty GetCimPropertyAdapter(CimProperty property, object baseObject, string propertyName)
 {
     return(new PSAdaptedProperty(propertyName, property)
     {
         baseObject = baseObject
     });
 }
示例#8
0
        public override string GetPropertyTypeName(PSAdaptedProperty adaptedProperty)
        {
            if (adaptedProperty == null)
            {
                throw new ArgumentNullException("adaptedProperty");
            }
            CimProperty tag = adaptedProperty.Tag as CimProperty;

            if (tag == null)
            {
                if (!adaptedProperty.Name.Equals(RemotingConstants.ComputerNameNoteProperty, StringComparison.OrdinalIgnoreCase))
                {
                    throw new ArgumentNullException("adaptedProperty");
                }
                return(ToStringCodeMethods.Type(typeof(string), false));
            }
            switch (tag.CimType)
            {
            case CimType.DateTime:
            case CimType.Reference:
            case CimType.Instance:
            case CimType.DateTimeArray:
            case CimType.ReferenceArray:
            case CimType.InstanceArray:
                return("CimInstance#" + tag.CimType.ToString());
            }
            return(ToStringCodeMethods.Type(CimConverter.GetDotNetType(tag.CimType), false));
        }
示例#9
0
        internal CimInstance ToCimInstance()
        {
            CimInstance c = InternalMISerializer.CreateCimInstance("PS_Command");
            CimProperty commandTextProperty = InternalMISerializer.CreateCimProperty("CommandText",
                                                                                     this.CommandText,
                                                                                     Microsoft.Management.Infrastructure.CimType.String);

            c.CimInstanceProperties.Add(commandTextProperty);
            CimProperty isScriptProperty = InternalMISerializer.CreateCimProperty("IsScript",
                                                                                  this.IsScript,
                                                                                  Microsoft.Management.Infrastructure.CimType.Boolean);

            c.CimInstanceProperties.Add(isScriptProperty);

            if (this.Parameters != null && this.Parameters.Count > 0)
            {
                List <CimInstance> parameterInstances = new List <CimInstance>();
                foreach (var p in this.Parameters)
                {
                    parameterInstances.Add(p.ToCimInstance());
                }

                if (parameterInstances.Count > 0)
                {
                    CimProperty parametersProperty = InternalMISerializer.CreateCimProperty("Parameters",
                                                                                            parameterInstances.ToArray(),
                                                                                            Microsoft.Management.Infrastructure.CimType.ReferenceArray);
                    c.CimInstanceProperties.Add(parametersProperty);
                }
            }

            return(c);
        }
 internal CimMethodParameterBackedByCimProperty(CimProperty backingProperty,
                                                string cimSessionComputerName,
                                                Guid cimSessionInstanceId)
 {
     Debug.Assert(backingProperty != null, "Caller should verify backingProperty != null");
     this._backingProperty = backingProperty;
     Initialize(cimSessionComputerName, cimSessionInstanceId);
 }
        private static PSAdaptedProperty GetCimPropertyAdapter(CimProperty property, object baseObject, string propertyName)
        {
            PSAdaptedProperty propertyToAdd = new PSAdaptedProperty(propertyName, property);

            propertyToAdd.baseObject = baseObject;
            //propertyToAdd.adapter = this;
            return(propertyToAdd);
        }
        internal static CimInstance CreatePSNegotiationData(Version powerShellVersion)
        {
            CimInstance c = InternalMISerializer.CreateCimInstance("PS_NegotiationData");
            CimProperty versionproperty = InternalMISerializer.CreateCimProperty("PSVersion", powerShellVersion.ToString(), Microsoft.Management.Infrastructure.CimType.String);

            c.CimInstanceProperties.Add(versionproperty);
            return(c);
        }
        /// <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);
        }
示例#14
0
        private static bool IsWsManQuotaReached(Exception exception)
        {
            var cimException = exception as CimException;

            if (cimException == null)
            {
                return(false);
            }

            if (cimException.NativeErrorCode != NativeErrorCode.ServerLimitsExceeded)
            {
                return(false);
            }

            CimInstance cimError = cimException.ErrorData;

            if (cimError == null)
            {
                return(false);
            }

            CimProperty errorCodeProperty = cimError.CimInstanceProperties["error_Code"];

            if (errorCodeProperty == null)
            {
                return(false);
            }

            if (errorCodeProperty.CimType != CimType.UInt32)
            {
                return(false);
            }

            WsManErrorCode wsManErrorCode = (WsManErrorCode)(UInt32)(errorCodeProperty.Value);

            switch (wsManErrorCode) // error codes that should result in sleep-and-retry are based on an email from Ryan
            {
            case WsManErrorCode.ERROR_WSMAN_QUOTA_MAX_SHELLS:
            case WsManErrorCode.ERROR_WSMAN_QUOTA_MAX_OPERATIONS:
            case WsManErrorCode.ERROR_WSMAN_QUOTA_USER:
            case WsManErrorCode.ERROR_WSMAN_QUOTA_SYSTEM:
            case WsManErrorCode.ERROR_WSMAN_QUOTA_MAX_SHELLUSERS:
            case WsManErrorCode.ERROR_WSMAN_QUOTA_MAX_SHELLS_PPQ:
            case WsManErrorCode.ERROR_WSMAN_QUOTA_MAX_USERS_PPQ:
            case WsManErrorCode.ERROR_WSMAN_QUOTA_MAX_PLUGINSHELLS_PPQ:
            case WsManErrorCode.ERROR_WSMAN_QUOTA_MAX_PLUGINOPERATIONS_PPQ:
            case WsManErrorCode.ERROR_WSMAN_QUOTA_MAX_OPERATIONS_USER_PPQ:
            case WsManErrorCode.ERROR_WSMAN_QUOTA_MAX_COMMANDS_PER_SHELL_PPQ:
            case WsManErrorCode.ERROR_WSMAN_QUOTA_MIN_REQUIREMENT_NOT_AVAILABLE_PPQ:
                return(true);

            default:
                return(false);
            }
        }
示例#15
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));
        }
示例#16
0
 private static PSAdaptedProperty GetCimPropertyAdapter(CimProperty property, object baseObject)
 {
     try
     {
         string name = property.Name;
         return(GetCimPropertyAdapter(property, baseObject, name));
     }
     catch (CimException)
     {
         return(null);
     }
 }
示例#17
0
            public bool IsMatch(CimInstance o)
            {
                bool flag;
                bool flag1;

                if (o != null)
                {
                    CimProperty item = o.CimInstanceProperties[this.propertyName];
                    if (item != null)
                    {
                        object value = item.Value;
                        if (this._cimTypedExpectedPropertyValue != null)
                        {
                            value = this.ConvertActualValueToExpectedType(value, this._cimTypedExpectedPropertyValue);
                            bool flag2 = this.IsMatchingValue(value);
                            ClientSideQuery.PropertyValueFilter propertyValueFilter = this;
                            if (this.hadMatch)
                            {
                                flag = true;
                            }
                            else
                            {
                                flag = flag2;
                            }
                            propertyValueFilter.hadMatch = flag;
                            return(flag2);
                        }
                        else
                        {
                            ClientSideQuery.PropertyValueFilter propertyValueFilter1 = this;
                            if (this.hadMatch)
                            {
                                flag1 = true;
                            }
                            else
                            {
                                flag1 = value == null;
                            }
                            propertyValueFilter1.hadMatch = flag1;
                            return(value == null);
                        }
                    }
                    else
                    {
                        return(false);
                    }
                }
                else
                {
                    return(false);
                }
            }
示例#18
0
        /// <summary>
        /// Extracts an integer from the Value.
        /// Extracting 'int's is a very common operation, so has a dedicated method.
        /// This is a nullable equivalent to calling cp.Value<int>
        /// </summary>
        public static int?ValueAsInt(this CimProperty cp)
        {
            string valueString = cp.Value.ToString();

            if (int.TryParse(valueString, out int val))
            {
                return(val);
            }
            else
            {
                return(null);
            }
        }
 private static PSAdaptedProperty GetCimPropertyAdapter(CimProperty property, object baseObject)
 {
     try
     {
         string propertyName = property.Name;
         return(GetCimPropertyAdapter(property, baseObject, propertyName));
     }
     catch (CimException)
     {
         // ignore "Name" property access failures and move on.
         return(null);
     }
 }
示例#20
0
        private static string ConvertUInt16ArrayToString(CimProperty cimInstanceProperty)
        {
            var value = cimInstanceProperty.Value;
            if (value == null)
            {
                return String.Empty;
            }
            var ushortValues = (ushort[]) value;

            var listOfChars = ushortValues.Select(x => Char.ConvertFromUtf32(Convert.ToInt32(x)));

            return string.Join("", listOfChars);
        }
示例#21
0
        private static T GetPropertyValue <T>(CimInstance cimInstance, string propertyName, T defaultValue)
        {
            CimProperty cimProperty = cimInstance.CimInstanceProperties[propertyName];

            if (cimProperty == null)
            {
                return(defaultValue);
            }

            object propertyValue = cimProperty.Value;

            if (propertyValue is T)
            {
                return((T)propertyValue);
            }

            if (propertyValue is string)
            {
                string stringValue = (string)propertyValue;
                try
                {
                    if (typeof(T) == typeof(bool))
                    {
                        return((T)(object)XmlConvert.ToBoolean(stringValue));
                    }
                    else if (typeof(T) == typeof(UInt16))
                    {
                        return((T)(object)UInt16.Parse(stringValue, CultureInfo.InvariantCulture));
                    }
                    else if (typeof(T) == typeof(byte[]))
                    {
                        byte[] contentBytes = Convert.FromBase64String(stringValue);
                        byte[] lengthBytes  = BitConverter.GetBytes(contentBytes.Length + 4);
                        if (BitConverter.IsLittleEndian)
                        {
                            Array.Reverse(lengthBytes);
                        }

                        return((T)(object)(lengthBytes.Concat(contentBytes).ToArray()));
                    }
                }
                catch (Exception)
                {
                    return(defaultValue);
                }
            }

            return(defaultValue);
        }
示例#22
0
        internal static MI_Value ConvertToNativeLayer(object value, CimType cimType)
        {
            var cimInstance = value as CimInstance;

            if (cimInstance != null)
            {
                MI_Value retval = new MI_Value();
                retval.Instance = cimInstance.InstanceHandle;
                return(retval);
            }

            var arrayOfCimInstances = value as CimInstance[];

            if (arrayOfCimInstances != null)
            {
                MI_Instance[] arrayOfInstanceHandles = new MI_Instance[arrayOfCimInstances.Length];
                for (int i = 0; i < arrayOfCimInstances.Length; i++)
                {
                    CimInstance inst = arrayOfCimInstances[i];
                    if (inst == null)
                    {
                        arrayOfInstanceHandles[i] = null;
                    }
                    else
                    {
                        arrayOfInstanceHandles[i] = inst.InstanceHandle;
                    }
                }

                MI_Value retval = new MI_Value();
                retval.InstanceA = arrayOfInstanceHandles;
                return(retval);
            }

            // TODO: What to do with Unknown types? Ignore? Uncomment and remove return line immediately below.
            return(CimProperty.ConvertToNativeLayer(value, cimType));

            /*
             * if (cimType != CimType.Unknown)
             * {
             * return CimProperty.ConvertToNativeLayer(value, cimType);
             * }
             * else
             * {
             * return value;
             * }
             */
        }
示例#23
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);
            }
        }
示例#24
0
        public override bool IsSettable(PSAdaptedProperty adaptedProperty)
        {
            if (adaptedProperty == null)
            {
                return(false);
            }
            CimProperty tag = adaptedProperty.Tag as CimProperty;

            if (tag == null)
            {
                return(false);
            }
            bool flag = CimFlags.ReadOnly == (tag.Flags & CimFlags.ReadOnly);

            return(!flag);
        }
        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);
        }
        // Processes the results from CIM method invocation
        public virtual void OnNext(CimMethodResultBase result)
        {
            // Retrieves and stores the streamed results of MSFT_ServerManagerServerComponent CIM classes
            var streamedResult = result as CimMethodStreamedResult;

            if (streamedResult != null)
            {
                if (streamedResult.ParameterName.Equals("ServerComponents", StringComparison.OrdinalIgnoreCase))
                {
                    serverComponents.AddRange((CimInstance[])streamedResult.ItemValue);
                }
            }

            // Retrieves the posted result of MSFT_ServerManagerRequestState CIM class and stores the RequestState property
            var postedResult = result as CimMethodResult;

            if (postedResult != null && postedResult.OutParameters != null)
            {
                CimInstance        requestStateInstance  = null;
                CimMethodParameter requestStateParameter = null;

                // The output parameter is named as "EnumerationState" when invoking the GetServerComponentsAsync method,
                // and it's named as "AlterationState" when invoking the Add/RemoveServerComponentAsync methods
                requestStateParameter = postedResult.OutParameters["EnumerationState"];
                if (requestStateParameter != null)
                {
                    requestStateInstance = (CimInstance)requestStateParameter.Value;
                }

                requestStateParameter = postedResult.OutParameters["AlterationState"];
                if (requestStateParameter != null)
                {
                    requestStateInstance = (CimInstance)requestStateParameter.Value;
                }

                if (requestStateInstance != null)
                {
                    CimProperty property = requestStateInstance.CimInstanceProperties["RequestState"];
                    if (property != null)
                    {
                        requestState = (RequestStateEnum)property.Value;
                    }
                }
            }
        }
        /// <summary>
        /// </summary>
        /// <param name="adaptedProperty"></param>
        /// <param name="value"></param>
        public override void SetPropertyValue(PSAdaptedProperty adaptedProperty, object value)
        {
            if (adaptedProperty == null)
            {
                throw new ArgumentNullException("adaptedProperty");
            }

            if (!IsSettable(adaptedProperty))
            {
                throw new SetValueException("ReadOnlyCIMProperty",
                                            null,
                                            CimInstanceTypeAdapterResources.ReadOnlyCIMProperty,
                                            adaptedProperty.Name);
            }

            CimProperty cimProperty = adaptedProperty.Tag as CimProperty;
            object      valueToSet  = value;

            if (valueToSet != null)
            {
                // Convert only if value is not null
                Type paramType;
                switch (cimProperty.CimType)
                {
                case CimType.DateTime:
                    paramType = typeof(object);
                    break;

                case CimType.DateTimeArray:
                    paramType = typeof(object[]);
                    break;

                default:
                    paramType = CimConverter.GetDotNetType(cimProperty.CimType);
                    Dbg.Assert(paramType != null, "'default' case should only be used for well-defined CimType->DotNetType conversions");
                    break;
                }

                valueToSet = Adapter.PropertySetAndMethodArgumentConvertTo(
                    value, paramType, CultureInfo.InvariantCulture);
            }

            cimProperty.Value = valueToSet;
            return;
        }
示例#28
0
        private static T GetPropertyValue <T>(CimInstance cimInstance, string propertyName, T defaultValue)
        {
            CimProperty property = cimInstance.CimInstanceProperties[propertyName];

            if (property != null)
            {
                object obj2 = property.Value;
                if (obj2 is T)
                {
                    return((T)obj2);
                }
                if (!(obj2 is string))
                {
                    return(defaultValue);
                }
                string s = (string)obj2;
                try
                {
                    if (typeof(T).Equals(typeof(bool)))
                    {
                        return((T)LanguagePrimitives.ConvertTo <T>(XmlConvert.ToBoolean(s)));
                    }
                    if (typeof(T).Equals(typeof(ushort)))
                    {
                        return((T)LanguagePrimitives.ConvertTo <T>(ushort.Parse(s, CultureInfo.InvariantCulture)));
                    }
                    if (!typeof(T).Equals(typeof(byte[])))
                    {
                        return(defaultValue);
                    }
                    byte[] second = Convert.FromBase64String(s);
                    byte[] bytes  = BitConverter.GetBytes((int)(second.Length + 4));
                    if (BitConverter.IsLittleEndian)
                    {
                        Array.Reverse(bytes);
                    }
                    return((T)LanguagePrimitives.ConvertTo <T>(bytes.Concat <byte>(second).ToArray <byte>()));
                }
                catch (Exception)
                {
                    return(defaultValue);
                }
            }
            return(defaultValue);
        }
示例#29
0
            public override object?Invoke(object proxy, MethodInfo method, object[] arguments)
            {
                if (method.DeclaringType == typeof(IWmiObject))
                {
                    return(method.Invoke(this, arguments));
                }

                // TODO: proper property support
                if (method.Name.StartsWith("set_"))
                {
#if FEATURE_CIM
                    CimProperty cimProperty = this.cimInstance.CimInstanceProperties[method.Name.Substring(4)];
                    Debug.Assert((cimProperty.Flags & CimFlags.ReadOnly) == CimFlags.None);
                    cimProperty.Value = arguments[0];
#else
                    this.wmiObject[method.Name.Substring(4)] = arguments[0];
#endif
                    return(null);
                }

                if (method.Name.StartsWith("get_"))
                {
#if FEATURE_CIM
                    return(this.cimInstance.CimInstanceProperties[method.Name.Substring(4)].Value);
#else
                    return(this.wmiObject[method.Name.Substring(4)]);
#endif
                }

                string methodName = method.Name;
#if FEATURE_CIM
                using CimMethodParametersCollection? cimParameters = arguments.Length == 0 ? null :
                                                                     this.GetMethodParameters(this.cimInstance.CimClass, methodName, method.GetParameters(), arguments);
                using CimMethodResult result = this.cimSession.InvokeMethod(CimNamespace, this.cimInstance, methodName, cimParameters);
                this.CheckError(result);
#else
                using ManagementBaseObject? wmiParameters = arguments.Length == 0 ? null :
                                                            this.GetMethodParameters(this.wmiObject, methodName, method.GetParameters(), arguments);
                using ManagementBaseObject result = this.wmiObject.InvokeMethod(methodName, wmiParameters, null);
                this.CheckError(result);
#endif
                return(null);
            }
示例#30
0
        internal static void SetObjectDataMember(object obj, BindingFlags binding, CimProperty cimProperty)
        {
            var type = obj.GetType();

            var pi = type.GetProperty(cimProperty.Name, binding);

            if (pi != null && pi.CanWrite)
            {
                pi.SetValue(obj, cimProperty.Value, null);
            }
            else
            {
                var fi = type.GetField(cimProperty.Name, binding);

                if (fi != null && !fi.IsInitOnly)
                {
                    fi.SetValue(obj, cimProperty.Value);
                }
            }
        }
示例#31
0
        public void WriteCimProperty(CimProperty property)
        {
            #region Actual XML Request
            /*
            <PROPERTY NAME="CSCreationClassName" TYPE="string" CLASSORIGIN="CIM_FileSystem" PROPAGATED="true" >
                <QUALIFIER NAME="Key" TYPE="boolean" OVERRIDABLE="false" >
                    <VALUE>true</VALUE>
                </QUALIFIER>
                [...]
                <VALUE>tCSCreationClassName</VALUE>
            </PROPERTY>

                        -or-

            <PROPERTY.ARRAY NAME="OperationalStatus" TYPE="uint16" CLASSORIGIN="CIM_ManagedSystemElement" PROPAGATED="true" >
                <QUALIFIER NAME="Description" TYPE="string" TRANSLATABLE="true" >
                    <VALUE>Indicates the current statuses of the element. Various operational statuses are defined. Many of the enumeration&apos;s values are self-explanatory. However, a few are not and are described here in more detail. &quot;Stressed&quot; indicates that the element is functioning, but needs attention. Examples of &quot;Stressed&quot; states are overload, overheated, and so on. &quot;Predictive Failure&quot; indicates that an element is functioning nominally but predicting a failure in the near future. &quot;In Service&quot; describes an element being configured, maintained, cleaned, or otherwise administered. &quot;No Contact&quot; indicates that the monitoring system has knowledge of this element, but has never been able to establish communications with it. &quot;Lost Communication&quot; indicates that the ManagedSystem Element is known to exist and has been contacted successfully in the past, but is currently unreachable. &quot;Stopped&quot; and &quot;Aborted&quot; are similar, although the former implies a clean and orderly stop, while the latter implies an abrupt stop where the state and configuration of the element might need to be updated. &quot;Dormant&quot; indicates that the element is inactive or quiesced. &quot;Supporting Entity in Error&quot; indicates that this element might be &quot;OK&quot; but that another element, on which it is dependent, is in error. An example is a network service or endpoint that cannot function due to lower-layer networking problems. &quot;Completed&quot; indicates that the element has completed its operation. This value should be combined with either OK, Error, or Degraded so that a client can tell if the complete operation Completed with OK (passed), Completed with Error (failed), or Completed with Degraded (the operation finished, but it did not complete OK or did not report an error). &quot;Power Mode&quot; indicates that the element has additional power model information contained in the Associated PowerManagementService association. OperationalStatus replaces the Status property on ManagedSystemElement to provide a consistent approach to enumerations, to address implementation needs for an array property, and to provide a migration path from today&apos;s environment to the future. This change was not made earlier because it required the deprecated qualifier. Due to the widespread use of the existing Status property in management applications, it is strongly recommended that providers or instrumentation provide both the Status and OperationalStatus properties. Further, the first value of OperationalStatus should contain the primary status for the element. When instrumented, Status (because it is single-valued) should also provide the primary status of the element.</VALUE>
                </QUALIFIER>
                [...]
                <VALUE.ARRAY>
                    <VALUE></VALUE>
                </VALUE.ARRAY>
            </PROPERTY.ARRAY>
            */
            #endregion
            WritePropertyElement();

            if (property.Name.IsSet)
                WriteCimNameAttributeString(property.Name);

            if (property.Type.IsSet)
                WriteTypeAttribute(property.Type.ToCimType());

            if (property.ClassOrigin.IsSet)
                WriteClassOriginAttributeString(property.ClassOrigin);

            if (property.IsPropagated.IsSet)
                WritePropagatedAttribute(property.IsPropagated.ToBool());

            WriteCimQualifierList(property.Qualifiers);

            if (property.Value != string.Empty)
                WriteValueString(property.Value);

            this.WriteEndElement();
        }