public PricesResponse Post(Prices request) { if (request.Price.Id > 0) { Bm2s.Data.Common.BLL.Article.Price item = Datas.Instance.DataStorage.Prices[request.Price.Id]; item.ArticleId = request.Price.Article.Id; item.BasePrice = Convert.ToDouble(request.Price.BasePrice); item.EndingDate = request.Price.EndingDate; item.StartingDate = request.Price.StartingDate; Datas.Instance.DataStorage.Prices[request.Price.Id] = item; } else { Bm2s.Data.Common.BLL.Article.Price item = new Data.Common.BLL.Article.Price() { ArticleId = request.Price.Article.Id, BasePrice = Convert.ToDouble(request.Price.BasePrice), EndingDate = request.Price.EndingDate, StartingDate = request.Price.StartingDate }; Datas.Instance.DataStorage.Prices.Add(item); request.Price.Id = item.Id; } PricesResponse response = new PricesResponse(); response.Prices.Add(request.Price); return response; }
public ActionResult Create(PriceCreateViewModel model, string redirectUrl) { if (!ModelState.IsValid) { return(View(model)); } List <Prices> prices = Price.Get().Where(t => t.ServicesId == model.ServiceSelected).ToList().Where(p => p.FromDate <= model.FromDate && (p.ToDate > model.FromDate || p.ToDate == null)).ToList(); if (prices.Count != 0) { prices[0].ToDate = model.FromDate; Price.Update(prices[0]); } var price = new Prices { ServicesId = model.ServiceSelected, ToDate = null, Value = model.Value, FromDate = model.FromDate }; if (prices.Count == 2) { price.ToDate = prices[1].FromDate; } Price.Create(price); return(RedirectToLocal(redirectUrl)); }
private void TextViewData_Click(object sender, EventArgs e) { DatePickerFragment frag = DatePickerFragment.NewInstance(delegate(DateTime time) { TripDate = time; TextViewData.Text = time.ToString("dd.MM.yyyy"); LoaderView.Visibility = ViewStates.Visible; AnimationLoader.Start(); new Thread(new ThreadStart(delegate //поток для загрузки данных { var cost = Prices.GetPrice(routs[SpinnerRouts.SelectedItemPosition].PromPynkt[SpinnerPoStart.SelectedItemPosition].id, ObratPO[SpinnerPoEnd.SelectedItemPosition].id, routs[SpinnerRouts.SelectedItemPosition].id); if (cost != "false") { trips = Trips.GetTripsOnDate(TripDate.ToString("yyyy-MM-dd"), routs[SpinnerRouts.SelectedItemPosition].PromPynkt[SpinnerPoStart.SelectedItemPosition].id.ToString(), ObratPO[SpinnerPoEnd.SelectedItemPosition].id.ToString(), routs[SpinnerRouts.SelectedItemPosition].id.ToString()); ListViewTripsParmetr.Height = Convert.ToInt32(function.convertDpToPixel(90, this)) * trips.Count; RunOnUiThread(() => ListViewTrips.Adapter = new TripsAdapter(this, trips)); RunOnUiThread(() => AnimationLoader.Stop()); RunOnUiThread(() => LoaderView.Visibility = ViewStates.Invisible); } else { RunOnUiThread(() => ListViewTrips.Adapter = null); RunOnUiThread(() => AnimationLoader.Stop()); RunOnUiThread(() => LoaderView.Visibility = ViewStates.Invisible); RunOnUiThread(() => function.AlertDialogShow("Предупреждение", "Между выбранными пунктами не осуществляется перевозка.", this)); } })).Start(); }); frag.Show(FragmentManager, DatePickerFragment.TAG); }
public override void ToStream(Stream output) { output.Write(TLUtils.SignatureToBytes(Signature)); Flags.ToStream(output); Currency.ToStream(output); Prices.ToStream(output); }
/// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { var hashCode = 41; // Suitable nullity checks etc, of course :) if (Name != null) { hashCode = hashCode * 59 + Name.GetHashCode(); } if (Code != null) { hashCode = hashCode * 59 + Code.GetHashCode(); } if (ChargingTriggerInfo != null) { hashCode = hashCode * 59 + ChargingTriggerInfo.GetHashCode(); } if (Prices != null) { hashCode = hashCode * 59 + Prices.GetHashCode(); } if (Minimum != null) { hashCode = hashCode * 59 + Minimum.GetHashCode(); } if (Maximum != null) { hashCode = hashCode * 59 + Maximum.GetHashCode(); } return(hashCode); } }
public JsonResult DeleteBerry(Prices prices) { KoskenkorvanLuomutilaEntities3 entity = new KoskenkorvanLuomutilaEntities3(); string berry = prices.Berry; bool success = false; var delete = (from p in entity.Prices where p.Berry == berry select p).FirstOrDefault(); if (delete != null) { ObjectContext oc = ((IObjectContextAdapter)entity).ObjectContext; oc.DeleteObject(delete); oc.SaveChanges(); success = true; } entity.Dispose(); return(Json(success)); }
private void addToDict(int type, int price, int currency) { if (!Prices.ContainsKey(type)) { Prices.Add(type, new Tuple <int, CurrencyType>(price, (CurrencyType)currency)); } }
public Prices SelectById(Int32 id) { SqlCommand sqlCommand = new SqlCommand(); sqlCommand.CommandType = CommandType.Text; sqlCommand.CommandText = "select * from prices where id = @id"; sqlCommand.Parameters.AddWithValue("@id", id); SqlDataReader sqlDataReader = Db.Select(sqlCommand); Prices prices = new Prices(); if (sqlDataReader.HasRows) { sqlDataReader.Read(); prices.Id = (Int32)sqlDataReader["id"]; prices.Usd = (String)sqlDataReader["usd"]; prices.UsdFoil = (String)sqlDataReader["usd_foil"]; prices.Eur = (String)sqlDataReader["eur"]; prices.Tix = (String)sqlDataReader["tix"]; return(prices); } else { return(null); } }
private void AddFrag_ProductHandler(object sender, OnCreateProductEvent e) { var client = new RestClient("http://10.0.2.2:60408"); RestReader reader = new RestReader(); RestInserter inserter = new RestInserter(); // Toast.MakeText(this, "Userprices might be null " + userPrices.Length, ToastLength.Short).Show(); Prices price = new Prices { Id = CurrentUserSignedInId, ProductId = (userPrices.Length == 0) ? 0 : userPrices[userPrices.Length - 1].ProductId + 1, Name = e.Name, Price = e.Price, Picture = "none", IdNavigation = null, Ingredients = null }; try { inserter.InsertPrice(price, client, CurrentUserSignedInId); } catch (Exception) { Toast.MakeText(this.ApplicationContext, "Exception at insertion attempt! (activity)", ToastLength.Short).Show(); } }
public async Task <IActionResult> Edit(int id, [Bind("ID,Price,DishesID,P_time")] Prices prices) { if (id != prices.ID) { return(NotFound()); } if (ModelState.IsValid) { try { _context.Update(prices); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!PricesExists(prices.ID)) { return(NotFound()); } else { throw; } } return(RedirectToAction(nameof(Index))); } ViewData["DishesID"] = new SelectList(_context.Dishes, "ID", "ID", prices.DishesID); return(View(prices)); }
public IActionResult Prices() { var late = _db.Dates.SingleOrDefault(x => x.name == "late").value; var islate = late < DateTime.Now; var prices = _db.Prices.Where(x => x.late == islate).ToList(); var m_workshop = prices.SingleOrDefault(x => x.member == true && x.type == "workshop")?.value ?? 0; var nm_workshop = prices.SingleOrDefault(x => x.member == false && x.type == "workshop")?.value ?? 0; var comprehensive = prices.SingleOrDefault(x => x.type == "comprehensive")?.value ?? 0; var critique = prices.SingleOrDefault(x => x.type == "critique")?.value ?? 0; var p = new Prices { workshop = new Dictionary <string, decimal> { { "member", m_workshop }, { "nonmember", nm_workshop } }, comprehensive = new Dictionary <string, decimal> { { "member", comprehensive } }, critique = new Dictionary <string, decimal> { { "regular", critique } } }; return(Success(p)); }
private void LoadDS(List <Products> DSDauVao) { EnableEditButton(false); this.listView_MonAn.Items.Clear(); foreach (Products product in DSDauVao) { float Price = Prices.GetPriceByDateAndProductID(DateTime.Now, product.ProductID); ListViewItem item = new ListViewItem(product.ProductID.ToString()); item.SubItems.Add(product.Name); item.SubItems.Add(product.Description); if (Price != -1) { item.SubItems.Add(Price.ToString()); } else { item.SubItems.Add("Chưa cài đặt giá"); this.btn_KiemSoatGia.Enabled = true; } item.SubItems.Add(product.Image); item.SubItems.Add(product.Unit); item.SubItems.Add(FindCatNameByCatId(product.CatId)); item.SubItems.Add(product.Type ? "Nhập" : "Bán"); this.listView_MonAn.Items.Add(item); } this.lblTongSo.Text = "Tổng số món: " + this.listView_MonAn.Items.Count; }
// GET id /// <summary> /// Return data of specific product. /// </summary> /// <param name="id">Id of the product</param> /// <returns>Specific product data</returns> public Products Get(int id, string CountryContext = "PLN") { using (IUMdbEntities entities = new IUMdbEntities()) { Products searchedProduct = entities.Products.Find(id); if (searchedProduct == null) { return(null); } Countries requestedCountry = entities.Countries.FirstOrDefault(country => country.CountryTag == CountryContext); Prices priceForProduct = entities.Prices.FirstOrDefault(price => price.ProductId == searchedProduct.Id && price.CountryId == requestedCountry.Id); if (priceForProduct == null) { searchedProduct.Price = decimal.MinusOne; } else { searchedProduct.Price = priceForProduct.Price; } return(searchedProduct); } }
public PriceTable() { product = new Prices[2]; string shop; string number; uint? price; for (int i = 0; i < 2; i++) { Console.WriteLine("Введите номер товара"); number = Console.ReadLine(); Console.WriteLine("Введите магазин"); shop = Console.ReadLine(); Console.WriteLine("Введите цену"); try { price = Convert.ToUInt32(Console.ReadLine()); } catch (Exception e) { Console.WriteLine("Попытка записи неверного формата."); Console.WriteLine(e.Message); price = null; } product[i] = new Prices(number, shop, price); } product = product.OrderBy(products => products.Number).ToArray <Prices>(); }
private void ComboBoxTypeBilet_SelectedIndexChanged(object sender, EventArgs e) { if (ComboBoxTypeBilet.Text != "" && ComboBoxKyda.Text != "" && ComboBoxOtkyda.Text != "") { string cout = Prices.GetPrice(marshruts[ComboBoxNewMarshrut.SelectedIndex].PromPynkt[ComboBoxOtkyda.SelectedIndex].id, marshruts[ComboBoxNewMarshrut.SelectedIndex].PromPynkt[(marshruts[ComboBoxNewMarshrut.SelectedIndex].PromPynkt.Count - 1 - ComboBoxKyda.SelectedIndex)].id, marshruts[ComboBoxNewMarshrut.SelectedIndex].id); if (cout != "false") { if (bilets[ComboBoxTypeBilet.SelectedIndex].fix == 1) { TextBoxCout.Text = bilets[ComboBoxTypeBilet.SelectedIndex].cost.ToString(); } else { TextBoxCout.Text = (Convert.ToDouble(cout) * bilets[ComboBoxTypeBilet.SelectedIndex].cost).ToString(); } } else { MetroMessageBox.Show(this, "Перевозка между этими пунктами не осуществляется.", "Внимание", MessageBoxButtons.OK, MessageBoxIcon.Question); } } else { MetroMessageBox.Show(this, "Перевозка между этими пунктами не осуществляется.", "Внимание", MessageBoxButtons.OK, MessageBoxIcon.Question); } }
public async Task <IActionResult> Edit(int id, [Bind("Id,Type,Price")] Prices prices) { if (id != prices.Id) { return(NotFound()); } if (ModelState.IsValid) { try { _context.Update(prices); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!PricesExists(prices.Id)) { return(NotFound()); } else { throw; } } return(RedirectToAction(nameof(Index))); } return(View(prices)); }
private void Them_Sua(string ChucNang) { if (!CheckDate()) { return; } Prices price = new Prices(); price.ID = int.Parse(this.txt_ID.Text); price.ProductID = this.ProductId; price.Price = float.Parse(this.txt_GiaTien.Text); price.DateStart = this.dtp_NgayBatDau.Value; price.DateEnd = this.dtp_NgayKetThuc.Value; try { switch (ChucNang) { case "Them": objPrice.Add(price); break; case "Sua": objPrice.Update(price); break; } MessageBox.Show("Thành công , dữ liệu đã thay đổi"); btn_LoadLai.PerformClick(); } catch (Exception ex) { MessageBox.Show("Lỗi đã sảy ra , vui lòng kiểm tra lại hoặc liên hệ kỹ thuật viên với mô tả lỗi dưới đây \n " + ex.Message, "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
static void Main(string[] args) { ShowMovieMenu(); CollectMovieTime(); string command1 = System.Console.ReadLine(); if(command1 == "1") { Prices myPrices = new Prices(); myPrices.GatherMatineePrice(); myPrices.GatherConcessionData(); System.Console.WriteLine(" Total Purchase: $" + myPrices.GetTotalPurchase()); } else if (command1 == "2") { Prices myPrices = new Prices(); myPrices.GatherEveningPrice(); myPrices.GatherConcessionData(); System.Console.WriteLine(" Total Purchase: $" + myPrices.GetTotalPurchase()); } else { System.Console.WriteLine(); System.Console.WriteLine(" Invalid Command. "); } EndofProgram(); }
public async Task <ActionResult <Prices> > PostPrices(Prices prices) { _context.Prices.Add(prices); await _context.SaveChangesAsync(); return(CreatedAtAction("GetPrices", new { id = prices.PriceId }, prices)); }
/// <summary> /// Determines whether the specified prices is triggered. /// </summary> /// <param name="prices">The prices.</param> /// <param name="price">The price.</param> /// <returns> /// <c>true</c> if the specified prices is triggered; otherwise, <c>false</c>. /// </returns> public bool IsTriggered(Prices prices, out decimal price) { //Current price price = prices.Current; //Check direction if (Direction == Direction.Long) { if (prices.Low < LimitPrice) { // fill at the worse price this bar or the limit price, this allows far out of the money limits // to be executed properly price = Math.Min(prices.High, LimitPrice); return(true); } } else if (Direction == Direction.Short) { if (prices.High > LimitPrice) { // fill at the worse price this bar or the limit price, this allows far out of the money limits // to be executed properly price = Math.Max(prices.Low, LimitPrice); return(true); } } else { return(true); } //All else return(false); }
public async Task <IActionResult> PutPrices([FromRoute] int id, [FromBody] Prices prices) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } if (id != prices.Id) { return(BadRequest()); } _context.Entry(prices).State = EntityState.Modified; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!PricesExists(id)) { return(NotFound()); } else { throw; } } return(NoContent()); }
public void SetDatePrices(List <Price> prices) { if (prices == null || !prices.Any()) { return; } // Check for any duplicates if (prices.Count != prices.Distinct().Count()) { throw new AvailabilityException(AvailabilityException.INVALID_DATA, $"Prices cannot contain duplicates"); } if (prices.Any(x => _bookedSlots.Any(y => x.Date.Date == y.Date))) { throw new AvailabilityException(AvailabilityException.INVALID_DATA, $"Cannot change the price for a time slot where a booking is already made"); } foreach (var newPrice in prices) { if (Prices.TryGetValue(newPrice, out var price)) { price.SetPriceValue(newPrice.Value); } else { Prices.Add(newPrice); } UpdatedDate = DateTime.Now; // need to refactor this - leaving it here for now.. } }
public List <Prices> SelectAll() { SqlCommand sqlCommand = new SqlCommand(); sqlCommand.CommandType = CommandType.Text; sqlCommand.CommandText = "select * from prices"; SqlDataReader sqlDataReader = Db.Select(sqlCommand); List <Prices> listPrices = new List <Prices>(); if (sqlDataReader.HasRows) { while (sqlDataReader.Read()) { Prices prices = new Prices(); prices.Id = (Int32)sqlDataReader["id"]; prices.Usd = (String)sqlDataReader["usd"]; prices.UsdFoil = (String)sqlDataReader["usd_foil"]; prices.Eur = (String)sqlDataReader["eur"]; prices.Tix = (String)sqlDataReader["tix"]; listPrices.Add(prices); } sqlDataReader.Read(); return(listPrices); } else { return(null); } }
public async Task <IActionResult> Edit(int id, [Bind("Id,Price,DateCreation,CurrencyId")] Prices prices) { prices.DateCreation = DateTime.Now; if (id != prices.Id) { return(NotFound()); } if (ModelState.IsValid) { try { _context.Update(prices); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!PricesExists(prices.Id)) { return(NotFound()); } else { throw; } } return(RedirectToAction(nameof(Index))); } ViewData["CurrencyId"] = new SelectList(_context.Currencys, "Id", "Id", prices.CurrencyId); return(View(prices)); }
public JsonResult UpdateBerryPrice(Prices prices) { KoskenkorvanLuomutilaEntities3 entity = new KoskenkorvanLuomutilaEntities3(); string berry = prices.Berry; bool success = false; Price oldPrice = (from p in entity.Prices where p.Berry == berry select p).FirstOrDefault(); if (oldPrice != null) { oldPrice.Berry = prices.Berry; oldPrice.Price_per_litre = prices.Price_Per_Litre; entity.SaveChanges(); success = true; } entity.Dispose(); return(Json(success)); }
public async Task <IActionResult> Create(int currencyId, [Bind("Id,Price,DateCreation,CurrencyId")] Prices prices) { prices.DateCreation = DateTime.Now; prices.CurrencyId = currencyId; Console.WriteLine("IDDDD : " + prices.Id); if (ModelState.IsValid) { _context.Add(prices); await _context.SaveChangesAsync(); //return RedirectToAction(nameof(Index)); return(RedirectToAction("Index", "Prices", new { id = currencyId, currency = _context.Currencys .Where(c => c.Id == currencyId) .FirstOrDefault().Currency })); } //ViewData["CurrencyId"] = new SelectList(_context.Currencys, "Id", "Id", prices.CurrencyId); return(RedirectToAction("Index", "Prices", new { id = currencyId, currency = _context.Currencys .Where(c => c.Id == currencyId) .FirstOrDefault().Currency })); }
public void WashTheCar(Car car) { if (Prices == null || Prices.Count == 0) { return; } // Читается так: словарь, попытайся дать значение для ключа car.BodyType и, если такой ключ есть, то помести // значение в переменную price. Если удачно, то выражение в круглых скобках вернёт true и условный оператор сработает, // если же нет (т.е. такого ключа нет в словаре), то и счётчики не поменяются. if (Prices.TryGetValue(car.BodyType, out var price)) { Profit += price; CarCounter++; } // Так код выглядел бы, если цены жёстко определены внутри автомойки. // В таком варианте теряется возможность менять цены без перепрограммирования кода автомойки. //switch (car.BodyType) //{ // case BodyType.Car: // Profit += 200; // break; // case BodyType.Crossover: // Profit += 250; // break; //} }
public async Task <IActionResult> GetCottageById(int id, bool includeCalendar = false, bool includeOwners = false, bool includeMinPrice = false, DateTime?arrivalDate = null, int noOfNights = 0) { if (User.IsInRole("Customer") && includeOwners) { return(Unauthorized()); } var cottage = await _repo.GetCottageById(id, includeCalendar, includeOwners); if (cottage == null) { return(NotFound()); } var cottageToReturn = _mapper.Map <CottageDto>(cottage); cottageToReturn.MinPrice7Nights = (includeMinPrice) ? Prices.MinPrice7Nights(cottage.Calendar) : 0; cottageToReturn.RequestedPrice = (arrivalDate.HasValue) ? Prices.PriceForDates(cottage.Calendar, arrivalDate.Value, noOfNights) : 0; return(Ok(cottageToReturn)); }
/// <summary> /// Apply prices to product /// </summary> /// <param name="prices"></param> /// <param name="currentCurrency"></param> /// <param name="allCurrencies"></param> public void ApplyPrices(IEnumerable <ProductPrice> prices, Currency currentCurrency, IEnumerable <Currency> allCurrencies) { Prices.Clear(); Price = null; Currency = currentCurrency; //group prices by currency var groupByCurrencyPrices = prices.GroupBy(x => x.Currency).Where(x => x.Any()); foreach (var currencyGroup in groupByCurrencyPrices) { //For each currency need get nominal price (with min qty) var orderedPrices = currencyGroup.OrderBy(x => x.MinQuantity ?? 0).ThenBy(x => x.ListPrice); var nominalPrice = orderedPrices.FirstOrDefault(); //and add to nominal price other prices as tier prices nominalPrice.TierPrices.AddRange(orderedPrices.Select(x => new TierPrice(x.SalePrice, x.MinQuantity ?? 1))); //Add nominal price to product prices list Prices.Add(nominalPrice); } ApplyPricesWithExchangeRates(allCurrencies); //Set current product price for current currency Price = Prices.FirstOrDefault(x => x.Currency == currentCurrency); }
private void SpinnerPoStart_ItemSelected(object sender, AdapterView.ItemSelectedEventArgs e) { if (SpinnerPoStart.SelectedItemPosition != -1) { LoaderView.Visibility = ViewStates.Visible; AnimationLoader.Start(); new Thread(new ThreadStart(delegate //поток для загрузки данных { var cost = Prices.GetPrice(routs[SpinnerRouts.SelectedItemPosition].PromPynkt[SpinnerPoStart.SelectedItemPosition].id, ObratPO[SpinnerPoEnd.SelectedItemPosition].id, routs[SpinnerRouts.SelectedItemPosition].id); if (cost != "false") { trips = Trips.GetTripsOnDate(TripDate.ToString("yyyy-MM-dd"), routs[SpinnerRouts.SelectedItemPosition].PromPynkt[SpinnerPoStart.SelectedItemPosition].id.ToString(), ObratPO[SpinnerPoEnd.SelectedItemPosition].id.ToString(), routs[SpinnerRouts.SelectedItemPosition].id.ToString()); ListViewTripsParmetr.Height = Convert.ToInt32(function.convertDpToPixel(90, this)) * trips.Count; RunOnUiThread(() => ListViewTrips.Adapter = new TripsAdapter(this, trips)); RunOnUiThread(() => AnimationLoader.Stop()); RunOnUiThread(() => LoaderView.Visibility = ViewStates.Invisible); } else { RunOnUiThread(() => ListViewTrips.Adapter = null); RunOnUiThread(() => AnimationLoader.Stop()); RunOnUiThread(() => LoaderView.Visibility = ViewStates.Invisible); RunOnUiThread(() => function.AlertDialogShow("Предупреждение", "Между выбранными пунктами не осуществляется перевозка.", this)); } })).Start(); } }
public override View GetView(int position, View convertView, ViewGroup parent) { View row = convertView; Prices price = productList[position]; if (row == null) { row = LayoutInflater.From(CurrentContext) .Inflate(Resource.Layout.productrowlayout, null, false); TextView productName = row.FindViewById <TextView>(Resource.Id.rowProductTitle); TextView productPrice = row.FindViewById <TextView>(Resource.Id.rowProductPrice); Button deleteButton = row.FindViewById <Button>(Resource.Id.deleteProductButton); productName.Text = productList[position].Name; productPrice.Text = "" + productList[position].Price + " kr."; deleteButton.Click += (object s, EventArgs e) => { TestCount++; //Toast.MakeText(row.Context, "Counts: " + TestCount, ToastLength.Short).Show(); DeleteHandler.Invoke(s, new DeleteEventArgs { ProductId = productList[position].ProductId }); }; } return(row); }
Prices[] product; //Создание массива екземпляров структруры Prices public PriceTable() //Конструктор по умолчанию { product = new Prices[2]; //Объявление массива из двух элементов string shop; string number; uint? price; for (int i = 0; i < 2; i++) { Console.WriteLine("Введите номер товара"); number = Console.ReadLine(); Console.WriteLine("Введите магазин"); shop = Console.ReadLine(); Console.WriteLine("Введите цену"); try //Попытка присвоить переменной price значения полученного от пользователя конвертированного в ToUInt32 { price = Convert.ToUInt32(Console.ReadLine()); } catch (Exception e) //Обратока возможного исключения { Console.WriteLine("Попытка записи неверного формата."); Console.WriteLine(e.Message); price = null; } product[i] = new Prices(number, shop, price); //В массив добавляется новый экземпляр Prices со значениями переданными в качестве аргументов конструктору } product = product.OrderBy(products => products.Number).ToArray <Prices>(); //Сортировка массива по полю Number }
/// <summary> /// Constructor that accepts values for all mandatory fields /// </summary> ///<param name="refId">GUID that identifies this meal price.</param> ///<param name="schoolInfoRefId">GUID that identifies the school this meal price belongs to</param> ///<param name="program">Refer to section 5.1.23 Program.</param> ///<param name="prices">Price of the meal</param> /// public FoodserviceMealPrices( string refId, string schoolInfoRefId, Program program, Prices prices ) : base(Adk.SifVersion, FoodDTD.FOODSERVICEMEALPRICES) { this.RefId = refId; this.SchoolInfoRefId = schoolInfoRefId; this.Program = program; this.Prices = prices; }
public PricesResponse Delete(Prices request) { Bm2s.Data.Common.BLL.Article.Price item = Datas.Instance.DataStorage.Prices[request.Price.Id]; item.EndingDate = DateTime.Now; Datas.Instance.DataStorage.Prices[item.Id] = item; PricesResponse response = new PricesResponse(); response.Prices.Add(request.Price); return response; }
public PricesResponse Get(Prices request) { PricesResponse response = new PricesResponse(); List<Bm2s.Data.Common.BLL.Article.Price> items = new List<Data.Common.BLL.Article.Price>(); if (!request.Ids.Any()) { items.AddRange(Datas.Instance.DataStorage.Prices.Where(item => (request.ArticleId == 0 || item.ArticleId == request.ArticleId) && (!request.Date.HasValue || (request.Date >= item.StartingDate && (!item.EndingDate.HasValue || request.Date < item.EndingDate.Value))) )); } else { items.AddRange(Datas.Instance.DataStorage.Prices.Where(item => request.Ids.Contains(item.Id))); } var collection = (from item in items select new Bm2s.Poco.Common.Article.Price() { Article = new ArticlesService().Get(new Articles() { Ids = new List<int>() { item.ArticleId } }).Articles.FirstOrDefault(), BasePrice = Convert.ToDecimal(item.BasePrice), EndingDate = item.EndingDate, Id = item.Id, StartingDate = item.StartingDate }).AsQueryable().OrderBy(request.Order, !request.DescendingOrder); response.ItemsCount = collection.Count(); if (request.PageSize > 0) { response.Prices.AddRange(collection.Skip((request.CurrentPage - 1) * request.PageSize).Take(request.PageSize)); } else { response.Prices.AddRange(collection); } try { response.PagesCount = collection.Count() / response.Prices.Count + (collection.Count() % response.Prices.Count > 0 ? 1 : 0); } catch { response.PagesCount = 1; } return response; }