/// <inheritdoc/> public override SpanData ToSpanData() { if (!this.IsRecordingEvents) { throw new InvalidOperationException("Getting SpanData for a Span without RECORD_EVENTS option."); } var attributesSpanData = this.attributes == null?Attributes.Create(new Dictionary <string, IAttributeValue>(), 0) : Attributes.Create(this.attributes, this.attributes.NumberOfDroppedAttributes); var annotationsSpanData = CreateTimedEvents(this.InitializedEvents, this.TimestampConverter); var linksSpanData = this.links == null?LinkList.Create(new List <ILink>(), 0) : LinkList.Create(this.links.Events, this.links.NumberOfDroppedEvents); return(SpanData.Create( this.Context, this.parentSpanId, Resource.Empty, // TODO: determine what to do with Resource in this context this.Name, Timestamp.FromDateTimeOffset(this.startTime), attributesSpanData, annotationsSpanData, linksSpanData, null, // Not supported yet. this.hasBeenEnded ? this.StatusWithDefault : null, this.Kind ?? SpanKind.Internal, this.hasBeenEnded ? Timestamp.FromDateTimeOffset(this.endTime) : null)); }
public Person(int id, string name, string email, DateTimeOffset dateOfBirth) { Id = id; Name = name; Email = email; DateOfBirth = Timestamp.FromDateTimeOffset(dateOfBirth); }
/// <summary> /// Converts the <see cref="CommittedEvent" /> to <see cref="Contracts.EventHorizonCommittedEvent" />. /// </summary> /// <param name="event">The <see cref="CommittedEvent" />.</param> /// <returns>The <see cref="Contracts.EventHorizonCommittedEvent" />.</returns> public static Contracts.EventHorizonCommittedEvent ToEventHorizonCommittedEvent(this CommittedEvent @event) { var committedEvent = new Contracts.EventHorizonCommittedEvent { EventLogSequenceNumber = @event.EventLogSequenceNumber, Occurred = Timestamp.FromDateTimeOffset(@event.Occurred), EventSourceId = @event.EventSource.Value, ExecutionContext = @event.ExecutionContext.ToProtobuf(), EventType = new Dolittle.Artifacts.Contracts.Artifact { Id = @event.Type.Id.ToProtobuf(), Generation = @event.Type.Generation }, Content = @event.Content, Public = @event.Public, }; if (Guid.TryParse(@event.EventSource, out var eventSourceGuid)) { committedEvent.EventSourceIdLegacy = eventSourceGuid.ToProtobuf(); } committedEvent.ExecutionContext.Claims.Clear(); committedEvent.ExecutionContext.Claims.AddRange(Claims.Empty.ToProtobuf()); return(committedEvent); }
private void CovertThroughDateTimeOffset(DateTimeOffset source) { Timestamp timestamp = Timestamp.FromDateTimeOffset(source); DateTimeOffset check = timestamp.ToDateTimeOffset(); Assert.AreEqual(source, check); }
protected internal override async Task PackToAsyncCore(Packer packer, DateTimeOffset objectTree, CancellationToken cancellationToken) { if (this._conversion == DateTimeConversionMethod.Timestamp) { await packer.PackAsync(Timestamp.FromDateTimeOffset( objectTree ).Encode(), cancellationToken).ConfigureAwait(false); } else if (this._conversion == DateTimeConversionMethod.Native) { await packer.PackArrayHeaderAsync(2, cancellationToken).ConfigureAwait(false); await packer.PackAsync(objectTree.DateTime.ToBinary(), cancellationToken).ConfigureAwait(false); unchecked { await packer.PackAsync(( short )(objectTree.Offset.Hours * 60 + objectTree.Offset.Minutes), cancellationToken).ConfigureAwait(false); } } else { #if DEBUG Contract.Assert(this._conversion == DateTimeConversionMethod.UnixEpoc); #endif // DEBUG await packer.PackAsync(MessagePackConvert.FromDateTimeOffset(objectTree), cancellationToken).ConfigureAwait(false); } }
public void FromDateTimeOffset() { var timestamp = Timestamp.FromDateTimeOffset(new DateTimeOffset(1970, 1, 1, 0, 0, 1, TimeSpan.Zero).AddTicks(1)); var expected = new Timestamp(1, 100); Assert.Equal(expected, timestamp); }
private void BufferEvent(LogEvent logEvent1) { if (!logEvent1.Properties.TryGetValue("ActorId", out LogEventPropertyValue v)) { return; } var actorId = ((ScalarValue)v).Value.ToString().ToLowerInvariant(); if (_buffer == null) { _buffer = new List <LogMessage>(); } _messageCounter.TryGetValue(actorId, out var last); last++; _messageCounter[actorId] = last; _buffer.Add(new LogMessage() { MessageNum = last, Timestamp = Timestamp.FromDateTimeOffset(logEvent1.Timestamp), ActorId = actorId, LogType = ConvertLogLevel(logEvent1.Level), Text = logEvent1.RenderMessage(_formatProvider), Logger = logEvent1.Properties["SourceContext"].ToString() }); }
public AutoMapperProfile() { CreateMap <Instrument, InstrumentDto>().ReverseMap(); CreateMap <Tick, TickDto>() .ForMember(dest => dest.OpenPrice, opt => opt.MapFrom(src => src.Open)) .ForMember(dest => dest.ClosePrice, opt => opt.MapFrom(src => src.Close)) .ForMember(dest => dest.HighPrice, opt => opt.MapFrom(src => src.High)) .ForMember(dest => dest.LowPrice, opt => opt.MapFrom(src => src.Low)) .ReverseMap(); CreateMap <TickToAdd, Tick>() .ForPath(dest => dest.Instrument.Id, opt => opt.MapFrom(src => src.Symbol)) .ForMember(dest => dest.Open, opt => opt.MapFrom(src => decimal.ToDouble(src.Open))) .ForMember(dest => dest.Close, opt => opt.MapFrom(src => decimal.ToDouble(src.Close))) .ForMember(dest => dest.High, opt => opt.MapFrom(src => decimal.ToDouble(src.High))) .ForMember(dest => dest.Low, opt => opt.MapFrom(src => decimal.ToDouble(src.Low))); CreateMap <Tick, TickReply>().ForMember(dest => dest.Open, opt => opt.MapFrom(src => (decimal)src.Open)) .ForMember(dest => dest.Close, opt => opt.MapFrom(src => (decimal)src.Close)) .ForMember(dest => dest.High, opt => opt.MapFrom(src => (decimal)src.High)) .ForMember(dest => dest.Low, opt => opt.MapFrom(src => (decimal)src.Low)) .ForMember(dest => dest.Symbol, opt => opt.MapFrom((src => src.Instrument.Name))) .ForMember(dest => dest.Time, opt => opt.MapFrom((src => Timestamp.FromDateTimeOffset(src.Time)))); }
private static async Task SendTime(TimePingRequest request, IServerStreamWriter <TimePingResponse> responseStream) { await responseStream.WriteAsync(new TimePingResponse() { Message = $"Its now:", TimeNow = Timestamp.FromDateTimeOffset(DateTimeOffset.Now) }).ConfigureAwait(false); }
public async Task GetTimelineTest() { // Create DetailService instance ReviewService service = new ReviewService(); var range = new TimestampRange() { End = Timestamp.FromDateTimeOffset(offsetEnd), Start = Timestamp.FromDateTimeOffset(offsetStart) }; FakeServerStreamWriter <TimelineResponse> fakeServerStreamWriter = new FakeServerStreamWriter <TimelineResponse>(); var timelinesForTest = new Dictionary <int, List <TimestampRange> >(timelines); fakeServerStreamWriter.Received += applicationResponse => { Assert.Contains(applicationResponse.Range, timelinesForTest[applicationResponse.Application.Id]); timelinesForTest[applicationResponse.Application.Id].Remove(applicationResponse.Range); if (timelinesForTest[applicationResponse.Application.Id].Count == 0) { timelinesForTest.Remove(applicationResponse.Application.Id); } }; await service.GetTimeline(new TimelineRequest() { Range = range }, fakeServerStreamWriter, null); Assert.IsEmpty(timelinesForTest); }
public void Any_WellKnownType_Timestamp() { var timestamp = Timestamp.FromDateTimeOffset(DateTimeOffset.UnixEpoch); var any = Google.Protobuf.WellKnownTypes.Any.Pack(timestamp); AssertWrittenJson(any); }
public async Task <List <WeatherForecast> > GenerateForecasts(string city, DateTimeOffset startDate, int numOfDays, int averageTemp) { var rng = new Random(); var maxEnum = Enum.GetValues(typeof(Summary)) .Cast <Int32>().Max(); var forecasts = Enumerable.Range(0, numOfDays - 1).Select(index => new WeatherForecast { Id = Guid.NewGuid().ToString(), City = city, CreationTime = Timestamp.FromDateTimeOffset(DateTimeOffset.UtcNow), Date = Timestamp.FromDateTimeOffset(startDate.AddDays(index)), TemperatureC = averageTemp + rng.Next(-20, 55), Summary = ((Summary)rng.Next(maxEnum)), Context = Context.InShade }).ToList() ; await _pgContext.AddRangeAsync(forecasts); await _pgContext.SaveChangesAsync(); return(forecasts); // var sampleTopic = new CreateTopicSample(); // sampleTopic.PublishMessage("project", "topic"); }
public static GrpcAlarmChange AssignFrom(this GrpcAlarmChange gAlarmChange, ModelAlarmChange alarmChange) { gAlarmChange.CreateTime = Timestamp.FromDateTimeOffset(alarmChange.Timestamp); gAlarmChange.AlarmType = alarmChange.Type; gAlarmChange.AlarmChangeDirection = alarmChange.Direction; return(gAlarmChange); }
/// <inheritdoc/> public override ISpanData ToSpanData() { if (!this.Options.HasFlag(SpanOptions.RecordEvents)) { throw new InvalidOperationException("Getting SpanData for a Span without RECORD_EVENTS option."); } Attributes attributesSpanData = this.attributes == null?Attributes.Create(new Dictionary <string, IAttributeValue>(), 0) : Attributes.Create(this.attributes, this.attributes.NumberOfDroppedAttributes); ITimedEvents <IEvent> annotationsSpanData = CreateTimedEvents(this.InitializedEvents, this.timestampConverter); LinkList linksSpanData = this.links == null?LinkList.Create(new List <ILink>(), 0) : LinkList.Create(this.links.Events, this.links.NumberOfDroppedEvents); return(SpanData.Create( this.Context, this.parentSpanId, this.hasRemoteParent, this.Name, Timestamp.FromDateTimeOffset(this.startTime), attributesSpanData, annotationsSpanData, linksSpanData, null, // Not supported yet. this.hasBeenEnded ? this.StatusWithDefault : null, this.Kind ?? SpanKind.Internal, this.hasBeenEnded ? Timestamp.FromDateTimeOffset(this.endTime) : null)); }
public async Task <Alarm> GetAlarmAsync(GetAlarmRequest request, DateTime?deadline) { if (request is null) { throw new ArgumentNullException(nameof(request)); } PlcFrame response = await this.InvokeAsync( PlcFrame.Create(PlcMessageType.GetAlarmRequest, ByteString.Empty), deadline) .ConfigureAwait(false); if (response.FrameHeader.MessageType != PlcMessageType.GetAlarmResponse) { throw new InvalidDataException( "Response message type mismatch: " + response.FrameHeader.MessageType); } using var reader = new BinaryReader(new MemoryStream(response.FrameBody.ToByteArray())); return(new Alarm { CreateTime = Timestamp.FromDateTimeOffset(DateTimeOffset.UtcNow), LowFlowRate = reader.ReadByte() != 0, HighHeaterPressure = reader.ReadByte() != 0, LowHeaterPressure = reader.ReadByte() != 0, NoPower = reader.ReadByte() != 0, HeaterOverloadedBroken = reader.ReadByte() != 0, ElectricalHeaterBroken = reader.ReadByte() != 0, NoWater = reader.ReadByte() == 0, HighVoltage = reader.ReadByte() == 0, LowVoltage = reader.ReadByte() == 0, EmergencyStopped = reader.ReadByte() == 0, }); }
public override Task <AddAuditLogEntryResponse> AddAuditLogEntry(AddAuditLogEntryRequest request, ServerCallContext context) { var entry = new AuditLogEntry { UserId = Guid.Parse(request.Entry.UserId), ObjectId = request.Entry.ObjectId, Action = request.Entry.Action, Log = request.Entry.Log, CreatedDateTime = request.Entry.CreatedDateTime.ToDateTimeOffset(), }; _dispatcher.Dispatch(new AddOrUpdateEntityCommand <AuditLogEntry>(entry)); var response = new AddAuditLogEntryResponse { Entry = new AuditLogEntryMessage { Id = entry.Id.ToString(), ObjectId = entry.ObjectId, UserId = entry.UserId.ToString(), Action = entry.Action, Log = entry.Log, CreatedDateTime = Timestamp.FromDateTimeOffset(entry.CreatedDateTime), } }; return(Task.FromResult(response)); }
public async Task <Metric> GetMetricAsync(GetMetricRequest request, DateTime?deadline) { if (request is null) { throw new ArgumentNullException(nameof(request)); } PlcFrame response = await this.InvokeAsync( PlcFrame.Create(PlcMessageType.GetMetricRequest, ByteString.Empty), deadline) .ConfigureAwait(false); if (response.FrameHeader.MessageType != PlcMessageType.GetMetricResponse) { throw new InvalidDataException( "Response message type mismatch: " + response.FrameHeader.MessageType); } using var reader = new BinaryReader(new MemoryStream(response.FrameBody.ToByteArray())); return(new Metric { CreateTime = Timestamp.FromDateTimeOffset(DateTimeOffset.UtcNow), OutputWaterCelsiusDegree = reader.ReadSingle(), InputWaterCelsiusDegree = reader.ReadSingle(), HeaterOutputWaterCelsiusDegree = reader.ReadSingle(), EnvironmentCelsiusDegree = reader.ReadSingle(), OutputWaterPressureMeter = reader.ReadSingle(), InputWaterPressureMeter = reader.ReadSingle(), HeaterPowerKilowatt = reader.ReadSingle(), WaterPumpFlowRateCubicMeterPerHour = reader.ReadSingle(), }); }
public override Task <Empty> Send(MessageModel message, ServerCallContext context) { message.Time = Timestamp.FromDateTimeOffset(DateTimeOffset.UtcNow); Console.WriteLine("Message {0} is sended!", message); history.Add(message); return(Task.FromResult(new Empty())); }
public async Task GetApplicationsTest() { // Create DetailService instance DashboardService service = new DashboardService(); var range = new TimestampRange() { End = Timestamp.FromDateTimeOffset(offsetEnd), Start = Timestamp.FromDateTimeOffset(offsetStart) }; FakeServerStreamWriter <ApplicationResponse> fakeServerStreamWriter = new FakeServerStreamWriter <ApplicationResponse>(); var totalTimesForTest = new Dictionary <int, int>(totalTimes); fakeServerStreamWriter.Received += applicationResponse => { Assert.AreEqual(totalTimesForTest[applicationResponse.Application.Id], applicationResponse.TotalTime.Seconds); totalTimesForTest.Remove(applicationResponse.Application.Id); }; await service.GetApplications(new ApplicationRequest() { Range = range }, fakeServerStreamWriter, null); Assert.IsEmpty(totalTimesForTest); }
public override async Task GetTimeline(TimelineRequest request, IServerStreamWriter <TimelineResponse> responseStream, ServerCallContext context) { var timestampRanges = new Dictionary <int, TimestampRange>(); // 요청받은 기간 내의 activity만 가져온다. var activities = from activity in _db.GetActivities() where activity.Time >= request.Range.Start.ToDateTime() && activity.Time <= request.Range.End.ToDateTime() where activity.Action == ActionType.Active || activity.Action == ActionType.Idle || activity.Action == ActionType.Blur || activity.Action == ActionType.Focus orderby activity.Time select activity; Application applicationNow = null; await foreach (var activity in activities) { var application = await _db.GetAsync <Application>(activity.ApplicationId); switch (activity.Action) { case ActionType.Focus: applicationNow = application; break; case ActionType.Active: if (applicationNow == null) { applicationNow = application; } if (!timestampRanges.ContainsKey(applicationNow.Id)) { timestampRanges[applicationNow.Id] = new TimestampRange() { Start = Timestamp.FromDateTimeOffset(activity.Time) }; } break; case ActionType.Blur: case ActionType.Idle: if (timestampRanges.ContainsKey(applicationNow.Id)) { timestampRanges[applicationNow.Id].End = Timestamp.FromDateTimeOffset(activity.Time); var response = new TimelineResponse() { Application = applicationNow.ToRpc(), Range = timestampRanges[applicationNow.Id] }; timestampRanges.Remove(applicationNow.Id); await responseStream.WriteAsync(response); } break; default: continue; } } }
private static TimeInterval GetCumulativeInterval(MetricData metricData) { return(new TimeInterval { StartTime = Timestamp.FromDateTimeOffset(metricData.StartTimestamp), EndTime = Timestamp.FromDateTimeOffset(metricData.Timestamp), }); }
public void DateTimeOffsetNullable_hasValue() { poco.DateTimeOffsetNullable = DateTimeOffset.UtcNow; var actual = EntityValueFactory.FromPropertyInfo(poco, poco.GetType().GetProperty("DateTimeOffsetNullable"), entityFactory, new List <string>()); Assert.Equal(Timestamp.FromDateTimeOffset(poco.DateTimeOffsetNullable.Value), actual.TimestampValue); Assert.Equal(true, actual.ExcludeFromIndexes); }
public void Timestamp_Nested() { var helloRequest = new HelloRequest { TimestampValue = Timestamp.FromDateTimeOffset(new DateTimeOffset(2020, 12, 1, 12, 30, 0, TimeSpan.FromHours(12))) }; AssertWrittenJson(helloRequest); }
protected override async Task EmitBatchAsync(IEnumerable <LogEvent> events) { var logEntries = new List <LogEntry>(); foreach (var e in events) { var entry = new LogEntry { LogName = _logName, Severity = TranslateSeverity(e.Level), Timestamp = Timestamp.FromDateTimeOffset(e.Timestamp) }; if (_sinkOptions.UseJsonOutput) { var jsonStruct = new Struct(); if (_errorReportingEnabled && entry.Severity == LogSeverity.Error && e.Exception != null) { jsonStruct.Fields.Add("message", Value.ForString(RenderEventMessage(e) + "\n" + RenderException(e.Exception))); var serviceContextStruct = new Struct(); jsonStruct.Fields.Add("serviceContext", Value.ForStruct(serviceContextStruct)); serviceContextStruct.Fields.Add("service", Value.ForString(_sinkOptions.ErrorReportingServiceName)); serviceContextStruct.Fields.Add("version", Value.ForString(_sinkOptions.ErrorReportingServiceVersion)); } else { jsonStruct.Fields.Add("message", Value.ForString(RenderEventMessage(e))); } var propertiesStruct = new Struct(); jsonStruct.Fields.Add("properties", Value.ForStruct(propertiesStruct)); foreach (var property in e.Properties) { WritePropertyAsJson(entry, propertiesStruct, property.Key, property.Value); } entry.JsonPayload = jsonStruct; } else { entry.TextPayload = RenderEventMessage(e); foreach (var property in e.Properties) { WritePropertyAsLabel(entry, property.Key, property.Value); } } logEntries.Add(entry); } await _client.WriteLogEntriesAsync(_logNameToWrite, _resource, _sinkOptions.Labels, logEntries); }
public static SuggestionDto ToTransfer(this Suggestion suggestion) => new SuggestionDto { Id = $"{suggestion.Id}", UserId = $"{suggestion.UserId}", MeetingId = $"{suggestion.MeetingId}", Start = Timestamp.FromDateTimeOffset(suggestion.Start), End = Timestamp.FromDateTimeOffset(suggestion.End) };
public Task AddAsync(Guid guid, ToDoItem item) { item.Id = guid.ToString(); item.InsertedOn = Timestamp.FromDateTimeOffset(DateTimeOffset.UtcNow); _items.AddOrUpdate(guid, id => item, (id, old) => item); return(Task.CompletedTask); }
static async Task Main(string[] args) { AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true); //Console.WriteLine("Hello World!"); var channel = GrpcChannel.ForAddress("http://localhost:6003", new GrpcChannelOptions() { //DisposeHttpClient = true, ThrowOperationCanceledOnCancellation = true, }); var client = new Jaeger.ApiV2.QueryService.QueryServiceClient(channel); var response = client.GetServices(new Jaeger.ApiV2.GetServicesRequest() { }, new Grpc.Core.CallOptions()); Console.WriteLine(string.Join(",", response.Services)); var response1 = client.GetOperations(new Jaeger.ApiV2.GetOperationsRequest() { Service = response.Services[0], }, new Grpc.Core.CallOptions()); Console.WriteLine(string.Join(",", response1.OperationNames)); var response2 = client.GetTrace(new Jaeger.ApiV2.GetTraceRequest() { TraceId = ByteString.CopyFrom(Jaeger.TraceId.FromString("4399add89a1b8a02").ToByteArray()), }, new Grpc.Core.CallOptions()); while (await response2.ResponseStream.MoveNext(CancellationToken.None)) { Console.WriteLine(string.Join("|", response2.ResponseStream.Current.Spans.Select(s => s.SpanId.ToString()))); } var ps = new Jaeger.ApiV2.TraceQueryParameters() { ServiceName = response.Services[0], StartTimeMin = Timestamp.FromDateTimeOffset(DateTimeOffset.Now.AddDays(-7)), //OperationName= response1.OperationNames[0], StartTimeMax = Timestamp.FromDateTimeOffset(DateTimeOffset.Now), OperationName = "HTTP GET", //DurationMin=Duration.FromTimeSpan(TimeSpan.Zero) }; //ps.Tags.Add("http.method", "GET"); var response3 = client.FindTraces(new Jaeger.ApiV2.FindTracesRequest() { Query = ps }, new Grpc.Core.CallOptions()); while (await response3.ResponseStream.MoveNext(CancellationToken.None)) { Console.WriteLine(string.Join("|", response3.ResponseStream.Current.Spans.Select(s => s.SpanId.ToString()))); } }
public static MeetingDto ToTransfer(this Meeting meeting) => new MeetingDto { Id = $"{meeting.Id}", UserId = $"{meeting.UserId}", Start = Timestamp.FromDateTimeOffset(meeting.Start), End = Timestamp.FromDateTimeOffset(meeting.End), Name = meeting.Name, Descripton = meeting.Description };
internal WhisperFormInput.Types.Time ToProto() { return(new WhisperFormInput.Types.Time { Label = Label, Order = checked ((uint)Order), Tooltip = Tooltip, Value = Timestamp.FromDateTimeOffset(Value), }); }
public ProfileEx() { CreateMap <ApplicationUser, UserReply>() .ForMember(dest => dest.LockoutEnd, opt => opt.MapFrom(src => Timestamp.FromDateTimeOffset(src.LockoutEnd ?? DateTimeOffset.Now))) .ForAllOtherMembers(opt => opt.Condition((src, dest, obj) => { return(obj != null); })); CreateMap <ApplicationRole, RoleListReplay.Types.RoleItem>() .ForAllOtherMembers(opt => opt.Condition((src, dest, obj) => { return(obj != null); })); }