public static void SafeAdd( this PSMemberInfoCollection<PSPropertyInfo> t, PSPropertyInfo item ) { if( null == t[item.Name]) { t.Add( item ); } }
private void WritePropertyWithNullValue( XmlWriter writer, PSPropertyInfo source, int depth) { WriteStartElement(writer, CustomSerializationStrings.Properties); WriteAttribute(writer, CustomSerializationStrings.NameAttribute, ((PSPropertyInfo)source).Name); if (!_notypeinformation) { WriteAttribute(writer, CustomSerializationStrings.TypeAttribute, ((PSPropertyInfo)source).TypeNameOfValue); } writer.WriteEndElement(); }
/// <summary> /// Prepend property value. /// </summary> /// <param name="maml1"> /// </param> /// <param name="maml2"> /// </param> /// <param name="path"> /// </param> /// <param name="shouldOverride"> /// Should Override the maml1 value from maml2 instead of prepend. /// </param> internal static void PrependPropertyValue(PSObject maml1, PSObject maml2, string[] path, bool shouldOverride) { // Final collection of PSObjects. List <object> items = new List <object>(); // Add maml2 first since we are prepending. // For maml2: Add as collection or single item. No-op if PSPropertyInfo propertyInfo2 = GetPropertyInfo(maml2, path); if (propertyInfo2 != null) { var array = propertyInfo2.Value as Array; if (array != null) { items.AddRange(propertyInfo2.Value as IEnumerable <object>); } else { items.Add(propertyInfo2.Value); } } // Extend maml1 to make sure the property-path exists - since we'll be modifying it soon. EnsurePropertyInfoPathExists(maml1, path); // For maml1: Add as collection or single item. Do nothing if null or some other type. PSPropertyInfo propertyInfo1 = GetPropertyInfo(maml1, path); if (propertyInfo1 != null) { if (!shouldOverride) { var array = propertyInfo1.Value as Array; if (array != null) { items.AddRange(propertyInfo1.Value as IEnumerable <object>); } else { items.Add(propertyInfo1.Value); } } // Now replace in maml1. If items.Count == 0 do nothing since Value is already null. if (items.Count == 1) { propertyInfo1.Value = items[0]; } else if (items.Count >= 2) { propertyInfo1.Value = items.ToArray(); } } }
private string GetHelpProperty(string propertyName) { PSPropertyInfo property = _deserializedRemoteHelp.Properties[propertyName]; if (property == null) { return(null); } return(property.Value as string); }
private void CheckAndAddProperty(PSPropertyInfo propertyInfo, Attribute[] attributes, ref PropertyDescriptorCollection returnValue) { using (typeDescriptor.TraceScope("Checking property \"{0}\".", new object[] { propertyInfo.Name })) { if (!propertyInfo.IsGettable) { typeDescriptor.WriteLine("Property \"{0}\" is write-only so it has been skipped.", new object[] { propertyInfo.Name }); } else { AttributeCollection propertyAttributes = null; Type propertyType = typeof(object); if ((attributes != null) && (attributes.Length != 0)) { PSProperty property = propertyInfo as PSProperty; if (property != null) { DotNetAdapter.PropertyCacheEntry adapterData = property.adapterData as DotNetAdapter.PropertyCacheEntry; if (adapterData == null) { typeDescriptor.WriteLine("Skipping attribute check for property \"{0}\" because it is an adapted property (not a .NET property).", new object[] { property.Name }); } else if (property.isDeserialized) { typeDescriptor.WriteLine("Skipping attribute check for property \"{0}\" because it has been deserialized.", new object[] { property.Name }); } else { propertyType = adapterData.propertyType; propertyAttributes = adapterData.Attributes; foreach (Attribute attribute in attributes) { if (!propertyAttributes.Contains(attribute)) { typeDescriptor.WriteLine("Property \"{0}\" does not contain attribute \"{1}\" so it has been skipped.", new object[] { property.Name, attribute }); return; } } } } } if (propertyAttributes == null) { propertyAttributes = new AttributeCollection(new Attribute[0]); } typeDescriptor.WriteLine("Adding property \"{0}\".", new object[] { propertyInfo.Name }); PSObjectPropertyDescriptor descriptor = new PSObjectPropertyDescriptor(propertyInfo.Name, propertyType, !propertyInfo.IsSettable, propertyAttributes); descriptor.SettingValueException += this.SettingValueException; descriptor.GettingValueException += this.GettingValueException; returnValue.Add(descriptor); } } }
private void CheckAndAddProperty(PSPropertyInfo propertyInfo, Attribute[] attributes, ref PropertyDescriptorCollection returnValue) { using (typeDescriptor.TraceScope("Checking property \"{0}\".", new object[] { propertyInfo.Name })) { if (!propertyInfo.IsGettable) { typeDescriptor.WriteLine("Property \"{0}\" is write-only so it has been skipped.", new object[] { propertyInfo.Name }); } else { AttributeCollection propertyAttributes = null; Type propertyType = typeof(object); if ((attributes != null) && (attributes.Length != 0)) { PSProperty property = propertyInfo as PSProperty; if (property != null) { DotNetAdapter.PropertyCacheEntry adapterData = property.adapterData as DotNetAdapter.PropertyCacheEntry; if (adapterData == null) { typeDescriptor.WriteLine("Skipping attribute check for property \"{0}\" because it is an adapted property (not a .NET property).", new object[] { property.Name }); } else if (property.isDeserialized) { typeDescriptor.WriteLine("Skipping attribute check for property \"{0}\" because it has been deserialized.", new object[] { property.Name }); } else { propertyType = adapterData.propertyType; propertyAttributes = adapterData.Attributes; foreach (Attribute attribute in attributes) { if (!propertyAttributes.Contains(attribute)) { typeDescriptor.WriteLine("Property \"{0}\" does not contain attribute \"{1}\" so it has been skipped.", new object[] { property.Name, attribute }); return; } } } } } if (propertyAttributes == null) { propertyAttributes = new AttributeCollection(new Attribute[0]); } typeDescriptor.WriteLine("Adding property \"{0}\".", new object[] { propertyInfo.Name }); PSObjectPropertyDescriptor descriptor = new PSObjectPropertyDescriptor(propertyInfo.Name, propertyType, !propertyInfo.IsSettable, propertyAttributes); descriptor.SettingValueException += this.SettingValueException; descriptor.GettingValueException += this.GettingValueException; returnValue.Add(descriptor); } } }
internal static string GetFullName(PSObject psObject) { if (psObject.BaseObject is CmdletInfo) { return(CmdletInfo.GetFullName((CmdletInfo)psObject.BaseObject)); } PSPropertyInfo property1 = psObject.Properties["Name"]; PSPropertyInfo property2 = psObject.Properties["PSSnapIn"]; string cmdletName = property1 == null ? "" : (string)property1.Value; return(CmdletInfo.GetFullName(property2 == null ? "" : (string)property2.Value, cmdletName)); }
private void ConstructFromPSObjectForRemoting(PSObject serializedErrorRecord) { if (serializedErrorRecord == null) { throw PSTraceSource.NewArgumentNullException("serializedErrorRecord"); } PSObject propertyValue = RemotingDecoder.GetPropertyValue <PSObject>(serializedErrorRecord, "Exception"); object targetObject = RemotingDecoder.GetPropertyValue <object>(serializedErrorRecord, "TargetObject"); PSObject serializedRemoteInvocationInfo = RemotingDecoder.GetPropertyValue <PSObject>(serializedErrorRecord, "InvocationInfo"); string str = null; if (propertyValue != null) { PSPropertyInfo info = propertyValue.Properties["Message"]; if (info != null) { str = info.Value as string; } } string fullyQualifiedErrorId = RemotingDecoder.GetPropertyValue <string>(serializedErrorRecord, "FullyQualifiedErrorId"); if (fullyQualifiedErrorId == null) { fullyQualifiedErrorId = "fullyQualifiedErrorId"; } ErrorCategory errorCategory = RemotingDecoder.GetPropertyValue <ErrorCategory>(serializedErrorRecord, "errorCategory_Category"); string str3 = RemotingDecoder.GetPropertyValue <string>(serializedErrorRecord, "ErrorCategory_Activity"); string str4 = RemotingDecoder.GetPropertyValue <string>(serializedErrorRecord, "ErrorCategory_Reason"); string str5 = RemotingDecoder.GetPropertyValue <string>(serializedErrorRecord, "ErrorCategory_TargetName"); string str6 = RemotingDecoder.GetPropertyValue <string>(serializedErrorRecord, "ErrorCategory_TargetType"); string str7 = RemotingDecoder.GetPropertyValue <string>(serializedErrorRecord, "ErrorCategory_Message"); string noteValue = GetNoteValue(serializedErrorRecord, "ErrorDetails_Message") as string; string str9 = GetNoteValue(serializedErrorRecord, "ErrorDetails_RecommendedAction") as string; RemoteException exception = new RemoteException((str != null) ? str : str7, propertyValue, serializedRemoteInvocationInfo); this.PopulateProperties(exception, targetObject, fullyQualifiedErrorId, errorCategory, str3, str4, str5, str6, str7, noteValue, str9); exception.SetRemoteErrorRecord(this); this.serializeExtendedInfo = RemotingDecoder.GetPropertyValue <bool>(serializedErrorRecord, "SerializeExtendedInfo"); if (this.serializeExtendedInfo) { this._invocationInfo = new System.Management.Automation.InvocationInfo(serializedErrorRecord); ArrayList list = RemotingDecoder.GetPropertyValue <ArrayList>(serializedErrorRecord, "PipelineIterationInfo"); if (list != null) { this.pipelineIterationInfo = new ReadOnlyCollection <int>((int[])list.ToArray(typeof(int))); } } else { this._invocationInfo = null; } }
/// <summary> /// Serializes properties of PSObject. /// </summary> private void WritePSObjectProperties(PSObject source, int depth) { Dbg.Assert(source != null, "caller should validate the information"); depth = GetDepthOfSerialization(source, depth); //Depth available for each property is one less --depth; Dbg.Assert(depth >= 0, "depth should be greater or equal to zero"); if (source.GetSerializationMethod(null) == SerializationMethod.SpecificProperties) { PSMemberInfoInternalCollection <PSPropertyInfo> specificProperties = new PSMemberInfoInternalCollection <PSPropertyInfo>(); foreach (string propertyName in source.GetSpecificPropertiesToSerialize(null)) { PSPropertyInfo property = source.Properties[propertyName]; if (property != null) { specificProperties.Add(property); } } SerializeProperties(specificProperties, CustomSerializationStrings.Properties, depth); return; } foreach (PSPropertyInfo prop in source.Properties) { Dbg.Assert(prop != null, "propertyCollection should only have member of type PSProperty"); object value = AutomationNull.Value; //PSObject throws GetValueException if it cannot //get value for a property. try { value = prop.Value; } catch (GetValueException) { WritePropertyWithNullValue(_writer, prop, depth); continue; } //Write the property if (value == null) { WritePropertyWithNullValue(_writer, prop, depth); } else { WriteOneObject(value, prop.Name, depth); } } }
internal static string GetFullName(PSObject psObject) { if (psObject.BaseObject is CmdletInfo) { CmdletInfo baseObject = (CmdletInfo)psObject.BaseObject; return(GetFullName(baseObject)); } PSPropertyInfo info2 = psObject.Properties["Name"]; PSPropertyInfo info3 = psObject.Properties["PSSnapIn"]; string cmdletName = (info2 == null) ? "" : ((string)info2.Value); string moduleName = (info3 == null) ? "" : ((string)info3.Value); return(GetFullName(moduleName, cmdletName)); }
private static CommandParameterInternal SplatEnumerableElement(object splattedArgument, IScriptExtent splatExtent) { PSObject obj2 = splattedArgument as PSObject; if (obj2 != null) { PSPropertyInfo info = obj2.Properties["<CommandParameterName>"]; object baseObject = obj2.BaseObject; if (((info != null) && (info.Value is string)) && (baseObject is string)) { return(CommandParameterInternal.CreateParameter(splatExtent, (string)info.Value, (string)baseObject)); } } return(CommandParameterInternal.CreateArgument(splatExtent, splattedArgument, false)); }
private static PSPropertyInfo GetProperty(PSObject psObject, string propertyName) { if (psObject == null) { throw PSTraceSource.NewArgumentNullException("psObject"); } if (propertyName == null) { throw PSTraceSource.NewArgumentNullException("propertyName"); } PSPropertyInfo info = psObject.Properties[propertyName]; if (info == null) { throw new PSRemotingDataStructureException(RemotingErrorIdStrings.MissingProperty, new object[] { propertyName }); } return(info); }
internal static void PrependPropertyValue( PSObject maml1, PSObject maml2, string[] path, bool shouldOverride) { List <object> objectList = new List <object>(); PSPropertyInfo properyInfo1 = MamlUtil.GetProperyInfo(maml2, path); if (properyInfo1.Value is PSObject[]) { objectList.AddRange((IEnumerable <object>)(PSObject[]) properyInfo1.Value); } else { objectList.Add(properyInfo1.Value); } MamlUtil.EnsurePropertyInfoPathExists(maml1, path); PSPropertyInfo properyInfo2 = MamlUtil.GetProperyInfo(maml1, path); if (!shouldOverride) { if (properyInfo2.Value is PSObject[]) { objectList.AddRange((IEnumerable <object>)(PSObject[]) properyInfo2.Value); } else { objectList.Add(properyInfo2.Value); } } if (objectList.Count == 1) { properyInfo2.Value = objectList[0]; } else { if (objectList.Count < 2) { return; } properyInfo2.Value = (object)objectList.ToArray(); } }
/// <summary> /// Sets the value of the component to a different value. /// </summary> /// <param name="component">The component with the property value that is to be set.</param> /// <param name="value">The new value.</param> /// <exception cref="ExtendedTypeSystemException"> /// If the property has not been found in the component or an exception has /// been thrown when setting the value of the property. /// This Exception will only be thrown if there is no event handler for the SettingValueException /// event of the <see cref="PSObjectTypeDescriptor"/> that created this <see cref="PSObjectPropertyDescriptor"/>. /// If there is an event handler, it can prevent this exception from being thrown, by changing /// the ShouldThrow property of <see cref="SettingValueExceptionEventArgs"/> /// from its default value of true to false. /// </exception> /// <exception cref="PSArgumentNullException">If <paramref name="component"/> is null.</exception> /// <exception cref="PSArgumentException">If <paramref name="component"/> is not an /// <see cref="PSObject"/> or an <see cref="PSObjectTypeDescriptor"/>. /// </exception> public override void SetValue(object component, object value) { if (component == null) { throw PSTraceSource.NewArgumentNullException("component"); } PSObject mshObj = GetComponentPSObject(component); try { PSPropertyInfo property = mshObj.Properties[this.Name] as PSPropertyInfo; if (property == null) { PSObjectTypeDescriptor.typeDescriptor.WriteLine("Could not find property \"{0}\" to set its value.", this.Name); ExtendedTypeSystemException e = new ExtendedTypeSystemException("PropertyNotFoundInPropertyDescriptorSetValue", null, ExtendedTypeSystem.PropertyNotFoundInTypeDescriptor, this.Name); bool shouldThrow; DealWithSetValueException(e, out shouldThrow); if (shouldThrow) { throw e; } return; } property.Value = value; } catch (ExtendedTypeSystemException e) { PSObjectTypeDescriptor.typeDescriptor.WriteLine("Exception setting the value of the property \"{0}\": \"{1}\".", this.Name, e.Message); bool shouldThrow; DealWithSetValueException(e, out shouldThrow); if (shouldThrow) { throw; } } OnValueChanged(component, EventArgs.Empty); }
internal static void AddCommonProperties(PSObject maml1, PSObject maml2) { if (maml1.Properties["PSSnapIn"] == null) { PSPropertyInfo info = maml2.Properties["PSSnapIn"]; if (info != null) { maml1.Properties.Add(new PSNoteProperty("PSSnapIn", info.Value)); } } if (maml1.Properties["ModuleName"] == null) { PSPropertyInfo info2 = maml2.Properties["ModuleName"]; if (info2 != null) { maml1.Properties.Add(new PSNoteProperty("ModuleName", info2.Value)); } } }
private void WritePSObjectProperties(PSObject source, int depth) { depth = GetDepthOfSerialization(source, depth); depth--; if (source.GetSerializationMethod(null) == SerializationMethod.SpecificProperties) { PSMemberInfoInternalCollection <PSPropertyInfo> propertyCollection = new PSMemberInfoInternalCollection <PSPropertyInfo>(); foreach (string str in source.GetSpecificPropertiesToSerialize(null)) { PSPropertyInfo member = source.Properties[str]; if (member != null) { propertyCollection.Add(member); } } this.SerializeProperties(propertyCollection, "Property", depth); } else { foreach (PSPropertyInfo info2 in source.Properties) { object obj2 = AutomationNull.Value; try { obj2 = info2.Value; } catch (GetValueException) { this.WritePropertyWithNullValue(this._writer, info2, depth); continue; } if (obj2 == null) { this.WritePropertyWithNullValue(this._writer, info2, depth); } else { this.WriteOneObject(obj2, info2.Name, depth); } } } }
internal static void PrependPropertyValue(PSObject maml1, PSObject maml2, string[] path, bool shouldOverride) { List <object> list = new List <object>(); PSPropertyInfo properyInfo = GetProperyInfo(maml2, path); if (properyInfo != null) { if (properyInfo.Value is Array) { list.AddRange(properyInfo.Value as IEnumerable <object>); } else { list.Add(properyInfo.Value); } } EnsurePropertyInfoPathExists(maml1, path); PSPropertyInfo info2 = GetProperyInfo(maml1, path); if (info2 != null) { if (!shouldOverride) { if (info2.Value is Array) { list.AddRange(info2.Value as IEnumerable <object>); } else { list.Add(info2.Value); } } if (list.Count == 1) { info2.Value = list[0]; } else if (list.Count >= 2) { info2.Value = list.ToArray(); } } }
internal RemoteHelpInfo(ExecutionContext context, RemoteRunspace remoteRunspace, string localCommandName, string remoteHelpTopic, string remoteHelpCategory, HelpCategory localHelpCategory) : base(localHelpCategory) { using (PowerShell shell = PowerShell.Create()) { Collection <PSObject> collection; shell.AddCommand("Get-Help"); shell.AddParameter("Name", remoteHelpTopic); if (!string.IsNullOrEmpty(remoteHelpCategory)) { shell.AddParameter("Category", remoteHelpCategory); } shell.Runspace = remoteRunspace; using (new PowerShellStopper(context, shell)) { collection = shell.Invoke(); } if ((collection == null) || (collection.Count == 0)) { throw new HelpNotFoundException(remoteHelpTopic); } this.deserializedRemoteHelp = collection[0]; this.deserializedRemoteHelp.Methods.Remove("ToString"); PSPropertyInfo info = this.deserializedRemoteHelp.Properties["Name"]; if (info != null) { info.Value = localCommandName; } PSObject details = base.Details; if (details != null) { info = details.Properties["Name"]; if (info != null) { info.Value = localCommandName; } else { details.InstanceMembers.Add(new PSNoteProperty("Name", localCommandName)); } } } }
/// <summary> /// Adds common properties like PSSnapIn,ModuleName from maml2 to maml1. /// </summary> /// <param name="maml1"></param> /// <param name="maml2"></param> internal static void AddCommonProperties(PSObject maml1, PSObject maml2) { if (maml1.Properties["PSSnapIn"] == null) { PSPropertyInfo snapInProperty = maml2.Properties["PSSnapIn"]; if (snapInProperty != null) { maml1.Properties.Add(new PSNoteProperty("PSSnapIn", snapInProperty.Value)); } } if (maml1.Properties["ModuleName"] == null) { PSPropertyInfo moduleNameProperty = maml2.Properties["ModuleName"]; if (moduleNameProperty != null) { maml1.Properties.Add(new PSNoteProperty("ModuleName", moduleNameProperty.Value)); } } }
private void SerializeProperties(PSMemberInfoInternalCollection <PSPropertyInfo> propertyCollection, string name, int depth) { if (propertyCollection.Count != 0) { foreach (PSMemberInfo info in propertyCollection) { PSPropertyInfo info2 = info as PSPropertyInfo; object source = AutomationNull.Value; try { source = info2.Value; } catch (GetValueException) { continue; } this.WriteOneObject(source, info2.Name, depth); } } }
/// <summary> /// Gets the full name of the cmdlet including the PSSnapin name. /// </summary> internal static string GetFullName(PSObject psObject) { // If this is a high-fidelity object then extract full-name normally. if (psObject.BaseObject is CmdletInfo) { CmdletInfo cmdletInfo = (CmdletInfo)psObject.BaseObject; return(GetFullName(cmdletInfo)); } // Otherwise, it is a PSCustomObject shredded in a remote call: extract name as a property. else { // Handle the case in one or both of the properties might not be defined. PSPropertyInfo nameProperty = psObject.Properties["Name"]; PSPropertyInfo psSnapInProperty = psObject.Properties["PSSnapIn"]; string nameString = nameProperty == null ? string.Empty : (string)nameProperty.Value; string psSnapInString = psSnapInProperty == null ? string.Empty : (string)psSnapInProperty.Value; return(GetFullName(psSnapInString, nameString)); } }
internal static PSPropertyInfo GetProperyInfo(PSObject psObject, string[] path) { if (path.Length > 0) { for (int i = 0; i < path.Length; i++) { string str = path[i]; PSPropertyInfo info = psObject.Properties[str]; if (i == (path.Length - 1)) { return(info); } if ((info == null) || !(info.Value is PSObject)) { return(null); } psObject = (PSObject)info.Value; } } return(null); }
private static T SafeGetProperty <T>(PSObject psObject, string propertyName) { if (psObject != null) { T local; PSPropertyInfo info = psObject.Properties[propertyName]; if (info == null) { return(default(T)); } object valueToConvert = info.Value; if (valueToConvert == null) { return(default(T)); } if (LanguagePrimitives.TryConvertTo <T>(valueToConvert, out local)) { return(local); } } return(default(T)); }
internal static PSPropertyInfo GetProperyInfo(PSObject psObject, string[] path) { if (path.Length <= 0) { return((PSPropertyInfo)null); } for (int index = 0; index < path.Length; ++index) { string name = path[index]; PSPropertyInfo property = psObject.Properties[name]; if (index == path.Length - 1) { return(property); } if (property == null || !(property.Value is PSObject)) { return((PSPropertyInfo)null); } psObject = (PSObject)property.Value; } return((PSPropertyInfo)null); }
/// <summary> /// Gets the string from PSObject using the information from /// types.ps1xml. This string is used for serializing the PSObject. /// </summary> /// /// <param name="source"> /// PSObject to be converted to string /// </param> /// /// <returns> /// string value to use for serializing this PSObject. /// </returns> private string GetStringFromPSObject(PSObject source) { Dbg.Assert(source != null, "caller should have validated the information"); // check if we have a well known string serialization source PSPropertyInfo serializationProperty = source.GetStringSerializationSource(null); string result = null; if (serializationProperty != null) { object val = serializationProperty.Value; if (val != null) { try { // if we have a string serialization value, return it result = val.ToString(); } catch (Exception exception) { CommandProcessorBase.CheckForSevereException(exception); } } } else { try { // fall back value result = source.ToString(); } catch (Exception exception) { CommandProcessorBase.CheckForSevereException(exception); } } return(result); }
/// <summary> /// Ensure property info path exists. /// </summary> internal static void EnsurePropertyInfoPathExists(PSObject psObject, string[] path) { if (path.Length == 0) { return; } // Walk the path and extend it if necessary. for (int i = 0; i < path.Length; ++i) { string propertyName = path[i]; PSPropertyInfo propertyInfo = psObject.Properties[propertyName]; // Add a property info here if none was found. if (propertyInfo == null) { // Add null on the last one, since we don't need to extend path further. object propertyValue = (i < path.Length - 1) ? new PSObject() : null; propertyInfo = new PSNoteProperty(propertyName, propertyValue); psObject.Properties.Add(propertyInfo); } // If we are on the last path element, we are done. Let's not mess with modifying Value. if (i == path.Length - 1) { return; } // If we are not on the last path element, let's make sure we can extend the path. if (propertyInfo.Value == null || propertyInfo.Value is not PSObject) { propertyInfo.Value = new PSObject(); } // Now move one step further along the path. psObject = (PSObject)propertyInfo.Value; } }
private static Exception GetExceptionFromErrorRecord(ErrorRecord errorRecord) { RuntimeException exception = errorRecord.Exception as RuntimeException; if (exception == null) { return(null); } RemoteException exception2 = exception as RemoteException; if (exception2 == null) { return(null); } PSPropertyInfo info = exception2.SerializedRemoteException.Properties["WasThrownFromThrowStatement"]; if ((info == null) || !((bool)info.Value)) { return(null); } exception.WasThrownFromThrowStatement = true; return(exception); }
public override object GetValue(object component) { if (component == null) { throw PSTraceSource.NewArgumentNullException("component"); } PSObject componentPSObject = GetComponentPSObject(component); try { PSPropertyInfo info = componentPSObject.Properties[this.Name]; if (info == null) { bool flag; PSObjectTypeDescriptor.typeDescriptor.WriteLine("Could not find property \"{0}\" to get its value.", new object[] { this.Name }); ExtendedTypeSystemException e = new ExtendedTypeSystemException("PropertyNotFoundInPropertyDescriptorGetValue", null, ExtendedTypeSystem.PropertyNotFoundInTypeDescriptor, new object[] { this.Name }); object obj3 = this.DealWithGetValueException(e, out flag); if (flag) { throw e; } return(obj3); } return(info.Value); } catch (ExtendedTypeSystemException exception2) { bool flag2; PSObjectTypeDescriptor.typeDescriptor.WriteLine("Exception getting the value of the property \"{0}\": \"{1}\".", new object[] { this.Name, exception2.Message }); object obj4 = this.DealWithGetValueException(exception2, out flag2); if (flag2) { throw; } return(obj4); } }
public override object GetValue(object component) { PSObject psObject = component != null?PSObjectPropertyDescriptor.GetComponentPSObject(component) : throw PSObjectPropertyDescriptor.tracer.NewArgumentNullException(nameof(component)); try { PSPropertyInfo property = psObject.Properties[this.Name]; if (property != null) { return(property.Value); } PSObjectTypeDescriptor.typeDescriptor.WriteLine("Could not find property \"{0}\" to get its value.", (object)this.Name); ExtendedTypeSystemException e = new ExtendedTypeSystemException("PropertyNotFoundInPropertyDescriptorGetValue", (Exception)null, "ExtendedTypeSystem", "PropertyNotFoundInTypeDescriptor", new object[1] { (object)this.Name }); bool shouldThrow; object valueException = this.DealWithGetValueException(e, out shouldThrow); if (shouldThrow) { throw e; } return(valueException); } catch (ExtendedTypeSystemException ex) { PSObjectTypeDescriptor.typeDescriptor.WriteLine("Exception getting the value of the property \"{0}\": \"{1}\".", (object)this.Name, (object)ex.Message); bool shouldThrow; object valueException = this.DealWithGetValueException(ex, out shouldThrow); if (!shouldThrow) { return(valueException); } throw; } }
internal string GetToStringValueForProperty(PSPropertyInfo property) { string str = null; try { object obj2 = property.Value; if (obj2 != null) { str = obj2.ToString(); } } catch (Exception exception) { UtilityCommon.CheckForSevereException(this._cmdlet, exception); } return str; }
internal override void SetUserValue(PSPropertyInfo info, string value) { try { // assign if (value == null) info.Value = null; else //! it is tempting to avoid our parsing, but it is not that good.. info.Value = Converter.Parse(info, value); // change is done WhenMemberChanged(Target); } catch (RuntimeException ex) { A.Msg(ex); } }
private string GetPropertyValue( PSPropertyInfo property, out bool fieldNeedsQuotes ) { try { string valueAsString; if ( property.Value is string ) { valueAsString = (string)property.Value; } else { valueAsString = String.Format( "{0}", property.Value ); } fieldNeedsQuotes = valueAsString.Contains( Delimiter ); return valueAsString; } catch ( Exception ) { fieldNeedsQuotes = false; return String.Empty; } }
IScaleDescriptorAssignment GetOrCreateScaleAssignment(string propertyName, PSPropertyInfo member) { using (_log.PushContext("GetOrCreateScaleAssignment [{0}]", propertyName)) { var scaleAssignment = (from s in Scales where StringComparer.InvariantCultureIgnoreCase.Equals(s.PropertyName, propertyName) select s).FirstOrDefault(); if (null == scaleAssignment && null == member) { return null; } if (null != scaleAssignment) { Scales.Add(new ScaleDescriptorAssignment {PropertyName = member.Name, Scale = scaleAssignment.Scale}); return scaleAssignment; } return AddDynamicScaleForProperty(member.Name); } }
/// <summary> /// Sets new value. /// </summary> /// <param name="info">Property info.</param> /// <param name="value">New value.</param> internal abstract void SetUserValue(PSPropertyInfo info, string value);
private bool RehydrateCimInstanceProperty(CimInstance cimInstance, PSPropertyInfo deserializedProperty, HashSet<string> namesOfModifiedProperties) { if (deserializedProperty.Name.Equals(RemotingConstants.ComputerNameNoteProperty, StringComparison.OrdinalIgnoreCase)) { string computerName = deserializedProperty.Value as string; if (computerName != null) { cimInstance.SetCimSessionComputerName(computerName); } return true; } CimProperty property = cimInstance.CimInstanceProperties[deserializedProperty.Name]; if (property == null) { return false; } object baseObject = deserializedProperty.Value; if (baseObject != null) { PSObject obj3 = PSObject.AsPSObject(baseObject); if (obj3.BaseObject is ArrayList) { Type type; object obj4; if ((obj3.InternalTypeNames == null) || (obj3.InternalTypeNames.Count == 0)) { return false; } string valueToConvert = Deserializer.MaskDeserializationPrefix(obj3.InternalTypeNames[0]); if (valueToConvert == null) { return false; } if (!LanguagePrimitives.TryConvertTo<Type>(valueToConvert, CultureInfo.InvariantCulture, out type)) { return false; } if (!type.IsArray) { return false; } if (!LanguagePrimitives.TryConvertTo(baseObject, type, CultureInfo.InvariantCulture, out obj4)) { return false; } obj3 = PSObject.AsPSObject(obj4); } baseObject = obj3.BaseObject; } try { property.Value = baseObject; if (!namesOfModifiedProperties.Contains(deserializedProperty.Name)) { property.IsValueModified = false; } } catch (FormatException) { return false; } catch (InvalidCastException) { return false; } catch (ArgumentException) { return false; } catch (CimException) { return false; } return true; }
internal static void SetPropertyFromTextUI(object target, PSPropertyInfo pi, string text) { bool isPSObject; object value; string type; if (pi.Value is PSObject && (pi.Value as PSObject).BaseObject != null) { isPSObject = true; type = (pi.Value as PSObject).BaseObject.GetType().FullName; } else { isPSObject = false; type = pi.TypeNameOfValue; } if (type == "System.Collections.ArrayList" || type.EndsWith("]", StringComparison.Ordinal)) { ArrayList lines = new ArrayList(); foreach (var line in FarNet.Works.Kit.SplitLines(text)) lines.Add(line); value = lines; } else { value = text; } if (isPSObject) value = PSObject.AsPSObject(value); try { pi.Value = value; MemberPanel.WhenMemberChanged(target); } catch (RuntimeException ex) { Far.Api.Message(ex.Message, "Setting property"); } }
private void WritePropertyWithNullValue( XmlWriter writer, PSPropertyInfo source, int depth) { WriteStartElement(writer, CustomSerializationStrings.Properties); WriteAttribute(writer, CustomSerializationStrings.NameAttribute, ((PSPropertyInfo)source).Name.ToString()); if (!_notypeinformation) WriteAttribute(writer, CustomSerializationStrings.TypeAttribute, ((PSPropertyInfo)source).TypeNameOfValue.ToString()); writer.WriteEndElement(); }
private string GetHelpProperty(string propertyName) { PSPropertyInfo property = this.deserializedRemoteHelp.Properties[propertyName]; return(property == null ? (string)null : property.Value as string); }
private static bool IsNumericType(PSPropertyInfo prop) { if( null == prop ) { return false; } var type = Type.GetType(prop.TypeNameOfValue, false, true); if (null == type) { return false; } double d; using (DefaultRunspaceManager.ForCurrentThread) { try { return Double.TryParse(prop.Value.ToString(), out d); } catch { } } return false; }
private static KeyValuePair<string, object> ConvertToKeyValuePair(PSPropertyInfo property) { string key = null; object value = null; try { key = property.Name; value = property.Value; } catch { } // hide or ignore errors reading values... because PowerShell does. Weird? return string.IsNullOrEmpty(key) ? new KeyValuePair<string, object>() : new KeyValuePair<string, object>(key, value ?? string.Empty); }
private bool IsPropertyValidForAxis(PSPropertyInfo prop, ChartAxisViewModel axis) { if( SeriesType == ChartSeriesType.Timeline ) { return axis.AxisType != ChartAxisType.CategoryX; } switch( axis.AxisType ) { case (ChartAxisType.NumericAngle): case( ChartAxisType.NumericRadius ): case( ChartAxisType.NumericX ): case( ChartAxisType.NumericY ): { return IsNumericType(prop); } //case( ChartAxisType.CategoryDateTimeX ): //case( ChartAxisType.CategoryX ): //case (ChartAxisType.CategoryAngle): default: return true; } }
internal override void SetUserValue(PSPropertyInfo info, string value) { try { A.SetPropertyValue(Explorer.ItemPath, info.Name, Converter.Parse(info, value)); WhenPropertyChanged(Explorer.ItemPath); } catch (RuntimeException ex) { A.Message(ex.Message); } }
private void WritePropertyWithNullValue(XmlWriter writer, PSPropertyInfo source, int depth) { WriteStartElement(writer, "Property"); WriteAttribute(writer, "Name", source.Name.ToString()); if (!this._notypeinformation) { WriteAttribute(writer, "Type", source.TypeNameOfValue.ToString()); } writer.WriteEndElement(); }
private CimClass RehydrateCimClass(PSPropertyInfo classMetadataProperty) { if ((classMetadataProperty == null) || (classMetadataProperty.Value == null)) { return null; } IEnumerable enumerable = LanguagePrimitives.GetEnumerable(classMetadataProperty.Value); if (enumerable == null) { return null; } Stack<KeyValuePair<CimClassSerializationId, CimClass>> stack = new Stack<KeyValuePair<CimClassSerializationId, CimClass>>(); CimClass parentClass = null; CimClass cimClassFromCache = null; foreach (object obj2 in enumerable) { parentClass = cimClassFromCache; if (obj2 == null) { return null; } PSObject obj3 = PSObject.AsPSObject(obj2); PSPropertyInfo info = obj3.InstanceMembers["Namespace"] as PSPropertyInfo; if (info == null) { return null; } string namespaceName = info.Value as string; PSPropertyInfo info2 = obj3.InstanceMembers["ClassName"] as PSPropertyInfo; if (info2 == null) { return null; } string className = info2.Value as string; PSPropertyInfo info3 = obj3.InstanceMembers["ServerName"] as PSPropertyInfo; if (info3 == null) { return null; } string computerName = info3.Value as string; PSPropertyInfo info4 = obj3.InstanceMembers["Hash"] as PSPropertyInfo; if (info4 == null) { return null; } object baseObject = info4.Value; if (baseObject == null) { return null; } if (baseObject is PSObject) { baseObject = ((PSObject) baseObject).BaseObject; } if (!(baseObject is int)) { return null; } int hashCode = (int) baseObject; CimClassSerializationId key = new CimClassSerializationId(className, namespaceName, computerName, hashCode); cimClassFromCache = this._context.cimClassSerializationIdCache.GetCimClassFromCache(key); if (cimClassFromCache == null) { PSPropertyInfo info5 = obj3.InstanceMembers["MiXml"] as PSPropertyInfo; if ((info5 == null) || (info5.Value == null)) { return null; } string s = info5.Value.ToString(); byte[] bytes = Encoding.Unicode.GetBytes(s); int offset = 0; try { cimClassFromCache = cimDeserializer.Value.DeserializeClass(bytes, ref offset, parentClass, computerName, namespaceName); stack.Push(new KeyValuePair<CimClassSerializationId, CimClass>(key, cimClassFromCache)); } catch (CimException) { return null; } } } foreach (KeyValuePair<CimClassSerializationId, CimClass> pair in stack) { this._context.cimClassSerializationIdCache.AddCimClassToCache(pair.Key, pair.Value); } return cimClassFromCache; }
private void CreateDynamicMemberProperty(ref PSPropertyInfo plotMember, string name, string proxyPropertyName) { if (String.IsNullOrEmpty(proxyPropertyName)) { return; } var pm = plotMember as PSScriptProperty; var script = String.Format("$this.'{0}' | foreach-object {{ {1} }}", proxyPropertyName, pm.GetterScript); plotMember = new PSScriptProperty(name, System.Management.Automation.ScriptBlock.Create(script)); }
public InvalidChartValueMemberException(ChartSeriesType seriesType, PSPropertyInfo prop, string valueMemberPath, string viewModelMemberName) : base(String.Format( "The value member [{0}] for the [{2}] of series type [{1}] is of an invalid type [{3}].", valueMemberPath, seriesType, viewModelMemberName, null != prop ? prop.TypeNameOfValue : "null" )) { SeriesType = seriesType; Property = prop; ValueMemberPath = valueMemberPath; }
public DynamicMemberDescriptor(PSPropertyInfo memberinfo, IScaleDescriptor scaleDescriptor, object indexValue) { _memberinfo = memberinfo; _scaleDescriptor = scaleDescriptor; _indexValue = indexValue; }
/// <summary> /// Override - Modify Parameters element in maml1 using the Parameters element from maml2. /// This will copy parameters from maml2 that are not present in maml1. /// </summary> internal static void OverrideParameters(PSObject maml1, PSObject maml2) { string[] parametersPath = new string[] { "Parameters", "Parameter" }; // Final collection of PSObjects. List <object> maml2items = new List <object>(); // Add maml2 first since we are prepending. // For maml2: Add as collection or single item. No-op if PSPropertyInfo propertyInfo2 = GetPropertyInfo(maml2, parametersPath); var array = propertyInfo2.Value as Array; if (array != null) { maml2items.AddRange(array as IEnumerable <object>); } else { maml2items.Add(PSObject.AsPSObject(propertyInfo2.Value)); } // Extend maml1 to make sure the property-path exists - since we'll be modifying it soon. EnsurePropertyInfoPathExists(maml1, parametersPath); // For maml1: Add as collection or single item. Do nothing if null or some other type. PSPropertyInfo propertyInfo1 = GetPropertyInfo(maml1, parametersPath); List <object> maml1items = new List <object>(); array = propertyInfo1.Value as Array; if (array != null) { maml1items.AddRange(array as IEnumerable <object>); } else { maml1items.Add(PSObject.AsPSObject(propertyInfo1.Value)); } // copy parameters from maml2 that are not present in maml1 for (int index = 0; index < maml2items.Count; index++) { PSObject m2paramObj = PSObject.AsPSObject(maml2items[index]); string param2Name = string.Empty; PSPropertyInfo m2propertyInfo = m2paramObj.Properties["Name"]; if (m2propertyInfo != null) { if (!LanguagePrimitives.TryConvertTo <string>(m2propertyInfo.Value, out param2Name)) { continue; } } bool isParamFoundInMaml1 = false; foreach (PSObject m1ParamObj in maml1items) { string param1Name = string.Empty; PSPropertyInfo m1PropertyInfo = m1ParamObj.Properties["Name"]; if (m1PropertyInfo != null) { if (!LanguagePrimitives.TryConvertTo <string>(m1PropertyInfo.Value, out param1Name)) { continue; } } if (param1Name.Equals(param2Name, StringComparison.OrdinalIgnoreCase)) { isParamFoundInMaml1 = true; } } if (!isParamFoundInMaml1) { maml1items.Add(maml2items[index]); } } // Now replace in maml1. If items.Count == 0 do nothing since Value is already null. if (maml1items.Count == 1) { propertyInfo1.Value = maml1items[0]; } else if (maml1items.Count >= 2) { propertyInfo1.Value = maml1items.ToArray(); } }
internal static object SafePropertyValue(PSPropertyInfo pi) { //! exceptions, e.g. exit code of running process try { return pi.Value; } catch (GetValueException e) { return string.Format(null, "<ERROR: {0}>", e.Message); } }
private void CheckAndAddProperty(PSPropertyInfo propertyInfo, Attribute[] attributes, ref PropertyDescriptorCollection returnValue) { using (typeDescriptor.TraceScope("Checking property \"{0}\".", propertyInfo.Name)) { // WriteOnly properties are not returned in TypeDescriptor.GetProperties, so we do the same. if (!propertyInfo.IsGettable) { typeDescriptor.WriteLine("Property \"{0}\" is write-only so it has been skipped.", propertyInfo.Name); return; } AttributeCollection propertyAttributes = null; Type propertyType = typeof(object); if (attributes != null && attributes.Length != 0) { PSProperty property = propertyInfo as PSProperty; if (property != null) { DotNetAdapter.PropertyCacheEntry propertyEntry = property.adapterData as DotNetAdapter.PropertyCacheEntry; if (propertyEntry == null) { typeDescriptor.WriteLine("Skipping attribute check for property \"{0}\" because it is an adapted property (not a .NET property).", property.Name); } else if (property.isDeserialized) { // At the moment we are not serializing attributes, so we can skip // the attribute check if the property is deserialized. typeDescriptor.WriteLine("Skipping attribute check for property \"{0}\" because it has been deserialized.", property.Name); } else { propertyType = propertyEntry.propertyType; propertyAttributes = propertyEntry.Attributes; foreach (Attribute attribute in attributes) { if (!propertyAttributes.Contains(attribute)) { typeDescriptor.WriteLine("Property \"{0}\" does not contain attribute \"{1}\" so it has been skipped.", property.Name, attribute); return; } } } } } if (propertyAttributes == null) { propertyAttributes = new AttributeCollection(); } typeDescriptor.WriteLine("Adding property \"{0}\".", propertyInfo.Name); PSObjectPropertyDescriptor propertyDescriptor = new PSObjectPropertyDescriptor(propertyInfo.Name, propertyType, !propertyInfo.IsSettable, propertyAttributes); propertyDescriptor.SettingValueException += this.SettingValueException; propertyDescriptor.GettingValueException += this.GettingValueException; returnValue.Add(propertyDescriptor); } }
public string PrintPsPropertyEmptyIfNull(PSPropertyInfo myOutput) { return myOutput != null && myOutput.Value != null ? myOutput.Value.ToString() : String.Empty; }
public DynamicMemberDescriptor( PSPropertyInfo memberinfo, IScaleDescriptor scaleDescriptor) : this(memberinfo, scaleDescriptor, null) { }
/// <summary> /// Initializes an instance of the VariableDetails class from /// the details contained in a PSPropertyInfo instance. /// </summary> /// <param name="psProperty"> /// The PSPropertyInfo instance from which variable details will be obtained. /// </param> public VariableDetails(PSPropertyInfo psProperty) : this(psProperty.Name, psProperty.Value) { }
GetToStringValueForProperty(PSPropertyInfo property) { Dbg.Assert(property != null, "Caller should validate the parameter"); string value = null; try { object temp = property.Value; if (temp != null) { value = temp.ToString(); } } //If we cannot read some value, treat it as null. catch (Exception ex) { UtilityCommon.CheckForSevereException(_cmdlet, ex); } return value; }
private void CheckAndAddProperty(PSPropertyInfo propertyInfo, Attribute[] attributes, ref PropertyDescriptorCollection returnValue) { using (typeDescriptor.TraceScope("Checking property \"{0}\".", propertyInfo.Name)) { // WriteOnly properties are not returned in TypeDescriptor.GetProperties, so we do the same. if (!propertyInfo.IsGettable) { typeDescriptor.WriteLine("Property \"{0}\" is write-only so it has been skipped.", propertyInfo.Name); return; } AttributeCollection propertyAttributes = null; Type propertyType = typeof(object); if (attributes != null && attributes.Length != 0) { PSProperty property = propertyInfo as PSProperty; if (property != null) { DotNetAdapter.PropertyCacheEntry propertyEntry = property.adapterData as DotNetAdapter.PropertyCacheEntry; if (propertyEntry == null) { typeDescriptor.WriteLine("Skipping attribute check for property \"{0}\" because it is an adapted property (not a .NET property).", property.Name); } else if (property.isDeserialized) { // At the moment we are not serializing attributes, so we can skip // the attribute check if the property is deserialized. typeDescriptor.WriteLine("Skipping attribute check for property \"{0}\" because it has been deserialized.", property.Name); } else { propertyType = propertyEntry.propertyType; propertyAttributes = propertyEntry.Attributes; foreach (Attribute attribute in attributes) { if (!propertyAttributes.Contains(attribute)) { typeDescriptor.WriteLine("Property \"{0}\" does not contain attribute \"{1}\" so it has been skipped.", property.Name, attribute); return; } } } } } if (propertyAttributes == null) { propertyAttributes = new AttributeCollection(); } typeDescriptor.WriteLine("Adding property \"{0}\".", propertyInfo.Name); PSObjectPropertyDescriptor propertyDescriptor = new PSObjectPropertyDescriptor(propertyInfo.Name, propertyType, !propertyInfo.IsSettable, propertyAttributes); propertyDescriptor.SettingValueException += this.SettingValueException; propertyDescriptor.GettingValueException += this.GettingValueException; returnValue.Add(propertyDescriptor); } }