/// <summary> /// Initializes a new instance of the CompletionResult class. /// </summary> /// <param name="completionText">The text to be used as the auto completion result.</param> /// <param name="listItemText">The text to be displayed in a list.</param> /// <param name="resultType">The type of completion result.</param> /// <param name="toolTip">The text for the tooltip with details to be displayed about the object.</param> public CompletionResult(string completionText, string listItemText, CompletionResultType resultType, string toolTip) { if (string.IsNullOrEmpty(completionText)) { throw PSTraceSource.NewArgumentNullException(nameof(completionText)); } if (string.IsNullOrEmpty(listItemText)) { throw PSTraceSource.NewArgumentNullException(nameof(listItemText)); } if (resultType < CompletionResultType.Text || resultType > CompletionResultType.DynamicKeyword) { throw PSTraceSource.NewArgumentOutOfRangeException(nameof(resultType), resultType); } if (string.IsNullOrEmpty(toolTip)) { throw PSTraceSource.NewArgumentNullException(nameof(toolTip)); } _completionText = completionText; _listItemText = listItemText; _toolTip = toolTip; _resultType = resultType; }
/// <summary> /// This method is not supported. /// </summary> /// <returns></returns> /// <remarks></remarks> /// <param name="maxRequested"> /// Return no more than maxRequested objects. /// </param> public override Collection <ReturnType> NonBlockingRead(int maxRequested) { if (maxRequested < 0) { throw PSTraceSource.NewArgumentOutOfRangeException(nameof(maxRequested), maxRequested); } if (maxRequested == 0) { return(new Collection <ReturnType>()); } Collection <ReturnType> results = new Collection <ReturnType>(); int readCount = maxRequested; while (readCount > 0) { if (_enumerator.MoveNext(false)) { results.Add(ConvertToReturnType(_enumerator.Current)); continue; } break; } return(results); }
/// <summary> /// Remove multiple items in the collection. /// </summary> /// <param name="index"></param> /// <param name="count"></param> /// <exception cref="PSArgumentOutOfRangeException">when <paramref name="index"/> is out of range.</exception> public void RemoveItem(int index, int count) { lock (_syncObject) { if (index < 0 || index + count > _data.Count) { throw PSTraceSource.NewArgumentOutOfRangeException("index", index); } for (int i = index + count - 1; i >= index; i--) { RecordRemove(_data[i]); _data.RemoveAt(i); } int _numBeforeBuiltInEnd = Math.Min(count, _builtInEnd - index); if (_numBeforeBuiltInEnd > 0) { _builtInEnd -= _numBeforeBuiltInEnd; } return; } }
/// <summary> /// This method is not supported. /// </summary> /// <returns></returns> /// <remarks></remarks> /// <param name="maxRequested"> /// Return no more than maxRequested objects. /// </param> public override Collection <ReturnType> NonBlockingRead(int maxRequested) { if (maxRequested < 0) { throw PSTraceSource.NewArgumentOutOfRangeException(nameof(maxRequested), maxRequested); } if (maxRequested == 0) { return(new Collection <ReturnType>()); } Collection <ReturnType> results = new Collection <ReturnType>(); int readCount = maxRequested; while (readCount > 0) { if (_datastore.Count > 0) { results.Add(ConvertToReturnType((_datastore.ReadAndRemove(1))[0])); readCount--; continue; } break; } return(results); }
public ZipFileItemStream(string archiveName, string path, System.IO.FileMode mode) { ZipArchiveMode zipArchiveMode = ZipArchiveMode.Read; switch (mode) { case FileMode.CreateNew: zipArchiveMode = ZipArchiveMode.Create; break; case FileMode.Create: zipArchiveMode = ZipArchiveMode.Create; break; case FileMode.Open: zipArchiveMode = ZipArchiveMode.Read; break; case FileMode.OpenOrCreate: throw new Exception("Invalid Parameter OpenOrCreate not valid"); break; case FileMode.Truncate: throw new Exception("Invalid Parameter Truncate not valid"); break; case FileMode.Append: zipArchiveMode = ZipArchiveMode.Update; break; } _zipArchive = System.IO.Compression.ZipFile.Open(archiveName, zipArchiveMode); _zipArchiveEntry = _zipArchive.GetEntry(path); if (_zipArchiveEntry.Length >= (int.MaxValue - 56)) { // Note: 2gb - 57 is max va throw PSTraceSource.NewArgumentOutOfRangeException(FileSystemProviderStrings.DriveMaxSizeError, "ZipFile Items must be below 2gb"); } _zipArchiveEntryStream = _zipArchiveEntry.Open(); this._stream = new MemoryStream(); // Note: This part is very Memory Intensive. _zipArchiveEntryStream.CopyTo(_stream); // Sets position to 0 so it can be fresh _stream.Position = 0; }
internal override Collection <object> Read(int count) { if (count < 0) { throw PSTraceSource.NewArgumentOutOfRangeException("count", count); } if (count == 0) { return(new Collection <object>()); } Collection <object> collection = new Collection <object>(); bool flag = false; while ((count > 0) && this.WaitRead()) { try { lock (this._monitorObject) { if (this._objects.Count == 0) { continue; } flag = true; int num = 0; foreach (object obj2 in this._objects) { collection.Add(obj2); num++; if (--count <= 0) { break; } } this._objects.RemoveRange(0, num); } continue; } finally { if (flag) { this.RaiseEvents(); } } } return(collection); }
internal ObjectStream(int capacity) { this._capacity = 0x7fffffff; this._monitorObject = new object(); if ((capacity <= 0) || (capacity > 0x7fffffff)) { throw PSTraceSource.NewArgumentOutOfRangeException("capacity", capacity); } this._capacity = capacity; this._readHandle = new AutoResetEvent(false); this._writeHandle = new AutoResetEvent(true); this._readClosedHandle = new ManualResetEvent(false); this._writeClosedHandle = new ManualResetEvent(false); this._objects = new ArrayList(); this._isOpen = true; }
private HistoryInfo CoreGetEntry(long id) { if (id <= 0L) { throw PSTraceSource.NewArgumentOutOfRangeException("id", id); } if (this._countEntriesInBuffer == 0) { return(null); } if (id > this._countEntriesAdded) { return(null); } return(this._buffer[this.GetIndexFromId(id)]); }
public void RemoveItem(int index) { lock (this._syncObject) { if ((index < 0) || (index >= this._data.Count)) { throw PSTraceSource.NewArgumentOutOfRangeException("index", index); } this.RecordRemove(this._data[index]); this._data.RemoveAt(index); if (index < this._builtInEnd) { this._builtInEnd--; } } }
public BufferCell[,] NewBufferCellArray(int width, int height, BufferCell contents) { if (width <= 0) { throw PSTraceSource.NewArgumentOutOfRangeException("width", width, "MshHostRawUserInterfaceStrings", "NonPositiveNumberErrorTemplate", new object[] { "width" }); } if (height <= 0) { throw PSTraceSource.NewArgumentOutOfRangeException("height", height, "MshHostRawUserInterfaceStrings", "NonPositiveNumberErrorTemplate", new object[] { "height" }); } BufferCell[,] cellArray = new BufferCell[height, width]; switch (this.LengthInBufferCells(contents.Character)) { case 1: for (int i = 0; i < cellArray.GetLength(0); i++) { for (int j = 0; j < cellArray.GetLength(1); j++) { cellArray[i, j] = contents; cellArray[i, j].BufferCellType = BufferCellType.Complete; } } return(cellArray); case 2: { int num4 = ((width % 2) == 0) ? width : (width - 1); for (int k = 0; k < height; k++) { for (int m = 0; m < num4; m++) { cellArray[k, m] = contents; cellArray[k, m].BufferCellType = BufferCellType.Leading; m++; cellArray[k, m] = new BufferCell('\0', contents.ForegroundColor, contents.BackgroundColor, BufferCellType.Trailing); } if (num4 < width) { cellArray[k, num4] = contents; cellArray[k, num4].BufferCellType = BufferCellType.Leading; } } break; } } return(cellArray); }
internal override Collection <object> NonBlockingRead(int maxRequested) { Collection <object> collection = null; bool flag = false; if (maxRequested == 0) { return(new Collection <object>()); } if (maxRequested < 0) { throw PSTraceSource.NewArgumentOutOfRangeException("maxRequested", maxRequested); } try { lock (this._monitorObject) { int count = this._objects.Count; if (count > maxRequested) { count = maxRequested; } if (count > 0) { collection = new Collection <object>(); for (int i = 0; i < count; i++) { collection.Add(this._objects[i]); } flag = true; this._objects.RemoveRange(0, count); } } } finally { if (flag) { this.RaiseEvents(); } } if (collection == null) { collection = new Collection <object>(); } return(collection); }
internal void Remove(T item) { lock (this._syncObject) { int index = this._data.IndexOf(item); if ((index < 0) || (index >= this._data.Count)) { throw PSTraceSource.NewArgumentOutOfRangeException("index", index); } this.RecordRemove(item); this._data.Remove(item); if (index < this._builtInEnd) { this._builtInEnd--; } } }
internal void ClearEntry(long id) { lock (this._syncRoot) { if (id < 0L) { throw PSTraceSource.NewArgumentOutOfRangeException("id", id); } if ((this._countEntriesInBuffer != 0) && (id <= this._countEntriesAdded)) { HistoryInfo info = this.CoreGetEntry(id); if (info != null) { info.Cleared = true; this._countEntriesInBuffer--; } } } }
public void RemoveItem(int index, int count) { lock (this._syncObject) { if ((index < 0) || ((index + count) > this._data.Count)) { throw PSTraceSource.NewArgumentOutOfRangeException("index", index); } for (int i = (index + count) - 1; i >= index; i--) { this.RecordRemove(this._data[i]); this._data.RemoveAt(i); } int num2 = Math.Min(count, this._builtInEnd - index); if (num2 > 0) { this._builtInEnd -= num2; } } }
/// <summary> /// Remove one item from the collection /// </summary> /// <param name="index"></param> /// <exception cref="PSArgumentOutOfRangeException">when <paramref name="index"/> is out of range.</exception> public void RemoveItem(int index) { lock (_syncObject) { if (index < 0 || index >= _data.Count) { throw PSTraceSource.NewArgumentOutOfRangeException("index", index); } RecordRemove(_data[index]); _data.RemoveAt(index); if (index < _builtInEnd) { _builtInEnd--; } return; } }
private static void CheckCoordinateWithinBuffer(ref Coordinates c, ref ConsoleControl.CONSOLE_SCREEN_BUFFER_INFO bufferInfo, string paramName) { if (c.X < 0 || c.X > bufferInfo.BufferSize.X) { object[] bufferSize = new object[1]; bufferSize[0] = bufferInfo.BufferSize; throw PSTraceSource.NewArgumentOutOfRangeException(string.Concat(paramName, ".X"), c.X, "ConsoleHostRawUserInterfaceStrings", "CoordinateOutOfBufferErrorTemplate", bufferSize); } else { if (c.Y < 0 || c.Y > bufferInfo.BufferSize.Y) { object[] objArray = new object[1]; objArray[0] = bufferInfo.BufferSize; throw PSTraceSource.NewArgumentOutOfRangeException(string.Concat(paramName, ".Y"), c.Y, "ConsoleHostRawUserInterfaceStrings", "CoordinateOutOfBufferErrorTemplate", objArray); } else { return; } } }
public override Collection <ReturnType> NonBlockingRead(int maxRequested) { if (maxRequested < 0) { throw PSTraceSource.NewArgumentOutOfRangeException("maxRequested", maxRequested); } if (maxRequested == 0) { return(new Collection <ReturnType>()); } Collection <ReturnType> collection = new Collection <ReturnType>(); for (int i = maxRequested; i > 0; i--) { if (this.datastore.Count <= 0) { return(collection); } collection.Add(this.ConvertToReturnType(this.datastore.ReadAndRemove(1)[0])); } return(collection); }
public override Collection <ReturnType> NonBlockingRead(int maxRequested) { if (maxRequested < 0) { throw PSTraceSource.NewArgumentOutOfRangeException("maxRequested", maxRequested); } if (maxRequested == 0) { return(new Collection <ReturnType>()); } Collection <ReturnType> collection = new Collection <ReturnType>(); int num = maxRequested; while (num > 0) { if (!this.enumerator.MoveNext(false)) { return(collection); } collection.Add(this.ConvertToReturnType(this.enumerator.Current)); } return(collection); }
/// <summary> /// Remove one item from the collection /// </summary> /// <param name="item"></param> internal void Remove(T item) { lock (_syncObject) { int index = _data.IndexOf(item); if (index < 0 || index >= _data.Count) { Dbg.Assert(false, "Index from which to remove the item is out of range."); throw PSTraceSource.NewArgumentOutOfRangeException("index", index); } RecordRemove(item); _data.Remove(item); if (index < _builtInEnd) { _builtInEnd--; } return; } }
/// <summary> /// Given a scope ID, walks the scope list to the appropriate scope and returns it. /// </summary> /// <param name="scopeID"> /// The numeric indexer to the scope relative to the current scope. /// </param> /// <returns> /// The scope at the index specified. The index is relative to the current /// scope. /// </returns> /// <exception cref="ArgumentOutOfRangeException"> /// If <paramref name="scopeID"/> is less than zero or greater than the number of currently /// active scopes. /// </exception> internal SessionStateScope GetScopeByID(int scopeID) { SessionStateScope processingScope = _currentScope; int originalID = scopeID; while (scopeID > 0 && processingScope != null) { processingScope = processingScope.Parent; scopeID--; } if (processingScope == null && scopeID >= 0) { ArgumentOutOfRangeException outOfRange = PSTraceSource.NewArgumentOutOfRangeException( ScopeParameterName, originalID, SessionStateStrings.ScopeIDExceedsAvailableScopes, originalID); throw outOfRange; } return(processingScope); }
/// <summary> /// Given a scope identifier, returns the proper session state scope. /// </summary> /// <param name="scopeID"> /// A scope identifier that is either one of the "special" scopes like /// "global", "local", or "private, or a numeric ID of a relative scope /// to the current scope. /// </param> /// <returns> /// The scope identified by the scope ID or the current scope if the /// scope ID is not defined as a special or numeric scope identifier. /// </returns> /// <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> internal SessionStateScope GetScopeByID(string scopeID) { SessionStateScope result = _currentScope; if (!string.IsNullOrEmpty(scopeID)) { if (string.Equals( scopeID, StringLiterals.Global, StringComparison.OrdinalIgnoreCase)) { result = GlobalScope; } else if (string.Equals( scopeID, StringLiterals.Local, StringComparison.OrdinalIgnoreCase)) { result = _currentScope; } else if (string.Equals( scopeID, StringLiterals.Private, StringComparison.OrdinalIgnoreCase)) { result = _currentScope; } else if (string.Equals( scopeID, StringLiterals.Script, StringComparison.OrdinalIgnoreCase)) { // Get the current script scope from the stack. result = _currentScope.ScriptScope; } else { // Since the scope is not any of the special scopes // try parsing it as an ID try { int scopeNumericID = Int32.Parse(scopeID, System.Globalization.CultureInfo.CurrentCulture); if (scopeNumericID < 0) { throw PSTraceSource.NewArgumentOutOfRangeException(ScopeParameterName, scopeID); } result = GetScopeByID(scopeNumericID) ?? _currentScope; } catch (FormatException) { throw PSTraceSource.NewArgumentException(ScopeParameterName, AutomationExceptions.InvalidScopeIdArgument, ScopeParameterName); } catch (OverflowException) { throw PSTraceSource.NewArgumentOutOfRangeException(ScopeParameterName, scopeID); } } } return(result); }
/// <summary> /// This method is added to be backward compatible with V1 hosts w.r.t /// new PromptForChoice method added in PowerShell V2. /// </summary> /// <param name="caption"></param> /// <param name="message"></param> /// <param name="choices"></param> /// <param name="defaultChoices"></param> /// <returns></returns> /// <exception cref="ArgumentException"> /// 1. Choices is null. /// 2. Choices.Count = 0 /// 3. DefaultChoice is either less than 0 or greater than Choices.Count /// </exception> private Collection <int> EmulatePromptForMultipleChoice(string caption, string message, Collection <ChoiceDescription> choices, IEnumerable <int> defaultChoices) { Dbg.Assert(_externalUI != null, "externalUI cannot be null."); if (choices == null) { throw PSTraceSource.NewArgumentNullException(nameof(choices)); } if (choices.Count == 0) { throw PSTraceSource.NewArgumentException(nameof(choices), InternalHostUserInterfaceStrings.EmptyChoicesError, "choices"); } Dictionary <int, bool> defaultChoiceKeys = new Dictionary <int, bool>(); if (defaultChoices != null) { foreach (int defaultChoice in defaultChoices) { if ((defaultChoice < 0) || (defaultChoice >= choices.Count)) { throw PSTraceSource.NewArgumentOutOfRangeException("defaultChoice", defaultChoice, InternalHostUserInterfaceStrings.InvalidDefaultChoiceForMultipleSelection, "defaultChoice", "choices", defaultChoice); } defaultChoiceKeys.TryAdd(defaultChoice, true); } } // Construct the caption + message + list of choices + default choices Text.StringBuilder choicesMessage = new Text.StringBuilder(); char newLine = '\n'; if (!string.IsNullOrEmpty(caption)) { choicesMessage.Append(caption); choicesMessage.Append(newLine); } if (!string.IsNullOrEmpty(message)) { choicesMessage.Append(message); choicesMessage.Append(newLine); } string[,] hotkeysAndPlainLabels = null; HostUIHelperMethods.BuildHotkeysAndPlainLabels(choices, out hotkeysAndPlainLabels); string choiceTemplate = "[{0}] {1} "; for (int i = 0; i < hotkeysAndPlainLabels.GetLength(1); ++i) { string choice = string.Format( Globalization.CultureInfo.InvariantCulture, choiceTemplate, hotkeysAndPlainLabels[0, i], hotkeysAndPlainLabels[1, i]); choicesMessage.Append(choice); choicesMessage.Append(newLine); } // default choices string defaultPrompt = string.Empty; if (defaultChoiceKeys.Count > 0) { string prepend = string.Empty; Text.StringBuilder defaultChoicesBuilder = new Text.StringBuilder(); foreach (int defaultChoice in defaultChoiceKeys.Keys) { string defaultStr = hotkeysAndPlainLabels[0, defaultChoice]; if (string.IsNullOrEmpty(defaultStr)) { defaultStr = hotkeysAndPlainLabels[1, defaultChoice]; } defaultChoicesBuilder.Append(string.Format(Globalization.CultureInfo.InvariantCulture, "{0}{1}", prepend, defaultStr)); prepend = ","; } string defaultChoicesStr = defaultChoicesBuilder.ToString(); if (defaultChoiceKeys.Count == 1) { defaultPrompt = StringUtil.Format(InternalHostUserInterfaceStrings.DefaultChoice, defaultChoicesStr); } else { defaultPrompt = StringUtil.Format(InternalHostUserInterfaceStrings.DefaultChoicesForMultipleChoices, defaultChoicesStr); } } string messageToBeDisplayed = choicesMessage.ToString() + defaultPrompt + newLine; // read choices from the user Collection <int> result = new Collection <int>(); int choicesSelected = 0; while (true) { string choiceMsg = StringUtil.Format(InternalHostUserInterfaceStrings.ChoiceMessage, choicesSelected); messageToBeDisplayed += choiceMsg; _externalUI.WriteLine(messageToBeDisplayed); string response = _externalUI.ReadLine(); // they just hit enter if (response.Length == 0) { // this may happen when // 1. user wants to go with the defaults // 2. user selected some choices and wanted those // choices to be picked. // user did not pick up any choices..choose the default if ((result.Count == 0) && (defaultChoiceKeys.Keys.Count >= 0)) { // if there's a default, pick that one. foreach (int defaultChoice in defaultChoiceKeys.Keys) { result.Add(defaultChoice); } } // allow for no choice selection. break; } int choicePicked = HostUIHelperMethods.DetermineChoicePicked(response.Trim(), choices, hotkeysAndPlainLabels); if (choicePicked >= 0) { result.Add(choicePicked); choicesSelected++; } // reset messageToBeDisplayed messageToBeDisplayed = string.Empty; } return(result); }
internal HistoryInfo[] GetEntries(long id, long count, SwitchParameter newest) { this.ReallocateBufferIfNeeded(); if (count < -1L) { throw PSTraceSource.NewArgumentOutOfRangeException("count", count); } if (newest.ToString() == null) { throw PSTraceSource.NewArgumentNullException("newest"); } if (((count == -1L) || (count > this._countEntriesAdded)) || (count > this._countEntriesInBuffer)) { count = this._countEntriesInBuffer; } if ((count == 0L) || (this._countEntriesInBuffer == 0)) { return(new HistoryInfo[0]); } lock (this._syncRoot) { ArrayList list = new ArrayList(); if (id > 0L) { long num; long num2 = id; if (!newest.IsPresent) { num = (num2 - count) + 1L; if (num < 1L) { num = 1L; } for (long i = num2; i >= num; i -= 1L) { if (num <= 1L) { break; } if ((this._buffer[this.GetIndexFromId(i)] != null) && this._buffer[this.GetIndexFromId(i)].Cleared) { num -= 1L; } } for (long j = num; j <= num2; j += 1L) { if ((this._buffer[this.GetIndexFromId(j)] != null) && !this._buffer[this.GetIndexFromId(j)].Cleared) { list.Add(this._buffer[this.GetIndexFromId(j)].Clone()); } } } else { num = (num2 + count) - 1L; if (num >= this._countEntriesAdded) { num = this._countEntriesAdded; } for (long k = num2; k <= num; k += 1L) { if (num >= this._countEntriesAdded) { break; } if ((this._buffer[this.GetIndexFromId(k)] != null) && this._buffer[this.GetIndexFromId(k)].Cleared) { num += 1L; } } for (long m = num; m >= num2; m -= 1L) { if ((this._buffer[this.GetIndexFromId(m)] != null) && !this._buffer[this.GetIndexFromId(m)].Cleared) { list.Add(this._buffer[this.GetIndexFromId(m)].Clone()); } } } } else { long num7; long num8 = 0L; if (this._capacity != 0x1000) { num8 = this.SmallestIDinBuffer(); } if (!newest.IsPresent) { num7 = 1L; if ((this._capacity != 0x1000) && (this._countEntriesAdded > this._capacity)) { num7 = num8; } long num9 = count - 1L; while (num9 >= 0L) { if (num7 > this._countEntriesAdded) { break; } if (((num7 <= 0L) || (this.GetIndexFromId(num7) >= this._buffer.Length)) || this._buffer[this.GetIndexFromId(num7)].Cleared) { num7 += 1L; } else { list.Add(this._buffer[this.GetIndexFromId(num7)].Clone()); num9 -= 1L; num7 += 1L; } } } else { num7 = this._countEntriesAdded; long num10 = count - 1L; while (num10 >= 0L) { if ((((this._capacity != 0x1000) && (this._countEntriesAdded > this._capacity)) && (num7 < num8)) || (num7 < 1L)) { break; } if (((num7 <= 0L) || (this.GetIndexFromId(num7) >= this._buffer.Length)) || this._buffer[this.GetIndexFromId(num7)].Cleared) { num7 -= 1L; } else { list.Add(this._buffer[this.GetIndexFromId(num7)].Clone()); num10 -= 1L; num7 -= 1L; } } } } HistoryInfo[] array = new HistoryInfo[list.Count]; list.CopyTo(array); return(array); } }
/// <summary> /// See base class. /// </summary> /// <param name="caption"></param> /// <param name="message"></param> /// <param name="choices"></param> /// <param name="defaultChoice"></param> /// <returns></returns> /// <exception cref="ArgumentNullException"> /// If <paramref name="choices"/> is null. /// </exception> /// <exception cref="ArgumentException"> /// If <paramref name="choices"/>.Count is 0. /// </exception> /// <exception cref="ArgumentOutOfRangeException"> /// If <paramref name="defaultChoice"/> is greater than /// the length of <paramref name="choices"/>. /// </exception> /// <exception cref="PromptingException"> /// when prompt is canceled by, for example, Ctrl-c. /// </exception> public override int PromptForChoice(string caption, string message, Collection <ChoiceDescription> choices, int defaultChoice) { HandleThrowOnReadAndPrompt(); if (choices == null) { throw PSTraceSource.NewArgumentNullException("choices"); } if (choices.Count == 0) { throw PSTraceSource.NewArgumentException("choices", ConsoleHostUserInterfaceStrings.EmptyChoicesErrorTemplate, "choices"); } if ((defaultChoice < -1) || (defaultChoice >= choices.Count)) { throw PSTraceSource.NewArgumentOutOfRangeException("defaultChoice", defaultChoice, ConsoleHostUserInterfaceStrings.InvalidDefaultChoiceErrorTemplate, "defaultChoice", "choice"); } // we lock here so that multiple threads won't interleave the various reads and writes here. lock (_instanceLock) { if (!string.IsNullOrEmpty(caption)) { // Should be a skin lookup WriteLineToConsole(); WriteToConsole(PromptColor, RawUI.BackgroundColor, WrapToCurrentWindowWidth(caption)); WriteLineToConsole(); } if (!string.IsNullOrEmpty(message)) { WriteLineToConsole(WrapToCurrentWindowWidth(message)); } int result = defaultChoice; string[,] hotkeysAndPlainLabels = null; HostUIHelperMethods.BuildHotkeysAndPlainLabels(choices, out hotkeysAndPlainLabels); Dictionary <int, bool> defaultChoiceKeys = new Dictionary <int, bool>(); // add the default choice key only if it is valid. -1 is used to specify // no default. if (defaultChoice >= 0) { defaultChoiceKeys.Add(defaultChoice, true); } do { WriteChoicePrompt(hotkeysAndPlainLabels, defaultChoiceKeys, false); ReadLineResult rlResult; string response = ReadChoiceResponse(out rlResult); if (rlResult == ReadLineResult.endedOnBreak) { string msg = ConsoleHostUserInterfaceStrings.PromptCanceledError; PromptingException e = new PromptingException( msg, null, "PromptForChoiceCanceled", ErrorCategory.OperationStopped); throw e; } if (response.Length == 0) { // they just hit enter. if (defaultChoice >= 0) { // if there's a default, pick that one. result = defaultChoice; break; } continue; } // decide which choice they made. if (response.Trim() == "?") { // show the help ShowChoiceHelp(choices, hotkeysAndPlainLabels); continue; } result = HostUIHelperMethods.DetermineChoicePicked(response.Trim(), choices, hotkeysAndPlainLabels); if (result >= 0) { break; } // their input matched none of the choices, so prompt again }while (true); return(result); } }
/// <summary> /// Presents a dialog allowing the user to choose options from a set of options. /// </summary> /// <param name="caption"> /// Caption to precede or title the prompt. E.g. "Parameters for get-foo (instance 1 of 2)" /// </param> /// <param name="message"> /// A message that describes what the choice is for. /// </param> /// <param name="choices"> /// An Collection of ChoiceDescription objects that describe each choice. /// </param> /// <param name="defaultChoices"> /// The index of the labels in the choices collection element to be presented to the user as /// the default choice(s). /// </param> /// <returns> /// The indices of the choice elements that corresponds to the options selected. /// </returns> /// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.PromptForChoice"/> public Collection <int> PromptForChoice(string caption, string message, Collection <ChoiceDescription> choices, IEnumerable <int> defaultChoices) { HandleThrowOnReadAndPrompt(); if (choices == null) { throw PSTraceSource.NewArgumentNullException("choices"); } if (choices.Count == 0) { throw PSTraceSource.NewArgumentException("choices", ConsoleHostUserInterfaceStrings.EmptyChoicesErrorTemplate, "choices"); } Dictionary <int, bool> defaultChoiceKeys = new Dictionary <int, bool>(); if (defaultChoices != null) { foreach (int defaultChoice in defaultChoices) { if ((defaultChoice < 0) || (defaultChoice >= choices.Count)) { throw PSTraceSource.NewArgumentOutOfRangeException("defaultChoice", defaultChoice, ConsoleHostUserInterfaceStrings.InvalidDefaultChoiceForMultipleSelection, "defaultChoice", "choices", defaultChoice); } if (!defaultChoiceKeys.ContainsKey(defaultChoice)) { defaultChoiceKeys.Add(defaultChoice, true); } } } Collection <int> result = new Collection <int>(); // we lock here so that multiple threads won't interleave the various reads and writes here. lock (_instanceLock) { // write caption on the console, if present. if (!string.IsNullOrEmpty(caption)) { // Should be a skin lookup WriteLineToConsole(); WriteToConsole(PromptColor, RawUI.BackgroundColor, WrapToCurrentWindowWidth(caption)); WriteLineToConsole(); } // write message if (!string.IsNullOrEmpty(message)) { WriteLineToConsole(WrapToCurrentWindowWidth(message)); } string[,] hotkeysAndPlainLabels = null; HostUIHelperMethods.BuildHotkeysAndPlainLabels(choices, out hotkeysAndPlainLabels); WriteChoicePrompt(hotkeysAndPlainLabels, defaultChoiceKeys, true); if (defaultChoiceKeys.Count > 0) { WriteLineToConsole(); } // used to display ChoiceMessage like Choice[0],Choice[1] etc int choicesSelected = 0; do { // write the current prompt string choiceMsg = StringUtil.Format(ConsoleHostUserInterfaceStrings.ChoiceMessage, choicesSelected); WriteToConsole(PromptColor, RawUI.BackgroundColor, WrapToCurrentWindowWidth(choiceMsg)); ReadLineResult rlResult; string response = ReadChoiceResponse(out rlResult); if (rlResult == ReadLineResult.endedOnBreak) { string msg = ConsoleHostUserInterfaceStrings.PromptCanceledError; PromptingException e = new PromptingException( msg, null, "PromptForChoiceCanceled", ErrorCategory.OperationStopped); throw e; } // they just hit enter if (response.Length == 0) { // this may happen when // 1. user wants to go with the defaults // 2. user selected some choices and wanted those // choices to be picked. // user did not pick up any choices..choose the default if ((result.Count == 0) && (defaultChoiceKeys.Keys.Count >= 0)) { // if there's a default, pick that one. foreach (int defaultChoice in defaultChoiceKeys.Keys) { result.Add(defaultChoice); } } // allow for no choice selection. break; } // decide which choice they made. if (response.Trim() == "?") { // show the help ShowChoiceHelp(choices, hotkeysAndPlainLabels); continue; } int choicePicked = HostUIHelperMethods.DetermineChoicePicked(response.Trim(), choices, hotkeysAndPlainLabels); if (choicePicked >= 0) { result.Add(choicePicked); choicesSelected++; } // prompt for multiple choices }while (true); return(result); } }
private Collection <int> EmulatePromptForMultipleChoice(string caption, string message, Collection <ChoiceDescription> choices, IEnumerable <int> defaultChoices) { if (choices == null) { throw PSTraceSource.NewArgumentNullException("choices"); } if (choices.Count == 0) { throw PSTraceSource.NewArgumentException("choices", "InternalHostUserInterfaceStrings", "EmptyChoicesError", new object[] { "choices" }); } Dictionary <int, bool> dictionary = new Dictionary <int, bool>(); if (defaultChoices != null) { foreach (int num in defaultChoices) { if ((num < 0) || (num >= choices.Count)) { throw PSTraceSource.NewArgumentOutOfRangeException("defaultChoice", num, "InternalHostUserInterfaceStrings", "InvalidDefaultChoiceForMultipleSelection", new object[] { "defaultChoice", "choices", num }); } if (!dictionary.ContainsKey(num)) { dictionary.Add(num, true); } } } StringBuilder builder = new StringBuilder(); char ch = '\n'; if (!string.IsNullOrEmpty(caption)) { builder.Append(caption); builder.Append(ch); } if (!string.IsNullOrEmpty(message)) { builder.Append(message); builder.Append(ch); } string[,] hotkeysAndPlainLabels = null; HostUIHelperMethods.BuildHotkeysAndPlainLabels(choices, out hotkeysAndPlainLabels); string format = "[{0}] {1} "; for (int i = 0; i < hotkeysAndPlainLabels.GetLength(1); i++) { string str2 = string.Format(CultureInfo.InvariantCulture, format, new object[] { hotkeysAndPlainLabels[0, i], hotkeysAndPlainLabels[1, i] }); builder.Append(str2); builder.Append(ch); } string str3 = ""; if (dictionary.Count > 0) { string str4 = ""; StringBuilder builder2 = new StringBuilder(); foreach (int num3 in dictionary.Keys) { string str5 = hotkeysAndPlainLabels[0, num3]; if (string.IsNullOrEmpty(str5)) { str5 = hotkeysAndPlainLabels[1, num3]; } builder2.Append(string.Format(CultureInfo.InvariantCulture, "{0}{1}", new object[] { str4, str5 })); str4 = ","; } string str6 = builder2.ToString(); if (dictionary.Count == 1) { str3 = StringUtil.Format(InternalHostUserInterfaceStrings.DefaultChoice, str6); } else { str3 = StringUtil.Format(InternalHostUserInterfaceStrings.DefaultChoicesForMultipleChoices, str6); } } string str7 = builder.ToString() + str3 + ch; Collection <int> collection = new Collection <int>(); int o = 0; while (true) { string str8 = StringUtil.Format(InternalHostUserInterfaceStrings.ChoiceMessage, o); str7 = str7 + str8; this.externalUI.WriteLine(str7); string str9 = this.externalUI.ReadLine(); if (str9.Length == 0) { if ((collection.Count == 0) && (dictionary.Keys.Count >= 0)) { foreach (int num5 in dictionary.Keys) { collection.Add(num5); } } return(collection); } int item = HostUIHelperMethods.DetermineChoicePicked(str9.Trim(), choices, hotkeysAndPlainLabels); if (item >= 0) { collection.Add(item); o++; } str7 = ""; } }
internal HistoryInfo[] GetEntries(WildcardPattern wildcardpattern, long count, SwitchParameter newest) { lock (this._syncRoot) { if (count < -1L) { throw PSTraceSource.NewArgumentOutOfRangeException("count", count); } if (newest.ToString() == null) { throw PSTraceSource.NewArgumentNullException("newest"); } if ((count > this._countEntriesAdded) || (count == -1L)) { count = this._countEntriesInBuffer; } ArrayList list = new ArrayList(); long num = 1L; if (this._capacity != 0x1000) { num = this.SmallestIDinBuffer(); } if (count != 0L) { if (!newest.IsPresent) { long id = 1L; if ((this._capacity != 0x1000) && (this._countEntriesAdded > this._capacity)) { id = num; } long num3 = 0L; while (num3 <= (count - 1L)) { if (id > this._countEntriesAdded) { break; } if (!this._buffer[this.GetIndexFromId(id)].Cleared && wildcardpattern.IsMatch(this._buffer[this.GetIndexFromId(id)].CommandLine.Trim())) { list.Add(this._buffer[this.GetIndexFromId(id)].Clone()); num3 += 1L; } id += 1L; } } else { long num4 = this._countEntriesAdded; long num5 = 0L; while (num5 <= (count - 1L)) { if ((((this._capacity != 0x1000) && (this._countEntriesAdded > this._capacity)) && (num4 < num)) || (num4 < 1L)) { break; } if (!this._buffer[this.GetIndexFromId(num4)].Cleared && wildcardpattern.IsMatch(this._buffer[this.GetIndexFromId(num4)].CommandLine.Trim())) { list.Add(this._buffer[this.GetIndexFromId(num4)].Clone()); num5 += 1L; } num4 -= 1L; } } } else { for (long i = 1L; i <= this._countEntriesAdded; i += 1L) { if (!this._buffer[this.GetIndexFromId(i)].Cleared && wildcardpattern.IsMatch(this._buffer[this.GetIndexFromId(i)].CommandLine.Trim())) { list.Add(this._buffer[this.GetIndexFromId(i)].Clone()); } } } HistoryInfo[] array = new HistoryInfo[list.Count]; list.CopyTo(array); return(array); } }