Пример #1
0
    static void Main(string[] args)
    {
        PriceClass   _priceClass = new PriceClass();
        Type         type        = typeof(PriceClass);
        PropertyInfo info        = type.GetProperty("Value");

        info.SetValue(_priceClass, 32, null);
        Console.WriteLine(_priceClass.Value);

        PriceStruct _priceStruct = new PriceStruct();

        type = typeof(PriceStruct);
        info = type.GetProperty("Value");
        info.SetValue(_priceStruct, 32, null);
        Console.WriteLine(_priceStruct.Value);

        object _bpriceStruct = new PriceStruct();  //Box first

        type = typeof(PriceStruct);
        info = type.GetProperty("Value");
        info.SetValue(_bpriceStruct, 65, null);
        Console.WriteLine(((PriceStruct)_bpriceStruct).Value); //now unbox and get value

        // Debugger.Break();
    }
        public async Task <ActionResult <PriceClassDTO> > PostPrice([FromBody] PriceClassDTO priceDTO)
        {
            //  Location location = mapper.Map<Location>(destinationDTO.LocationDTO);
            // Location createdLocation = await genericLocationRepo.Create(location);
            if (priceDTO == null)
            {
                return(BadRequest(new { Message = "No price input" }));
            }

            try
            {
                PriceClass price  = mapper.Map <PriceClass>(priceDTO);
                var        result = await genericPriceRepo.Create(price);

                if (result == null)
                {
                    return(BadRequest(new { Message = $"Price {priceDTO.Value} could not be saved" }));
                }
                return(Created("api/reservations/price", priceDTO));
            }
            catch (Exception ex)
            {
                return(RedirectToAction("HandleErrorCode", "Error", new
                {
                    statusCode = 400,
                    errorMessage = $"Creating price {priceDTO} failed : {ex}"
                }));
            }
        }
Пример #3
0
        public IActionResult AddFuel(PriceClass priceFuels)
        {
            //CookieOptions option = new CookieOptions();
            //option.Expires = DateTime.Now.AddSeconds(2 * 10 + 240);
            //Response.Cookies.Append(_cookieKey, JsonConvert.SerializeObject(priceFuels), option);
            _service.AddPriceFuels(priceFuels);
            //_cache.Remove("PriceFuels");

            return(View("PriceList", _service.GetPriceFuels()));
        }
Пример #4
0
        private PriceClassVM ConvertPriceClass(PriceClass price)
        {
            PriceClassVM OutPrice = new PriceClassVM()
            {
                Id    = price.Id,
                Price = price.Price
            };

            return(OutPrice);
        }
Пример #5
0
 /// <summary>
 /// Copies fields from source record. This is low-level method that
 /// disregards if destination record (i.e. this record) is immutable.
 /// </summary>
 ///
 protected override void SetFieldsFrom(MovieExemplar source)
 {
     this.media       = source.media;
     this.priceClass  = source.priceClass;
     this.isan        = source.isan;
     this.released    = source.released;
     this.subtitles   = source.subtitles;
     this.imageFormat = source.imageFormat;
     this.features    = source.features;
 }
        /// <summary>
        /// Edits the row in the database table that corresponds to the provided input film
        /// with information encapsulated in the wrapper class object.
        /// </summary>
        /// <param name="editAddFilm">The wrapper class for creating/editing films</param>
        /// <param name="priceClassId">PK for the price class that is selected</param>
        /// <param name="genreIds">PKs for the selected genres</param>
        /// <returns>An empty string if successful, an error message if not</returns>
        public string EditFilm(AddFilmVM editAddFilm, int priceClassId, int[] genreIds)
        {
            var editFilm = new FilmVM()
            {
                Id          = editAddFilm.FilmId,
                Title       = editAddFilm.Title,
                Description = editAddFilm.Description,
                ImgURL      = editAddFilm.ImgURL
            };

            try
            {
                using (var db = new VideoDB())
                {
                    Film film = db.Films.Find(editFilm.Id);
                    film.Title       = editFilm.Title;
                    film.Description = editFilm.Description;
                    film.ImgURL      = editFilm.ImgURL;

                    PriceClass findPriceClass = db.PriceClasses.Find(priceClassId);
                    film.PriceClasses = findPriceClass;
                    film.PriceClassId = priceClassId;

                    //Bug i EF? Må iterere gjennom listen for å nullstille
                    foreach (Genre g in film.Genres)
                    {
                    }

                    if (genreIds != null)
                    {
                        film.Genres.RemoveRange(0, film.Genres.Count);
                        foreach (int genreId in genreIds)
                        {
                            film.Genres.Add(db.Genres.Find(genreId));
                        }
                    }

                    string gIDs = "";

                    if (genreIds.Length > 0)
                    {
                        gIDs = string.Join(" ", genreIds);
                    }
                    film.GenreIds = gIDs;

                    db.SaveChanges();
                    return("");
                }
            }
            catch (Exception e)
            {
                new ErrorLogRepository().CreateError("Oblig1.DAL.FilmDAL.EditFilm(FilmVM newFilm)", editFilm.ToString(), e);
                return("Kunne ikke lagre filmen i databasen, vennligst kontakt kundeservice!");
            }
        }
        /// <summary>
        /// Creates a new film from the provided data and initializes a new row in the film
        /// database table with the required information returned from the view.
        /// </summary>
        /// <param name="newAddFilm">The wrapper class for creating/editing films</param>
        /// <param name="priceClassId">PK for the selected price class</param>
        /// <param name="genreIds">PKs for the selected genres</param>
        /// <returns>An empty string if the operations were successful, otherwise an error message</returns>
        public string CreateFilm(AddFilmVM newAddFilm, int priceClassId, int[] genreIds)
        {
            var newFilm = new FilmVM()
            {
                Title       = newAddFilm.Title,
                Description = newAddFilm.Description,
                ImgURL      = newAddFilm.ImgURL
            };

            try
            {
                using (var db = new VideoDB())
                {
                    var newDBFilm = new Film
                    {
                        Title       = newFilm.Title,
                        Description = newFilm.Description,
                        ImgURL      = newFilm.ImgURL
                    };

                    PriceClass findPriceClass = db.PriceClasses.Find(priceClassId);
                    newDBFilm.PriceClasses = findPriceClass;

                    newDBFilm.PriceClassId = priceClassId;

                    List <Genre> genreList   = new List <Genre>();
                    List <int>   genreIdList = new List <int>();
                    foreach (int genreId in genreIds)
                    {
                        genreList.Add(db.Genres.Find(genreId));
                        genreIdList.Add(genreId);
                    }

                    newDBFilm.Genres = genreList;
                    string gIDs = "";

                    if (genreIds.Length > 0)
                    {
                        gIDs = string.Join(" ", genreIds);
                    }

                    newDBFilm.GenreIds = gIDs;
                    db.Films.Add(newDBFilm);
                    db.SaveChanges();
                    return("");
                }
            }
            catch (Exception e)
            {
                new ErrorLogRepository().CreateError("Oblig1.DAL.CustomerDAL.CreateFilm(FilmVM newFilm)", newFilm.ToString(), e);
                return("Kunne ikke lagre filmen i databasen, vennligst kontakt kundeservice!");
            }
        }
Пример #8
0
        public void AddPriceFuels(PriceClass priceFuels)
        {
            //ClassType classType = new ClassType { Name = Char.ConvertFromUtf32(Char.ConvertToUtf32("о", 0)) , Description = "Стандартный" };
            //_db.ClassTypes.Add(classType);
            //_db.SaveChanges();

            Class newClass = new Class {
                ClassLead = priceFuels.ClassLead, Count = priceFuels.Count, Date = DateTime.Now, ClassTypeId = priceFuels.ClassTypeId
            };

            _db.Classes.Add(newClass);
            _db.SaveChanges();
        }
Пример #9
0
        /////////////////////////////////////////////////////////////////////////////////

        #region [ Constructors ]

        /// <summary>
        /// Creates a new instance of price specification. Note that constructor is
        /// marked as internal, so the user cannot directly create instances --
        /// it must use <see cref="PriceList.UpdatePrice"/> method instead.
        /// </summary>
        ///
        internal MinQuantityPrice(VideoRentalOutlet database,
                                  Membership membership, PriceClass priceClass)
            : base(database, "Price Specification")
        {
            // Mandatory values
            //
            this.ID         = database.NextPriceSpecID;
            this.Membership = membership;
            this.PriceClass = priceClass;

            // Default properties:
            //
            this.MinimumQuantity = 0;
            this.Price           = 0;
        }
Пример #10
0
        /////////////////////////////////////////////////////////////////////////////////

        #region [ Public Methods ]

        /// <summary>
        /// Updates price for minimum quantity of rented items for specific membership
        /// and movie price class. If price does not exist, a new min-qty price
        /// specification is added.
        /// </summary>
        /// <param name="membership">Membership category</param>
        /// <param name="priceClass">Movie price class</param>
        /// <param name="minimumQuantity">Minimum quantity of rented items</param>
        /// <param name="newPrice">New renting price</param>
        ///
        public MinQuantityPrice UpdatePrice(
            Membership membership, PriceClass priceClass,
            int minimumQuantity, decimal newPrice
            )
        {
            // Find exising min-qty price for given membership, price class and minimum
            // quantity
            //
            MinQuantityPrice price = this.Items.Find(priceSpec =>
            {
                return(priceSpec.Membership == membership &&
                       priceSpec.PriceClass == priceClass &&
                       priceSpec.MinimumQuantity == minimumQuantity);
            });

            if (price != null)
            {
                // Update min-qty price if it exists
                //
                price.Price = newPrice;

                OnUpdated(price);

                return(price);
            }

            // If min-qty price is not found, add new association between membership
            // and price class with minimum quantity and new price as attributes.
            //
            this.Items.Add
            (
                price = new MinQuantityPrice(Database, membership, priceClass)
            {
                MinimumQuantity = minimumQuantity,
                Price           = newPrice
            }
            );

            // Keep list sorted, so it can be searched properly.
            //
            Sort();

            // Raise event that a new price specification was added to the price list
            //
            OnAddedNew(price);

            return(price);
        }
Пример #11
0
        /// <summary>
        /// Gets suggested rental fee from price list according customer's membership
        /// status and movie exemplar's price class. Price list (which is sorted with
        /// descending membership status, ascending price class and descending minimum
        /// quantity) is searched until minimal qualifying price specification is found.
        /// </summary>
        ///
        public decimal GetPrice(
            Membership membership, PriceClass priceClass, int quantity)
        {
            decimal fee = 0;

            foreach (MinQuantityPrice price in PriceList)
            {
                fee = price.Price;

                if (membership >= price.Membership && priceClass <= price.PriceClass &&
                    quantity >= price.MinimumQuantity)
                {
                    break;
                }
            }

            return(fee);
        }
Пример #12
0
        public IActionResult AddFuel()
        {
            ViewData["Message"] = "Add fuel date";
            List <string> TypeClass = new List <string> {
                "1", "2", "3", "4"
            };

            ViewBag.TypeClass = new SelectList(TypeClass);
            PriceClass priceClass = new PriceClass("1", "11", 1, DateTime.Now);

            if (Request.Cookies.ContainsKey(_cookieKey))
            {
                priceClass = JsonConvert.DeserializeObject <PriceClass>(Request.Cookies[_cookieKey]);
            }

            //ViewBag.PriceClass = priceClass;

            return(View(priceClass));
        }
Пример #13
0
        /// <summary>
        /// Saving price changes to the database.
        /// </summary>
        /// <param name="id">Price class id</param>
        /// <param name="newPrice">New price value</param>
        /// <returns>True if successful, else false.</returns>
        public bool ChangePrice(int id, int newPrice)
        {
            try
            {
                using (var db = new VideoDB())
                {
                    PriceClass Price = db.PriceClasses.Find(id);
                    Price.Price = newPrice;
                    db.SaveChanges();

                    return(true);
                }
            }
            catch (Exception e)
            {
                new ErrorLogRepository().CreateError("Oblig1.DAL.PriceRepository.ChangePrice(int id, int newPrice)", id.ToString() + "/r/n" + newPrice.ToString(), e);

                return(false);
            }
        }
Пример #14
0
    static void Main(string[] args)
    {
        PriceClass _priceClass = new PriceClass();
        Type type = typeof(PriceClass);
        PropertyInfo info = type.GetProperty("Value");
        info.SetValue(_priceClass, 32, null);
        Console.WriteLine(_priceClass.Value);

        PriceStruct _priceStruct = new PriceStruct();
        type = typeof(PriceStruct);
        info = type.GetProperty("Value");
        info.SetValue(_priceStruct, 32, null);
        Console.WriteLine(_priceStruct.Value);
        
         object _bpriceStruct = new PriceStruct(); //Box first
    type = typeof(PriceStruct);
    info = type.GetProperty("Value");
    info.SetValue(_bpriceStruct, 65, null);
    Console.WriteLine(((PriceStruct)_bpriceStruct).Value); //now unbox and get value

       // Debugger.Break();
    }
        public void PostNewPrice(PriceClass price)
        {
            if (price.Id == 0)
            {
                var newId = Prices.Select(@class => @class.Id).Max() + 1;
                price.Id = newId;
                Prices.Add(price);

                var newPriceChange = new PriceChangeClass
                {
                    Action   = "New",
                    Id       = price.Id,
                    ItemName = price.ItemName,
                    Price    = price.Price,
                    priceWas = 0
                };
                PriceChanges.Add(newPriceChange);
            }

            else
            {
                var oldPrice = Prices.FirstOrDefault(@class => @class.Id == price.Id);
                Prices.Remove(oldPrice);
                Prices.Add(price);

                var newPriceChange = new PriceChangeClass
                {
                    Action   = "Edit",
                    Id       = price.Id,
                    ItemName = price.ItemName,
                    Price    = price.Price,
                    priceWas = oldPrice.Price
                };
                PriceChanges.Add(newPriceChange);
            }
            Utils.SaveToFile();
        }
        private static async Task MakeReservations()
        {
            foreach (Flight flight in _flightsData)
            {
                List <ReservedSeat> reservedSeats = new List <ReservedSeat>();
                Reservation         reservation   = new Reservation
                {
                    FlightId = flight.Id,
                    UserId   = UserId,
                };

                for (var i = 0; i < _personData.Count(); i++)
                {
                    Seat         freeSeat     = _seatData.Where(se => se.AirplaneId == flight.AirplaneId && se.Reserved == false).ToList()[0];
                    PriceClass   price        = _priceData.Where(price => price.BeginDate <= DateTime.Now && price.EndDate >= DateTime.Now).FirstOrDefault();
                    ReservedSeat reservedSeat = new ReservedSeat
                    {
                        SeatId        = freeSeat.Id,
                        PriceId       = price.Id,
                        PersonId      = _personData[i].Id,
                        ReservationId = reservation.Id,
                        TicketPrice   = Math.Round((price.Value * flight.DistanceInKm / 1000), 2)
                    };


                    freeSeat.Reserved       = true;
                    reservation.TotalPrice += reservedSeat.TicketPrice;
                    reservation.TotalSeats += 1;
                    reservedSeats.Add(reservedSeat);
                }

                _reservedSeatData.AddRange(reservedSeats);
                _reservationData.Add(reservation);
                _airplaneData.Where(ap => ap.Id == flight.AirplaneId).FirstOrDefault().ReservedSeats = reservedSeats.Count();
            }
        }
        public async Task <ActionResult <CreateReservationDTO> > PostReservation(CreateReservationDTO reservationDTO)
        {
            if (reservationDTO == null)
            {
                return(BadRequest(new { Message = "No reservation input" }));
            }
            //TODO: check if reservation with flightId and userId exists. if it does do put, else continu post.

            try
            {
                Flight flight = await flightRepo.GetAsyncByGuid(reservationDTO.FlightId);

                if (flight != null)
                {
                    Reservation reservation = mapper.Map <Reservation>(reservationDTO);
                    foreach (ReservedSeat reservedSeat in reservation.ReservedSeats)
                    {
                        PriceClass price = await genericPriceRepo.GetAsyncByGuid(reservedSeat.PriceId);

                        if (price != null)
                        {
                            Seat seat = await genericSeatRepo.GetAsyncByGuid(reservedSeat.SeatId);

                            seat.Reserved = true;
                            await genericSeatRepo.Update(seat, seat.Id);

                            reservedSeat.TicketPrice = price.Value != 0 && flight.DistanceInKm != 0 ? price.Value * (flight.DistanceInKm / 1000) : 0;
                            reservedSeat.PersonId    = reservedSeat.Person.Id;
                            reservation.TotalPrice  += reservedSeat.TicketPrice;
                            reservation.TotalSeats  += 1;
                            flight.Airplane          = await airplaneRepo.GetAsyncByGuid(flight.AirplaneId.Value);

                            flight.Airplane.ReservedSeats += 1;
                            if (flight.Airplane.ReservedSeats == flight.Airplane.TotalSeats)
                            {
                                //TODO: realtime message to admin
                                Console.WriteLine("Airplane is fully booked.");
                                MessageObject message = new MessageObject()
                                {
                                    Message = $"Airplane {flight.Airplane.Name} on flight with Id {flight.Id} is fully booked. Please add an extra plane."
                                };
                                await sender.Send(message);
                            }
                        }
                        else
                        {
                            return(RedirectToAction("HandleErrorCode", "Error", new
                            {
                                statusCode = 404,
                                errorMessage = $"Could not find price. "
                            }));
                        }
                    }

                    var createdReservation = await reservationRepo.Create(reservation);

                    if (createdReservation == null)
                    {
                        return(BadRequest(new { Message = $"Reservation could not be saved" }));
                    }
                    return(Created("/api/reservations", reservationDTO));
                }
                else
                {
                    return(RedirectToAction("HandleErrorCode", "Error", new
                    {
                        statusCode = 404,
                        errorMessage = $"Could not find flight. "
                    }));
                }
            }
            catch (Exception ex)
            {
                return(RedirectToAction("HandleErrorCode", "Error", new
                {
                    statusCode = 400,
                    errorMessage = $"Creating reservation failed {ex}"
                }));
            }
        }
Пример #18
0
 public void PostNewPrice(PriceClass price)
 {
     throw new NotImplementedException();
 }
 public void PostNewPrice(PriceClass price)
 {
     dataAccess.PostNewPrice(price);
 }