private void CreateSpinXElement(XElement element) { if (!string.IsNullOrEmpty(Type)) { element.SetAttributeValue("type", Type); } if (TransactionId != 0) { element.SetAttributeValue("tid", Convert.ToString(TransactionId)); } if (null != CollapsePosition && !CollapsePosition.Any()) { element.SetAttributeValue("finish", "true"); } element.SetAttributeValue( "bet", SpinBet == null ? 0m.ToCustomString() : SpinBet.LineBet.ToCustomString()); element.SetAttributeValue("lines", SpinBet == null ? "0" : Convert.ToString(SpinBet.Lines)); element.SetAttributeValue( "multiplier", SpinBet == null ? "0" : Convert.ToString(SpinBet.Multiplier)); element.SetAttributeValue( "totalbet", SpinBet == null ? 0m.ToCustomString() : SpinBet.TotalBet.ToCustomString()); element.SetAttributeValue("ts", DateTimeUtc.ToUnixTimeStamp()); }
public void OnCreateUser_Should_Emit_UserCreatedEvent() { Given(aggregate => { }); var fullname = Fullname.Create(Faker.Name.FirstName(), Faker.Name.LastName()); var email = Email.Create($"{Faker.Random.Word()}@example.com"); var password = Password.Create(Faker.Random.Word()); var start = DateTimeUtc.Now(); When(aggregate => { aggregate.Create( fullname, email, password); }); var end = DateTimeUtc.Now(); Then(aggregate => { aggregate.Fullname.Should().Be(fullname); aggregate.Email.Should().Be(email); aggregate.Password.Should().Be(password); }); Then <UserCreatedEvent>((aggregate, @event) => { @event.Firstname.Should().Be(fullname.Firstname); @event.Lastname.Should().Be(fullname.Lastname); @event.Email.Should().Be(email.ToString()); @event.Password.Should().Be(password.ToString()); @event.CreatedOn.Should().NotBe(default);
internal static string BuildTooltip(XElement thumbElement) { var tooltip = new StringBuilder(200); var titleElement = thumbElement.Element("title"); if (titleElement != null) { tooltip.Append(Properties.Resources.NiconicoInfoText1); tooltip.Append(titleElement.Value); tooltip.AppendLine(); } var lengthElement = thumbElement.Element("length"); if (lengthElement != null) { tooltip.Append(Properties.Resources.NiconicoInfoText2); tooltip.Append(lengthElement.Value); tooltip.AppendLine(); } var firstRetrieveElement = thumbElement.Element("first_retrieve"); if (firstRetrieveElement != null && DateTimeUtc.TryParse(firstRetrieveElement.Value, DateTimeFormatInfo.InvariantInfo, out var firstRetrieveDate)) { tooltip.Append(Properties.Resources.NiconicoInfoText3); tooltip.Append(firstRetrieveDate.ToLocalTimeString()); tooltip.AppendLine(); } var viewCounterElement = thumbElement.Element("view_counter"); if (viewCounterElement != null) { tooltip.Append(Properties.Resources.NiconicoInfoText4); tooltip.Append(viewCounterElement.Value); tooltip.AppendLine(); } var commentNumElement = thumbElement.Element("comment_num"); if (commentNumElement != null) { tooltip.Append(Properties.Resources.NiconicoInfoText5); tooltip.Append(commentNumElement.Value); tooltip.AppendLine(); } var mylistCounterElement = thumbElement.Element("mylist_counter"); if (mylistCounterElement != null) { tooltip.Append(Properties.Resources.NiconicoInfoText6); tooltip.Append(mylistCounterElement.Value); tooltip.AppendLine(); } return(tooltip.ToString()); }
private void WriteSpinElement(XmlWriter writer) { if (!string.IsNullOrEmpty(Type)) { writer.WriteAttributeString("type", Type); } if (TransactionId != 0) { writer.WriteAttributeString("tid", Convert.ToString(TransactionId)); } if (null != CollapsePosition && !CollapsePosition.Any()) { writer.WriteAttributeString("finish", "true"); } writer.WriteAttributeString( "bet", SpinBet == null ? 0m.ToCustomString() : SpinBet.LineBet.ToCustomString()); writer.WriteAttributeString("lines", SpinBet == null ? "0" : Convert.ToString(SpinBet.Lines)); writer.WriteAttributeString( "multiplier", SpinBet == null ? "0" : Convert.ToString(SpinBet.Multiplier)); writer.WriteAttributeString( "totalbet", SpinBet == null ? 0m.ToCustomString() : SpinBet.TotalBet.ToCustomString()); writer.WriteAttributeString("ts", Convert.ToString(DateTimeUtc.ToUnixTimeStamp())); }
/// <summary> /// タイムラインに追加された発言件数を反映し、タイムラインの流速を更新します /// </summary> private void UpdateTimelineSpeed(DateTimeUtc postCreatedAt) { var now = DateTimeUtc.Now; // 1 時間以上前の時刻は追加しない var oneHour = TimeSpan.FromHours(1); if (now - postCreatedAt > oneHour) { return; } this.tweetsTimestamps.AddOrUpdate(postCreatedAt, 1, (k, v) => v + 1); var removeKeys = new List <DateTimeUtc>(); var tweetsInWindow = 0; foreach (var(timestamp, count) in this.tweetsTimestamps) { if (now - timestamp > oneHour) { removeKeys.Add(timestamp); } else { tweetsInWindow += count; } } Interlocked.Exchange(ref this.tweetsPerHour, tweetsInWindow); foreach (var key in removeKeys) { this.tweetsTimestamps.TryRemove(key, out var _); } }
public LogEntry(LogLevel logLevel, DateTimeUtc timestamp, string summary, string detail) { this.LogLevel = logLevel; this.Timestamp = timestamp; this.Summary = summary; this.Detail = detail; }
public ApiLimit(int limitCount, int limitRemain, DateTimeUtc resetDate, DateTimeUtc updatedAt) { this.AccessLimitCount = limitCount; this.AccessLimitRemain = limitRemain; this.AccessLimitResetDate = resetDate; this.UpdatedAt = updatedAt; }
private static HistoryData HW(Quality quality, double @value, DateTimeUtc timeWrite, TagDef tagDef) { return(new HistoryData( tagDef, new TagData(quality, DateTimeUtc.Now, value), timeWrite, HistoryWriterKind.InsertUpdate)); }
private static HistoryData HW(Quality quality, DataDriverEvent @value, DateTimeUtc timeWrite, TagDef tagDef) { return(new HistoryData( tagDef, new TagData(quality, DateTimeUtc.Now, TagValue.FromObject(DataType.Structured, value)), timeWrite, HistoryWriterKind.Insert)); }
protected void Emit(IDomainEvent @event) { if (_unCommittedEvents.Any(e => e.EventId == @event.EventId)) { return; } @event.SetProperty(nameof(@event.CreatedOn), DateTimeUtc.Now().Value); Apply(@event); _unCommittedEvents.Add(@event); }
public void DateTimeUtc_OriginalTime() { var dateTimeConverter = new DateTimeUtc(madisonWisconsin); var solarTime = new DateTime(2020, 2, 3, 10, 18, 54); var result = dateTimeConverter.SolarTimeToOriginalTime(solarTime); Assert.AreEqual(solarTime.Date, result.Date); Assert.AreEqual(16, result.Hour); var remainderMinutesAndSeconds = result.Minute + result.Second / 60.0; Assert.AreEqual(30, remainderMinutesAndSeconds, 0.5); }
public void DateTimeUtc_LocalTime() { var dateTimeConverter = new DateTimeUtc(madisonWisconsin); var originalTime = new DateTime(2020, 2, 3, 16, 30, 0); var result = dateTimeConverter.OriginalTimeToSolarTime(originalTime); Assert.AreEqual(originalTime.Date, result.Date); Assert.AreEqual(10, result.Hour); var remainderMinutesAndSeconds = result.Minute + result.Second / 60.0; Assert.AreEqual(19, remainderMinutesAndSeconds, 0.5); }
public async Task UpdateAccessTokenIfExpired() { if (this.AccessToken != null && this.RefreshAccessTokenAt > DateTimeUtc.Now) { return; } var(accessToken, expiresIn) = await this.GetAccessTokenAsync() .ConfigureAwait(false); this.AccessToken = accessToken; // アクセストークンの実際の有効期限より 30 秒早めに失効として扱う this.RefreshAccessTokenAt = DateTimeUtc.Now + expiresIn - TimeSpan.FromSeconds(30); }
internal static ApiLimit ParseRateLimit(IDictionary <string, string> header, string prefix) { var limitCount = (int?)ParseHeaderValue(header, prefix + "Limit"); var limitRemain = (int?)ParseHeaderValue(header, prefix + "Remaining"); var limitReset = ParseHeaderValue(header, prefix + "Reset"); if (limitCount == null || limitRemain == null || limitReset == null) { return(null); } var limitResetDate = DateTimeUtc.FromUnixTime(limitReset.Value); return(new ApiLimit(limitCount.Value, limitRemain.Value, limitResetDate)); }
public void UpdateFromJson(TwitterRateLimits json) { var rateLimits = from res in json.Resources from item in res.Value select( EndpointName : item.Key, Limit : new ApiLimit( item.Value.Limit, item.Value.Remaining, DateTimeUtc.FromUnixTime(item.Value.Reset) ) ); this.AccessLimit.AddAll(rateLimits.ToDictionary(x => x.EndpointName, x => x.Limit)); }
internal IEnumerable <DateTimeZone> GetHoles( TypeInc typeInc, DateTimeZone fromTime, int depth, DateTimeUtc deepSyncTime, TagDef[] tagsWatch) { Discrete disc; int discVal; GetDiscrette(typeInc, out disc, out discVal); DateTimeZone beginTime = RequestParam.GetFromSync(() => fromTime, true, disc, discVal); var holes = driver.Storage.ReadHoles( RequestParam.HolesMode, beginTime, depth - 1, deepSyncTime, tagsWatch); this.driver.Log.Trace.Info(2, SR.ReadHoles, fromTime, depth, deepSyncTime, beginTime, holes.Count()); return(holes); }
public OperationResult TryReadDateTime(IIODriverClient channel, int address, string psw, TimeZoneMap zone, out DateTimeUtc response, out int timeTwoSidePathMsec) { OperationResult result = OperationResult.Bad; response = DateTimeUtc.MinValue; timeTwoSidePathMsec = 0; byte[] send = CreateRequest(address, Codes.CODE_READ_DATETIME, psw); result = WaitRequest(channel); if (!result.IsGood) { return(result); } var span = SpanSnapshot.Now; result = WriteReadCheck(channel, nRepeatGlobal, send, out byte[] answer); timeTwoSidePathMsec = (int)span.DiffNowMsec(); if (!result.IsGood) { return(result); } try { response = ParseDateTime(answer, zone); } catch (Exception e) { result = OperationResult.From(e); } return(result); }
/// <summary> /// Чтение приращений (показаний) /// </summary> /// <param name="fromTime"></param> /// <param name="typeQuery"></param> /// <param name="typeInc"></param> /// <param name="aplus"></param> /// <param name="aminus"></param> /// <param name="rplus"></param> /// <param name="rminus"></param> /// <param name="depth"></param> /// <param name="deepSyncTime"></param> /// <param name="tariff"> /// Добавлена поддержка чтения тарифов для показаний, т.к. эту величину нельзя расчитать. /// </param> static internal void ReadInc( QueryInfo info, DateTimeZone fromTime, TypeQuery typeQuery, TypeInc typeInc, TagDef aplus, TagDef aminus, TagDef rplus, TagDef rminus, int depth, DateTimeUtc deepSyncTime, ETariff tariff = ETariff.NoTariff) { //Если в гране нет данных то дальше этой даты записываем что нельзя востонавить bool fillBadNoRestore = false; int itemNum = 0; OperationResult oper = new OperationResult(Quality.Bad); var holes = info.GetHoles(typeInc, fromTime, depth, deepSyncTime, new[] { aplus }); var reversedHoles = holes.Reverse(); foreach (var item in reversedHoles) { itemNum++; Energy read = null; OperationResult res = OperationResult.Bad; if (fillBadNoRestore) { read = new Energy(0, 0, 0, 0); oper = new OperationResult(Quality.BadNoRestore); } else if (info.Session.BeginOperation()) { if (DataBusSetting.StubData) //STUBDATA-> { read = new Energy(StubUtil.Int32(500), StubUtil.Int32(600), StubUtil.Int32(700), StubUtil.Int32(800)); oper = new OperationResult(Quality.Good); } else { switch (typeQuery) { #region (case TypeQuery.SlicesEnergy:) case TypeQuery.SlicesEnergy: if (!info.IsHalfHourInterval) { oper = new OperationResult(Quality.Bad, "HalfHour Interval is incorrect!"); } else { // только для версий СЕ102 S7, R8, CE301M S31, R33 // версии CE102 S6, R5 не поддерживают архив получасов oper = info.Request.TryReadSlicesEnergy( info.DataBus, info.Cs.Psw, info.Session.TimeDevice, SlicesQuery.From(item, info.Cs.Address), out read); read.Calc(info.DeviceKoef); } break; #endregion #region (case TypeQuery.Counter:) case TypeQuery.Counter: oper = info.Request.TryReadCounter( info.DataBus, info.Cs.Psw, typeInc, RequestIndex.From(item, typeInc, info.Cs.Address, true), tariff, out read); read.Calc(info.DeviceKoef); break; #endregion /*#region (case TypeQuery.Power3min:) * case TypeQuery.Power3min: * AvPowerIndex pi; * oper = info.Request.TryReadAvPower3min( * info.DataBus, * info.Session.TimeDevice, * info.Session.Zone, * RequestIndex.From(item, typeInc, info.Cs.Address, false), * item, * out pi); * if (oper.IsGood) * read = pi.Power.ToEnergy(20); * break; #endregion*/ } //Может возникать ситуация когда на компе уже наступило время опроса а на счетчике нет и будет возвращен блок поврежден //TODO if ((itemNum < 3) && (oper.Quality == Quality.BadNoRestore)) oper.Quality = Quality.Bad; } /*if ((!oper.IsGood) && (oper.Code == 2)) * { * if (info.Session.OpenData.NewDevice != ChangeDeviceInfo.None) * info.LogWarn(SR.NOT_PARAM, info.DisplayName, aplus.AccountKind, aplus.Discrete, aplus.DiscreteValue); * info.Session.EndOperation(OperationResult.Good); * break; //Неизвестная функция не подерживаемая версией устройства * }*/ info.Session.EndOperation(oper); if (!oper.IsGood) { read = new Energy(0, 0, 0, 0); info.DataBus.DiscardInBuffer(); } if (oper.Quality == Quality.BadNoRestore) { fillBadNoRestore = true; //заполним все полохими не востанавливаемыми } } else { break; } info.Storage.WriteTagsValue( HW(oper.Quality, read.Aplus, item, aplus), HW(Quality.Bad, read.Aminus, item, aminus), HW(Quality.Bad, read.Rplus, item, rplus), HW(Quality.Bad, read.Rminus, item, rminus)); if (info.Log.Trace.IsOn(2)) { var sb = new StringBuilder(); sb.AppendFormat("Read from [{0}] {1} {2}", item, typeInc, oper.Quality); if (typeQuery != TypeQuery.SlicesEnergy) { sb.Append(" " + typeQuery); } if (!oper.IsGood) { sb.AppendFormat(". Error: {0}", oper.ErrorMsg); info.Log.Trace.Error(2, sb.ToString()); } else { sb.AppendFormat(". A+: {0}, A-: {1}, R+: {2}, R-: {3}", read.Aplus, read.Aminus, read.Rplus, read.Rminus); info.Log.Trace.Info(2, sb.ToString()); } } } }
public override TestResult Test(TestRequestDataDrv request) { TestResult result = new TestResult(); var drvSetting = request.GetDriverSetting(() => new DriverSetting()); var cs = request.GetContentSetting <EmeraContentSetting>(() => new EmeraContentSetting()); EmeraRequest emera = new EmeraRequest(this, drvSetting, ReadTimeOutRequestMSec()); //var sr = new Def.ShortRequest(cs.Address); if ((request.TestLevel == TestLevel.Ping) || (request.TestLevel == TestLevel.Search)) { DateTimeUtc dateTimeUtc; int timeTwoSidePathMsec; if (!DataBusSetting.StubData) { var readRes = emera.TryReadDateTime(this.Channel, cs.Address, cs.Psw, TimeZoneMap.Local, out dateTimeUtc, out timeTwoSidePathMsec); if (!readRes.IsGood) { result.Add(new TestDriverError(false, "Error Connect. {0}", readRes.ErrorMsg)); } } } else if (request.TestLevel == TestLevel.Full) { DateTimeUtc dateTimeUtcPrb = DateTimeUtc.MinValue; int timeTwoSidePathMsec; if (!OneTest(SR.Test_DT, request, result, () => { var res = emera.TryReadDateTime(this.Channel, cs.Address, cs.Psw, TimeZoneMap.Local, out dateTimeUtcPrb, out timeTwoSidePathMsec); return(new MsgTest(res, res.IsGood ? dateTimeUtcPrb.ToLocal().ToString() : string.Empty)); })) { return(result); } TimeSpan diffTime = DateTimeUtc.Now - dateTimeUtcPrb; string sn = string.Empty; if (!OneTest(SR.Test_SN, request, result, () => { var res = emera.TryReadSerialNumber(this.Channel, cs.Address, cs.Psw, out sn); return(new MsgTest(res, res.IsGood ? sn : string.Empty)); })) { return(result); } string deviceConfiguration = string.Empty; if (!OneTest(SR.Test_SV, request, result, () => { var res = emera.TryReadDeviceConfiguration(this.Channel, cs.Address, cs.Psw, out deviceConfiguration, true); return(new MsgTest(res, res.IsGood ? deviceConfiguration.ToString() : string.Empty)); })) { return(result); } /*if (!OneTest(SR.Test_Error_Req, request, result, () => * { * Energy eRead; * var res = emera.TryReadSlicesEnergy(this.Channel, DeviceCompOn.Default, SlicesQuery.GetEmulError(sr.Address), TypeInfo.Imp, out eRead); * return new MsgTest(res, res.IsGood ? "" : "Ok"); * }, true)) return result;*/ result.Message = String.Format("Сер.Номер: {0}, Временной разрыв: {1} sec, Конфигурация: {2}", sn, (int)diffTime.TotalSeconds, deviceConfiguration); } return(result); }
public void WriteTags(StorageDataDriver storage, ElectroChannel eChannel, Quality quality, DateTimeUtc time) { var eid = new ElectroIMData(quality, time, this.InsActivePower.InsPowerPhase.Phase_A, this.InsActivePower.InsPowerPhase.Phase_B, this.InsActivePower.InsPowerPhase.Phase_C, this.InsReactivePower.InsPowerPhase.Phase_A, this.InsReactivePower.InsPowerPhase.Phase_B, this.InsReactivePower.InsPowerPhase.Phase_C, this.Voltage.Phase_A, this.Voltage.Phase_B, this.Voltage.Phase_C, this.Amperage.Phase_A, this.Amperage.Phase_B, this.Amperage.Phase_C, this.Frequency, this.PowerFactor.Phase_A, this.PowerFactor.Phase_B, this.PowerFactor.Phase_C); eid.WriteTags(eChannel); }
public LogEntry(DateTimeUtc timestamp, string summary) : this(LogLevel.Debug, timestamp, summary, summary) { }
public ApiLimit(int limitCount, int limitRemain, DateTimeUtc resetDate) : this(limitCount, limitRemain, resetDate, DateTimeUtc.Now) { }