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); } }
internal static System.Management.Automation.Signature GetSignature(string fileName, string fileContent) { System.Management.Automation.Signature signature = null; uint error = 0x80004005; Utils.CheckArgForNullOrEmpty(fileName, "fileName"); SecuritySupport.CheckIfFileExists(fileName); try { System.Management.Automation.Security.NativeMethods.WINTRUST_DATA wintrust_data; error = GetWinTrustData(fileName, fileContent, out wintrust_data); if (error != 0) { tracer.WriteLine("GetWinTrustData failed: {0:x}", new object[] { error }); } signature = GetSignatureFromWintrustData(fileName, error, wintrust_data); error = System.Management.Automation.Security.NativeMethods.DestroyWintrustDataStruct(wintrust_data); if (error != 0) { tracer.WriteLine("DestroyWinTrustDataStruct failed: {0:x}", new object[] { error }); } } catch (AccessViolationException) { signature = new System.Management.Automation.Signature(fileName, 0x800b0100); } return(signature); }
internal bool HasErrors() { bool flag = false; if ((this.accumulatedErrorObjects != null) && (this.accumulatedErrorObjects.Count > 0)) { flag = true; } tracer.WriteLine("result = {0}", new object[] { flag }); return(flag); }
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); } } }
/// <summary> /// Writes an object to the output. /// </summary> /// <param name="obj"> /// The object to be written. /// </param> /// <remarks> /// If streaming is on and the writeObjectHandler was specified then the object /// gets written to the writeObjectHandler. If streaming is on and the writeObjectHandler /// was not specified and the command object was specified, the object gets written to /// the WriteObject method of the command object. /// If streaming is off the object gets written to an accumulator collection. The collection /// of written object can be retrieved using the AccumulatedObjects method. /// </remarks> /// <exception cref="InvalidOperationException"> /// The CmdletProvider could not stream the results because no /// cmdlet was specified to stream the output through. /// </exception> /// <exception cref="PipelineStoppedException"> /// If the pipeline has been signaled for stopping but /// the provider calls this method. /// </exception> internal void WriteObject(object obj) { // Making sure to obey the StopProcessing by // throwing an exception anytime a provider tries // to WriteObject if (Stopping) { PipelineStoppedException stopPipeline = new PipelineStoppedException(); throw stopPipeline; } if (PassThru) { if (_command != null) { s_tracer.WriteLine("Writing to command pipeline"); // Since there was no writeObject handler use // the command WriteObject method. _command.WriteObject(obj); } else { // The flag was set for streaming but we have no where // to stream to. InvalidOperationException e = PSTraceSource.NewInvalidOperationException( SessionStateStrings.OutputStreamingNotEnabled); throw e; } } else { s_tracer.WriteLine("Writing to accumulated objects"); // Convert the object to a PSObject if it's not already // one. PSObject newObj = PSObject.AsPSObject(obj); // Since we are not streaming, just add the object to the accumulatedObjects _accumulatedObjects.Add(newObj); } } // WriteObject
private void LoadHelpFile(string helpFile, string helpFileIdentifier, string commandName, bool reportErrors) { Exception e = null; try { LoadHelpFile(helpFile, helpFileIdentifier); } catch (IOException ioException) { e = ioException; } catch (System.Security.SecurityException securityException) { e = securityException; } catch (XmlException xmlException) { e = xmlException; } catch (NotSupportedException notSupportedException) { e = notSupportedException; } catch (UnauthorizedAccessException unauthorizedAccessException) { e = unauthorizedAccessException; } catch (InvalidOperationException invalidOperationException) { e = invalidOperationException; } if (e != null) { s_tracer.WriteLine("Error occurred in PSClassHelpProvider {0}", e.Message); } if (reportErrors && (e != null)) { ReportHelpFileError(e, commandName, helpFile); } }
private string FindHelpFile(CmdletInfo cmdletInfo) { if (cmdletInfo == null) { throw PSTraceSource.NewArgumentNullException("cmdletInfo"); } string helpFile = cmdletInfo.HelpFile; if (string.IsNullOrEmpty(helpFile)) { if ((cmdletInfo.Module != null) && InitialSessionState.IsEngineModule(cmdletInfo.Module.Name)) { return(Path.Combine(cmdletInfo.Module.ModuleBase, Thread.CurrentThread.CurrentCulture.Name, engineModuleHelpFileCache[cmdletInfo.Module.Name])); } return(helpFile); } string file = helpFile; PSSnapInInfo pSSnapIn = cmdletInfo.PSSnapIn; Collection <string> searchPaths = new Collection <string>(); if (pSSnapIn != null) { file = Path.Combine(pSSnapIn.ApplicationBase, helpFile); } else if ((cmdletInfo.Module != null) && !string.IsNullOrEmpty(cmdletInfo.Module.Path)) { file = Path.Combine(cmdletInfo.Module.ModuleBase, helpFile); } else { searchPaths.Add(base.GetDefaultShellSearchPath()); searchPaths.Add(GetCmdletAssemblyPath(cmdletInfo)); } string str3 = MUIFileSearcher.LocateFile(file, searchPaths); if (string.IsNullOrEmpty(str3)) { tracer.WriteLine("Unable to load file {0}", new object[] { file }); } return(str3); }
private static Signature GetSignatureFromWinVerifyTrust(string fileName, string fileContent) { Signature signature = null; NativeMethods.WINTRUST_DATA wtd; DWORD error = Win32Errors.E_FAIL; if (fileContent == null) { Utils.CheckArgForNullOrEmpty(fileName, "fileName"); SecuritySupport.CheckIfFileExists(fileName); //SecurityUtils.CheckIfFileSmallerThan4Bytes(fileName); } try { error = GetWinTrustData(fileName, fileContent, out wtd); if (error != Win32Errors.NO_ERROR) { s_tracer.WriteLine("GetWinTrustData failed: {0:x}", error); } signature = GetSignatureFromWintrustData(fileName, error, wtd); error = NativeMethods.DestroyWintrustDataStruct(wtd); if (error != Win32Errors.NO_ERROR) { s_tracer.WriteLine("DestroyWinTrustDataStruct failed: {0:x}", error); } } catch (AccessViolationException) { signature = new Signature(fileName, Win32Errors.TRUST_E_NOSIGNATURE); } return(signature); }
/// <summary> /// Traces the virtual drive. /// </summary> internal void Trace() { s_tracer.WriteLine( "A drive was found:"); if (Name != null) { s_tracer.WriteLine( "\tName: {0}", Name); } if (Provider != null) { s_tracer.WriteLine( "\tProvider: {0}", Provider); } if (Root != null) { s_tracer.WriteLine( "\tRoot: {0}", Root); } if (CurrentLocation != null) { s_tracer.WriteLine( "\tCWD: {0}", CurrentLocation); } if (Description != null) { s_tracer.WriteLine( "\tDescription: {0}", Description); } }
internal void Trace() { tracer.WriteLine("A drive was found:", new object[0]); if (this.Name != null) { tracer.WriteLine("\tName: {0}", new object[] { this.Name }); } if (this.Provider != null) { tracer.WriteLine("\tProvider: {0}", new object[] { this.Provider }); } if (this.Root != null) { tracer.WriteLine("\tRoot: {0}", new object[] { this.Root }); } if (this.CurrentLocation != null) { tracer.WriteLine("\tCWD: {0}", new object[] { this.CurrentLocation }); } if (this.Description != null) { tracer.WriteLine("\tDescription: {0}", new object[] { this.Description }); } }
public bool MoveNext() { bool result = false; if (_justReset) { _justReset = false; if (!_patternEnumerator.MoveNext()) { s_tracer.TraceError("No patterns were specified"); return(false); } if (!_lookupPathsEnumerator.MoveNext()) { s_tracer.TraceError("No lookup paths were specified"); return(false); } GetNewDirectoryResults(_patternEnumerator.Current, _lookupPathsEnumerator.Current); } while (true) // while lookupPathsEnumerator is valid { while (true) // while patternEnumerator is valid { // Try moving to the next path in the current results if (!_currentDirectoryResultsEnumerator.MoveNext()) { s_tracer.WriteLine("Current directory results are invalid"); // Since a path was not found in the current result, // advance the pattern and try again if (!_patternEnumerator.MoveNext()) { s_tracer.WriteLine("Current patterns exhausted in current directory: {0}", _lookupPathsEnumerator.Current); break; } // Get the results of the next pattern GetNewDirectoryResults(_patternEnumerator.Current, _lookupPathsEnumerator.Current); } else { s_tracer.WriteLine("Next path found: {0}", _currentDirectoryResultsEnumerator.Current); result = true; break; } // Since we have reset the results, loop again to find the next result. } if (result) { break; } // Since the path was not found in the current results, and all patterns were exhausted, // advance the path and continue if (!_lookupPathsEnumerator.MoveNext()) { s_tracer.WriteLine("All lookup paths exhausted, no more matches can be found"); break; } // Reset the pattern enumerator and get new results using the new lookup path _patternEnumerator = _patterns.GetEnumerator(); if (!_patternEnumerator.MoveNext()) { s_tracer.WriteLine("All patterns exhausted, no more matches can be found"); break; } GetNewDirectoryResults(_patternEnumerator.Current, _lookupPathsEnumerator.Current); } return(result); }
public bool MoveNext() { bool flag = false; if (this.justReset) { this.justReset = false; if (!this.patternEnumerator.MoveNext()) { tracer.TraceError("No patterns were specified", new object[0]); return(false); } if (!this.lookupPathsEnumerator.MoveNext()) { tracer.TraceError("No lookup paths were specified", new object[0]); return(false); } this.GetNewDirectoryResults(this.patternEnumerator.Current, this.lookupPathsEnumerator.Current); } Label_0075: if (!this.currentDirectoryResultsEnumerator.MoveNext()) { tracer.WriteLine("Current directory results are invalid", new object[0]); if (!this.patternEnumerator.MoveNext()) { tracer.WriteLine("Current patterns exhausted in current directory: {0}", new object[] { this.lookupPathsEnumerator.Current }); goto Label_0118; } this.GetNewDirectoryResults(this.patternEnumerator.Current, this.lookupPathsEnumerator.Current); } else { tracer.WriteLine("Next path found: {0}", new object[] { this.currentDirectoryResultsEnumerator.Current }); flag = true; goto Label_0118; } if (!flag) { goto Label_0075; } Label_0118: if (!flag) { if (!this.lookupPathsEnumerator.MoveNext()) { tracer.WriteLine("All lookup paths exhausted, no more matches can be found", new object[0]); } else { this.patternEnumerator = this.patterns.GetEnumerator(); if (!this.patternEnumerator.MoveNext()) { tracer.WriteLine("All patterns exhausted, no more matches can be found", new object[0]); } else { this.GetNewDirectoryResults(this.patternEnumerator.Current, this.lookupPathsEnumerator.Current); if (!flag) { goto Label_0075; } } } } tracer.WriteLine("result = {0}", new object[] { flag }); return(flag); }
/// <summary> /// Reads the specified number of characters or a lines from the Stream. /// </summary> /// <param name="readCount"> /// If less than 1, then the entire Stream is read at once. If 1 or greater, then /// readCount is used to determine how many items (ie: lines, bytes, delimited tokens) /// to read per call. /// </param> /// <returns> /// An array of strings representing the character(s) or line(s) read from /// the Stream. /// </returns> public IList Read(long readCount) { s_tracer.WriteLine("blocks requested = {0}", readCount); ArrayList blocks = new ArrayList(); bool readToEnd = (readCount <= 0); bool waitChanges = false; if (_alreadyDetectEncoding && _reader.BaseStream.Position == 0) { Encoding curEncoding = _reader.CurrentEncoding; // Close the stream, and reopen the stream to make the BOM correctly processed. // The reader has already detected encoding, so if we don't reopen the stream, the BOM (if there is any) // will be treated as a regular character. // _stream.Dispose(); CreateStreams(_stream, curEncoding); _alreadyDetectEncoding = false; } try { for (long currentBlock = 0; (currentBlock < readCount) || (readToEnd); ++currentBlock) { if (_usingByteEncoding) { if (!ReadByteEncoded(waitChanges, blocks, false)) { break; } } else { if (_usingDelimiter || _isRawStream) { if (!ReadDelimited(waitChanges, blocks, false, _delimiter)) { break; } } else { if (!ReadByLine(waitChanges, blocks, false)) { break; } } } } s_tracer.WriteLine("blocks read = {0}", blocks.Count); } catch (Exception e) { if ((e is IOException) || (e is ArgumentException) || (e is System.Security.SecurityException) || (e is UnauthorizedAccessException) || (e is ArgumentNullException)) { // Exception contains specific message about the error occured and so no need for errordetails. _provider.WriteError(new ErrorRecord(e, "GetContentReaderIOError", ErrorCategory.ReadError, "System.IO.Stream")); return(null); } else { throw; } } return(blocks.ToArray()); }
internal Type GetInferredType(Type typeParameter) { Func <Type, bool> predicate = null; ICollection <Type> inferenceCandidates = this.typeParameterIndexToSetOfInferenceCandidates[typeParameter.GenericParameterPosition]; if ((inferenceCandidates != null) && inferenceCandidates.Any <Type>(t => t.Equals(typeof(LanguagePrimitives.Null)))) { Type type = inferenceCandidates.FirstOrDefault <Type>(t => t.IsValueType); if (type != null) { tracer.WriteLine("Cannot reconcile null and {0} (a value type)", new object[] { type }); inferenceCandidates = null; this.typeParameterIndexToSetOfInferenceCandidates[typeParameter.GenericParameterPosition] = null; } else { inferenceCandidates = (from t in inferenceCandidates where !t.Equals(typeof(LanguagePrimitives.Null)) select t).ToList <Type>(); if (inferenceCandidates.Count == 0) { inferenceCandidates = null; this.typeParameterIndexToSetOfInferenceCandidates[typeParameter.GenericParameterPosition] = null; } } } if ((inferenceCandidates != null) && (inferenceCandidates.Count > 1)) { if (predicate == null) { predicate = potentiallyCommonBaseClass => inferenceCandidates.All <Type>(delegate(Type otherCandidate) { if (!otherCandidate.Equals(potentiallyCommonBaseClass)) { return(potentiallyCommonBaseClass.IsAssignableFrom(otherCandidate)); } return(true); }); } Type item = inferenceCandidates.Where <Type>(predicate).FirstOrDefault <Type>(); if (item != null) { inferenceCandidates.Clear(); inferenceCandidates.Add(item); } else { tracer.WriteLine("Multiple unreconcilable inferences for type parameter {0}", new object[] { typeParameter }); inferenceCandidates = null; this.typeParameterIndexToSetOfInferenceCandidates[typeParameter.GenericParameterPosition] = null; } } if (inferenceCandidates == null) { tracer.WriteLine("Couldn't infer type parameter {0}", new object[] { typeParameter }); return(null); } return(inferenceCandidates.Single <Type>()); }
internal virtual bool BindParameter(CommandParameterInternal parameter, CompiledCommandParameter parameterMetadata, ParameterBindingFlags flags) { bool flag = false; bool flag2 = (flags & ParameterBindingFlags.ShouldCoerceType) != ParameterBindingFlags.None; if (parameter == null) { throw PSTraceSource.NewArgumentNullException("parameter"); } if (parameterMetadata == null) { throw PSTraceSource.NewArgumentNullException("parameterMetadata"); } using (bindingTracer.TraceScope("BIND arg [{0}] to parameter [{1}]", new object[] { parameter.ArgumentValue, parameterMetadata.Name })) { parameter.ParameterName = parameterMetadata.Name; object argumentValue = parameter.ArgumentValue; ScriptParameterBinder binder = this as ScriptParameterBinder; bool bindingScriptCmdlet = false; if (binder != null) { bindingScriptCmdlet = binder.Script.UsesCmdletBinding; } foreach (ArgumentTransformationAttribute attribute in parameterMetadata.ArgumentTransformationAttributes) { using (bindingTracer.TraceScope("Executing DATA GENERATION metadata: [{0}]", new object[] { attribute.GetType() })) { try { ArgumentTypeConverterAttribute attribute2 = attribute as ArgumentTypeConverterAttribute; if (attribute2 != null) { if (flag2) { argumentValue = attribute2.Transform(this.engine, argumentValue, true, bindingScriptCmdlet); } } else { argumentValue = attribute.Transform(this.engine, argumentValue); } bindingTracer.WriteLine("result returned from DATA GENERATION: {0}", new object[] { argumentValue }); } catch (Exception exception) { CommandProcessorBase.CheckForSevereException(exception); bindingTracer.WriteLine("ERROR: DATA GENERATION: {0}", new object[] { exception.Message }); ParameterBindingException exception2 = new ParameterBindingArgumentTransformationException(exception, ErrorCategory.InvalidData, this.InvocationInfo, this.GetErrorExtent(parameter), parameterMetadata.Name, parameterMetadata.Type, (argumentValue == null) ? null : argumentValue.GetType(), "ParameterBinderStrings", "ParameterArgumentTransformationError", new object[] { exception.Message }); throw exception2; } } } if (flag2) { argumentValue = this.CoerceTypeAsNeeded(parameter, parameterMetadata.Name, parameterMetadata.Type, parameterMetadata.CollectionTypeInformation, argumentValue); } else if (!this.ShouldContinueUncoercedBind(parameter, parameterMetadata, flags, ref argumentValue)) { goto Label_040E; } if ((parameterMetadata.PSTypeName != null) && (argumentValue != null)) { IEnumerable enumerable = LanguagePrimitives.GetEnumerable(argumentValue); if (enumerable != null) { foreach (object obj3 in enumerable) { this.ValidatePSTypeName(parameter, parameterMetadata, !flag2, obj3); } } else { this.ValidatePSTypeName(parameter, parameterMetadata, !flag2, argumentValue); } } if ((flags & ParameterBindingFlags.IsDefaultValue) == ParameterBindingFlags.None) { foreach (ValidateArgumentsAttribute attribute3 in parameterMetadata.ValidationAttributes) { using (bindingTracer.TraceScope("Executing VALIDATION metadata: [{0}]", new object[] { attribute3.GetType() })) { try { attribute3.InternalValidate(argumentValue, this.engine); } catch (Exception exception3) { CommandProcessorBase.CheckForSevereException(exception3); bindingTracer.WriteLine("ERROR: VALIDATION FAILED: {0}", new object[] { exception3.Message }); ParameterBindingValidationException exception4 = new ParameterBindingValidationException(exception3, ErrorCategory.InvalidData, this.InvocationInfo, this.GetErrorExtent(parameter), parameterMetadata.Name, parameterMetadata.Type, (argumentValue == null) ? null : argumentValue.GetType(), "ParameterBinderStrings", "ParameterArgumentValidationError", new object[] { exception3.Message }); throw exception4; } tracer.WriteLine("Validation attribute on {0} returned {1}.", new object[] { parameterMetadata.Name, flag }); } } if (IsParameterMandatory(parameterMetadata)) { this.ValidateNullOrEmptyArgument(parameter, parameterMetadata, parameterMetadata.Type, argumentValue, true); } } Exception innerException = null; try { this.BindParameter(parameter.ParameterName, argumentValue); flag = true; } catch (SetValueException exception6) { innerException = exception6; } if (innerException != null) { Type typeSpecified = (argumentValue == null) ? null : argumentValue.GetType(); ParameterBindingException exception7 = new ParameterBindingException(innerException, ErrorCategory.WriteError, this.InvocationInfo, this.GetErrorExtent(parameter), parameterMetadata.Name, parameterMetadata.Type, typeSpecified, "ParameterBinderStrings", "ParameterBindingFailed", new object[] { innerException.Message }); throw exception7; } Label_040E :; bindingTracer.WriteLine("BIND arg [{0}] to param [{1}] {2}", new object[] { argumentValue, parameter.ParameterName, flag ? "SUCCESSFUL" : "SKIPPED" }); if (flag) { if (this.RecordBoundParameters) { this.CommandLineParameters.Add(parameter.ParameterName, argumentValue); } MshCommandRuntime commandRuntime = this.Command.commandRuntime as MshCommandRuntime; if ((commandRuntime != null) && commandRuntime.LogPipelineExecutionDetail) { IEnumerable source = LanguagePrimitives.GetEnumerable(argumentValue); if (source != null) { string parameterValue = string.Join(", ", source.Cast <object>().ToArray <object>()); commandRuntime.PipelineProcessor.LogExecutionParameterBinding(this.InvocationInfo, parameter.ParameterName, parameterValue); } else { commandRuntime.PipelineProcessor.LogExecutionParameterBinding(this.InvocationInfo, parameter.ParameterName, (argumentValue == null) ? "" : argumentValue.ToString()); } } } return(flag); } }