public override object Transform(EngineIntrinsics engineIntrinsics, object inputData) { if (null == inputData ) { return null; } var typeName = inputData.ToString(); var re = new Regex(@"^\[[\w\.]+\]$"); if (!re.IsMatch( typeName )) { return inputData; } var results = engineIntrinsics.InvokeCommand.InvokeScript(typeName); if (! results.Any()) { return null; } var type = results.First().BaseObject as Type; if (null == type) { throw new ArgumentException( String.Format( "The string specified '{0}' could not be interpreted as a valid type name. Please ensure you have loaded the assembly containing the type into your PowerShell session prior to calling this command.", inputData ) ); } return type; }
protected override void Validate(object arguments, EngineIntrinsics engineIntrinsics) { if (!Uri.IsWellFormedUriString(arguments.ToString(), UriKind.Absolute)) { throw new ValidationMetadataException("{0} is not a valid uri.".format(arguments.ToString())); } }
protected override void Validate(object arguments, EngineIntrinsics engineIntrinsics) { IEnumerable enumerable = null; IEnumerator enumerator = null; if ((arguments == null) || (arguments == AutomationNull.Value)) { throw new ValidationMetadataException("ArgumentIsNull", null, Metadata.ValidateNotNullFailure, new object[0]); } enumerable = arguments as IEnumerable; if (enumerable != null) { foreach (object obj2 in enumerable) { if ((obj2 == null) || (obj2 == AutomationNull.Value)) { throw new ValidationMetadataException("ArgumentIsNull", null, Metadata.ValidateNotNullCollectionFailure, new object[0]); } } } else { enumerator = arguments as IEnumerator; if (enumerator != null) { while (enumerator.MoveNext()) { if ((enumerator.Current == null) || (enumerator.Current == AutomationNull.Value)) { throw new ValidationMetadataException("ArgumentIsNull", null, Metadata.ValidateNotNullCollectionFailure, new object[0]); } } } } }
protected override void Validate(object arguments, EngineIntrinsics engineIntrinsics) { // Null object test if (arguments == null) { throw new ValidationMetadataException("Parameter arguments can not be empty or null."); } // String test if (String.IsNullOrEmpty(arguments as String)) { throw new ValidationMetadataException("Parameter arguments can not be empty or null."); } // Collections test IEnumerable collection = arguments as IEnumerable; if (collection != null) { object obj = collection.GetEnumerator().Current; if (obj == null) { throw new ValidationMetadataException("Parameter arguments can not be empty or null."); } } }
protected override void Validate(object arguments, EngineIntrinsics engineIntrinsics) { if (arguments == null || arguments == AutomationNull.Value) { return; } else { object[] objArray = arguments as object[]; if (objArray != null) { object[] objArray1 = objArray; int num = 0; while (num < (int)objArray1.Length) { object obj = objArray1[num]; if ((obj == null || obj == AutomationNull.Value) && (int)objArray.Length > 1) { throw new ValidationMetadataException(string.Format(CultureInfo.CurrentCulture, StringResources.InvalidNullValue, new object[0])); } else { num++; } } return; } else { return; } } }
protected override void Validate(object arguments, EngineIntrinsics engineIntrinsics) { if (arguments == null || arguments == AutomationNull.Value) { return; } else { IEnumerable enumerable = arguments as IEnumerable; if (enumerable != null) { HashSet<object> objs = new HashSet<object>(); foreach (object obj in enumerable) { if (!objs.Contains(obj)) { objs.Add(obj); } else { object[] str = new object[1]; str[0] = obj.ToString(); throw new ValidationMetadataException(string.Format(CultureInfo.CurrentCulture, StringResources.DuplicateValuesSpecified, str)); } } return; } else { return; } } }
protected override void Validate(object arguments, EngineIntrinsics engineIntrinsics) { if (arguments == null || arguments == AutomationNull.Value) { return; } else { int? nullable = (int?)(arguments as int?); if (nullable.HasValue) { if (nullable.Value >= this._minRange) { if (nullable.Value > this._maxRange) { object[] objArray = new object[2]; objArray[0] = nullable; objArray[1] = this._maxRange; throw new ValidationMetadataException(string.Format(CultureInfo.CurrentCulture, StringResources.ValidateRangeGreaterThanMaxValue, objArray)); } } else { object[] objArray1 = new object[2]; objArray1[0] = nullable; objArray1[1] = this._minRange; throw new ValidationMetadataException(string.Format(CultureInfo.CurrentCulture, StringResources.ValidateRangeLessThanMinValue, objArray1)); } } return; } }
public override object Transform(EngineIntrinsics engineIntrinsics, object inputData) { if (null == inputData) { return null; } var pso = PSObject.AsPSObject(inputData); FileInfo file = pso.BaseObject as FileInfo; if (null == file) { string filePath = pso.BaseObject as string; if (null != filePath) { file = new FileInfo(filePath); } } if (null == file || ! file.Exists ) { return inputData; } var results = engineIntrinsics.InvokeCommand.InvokeScript("$input | get-packageXml", false, PipelineResultTypes.None, new ArrayList{inputData}, null); return results.FirstOrDefault(); }
public override object Transform(EngineIntrinsics engineIntrinsics, object inputData) { if (null == inputData) { return inputData; } var inputObject = inputData.ToPSObject().BaseObject; if (!(inputObject is ScriptBlock)) { return inputData; } var script = inputObject as ScriptBlock; var dataSource = new PowerShellDataSource { Name = script.ToString(), ScriptBlock = script.ToString(), Trigger = new ImmediateTrigger() }; //TODO: add datasource to datasources: drive var drive = engineIntrinsics.InvokeCommand.InvokeScript("get-psdrive datasources") as IDriveOf<IPowerShellDataSource>; drive.Add(dataSource); return dataSource; }
/// <summary> /// Validates that a variable name is valid with or without optional append character "+". /// </summary> /// <param name="arguments">The arguments to validate.</param> /// <param name="engineIntrinsics"><see cref="EngineIntrinsics"/> for additional information.</param> /// <exception cref="ValidationMetadataException">The variable name is invalid.</exception> protected override void Validate(object arguments, EngineIntrinsics engineIntrinsics) { if (!this.Validate(arguments)) { throw new ValidationMetadataException(Properties.Resources.Error_InvalidVariableName); } }
protected override void Validate(object arguments, EngineIntrinsics engineIntrinsics) { int _total = 0; if (arguments != null) { IEnumerable _collection = arguments as IEnumerable; if (_collection != null) { while (_collection.GetEnumerator().MoveNext()) { _total++; } } else _total = 1; } if (_total < MinLength) { throw new ValidationMetadataException("Argument requires minimum of " + MinLength + " values."); } if (_total > MaxLength) { throw new ValidationMetadataException("Argument requires maximum of " + MaxLength + " values."); } }
public override object Transform(EngineIntrinsics engineIntrinsics, object inputData) { var enumerable = inputData as IEnumerable<object> ?? new[] { inputData }; return enumerable.Select( inputElement => _typeTransformationAttribute.Transform(engineIntrinsics, inputElement) ).ToArray(); }
protected override void Validate(object arguments, EngineIntrinsics engineIntrinsics) { var webAppName = arguments as string; if (CmdletHelpers.IsDeploymentSlot(webAppName)) { throw new ValidationMetadataException(string.Format("Specified resource '{0}' is a non-production web app slot. Please use the AzureRMWebAppSlot cmdlets to manage this resource", webAppName)); } }
protected override void Validate(object arguments, EngineIntrinsics engineIntrinsics) { Version version = arguments as Version; if ((version == null) || !PSVersionInfo.IsValidPSVersion(version)) { throw new ValidationMetadataException("InvalidPSVersion", null, Metadata.ValidateVersionFailure, new object[] { arguments }); } }
internal ParameterBinderBase(System.Management.Automation.InvocationInfo invocationInfo, System.Management.Automation.ExecutionContext context, InternalCommand command) { this.RecordBoundParameters = true; bindingTracer.ShowHeaders = false; this.command = command; this.invocationInfo = invocationInfo; this.context = context; this.engine = context.EngineIntrinsics; }
public override object Transform(EngineIntrinsics engineIntrinsics, object inputData) { string str; if (!LanguagePrimitives.TryConvertTo<string>(inputData, out str) || (((!string.Equals(str, "unknown", StringComparison.OrdinalIgnoreCase) && !string.Equals(str, "string", StringComparison.OrdinalIgnoreCase)) && (!string.Equals(str, "unicode", StringComparison.OrdinalIgnoreCase) && !string.Equals(str, "bigendianunicode", StringComparison.OrdinalIgnoreCase))) && (((!string.Equals(str, "utf8", StringComparison.OrdinalIgnoreCase) && !string.Equals(str, "utf7", StringComparison.OrdinalIgnoreCase)) && (!string.Equals(str, "utf32", StringComparison.OrdinalIgnoreCase) && !string.Equals(str, "ascii", StringComparison.OrdinalIgnoreCase))) && (!string.Equals(str, "default", StringComparison.OrdinalIgnoreCase) && !string.Equals(str, "oem", StringComparison.OrdinalIgnoreCase))))) { return inputData; } return EncodingConversion.Convert(null, str); }
protected override void Validate(object arguments, EngineIntrinsics engineIntrinsics) { int count = 0; if ((arguments == null) || (arguments == AutomationNull.Value)) { count = 0; } else { IList list = arguments as IList; if (list != null) { count = (int) list.Count; } else { ICollection is2 = arguments as ICollection; if (is2 != null) { count = (int) is2.Count; } else { IEnumerable enumerable = arguments as IEnumerable; if (enumerable != null) { IEnumerator enumerator2 = enumerable.GetEnumerator(); while (enumerator2.MoveNext()) { count++; } } else { IEnumerator enumerator = arguments as IEnumerator; if (enumerator == null) { throw new ValidationMetadataException("NotAnArrayParameter", null, Metadata.ValidateCountNotInArray, new object[0]); } while (enumerator.MoveNext()) { count++; } } } } } if (count < this.minLength) { throw new ValidationMetadataException("ValidateCountSmallerThanMin", null, Metadata.ValidateCountMinLengthFailure, new object[] { this.minLength, count }); } if (count > this.maxLength) { throw new ValidationMetadataException("ValidateCountGreaterThanMax", null, Metadata.ValidateCountMaxLengthFailure, new object[] { this.maxLength, count }); } }
protected override void Validate(object arguments, EngineIntrinsics engineIntrinsics) { var serverFarm = arguments as ServerFarmWithRichSku; if (serverFarm == null) { throw new ValidationMetadataException("Argument 'ServerFarm' must be of type Microsoft.Azure.Management.WebSites.Models.ServerFarmWithRichSku"); } ValidateSku(serverFarm.Sku); }
public void Begin(bool expectInput, EngineIntrinsics contextToRedirectTo) { if (contextToRedirectTo == null) { throw new ArgumentNullException("contextToRedirectTo"); } CommandProcessorBase currentCommandProcessor = contextToRedirectTo.SessionState.Internal.ExecutionContext.CurrentCommandProcessor; ICommandRuntime commandRuntime = (currentCommandProcessor == null) ? null : currentCommandProcessor.CommandRuntime; this.Begin(expectInput, commandRuntime); }
/// <summary> /// Transforms a string or integer to an <see cref="System.Text.Encoding"/>. /// </summary> /// <param name="engineIntrinsics">Provides access to the APIs for managing the transformation context.</param> /// <param name="inputData">The parameter argument that is to be transformed.</param> /// <returns>The transformed object.</returns> public override object Transform(EngineIntrinsics engineIntrinsics, object inputData) { if (null != inputData) { var converter = new EncodingConverter(); if (converter.CanConvertFrom(inputData.GetType())) { return converter.ConvertFrom(inputData); } } return inputData; }
protected override void Validate(object arguments, EngineIntrinsics engineIntrinsics) { if (arguments == null) { throw new ValidationMetadataException("Specify a parameter of type 'System.Guid' and try again."); } Guid param = (Guid)arguments; if (param == Guid.Empty) { throw new ValidationMetadataException("Specify a non empty value of type 'System.Guid' and try again."); } }
public override object Transform(EngineIntrinsics engineIntrinsics, object inputData) { if (null == inputData) { inputData = "."; } var path = inputData.ToString(); var drive = MetadataHelpers.GetEntityDriveFromPSPath(engineIntrinsics.SessionState.Path, path); return drive; }
protected override void Validate(object arguments, EngineIntrinsics engineIntrinsics) { string str = arguments as string; if (string.IsNullOrEmpty(str)) { throw new PSArgumentNullException(); } if (!File.Exists(str)) { throw new PSArgumentException("File not found"); } }
public override object Transform(EngineIntrinsics engineIntrinsics, object inputData) { if (null == inputData || typeof(string) != inputData.GetType()) { return inputData; } var path = inputData.ToString(); var entity = MetadataHelpers.GetEntityFromPSPath(engineIntrinsics, path); return entity ?? inputData; }
/// <summary> /// Check against legal values. /// </summary> /// <param name="arguments"></param> /// <param name="engineIntrinsics"></param> protected override void Validate(object arguments, EngineIntrinsics engineIntrinsics) { var s = arguments as string; if (s == null) { throw new ValidationMetadataException("Argument is not a string."); } if (!_validLocations.Contains(s)) { var err = _validLocations.Aggregate(new StringBuilder(), (bld, loc) => bld.Append($" {loc}")); throw new ValidationMetadataException($"Illegal value for Location - possible values:{err.ToString()}"); } }
public override object Transform(EngineIntrinsics engineIntrinsics, object inputData) { if (null == inputData) { return null; } var inputType = inputData.ToPSObject().BaseObject.GetType(); if( inputType.IsAssignableFrom( typeof( short )) ) { return TimeSpan.FromMilliseconds((double) inputData); } if (typeof(string) == inputType) { TimeSpan result = TimeSpan.MinValue; var s = inputData.ToString(); if( TimeSpan.TryParse( s, out result ) ) { return result; } Regex re = new Regex(@"(?<n>[\.0-9]+)((?<ticks>t.*)|(?<milliseconds>ms.*)|(?<seconds>s.*)|(?<minutes>m.*)|(?<hours>h.*)||(?<days>d.*))", RegexOptions.IgnoreCase | RegexOptions.Singleline); var match = re.Match(s); if( match.Success ) { var l = match.Groups["l"].Value; var n = Double.Parse(match.Groups["n"].Value); var map = new Dictionary<string, Func<double,TimeSpan>> { {"milliseconds", d => TimeSpan.FromMilliseconds(d)}, {"seconds", d => TimeSpan.FromSeconds(d)}, {"minutes", d => TimeSpan.FromMinutes(d)}, {"hours", d => TimeSpan.FromHours(d)}, {"days", d => TimeSpan.FromDays(d)}, {"ticks", d => TimeSpan.FromTicks((int) d)} }; foreach( var pair in map ) { if( match.Groups[pair.Key].Success) { return pair.Value(n); } } } } return inputData; }
public CmdletParameterBinder(CmdletInfo cmdletInfo, Cmdlet cmdlet) { _cmdletInfo = cmdletInfo; _cmdlet = cmdlet; _defaultValues = new Dictionary<MemberInfo, object>(); _boundParameters = new Collection<MemberInfo>(); _candidateParameterSets = _cmdletInfo.ParameterSets.ToList(); _commandLineValuesBackup = new Dictionary<MemberInfo, object>(); _activeSet = null; _defaultSet = null; _hasDefaultSet = true; _commonParameters = (from parameter in CommonCmdletParameters.CommonParameterSetInfo.Parameters select parameter.MemberInfo).ToList(); _engineIntrinsics = new EngineIntrinsics(_cmdlet.ExecutionContext); }
public override object Transform(EngineIntrinsics engineIntrinsics, object inputData) { var results = engineIntrinsics.InvokeCommand.InvokeScript( engineIntrinsics.SessionState, _script, inputData ); if( null == results || 0 == results.Count ) { return inputData; } return results[0]; }
public CmdletParameterBinder(CmdletInfo cmdletInfo, Cmdlet cmdlet) { _cmdletInfo = cmdletInfo; _cmdlet = cmdlet; _defaultValues = new Dictionary<MemberInfo, object>(); _boundParameters = new Collection<MemberInfo>(); _candidateParameterSets = _cmdletInfo.ParameterSets.ToList(); _commandLineValuesBackup = new Dictionary<MemberInfo, object>(); _activeSet = null; _defaultSet = null; _hasDefaultSet = true; _bindDestinationLookup = new Dictionary<MemberInfo, object>(); _engineIntrinsics = new EngineIntrinsics(_cmdlet.ExecutionContext); // make sure common parameters are set in the CommonParameter member object, not the cmdlet itself AddBindDestionations(CommonCmdletParameters.ParameterDiscovery, _cmdlet.CommonParameters); }
object TransformItem( EngineIntrinsics engineIntrinsics, object inputData ) { var inputObject = inputData.ToPSObject().BaseObject; var scriptBlock = inputObject as ScriptBlock; if (null == scriptBlock) { return inputData; } scriptBlock = ScriptBlock.Create( "if( -not($_) ){ $_ = $this; } " + scriptBlock ); var property = new PSScriptProperty( "_" + Guid.NewGuid().ToString("N"), scriptBlock); return property; }
protected abstract void Validate(object arguments, EngineIntrinsics engineIntrinsics);
public abstract object Transform(EngineIntrinsics engineIntrinsics, object inputData);
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; } PSReference reference = temp as PSReference; if (reference == null) { 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 of Suspend is not supported as a preference variable. We can only block "Suspend" // during variable assignment (here) - "Ignore" is blocked during variable retrieval. if (_convertTypes[i] == typeof(ActionPreference)) { ActionPreference resultPreference = (ActionPreference)result; if (resultPreference == ActionPreference.Suspend) { throw new PSInvalidCastException("InvalidActionPreference", null, ErrorPackage.UnsupportedPreferenceVariable, resultPreference); } } } } } catch (PSInvalidCastException e) { throw new ArgumentTransformationMetadataException(e.Message, e); } return(result); }
public override object Transform(EngineIntrinsics engineIntrinsics, object inputData) { return(Transform(engineIntrinsics, inputData, false, false)); }
// internals internal void InternalValidate(object o, EngineIntrinsics engineIntrinsics) { Validate(o, engineIntrinsics); }