internal HttpClient ProvideHttpClient(string proxyAddress = null, string proxyUsername = null, string proxyPassword = null) { if (this._httpClient != null) { Assumption.AssertTrue( (string.IsNullOrWhiteSpace(proxyAddress) && string.IsNullOrWhiteSpace(this._proxyAddress)) || (string.Compare(proxyAddress, this._proxyAddress, true) == 0) , nameof(proxyAddress) ); Assumption.AssertTrue( (string.IsNullOrWhiteSpace(proxyUsername) && string.IsNullOrWhiteSpace(this._proxyUsername)) || (string.Compare(proxyUsername, this._proxyUsername, true) == 0) , nameof(proxyUsername) ); Assumption.AssertTrue( (string.IsNullOrWhiteSpace(proxyPassword) && string.IsNullOrWhiteSpace(this._proxyPassword)) || (string.Compare(proxyPassword, this._proxyPassword, true) == 0) , nameof(proxyPassword) ); // reuse what is already there: return(this._httpClient); } // create new instance: this._proxyAddress = proxyAddress; this._proxyUsername = proxyUsername; this._proxyPassword = proxyPassword; this._httpClient = HttpClientUtil.CreateHttpClient(proxyAddress, proxyUsername, proxyPassword); return(this._httpClient); }
/// <summary> /// Validates this instance. /// </summary> public override void Validate() { base.Validate(); Assumption.AssertNotNull(this.Body, nameof(this.Body)); Assumption.AssertTrue(this.Body.GetType().Name.Contains(this.Type.ToString()), nameof(this.Body)); }
/// <summary> /// Gets or sets the <see cref="System.Object"/> with the specified key. /// </summary> /// <value> /// The <see cref="System.Object"/>. /// </value> /// <param name="key">The key.</param> /// <returns></returns> public object this[string key] { get { if (this._keyedValues.TryGetValue(key, out object result)) { return(result); } return(null); } set { Assumption.AssertTrue( !this._keyedValues.ContainsKey(key) || // no such key preset yet this._keyedValues[key] == null || // OR its not initialized yet value != null || // OR no-null value !this._metadata.ReservedPropertyInfoByReservedKey.Keys.Contains(key), // OR not about reserved property/key "conditional " + nameof(value) + " assessment" ); //Assumption.AssertTrue( // !this._metadata.ReservedPropertyInfoByReservedKey.Keys.Contains(key) // not about reserved property/key // , "conditional " + nameof(value) + " assessment" // ); this._keyedValues[key] = value; } }
/// <summary> /// Initializes a new instance of the <see cref="RollbarLogger" /> class. /// </summary> /// <param name="rollbarConfig">The rollbar configuration.</param> internal RollbarLogger(IRollbarLoggerConfig?rollbarConfig) { Assumption.AssertTrue(RollbarInfrastructure.Instance.IsInitialized, nameof(RollbarInfrastructure.Instance.IsInitialized)); if (RollbarTelemetryCollector.Instance != null && !RollbarTelemetryCollector.Instance.IsAutocollecting ) { RollbarTelemetryCollector.Instance.StartAutocollection(); } if (rollbarConfig != null) { ValidateConfiguration(rollbarConfig); this._config = new RollbarLoggerConfig(this).Reconfigure(rollbarConfig); } else { this._config = new RollbarLoggerConfig(this); } // let's init proper Rollbar client: var rollbarClient = new RollbarClient(this); // let's init the corresponding queue and register it: this._payloadQueue = new PayloadQueue(this, rollbarClient); RollbarQueueController.Instance?.Register(this._payloadQueue); }
/// <summary> /// Gets or sets the <see cref="System.Object"/> with the specified key. /// </summary> /// <value> /// The <see cref="System.Object"/>. /// </value> /// <param name="key">The key.</param> /// <returns></returns> public object this[string key] { get { if (this._keyedValues.TryGetValue(key, out object result)) { return(result); } return(null); } set { Assumption.AssertTrue( !this._keyedValues.ContainsKey(key) || // no such key preset yet this._keyedValues[key] == null || // OR its not initialized yet value != null || // OR no-null value !this._metadata.ReservedPropertyInfoByReservedKey.Keys.Contains(key), // OR not about reserved property/key "conditional " + nameof(value) + " assessment" ); Assumption.AssertTrue( !metadataByDerivedType[this.GetType()].ReservedPropertyInfoByReservedKey.ContainsKey(key) || value == null || metadataByDerivedType[this.GetType()].ReservedPropertyInfoByReservedKey[key].PropertyType == value.GetType() || (metadataByDerivedType[this.GetType()].ReservedPropertyInfoByReservedKey[key].PropertyType.IsGenericType && // dealing with nullable type metadataByDerivedType[this.GetType()].ReservedPropertyInfoByReservedKey[key].PropertyType.GenericTypeArguments.Length == 1 && metadataByDerivedType[this.GetType()].ReservedPropertyInfoByReservedKey[key].PropertyType.GenericTypeArguments[0] == value.GetType()) , nameof(value) ); this._keyedValues[key] = value; } }
/// <summary> /// Gets or sets the <see cref="System.Object"/> with the specified key. /// </summary> /// <value> /// The <see cref="System.Object"/>. /// </value> /// <param name="key">The key.</param> /// <returns></returns> public object this[string key] { get { if (this._keyedValues.TryGetValue(key, out object result)) { return(result); } var concreteDtoMetadata = metadataByDerivedType[this.GetType()]; if (concreteDtoMetadata .ReservedPropertyInfoByReservedKey .TryGetValue(key, out PropertyInfo reservedPropertyInfo)) { //if we have matching reserved property of value type - return default for it: if (reservedPropertyInfo.PropertyType.IsValueType) { return(Activator.CreateInstance(reservedPropertyInfo.PropertyType)); } } return(null); } set { Assumption.AssertTrue( !this._keyedValues.ContainsKey(key) || // no such key preset yet this._keyedValues[key] == null || // OR its not initialized yet value != null || // OR no-null value !this._metadata.ReservedPropertyInfoByReservedKey.Keys.Contains(key), // OR not about reserved property/key "conditional " + nameof(value) + " assessment" ); // var concreteDtoMetadata = metadataByDerivedType[this.GetType()]; if (concreteDtoMetadata .ReservedPropertyInfoByReservedKey .TryGetValue(key, out PropertyInfo reservedPropertyInfo)) { var reservedPropertyType = reservedPropertyInfo.PropertyType; var valueType = value?.GetType(); Assumption.AssertTrue( //we are not dealing with a reserved property, hence, anything works: !concreteDtoMetadata.ReservedPropertyInfoByReservedKey.ContainsKey(key) //OR we are dealing with a reserved property and the value and its type should make sense: || value == null || reservedPropertyType == valueType || (reservedPropertyType.IsInterface && ReflectionUtility.DoesTypeImplementInterface(valueType, reservedPropertyType)) || (reservedPropertyType.IsGenericType && // dealing with nullable type reservedPropertyType.GenericTypeArguments.Length == 1 && reservedPropertyType.GenericTypeArguments[0] == valueType) || valueType.IsSubclassOf(reservedPropertyType), nameof(value) ); } // this._keyedValues[key] = value; } }
/// <summary> /// Begins a logical operation scope. /// </summary> /// <typeparam name="TState"></typeparam> /// <param name="state">The identifier for the scope.</param> /// <returns> /// An IDisposable that ends the logical operation scope on dispose. /// </returns> public virtual IDisposable BeginScope <TState>(TState state) { Assumption.AssertTrue(!object.Equals(state, default(TState)), nameof(state)); var scope = new RollbarScope(_name, state); return(RollbarScope.Push(scope)); }
/// <summary> /// Does the type implement interface. /// </summary> /// <param name="type">The type.</param> /// <param name="interfaceType">Type of the interface.</param> /// <returns><c>true</c> if implements, <c>false</c> otherwise.</returns> public static bool DoesTypeImplementInterface(Type type, Type interfaceType) { Assumption.AssertNotNull(type, nameof(type)); Assumption.AssertNotNull(interfaceType, nameof(interfaceType)); Assumption.AssertTrue(interfaceType.IsInterface, nameof(interfaceType)); return(type.GetInterfaces().Any(i => i.FullName == interfaceType.FullName)); }
/// <summary> /// Gets the static field value. /// </summary> /// <typeparam name="TFieldDataType">The type of the field data type.</typeparam> /// <param name="staticField">The static field.</param> /// <returns></returns> public static TFieldDataType GetStaticFieldValue <TFieldDataType>(FieldInfo staticField) { Assumption.AssertTrue(staticField.IsStatic, nameof(staticField.IsStatic)); TFieldDataType result = (TFieldDataType)staticField.GetValue(null); return(result); }
/// <summary> /// Begins a logical operation scope. /// </summary> /// <typeparam name="TState"></typeparam> /// <param name="state">The identifier for the scope.</param> /// <returns> /// An IDisposable that ends the logical operation scope on dispose. /// </returns> public IDisposable BeginScope <TState>(TState state) { Assumption.AssertTrue(state != null, nameof(state)); var scope = new RollbarScope(_name, state); scope.HttpContext = RollbarScope.Current?.HttpContext ?? new RollbarHttpContext(); return(RollbarScope.Push(scope)); }
/// <summary> /// Begins a logical operation scope. /// </summary> /// <typeparam name="TState"></typeparam> /// <param name="state">The identifier for the scope.</param> /// <returns> /// An IDisposable that ends the logical operation scope on dispose. /// </returns> public override IDisposable BeginScope <TState>(TState state) { Assumption.AssertTrue(!object.Equals(state, default(TState)), nameof(state)); var scope = new RollbarScope(this.Name, state); scope.HttpContext = RollbarScope.Current?.HttpContext ?? new RollbarHttpContext(); return(RollbarScope.Push(scope)); }
public async Task <RollbarResponse> PostAsJsonAsync(PayloadBundle payloadBundle) { Assumption.AssertNotNull(payloadBundle, nameof(payloadBundle)); Payload payload = payloadBundle.GetPayload(); Assumption.AssertNotNull(payload, nameof(payload)); if (payloadBundle.AsHttpContentToSend == null) { if (this._payloadTruncationStrategy.Truncate(payloadBundle.GetPayload()) > this._payloadTruncationStrategy.MaxPayloadSizeInBytes) { throw new ArgumentOutOfRangeException( paramName: nameof(payloadBundle), message: $"Payload size exceeds {this._payloadTruncationStrategy.MaxPayloadSizeInBytes} bytes limit!" ); } var jsonData = JsonConvert.SerializeObject(payload); jsonData = ScrubPayload(jsonData, this._config.GetFieldsToScrub()); payloadBundle.AsHttpContentToSend = new StringContent(jsonData, Encoding.UTF8, "application/json"); //CONTENT-TYPE header } Assumption.AssertNotNull(payloadBundle.AsHttpContentToSend, nameof(payloadBundle.AsHttpContentToSend)); Assumption.AssertTrue(string.Equals(payload.AccessToken, this._config.AccessToken), nameof(payload.AccessToken)); HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, this._payloadPostUri); const string accessTokenHeader = "X-Rollbar-Access-Token"; request.Headers.Add(accessTokenHeader, this._config.AccessToken); request.Content = payloadBundle.AsHttpContentToSend; var postResponse = await this._httpClient.SendAsync(request); RollbarResponse response = null; if (postResponse.IsSuccessStatusCode) { string reply = await postResponse.Content.ReadAsStringAsync(); response = JsonConvert.DeserializeObject <RollbarResponse>(reply); response.HttpDetails = $"Response: {postResponse}" + Environment.NewLine + $"Request: {postResponse.RequestMessage}" + Environment.NewLine ; } else { postResponse.EnsureSuccessStatusCode(); } return(response); }
public PayloadQueue(RollbarLogger logger, RollbarClient client) { Assumption.AssertNotNull(logger, nameof(logger)); Assumption.AssertNotNull(client, nameof(client)); Assumption.AssertTrue(object.ReferenceEquals(logger.Config, client.Config), nameof(client.Config)); this._logger = logger; this._syncLock = new object(); this._queue = new Queue <Payload>(); this._client = client; }
/// <summary> /// Ensures the HTTP content to send. /// </summary> /// <param name="payloadBundle">The payload bundle.</param> /// <returns><c>true</c> if succeeds, <c>false</c> otherwise.</returns> public bool EnsureHttpContentToSend(PayloadBundle payloadBundle) { if (payloadBundle.AsHttpContentToSend != null) { return(true); } Payload payload = payloadBundle.GetPayload(); Assumption.AssertNotNull(payload, nameof(payload)); if (!TruncatePayload(payloadBundle)) { return(false); } if (!ScrubHttpMessages(payloadBundle)) { return(false); } string jsonData = SerializePayloadAsJsonString(payloadBundle); if (string.IsNullOrWhiteSpace(jsonData)) { return(false); } try { jsonData = ScrubPayload(jsonData); } catch (System.Exception exception) { RollbarErrorUtility.Report( this._rollbarLogger, payload, InternalRollbarError.PayloadScrubbingError, "While scrubbing a payload...", exception, payloadBundle ); return(false); } payloadBundle.AsHttpContentToSend = new StringContent(jsonData, Encoding.UTF8, "application/json"); //CONTENT-TYPE header Assumption.AssertNotNull(payloadBundle.AsHttpContentToSend, nameof(payloadBundle.AsHttpContentToSend)); Assumption.AssertTrue(string.Equals(payload.AccessToken, this._rollbarLogger.Config.AccessToken), nameof(payload.AccessToken)); return(true); }
// TODO: override a finalizer only if Dispose(bool disposing) above has code to free unmanaged resources. // ~RollbarLogger() { // // Do not change this code. Put cleanup code in Dispose(bool disposing) above. // Dispose(false); // } /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> /// <remarks>This code added to correctly implement the disposable pattern.</remarks> public void Dispose() { // RollbarLogger type supports both paradigms: singleton-like (via RollbarLocator) and // multiple disposable instances (via RollbarFactory). // Here we want to make sure that the singleton instance is never disposed: Assumption.AssertTrue(!this.IsSingleton, nameof(this.IsSingleton)); // Do not change this code. Put cleanup code in Dispose(bool disposing) above. Dispose(true); // TODO: uncomment the following line if the finalizer is overridden above. // GC.SuppressFinalize(this); }
/// <summary> /// Registers the specified queue. /// </summary> /// <param name="queue">The queue.</param> internal void Register(PayloadQueue queue) { lock (this._syncLock) { Assumption.AssertTrue(!this._allQueues.Contains(queue), nameof(queue)); this._allQueues.Add(queue); this.IndexByToken(queue); queue.Logger.Config.Reconfigured += Config_Reconfigured; Debug.WriteLine(this.GetType().Name + ": Registered a queue. Total queues count: " + this._allQueues.Count + "."); } }
/// <summary> /// Initializes a new instance of the <see cref="RollbarLoggerProvider" /> class. /// </summary> /// <param name="configuration">The configuration.</param> /// <param name="options">The options.</param> /// <param name="httpContextAccessor">The HTTP context accessor.</param> public RollbarLoggerProvider( IConfiguration configuration , IOptions <NetPlatformExtensions.RollbarOptions> options , IHttpContextAccessor?httpContextAccessor ) : base(configuration, options) { Assumption.AssertNotNull(configuration, nameof(configuration)); Assumption.AssertNotNull(options, nameof(options)); Assumption.AssertTrue(this._rollbarInfrastructureConfig != null || this._rollbarLoggerConfig != null, "configuration"); this._httpContextAccessor = httpContextAccessor; }
/// <summary> /// Unregisters the specified queue. /// </summary> /// <param name="queue">The queue.</param> internal void Unregister(PayloadQueue queue) { lock (this._syncLock) { Assumption.AssertTrue(!queue.Logger.IsSingleton, nameof(queue.Logger.IsSingleton)); Assumption.AssertTrue(this._allQueues.Contains(queue), nameof(queue)); this.DropIndexByToken(queue); this._allQueues.Remove(queue); queue.Logger.Config.Reconfigured -= Config_Reconfigured; Debug.WriteLine(this.GetType().Name + ": Unregistered a queue. Total queues count: " + this._allQueues.Count + "."); } }
/// <summary> /// Gets the static field value. /// </summary> /// <typeparam name="TFieldDataType">The type of the field data type.</typeparam> /// <param name="staticField">The static field.</param> /// <returns></returns> public static TFieldDataType?GetStaticFieldValue <TFieldDataType>(FieldInfo staticField) { Assumption.AssertTrue(staticField.IsStatic, nameof(staticField.IsStatic)); object?valueObject = staticField.GetValue(null); if (valueObject != null) { TFieldDataType result = (TFieldDataType)valueObject; return(result); } return(default);
/// <summary> /// Registers the specified queue. /// </summary> /// <param name="queue">The queue.</param> internal void Register(PayloadQueue queue) { lock (this._syncLock) { Assumption.AssertTrue(!this._allQueues.Contains(queue), nameof(queue)); this._allQueues.Add(queue); this.IndexByToken(queue); ((RollbarConfig)queue.Logger.Config).Reconfigured += Config_Reconfigured; // The following debug line causes stack overflow when RollbarTraceListener is activated: Debug.WriteLineIf(RollbarTraceListener.InstanceCount == 0, this.GetType().Name + ": Registered a queue. Total queues count: " + this._allQueues.Count + "."); } }
/// <summary> /// Posts the specified deployment asynchronously. /// </summary> /// <param name="deployment">The deployment.</param> /// <returns></returns> public async Task PostAsync(IDeployment deployment) { Assumption.AssertNotNull(this._config, nameof(this._config)); Assumption.AssertNotNullOrWhiteSpace(this._config.AccessToken, nameof(this._config.AccessToken)); Assumption.AssertFalse(string.IsNullOrWhiteSpace(deployment.Environment) && string.IsNullOrWhiteSpace(this._config.Environment), nameof(deployment.Environment)); Assumption.AssertNotNullOrWhiteSpace(deployment.Revision, nameof(deployment.Revision)); Assumption.AssertLessThan( deployment.Environment.Length, 256, nameof(deployment.Environment.Length) ); Assumption.AssertTrue( deployment.LocalUsername == null || deployment.LocalUsername.Length < 256, nameof(deployment.LocalUsername) ); Assumption.AssertTrue( deployment.Comment == null || StringUtility.CalculateExactEncodingBytes(deployment.Comment, Encoding.UTF8) <= (62 * 1024), nameof(deployment.Comment) ); var uri = new Uri(this._config.EndPoint + RollbarDeployClient.deployApiPath); var parameters = new Dictionary <string, string> { { "access_token", this._config.AccessToken }, { "environment", (!string.IsNullOrWhiteSpace(deployment.Environment)) ? deployment.Environment : this._config.Environment }, { "revision", deployment.Revision }, { "rollbar_username", deployment.RollbarUsername }, { "local_username", deployment.LocalUsername }, { "comment", deployment.Comment }, }; var httpContent = new FormUrlEncodedContent(parameters); var httpClient = ProvideHttpClient(); var postResponse = await httpClient.PostAsync(uri, httpContent); if (postResponse.IsSuccessStatusCode) { string reply = await postResponse.Content.ReadAsStringAsync(); } else { postResponse.EnsureSuccessStatusCode(); } this.Release(httpClient); return; }
/// <summary> /// Unregisters the specified queue. /// </summary> /// <param name="queue">The queue.</param> private void Unregister(PayloadQueue queue) { if (queue.Logger == RollbarLocator.RollbarInstance.Logger) { return; // we do not want to unregister the singleton's queue. } lock (this._syncLock) { Assumption.AssertNotNull(this._config, nameof(this._config)); Assumption.AssertTrue(this._allQueues.Contains(queue), nameof(queue)); this.DropIndexByToken(queue); this._allQueues.Remove(queue); ((RollbarLoggerConfig)queue.Logger.Config).Reconfigured -= LoggerConfig_Reconfigured; Debug.WriteLine(this.GetType().Name + ": Unregistered a queue. Total queues count: " + this._allQueues.Count + "."); } }
private static IConfiguration LoadAppSettings(string folderPath, string appSettingsFileName) { Assumption.AssertTrue( Directory.Exists(folderPath), nameof(folderPath) ); Assumption.AssertTrue( File.Exists(Path.Combine(folderPath, appSettingsFileName)), nameof(appSettingsFileName) ); IConfiguration appConfiguration = new ConfigurationBuilder() .SetBasePath(folderPath) .AddJsonFile(appSettingsFileName) .Build(); return(appConfiguration); }
public HttpClient ProvideHttpClient(string proxySettings) { if (this._httpClient != null) { Assumption.AssertTrue( (string.IsNullOrWhiteSpace(proxySettings) && string.IsNullOrWhiteSpace(this._proxySettings)) || (string.Compare(proxySettings, this._proxySettings, true) == 0) , nameof(proxySettings) ); // reuse what is already there: return(this._httpClient); } // create new instance: this._proxySettings = proxySettings; this._httpClient = HttpClientUtil.CreateHttpClient(proxySettings); return(this._httpClient); }
/// <summary> /// Initializes a new instance of the <see cref="Classification"/> class. /// </summary> /// <param name="classifiers">The classifiers.</param> protected Classification(IEnumerable <Classifier> classifiers) { if (classifiers == null) { this._classifiers = new HashSet <Classifier>(); this._classifierTypes = new HashSet <Type>(); } else { Assumption.AssertTrue(classifiers.Count() == classifiers.Distinct().Count(), nameof(classifiers)); this._classifiers = new HashSet <Classifier>(classifiers); var classifierTypes = this._classifiers.Select(i => i.ClassifierObject.GetType()).ToList(); this._classifierTypes = new HashSet <Type>(classifierTypes); Assumption.AssertEqual(this._classifierTypes.Count, this._classifiers.Count, nameof(this._classifierTypes.Count)); } this.ID = this.GenerateID(this._classifiers); }
/// <summary> /// Truncates the specified input. /// </summary> /// <param name="input">The input.</param> /// <param name="encoding">The encoding.</param> /// <param name="encodedBytesLimit">The encoded bytes limit.</param> /// <returns></returns> public static string?Truncate(string?input, Encoding encoding, int encodedBytesLimit) { if (input == null) { return(input); //nothing to truncate... } byte[] inputEncodedBytes = encoding.GetBytes(input); Assumption.AssertEqual(inputEncodedBytes.Length, encoding.GetByteCount(input), nameof(inputEncodedBytes.Length)); if (inputEncodedBytes.Length <= encodedBytesLimit) { return(input); //nothing to truncate... } int truncationIndicatorTotalBytes = encoding.GetByteCount(truncationIndicator); int totalBytes = encodedBytesLimit - truncationIndicatorTotalBytes; if (totalBytes < 0) { totalBytes = 0; } string truncatedInput = encoding.GetString(inputEncodedBytes, 0, totalBytes); if ((totalBytes > 0) && (truncatedInput[truncatedInput.Length - 1] != input[truncatedInput.Length - 1]) ) { truncatedInput = truncatedInput.Substring(0, truncatedInput.Length - 1); } truncatedInput += truncationIndicator; Assumption.AssertTrue(encoding.GetByteCount( truncatedInput) <= encodedBytesLimit || encodedBytesLimit < truncationIndicatorTotalBytes, nameof(truncatedInput) ); return(truncatedInput); }
/// <summary> /// Registers the specified queue. /// </summary> /// <param name="queue">The queue.</param> internal void Register(PayloadQueue queue) { lock (this._syncLock) { Assumption.AssertTrue(!this._allQueues.Contains(queue), nameof(queue)); this._allQueues.Add(queue); this.IndexByToken(queue); this._useLocalPayloadStore |= queue.Logger.Config.EnableLocalPayloadStore; if (this._useLocalPayloadStore && this._storeContext == null) { Debug.WriteLine(this.GetType().Name + ": Initializing StoreContext from: " + nameof(this.Register) + "..."); this._storeContext = new StoreContext(); this._storeContext.MakeSureDatabaseExistsAndReady(); Debug.WriteLine(this.GetType().Name + ": Initialized StoreContext from: " + nameof(this.Register) + "."); } ((RollbarConfig)queue.Logger.Config).Reconfigured += Config_Reconfigured; // The following debug line causes stack overflow when RollbarTraceListener is activated: Debug.WriteLineIf(RollbarTraceListener.InstanceCount == 0, this.GetType().Name + ": Registered a queue. Total queues count: " + this._allQueues.Count + "."); } }
private void SendBody( Body body, ErrorLevel?level, IDictionary <string, object> custom, DateTime?timeoutAt = null, SemaphoreSlim signal = null ) { Assumption.AssertTrue(timeoutAt.HasValue == (signal != null), nameof(timeoutAt) + " or " + nameof(signal)); lock (this._syncRoot) { if (string.IsNullOrWhiteSpace(this._config.AccessToken) || this._config.Enabled == false ) { return; } var data = new Data(this._config.Environment, body) { Custom = custom, Level = level ?? this._config.LogLevel }; var payload = new Payload(this._config.AccessToken, data, timeoutAt, signal); payload.Data.GuidUuid = Guid.NewGuid(); payload.Data.Person = this._config.Person; if (this._config.Server != null) { payload.Data.Server = this._config.Server; } try { if (this._config.CheckIgnore != null && this._config.CheckIgnore.Invoke(payload) ) { return; } } catch (System.Exception ex) { OnRollbarEvent(new InternalErrorEventArgs(this._config, payload, ex, "While check-ignoring a payload...")); } try { this._config.Transform?.Invoke(payload); } catch (System.Exception ex) { OnRollbarEvent(new InternalErrorEventArgs(this._config, payload, ex, "While transforming a payload...")); } try { this._config.Truncate?.Invoke(payload); } catch (System.Exception ex) { OnRollbarEvent(new InternalErrorEventArgs(this._config, payload, ex, "While truncating a payload...")); } this._payloadQueue.Enqueue(payload); return; } }
public object?this[string key] { get { if (this._keyedValues.TryGetValue(key, out var result)) { return(result); } var concreteDtoMetadata = metadataByDerivedType[this.GetType()]; if (concreteDtoMetadata.ReservedPropertyInfoByReservedKey == null) { return(null); } if (concreteDtoMetadata .ReservedPropertyInfoByReservedKey .TryGetValue(key, out var reservedPropertyInfo) && reservedPropertyInfo.PropertyType.IsValueType ) { return(Activator.CreateInstance(reservedPropertyInfo.PropertyType)); } return(null); } set { bool isReservedProperty = this._metadata?.ReservedPropertyInfoByReservedKey?.Keys.Contains(key) ?? false; Assumption.AssertTrue( !this._keyedValues.ContainsKey(key) || // no such key preset yet this._keyedValues[key] == null || // OR its not initialized yet value != null || // OR no-null value !isReservedProperty, // OR not about reserved property/key "conditional " + nameof(value) + " assessment" ); var lowCaseKey = key.ToLower(); var concreteDtoMetadata = metadataByDerivedType[this.GetType()]; if (concreteDtoMetadata.ReservedPropertyInfoByReservedKey != null && concreteDtoMetadata .ReservedPropertyInfoByReservedKey .TryGetValue(key, out PropertyInfo? reservedPropertyInfo)) { var reservedPropertyType = reservedPropertyInfo.PropertyType; var valueType = value?.GetType(); if (valueType != null) { Assumption.AssertTrue( //we are not dealing with a reserved property, hence, anything works: !(concreteDtoMetadata.ReservedPropertyInfoByReservedKey.ContainsKey(key) || concreteDtoMetadata.ReservedPropertyInfoByReservedKey.ContainsKey(lowCaseKey)) //OR we are dealing with a reserved property and the value and its type should make sense: || value == null || reservedPropertyType == valueType || (reservedPropertyType.IsInterface && ReflectionUtility.DoesTypeImplementInterface(valueType, reservedPropertyType)) || (reservedPropertyType.IsGenericType && // dealing with nullable type reservedPropertyType.GenericTypeArguments.Length == 1 && reservedPropertyType.GenericTypeArguments[0] == valueType) || valueType.IsSubclassOf(reservedPropertyType), nameof(value) ); } } if (concreteDtoMetadata.ReservedPropertyInfoByReservedKey != null && concreteDtoMetadata.ReservedPropertyInfoByReservedKey.ContainsKey(lowCaseKey)) { // we are setting a reserved key when calling Bind(...) on an IConfigurationSection // that treats this instance of ExtendableDtoBase as a dictionary while binding to the targeted deserialization object: this._keyedValues[lowCaseKey] = value; } else { this._keyedValues[key] = value; } } }