private async Task <Metadata> GetResponseHeadersCoreAsync() { Debug.Assert(_httpResponseTask != null); try { var httpResponse = await _httpResponseTask.ConfigureAwait(false); // Check if the headers have a status. If they do then wait for the overall call task // to complete before returning headers. This means that if the call failed with a // a status then it is possible to await response headers and then call GetStatus(). var grpcStatus = GrpcProtocolHelpers.GetHeaderValue(httpResponse.Headers, GrpcProtocolConstants.StatusTrailer); if (grpcStatus != null) { await CallTask.ConfigureAwait(false); } return(GrpcProtocolHelpers.BuildMetadata(httpResponse.Headers)); } catch (Exception ex) { ResolveException(ex, out _, out var resolvedException); throw resolvedException; } }
public void GetStatistics() { DateTime start = FilterViewModel.StartDate.Date; DateTime end = FilterViewModel.EndDate.Date.AddHours(23).AddMinutes(59).AddSeconds(59); CallTask tasksAlias = null; var baseQuery = UoW.Session.QueryOver(() => tasksAlias) .Where(() => tasksAlias.CompleteDate >= start) .And(() => tasksAlias.CompleteDate <= end); if (FilterViewModel.Employee != null) { baseQuery.And(() => tasksAlias.AssignedEmployee.Id == FilterViewModel.Employee.Id); } var callTaskQuery = baseQuery.And(() => tasksAlias.TaskState == CallTaskStatus.Call); footerViewModel.RingCount = callTaskQuery.RowCount(); var difTaskQuery = baseQuery.And(() => tasksAlias.TaskState == CallTaskStatus.DifficultClient); footerViewModel.HardClientsCount = difTaskQuery.RowCount(); var jobTaskQuery = baseQuery.And(() => tasksAlias.TaskState == CallTaskStatus.Task); footerViewModel.TasksCount = jobTaskQuery.RowCount(); footerViewModel.Tasks = DataLoader.Items.Count; footerViewModel.TareReturn = DataLoader.Items.OfType <BusinessTaskJournalNode>().Sum(x => x.TareReturn); }
private async Task <Metadata> GetResponseHeadersCoreAsync() { CompatibilityExtensions.Assert(_httpResponseTask != null); try { var httpResponse = await _httpResponseTask.ConfigureAwait(false); // Check if the headers have a status. If they do then wait for the overall call task // to complete before returning headers. This means that if the call failed with a // a status then it is possible to await response headers and then call GetStatus(). var grpcStatus = GrpcProtocolHelpers.GetHeaderValue(httpResponse.Headers, GrpcProtocolConstants.StatusTrailer); if (grpcStatus != null) { await CallTask.ConfigureAwait(false); } var metadata = GrpcProtocolHelpers.BuildMetadata(httpResponse.Headers); // https://github.com/grpc/proposal/blob/master/A6-client-retries.md#exposed-retry-metadata if (_attemptCount > 1) { metadata.Add(GrpcProtocolConstants.RetryPreviousAttemptsHeader, (_attemptCount - 1).ToString(CultureInfo.InvariantCulture)); } return(metadata); } catch (Exception ex) when(ResolveException(ErrorStartingCallMessage, ex, out _, out var resolvedException)) { throw resolvedException; } }
public CallTask FillNewTask(IUnitOfWork uow, CallTask callTask, IEmployeeRepository employeeRepository) { callTask.CreationDate = DateTime.Now; callTask.TaskCreator = employeeRepository.GetEmployeeForCurrentUser(uow); callTask.EndActivePeriod = DateTime.Now.Date.AddHours(23).AddMinutes(59).AddSeconds(59); return(callTask); }
//Создаёт задачу если клиент переехал private void CreateTaskIfCounterpartyRelocated(Order order, IUnitOfWork uow) { if ( //Есть тара на возврат !order.BottlesReturn.HasValue || order.BottlesReturn.Value == 0 //Указана точка доставки || order.SelfDelivery || order.DeliveryPoint == null //Нет заказов на указанную точку доставки || uow.Session.QueryOver <Order>().Where(x => x.DeliveryPoint == order.DeliveryPoint).List().Any(x => x.Id != order.Id) //Нет созданных CallTask на указанную точку доставки || uow.Session.QueryOver <CallTask>().Where(x => x.DeliveryPoint == order.DeliveryPoint).List().Any() //Есть заказы на другую точку доставки || !uow.Session.QueryOver <Order>() .Where(x => x.Client == order.Client) .Where(x => !x.SelfDelivery) .Where(x => x.DeliveryPoint != order.DeliveryPoint) .List().Any(x => x.Id != order.Id) ) { return; } var newTask = new CallTask(); callTaskFactory.FillNewTask(uow, newTask, employeeRepository); newTask.AssignedEmployee = uow.GetById <Employee>(personProvider.GetDefaultEmployeeForCallTask()); newTask.TaskState = CallTaskStatus.Task; newTask.DeliveryPoint = order.DeliveryPoint; newTask.Counterparty = order.Client; newTask.EndActivePeriod = DateTime.Now.Date.AddHours(23).AddMinutes(59); newTask.SourceDocumentId = order.Id; newTask.Source = TaskSource.AutoFromOrder; uow.Save(newTask); }
private void FillFromOrder(IUnitOfWork uow, CallTask callTask, IPersonProvider personProvider, Order order) { callTask.Counterparty = uow.GetById <Counterparty>(order.Client.Id); callTask.DeliveryPoint = uow.GetById <DeliveryPoint>(order.DeliveryPoint.Id); callTask.TaskState = CallTaskStatus.Reconciliation; callTask.AssignedEmployee = uow.GetById <Employee>(personProvider.GetDefaultEmployeeForCallTask()); callTask.SourceDocumentId = order.Id; }
public CallTask CreateCopyTask(IUnitOfWork uow, IEmployeeRepository employeeRepository, CallTask originTask) { var task = new CallTask { DeliveryPoint = uow.GetById <DeliveryPoint>(originTask.DeliveryPoint.Id), Counterparty = uow.GetById <Counterparty>(originTask.Counterparty.Id), AssignedEmployee = uow.GetById <Employee>(originTask.AssignedEmployee.Id) }; FillNewTask(uow, task, employeeRepository); return(task); }
/// <summary> /// Resolve the specified exception to an end-user exception that will be thrown from the client. /// The resolved exception is normally a RpcException. Returns true when the resolved exception is changed. /// </summary> internal bool ResolveException(string summary, Exception ex, [NotNull] out Status?status, out Exception resolvedException) { if (ex is OperationCanceledException) { status = (CallTask.IsCompletedSuccessfully()) ? CallTask.Result : new Status(StatusCode.Cancelled, string.Empty); if (!Channel.ThrowOperationCanceledOnCancellation) { resolvedException = CreateRpcException(status.Value); return(true); } } else if (ex is RpcException rpcException) { status = rpcException.Status; // If trailers have been set, and the RpcException isn't using them, then // create new RpcException with trailers. Want to try and avoid this as // the exact stack location will be lost. // // Trailers could be set in another thread so copy to local variable. var trailers = Trailers; if (trailers != null && rpcException.Trailers != trailers) { resolvedException = CreateRpcException(status.Value); return(true); } } else { var s = GrpcProtocolHelpers.CreateStatusFromException(summary, ex); // The server could exceed the deadline and return a CANCELLED status before the // client's deadline timer is triggered. When CANCELLED is received check the // deadline against the clock and change status to DEADLINE_EXCEEDED if required. if (s.StatusCode == StatusCode.Cancelled) { lock (this) { if (IsDeadlineExceededUnsynchronized()) { s = new Status(StatusCode.DeadlineExceeded, s.Detail, s.DebugException); } } } status = s; resolvedException = CreateRpcException(s); return(true); } resolvedException = ex; return(false); }
public Status GetStatus() { using (StartScope()) { if (CallTask.IsCompletedSuccessfully()) { return(CallTask.Result); } throw new InvalidOperationException("Unable to get the status because the call is not complete."); } }
public IEnumerable <CallTask> GetAutoGeneratedTask(IUnitOfWork UoW, Domain.Orders.Order order, CallTaskStatus?taskStatus = null) { CallTask callTaskAlias = null; return(UoW.Session.QueryOver(() => callTaskAlias) .Where(x => x.SourceDocumentId.Value == order.Id) .And(x => x.Source == TaskSource.AutoFromOrder) .And(x => x.Comment == null) .And(x => !x.IsTaskComplete) .And(x => taskStatus == null || x.TaskState == taskStatus.Value) .Take(1) .List()); }
private bool UpdateDepositReturnTask(Order order) { bool createTask = false; var equipmentToClient = order.OrderEquipments.Where(x => x.Direction == Direction.Deliver); var equipmentFromClient = order.OrderEquipments.Where(x => x.Direction == Direction.PickUp); foreach (var item in equipmentFromClient.ToList()) { if (!equipmentToClient.ToList().Any(x => x.Nomenclature.Id == item.Nomenclature.Id)) { createTask = true; } } if (!createTask) { return(false); } CallTask activeTask; if (order.SelfDelivery) { activeTask = callTaskRepository.GetActiveSelfDeliveryTaskByCounterparty(order.UoW, order.Client, CallTaskStatus.DepositReturn, 1)?.FirstOrDefault(); } else { activeTask = callTaskRepository.GetActiveTaskByDeliveryPoint(order.UoW, order.DeliveryPoint, CallTaskStatus.DepositReturn, 1)?.FirstOrDefault(); } if (activeTask != null) { return(false); } var newTask = new CallTask(); callTaskFactory.FillNewTask(order.UoW, newTask, employeeRepository); newTask.AssignedEmployee = order.UoW.GetById <Employee>(personProvider.GetDefaultEmployeeForDepositReturnTask()); newTask.TaskState = CallTaskStatus.DepositReturn; newTask.DeliveryPoint = order.DeliveryPoint; newTask.Counterparty = order.Client; newTask.EndActivePeriod = DateTime.Now.Date.AddHours(23).AddMinutes(59); newTask.SourceDocumentId = order.Id; newTask.Source = TaskSource.AutoFromOrder; order.UoW.Save(newTask); return(true); }
public string GetCommentsByDeliveryPoint(IUnitOfWork UoW, DeliveryPoint deliveryPoint, CallTask currentCallTask) { CallTask callTaskAlias = null; string comments = String.Empty; var tasks = UoW.Session.QueryOver(() => callTaskAlias) .Where(x => x.DeliveryPoint.Id == deliveryPoint.Id) .And(x => x.Id != currentCallTask.Id) .List(); foreach (var task in tasks) { comments += task.Comment; } return(comments); }
public IEnumerable <CallTask> GetActiveTaskByDeliveryPoint(IUnitOfWork UoW, DeliveryPoint deliveryPoint, CallTaskStatus?taskStatus = null, int?limit = null) { CallTask callTaskAlias = null; DeliveryPoint deliveryPointAlias = null; var tasks = UoW.Session.QueryOver(() => callTaskAlias) .JoinAlias(x => x.DeliveryPoint, () => deliveryPointAlias, NHibernate.SqlCommand.JoinType.LeftOuterJoin) .Where(() => deliveryPointAlias.Id == deliveryPoint.Id) .And(x => !x.IsTaskComplete) .And(x => taskStatus == null || x.TaskState == taskStatus.Value); if (limit.HasValue) { tasks.Take(limit.Value); } return(tasks.List()); }
public CallTask CreateTask(IUnitOfWork uow, IEmployeeRepository employeeRepository, IPersonProvider personProvider, CallTask newTask = null, object source = null, string creationComment = null) { CallTask callTask = newTask ?? new CallTask(); FillNewTask(uow, callTask, employeeRepository); switch (source) { case Order order: FillFromOrder(uow, callTask, personProvider, order); break; } if (creationComment != null) { callTask.AddComment(uow, creationComment, employeeRepository); } return(callTask); }
/// <summary> /// Resolve the specified exception to an end-user exception that will be thrown from the client. /// The resolved exception is normally a RpcException. Returns true when the resolved exception is changed. /// </summary> internal bool ResolveException(string summary, Exception ex, [NotNull] out Status?status, out Exception resolvedException) { if (ex is OperationCanceledException) { status = (CallTask.IsCompletedSuccessfully()) ? CallTask.Result : new Status(StatusCode.Cancelled, string.Empty); if (!Channel.ThrowOperationCanceledOnCancellation) { resolvedException = CreateRpcException(status.Value); return(true); } } else if (ex is RpcException rpcException) { status = rpcException.Status; // If trailers have been set, and the RpcException isn't using them, then // create new RpcException with trailers. Want to try and avoid this as // the exact stack location will be lost. // // Trailers could be set in another thread so copy to local variable. var trailers = Trailers; if (trailers != null && rpcException.Trailers != trailers) { resolvedException = CreateRpcException(status.Value); return(true); } } else { var exceptionMessage = CommonGrpcProtocolHelpers.ConvertToRpcExceptionMessage(ex); var statusCode = GrpcProtocolHelpers.ResolveRpcExceptionStatusCode(ex); status = new Status(statusCode, summary + " " + exceptionMessage, ex); resolvedException = CreateRpcException(status.Value); return(true); } resolvedException = ex; return(false); }
public IEnumerable <CallTask> GetActiveSelfDeliveryTaskByCounterparty(IUnitOfWork UoW, Counterparty counterparty, CallTaskStatus?taskStatus = null, int?limit = null) { CallTask callTaskAlias = null; DeliveryPoint deliveryPointAlias = null; Counterparty counterpartyAlias = null; var tasks = UoW.Session.QueryOver(() => callTaskAlias) .JoinAlias(() => callTaskAlias.DeliveryPoint, () => deliveryPointAlias, NHibernate.SqlCommand.JoinType.LeftOuterJoin) .JoinAlias(() => callTaskAlias.Counterparty, () => counterpartyAlias, NHibernate.SqlCommand.JoinType.LeftOuterJoin) .Where(Restrictions.On(() => deliveryPointAlias.Id).IsNull) .And(() => counterpartyAlias.Id == counterparty.Id) .And(x => !x.IsTaskComplete); if (taskStatus.HasValue) { tasks = tasks.Where(() => callTaskAlias.TaskState == taskStatus.Value); } if (limit.HasValue) { tasks.Take(limit.Value); } return(tasks.List()); }
private bool UpdateCallTask(Order order) { IEnumerable <CallTask> tasks; if (order.SelfDelivery) { tasks = callTaskRepository.GetActiveSelfDeliveryTaskByCounterparty(order.UoW, order.Client, CallTaskStatus.Call); } else { tasks = callTaskRepository.GetActiveTaskByDeliveryPoint(order.UoW, order.DeliveryPoint, CallTaskStatus.Call); } if (tasks?.FirstOrDefault() == null) { return(false); } DateTime?dateTime = null; if (TaskCreationInteractive != null) { if (TaskCreationInteractive.RunQuestion(ref dateTime) == CreationTaskResult.Cancel) { return(false); } } bool autoDate = false; if (dateTime == null) { autoDate = true; int? ordersCount; double dif = orderRepository.GetAvgRangeBetweenOrders(order.UoW, order.DeliveryPoint, out ordersCount); dateTime = (ordersCount.HasValue && ordersCount.Value >= 3) ? order.DeliveryDate.Value.AddDays(dif) : DateTime.Now.AddMonths(1); } var newTask = new CallTask(); callTaskFactory.FillNewTask(order.UoW, newTask, employeeRepository); newTask.AssignedEmployee = tasks?.OrderBy(x => x.EndActivePeriod).LastOrDefault().AssignedEmployee; newTask.TaskState = CallTaskStatus.Call; newTask.DeliveryPoint = order.DeliveryPoint; newTask.Counterparty = order.Client; newTask.EndActivePeriod = dateTime.Value; newTask.SourceDocumentId = order.Id; newTask.Source = TaskSource.AutoFromOrder; order.UoW.Save(newTask); if (tasks?.FirstOrDefault() != null) { foreach (var task in tasks) { string comment; task.IsTaskComplete = true; if (autoDate) { comment = $"Автоперенос задачи на {dateTime?.ToString("dd/MM/yyyy")}"; } else { comment = $"Ручной перенос задачи на {dateTime?.ToString("dd/MM/yyyy")}"; } task.AddComment(order.UoW, comment); order.UoW.Save(task); } } return(true); }
private void Calls_Load(object sender, EventArgs e) { _callTask = new CallTask(); _callTask.CallReceived += OnCallReceived; }
public Exception CreateCanceledStatusException() { var status = (CallTask.IsCompletedSuccessfully()) ? CallTask.Result : new Status(StatusCode.Cancelled, string.Empty); return(CreateRpcException(status)); }
private async ValueTask RunCall(HttpRequestMessage request) { using (StartScope()) { var(diagnosticSourceEnabled, activity) = InitializeCall(request); if (Options.Credentials != null || Channel.CallCredentials?.Count > 0) { await ReadCredentials(request).ConfigureAwait(false); } Status?status = null; try { try { HttpResponse = await Channel.HttpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, _callCts.Token).ConfigureAwait(false); } catch (Exception ex) { GrpcCallLog.ErrorStartingCall(Logger, ex); throw; } BuildMetadata(HttpResponse); status = ValidateHeaders(HttpResponse); // A status means either the call has failed or grpc-status was returned in the response header if (status != null) { if (_responseTcs != null) { // gRPC status in the header if (status.Value.StatusCode != StatusCode.OK) { SetFailedResult(status.Value); } else { // The server should never return StatusCode.OK in the header for a unary call. // If it does then throw an error that no message was returned from the server. GrpcCallLog.MessageNotReturned(Logger); _responseTcs.TrySetException(new InvalidOperationException("Call did not return a response message.")); } } FinishResponse(status.Value); } else { if (_responseTcs != null) { // Read entire response body immediately and read status from trailers // Trailers are only available once the response body had been read var responseStream = await HttpResponse.Content.ReadAsStreamAsync().ConfigureAwait(false); var message = await responseStream.ReadMessageAsync( Logger, Method.ResponseMarshaller.ContextualDeserializer, GrpcProtocolHelpers.GetGrpcEncoding(HttpResponse), Channel.ReceiveMaxMessageSize, Channel.CompressionProviders, singleMessage : true, _callCts.Token).ConfigureAwait(false); status = GrpcProtocolHelpers.GetResponseStatus(HttpResponse); FinishResponse(status.Value); if (message == null) { GrpcCallLog.MessageNotReturned(Logger); SetFailedResult(status.Value); } else { GrpcEventSource.Log.MessageReceived(); if (status.Value.StatusCode == StatusCode.OK) { _responseTcs.TrySetResult(message); } else { SetFailedResult(status.Value); } } } else { // Duplex or server streaming call Debug.Assert(ClientStreamReader != null); ClientStreamReader.HttpResponseTcs.TrySetResult((HttpResponse, status)); // Wait until the response has been read and status read from trailers. // TCS will also be set in Dispose. status = await CallTask.ConfigureAwait(false); } } } catch (Exception ex) { Exception resolvedException; if (ex is OperationCanceledException) { status = (CallTask.IsCompletedSuccessfully) ? CallTask.Result : new Status(StatusCode.Cancelled, string.Empty); resolvedException = Channel.ThrowOperationCanceledOnCancellation ? ex : CreateRpcException(status.Value); } else if (ex is RpcException rpcException) { status = rpcException.Status; resolvedException = CreateRpcException(status.Value); } else { status = new Status(StatusCode.Internal, "Error starting gRPC call: " + ex.Message); resolvedException = CreateRpcException(status.Value); } _metadataTcs.TrySetException(resolvedException); _responseTcs?.TrySetException(resolvedException); Cleanup(status !.Value); } FinishCall(request, diagnosticSourceEnabled, activity, status); } }
private async Task RunCall(HttpRequestMessage request, TimeSpan?timeout) { using (StartScope()) { var(diagnosticSourceEnabled, activity) = InitializeCall(request, timeout); if (Options.Credentials != null || Channel.CallCredentials?.Count > 0) { await ReadCredentials(request).ConfigureAwait(false); } // Unset variable to check that FinishCall is called in every code path bool finished; Status?status = null; try { // Fail early if deadline has already been exceeded _callCts.Token.ThrowIfCancellationRequested(); try { // If a HttpClient has been specified then we need to call it with ResponseHeadersRead // so that the response message is available for streaming _httpResponseTask = (Channel.HttpInvoker is HttpClient httpClient) ? httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, _callCts.Token) : Channel.HttpInvoker.SendAsync(request, _callCts.Token); HttpResponse = await _httpResponseTask.ConfigureAwait(false); } catch (Exception ex) { // Don't log OperationCanceledException if deadline has exceeded. if (ex is OperationCanceledException && _callTcs.Task.IsCompletedSuccessfully && _callTcs.Task.Result.StatusCode == StatusCode.DeadlineExceeded) { throw; } else { GrpcCallLog.ErrorStartingCall(Logger, ex); throw; } } status = ValidateHeaders(HttpResponse); // A status means either the call has failed or grpc-status was returned in the response header if (status != null) { if (_responseTcs != null) { // gRPC status in the header if (status.Value.StatusCode != StatusCode.OK) { finished = FinishCall(request, diagnosticSourceEnabled, activity, status.Value); } else { // The server should never return StatusCode.OK in the header for a unary call. // If it does then throw an error that no message was returned from the server. GrpcCallLog.MessageNotReturned(Logger); // Change the status code to a more accurate status. // This is consistent with Grpc.Core client behavior. status = new Status(StatusCode.Internal, "Failed to deserialize response message."); finished = FinishCall(request, diagnosticSourceEnabled, activity, status.Value); } FinishResponseAndCleanUp(status.Value); // Set failed result makes the response task thrown an error. Must be called after // the response is finished. Reasons: // - Finishing the response sets the status. Required for GetStatus to be successful. // - We want GetStatus to always work when called after the response task is done. SetFailedResult(status.Value); } else { finished = FinishCall(request, diagnosticSourceEnabled, activity, status.Value); FinishResponseAndCleanUp(status.Value); } } else { if (_responseTcs != null) { // Read entire response body immediately and read status from trailers // Trailers are only available once the response body had been read var responseStream = await HttpResponse.Content.ReadAsStreamAsync().ConfigureAwait(false); var message = await ReadMessageAsync( responseStream, GrpcProtocolHelpers.GetGrpcEncoding(HttpResponse), singleMessage : true, _callCts.Token).ConfigureAwait(false); status = GrpcProtocolHelpers.GetResponseStatus(HttpResponse, Channel.OperatingSystem.IsBrowser); if (message == null) { GrpcCallLog.MessageNotReturned(Logger); if (status.Value.StatusCode == StatusCode.OK) { // Change the status code if OK is returned to a more accurate status. // This is consistent with Grpc.Core client behavior. status = new Status(StatusCode.Internal, "Failed to deserialize response message."); } FinishResponseAndCleanUp(status.Value); finished = FinishCall(request, diagnosticSourceEnabled, activity, status.Value); // Set failed result makes the response task thrown an error. Must be called after // the response is finished. Reasons: // - Finishing the response sets the status. Required for GetStatus to be successful. // - We want GetStatus to always work when called after the response task is done. SetFailedResult(status.Value); } else { GrpcEventSource.Log.MessageReceived(); FinishResponseAndCleanUp(status.Value); finished = FinishCall(request, diagnosticSourceEnabled, activity, status.Value); if (status.Value.StatusCode == StatusCode.OK) { _responseTcs.TrySetResult(message); } else { // Set failed result makes the response task thrown an error. Must be called after // the response is finished. Reasons: // - Finishing the response sets the status. Required for GetStatus to be successful. // - We want GetStatus to always work when called after the response task is done. SetFailedResult(status.Value); } } } else { // Duplex or server streaming call Debug.Assert(ClientStreamReader != null); ClientStreamReader.HttpResponseTcs.TrySetResult((HttpResponse, status)); // Wait until the response has been read and status read from trailers. // TCS will also be set in Dispose. status = await CallTask.ConfigureAwait(false); finished = FinishCall(request, diagnosticSourceEnabled, activity, status.Value); Cleanup(status.Value); } } } catch (Exception ex) { Exception resolvedException; ResolveException(ErrorStartingCallMessage, ex, out status, out resolvedException); finished = FinishCall(request, diagnosticSourceEnabled, activity, status.Value); _responseTcs?.TrySetException(resolvedException); Cleanup(status.Value); } // Verify that FinishCall is called in every code path of this method. // Should create an "Unassigned variable" compiler error if not set. Debug.Assert(finished); } }
public void CopyTask(IUnitOfWork uow, IEmployeeRepository employeeRepository, CallTask copyFrom, CallTask copyTo) { copyTo.DeliveryPoint = copyFrom.DeliveryPoint != null?uow.GetById <DeliveryPoint>(copyFrom.DeliveryPoint.Id) : null; copyTo.Counterparty = uow.GetById <Counterparty>(copyFrom.Counterparty.Id); copyTo.AssignedEmployee = copyFrom.AssignedEmployee != null?uow.GetById <Employee>(copyFrom.AssignedEmployee.Id) : null; copyTo.TaskCreator = employeeRepository.GetEmployeeForCurrentUser(uow); copyTo.CreationDate = DateTime.Now; copyTo.EndActivePeriod = DateTime.Now.Date.AddHours(23).AddMinutes(59).AddSeconds(59); }
private async ValueTask RunCall(HttpRequestMessage request, TimeSpan?timeout) { using (StartScope()) { var(diagnosticSourceEnabled, activity) = InitializeCall(request, timeout); if (Options.Credentials != null || Channel.CallCredentials?.Count > 0) { await ReadCredentials(request).ConfigureAwait(false); } // Unset variable to check that FinishCall is called in every code path bool finished; Status?status = null; try { // Fail early if deadline has already been exceeded _callCts.Token.ThrowIfCancellationRequested(); try { _httpResponseTask = Channel.HttpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, _callCts.Token); HttpResponse = await _httpResponseTask.ConfigureAwait(false); } catch (Exception ex) { GrpcCallLog.ErrorStartingCall(Logger, ex); throw; } status = ValidateHeaders(HttpResponse); // A status means either the call has failed or grpc-status was returned in the response header if (status != null) { if (_responseTcs != null) { // gRPC status in the header if (status.Value.StatusCode != StatusCode.OK) { finished = FinishCall(request, diagnosticSourceEnabled, activity, status.Value); SetFailedResult(status.Value); } else { // The server should never return StatusCode.OK in the header for a unary call. // If it does then throw an error that no message was returned from the server. GrpcCallLog.MessageNotReturned(Logger); finished = FinishCall(request, diagnosticSourceEnabled, activity, status.Value); _responseTcs.TrySetException(new InvalidOperationException("Call did not return a response message.")); } FinishResponseAndCleanUp(status.Value); } else { finished = FinishCall(request, diagnosticSourceEnabled, activity, status.Value); FinishResponseAndCleanUp(status.Value); } } else { if (_responseTcs != null) { // Read entire response body immediately and read status from trailers // Trailers are only available once the response body had been read var responseStream = await HttpResponse.Content.ReadAsStreamAsync().ConfigureAwait(false); var message = await responseStream.ReadMessageAsync( Logger, Method.ResponseMarshaller.ContextualDeserializer, GrpcProtocolHelpers.GetGrpcEncoding(HttpResponse), Channel.ReceiveMaxMessageSize, Channel.CompressionProviders, singleMessage : true, _callCts.Token).ConfigureAwait(false); status = GrpcProtocolHelpers.GetResponseStatus(HttpResponse); FinishResponseAndCleanUp(status.Value); if (message == null) { GrpcCallLog.MessageNotReturned(Logger); finished = FinishCall(request, diagnosticSourceEnabled, activity, status.Value); SetFailedResult(status.Value); } else { GrpcEventSource.Log.MessageReceived(); finished = FinishCall(request, diagnosticSourceEnabled, activity, status.Value); if (status.Value.StatusCode == StatusCode.OK) { _responseTcs.TrySetResult(message); } else { SetFailedResult(status.Value); } } } else { // Duplex or server streaming call Debug.Assert(ClientStreamReader != null); ClientStreamReader.HttpResponseTcs.TrySetResult((HttpResponse, status)); // Wait until the response has been read and status read from trailers. // TCS will also be set in Dispose. status = await CallTask.ConfigureAwait(false); finished = FinishCall(request, diagnosticSourceEnabled, activity, status.Value); FinishResponseAndCleanUp(status.Value); } } } catch (Exception ex) { Exception resolvedException; ResolveException(ex, out status, out resolvedException); finished = FinishCall(request, diagnosticSourceEnabled, activity, status.Value); _responseTcs?.TrySetException(resolvedException); Cleanup(status.Value); } // Verify that FinishCall is called in every code path of this method. // Should create an "Unassigned variable" compiler error if not set. Debug.Assert(finished); } }
/// <summary> /// Executes the default target and wraps in error handling and time /// stamping. /// </summary> /// <returns> /// <see langword="true" /> if the build was successful; otherwise, /// <see langword="false" />. /// </returns> public bool Run() { Exception error = null; try { OnBuildStarted(this, new BuildEventArgs(this)); // output build file that we're running Log(Level.Info, "Buildfile: {0}", BuildFileUri); // output current target framework in build log Log(Level.Info, "Target framework: {0}", TargetFramework != null ? TargetFramework.Description : "None"); // write verbose project information after Initialize to make // sure properties are correctly initialized Log(Level.Verbose, "Base Directory: {0}.", BaseDirectory); // execute the project Execute(); // signal build success return true; } catch (BuildException e) { // store exception in error variable in order to include it // in the BuildFinished event. error = e; // log exception details to log4net logger.Error("Build failed.", e); // signal build failure return false; } catch (Exception e) { // store exception in error variable in order to include it // in the BuildFinished event. error = e; // log exception details to log4net logger.Fatal("Build failed.", e); // signal build failure return false; } finally { string endTarget; if (error == null) { endTarget = Properties[CIScriptPropertyOnSuccess]; } else { endTarget = Properties[CIScriptPropertyOnFailure]; } // TO-DO : remove this after release of CIScript 0.8.4 or so string deprecatedFailureTarget = Properties["ciscript.failure"]; if (!StringUtils.IsNullOrEmpty(deprecatedFailureTarget)) { Log(Level.Warning, "The 'ciscript.failure' property has been deprecated." + " You should use '{0}' to designate the target that should be" + " executed when the build fails." + Environment.NewLine, Project.CIScriptPropertyOnFailure); if (error != null) { Execute(deprecatedFailureTarget); } } if (!StringUtils.IsNullOrEmpty(endTarget)) { // executing the target identified by the 'ciscript.onsuccess' // or 'ciscript.onfailure' properties should not affect the // build outcome CallTask callTask = new CallTask(); callTask.Parent = this; callTask.Project = this; callTask.NamespaceManager = NamespaceManager; callTask.Verbose = Verbose; callTask.FailOnError = false; callTask.TargetName = endTarget; callTask.Execute(); } // fire BuildFinished event with details of build outcome BuildEventArgs buildFinishedArgs = new BuildEventArgs(this); buildFinishedArgs.Exception = error; OnBuildFinished(this, buildFinishedArgs); } }