Ejemplo n.º 1
0
        /// <summary>
        /// Efficiently multiplies collection by integer.
        /// </summary>
        /// <param name="array">Collection to multiply.</param>
        /// <param name="times">Number of times the collection is to be multiplied/copied.</param>
        /// <returns>Collection multiplied by integer.</returns>
        internal static T[] Multiply <T>(T[] array, uint times)
        {
            Diagnostics.Assert(array != null, "Caller should verify the arguments for array multiplication");

            if (times == 1)
            {
                return(array);
            }

            if (times == 0 || array.Length == 0)
            {
#pragma warning disable CA1825 // Avoid zero-length array allocations
                // Don't use Array.Empty<T>(); always return a new instance.
                return(new T[0]);

#pragma warning restore CA1825 // Avoid zero-length array allocations
            }

            var context = LocalPipeline.GetExecutionContextFromTLS();
            if (context != null &&
                context.LanguageMode == PSLanguageMode.RestrictedLanguage && (array.Length * times) > 1024)
            {
                throw InterpreterError.NewInterpreterException(times, typeof(RuntimeException),
                                                               null, "ArrayMultiplyToolongInDataSection", ParserStrings.ArrayMultiplyToolongInDataSection, 1024);
            }

            var uncheckedLength = array.Length * times;
            int elements        = -1;
            try
            {
                elements = checked ((int)uncheckedLength);
            }
            catch (OverflowException)
            {
                LanguagePrimitives.ThrowInvalidCastException(uncheckedLength, typeof(int));
            }

            // Make the minimum number of calls to Array.Copy by doubling the array up to
            // the most significant bit in times, then do one final Array.Copy to get the
            // remaining copies.

            T[] result       = new T[elements];
            int resultLength = array.Length;
            Array.Copy(array, 0, result, 0, resultLength);
            times >>= 1;
            while (times != 0)
            {
                Array.Copy(result, 0, result, resultLength, resultLength);
                resultLength *= 2;
                times       >>= 1;
            }

            if (result.Length != resultLength)
            {
                Array.Copy(result, 0, result, resultLength, (result.Length - resultLength));
            }

            return(result);
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Execute formatting on a single object.
        /// </summary>
        /// <param name="input">Object to process.</param>
        private void ProcessObject(PSObject input)
        {
            // Make sure the OGV window is not closed.
            if (_windowProxy.IsWindowClosed())
            {
                LocalPipeline pipeline = (LocalPipeline)this.Context.CurrentRunspace.GetCurrentlyRunningPipeline();

                if (pipeline != null && !pipeline.IsStopping)
                {
                    // Stop the pipeline cleanly.
                    pipeline.StopAsync();
                }

                return;
            }

            object baseObject = input.BaseObject;

            // Throw a terminating error for types that are not supported.
            if (baseObject is ScriptBlock ||
                baseObject is SwitchParameter ||
                baseObject is PSReference ||
                baseObject is FormatInfoData ||
                baseObject is PSObject)
            {
                ErrorRecord error = new ErrorRecord(
                    new FormatException(StringUtil.Format(FormatAndOut_out_gridview.DataNotQualifiedForGridView)),
                    DataNotQualifiedForGridView,
                    ErrorCategory.InvalidType,
                    null);

                this.ThrowTerminatingError(error);
            }

            if (_gridHeader == null)
            {
                // Columns have not been added yet; Start the main window and add columns.
                _windowProxy.ShowWindow();
                _gridHeader = GridHeader.ConstructGridHeader(input, this);
            }
            else
            {
                _gridHeader.ProcessInputObject(input);
            }

            // Some thread synchronization needed.
            Exception exception = _windowProxy.GetLastException();

            if (exception != null)
            {
                ErrorRecord error = new ErrorRecord(
                    exception,
                    "ManagementListInvocationException",
                    ErrorCategory.OperationStopped,
                    null);

                this.ThrowTerminatingError(error);
            }
        }
Ejemplo n.º 3
0
        internal static bool SuspendStoppingPipeline(ExecutionContext context)
        {
            LocalPipeline currentlyRunningPipeline = (LocalPipeline)context.CurrentRunspace.GetCurrentlyRunningPipeline();
            bool          isStopping = currentlyRunningPipeline.Stopper.IsStopping;

            currentlyRunningPipeline.Stopper.IsStopping = false;
            return(isStopping);
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Constructs the MergedCommandParameterMetadata, using any arguments that
        /// may have been specified so that dynamic parameters can be determined, if any.
        /// </summary>
        /// <returns></returns>
        private MergedCommandParameterMetadata GetMergedCommandParameterMetadataSafely()
        {
            if (_context == null)
            {
                return(null);
            }

            MergedCommandParameterMetadata result;

            if (_context != LocalPipeline.GetExecutionContextFromTLS())
            {
                // In the normal case, _context is from the thread we're on, and we won't get here.
                // But, if it's not, we can't safely get the parameter metadata without running on
                // on the correct thread, because that thread may be busy doing something else.
                // One of the things we do here is change the current scope in execution context,
                // that can mess up the runspace our CommandInfo object came from.

                var runspace = (RunspaceBase)_context.CurrentRunspace;
                if (runspace.CanRunActionInCurrentPipeline())
                {
                    GetMergedCommandParameterMetadata(out result);
                }
                else
                {
                    _context.Events.SubscribeEvent(
                        source: null,
                        eventName: PSEngineEvent.GetCommandInfoParameterMetadata,
                        sourceIdentifier: PSEngineEvent.GetCommandInfoParameterMetadata,
                        data: null,
                        handlerDelegate: new PSEventReceivedEventHandler(OnGetMergedCommandParameterMetadataSafelyEventHandler),
                        supportEvent: true,
                        forwardEvent: false,
                        shouldQueueAndProcessInExecutionThread: true,
                        maxTriggerCount: 1);

                    var eventArgs = new GetMergedCommandParameterMetadataSafelyEventArgs();

                    _context.Events.GenerateEvent(
                        sourceIdentifier: PSEngineEvent.GetCommandInfoParameterMetadata,
                        sender: null,
                        args: new[] { eventArgs },
                        extraData: null,
                        processInCurrentThread: true,
                        waitForCompletionInCurrentThread: true);

                    if (eventArgs.Exception != null)
                    {
                        // An exception happened on a different thread, rethrow it here on the correct thread.
                        eventArgs.Exception.Throw();
                    }

                    return(eventArgs.Result);
                }
            }

            GetMergedCommandParameterMetadata(out result);
            return(result);
        }
Ejemplo n.º 5
0
        private void ReplaceHistoryString(HistoryInfo entry)
        {
            LocalPipeline currentlyRunningPipeline = (LocalPipeline)((LocalRunspace)base.Context.CurrentRunspace).GetCurrentlyRunningPipeline();

            if (currentlyRunningPipeline.AddToHistory)
            {
                currentlyRunningPipeline.HistoryString = entry.CommandLine;
            }
        }
Ejemplo n.º 6
0
        internal static void Trace(int level, string messageId, string resourceString, params object[] args)
        {
            ExecutionContext executionContextFromTLS = LocalPipeline.GetExecutionContextFromTLS();

            if (executionContextFromTLS != null)
            {
                Trace(executionContextFromTLS, level, messageId, resourceString, args);
            }
        }
Ejemplo n.º 7
0
        private static CommandCompletion CompleteInputImpl(Ast ast, Token[] tokens, IScriptPosition positionOfCursor, Hashtable options)
        {
            PowerShell powershell        = PowerShell.Create(RunspaceMode.CurrentRunspace);
            int        replacementIndex  = -1;
            int        replacementLength = -1;
            List <CompletionResult> list = null;

            if (NeedToInvokeLegacyTabExpansion(powershell))
            {
                Tuple <string, int, int> inputAndCursorFromAst = GetInputAndCursorFromAst(positionOfCursor);
                list              = InvokeLegacyTabExpansion(powershell, inputAndCursorFromAst.Item1, inputAndCursorFromAst.Item2, false, out replacementIndex, out replacementLength);
                replacementIndex += inputAndCursorFromAst.Item3;
            }
            if ((list == null) || (list.Count == 0))
            {
                ExecutionContext executionContextFromTLS = LocalPipeline.GetExecutionContextFromTLS();
                MutableTuple     tuple2 = null;
                foreach (CallStackFrame frame in executionContextFromTLS.Debugger.GetCallStack())
                {
                    dynamic obj2  = PSObject.AsPSObject(frame);
                    var     site1 = CallSite <Func <CallSite, object, bool> > .Create(Binder.UnaryOperation(CSharpBinderFlags.None, ExpressionType.IsTrue, typeof(CommandCompletion), new CSharpArgumentInfo[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) }));

                    if (site1.Target(site1, obj2.Command.Equals("TabExpansion2", StringComparison.OrdinalIgnoreCase)))
                    {
                        tuple2 = frame.FunctionContext._localsTuple;
                        break;
                    }
                }
                SessionStateScope currentScope = null;
                if (tuple2 != null)
                {
                    currentScope = executionContextFromTLS.EngineSessionState.CurrentScope;
                    SessionStateScope parent = executionContextFromTLS.EngineSessionState.CurrentScope;
                    while ((parent != null) && (parent.LocalsTuple != tuple2))
                    {
                        parent = parent.Parent;
                    }
                    if (parent != null)
                    {
                        executionContextFromTLS.EngineSessionState.CurrentScope = parent.Parent;
                    }
                }
                try
                {
                    list = new CompletionAnalysis(ast, tokens, positionOfCursor, options).GetResults(powershell, out replacementIndex, out replacementLength);
                }
                finally
                {
                    if (currentScope != null)
                    {
                        executionContextFromTLS.EngineSessionState.CurrentScope = currentScope;
                    }
                }
            }
            return(new CommandCompletion(new Collection <CompletionResult>(list ?? EmptyCompletionResult), -1, replacementIndex, replacementLength));
        }
Ejemplo n.º 8
0
        private static Assembly PowerShellAssemblyResolveHandler(object sender, ResolveEventArgs args)
        {
            ExecutionContext executionContextFromTLS = LocalPipeline.GetExecutionContextFromTLS();

            if (((executionContextFromTLS != null) && (executionContextFromTLS._assemblyCache != null)) && executionContextFromTLS._assemblyCache.ContainsKey(args.Name))
            {
                return(executionContextFromTLS._assemblyCache[args.Name]);
            }
            return(null);
        }
Ejemplo n.º 9
0
        private void ReplaceHistoryString(HistoryInfo entry)
        {
            LocalPipeline currentlyRunningPipeline = (LocalPipeline)this.Context.CurrentRunspace.GetCurrentlyRunningPipeline();

            if (!currentlyRunningPipeline.AddToHistory)
            {
                return;
            }
            currentlyRunningPipeline.HistoryString = entry.CommandLine;
        }
Ejemplo n.º 10
0
        internal static TypeTable GetTypeTableFromTLS()
        {
            ExecutionContext executionContextFromTLS = LocalPipeline.GetExecutionContextFromTLS();

            if (executionContextFromTLS == null)
            {
                return(null);
            }
            return(executionContextFromTLS.TypeTable);
        }
Ejemplo n.º 11
0
        internal static void Trace(int level, string messageId, params object[] args)
        {
            ExecutionContext executionContextFromTls = LocalPipeline.GetExecutionContextFromTLS();

            if (executionContextFromTls == null)
            {
                return;
            }
            ScriptTrace.Trace(executionContextFromTls, level, messageId, args);
        }
Ejemplo n.º 12
0
        public SessionState()
        {
            ExecutionContext executionContextFromTLS = LocalPipeline.GetExecutionContextFromTLS();

            if (executionContextFromTLS == null)
            {
                throw new InvalidOperationException("ExecutionContext");
            }
            this.sessionState = new SessionStateInternal(executionContextFromTLS);
            this.sessionState.PublicSessionState = this;
        }
Ejemplo n.º 13
0
 public PSModuleInfo(bool linkToGlobal)
 {
     this._context = LocalPipeline.GetExecutionContextFromTLS();
     if (this._context == null)
     {
         throw new InvalidOperationException(nameof(PSModuleInfo));
     }
     PSModuleInfo.SetDefaultDynamicNameAndPath(this);
     this._sessionState = new SessionState(this._context.EngineSessionState, true, linkToGlobal);
     this._sessionState.Internal.Module = this;
 }
Ejemplo n.º 14
0
        /// <summary>
        /// This method calls all Validate attributes for the property to validate value.
        /// Called from class property setters with ValidateArgumentsAttribute attributes.
        /// </summary>
        /// <param name="type"></param>
        /// <param name="propertyName"></param>
        /// <param name="value"></param>
        public static void ValidateSetProperty(Type type, string propertyName, object value)
        {
            var validateAttributes = type.GetProperty(propertyName).GetCustomAttributes <ValidateArgumentsAttribute>();
            var executionContext   = LocalPipeline.GetExecutionContextFromTLS();
            var engineIntrinsics   = executionContext == null ? null : executionContext.EngineIntrinsics;

            foreach (var validateAttribute in validateAttributes)
            {
                validateAttribute.InternalValidate(value, engineIntrinsics);
            }
        }
Ejemplo n.º 15
0
 internal void PopPipelineProcessor(bool fromSteppablePipeline)
 {
     if (this.currentRunspace != null)
     {
         LocalPipeline currentlyRunningPipeline = (LocalPipeline)((RunspaceBase)this.currentRunspace).GetCurrentlyRunningPipeline();
         if (currentlyRunningPipeline != null)
         {
             currentlyRunningPipeline.Stopper.Pop(fromSteppablePipeline);
         }
     }
 }
Ejemplo n.º 16
0
        internal SessionState(SessionStateInternal parent, bool createAsChild, bool linkToGlobal)
        {
            ExecutionContext executionContextFromTls = LocalPipeline.GetExecutionContextFromTLS();

            if (executionContextFromTls == null)
            {
                throw new InvalidOperationException("ExecutionContext");
            }
            this.sessionState = !createAsChild ? new SessionStateInternal(executionContextFromTls) : new SessionStateInternal(parent, linkToGlobal, executionContextFromTls);
            this.sessionState.PublicSessionState = this;
        }
Ejemplo n.º 17
0
        internal void DebuggerCheckVariableWrite()
        {
            var context = SessionState != null
                              ? SessionState.ExecutionContext
                              : LocalPipeline.GetExecutionContextFromTLS();

            if (context != null && context._debuggingMode > 0)
            {
                context.Debugger.CheckVariableWrite(Name);
            }
        }
Ejemplo n.º 18
0
 internal void PushPipelineProcessor(PipelineProcessor pp)
 {
     if (this.currentRunspace != null)
     {
         LocalPipeline currentlyRunningPipeline = (LocalPipeline)((RunspaceBase)this.currentRunspace).GetCurrentlyRunningPipeline();
         if (currentlyRunningPipeline != null)
         {
             currentlyRunningPipeline.Stopper.Push(pp);
         }
     }
 }
Ejemplo n.º 19
0
        internal static SteppablePipeline GetSteppablePipeline(PipelineAst pipelineAst, CommandOrigin commandOrigin)
        {
            PipelineProcessor pipe = new PipelineProcessor();

            System.Management.Automation.ExecutionContext executionContextFromTLS = LocalPipeline.GetExecutionContextFromTLS();
            foreach (CommandAst ast in pipelineAst.PipelineElements.Cast <CommandAst>())
            {
                List <CommandParameterInternal> list = new List <CommandParameterInternal>();
                foreach (CommandElementAst ast2 in ast.CommandElements)
                {
                    CommandParameterAst commandParameterAst = ast2 as CommandParameterAst;
                    if (commandParameterAst != null)
                    {
                        list.Add(GetCommandParameter(commandParameterAst, executionContextFromTLS));
                    }
                    else
                    {
                        ExpressionAst expressionAst = (ExpressionAst)ast2;
                        object        obj2          = Compiler.GetExpressionValue(expressionAst, executionContextFromTLS, (IList)null);
                        bool          splatted      = (expressionAst is VariableExpressionAst) && ((VariableExpressionAst)expressionAst).Splatted;
                        list.Add(CommandParameterInternal.CreateArgument(expressionAst.Extent, obj2, splatted));
                    }
                }
                List <CommandRedirection> list2 = new List <CommandRedirection>();
                foreach (RedirectionAst ast5 in ast.Redirections)
                {
                    list2.Add(GetCommandRedirection(ast5, executionContextFromTLS));
                }
                CommandProcessorBase base2 = AddCommand(pipe, list.ToArray(), ast, list2.ToArray(), executionContextFromTLS);
                base2.Command.CommandOriginInternal      = commandOrigin;
                base2.CommandScope.ScopeOrigin           = commandOrigin;
                base2.Command.MyInvocation.CommandOrigin = commandOrigin;
                CallStackFrame[] frameArray = executionContextFromTLS.Debugger.GetCallStack().ToArray <CallStackFrame>();
                if ((frameArray.Length > 0) && Regex.IsMatch(frameArray[0].Position.Text, "GetSteppablePipeline", RegexOptions.IgnoreCase))
                {
                    InvocationInfo myInvocation = base2.Command.MyInvocation;
                    myInvocation.InvocationName = frameArray[0].InvocationInfo.InvocationName;
                    if (frameArray.Length > 1)
                    {
                        IScriptExtent position = frameArray[1].Position;
                        if ((position != null) && (position != PositionUtilities.EmptyExtent))
                        {
                            myInvocation.DisplayScriptPosition = position;
                        }
                    }
                }
                if ((executionContextFromTLS.CurrentCommandProcessor != null) && (executionContextFromTLS.CurrentCommandProcessor.CommandRuntime != null))
                {
                    base2.CommandRuntime.SetMergeFromRuntime(executionContextFromTLS.CurrentCommandProcessor.CommandRuntime);
                }
            }
            return(new SteppablePipeline(executionContextFromTLS, pipe));
        }
Ejemplo n.º 20
0
 public WmiBaseCmdlet()
 {
     string[] strArrays = new string[1];
     strArrays[0]             = "localhost";
     this.computerName        = strArrays;
     this.nameSpace           = "root\\cimv2";
     this.impersonationLevel  = ImpersonationLevel.Impersonate;
     this.authenticationLevel = AuthenticationLevel.Packet;
     this.async         = false;
     this.throttleLimit = WmiBaseCmdlet.DEFAULT_THROTTLE_LIMIT;
     this._context      = LocalPipeline.GetExecutionContextFromTLS();
 }
Ejemplo n.º 21
0
 internal static bool IsStrictVersion(ExecutionContext context, int majorVersion)
 {
     if (context == null)
     {
         context = LocalPipeline.GetExecutionContextFromTLS();
     }
     if (context == null)
     {
         return(false);
     }
     return(context.IsStrictVersion(majorVersion));
 }
Ejemplo n.º 22
0
        public PSModuleInfo(ScriptBlock scriptBlock)
        {
            this._name                         = string.Empty;
            this._path                         = string.Empty;
            this._description                  = string.Empty;
            this._version                      = new System.Version(0, 0);
            this._detectedFunctionExports      = new List <string>();
            this._detectedWorkflowExports      = new List <string>();
            this._detectedCmdletExports        = new List <string>();
            this._compiledExports              = new List <CmdletInfo>();
            this._fileList                     = new List <string>();
            this._moduleList                   = new Collection <object>();
            this._nestedModules                = new List <PSModuleInfo>();
            this._scripts                      = new List <string>();
            this._requiredAssemblies           = new Collection <string>();
            this._requiredModules              = new List <PSModuleInfo>();
            this._requiredModulesSpecification = new List <ModuleSpecification>();
            this._detectedAliasExports         = new Dictionary <string, string>();
            this._exportedFormatFiles          = new ReadOnlyCollection <string>(new List <string>());
            this._exportedTypeFiles            = new ReadOnlyCollection <string>(new List <string>());
            if (scriptBlock == null)
            {
                throw PSTraceSource.NewArgumentException("scriptBlock");
            }
            ExecutionContext executionContextFromTLS = LocalPipeline.GetExecutionContextFromTLS();

            if (executionContextFromTLS == null)
            {
                throw new InvalidOperationException("PSModuleInfo");
            }
            SetDefaultDynamicNameAndPath(this);
            this._sessionState = new System.Management.Automation.SessionState(executionContextFromTLS, true, true);
            this._sessionState.Internal.Module = this;
            SessionStateInternal engineSessionState = executionContextFromTLS.EngineSessionState;

            try
            {
                executionContextFromTLS.EngineSessionState = this._sessionState.Internal;
                executionContextFromTLS.SetVariable(SpecialVariables.PSScriptRootVarPath, this._path);
                scriptBlock = scriptBlock.Clone(true);
                scriptBlock.SessionState = this._sessionState;
                Pipe outputPipe = new Pipe {
                    NullPipe = true
                };
                scriptBlock.InvokeWithPipe(false, ScriptBlock.ErrorHandlingBehavior.WriteToCurrentErrorPipe, AutomationNull.Value, AutomationNull.Value, AutomationNull.Value, outputPipe, null, new object[0]);
            }
            finally
            {
                executionContextFromTLS.EngineSessionState = engineSessionState;
            }
        }
Ejemplo n.º 23
0
        internal static BindingRestrictions GetLanguageModeCheckIfHasEverUsedConstrainedLanguage()
        {
            BindingRestrictions empty = BindingRestrictions.Empty;

            if (!ExecutionContext.HasEverUsedConstrainedLanguage)
            {
                return(empty);
            }
            if (LocalPipeline.GetExecutionContextFromTLS().LanguageMode == PSLanguageMode.ConstrainedLanguage)
            {
                return(BindingRestrictions.GetExpressionRestriction(Expression.Equal(Expression.Property(ExpressionCache.GetExecutionContextFromTLS, CachedReflectionInfo.ExecutionContext_LanguageMode), Expression.Constant(PSLanguageMode.ConstrainedLanguage))));
            }
            return(BindingRestrictions.GetExpressionRestriction(Expression.NotEqual(Expression.Property(ExpressionCache.GetExecutionContextFromTLS, CachedReflectionInfo.ExecutionContext_LanguageMode), Expression.Constant(PSLanguageMode.ConstrainedLanguage))));
        }
Ejemplo n.º 24
0
        internal static TypeResolutionState GetDefaultUsingState(ExecutionContext context)
        {
            if (context == null)
            {
                context = LocalPipeline.GetExecutionContextFromTLS();
            }

            if (context != null)
            {
                return(context.EngineSessionState.CurrentScope.TypeResolutionState);
            }

            return(TypeResolutionState.UsingSystem);
        }
Ejemplo n.º 25
0
        internal ScriptBlockAst GetScriptBlockAst()
        {
            var scriptContents = ScriptContents;

            if (_scriptBlock == null)
            {
                this.ScriptBlock = ScriptBlock.TryGetCachedScriptBlock(_path, scriptContents);
            }

            if (_scriptBlock != null)
            {
                return((ScriptBlockAst)_scriptBlock.Ast);
            }

            if (_scriptBlockAst == null)
            {
                ParseError[] errors;
                Parser       parser = new Parser();

                // If we are in ConstrainedLanguage mode but the defining language mode is FullLanguage, then we need
                // to parse the script contents in FullLanguage mode context.  Otherwise we will get bogus parsing errors
                // such as "Configuration or Class keyword not allowed".
                var context = LocalPipeline.GetExecutionContextFromTLS();
                if (context != null && context.LanguageMode == PSLanguageMode.ConstrainedLanguage &&
                    DefiningLanguageMode == PSLanguageMode.FullLanguage)
                {
                    context.LanguageMode = PSLanguageMode.FullLanguage;
                    try
                    {
                        _scriptBlockAst = parser.Parse(_path, ScriptContents, null, out errors, ParseMode.Default);
                    }
                    finally
                    {
                        context.LanguageMode = PSLanguageMode.ConstrainedLanguage;
                    }
                }
                else
                {
                    _scriptBlockAst = parser.Parse(_path, ScriptContents, null, out errors, ParseMode.Default);
                }

                if (errors.Length == 0)
                {
                    this.ScriptBlock = new ScriptBlock(_scriptBlockAst, isFilter: false);
                    ScriptBlock.CacheScriptBlock(_scriptBlock.Clone(), _path, scriptContents);
                }
            }

            return(_scriptBlockAst);
        }
        /// <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)
        {
            if (_externalUI == null)
            {
                ThrowPromptNotInteractive(message);
            }

            IHostUISupportsMultipleChoiceSelection hostForMultipleChoices =
                _externalUI as IHostUISupportsMultipleChoiceSelection;

            Collection <int> result = null;

            try
            {
                if (hostForMultipleChoices == null)
                {
                    // host did not implement this new interface..
                    // so work with V1 host API to get the behavior..
                    // this will allow Hosts that were developed with
                    // V1 API to interact with PowerShell V2.
                    result = EmulatePromptForMultipleChoice(caption, message, choices, defaultChoices);
                }
                else
                {
                    result = hostForMultipleChoices.PromptForChoice(caption, message, choices, defaultChoices);
                }
            }
            catch (PipelineStoppedException)
            {
                // PipelineStoppedException is thrown by host when it wants
                // to stop the pipeline.
                LocalPipeline lpl = (LocalPipeline)((RunspaceBase)_parent.Context.CurrentRunspace).GetCurrentlyRunningPipeline();
                if (lpl == null)
                {
                    throw;
                }

                lpl.Stopper.Stop();
            }

            return(result);
        }
Ejemplo n.º 27
0
        internal static object GetNonIndexable(object target, object[] indices)
        {
            if (indices.Length == 1)
            {
                object second = indices[0];
                if ((second != null) && (LanguagePrimitives.Equals(0, second) || LanguagePrimitives.Equals(-1, second)))
                {
                    return(target);
                }
            }
            ExecutionContext executionContextFromTLS = LocalPipeline.GetExecutionContextFromTLS();

            if ((executionContextFromTLS != null) && executionContextFromTLS.IsStrictVersion(2))
            {
                throw InterpreterError.NewInterpreterException(target, typeof(RuntimeException), null, "CannotIndex", ParserStrings.CannotIndex, new object[] { target.GetType() });
            }
            return(AutomationNull.Value);
        }
Ejemplo n.º 28
0
 internal static void CheckForSevereException(Exception e)
 {
     if ((e is AccessViolationException) || (e is StackOverflowException))
     {
         try
         {
             if (!alreadyFailing)
             {
                 alreadyFailing = true;
                 MshLog.LogCommandHealthEvent(LocalPipeline.GetExecutionContextFromTLS(), e, Severity.Critical);
             }
         }
         finally
         {
             WindowsErrorReporting.FailFast(e);
         }
     }
 }
Ejemplo n.º 29
0
        internal static object SetAdaptedValue(object obj, string member, object value)
        {
            object obj2;

            try
            {
                ExecutionContext executionContextFromTLS = LocalPipeline.GetExecutionContextFromTLS();
                PSMemberInfo     memberInfo = null;
                if ((executionContextFromTLS != null) && (executionContextFromTLS.TypeTable != null))
                {
                    ConsolidatedString typeNames = PSObject.GetTypeNames(obj);
                    memberInfo = executionContextFromTLS.TypeTable.GetMembers <PSMemberInfo>(typeNames)[member];
                    if (memberInfo != null)
                    {
                        memberInfo = PSGetMemberBinder.CloneMemberInfo(memberInfo, obj);
                    }
                }
                PSObject.AdapterSet mappedAdapter = PSObject.GetMappedAdapter(obj, (executionContextFromTLS != null) ? executionContextFromTLS.TypeTable : null);
                if (memberInfo == null)
                {
                    memberInfo = mappedAdapter.OriginalAdapter.BaseGetMember <PSMemberInfo>(obj, member);
                }
                if ((memberInfo == null) && (mappedAdapter.DotNetAdapter != null))
                {
                    memberInfo = mappedAdapter.DotNetAdapter.BaseGetMember <PSMemberInfo>(obj, member);
                }
                if (memberInfo == null)
                {
                    throw InterpreterError.NewInterpreterException(null, typeof(RuntimeException), null, "PropertyAssignmentException", ParserStrings.PropertyNotFound, new object[] { member });
                }
                memberInfo.Value = value;
                obj2             = value;
            }
            catch (SetValueException)
            {
                throw;
            }
            catch (Exception exception)
            {
                ExceptionHandlingOps.ConvertToMethodInvocationException(exception, typeof(SetValueInvocationException), member, 0, null);
                throw;
            }
            return(obj2);
        }
Ejemplo n.º 30
0
        internal static T[] Multiply <T>(T[] array, int times)
        {
            if (times == 1)
            {
                return(array);
            }
            if ((times == 0) || (array.Length == 0))
            {
                return(new T[0]);
            }
            ExecutionContext executionContextFromTLS = LocalPipeline.GetExecutionContextFromTLS();

            if (((executionContextFromTLS != null) && (executionContextFromTLS.LanguageMode == PSLanguageMode.RestrictedLanguage)) && ((array.Length * times) > 0x400L))
            {
                throw InterpreterError.NewInterpreterException(times, typeof(RuntimeException), null, "ArrayMultiplyToolongInDataSection", ParserStrings.ArrayMultiplyToolongInDataSection, new object[] { 0x400 });
            }
            long valueToConvert = array.Length * times;
            int  num2           = -1;

            try
            {
                num2 = (int)valueToConvert;
            }
            catch (OverflowException)
            {
                LanguagePrimitives.ThrowInvalidCastException(valueToConvert, typeof(int));
            }
            T[] destinationArray = new T[num2];
            int length           = array.Length;

            Array.Copy(array, 0, destinationArray, 0, length);
            times = times >> 1;
            while (times != 0)
            {
                Array.Copy(destinationArray, 0, destinationArray, length, length);
                length *= 2;
                times   = times >> 1;
            }
            if (destinationArray.Length != length)
            {
                Array.Copy(destinationArray, 0, destinationArray, length, destinationArray.Length - length);
            }
            return(destinationArray);
        }
Ejemplo n.º 31
0
        public override Pipeline CreatePipeline(string command, bool addToHistory)
        {
            // TODO: take care of the command history
            // TODO: make sure to fail if not Open
            LocalPipeline pipeline = new LocalPipeline(this, command);

            return pipeline;
        }