using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Configuration; using System.Linq; using System.Text.RegularExpressions; using InfluxDB.Client.Core; namespace InfluxDB.Client.Writes { /// /// The setting for store data point: default values, threshold, ... /// public class PointSettings { private readonly SortedDictionary _defaultTags = new SortedDictionary(StringComparer.Ordinal); private static readonly Regex AppSettingsRegex = new Regex("^(\\${)(?.+)(})$", RegexOptions.ExplicitCapture | RegexOptions.Compiled | RegexOptions.CultureInvariant | RegexOptions.RightToLeft); private static readonly Regex EnvVariableRegex = new Regex("^(\\${env.)(?.+)(})$", RegexOptions.ExplicitCapture | RegexOptions.Compiled | RegexOptions.CultureInvariant | RegexOptions.RightToLeft); /// /// Default tags that will be use for writes by Point and POJO. /// public Dictionary DefaultTags { get => (Dictionary)GetDefaultTags(); set { Arguments.CheckNotNull(value, "DefaultTags"); _defaultTags.Clear(); foreach (var tag in value) { Arguments.CheckNotNull(tag.Key, "TagName"); _defaultTags[tag.Key] = tag.Value; } } } /// /// Add default tag. /// /// the tag name /// the tag value expression /// this public PointSettings AddDefaultTag(string key, string expression) { Arguments.CheckNotNull(key, "tagName"); _defaultTags[key] = expression; return this; } /// /// Get default tags with evaluated expressions. /// /// evaluated default tags internal IDictionary GetDefaultTags() { if (_defaultTags.Count == 0) { return ImmutableDictionary.Empty; } string Evaluation(string expression) { if (string.IsNullOrEmpty(expression)) { return null; } var matcher = EnvVariableRegex.Match(expression); if (matcher.Success) { return Environment.GetEnvironmentVariable(matcher.Groups["Value"].Value); } matcher = AppSettingsRegex.Match(expression); if (matcher.Success) { return ConfigurationManager.AppSettings[matcher.Groups["Value"].Value]; } return expression; } return _defaultTags .Select(it => new KeyValuePair(it.Key, Evaluation(it.Value))) .Where(it => !string.IsNullOrEmpty(it.Value)) .ToDictionary(it => it.Key, it => it.Value, StringComparer.Ordinal); } } }