/// <summary> /// Sends the asynchronous. /// </summary> /// <returns> /// Task. /// </returns> public async Task SendAsync() { var cacheKey = TypeExtensions.GetCallingMethod(); string eml; using (var sr = new StreamReader(_message.RawMessage())) { eml = await sr.ReadToEndAsync().ConfigureAwait(false); } var date = DateTime.Now.ToString(@"yyyy-MM-dd HH.mm.ss.ffffff", CultureInfo.InvariantCulture); LogConsumer.DebugTo <TextFileLogProvider>(eml, $@"{_message.Subject} {date}.{Guid.NewGuid()}.eml"); if (OperationManager.IsInTestEnvironment) { LogConsumer.Trace(Resources.SmtpMailer_SendAsync_Disabled, Resources.SmtpMailer_SendAsync_DisabledDue_TestEnvironment); return; } try { await SendInternalAsync(cacheKey).ConfigureAwait(false); } catch (Exception e) { if (!HandleExtension(e, cacheKey)) { throw; } } }
/// <summary> /// Adds the client. /// </summary> /// <typeparam name="TTelemetryClient">The type of the i telemetry client.</typeparam> /// <returns></returns> public static ITelemetryClient AddClient <TTelemetryClient>() where TTelemetryClient : ITelemetryClient { var client = ServiceLocator.Resolve <TTelemetryClient>(); LogConsumer.Trace("Adding telemetry client of type {0}", client.GetType().FullName); Clients.Add(client); return(client); }
/// <summary> /// Removes the hit. /// </summary> /// <param name="hitName">Name of the hit.</param> public static void RemoveHit(string hitName) { LogConsumer.Trace("Removing hits of {0}", hitName); foreach (var client in Clients) { client.RemoveHit(hitName); } }
/// <summary> /// Tracks the exception. /// </summary> /// <param name="exceptionType">Type of the exception.</param> public static void TrackException(Type exceptionType) { LogConsumer.Trace("Tracking exception of type {0}", exceptionType.FullName); foreach (var client in Clients) { client.TrackException(exceptionType); } }
/// <summary> /// Removes the metric. /// </summary> /// <param name="metricName">Name of the metric.</param> /// <param name="variation">The variation.</param> public static void RemoveMetric([Localizable(false)] string metricName, [Localizable(false)] string variation) { LogConsumer.Trace("Deleting metric {0} with variation {1}", metricName, variation); foreach (var client in Clients) { client.RemoveMetric(metricName, variation); } }
/// <summary> /// Sets the specified value. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="value">The value.</param> /// <param name="key">The key.</param> /// <param name="subKey">The sub key.</param> public static void Set <T>(T value, [Localizable(false)] string key, [Localizable(false)] string subKey) { LogConsumer.Trace("Adding {0}/{2} to {1} cache repositories", key, Repositories.Count, subKey); foreach (var repository in Repositories.Values) { repository.Set(value, key, subKey); } }
/// <summary> /// Sets the specified value. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="value">The value.</param> /// <param name="key">The key.</param> /// <param name="ttl">The TTL.</param> public static void Set <T>(T value, [Localizable(false)] string key, TimeSpan ttl) { LogConsumer.Trace("Adding {0} to {1} cache repositories with TTL of {2:g}", key, Repositories.Count, ttl); foreach (var repository in Repositories.Values) { repository.Set(value, key, ttl); } }
/// <summary> /// Tracks the event. /// </summary> /// <typeparam name="TEvent">The type of the event.</typeparam> /// <param name="event">The event.</param> /// <param name="ttl">The TTL.</param> public static void TrackEvent <TEvent>(ITelemetryEvent <TEvent> @event, TimeSpan ttl) where TEvent : class, new() { LogConsumer.Trace("Tracking event of type {0}", typeof(TEvent).FullName); foreach (var client in Clients) { client.TrackEvent(@event, ttl); } }
/// <summary> /// Removes the specified key. /// </summary> /// <param name="key">The key.</param> /// <param name="subKey">The sub key.</param> public static void Remove([Localizable(false)] string key, [Localizable(false)] string subKey) { LogConsumer.Trace("Removing key {0} and sub key {2} from {1} repositories", key, Repositories.Count, subKey); foreach (var repository in Repositories.Values) { repository.Remove(key, subKey); } }
/// <summary> /// Tracks the hit. /// </summary> /// <param name="hitName">Name of the hit.</param> public static void TrackHit([Localizable(false)] string hitName) { LogConsumer.Trace("Tracking hit of {0}", hitName); foreach (var client in Clients) { client.TrackHit(hitName); } }
/// <summary> /// Services the invoker internal. /// </summary> /// <param name="method">The method.</param> /// <param name="endpoint">The endpoint.</param> /// <param name="token">The token.</param> /// <param name="data">The data.</param> /// <param name="uriBuilder">The URI builder.</param> /// <param name="cookie">The cookie.</param> /// <param name="requiresAuthentication">if set to <c>true</c> [requires authentication].</param> /// <param name="isRetry">if set to <c>true</c> [is retry].</param> /// <returns></returns> private async Task <string> ServiceInvokerInternal( HttpRequestMethod method, string endpoint, CancellationToken token, string data, UriBuilder uriBuilder, Cookie cookie, bool requiresAuthentication, bool isRetry = false) { HttpResponseMessage response = null; string result = null; Exception exr; try { _requestMediator.WaitOne(); LogConsumer.Trace("ServiceInvokerAsync -> Method: {0} | Endpoint: {1}", method.GetHumanReadableValue(), endpoint); LogConsumer.Debug(uriBuilder.ToString()); var cookieContainer = new CookieContainer(); using var handler = new HttpClientHandler { CookieContainer = cookieContainer }; using var client = new HttpClient(handler); ConfigureClient(client, requiresAuthentication); if (cookie != null) { cookieContainer.Add(uriBuilder.Uri, cookie); } response = await RequestInternalAsync(method, token, data, client, uriBuilder) .ConfigureAwait(false); token.ThrowIfCancellationRequested(); result = await response.Content.ReadAsStringAsync().ConfigureAwait(false); response.EnsureSuccessStatusCode(); return(result); } catch (AggregateException e) { var ex = e.InnerExceptions.FirstOrDefault() ?? e.InnerException ?? e; exr = HandleException(ex, response, uriBuilder.Uri, method, data, result); if (isRetry) { throw exr; } } catch (Exception e) { exr = HandleException(e, response, uriBuilder.Uri, method, data, result); if (isRetry) { throw exr; } } return(await ServiceInvokerInternal(method, endpoint, token, data, uriBuilder, cookie, requiresAuthentication, true).ConfigureAwait(false)); }
/// <summary> /// Handles the exception. /// </summary> /// <param name="e">The e.</param> private static void HandleException(Exception e) { if (e.Message.IndexOf("timeout", StringComparison.InvariantCultureIgnoreCase) != -1) { LogConsumer.Trace(e); } else { LogConsumer.Handle(e); } }
/// <summary> /// Raises the specified event. /// </summary> /// <typeparam name="TEvent">The type of the event.</typeparam> /// <param name="event">The event.</param> public static void Raise <TEvent>(TEvent @event) where TEvent : IEvent { var handlers = ServiceLocator.ResolveAll <IEventHandler <TEvent> >(); foreach (var handler in handlers) { LogConsumer.Trace($"Calling {handler.GetType().FullName} for event {@event.GetType().FullName}"); handler.Handle(@event); } }
/// <summary> /// Propagates the message internal. /// </summary> /// <param name="message">The message.</param> private void PropagateMessageInternal(string message) { try { var body = Encoding.UTF8.GetBytes(message); _channel.BasicPublish(_connector.DefaultExchangeName, "", null, body); } catch (Exception e) { LogConsumer.Trace(e); } }
/// <summary> /// Tracks the dependency. /// </summary> /// <param name="interfaceType">Type of the interface.</param> /// <param name="resolvedTimes">The resolved times.</param> public static void TrackDependency(Type interfaceType, int resolvedTimes) { LogConsumer.Trace("Tracking dependency of {0}, resolved {1} time{2}", interfaceType.FullName, resolvedTimes, resolvedTimes == 1 ? string.Empty : @"s"); foreach (var client in Clients) { client.TrackDependency(interfaceType, resolvedTimes); } }
/// <summary> /// Removes from. /// </summary> /// <typeparam name="TCacheRepository">The type of the cache repository.</typeparam> /// <param name="key">The key.</param> /// <param name="subKey">The sub key.</param> /// <exception cref="InvalidOperationException"></exception> public static void RemoveFrom <TCacheRepository>([Localizable(false)] string key, [Localizable(false)] string subKey) { var type = typeof(TCacheRepository); LogConsumer.Trace("Removing key {0} and sub key {2} from {1} repository", key, Repositories.Count, subKey); var repository = Repositories.SingleOrDefault(r => type == r.Value.GetType()).Value; if (repository == null) { throw new InvalidOperationException($"The repository of type {type.FullName} isn't available in the repositories providers list"); } repository.Remove(key, subKey); }
/// <summary> /// Gets from. /// </summary> /// <typeparam name="TCacheRepository">The type of the cache repository.</typeparam> /// <typeparam name="TValue">The type of the value.</typeparam> /// <param name="key">The key.</param> /// <param name="subKey">The sub key.</param> /// <returns></returns> /// <exception cref="InvalidOperationException"></exception> public static TValue GetFrom <TCacheRepository, TValue>([Localizable(false)] string key, [Localizable(false)] string subKey) { var type = typeof(TCacheRepository); LogConsumer.Trace("Getting {0}/{2} from repository {1}", key, type.FullName, subKey); var repository = Repositories.SingleOrDefault(r => type == r.Value.GetType()).Value; if (repository == null) { throw new InvalidOperationException($"The repository of type {type.FullName} isn't available in the repositories providers list"); } return(repository.Get <TValue>(key, subKey)); }
/// <summary> /// Sets to. /// </summary> /// <typeparam name="TCacheRepository">The type of the cache repository.</typeparam> /// <typeparam name="TValue">The type of the value.</typeparam> /// <param name="value">The value.</param> /// <param name="key">The key.</param> /// <param name="subKey">The sub key.</param> /// <param name="ttl">The TTL.</param> /// <exception cref="InvalidOperationException"></exception> public static void SetTo <TCacheRepository, TValue>(TValue value, [Localizable(false)] string key, [Localizable(false)] string subKey, TimeSpan ttl) { var type = typeof(TCacheRepository); LogConsumer.Trace("Adding {0}/{2} to repository of type {1} with TTL of {2:g}", key, type.FullName, ttl, subKey); var repository = Repositories.SingleOrDefault(r => type == r.Value.GetType()).Value; if (repository == null) { throw new InvalidOperationException($"The repository of type {type.FullName} isn't available in the repositories providers list"); } repository.Set(value, key, subKey); }
/// <summary> /// Gets the hit. /// </summary> /// <param name="hitName">Name of the hit.</param> /// <returns></returns> public static int GetHit(string hitName) { int temp; LogConsumer.Trace("Getting hits of {0}", hitName); foreach (var client in Clients) { if ((temp = client.GetHit(hitName)) > 0) { return(temp); } } return(0); }
/// <summary> /// Gets the event. /// </summary> /// <typeparam name="TEvent">The type of the event.</typeparam> /// <param name="event">The event.</param> /// <returns></returns> public static TEvent GetEvent <TEvent>(ITelemetryEvent <TEvent> @event) where TEvent : class, new() { LogConsumer.Trace("Getting event of type {0} with key {1}", typeof(TEvent).FullName, @event.Name); TEvent result; foreach (var client in Clients) { if ((result = client.GetEvent(@event)) != null) { return(result); } } return(null); }
/// <summary> /// Gets the metric. /// </summary> /// <param name="metricName">Name of the metric.</param> /// <param name="variation">The variation.</param> /// <returns></returns> public static int GetMetric([Localizable(false)] string metricName, [Localizable(false)] string variation) { var result = 0; LogConsumer.Trace("Getting metric {0} with variation {1}", metricName, variation); foreach (var client in Clients) { result = client.GetMetric(metricName, variation); if (result != 0) { break; } } return(result); }
/// <summary> /// TTLs the specified key. /// </summary> /// <param name="key">The key.</param> /// <returns></returns> public static TimeSpan TTL([Localizable(false)] string key) { LogConsumer.Trace("Trying to get TTL of key {0} from {1} repositories", key, Repositories.Count); var result = new TimeSpan(0); foreach (var repository in Repositories.Values) { var currentResult = repository.TTL(key); if (currentResult == result) { continue; } return(currentResult); } return(new TimeSpan(0)); }
/// <summary> /// Adds the repository with the defined priority. /// </summary> /// <param name="repository">The repository.</param> /// <param name="priority">The priority.</param> /// <returns>Returns the priority with the repository was added</returns> public static int AddRepository(ICacheRepository repository, int priority) { while (true) { if (!Repositories.ContainsKey(priority)) { Repositories.Add(priority, repository); LogConsumer.Trace("Adding cache repository of type {0} with priority {1}", repository.GetType().FullName, priority); if (repository.GetType() == MemoryType) { _isMemoryRepositoryInList = true; } return(priority); } priority++; } }
/// <summary> /// send internal as an asynchronous operation. /// </summary> /// <param name="cacheKey">The cache key.</param> /// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns> private async Task SendInternalAsync(string cacheKey) { if (CacheManager.TryGet(cacheKey, out bool exists) && exists) { LogConsumer.Trace(Resources.SmtpMailer_SendAsync_Disabled, Resources.SmtpMailer_SendAsync_DisabledDue_NetworkError); return; } var receivers = _message.To.Select(d => d).ToList(); _message.CC.ToList().ForEach(receivers.Add); LogConsumer.Trace(Resources.SmtpMailer_SendAsync_Sending, _message.Subject.Replace(@" - Integração Service", ""), string.Join(@",", receivers.Select(d => d.DisplayName))); await _client.SendMailAsync(_message).ConfigureAwait(false); }
/// <summary> /// Gets the specified key. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="key">The key.</param> /// <param name="subKey">The sub key.</param> /// <returns></returns> /// <exception cref="InvalidOperationException"></exception> public static T Get <T>([Localizable(false)] string key, [Localizable(false)] string subKey) { LogConsumer.Trace("Getting {0}/{2} from any of {1} cache repositories", key, Repositories.Count, subKey); foreach (var repository in Repositories.Values) { if (!repository.TryGet(key, subKey, out T value)) { continue; } if (_isMemoryRepositoryInList && repository.GetType() != typeof(MemoryCacheRepository)) { SetTo <MemoryCacheRepository, T>(value, key, subKey); } return(value); } throw new InvalidOperationException($"Unable to get the item with key {key} and sub key {subKey}"); }
/// <summary> /// Tries the get. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="key">The key.</param> /// <param name="subKey">The sub key.</param> /// <param name="value">The value.</param> /// <returns></returns> public static bool TryGet <T>([Localizable(false)] string key, [Localizable(false)] string subKey, out T value) { LogConsumer.Trace("Trying to get {0}/{2} from any of {1} repositories", key, Repositories.Count, subKey); value = default; foreach (var repository in Repositories.Values) { if (!repository.TryGet(key, subKey, out value)) { continue; } if (_isMemoryRepositoryInList && repository.GetType() != typeof(MemoryCacheRepository)) { SetTo <MemoryCacheRepository, T>(value, key, subKey); } return(true); } return(false); }
/// <summary> /// Disposes all registrations. /// </summary> public static void DisposeAllRegistrations() { LogConsumer.Trace("Service locator statistics"); var temp = new Dictionary <Type, int>(RegistrationsCalls); foreach (var calls in temp) { TelemetryAnalytics.TrackDependency(calls.Key, calls.Value); } var type = typeof(IDisposable); var instances = RegistrationsCalls .Where(call => call.Value > 0) .SelectMany(call => Registrations.Where(implementation => type.IsAssignableFrom(implementation.Key) && call.Key.IsAssignableFrom(implementation.Key))) .ToList(); foreach (var instance in instances) { ((IDisposable)instance.Value()).Dispose(); } }
/// <summary> /// Adds the client. /// </summary> /// <param name="client">The client.</param> /// <returns></returns> public static ITelemetryClient AddClient(ITelemetryClient client) { LogConsumer.Trace("Adding telemetry client of type {0}", client.GetType().FullName); Clients.Add(client); return(client); }