Exemplo n.º 1
0
        public Task <ActionResult> CaptureTraceCustom(
            [FromBody][Required]
            Models.EventPipeConfiguration configuration,
            [FromQuery]
            int?pid = null,
            [FromQuery]
            Guid?uid = null,
            [FromQuery]
            string name = null,
            [FromQuery][Range(-1, int.MaxValue)]
            int durationSeconds = 30,
            [FromQuery]
            string egressProvider = null)
        {
            ProcessKey?processKey = GetProcessKey(pid, uid, name);

            return(InvokeForProcess(processInfo =>
            {
                foreach (Models.EventPipeProvider provider in configuration.Providers)
                {
                    if (!CounterValidator.ValidateProvider(_counterOptions.CurrentValue,
                                                           provider, out string errorMessage))
                    {
                        throw new ValidationException(errorMessage);
                    }
                }

                TimeSpan duration = Utilities.ConvertSecondsToTimeSpan(durationSeconds);

                var traceConfiguration = TraceUtilities.GetTraceConfiguration(configuration.Providers, configuration.RequestRundown, configuration.BufferSizeInMB);

                return StartTrace(processInfo, traceConfiguration, duration, egressProvider);
            }, processKey, Utilities.ArtifactType_Trace));
        }
        /// <summary>
        /// Performs the SOAP and HTTP logging.
        /// </summary>
        /// <param name="service">The SOAP service.</param>
        /// <param name="soapResponse">The SOAP response xml.</param>
        /// <param name="soapRequest">The SOAP request xml.</param>
        private void PerformLogging(AdsClient service, string soapRequest, string soapResponse)
        {
            if (service == null || service.User == null || soapRequest == null || soapResponse == null)
            {
                return;
            }

            if (config.MaskCredentials)
            {
                XmlDocument xDoc = SerializationUtilities.LoadXml(soapRequest);
                MaskCredentialsInLogs(xDoc, GetFieldsToMask());
                soapRequest = xDoc.OuterXml;
            }

            string formattedSoapRequest  = FormatSoapRequest(service.LastRequest, soapRequest);
            string formattedSoapResponse = FormatSoapResponse(service.LastResponse, soapResponse);
            string formattedHttpRequest  = FormatHttpRequest(soapRequest);
            string formattedHttpResponse = FormatHttpResponse(soapResponse);

            string soapLog    = formattedSoapRequest + formattedSoapResponse;
            string requestLog = string.Format(CultureInfo.InvariantCulture, "host={0},url={1},{2},{3}",
                                              service.LastRequest.RequestUri.Host, service.LastRequest.RequestUri.AbsolutePath,
                                              formattedHttpRequest, formattedHttpResponse);

            ContextStore.AddKey("FormattedSoapLog", soapLog);
            ContextStore.AddKey("FormattedRequestLog", requestLog);

            bool isError = service.LastResponse != null && service.LastResponse is HttpWebResponse &&
                           (service.LastResponse as HttpWebResponse).StatusCode ==
                           HttpStatusCode.InternalServerError;

            TraceUtilities.WriteSoapXmlLogs(soapLog, isError);
            TraceUtilities.WriteRequestInfoLogs(requestLog, isError);
        }
Exemplo n.º 3
0
        private Task <ActionResult> StartTrace(
            IProcessInfo processInfo,
            MonitoringSourceConfiguration configuration,
            TimeSpan duration,
            string egressProvider)
        {
            string fileName = TraceUtilities.GenerateTraceFileName(processInfo.EndpointInfo);

            return(Result(
                       Utilities.ArtifactType_Trace,
                       egressProvider,
                       async(outputStream, token) =>
            {
                IDisposable operationRegistration = null;
                try
                {
                    if (_diagnosticPortOptions.Value.ConnectionMode == DiagnosticPortConnectionMode.Listen)
                    {
                        operationRegistration = _operationTrackerService.Register(processInfo.EndpointInfo);
                    }
                    await TraceUtilities.CaptureTraceAsync(null, processInfo.EndpointInfo, configuration, duration, outputStream, token);
                }
                finally
                {
                    operationRegistration?.Dispose();
                }
            },
                       fileName,
                       ContentTypes.ApplicationOctetStream,
                       processInfo.EndpointInfo));
        }
Exemplo n.º 4
0
 /// <summary>
 /// Handles the logging of asynchronous server streaming calls.
 /// </summary>
 /// <typeparam name="TRequest">The type of the request.</typeparam>
 /// <typeparam name="TResponse">The type of the response.</typeparam>
 /// <param name="request">The request.</param>
 /// <param name="response">The response.</param>
 /// <param name="context">The context.</param>
 /// <param name="rpcException">The RPC exception.</param>
 /// <param name="call">The call.</param>
 internal void HandleAsyncServerStreamingLogging <TRequest, TResponse>(TRequest request,
                                                                       TResponse response, ClientInterceptorContext <TRequest, TResponse> context,
                                                                       AggregateException rpcException, AsyncServerStreamingCall <TResponse> call)
     where TRequest : class
     where TResponse : class
 {
     // Generating log entry is expensive, so let's do that only if the log source
     // has been configured to do so.
     if (TraceUtilities.ShouldGenerateRequestLogs())
     {
         LogEntry logEntry = new LogEntry()
         {
             Host            = config.ServerUrl,
             Method          = context.Method.FullName,
             RequestHeaders  = context.Options.Headers,
             Request         = request,
             ResponseHeaders = Merge(GetResponseHeader(call.ResponseHeadersAsync),
                                     TryGetCallTrailers(call)),
             Response        = response,
             Exception       = UnaryRpcInterceptor.ParseTaskException(rpcException),
             IsFailure       = (rpcException != null),
             CustomerId      = GetCustomerId(request),
             PartialFailures = (rpcException != null) ? "" : GetPartialFailures(response)
         };
         WriteLogs(logEntry);
     }
 }
Exemplo n.º 5
0
        /// <summary>
        /// Initializes the service before MakeApiCall.
        /// </summary>
        /// <param name="methodName">Name of the method.</param>
        /// <param name="parameters">The method parameters.</param>
        protected override void InitForCall(string methodName, object[] parameters)
        {
            AdWordsAppConfig config = this.User.Config as AdWordsAppConfig;
            RequestHeader    header = GetRequestHeader();

            if (string.IsNullOrEmpty(header.developerToken))
            {
                throw new ArgumentNullException(AdWordsErrorMessages.DeveloperTokenCannotBeEmpty);
            }

            if (string.IsNullOrEmpty(header.clientCustomerId))
            {
                TraceUtilities.WriteGeneralWarnings(AdWordsErrorMessages.ClientCustomerIdIsEmpty);
            }

            string oAuthHeader = null;

            if (this.User.OAuthProvider != null)
            {
                oAuthHeader = this.User.OAuthProvider.GetAuthHeader();
            }
            else
            {
                throw new AdWordsApiException(null, AdWordsErrorMessages.OAuthProviderCannotBeNull);
            }
            ContextStore.AddKey("OAuthHeader", oAuthHeader);
            base.InitForCall(methodName, parameters);
        }
        /// <summary>
        /// Intercepts an asynchronous invocation of a simple remote call.
        /// </summary>
        /// <param name="request">The request message of the invocation.</param>
        /// <param name="context">The <see cref="ClientInterceptorContext{TRequest, TResponse}" />
        /// associated with the current invocation.</param>
        /// <param name="continuation">The callback that continues the invocation process.
        /// This can be invoked zero or more times by the interceptor.
        /// The interceptor can invoke the continuation passing the given
        /// request value and context arguments, or substitute them as it sees fit.</param>
        /// <returns>
        /// An instance of <see cref="AsyncUnaryCall{TResponse}" />
        /// representing an asynchronous unary invocation.
        /// The interceptor can simply return the return value of the
        /// continuation delegate passed to it intact, or construct its
        /// own substitute as it sees fit.
        /// </returns>
        public override AsyncUnaryCall <TResponse> AsyncUnaryCall <TRequest, TResponse>(
            TRequest request, ClientInterceptorContext <TRequest, TResponse> context,
            AsyncUnaryCallContinuation <TRequest, TResponse> continuation)
        {
            AsyncUnaryCall <TResponse> call = continuation(request, context);
            Task t = call.ResponseAsync.ContinueWith(
                delegate(Task <TResponse> oldTask)
            {
                // Generating log entry is expensive, so let's do that only if the log source
                // has been configured to do so.
                if (TraceUtilities.ShouldGenerateRequestLogs())
                {
                    LogEntry logEntry = new LogEntry()
                    {
                        Host            = Config.ServerUrl,
                        Method          = context.Method.FullName,
                        RequestHeaders  = context.Options.Headers,
                        Request         = request,
                        ResponseHeaders = GetResponseHeader(call),
                        Response        = (oldTask.IsFaulted) ? default(TResponse) : oldTask.Result,
                        Exception       = GetGoogleAdsException(oldTask.Exception),
                        IsFailure       = oldTask.IsFaulted,
                        CustomerId      = GetCustomerId(request),
                        PartialFailures = (oldTask.IsFaulted)? "" :
                                          GetPartialFailures(oldTask.Result)
                    };
                    OnLogEventAvailable?.Invoke(this, logEntry);
                }
            });

            t.Wait();
            return(call);
        }
Exemplo n.º 7
0
        /// <summary>
        /// Enumerates a sequence of extensions, omitting any extensions that throw MEF exceptions.
        /// </summary>
        /// <typeparam name="T">The type of extension.</typeparam>
        /// <param name="extensions">The collection of extensions.</param>
        /// <param name="onlyCreatedValues">
        /// <c>true</c> to only enumerate extensions from Lazy's that have previously been created.
        /// This is useful in Dispose methods to avoid MEF ObjectDisposedExceptions from accidentally
        /// creating values during a container disposal.
        /// </param>
        /// <returns>The safely constructed sequence of extensions.</returns>
        internal static IEnumerable <T> ExtensionValues <T>(this IEnumerable <Lazy <T> > extensions, bool onlyCreatedValues = false)
        {
            Requires.NotNull(extensions, nameof(extensions));
            var traceErrorMessage = "Roslyn project system extension rejected due to exception: {0}";

            foreach (var extension in extensions)
            {
                T value;
                try
                {
                    if (onlyCreatedValues && !extension.IsValueCreated)
                    {
                        continue;
                    }

                    value = extension.Value;
                }
                catch (CompositionContractMismatchException ex)
                {
                    TraceUtilities.TraceError(traceErrorMessage, ex);
                    continue;
                }
                catch (CompositionException ex)
                {
                    TraceUtilities.TraceError(traceErrorMessage, ex);
                    continue;
                }

                yield return(value);
            }
        }
        /// <summary>
        /// Gets an IRule to attach to a project item so that browse object properties will be displayed.
        /// </summary>
        private IRule GetRuleForUnresolvableReference(IProjectPropertiesContext unresolvedContext,
                                                      IProjectCatalogSnapshot catalogs,
                                                      ConfiguredProjectExports configuredProjectExports)
        {
            Requires.NotNull(unresolvedContext, nameof(unresolvedContext));
            Requires.NotNull(configuredProjectExports, nameof(configuredProjectExports));

            var namedCatalogs = GetNamedCatalogs(catalogs);
            var schemas       = GetSchemaForReference(unresolvedContext.ItemType, false, namedCatalogs).ToList();

            if (schemas.Count == 1)
            {
                Requires.NotNull(namedCatalogs, nameof(namedCatalogs));
                var browseObjectCatalog = namedCatalogs[PropertyPageContexts.BrowseObject];
                return(browseObjectCatalog.BindToContext(schemas[0].Name, unresolvedContext));
            }

            if (schemas.Count > 1)
            {
                TraceUtilities.TraceWarning(
                    "Too many rule schemas ({0}) in the BrowseObject context were found. Only 1 is allowed.",
                    schemas.Count);
            }

            // Since we have no browse object, we still need to create *something* so that standard property
            // pages can pop up.
            var emptyRule = RuleExtensions.SynthesizeEmptyRule(unresolvedContext.ItemType);

            return(configuredProjectExports.PropertyPagesDataModelProvider.GetRule(
                       emptyRule,
                       unresolvedContext.File,
                       unresolvedContext.ItemType,
                       unresolvedContext.ItemName));
        }
Exemplo n.º 9
0
        public Task <ActionResult> CaptureTrace(
            [FromQuery]
            int?pid = null,
            [FromQuery]
            Guid?uid = null,
            [FromQuery]
            string name = null,
            [FromQuery]
            Models.TraceProfile profile = DefaultTraceProfiles,
            [FromQuery][Range(-1, int.MaxValue)]
            int durationSeconds = 30,
            [FromQuery]
            string egressProvider = null)
        {
            ProcessKey?processKey = GetProcessKey(pid, uid, name);

            return(InvokeForProcess(processInfo =>
            {
                TimeSpan duration = Utilities.ConvertSecondsToTimeSpan(durationSeconds);

                var aggregateConfiguration = TraceUtilities.GetTraceConfiguration(profile, _counterOptions.CurrentValue.GetIntervalSeconds());

                return StartTrace(processInfo, aggregateConfiguration, duration, egressProvider);
            }, processKey, Utilities.ArtifactType_Trace));
        }
Exemplo n.º 10
0
 /// <summary>
 /// Handles the logging of asynchronous unary calls.
 /// </summary>
 /// <typeparam name="TRequest">The type of the request.</typeparam>
 /// <typeparam name="TResponse">The type of the response.</typeparam>
 /// <param name="request">The request.</param>
 /// <param name="context">The context.</param>
 /// <param name="oldTask">The old task.</param>
 /// <param name="call">The call.</param>
 internal void HandleAsyncUnaryLogging <TRequest, TResponse>(TRequest request,
                                                             ClientInterceptorContext <TRequest, TResponse> context,
                                                             Task <TResponse> oldTask, AsyncUnaryCall <TResponse> call)
     where TRequest : class
     where TResponse : class
 {
     // Generating log entry is expensive, so let's do that only if the log source
     // has been configured to do so.
     if (TraceUtilities.ShouldGenerateRequestLogs())
     {
         LogEntry logEntry = new LogEntry()
         {
             Host            = config.ServerUrl,
             Method          = context.Method.FullName,
             RequestHeaders  = context.Options.Headers,
             Request         = request,
             ResponseHeaders = Merge(GetResponseHeader(call.ResponseHeadersAsync),
                                     call.GetTrailers()),
             Response                                     = (oldTask.IsFaulted) ? default : oldTask.Result,
                                          Exception       = UnaryRpcInterceptor.ParseTaskException(oldTask.Exception),
                                          IsFailure       = oldTask.IsFaulted,
                                          CustomerId      = GetCustomerId(request),
                                          PartialFailures = (oldTask.IsFaulted) ? "" :
                                                            GetPartialFailures(oldTask.Result)
         };
         WriteLogs(logEntry);
     }
 }
Exemplo n.º 11
0
 public void TestWriteSummaryRequestLogsSuccess()
 {
     VerifyLog(TraceUtilities.SUMMARY_REQUEST_LOGS_SOURCE, delegate()
     {
         // Ensure success summaries are logged at the info level.
         TraceUtilities.WriteSummaryRequestLogs(TEST_LOG_MESSAGE, false);
     }, INFO_MARKER);
 }
Exemplo n.º 12
0
 public void TestWriteSummaryRequestLogsFailure()
 {
     VerifyLog(TraceUtilities.SUMMARY_REQUEST_LOGS_SOURCE, delegate()
     {
         // Ensure failure summaries are logged at the warning level.
         TraceUtilities.WriteSummaryRequestLogs(TEST_LOG_MESSAGE, true);
     }, WARNING_MARKER);
 }
Exemplo n.º 13
0
 public void TestWriteDetailedRequestLogsSuccess()
 {
     VerifyLog(TraceUtilities.DETAILED_REQUEST_LOGS_SOURCE, delegate()
     {
         // Ensure success details are logged at the verbose level.
         TraceUtilities.WriteDetailedRequestLogs(TEST_LOG_MESSAGE, false);
     }, VERBOSE_MARKER);
 }
Exemplo n.º 14
0
 public void WriteDeprecationWarnings()
 {
     VerifyLog(TraceUtilities.DEPRECATION_MESSAGES_SOURCE, delegate()
     {
         // Ensure deprecation warnings are logged at the warning level.
         TraceUtilities.WriteDeprecationWarnings(TEST_LOG_MESSAGE);
     }, WARNING_MARKER);
 }
Exemplo n.º 15
0
 public void WriteGeneralErrors()
 {
     VerifyLog(TraceUtilities.GENERAL_WARNING_MESSAGES_SOURCE, delegate()
     {
         // Ensure general errors are logged at the error level.
         TraceUtilities.WriteGeneralErrors(TEST_LOG_MESSAGE);
     }, ERROR_MARKER);
 }
Exemplo n.º 16
0
 public void WriteGeneralWarnings()
 {
     VerifyLog(TraceUtilities.GENERAL_WARNING_MESSAGES_SOURCE, delegate()
     {
         // Ensure general warnings are logged at the warning level.
         TraceUtilities.WriteGeneralWarnings(TEST_LOG_MESSAGE);
     }, WARNING_MARKER);
 }
Exemplo n.º 17
0
 public void TestWriteDetailedRequestLogsFailure()
 {
     VerifyLog(TraceUtilities.DETAILED_REQUEST_LOGS_SOURCE, delegate()
     {
         // Ensure failure details are logged at the warning level.
         TraceUtilities.WriteDetailedRequestLogs(TEST_LOG_MESSAGE, true);
     }, INFO_MARKER);
 }
Exemplo n.º 18
0
        /// <summary>
        /// The main method.
        /// </summary>
        /// <param name="args">The command line arguments.</param>
        public static void Main(string[] args)
        {
            // Turn on logging. This is useful for debugging your requests.
            TraceUtilities.Configure(TraceUtilities.DETAILED_REQUEST_LOGS_SOURCE,
                                     "C:\\logs\\details.log", System.Diagnostics.SourceLevels.All);

            // If the API log doesn't give you enough details, then you can enable more low level
            // logging at grpc level. Keep in mind that this can get pretty detailed and long. The
            // grpc logs are written to stderr.
            // You can find all the supported environment variables here:
            // https://github.com/grpc/grpc/blob/master/doc/environment_variables.md
            // Environment.SetEnvironmentVariable("GRPC_VERBOSITY", "DEBUG");
            // Environment.SetEnvironmentVariable("GRPC_TRACE", "http");

            // If you simply want to try out a code example, you can create an instance of it here,
            // and call it's Run method. E.g.

            // Optional: If you have specified these keys in the App.config file, you can skip
            // creating a GoogleAdsConfig object and do
            // GoogleAdsClient googleAdsClient = new GoogleAdsClient();

            // string developerToken = "INSERT_YOUR_DEVELOPER_TOKEN_HERE";
            // string oAuth2clientId = "INSERT_OAUTH2_CLIENT_ID_HERE";
            // string oAuth2Secret = "INSERT_OAUTH2_CLIENT_SECRET_HERE";
            // string oAuth2RefreshToken = "INSERT_OAUTH2_REFRESH_TOKEN_HERE";
            // long loginCustomerId = long.Parse("INSERT_LOGIN_CUSTOMER_ID_HERE");

            // GoogleAdsConfig googleAdsConfig = new GoogleAdsConfig()
            // {
            //     DeveloperToken = developerToken,
            //     LoginCustomerId = loginCustomerId.ToString(),
            //     OAuth2ClientId = oAuth2clientId,
            //     OAuth2ClientSecret = oAuth2Secret,
            //     OAuth2RefreshToken = oAuth2RefreshToken,
            // };

            //GoogleAdsClient googleAdsClient = new GoogleAdsClient(googleAdsConfig);

            // Run the code example.
            //new V1.GetCampaigns().Run(new GoogleAdsClient(), 1234567890);

            // Alternatively, you can pass command line arguments to run the code example. E.g.
            // V1.GetCampaigns --customerId=1234567890
            // The first argument has the form VersionName.ExampleName, e.g. V1.GetCampaigns to run
            // Google.Ads.GoogleAds.Examples.V1.GetCampaigns example.
            // The subsequent arguments can be inferred by looking at the Run method of the code
            // example and skipping the first parameter.
            // E.g. GetCampaigns.cs has a Run method is defined as
            //
            //     public void Run(GoogleAdsClient client, long customerId)
            //
            // So, this example can be run with the command line arguments
            //
            //     V1.GetCampaigns --customerId=1234567890
            RunExamplesFromCommandLineArguments(args);
        }
Exemplo n.º 19
0
        public void TestWriteDetailedRequestLogsFailure()
        {
            using (var stream = new MemoryStream()) {
                enableLoggingToMemoryStream(TraceUtilities.DETAILED_REQUEST_LOGS_SOURCE, stream);

                // Ensure failure details are logged at the warning level.
                TraceUtilities.WriteDetailedRequestLogs(TEST_LOG_MESSAGE, true);
                StringAssert.Contains(INFO_MARKER, getLogFromMemoryStream(stream));
            }
        }
Exemplo n.º 20
0
        public void WriteDeprecationWarnings()
        {
            using (var stream = new MemoryStream()) {
                enableLoggingToMemoryStream(TraceUtilities.DEPRECATION_MESSAGES_SOURCE, stream);

                // Ensure deprecation warnings are logged at the warning level.
                TraceUtilities.WriteDeprecationWarnings(TEST_LOG_MESSAGE);
                StringAssert.Contains(WARNING_MARKER, getLogFromMemoryStream(stream));
            }
        }
Exemplo n.º 21
0
        public void TestWriteDetailedRequestLogsSuccess()
        {
            using (var stream = new MemoryStream()) {
                enableLoggingToMemoryStream(TraceUtilities.DETAILED_REQUEST_LOGS_SOURCE, stream);

                // Ensure success details are logged at the verbose level.
                TraceUtilities.WriteDetailedRequestLogs(TEST_LOG_MESSAGE, false);
                StringAssert.Contains(VERBOSE_MARKER, getLogFromMemoryStream(stream));
            }
        }
Exemplo n.º 22
0
        public void WriteGeneralErrors()
        {
            using (var stream = new MemoryStream()) {
                enableLoggingToMemoryStream(TraceUtilities.GENERAL_WARNING_MESSAGES_SOURCE, stream);

                // Ensure general errors are logged at the error level.
                TraceUtilities.WriteGeneralErrors(TEST_LOG_MESSAGE);
                StringAssert.Contains(ERROR_MARKER, getLogFromMemoryStream(stream));
            }
        }
Exemplo n.º 23
0
        public void TestWriteSummaryRequestLogsSuccess()
        {
            using (var stream = new MemoryStream()) {
                enableLoggingToMemoryStream(TraceUtilities.SUMMARY_REQUEST_LOGS_SOURCE, stream);

                // Ensure success summaries are logged at the info level.
                TraceUtilities.WriteSummaryRequestLogs(TEST_LOG_MESSAGE, false);
                StringAssert.Contains(INFO_MARKER, getLogFromMemoryStream(stream));
            }
        }
Exemplo n.º 24
0
        private void enableLoggingToMemoryStream(string logSourceName, MemoryStream stream)
        {
            TraceSource source = TraceUtilities.GetSource(logSourceName);

            source.Switch.Level = SourceLevels.All;
            source.Listeners.Add(new TextWriterTraceListener(stream)
            {
                Filter = new EventTypeFilter(SourceLevels.All)
            });
        }
Exemplo n.º 25
0
        public void TestWriteSummaryRequestLogsFailure()
        {
            using (var stream = new MemoryStream()) {
                enableLoggingToMemoryStream(TraceUtilities.SUMMARY_REQUEST_LOGS_SOURCE, stream);

                // Ensure failure summaries are logged at the warning level.
                TraceUtilities.WriteSummaryRequestLogs(TEST_LOG_MESSAGE, true);
                StringAssert.Contains(WARNING_MARKER, getLogFromMemoryStream(stream));
            }
        }
Exemplo n.º 26
0
            protected override async Task <CollectionRuleActionResult> ExecuteCoreAsync(
                TaskCompletionSource <object> startCompletionSource,
                CancellationToken token)
            {
                TimeSpan duration       = Options.Duration.GetValueOrDefault(TimeSpan.Parse(CollectTraceOptionsDefaults.Duration));
                string   egressProvider = Options.Egress;

                MonitoringSourceConfiguration configuration;

                if (Options.Profile.HasValue)
                {
                    TraceProfile profile = Options.Profile.Value;
                    float        metricsIntervalSeconds = _counterOptions.CurrentValue.GetIntervalSeconds();

                    configuration = TraceUtilities.GetTraceConfiguration(profile, metricsIntervalSeconds);
                }
                else
                {
                    EventPipeProvider[] optionsProviders = Options.Providers.ToArray();
                    bool requestRundown      = Options.RequestRundown.GetValueOrDefault(CollectTraceOptionsDefaults.RequestRundown);
                    int  bufferSizeMegabytes = Options.BufferSizeMegabytes.GetValueOrDefault(CollectTraceOptionsDefaults.BufferSizeMegabytes);

                    configuration = TraceUtilities.GetTraceConfiguration(optionsProviders, requestRundown, bufferSizeMegabytes);
                }

                string fileName = TraceUtilities.GenerateTraceFileName(EndpointInfo);

                KeyValueLogScope scope = Utils.CreateArtifactScope(Utils.ArtifactType_Trace, EndpointInfo);

                EgressOperation egressOperation = new EgressOperation(
                    async(outputStream, token) =>
                {
                    using IDisposable operationRegistration = _operationTrackerService.Register(EndpointInfo);
                    await TraceUtilities.CaptureTraceAsync(startCompletionSource, EndpointInfo, configuration, duration, outputStream, token);
                },
                    egressProvider,
                    fileName,
                    EndpointInfo,
                    ContentTypes.ApplicationOctetStream,
                    scope);

                ExecutionResult <EgressResult> result = await egressOperation.ExecuteAsync(_serviceProvider, token);

                string traceFilePath = result.Result.Value;

                return(new CollectionRuleActionResult()
                {
                    OutputValues = new Dictionary <string, string>(StringComparer.Ordinal)
                    {
                        { CollectionRuleActionConstants.EgressPathOutputValueName, traceFilePath }
                    }
                });
            }
Exemplo n.º 27
0
        /// <summary>
        /// Initializes the service before MakeApiCall.
        /// </summary>
        /// <param name="methodName">Name of the method.</param>
        /// <param name="parameters">The method parameters.</param>
        protected override void InitForCall(string methodName, object[] parameters)
        {
            AdWordsAppConfig config = this.User.Config as AdWordsAppConfig;
            RequestHeader    header = GetRequestHeader();

            if (string.IsNullOrEmpty(header.developerToken))
            {
                throw new ArgumentNullException(AdWordsErrorMessages.DeveloperTokenCannotBeEmpty);
            }

            if (string.IsNullOrEmpty(header.clientCustomerId))
            {
                TraceUtilities.WriteGeneralWarnings(AdWordsErrorMessages.ClientCustomerIdIsEmpty);
            }

            // Validate Express business headers.
            if (this.Signature.ServiceName == "PromotionService")
            {
                if (header.expressBusinessIdSpecified && header.pageIdSpecified)
                {
                    throw new ArgumentException(AdWordsErrorMessages.OnlyOneExpressHeaderShouldBeSpecified);
                }
                else if (!header.expressBusinessIdSpecified && !header.pageIdSpecified)
                {
                    throw new ArgumentException(AdWordsErrorMessages.MissingExpressHeaders + ' ' +
                                                AdWordsErrorMessages.OnlyOneExpressHeaderShouldBeSpecified);
                }
            }
            else
            {
                if (header.expressBusinessIdSpecified || header.pageIdSpecified)
                {
                    throw new ArgumentException(AdWordsErrorMessages.ExpressHeadersShouldNotBeSpecified);
                }
            }

            header.userAgent = config.GetUserAgent();

            string oAuthHeader = null;

            if (this.User.OAuthProvider != null)
            {
                oAuthHeader = this.User.OAuthProvider.GetAuthHeader();
            }
            else
            {
                throw new AdWordsApiException(null, AdWordsErrorMessages.OAuthProviderCannotBeNull);
            }
            ContextStore.AddKey("OAuthHeader", oAuthHeader);
            base.InitForCall(methodName, parameters);
        }
Exemplo n.º 28
0
        /// <summary>
        /// Verifies that the text logged by <paramref name="loggingAction"/> contains
        /// <paramref name="markerToVerify"/> text.
        /// </summary>
        /// <param name="logSource">The log source.</param>
        /// <param name="loggingAction">The logging action.</param>
        /// <param name="markerToVerify">The marker to verify.</param>
        private void VerifyLog(string logSource, Action loggingAction, string markerToVerify)
        {
            using (var stream = new MemoryStream())
            {
                TraceUtilities.Configure(logSource, new StreamWriter(stream), SourceLevels.All);

                loggingAction();
                // Ensure failure summaries are logged at the warning level.
                TraceUtilities.WriteSummaryRequestLogs(TEST_LOG_MESSAGE, true);

                string logFromMemStream = Encoding.UTF8.GetString(stream.ToArray());
                StringAssert.Contains(markerToVerify, logFromMemStream);
            }
        }
Exemplo n.º 29
0
        /// <summary>
        /// Initializes a new instance of the <see cref="LoggingInterceptorTests"/> class.
        /// </summary>
        public LoggingInterceptorTests() : base(new GoogleAdsConfig())
        {
            // Initialize request metadata.
            TEST_REQUEST_METADATA = new Metadata();
            TEST_REQUEST_METADATA.Add(GoogleAdsConfig.DEVELOPER_TOKEN_KEYNAME,
                                      TEST_DEVELOPER_TOKEN);

            // Initialize response metadata.
            TEST_RESPONSE_METADATA = new Metadata();
            TEST_RESPONSE_METADATA.Add(GoogleAdsException.REQUEST_ID_KEY, TEST_REQUEST_ID);

            // Create the test exception.
            TEST_EXCEPTION = TestUtils.CreateRpcException(TEST_ERROR_MESSAGE, TEST_ERROR_TRIGGER,
                                                          TEST_REQUEST_ID);
            TraceUtilities.Configure(TraceUtilities.DETAILED_REQUEST_LOGS_SOURCE,
                                     new StringWriter(), SourceLevels.All);
        }
 /// <summary>
 /// Gets the message body as a string.
 /// </summary>
 /// <returns>The message body.</returns>
 /// <param name="message">Message.</param>
 private string GetMessageBody(ref Message message)
 {
     using (MessageBuffer buffer = message.CreateBufferedCopy(Int32.MaxValue)) {
         // Message can only be read once, so replace it with a copy.
         message = buffer.CreateMessage();
         StringBuilder sb = new StringBuilder();
         try {
             using (XmlWriter xmlWriter = XmlWriter.Create(sb, xmlWriterSettings)) {
                 buffer.CreateMessage().WriteMessage(xmlWriter);
             }
             return(sb.ToString());
         } catch (Exception e) {
             TraceUtilities.WriteGeneralWarnings(string.Format(CommonErrorMessages.MalformedSoap, e));
             return("<soap />");
         }
     }
 }