/// <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); }
/// <summary> /// Retrieve the reference object or reference array object. /// The returned object has to be either CimInstance or CImInstance[] type, /// if not thrown exception. /// </summary> /// <param name="value"></param> /// <param name="referenceType">Output the cimtype of the value, either Reference or ReferenceArray.</param> /// <returns></returns> protected object GetReferenceOrReferenceArrayObject(object value, ref CimType referenceType) { PSReference cimReference = value as PSReference; if (cimReference != null) { object baseObject = GetBaseObject(cimReference.Value); CimInstance cimInstance = baseObject as CimInstance; if (cimInstance == null) { return(null); } referenceType = CimType.Reference; return(cimInstance); } else { object[] cimReferenceArray = value as object[]; if (cimReferenceArray == null) { return(null); } else if (!(cimReferenceArray[0] is PSReference)) { return(null); } CimInstance[] cimInstanceArray = new CimInstance[cimReferenceArray.Length]; for (int i = 0; i < cimReferenceArray.Length; i++) { PSReference tempCimReference = cimReferenceArray[i] as PSReference; if (tempCimReference == null) { return(null); } object baseObject = GetBaseObject(tempCimReference.Value); cimInstanceArray[i] = baseObject as CimInstance; if (cimInstanceArray[i] == null) { return(null); } } referenceType = CimType.ReferenceArray; return(cimInstanceArray); } }
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); } }
} // end InvokeScript internal static Collection <PSObject> InvokeWithContext(ScriptBlock scriptBlock, PsContext withContext, PSReference saveContext) { if (null == withContext) { withContext = new PsContext(); // TODO: share a single, readonly Empty context } using (var ctxHelper = new PsContextHelper(scriptBlock, withContext, null != saveContext)) { // TODO: Should I switch to using shell.AddScript, like in FormatBaseCommand.cs? var results = ctxHelper.AdjustedScriptBlock.InvokeWithContext(ctxHelper.WithContext.Funcs, ctxHelper.WithContext.VarList); if (null != saveContext) { saveContext.Value = ctxHelper.SavedContext; } return(results); } // end using( ctxHelper ) } // end InvokeWithContext
internal static object ConvertFromDotNetToCim(object dotNetObject) { if (dotNetObject != null) { PSObject pSObject = PSObject.AsPSObject(dotNetObject); Type type = pSObject.BaseObject.GetType(); if (!LanguagePrimitives.IsCimIntrinsicScalarType(type)) { if (!typeof(CimInstance).IsAssignableFrom(type)) { if (!typeof(PSReference).IsAssignableFrom(type)) { if (type.IsArray) { Type elementType = CimValueConverter.GetElementType(type); if (elementType != null) { Array baseObject = (Array)pSObject.BaseObject; Type cimType = CimValueConverter.GetCimType(elementType); Array arrays = Array.CreateInstance(cimType, baseObject.Length); for (int i = 0; i < arrays.Length; i++) { object cim = CimValueConverter.ConvertFromDotNetToCim(baseObject.GetValue(i)); arrays.SetValue(cim, i); } return(arrays); } } Type convertibleCimType = CimValueConverter.GetConvertibleCimType(type); if (convertibleCimType == null) { if (!typeof(ObjectSecurity).IsAssignableFrom(type)) { if (!typeof(X509Certificate2).IsAssignableFrom(type)) { if (!typeof(X500DistinguishedName).IsAssignableFrom(type)) { if (!typeof(PhysicalAddress).IsAssignableFrom(type)) { if (!typeof(IPEndPoint).IsAssignableFrom(type)) { if (!typeof(WildcardPattern).IsAssignableFrom(type)) { if (!typeof(XmlDocument).IsAssignableFrom(type)) { throw CimValueConverter.GetInvalidCastException(null, "InvalidDotNetToCimCast", dotNetObject, CmdletizationResources.CimConversion_CimIntrinsicValue); } else { XmlDocument xmlDocument = (XmlDocument)pSObject.BaseObject; string outerXml = xmlDocument.OuterXml; return(outerXml); } } else { WildcardPattern wildcardPattern = (WildcardPattern)pSObject.BaseObject; return(wildcardPattern.ToWql()); } } else { object obj = LanguagePrimitives.ConvertTo(dotNetObject, typeof(string), CultureInfo.InvariantCulture); return(obj); } } else { object obj1 = LanguagePrimitives.ConvertTo(dotNetObject, typeof(string), CultureInfo.InvariantCulture); return(obj1); } } else { X500DistinguishedName x500DistinguishedName = (X500DistinguishedName)pSObject.BaseObject; byte[] rawData = x500DistinguishedName.RawData; return(rawData); } } else { X509Certificate2 x509Certificate2 = (X509Certificate2)pSObject.BaseObject; byte[] numArray = x509Certificate2.RawData; return(numArray); } } else { string sddl = SecurityDescriptorCommandsBase.GetSddl(pSObject); return(sddl); } } else { object obj2 = LanguagePrimitives.ConvertTo(dotNetObject, convertibleCimType, CultureInfo.InvariantCulture); return(obj2); } } else { PSReference pSReference = (PSReference)pSObject.BaseObject; if (pSReference.Value != null) { PSObject pSObject1 = PSObject.AsPSObject(pSReference.Value); return(CimValueConverter.ConvertFromDotNetToCim(pSObject1.BaseObject)); } else { return(null); } } } else { return(pSObject.BaseObject); } } else { return(pSObject.BaseObject); } } else { return(null); } }
// this helper prepares arguments for COM binding by transforming ByVal StongBox arguments // into ByRef expressions that represent the argument's Value fields. internal static bool[] ProcessArgumentsForCom(ComMethodDesc method, ref DynamicMetaObject[] args, List <ParameterExpression> temps, List <Expression> initTemps) { Debug.Assert(args != null); DynamicMetaObject[] newArgs = new DynamicMetaObject[args.Length]; bool[] isByRefArg = new bool[args.Length]; for (int i = 0; i < args.Length; i++) { DynamicMetaObject curArgument = args[i]; // set new arg infos to their original values or set default ones // we will do this fixup early so that we can assume we always have // arginfos in COM binder. if (IsByRef(curArgument)) { newArgs[i] = curArgument; isByRefArg[i] = true; } else { if (IsPSReferenceArg(curArgument)) { var restrictions = curArgument.Restrictions.Merge( GetTypeRestrictionForDynamicMetaObject(curArgument) ); // we have restricted this argument to LimitType so we can convert and conversion will be trivial cast. Expression boxedValueAccessor = Expression.Property( Helpers.Convert( curArgument.Expression, curArgument.LimitType ), curArgument.LimitType.GetProperty("Value") ); PSReference value = curArgument.Value as PSReference; object boxedValue = value != null ? value.Value : null; newArgs[i] = new DynamicMetaObject( boxedValueAccessor, restrictions, boxedValue ); isByRefArg[i] = true; } else { if ((method.ParameterInformation != null) && (i < method.ParameterInformation.Length)) { newArgs[i] = new DynamicMetaObject(curArgument.CastOrConvertMethodArgument( method.ParameterInformation[i].parameterType, i.ToString(CultureInfo.InvariantCulture), method.Name, temps, initTemps), curArgument.Restrictions); } else { newArgs[i] = curArgument; } isByRefArg[i] = false; } } } args = newArgs; return(isByRefArg); }
/// <exception cref="PSInvalidCastException">The only kind of exception this method can throw.</exception> internal static object ConvertFromDotNetToCim(object dotNetObject) { if (dotNetObject == null) { return(null); } PSObject psObject = PSObject.AsPSObject(dotNetObject); Type dotNetType = psObject.BaseObject.GetType(); Dbg.Assert( !(dotNetType.GetTypeInfo().IsGenericType&& dotNetType.GetGenericTypeDefinition() == typeof(Nullable <>)), "GetType on a boxed object should never return Nullable<T>"); if (LanguagePrimitives.IsCimIntrinsicScalarType(dotNetType)) { return(psObject.BaseObject); } if (typeof(CimInstance).IsAssignableFrom(dotNetType)) { return(psObject.BaseObject); } if (typeof(PSReference).IsAssignableFrom(dotNetType)) { PSReference psReference = (PSReference)psObject.BaseObject; if (psReference.Value == null) { return(null); } else { PSObject innerPso = PSObject.AsPSObject(psReference.Value); return(ConvertFromDotNetToCim(innerPso.BaseObject)); } } if (dotNetType.IsArray) { Type dotNetElementType = GetElementType(dotNetType); if (dotNetElementType != null) { var dotNetArray = (Array)psObject.BaseObject; Type cimElementType = CimValueConverter.GetCimType(dotNetElementType); Array cimArray = Array.CreateInstance(cimElementType, dotNetArray.Length); for (int i = 0; i < cimArray.Length; i++) { object cimElement = ConvertFromDotNetToCim(dotNetArray.GetValue(i)); cimArray.SetValue(cimElement, i); } return(cimArray); } } Type convertibleCimType = GetConvertibleCimType(dotNetType); if (convertibleCimType != null) { object cimIntrinsicValue = LanguagePrimitives.ConvertTo(dotNetObject, convertibleCimType, CultureInfo.InvariantCulture); return(cimIntrinsicValue); } if (typeof(ObjectSecurity).IsAssignableFrom(dotNetType)) { string cimIntrinsicValue = Microsoft.PowerShell.Commands.SecurityDescriptorCommandsBase.GetSddl(psObject); return(cimIntrinsicValue); } if (typeof(X509Certificate2).IsAssignableFrom(dotNetType)) { var cert = (X509Certificate2)(psObject.BaseObject); byte[] cimIntrinsicValue = cert.RawData; return(cimIntrinsicValue); } if (typeof(X500DistinguishedName).IsAssignableFrom(dotNetType)) { var x500name = (X500DistinguishedName)(psObject.BaseObject); byte[] cimIntrinsicValue = x500name.RawData; return(cimIntrinsicValue); } if (typeof(PhysicalAddress).IsAssignableFrom(dotNetType)) { object cimIntrinsicValue = LanguagePrimitives.ConvertTo(dotNetObject, typeof(string), CultureInfo.InvariantCulture); return(cimIntrinsicValue); } if (typeof(IPEndPoint).IsAssignableFrom(dotNetType)) { object cimIntrinsicValue = LanguagePrimitives.ConvertTo(dotNetObject, typeof(string), CultureInfo.InvariantCulture); return(cimIntrinsicValue); } if (typeof(WildcardPattern).IsAssignableFrom(dotNetType)) { var wildcardPattern = (WildcardPattern)(psObject.BaseObject); return(wildcardPattern.ToWql()); } if (typeof(XmlDocument).IsAssignableFrom(dotNetType)) { var xmlDocument = (XmlDocument)(psObject.BaseObject); string cimIntrinsicValue = xmlDocument.OuterXml; return(cimIntrinsicValue); } // unrecognized type = throw invalid cast exception throw CimValueConverter.GetInvalidCastException( null, /* inner exception */ "InvalidDotNetToCimCast", dotNetObject, CmdletizationResources.CimConversion_CimIntrinsicValue); }
internal object Transform(EngineIntrinsics engineIntrinsics, object inputData, bool bindingParameters, bool bindingScriptCmdlet) { if (_convertTypes == null) { return(inputData); } object result = inputData; try { for (int i = 0; i < _convertTypes.Length; i++) { if (bindingParameters) { // We should not be doing a conversion here if [ref] is the last type. // When [ref] appears in an argument list, it is used for checking only. // No Conversion should be done. if (_convertTypes[i].Equals(typeof(System.Management.Automation.PSReference))) { object temp; PSObject mshObject = result as PSObject; if (mshObject != null) { temp = mshObject.BaseObject; } else { temp = result; } if (!(temp is PSReference reference)) { throw new PSInvalidCastException("InvalidCastExceptionReferenceTypeExpected", null, ExtendedTypeSystem.ReferenceTypeExpected); } } else { object temp; PSObject mshObject = result as PSObject; if (mshObject != null) { temp = mshObject.BaseObject; } else { temp = result; } // If a non-ref type is expected but currently passed in is a ref, do an implicit dereference. PSReference reference = temp as PSReference; if (reference != null) { result = reference.Value; } if (bindingScriptCmdlet && _convertTypes[i] == typeof(string)) { // Don't allow conversion from array to string in script w/ cmdlet binding. Allow // the conversion for ordinary script parameter binding for V1 compatibility. temp = PSObject.Base(result); if (temp != null && temp.GetType().IsArray) { throw new PSInvalidCastException("InvalidCastFromAnyTypeToString", null, ExtendedTypeSystem.InvalidCastCannotRetrieveString); } } } } // BUGBUG // NTRAID#Windows Out of Band Releases - 930116 - 03/14/06 // handling special case for boolean, switchparameter and Nullable<bool> // These parameter types will not be converted if the incoming value types are not // one of the accepted categories - $true/$false or numbers (0 or otherwise) if (LanguagePrimitives.IsBoolOrSwitchParameterType(_convertTypes[i])) { CheckBoolValue(result, _convertTypes[i]); } if (bindingScriptCmdlet) { // Check for conversion to something like bool[] or ICollection<bool>, but only for cmdlet binding // to stay compatible with V1. ParameterCollectionTypeInformation collectionTypeInfo = new ParameterCollectionTypeInformation(_convertTypes[i]); if (collectionTypeInfo.ParameterCollectionType != ParameterCollectionType.NotCollection && LanguagePrimitives.IsBoolOrSwitchParameterType(collectionTypeInfo.ElementType)) { IList currentValueAsIList = ParameterBinderBase.GetIList(result); if (currentValueAsIList != null) { foreach (object val in currentValueAsIList) { CheckBoolValue(val, collectionTypeInfo.ElementType); } } else { CheckBoolValue(result, collectionTypeInfo.ElementType); } } } result = LanguagePrimitives.ConvertTo(result, _convertTypes[i], CultureInfo.InvariantCulture); // Do validation of invalid direct variable assignments which are allowed to // be used for parameters. // // Note - this is duplicated in ExecutionContext.cs as parameter binding for script cmdlets can avoid this code path. if ((!bindingScriptCmdlet) && (!bindingParameters)) { // ActionPreference.Suspend is reserved for future use and is not supported as a preference variable. if (_convertTypes[i] == typeof(ActionPreference)) { ActionPreference resultPreference = (ActionPreference)result; if (resultPreference == ActionPreference.Suspend) { throw new PSInvalidCastException("InvalidActionPreference", null, ErrorPackage.ActionPreferenceReservedForFutureUseError, resultPreference); } } } } } catch (PSInvalidCastException e) { throw new ArgumentTransformationMetadataException(e.Message, e); } // Track the flow of untrusted object during the conversion when it's called directly from ParameterBinderBase. // When it's called from the override Transform method, the tracking is taken care of in the base type. if (bindingParameters || bindingScriptCmdlet) { ExecutionContext.PropagateInputSource(inputData, result, engineIntrinsics.SessionState.Internal.LanguageMode); } return(result); }
protected object GetReferenceOrReferenceArrayObject(object value, ref CimType referenceType) { PSReference pSReference = value as PSReference; if (pSReference == null) { object[] objArray = value as object[]; if (objArray != null) { if (objArray[0] as PSReference != null) { CimInstance[] cimInstanceArray = new CimInstance[(int)objArray.Length]; int num = 0; while (num < (int)objArray.Length) { PSReference pSReference1 = objArray[num] as PSReference; if (pSReference1 != null) { object baseObject = this.GetBaseObject(pSReference1.Value); cimInstanceArray[num] = baseObject as CimInstance; if (cimInstanceArray[num] != null) { num++; } else { return(null); } } else { return(null); } } referenceType = CimType.ReferenceArray; return(cimInstanceArray); } else { return(null); } } else { return(null); } } else { object obj = this.GetBaseObject(pSReference.Value); CimInstance cimInstance = obj as CimInstance; if (cimInstance != null) { referenceType = CimType.Reference; return(cimInstance); } else { return(null); } } }