public void SimpleArrayConversions() { DateTime sampleDateTime = new DateTime(2016, 9, 20, 1, 1, 1, DateTimeKind.Utc); Key sampleKey = new Key { PartitionId = new PartitionId("proj", "ns"), Path = { new PathElement("kind", 0L) } }; ArrayValue sampleArray = new[] { "a", "b" }; ByteString sampleByteString = ByteString.CopyFrom(1, 2); Entity sampleEntity = new Entity(); LatLng sampleLatLng = new LatLng { Latitude = 1, Longitude = 2 }; Timestamp sampleTimestamp = Timestamp.FromDateTime(sampleDateTime); DateTimeOffset sampleDateTimeOffset = new DateTimeOffset(sampleDateTime, TimeSpan.Zero); AssertArrayConversions(new ArrayValue { Values = { "a", "b" } }, new[] { "a", "b" }); AssertArrayConversions(new ArrayValue { Values = { 1, 2 } }, new long[] { 1, 2 }); AssertArrayConversions(new ArrayValue { Values = { 1, 2 } }, new long?[] { 1, 2 }); AssertArrayConversions(new ArrayValue { Values = { sampleKey } }, new Key[] { sampleKey }); AssertArrayConversions(new ArrayValue { Values = { 1.0, 2.0 } }, new double[] { 1.0, 2.0 }); AssertArrayConversions(new ArrayValue { Values = { 1.0, 2.0 } }, new double?[] { 1.0, 2.0 }); AssertArrayConversions(new ArrayValue { Values = { false, true } }, new bool[] { false, true }); AssertArrayConversions(new ArrayValue { Values = { false, true } }, new bool?[] { false, true }); AssertArrayConversions(new ArrayValue { Values = { sampleArray } }, new ArrayValue[] { sampleArray }); AssertArrayConversions(new ArrayValue { Values = { sampleByteString } }, new ByteString[] { sampleByteString }); AssertArrayConversions(new ArrayValue { Values = { new byte[] { 1, 2 } } }, new byte[][] { new byte[] { 1, 2 } }); AssertArrayConversions(new ArrayValue { Values = { sampleEntity } }, new Entity[] { sampleEntity }); AssertArrayConversions(new ArrayValue { Values = { sampleLatLng } }, new LatLng[] { sampleLatLng }); AssertArrayConversions(new ArrayValue { Values = { sampleTimestamp } }, new Timestamp[] { sampleTimestamp }); AssertArrayConversions(new ArrayValue { Values = { sampleDateTime } }, new DateTime[] { sampleDateTime }); AssertArrayConversions(new ArrayValue { Values = { sampleDateTime } }, new DateTime?[] { sampleDateTime }); AssertArrayConversions(new ArrayValue { Values = { sampleDateTimeOffset } }, new DateTimeOffset[] { sampleDateTime }); AssertArrayConversions(new ArrayValue { Values = { sampleDateTimeOffset } }, new DateTimeOffset?[] { sampleDateTime }); AssertArrayConversions(new ArrayValue { Values = { "a", 1, true, Value.ForNull() } }, new Value[] { "a", 1, true, null }); }
public static Timestamp ToTS(this DateTime dt) => Timestamp.FromDateTime(dt.ToUniversalTime());
/// <summary> /// Rpc invocation wrapper /// </summary> /// <typeparam name="TReturnType"></typeparam> /// <param name="func"></param> /// <param name="runtimeExceptionPrompt"></param> /// <param name="connectionExceptionPrompt"></param> /// <param name="rethrow"></param> /// <param name="checkError"></param> /// <param name="notifyError">when the error is insiginficant it may not be notified</param> /// <param name="onError"></param> /// <returns></returns> private TReturnType TryInvoke <TReturnType>([NotNull] Func <TReturnType> func, string runtimeExceptionPrompt, string connectionExceptionPrompt = CameraControllerConnectionErrorPrompt, bool rethrow = false, bool checkError = true, bool notifyError = true, Action <string> onError = null) { var ret = default(TReturnType); try { ret = func.Invoke(); } catch (Exception e) { _log.Logger.Error(e); _eventAggregator.GetEvent <ExceptionEvent>() .Publish(new CameraControllerRpcServerConnectionException(connectionExceptionPrompt)); if (rethrow) { throw; } return(ret); } bool hasError = false; Error error = null; if (checkError) { try { // what will happen if the object does not contain error at all? error = (Error)typeof(TReturnType).GetProperty("Error")?.GetValue(ret); if (error != null) { hasError = true; } } catch (Exception e) { error = new Error() { Level = Error.Types.Level.Error, Message = e.Message, Timestamp = Timestamp.FromDateTime(DateTime.Now) }; hasError = true; } } if (ret == null || hasError) { onError?.Invoke(error?.Message); if (notifyError) { _eventAggregator.GetEvent <ExceptionEvent>() .Publish(new Exception($"{runtimeExceptionPrompt} {error?.Message}")); } } return(ret); }
public override async Task GetTownWeatherStream( IAsyncStreamReader <TownWeatherRequest> requestStream, IServerStreamWriter <TownWeatherForecast> responseStream, ServerCallContext context) { var rng = new Random(); var now = DateTime.UtcNow; // we'll use a channel here to handle in-process 'messages' concurrently being written to and read from the channel. var channel = Channel.CreateUnbounded <TownWeatherForecast>(); // background task which uses async streams to write each forecast from the channel to the response steam. _ = Task.Run(async() => { await foreach (var forecast in channel.Reader.ReadAllAsync()) { await responseStream.WriteAsync(forecast); } }); // a list of tasks handling requests concurrently var getTownWeatherRequestTasks = new List <Task>(); try { // async streams used to process each request from the stream as they are receieved await foreach (var request in requestStream.ReadAllAsync()) { _logger.LogInformation($"Getting weather for {request.TownName}"); getTownWeatherRequestTasks.Add(GetTownWeatherAsync(request.TownName)); // start and add the request handling task } _logger.LogInformation("Client finished streaming"); } catch (Exception e) { _logger.LogError(e, "An exception occurred"); } // wait for all responses to be written to the channel // from the concurrent tasks handling each request await Task.WhenAll(getTownWeatherRequestTasks); channel.Writer.TryComplete(); // wait for all responses to be read from the channel and streamed as responses await channel.Reader.Completion; _logger.LogInformation("Completed response streaming"); // a local function which defines a task to handle a town forecast request // it produces 10 forecasts for each town, simulating a 0.5s time to gather each forecast // multiple instances of this will run concurrently for each recieved request async Task GetTownWeatherAsync(string town) { for (var i = 0; i < 10; i++) { var forecast = new WeatherData { DateTimeStamp = Timestamp.FromDateTime(now.AddDays(i)), TemperatureC = rng.Next(-20, 55), Summary = Summaries[rng.Next(Summaries.Length)] }; await Task.Delay(500); // Gotta look busy // write the forecast to the channel which will be picked up concurrently by the channel reading background task await channel.Writer.WriteAsync(new TownWeatherForecast { TownName = town, WeatherData = forecast }); } } }
public override Task <TimeResult> GetTime(Empty request, ServerCallContext context) { return(Task.FromResult(new TimeResult { Time = Timestamp.FromDateTime(DateTime.UtcNow) })); }
public void ConversionsToValue_NonNull() { Assert.Equal(new Value { StringValue = "foo" }, (Value)"foo"); Assert.Equal(new Value { IntegerValue = 5 }, (Value)5L); Assert.Equal(new Value { IntegerValue = 5 }, (Value)(long?)5L); Assert.Equal(new Value { KeyValue = new Key { PartitionId = new PartitionId { ProjectId = "foo" } } }, (Value) new Key { PartitionId = new PartitionId { ProjectId = "foo" } }); Assert.Equal(new Value { DoubleValue = 1.5 }, (Value)1.5); Assert.Equal(new Value { DoubleValue = 1.5 }, (Value)(double?)1.5); Assert.Equal(new Value { BooleanValue = true }, (Value)true); Assert.Equal(new Value { BooleanValue = true }, (Value)(bool?)true); // Just to prove the "default" of false doesn't interfere... Assert.Equal(new Value { BooleanValue = false }, (Value)false); Assert.Equal(new Value { ArrayValue = new ArrayValue { Values = { "foo", "bar" } } }, (Value) new ArrayValue { Values = { "foo", "bar" } }); Assert.Equal(new Value { BlobValue = ByteString.CopyFromUtf8("foo") }, (Value)ByteString.CopyFromUtf8("foo")); Assert.Equal(new Value { BlobValue = ByteString.CopyFrom(new byte[] { 1, 2 }) }, (Value) new byte[] { 1, 2 }); Assert.Equal(new Value { EntityValue = new Entity { Properties = { { "key", "value" } } } }, (Value) new Entity { Properties = { { "key", "value" } } }); Assert.Equal(new Value { GeoPointValue = new LatLng { Latitude = 5.0, Longitude = 2.5 } }, (Value) new LatLng { Latitude = 5.0, Longitude = 2.5 }); var dateTime = DateTime.UtcNow; Assert.Equal(new Value { TimestampValue = Timestamp.FromDateTime(dateTime) }, (Value)Timestamp.FromDateTime(dateTime)); Assert.Equal(new Value { TimestampValue = Timestamp.FromDateTime(dateTime) }, (Value)dateTime); Assert.Equal(new Value { TimestampValue = Timestamp.FromDateTime(dateTime) }, new DateTimeOffset(dateTime)); }
public void GetSalary_should_return_month_salary_only_with_work_days() { // Arrange SalaryResponse expected = new() { CurrentPosition = _position1.Id, PersonId = _staff1.PersonId.GetValueOrDefault(), Salary = 1680, StartedOn = Timestamp.FromDateTime(_dateTimeUtil.GetCurrentDateTime().ToUniversalTime()) }; ISalaryResponse salaryResponse = new() { Status = new BaseResponse { Code = Code.Success, ErrorMessage = string.Empty } }; salaryResponse.SalaryResponse.Add(expected); SalaryRequest request = new() { StartDate = Timestamp.FromDateTime(new DateTime(2021, 1, 1, 0, 0, 0, DateTimeKind.Utc)), EndDate = Timestamp.FromDateTime(new DateTime(2021, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddMonths(1).AddDays(-1)) }; LogData expectedLog = new() { CallSide = nameof(SalaryService), CallerMethodName = nameof(_salaryService.GetSalary), CreatedOn = _dateTimeUtil.GetCurrentDateTime(), Request = request, Response = salaryResponse }; // Act ISalaryResponse response = _salaryService.GetSalary(request, null).Result; // Assert Assert.AreEqual(salaryResponse, response, "Calculated as expected"); _loggerMock.Verify(m => m.AddLog(expectedLog), Times.Once); } [Test] public void GetSalary_should_return_month_salary_for_preson_who_started_work_later_than_start_period_date() { // Arrange _staff1.CreatedOn = new DateTime(2021, 1, 15, 12, 00, 00); _dbContext.Staff.Update(_staff1); SalaryResponse expected = new() { CurrentPosition = _position1.Id, PersonId = _staff1.PersonId.GetValueOrDefault(), Salary = 880, StartedOn = Timestamp.FromDateTime(new DateTime(2021, 1, 15, 12, 00, 00).ToUniversalTime()) }; ISalaryResponse salaryResponse = new() { Status = new BaseResponse { Code = Code.Success, ErrorMessage = string.Empty } }; salaryResponse.SalaryResponse.Add(expected); SalaryRequest request = new() { StartDate = Timestamp.FromDateTime(new DateTime(2021, 1, 1, 0, 0, 0, DateTimeKind.Utc)), EndDate = Timestamp.FromDateTime(new DateTime(2021, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddMonths(1).AddDays(-1)) }; LogData expectedLog = new() { CallSide = nameof(SalaryService), CallerMethodName = nameof(_salaryService.GetSalary), CreatedOn = _dateTimeUtil.GetCurrentDateTime(), Request = request, Response = salaryResponse }; // Act ISalaryResponse response = _salaryService.GetSalary(request, null).Result; // Assert Assert.AreEqual(salaryResponse, response, "Calculated as expected"); _loggerMock.Verify(m => m.AddLog(expectedLog), Times.Once); } [Test] public void GetSalary_should_return_month_salary_with_paid_holidays() { // Arrange SalaryResponse expected = new() { CurrentPosition = _position1.Id, PersonId = _staff1.PersonId.GetValueOrDefault(), Salary = 1680, StartedOn = Timestamp.FromDateTime(_dateTimeUtil.GetCurrentDateTime().ToUniversalTime()) }; Holiday holiday = new() { HolidayDate = new DateTime(2021, 1, 1, 0, 0, 0, DateTimeKind.Utc), Id = 1, Description = "Test" }; _dbContext.Holidays.Add(holiday); ISalaryResponse salaryResponse = new() { Status = new BaseResponse { Code = Code.Success, ErrorMessage = string.Empty } }; salaryResponse.SalaryResponse.Add(expected); SalaryRequest request = new() { StartDate = Timestamp.FromDateTime(new DateTime(2021, 1, 1, 0, 0, 0, DateTimeKind.Utc)), EndDate = Timestamp.FromDateTime(new DateTime(2021, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddMonths(1).AddDays(-1)), ManagerId = 1 }; // Act ISalaryResponse response = _salaryService.GetSalary(request, null).Result; // Assert Assert.AreEqual(salaryResponse, response, "Calculated as expected"); } [Test] public void GetSalary_should_return_month_salary_with_unpaid_holidays() { // Arrange SalaryResponse expected = new() { CurrentPosition = _position1.Id, PersonId = _staff1.PersonId.GetValueOrDefault(), Salary = 1680, StartedOn = Timestamp.FromDateTime(_dateTimeUtil.GetCurrentDateTime().ToUniversalTime()) }; Holiday holiday = new() { HolidayDate = new DateTime(2021, 1, 1, 0, 0, 0, DateTimeKind.Utc), ToDoDate = new DateTime(2021, 1, 2, 0, 0, 0, DateTimeKind.Utc), Id = 1, Description = "Test" }; _dbContext.Holidays.Add(holiday); ISalaryResponse salaryResponse = new() { Status = new BaseResponse { Code = Code.Success, ErrorMessage = string.Empty } }; salaryResponse.SalaryResponse.Add(expected); SalaryRequest request = new() { StartDate = Timestamp.FromDateTime(new DateTime(2021, 1, 1, 0, 0, 0, DateTimeKind.Utc)), EndDate = Timestamp.FromDateTime(new DateTime(2021, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddMonths(1).AddDays(-1)) }; // Act ISalaryResponse response = _salaryService.GetSalary(request, null).Result; // Assert Assert.AreEqual(salaryResponse, response, "Calculated as expected"); } [Test] public void GetSalary_should_return_month_salary_with_paid_dayoff() { // Arrange SalaryResponse expected = new() { CurrentPosition = _position1.Id, PersonId = _staff1.PersonId.GetValueOrDefault(), Salary = 1680, StartedOn = Timestamp.FromDateTime(_dateTimeUtil.GetCurrentDateTime().ToUniversalTime()) }; DayOff dayOff = new() { DayOffType = Enums.DayOffType.Vacation, IsPaid = true, PersonId = _staff1.PersonId.GetValueOrDefault(), Hours = 8, Id = 1, CreatedOn = new DateTime(2021, 1, 1, 0, 0, 0, DateTimeKind.Utc) }; expected.DayOffs.Add(new DayOffInfo { DayOffType = (int)dayOff.DayOffType, Hours = dayOff.Hours }); _dbContext.DaysOff.Add(dayOff); SalaryRequest request = new() { StartDate = Timestamp.FromDateTime(new DateTime(2021, 1, 1, 0, 0, 0, DateTimeKind.Utc)), EndDate = Timestamp.FromDateTime(new DateTime(2021, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddMonths(1).AddDays(-1)) }; ISalaryResponse salaryResponse = new() { Status = new BaseResponse { Code = Code.Success, ErrorMessage = string.Empty } }; salaryResponse.SalaryResponse.Add(expected); // Act ISalaryResponse response = _salaryService.GetSalary(request, null).Result; // Assert Assert.AreEqual(salaryResponse, response, "Calculated as expected"); } [Test] public void GetSalary_should_return_month_salary_with_unpaid_dayoff() { // Arrange SalaryResponse expected = new() { CurrentPosition = _position1.Id, PersonId = _staff1.PersonId.GetValueOrDefault(), Salary = 1600, StartedOn = Timestamp.FromDateTime(_dateTimeUtil.GetCurrentDateTime().ToUniversalTime()) }; DayOff dayOff = new() { DayOffType = Enums.DayOffType.Vacation, IsPaid = false, PersonId = _staff1.PersonId.GetValueOrDefault(), Hours = 8, Id = 1, CreatedOn = new DateTime(2021, 1, 1, 0, 0, 0, DateTimeKind.Utc) }; expected.DayOffs.Add(new DayOffInfo { DayOffType = (int)dayOff.DayOffType, Hours = dayOff.Hours }); _dbContext.DaysOff.Add(dayOff); SalaryRequest request = new() { StartDate = Timestamp.FromDateTime(new DateTime(2021, 1, 1, 0, 0, 0, DateTimeKind.Utc)), EndDate = Timestamp.FromDateTime(new DateTime(2021, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddMonths(1).AddDays(-1)) }; ISalaryResponse salaryResponse = new() { Status = new BaseResponse { Code = Code.Success, ErrorMessage = string.Empty } }; salaryResponse.SalaryResponse.Add(expected); // Act ISalaryResponse response = _salaryService.GetSalary(request, null).Result; // Assert Assert.AreEqual(salaryResponse, response, "Calculated as expected"); } [Test] public void GetSalary_should_return_month_salary_with_partly_unpaid_dayoff() { // Arrange SalaryResponse expected = new() { CurrentPosition = _position1.Id, PersonId = _staff1.PersonId.GetValueOrDefault(), Salary = 1640, StartedOn = Timestamp.FromDateTime(_dateTimeUtil.GetCurrentDateTime().ToUniversalTime()) }; DayOff dayOff = new() { DayOffType = Enums.DayOffType.Vacation, IsPaid = false, PersonId = _staff1.PersonId.GetValueOrDefault(), Hours = 4, Id = 1, CreatedOn = new DateTime(2021, 1, 1, 0, 0, 0, DateTimeKind.Utc) }; expected.DayOffs.Add(new DayOffInfo { DayOffType = (int)dayOff.DayOffType, Hours = dayOff.Hours }); _dbContext.DaysOff.Add(dayOff); SalaryRequest request = new() { StartDate = Timestamp.FromDateTime(new DateTime(2021, 1, 1, 0, 0, 0, DateTimeKind.Utc)), EndDate = Timestamp.FromDateTime(new DateTime(2021, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddMonths(1).AddDays(-1)) }; ISalaryResponse salaryResponse = new() { Status = new BaseResponse { Code = Code.Success, ErrorMessage = string.Empty } }; salaryResponse.SalaryResponse.Add(expected); // Act ISalaryResponse response = _salaryService.GetSalary(request, null).Result; // Assert Assert.AreEqual(salaryResponse, response, "Calculated as expected"); } [Test] public void GetSalary_should_return_month_salary_with_partly_payed_dayoff() { // Arrange SalaryResponse expected = new() { CurrentPosition = _position1.Id, PersonId = _staff1.PersonId.GetValueOrDefault(), Salary = 1680, StartedOn = Timestamp.FromDateTime(_dateTimeUtil.GetCurrentDateTime().ToUniversalTime()) }; DayOff dayOff = new() { DayOffType = Enums.DayOffType.Vacation, IsPaid = true, PersonId = _staff1.PersonId.GetValueOrDefault(), Hours = 4, Id = 1, CreatedOn = new DateTime(2021, 1, 1, 0, 0, 0, DateTimeKind.Utc) }; expected.DayOffs.Add(new DayOffInfo { DayOffType = (int)dayOff.DayOffType, Hours = dayOff.Hours }); _dbContext.DaysOff.Add(dayOff); SalaryRequest request = new() { StartDate = Timestamp.FromDateTime(new DateTime(2021, 1, 1, 0, 0, 0, DateTimeKind.Utc)), EndDate = Timestamp.FromDateTime(new DateTime(2021, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddMonths(1).AddDays(-1)) }; ISalaryResponse salaryResponse = new() { Status = new BaseResponse { Code = Code.Success, ErrorMessage = string.Empty } }; salaryResponse.SalaryResponse.Add(expected); // Act ISalaryResponse response = _salaryService.GetSalary(request, null).Result; // Assert Assert.AreEqual(salaryResponse, response, "Calculated as expected"); } [Test] public void GetSalary_should_return_month_salary_with_motivation_modificator() { // Arrange SalaryResponse expected = new() { CurrentPosition = _position1.Id, PersonId = _staff1.PersonId.GetValueOrDefault(), Salary = 840, StartedOn = Timestamp.FromDateTime(_dateTimeUtil.GetCurrentDateTime().ToUniversalTime()) }; MotivationModificator modificator = new() { Id = 1, ModValue = 0.5, StaffId = _staff1.Id }; _dbContext.MotivationModificators.Add(modificator); _staff1.MotivationModificatorId = modificator.Id; SalaryRequest request = new() { StartDate = Timestamp.FromDateTime(new DateTime(2021, 1, 1, 0, 0, 0, DateTimeKind.Utc)), EndDate = Timestamp.FromDateTime(new DateTime(2021, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddMonths(1).AddDays(-1)) }; ISalaryResponse salaryResponse = new() { Status = new BaseResponse { Code = Code.Success, ErrorMessage = string.Empty } }; salaryResponse.SalaryResponse.Add(expected); // Act ISalaryResponse response = _salaryService.GetSalary(request, null).Result; // Assert Assert.AreEqual(salaryResponse, response, "Calculated as expected"); } [Test] public void GetSalary_should_return_month_salary_with_other_payments() { // Arrange SalaryResponse expected = new() { CurrentPosition = _position1.Id, PersonId = _staff1.PersonId.GetValueOrDefault(), Salary = 1700, StartedOn = Timestamp.FromDateTime(_dateTimeUtil.GetCurrentDateTime().ToUniversalTime()) }; OtherPayment otherPayment = new() { CreatedOn = new DateTime(2021, 1, 15, 0, 0, 0, DateTimeKind.Utc), Id = 1, PersonId = _staff1.PersonId.Value, Value = 20 }; _dbContext.OtherPayments.Add(otherPayment); SalaryRequest request = new() { StartDate = Timestamp.FromDateTime(new DateTime(2021, 1, 1, 0, 0, 0, DateTimeKind.Utc)), EndDate = Timestamp.FromDateTime(new DateTime(2021, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddMonths(1).AddDays(-1)) }; ISalaryResponse salaryResponse = new() { Status = new BaseResponse { Code = Code.Success, ErrorMessage = string.Empty } }; salaryResponse.SalaryResponse.Add(expected); // Act ISalaryResponse response = _salaryService.GetSalary(request, null).Result; // Assert Assert.AreEqual(salaryResponse, response, "Calculated as expected"); } [Test] public void GetSalary_should_handle_null_reference_exception() { // Arrange _dbContext.Positions.Remove(_position1); SalaryRequest request = new() { StartDate = Timestamp.FromDateTime(new DateTime(2021, 1, 1, 0, 0, 0, DateTimeKind.Utc)), EndDate = Timestamp.FromDateTime(new DateTime(2021, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddMonths(1).AddDays(-1)) }; LogData expectedLog = new() { CallSide = nameof(SalaryService), CallerMethodName = nameof(_salaryService.GetSalary), CreatedOn = _dateTimeUtil.GetCurrentDateTime(), Request = request, Response = new Exception("Object reference not set to an instance of an object.") }; // Act ISalaryResponse actual = _salaryService.GetSalary(request, null).Result; // Assert Assert.AreEqual(Code.DataError, actual.Status.Code, "Code returned as expected"); Assert.AreEqual("Some data has not found (type: NullReferenceException)", actual.Status.ErrorMessage, "Error message as expected"); _loggerMock.Verify(m => m.AddErrorLog(expectedLog), Times.Once); } [Test] public void GetSalary_should_handle_base_exception() { // Arrange _dbContext.Positions = null; SalaryRequest request = new() { StartDate = Timestamp.FromDateTime(new DateTime(2021, 1, 1, 0, 0, 0, DateTimeKind.Utc)), EndDate = Timestamp.FromDateTime(new DateTime(2021, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddMonths(1).AddDays(-1)) }; LogData expectedLog = new() { CallSide = nameof(SalaryService), CallerMethodName = nameof(_salaryService.GetSalary), CreatedOn = _dateTimeUtil.GetCurrentDateTime(), Request = request, Response = new Exception("Value cannot be null. (Parameter 'source')") }; // Act ISalaryResponse actual = _salaryService.GetSalary(request, null).Result; // Assert Assert.AreEqual(Code.UnknownError, actual.Status.Code, "Code returned as expected"); Assert.AreEqual("Value cannot be null. (Parameter 'source')", actual.Status.ErrorMessage, "Error message as expected"); _loggerMock.Verify(m => m.AddErrorLog(expectedLog), Times.Once); } } }
// ReSharper disable once MemberCanBeMadeStatic.Local private Timestamp GetTimestampWithOffset(Timestamp origin, int offset) { return(Timestamp.FromDateTime(origin.ToDateTime().AddMilliseconds(offset))); }
public async Task StartAsync_WhenReceivedValidEvent_ShouldInvokeCorrespondingConsumer() { // Arrange. using var received = new SemaphoreSlim(0); var @event = new Person() { Id = ByteString.CopyFrom(Guid.NewGuid().ToByteArray()), Name = "John Doe", LastUpdated = Timestamp.FromDateTime(DateTime.UtcNow), }; @event.Emails.Add("*****@*****.**"); @event.Phones.Add(new PhoneNumber() { Number = "+66123456789", Type = PhoneType.Home, }); this.consumer .Setup(c => c.ConsumeEventAsync(It.IsAny <Person>(), It.IsAny <CancellationToken>())) .Returns <Person, CancellationToken>((p, c) => { received.Release(); return(new ValueTask(Task.CompletedTask)); }); // Act. bool result; await this.subject.StartAsync(); try { this.PublishEvent(@event); result = await received.WaitAsync(1000 * 5); } finally { await this.subject.StopAsync(); } // Assert. Assert.True(result); this.coordinator.Verify( c => c.RegisterSupportedEventAsync(Person.Descriptor.FullName, default), Times.Once()); this.coordinator.Verify( c => c.RegisterSupportedEventAsync( It.IsNotIn(Person.Descriptor.FullName), It.IsAny <CancellationToken>()), Times.Never()); this.coordinator.Verify( c => c.IsEventSupportedAsync(It.IsAny <string>(), It.IsAny <CancellationToken>()), Times.Never()); this.consumer.Verify( c => c.ConsumeEventAsync(@event, default), Times.Once()); this.consumer.Verify( c => c.ConsumeEventAsync(It.IsNotIn(@event), It.IsAny <CancellationToken>()), Times.Never()); this.host.Verify( h => h.StopApplication(), Times.Never()); this.logger.Verify( l => l.Log( It.IsNotIn(LogLevel.Information), It.IsAny <EventId>(), It.Is <It.IsAnyType>((v, t) => true), It.IsAny <Exception>(), It.Is <Func <It.IsAnyType, Exception, string> >((v, t) => true)), Times.Never()); }
private async ValueTask <ThumbnailGeneratorGetThumbnailResult> GetPictureThumbnailAsync(NestedPath filePath, ThumbnailGeneratorGetThumbnailOptions options, CancellationToken cancellationToken = default) { var ext = filePath.GetExtension().ToLower(); if (!_pictureTypeExtensionList.Contains(ext)) { return(new ThumbnailGeneratorGetThumbnailResult(ThumbnailGeneratorResultStatus.Failed)); } try { var fileLength = await _fileSystem.GetFileSizeAsync(filePath, cancellationToken); var fileLastWriteTime = await _fileSystem.GetFileLastWriteTimeAsync(filePath, cancellationToken); using (var inStream = await _fileSystem.GetFileStreamAsync(filePath, cancellationToken)) using (var outStream = new RecyclableMemoryStream(_bytesPool)) { this.ConvertImage(inStream, outStream, options.Width, options.Height, options.ResizeType, options.FormatType); outStream.Seek(0, SeekOrigin.Begin); var fileMeta = new FileMeta(filePath, (ulong)fileLength, Timestamp.FromDateTime(fileLastWriteTime)); var thumbnailMeta = new ThumbnailMeta(options.ResizeType, options.FormatType, (uint)options.Width, (uint)options.Height); var content = new ThumbnailContent(outStream.ToMemoryOwner()); var cache = new ThumbnailCache(fileMeta, thumbnailMeta, new[] { content }); await _thumbnailGeneratorRepository.ThumbnailCaches.InsertAsync(cache); return(new ThumbnailGeneratorGetThumbnailResult(ThumbnailGeneratorResultStatus.Succeeded, cache.Contents)); } } catch (NotSupportedException e) { _logger.Warn(e); } catch (OperationCanceledException e) { _logger.Debug(e); } catch (Exception e) { _logger.Error(e); throw; } return(new ThumbnailGeneratorGetThumbnailResult(ThumbnailGeneratorResultStatus.Failed)); }
public async Task <List <Sentence> > GetSentencesAsync(string keyword, DateTime yearMonth) { var channel = new Channel("storage:7878", ChannelCredentials.Insecure); var client = new Storage.StorageClient(channel); var result = await client.GetSentencesAsync(new GetSentencesRequest { Keyword = keyword, YearMonth = Timestamp.FromDateTime(yearMonth.ToUniversalTime()) }); await channel.ShutdownAsync(); var yearMonths = new List <DateTime>(); var sentences = new List <Sentence>(); foreach (var s in result.Sentences) { sentences.Add(new Sentence() { Keyword = new Keyword() { Text = s.Keyword.Text }, Source = new Source() { Url = s.Source.Url }, Text = s.Text, Positive = s.Positive, Received = s.Received.ToDateTime(), SourceArticleHeader = s.Sourcearticleheader, SourceArticleUrl = s.Sourcearticleurl }); } return(sentences); }
public static Timestamp ToNullableTimestamp(this DateTime dateTime) { return(Timestamp.FromDateTime(DateTime.SpecifyKind(dateTime, DateTimeKind.Utc))); }
public override Task <FolderFilesReply> FolderFiles(FolderFilesRequest request, ServerCallContext context) { var result = new FolderFilesReply(); // Get the file details list in folder List <Interfaces.SharePointFileManager.FileDetailsList> fileDetailsList = null; SharePointFileManager _sharePointFileManager = new SharePointFileManager(_configuration); try { fileDetailsList = _sharePointFileManager.GetFileDetailsListInFolder(GetDocumentTemplateUrlPart(request.EntityName), request.FolderName, request.DocumentType).GetAwaiter().GetResult(); if (fileDetailsList != null) { // gRPC ensures that the collection has space to accept new data; no need to call a constructor foreach (var item in fileDetailsList) { // Sharepoint API responds with dates in UTC format var utcFormat = DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal; DateTime parsedCreateDate, parsedLastModified; DateTime.TryParse(item.TimeCreated, CultureInfo.InvariantCulture, utcFormat, out parsedCreateDate); DateTime.TryParse(item.TimeLastModified, CultureInfo.InvariantCulture, utcFormat, out parsedLastModified); FileSystemItem newItem = new FileSystemItem() { DocumentType = item.DocumentType, Name = item.Name, ServerRelativeUrl = item.ServerRelativeUrl, Size = int.Parse(item.Length), TimeCreated = parsedCreateDate != null?Timestamp.FromDateTime(parsedCreateDate) : null, TimeLastModified = parsedLastModified != null?Timestamp.FromDateTime(parsedLastModified) : null, }; result.Files.Add(newItem); } result.ResultStatus = ResultStatus.Success; } } catch (SharePointRestException spre) { Log.Error(spre, "Error getting SharePoint File List"); result.ResultStatus = ResultStatus.Fail; result.ErrorDetail = "Error getting SharePoint File List"; } return(Task.FromResult(result)); }
private static async Task InsertBulkProductAsync(ProductProtoService.ProductProtoServiceClient client) { using var clientBulk = client.InsertBulkProduct(); var listProduct = new List <ProductModel> { new ProductModel { Name = "Product_1", Description = "Description_1", Price = 100, Status = ProductStatus.Instock, CreatedTime = Timestamp.FromDateTime(DateTime.UtcNow) }, new ProductModel { Name = "Product_2", Description = "Description_2", Price = 200, Status = ProductStatus.Instock, CreatedTime = Timestamp.FromDateTime(DateTime.UtcNow) }, new ProductModel { Name = "Product_3", Description = "Description_3", Price = 300, Status = ProductStatus.Instock, CreatedTime = Timestamp.FromDateTime(DateTime.UtcNow) }, new ProductModel { Name = "Product_4", Description = "Description_4", Price = 400, Status = ProductStatus.Instock, CreatedTime = Timestamp.FromDateTime(DateTime.UtcNow) }, new ProductModel { Name = "Product_", Description = "Description_", Price = 100, Status = ProductStatus.Instock, CreatedTime = Timestamp.FromDateTime(DateTime.UtcNow) }, new ProductModel { Name = "Product_5", Description = "Description_5", Price = 500, Status = ProductStatus.Instock, CreatedTime = Timestamp.FromDateTime(DateTime.UtcNow) }, new ProductModel { Name = "Product_6", Description = "Description_6", Price = 600, Status = ProductStatus.Instock, CreatedTime = Timestamp.FromDateTime(DateTime.UtcNow) }, new ProductModel { Name = "Product_7", Description = "Description_7", Price = 700, Status = ProductStatus.Instock, CreatedTime = Timestamp.FromDateTime(DateTime.UtcNow) }, new ProductModel { Name = "Product_8", Description = "Description_8", Price = 800, Status = ProductStatus.Instock, CreatedTime = Timestamp.FromDateTime(DateTime.UtcNow) }, new ProductModel { Name = "Product_", Description = "Description_", Price = 100, Status = ProductStatus.Instock, CreatedTime = Timestamp.FromDateTime(DateTime.UtcNow) }, new ProductModel { Name = "Product_9", Description = "Description_9", Price = 900, Status = ProductStatus.Instock, CreatedTime = Timestamp.FromDateTime(DateTime.UtcNow) }, }; foreach (var product in listProduct) { await clientBulk.RequestStream.WriteAsync(product); } await clientBulk.RequestStream.CompleteAsync(); var response = await clientBulk; Console.WriteLine("Total Inserted Product: " + response.InsertCount + " Status: " + response.Success); }
public void SetTime(DateTime currentTime, DateTime newTime, string accessToken = null) { if (currentTime >= newTime) { throw new SetTimeException(currentTime, newTime); } var request = new SetTimeRequest { LedgerId = _ledgerId, CurrentTime = Timestamp.FromDateTime(currentTime), NewTime = Timestamp.FromDateTime(newTime) }; _timeClient.WithAccess(accessToken).Dispatch(request, (c, r, co) => c.SetTime(r, co)); }
public void GetByStaffId_should_return_modificator_by_staff_id() { // Arrange MotivationModificatorResponse expectedResponse = new() { Status = new BaseResponse { Code = Code.Success, ErrorMessage = string.Empty }, Data = new MotivationModificatorData { Id = _motivationModificator1.Id, ModValue = _motivationModificator1.ModValue, StaffId = _motivationModificator1.StaffId, CreatedOn = Timestamp.FromDateTime(_dateTimeUtil.GetCurrentDateTime()) } }; ByStaffIdRequest request = new() { StaffId = _motivationModificator1.StaffId }; LogData expectedLog = new() { CallSide = nameof(MotivationModificatorsService), CallerMethodName = nameof(_motivationModificatorsService.GetByStaffId), CreatedOn = _dateTimeUtil.GetCurrentDateTime(), Request = request, Response = expectedResponse }; // Act MotivationModificatorResponse actual = _motivationModificatorsService.GetByStaffId(request, null).Result; // Assert Assert.AreEqual(expectedResponse, actual, "Response as expected"); _loggerMock.Verify(mocks => mocks.AddLog(expectedLog), Times.Once); } [Test]
public async Task SetTimeAsync(DateTime currentTime, DateTime newTime, string accessToken = null) { var request = new SetTimeRequest { LedgerId = _ledgerId, CurrentTime = Timestamp.FromDateTime(currentTime), NewTime = Timestamp.FromDateTime(newTime) }; await _timeClient.WithAccess(accessToken).Dispatch(request, (c, r, co) => c.SetTimeAsync(r, co)); }
public GrpcProfile() { CreateMap <DateTime, string>().ConvertUsing(dt => dt.ToString("yyyy-MM-ddTHH:mm:ss.fffZ")); CreateMap <DateTime?, string>().ConvertUsing(dt => dt.HasValue ? dt.Value.ToString("yyyy-MM-ddTHH:mm:ss.fffZ") : string.Empty); CreateMap <decimal, string>().ConvertUsing(d => d.ToString("0." + new string('#', 339), CultureInfo.InvariantCulture)); CreateMap <decimal?, string>().ConvertUsing(d => d.HasValue ? d.Value.ToString("0." + new string('#', 339), CultureInfo.InvariantCulture) : string.Empty); CreateMap <double, string>().ConvertUsing(d => d.ToString("0." + new string('#', 339), CultureInfo.InvariantCulture)); CreateMap <double?, string>().ConvertUsing(d => d.HasValue ? d.Value.ToString("0." + new string('#', 339), CultureInfo.InvariantCulture) : string.Empty); CreateMap <string, string>().ConvertUsing(d => d ?? string.Empty); CreateMap <string, double>().ConvertUsing(d => double.Parse(d, NumberStyles.Any, CultureInfo.InvariantCulture)); CreateMap <DateTime, Timestamp>().ConvertUsing((dt, timestamp) => { var date = DateTime.SpecifyKind(dt, DateTimeKind.Utc); return(Timestamp.FromDateTime(date)); }); CreateMap <DateTimeOffset, Timestamp>().ConvertUsing((dt, timestamp) => Timestamp.FromDateTime(dt.UtcDateTime)); CreateMap <string, Timestamp>().ConvertUsing((str, timestamp) => { var date = DateTime.SpecifyKind(DateTime.Parse(str, CultureInfo.InvariantCulture), DateTimeKind.Utc); return(Timestamp.FromDateTime(date)); }); CreateMap <Lykke.Service.Assets.Client.Models.Asset, Asset>(MemberList.Destination) .ForMember(d => d.CardDeposit, o => o.MapFrom(x => x.BankCardsDepositEnabled)) .ForMember(d => d.SwiftDeposit, o => o.MapFrom(x => x.SwiftDepositEnabled)) .ForMember(d => d.BlockchainDeposit, o => o.MapFrom(x => x.BlockchainDepositEnabled)) .ForMember(d => d.CanBeBase, o => o.MapFrom(x => x.IsBase)) .ForMember(d => d.PopularPairs, o => o.Ignore()); CreateMap <Lykke.Service.Assets.Client.Models.AssetCategory, AssetCategory>(MemberList.Destination) .ForMember(d => d.IconUrl, o => o.MapFrom(x => x.AndroidIconUrl)); CreateMap <PriceEntity, PriceUpdate>(MemberList.Destination) .ForMember(d => d.Timestamp, o => o.MapFrom(x => x.UpdatedDt)) .ForMember(d => d.VolumeBase24H, o => o.Ignore()) .ForMember(d => d.VolumeQuote24H, o => o.Ignore()) .ForMember(d => d.PriceChange24H, o => o.Ignore()); CreateMap <CandlePriceType, CandleType>(); CreateMap <CandleTimeInterval, CandleInterval>(); CreateMap <Lykke.Job.CandlesProducer.Contract.CandlePriceType, CandleType>(); CreateMap <Lykke.Job.CandlesProducer.Contract.CandleTimeInterval, CandleInterval>(); CreateMap <Lykke.Service.CandlesHistory.Client.Models.Candle, Candle>() .ForMember(d => d.Timestamp, o => o.MapFrom(x => x.DateTime)) .ForMember(d => d.Volume, o => o.MapFrom(x => x.TradingVolume)) .ForMember(d => d.OppositeVolume, o => o.MapFrom(x => x.TradingOppositeVolume)) .ForMember(d => d.LastPrice, o => o.MapFrom(x => x.LastTradePrice)); CreateMap <CandleEntity, CandleUpdate>() .ForMember(d => d.Timestamp, o => o.MapFrom(x => x.CandleTimestamp)) .ForMember(d => d.UpdateTimestamp, o => o.MapFrom(x => x.UpdatedAt)) .ForMember(d => d.Volume, o => o.MapFrom(x => x.TradingVolume)) .ForMember(d => d.OppositeVolume, o => o.MapFrom(x => x.TradingOppositeVolume)) .ForMember(d => d.LastPrice, o => o.MapFrom(x => x.LastTradePrice)); CreateMap <OrderbookEntity, Orderbook>(MemberList.Destination) .ForMember(d => d.Timestamp, o => o.MapFrom(x => x.CreatedAt)); CreateMap <Lykke.Service.TradesAdapter.Contract.Trade, PublicTrade>(MemberList.Destination) .ForMember(d => d.Side, o => o.MapFrom(x => x.Action)); CreateMap <VolumePriceEntity, Orderbook.Types.PriceVolume>(MemberList.Destination) .ForMember(d => d.V, o => o.MapFrom(x => x.Volume)) .ForMember(d => d.P, o => o.MapFrom(x => x.Price)); CreateMap <ClientBalanceResponseModel, Balance>() .ForMember(d => d.Timestamp, o => o.MapFrom(x => x.UpdatedAt)) .ForMember(d => d.Available, o => o.MapFrom(x => x.Balance)) .ForMember(d => d.Reserved, o => o.MapFrom(x => x.Reserved)) .ForMember(d => d.AssetId, o => o.MapFrom(x => x.AssetId)); CreateMap <ApiHotWalletOrder, OrderModel>(); CreateMap <ApiOffchainOrder, LimitOrderModel>(); CreateMap <WatchList, Watchlist>(); CreateMap <CurrentTierInfo, CurrentTier>(); CreateMap <TierInfo, NextTier>(); CreateMap <Lykke.ApiClients.V1.UpgradeRequest, UpgradeRequest>(); CreateMap <GetSwiftCredentialsModel, SwiftCredentialsResponse.Types.Body>(); CreateMap <BankCardPaymentUrlInputModel, BankCardPaymentDetailsResponse.Types.Body>(); CreateMap <BankCardPaymentUrlResponceModel, BankCardPaymentUrlResponse.Types.Body>(); CreateMap <BankCardPaymentUrlRequest, BankCardPaymentUrlInputModel>() .ForMember(d => d.WalletId, o => o.Ignore()) .ForMember(d => d.OkUrl, o => o.Ignore()) .ForMember(d => d.FailUrl, o => o.Ignore()) .ForMember(d => d.FirstName, o => o.Ignore()) .ForMember(d => d.LastName, o => o.Ignore()) .ForMember(d => d.City, o => o.Ignore()) .ForMember(d => d.Zip, o => o.Ignore()) .ForMember(d => d.Address, o => o.Ignore()) .ForMember(d => d.Country, o => o.Ignore()) .ForMember(d => d.Email, o => o.Ignore()) .ForMember(d => d.Phone, o => o.Ignore()) .ForMember(d => d.DepositOption, o => o.MapFrom(x => "BankCard")); CreateMap <CountryItem, Country>(); CreateMap <EthereumAssetResponse, EthereumSettingsResponse.Types.Body>(); CreateMap <BitcoinFeeSettings, EthereumSettingsResponse.Types.BitcoinFee>(); CreateMap <WithdrawalCryptoInfoModel, WithdrawalCryptoInfoResponse.Types.Body>(); CreateMap <CashoutSwiftLastDataResponse, SwiftCashoutInfoResponse.Types.Body>(); CreateMap <CashoutSwiftFeeResponse, SwiftCashoutFeeResponse.Types.Body>(); CreateMap <SwiftCashoutRequest, OffchainCashoutSwiftModel>() .ForMember(d => d.PrevTempPrivateKey, o => o.Ignore()); CreateMap <OffchainTradeRespModel, SwiftCashoutResponse.Types.Body>(); CreateMap <ApiAppSettingsModel, AppSettingsResponse.Types.Body>(); CreateMap <ApiAssetModel, AppSettingsResponse.Types.ApiAsset>(); CreateMap <ApiRefundSettings, AppSettingsResponse.Types.ApiRefundSettings>(); CreateMap <ApiFeeSettings, AppSettingsResponse.Types.ApiFeeSettings>(); CreateMap <Lykke.ApiClients.V1.CashOutFee, Swisschain.Lykke.AntaresWalletApi.ApiContract.CashOutFee>(); CreateMap <ApiWalletAssetModel, WalletResponse.Types.Body>(); CreateMap <ApiPrivateWallet, PrivateWallet>(); CreateMap <ApiBalanceRecord, BalanceRecord>(); CreateMap <CryptoCashoutRequest, HotWalletCashoutOperation>(); CreateMap <AssetPairModel, AssetPair>(); CreateMap <TradeResponseModel, TradesResponse.Types.TradeModel>(); CreateMap <MarketSlice, MarketsResponse.Types.MarketModel>(); CreateMap <PendingActionsModel, PendingActionsResponse.Types.Body>(); CreateMap <Lykke.ApiClients.V1.ApiPersonalDataModel, PersonalData>(); CreateMap <DocumentModel, KycDocument>(); CreateMap <FileModel, KycFile>(); CreateMap <QuestionModel, QuestionnaireResponse.Types.Question>(); CreateMap <AnswerModel, QuestionnaireResponse.Types.Answer>(); CreateMap <AnswersRequest.Types.Choice, ChoiceModel>(); CreateMap <FundsResponseModel, FundsResponse.Types.FundsModel>(); CreateMap <Lykke.ApiClients.V1.AccountsRegistrationResponseModel, RegisterResponse.Types.Body>() .ForMember(d => d.SessionId, o => o.Ignore()); CreateMap <Lykke.Service.TradesAdapter.AutorestClient.Models.Trade, PublicTrade>() .ForMember(d => d.Side, o => o.MapFrom(x => x.Action)); CreateMap <BlockchainExplorerLinkResponse, ExplorerLinksResponse.Types.ExplorerLinkModel>(); }
public MappingProfile() { CreateMap <UserDocument, User>() .ForMember(m => m.Authorize, op => op.MapFrom(src => Timestamp.FromDateTime(new DateTime ( src.Authorize.Year, src.Authorize.Month, src.Authorize.Day, src.Authorize.Hour, src.Authorize.Minute, src.Authorize.Second, DateTimeKind.Utc )))) .ForMember(m => m.ChatsIds, opt => opt.MapFrom(src => src.ChatsIds)) .ForMember(m => m.Id, opt => opt.MapFrom(src => src.Id)) .ForMember(m => m.Login, opt => opt.MapFrom(src => src.Login)) .ForMember(m => m.Password, opt => opt.MapFrom(src => src.Password)) .ForMember(m => m.Private, opt => opt.MapFrom(src => src.Private)) .ForMember(m => m.Registration, opt => opt.MapFrom(src => Timestamp.FromDateTime(new DateTime ( src.Registration.Year, src.Registration.Month, src.Registration.Day, src.Registration.Hour, src.Registration.Minute, src.Registration.Second, DateTimeKind.Utc )))) .ForMember(m => m.InNetwork, opt => opt.MapFrom(src => src.InNetwork)) //.ForMember(m => m.ProfileImage, opt => opt.MapFrom(src => src.ProfileImage)) .ForMember(m => m.UserName, opt => opt.MapFrom(src => src.UserName)); CreateMap <User, UserDocument>() .ForMember(m => m.Authorize, op => op.MapFrom(src => src.Authorize.ToDateTime())) .ForMember(m => m.ChatsIds, opt => opt.MapFrom(src => src.ChatsIds)) .ForMember(m => m.Id, opt => opt.MapFrom(src => src.Id)) .ForMember(m => m.Login, opt => opt.MapFrom(src => src.Login)) .ForMember(m => m.Password, opt => opt.MapFrom(src => src.Password)) .ForMember(m => m.Private, opt => opt.MapFrom(src => src.Private)) .ForMember(m => m.Registration, opt => opt.MapFrom(src => src.Registration.ToDateTime())) .ForMember(m => m.InNetwork, opt => opt.MapFrom(src => src.InNetwork)) //.ForMember(m => m.ProfileImage, opt => opt.MapFrom(src => src.ProfileImage)) .ForMember(m => m.UserName, opt => opt.MapFrom(src => src.UserName)); CreateMap <ChatDocument, Chat>() .ForMember(c => c.History, op => op.MapFrom(src => src.History)) .ForMember(c => c.Id, op => op.MapFrom(src => Guid.Parse(src.Id))) .ForMember(c => c.UserIds, op => op.MapFrom(src => src.UserIds)); CreateMap <Chat, ChatDocument>() .ForMember(c => c.History, op => op.MapFrom(src => src.History)) .ForMember(c => c.Id, op => op.MapFrom(src => Guid.Parse(src.Id))) .ForMember(c => c.UserIds, op => op.MapFrom(src => src.UserIds)); CreateMap <Message, Domain.Models.Message>() .ForMember(c => c.Content, op => op.MapFrom(src => src.Content)) .ForMember(c => c.Time, op => op.MapFrom(src => src.Time.ToDateTime())) .ForMember(c => c.AuthorId, op => op.MapFrom(src => Guid.Parse(src.AuthorId))) .ForMember(c => c.AuthorName, op => op.MapFrom(src => src.AuthorName)); CreateMap <Domain.Models.Message, Message>() .ForMember(c => c.Content, op => op.MapFrom(src => src.Content)) .ForMember(c => c.Time, op => op.MapFrom(src => Timestamp.FromDateTime(new DateTime( src.Time.Year, src.Time.Month, src.Time.Day, src.Time.Hour, src.Time.Minute, src.Time.Second, DateTimeKind.Utc )))) .ForMember(c => c.AuthorId, op => op.MapFrom(src => src.AuthorId.ToString())) .ForMember(c => c.AuthorName, op => op.MapFrom(src => src.AuthorName)); }
public static HelloReply Create(string message, ReplyStatusEnum status = ReplyStatusEnum.Success) => new HelloReply { Message = message, Status = status, Timestamp = Timestamp.FromDateTime(DateTime.UtcNow) };
public static void HandleDBReply(Packet packet) { var dbReply = packet.Holder.DbReply = new(); var type = packet.ReadUInt32E <DB2Hash>("TableHash"); dbReply.TableHash = (uint)type; var entry = dbReply.RecordId = packet.ReadInt32("RecordID"); var timeStamp = packet.ReadUInt32(); var time = packet.AddValue("Timestamp", Utilities.GetDateTimeFromUnixTime(timeStamp)); dbReply.Time = Timestamp.FromDateTime(DateTime.SpecifyKind(time, DateTimeKind.Utc)); var allow = packet.ReadBit("Allow"); var size = packet.ReadInt32("Size"); var data = packet.ReadBytes(size); var db2File = new Packet(data, packet.Opcode, packet.Time, packet.Direction, packet.Number, packet.Writer, packet.FileName); if (entry < 0 || !allow) { dbReply.Status = PacketDbReplyRecordStatus.RecordStatusRecordRemoved; packet.WriteLine("Row {0} has been removed.", -entry); HotfixStoreMgr.RemoveRecord(type, entry); } else { dbReply.Status = PacketDbReplyRecordStatus.RecordStatusValid; switch (type) { case DB2Hash.BroadcastText: { var bct = new BroadcastText() { ID = (uint)entry, Text = db2File.ReadCString("Text"), Text1 = db2File.ReadCString("Text1"), }; bct.EmoteID = new ushort?[3]; bct.EmoteDelay = new ushort?[3]; for (int i = 0; i < 3; ++i) { bct.EmoteID[i] = db2File.ReadUInt16("EmoteID", i); } for (int i = 0; i < 3; ++i) { bct.EmoteDelay[i] = db2File.ReadUInt16("EmoteDelay", i); } bct.EmotesID = db2File.ReadUInt16("EmotesID"); bct.LanguageID = db2File.ReadByte("LanguageID"); bct.Flags = db2File.ReadByte("Flags"); if (ClientVersion.AddedInVersion(ClientVersionBuild.V7_3_5_25848)) { bct.ConditionID = db2File.ReadUInt32("ConditionID"); } bct.SoundEntriesID = new uint?[2]; for (int i = 0; i < 2; ++i) { bct.SoundEntriesID[i] = db2File.ReadUInt32("SoundEntriesID", i); } if (ClientVersion.AddedInVersion(ClientVersionBuild.V7_0_3_22248) && ClientVersion.RemovedInVersion(ClientVersionBuild.V7_3_5_25848)) { bct.ConditionID = db2File.ReadUInt32("ConditionID"); } Storage.BroadcastTexts.Add(bct, packet.TimeSpan); if (ClientLocale.PacketLocale != LocaleConstant.enUS) { BroadcastTextLocale lbct = new BroadcastTextLocale { ID = bct.ID, TextLang = bct.Text, Text1Lang = bct.Text1 }; Storage.BroadcastTextLocales.Add(lbct, packet.TimeSpan); } dbReply.BroadcastText = new PacketDbReplyBroadcastText() { Id = bct.ID.Value, Text0 = bct.Text, Text1 = bct.Text1, Language = bct.LanguageID.Value, ConditionId = bct.ConditionID ?? 0, EmotesId = bct.EmotesID.Value, Flags = bct.Flags.Value, ChatBubbleDuration = 0, }; dbReply.BroadcastText.Sounds.Add(bct.SoundEntriesID1 ?? 0); dbReply.BroadcastText.Sounds.Add(bct.SoundEntriesID2 ?? 0); for (int i = 0; i < 3; ++i) { dbReply.BroadcastText.Emotes.Add(new BroadcastTextEmote() { EmoteId = bct.EmoteID[i] ?? 0, Delay = bct.EmoteDelay[i] ?? 0 }); } break; } default: HotfixStoreMgr.AddRecord(type, entry, db2File); break; } db2File.ClosePacket(false); } }
public async Task SaveAll() { var employees = new List <Employee> { new Employee { No = 222, FirstName = "张三", Id = 5, Salary = 143.23f, Status = EmployeeStatus.OnVacation, LastModified = Timestamp.FromDateTime(DateTime.UtcNow), }, new Employee { No = 444, FirstName = "李四", Id = 6, Salary = 33.33f } }; //传入元数据 var md = new Metadata { { "username", "jack" }, { "role", "admin" } }; using var channel = GrpcChannel.ForAddress("http://localhost:6001"); var client = new EmployeeService.EmployeeServiceClient(channel); using var call = client.SaveAll(); var requestStream = call.RequestStream; var responseStream = call.ResponseStream; //var responseTask = Task.Run(async () => //{ // while (await responseStream.MoveNext()) // { // Console.WriteLine($"接收:{responseStream.Current.Employee}"); // } //}); var responseTask = await Task.Factory.StartNew(async() => { while (await responseStream.MoveNext()) { Console.WriteLine($"接收:{responseStream.Current.Employee}"); } }); foreach (var employee in employees) { await requestStream.WriteAsync(new EmployeeRequest { Employee = employee }); } await requestStream.CompleteAsync(); //通知服务端请求结束 //await responseTask必须位于requestStream.CompleteAsync()之后 await responseTask; }
async Task ISendTransport.Send <T>(T message, IPipe <SendContext <T> > pipe, CancellationToken cancellationToken) { LogContext.SetCurrentIfNull(_context.LogContext); var context = new TransportGrpcSendContext <T>(_context.Exchange.Name, message, cancellationToken); await pipe.Send(context).ConfigureAwait(false); StartedActivity?activity = LogContext.IfEnabled(OperationName.Transport.Send)?.StartSendActivity(context); try { if (_context.SendObservers.Count > 0) { await _context.SendObservers.PreSend(context).ConfigureAwait(false); } var messageId = context.MessageId ?? NewId.NextGuid(); var transportMessage = new TransportMessage { Deliver = new Deliver { Exchange = new ExchangeDestination { Name = _context.Exchange.Name, RoutingKey = context.RoutingKey ?? "" }, Envelope = new Envelope { MessageId = messageId.ToString("D"), RequestId = context.RequestId?.ToString("D") ?? "", ConversationId = context.ConversationId?.ToString("D") ?? "", CorrelationId = context.CorrelationId?.ToString("D") ?? "", InitiatorId = context.InitiatorId?.ToString("D") ?? "", SourceAddress = context.SourceAddress?.ToString() ?? "", DestinationAddress = context.DestinationAddress?.ToString() ?? "", ResponseAddress = context.ResponseAddress?.ToString() ?? "", FaultAddress = context.FaultAddress?.ToString() ?? "", ContentType = context.ContentType?.MediaType ?? "", Body = ByteString.CopyFrom(context.Body), EnqueueTime = context.Delay.ToFutureDateTime(), ExpirationTime = context.TimeToLive.ToFutureDateTime(), SentTime = Timestamp.FromDateTime(context.SentTime ?? DateTime.UtcNow), } } }; transportMessage.Deliver.Envelope.MessageType.AddRange(TypeMetadataCache <T> .MessageTypeNames); SetHeaders(transportMessage.Deliver.Envelope.Headers, context.Headers); var grpcTransportMessage = new GrpcTransportMessage(transportMessage, HostMetadataCache.Host); await _context.Exchange.Send(grpcTransportMessage, cancellationToken).ConfigureAwait(false); context.LogSent(); activity.AddSendContextHeadersPostSend(context); if (_context.SendObservers.Count > 0) { await _context.SendObservers.PostSend(context).ConfigureAwait(false); } } catch (Exception ex) { context.LogFaulted(ex); if (_context.SendObservers.Count > 0) { await _context.SendObservers.SendFault(context, ex).ConfigureAwait(false); } throw; } finally { activity?.Stop(); } }
private static DataValue MakeDataValue(Variant v, DataValue lastValue) { bool array = v.ArrayDimensions != null && v.ArrayDimensions.Length > 0; switch (v.Type) { case VariantType.Float: if (array) { return(DataValue.FromFloatArray((float[]?)v)); } else { return(DataValue.FromFloat((float)v)); } case VariantType.Double: if (array) { return(DataValue.FromDoubleArray((double[]?)v)); } else { return(DataValue.FromDouble((double)v)); } case VariantType.Boolean: if (array) { return(DataValue.FromBoolArray((bool[]?)v)); } else { return(DataValue.FromBool((bool)v)); } case VariantType.Int64: if (array) { return(DataValue.FromLongArray((long[]?)v)); } else { return(DataValue.FromLong((long)v)); } case VariantType.UInt64: if (array) { return(DataValue.FromULongArray((ulong[]?)v)); } else { return(DataValue.FromULong((ulong)v)); } case VariantType.Int32: if (array) { return(DataValue.FromIntArray((int[]?)v)); } else { return(DataValue.FromInt((int)v)); } case VariantType.UInt32: if (array) { return(DataValue.FromUIntArray((uint[]?)v)); } else { return(DataValue.FromUInt((uint)v)); } case VariantType.Int16: if (array) { return(DataValue.FromShortArray((short[]?)v)); } else { return(DataValue.FromShort((short)v)); } case VariantType.UInt16: if (array) { return(DataValue.FromUShortArray((ushort[]?)v)); } else { return(DataValue.FromUShort((ushort)v)); } case VariantType.SByte: if (array) { return(DataValue.FromSByteArray((sbyte[]?)v)); } else { return(DataValue.FromSByte((sbyte)v)); } case VariantType.Byte: if (array) { return(DataValue.FromByteArray((byte[]?)v)); } else { return(DataValue.FromByte((byte)v)); } case VariantType.String: if (array) { return(DataValue.FromStringArray((string[]?)v)); } else { return(DataValue.FromString((string?)v)); } case VariantType.Null: return(lastValue); case VariantType.DateTime: if (array) { DateTime[]? theArr = (DateTime[]?)v; Timestamp[]? timestamps = theArr == null ? null : theArr.Select(Timestamp.FromDateTime).ToArray(); return(DataValue.FromTimestampArray(timestamps)); } else { return(DataValue.FromTimestamp(Timestamp.FromDateTime((DateTime)v))); } case VariantType.Guid: case VariantType.ByteString: case VariantType.XmlElement: case VariantType.NodeId: case VariantType.ExpandedNodeId: case VariantType.StatusCode: case VariantType.QualifiedName: case VariantType.LocalizedText: case VariantType.ExtensionObject: case VariantType.DataValue: case VariantType.Variant: case VariantType.DiagnosticInfo: default: throw new Exception($"Type {v.Type} not implemented"); } }
// [END dlp_inspect_bigquery] // [START dlp_inspect_datastore] public static object InspectCloudDataStore( string projectId, string minLikelihood, int maxFindings, bool includeQuote, string kindName, string namespaceId, IEnumerable <InfoType> infoTypes, string datasetId, string tableId) { var inspectJob = new InspectJobConfig { StorageConfig = new StorageConfig { DatastoreOptions = new DatastoreOptions { Kind = new KindExpression { Name = kindName }, PartitionId = new PartitionId { NamespaceId = namespaceId, ProjectId = projectId, } }, TimespanConfig = new StorageConfig.Types.TimespanConfig { StartTime = Timestamp.FromDateTime(System.DateTime.UtcNow.AddYears(-1)), EndTime = Timestamp.FromDateTime(System.DateTime.UtcNow) } }, InspectConfig = new InspectConfig { InfoTypes = { infoTypes }, Limits = new FindingLimits { MaxFindingsPerRequest = maxFindings }, ExcludeInfoTypes = false, IncludeQuote = includeQuote, MinLikelihood = (Likelihood)System.Enum.Parse(typeof(Likelihood), minLikelihood) }, Actions = { new Google.Cloud.Dlp.V2.Action { // Save results in BigQuery Table SaveFindings = new Google.Cloud.Dlp.V2.Action.Types.SaveFindings { OutputConfig = new OutputStorageConfig { Table = new Google.Cloud.Dlp.V2.BigQueryTable { ProjectId = projectId, DatasetId = datasetId, TableId = tableId } } }, } } }; // Issue Create Dlp Job Request DlpServiceClient client = DlpServiceClient.Create(); var request = new CreateDlpJobRequest { InspectJob = inspectJob, ParentAsProjectName = new Google.Cloud.Dlp.V2.ProjectName(projectId), }; // We need created job name var dlpJob = client.CreateDlpJob(request); var jobName = dlpJob.Name; // Make sure the job finishes before inspecting the results. // Alternatively, we can inspect results opportunistically, but // for testing purposes, we want consistent outcome bool jobFinished = EnsureJobFinishes(projectId, jobName); if (jobFinished) { var bigQueryClient = BigQueryClient.Create(projectId); var table = bigQueryClient.GetTable(datasetId, tableId); // Return only first page of 10 rows Console.WriteLine("DLP v2 Results:"); var firstPage = table.ListRows(new ListRowsOptions { StartIndex = 0, PageSize = 10 }); foreach (var item in firstPage) { Console.WriteLine($"\t {item[""]}"); } } return(0); }
/// <inheritdoc /> public void Log <TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func <TState, Exception, string> formatter) { try { GaxPreconditions.CheckNotNull(formatter, nameof(formatter)); if (!IsEnabled(logLevel)) { return; } string message = formatter(state, exception); if (string.IsNullOrEmpty(message)) { return; } var jsonStruct = new Struct(); jsonStruct.Fields.Add("message", Value.ForString(message)); jsonStruct.Fields.Add("log_name", Value.ForString(_logName)); if (eventId.Id != 0 || eventId.Name != null) { var eventStruct = new Struct(); if (eventId.Id != 0) { eventStruct.Fields.Add("id", Value.ForNumber(eventId.Id)); } if (!string.IsNullOrWhiteSpace(eventId.Name)) { eventStruct.Fields.Add("name", Value.ForString(eventId.Name)); } jsonStruct.Fields.Add("event_id", Value.ForStruct(eventStruct)); } // If we have format params and its more than just the original message add them. if (state is IEnumerable <KeyValuePair <string, object> > formatParams && !(formatParams.Count() == 1 && formatParams.Single().Key.Equals("{OriginalFormat}"))) { var paramStruct = new Struct(); foreach (var pair in formatParams) { // Consider adding formatting support for values that are IFormattable. paramStruct.Fields[pair.Key] = Value.ForString(pair.Value?.ToString() ?? ""); } if (paramStruct.Fields.Count > 0) { jsonStruct.Fields.Add("format_parameters", Value.ForStruct(paramStruct)); } } var currentLogScope = GoogleLoggerScope.Current; if (currentLogScope != null) { jsonStruct.Fields.Add("scope", Value.ForString(currentLogScope.ToString())); } // Create a map of format parameters of all the parent scopes, // starting from the most inner scope to the top-level scope. var scopeParamsList = new List <Value>(); while (currentLogScope != null) { // Determine if the state of the scope are format params if (currentLogScope.State is FormattedLogValues scopeFormatParams) { var scopeParams = new Struct(); foreach (var pair in scopeFormatParams) { scopeParams.Fields[pair.Key] = Value.ForString(pair.Value?.ToString() ?? ""); } scopeParamsList.Add(Value.ForStruct(scopeParams)); } currentLogScope = currentLogScope.Parent; } if (scopeParamsList.Count > 0) { jsonStruct.Fields.Add("parent_scopes", Value.ForList(scopeParamsList.ToArray())); } Dictionary <string, string> labels; var labelProviders = GetLabelProviders()?.ToArray(); if (labelProviders?.Length > 0) { // Create a copy of the labels from the options and invoke each provider labels = _loggerOptions.Labels.ToDictionary(kvp => kvp.Key, kvp => kvp.Value); foreach (var provider in labelProviders) { provider.Invoke(labels); } } else { labels = _loggerOptions.Labels; } LogEntry entry = new LogEntry { Resource = _loggerOptions.MonitoredResource, LogName = _fullLogName, Severity = logLevel.ToLogSeverity(), Timestamp = Timestamp.FromDateTime(_clock.GetCurrentDateTimeUtc()), JsonPayload = jsonStruct, Labels = { labels }, Trace = GetTraceName() ?? "", }; _consumer.Receive(new[] { entry }); } catch (Exception) when(_loggerOptions.RetryOptions.ExceptionHandling == ExceptionHandling.Ignore) { } }
public static SessionRequest ConvertSession(SessionModel model) => new SessionRequest { SessionId = model.ID.ToString(), Username = model.Username, LogInDateTime = Timestamp.FromDateTime(DateTime.SpecifyKind(model.LogInDateTime, DateTimeKind.Utc)) };
static async Task Main(string[] args) { using var channel = GrpcChannel.ForAddress("https://localhost:5001"); var client = new GCache.Caching.CachingClient(channel); var setCacheResponse = await client.SetCacheAsync(new CacheVM { Key = "vv", ExpiresAt = Timestamp.FromDateTime(DateTime.UtcNow.AddSeconds(5)), Value = "bbb" }); Console.WriteLine("setCacheResponse: " + JsonConvert.SerializeObject(setCacheResponse)); var getAllResponse = await client.GetCacheAsync(new CacheVM { Key = "vv" }); Console.WriteLine("setCacheResponse: " + JsonConvert.SerializeObject(getAllResponse)); var getKeyResponse = await client.GetAllAsync(new CacheVM { Key = "a" }); Console.WriteLine("setCacheResponse: " + JsonConvert.SerializeObject(getKeyResponse)); Console.WriteLine("Press any key to exit..."); Console.ReadKey(); }
#pragma warning restore CS1998 // Async method lacks 'await' operators and will run synchronously private Any GetMetadata(DateTime dateTime) => GenerateMetadata?Any.Pack(Timestamp.FromDateTime(dateTime)) : null;
protected internal override Task PackToAsyncCore(Packer packer, FILETIME objectTree, CancellationToken cancellationToken) { return(packer.PackAsync(Timestamp.FromDateTime(objectTree.ToDateTime()).Encode(), cancellationToken)); }