Example #1
0
 partial void BeforeCreatePipeline(System.Management.Automation.InvocationInfo invocationInfo, ref Runtime.HttpPipeline pipeline)
 {
     // Call Init to trigger any custom initialization needed after
     // module load and before pipeline is setup and used.
     Init();
     pipeline = new Runtime.HttpPipeline(new Runtime.HttpClientFactory(HttpHelpers.GetGraphHttpClient()));
 }
 internal static TerminatingErrorTracker GetTracker(InvocationInfo invocationInfo)
 {
     TerminatingErrorTracker tracker;
     bool foundTracker = s_invocationToTracker.TryGetValue(invocationInfo, out tracker);
     Dbg.Assert(foundTracker, "The other overload of GetTracker should always be called first");
     return tracker;
 }
Example #3
0
 internal void InternalDispose(bool isDisposing)
 {
     this.myInvocation = null;
     this.state = null;
     this.commandInfo = null;
     this.context = null;
 }
Example #4
0
        /// <summary>
        /// Instantiates a new instance of the CmdletInvocationException class
        /// </summary>
        /// <param name="innerException">wrapped exception</param>
        /// <param name="invocationInfo">
        /// identity of cmdlet, null is unknown
        /// </param>
        internal CmdletInvocationException(Exception innerException,
                                           InvocationInfo invocationInfo)
            : base(RetrieveMessage(innerException), innerException)
        {
            if (null == innerException)
            {
                throw new ArgumentNullException("innerException");
            }
            // invocationInfo may be null

            IContainsErrorRecord icer = innerException as IContainsErrorRecord;
            if (null != icer && null != icer.ErrorRecord)
            {
                _errorRecord = new ErrorRecord(icer.ErrorRecord, innerException);
            }
            else
            {
                // When no ErrorId is specified by a thrown exception,
                //  we use innerException.GetType().FullName.
                _errorRecord = new ErrorRecord(
                    innerException,
                    innerException.GetType().FullName,
                    ErrorCategory.NotSpecified,
                    null);
            }
            _errorRecord.SetInvocationInfo(invocationInfo);
            // 2005/04/13-JonN Can't do this in an unsealed class: HelpLink = innerException.HelpLink;
            // Exception.Source is set by Throw
            // Source = innerException.Source;
        }
        internal static TerminatingErrorTracker GetTracker(InvocationInfo invocationInfo, bool isStaticCmdlet)
        {
            var tracker = s_invocationToTracker.GetValue(
                invocationInfo,
                _ => new TerminatingErrorTracker(GetNumberOfSessions(invocationInfo)));

            return tracker;
        }
 internal ActionPreferenceStopException(InvocationInfo invocationInfo, System.Management.Automation.ErrorRecord errorRecord, string baseName, string resourceId, params object[] args) : this(invocationInfo, baseName, resourceId, args)
 {
     if (errorRecord == null)
     {
         throw new ArgumentNullException("errorRecord");
     }
     this._errorRecord = errorRecord;
 }
 internal CmdletProviderInvocationException(System.Management.Automation.ProviderInvocationException innerException, InvocationInfo myInvocation) : base(GetInnerException(innerException), myInvocation)
 {
     if (innerException == null)
     {
         throw new ArgumentNullException("innerException");
     }
     this._providerInvocationException = innerException;
 }
 internal ParameterBindingValidationException(Exception innerException, ErrorCategory errorCategory, InvocationInfo invocationInfo, IScriptExtent errorPosition, string parameterName, Type parameterType, Type typeSpecified, string resourceBaseName, string errorIdAndResourceId, params object[] args) : base(innerException, errorCategory, invocationInfo, errorPosition, parameterName, parameterType, typeSpecified, resourceBaseName, errorIdAndResourceId, args)
 {
     ValidationMetadataException exception = innerException as ValidationMetadataException;
     if ((exception != null) && exception.SwallowException)
     {
         this._swallowException = true;
     }
 }
Example #9
0
 /// <summary>
 /// Constructor.
 /// </summary>
 /// <param name="invocationInfo"></param>
 /// <param name="breakpoints"></param>
 /// <param name="resumeAction"></param>
 public DebuggerStopEventArgs(
     InvocationInfo invocationInfo,
     Collection<Breakpoint> breakpoints,
     DebuggerResumeAction resumeAction)
 {
     this.InvocationInfo = invocationInfo;
     this.Breakpoints = new ReadOnlyCollection<Breakpoint>(breakpoints);
     this.ResumeAction = resumeAction;
 }
        /// <summary>
        /// Constructs a parameter binder controller for the specified command
        /// in the specified engine context.
        /// </summary>
        /// 
        /// <param name="invocationInfo">
        ///     The invocation information about the code being run.
        /// </param>
        /// <param name="context">
        ///     The engine context in which the command is being run.
        /// </param>
        /// <param name="parameterBinder">
        ///     The default parameter binder for the command.
        /// </param>
        internal ParameterBinderController(InvocationInfo invocationInfo, ExecutionContext context, ParameterBinderBase parameterBinder)
        {
            Diagnostics.Assert(invocationInfo != null, "Caller to verify invocationInfo is not null.");
            Diagnostics.Assert(parameterBinder != null, "Caller to verify parameterBinder is not null.");
            Diagnostics.Assert(context != null, "call to verify context is not null.");

            this.DefaultParameterBinder = parameterBinder;
            Context = context;
            InvocationInfo = invocationInfo;
        }
Example #11
0
        /// <summary>
        /// Constructs a ScriptParameterBinder with the specified context
        /// </summary>
        /// 
        /// <param name="script">
        /// The script block representing the code being run
        /// </param>
        /// 
        /// <param name="invocationInfo">
        /// The invocation information about the code that is being run.
        /// </param>
        /// 
        /// <param name="context">
        /// The context under which the shell function is executing.
        /// </param>
        /// 
        /// <param name="command">
        /// The command instance that represents the script in a pipeline. May be null.
        /// </param>
        /// 
        /// <param name="localScope">
        /// If binding in a new local scope, the scope to set variables in.  If dotting, the value is null.
        /// </param>
        internal ScriptParameterBinder(
            ScriptBlock script,
            InvocationInfo invocationInfo,
            ExecutionContext context,
            InternalCommand command,
            SessionStateScope localScope) : base(invocationInfo, context, command)
        {
            Diagnostics.Assert(script != null, "caller to verify script is not null.");

            this.Script = script;
            this.LocalScope = localScope;
        }
Example #12
0
 internal bool Trigger(InvocationInfo invocationInfo)
 {
     if (!this.CommandPattern.IsMatch(invocationInfo.InvocationName) && !this.CommandInfoMatches(invocationInfo.MyCommand))
     {
         return false;
     }
     if (base.Script != null)
     {
         return base.Script.Equals(invocationInfo.ScriptName, StringComparison.OrdinalIgnoreCase);
     }
     return true;
 }
 internal ScriptParameterBinderController(ScriptBlock script, InvocationInfo invocationInfo, ExecutionContext context, InternalCommand command, SessionStateScope localScope) : base(invocationInfo, context, new ScriptParameterBinder(script, invocationInfo, context, command, localScope))
 {
     this.DollarArgs = new List<object>();
     if (script.HasDynamicParameters)
     {
         base.UnboundParameters = base.BindableParameters.ReplaceMetadata(script.ParameterMetadata);
     }
     else
     {
         base._bindableParameters = script.ParameterMetadata;
         base.UnboundParameters = new List<MergedCompiledCommandParameter>(base._bindableParameters.BindableParameters.Values);
     }
 }
Example #14
0
 internal RuntimeException(ErrorCategory errorCategory, InvocationInfo invocationInfo, IScriptExtent errorPosition, string errorIdAndResourceId, string message, Exception innerException) : base(message, innerException)
 {
     this._errorId = "RuntimeException";
     this.SetErrorCategory(errorCategory);
     this.SetErrorId(errorIdAndResourceId);
     if ((errorPosition == null) && (invocationInfo != null))
     {
         errorPosition = invocationInfo.ScriptPosition;
     }
     if (invocationInfo != null)
     {
         this._errorRecord = new System.Management.Automation.ErrorRecord(new ParentContainsErrorRecordException(this), this._errorId, this._errorCategory, this._targetObject);
         this._errorRecord.SetInvocationInfo(new InvocationInfo(invocationInfo.MyCommand, errorPosition));
     }
 }
        partial void BeforeCreatePipeline(System.Management.Automation.InvocationInfo invocationInfo, ref Runtime.HttpPipeline pipeline)
        {
            using (var powershell = PowerShell.Create(RunspaceMode.CurrentRunspace))
            {
                powershell.Commands.AddCommand(new Command($"$executioncontext.SessionState.PSVariable.GetValue('{Constants.GraphAuthConfigId}')", true));

                AuthConfig authConfig = powershell.Invoke <AuthConfig>().FirstOrDefault();

                if (authConfig == null)
                {
                    throw new Exception("Authentication needed, call Connect-Graph.");
                }

                pipeline = new Runtime.HttpPipeline(new Runtime.HttpClientFactory(HttpHelpers.GetGraphHttpClient(authConfig)));
            }
        }
 internal ParameterBindingException(Exception innerException, ParameterBindingException pbex, string resourceBaseName, string resourceId, params object[] args) : base(string.Empty, innerException)
 {
     this.parameterName = string.Empty;
     this.line = -9223372036854775808L;
     this.offset = -9223372036854775808L;
     this.args = new object[0];
     if (pbex == null)
     {
         throw PSTraceSource.NewArgumentNullException("pbex");
     }
     if (string.IsNullOrEmpty(resourceBaseName))
     {
         throw PSTraceSource.NewArgumentException("resourceBaseName");
     }
     if (string.IsNullOrEmpty(resourceId))
     {
         throw PSTraceSource.NewArgumentException("resourceId");
     }
     this.invocationInfo = pbex.CommandInvocation;
     if (this.invocationInfo != null)
     {
         this.commandName = this.invocationInfo.MyCommand.Name;
     }
     IScriptExtent scriptPosition = null;
     if (this.invocationInfo != null)
     {
         scriptPosition = this.invocationInfo.ScriptPosition;
     }
     this.line = pbex.Line;
     this.offset = pbex.Offset;
     this.parameterName = pbex.ParameterName;
     this.parameterType = pbex.ParameterType;
     this.typeSpecified = pbex.TypeSpecified;
     this.errorId = pbex.ErrorId;
     this.resourceBaseName = resourceBaseName;
     this.resourceId = resourceId;
     if (args != null)
     {
         this.args = args;
     }
     base.SetErrorCategory(pbex.ErrorRecord._category);
     base.SetErrorId(this.errorId);
     if (this.invocationInfo != null)
     {
         base.ErrorRecord.SetInvocationInfo(new InvocationInfo(this.invocationInfo.MyCommand, scriptPosition));
     }
 }
Example #17
0
 internal ScriptWriter(TextReader cmdletizationXmlReader, string moduleName, string defaultObjectModelWrapper, InvocationInfo invocationInfo, GenerationOptions generationOptions)
 {
     XmlReader xmlReader = XmlReader.Create(cmdletizationXmlReader, xmlReaderSettings);
     try
     {
         XmlSerializer serializer = new PowerShellMetadataSerializer();
         this.cmdletizationMetadata = (PowerShellMetadata) serializer.Deserialize(xmlReader);
     }
     catch (InvalidOperationException exception)
     {
         XmlSchemaException innerException = exception.InnerException as XmlSchemaException;
         if (innerException != null)
         {
             throw new XmlException(innerException.Message, innerException, innerException.LineNumber, innerException.LinePosition);
         }
         XmlException exception3 = exception.InnerException as XmlException;
         if (exception3 != null)
         {
             throw exception3;
         }
         if (exception.InnerException != null)
         {
             throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, CmdletizationCoreResources.ScriptWriter_ConcatenationOfDeserializationExceptions, new object[] { exception.Message, exception.InnerException.Message }), exception.InnerException);
         }
         throw;
     }
     string valueToConvert = this.cmdletizationMetadata.Class.CmdletAdapter ?? defaultObjectModelWrapper;
     this.objectModelWrapper = (Type) LanguagePrimitives.ConvertTo(valueToConvert, typeof(Type), CultureInfo.InvariantCulture);
     if (this.objectModelWrapper.IsGenericType)
     {
         throw new XmlException(string.Format(CultureInfo.CurrentCulture, CmdletizationCoreResources.ScriptWriter_ObjectModelWrapperIsStillGeneric, new object[] { valueToConvert }));
     }
     Type objectModelWrapper = this.objectModelWrapper;
     while (!objectModelWrapper.IsGenericType || (objectModelWrapper.GetGenericTypeDefinition() != typeof(CmdletAdapter<>)))
     {
         objectModelWrapper = objectModelWrapper.BaseType;
         if (objectModelWrapper.Equals(typeof(object)))
         {
             throw new XmlException(string.Format(CultureInfo.CurrentCulture, CmdletizationCoreResources.ScriptWriter_ObjectModelWrapperNotDerivedFromObjectModelWrapper, new object[] { valueToConvert, typeof(CmdletAdapter<>).FullName }));
         }
     }
     this.objectInstanceType = objectModelWrapper.GetGenericArguments()[0];
     this.moduleName = moduleName;
     this.invocationInfo = invocationInfo;
     this.generationOptions = generationOptions;
 }
 internal CmdletInvocationException(Exception innerException, InvocationInfo invocationInfo) : base(RuntimeException.RetrieveMessage(innerException), innerException)
 {
     if (innerException == null)
     {
         throw new ArgumentNullException("innerException");
     }
     IContainsErrorRecord record = innerException as IContainsErrorRecord;
     if ((record != null) && (record.ErrorRecord != null))
     {
         this._errorRecord = new System.Management.Automation.ErrorRecord(record.ErrorRecord, innerException);
     }
     else
     {
         this._errorRecord = new System.Management.Automation.ErrorRecord(innerException, innerException.GetType().FullName, ErrorCategory.NotSpecified, null);
     }
     this._errorRecord.SetInvocationInfo(invocationInfo);
 }
Example #19
0
        /// <summary>
        /// Creates an InformationalRecord object from a record serialized as a PSObject by ToPSObjectForRemoting.
        /// </summary>
        internal InformationalRecord(PSObject serializedObject)
        {
            _message = (string)SerializationUtilities.GetPropertyValue(serializedObject, "InformationalRecord_Message");
            _serializeExtendedInfo = (bool)SerializationUtilities.GetPropertyValue(serializedObject, "InformationalRecord_SerializeInvocationInfo");

            if (_serializeExtendedInfo)
            {
                _invocationInfo = new InvocationInfo(serializedObject);

                ArrayList pipelineIterationInfo = (ArrayList)SerializationUtilities.GetPsObjectPropertyBaseObject(serializedObject, "InformationalRecord_PipelineIterationInfo");

                _pipelineIterationInfo = new ReadOnlyCollection<int>((int[])pipelineIterationInfo.ToArray(typeof(int)));
            }
            else
            {
                _invocationInfo = null;
            }
        }
Example #20
0
        private static int GetNumberOfSessions(InvocationInfo invocationInfo)
        {
            // if user explicitly specifies CimSession, then the cmdlet runs against exactly those sessions
            object cimSessionArgument;
            if (invocationInfo.BoundParameters.TryGetValue("CimSession", out cimSessionArgument))
            {
                IList cimSessionArgumentAsList = (IList)cimSessionArgument;
                return cimSessionArgumentAsList.Count;
            }
            // else - either CimSession=localhost OR CimSession is based on CimInstance->CimSession affinity

            // CimInstance->CimSession affinity in instance cmdlets can come from:
            // 1. InputObject (either passed through pipeline or explicitly bound to the parameter)
            // 2. AssociatedObject (either passed through pipeline or explicitly bound to the parameter [we don't know the name of the parameter though])
            // CimInstance->CimSession affinity in static cmdlets can come from:
            // 1. Any method argument that is either a CimInstance or CimInstance[]
            // Additionally in both instance and static cmdlets, if the pipeline object is a CimInstance, then it can affect the session acted against
            if (invocationInfo.ExpectingInput)
            {
                // can get unlimited number of CimInstances through pipeline 
                // - this translates into potentially unlimited number of CimSession we will work with
                return int.MaxValue;
            }
            int maxNumberOfSessionsIndicatedByCimInstanceArguments = 1;
            foreach (object cmdletArgument in invocationInfo.BoundParameters.Values)
            {
                CimInstance[] array = cmdletArgument as CimInstance[];
                if (array != null)
                {
                    int numberOfSessionsAssociatedWithArgument = array
                        .Select(CimCmdletAdapter.GetSessionOfOriginFromCimInstance)
                        .Distinct()
                        .Count();
                    maxNumberOfSessionsIndicatedByCimInstanceArguments = Math.Max(
                        maxNumberOfSessionsIndicatedByCimInstanceArguments,
                        numberOfSessionsAssociatedWithArgument);
                }
            }
            return maxNumberOfSessionsIndicatedByCimInstanceArguments;
        }
        /// <summary>
        /// Initializes the cmdlet parameter binder controller for
        /// the specified cmdlet and engine context
        /// </summary>
        /// 
        /// <param name="script">
        /// The script that contains the parameter metadata.
        /// </param>
        /// <param name="invocationInfo">
        /// The invocation information about the code being run.
        /// </param>
        /// <param name="context">
        /// The engine context the cmdlet is run in.
        /// </param>
        /// <param name="command">
        /// The command that the parameters will be bound to.
        /// </param>
        /// <param name="localScope">
        /// The scope that the parameter binder will use to set parameters.
        /// </param>
        internal ScriptParameterBinderController(
            ScriptBlock script,
            InvocationInfo invocationInfo,
            ExecutionContext context,
            InternalCommand command,
            SessionStateScope localScope)
            : base(invocationInfo, context, new ScriptParameterBinder(script, invocationInfo, context, command, localScope))
        {
            this.DollarArgs = new List<object>();

            // Add the script parameter metadata to the bindable parameters
            // And add them to the unbound parameters list

            if (script.HasDynamicParameters)
            {
                UnboundParameters = this.BindableParameters.ReplaceMetadata(script.ParameterMetadata);
            }
            else
            {
                _bindableParameters = script.ParameterMetadata;
                UnboundParameters = new List<MergedCompiledCommandParameter>(_bindableParameters.BindableParameters.Values);
            }
        }
 public DefaultPowershellCommandInvoker(CommandInvocationIntrinsics invokeCommand, InvocationInfo myInvocation)
 {
     _invokeCommand = invokeCommand;
     _myInvocation = myInvocation;
 }
Example #23
0
 /// <summary>
 /// Instantiates a new instance of the ActionPreferenceStopException class
 /// </summary>
 /// <param name="invocationInfo">  </param>
 /// <param name="message">  </param>
 /// <returns> constructed object </returns>
 internal ActionPreferenceStopException(InvocationInfo invocationInfo, string message)
     : this(message)
 {
     base.ErrorRecord.SetInvocationInfo(invocationInfo);
 }
Example #24
0
 public static string GetScriptName(InvocationInfo iInfo)
 {
     string result = string.Empty;
     try{
         result =
             iInfo.ScriptName;
     }
     catch {
         return result;
     }
     return result;
 }
Example #25
0
 public static int GetPipelinePosition(InvocationInfo iInfo)
 {
     int result = 0;
     try{
         result =
             iInfo.PipelinePosition;
     }
     catch {
     }
     return result;
 }
Example #26
0
 internal PSDebugContext(InvocationInfo invocationInfo, List <Breakpoint> breakpoints)
 {
     this.invocationInfo = invocationInfo;
     this.breakpoints    = breakpoints.ToArray();
 }
Example #27
0
 /// <summary>
 /// Generate LogContext structure based on executionContext and invocationInfo passed in.
 /// 
 /// LogContext structure is used in log provider interface. 
 /// </summary>
 /// <param name="executionContext"></param>
 /// <param name="invocationInfo"></param>
 /// <returns></returns>
 internal static LogContext GetLogContext(ExecutionContext executionContext, InvocationInfo invocationInfo)
 {
     return GetLogContext(executionContext, invocationInfo, Severity.Informational);
 }
Example #28
0
        /// <summary>
        /// LogPipelineExecutionDetailEvent: Log a pipeline execution detail event.
        /// 
        /// </summary>
        /// <param name="executionContext">Execution Context for the current running engine</param>
        /// <param name="detail">detail to be logged for this pipeline execution detail</param>
        /// <param name="invocationInfo">invocation data for current command that is running</param>
        internal static void LogPipelineExecutionDetailEvent(ExecutionContext executionContext,
                                                            List<String> detail,
                                                            InvocationInfo invocationInfo)

        {
            if (executionContext == null)
            {
                PSTraceSource.NewArgumentNullException("executionContext");
                return;
            }

            foreach (LogProvider provider in GetLogProvider(executionContext))
            {
                if (NeedToLogPipelineExecutionDetailEvent(provider, executionContext))
                {
                    provider.LogPipelineExecutionDetailEvent(GetLogContext(executionContext, invocationInfo), detail);
                }
            }
        }
        /// <summary>
        /// Gets the parameters by matching its name.
        /// </summary>
        ///
        /// <param name="name">
        /// The name of the parameter.
        /// </param>
        ///
        /// <param name="throwOnParameterNotFound">
        /// If true and a matching parameter is not found, an exception will be
        /// throw. If false and a matching parameter is not found, null is returned.
        /// </param>
        ///
        /// <param name="tryExactMatching">
        /// If true we do exact matching, otherwise we do not.
        /// </param>
        ///
        /// <param name="invocationInfo">
        /// The invocation information about the code being run.
        /// </param>
        ///
        /// <returns>
        /// The a collection of the metadata associated with the parameters that
        /// match the specified name. If no matches were found, an empty collection
        /// is returned.
        /// </returns>
        ///
        /// <exception cref="ArgumentException">
        /// If <paramref name="name"/> is null or empty.
        /// </exception>
        ///
        internal MergedCompiledCommandParameter GetMatchingParameter(
            string name,
            bool throwOnParameterNotFound,
            bool tryExactMatching,
            InvocationInfo invocationInfo)
        {
            if (string.IsNullOrEmpty(name))
            {
                throw PSTraceSource.NewArgumentException("name");
            }

            Collection <MergedCompiledCommandParameter> matchingParameters =
                new Collection <MergedCompiledCommandParameter>();

            // Skip the leading '-' if present
            if (name.Length > 0 && SpecialCharacters.IsDash(name[0]))
            {
                name = name.Substring(1);
            }


            // First try to match the bindable parameters

            foreach (string parameterName in _bindableParameters.Keys)
            {
                if (CultureInfo.InvariantCulture.CompareInfo.IsPrefix(parameterName, name, CompareOptions.IgnoreCase))
                {
                    // If it is an exact match then only return the exact match
                    // as the result

                    if (tryExactMatching && String.Equals(parameterName, name, StringComparison.OrdinalIgnoreCase))
                    {
                        return(_bindableParameters[parameterName]);
                    }
                    else
                    {
                        matchingParameters.Add(_bindableParameters[parameterName]);
                    }
                }
            }

            // Now check the aliases

            foreach (string parameterName in _aliasedParameters.Keys)
            {
                if (CultureInfo.InvariantCulture.CompareInfo.IsPrefix(parameterName, name, CompareOptions.IgnoreCase))
                {
                    // If it is an exact match then only return the exact match
                    // as the result

                    if (tryExactMatching && String.Equals(parameterName, name, StringComparison.OrdinalIgnoreCase))
                    {
                        return(_aliasedParameters[parameterName]);
                    }
                    else
                    {
                        if (!matchingParameters.Contains(_aliasedParameters[parameterName]))
                        {
                            matchingParameters.Add(_aliasedParameters[parameterName]);
                        }
                    }
                }
            }

            if (matchingParameters.Count > 1)
            {
                // Prefer parameters in the cmdlet over common parameters
                Collection <MergedCompiledCommandParameter> filteredParameters =
                    new Collection <MergedCompiledCommandParameter>();

                foreach (MergedCompiledCommandParameter matchingParameter in matchingParameters)
                {
                    if ((matchingParameter.BinderAssociation == ParameterBinderAssociation.DeclaredFormalParameters) ||
                        (matchingParameter.BinderAssociation == ParameterBinderAssociation.DynamicParameters))
                    {
                        filteredParameters.Add(matchingParameter);
                    }
                }

                if (filteredParameters.Count == 1)
                {
                    matchingParameters = filteredParameters;
                }
                else
                {
                    StringBuilder possibleMatches = new StringBuilder();

                    foreach (MergedCompiledCommandParameter matchingParameter in matchingParameters)
                    {
                        possibleMatches.Append(" -");
                        possibleMatches.Append(matchingParameter.Parameter.Name);
                    }

                    ParameterBindingException exception =
                        new ParameterBindingException(
                            ErrorCategory.InvalidArgument,
                            invocationInfo,
                            null,
                            name,
                            null,
                            null,
                            ParameterBinderStrings.AmbiguousParameter,
                            "AmbiguousParameter",
                            possibleMatches);

                    throw exception;
                }
            }
            else if (matchingParameters.Count == 0)
            {
                if (throwOnParameterNotFound)
                {
                    ParameterBindingException exception =
                        new ParameterBindingException(
                            ErrorCategory.InvalidArgument,
                            invocationInfo,
                            null,
                            name,
                            null,
                            null,
                            ParameterBinderStrings.NamedParameterNotFound,
                            "NamedParameterNotFound");

                    throw exception;
                }
            }

            MergedCompiledCommandParameter result = null;

            if (matchingParameters.Count > 0)
            {
                result = matchingParameters[0];
            }
            return(result);
        } // GetMatchingParameter
Example #30
0
 /// <summary>
 /// Generate LogContext structure based on executionContext and invocationInfo passed in.
 ///
 /// LogContext structure is used in log provider interface.
 /// </summary>
 /// <param name="executionContext"></param>
 /// <param name="invocationInfo"></param>
 /// <returns></returns>
 internal static LogContext GetLogContext(ExecutionContext executionContext, InvocationInfo invocationInfo)
 {
     return(GetLogContext(executionContext, invocationInfo, Severity.Informational));
 }
Example #31
0
 private static bool IsGetPsCallStackCmdlet(InvocationInfo invocationInfo) => invocationInfo.ScriptLineNumber == 0 && invocationInfo.MyCommand != null && (invocationInfo.MyCommand.Context != null && invocationInfo.MyCommand.Context.CurrentCommandProcessor != null) && invocationInfo.MyCommand.Context.CurrentCommandProcessor.Command != null && invocationInfo.MyCommand.Context.CurrentCommandProcessor.Command.GetType().FullName == "Microsoft.PowerShell.Commands.GetPSCallStackCommand";
Example #32
0
        /// <summary>
        /// Generate LogContext structure based on executionContext and invocationInfo passed in.
        ///
        /// LogContext structure is used in log provider interface.
        /// </summary>
        /// <param name="executionContext"></param>
        /// <param name="invocationInfo"></param>
        /// <param name="severity"></param>
        /// <returns></returns>
        private static LogContext GetLogContext(ExecutionContext executionContext, InvocationInfo invocationInfo, Severity severity)
        {
            if (executionContext == null)
            {
                return(null);
            }

            LogContext logContext = new LogContext();

            string shellId = executionContext.ShellID;

            logContext.ExecutionContext = executionContext;
            logContext.ShellId          = shellId;
            logContext.Severity         = severity.ToString();

            if (executionContext.EngineHostInterface != null)
            {
                logContext.HostName    = executionContext.EngineHostInterface.Name;
                logContext.HostVersion = executionContext.EngineHostInterface.Version.ToString();
                logContext.HostId      = (string)executionContext.EngineHostInterface.InstanceId.ToString();
            }

            logContext.HostApplication = string.Join(" ", Environment.GetCommandLineArgs());

            if (executionContext.CurrentRunspace != null)
            {
                logContext.EngineVersion = executionContext.CurrentRunspace.Version.ToString();
                logContext.RunspaceId    = executionContext.CurrentRunspace.InstanceId.ToString();

                Pipeline currentPipeline = ((RunspaceBase)executionContext.CurrentRunspace).GetCurrentlyRunningPipeline();
                if (currentPipeline != null)
                {
                    logContext.PipelineId = currentPipeline.InstanceId.ToString(CultureInfo.CurrentCulture);
                }
            }

            logContext.SequenceNumber = NextSequenceNumber;

            try
            {
                if (executionContext.LogContextCache.User == null)
                {
                    logContext.User = Environment.UserDomainName + "\\" + Environment.UserName;
                    executionContext.LogContextCache.User = logContext.User;
                }
                else
                {
                    logContext.User = executionContext.LogContextCache.User;
                }
            }
            catch (InvalidOperationException)
            {
                logContext.User = Logging.UnknownUserName;
            }

            System.Management.Automation.Remoting.PSSenderInfo psSenderInfo =
                executionContext.SessionState.PSVariable.GetValue("PSSenderInfo") as System.Management.Automation.Remoting.PSSenderInfo;
            if (psSenderInfo != null)
            {
                logContext.ConnectedUser = psSenderInfo.UserInfo.Identity.Name;
            }

            logContext.Time = DateTime.Now.ToString(CultureInfo.CurrentCulture);

            if (invocationInfo == null)
            {
                return(logContext);
            }

            logContext.ScriptName  = invocationInfo.ScriptName;
            logContext.CommandLine = invocationInfo.Line;

            if (invocationInfo.MyCommand != null)
            {
                logContext.CommandName = invocationInfo.MyCommand.Name;
                logContext.CommandType = invocationInfo.MyCommand.CommandType.ToString();

                switch (invocationInfo.MyCommand.CommandType)
                {
                case CommandTypes.Application:
                    logContext.CommandPath = ((ApplicationInfo)invocationInfo.MyCommand).Path;
                    break;

                case CommandTypes.ExternalScript:
                    logContext.CommandPath = ((ExternalScriptInfo)invocationInfo.MyCommand).Path;
                    break;
                }
            }

            return(logContext);
        }
Example #33
0
        /// <summary>
        /// LogEngineLifecycleEvent: Log an engine lifecycle event. 
        /// 
        /// This is the basic form of EngineLifecycleEvent logging api, in which all parameters are provided.
        /// 
        /// Variant form of this function is defined below, which will make parameter additionalInfo 
        /// optional.
        /// </summary>
        /// <param name="executionContext">execution context for current engine instance</param>
        /// <param name="engineState">new engine state</param>
        /// <param name="invocationInfo">invocationInfo for current command that is running</param>
        internal static void LogEngineLifecycleEvent(ExecutionContext executionContext,
                                                EngineState engineState,
                                                InvocationInfo invocationInfo)
        {
            if (executionContext == null)
            {
                PSTraceSource.NewArgumentNullException("executionContext");
                return;
            }

            EngineState previousState = GetEngineState(executionContext);
            if (engineState == previousState)
                return;

            foreach (LogProvider provider in GetLogProvider(executionContext))
            {
                if (NeedToLogEngineLifecycleEvent(provider, executionContext))
                {
                    provider.LogEngineLifecycleEvent(GetLogContext(executionContext, invocationInfo), engineState, previousState);
                }
            }

            SetEngineState(executionContext, engineState);
        }
Example #34
0
        /// <summary>
        /// LogCommandLifecycleEvent: Log a command lifecycle event.
        /// 
        /// This is the only form of CommandLifecycleEvent logging api.
        /// </summary>
        /// <param name="executionContext">Execution Context for the current running engine</param>
        /// <param name="commandState">new command state</param>
        /// <param name="invocationInfo">invocation data for current command that is running</param>
        internal static void LogCommandLifecycleEvent(ExecutionContext executionContext,
                                                CommandState commandState,
                                                InvocationInfo invocationInfo)
        {
            if (executionContext == null)
            {
                PSTraceSource.NewArgumentNullException("executionContext");
                return;
            }

            if (invocationInfo == null)
            {
                PSTraceSource.NewArgumentNullException("invocationInfo");
                return;
            }

            if (s_ignoredCommands.Contains(invocationInfo.MyCommand.Name))
            {
                return;
            }

            LogContext logContext = null;
            foreach (LogProvider provider in GetLogProvider(executionContext))
            {
                if (NeedToLogCommandLifecycleEvent(provider, executionContext))
                {
                    provider.LogCommandLifecycleEvent(
                        () => logContext ?? (logContext = GetLogContext(executionContext, invocationInfo)), commandState);
                }
            }
        }
 internal ActionPreferenceStopException(InvocationInfo invocationInfo, string baseName, string resourceId, params object[] args) : this(ResourceManagerCache.FormatResourceString(Assembly.GetCallingAssembly(), baseName, resourceId, args))
 {
     this.ErrorRecord.SetInvocationInfo(invocationInfo);
 }
Example #36
0
        /// <summary>
        /// LogSettingsEvent: Log a settings event
        /// 
        /// This is the basic form of LoggingSettingsEvent API. Variation of this function defined
        /// below will make parameter invocationInfo optional.
        /// </summary>
        /// <param name="executionContext">Execution context for current running engine</param>
        /// <param name="variableName">Variable name</param>
        /// <param name="newValue">New value for the variable</param>
        /// <param name="previousValue">Previous value for the variable</param>
        /// <param name="invocationInfo">Invocation data for the command that is currently running</param>
        internal static void LogSettingsEvent(ExecutionContext executionContext,
                                            string variableName,
                                            string newValue,
                                            string previousValue,
                                            InvocationInfo invocationInfo)
        {
            if (executionContext == null)
            {
                PSTraceSource.NewArgumentNullException("executionContext");
                return;
            }

            foreach (LogProvider provider in GetLogProvider(executionContext))
            {
                if (NeedToLogSettingsEvent(provider, executionContext))
                {
                    provider.LogSettingsEvent(GetLogContext(executionContext, invocationInfo), variableName, newValue, previousValue);
                }
            }
        }
Example #37
0
 partial void BeforeCreatePipeline(System.Management.Automation.InvocationInfo invocationInfo, ref Runtime.HttpPipeline pipeline)
 {
     pipeline = new Runtime.HttpPipeline(new Runtime.HttpClientFactory(HttpHelpers.GetGraphHttpClient()));
 }
Example #38
0
        /// <summary>
        /// Generate LogContext structure based on executionContext and invocationInfo passed in.
        /// 
        /// LogContext structure is used in log provider interface. 
        /// </summary>
        /// <param name="executionContext"></param>
        /// <param name="invocationInfo"></param>
        /// <param name="severity"></param>
        /// <returns></returns>
        private static LogContext GetLogContext(ExecutionContext executionContext, InvocationInfo invocationInfo, Severity severity)
        {
            if (executionContext == null)
                return null;

            LogContext logContext = new LogContext();

            string shellId = executionContext.ShellID;

            logContext.ExecutionContext = executionContext;
            logContext.ShellId = shellId;
            logContext.Severity = severity.ToString();

            if (executionContext.EngineHostInterface != null)
            {
                logContext.HostName = executionContext.EngineHostInterface.Name;
                logContext.HostVersion = executionContext.EngineHostInterface.Version.ToString();
                logContext.HostId = (string)executionContext.EngineHostInterface.InstanceId.ToString();
            }

            logContext.HostApplication = String.Join(" ", Environment.GetCommandLineArgs());

            if (executionContext.CurrentRunspace != null)
            {
                logContext.EngineVersion = executionContext.CurrentRunspace.Version.ToString();
                logContext.RunspaceId = executionContext.CurrentRunspace.InstanceId.ToString();

                Pipeline currentPipeline = ((RunspaceBase)executionContext.CurrentRunspace).GetCurrentlyRunningPipeline();
                if (currentPipeline != null)
                {
                    logContext.PipelineId = currentPipeline.InstanceId.ToString(CultureInfo.CurrentCulture);
                }
            }

            logContext.SequenceNumber = NextSequenceNumber;

            try
            {
                if (executionContext.LogContextCache.User == null)
                {
                    logContext.User = Environment.UserDomainName + "\\" + Environment.UserName;
                    executionContext.LogContextCache.User = logContext.User;
                }
                else
                {
                    logContext.User = executionContext.LogContextCache.User;
                }
            }
            catch (InvalidOperationException)
            {
                logContext.User = Logging.UnknownUserName;
            }

            System.Management.Automation.Remoting.PSSenderInfo psSenderInfo =
                    executionContext.SessionState.PSVariable.GetValue("PSSenderInfo") as System.Management.Automation.Remoting.PSSenderInfo;
            if (psSenderInfo != null)
            {
                logContext.ConnectedUser = psSenderInfo.UserInfo.Identity.Name;
            }

            logContext.Time = DateTime.Now.ToString(CultureInfo.CurrentCulture);

            if (invocationInfo == null)
                return logContext;

            logContext.ScriptName = invocationInfo.ScriptName;
            logContext.CommandLine = invocationInfo.Line;

            if (invocationInfo.MyCommand != null)
            {
                logContext.CommandName = invocationInfo.MyCommand.Name;
                logContext.CommandType = invocationInfo.MyCommand.CommandType.ToString();

                switch (invocationInfo.MyCommand.CommandType)
                {
                    case CommandTypes.Application:
                        logContext.CommandPath = ((ApplicationInfo)invocationInfo.MyCommand).Path;
                        break;
                    case CommandTypes.ExternalScript:
                        logContext.CommandPath = ((ExternalScriptInfo)invocationInfo.MyCommand).Path;
                        break;
                }
            }

            return logContext;
        }
 internal ParameterBindingException(Exception innerException, ErrorCategory errorCategory, InvocationInfo invocationInfo, IScriptExtent errorPosition, string parameterName, Type parameterType, Type typeSpecified, string resourceBaseName, string errorIdAndResourceId, params object[] args) : base(errorCategory, invocationInfo, errorPosition, errorIdAndResourceId, null, innerException)
 {
     this.parameterName = string.Empty;
     this.line          = -9223372036854775808L;
     this.offset        = -9223372036854775808L;
     this.args          = new object[0];
     if (invocationInfo == null)
     {
         throw PSTraceSource.NewArgumentNullException("invocationInfo");
     }
     if (string.IsNullOrEmpty(resourceBaseName))
     {
         throw PSTraceSource.NewArgumentException("resourceBaseName");
     }
     if (string.IsNullOrEmpty(errorIdAndResourceId))
     {
         throw PSTraceSource.NewArgumentException("errorIdAndResourceId");
     }
     this.invocationInfo = invocationInfo;
     this.commandName    = invocationInfo.MyCommand.Name;
     this.parameterName  = parameterName;
     this.parameterType  = parameterType;
     this.typeSpecified  = typeSpecified;
     if (errorPosition == null)
     {
         errorPosition = invocationInfo.ScriptPosition;
     }
     if (errorPosition != null)
     {
         this.line   = errorPosition.StartLineNumber;
         this.offset = errorPosition.StartColumnNumber;
     }
     this.resourceBaseName = resourceBaseName;
     this.resourceId       = errorIdAndResourceId;
     this.errorId          = errorIdAndResourceId;
     if (args != null)
     {
         this.args = args;
     }
 }
Example #40
0
        //        public static void CloseTestResultAsIs()
        //        {
        //
        //            if (TestData.TestSuites.Count == 0) {
        //                TestData.InitTestData();
        //            }
        //            
        //            if (null != TestData.CurrentTestResult) {
        //                TestData.CurrentTestScenario.TestResults.Add(TestData.CurrentTestResult);
        //            }
        //            
        //            TestData.CurrentTestResult =
        //                new TestResult(
        //                    TestData.CurrentTestScenario.Id,
        //                    TestData.CurrentTestSuite.Id);
        //
        //        }
        // 20121224
        //public static bool CloseTestResult(
        public static void CloseTestResult(
            string testResultName, 
            string testResultId, 
            bool testResult,
            bool isKnownIssue,
            InvocationInfo myInvocation,
            ErrorRecord error,
            string description,
            // 20130322
            //bool generated)
            //bool generated,
            TestResultOrigins origin,
            bool skipAutomatic)
        {
            // 20121224
            //bool result = false;

            //            if (TestData.TestSuites.Count == 0) {
            //                TestData.InitTestData();
            //            }

            TMX.TestData.AddTestResult(
                testResultName,
                testResultId,
                testResult,
                isKnownIssue,
                true,
                myInvocation,
                error,
                description,
                // 20130322
                //generated);
                // 20130626
                //generated,
                origin,
                skipAutomatic);

            // 20121224
            //return result;
        }
Example #41
0
        private PSModuleInfo CreateModuleImplementation(string name, string path, object moduleCode, IScriptExtent scriptPosition, SessionState ss, object privateData, out ArrayList result, params object[] arguments)
        {
            if (ss == null)
            {
                ss = new SessionState(this._context, true, true);
            }
            SessionStateInternal engineSessionState = this._context.EngineSessionState;
            PSModuleInfo         info = new PSModuleInfo(name, path, this._context, ss);

            ss.Internal.Module = info;
            info.PrivateData   = privateData;
            bool flag     = false;
            int  newValue = 0;

            try
            {
                ScriptBlock scriptBlock;
                this._context.EngineSessionState = ss.Internal;
                ExternalScriptInfo scriptCommandInfo = moduleCode as ExternalScriptInfo;
                if (scriptCommandInfo != null)
                {
                    scriptBlock = scriptCommandInfo.ScriptBlock;
                    this._context.Debugger.RegisterScriptFile(scriptCommandInfo);
                }
                else
                {
                    scriptBlock = moduleCode as ScriptBlock;
                    if (scriptBlock != null)
                    {
                        PSLanguageMode?languageMode = scriptBlock.LanguageMode;
                        scriptBlock = scriptBlock.Clone(true);
                        scriptBlock.LanguageMode = languageMode;
                        scriptBlock.SessionState = ss;
                    }
                    else if (moduleCode is string)
                    {
                        scriptBlock = ScriptBlock.Create(this._context, (string)moduleCode);
                    }
                }
                if (scriptBlock == null)
                {
                    throw PSTraceSource.NewInvalidOperationException();
                }
                scriptBlock.SessionStateInternal = ss.Internal;
                InvocationInfo invocationInfo = new InvocationInfo(scriptCommandInfo, scriptPosition);
                info._definitionExtent = scriptBlock.Ast.Extent;
                ArrayList resultList = new ArrayList();
                try
                {
                    Pipe outputPipe = new Pipe(resultList);
                    scriptBlock.InvokeWithPipe(false, ScriptBlock.ErrorHandlingBehavior.WriteToCurrentErrorPipe, AutomationNull.Value, AutomationNull.Value, AutomationNull.Value, outputPipe, invocationInfo, arguments ?? new object[0]);
                }
                catch (ExitException exception)
                {
                    newValue = (int)exception.Argument;
                    flag     = true;
                }
                result = resultList;
            }
            finally
            {
                this._context.EngineSessionState = engineSessionState;
            }
            if (flag)
            {
                this._context.SetVariable(SpecialVariables.LastExitCodeVarPath, newValue);
            }
            return(info);
        }
Example #42
0
 public static int GetScriptLineNumber(InvocationInfo iInfo)
 {
     int result = 0;
     try{
         result =
             iInfo.ScriptLineNumber;
     }
     catch {
         return result;
     }
     return result;
 }
 internal CmdletProviderInvocationException(System.Management.Automation.ProviderInvocationException innerException, InvocationInfo myInvocation) : base(GetInnerException(innerException), myInvocation)
 {
     if (innerException == null)
     {
         throw new ArgumentNullException("innerException");
     }
     this._providerInvocationException = innerException;
 }
Example #44
0
        private void OnDebuggerStop(InvocationInfo invocationInfo, List <Breakpoint> breakpoints)
        {
            LocalRunspace currentRunspace = this._context.CurrentRunspace as LocalRunspace;

            if (currentRunspace.PulsePipeline != null && currentRunspace.PulsePipeline == currentRunspace.GetCurrentlyRunningPipeline())
            {
                if (breakpoints.Count > 0)
                {
                    this._context.EngineHostInterface.UI.WriteWarningLine(ResourceManagerCache.FormatResourceString("DebuggerStrings", "WarningBreakpointWillNotBeHit", (object)breakpoints[0]));
                }
                else
                {
                    this._context.EngineHostInterface.UI.WriteWarningLine(new InvalidOperationException().Message);
                }
            }
            else
            {
                this._steppingMode = Debugger.SteppingMode.None;
                EventHandler <DebuggerStopEventArgs> debuggerStop = this.DebuggerStop;
                if (debuggerStop == null)
                {
                    return;
                }
                this._inBreakpoint = true;
                if (invocationInfo != null)
                {
                    this._callStack.Push(new Debugger.CallStackInfo()
                    {
                        InvocationInfo = invocationInfo
                    });
                }
                this._context.SetVariable("PSDebugContext", (object)new PSDebugContext(invocationInfo, breakpoints));
                PSLanguageMode languageMode = this._context.LanguageMode;
                bool           flag         = languageMode != PSLanguageMode.FullLanguage && this._context.UseFullLanguageModeInDebugger;
                if (flag)
                {
                    this._context.LanguageMode = PSLanguageMode.FullLanguage;
                }
                RunspaceAvailability runspaceAvailability = this._context.CurrentRunspace.RunspaceAvailability;
                this._context.CurrentRunspace.UpdateRunspaceAvailability(this._context.CurrentRunspace.GetCurrentlyRunningPipeline() != null ? RunspaceAvailability.AvailableForNestedCommand : RunspaceAvailability.Available, true);
                try
                {
                    DebuggerStopEventArgs e = new DebuggerStopEventArgs(invocationInfo, breakpoints);
                    debuggerStop((object)this, e);
                    this.ResumeExecution(e);
                }
                finally
                {
                    this._context.CurrentRunspace.UpdateRunspaceAvailability(runspaceAvailability, true);
                    if (flag)
                    {
                        this._context.LanguageMode = languageMode;
                    }
                    this._context.RemoveVariable("PSDebugContext");
                    if (invocationInfo != null)
                    {
                        this._callStack.Pop();
                    }
                    this._inBreakpoint = false;
                }
            }
        }
Example #45
0
        /// <summary>
        /// The cmdlet will call this for every event during the pipeline.
        /// </summary>
        /// <param name="id">a <c>string</c> containing the name of the event being raised (well-known events are in <see cref="Microsoft.Azure.Commands.Common.Events"/></param>
        /// <param name="cancellationToken">a <c>CancellationToken</c> indicating if this request is being cancelled.</param>
        /// <param name="getEventData">a delegate to call to get the event data for this event</param>
        /// <param name="signal">a delegate to signal an event from the handler to the cmdlet.</param>
        /// <param name="invocationInfo">The <see cref="System.Management.Automation.InvocationInfo" /> from the cmdlet</param>
        /// <param name="parameterSetName">The <see cref="string" /> containing the name of the parameter set for this invocation (if available></param>
        /// <param name="correlationId">The <see cref="string" /> containing the correlation id for the cmdlet (if available)</param>
        /// <param name="processRecordId">The <see cref="string" /> containing the correlation id for the individual process record. (if available)</param>
        /// <param name="exception">The <see cref="System.Exception" /> that is being thrown (if available)</param>
        public async Task EventListener(string id, CancellationToken cancellationToken, GetEventData getEventData, SignalDelegate signal, System.Management.Automation.InvocationInfo invocationInfo, string parameterSetName, string correlationId, string processRecordId, System.Exception exception)
        {
            switch (id)
            {
            case Events.CmdletException:
            {
                var data = EventDataConverter.ConvertFrom(getEventData());
                await signal("Warning", cancellationToken, () => EventHelper.CreateLogEvent($"Received Exception with message '{data?.Message}'"));
            }

            break;

            case Events.BeforeCall:
            {
                var data = EventDataConverter.ConvertFrom(getEventData());         // also, we manually use our TypeConverter to return an appropriate type
                await signal("Debug", cancellationToken, () => EventHelper.CreateLogEvent($"BEFORE CALL The contents are '{data?.Id}' and '{data?.Message}'"));

                var request = data?.RequestMessage as HttpRequestMessage;
                if (request != null)
                {
                    // alias/casting the request message to an HttpRequestMessage is necessary so that we can
                    // support other protocols later on. (ie, JSONRPC, MQTT, GRPC ,AMPQ, Etc..)

                    // at this point, we can do with the request
                    request.Headers.Add("x-ms-peekaboo", "true");
                    await signal("Debug", cancellationToken, () => EventHelper.CreateLogEvent(GeneralUtilities.GetLog(request)));
                }
            }
            break;

            case Events.ResponseCreated:
            {
                // once we're sure we're handling the event, then we can retrieve the event data.
                // (this ensures that we're not doing any of the work unless we really care about the event. )
                var data = EventDataConverter.ConvertFrom(getEventData());
                await signal("Debug", cancellationToken, () => EventHelper.CreateLogEvent($"RESPONSE CREATED The contents are '{data?.Id}' and '{data?.Message}'"));

                var response = data?.ResponseMessage as HttpResponseMessage;
                if (response != null)
                {
                    await signal("Debug", cancellationToken, () => EventHelper.CreateLogEvent(GeneralUtilities.GetLog(response)));
                }
            }
            break;

            default:
                // By default, just print out event details
                getEventData.Print(signal, cancellationToken, "Verbose", id);
                break;
            }
        }