Пример #1
0
        public object Intercept(InvocationInfo info)
        {
            object result = null;
            _wrapper.BeforeInvoke(info);
            result = _wrapper.DoInvoke(info);
            _wrapper.AfterInvoke(info, result);

            return result;
        }
        public object Intercept(InvocationInfo info)
        {
            var targetMethod = info.TargetMethod;
            if (_isFrozen && targetMethod.Name.StartsWith("set_", StringComparison.OrdinalIgnoreCase))
            {
                throw new InvalidOperationException();
            }

            return info.TargetMethod.Invoke(info.Target, info.Arguments);
        }
Пример #3
0
        /**
         * This function takes in a CommandInfo (CmdletInfo or FunctionInfo)
         * And returns all the deprecation attributes attached to it
         *
         * the boundParameterNames is a list of parameters bound to the cmdlet at runtime,
         * We only process the Parameter beaking change attributes attached only params listed in this list (if present)
         **/
        private static IEnumerable <GenericBreakingChangeAttribute> GetAllBreakingChangeAttributesInType(CommandInfo commandInfo, InvocationInfo invocationInfo, String parameterSet)
        {
            List <GenericBreakingChangeAttribute> attributeList = new List <GenericBreakingChangeAttribute>();

            if (commandInfo.GetType() == typeof(CmdletInfo))
            {
                var type = ((CmdletInfo)commandInfo).ImplementingType;
                attributeList.AddRange(type.GetCustomAttributes(typeof(GenericBreakingChangeAttribute), false).Cast <GenericBreakingChangeAttribute>());

                foreach (MethodInfo m in type.GetRuntimeMethods())
                {
                    attributeList.AddRange((m.GetCustomAttributes(typeof(GenericBreakingChangeAttribute), false).Cast <GenericBreakingChangeAttribute>()));
                }

                foreach (FieldInfo f in type.GetRuntimeFields())
                {
                    attributeList.AddRange(f.GetCustomAttributes(typeof(GenericBreakingChangeAttribute), false).Cast <GenericBreakingChangeAttribute>());
                }

                foreach (PropertyInfo p in type.GetRuntimeProperties())
                {
                    attributeList.AddRange(p.GetCustomAttributes(typeof(GenericBreakingChangeAttribute), false).Cast <GenericBreakingChangeAttribute>());
                }
            }
            else if (commandInfo.GetType() == typeof(FunctionInfo))
            {
                attributeList.AddRange(((FunctionInfo)commandInfo).ScriptBlock.Attributes.Where(e => typeof(GenericBreakingChangeAttribute).IsAssignableFrom(e.GetType())).Cast <GenericBreakingChangeAttribute>());
                foreach (var parameter in ((FunctionInfo)commandInfo).Parameters)
                {
                    attributeList.AddRange(parameter.Value.Attributes.Where(e => typeof(GenericBreakingChangeAttribute).IsAssignableFrom(e.GetType())).Cast <GenericBreakingChangeAttribute>());
                }
            }
            return(invocationInfo == null ? attributeList : attributeList.Where(e => e.GetType() == typeof(ParameterSetBreakingChangeAttribute) ? ((ParameterSetBreakingChangeAttribute)e).IsApplicableToInvocation(invocationInfo, parameterSet) : e.IsApplicableToInvocation(invocationInfo)));
        }
Пример #4
0
 public virtual bool IsApplicableToInvocation(InvocationInfo invocation)
 {
     return(true);
 }
Пример #5
0
        /// <summary>
        /// </summary>
        protected override void BeginProcessing()
        {
            // ValidateNotNullOrEmpty attribute is not working for System.Uri datatype, so handling it here
            if ((_cssuriSpecified) && (string.IsNullOrEmpty(_cssuri.OriginalString.Trim())))
            {
                ArgumentException ex = new(StringUtil.Format(UtilityCommonStrings.EmptyCSSUri, "CSSUri"));
                ErrorRecord       er = new(ex, "ArgumentException", ErrorCategory.InvalidArgument, "CSSUri");
                ThrowTerminatingError(er);
            }

            _propertyMshParameterList = ProcessParameter(_property);

            if (!string.IsNullOrEmpty(_title))
            {
                WebUtility.HtmlEncode(_title);
            }

            // This first line ensures w3c validation will succeed. However we are not specifying
            // an encoding in the HTML because we don't know where the text will be written and
            // if a particular encoding will be used.

            if (!_fragment)
            {
                if (!_transitional)
                {
                    WriteObject("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"  \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">");
                }
                else
                {
                    WriteObject("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"  \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">");
                }

                WriteObject("<html xmlns=\"http://www.w3.org/1999/xhtml\">");
                WriteObject("<head>");
                if (_charsetSpecified)
                {
                    WriteObject("<meta charset=\"" + _charset + "\">");
                }

                if (_metaSpecified)
                {
                    List <string> useditems = new();
                    foreach (string s in _meta.Keys)
                    {
                        if (!useditems.Contains(s))
                        {
                            switch (s.ToLower())
                            {
                            case "content-type":
                            case "default-style":
                            case "x-ua-compatible":
                                WriteObject("<meta http-equiv=\"" + s + "\" content=\"" + _meta[s] + "\">");
                                break;

                            case "application-name":
                            case "author":
                            case "description":
                            case "generator":
                            case "keywords":
                            case "viewport":
                                WriteObject("<meta name=\"" + s + "\" content=\"" + _meta[s] + "\">");
                                break;

                            default:
                                MshCommandRuntime mshCommandRuntime = this.CommandRuntime as MshCommandRuntime;
                                string            Message           = StringUtil.Format(ConvertHTMLStrings.MetaPropertyNotFound, s, _meta[s]);
                                WarningRecord     record            = new(Message);
                                InvocationInfo    invocationInfo    = GetVariableValue(SpecialVariables.MyInvocation) as InvocationInfo;

                                if (invocationInfo != null)
                                {
                                    record.SetInvocationInfo(invocationInfo);
                                }

                                mshCommandRuntime.WriteWarning(record);
                                WriteObject("<meta name=\"" + s + "\" content=\"" + _meta[s] + "\">");
                                break;
                            }

                            useditems.Add(s);
                        }
                    }
                }

                WriteObject(_head ?? new string[] { "<title>" + _title + "</title>" }, true);
                if (_cssuriSpecified)
                {
                    WriteObject("<link rel=\"stylesheet\" type=\"text/css\" href=\"" + _cssuri + "\" />");
                }

                WriteObject("</head><body>");
                if (_body != null)
                {
                    WriteObject(_body, true);
                }
            }

            if (_preContent != null)
            {
                WriteObject(_preContent, true);
            }

            WriteObject("<table>");
            _isTHWritten = false;
        }
Пример #6
0
 public void BeforeInvoke(InvocationInfo info)
 {
 }
Пример #7
0
 public void AfterInvoke(InvocationInfo info, object returnValue)
 {
 }
Пример #8
0
 /// <summary>
 /// Helper to transcribe an error through formatting and output.
 /// </summary>
 /// <param name="context">The Execution Context</param>
 /// <param name="invocation">The invocation info associated with the record</param>
 /// <param name="errorWrap">The error record</param>
 internal void TranscribeError(ExecutionContext context, InvocationInfo invocation, PSObject errorWrap)
 {
     context.InternalHost.UI.TranscribeCommandComplete(invocation);
     InitialSessionState minimalState = InitialSessionState.CreateDefault2();
     Collection<PSObject> results = PowerShell.Create(minimalState).AddCommand("Out-String").Invoke(
         new List<PSObject>() { errorWrap });
     TranscribeResult(results[0].ToString());
 }
Пример #9
0
 internal void LogExecutionParameterBinding(InvocationInfo invocationInfo, string parameterName, string parameterValue)
 {
     string message = StringUtil.Format(PipelineStrings.PipelineExecutionParameterBinding, GetCommand(invocationInfo), parameterName, parameterValue);
     Log(message, invocationInfo, PipelineExecutionStatus.ParameterBinding);
 }
 public ConnectToSourceMongoDbTaskCmdlet(InvocationInfo myInvocation) : base(myInvocation)
 {
 }
Пример #11
0
 public UserAgent(InvocationInfo invocation)
     : this(invocation?.MyCommand?.Module?.Version ?? new Version("1.0.0"))
 {
 }
Пример #12
0
 public object Intercept(InvocationInfo info)
 {
     return(info.TargetMethod.Invoke(target, info.Arguments));
 }
Пример #13
0
 public ConnectToTargetSqlDbMiSsisTaskCmdlet(InvocationInfo myInvocation) : base(myInvocation)
 {
 }
Пример #14
0
 internal Decision(InvocationInfo method, int num)
     : base("Decision" + num.ToString())
 {
     Method = method;
 }
Пример #15
0
 public ConnectToSourceSqlServerSsisTaskCmdlet(InvocationInfo myInvocation) : base(myInvocation)
 {
 }
Пример #16
0
        private void Log(string logElement, InvocationInfo invocation, PipelineExecutionStatus pipelineExecutionStatus)
        {
            System.Management.Automation.Host.PSHostUserInterface hostInterface = null;
            if (this.LocalPipeline != null)
            {
                hostInterface = this.LocalPipeline.Runspace.GetExecutionContext.EngineHostInterface.UI;
            }

            // Acknowledge command completion
            if (hostInterface != null)
            {
                if (pipelineExecutionStatus == PipelineExecutionStatus.Complete)
                {
                    hostInterface.TranscribeCommandComplete(invocation);
                    return;
                }
                else if (pipelineExecutionStatus == PipelineExecutionStatus.PipelineComplete)
                {
                    hostInterface.TranscribePipelineComplete();
                    return;
                }
            }

            // Log the cmdlet invocation execution details if we didn't have an associated script line with it.
            if ((invocation == null) || String.IsNullOrEmpty(invocation.Line))
            {
                if (hostInterface != null)
                {
                    hostInterface.TranscribeCommand(logElement, invocation);
                }
            }

            if (!String.IsNullOrEmpty(logElement))
            {
                _eventLogBuffer.Add(logElement);
            }
        }
Пример #17
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, InvocationInfo invocationInfo, string parameterSetName, string correlationId, string processRecordId, System.Exception exception)
        {
            /// Drain the queue of ADAL events whenever an event is fired
            DrainDeferredEvents(signal, cancellationToken);
            switch (id)
            {
            case Events.BeforeCall:
                await OnBeforeCall(id, cancellationToken, getEventData, signal, processRecordId);

                break;

            case Events.CmdletProcessRecordAsyncStart:
                await OnProcessRecordAsyncStart(id, cancellationToken, getEventData, signal, processRecordId, invocationInfo, parameterSetName, correlationId);

                break;

            case Events.CmdletProcessRecordAsyncEnd:
                await OnProcessRecordAsyncEnd(id, cancellationToken, getEventData, signal, processRecordId);

                break;

            case Events.CmdletException:
                await OnCmdletException(id, cancellationToken, getEventData, signal, processRecordId, exception);

                break;

            case Events.ResponseCreated:
                await OnResponseCreated(id, cancellationToken, getEventData, signal, processRecordId);

                break;

            case Events.Polling:
                await OnPolling(id, cancellationToken, getEventData, signal, processRecordId);

                break;

            default:
                getEventData.Print(signal, cancellationToken, Events.Information, id);
                break;
            }
        }
 public override void AfterInvoke(InvocationInfo info, ref object returnValue)
 {
     return;
 }
Пример #19
0
        private string GetCommand(InvocationInfo invocationInfo)
        {
            if (invocationInfo == null)
                return "";

            if (invocationInfo.MyCommand != null)
            {
                return invocationInfo.MyCommand.Name;
            }

            return "";
        }
 public override void ReplaceMethod(InvocationInfo info, out object returnValue)
 {
     App.Popups.ShowOkCancel(this, "fail", "Tutorial?", "Do you really want to play the Tutorial?", "Yes", "No");
     returnValue = null;
 }
Пример #21
0
 /// <summary>
 /// IDisposable implementation
 /// When the command is complete, release the associated members
 /// </summary>
 /// <remarks>
 /// Using InternalDispose instead of Dispose pattern because this
 /// interface was shipped in PowerShell V1 and 3rd cmdlets indirectly
 /// derive from this interface. If we depend on Dispose() and 3rd
 /// party cmdlets do not call base.Dispose (which is the case), we 
 /// will still end up having this leak.
 /// </remarks>
 internal void InternalDispose(bool isDisposing)
 {
     _myInvocation = null;
     _state = null;
     _commandInfo = null;
     _context = null;
 }
Пример #22
0
 public static IEnumerable <RuntimeDefinedParameter> GetUsedDynamicParameters(RuntimeDefinedParameterDictionary dynamicParameters, InvocationInfo MyInvocation)
 {
     return(dynamicParameters.Values.Where(dp => MyInvocation.BoundParameters.Keys.Any(bp => bp.Equals(dp.Name))));
 }
Пример #23
0
 public CmdInfoHandler(string processRecordId, InvocationInfo invocationInfo, string parameterSetName)
 {
     this.processRecordId  = processRecordId;
     this.parameterSetName = parameterSetName;
     this.invocationInfo   = invocationInfo;
 }
Пример #24
0
 public ValidateMongoDbMigrationTaskCmdlet(InvocationInfo myInvocation) : base(myInvocation)
 {
 }
Пример #25
0
        private async Task <object> DoInvokeImpl(InvocationInfo info)
        {
            using (var cts = new CancellationTokenSource())
            {
                try
                {
                    string methodName = info.TargetMethod.Name;
                    if (!_methodsDb.ContainsKey(methodName))
                    {
                        throw new EnumException <DoInvokeImplExcs>(
                                  DoInvokeImplExcs.MethodNotFound,
                                  tag: methodName
                                  );
                    }
                    var  methodInfo    = _methodsDb[methodName];
                    uint sendMessageId = await _reliableSamHelper.GetNextOutMessageId().ConfigureAwait(false);

                    var         pingCallbackTimeoutTcs        = new TaskCompletionSource <object>();
                    IDisposable pingCallbackCheckSubscription =
                        _reliableSamHelper.RawDatagramReceived
                        .Where(
                            x =>
                            x.ReplyToMessageId == sendMessageId &&
                            x.MessageKind ==
                            (byte)EJsonRpcSamI2PMessageKinds.ReceiveCallbackPing &&
                            x.Destination == _serverDestination
                            ).Timeout(_samClientSettings.CallbackPingTimeout)
                        .ObserveOn(TaskPoolScheduler.Default)
                        .Subscribe(
                            i => { },
                            exc =>
                    {
                        if (exc is TimeoutException)
                        {
                            pingCallbackTimeoutTcs.TrySetResult(null);
                        }
                    }
                            );
                    try
                    {
                        Task <ReliableSamHelper.ReliableMessageReceivedArgs> waitResult;
                        if (methodInfo.ReturnResultReliable)
                        {
                            waitResult = _reliableSamHelper.ReliableMessageReceived
                                         .Where(
                                x =>
                                x.ReplyToMessageId == sendMessageId &&
                                x.MessageKind ==
                                (byte)EJsonRpcSamI2PMessageKinds.ReceiveResult &&
                                x.Destination == _serverDestination
                                )
                                         .FirstAsync()
                                         .ToTask(cts.Token);
                        }
                        else
                        {
                            waitResult = _reliableSamHelper.RawDatagramReceived
                                         .Where(
                                x =>
                                x.ReplyToMessageId == sendMessageId &&
                                x.MessageKind ==
                                (byte)EJsonRpcSamI2PMessageKinds.ReceiveResult &&
                                x.Destination == _serverDestination
                                )
                                         .FirstAsync()
                                         .ToTask(cts.Token);
                        }

                        var waitResultErr = _reliableSamHelper.RawDatagramReceived
                                            .Where(
                            x =>
                            x.ReplyToMessageId == sendMessageId &&
                            x.MessageKind ==
                            (byte)EJsonRpcSamI2PMessageKinds.ReceiveError &&
                            x.Destination == _serverDestination
                            ).FirstAsync()
                                            .ToTask(cts.Token);

                        var    joe             = JsonRpcClientProcessor.GetJsonRpcRequest(info);
                        string jsonRequest     = JsonConvert.SerializeObject(joe, Formatting.Indented);
                        byte[] byteJsonRequest = Encoding.UTF8.GetBytes(jsonRequest);
                        if (_samClientSettings.CompressData)
                        {
                            byteJsonRequest = byteJsonRequest.Compress();
                        }
                        try
                        {
                            if (methodInfo.CallReliable)
                            {
                                await _reliableSamHelper.SendReliableMessage(
                                    _serverDestination,
                                    byteJsonRequest,
                                    messageId :
                                    sendMessageId,
                                    messageKind :
                                    (byte)EJsonRpcSamI2PMessageKinds.SendCall,
                                    token : cts.Token
                                    ).ConfigureAwait(false);
                            }
                            else
                            {
                                await _reliableSamHelper.SendRawDatagram(
                                    _serverDestination,
                                    byteJsonRequest,
                                    sendMessageId,
                                    (byte)EJsonRpcSamI2PMessageKinds.SendCall
                                    ).ConfigureAwait(false);
                            }
                        }
                        catch (
                            EnumException <
                                ReliableSamHelper.SendReliableMessageExcs
                                > reliableExc
                            )
                        {
                            if (
                                reliableExc.ExceptionCode
                                == ReliableSamHelper
                                .SendReliableMessageExcs
                                .HandshakeTimeout
                                ||
                                reliableExc.ExceptionCode
                                == ReliableSamHelper
                                .SendReliableMessageExcs
                                .SendBlocksTimeout
                                )
                            {
                                ServiceStatus.OnNext(false);
                                throw new I2PTimeoutException(
                                          "Send rpc request i2p error",
                                          reliableExc
                                          );
                            }
                            throw;
                        }
                        var delyOrResultTask = await Task.WhenAny(
                            waitResult,
                            waitResultErr,
                            Task.Delay(
                                _samClientSettings.TotalReturnTimeout,
                                cts.Token
                                ),
                            pingCallbackTimeoutTcs.Task
                            ).ConfigureAwait(false);

                        if (delyOrResultTask != waitResult)
                        {
                            if (delyOrResultTask == waitResultErr)
                            {
                                var errResult = await waitResultErr.ConfigureAwait(false);

                                ServiceStatus.OnNext(true);
                                var errResultData = errResult.Data;
                                if (_samClientSettings.CompressData)
                                {
                                    errResultData = errResultData.Decompress();
                                }
                                var jsonResult
                                    = JsonConvert.DeserializeObject <JObject>(
                                          Encoding.UTF8.GetString(errResultData)
                                          );
                                return(await JsonRpcClientProcessor.GetJsonRpcResult(
                                           jsonResult,
                                           info
                                           ).ConfigureAwait(false));
                            }
                            ServiceStatus.OnNext(false);
                            if (delyOrResultTask == pingCallbackTimeoutTcs.Task)
                            {
                                throw new I2PTimeoutException(
                                          "Callback ping timeout",
                                          null
                                          );
                            }
                            throw new I2PTimeoutException(
                                      "Get result timeout",
                                      null
                                      );
                        }
                        {
                            var retArgs = await waitResult.ConfigureAwait(false);

                            ServiceStatus.OnNext(true);
                            var retArgsData = retArgs.Data;
                            if (_samClientSettings.CompressData)
                            {
                                retArgsData = retArgsData.Decompress();
                            }
                            var jsonResult = JsonConvert.DeserializeObject <JObject>(
                                Encoding.UTF8.GetString(retArgsData)
                                );
                            return(await JsonRpcClientProcessor.GetJsonRpcResult(jsonResult, info)
                                   .ConfigureAwait(false));
                        }
                    }
                    finally
                    {
                        pingCallbackCheckSubscription.Dispose();
                    }
                }
                catch (TimeoutException)
                {
                    throw;
                }
                catch (RpcRethrowableException rpcExc)
                {
                    if (_advancedRpcRethrowableExceptionHandling != null)
                    {
                        _advancedRpcRethrowableExceptionHandling(rpcExc);
                    }
                    throw;
                }
                catch (EnumException <DoInvokeImplExcs> )
                {
                    throw;
                }
                catch (Exception exc)
                {
                    throw new EnumException <DoInvokeImplExcs>(
                              DoInvokeImplExcs.UnexpectedError,
                              innerException: exc
                              );
                }
                finally
                {
                    cts.Cancel();
                }
            }
        }
Пример #26
0
        /// <summary>
        /// Common Module Event Listener, allows to handle emitted by CmdLets
        /// </summary>
        /// <param name="id">The ID of the event </param>
        /// <param name="cancellationToken">The cancellation token for the event </param>
        /// <param name="getEventData">A delegate to get the detailed event data</param>
        /// <param name="signal">The callback for the event dispatcher</param>
        /// <param name="invocationInfo">The <see cref="System.Management.Automation.InvocationInfo" /> from the cmdlet</param>
        /// <param name="parameterSetName">The cmdlet's parameterset name</param>
        /// <param name="exception">the exception that is being thrown (if available)</param>
        /// <returns>
        /// A <see cref="global::System.Threading.Tasks.Task" /> that will be complete when handling of the event is completed.
        /// </returns>
        public async Task EventHandler(string id, CancellationToken cancellationToken, Func <EventArgs> getEventData, Func <string, CancellationToken, Func <EventArgs>, Task> signal, InvocationInfo invocationInfo, string parameterSetName, System.Exception exception)
        {
            if (invocationInfo.BoundParameters.ContainsKey("Debug"))
            {
                switch (id)
                {
                case Events.BeforeCall:
                    await BeforeCall(id, cancellationToken, getEventData, signal);

                    break;

                case Events.Finally:
                    await Finally(id, cancellationToken, getEventData, signal);

                    break;

                default:
                    getEventData.Print(signal, cancellationToken, Events.Information, id);
                    break;
                }
            }
        }
Пример #27
0
 public SqlConnectionInfoCmdlet(InvocationInfo myInvocation) : base(myInvocation)
 {
 }
Пример #28
0
        /// <summary>
        /// Write an error to the output pipe, or throw a terminating error.
        /// </summary>
        protected override void ProcessRecord()
        {
            ErrorRecord errorRecord = this.ErrorRecord;

            if (errorRecord != null)
            {
                // copy constructor
                errorRecord = new ErrorRecord(errorRecord, null);
            }
            else
            {
                Exception e   = this.Exception;
                string    msg = Message;
                if (e == null)
                {
                    e = new WriteErrorException(msg);
                }

                string errid = ErrorId;
                if (string.IsNullOrEmpty(errid))
                {
                    errid = e.GetType().FullName;
                }

                errorRecord = new ErrorRecord(
                    e,
                    errid,
                    Category,
                    TargetObject
                    );

                if (this.Exception != null && !string.IsNullOrEmpty(msg))
                {
                    errorRecord.ErrorDetails = new ErrorDetails(msg);
                }
            }

            string recact = RecommendedAction;

            if (!string.IsNullOrEmpty(recact))
            {
                if (errorRecord.ErrorDetails == null)
                {
                    errorRecord.ErrorDetails = new ErrorDetails(errorRecord.ToString());
                }

                errorRecord.ErrorDetails.RecommendedAction = recact;
            }

            if (!string.IsNullOrEmpty(CategoryActivity))
            {
                errorRecord.CategoryInfo.Activity = CategoryActivity;
            }
            if (!string.IsNullOrEmpty(CategoryReason))
            {
                errorRecord.CategoryInfo.Reason = CategoryReason;
            }
            if (!string.IsNullOrEmpty(CategoryTargetName))
            {
                errorRecord.CategoryInfo.TargetName = CategoryTargetName;
            }
            if (!string.IsNullOrEmpty(CategoryTargetType))
            {
                errorRecord.CategoryInfo.TargetType = CategoryTargetType;
            }

            /* 2005/01/25 removing throw-error
             * if (_terminating)
             * {
             *  ThrowTerminatingError(errorRecord);
             * }
             * else
             * {
             */

            // 2005/07/14-913791 "write-error output is confusing and misleading"
            // set InvocationInfo to the script not the command
            InvocationInfo myInvocation = GetVariableValue(SpecialVariables.MyInvocation) as InvocationInfo;

            if (myInvocation != null)
            {
                errorRecord.SetInvocationInfo(myInvocation);
                errorRecord.PreserveInvocationInfoOnce = true;
                if (!string.IsNullOrEmpty(CategoryActivity))
                {
                    errorRecord.CategoryInfo.Activity = CategoryActivity;
                }
                else
                {
                    errorRecord.CategoryInfo.Activity = "Write-Error";
                }
            }

            WriteError(errorRecord);

            /*
             * }
             */
        }
Пример #29
0
        /// <summary>
        /// See if the bound parameters contain the current parameter, if they do
        /// then the attribbute is applicable
        /// If the invocationInfo is null we return true
        /// </summary>
        /// <param name="invocation"></param>
        /// <returns>bool</returns>
        public override bool IsApplicableToInvocation(InvocationInfo invocationInfo)
        {
            bool?applicable = invocationInfo == null ? true : invocationInfo.BoundParameters?.Keys?.Contains(this.NameOfParameterChanging);

            return(applicable.HasValue ? applicable.Value : false);
        }
Пример #30
0
 public ValidateSqlServerSqlDbMiSyncTaskCmdlet(InvocationInfo myInvocation) : base(myInvocation)
 {
 }
Пример #31
0
 public MigrateSqlServerSqlDbSyncTaskCmdlet(InvocationInfo myInvocation) : base(myInvocation)
 {
 }
Пример #32
0
        /// <summary>
        /// Transcribes a command being invoked
        /// </summary>
        /// <param name="commandText">The text of the command being invoked.</param>
        /// <param name="invocation">The invocation info of the command being transcribed.</param>
        internal void TranscribeCommand(string commandText, InvocationInfo invocation)
        {
            if (ShouldIgnoreCommand(commandText, invocation))
            {
                return;
            }

            if (IsTranscribing)
            {
                // We don't actually log the output here, because there may be multiple command invocations
                // in a single input - especially in the case of API logging, which logs the command and
                // its parameters as separate calls.
                // Instead, we add this to the 'pendingOutput' collection, which we flush when either
                // the command generates output, or when we are told to invoke ignore the next command.
                foreach (TranscriptionOption transcript in TranscriptionData.Transcripts.Prepend<TranscriptionOption>(TranscriptionData.SystemTranscript))
                {
                    if (transcript != null)
                    {
                        lock (transcript.OutputToLog)
                        {
                            if (transcript.OutputToLog.Count == 0)
                            {
                                if (transcript.IncludeInvocationHeader)
                                {
                                    transcript.OutputToLog.Add("**********************");
                                    transcript.OutputToLog.Add(
                                        String.Format(
                                            Globalization.CultureInfo.InvariantCulture, InternalHostUserInterfaceStrings.CommandStartTime,
                                            DateTime.Now.ToString("yyyyMMddHHmmss", CultureInfo.InvariantCulture)));
                                    transcript.OutputToLog.Add("**********************");
                                }

                                transcript.OutputToLog.Add(TranscriptionData.PromptText + commandText);
                            }
                            else
                            {
                                transcript.OutputToLog.Add(">> " + commandText);
                            }
                        }
                    }
                }
            }
        }
Пример #33
0
        internal async Task OnProcessRecordAsyncStart(string id, CancellationToken cancellationToken, GetEventData getEventData, SignalDelegate signal, string processRecordId, InvocationInfo invocationInfo, string parameterSetName, string correlationId)
        {
            var qos = _telemetry.CreateQosEvent(invocationInfo, parameterSetName, correlationId, processRecordId);

            await signal(Events.Debug, cancellationToken,
                         () => EventHelper.CreateLogEvent($"[{id}]: Created new QosEvent for command '{qos?.CommandName}': {qos?.ToString()}"));
        }
Пример #34
0
        /// <summary>
        /// Signals that a command being invoked (and its output) should be ignored.
        /// </summary>
        /// <param name="commandText">The text of the command being invoked.</param>
        /// <param name="invocation">The invocation info of the command being transcribed.</param>
        internal void IgnoreCommand(string commandText, InvocationInfo invocation)
        {
            TranscribeCommandComplete(null);

            if (TranscriptionData.CommandBeingIgnored == null)
            {
                TranscriptionData.CommandBeingIgnored = commandText;
                TranscriptionData.IsHelperCommand = false;

                if ((invocation != null) && (invocation.MyCommand != null))
                {
                    TranscriptionData.CommandBeingIgnored = invocation.MyCommand.Name;
                }
            }
        }
Пример #35
0
 public object Intercept(InvocationInfo info)
 {
     return(info.TargetMethod == interceptMethod?
            doImmediateLoad((string)info.Arguments[0]) :
                info.TargetMethod.Invoke(_target, info.Arguments));
 }
Пример #36
0
        internal void LogExecutionError(InvocationInfo invocationInfo, ErrorRecord errorRecord)
        {
            if (errorRecord == null)
                return;

            string message = StringUtil.Format(PipelineStrings.PipelineExecutionNonTerminatingError, GetCommand(invocationInfo), errorRecord.ToString());
            Log(message, invocationInfo, PipelineExecutionStatus.Error);
        }
Пример #37
0
        private bool ShouldIgnoreCommand(string logElement, InvocationInfo invocation)
        {
            string commandName = logElement;

            if (invocation != null)
            {
                commandName = invocation.InvocationName;

                // Do not transcribe Out-Default
                CmdletInfo invocationCmdlet = invocation.MyCommand as CmdletInfo;
                if (invocationCmdlet != null)
                {
                    if (invocationCmdlet.ImplementingType == typeof(Microsoft.PowerShell.Commands.OutDefaultCommand))
                    {
                        // We will ignore transcribing the command itself, but not call the IgnoreCommand() method
                        // (because that will ignore the results)
                        return true;
                    }
                }

                // Don't log internal commands to the transcript.
                if (invocation.CommandOrigin == CommandOrigin.Internal)
                {
                    IgnoreCommand(logElement, invocation);
                    return true;
                }
            }

            // Don't log helper commands to the transcript
            string[] helperCommands = { "TabExpansion2", "prompt", "TabExpansion", "PSConsoleHostReadline" };
            foreach (string helperCommand in helperCommands)
            {
                if (String.Equals(helperCommand, commandName, StringComparison.OrdinalIgnoreCase))
                {
                    IgnoreCommand(logElement, invocation);

                    // Record that this is a helper command. In this case, we ignore even the results
                    // from Out-Default
                    TranscriptionData.IsHelperCommand = true;
                    return true;
                }
            }

            return false;
        }
Пример #38
0
 public object DoInvoke(InvocationInfo info)
 {
     return(JsonRpcClientProcessor.DoInvokeHelper(info, DoInvokeImpl));
 }
Пример #39
0
        /// <summary>
        /// Transcribes / records the completion of a command
        /// </summary>
        /// <param name="invocation"></param>
        internal void TranscribeCommandComplete(InvocationInfo invocation)
        {
            FlushPendingOutput();

            if (invocation != null)
            {
                // If we're ignoring a command that was internal, we still want the
                // results of Out-Default. However, if it was a host helper command,
                // ignore all output (including Out-Default)
                string commandNameToCheck = TranscriptionData.CommandBeingIgnored;
                if (TranscriptionData.IsHelperCommand)
                {
                    commandNameToCheck = "Out-Default";
                }

                // If we're completing a command that we were ignoring, start transcribing results / etc. again.
                if ((TranscriptionData.CommandBeingIgnored != null) &&
                    (invocation != null) && (invocation.MyCommand != null) &&
                    String.Equals(commandNameToCheck, invocation.MyCommand.Name, StringComparison.OrdinalIgnoreCase))
                {
                    TranscriptionData.CommandBeingIgnored = null;
                    TranscriptionData.IsHelperCommand = false;
                }
            }
        }
 public MongoDbObjectCommandCmdlet(InvocationInfo myInvocation, string commandName) : base(myInvocation)
 {
     this.commandName = commandName;
 }
Пример #41
0
 public override void BeforeInvoke(InvocationInfo info)
 {
     return;
 }
Пример #42
0
 public virtual object DoInvoke(InvocationInfo info) => info.TargetMethod.Invoke(Target, info.Arguments);
Пример #43
0
 public object Invoke(InvocationInfo invocationInfo)
 {
     return invocationInfo.Proceed();
 }
Пример #44
0
 internal void LogExecutionComplete(InvocationInfo invocationInfo, string text)
 {
     string message = StringUtil.Format(PipelineStrings.PipelineExecutionInformation, GetCommand(invocationInfo), text);
     Log(message, invocationInfo, PipelineExecutionStatus.Complete);
 }