public static MediaTypeFormatter CreateTracer(MediaTypeFormatter formatter, ITraceWriter traceWriter, HttpRequestMessage request) { // If we have been asked to wrap a tracer around a formatter, it could be // already wrapped, and there is nothing to do. But if we see it is a tracer // that is not associated with a request, we wrap it into a new tracer that // does have a request. The only formatter tracers without requests are the // ones in the default MediaTypeFormatterCollection in the HttpConfiguration. IFormatterTracer formatterTracer = formatter as IFormatterTracer; if (formatterTracer != null) { if (formatterTracer.Request == request) { return formatter; } formatter = formatterTracer.InnerFormatter; } MediaTypeFormatter tracer = null; // We special-case Xml, Json and FormUrlEncoded formatters because we expect to be able // to find them with IsAssignableFrom in the MediaTypeFormatterCollection. if (formatter is XmlMediaTypeFormatter) { tracer = new XmlMediaTypeFormatterTracer(formatter, traceWriter, request); } else if (formatter is JsonMediaTypeFormatter) { tracer = new JsonMediaTypeFormatterTracer(formatter, traceWriter, request); } else if (formatter is FormUrlEncodedMediaTypeFormatter) { tracer = new FormUrlEncodedMediaTypeFormatterTracer(formatter, traceWriter, request); } else if (formatter is BufferedMediaTypeFormatter) { tracer = new BufferedMediaTypeFormatterTracer(formatter, traceWriter, request); } else { tracer = new MediaTypeFormatterTracer(formatter, traceWriter, request); } // Copy SupportedMediaTypes and MediaTypeMappings because they are publically visible tracer.SupportedMediaTypes.Clear(); foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { tracer.SupportedMediaTypes.Add(mediaType); } tracer.MediaTypeMappings.Clear(); foreach (MediaTypeMapping mapping in formatter.MediaTypeMappings) { tracer.MediaTypeMappings.Add(mapping); } return tracer; }
public GlimpseTraceWriter(IMessageBroker messageBroker, Func<IExecutionTimer> timerStrategy, ITraceWriter innerTraceWriter) { _messageBroker = messageBroker; _timerStrategy = timerStrategy; _innerTraceWriter = innerTraceWriter; _traceMessages = new List<JsonTraceMessage>(); }
/// <summary> /// Initializes the debug component /// </summary> /// <param name="performanceMonitorConfig">Component that contains the list of performance counters and default performance counter</param> public Debug(IDictionary<string, ITraceWriter> traceConfiguration, ITraceWriter defaultWriter) { this.traceCollection = traceConfiguration; this.defaultTrace = defaultWriter; this.Register(this.traceCollection.Values); this.Register(this.defaultTrace); }
public CorsPolicyProviderFactoryTracer(ICorsPolicyProviderFactory innerPolicyProviderFactory, ITraceWriter traceWriter) { Contract.Assert(innerPolicyProviderFactory != null); Contract.Assert(traceWriter != null); _innerPolicyProviderFactory = innerPolicyProviderFactory; _traceWriter = traceWriter; }
public FormatterParameterBindingTracer(FormatterParameterBinding innerBinding, ITraceWriter traceWriter) : base(innerBinding.Descriptor, innerBinding.Formatters, innerBinding.BodyModelValidator) { Contract.Assert(innerBinding != null); Contract.Assert(traceWriter != null); _innerBinding = innerBinding; _traceWriter = traceWriter; }
public ActionFilterAttributeTracer(ActionFilterAttribute innerFilter, ITraceWriter traceWriter) { Contract.Assert(innerFilter != null); Contract.Assert(traceWriter != null); _innerFilter = innerFilter; _traceWriter = traceWriter; }
public MessageHandlerTracer(DelegatingHandler innerHandler, ITraceWriter traceWriter) { Contract.Assert(innerHandler != null); Contract.Assert(traceWriter != null); _innerHandler = innerHandler; _traceWriter = traceWriter; }
public BufferedMediaTypeFormatterTracer(BufferedMediaTypeFormatter innerFormatter, ITraceWriter traceWriter, HttpRequestMessage request) { _innerTracer = new MediaTypeFormatterTracer(innerFormatter, traceWriter, request); // copy non-overridable members from inner formatter _innerTracer.CopyNonOverriableMembersFromInner(this); BufferSize = innerFormatter.BufferSize; }
public HttpParameterBindingTracer(HttpParameterBinding innerBinding, ITraceWriter traceWriter) : base(innerBinding.Descriptor) { Contract.Assert(innerBinding != null); Contract.Assert(traceWriter != null); InnerBinding = innerBinding; TraceWriter = traceWriter; }
public FilterTracer(IFilter innerFilter, ITraceWriter traceWriter) { Contract.Assert(innerFilter != null); Contract.Assert(traceWriter != null); InnerFilter = innerFilter; TraceWriter = traceWriter; }
public HttpControllerSelectorTracer(IHttpControllerSelector innerSelector, ITraceWriter traceWriter) { Contract.Assert(innerSelector != null); Contract.Assert(traceWriter != null); _innerSelector = innerSelector; _traceWriter = traceWriter; }
public AuthorizationFilterAttributeTracer(AuthorizationFilterAttribute innerFilter, ITraceWriter traceWriter) { Contract.Assert(innerFilter != null); Contract.Assert(traceWriter != null); _innerFilter = innerFilter; _traceStore = traceWriter; }
public ContentNegotiatorTracer(IContentNegotiator innerNegotiator, ITraceWriter traceWriter) { Contract.Assert(innerNegotiator != null); Contract.Assert(traceWriter != null); _innerNegotiator = innerNegotiator; _traceWriter = traceWriter; }
public HttpActionInvokerTracer(IHttpActionInvoker innerInvoker, ITraceWriter traceWriter) { Contract.Assert(innerInvoker != null); Contract.Assert(traceWriter != null); _innerInvoker = innerInvoker; _traceWriter = traceWriter; }
public CorsPolicyProviderTracer(ICorsPolicyProvider innerPolicyProvider, ITraceWriter traceWriter) { Contract.Assert(innerPolicyProvider != null); Contract.Assert(traceWriter != null); _innerPolicyProvider = innerPolicyProvider; _traceWriter = traceWriter; }
public CorsEngineTracer(ICorsEngine corsEngine, ITraceWriter traceWriter) { Contract.Assert(corsEngine != null); Contract.Assert(traceWriter != null); _innerCorsEngine = corsEngine; _traceWriter = traceWriter; }
public ActionValueBinderTracer(IActionValueBinder innerBinder, ITraceWriter traceWriter) { Contract.Assert(innerBinder != null); Contract.Assert(traceWriter != null); _innerBinder = innerBinder; _traceWriter = traceWriter; }
private static HttpControllerDescriptorTracer GetHttpControllerDescriptorTracer(HttpControllerDescriptor controllerDescriptor, ITraceWriter traceWriter) { return new HttpControllerDescriptorTracer( configuration: new HttpConfiguration(), controllerName: "AnyController", controllerType: _controller.GetType(), innerDescriptor: controllerDescriptor, traceWriter: traceWriter); }
public TraceWriterExtensionsTests() { this.category = "TestCategory"; this.message = "TestMessage"; this.exception = new Exception("Catch this!"); this.request = new HttpRequestMessage(); this.tracerMock = new Mock<ITraceWriter>(); this.tracer = this.tracerMock.Object; }
public FormUrlEncodedMediaTypeFormatterTracer(FormUrlEncodedMediaTypeFormatter innerFormatter, ITraceWriter traceWriter, HttpRequestMessage request) { _innerTracer = new MediaTypeFormatterTracer(innerFormatter, traceWriter, request); // copy non-overridable members from inner formatter _innerTracer.CopyNonOverriableMembersFromInner(this); MaxDepth = innerFormatter.MaxDepth; ReadBufferSize = innerFormatter.ReadBufferSize; }
public HttpControllerTracer(HttpRequestMessage request, IHttpController innerController, ITraceWriter traceWriter) { Contract.Assert(innerController != null); Contract.Assert(traceWriter != null); _innerController = innerController; _request = request; _traceWriter = traceWriter; }
public static IEnumerable<IFilter> CreateFilterTracers(IFilter filter, ITraceWriter traceWriter) { List<IFilter> filters = new List<IFilter>(); bool addedActionAttributeTracer = false; bool addedAuthorizationAttributeTracer = false; bool addedExceptionAttributeTracer = false; ActionFilterAttribute actionFilterAttribute = filter as ActionFilterAttribute; if (actionFilterAttribute != null) { filters.Add(new ActionFilterAttributeTracer(actionFilterAttribute, traceWriter)); addedActionAttributeTracer = true; } AuthorizationFilterAttribute authorizationFilterAttribute = filter as AuthorizationFilterAttribute; if (authorizationFilterAttribute != null) { filters.Add(new AuthorizationFilterAttributeTracer(authorizationFilterAttribute, traceWriter)); addedAuthorizationAttributeTracer = true; } ExceptionFilterAttribute exceptionFilterAttribute = filter as ExceptionFilterAttribute; if (exceptionFilterAttribute != null) { filters.Add(new ExceptionFilterAttributeTracer(exceptionFilterAttribute, traceWriter)); addedExceptionAttributeTracer = true; } // Do not add an IActionFilter tracer if we already added an ActionFilterAttribute tracer IActionFilter actionFilter = filter as IActionFilter; if (actionFilter != null && !addedActionAttributeTracer) { filters.Add(new ActionFilterTracer(actionFilter, traceWriter)); } // Do not add an IAuthorizationFilter tracer if we already added an AuthorizationFilterAttribute tracer IAuthorizationFilter authorizationFilter = filter as IAuthorizationFilter; if (authorizationFilter != null && !addedAuthorizationAttributeTracer) { filters.Add(new AuthorizationFilterTracer(authorizationFilter, traceWriter)); } // Do not add an IExceptionFilter tracer if we already added an ExceptoinFilterAttribute tracer IExceptionFilter exceptionFilter = filter as IExceptionFilter; if (exceptionFilter != null && !addedExceptionAttributeTracer) { filters.Add(new ExceptionFilterTracer(exceptionFilter, traceWriter)); } if (filters.Count == 0) { filters.Add(new FilterTracer(filter, traceWriter)); } return filters; }
public XmlMediaTypeFormatterTracer(XmlMediaTypeFormatter innerFormatter, ITraceWriter traceWriter, HttpRequestMessage request) { _innerTracer = new MediaTypeFormatterTracer(innerFormatter, traceWriter, request); // copy values we cannot override _innerTracer.CopyNonOverriableMembersFromInner(this); UseXmlSerializer = innerFormatter.UseXmlSerializer; Indent = innerFormatter.Indent; MaxDepth = innerFormatter.MaxDepth; }
private TalentsManager() { _traceWriter = new MemoryTraceWriter(); _serializerSettings = new JsonSerializerSettings() { Error = (sender, args) => Console.Write(args.ErrorContext.Error), Formatting = Formatting.Indented, TraceWriter = _traceWriter }; }
private static void CreateMediaTypeFormatterTracers(HttpConfiguration configuration, ITraceWriter traceWriter) { for (int i = 0; i < configuration.Formatters.Count; i++) { configuration.Formatters[i] = MediaTypeFormatterTracer.CreateTracer( configuration.Formatters[i], traceWriter, request: null); } }
private static void CreateAllTracers(HttpConfiguration configuration, ITraceWriter traceWriter) { CreateActionInvokerTracer(configuration, traceWriter); CreateActionSelectorTracer(configuration, traceWriter); CreateActionValueBinderTracer(configuration, traceWriter); CreateContentNegotiatorTracer(configuration, traceWriter); CreateControllerActivatorTracer(configuration, traceWriter); CreateControllerFactoryTracer(configuration, traceWriter); CreateMessageHandlerTracers(configuration, traceWriter); CreateMediaTypeFormatterTracers(configuration, traceWriter); }
private RacesManager() { _traceWriter = new MemoryTraceWriter(); _serializerSettings = new JsonSerializerSettings() { Error = (sender, args) => Log.Logger.Write(args.ErrorContext.Error.Message), Formatting = Formatting.Indented, TraceWriter = _traceWriter, MissingMemberHandling = MissingMemberHandling.Error, }; }
public JsonMediaTypeFormatterTracer(JsonMediaTypeFormatter innerFormatter, ITraceWriter traceWriter, HttpRequestMessage request) { _innerTracer = new MediaTypeFormatterTracer(innerFormatter, traceWriter, request); // copy values we cannot override _innerTracer.CopyNonOverriableMembersFromInner(this); MaxDepth = innerFormatter.MaxDepth; Indent = innerFormatter.Indent; UseDataContractJsonSerializer = innerFormatter.UseDataContractJsonSerializer; SerializerSettings = innerFormatter.SerializerSettings; }
public static IEnumerable<FilterInfo> CreateFilterTracers(FilterInfo filter, ITraceWriter traceWriter) { IFilter filterInstance = filter.Instance; IEnumerable<IFilter> filterTracers = CreateFilterTracers(filterInstance, traceWriter); List<FilterInfo> filters = new List<FilterInfo>(); foreach (IFilter filterTracer in filterTracers) { filters.Add(new FilterInfo(filterTracer, filter.Scope)); } return filters; }
public MediaTypeFormatterTracer(MediaTypeFormatter innerFormatter, ITraceWriter traceWriter, HttpRequestMessage request) { Contract.Assert(innerFormatter != null); Contract.Assert(traceWriter != null); InnerFormatter = innerFormatter; TraceWriter = traceWriter; Request = request; // copy all non-overridable members from inner formatter CopyNonOverriableMembersFromInner(this); }
/// <summary> /// Creates a new instance of the HttpTransportListener class. /// </summary> /// <param name="port">The port for listening.</param> /// <param name="hostName">Name of the host for binding.</param> /// <param name="useHttps">if set to <c>true</c> the listener endpoint will use HTTPS.</param> /// <param name="requestTimeout">The request timeout.</param> /// <param name="writeExceptionsToOutput">if set to <c>true</c> the exceptions details will be written in the response body.</param> /// <param name="httpServer">The HTTP server instance.</param> /// <param name="httpTransportProvider">The HTTP transport provider instance.</param> /// <param name="serializer">The serializer instance.</param> /// <param name="messageStorage">The message storage instance.</param> /// <param name="notificationStorage">The notification storage instance.</param> /// <param name="processors">The processors.</param> /// <param name="traceWriter">The trace writer.</param> public HttpTransportListener(int port, string hostName = "*", bool useHttps = false, TimeSpan requestTimeout = default(TimeSpan), TimeSpan transportExpirationInactivityInterval = default(TimeSpan), bool writeExceptionsToOutput = true, int maxDegreeOfParallelism = 1, IHttpServer httpServer = null, IHttpTransportProvider httpTransportProvider = null, IDocumentSerializer serializer = null, IEnvelopeStorage <Message> messageStorage = null, IEnvelopeStorage <Notification> notificationStorage = null, IHttpProcessor[] processors = null, ITraceWriter traceWriter = null) { _useHttps = useHttps; var scheme = _useHttps ? Uri.UriSchemeHttps : Uri.UriSchemeHttp; _writeExceptionsToOutput = writeExceptionsToOutput; _maxDegreeOfParallelism = maxDegreeOfParallelism; _requestTimeout = requestTimeout != default(TimeSpan) ? requestTimeout : TimeSpan.FromSeconds(Constants.DEFAULT_REQUEST_TIMEOUT); var basePath = string.Format("{0}://{1}:{2}", scheme, hostName, port); var prefixes = new string[] { Constants.ROOT + Constants.MESSAGES_PATH + Constants.ROOT, Constants.ROOT + Constants.COMMANDS_PATH + Constants.ROOT, Constants.ROOT + Constants.NOTIFICATIONS_PATH + Constants.ROOT }; var fullPrefixes = prefixes.Select(p => basePath + p).ToArray(); var safeHostName = hostName; if (hostName.Equals("*") || hostName.Equals("+")) { safeHostName = "localhost"; } var baseUri = new Uri(string.Format("{0}://{1}:{2}", scheme, safeHostName, port)); ListenerUris = prefixes .Select(p => new Uri(baseUri, p)) .ToArray(); _httpServer = httpServer ?? new HttpServer(fullPrefixes, AuthenticationSchemes.Basic); _serializer = serializer ?? new DocumentSerializer(); _messageStorage = messageStorage ?? new DictionaryEnvelopeStorage <Message>(); _notificationStorage = notificationStorage ?? new DictionaryEnvelopeStorage <Notification>(); _traceWriter = traceWriter; transportExpirationInactivityInterval = transportExpirationInactivityInterval != default(TimeSpan) ? transportExpirationInactivityInterval : TimeSpan.FromSeconds(Constants.DEFAULT_TRANSPORT_EXPIRATION_INACTIVITY_INTERVAL); _httpTransportProvider = httpTransportProvider ?? new HttpTransportProvider(_useHttps, _messageStorage, _notificationStorage, transportExpirationInactivityInterval); _httpTransportProvider.TransportCreated += async(sender, e) => await _transportBufferBlock.SendAsync(e.Transport, _listenerCancellationTokenSource.Token).ConfigureAwait(false); // Context processors _uriTemplateTable = new UriTemplateTable(baseUri); if (processors == null) { processors = CreateProcessors(); } foreach (var processor in processors) { _uriTemplateTable.KeyValuePairs.Add(new KeyValuePair <UriTemplate, object>(processor.Template, processor)); } _uriTemplateTable.MakeReadOnly(true); }
public HttpControllerDescriptorTracer(HttpConfiguration configuration, string controllerName, Type controllerType, HttpControllerDescriptor innerDescriptor, ITraceWriter traceWriter) : base(configuration, controllerName, controllerType) { _innerDescriptor = innerDescriptor; _traceWriter = traceWriter; }
public DemoController() { _tracer = Request.GetConfiguration().Services.GetTraceWriter(); }
public HttpActionBindingTracer(HttpActionBinding innerBinding, ITraceWriter traceWriter) { _innerBinding = innerBinding; _traceWriter = traceWriter; }
public static Task TraceBeginEndAsync(this ITraceWriter traceWriter, HttpRequestMessage request, string category, TraceLevel level, string operatorName, string operationName, Action <TraceRecord> beginTrace, Func <Task> execute, Action <TraceRecord> endTrace, Action <TraceRecord> errorTrace) { if (traceWriter == null) { throw System.Web.Http.Error.ArgumentNull("traceWriter"); } if (execute == null) { throw System.Web.Http.Error.ArgumentNull("execute"); } bool isTracing = false; traceWriter.Trace( request, category, level, (TraceRecord traceRecord) => { isTracing = true; traceRecord.Kind = TraceKind.Begin; traceRecord.Operator = operatorName; traceRecord.Operation = operationName; if (beginTrace != null) { beginTrace(traceRecord); } }); try { Task task = execute(); // If we are not tracing, there is no need to ContinueWith if (!isTracing || task == null) { return(task); } Task <Task> returnTask = task.ContinueWith <Task>((t) => { if (t.IsCanceled) { traceWriter.Trace( request, category, TraceLevel.Warn, (TraceRecord traceRecord) => { traceRecord.Kind = TraceKind.End; traceRecord.Operator = operatorName; traceRecord.Operation = operationName; traceRecord.Message = SRResources.TraceCancelledMessage; if (errorTrace != null) { errorTrace(traceRecord); } }); return(TaskHelpers.Canceled()); } if (t.IsFaulted) { traceWriter.Trace( request, category, TraceLevel.Error, (TraceRecord traceRecord) => { traceRecord.Kind = TraceKind.End; traceRecord.Exception = t.Exception.GetBaseException(); traceRecord.Operator = operatorName; traceRecord.Operation = operationName; if (errorTrace != null) { errorTrace(traceRecord); } }); return(TaskHelpers.FromErrors(t.Exception.InnerExceptions)); } traceWriter.Trace( request, category, level, (TraceRecord traceRecord) => { traceRecord.Kind = TraceKind.End; traceRecord.Operator = operatorName; traceRecord.Operation = operationName; if (endTrace != null) { endTrace(traceRecord); } }); return(TaskHelpers.Completed()); }); return(returnTask.FastUnwrap()); } catch (Exception ex) { if (isTracing) { traceWriter.Trace( request, category, TraceLevel.Error, (TraceRecord traceRecord) => { traceRecord.Kind = TraceKind.End; traceRecord.Operator = operatorName; traceRecord.Operation = operationName; traceRecord.Exception = ex; if (errorTrace != null) { errorTrace(traceRecord); } }); } throw; } }
/// <summary> /// Writes a <see cref="TraceRecord"/> at <see cref="TraceLevel.Error"/> with the given <paramref name="exception"/>. /// </summary> /// <param name="traceWriter">The <see cref="ITraceWriter"/></param> /// <param name="request">The <see cref="HttpRequestMessage"/> with which to correlate the request. /// It may be null, but if so will not be correlated with any request.</param> /// <param name="category">The category for the trace.</param> /// <param name="exception">The exception to trace</param> public static void Error(this ITraceWriter traceWriter, HttpRequestMessage request, string category, Exception exception) { Trace(traceWriter, request, category, TraceLevel.Error, exception); }
public FeaturesController(IMasterRepository repo, ITraceWriter logger) { this._repo = repo; this._tracer = logger; }
public AuthorizationFilterTracer(IAuthorizationFilter innerFilter, ITraceWriter traceWriter) : base(innerFilter, traceWriter) { }
/// <summary> /// Initializes a new instance of the <see cref="BaseCommandController" /> class. /// </summary> /// <param name="commandProcessor">An <see cref="ICommandProcessor" /></param> /// <param name="logger">An <see cref="ITraceWriter" /></param> protected BaseCommandController(ICommandProcessor commandProcessor, ITraceWriter logger) { _commandProcessor = commandProcessor; _logger = logger; }
public ActionFilterTracer(IActionFilter innerFilter, ITraceWriter traceWriter) : base(innerFilter, traceWriter) { }
public HttpControllerDescriptorTracer(HttpControllerDescriptor innerDescriptor, ITraceWriter traceWriter) { Contract.Assert(innerDescriptor != null); Contract.Assert(traceWriter != null); Configuration = innerDescriptor.Configuration; ControllerName = innerDescriptor.ControllerName; ControllerType = innerDescriptor.ControllerType; _innerDescriptor = innerDescriptor; _traceWriter = traceWriter; }
/// <summary> /// 错误 /// </summary> /// <param name="tracer">跟踪编写器</param> /// <param name="request">Http请求消息</param> /// <param name="controller">WebApi控制器</param> /// <param name="exception">异常信息</param> /// <param name="messageFormat">消息</param> /// <param name="messageArguments">消息参数</param> public static void Error(this ITraceWriter tracer, HttpRequestMessage request, ApiController controller, Exception exception, string messageFormat, params object[] messageArguments) { tracer.Error(request, controller.ControllerContext.ControllerDescriptor.ControllerType.FullName, exception, messageFormat, messageArguments); }
/// <summary> /// 错误 /// </summary> /// <param name="tracer">跟踪编写器</param> /// <param name="request">Http请求消息</param> /// <param name="controller">WebApi控制器</param> /// <param name="exception">异常信息</param> public static void Error(this ITraceWriter tracer, HttpRequestMessage request, ApiController controller, Exception exception) { tracer.Error(request, controller.ControllerContext.ControllerDescriptor.ControllerType.FullName, exception); }
public JsonMediaTypeFormatterTracer(JsonMediaTypeFormatter innerFormatter, ITraceWriter traceWriter, HttpRequestMessage request) : base(innerFormatter) { _inner = innerFormatter; _innerTracer = new MediaTypeFormatterTracer(innerFormatter, traceWriter, request); }
/// <summary> /// Writes a <see cref="TraceRecord"/> at <see cref="TraceLevel.Warn"/> with the given message. /// </summary> /// <param name="traceWriter">The <see cref="ITraceWriter"/></param> /// <param name="request">The <see cref="HttpRequestMessage"/> with which to correlate the request. /// It may be null, but if so will not be correlated with any request.</param> /// <param name="category">The category for the trace.</param> /// <param name="messageFormat">The string to use to format a message. It may not be null.</param> /// <param name="messageArguments">Optional list of arguments for the <paramref name="messageFormat"/>.</param> public static void Warn(this ITraceWriter traceWriter, HttpRequestMessage request, string category, string messageFormat, params object[] messageArguments) { Trace(traceWriter, request, category, TraceLevel.Warn, messageFormat, messageArguments); }
public override FormUrlEncodedMediaTypeFormatterTracer CreateTracer(FormUrlEncodedMediaTypeFormatter formatter, HttpRequestMessage request, ITraceWriter traceWriter) { return(new FormUrlEncodedMediaTypeFormatterTracer(formatter, traceWriter, request)); }
/// <summary> /// Traces both a begin and an end trace around a specified operation. /// </summary> /// <param name="traceWriter">The <see cref="ITraceWriter"/>.</param> /// <param name="request">The <see cref="HttpRequestMessage"/> with which to associate the trace. It may be null.</param> /// <param name="category">The logical category of the trace.</param> /// <param name="level">The <see cref="TraceLevel"/> of the trace.</param> /// <param name="operatorName">The name of the object performing the operation. It may be null.</param> /// <param name="operationName">The name of the operation being performaed. It may be null.</param> /// <param name="beginTrace">The <see cref="Action"/> to invoke prior to performing the operation, /// allowing the given <see cref="TraceRecord"/> to be filled in. It may be null.</param> /// <param name="execute">An <see cref="Action"/> that performs the operation.</param> /// <param name="endTrace">The <see cref="Action"/> to invoke after successfully performing the operation, /// allowing the given <see cref="TraceRecord"/> to be filled in. It may be null.</param> /// <param name="errorTrace">The <see cref="Action"/> to invoke if an error was encountered performing the operation, /// allowing the given <see cref="TraceRecord"/> to be filled in. It may be null.</param> public static void TraceBeginEnd(this ITraceWriter traceWriter, HttpRequestMessage request, string category, TraceLevel level, string operatorName, string operationName, Action <TraceRecord> beginTrace, Action execute, Action <TraceRecord> endTrace, Action <TraceRecord> errorTrace) { if (traceWriter == null) { throw System.Web.Http.Error.ArgumentNull("traceWriter"); } if (execute == null) { throw System.Web.Http.Error.ArgumentNull("execute"); } bool isTracing = false; traceWriter.Trace( request, category, level, (TraceRecord traceRecord) => { isTracing = true; traceRecord.Kind = TraceKind.Begin; traceRecord.Operator = operatorName; traceRecord.Operation = operationName; if (beginTrace != null) { beginTrace(traceRecord); } }); try { execute(); if (isTracing) { traceWriter.Trace( request, category, level, (TraceRecord traceRecord) => { traceRecord.Kind = TraceKind.End; traceRecord.Operator = operatorName; traceRecord.Operation = operationName; if (endTrace != null) { endTrace(traceRecord); } }); } } catch (Exception ex) { if (isTracing) { traceWriter.Trace( request, category, TraceLevel.Error, (TraceRecord traceRecord) => { traceRecord.Kind = TraceKind.End; traceRecord.Operator = operatorName; traceRecord.Operation = operationName; traceRecord.Exception = ex; if (errorTrace != null) { errorTrace(traceRecord); } }); } throw; } }
public async Task <HttpResponseMessage> PutInstallation([FromUri] string installationId, [FromBody] NotificationInstallation notificationInstallation) { //String ni = Newtonsoft.Json.JsonConvert.SerializeObject(notificationInstallation); ITraceWriter traceWriter = this.Configuration.Services.GetTraceWriter(); traceWriter.Info($"notificationInstallation.Tags.Count : {notificationInstallation.Tags.Count}"); if (!ModelState.IsValid) { throw new HttpResponseException(this.Request.CreateErrorResponse(HttpStatusCode.BadRequest, this.ModelState)); } this.ValidateInstallationId(installationId); this.ValidateNotificationInstallation(installationId, notificationInstallation); // The installation object that will be sent to NH. Installation installation = this.CreateInstallation(notificationInstallation); CopyAllTagsToInstallation(installation, notificationInstallation.Tags); HashSet <string> tagsAssociatedWithInstallationId = await this.GetTagsAssociatedWithInstallationId(notificationInstallation.InstallationId); ClaimsPrincipal serviceUser = this.User as ClaimsPrincipal; if (tagsAssociatedWithInstallationId.Count == 0) { // Installation does not exist on NH. Add it. if (installation.Tags == null) { installation.Tags = new List <string>(); } // Tag the installation with the UserId if authenticated. if (serviceUser != null && serviceUser.Identity.IsAuthenticated) { Claim userIdClaim = serviceUser.FindFirst(ClaimTypes.NameIdentifier); if (userIdClaim != null) { string incomingUserTag = string.Format(UserIdTagPlaceholder, userIdClaim.Value); installation.Tags.Add(incomingUserTag); } } try { await this.UpsertInstallationAsync(installation); } catch (HttpResponseException) { throw; } catch (Exception ex) { string error = RResources.NotificationHub_CreateOrUpdateInstallationFailed.FormatForUser(installationId, ex.Message); traceWriter.Error(error, ex, this.Request, ServiceLogCategories.NotificationControllers); traceWriter.Error(error, ex, this.Request, LogCategories.NotificationControllers); // We return 4xx status code on error as it is impossible to know whether it is bad input or a // server error from NH. As a result we err on the bad request side. return(this.Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex.Message)); } } else { // Installation already existed on NH. if (serviceUser != null && serviceUser.Identity.IsAuthenticated) { // Because the user is authenticated, copy all previous tags except UserId. CopyTagsToInstallation(installation, tagsAssociatedWithInstallationId, false); // Add the incoming UserId. Claim userIdClaim = serviceUser.FindFirst(ClaimTypes.NameIdentifier); if (userIdClaim != null) { string incomingUserTag = string.Format(UserIdTagPlaceholder, userIdClaim.Value); AddTagToInstallation(installation, incomingUserTag); } } else { // Because the request is anonymous, copy all previous tags to the installation object, including the previous user tag. CopyTagsToInstallation(installation, tagsAssociatedWithInstallationId, true); } CopyTagsToInstallation(installation, tagsAssociatedWithInstallationId, true); try { await this.UpsertInstallationAsync(installation); } catch (HttpResponseException) { throw; } catch (Exception ex) { string error = RResources.NotificationHub_CreateOrUpdateInstallationFailed.FormatForUser(installationId, ex.Message); traceWriter.Error(error, ex, this.Request, ServiceLogCategories.NotificationControllers); traceWriter.Error(error, ex, this.Request, LogCategories.NotificationControllers); // We return 4xx status code on error as it is impossible to know whether it is bad input or a // server error from NH. As a result we err on the bad request side. return(this.Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex.Message)); } } return(this.Request.CreateResponse(HttpStatusCode.OK)); }
public RequestMessageHandlerTracer(ITraceWriter traceWriter) { _traceWriter = traceWriter; }
public ProcessInvoker(ITraceWriter trace) { this.Trace = trace; }
public HttpControllerActivatorTracer(IHttpControllerActivator innerActivator, ITraceWriter traceWriter) { _innerActivator = innerActivator; _traceWriter = traceWriter; }
public PipeWebSocketTransportListener( Uri[] listenerUris, IEnvelopeSerializer envelopeSerializer, X509Certificate2 tlsCertificate = null, ITraceWriter traceWriter = null, int bufferSize = WebSocketTransport.DEFAULT_BUFFER_SIZE, TimeSpan?keepAliveInterval = null, int acceptCapacity = -1, HttpProtocols httpProtocols = HttpProtocols.Http1AndHttp2, SslProtocols sslProtocols = SslProtocols.Tls11 | SslProtocols.Tls12, WebSocketMessageType webSocketMessageType = WebSocketMessageType.Text, bool closeGracefully = true, int pauseWriterThreshold = EnvelopePipe.DEFAULT_PAUSE_WRITER_THRESHOLD, MemoryPool <byte> memoryPool = null, Func <X509Certificate2, X509Chain, SslPolicyErrors, bool> clientCertificateValidationCallback = null) { if (listenerUris == null) { throw new ArgumentNullException(nameof(listenerUris)); } if (listenerUris.Length == 0) { throw new ArgumentException("At least one listener URI should be provided.", nameof(listenerUris)); } if (listenerUris.Any(u => u.Scheme != UriSchemeWebSocket && u.Scheme != UriSchemeWebSocketSecure)) { throw new ArgumentException($"Invalid URI scheme. Should be '{UriSchemeWebSocket}' or '{UriSchemeWebSocketSecure}'.", nameof(listenerUris)); } if (tlsCertificate == null && listenerUris.Any(u => u.Scheme == UriSchemeWebSocketSecure)) { throw new ArgumentException($"The certificate should be provided when listening to a '{UriSchemeWebSocketSecure}' URI.", nameof(listenerUris)); } ListenerUris = listenerUris; _envelopeSerializer = envelopeSerializer; _traceWriter = traceWriter; _acceptCapacity = acceptCapacity; _webSocketMessageType = webSocketMessageType; _closeGracefully = closeGracefully; _pauseWriterThreshold = pauseWriterThreshold; _memoryPool = memoryPool; _webHost = new WebHostBuilder() .UseKestrel(serverOptions => { foreach (var listenerUri in ListenerUris) { if (!IPAddress.TryParse(listenerUri.Host, out var ipAddress)) { ipAddress = IPAddress.Any; } var endPoint = new IPEndPoint(ipAddress, listenerUri.Port); serverOptions.Listen(endPoint, listenOptions => { listenOptions.Protocols = httpProtocols; if (listenerUri.Scheme == UriSchemeWebSocketSecure) { listenOptions.UseHttps(tlsCertificate, httpsOptions => { httpsOptions.SslProtocols = sslProtocols; httpsOptions.ClientCertificateValidation = clientCertificateValidationCallback; }); } }); } serverOptions.AddServerHeader = false; }) .SuppressStatusMessages(true) .Configure(app => { // Add the WebSockets middleware app.UseWebSockets( new WebSocketOptions() { KeepAliveInterval = keepAliveInterval ?? System.Net.WebSockets.WebSocket.DefaultKeepAliveInterval, ReceiveBufferSize = bufferSize, }); app.Run(ProcessHttpContextAsync); }) .Build(); }
/// <summary> /// Creates new instance of controller. /// </summary> public GroupController(IGroupService groupService, IUserService userService, IUserIdentityService userIdentityService, ITraceWriter tracer) { this.userService = userService; this.groupService = groupService; this.userIdentityService = userIdentityService; this.tracer = tracer; }
public abstract MediaTypeFormatter CreateTracer( TFormatter formatter, HttpRequestMessage request, ITraceWriter traceWriter );
public WebApiLogController(IComponentContext container, IEntityService <TEntity> service, ILog <TLog> logger) : base(container, service) { this._tracer = GlobalConfiguration.Configuration.Services.GetTraceWriter(); this._logger = logger; }
public ChangeFrameworkActionFactory(ITraceWriter traceWriter, IDirectoryWalkerFactory directoryWalkerFactory) { _traceWriter = traceWriter; _directoryWalkerFactory = directoryWalkerFactory; }
/// <summary> /// Writes a <see cref="TraceRecord"/> at <see cref="TraceLevel.Error"/> with the given message and exception. /// </summary> /// <param name="traceWriter">The <see cref="ITraceWriter"/></param> /// <param name="request">The <see cref="HttpRequestMessage"/> with which to correlate the request. /// It may be null, but if so will not be correlated with any request.</param> /// <param name="category">The category for the trace.</param> /// <param name="exception">The exception to trace</param> /// <param name="messageFormat">The string to use to format a message. It may not be null.</param> /// <param name="messageArguments">Optional list of arguments for the <paramref name="messageFormat"/>.</param> public static void Error(this ITraceWriter traceWriter, HttpRequestMessage request, string category, Exception exception, string messageFormat, params object[] messageArguments) { Trace(traceWriter, request, category, TraceLevel.Error, exception, messageFormat, messageArguments); }
/// <summary> /// Initializes a new instance of the <see cref="CommandHandlerFilterAttributeTracer"/> class. /// </summary> /// <param name="innerFilter"> /// The inner filter. /// </param> /// <param name="traceWriter"> /// The trace writer. /// </param> public CommandHandlerFilterAttributeTracer(CommandHandlerFilterAttribute innerFilter, ITraceWriter traceWriter) { Contract.Requires(innerFilter != null); Contract.Requires(traceWriter != null); this.innerFilter = innerFilter; this.traceWriter = traceWriter; }
public ActionFilterAttributeTracer(ActionFilterAttribute innerFilter, ITraceWriter traceWriter) { _innerFilter = innerFilter; _traceWriter = traceWriter; }