private void UpdateQuoteSaleState(QuoteDTO quoteToUpdate) //General UpdateQuote Method { Log.Logger.Information("Updating quote " + quoteToUpdate.QuoteID); Quote upQuote = new Quote() { QuoteID = quoteToUpdate.QuoteID, ClientCode = quoteToUpdate.ClientCode, IsSell = quoteToUpdate.IsSell, QuoteName = quoteToUpdate.QuoteName }; //QuoteItems Mapping List <QuoteProducts> quoteProducts = new List <QuoteProducts>(); foreach (QuoteProductsDTO qpdto in quoteToUpdate.QuoteLineItems) { quoteProducts.Add ( new QuoteProducts() { ProductCode = qpdto.ProductCode, Quantity = qpdto.Quantity, Price = qpdto.Price } ); } upQuote.QuoteLineItems = quoteProducts; _quoteListDB.Update(upQuote); }
public QuoteDTO SaveQuote(QuoteDTO dto) { using (var context = new QuestionnaireEntities()) { Quote dao = null; if (dto.QuoteID != 0) { dao = context.Quotes.Where(q => q.Quote_ID == dto.QuoteID).FirstOrDefault(); } else { dao = new Quote(); context.Quotes.Add(dao); } dao.Scheme_ID = dto.SchemeID; dao.Reference = dto.Reference; dao.QuoteDate = dto.QuoteDate; context.SaveChanges(); QuestionnaireCacheManager.Instance.ClearListQuotesForDisplayFromCache(); dto.QuoteID = dao.Quote_ID; } return(dto); }
public void CanConsumeQuotesStream() { var gate = new ManualResetEvent(false); var streamingClient = BuildStreamingClient(); //streamingClient.Connect(); var newsListener = streamingClient.BuildQuotesListener(); //newsListener.Start(); QuoteDTO actual = null; //Trap the Price given by the update event for checking newsListener.MessageReceived += (s, e) => { actual = e.Data; Console.WriteLine(actual); gate.Set(); }; bool timedOut = false; if (!gate.WaitOne(TimeSpan.FromSeconds(15))) { timedOut = true; } streamingClient.TearDownListener(newsListener); streamingClient.Dispose(); Assert.IsFalse(timedOut, "timed out"); Assert.IsNotNull(actual); }
public IActionResult PostNewQuote(string userId, [FromBody] Quote quote) { if (quote == null) { return(BadRequest()); } if (!ModelState.IsValid) { return(BadRequest()); } var maxQuoteId = QuotesDataStore.Current.Quotes.Max(q => q.Id); var newQuote = new QuoteDTO { Id = ++maxQuoteId, UserId = userId, Content = quote.Content, Author = quote.Author, DateCreated = DateTime.Now.ToUniversalTime(), DatePosted = null }; QuotesDataStore.Current.Quotes.Add(newQuote); return(CreatedAtRoute("GetUserQuote", new { userId = userId, id = newQuote.Id }, newQuote)); }
public async Task <IActionResult> GetMovieQuoteById(int movieId, int quoteId) { _logger.LogInformation("Getting quote with id {QuoteID} from movie with Id: {ID} @ {DATE}", quoteId, movieId, DateTime.UtcNow); var movie = await _context.Movies.FindAsync(movieId); if (movie == null) { _logger.LogWarning("Not found movie with Id: {ID} @ {DATE}", movieId, DateTime.UtcNow); return(NotFound()); } var quote = movie.Quotes.Where(q => q.Id == quoteId).SingleOrDefault(); if (quote == null) { _logger.LogWarning("Not found quote with Id: {ID} @ {DATE}", quoteId, DateTime.UtcNow); return(NotFound()); } var quoteDTO = new QuoteDTO { Actor = quote.Actor.Name + ' ' + quote.Actor.Surname, Content = quote.Content, Id = quote.Id, Movie = quote.Movie.Title, Year = quote.Movie.Year }; return(Ok(quoteDTO)); }
public Guid CreateQuote(QuoteDTO newQuote) { try { if (newQuote != null) { var quote = new Quote() { Email = newQuote.Email, FirstName = newQuote.FirstName, LastName = newQuote.LastName, Mobile = newQuote.Mobile, Term = newQuote.Term, Title = newQuote.Title, Amount = newQuote.Amount, CreatedDate = DateTime.UtcNow, CreatedByName = "SYSTEM", LastUpdatedDate = DateTime.UtcNow, LastUpdatedBy = Guid.Empty, LastUpdatedByName = "SYSTEM" }; _moneyMeContext.Quotes.Add(quote); _moneyMeContext.SaveChanges(); CheckLimitQuoteRecordsInDb(); return(quote.Id); } throw new Exception(string.Format("Creating quote for {0} {1}", newQuote.FirstName, newQuote.LastName)); } catch (Exception ex) { throw ex; } }
public async Task <IActionResult> GetMovieRandomQuote(int id) { _logger.LogInformation("Getting random quote from movie with Id: {ID} @ {DATE}", id, DateTime.UtcNow); var movie = await _context.Movies.FindAsync(id); if (movie == null) { _logger.LogWarning("Not found movie with Id: {ID} @ {DATE}", id, DateTime.UtcNow); return(NotFound()); } var randomIndex = _random.Next(1, movie.Quotes.Count()); Quote randomQuote = movie.Quotes.ElementAt(randomIndex); var randomQuoteDTO = new QuoteDTO { Id = randomQuote.Id, Actor = randomQuote.Actor.Name + ' ' + randomQuote.Actor.Surname, Content = randomQuote.Content, Year = movie.Year }; return(Ok(randomQuoteDTO)); }
public async Task <IActionResult> GetRandomQuote(int id) { _logger.LogInformation("Getting random quote of actor with Id: {ID} @ {DATE}", id, DateTime.UtcNow); var actor = await _context.Actors.FindAsync(id); if (actor == null || actor.Quotes.Count() == 0) { _logger.LogWarning("Not found actor with Id: {ID} @ {DATE}", id, new DateTime()); return(NotFound()); } Random rnd = new Random(Guid.NewGuid().GetHashCode()); int randomIndex = rnd.Next(actor.Quotes.Count()); var randomQuote = actor.Quotes.ToArray()[randomIndex]; var randomQuoteDTO = new QuoteDTO { Id = randomQuote.Id, Content = randomQuote.Content, Movie = randomQuote.Movie.Title, Year = randomQuote.Movie.Year }; return(Ok(randomQuoteDTO)); }
private void UpdateQuoteFunction(QuoteDTO updatedQuote, QuoteDTO quoteToUpdate) //General UpdateQuote Method { quoteToUpdate.IsSell = updatedQuote.IsSell; quoteToUpdate.QuoteName = updatedQuote.QuoteName; quoteToUpdate.QuoteLineItems = updatedQuote.QuoteLineItems; quoteToUpdate.ClientCode = updatedQuote.ClientCode; //Update QuoteDTO List Quote upQuote = new Quote() { QuoteID = quoteToUpdate.QuoteID, ClientCode = quoteToUpdate.ClientCode, IsSell = quoteToUpdate.IsSell, QuoteName = quoteToUpdate.QuoteName }; //QuoteItems Mapping List <QuoteProducts> quoteProducts = new List <QuoteProducts>(); foreach (QuoteProductsDTO qpdto in quoteToUpdate.QuoteLineItems) { qpdto.Price = DiscountApplier(qpdto, qpdto.Price).Price; quoteProducts.Add ( new QuoteProducts() { ProductCode = qpdto.ProductCode, Quantity = qpdto.Quantity, Price = qpdto.Price } ); } upQuote.QuoteLineItems = quoteProducts; _quoteListDB.Update(upQuote); }
/// <summary> /// Запуск приложения-сервера передачи котировок. /// </summary> internal void Run() { UdpClient sender = new UdpClient(); IPAddress remoteAddress = IPAddress.Parse(_endPointSettings.IPAddress); IPEndPoint endPoint = new IPEndPoint(remoteAddress, _endPointSettings.Port); int counter = 0; while (true) { //получаем цену котировок double price = _quotesService.GetPrice(); //отправляемая информацию о котировке QuoteDTO package = new QuoteDTO() { Price = price, Index = counter++ }; byte[] buffer = JsonDataSerializer.Serialize(package); sender.Send(buffer, buffer.Length, endPoint); } }
public void ExistingQuote(int quoteId) { SetQuote = QuestionnaireBusinessManager.Instance.LoadQuote(quoteId); SetSchemeID = Quote.SchemeID; if (Quote.Answers == null) { Quote.Answers = new List <QuoteQuestionAnswerDTO>(); } }
public IActionResult Put([FromBody] QuoteDTO item) { if (item == null) { return(BadRequest()); } _quoteService.EditQuote(item); return(Ok(item)); }
public QuoteDTO WriteQuoteDto(IEnumerable <PartDTO> partDtos) { var quoteDto = new QuoteDTO(); foreach (var part in partDtos) { quoteDto.Parts.Add(part); } return(quoteDto); }
public QuoteDTO getQuoteById(string id) { Quote q = db.Quotes.Where(qq=> qq.quoteCode == id).FirstOrDefault(); QuoteDTO q2 = new QuoteDTO(); q2.QuoteCode = q.quoteCode; q2.TotalPrice = q.totalPrice.ToString(); q2.TotalTime = q.totalTime.ToString(); q2.QuoteName = q.name; q2.Email = q.email; return q2; }
public QuoteDTO getQuoteById(string id) { Quote q = db.Quotes.Where(qq => qq.quoteCode == id).FirstOrDefault(); QuoteDTO q2 = new QuoteDTO(); q2.QuoteCode = q.quoteCode; q2.TotalPrice = q.totalPrice.ToString(); q2.TotalTime = q.totalTime.ToString(); q2.QuoteName = q.name; q2.Email = q.email; return(q2); }
public void NewQuote(int schemeId) { QuoteDTO quote = new QuoteDTO() { QuoteDate = DateTime.Now, SchemeID = schemeId, Answers = new List <QuoteQuestionAnswerDTO>() }; SetSchemeID = schemeId; SetQuote = quote; quote.Reference = ReferenceGenerator(); quote = QuestionnaireBusinessManager.Instance.SaveQuote(quote); }
public QuoteDTO LoadQuote(int quoteId) { QuoteDTO result = null; using (var context = new QuestionnaireEntities()) { var dao = context.Quotes.Find(quoteId); if (dao != null) { result = AutoMapper.Mapper.Map <Quote, QuoteDTO>(dao); result.Answers = ListAnswersByQuote(result.QuoteID); } } return(result); }
[HttpPut("quotes/{quoteId}")] //update by id public bool Put(string quoteId, [FromBody] QuoteDTO updatedQuote) { var exists = _quotesLogic.GetQuoteList().FirstOrDefault(q => q.QuoteID == quoteId); if (exists != null) { Log.Logger.Information("PUT request"); _quotesLogic.UpdateQuote(quoteId, updatedQuote); return(true); } else { throw new DatabaseException("The ID couldn't be found ! { " + quoteId + " }"); } }
public async Task <IActionResult> GetRandomQuote() { _logger.LogInformation("Getting a random quote @ {DATE}", DateTime.UtcNow); var _random = new Random(Guid.NewGuid().GetHashCode()); int randomIndex = _random.Next(1, _context.Quotes.Count()); var randomQuote = await _context.Quotes.FindAsync(randomIndex); var randomQuoteDTO = new QuoteDTO { Id = randomQuote.Id, Actor = randomQuote.Actor.Name + ' ' + randomQuote.Actor.Surname, Content = randomQuote.Content, Movie = randomQuote.Movie.Title, Year = randomQuote.Movie.Year }; return(Ok(randomQuoteDTO)); }
public void Init() { this.quotesServiceMock = new Mock <IQuotesService>(); var quoteDTO = new QuoteDTO { Id = 1, Author = "Pesho", Content = "I am cool" }; this.quotesServiceMock.Setup(x => x.GetRandomQuote()).ReturnsAsync(quoteDTO); this.authorsServiceMock = new Mock <IAuthorsService>(); var authorDTO = new AuthorDTO { Name = "Pesho" }; this.authorsServiceMock.Setup(x => x.GetRandomAuthor()).ReturnsAsync(authorDTO); this.modesServiceMock = new Mock <IModesService>(); this.modesServiceMock.Setup(x => x.GetSelectedMode()).ReturnsAsync(QuizModeType.Binary); }
public void UpdateQuote(string id, QuoteDTO updatedQuote)//update by id { if (string.IsNullOrEmpty(updatedQuote.ClientCode)) { Log.Logger.Information("Empty or null field"); throw new QuoteLogicException("Empty or null field"); } Log.Logger.Information("Updating quote " + updatedQuote.ClientCode); List <QuoteDTO> quoteList = GetQuoteList(); foreach (QuoteDTO quoteToUpdate in quoteList) { if (quoteToUpdate.QuoteID == id) //Search for quoteToUpdate by id { UpdateQuoteFunction(updatedQuote, quoteToUpdate); } } }
public async Task <ActionResult> Index() { var viewModel = new QuoteAndAuthorAnswersDTO(); QuoteDTO randomQuote = await this.quotesService.GetRandomQuote(); viewModel.Quote = randomQuote; var authorAnswers = new List <string>(); viewModel.QuizModeType = await this.modesService.GetSelectedMode(); if (viewModel.QuizModeType == QuizModeType.Binary) { var randomAuthor = await this.authorsService.GetRandomAuthor(); authorAnswers.Add(randomAuthor.Name); } else { while (authorAnswers.Count < GlobalConstants.MultipleChoiceModeDefaultAuthorsCount) { var randomAuthor = await this.authorsService.GetRandomAuthor(); if (authorAnswers.Contains(randomAuthor.Name)) { continue; } authorAnswers.Add(randomAuthor.Name); } if (!authorAnswers.Contains(randomQuote.Author)) { int randomPosition = StaticRandomizer.RandomNumber(0, GlobalConstants.MultipleChoiceModeDefaultAuthorsCount); authorAnswers[randomPosition] = randomQuote.Author; } } viewModel.AuthorAnswers = authorAnswers; return(this.View(viewModel)); }
public async Task <QuoteSendDTO> GetQuoteAsync(String id) { try { HttpResponseMessage response = await client.GetAsync(apiUrl + "/quote-management/quotes/" + id); string resp = await ResponseUtility.Verification(response); QuoteDTO quoteDTO = JsonConvert.DeserializeObject <QuoteDTO>(resp); return(TransformItemListAsync(quoteDTO).Result); } catch (ServicesException ex) { throw ex; } catch (Exception e) { throw new ServicesException("Quote api not found", 408); } }
/// <summary> /// Получение котировок. /// </summary> /// <param name="state"></param> private void GetQuotes(object state) { try { IPEndPoint endPoint = null; byte[] result = _client.Receive(ref endPoint); QuoteDTO quote = JsonDataSerializer.Deserialize <QuoteDTO>(result); //обновление статистики Statistics.UpdateStatistics(quote.Price); } catch (SocketException ex) { OnSocketError(ex.SocketErrorCode); } catch (Exception ex) { throw new Exception($"В процессе получения котировок произошла неожиданная ошибка: {ex}"); } }
public async Task <string> GetQuoteByCurrencyISOCode(string isoCode) { if (string.IsNullOrEmpty(isoCode)) { throw new ArgumentNullException(); } var currency = await _currencyService.GetCurrencyByISOCode(isoCode); if (currency == null) { throw new ArgumentException(); } QuoteDTO result; if (!string.IsNullOrEmpty(currency.ExchangeRateProvider) && !currency.UseUSDFactor) { result = await _getQuoteFromProviderAsync(currency); } else if (currency.UseUSDFactor) { var usdCurrency = await _currencyService.GetCurrencyByISOCode("USD"); var usdQuote = await _getQuoteFromProviderAsync(usdCurrency); result = new QuoteDTO { id = isoCode, buy = usdQuote.buy * currency.USDFactor, sale = usdQuote.sale * currency.USDFactor, updated = usdQuote.updated }; } else { throw new InvalidOperationException(); } return(JsonConvert.SerializeObject(result)); }
public async Task <QuoteDTO> CreateQuote(QuoteDTO quote) { try { String json = JsonConvert.SerializeObject(quote, new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() }); StringContent data = new StringContent(json, Encoding.UTF8, "application/json"); HttpResponseMessage response = await this.client.PostAsync(apiUrl + "/quote-management/quotes", data); string result = await ResponseUtility.Verification(response); return(JsonConvert.DeserializeObject <QuoteDTO>(result)); } catch (ServicesException ex) { throw ex; } catch (Exception e) { throw new ServicesException("Quote api not found", 408); } }
public async Task <IActionResult> GetQuote(int id) { _logger.LogInformation("Getting quote with Id: {ID} @ {DATE}", id, DateTime.UtcNow); var quote = await _context.Quotes.FindAsync(id); if (quote == null) { _logger.LogWarning("Not found quote with Id: {ID} @ {DATE}", id, DateTime.UtcNow); return(NotFound()); } var quoteDTO = new QuoteDTO { Id = quote.Id, Actor = quote.Actor.Name + ' ' + quote.Actor.Surname, Content = quote.Content, Movie = quote.Movie.Title, Year = quote.Movie.Year }; return(Ok(quoteDTO)); }
private async Task <QuoteSendDTO> TransformItemListAsync(QuoteDTO quoteDTO) { QuoteSendDTO quoteSendDTO = new QuoteSendDTO(); quoteSendDTO.Sold = quoteDTO.Sold; quoteSendDTO.Date = quoteDTO.Date; quoteSendDTO.QuoteName = quoteDTO.QuoteName; HttpResponseMessage clientResponse = await client.GetAsync(_configuration.GetSection("MicroServices").GetSection("Clients").Value + "/client-management/clients/" + quoteDTO.ClientCode); string clientResult = await ResponseUtility.Verification(clientResponse); ClientDTO clientDTO = JsonConvert.DeserializeObject <ClientDTO>(clientResult); quoteSendDTO.Client = clientDTO; quoteSendDTO.QuoteListItems = new List <ListItemSendDTO>(); if (quoteDTO.QuoteLineItems.Count > 0) { string codes = quoteDTO.QuoteLineItems[0].ProductCode; for (int i = 1; i < quoteDTO.QuoteLineItems.Count; i++) { codes = codes + "," + quoteDTO.QuoteLineItems[i].ProductCode; } HttpResponseMessage productResponse = await client.GetAsync(_configuration.GetSection("MicroServices").GetSection("Products").Value + "/product-management/products?ids=" + codes); string productResult = await ResponseUtility.Verification(productResponse); List <ProductGetDTO> productos = JsonConvert.DeserializeObject <List <ProductGetDTO> >(productResult); for (int i = 0; i < quoteDTO.QuoteLineItems.Count; i++) { ListItemSendDTO item = new ListItemSendDTO(); item.Price = quoteDTO.QuoteLineItems[i].Price; item.Quantity = quoteDTO.QuoteLineItems[i].Quantity; item.QuoteName = quoteDTO.QuoteLineItems[i].QuoteName; item.Product = productos.Find(x => x.Code.Equals(quoteDTO.QuoteLineItems[i].ProductCode)); quoteSendDTO.QuoteListItems.Add(item); } } return(quoteSendDTO); }
public IHttpActionResult PutQuote(int id, QuoteDTO quote) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } // get the object out of the db var q = db.Quotes.Find(id); if (id != quote.QuoteId) { return(BadRequest()); } //Set the current value of active to be false q.Active = quote.Active; db.Entry(q).State = EntityState.Modified; try { db.SaveChanges(); } catch (DbUpdateConcurrencyException) { if (!QuoteExists(id)) { return(NotFound()); } else { throw; } } return(StatusCode(HttpStatusCode.OK)); }
public QuoteDTO GetQuote(Guid quoteId) { QuoteDTO quoteDTO = new QuoteDTO(); if (quoteId != null) { quoteDTO = _moneyMeContext.Quotes .Where(q => q.Id == quoteId) .Select(q => new QuoteDTO() { Id = q.Id, Email = q.Email, FirstName = q.FirstName, LastName = q.LastName, Mobile = q.Mobile, Term = q.Term, Title = q.Title, Amount = q.Amount }).FirstOrDefault(); } return(quoteDTO); }
public QuoteDTO Post([FromBody] QuoteDTO newQuoteDTO) { Log.Logger.Information("POST request"); var dbServer = _configuration.GetSection("Database").GetSection("connectionString"); List <QuoteProductsDTO> qp = new List <QuoteProductsDTO>(); qp = newQuoteDTO.QuoteLineItems; QuoteDTO newQuote = _quotesLogic.AddNewQuote(newQuoteDTO); Console.WriteLine("POST = > \t| QUOTE ID : " + $"{newQuote.QuoteID}" + " | NAME : " + newQuoteDTO.QuoteName + " | CLIENT CODE : " + newQuoteDTO.ClientCode + " | SALE STATUS : " + newQuoteDTO.IsSell); foreach (QuoteProductsDTO quop in qp) { Console.WriteLine("\t\t\t -> | PRODUCT CODE : " + quop.ProductCode + " | QUANTITY : " + quop.Quantity + " | PRICE : " + $"{quop.Price}" + "\n"); } newQuote.QuoteID = $"{newQuote.QuoteID} data from { dbServer.Value }"; return(newQuote); }