public async Task <IActionResult> PutRoundtrip([FromRoute] int id, [FromBody] Roundtrip roundtrip) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } if (id != roundtrip.Id) { return(BadRequest()); } _context.Entry(roundtrip).State = EntityState.Modified; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!RoundtripExists(id)) { return(NotFound()); } else { throw; } } return(NoContent()); }
public void Exit(Roundtrip roundtrip) { if (roundtrip == null) { throw new InvestingDomainException("Roundtrip not provided;"); } if (roundtrip.InvestmentId != this.InvestmentId) { throw new InvestingDomainException("InvestmentId not match."); } if (roundtrip.RoundtripNumber != this.RoundtripNumber) { throw new InvestingDomainException("RoundtripNumber not match."); } if (roundtrip.RoundtripStatus.Id != RoundtripStatus.Exit.Id && roundtrip.RoundtripStatus.Id != RoundtripStatus.ForceExit.Id) { throw new InvestingDomainException("The Roundtrip's status must be exit."); } if (this.IsFinished()) { throw new InvestingDomainException("InvestmentRoundtrip is already exit."); } var exitBalance = roundtrip.ExitBalance; this.ExitBalance = exitBalance; }
public async Task Handle(InvestmentRoundtripCreatedDomainEvent investmentRoundtripCreatedDomainEvent, CancellationToken cancellationToken) { try { var roundtrip = new Roundtrip( investmentRoundtripCreatedDomainEvent.InvestmentId, investmentRoundtripCreatedDomainEvent.RoundtripNumber, investmentRoundtripCreatedDomainEvent.Market, investmentRoundtripCreatedDomainEvent.EntryBalance, investmentRoundtripCreatedDomainEvent.ExecutePrice, investmentRoundtripCreatedDomainEvent.TargetPrice, investmentRoundtripCreatedDomainEvent.StopLossPrice, investmentRoundtripCreatedDomainEvent.DateCreated ); _roundtripRepository.Add(roundtrip); await _roundtripRepository.UnitOfWork .SaveEntitiesAsync(); } catch (Exception ex) { Console.WriteLine("Handle Domain Event: InvestmentRoundtripCreatedDomainEvent."); Console.WriteLine("Result: Failure."); Console.WriteLine("Error Message: " + ex.Message); } }
public RoundtripExitOrderSubmittedDomainEvent(Roundtrip roundtrip, string investmentId, string roundtripId, RoundtripStatus roundtripStatus, Market market, decimal exitAmount, decimal exitPrice, DateTime adviceCreationDate) { Roundtrip = roundtrip; InvestmentId = investmentId; RoundtripId = roundtripId; RoundtripStatus = roundtripStatus; Market = market; ExitAmount = exitAmount; ExitPrice = exitPrice; AdviceCreationDate = adviceCreationDate; }
/// <summary> /// Method that save received data in tables of database /// </summary> /// <param name="dep_time">departure time</param> /// <param name="arr_time">arrival time</param> /// <param name="rDepTime">return departure time</param> /// <param name="rArrTime">return arrival time</param> /// <param name="cost">price of flight</param> /// <param name="airline">airline company that provide the flight</param> /// <param name="siteName">the name of website</param> /// <param name="leg">index of investigated route</param> private void SaveDataInDatabase(string dep_time, string arr_time, string rDepTime, string rArrTime, string cost, List <string> airline, string siteName, int leg) { Roundtrip roundtrip = new Roundtrip(); SearchResult result = new SearchResult(); Database.Database database = new Database.Database(_controller.Config.DatabaseRemote, _controller.Config.DatabaseUser, _controller.Config.DatabasePassword, _controller.Config.DatabaseName, (uint)_controller.Config.DatabasePort); if (_controller.ArrivalDate != null) { roundtrip.ArrDate = DateTime.Parse($"{_controller.ArrivalDate:d}"); roundtrip.DepTime = DateTime.Parse(rArrTime); roundtrip.ArrTime = DateTime.Parse(rDepTime); roundtrip.DepDate = roundtrip.ArrTime > roundtrip.DepTime ? roundtrip.ArrDate : roundtrip.ArrDate.AddDays(1); roundtrip.Departure = _controller.FlightLegs[leg].Arrival; roundtrip.Arrival = _controller.FlightLegs[leg].Departure; roundtrip.ServiceClass = 2; roundtrip.ValidateCarrier = database.GetAirlineCode(airline[0]); } result.SearchTime = DateTime.Now; result.DepDate = DateTime.Parse($"{_controller.DepartureDate:d}"); result.DepTime = DateTime.Parse(dep_time); result.ArrTime = DateTime.Parse(arr_time); result.ArrDate = result.ArrTime < result.DepTime ? result.DepDate.AddDays(1) : result.DepDate; result.Price = decimal.Parse(cost); result.ValidateCarrier = database.GetAirlineCode(airline[0]); result.ServiceClass = 2; result.Type1 = 3; result.Url = siteName; result.Departure = _controller.FlightLegs[leg].Departure; result.Arrival = _controller.FlightLegs[leg].Arrival; if (roundtrip.ValidateCarrier == null) { roundtrip.ValidateCarrier = result.ValidateCarrier; } if (roundtrip.ArrTime != null) { int rid = database.RoundtripIsExistsInDatabase(roundtrip); if (rid != 0) { result.Rtrip = 1; result.RoundtripId = rid; } else { rid = database.InsertRoundtripsToDatabase(roundtrip); result.Rtrip = 1; result.RoundtripId = rid; } } if (database.SearchResultsIsExistsInDatabase(result) == 0) { var n = database.InsertSearchResultsToDatabase(result); } }
public async Task <IActionResult> PostRoundtrip([FromBody] Roundtrip roundtrip) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } _context.Roundtrips.Add(roundtrip); await _context.SaveChangesAsync(); return(CreatedAtAction("GetRoundtrip", new { id = roundtrip.Id }, roundtrip)); }
public Roundtrip Add(Roundtrip roundtrip) { if (roundtrip.IsTransient()) { return(_context.Roundtrips .Add(roundtrip) .Entity); } else { return(roundtrip); } }
private void LogRequestDetails(Action <Enum, string> logDetail, Roundtrip roundtrip, bool exceptionThrown) { string arg = string.Join(" ", from request in roundtrip.RequestBatch.Requests select CobaltStore.GetRequestNameAndPartition(request)); logDetail(WacRequestHandlerMetadata.CobaltOperations, arg); StringBuilder stringBuilder = new StringBuilder(); bool flag = false; foreach (Request request2 in roundtrip.RequestBatch.Requests) { if (request2.Failed) { flag = true; stringBuilder.Append(request2.GetType().Name); stringBuilder.Append(" failed. "); try { string conciseLoggingStatement = Log.GetConciseLoggingStatement(request2, this.userAddress); if (exceptionThrown || request2.Failed) { stringBuilder.AppendLine(conciseLoggingStatement); } } catch (ErrorException) { stringBuilder.AppendLine("Concise logging not supported."); } } } try { roundtrip.ThrowIfAnyError(); } catch (Exception ex) { exceptionThrown = true; stringBuilder.AppendLine("ThrowIfAnyError: " + ex.ToString()); } if (exceptionThrown || flag) { logDetail(WacRequestHandlerMetadata.ErrorDetails, stringBuilder.ToString()); } }
public void RoundtripExit(Roundtrip roundtrip) { if (this._investmentStatusId != InvestmentStatus.Started.Id && this._investmentStatusId != InvestmentStatus.ForcedClosing.Id) { throw new InvestingDomainException("A roundtrip should exist after started and before close."); } if (roundtrip.InvestmentId != this.InvestmentId) { throw new InvestingDomainException("The investmentId of roundtrip must match the investment's Id."); } var roundtripNumber = roundtrip.RoundtripNumber; var existingRoundtrip = this._investmentRoundtrips.Where(r => r.RoundtripNumber == roundtripNumber).SingleOrDefault(); if (existingRoundtrip == null) { throw new InvestingDomainException($"The roundtrip with number {roundtrip.RoundtripNumber} was not found."); } existingRoundtrip.Exit(roundtrip); this.UpdateCurrentBalance( this.CurrentBalance + existingRoundtrip.ExitBalance ?? throw new InvestingDomainException("Exit balance missing.")); //Close investment if the fund is almost lost. if (this.CurrentBalance <= this.InitialBalance * 0.1M) { this.Close(); } //Check if this is forced closing. if (this._investmentStatusId == InvestmentStatus.ForcedClosing.Id) { this.Close(forceClose: true); } }
public async Task Handle(BacktestingPriceChangedIntegrationEvent @event) { IEnumerable <Roundtrip> roundtrips = null; Roundtrip roundtrip = null; try { roundtrips = await this._roundtripRepository.GetByInvestmentId(@event.InvestmentId); roundtrip = roundtrips.Where(r => r.GetStatus().Id == RoundtripStatus.Entry.Id).SingleOrDefault(); } catch (Exception ex) { Console.WriteLine("Handle IntegrationEvent Event: BacktestingPriceChangedIntegrationEventHandler."); Console.WriteLine("Result: Failure."); Console.WriteLine("Error Message: " + ex.Message); } try { if (roundtrip != null) { roundtrip.PriceChanged(@event.LowestPrice, @event.BacktestingCurrentTime, @event.HighestPrice, @event.LowestPrice, @event.TargetPrice); this._roundtripRepository.Update(roundtrip); await _roundtripRepository.UnitOfWork .SaveEntitiesAsync(); } } catch (Exception ex) { Console.WriteLine("Handle IntegrationEvent Event: BacktestingPriceChangedIntegrationEventHandler."); Console.WriteLine("Result: Failure."); Console.WriteLine("Error Message: " + ex.Message); } }
public void ProcessRequest(Stream requestStream, Stream responseStream, Action <Enum, string> logDetail) { if (this.permanentException != null) { throw new CobaltStore.OrphanedCobaltStoreException(string.Format("The attachment is no longer available for CobaltStore {0}.", this.correlationId), this.permanentException); } try { Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); if (!Monitor.TryEnter(this.synchronizationObject, TimeSpan.FromSeconds(15.0))) { throw new Exception("Unable to acquire CobaltStore lock."); } stopwatch.Stop(); logDetail(WacRequestHandlerMetadata.LockWaitTime, stopwatch.ElapsedMilliseconds.ToString()); using (DisposalEscrow disposalEscrow = new DisposalEscrow("CobaltStore.ProcessRequest")) { using (Stream stream = new MemoryStream(65536)) { requestStream.CopyTo(stream, 65536); stream.Position = 0L; logDetail(WacRequestHandlerMetadata.CobaltRequestLength, stream.Length.ToString()); CobaltFile cobaltFile = this.CreateCobaltFile(disposalEscrow, false); this.SaveDiagnosticDocument(cobaltFile, "BeforeRoundTrip.bin"); this.SaveDiagnosticStream(requestStream, "Request.xml"); using (DisposableAtomFromStream disposableAtomFromStream = new DisposableAtomFromStream(stream)) { Roundtrip roundtrip = cobaltFile.CobaltEndpoint.CreateRoundtrip(); bool exceptionThrown = false; Atom atom = null; Stopwatch stopwatch2 = new Stopwatch(); stopwatch2.Start(); try { object obj; ProtocolVersion protocolVersion; roundtrip.DeserializeInputFromProtocol(disposableAtomFromStream, ref obj, ref protocolVersion); roundtrip.Execute(); cobaltFile.CommitChanges(); atom = roundtrip.SerializeOutputToProtocol(1, obj, null); } catch (Exception) { exceptionThrown = true; throw; } finally { stopwatch2.Stop(); logDetail(WacRequestHandlerMetadata.CobaltTime, stopwatch2.ElapsedMilliseconds.ToString()); this.LogBlobStoreMetrics(logDetail, cobaltFile); this.LogRequestDetails(logDetail, roundtrip, exceptionThrown); } this.UpdateEditorCount(roundtrip.RequestBatch); this.SaveDiagnosticDocument(cobaltFile, "AfterRoundTrip.bin"); atom.CopyTo(responseStream); logDetail(WacRequestHandlerMetadata.CobaltResponseLength, atom.Length.ToString()); if (this.diagnosticsEnabled) { using (MemoryStream memoryStream = new MemoryStream()) { atom.CopyTo(memoryStream); this.SaveDiagnosticStream(memoryStream, "Response.xml"); } } } } } } finally { if (Monitor.IsEntered(this.synchronizationObject)) { Monitor.Exit(this.synchronizationObject); } } }
/// <summary> /// Method of receiving and store data from GDS using web service /// </summary> /// <param name="controller">object variable with predefined application configuration and parameters of investigation</param> /// <param name="leg">object variable where stored information about flight routes that need to investigate (Departure point and Arrival point)</param> public void Start(Controller controller, Route leg) { var wdslUrl = new Uri("https://devlt.berlogic.de:444/Partner/Avia?wsdl "); var serviceUrl = new Uri("https://devlt.berlogic.de:444/Partner/Avia"); var agencyCode = controller.Config.AgencyNumber; var salesPoint = controller.Config.AgencySalespoint; var agentCode = controller.Config.AgencyName; var agentPassword = controller.Config.AgencyPassword; var client = new Avia { Url = serviceUrl.AbsoluteUri }; routeSegment[] routes; routeSegment routeTo = new routeSegment { beginLocation = leg.Departure, endLocation = leg.Arrival, date = DateTime.Parse(controller.DepartureDate, null, System.Globalization.DateTimeStyles.RoundtripKind), dateSpecified = true, departureTimeFrom = null, departureTimeTo = null }; if (controller.ArrivalDate != null) { routeSegment routeFrom = new routeSegment { beginLocation = leg.Arrival, endLocation = leg.Departure, date = DateTime.Parse(controller.ArrivalDate, null, System.Globalization.DateTimeStyles.RoundtripKind), dateSpecified = true, departureTimeFrom = null, departureTimeTo = null }; routes = new routeSegment[2]; routes[0] = routeTo; routes[1] = routeFrom; } else { routes = new routeSegment[1]; routes[0] = routeTo; } flightSearchSettingsEntry adult = new flightSearchSettingsEntry { key = passengerCategory.ADULT, value = 1, keySpecified = true, valueSpecified = true }; flightSearchSettingsEntry child = new flightSearchSettingsEntry { key = passengerCategory.CHILD, value = 0, keySpecified = true, valueSpecified = true }; flightSearchSettingsEntry infant = new flightSearchSettingsEntry { key = passengerCategory.INFANT, value = 0, keySpecified = true, valueSpecified = true }; flightSearchSettings settings = new flightSearchSettings { agencyCode = agencyCode, salesPoint = salesPoint, agentCode = agentCode, agentPassword = agentPassword, dateTolerance = 0, eticketsOnly = false, lang = "ru", mixedVendors = true, preferredCurrency = "RUB", serviceClass = serviceClass.ECONOM, skipConnected = false, route = routes, seats = new[] { adult, child, infant }, serviceClassSpecified = true }; try { client.authenticate(agentCode, agentPassword); var response = client.searchFlights(settings); Thread.Sleep(5000); Database.Database database = new Database.Database(controller.Config.DatabaseRemote, controller.Config.DatabaseUser, controller.Config.DatabasePassword, controller.Config.DatabaseName, (uint)controller.Config.DatabasePort); foreach (flight flight in response) { Roundtrip roundtrip = new Roundtrip(); Service service = new Service(); SearchResult result = new SearchResult(); List <Stops> stopsList = new List <Stops>(); Service rtService = new Service(); decimal fee = 0; decimal tariff = 0; decimal taxes = 0; fee += flight.cost.fee; foreach (costElement t in flight.cost.elements) { fee += t.fee; tariff += t.tariff; taxes += t.taxes; } var price = fee + tariff + taxes; result.Fee = fee; result.Tariff = tariff; result.Taxes = taxes; result.Price = price; result.Charges = 0; result.SearchTime = DateTime.Now; int durationOneLeg = 0; int durationSecondLeg = 0; result.Type1 = 2; result.Url = salesPoint; bool isOneWay = true; int segments = flight.segments.Length; for (int i = 0; i < segments; i++) { Stops stops = new Stops(); var isStop = flight.segments[i].connected; if (isOneWay && !isStop) //в одну сторону без пересадки { result.Departure = flight.segments[i].beginLocation.id; result.DepDate = flight.segments[i].beginDate.Date; result.DepTime = flight.segments[i].beginDate; result.ArrDate = flight.segments[i].endDate.Date; result.ArrTime = flight.segments[i].endDate; result.Arrival = flight.segments[i].endLocation.id; result.OperateCarrier = flight.segments[i].operatingVendor.id; result.OperateCarrierNumber = Int32.Parse(flight.segments[i].flightNumber); result.ValidateCarrier = flight.segments[i].marketingVendor.id; result.ValidateCarrierNumber = Int32.Parse(flight.segments[i].flightNumber); result.Rtrip = 0; service.ServiceClassName = flight.segments[i].serviceClass.ToString(); if (database.GetServiceId(service) == 0) { database.InsertServiceClassToDatabase(service); service.Id = database.GetServiceId(service); } else { service.Id = database.GetServiceId(service); } durationOneLeg += flight.segments[i].travelDuration; if (!flight.segments[i + 1].connected) { isOneWay = false; } result.TravelDuration = durationOneLeg; result.ServiceClass = service.Id; continue; } if (isOneWay && isStop) //в одну сторону но есть пересадка { stops.ArrDate = flight.segments[i].endDate.Date; stops.ArrTime = flight.segments[i].endDate; stops.Arrival = flight.segments[i].endLocation.id; stops.DepDate = flight.segments[i].beginDate.Date; stops.DepTime = flight.segments[i].beginDate; stops.Departure = flight.segments[i].beginLocation.id; stops.OperateCarrier = flight.segments[i].operatingVendor.id; stops.OperateFlightNumber = Int32.Parse(flight.segments[i].flightNumber); durationOneLeg += flight.segments[i].travelDuration; stopsList.Add(stops); if (!flight.segments[i + 1].connected) { isOneWay = false; result.ArrDate = flight.segments[i].endDate.Date; result.ArrTime = flight.segments[i].endDate; result.Arrival = flight.segments[i].endLocation.id; result.TravelDuration = durationOneLeg; } continue; } if (!isOneWay && !isStop) //обратно, но без пересадки { roundtrip.Departure = flight.segments[i].beginLocation.id; roundtrip.DepDate = flight.segments[i].beginDate.Date; roundtrip.DepTime = flight.segments[i].beginDate; roundtrip.ArrDate = flight.segments[i].endDate.Date; roundtrip.ArrTime = flight.segments[i].endDate; roundtrip.Arrival = flight.segments[i].endLocation.id; roundtrip.OperateCarrier = flight.segments[i].operatingVendor.id; roundtrip.OperateCarrierNumber = Int32.Parse(flight.segments[i].flightNumber); rtService.ServiceClassName = flight.segments[i].serviceClass.ToString(); if (database.GetServiceId(rtService) == 0) { database.InsertServiceClassToDatabase(rtService); rtService.Id = database.GetServiceId(rtService); } else { rtService.Id = database.GetServiceId(rtService); } roundtrip.ServiceClass = rtService.Id; roundtrip.ValidateCarrier = flight.segments[i].marketingVendor.id; roundtrip.ValidateCarrierNumber = Int32.Parse(flight.segments[i].flightNumber); durationSecondLeg += flight.segments[i].travelDuration; roundtrip.TravelDuration = durationSecondLeg; continue; } if (!isOneWay && isStop) //обратно, с пересадками { stops.ArrDate = flight.segments[i].endDate.Date; stops.ArrTime = flight.segments[i].endDate; stops.Arrival = flight.segments[i].endLocation.id; stops.DepDate = flight.segments[i].beginDate.Date; stops.DepTime = flight.segments[i].beginDate; stops.Departure = flight.segments[i].beginLocation.id; stops.OperateCarrier = flight.segments[i].operatingVendor.id; stops.OperateFlightNumber = Int32.Parse(flight.segments[i].flightNumber); durationSecondLeg += flight.segments[i].travelDuration; stopsList.Add(stops); if (i == flight.segments.Length - 1) { roundtrip.ArrDate = flight.segments[i].endDate.Date; roundtrip.ArrTime = flight.segments[i].endDate; roundtrip.Arrival = flight.segments[i].endLocation.id; roundtrip.ServiceClass = rtService.Id; roundtrip.TravelDuration = durationSecondLeg; } } } var rtid = database.RoundtripIsExistsInDatabase(roundtrip) == 0 ? database.InsertRoundtripsToDatabase(roundtrip) : database.RoundtripIsExistsInDatabase(roundtrip); int sid = 0; if (rtid != 0) { result.Rtrip = 1; result.RoundtripId = rtid; if (database.SearchResultsIsExistsInDatabase(result) == 0) { sid = database.InsertSearchResultsToDatabase(result); } } else { result.Rtrip = 0; sid = database.InsertSearchResultsToDatabase(result); } if (stopsList.Count > 0) { foreach (Stops stopse in stopsList) { stopse.SearchId = sid; database.InsertStopsToDatabase(stopse); } } } } catch (Exception exception) { Debug.Assert(true, exception.Message); //ignore } }
public RoundtripForcedExitDomainEvent(Roundtrip roundtrip) { Roundtrip = roundtrip ?? throw new ArgumentNullException(nameof(roundtrip)); }
public Roundtrip Update(Roundtrip roundtrip) { return(_context.Roundtrips.Update(roundtrip).Entity); }