示例#1
0
        public TagDetails(UtcTimestamp whenCreated, UserName createdBy, UtcTimestamp?whenUpdated, UserName?updatedBy)
        {
            WhenCreated = Guard.NotNull(whenCreated, nameof(whenCreated));
            CreatedBy   = Guard.NotNull(createdBy, nameof(createdBy));

            WhenUpdated = whenUpdated;
            UpdatedBy   = updatedBy;

            Guard.BothNullOrBothNotNull(whenUpdated, updatedBy);
        }
        private string SaveThumbnail(Image thumbnail, UtcTimestamp timestamp)
        {
            using var memoryStream = new MemoryStream(50 * 1024);

            thumbnail.Save(memoryStream, ImageFormat.Jpeg);

            string newFileName = FileUtils.GetRandomFileNameWithTimestamp(timestamp.Value, "_.jpg");

            var thumbFile = fileContainer.Create(memoryStream, new FileName(newFileName));

            return(thumbFile.Name);
        }
示例#3
0
        /// <summary>
        /// Returns the string representing the point in InfluxDB Line protocol
        /// </summary>
        /// <returns></returns>
        /// <see cref="https://influxdb.com/docs/v0.9/write_protocols/write_syntax.html"/>
        public string ConvertToInfluxLineProtocol()
        {
            if (Fields.Count == 0)
            {
                throw new InvalidOperationException("InfluxDB needs atleast one field in a line");
            }

            var line = new StringBuilder();

            line.AppendFormat("{0}", MeasurementName);

            if (Tags.Count > 0)
            {
                line.AppendFormat(",{0}", String.Join(",", Tags.Select(t => new StringBuilder().AppendFormat("{0}={1}", EscapeChars(t.Key), EscapeChars(t.Value)))));
            }

            var    tType = typeof(T);
            string fields;

            if (tType == typeof(string))
            {
                //string needs escaping, but = is allowed in value
                fields = String.Join(",", Fields.Select(v => new StringBuilder().AppendFormat("{0}=\"{1}\"", EscapeChars(v.Key), EscapeChars(v.Value.ToString(), false))));
            }
            else if (tType == typeof(int))
            {
                //int needs i suffix
                fields = String.Join(",", Fields.Select(v => new StringBuilder().AppendFormat("{0}={1}i", EscapeChars(v.Key), v.Value)));
            }
            else if (tType == typeof(bool))
            {
                //bool is okay with True or False
                fields = String.Join(",", Fields.Select(v => new StringBuilder().AppendFormat("{0}={1}", EscapeChars(v.Key), v.Value)));
            }
            else
            {
                ////double has to have a . as decimal seperator for Influx
                fields = String.Join(",", Fields.Select(v => new StringBuilder().AppendFormat("{0}={1}", EscapeChars(v.Key), String.Format(System.Globalization.CultureInfo.GetCultureInfo("en-US"), "{0}", v.Value))));
            }

            line.AppendFormat(" {0} {1}", fields, UtcTimestamp.ToEpoch(Precision));

            return(line.ToString());
        }
        //====== IThumbnailsMaker

        public ThumbnailMakerResult?TryMakeAndSaveThumbnail(IFileInfo fileInfo, UtcTimestamp timestamp)
        {
            Guard.NotNull(fileInfo, nameof(fileInfo));
            Guard.NotNull(timestamp, nameof(timestamp));

            try
            {
                using var stream     = fileInfo.CreateReadStream();
                using Image srcImage = Image.FromStream(stream);

                using Image thumbnail = imageResizer.Resize(srcImage, new Size(300, 300), true);

                string thumbFileName = SaveThumbnail(thumbnail, timestamp);

                return(new ThumbnailMakerResult(new FileName(thumbFileName), srcImage.Size));
            }
            catch
            {
                return(null); // TODO: error logging
            }
        }
 public AppUserDetails(AppUser user, EmailAddress?email, UtcTimestamp whenCreated)
 {
     User        = Guard.NotNull(user, nameof(user));
     Email       = email;
     WhenCreated = Guard.NotNull(whenCreated, nameof(whenCreated));
 }
示例#6
0
        public void ConvertToInfluxLineProtocol(StringBuilder line)

        {
            if (Fields.Count == 0)
            {
                throw new InvalidOperationException("InfluxDB needs atleast one field in a line");
            }
            if (String.IsNullOrWhiteSpace(MeasurementName))
            {
                throw new InvalidOperationException("InfluxDB needs a measurement name to accept a point");
            }


            line.AppendFormat("{0}", MeasurementName.EscapeChars(comma: true, space: true));

            if (Tags.Count > 0)
            {
                Tags.ToList().ForEach(t =>
                {
                    line.AppendFormat(",{0}={1}", t.Key.EscapeChars(comma: true, equalSign: true, space: true), t.Value.EscapeChars(comma: true, equalSign: true, space: true));
                });
            }

            var    tType = typeof(T);
            string fields;

            line.Append(" ");

            if (tType == typeof(string))
            {
                //string needs escaping, but = is allowed in value
                Fields.ToList().ForEach(v =>
                {
                    line.AppendFormat("{0}=\"{1}\",", v.Key.EscapeChars(comma: true, equalSign: true, space: true), v.Value.ToString().EscapeChars(doubleQuote: true));
                });
                line.Remove(line.Length - 1, 1);
            }
            else if (tType == typeof(long) || tType == typeof(int))
            {
                //int needs i suffix
                Fields.ToList().ForEach(v =>
                {
                    line.AppendFormat("{0}={1}i,", v.Key.EscapeChars(comma: true, equalSign: true, space: true), v.Value);
                });
                line.Remove(line.Length - 1, 1);
            }

            else if (tType == typeof(bool))
            {
                //bool is okay with True or False
                Fields.ToList().ForEach(v =>
                {
                    line.AppendFormat("{0}={1},", v.Key.EscapeChars(comma: true, equalSign: true, space: true), v.Value);
                });
                line.Remove(line.Length - 1, 1);
            }

            else if (tType == typeof(double))
            {
                //double has to have a . as decimal seperator for Influx
                Fields.ToList().ForEach(v =>
                {
                    line.AppendFormat("{0}={1},", v.Key.EscapeChars(comma: true, equalSign: true, space: true), String.Format(CultureInfo.GetCultureInfo("en-US"), "{0}", v.Value));
                });
                line.Remove(line.Length - 1, 1);
            }
            else if (typeof(IInfluxValueField).IsAssignableFrom(tType))
            {
                //fields = String.Join(",", Fields.Select(v => new StringBuilder().AppendFormat("{0}={1}", v.Key.EscapeChars(comma: true, equalSign: true, space: true), v.Value.ToString())));
                Fields.ToList().ForEach(v =>
                {
                    line.AppendFormat("{0}={1},", v.Key.EscapeChars(comma: true, equalSign: true, space: true), v.Value.ToString());
                });
                line.Remove(line.Length - 1, 1);
            }

            else
            {
                throw new ArgumentException(tType + " is not supported by this library at this point");
            }

            line.AppendFormat(" {0}", UtcTimestamp != DateTime.MinValue ? UtcTimestamp.ToEpoch(Precision) : DateTime.UtcNow.ToEpoch(Precision));
        }
示例#7
0
 public MySqlFunctionManager(bool allowFuncDefChange)
 {
     this.allowFuncDefChange                = allowFuncDefChange;
     parsingStrateg["CAST"]                 = FunctionParsingStrategy.Cast;
     parsingStrateg["POSITION"]             = FunctionParsingStrategy.Position;
     parsingStrateg["SUBSTR"]               = FunctionParsingStrategy.Substring;
     parsingStrateg["SUBSTRING"]            = FunctionParsingStrategy.Substring;
     parsingStrateg["TRIM"]                 = FunctionParsingStrategy.Trim;
     parsingStrateg["AVG"]                  = FunctionParsingStrategy.Avg;
     parsingStrateg["COUNT"]                = FunctionParsingStrategy.Count;
     parsingStrateg["GROUP_CONCAT"]         = FunctionParsingStrategy.GroupConcat;
     parsingStrateg["MAX"]                  = FunctionParsingStrategy.Max;
     parsingStrateg["MIN"]                  = FunctionParsingStrategy.Min;
     parsingStrateg["SUM"]                  = FunctionParsingStrategy.Sum;
     parsingStrateg["ROW"]                  = FunctionParsingStrategy.Row;
     parsingStrateg["CHAR"]                 = FunctionParsingStrategy.Char;
     parsingStrateg["CONVERT"]              = FunctionParsingStrategy.Convert;
     parsingStrateg["EXTRACT"]              = FunctionParsingStrategy.Extract;
     parsingStrateg["TIMESTAMPADD"]         = FunctionParsingStrategy.Timestampadd;
     parsingStrateg["TIMESTAMPDIFF"]        = FunctionParsingStrategy.Timestampdiff;
     parsingStrateg["GET_FORMAT"]           = FunctionParsingStrategy.GetFormat;
     functionPrototype["ABS"]               = new Abs(null);
     functionPrototype["ACOS"]              = new Acos(null);
     functionPrototype["ADDDATE"]           = new Adddate(null);
     functionPrototype["ADDTIME"]           = new Addtime(null);
     functionPrototype["AES_DECRYPT"]       = new AesDecrypt(null);
     functionPrototype["AES_ENCRYPT"]       = new AesEncrypt(null);
     functionPrototype["ANALYSE"]           = new Analyse(null);
     functionPrototype["ASCII"]             = new Ascii(null);
     functionPrototype["ASIN"]              = new Asin(null);
     functionPrototype["ATAN2"]             = new Atan2(null);
     functionPrototype["ATAN"]              = new Atan(null);
     functionPrototype["BENCHMARK"]         = new Benchmark(null);
     functionPrototype["BIN"]               = new Bin(null);
     functionPrototype["BIT_AND"]           = new BitAnd(null);
     functionPrototype["BIT_COUNT"]         = new BitCount(null);
     functionPrototype["BIT_LENGTH"]        = new BitLength(null);
     functionPrototype["BIT_OR"]            = new BitOR(null);
     functionPrototype["BIT_XOR"]           = new BitXor(null);
     functionPrototype["CEIL"]              = new Ceiling(null);
     functionPrototype["CEILING"]           = new Ceiling(null);
     functionPrototype["CHAR_LENGTH"]       = new CharLength(null);
     functionPrototype["CHARACTER_LENGTH"]  = new CharLength(null);
     functionPrototype["CHARSET"]           = new Charset(null);
     functionPrototype["COALESCE"]          = new Coalesce(null);
     functionPrototype["COERCIBILITY"]      = new Coercibility(null);
     functionPrototype["COLLATION"]         = new Collation(null);
     functionPrototype["COMPRESS"]          = new Compress(null);
     functionPrototype["CONCAT_WS"]         = new ConcatWs(null);
     functionPrototype["CONCAT"]            = new Concat(null);
     functionPrototype["CONNECTION_ID"]     = new ConnectionId(null);
     functionPrototype["CONV"]              = new Conv(null);
     functionPrototype["CONVERT_TZ"]        = new ConvertTz(null);
     functionPrototype["COS"]               = new Cos(null);
     functionPrototype["COT"]               = new Cot(null);
     functionPrototype["CRC32"]             = new Crc32(null);
     functionPrototype["CURDATE"]           = new Curdate();
     functionPrototype["CURRENT_DATE"]      = new Curdate();
     functionPrototype["CURRENT_TIME"]      = new Curtime();
     functionPrototype["CURTIME"]           = new Curtime();
     functionPrototype["CURRENT_TIMESTAMP"] = new Now();
     functionPrototype["CURRENT_USER"]      = new CurrentUser();
     functionPrototype["CURTIME"]           = new Curtime();
     functionPrototype["DATABASE"]          = new Database(null);
     functionPrototype["DATE_ADD"]          = new DateAdd(null);
     functionPrototype["DATE_FORMAT"]       = new DateFormat(null);
     functionPrototype["DATE_SUB"]          = new DateSub(null);
     functionPrototype["DATE"]              = new Date(null);
     functionPrototype["DATEDIFF"]          = new Datediff(null);
     functionPrototype["DAY"]               = new Dayofmonth(null);
     functionPrototype["DAYOFMONTH"]        = new Dayofmonth(null);
     functionPrototype["DAYNAME"]           = new Dayname(null);
     functionPrototype["DAYOFWEEK"]         = new Dayofweek(null);
     functionPrototype["DAYOFYEAR"]         = new Dayofyear(null);
     functionPrototype["DECODE"]            = new Decode(null);
     functionPrototype["DEFAULT"]           = new Default(null);
     functionPrototype["DEGREES"]           = new Degrees(null);
     functionPrototype["DES_DECRYPT"]       = new DesDecrypt(null);
     functionPrototype["DES_ENCRYPT"]       = new DesEncrypt(null);
     functionPrototype["ELT"]               = new Elt(null);
     functionPrototype["ENCODE"]            = new Encode(null);
     functionPrototype["ENCRYPT"]           = new Encrypt(null);
     functionPrototype["EXP"]               = new Exp(null);
     functionPrototype["EXPORT_SET"]        = new ExportSet(null);
     // functionPrototype.put("EXTRACT", new Extract(null));
     functionPrototype["EXTRACTVALUE"]  = new ExtractValue(null);
     functionPrototype["FIELD"]         = new Field(null);
     functionPrototype["FIND_IN_SET"]   = new FindInSet(null);
     functionPrototype["FLOOR"]         = new Floor(null);
     functionPrototype["FORMAT"]        = new Format(null);
     functionPrototype["FOUND_ROWS"]    = new FoundRows(null);
     functionPrototype["FROM_DAYS"]     = new FromDays(null);
     functionPrototype["FROM_UNIXTIME"] = new FromUnixtime(null);
     // functionPrototype.put("GET_FORMAT", new GetFormat(null));
     functionPrototype["GET_LOCK"]       = new GetLock(null);
     functionPrototype["GREATEST"]       = new Greatest(null);
     functionPrototype["HEX"]            = new Hex(null);
     functionPrototype["HOUR"]           = new Hour(null);
     functionPrototype["IF"]             = new IF(null);
     functionPrototype["IFNULL"]         = new IFNull(null);
     functionPrototype["INET_ATON"]      = new InetAton(null);
     functionPrototype["INET_NTOA"]      = new InetNtoa(null);
     functionPrototype["INSERT"]         = new Insert(null);
     functionPrototype["INSTR"]          = new Instr(null);
     functionPrototype["INTERVAL"]       = new Interval(null);
     functionPrototype["IS_FREE_LOCK"]   = new IsFreeLock(null);
     functionPrototype["IS_USED_LOCK"]   = new IsUsedLock(null);
     functionPrototype["ISNULL"]         = new IsNull(null);
     functionPrototype["LAST_DAY"]       = new LastDay(null);
     functionPrototype["LAST_INSERT_ID"] = new LastInsertId(null);
     functionPrototype["LCASE"]          = new Lower(null);
     functionPrototype["LEAST"]          = new Least(null);
     functionPrototype["LEFT"]           = new Left(null);
     functionPrototype["LENGTH"]         = new Length(null);
     functionPrototype["LN"]             = new Log(null);
     // Ln(X) equals Log(X)
     functionPrototype["LOAD_FILE"]       = new LoadFile(null);
     functionPrototype["LOCALTIME"]       = new Now();
     functionPrototype["LOCALTIMESTAMP"]  = new Now();
     functionPrototype["LOCATE"]          = new Locate(null);
     functionPrototype["LOG10"]           = new Log10(null);
     functionPrototype["LOG2"]            = new Log2(null);
     functionPrototype["LOG"]             = new Log(null);
     functionPrototype["LOWER"]           = new Lower(null);
     functionPrototype["LPAD"]            = new Lpad(null);
     functionPrototype["LTRIM"]           = new Ltrim(null);
     functionPrototype["MAKE_SET"]        = new MakeSet(null);
     functionPrototype["MAKEDATE"]        = new Makedate(null);
     functionPrototype["MAKETIME"]        = new Maketime(null);
     functionPrototype["MASTER_POS_WAIT"] = new MasterPosWait(null);
     functionPrototype["MD5"]             = new Md5(null);
     functionPrototype["MICROSECOND"]     = new Microsecond(null);
     functionPrototype["MID"]             = new Substring(null);
     functionPrototype["MINUTE"]          = new Minute(null);
     functionPrototype["MONTH"]           = new Month(null);
     functionPrototype["MONTHNAME"]       = new Monthname(null);
     functionPrototype["NAME_CONST"]      = new NameConst(null);
     functionPrototype["NOW"]             = new Now();
     functionPrototype["NULLIF"]          = new NullIF(null);
     functionPrototype["OCT"]             = new Oct(null);
     functionPrototype["OCTET_LENGTH"]    = new Length(null);
     functionPrototype["OLD_PASSWORD"]    = new OldPassword(null);
     functionPrototype["ORD"]             = new Ord(null);
     functionPrototype["PASSWORD"]        = new Password(null);
     functionPrototype["PERIOD_ADD"]      = new PeriodAdd(null);
     functionPrototype["PERIOD_DIFF"]     = new PeriodDiff(null);
     functionPrototype["PI"]              = new PI(null);
     functionPrototype["POW"]             = new Pow(null);
     functionPrototype["POWER"]           = new Pow(null);
     functionPrototype["QUARTER"]         = new Quarter(null);
     functionPrototype["QUOTE"]           = new Quote(null);
     functionPrototype["RADIANS"]         = new Radians(null);
     functionPrototype["RAND"]            = new Rand(null);
     functionPrototype["RELEASE_LOCK"]    = new ReleaseLock(null);
     functionPrototype["REPEAT"]          = new Repeat(null);
     functionPrototype["REPLACE"]         = new Replace(null);
     functionPrototype["REVERSE"]         = new Reverse(null);
     functionPrototype["RIGHT"]           = new Right(null);
     functionPrototype["ROUND"]           = new Round(null);
     functionPrototype["ROW_COUNT"]       = new RowCount(null);
     functionPrototype["RPAD"]            = new Rpad(null);
     functionPrototype["RTRIM"]           = new Rtrim(null);
     functionPrototype["SCHEMA"]          = new Database(null);
     functionPrototype["SEC_TO_TIME"]     = new SecToTime(null);
     functionPrototype["SECOND"]          = new Second(null);
     functionPrototype["SESSION_USER"]    = new User(null);
     functionPrototype["SHA1"]            = new Sha1(null);
     functionPrototype["SHA"]             = new Sha1(null);
     functionPrototype["SHA2"]            = new Sha2(null);
     functionPrototype["SIGN"]            = new Sign(null);
     functionPrototype["SIN"]             = new Sin(null);
     functionPrototype["SLEEP"]           = new Sleep(null);
     functionPrototype["SOUNDEX"]         = new Soundex(null);
     functionPrototype["SPACE"]           = new Space(null);
     functionPrototype["SQRT"]            = new Sqrt(null);
     functionPrototype["STD"]             = new Std(null);
     functionPrototype["STDDEV_POP"]      = new StdDevPop(null);
     functionPrototype["STDDEV_SAMP"]     = new StdDevSamp(null);
     functionPrototype["STDDEV"]          = new StdDev(null);
     functionPrototype["STR_TO_DATE"]     = new StrToDate(null);
     functionPrototype["STRCMP"]          = new Strcmp(null);
     functionPrototype["SUBDATE"]         = new Subdate(null);
     functionPrototype["SUBSTRING_INDEX"] = new SubstringIndex(null);
     functionPrototype["SUBTIME"]         = new Subtime(null);
     functionPrototype["SYSDATE"]         = new Sysdate(null);
     functionPrototype["SYSTEM_USER"]     = new User(null);
     functionPrototype["TAN"]             = new Tan(null);
     functionPrototype["TIME_FORMAT"]     = new TimeFormat(null);
     functionPrototype["TIME_TO_SEC"]     = new TimeToSec(null);
     functionPrototype["TIME"]            = new Time(null);
     functionPrototype["TIMEDIFF"]        = new Timediff(null);
     functionPrototype["TIMESTAMP"]       = new Timestamp(null);
     // functionPrototype.put("TIMESTAMPADD", new Timestampadd(null));
     // functionPrototype.put("TIMESTAMPDIFF", new Timestampdiff(null));
     functionPrototype["TO_DAYS"]             = new ToDays(null);
     functionPrototype["TO_SECONDS"]          = new ToSeconds(null);
     functionPrototype["TRUNCATE"]            = new Truncate(null);
     functionPrototype["UCASE"]               = new Upper(null);
     functionPrototype["UNCOMPRESS"]          = new Uncompress(null);
     functionPrototype["UNCOMPRESSED_LENGTH"] = new UncompressedLength(null);
     functionPrototype["UNHEX"]               = new Unhex(null);
     functionPrototype["UNIX_TIMESTAMP"]      = new UnixTimestamp(null);
     functionPrototype["UPDATEXML"]           = new UpdateXml(null);
     functionPrototype["UPPER"]               = new Upper(null);
     functionPrototype["USER"]          = new User(null);
     functionPrototype["UTC_DATE"]      = new UtcDate(null);
     functionPrototype["UTC_TIME"]      = new UtcTime(null);
     functionPrototype["UTC_TIMESTAMP"] = new UtcTimestamp(null);
     functionPrototype["UUID_SHORT"]    = new UuidShort(null);
     functionPrototype["UUID"]          = new Uuid(null);
     functionPrototype["VALUES"]        = new Values(null);
     functionPrototype["VAR_POP"]       = new VarPop(null);
     functionPrototype["VAR_SAMP"]      = new VarSamp(null);
     functionPrototype["VARIANCE"]      = new Variance(null);
     functionPrototype["VERSION"]       = new Version(null);
     functionPrototype["WEEK"]          = new Week(null);
     functionPrototype["WEEKDAY"]       = new Weekday(null);
     functionPrototype["WEEKOFYEAR"]    = new Weekofyear(null);
     functionPrototype["YEAR"]          = new Year(null);
     functionPrototype["YEARWEEK"]      = new Yearweek(null);
 }
示例#8
0
        public async Task <UploadId> Handle(UploadFilesCommand request, CancellationToken cancellationToken)
        {
            AppUserEntity?uploader = await context.Entities.AppUsers.FirstOrDefaultAsync(x => x.UserName == context.Requestor.UserName.Value);

            if (uploader is null)
            {
                throw new ArgumentException("Invalid requestor.");                     // todo: custom exception
            }
            UtcTimestamp startTimestamp = context.UtcNow;

            var tempFiles  = new List <FileEntity>();
            var duplicates = new List <string>();

            foreach (SourceFile sourceFile in request.Parameters.SourceFiles)
            {
                UtcTimestamp timestamp = context.UtcNow;

                Sha256Hash hash = sha256Generator.GenerateHash(sourceFile.Content);

                if (IsDuplicate(hash))
                {
                    duplicates.Add(sourceFile.OrginalFileName ?? "???");
                }
                else
                {
                    string newFileName = FileUtils.GetRandomFileNameWithTimestamp(timestamp.Value, sourceFile.OrginalFileName);

                    IFileInfo fileInfo = fileDatabase.SourceFiles.Create(sourceFile.Content, new FileName(newFileName));

                    ThumbnailMakerResult?thumbResult = thumbnailMaker.TryMakeAndSaveThumbnail(fileInfo, timestamp);

                    var fileEntity = new FileEntity
                    {
                        MimeType        = sourceFile.MimeType.Value,
                        FileName        = sourceFile.OrginalFileName,
                        UtcWhenAdded    = timestamp.Value,
                        SourceFileName  = newFileName,
                        SourceFileSize  = sourceFile.Content.Length,
                        Description     = null,
                        Title           = null,
                        Hash            = hash.ToHexString(),
                        PrimaryDateTime = null,

                        Image = new ImageEntity()
                        {
                            Width             = thumbResult?.OrginalImageSize.Width,
                            Height            = thumbResult?.OrginalImageSize.Height,
                            ThumbnailFileName = thumbResult?.ThumbnailFileName.Value,
                        },

                        Uploader = uploader
                    };

                    tempFiles.Add(fileEntity);
                }
            }

            var uploadEntity = new UploadEntity
            {
                Description  = request.Parameters.Description.Value,
                UtcWhenAdded = startTimestamp.Value,
                FileCount    = tempFiles.Count,
                TotalSize    = tempFiles.Select(x => x.SourceFileSize).Aggregate(0L, (a, b) => a + b),
                Uploader     = uploader
            };

            foreach (var file in tempFiles)
            {
                file.Upload = uploadEntity;
                // TODO: handle 0 files as error
            }

            context.Entities.Files.AddRange(tempFiles);

            await context.Entities.SaveChangesAsync();

            logger.Add($"New upload #{uploadEntity.Id}. Files added (except duplicates): {uploadEntity.FileCount}");

            return(new UploadId(uploadEntity.Id));
        }
示例#9
0
 public ActivityLogEntry(UserName userName, UtcTimestamp timestamp, string message)
 {
     UserName  = Guard.NotNull(userName, nameof(userName));
     Timestamp = Guard.NotNull(timestamp, nameof(timestamp));
     Message   = Guard.NotNull(message, nameof(message));
 }
示例#10
0
        /// <summary>
        /// Returns the string representing the point in InfluxDB Line protocol
        /// </summary>
        /// <returns></returns>
        /// <see cref="https://docs.influxdata.com/influxdb/v0.12/write_protocols/line/"/>
        public string ConvertToInfluxLineProtocol()
        {
            if (Fields.Count == 0)
            {
                throw new InvalidOperationException("InfluxDB needs atleast one field in a line");
            }
            if (String.IsNullOrWhiteSpace(MeasurementName))
            {
                throw new InvalidOperationException("InfluxDB needs a measurement name to accept a point");
            }

            var line = new StringBuilder();

            line.AppendFormat("{0}", MeasurementName);

            if (Tags.Count > 0)
            {
                line.AppendFormat(",{0}", String.Join(",", Tags.Select(t => new StringBuilder().AppendFormat("{0}={1}", t.Key.EscapeChars(), t.Value.EscapeChars()))));
            }

            var    tType = typeof(T);
            string fields;

            if (tType == typeof(string))
            {
                //string needs escaping, but = is allowed in value
                fields = String.Join(",", Fields.Select(v => new StringBuilder().AppendFormat("{0}=\"{1}\"", v.Key.EscapeChars(), v.Value.ToString().EscapeChars(false))));
            }
            else if (tType == typeof(long) || tType == typeof(int))
            {
                //int needs i suffix
                fields = String.Join(",", Fields.Select(v => new StringBuilder().AppendFormat("{0}={1}i", v.Key.EscapeChars(), v.Value)));
            }
            else if (tType == typeof(bool))
            {
                //bool is okay with True or False
                fields = String.Join(",", Fields.Select(v => new StringBuilder().AppendFormat("{0}={1}", v.Key.EscapeChars(), v.Value)));
            }
            else if (tType == typeof(double))
            {
                ////double has to have a . as decimal seperator for Influx
                fields = String.Join(",", Fields.Select(v => new StringBuilder().AppendFormat("{0}={1}", v.Key.EscapeChars(), String.Format(new CultureInfo("en-US"), "{0}", v.Value))));
            }
            else if (tType == typeof(InfluxValueField))
            {
                fields = String.Join(",", Fields.Select(v => new StringBuilder().AppendFormat("{0}={1}", v.Key.EscapeChars(), v.Value.ToString())));
            }
            else
            {
                throw new ArgumentException(tType + " is not supported by this library at this point");
            }

            line.AppendFormat(" {0} {1}", fields, UtcTimestamp != DateTime.MinValue ? UtcTimestamp.ToEpoch(Precision) : DateTime.UtcNow.ToEpoch(Precision));

            return(line.ToString());
        }