/// <summary> /// Seeks to the end of the writer stream in each of the writers in the /// content holders. /// </summary> /// /// <param name="contentHolders"> /// The content holders that contain the writers to be moved. /// </param> /// /// <exception cref="ProviderInvocationException"> /// If calling Seek on the content writer throws an exception. /// </exception> /// internal override void SeekContentPosition(List<ContentHolder> contentHolders) { foreach (ContentHolder holder in contentHolders) { if (holder.Writer != null) { try { holder.Writer.Seek(0, System.IO.SeekOrigin.End); } catch (Exception e) // Catch-all OK, 3rd party callout { CommandsCommon.CheckForSevereException(this, e); ProviderInvocationException providerException = new ProviderInvocationException( "ProviderSeekError", SessionStateStrings.ProviderSeekError, holder.PathInfo.Provider, holder.PathInfo.Path, e); // Log a provider health event MshLog.LogProviderHealthEvent( this.Context, holder.PathInfo.Provider.Name, providerException, Severity.Warning); throw providerException; } } } } // SeekContentPosition
internal CmdletProviderInvocationException( ProviderInvocationException innerException, InvocationInfo myInvocation) : base(CmdletProviderInvocationException.GetInnerException((Exception)innerException), myInvocation) { this._providerInvocationException = innerException != null ? innerException : throw new ArgumentNullException(nameof(innerException)); }
/// <summary> /// Constructs a new instance of a ProviderInvocationException /// using the specified data /// </summary> /// /// <param name="resourceId"> /// The resource ID to use as the format message for the error. /// </param> /// /// <param name="resourceStr"> /// This is the message template string. /// </param> /// /// <param name="provider"> /// The provider information used when formatting the error message. /// </param> /// /// <param name="path"> /// The path used when formatting the error message. /// </param> /// /// <param name="e"> /// The exception that was thrown by the provider. This will be set as /// the ProviderInvocationException's InnerException and the message will /// be used when formatting the error message. /// </param> /// /// <param name="useInnerExceptionErrorMessage"> /// If true, the error record from the inner exception will be used if it contains one. /// If false, the error message specified by the resourceId will be used. /// </param> /// /// <returns> /// A new instance of a ProviderInvocationException. /// </returns> /// /// <exception cref="ProviderInvocationException"> /// Wraps <paramref name="e"/> in a ProviderInvocationException /// and then throws it. /// </exception> /// internal ProviderInvocationException NewProviderInvocationException( string resourceId, string resourceStr, ProviderInfo provider, string path, Exception e, bool useInnerExceptionErrorMessage) { // If the innerException was itself thrown by // ProviderBase.ThrowTerminatingError, it is already a // ProviderInvocationException, and we don't want to // re-wrap it. ProviderInvocationException pie = e as ProviderInvocationException; if (null != pie) { pie._providerInfo = provider; return(pie); } pie = new ProviderInvocationException(resourceId, resourceStr, provider, path, e, useInnerExceptionErrorMessage); // Log a provider health event MshLog.LogProviderHealthEvent( ExecutionContext, provider.Name, pie, Severity.Warning); return(pie); }
/// <summary> /// Instantiates a new instance of the CmdletProviderInvocationException class /// </summary> /// <param name="innerException">wrapped exception</param> /// <param name="myInvocation"> /// identity of cmdlet, null is unknown /// </param> /// <returns>constructed object</returns> internal CmdletProviderInvocationException( ProviderInvocationException innerException, InvocationInfo myInvocation) : base(GetInnerException(innerException), myInvocation) { if (null == innerException) { throw new ArgumentNullException("innerException"); } _providerInvocationException = innerException; }
internal PipelineStoppedException ManageInvocationException(Exception e) { PipelineStoppedException exception4; try { if (this.Command != null) { ProviderInvocationException innerException = e as ProviderInvocationException; if (innerException != null) { e = new CmdletProviderInvocationException(innerException, this.Command.MyInvocation); } else if (((!(e is PipelineStoppedException) && !(e is CmdletInvocationException)) && (!(e is ActionPreferenceStopException) && !(e is HaltCommandException))) && (!(e is FlowControlException) && !(e is ScriptCallDepthException))) { RuntimeException exception2 = e as RuntimeException; if ((exception2 == null) || !exception2.WasThrownFromThrowStatement) { e = new CmdletInvocationException(e, this.Command.MyInvocation); } } if (this.commandRuntime.UseTransaction != 0) { bool flag = false; for (Exception exception3 = e; exception3 != null; exception3 = exception3.InnerException) { if (exception3 is TimeoutException) { flag = true; break; } } if (flag) { ErrorRecord errorRecord = new ErrorRecord(new InvalidOperationException(TransactionStrings.TransactionTimedOut), "TRANSACTION_TIMEOUT", ErrorCategory.InvalidOperation, e); errorRecord.SetInvocationInfo(this.Command.MyInvocation); e = new CmdletInvocationException(errorRecord); } if (this._context.TransactionManager.HasTransaction && (this._context.TransactionManager.RollbackPreference != RollbackSeverity.Never)) { this.Context.TransactionManager.Rollback(true); } } return((PipelineStoppedException)this.commandRuntime.ManageException(e)); } exception4 = new PipelineStoppedException(); } catch (Exception) { throw; } return(exception4); }
/// <summary> /// If there are any errors accumulated, the first error is thrown. /// </summary> /// <param name="wrapExceptionInProviderException"> /// If true, the error will be wrapped in a ProviderInvocationException before /// being thrown. If false, the error will be thrown as is. /// </param> /// <exception cref="ProviderInvocationException"> /// If <paramref name="wrapExceptionInProviderException"/> is true, the /// first exception that was written to the error pipeline by a CmdletProvider /// is wrapped and thrown. /// </exception> /// <exception> /// If <paramref name="wrapExceptionInProviderException"/> is false, /// the first exception that was written to the error pipeline by a CmdletProvider /// is thrown. /// </exception> internal void ThrowFirstErrorOrDoNothing(bool wrapExceptionInProviderException) { if (HasErrors()) { Collection <ErrorRecord> errors = GetAccumulatedErrorObjects(); if (errors != null && errors.Count > 0) { // Throw the first exception if (wrapExceptionInProviderException) { ProviderInfo providerInfo = null; if (this.ProviderInstance != null) { providerInfo = this.ProviderInstance.ProviderInfo; } ProviderInvocationException e = new ProviderInvocationException( providerInfo, errors[0]); // Log a provider health event MshLog.LogProviderHealthEvent( this.ExecutionContext, providerInfo != null ? providerInfo.Name : "unknown provider", e, Severity.Warning); throw e; } else { throw errors[0].Exception; } } } }
internal override void SeekContentPosition(List<ContentCommandBase.ContentHolder> contentHolders) { foreach (ContentCommandBase.ContentHolder contentHolder in contentHolders) { if (contentHolder.Writer == null) { continue; } try { contentHolder.Writer.Seek((long)0, SeekOrigin.End); } catch (Exception exception1) { Exception exception = exception1; CommandsCommon.CheckForSevereException(this, exception); ProviderInvocationException providerInvocationException = new ProviderInvocationException("ProviderSeekError", SessionStateStrings.ProviderSeekError, contentHolder.PathInfo.Provider, contentHolder.PathInfo.Path, exception); MshLog.LogProviderHealthEvent(base.Context, contentHolder.PathInfo.Provider.Name, providerInvocationException, Severity.Warning); throw providerInvocationException; } } }
internal void ThrowFirstErrorOrDoNothing(bool wrapExceptionInProviderException) { if (this.HasErrors()) { Collection <ErrorRecord> accumulatedErrorObjects = this.GetAccumulatedErrorObjects(); if ((accumulatedErrorObjects != null) && (accumulatedErrorObjects.Count > 0)) { if (!wrapExceptionInProviderException) { throw accumulatedErrorObjects[0].Exception; } ProviderInfo provider = null; if (this.ProviderInstance != null) { provider = this.ProviderInstance.ProviderInfo; } ProviderInvocationException exception = new ProviderInvocationException(provider, accumulatedErrorObjects[0]); MshLog.LogProviderHealthEvent(this.ExecutionContext, (provider != null) ? provider.Name : "unknown provider", exception, Severity.Warning); throw exception; } } }
protected CmdletProviderInvocationException(SerializationInfo info, StreamingContext context) : base(info, context) { ProviderInvocationException = base.InnerException as ProviderInvocationException; }
public CmdletProviderInvocationException(string message, Exception innerException) : base(message, innerException) { ProviderInvocationException = base.InnerException as ProviderInvocationException; }
/// <summary> /// Looks up the specified variable and returns the context under which /// the variable was found as well as the variable itself. /// </summary> /// /// <param name="variablePath"> /// The VariablePath helper for the variable. /// </param> /// /// <param name="scope"> /// The scope the variable was found in. Null if the variable wasn't found. /// </param> /// /// <param name="context"> /// Returns the context under which the variable was found. The context will /// have the drive data already set. This will be null if the variable was /// not found. /// </param> /// /// <param name="origin"> /// The origin of the caller of this API /// </param> /// /// <returns> /// The variable if it was found or null if it was not. /// </returns> /// /// <remarks> /// The <paramref name="variablePath" /> is first parsed to see if it contains a drive /// specifier or special scope. If a special scope is found ("LOCAL" or "GLOBAL") /// then only that scope is searched for the variable. If any other drive specifier /// is found the lookup goes in the following order. /// - current scope /// - each consecutive parent scope until the variable is found. /// - global scope /// </remarks> /// /// <exception cref="ArgumentNullException"> /// If <paramref name="variablePath"/> is null. /// </exception> /// /// <exception cref="ProviderNotFoundException"> /// If the <paramref name="variablePath"/> refers to a provider that could not be found. /// </exception> /// /// <exception cref="DriveNotFoundException"> /// If the <paramref name="variablePath"/> refers to a drive that could not be found. /// </exception> /// /// <exception cref="NotSupportedException"> /// If the provider that the <paramref name="variablePath"/> refers to does /// not support this operation. /// </exception> /// /// <exception cref="ProviderInvocationException"> /// If the provider threw an exception. /// </exception> /// #pragma warning disable 0162 internal object GetVariableValueFromProvider( VariablePath variablePath, out CmdletProviderContext context, out SessionStateScope scope, CommandOrigin origin) { scope = null; if (variablePath == null) { throw PSTraceSource.NewArgumentNullException("variablePath"); } Dbg.Diagnostics.Assert( !variablePath.IsVariable, "This method can only be used to retrieve provider content"); context = null; DriveScopeItemSearcher searcher = new DriveScopeItemSearcher( this, variablePath); object result = null; do // false loop { if (!searcher.MoveNext()) { break; } PSDriveInfo drive = ((IEnumerator<PSDriveInfo>)searcher).Current; if (drive == null) { break; } // Create a new CmdletProviderContext and set the drive data context = new CmdletProviderContext(this.ExecutionContext, origin); context.Drive = drive; #if true // PSVariable get/set is the get/set of content in the provider Collection<IContentReader> readers = null; try { readers = GetContentReader(new string[] { variablePath.QualifiedName }, context); } // If the item is not found we just return null like the normal // variable semantics. catch (ItemNotFoundException) { break; } catch (DriveNotFoundException) { break; } catch (ProviderNotFoundException) { break; } catch (NotImplementedException notImplemented) { // First get the provider for the path. ProviderInfo providerInfo = null; string unused = this.Globber.GetProviderPath(variablePath.QualifiedName, out providerInfo); throw NewProviderInvocationException( "ProviderCannotBeUsedAsVariable", SessionStateStrings.ProviderCannotBeUsedAsVariable, providerInfo, variablePath.QualifiedName, notImplemented, false); } catch (NotSupportedException notSupported) { // First get the provider for the path. ProviderInfo providerInfo = null; string unused = this.Globber.GetProviderPath(variablePath.QualifiedName, out providerInfo); throw NewProviderInvocationException( "ProviderCannotBeUsedAsVariable", SessionStateStrings.ProviderCannotBeUsedAsVariable, providerInfo, variablePath.QualifiedName, notSupported, false); } if (readers == null || readers.Count == 0) { // The drive was found but the path was wrong or something so return null. // We don't want to continue searching if the provider didn't support content // or the path wasn't found. break; } if (readers.Count > 1) { // Since more than one path was resolved, this is an error. //Before throwing exception. Close the readers to avoid sharing violation. foreach (IContentReader r in readers) { r.Close(); } PSArgumentException argException = PSTraceSource.NewArgumentException( "path", SessionStateStrings.VariablePathResolvedToMultiple, variablePath.QualifiedName); // First get the provider for the path. ProviderInfo providerInfo = null; string unused = this.Globber.GetProviderPath(variablePath.QualifiedName, out providerInfo); throw NewProviderInvocationException( "ProviderVariableSyntaxInvalid", SessionStateStrings.ProviderVariableSyntaxInvalid, providerInfo, variablePath.QualifiedName, argException); } IContentReader reader = readers[0]; try { // Read all the content IList resultList = reader.Read(-1); if (resultList != null) { if (resultList.Count == 0) { result = null; } else if (resultList.Count == 1) { result = resultList[0]; } else { result = resultList; } } } catch (Exception e) // Third-party callout, catch-all OK { // First get the provider for the path. ProviderInfo providerInfo = null; string unused = this.Globber.GetProviderPath(variablePath.QualifiedName, out providerInfo); CommandProcessorBase.CheckForSevereException(e); ProviderInvocationException providerException = new ProviderInvocationException( "ProviderContentReadError", SessionStateStrings.ProviderContentReadError, providerInfo, variablePath.QualifiedName, e); throw providerException; } finally { reader.Close(); } #else try { GetItem(variablePath.LookupPath.ToString(), context); } catch (ItemNotFoundException) { break; } Collection<PSObject> items = context.GetAccumulatedObjects (); if (items != null && items.Count > 0) { result = items[0]; if (!items[0].basObjectIsEmpty) { result = items[0].BaseObject; } try { DictionaryEntry entry = (DictionaryEntry)result; result = entry.Value; } // Since DictionaryEntry is a value type we have to // try the cast and catch the exception to determine // if it is a DictionaryEntry type. catch (InvalidCastException) { } } #endif break; } while (false); return result; } // GetVariableFromProvider
protected override void ProcessRecord() { if (!this._totalCountSpecified || !this._tailSpecified) { if (this.TotalCount != (long)0) { CmdletProviderContext cmdletProviderContext = this.CmdletProviderContext; this.contentStreams = base.GetContentReaders(base.Path, cmdletProviderContext); try { Label0: foreach (ContentCommandBase.ContentHolder contentStream in this.contentStreams) { long count = (long)0; if (!this._tailSpecified || contentStream.Reader as FileSystemContentReaderWriter != null) { if (this.Tail >= 0) { bool flag = false; try { flag = this.SeekPositionForTail(contentStream.Reader); } catch (Exception exception1) { Exception exception = exception1; CommandsCommon.CheckForSevereException(this, exception); ProviderInvocationException providerInvocationException = new ProviderInvocationException("ProviderContentReadError", SessionStateStrings.ProviderContentReadError, contentStream.PathInfo.Provider, contentStream.PathInfo.Path, exception); MshLog.LogProviderHealthEvent(base.Context, contentStream.PathInfo.Provider.Name, providerInvocationException, Severity.Warning); base.WriteError(new ErrorRecord(providerInvocationException.ErrorRecord, providerInvocationException)); continue; } if (!flag && !this.ScanForwardsForTail(contentStream, cmdletProviderContext)) { continue; } } if (this.TotalCount == (long)0) { continue; } IList lists = null; do { long readCount = this.ReadCount; if (this.TotalCount > (long)0 && this.TotalCount - readCount < count) { readCount = this.TotalCount - count; } try { lists = contentStream.Reader.Read(readCount); } catch (Exception exception3) { Exception exception2 = exception3; CommandsCommon.CheckForSevereException(this, exception2); ProviderInvocationException providerInvocationException1 = new ProviderInvocationException("ProviderContentReadError", SessionStateStrings.ProviderContentReadError, contentStream.PathInfo.Provider, contentStream.PathInfo.Path, exception2); MshLog.LogProviderHealthEvent(base.Context, contentStream.PathInfo.Provider.Name, providerInvocationException1, Severity.Warning); base.WriteError(new ErrorRecord(providerInvocationException1.ErrorRecord, providerInvocationException1)); goto Label0; } if (lists == null || lists.Count <= 0) { continue; } count = count + (long)lists.Count; if (this.ReadCount != (long)1) { base.WriteContentObject(lists, count, contentStream.PathInfo, cmdletProviderContext); } else { base.WriteContentObject(lists[0], count, contentStream.PathInfo, cmdletProviderContext); } } while (lists != null && lists.Count > 0 && (this.TotalCount < (long)0 || count < this.TotalCount)); } else { string getContentTailNotSupported = SessionStateStrings.GetContent_TailNotSupported; ErrorRecord errorRecord = new ErrorRecord(new InvalidOperationException(getContentTailNotSupported), "TailNotSupported", ErrorCategory.InvalidOperation, (object)this.Tail); base.WriteError(errorRecord); } } } finally { base.CloseContent(this.contentStreams, false); this.contentStreams = new List<ContentCommandBase.ContentHolder>(); } return; } else { return; } } else { string str = StringUtil.Format(SessionStateStrings.GetContent_TailAndHeadCannotCoexist, "TotalCount", "Tail"); ErrorRecord errorRecord1 = new ErrorRecord(new InvalidOperationException(str), "TailAndHeadCannotCoexist", ErrorCategory.InvalidOperation, null); base.WriteError(errorRecord1); return; } }
internal object GetVariableValueFromProvider(VariablePath variablePath, out CmdletProviderContext context, out SessionStateScope scope, CommandOrigin origin) { scope = null; if (variablePath == null) { throw PSTraceSource.NewArgumentNullException("variablePath"); } context = null; DriveScopeItemSearcher searcher = new DriveScopeItemSearcher(this, variablePath); object obj2 = null; if (searcher.MoveNext()) { PSDriveInfo current = (PSDriveInfo)searcher.Current; if (current == null) { return obj2; } context = new CmdletProviderContext(this.ExecutionContext, origin); context.Drive = current; Collection<IContentReader> contentReader = null; try { contentReader = this.GetContentReader(new string[] { variablePath.QualifiedName }, context); } catch (ItemNotFoundException) { return obj2; } catch (System.Management.Automation.DriveNotFoundException) { return obj2; } catch (ProviderNotFoundException) { return obj2; } catch (NotImplementedException exception) { ProviderInfo provider = null; this.Globber.GetProviderPath(variablePath.QualifiedName, out provider); throw this.NewProviderInvocationException("ProviderCannotBeUsedAsVariable", SessionStateStrings.ProviderCannotBeUsedAsVariable, provider, variablePath.QualifiedName, exception, false); } catch (NotSupportedException exception2) { ProviderInfo info3 = null; this.Globber.GetProviderPath(variablePath.QualifiedName, out info3); throw this.NewProviderInvocationException("ProviderCannotBeUsedAsVariable", SessionStateStrings.ProviderCannotBeUsedAsVariable, info3, variablePath.QualifiedName, exception2, false); } if ((contentReader == null) || (contentReader.Count == 0)) { return obj2; } if (contentReader.Count > 1) { foreach (IContentReader reader in contentReader) { reader.Close(); } PSArgumentException e = PSTraceSource.NewArgumentException("path", "SessionStateStrings", "VariablePathResolvedToMultiple", new object[] { variablePath.QualifiedName }); ProviderInfo info4 = null; this.Globber.GetProviderPath(variablePath.QualifiedName, out info4); throw this.NewProviderInvocationException("ProviderVariableSyntaxInvalid", SessionStateStrings.ProviderVariableSyntaxInvalid, info4, variablePath.QualifiedName, e); } IContentReader reader2 = contentReader[0]; try { IList list = reader2.Read(-1L); if (list == null) { return obj2; } if (list.Count == 0) { return null; } if (list.Count == 1) { return list[0]; } return list; } catch (Exception exception4) { ProviderInfo info5 = null; this.Globber.GetProviderPath(variablePath.QualifiedName, out info5); CommandProcessorBase.CheckForSevereException(exception4); ProviderInvocationException exception5 = new ProviderInvocationException("ProviderContentReadError", SessionStateStrings.ProviderContentReadError, info5, variablePath.QualifiedName, exception4); throw exception5; } finally { reader2.Close(); } } return obj2; }
internal object GetVariableValueAtScope(string name, string scopeID) { if (name == null) { throw PSTraceSource.NewArgumentNullException("name"); } VariablePath path = new VariablePath(name); SessionStateScope scopeByID = null; scopeByID = this.GetScopeByID(scopeID); object obj2 = null; if (path.IsVariable) { obj2 = scopeByID.GetVariable(path.QualifiedName); } else { PSDriveInfo drive = scopeByID.GetDrive(path.DriveName); if (drive != null) { CmdletProviderContext context = new CmdletProviderContext(this.ExecutionContext) { Drive = drive }; Collection<IContentReader> contentReader = null; try { contentReader = this.GetContentReader(new string[] { path.QualifiedName }, context); } catch (ItemNotFoundException) { return null; } catch (System.Management.Automation.DriveNotFoundException) { return null; } catch (ProviderNotFoundException) { return null; } catch (NotImplementedException exception) { ProviderInfo provider = null; this.Globber.GetProviderPath(path.QualifiedName, out provider); throw this.NewProviderInvocationException("ProviderCannotBeUsedAsVariable", SessionStateStrings.ProviderCannotBeUsedAsVariable, provider, path.QualifiedName, exception, false); } catch (NotSupportedException exception2) { ProviderInfo info3 = null; this.Globber.GetProviderPath(path.QualifiedName, out info3); throw this.NewProviderInvocationException("ProviderCannotBeUsedAsVariable", SessionStateStrings.ProviderCannotBeUsedAsVariable, info3, path.QualifiedName, exception2, false); } if ((contentReader == null) || (contentReader.Count == 0)) { return null; } if (contentReader.Count > 1) { foreach (IContentReader reader in contentReader) { reader.Close(); } PSArgumentException e = PSTraceSource.NewArgumentException("path", "SessionStateStrings", "VariablePathResolvedToMultiple", new object[] { name }); ProviderInfo info4 = null; this.Globber.GetProviderPath(path.QualifiedName, out info4); throw this.NewProviderInvocationException("ProviderVariableSyntaxInvalid", SessionStateStrings.ProviderVariableSyntaxInvalid, info4, path.QualifiedName, e); } IContentReader reader2 = contentReader[0]; try { IList list = reader2.Read(-1L); if (list != null) { if (list.Count == 0) { obj2 = null; } else if (list.Count == 1) { obj2 = list[0]; } else { obj2 = list; } } } catch (Exception exception4) { ProviderInfo info5 = null; this.Globber.GetProviderPath(path.QualifiedName, out info5); CommandProcessorBase.CheckForSevereException(exception4); ProviderInvocationException exception5 = new ProviderInvocationException("ProviderContentReadError", SessionStateStrings.ProviderContentReadError, info5, path.QualifiedName, exception4); throw exception5; } finally { reader2.Close(); } } } if (obj2 != null) { PSVariable variable = obj2 as PSVariable; if (variable != null) { return variable.Value; } try { DictionaryEntry entry = (DictionaryEntry) obj2; obj2 = entry.Value; } catch (InvalidCastException) { } } return obj2; }
/// <summary> /// Constructs a new instance of a ProviderInvocationException /// using the specified data /// </summary> /// /// <param name="resourceId"> /// The resource ID to use as the format message for the error. /// </param> /// /// <param name="resourceStr"> /// This is the message template string. /// </param> /// /// <param name="provider"> /// The provider information used when formatting the error message. /// </param> /// /// <param name="path"> /// The path used when formatting the error message. /// </param> /// /// <param name="e"> /// The exception that was thrown by the provider. This will be set as /// the ProviderInvocationException's InnerException and the message will /// be used when formatting the error message. /// </param> /// /// <param name="useInnerExceptionErrorMessage"> /// If true, the error record from the inner exception will be used if it contains one. /// If false, the error message specified by the resourceId will be used. /// </param> /// /// <returns> /// A new instance of a ProviderInvocationException. /// </returns> /// /// <exception cref="ProviderInvocationException"> /// Wraps <paramref name="e"/> in a ProviderInvocationException /// and then throws it. /// </exception> /// internal ProviderInvocationException NewProviderInvocationException( string resourceId, string resourceStr, ProviderInfo provider, string path, Exception e, bool useInnerExceptionErrorMessage) { // If the innerException was itself thrown by // ProviderBase.ThrowTerminatingError, it is already a // ProviderInvocationException, and we don't want to // re-wrap it. ProviderInvocationException pie = e as ProviderInvocationException; if (null != pie) { pie._providerInfo = provider; return pie; } pie = new ProviderInvocationException(resourceId, resourceStr, provider, path, e, useInnerExceptionErrorMessage); // Log a provider health event MshLog.LogProviderHealthEvent( ExecutionContext, provider.Name, pie, Severity.Warning); return pie; }
/// <summary> /// Appends the content to the specified item. /// </summary> protected override void ProcessRecord() { CmdletProviderContext currentContext = GetCurrentContext(); // Initialize the content if (_content == null) { _content = new object[0]; } if (_pipingPaths) { // Make sure to clean up the content writers that are already there if (contentStreams != null && contentStreams.Count > 0) { CloseContent(contentStreams, false); _contentWritersOpen = false; contentStreams = new List<ContentHolder>(); } } if (!_contentWritersOpen) { // Since the paths are being pipelined in, we have // to get new content writers for the new paths string[] paths = GetAcceptedPaths(Path, currentContext); if (paths.Length > 0) { BeforeOpenStreams(paths); contentStreams = GetContentWriters(paths, currentContext); SeekContentPosition(contentStreams); } _contentWritersOpen = true; } // Now write the content to the item try { foreach (ContentHolder holder in contentStreams) { if (holder.Writer != null) { IList result = null; try { result = holder.Writer.Write(_content); } catch (Exception e) // Catch-all OK. 3rd party callout { CommandsCommon.CheckForSevereException(this, e); ProviderInvocationException providerException = new ProviderInvocationException( "ProviderContentWriteError", SessionStateStrings.ProviderContentWriteError, holder.PathInfo.Provider, holder.PathInfo.Path, e); // Log a provider health event MshLog.LogProviderHealthEvent( this.Context, holder.PathInfo.Provider.Name, providerException, Severity.Warning); WriteError( new ErrorRecord( providerException.ErrorRecord, providerException)); continue; } if (result != null && result.Count > 0 && PassThru) { WriteContentObject(result, result.Count, holder.PathInfo, currentContext); } } } } finally { // Need to close all the writers if the paths are being pipelined if (_pipingPaths) { CloseContent(contentStreams, false); _contentWritersOpen = false; contentStreams = new List<ContentHolder>(); } } } // ProcessRecord
internal void ThrowFirstErrorOrDoNothing(bool wrapExceptionInProviderException) { if (this.HasErrors()) { Collection<ErrorRecord> accumulatedErrorObjects = this.GetAccumulatedErrorObjects(); if ((accumulatedErrorObjects != null) && (accumulatedErrorObjects.Count > 0)) { if (!wrapExceptionInProviderException) { throw accumulatedErrorObjects[0].Exception; } ProviderInfo provider = null; if (this.ProviderInstance != null) { provider = this.ProviderInstance.ProviderInfo; } ProviderInvocationException exception = new ProviderInvocationException(provider, accumulatedErrorObjects[0]); MshLog.LogProviderHealthEvent(this.ExecutionContext, (provider != null) ? provider.Name : "unknown provider", exception, Severity.Warning); throw exception; } } }
} // GetVariable /// <summary> /// Get a variable out of session state. This interface supports /// the "namespace:name" syntax so you can do things like /// "env:PATH" or "global:foobar" /// </summary> /// /// <param name="name"> /// name of variable to look up /// </param> /// /// <param name="scopeID"> /// The ID of the scope to lookup the variable in. /// </param> /// /// <returns> /// The value of the specified variable. /// </returns> /// /// <exception cref="ArgumentNullException"> /// If <paramref name="name"/> is null. /// </exception> /// /// <exception cref="ArgumentException"> /// If <paramref name="scopeID"/> is less than zero, or not /// a number and not "script", "global", "local", or "private" /// </exception> /// /// <exception cref="ArgumentOutOfRangeException"> /// If <paramref name="scopeID"/> is less than zero or greater than the number of currently /// active scopes. /// </exception> /// /// <exception cref="ProviderNotFoundException"> /// If the <paramref name="name"/> refers to a provider that could not be found. /// </exception> /// /// <exception cref="DriveNotFoundException"> /// If the <paramref name="name"/> refers to a drive that could not be found. /// </exception> /// /// <exception cref="NotSupportedException"> /// If the provider that the <paramref name="name"/> refers to does /// not support this operation. /// </exception> /// /// <exception cref="ProviderInvocationException"> /// If the provider threw an exception. /// </exception> /// internal object GetVariableValueAtScope(string name, string scopeID) { if (name == null) { throw PSTraceSource.NewArgumentNullException("name"); } VariablePath variablePath = new VariablePath(name); SessionStateScope lookupScope = null; // The lookup scope from above is ignored and the scope is retrieved by // ID. lookupScope = GetScopeByID(scopeID); object resultItem = null; if (variablePath.IsVariable) { resultItem = lookupScope.GetVariable(variablePath.QualifiedName); } else { PSDriveInfo drive = lookupScope.GetDrive(variablePath.DriveName); if (drive != null) { CmdletProviderContext context = new CmdletProviderContext(this.ExecutionContext); context.Drive = drive; #if true // PSVariable get/set is the get/set of content in the provider Collection<IContentReader> readers = null; try { readers = GetContentReader(new string[] { variablePath.QualifiedName }, context); } // If the item is not found we just return null like the normal // variable semantics. catch (ItemNotFoundException) { return null; } catch (DriveNotFoundException) { return null; } catch (ProviderNotFoundException) { return null; } catch (NotImplementedException notImplemented) { // First get the provider for the path. ProviderInfo providerInfo = null; string unused = this.Globber.GetProviderPath(variablePath.QualifiedName, out providerInfo); throw NewProviderInvocationException( "ProviderCannotBeUsedAsVariable", SessionStateStrings.ProviderCannotBeUsedAsVariable, providerInfo, variablePath.QualifiedName, notImplemented, false); } catch (NotSupportedException notSupported) { // First get the provider for the path. ProviderInfo providerInfo = null; string unused = this.Globber.GetProviderPath(variablePath.QualifiedName, out providerInfo); throw NewProviderInvocationException( "ProviderCannotBeUsedAsVariable", SessionStateStrings.ProviderCannotBeUsedAsVariable, providerInfo, variablePath.QualifiedName, notSupported, false); } if (readers == null || readers.Count == 0) { // The drive was found but the path was wrong or something so return null. // We don't want to continue searching if the provider didn't support content // or the path wasn't found. // Any errors should have been written to the error pipeline. return null; } if (readers.Count > 1) { foreach (IContentReader closeReader in readers) { closeReader.Close(); } // Since more than one path was resolved, this is an error. PSArgumentException argException = PSTraceSource.NewArgumentException( "path", SessionStateStrings.VariablePathResolvedToMultiple, name); // First get the provider for the path. ProviderInfo providerInfo = null; string unused = this.Globber.GetProviderPath(variablePath.QualifiedName, out providerInfo); throw NewProviderInvocationException( "ProviderVariableSyntaxInvalid", SessionStateStrings.ProviderVariableSyntaxInvalid, providerInfo, variablePath.QualifiedName, argException); } IContentReader reader = readers[0]; try { // Read all the content IList resultList = reader.Read(-1); if (resultList != null) { if (resultList.Count == 0) { resultItem = null; } else if (resultList.Count == 1) { resultItem = resultList[0]; } else { resultItem = resultList; } } } catch (Exception e) // Third-party callout, catch-all OK { // First get the provider for the path. ProviderInfo providerInfo = null; string unused = this.Globber.GetProviderPath(variablePath.QualifiedName, out providerInfo); CommandProcessorBase.CheckForSevereException(e); ProviderInvocationException providerException = new ProviderInvocationException( "ProviderContentReadError", SessionStateStrings.ProviderContentReadError, providerInfo, variablePath.QualifiedName, e); throw providerException; } finally { reader.Close(); } #else GetItem (variablePath.LookupPath.ToString (), context); Collection<PSObject> results = context.GetAccumulatedObjects (); if (results != null & results.Count > 0) { // Only return the first value. If the caller wants globbing // they need to call the GetItem method directly. if (!results[0].basObjectIsEmpty) { resultItem = results[0].BaseObject; } else { resultItem = results[0]; } } #endif } } // If we get a PSVariable or DictionaryEntry returned then we have to // grab the value from it and return that instead. if (resultItem != null) { PSVariable variable = resultItem as PSVariable; if (variable != null) { resultItem = variable.Value; } else { try { DictionaryEntry entry = (DictionaryEntry)resultItem; resultItem = entry.Value; } catch (InvalidCastException) { } } } // if resultItem != null return resultItem; } // GetVariableValueAtScope
/// <summary> /// If there are any errors accumulated, the first error is thrown. /// </summary> /// /// <param name="wrapExceptionInProviderException"> /// If true, the error will be wrapped in a ProviderInvocationException before /// being thrown. If false, the error will be thrown as is. /// </param> /// /// <exception cref="ProviderInvocationException"> /// If <paramref name="wrapExceptionInProviderException"/> is true, the /// first exception that was written to the error pipeline by a CmdletProvider /// is wrapped and thrown. /// </exception> /// /// <exception> /// If <paramref name="wrapExceptionInProviderException"/> is false, /// the first exception that was written to the error pipeline by a CmdletProvider /// is thrown. /// </exception> /// internal void ThrowFirstErrorOrDoNothing(bool wrapExceptionInProviderException) { if (HasErrors()) { Collection<ErrorRecord> errors = GetAccumulatedErrorObjects(); if (errors != null && errors.Count > 0) { // Throw the first exception if (wrapExceptionInProviderException) { ProviderInfo providerInfo = null; if (this.ProviderInstance != null) { providerInfo = this.ProviderInstance.ProviderInfo; } ProviderInvocationException e = new ProviderInvocationException( providerInfo, errors[0]); // Log a provider health event MshLog.LogProviderHealthEvent( this.ExecutionContext, providerInfo != null ? providerInfo.Name : "unknown provider", e, Severity.Warning); throw e; } else { throw errors[0].Exception; } } } }
private bool ScanForwardsForTail(ContentCommandBase.ContentHolder holder, CmdletProviderContext currentContext) { FileSystemContentReaderWriter reader = holder.Reader as FileSystemContentReaderWriter; Queue<object> objs = new Queue<object>(); IList lists = null; ErrorRecord errorRecord = null; do { try { lists = reader.ReadWithoutWaitingChanges(this.ReadCount); } catch (Exception exception1) { Exception exception = exception1; CommandsCommon.CheckForSevereException(this, exception); ProviderInvocationException providerInvocationException = new ProviderInvocationException("ProviderContentReadError", SessionStateStrings.ProviderContentReadError, holder.PathInfo.Provider, holder.PathInfo.Path, exception); MshLog.LogProviderHealthEvent(base.Context, holder.PathInfo.Provider.Name, providerInvocationException, Severity.Warning); errorRecord = new ErrorRecord(providerInvocationException.ErrorRecord, providerInvocationException); break; } if (lists == null || lists.Count <= 0) { continue; } foreach (object obj in lists) { if (objs.Count == this.Tail) { objs.Dequeue(); } objs.Enqueue(obj); } } while (lists != null && lists.Count > 0); if (objs.Count > 0) { int count = 0; if (this.ReadCount <= (long)0 || this.ReadCount >= (long)objs.Count && this.ReadCount != (long)1) { count = objs.Count; ArrayList arrayLists = new ArrayList(); while (objs.Count > 0) { arrayLists.Add(objs.Dequeue()); } base.WriteContentObject(arrayLists.ToArray(), (long)count, holder.PathInfo, currentContext); } else { if (this.ReadCount != (long)1) { while ((long)objs.Count >= this.ReadCount) { ArrayList arrayLists1 = new ArrayList(); int num = 0; while ((long)num < this.ReadCount) { arrayLists1.Add(objs.Dequeue()); num++; count++; } base.WriteContentObject(arrayLists1.ToArray(), (long)count, holder.PathInfo, currentContext); } int count1 = objs.Count; if (count1 > 0) { ArrayList arrayLists2 = new ArrayList(); while (count1 > 0) { arrayLists2.Add(objs.Dequeue()); count1--; count++; } base.WriteContentObject(arrayLists2.ToArray(), (long)count, holder.PathInfo, currentContext); } } else { while (objs.Count > 0) { int num1 = count; count = num1 + 1; base.WriteContentObject(objs.Dequeue(), (long)num1, holder.PathInfo, currentContext); } } } } if (errorRecord == null) { return true; } else { base.WriteError(errorRecord); return false; } }
} // ProcessRecord /// <summary> /// Scan forwards to get the tail content /// </summary> /// <param name="holder"></param> /// <param name="currentContext"></param> /// <returns> /// true if no error occured /// false if there was an error /// </returns> private bool ScanForwardsForTail(ContentHolder holder, CmdletProviderContext currentContext) { var fsReader = holder.Reader as FileSystemContentReaderWriter; Dbg.Diagnostics.Assert(fsReader != null, "Tail is only supported for FileSystemContentReaderWriter"); var tailResultQueue = new Queue<object>(); IList results = null; ErrorRecord error = null; do { try { results = fsReader.ReadWithoutWaitingChanges(ReadCount); } catch (Exception e) { CommandsCommon.CheckForSevereException(this, e); ProviderInvocationException providerException = new ProviderInvocationException( "ProviderContentReadError", SessionStateStrings.ProviderContentReadError, holder.PathInfo.Provider, holder.PathInfo.Path, e); // Log a provider health event MshLog.LogProviderHealthEvent( this.Context, holder.PathInfo.Provider.Name, providerException, Severity.Warning); // Create and save the error record. The error record // will be written outside the while loop. // This is to make sure the accumulated results get written // out before the error record when the 'scanForwardForTail' is true. error = new ErrorRecord( providerException.ErrorRecord, providerException); break; } if (results != null && results.Count > 0) { foreach (object entry in results) { if (tailResultQueue.Count == Tail) tailResultQueue.Dequeue(); tailResultQueue.Enqueue(entry); } } } while (results != null && results.Count > 0); if (tailResultQueue.Count > 0) { // Respect the ReadCount parameter. // Output single object when ReadCount == 1; Output array otherwise int count = 0; if (ReadCount <= 0 || (ReadCount >= tailResultQueue.Count && ReadCount != 1)) { count = tailResultQueue.Count; ArrayList outputList = new ArrayList(); while (tailResultQueue.Count > 0) { outputList.Add(tailResultQueue.Dequeue()); } // Write out the content as an array of objects WriteContentObject(outputList.ToArray(), count, holder.PathInfo, currentContext); } else if (ReadCount == 1) { // Write out the content as single object while (tailResultQueue.Count > 0) WriteContentObject(tailResultQueue.Dequeue(), count++, holder.PathInfo, currentContext); } else // ReadCount < Queue.Count { while (tailResultQueue.Count >= ReadCount) { ArrayList outputList = new ArrayList(); for (int idx = 0; idx < ReadCount; idx++, count++) outputList.Add(tailResultQueue.Dequeue()); // Write out the content as an array of objects WriteContentObject(outputList.ToArray(), count, holder.PathInfo, currentContext); } int remainder = tailResultQueue.Count; if (remainder > 0) { ArrayList outputList = new ArrayList(); for (; remainder > 0; remainder--, count++) outputList.Add(tailResultQueue.Dequeue()); // Write out the content as an array of objects WriteContentObject(outputList.ToArray(), count, holder.PathInfo, currentContext); } } } if (error != null) { WriteError(error); return false; } return true; }
/// <summary> /// Wraps the exception which occurred during cmdlet invocation, /// stores that as the exception to be returned from /// PipelineProcessor.SynchronousExecute, and writes it to /// the error variable. /// </summary> /// <param name="e"> /// The exception to wrap in a CmdletInvocationException or /// CmdletProviderInvocationException. /// </param> /// <returns> /// Always returns PipelineStoppedException. The caller should /// throw this exception. /// </returns> /// <remarks> /// Almost all exceptions which occur during pipeline invocation /// are wrapped in CmdletInvocationException before they are stored /// in the pipeline. However, there are several exceptions: /// /// AccessViolationException, StackOverflowException: /// These are considered to be such severe errors that we /// FailFast the process immediately. /// /// ProviderInvocationException: In this case, we assume that the /// cmdlet is get-item or the like, a thin wrapper around the /// provider API. We discard the original ProviderInvocationException /// and re-wrap its InnerException (the real error) in /// CmdletProviderInvocationException. This makes it easier to reach /// the real error. /// /// CmdletInvocationException, ActionPreferenceStopException: /// This indicates that the cmdlet itself ran a command which failed. /// We could go ahead and wrap the original exception in multiple /// layers of CmdletInvocationException, but this makes it difficult /// for the caller to access the root problem, plus the serialization /// layer might not communicate properties beyond some fixed depth. /// Instead, we choose to not re-wrap the exception. /// /// PipelineStoppedException: This could mean one of two things. /// It usually means that this pipeline has already stopped, /// in which case the pipeline already stores the original error. /// It could also mean that the cmdlet ran a command which was /// stopped by CTRL-C etc, in which case we choose not to /// re-wrap the exception as with CmdletInvocationException. /// </remarks> internal PipelineStoppedException ManageInvocationException(Exception e) { try { if (Command != null) { do // false loop { ProviderInvocationException pie = e as ProviderInvocationException; if (pie != null) { // If a ProviderInvocationException occurred, // discard the ProviderInvocationException and // re-wrap in CmdletProviderInvocationException e = new CmdletProviderInvocationException( pie, Command.MyInvocation); break; } // 1021203-2005/05/09-JonN // HaltCommandException will cause the command // to stop, but not be reported as an error. // 906445-2005/05/16-JonN // FlowControlException should not be wrapped if (e is PipelineStoppedException || e is CmdletInvocationException || e is ActionPreferenceStopException || e is HaltCommandException || e is FlowControlException || e is ScriptCallDepthException) { // do nothing; do not rewrap these exceptions break; } RuntimeException rte = e as RuntimeException; if (rte != null && rte.WasThrownFromThrowStatement) { // do not rewrap a script based throw break; } // wrap all other exceptions e = new CmdletInvocationException( e, Command.MyInvocation); } while (false); // commandRuntime.ManageException will always throw PipelineStoppedException // Otherwise, just return this exception... // If this exception happened in a transacted cmdlet, // rollback the transaction if (commandRuntime.UseTransaction) { // The "transaction timed out" exception is // exceedingly obtuse. We clarify things here. bool isTimeoutException = false; Exception tempException = e; while (tempException != null) { if (tempException is System.TimeoutException) { isTimeoutException = true; break; } tempException = tempException.InnerException; } if (isTimeoutException) { ErrorRecord errorRecord = new ErrorRecord( new InvalidOperationException( TransactionStrings.TransactionTimedOut), "TRANSACTION_TIMEOUT", ErrorCategory.InvalidOperation, e); errorRecord.SetInvocationInfo(Command.MyInvocation); e = new CmdletInvocationException(errorRecord); } // Rollback the transaction in the case of errors. if ( _context.TransactionManager.HasTransaction && _context.TransactionManager.RollbackPreference != RollbackSeverity.Never ) { Context.TransactionManager.Rollback(true); } } return((PipelineStoppedException)this.commandRuntime.ManageException(e)); } // Upstream cmdlets see only that execution stopped // This should only happen if Command is null return(new PipelineStoppedException()); } catch (Exception) { // this method should not throw exceptions; warn about any violations on checked builds and re-throw Diagnostics.Assert(false, "This method should not throw exceptions!"); throw; } }
internal ProviderInvocationException NewProviderInvocationException(string resourceId, string resourceStr, ProviderInfo provider, string path, Exception e, bool useInnerExceptionErrorMessage) { ProviderInvocationException exception = e as ProviderInvocationException; if (exception != null) { exception._providerInfo = provider; return exception; } exception = new ProviderInvocationException(resourceId, resourceStr, provider, path, e, useInnerExceptionErrorMessage); MshLog.LogProviderHealthEvent(this._context, provider.Name, exception, Severity.Warning); return exception; }
/// <summary> /// Set a variable using a pre-parsed variablePath object instead of a string. /// </summary> /// /// <param name="variablePath"> /// A pre-parsed variable path object for the variable in question. /// </param> /// /// <param name="newValue"> /// The value to set. /// </param> /// /// <param name="asValue"> /// If true, sets the variable value to newValue. If false, newValue must /// be a PSVariable object and the item will be set rather than the value. /// </param> /// /// <param name="force"> /// If true, the variable is set even if it is ReadOnly. /// </param> /// /// <param name="origin"> /// The origin of the caller /// </param> /// /// <returns> /// A PSVariable object if <paramref name="variablePath"/> refers to a variable. /// An PSObject if <paramref name="variablePath"/> refers to a provider path. /// </returns> /// /// <exception cref="ArgumentNullException"> /// If <paramref name="variablePath"/> is null. /// </exception> /// /// <exception cref="SessionStateUnauthorizedAccessException"> /// If the variable is read-only or constant. /// </exception> /// /// <exception cref="SessionStateOverflowException"> /// If the maximum number of variables has been reached for this scope. /// </exception> /// /// <exception cref="ProviderNotFoundException"> /// If the <paramref name="variablePath"/> refers to a provider that could not be found. /// </exception> /// /// <exception cref="DriveNotFoundException"> /// If the <paramref name="variablePath"/> refers to a drive that could not be found. /// </exception> /// /// <exception cref="NotSupportedException"> /// If the provider that the <paramref name="variablePath"/> refers to does /// not support this operation. /// </exception> /// /// <exception cref="ProviderInvocationException"> /// If the provider threw an exception. /// </exception> /// internal object SetVariable( VariablePath variablePath, object newValue, bool asValue, bool force, CommandOrigin origin) { object result = null; if (variablePath == null) { throw PSTraceSource.NewArgumentNullException("variablePath"); } CmdletProviderContext context = null; SessionStateScope scope = null; if (variablePath.IsVariable) { // Make sure to set the variable in the appropriate scope if (variablePath.IsLocal || variablePath.IsUnscopedVariable) { scope = _currentScope; } else if (variablePath.IsScript) { scope = _currentScope.ScriptScope; } else if (variablePath.IsGlobal) { scope = GlobalScope; } else if (variablePath.IsPrivate) { scope = _currentScope; } PSVariable varResult = scope.SetVariable( variablePath.QualifiedName, newValue, asValue, force, this, origin); // If the name is scoped as private we need to mark the // variable as private if (variablePath.IsPrivate && varResult != null) { varResult.Options = varResult.Options | ScopedItemOptions.Private; } result = varResult; } else { // Use GetVariable to get the correct context for the set operation. // NTRAID#Windows OS Bugs-896768-2004/07/06-JeffJon // There is probably a more efficient way to do this. GetVariableValue(variablePath, out context, out scope); #if true // PSVariable get/set is the get/set of content in the provider Collection<IContentWriter> writers = null; try { if (context != null) { try { CmdletProviderContext clearContentContext = new CmdletProviderContext(context); // First clear the content if it is supported. ClearContent(new string[] { variablePath.QualifiedName }, clearContentContext); } catch (NotSupportedException) { } catch (ItemNotFoundException) { } writers = GetContentWriter( new string[] { variablePath.QualifiedName }, context); context.ThrowFirstErrorOrDoNothing(true); } else { try { // First clear the content if it is supported. ClearContent(new string[] { variablePath.QualifiedName }, false, false); } catch (NotSupportedException) { } catch (ItemNotFoundException) { } writers = GetContentWriter( new string[] { variablePath.QualifiedName }, false, false); } } catch (NotImplementedException notImplemented) { // First get the provider for the path. ProviderInfo providerInfo = null; string unused = this.Globber.GetProviderPath(variablePath.QualifiedName, out providerInfo); throw NewProviderInvocationException( "ProviderCannotBeUsedAsVariable", SessionStateStrings.ProviderCannotBeUsedAsVariable, providerInfo, variablePath.QualifiedName, notImplemented, false); } catch (NotSupportedException notSupported) { // First get the provider for the path. ProviderInfo providerInfo = null; string unused = this.Globber.GetProviderPath(variablePath.QualifiedName, out providerInfo); throw NewProviderInvocationException( "ProviderCannotBeUsedAsVariable", SessionStateStrings.ProviderCannotBeUsedAsVariable, providerInfo, variablePath.QualifiedName, notSupported, false); } if (writers == null || writers.Count == 0) { ItemNotFoundException itemNotFound = new ItemNotFoundException( variablePath.QualifiedName, "PathNotFound", SessionStateStrings.PathNotFound); throw itemNotFound; } if (writers.Count > 1) { // Since more than one path was resolved, this is an error. foreach (IContentWriter w in writers) { w.Close(); } PSArgumentException argException = PSTraceSource.NewArgumentException( "path", SessionStateStrings.VariablePathResolvedToMultiple, variablePath.QualifiedName); // First get the provider for the path. ProviderInfo providerInfo = null; string unused = this.Globber.GetProviderPath(variablePath.QualifiedName, out providerInfo); throw NewProviderInvocationException( "ProviderVariableSyntaxInvalid", SessionStateStrings.ProviderVariableSyntaxInvalid, providerInfo, variablePath.QualifiedName, argException); } IContentWriter writer = writers[0]; IList content = newValue as IList ?? new object[] { newValue }; try { writer.Write(content); } catch (Exception e) // Third-party callout, catch-all OK { // First get the provider for the path. ProviderInfo providerInfo = null; string unused = this.Globber.GetProviderPath(variablePath.QualifiedName, out providerInfo); CommandProcessorBase.CheckForSevereException(e); ProviderInvocationException providerException = new ProviderInvocationException( "ProviderContentWriteError", SessionStateStrings.ProviderContentWriteError, providerInfo, variablePath.QualifiedName, e); throw providerException; } finally { writer.Close(); } #else if (context != null) { context.Force = force; SetItem (variablePath.LookupPath.ToString (), newValue, context); context.ThrowFirstErrorOrDoNothing(true); } else { Collection<PSObject> setItemResult = SetItem (variablePath.LookupPath.ToString (), newValue); if (setItemResult != null && setItemResult.Count > 0) { result = setItemResult[0]; } } #endif } return result; } // SetVariable
/// <summary> /// Gets the content of an item at the specified path /// </summary> protected override void ProcessRecord() { // TotalCount and Tail should not be specified at the same time. // Throw out terminating error if this is the case. if (_totalCountSpecified && _tailSpecified) { string errMsg = StringUtil.Format(SessionStateStrings.GetContent_TailAndHeadCannotCoexist, "TotalCount", "Tail"); ErrorRecord error = new ErrorRecord(new InvalidOperationException(errMsg), "TailAndHeadCannotCoexist", ErrorCategory.InvalidOperation, null); WriteError(error); return; } if (TotalCount == 0) { // Don't read anything return; } // Get the content readers CmdletProviderContext currentContext = CmdletProviderContext; contentStreams = this.GetContentReaders(Path, currentContext); try { // Iterate through the content holders reading the content foreach (ContentHolder holder in contentStreams) { long countRead = 0; Dbg.Diagnostics.Assert( holder.Reader != null, "All holders should have a reader assigned"); if (_tailSpecified && !(holder.Reader is FileSystemContentReaderWriter)) { string errMsg = SessionStateStrings.GetContent_TailNotSupported; ErrorRecord error = new ErrorRecord(new InvalidOperationException(errMsg), "TailNotSupported", ErrorCategory.InvalidOperation, Tail); WriteError(error); continue; } // If Tail is negative, we are supposed to read all content out. This is same // as reading forwards. So we read forwards in this case. // If Tail is positive, we seek the right position. Or, if the seek failed // because of an unsupported encoding, we scan forward to get the tail content. if (Tail >= 0) { bool seekSuccess = false; try { seekSuccess = SeekPositionForTail(holder.Reader); } catch (Exception e) { CommandsCommon.CheckForSevereException(this, e); ProviderInvocationException providerException = new ProviderInvocationException( "ProviderContentReadError", SessionStateStrings.ProviderContentReadError, holder.PathInfo.Provider, holder.PathInfo.Path, e); // Log a provider health event MshLog.LogProviderHealthEvent( this.Context, holder.PathInfo.Provider.Name, providerException, Severity.Warning); WriteError(new ErrorRecord( providerException.ErrorRecord, providerException)); continue; } // If the seek was successful, we start to read forwards from that // point. Otherwise, we need to scan forwards to get the tail content. if (!seekSuccess && !ScanForwardsForTail(holder, currentContext)) { continue; } } if (TotalCount != 0) { IList results = null; do { long countToRead = ReadCount; // Make sure we only ask for the amount the user wanted // I am using TotalCount - countToRead so that I don't // have to worry about overflow if ((TotalCount > 0) && (TotalCount - countToRead < countRead)) { countToRead = TotalCount - countRead; } try { results = holder.Reader.Read(countToRead); } catch (Exception e) // Catch-all OK. 3rd party callout { CommandsCommon.CheckForSevereException(this, e); ProviderInvocationException providerException = new ProviderInvocationException( "ProviderContentReadError", SessionStateStrings.ProviderContentReadError, holder.PathInfo.Provider, holder.PathInfo.Path, e); // Log a provider health event MshLog.LogProviderHealthEvent( this.Context, holder.PathInfo.Provider.Name, providerException, Severity.Warning); WriteError(new ErrorRecord( providerException.ErrorRecord, providerException)); break; } if (results != null && results.Count > 0) { countRead += results.Count; if (ReadCount == 1) { // Write out the content as a single object WriteContentObject(results[0], countRead, holder.PathInfo, currentContext); } else { // Write out the content as an array of objects WriteContentObject(results, countRead, holder.PathInfo, currentContext); } } } while (results != null && results.Count > 0 && ((TotalCount < 0) || countRead < TotalCount)); } } // foreach holder in contentStreams } finally { // close all the content readers CloseContent(contentStreams, false); // Empty the content holder array contentStreams = new List<ContentHolder>(); } } // ProcessRecord
internal object SetVariable(VariablePath variablePath, object newValue, bool asValue, bool force, CommandOrigin origin) { if (variablePath == null) { throw PSTraceSource.NewArgumentNullException("variablePath"); } CmdletProviderContext context = null; SessionStateScope currentScope = null; if (variablePath.IsVariable) { if (variablePath.IsLocal || variablePath.IsUnscopedVariable) { currentScope = this.currentScope; } else if (variablePath.IsScript) { currentScope = this.currentScope.ScriptScope; } else if (variablePath.IsGlobal) { currentScope = this._globalScope; } else if (variablePath.IsPrivate) { currentScope = this.currentScope; } PSVariable variable = currentScope.SetVariable(variablePath.QualifiedName, newValue, asValue, force, this, origin, false); if (variablePath.IsPrivate && (variable != null)) { variable.Options |= ScopedItemOptions.Private; } return variable; } this.GetVariableValue(variablePath, out context, out currentScope); Collection<IContentWriter> contentWriter = null; try { if (context != null) { try { CmdletProviderContext context2 = new CmdletProviderContext(context); this.ClearContent(new string[] { variablePath.QualifiedName }, context2); } catch (NotSupportedException) { } catch (ItemNotFoundException) { } contentWriter = this.GetContentWriter(new string[] { variablePath.QualifiedName }, context); context.ThrowFirstErrorOrDoNothing(true); } else { try { this.ClearContent(new string[] { variablePath.QualifiedName }, false, false); } catch (NotSupportedException) { } catch (ItemNotFoundException) { } contentWriter = this.GetContentWriter(new string[] { variablePath.QualifiedName }, false, false); } } catch (NotImplementedException exception) { ProviderInfo provider = null; this.Globber.GetProviderPath(variablePath.QualifiedName, out provider); throw this.NewProviderInvocationException("ProviderCannotBeUsedAsVariable", SessionStateStrings.ProviderCannotBeUsedAsVariable, provider, variablePath.QualifiedName, exception, false); } catch (NotSupportedException exception2) { ProviderInfo info2 = null; this.Globber.GetProviderPath(variablePath.QualifiedName, out info2); throw this.NewProviderInvocationException("ProviderCannotBeUsedAsVariable", SessionStateStrings.ProviderCannotBeUsedAsVariable, info2, variablePath.QualifiedName, exception2, false); } if ((contentWriter == null) || (contentWriter.Count == 0)) { ItemNotFoundException exception3 = new ItemNotFoundException(variablePath.QualifiedName, "PathNotFound", SessionStateStrings.PathNotFound); throw exception3; } if (contentWriter.Count > 1) { foreach (IContentWriter writer in contentWriter) { writer.Close(); } PSArgumentException e = PSTraceSource.NewArgumentException("path", "SessionStateStrings", "VariablePathResolvedToMultiple", new object[] { variablePath.QualifiedName }); ProviderInfo info3 = null; this.Globber.GetProviderPath(variablePath.QualifiedName, out info3); throw this.NewProviderInvocationException("ProviderVariableSyntaxInvalid", SessionStateStrings.ProviderVariableSyntaxInvalid, info3, variablePath.QualifiedName, e); } IContentWriter writer2 = contentWriter[0]; IList content = newValue as IList; if (content == null) { content = new object[] { newValue }; } try { writer2.Write(content); } catch (Exception exception5) { ProviderInfo info4 = null; this.Globber.GetProviderPath(variablePath.QualifiedName, out info4); CommandProcessorBase.CheckForSevereException(exception5); ProviderInvocationException exception6 = new ProviderInvocationException("ProviderContentWriteError", SessionStateStrings.ProviderContentWriteError, info4, variablePath.QualifiedName, exception5); throw exception6; } finally { writer2.Close(); } return null; }
protected override void ProcessRecord() { CmdletProviderContext currentContext = base.GetCurrentContext(); if (this.content == null) { this.content = new object[0]; } if (this.pipingPaths && this.contentStreams != null && this.contentStreams.Count > 0) { base.CloseContent(this.contentStreams, false); this.contentWritersOpen = false; this.contentStreams = new List<ContentCommandBase.ContentHolder>(); } if (!this.contentWritersOpen) { string[] acceptedPaths = this.GetAcceptedPaths(base.Path, currentContext); if ((int)acceptedPaths.Length > 0) { this.BeforeOpenStreams(acceptedPaths); this.contentStreams = this.GetContentWriters(acceptedPaths, currentContext); this.SeekContentPosition(this.contentStreams); } this.contentWritersOpen = true; } try { foreach (ContentCommandBase.ContentHolder contentStream in this.contentStreams) { if (contentStream.Writer == null) { continue; } IList lists = null; try { lists = contentStream.Writer.Write(this.content); } catch (Exception exception1) { Exception exception = exception1; CommandsCommon.CheckForSevereException(this, exception); ProviderInvocationException providerInvocationException = new ProviderInvocationException("ProviderContentWriteError", SessionStateStrings.ProviderContentWriteError, contentStream.PathInfo.Provider, contentStream.PathInfo.Path, exception); MshLog.LogProviderHealthEvent(base.Context, contentStream.PathInfo.Provider.Name, providerInvocationException, Severity.Warning); base.WriteError(new ErrorRecord(providerInvocationException.ErrorRecord, providerInvocationException)); continue; } if (lists == null || lists.Count <= 0 || !base.PassThru) { continue; } base.WriteContentObject(lists, (long)lists.Count, contentStream.PathInfo, currentContext); } } finally { if (this.pipingPaths) { base.CloseContent(this.contentStreams, false); this.contentWritersOpen = false; this.contentStreams = new List<ContentCommandBase.ContentHolder>(); } } }
} // struct ContentHolder /// <summary> /// Closes the content readers and writers in the content holder array /// </summary> internal void CloseContent(List<ContentHolder> contentHolders, bool disposing) { if (contentHolders == null) { throw PSTraceSource.NewArgumentNullException("contentHolders"); } foreach (ContentHolder holder in contentHolders) { try { if (holder.Writer != null) { holder.Writer.Close(); } } catch (Exception e) // Catch-all OK. 3rd party callout { CommandsCommon.CheckForSevereException(this, e); // Catch all the exceptions caused by closing the writer // and write out an error. ProviderInvocationException providerException = new ProviderInvocationException( "ProviderContentCloseError", SessionStateStrings.ProviderContentCloseError, holder.PathInfo.Provider, holder.PathInfo.Path, e); // Log a provider health event MshLog.LogProviderHealthEvent( this.Context, holder.PathInfo.Provider.Name, providerException, Severity.Warning); if (!disposing) { WriteError( new ErrorRecord( providerException.ErrorRecord, providerException)); } } try { if (holder.Reader != null) { holder.Reader.Close(); } } catch (Exception e) // Catch-all OK. 3rd party callout { CommandsCommon.CheckForSevereException(this, e); // Catch all the exceptions caused by closing the writer // and write out an error. ProviderInvocationException providerException = new ProviderInvocationException( "ProviderContentCloseError", SessionStateStrings.ProviderContentCloseError, holder.PathInfo.Provider, holder.PathInfo.Path, e); // Log a provider health event MshLog.LogProviderHealthEvent( this.Context, holder.PathInfo.Provider.Name, providerException, Severity.Warning); if (!disposing) { WriteError( new ErrorRecord( providerException.ErrorRecord, providerException)); } } } } // CloseContent
public void ThrowTerminatingError(ErrorRecord errorRecord) { using (PSTransactionManager.GetEngineProtectionScope()) { if (errorRecord == null) { throw PSTraceSource.NewArgumentNullException("errorRecord"); } if ((errorRecord.ErrorDetails != null) && (errorRecord.ErrorDetails.TextLookupError != null)) { Exception textLookupError = errorRecord.ErrorDetails.TextLookupError; errorRecord.ErrorDetails.TextLookupError = null; MshLog.LogProviderHealthEvent(this.Context.ExecutionContext, this.ProviderInfo.Name, textLookupError, Severity.Warning); } ProviderInvocationException exception2 = new ProviderInvocationException(this.ProviderInfo, errorRecord); MshLog.LogProviderHealthEvent(this.Context.ExecutionContext, this.ProviderInfo.Name, exception2, Severity.Warning); throw exception2; } }