示例#1
0
        public ActionResult Create([Bind(Include = "Name,YearOfEstablishment,NumberOfWonChampionShip,EntryFee")] Team team)
        {
            if (ModelState.IsValid)
            {
                db.Teams.Add(team);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            return(View(team));
        }
 public ActionResult Edit([Bind(Include = "WorkoutID,AthleteID,WorkoutDescription,WorkoutDate,WorkoutDistance,WorkoutIntensity,WorkoutCategory")] Workout workout)
 {
     if (ModelState.IsValid)
     {
         db.Entry(workout).State = EntityState.Modified;
         db.SaveChanges();
         return(RedirectToAction("Index"));
     }
     ViewBag.AthleteID = new SelectList(db.Athletes, "AthleteID", "FirstName", workout.AthleteID);
     return(View(workout));
 }
示例#3
0
        public void TestRaceInfo()
        {
            using (RaceContext context = new RaceContext())
            {
                context.Races.Clear();
                context.Cars.Clear();
                context.Tracks.Clear();
                context.CarInRaces.Clear();
                context.Cars.AddRange(RaceTestCars);
                context.Tracks.AddRange(RaceTestTracks);
                context.Races.AddRange(RaceTestRaces);
                context.CarInRaces.AddRange(RaceTestCarInRaces);
                context.SaveChanges();
                Queries queries  = new Queries();
                var     raceInfo = queries.GetRaceInfo(RaceTestRaces[2].Id);
                var     expected = new RaceInfo()
                {
                    RaceId       = RaceTestRaces[2].Id,
                    ActualEnd    = RaceTestRaces[2].ActualEndTime,
                    ActualStart  = RaceTestRaces[2].ActualStartTime,
                    NumberOfLaps = RaceTestRaces[2].NumberOfLaps,
                    PlannedEnd   = RaceTestRaces[2].PlannedEndTime,
                    PlannedStart = RaceTestRaces[2].PlannedStartTime,
                    TrackId      = RaceTestRaces[2].Tracks.Id,
                    TrackName    = RaceTestRaces[2].Tracks.Name,

                    Cars = CreateListOfCarInfo(new CarInRaces[3] {
                        RaceTestCarInRaces[2], RaceTestCarInRaces[6], RaceTestCarInRaces[10]
                    })
                };

                Assert.Equal(expected.ToString(), raceInfo.ToString());
            }
        }
示例#4
0
        public void TestTrackInfo()
        {
            using (RaceContext context = new RaceContext())
            {
                context.Races.Clear();
                context.Cars.Clear();
                context.Tracks.Clear();
                context.CarInRaces.Clear();
                context.Cars.AddRange(TrackTestCars);
                context.Tracks.AddRange(TrackTestTracks);
                context.Races.AddRange(TrackTestRaces);
                context.CarInRaces.AddRange(TrackTestCarInRaces);
                context.SaveChanges();
                Queries querie    = new Queries();
                var     trackInfo = querie.GetTrackInfo(TrackTestTracks[0].Id);
                var     expected  = new TrackInfo()
                {
                    Id             = TrackTestTracks[0].Id,
                    FastestLap     = TimeSpan.FromTicks(2345524323),
                    FastestsCar    = "PW",
                    FastestsDriver = "Karl",
                    Name           = "LongTrack",
                    NumberOfRaces  = 4
                };

                Assert.Equal(expected.ToString(), trackInfo.ToString());
            }
        }
示例#5
0
        public void ForceCloseOrder(int orderid, string reason, List <ForceClearPOCO> clearitem, int vendorid)
        {
            List <string> errors = new List <string>();

            using (var context = new RaceContext())
            {
                var closed = (from x in context.Orders
                              where x.OrderID == orderid
                              select x.Closed).FirstOrDefault();
                var closeorderlist = new List <ForceClearPOCO>();

                if (closed)
                {
                    errors.Add("You cannot close an already closed order");
                }
                else
                {
                    foreach (var item in clearitem)
                    {
                        var closesearch = (from x in context.Products
                                           where x.ItemName == item.ItemName
                                           select x).FirstOrDefault();

                        closesearch.QuantityOnOrder = closesearch.QuantityOnOrder - item.Remaining;
                    }
                    var query = (from x in context.Orders
                                 where x.OrderID == orderid && x.VendorID == vendorid
                                 select x).FirstOrDefault();
                    query.Comment = reason;
                    CloseOrder(orderid);
                    context.SaveChanges();
                }
            }
        }
示例#6
0
        public int Update_RaceResultsView(int employeeid, int raceid, List <RaceResultsView> items)
        {
            using (var context = new RaceContext())
            {
                foreach (RaceResultsView item in items)
                {
                    if (item.Time == null)
                    {
                        errors.Add("Times must be in the format hh:mm:ss.");
                        break;
                    }
                }
                foreach (RaceResultsView item in items)
                {
                    if (item.Time != null & item.Time < new TimeSpan(00, 00, 00))
                    {
                        errors.Add("Times must be positive.");
                        break;
                    }
                }

                if (errors.Count == 0)
                {
                    items = items.OrderBy(x => x.Time).ToList();
                    int?placement = 0;
                    int?penalties = null;
                    foreach (RaceResultsView item in items)
                    {
                        if (item.Time != new TimeSpan(00, 00, 00))
                        {
                            placement++;
                        }
                        else
                        {
                            item.Time = null;
                        }
                        if (item.Penalties != 0)
                        {
                            penalties = item.Penalties;
                        }
                        RaceDetail newitem = (from x in context.RaceDetails
                                              where x.RaceDetailID == item.RaceDetailID
                                              select x).FirstOrDefault();
                        newitem.Place                = placement == 0 ? null : placement;
                        newitem.RunTime              = item.Time;
                        newitem.PenaltyID            = penalties;
                        context.Entry(newitem).State = System.Data.Entity.EntityState.Modified;
                    }
                }
                if (errors.Count == 0)
                {
                    return(context.SaveChanges());
                }
                else
                {
                    throw new BusinessRuleException("Race Time Validation Error.", errors);
                }
            }
        }
示例#7
0
 public ActionResult Create([Bind(Include = "AthleteID,FirstName,LastName,Gender,Email,DOB,CreatedAt,FitnessLevel,FitnessGoal")] Athlete athlete)
 {
     try
     {
         if (ModelState.IsValid)
         {
             db.Athletes.Add(athlete);
             db.SaveChanges();
             return(RedirectToAction("Index"));
         }
     }
     catch (DataException)
     {
         ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists see your system administrator.");
     }
     return(View(athlete));
 }
示例#8
0
        public int Item_Delete(int itemid)
        {
            using (var context = new RaceContext())
            {
                var existing = context.UnOrderedItems.Find(itemid);

                context.UnOrderedItems.Remove(existing);
                return(context.SaveChanges());
            }
        }
示例#9
0
 public void CloseOrder(int orderid)
 {
     using (var context = new RaceContext())
     {
         var query = (from q in context.Orders
                      where q.OrderID == orderid
                      select q).First();
         query.Closed = true;
         context.SaveChanges();
     }
 }
示例#10
0
        public int Do_RefundTransaction(List <RefundItem> list)
        {
            // Check refund for Oinvoice already there
            using (var context = new RaceContext())
            {
                int invoiceID = list[0].InvoiceID;
                if (context.StoreRefunds.Where(x => x.InvoiceID == invoiceID) != null)
                {
                    var totals = CalculateTotals(list);
                    // Invoice with negative values
                    Invoice invoice = new Invoice();
                    invoice.EmployeeID  = list[0].EmployeeID;
                    invoice.GST         = (decimal)totals.Item2;
                    invoice.SubTotal    = (decimal)totals.Item1;
                    invoice.Total       = (decimal)totals.Item3;
                    invoice.InvoiceDate = DateTime.Now;

                    context.Invoices.Add(invoice);

                    // Invoice details

                    foreach (RefundItem item in list)
                    {
                        InvoiceDetail temp   = new InvoiceDetail();
                        StoreRefund   retemp = new StoreRefund();
                        if (item.ItemToBeRefunded)
                        {
                            temp.InvoiceID = invoice.InvoiceID;
                            temp.ProductID = item.ProductID;
                            temp.Quantity  = item.ProductQuantity;
                            temp.Price     = (decimal)item.ProductPrice;

                            retemp.InvoiceID         = invoice.InvoiceID;
                            retemp.ProductID         = item.ProductID;
                            retemp.OriginalInvoiceID = item.InvoiceID;
                            retemp.Reason            = item.Reason;
                            context.StoreRefunds.Add(retemp);

                            Product prodTemp = context.Products.Where(x => x.ProductID == item.ProductID && x.CategoryID == item.CategoryID).Single();
                            prodTemp.QuantityOnHand      += item.ProductQuantity;
                            context.Entry(prodTemp).State = System.Data.Entity.EntityState.Modified;
                        }
                    }
                    context.SaveChanges();
                    return(invoice.InvoiceID);
                }
                else
                {
                    throw new BusinessRuleException("Refund Error", new List <string> {
                        "Refund already exsists"
                    });
                }
            }
        }
示例#11
0
        private static void PopulatePilotData(RaceContext context)
        {
            context.Database.ExecuteSqlCommand("SET IDENTITY_INSERT dbo.Pilots ON");

            context.Pilots.Add(new Pilot
            {
                Id          = 1000,
                Code        = "Test",
                Name        = "Test Pilot",
                Nationality = "HUN",
                Number      = "33",
                TeamId      = 1000,
            });
            context.SaveChanges();
            context.Database.ExecuteSqlCommand("SET IDENTITY_INSERT dbo.Pilots OFF");
        }
示例#12
0
        public void TestFindById()
        {
            using (RaceContext context = new RaceContext())
            {
                using (CarCRUD CarCRUD = new CarCRUD(new RaceContext()))
                {
                    var car = new Cars {
                        Name = "Test2", DriverName = "Test2"
                    };
                    context.Cars.Add(car);
                    context.SaveChanges();


                    Assert.Equal(car.Id, CarCRUD.FindById(car.Id).Id);
                }
            }
        }
示例#13
0
        private static void PopulateTeamData(RaceContext context)
        {
            context.Database.ExecuteSqlCommand("SET IDENTITY_INSERT dbo.Teams ON");

            context.Teams.Add(new Team
            {
                Id        = 1000,
                OwnerName = "Test Owner",
                //    Pilots = new List<Pilot> { new Pilot { Id = 1000 } },
                Name = "Test Team",
                ChampionShipPoints = 10,
                DateOfFoundation   = DateTime.Now,
            });

            context.SaveChanges();
            context.Database.ExecuteSqlCommand("SET IDENTITY_INSERT dbo.Teams OFF");
        }
示例#14
0
        public void TestDelete()
        {
            Cars car = new Cars {
                Name = "hej", DriverName = "hehe"
            };

            using (RaceContext context = new RaceContext())
            {
                context.Cars.Add(car);
                context.SaveChanges();
            }
            using (CarCRUD CarCRUD = new CarCRUD(new RaceContext()))
            {
                CarCRUD.Delete(car.Id);
            }
            using (RaceContext context = new RaceContext())
            {
                Assert.Null(context.Cars.Find(car.Id));
            }
        }
示例#15
0
 public void SaveChanges()
 {
     if (_context != null)
     {
         _context.SaveChanges();
     }
     if (_spellsContext != null)
     {
         _spellsContext.SaveChanges();
     }
     if (_itemsContext != null)
     {
         _itemsContext.SaveChanges();
     }
     if (_playableClassContext != null)
     {
         _playableClassContext.SaveChanges();
     }
     if (_raceContext != null)
     {
         _raceContext.SaveChanges();
     }
 }
示例#16
0
        public int UnOrderedItem_Add(UnOrderedItem item)
        {
            using (var context = new RaceContext())
            {
                if (string.IsNullOrEmpty(item.ItemName))
                {
                    throw new BusinessRuleException("Please enter an unordered item.", reasons);
                }
                else if (item.Quantity <= 0)
                {
                    throw new BusinessRuleException("The Unordered item quantity must be greater than 0", reasons);
                }
                else
                {
                    var exists = (from x in context.Products
                                  where x.ItemName == item.ItemName
                                  select x.ProductID).FirstOrDefault().ToString();


                    item.VendorProductID = exists;

                    item.OrderID = 999;

                    if (item.VendorProductID == null || int.Parse(item.VendorProductID) == 0)
                    {
                        throw new BusinessRuleException("Item does not exist in the database.", reasons);
                    }
                    else
                    {
                        context.UnOrderedItems.Add(item); //staging
                        context.SaveChanges();            //actual commit to the database
                        return(item.ItemID);
                    }
                }
            }
        }
示例#17
0
        public void DeletePO(int vendorid)
        {
            using (var context = new RaceContext())
            {
                Order oldorder = null;
                oldorder = context.Orders.Where(x => x.VendorID == vendorid &&
                                                x.OrderNumber == null && x.OrderDate == null)
                           .Select(x => x).FirstOrDefault();

                if (oldorder != null)
                {
                    foreach (var row in context.OrderDetails)
                    {
                        if (row.OrderID == oldorder.OrderID)
                        {
                            context.OrderDetails.Remove(row);
                        }
                    }
                    context.Orders.Remove(oldorder);
                }

                context.SaveChanges();
            }
        }
示例#18
0
        public int Do_CartTransaction(List <CartDisplay> cartItems)
        {
            if (cartItems.Count < 1)
            {
                throw new BusinessRuleException("Cart Error: ", new List <string> {
                    "No Items in Cart"
                });
            }
            else
            {
                using (var context = new RaceContext())
                {
                    double subtotal = 0;
                    double total    = 0;
                    double tax      = 0;
                    foreach (CartDisplay item in cartItems)
                    {
                        CartDisplay tempItem = context.Products
                                               .Where(x => x.ProductID == item.ProductID && x.CategoryID == item.CategoryID)
                                               .Select(x => new CartDisplay {
                        }).Single();
                        if (tempItem == null)
                        {
                            throw new BusinessRuleException("Product not in database", new List <String> {
                                item.ProductName
                            });
                        }
                    }
                    // update product quantities
                    foreach (CartDisplay item in cartItems)
                    {
                        subtotal += item.ExtendedAmount;
                        tax      += subtotal * 0.05;
                        total    += subtotal + tax;
                        Product temp = context.Products
                                       .Where(x => x.CategoryID == item.CategoryID && x.ProductID == item.ProductID)
                                       .Single();
                        temp.QuantityOnHand      -= item.ProductQuantity;
                        context.Entry(temp).State = System.Data.Entity.EntityState.Modified;
                    }
                    // Create invoice
                    Invoice invoice = new Invoice();
                    invoice.EmployeeID  = cartItems[0].EmployeeID;
                    invoice.GST         = (decimal)tax;
                    invoice.InvoiceDate = DateTime.Now;
                    invoice.SubTotal    = (decimal)subtotal;
                    invoice.Total       = (decimal)total;

                    invoice = context.Invoices.Add(invoice);

                    // Create invoice details
                    foreach (CartDisplay item in cartItems)
                    {
                        InvoiceDetail temp = new InvoiceDetail();
                        temp.InvoiceID = invoice.InvoiceID;
                        temp.ProductID = item.ProductID;
                        temp.Quantity  = item.ProductQuantity;
                        temp.Price     = (decimal)item.ProductPrice;
                        context.InvoiceDetails.Add(temp);
                    }
                    int test = context.SaveChanges();
                    return(invoice.InvoiceID);
                }
            }
        }
示例#19
0
        public void DownloadData(string url)
        {
            string              MAIN_URL = url;
            HtmlDocument        doc;
            Task <HtmlDocument> tsk = GetData(MAIN_URL);

            doc = tsk.Result;
            Link lnk = new Link();

            lnk.URL = (MAIN_URL);


            HtmlNode node = doc.GetElementbyId("racecard");

            string courseandDate = node.ChildNodes[1].InnerText;


            DateTime raceDate;
            string   raceLocation = "";

            if (courseandDate.Contains('-'))
            {
                raceLocation = courseandDate.Split('-').ElementAt(0).Split(',').ElementAt(0);
                var dateStr = courseandDate.Split('-').ElementAt(1).Split(',').ElementAt(1);
                raceDate = DateTime.Parse(dateStr);
            }
            else
            {
                raceLocation = courseandDate.Split(',').ElementAt(0);
                int tempLen = courseandDate.Split(',').Count();
                raceDate = DateTime.Parse(courseandDate.Split(',').ElementAt(tempLen - 1));
            }


            var allRace    = node.ChildNodes[5].ChildNodes.Where(m => m.OriginalName.Equals("li"));
            int totalRaces = allRace.Count();

            if (totalRaces > 0)
            {
                using (var conn = new RaceContext())
                {
                    conn.Links.Add(lnk);
                    //conn.SaveChanges();
                    lnk.Races = new List <Race>();
                    var tempcontentsRaces = node.ChildNodes[7].ChildNodes[3].ChildNodes[1];
                    var contentsRaces     = tempcontentsRaces.ChildNodes.Where(m => m.Name == "div");

                    List <Race> races = new List <Race>();

                    foreach (var item in contentsRaces)
                    {
                        Race race = new Race();
                        race.Date     = raceDate;
                        race.Location = raceLocation;

                        var itemcontentsRace        = item.ChildNodes.Where(m => m.Attributes.Contains("class") && m.Attributes["class"].Value.Contains("raceDetails")).SingleOrDefault();
                        var itemcontentsRaceRunners = item.ChildNodes.Where(m => m.Attributes.Contains("class") && m.Attributes["class"].Value.Contains("cardFields")).SingleOrDefault();

                        var detailsInfo = itemcontentsRace.ChildNodes.Where(m => m.Attributes.Contains("class") && m.Attributes["class"].Value.Contains("detailInfo")).SingleOrDefault();

                        race.Title = detailsInfo.ChildNodes[1].InnerText;
                        var tempTime = detailsInfo.ChildNodes[3].ChildNodes[1].InnerText;
                        race.Time = race.Date;
                        if (!tempTime.Equals(" : : : "))
                        {
                            race.Time = race.Time.AddHours(double.Parse(tempTime.Split(':')[0]));
                            race.Time = race.Time.AddMinutes(double.Parse(tempTime.Split(':')[1]));
                        }

                        var typeandclass = detailsInfo.ChildNodes[3].ChildNodes[3].InnerText;
                        race.Class       = typeandclass.Split('-')[1];
                        race.Type        = typeandclass.Split('-')[0];
                        race.TrackLength = detailsInfo.ChildNodes[3].ChildNodes[5].InnerText.Split('M')[0] + "M";
                        race.TrackType   = detailsInfo.ChildNodes[3].ChildNodes[5].InnerText.Split('M')[1];

                        var winningPriceCurrency = detailsInfo.ChildNodes[3].ChildNodes[7].InnerText.Split(' ');
                        race.WinningCurrency = winningPriceCurrency.ElementAt(1);

                        string temprice = winningPriceCurrency.ElementAt(19).ToString().Replace(",", "");
                        race.WinningPrice = long.Parse(temprice);

                        var railSafety = detailsInfo.ChildNodes.Where(m => m.Attributes.Contains("class") && m.Attributes["class"].Value.Contains("railSafety")).SingleOrDefault();
                        race.Weather = railSafety.ChildNodes[1].ChildNodes[2].ChildNodes[0].InnerText;

                        race.TrackCondition = railSafety.ChildNodes[3].ChildNodes[2].ChildNodes.Count > 0 ? railSafety.ChildNodes[3].ChildNodes[2].ChildNodes[0].InnerText : "";

                        race.RailPosition = railSafety.ChildNodes[7].ChildNodes[2].ChildNodes.Count > 0 ? railSafety.ChildNodes[7].ChildNodes[2].ChildNodes[0].InnerText : "";

                        race.SafetyLimit = railSafety.ChildNodes[9].ChildNodes[2].ChildNodes.Count > 0 ? railSafety.ChildNodes[9].ChildNodes[2].ChildNodes[0].InnerText : "";

                        var finishTime = detailsInfo.ChildNodes.Where(m => m.Attributes.Contains("class") && m.Attributes["class"].Value.Contains("finishTime")).SingleOrDefault();
                        //finishTime.InnerText.Substring(finishTime.InnerText.IndexOf(@" " "))
                        Regex reg = new Regex("[0-9]{2}:[0-9]{2}:[0-9]{2}");
                        Match mch = reg.Match(finishTime.InnerText);
                        race.RunningTime = mch.Value;

                        //getting null string <span>(Hand Timed)</span> = <span></span>
                        reg = new Regex("[(].*[)]");
                        mch = reg.Match(finishTime.InnerHtml);
                        race.RunningTimeType = mch.Value;
                        //race.RunningTimeType = "Test";
                        var fullConditions = itemcontentsRace.ChildNodes.Where(m => m.Attributes.Contains("class") && m.Attributes["class"].Value.Contains("fullConditions")).SingleOrDefault();
                        var prizeBreak     = fullConditions.ChildNodes.Where(m => m.Attributes.Contains("class") && m.Attributes["class"].Value.Contains("prizeBreak")).SingleOrDefault();


                        var prizeTable = prizeBreak.ChildNodes.Where(m => m.Name == "table").SingleOrDefault();


                        var prizeTableTr = prizeTable.ChildNodes.Where(m => m.Name == "tr");
                        List <WinningPrice> allPrizes  = new List <WinningPrice>();
                        List <Runner>       allRunners = new List <Runner>();

                        int[] pricePosition = { 1, 4, 2, 5, 3, 7 };
                        int   tmp           = 0;

                        foreach (var bodyRow in prizeTableTr)
                        {
                            WinningPrice prize  = new WinningPrice();
                            WinningPrice prize2 = new WinningPrice();

                            var tablePrizestd = bodyRow.ChildNodes.Where(m => m.Name == "td");
                            prize.Position = pricePosition[tmp];
                            prize.Price    = long.Parse(tablePrizestd.ElementAt(1).InnerHtml.Replace(",", ""));
                            prize.Race     = race;
                            conn.WinningPrizes.Add(prize);
                            tmp = tmp + 1;

                            prize2.Position = pricePosition[tmp];
                            prize2.Price    = long.Parse(tablePrizestd.ElementAt(4).InnerHtml.Replace(",", ""));
                            prize2.Race     = race;

                            allPrizes.Add(prize);
                            allPrizes.Add(prize2);
                            tmp = tmp + 1;
                            conn.WinningPrizes.Add(prize2);
                        }
                        var detailedConditions = fullConditions.ChildNodes.Where(m => m.Attributes.Contains("class") && m.Attributes["class"].Value.Contains("detailedConditions")).SingleOrDefault();
                        race.Notes = detailedConditions.InnerText;

                        race.WinningPrices = allPrizes;
                        conn.Races.Add(race);

                        lnk.Races.Add(race);
                        //conn.SaveChanges();



                        var resultsTable     = itemcontentsRaceRunners.ChildNodes.Where(m => m.Attributes.Contains("class") && m.Attributes["class"].Value.Contains("entriesTable resultsTable")).SingleOrDefault();
                        var resultsTableRows = resultsTable.ChildNodes.Where(m => m.Name == "tbody").SingleOrDefault().ChildNodes.Where(m => m.Name == "tr");
                        race.Runners = new List <Runner>();
                        foreach (var runnerRow in resultsTableRows)
                        {
                            Runner tempRunner = new Runner();
                            tempRunner.Name = runnerRow.Attributes["owner"].Value;
                            var tempRunnerCols       = runnerRow.ChildNodes.Where(m => m.Name == "td");
                            var tempPositionValidate = tempRunnerCols.ElementAt(0).InnerText;

                            var tmpPosition = (tempPositionValidate.Contains("nd") ? tempPositionValidate.Replace("nd", "") : tempPositionValidate.Contains("st") ? tempPositionValidate.Replace("st", "") : tempPositionValidate.Contains("th") ? tempPositionValidate.Replace("th", "") : tempPositionValidate.Contains("rd") ? tempPositionValidate.Replace("rd", "") : tempPositionValidate);
                            tempRunner.Position = tmpPosition;
                            tempRunner.Margin   = tempRunnerCols.ElementAt(1).InnerText.ToString();
                            tempRunner.Drawn    = !string.IsNullOrEmpty(tempRunnerCols.ElementAt(2).InnerText) ? int.Parse(tempRunnerCols.ElementAt(2).InnerText) : 0;
                            tempRunner.OR       = tempRunnerCols.ElementAt(3).InnerText;
                            //tempRunner. Horse

                            string horseUrl = "http:/" + tempRunnerCols.ElementAt(4).ChildNodes.Where(m => m.Name == "a").SingleOrDefault().Attributes["href"].Value;

                            Horse tempHorse = new Horse()
                            {
                                URL  = horseUrl,
                                Name = tempRunnerCols.ElementAt(4).ChildNodes.Where(m => m.Name == "a").SingleOrDefault().InnerText,
                            };

                            conn.Horses.Add(tempHorse);
                            tempHorse.Runners = new List <Runner>();
                            tempHorse.Runners.Add(tempRunner);
                            tempRunner.Equipment = tempRunnerCols.ElementAt(6).InnerText;

                            string  trainerURl  = "http:/" + tempRunnerCols.ElementAt(7).ChildNodes.Where(m => m.Name == "a").SingleOrDefault().Attributes["href"].Value;
                            Trainer tempTrainer = new Trainer()
                            {
                                Name = tempRunnerCols.ElementAt(7).ChildNodes.Where(m => m.Name == "a").SingleOrDefault().InnerText,
                                URL  = trainerURl
                            };
                            tempTrainer.Runners = new List <Runner>();
                            tempTrainer.Runners.Add(tempRunner);
                            conn.Trainers.Add(tempTrainer);

                            string jockeyUrl  = "http:/" + tempRunnerCols.ElementAt(8).ChildNodes.Where(m => m.Name == "a").SingleOrDefault().Attributes["href"].Value;
                            Jockey tempJockey = new Jockey()
                            {
                                URL    = jockeyUrl,
                                Name   = tempRunnerCols.ElementAt(8).ChildNodes.Where(m => m.Name == "a").SingleOrDefault().InnerText,
                                Weight = decimal.Parse(tempRunnerCols.ElementAt(5).InnerText)
                            };

                            tempJockey.Runners = new List <Runner>();
                            tempJockey.Runners.Add(tempRunner);
                            conn.Jockeys.Add(tempJockey);
                            tempRunner.Race = race;
                            race.Runners.Add(tempRunner);

                            conn.Runners.Add(tempRunner);
                        }



                        conn.SaveChanges();
                    }
                }
            }
        }
示例#20
0
        public void PlacePO(List <PurchaseOrder> po, InfoToSave infolist)
        {
            using (var context = new RaceContext())
            {
                var results = po.Select(x => x);
                if (results.Count() == 0)
                {
                    errors.Add("The purchase order is empty. There is no purchase order to place.");
                }
                if (infolist.EmployeeID == 0)
                {
                    errors.Add("Select an employee.");
                }
                if (infolist.VendorID == 0)
                {
                    errors.Add("Select a vendor.");
                }
                if (errors.Count > 0)
                {
                    throw new BusinessRuleException("Placing Purchase Order", errors);
                }

                Order oldorder = null;
                oldorder = context.Orders.Where(x => x.VendorID == infolist.VendorID &&
                                                x.OrderNumber == null && x.OrderDate == null)
                           .Select(x => x).FirstOrDefault();

                if (oldorder != null)
                {
                    foreach (var row in context.OrderDetails)
                    {
                        if (row.OrderID == oldorder.OrderID)
                        {
                            context.OrderDetails.Remove(row);
                        }
                    }
                    context.Orders.Remove(oldorder);
                }

                int?neworderno = context.Orders.Where(x => x.OrderNumber != null).Select(x => x.OrderNumber).Max();
                neworderno++;

                Order neworder = new Order
                {
                    OrderNumber = neworderno,
                    OrderDate   = DateTime.Now,
                    EmployeeID  = infolist.EmployeeID,
                    VendorID    = infolist.VendorID,
                    Comment     = infolist.Comments,
                    SubTotal    = infolist.Subtotal,
                    TaxGST      = infolist.Tax
                };
                context.Orders.Add(neworder);

                foreach (var row in po)
                {
                    context.OrderDetails.Add(new OrderDetail
                    {
                        ProductID     = row.ProductID,
                        Quantity      = row.OrderQty,
                        OrderUnitSize = row.UnitSize,
                        Cost          = row.UnitCost
                    });
                }

                Product item = null;
                foreach (var row in po)
                {
                    item = context.Products
                           .Where(p => p.ProductID == row.ProductID)
                           .Select(od => od).FirstOrDefault();
                    if (item != null)
                    {
                        item.QuantityOnOrder += row.OrderQty * row.UnitSize;
                        context.Entry(item).Property(x => x.QuantityOnOrder).IsModified = true;
                    }
                }

                context.SaveChanges();
            }
        }
示例#21
0
        public void ReceiveShipment(int orderid, List <TransactionItemPOCO> received, List <RejectedItemPOCO> rejected)
        {
            List <string> errors = new List <string>();

            using (var context = new RaceContext())
            {
                var closed = (from x in context.Orders
                              where x.OrderID == orderid
                              select x.Closed).FirstOrDefault();


                if (closed)
                {
                    errors.Add("You cannot receive a closed order");
                }
                else if (received.Any(x => x.ItemQuantity < 0))
                {
                    errors.Add("You cannot have a negative received amount");
                }
                else
                {
                    int newrecieveorderid = context.ReceiveOrders.Select(x => x.ReceiveOrderID).Max();
                    newrecieveorderid++;


                    var recieveorderlist = new List <ReceiveOrderItem>();
                    var returnorderlist  = new List <ReturnOrderItem>();

                    foreach (var item in received)
                    {
                        int newrecieveorderitemid = context.ReceiveOrderItems.Select(x => x.ReceiveOrderItemID).Max();
                        newrecieveorderid++;

                        int orderDetailID = (from x in context.Products
                                             from y in x.OrderDetails
                                             where x.ItemName == item.ItemName && y.OrderID == orderid
                                             select y.OrderDetailID).FirstOrDefault();


                        recieveorderlist.Add(new ReceiveOrderItem()
                        {
                            ReceiveOrderItemID = newrecieveorderitemid,
                            ReceiveOrderID     = newrecieveorderid,
                            OrderDetailID      = orderDetailID,
                            ItemQuantity       = item.ItemQuantity,
                            OrderDetail        = (from x in context.OrderDetails
                                                  where x.OrderDetailID == orderDetailID
                                                  select x).FirstOrDefault(),
                            ReceiveOrder = (from x in context.ReceiveOrders
                                            where x.ReceiveOrderID == newrecieveorderid
                                            select x).FirstOrDefault()
                        });
                    }

                    if (rejected.Count() > 0)
                    {
                        foreach (var item in rejected)
                        {
                            int newreturnorderitemid = context.ReturnOrderItems.Select(x => x.ReturnOrderItemID).Max();
                            newreturnorderitemid++;

                            int orderDetailID = (from x in context.Products
                                                 from y in x.OrderDetails
                                                 where x.ItemName == item.ItemName && y.OrderID == orderid
                                                 select y.OrderDetailID).FirstOrDefault();


                            returnorderlist.Add(new ReturnOrderItem()
                            {
                                ReturnOrderItemID = newreturnorderitemid,
                                ReceiveOrderID    = newrecieveorderid,
                                OrderDetailID     = orderDetailID,
                                UnOrderedItem     = null,
                                ItemQuantity      = item.ItemQuantity,
                                Comment           = item.Reason,
                                VendorProductID   = null,
                                OrderDetail       = (from x in context.OrderDetails
                                                     where x.OrderDetailID == orderDetailID
                                                     select x).FirstOrDefault(),
                                ReceiveOrder = (from x in context.ReceiveOrders
                                                where x.ReceiveOrderID == newrecieveorderid
                                                select x).FirstOrDefault()
                            });
                        }
                    }


                    ReceiveOrder receiveOrder = new ReceiveOrder
                    {
                        ReceiveOrderID = newrecieveorderid,
                        OrderID        = orderid,
                        ReceiveDate    = DateTime.Now,
                        EmployeeID     = 56,
                        Employee       = (from x in context.Employees
                                          where x.EmployeeID == 56
                                          select x).FirstOrDefault(),
                        Order = (from x in context.Orders
                                 where x.OrderID == orderid
                                 select x).FirstOrDefault(),
                        ReceiveOrderItems = recieveorderlist,
                        ReturnOrderItems  = returnorderlist
                    };
                    context.ReceiveOrders.Add(receiveOrder);


                    foreach (var item in recieveorderlist.ToList())
                    {
                        ReceiveOrderItem receiveOrderItem = new ReceiveOrderItem
                        {
                            ReceiveOrderItemID = item.ReceiveOrderItemID,
                            ReceiveOrderID     = item.ReceiveOrderID,
                            OrderDetailID      = item.OrderDetailID,
                            ItemQuantity       = item.ItemQuantity,
                            OrderDetail        = item.OrderDetail,
                            ReceiveOrder       = item.ReceiveOrder
                        };

                        var query = (from x in context.OrderDetails
                                     join prod in context.Products on x.ProductID equals prod.ProductID
                                     where x.OrderDetailID == receiveOrderItem.OrderDetailID
                                     select prod).FirstOrDefault();

                        query.QuantityOnHand  = query.QuantityOnHand + receiveOrderItem.ItemQuantity;
                        query.QuantityOnOrder = query.QuantityOnOrder - receiveOrderItem.ItemQuantity;
                    }

                    if (returnorderlist.Count > 0)
                    {
                        foreach (var item in returnorderlist.ToList())
                        {
                            ReturnOrderItem returnOrderItem = new ReturnOrderItem()
                            {
                                ReturnOrderItemID = item.ReturnOrderItemID,
                                ReceiveOrderID    = item.ReceiveOrderID,
                                OrderDetailID     = item.OrderDetailID,
                                UnOrderedItem     = item.UnOrderedItem,
                                ItemQuantity      = item.ItemQuantity,
                                Comment           = item.Comment,
                                VendorProductID   = item.VendorProductID,
                                OrderDetail       = item.OrderDetail,
                                ReceiveOrder      = item.ReceiveOrder
                            };

                            var query = (from x in context.OrderDetails
                                         join prod in context.Products on x.ProductID equals prod.ProductID
                                         where x.OrderDetailID == returnOrderItem.OrderDetailID
                                         select prod).FirstOrDefault();
                        }
                    }


                    context.SaveChanges();
                }
                if (errors.Count > 0)
                {
                    throw new BusinessRuleException("Receive Shipment", errors);
                }
            }
        }
示例#22
0
        public void SavePO(List <PurchaseOrder> po, InfoToSave infolist)
        {
            using (var context = new RaceContext())
            {
                var results = po.Select(x => x);
                if (results.Count() == 0)
                {
                    errors.Add("The purchase order is empty. There is nothing to save.");
                }
                if (infolist.EmployeeID == 0)
                {
                    errors.Add("Select an employee.");
                }
                if (infolist.VendorID == 0)
                {
                    errors.Add("Select a vendor.");
                }
                if (errors.Count > 0)
                {
                    throw new BusinessRuleException("Saving Purchase Order", errors);
                }

                Order oldorder = null;
                oldorder = context.Orders.Where(x => x.VendorID == infolist.VendorID &&
                                                x.OrderNumber == null && x.OrderDate == null)
                           .Select(x => x).FirstOrDefault();

                if (oldorder != null)
                {
                    foreach (var row in context.OrderDetails)
                    {
                        if (row.OrderID == oldorder.OrderID)
                        {
                            context.OrderDetails.Remove(row);
                        }
                    }
                    context.Orders.Remove(oldorder);
                }

                Order neworder = new Order
                {
                    EmployeeID = infolist.EmployeeID,
                    VendorID   = infolist.VendorID,
                    Comment    = infolist.Comments,
                    SubTotal   = infolist.Subtotal,
                    TaxGST     = infolist.Tax
                };
                context.Orders.Add(neworder);

                foreach (var row in po)
                {
                    context.OrderDetails.Add(new OrderDetail
                    {
                        ProductID     = row.ProductID,
                        Quantity      = row.OrderQty,
                        OrderUnitSize = row.UnitSize,
                        Cost          = row.UnitCost
                    });
                }

                context.SaveChanges();
            }
        }
示例#23
0
        public int Insert_RosterView(int employeeid, int raceid, RosterView item)
        {
            using (var context = new RaceContext())
            {
                RaceDetail newitem    = new RaceDetail();
                Invoice    newinvoice = new Invoice();
                if ((from x in context.RaceDetails
                     where x.RaceID == raceid &&
                     x.Refund == false
                     select x).Count() >= (from x in context.Races
                                           where x.RaceID == raceid
                                           select x.NumberOfCars).FirstOrDefault())
                {
                    errors.Add("Race contestant limit has already been reached.");
                }
                if (item.Name == "0")
                {
                    errors.Add("Please select a driver.");
                }
                List <int> members = (from x in context.RaceDetails
                                      where x.RaceID == raceid &&
                                      x.Refund == false
                                      select x.MemberID).ToList();
                if (members.Contains(int.Parse(item.Name)))
                {
                    errors.Add("Member cannot be entered in a race twice.");
                }
                string certif = (from y in context.Races
                                 where y.RaceID == raceid
                                 select y.CertificationLevel).FirstOrDefault();
                if (item.CarID != 0 && !(from x in context.Cars
                                         where x.CarClass.CertificationLevel == certif
                                         select x.CarID).Contains((int)item.CarID))
                {
                    errors.Add("CarID must have proper certification level.");
                }

                if (errors.Count == 0)
                {
                    newitem = new RaceDetail
                    {
                        RaceID   = raceid,
                        MemberID = int.Parse(item.Name),
                        RaceFee  = (decimal)(from x in context.RaceDetails
                                             where x.RaceID == raceid &&
                                             x.RaceFee != 0
                                             select x.RaceFee).FirstOrDefault(),
                        CarID     = item.CarID == 0 ? null : item.CarID,
                        RentalFee = item.CarID == 0 ? 0 : (from x in context.CarClasses
                                                           where x.CarClassID == (from y in context.Cars
                                                                                  where y.CarID == item.CarID
                                                                                  select y.CarClassID).FirstOrDefault()
                                                           select x.RaceRentalFee).FirstOrDefault(),
                        Place        = item.Placement,
                        Refund       = false,
                        Comment      = item.Comment,
                        RefundReason = item.RefundReason
                    };
                    decimal subtotal = (from x in context.RaceDetails
                                        where x.RaceDetailID == item.RaceDetailID
                                        select x.Invoice.SubTotal).FirstOrDefault();
                    newinvoice = new Invoice
                    {
                        InvoiceDate = DateTime.Now.Date,
                        EmployeeID  = employeeid,
                        SubTotal    = subtotal,
                        GST         = subtotal * (decimal)0.05,
                        Total       = subtotal * (decimal)1.05
                    };

                    context.RaceDetails.Add(newitem);
                    context.Invoices.Add(newinvoice);

                    context.SaveChanges();
                    return(newitem.RaceDetailID);
                }
                else
                {
                    throw new BusinessRuleException("Insert Validation Error", errors);
                }
            }
        }
示例#24
0
        public int Update_RosterView(int employeeid, int raceid, RosterView item)
        {
            using (var context = new RaceContext())
            {
                RaceDetail newitem    = new RaceDetail();
                Invoice    newinvoice = new Invoice();
                if (item.CarID != 0 && !(from x in context.Cars
                                         where x.CarClass.CertificationLevel == (from y in context.RaceDetails
                                                                                 where y.RaceDetailID == item.RaceDetailID
                                                                                 select y.Race.CertificationLevel).FirstOrDefault()
                                         select x.CarID).Contains((int)item.CarID))
                {
                    errors.Add("CarID must have proper certification level.");
                }
                if (item.Refunded)
                {
                    if (string.IsNullOrEmpty(item.RefundReason))
                    {
                        errors.Add("Refunds require a refund reason.");
                    }
                    else
                    {
                        newitem = new RaceDetail
                        {
                            RaceDetailID = item.RaceDetailID,
                            RaceID       = raceid,
                            MemberID     = (from x in context.Members
                                            where x.FirstName + " " + x.LastName == item.Name
                                            select x.MemberID).FirstOrDefault(),
                            RaceFee      = 0,
                            CarID        = null,
                            RentalFee    = 0,
                            Place        = null,
                            Refund       = true,
                            Comment      = item.Comment,
                            RefundReason = item.RefundReason
                        };

                        decimal subtotal = item.RaceFee;
                        newinvoice = new Invoice
                        {
                            InvoiceDate = DateTime.Now.Date,
                            EmployeeID  = employeeid,
                            SubTotal    = subtotal,
                            GST         = subtotal * (decimal)0.05,
                            Total       = subtotal * (decimal)1.05
                        };
                        context.Invoices.Add(newinvoice);
                    }
                }
                else
                {
                    newitem = (from x in context.RaceDetails
                               where x.RaceDetailID == item.RaceDetailID
                               select x).FirstOrDefault();
                    newitem.CarID     = item.CarID == 0 ? null : item.CarID;
                    newitem.RentalFee = item.CarID == 0 ? 0 : (from x in context.CarClasses
                                                               where x.CarClassID == (from y in context.Cars
                                                                                      where y.CarID == item.CarID
                                                                                      select y.CarClassID).FirstOrDefault()
                                                               select x.RaceRentalFee).FirstOrDefault();
                    newitem.Refund       = false;
                    newitem.Comment      = item.Comment;
                    newitem.RefundReason = item.RefundReason;
                }

                if (errors.Count == 0)
                {
                    context.Entry(newitem).State = System.Data.Entity.EntityState.Modified;
                    return(context.SaveChanges());
                }
                else
                {
                    throw new BusinessRuleException("Update Validation Error", errors);
                }
            }
        }