Пример #1
0
        public CarController(CarContext context)
        {
            _context = context;

            if (_context.Car.Count() == 0)
            {
                _context.Car.Add(new Car {
                    Make = "Mazda", Model = "CX-5", Year = 2016, Color = "Red"
                });
                _context.SaveChanges();
            }
        }
Пример #2
0
        public CarController(CarContext context)
        {
            _context = context;

            if (_context.CarItems.Count() == 0)
            {
                _context.CarItems.Add(new CarItem {
                    Firstname = "John", Lastname = "Doe", Name_speak = "Johnny"
                });
                _context.SaveChanges();
            }
        }
Пример #3
0
 public void DeleteCar()
 {
     using (CarContext context = new CarContext())
     {
         context.Car.Attach(selectedCar);
         context.Car.Remove(selectedCar);
         context.SaveChanges();
     }
     selectedCar = new Car();
     Cars.Clear();
     GetAllCars();
 }
Пример #4
0
 /// <summary>
 /// Deletes the car the user has selected.
 /// </summary>
 public void DeleteCar()
 {
     using (CarContext ccx = new CarContext())
     {
         // Attaches SelectedCar to the DbSet
         ccx.Cars.Attach(SelectedCar);
         ccx.Cars.Remove(SelectedCar);
         ccx.SaveChanges();
     }
     SelectedCar = new Car();
     GetData(false);
 }
Пример #5
0
        //
        // GET: /Xml2Model/

        public ActionResult Index()
        {
            rss cars = null;
            //  System.Net.WebClient client = new WebClient();
            //  byte[] page = client.DownloadData("http://rss.nytimes.com/services/xml/rss/nyt/US.xml");
            // string path = System.Text.Encoding.UTF8.GetString(page);
            //string path = "cars.xml";

            XmlSerializer serializer = new XmlSerializer(typeof(rss));

            //HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://rss.nytimes.com/services/xml/rss/nyt/US.xml");
            //使用Cookie设置AllowAutoRedirect属性为false,是解决“尝试自动重定向的次数太多。”的核心
            // request.CookieContainer = new CookieContainer();
            // request.AllowAutoRedirect = false;
            //  WebResponse response = (WebResponse)request.GetResponse();
            //  Stream sm = response.GetResponseStream();
            //  System.IO.StreamReader streamReader = new System.IO.StreamReader(sm);
            //将流转换为字符串
            // string html = streamReader.ReadToEnd();
            // streamReader.Close();

            //  TextReader reader = new StreamReader(path);

            XmlReader reader = new XmlTextReader("http://rss.nytimes.com/services/xml/rss/nyt/US.xml");

            cars = (rss)serializer.Deserialize(reader);

            /*var serializer = new XmlSerializer(typeof(rss));
             * using (TextReader reader = new StringReader(html))
             * {
             *    cars = (rss)serializer.Deserialize(reader);
             * }*/


            //  reader.Close();


            db.sources.Add(new Models.source("NYTimes", DateTime ???));

            for (var i = 0; i < cars.item.Length; i++)
            {
                string   httpTime = cars.item[i].pubDate;
                DateTime time     = DateTime.Parse(httpTime);


                Models.item item = new Models.item(cars.item[i], time, "NYTimes");

                db.channel.Add(item);               //item include 4 elements
                //db.channel.Add(cars.item[i]);
            }
            db.SaveChanges();
            return(View(db.channel.ToList()));
        }
Пример #6
0
        public IActionResult Create([FromBody] Car item)
        {
            if (item == null)
            {
                return(BadRequest());
            }


            _context.Cars.Add(item);
            _context.SaveChanges();

            return(CreatedAtRoute("GetCar", new { id = item.CarId }, item));
        }
Пример #7
0
 public void SaveCar()
 {
     using (CarContext acx = new CarContext())
     {
         acx.Propellant.Attach(selectedCar.Propellant);
         acx.CarModel.Attach(selectedCar.CarModel);
         acx.Car.AddOrUpdate(selectedCar);
         acx.SaveChanges();
     }
     selectedCar = new Car();
     Cars.Clear();
     GetAllCars();
 }
Пример #8
0
        public async Task <IActionResult> Delete(string id)
        {
            Car car = await context.Cars.FindAsync(id);

            Order order = context.Orders.Include(c => c.Car).Where(p => p.Car.Id == id).FirstOrDefault();

            if (car != null)
            {
                if (order == null)
                {
                    context.Cars.Remove(car);
                    context.SaveChanges();
                    return(RedirectToAction("Index"));
                }
                else
                {
                    ModelState.AddModelError("", "This car is included in the order!");
                    RedirectToAction("Index");
                }
            }
            return(View("Index", context.Cars));
        }
Пример #9
0
        private void ViewAddButtonClicked(object sender, EventArgs e)
        {
            Car car = new Car {
                Model        = _view.ModelText,
                Vendor       = _view.VendorText,
                Year         = int.Parse(_view.YearText),
                Color        = _view.ColorText,
                Transmission = _view.TransmissionText
            };

            _db.Cars.Add(car);
            _db.SaveChanges();
        }
Пример #10
0
 public CarController(CarContext context)
 {
     _context = context;
     if (_context.Cars.Count() == 0)
     {
         _context.Cars.Add((new Car {
             Make = "Mazda", CarModel = "Takuya", Colour = "Aluminium"
         }));
         _context.Cars.Add(new Car {
             Make = "BMW", Colour = "Black", CarModel = "5 Series"
         });
         _context.SaveChanges();
     }
 }
        public ActionResult Create(Car car)
        {
            if (!ModelState.IsValid)
            {
                return(View(car));
            }


            _context.Cars.Add(car);
            _context.SaveChanges();


            return(RedirectToAction(nameof(Index)));
        }
Пример #12
0
 /// <summary>
 /// Saves the new car or changes to existing car in Data Base.
 /// </summary>
 /// <param name="isEdited">True if editing an existing car, otherwise false.</param>
 public void SaveCar()
 {
     using (CarContext ccx = new CarContext())
     {
         ccx.Brands.Attach(SelectedCar.Brand);
         ccx.Propellants.Attach(SelectedCar.Propellant);
         ccx.Cars.AddOrUpdate(SelectedCar);
         ccx.SaveChanges();
     }
     if (SelectedCar.CarId == 0)
     {
         SelectedCar = new Car();
     }
     GetData(false);
 }
Пример #13
0
        public ActionResult Form(string userName, string userEmail, int carId)
        {
            var order = new Order
            {
                UserName  = userName,
                UserEmail = userEmail,
                CarId     = carId,
                Status    = "Создана"
            };

            db.Orders.Add(order);
            db.SaveChanges();

            return(Content(string.Format("{0}, ваша заявка на автомобиль {1}, была принята!", userName, db.Cars.FirstOrDefault(c => c.Id == carId).Title)));
        }
Пример #14
0
        public CarController(CarContext context)
        {
            _context = context;

            if (_context.CarItems.Count() == 0)
            {
                _context.CarItems.Add(new CarItems {
                    Id = 1, CarName = "Mercedes Benz C", Color = "Blue", Company = "mercedes", Engine = "v8"
                });
                _context.CarItems.Add(new CarItems {
                    Id = 2, CarName = "Audi A3", Color = "Black", Company = "Audi", Engine = "t8"
                });
                _context.SaveChanges();
            }
        }
Пример #15
0
 public string Index(string name, string phone, int Car)
 {
     if (ModelState.IsValid)
     {
         db.Orders.Add(new Order {
             name = name, phone = phone, CarId = Car
         });
         db.SaveChanges();
         return($"Добрый день, {name}, ваш заказ принят в ближайшее время вам позвонят по указанному номеру {phone}!");
     }
     else
     {
         return($"Ошибка ввода");
     }
 }
Пример #16
0
        public static void Initialize(IServiceProvider serviceProvider)
        {
            using (var context = new CarContext(
                       serviceProvider.GetRequiredService <DbContextOptions <CarContext> >()))
            {
                if (context.CarModels.Any())
                {
                    return;
                }

                context.CarModels.AddRange(
                    new CarModel(1, "ALFA", "Giulia", 2019, Enums.TypeEnum.SEDAN, "alfa"),
                    new CarModel(2, "BMW", "M3", 2010, Enums.TypeEnum.SEDAN, "bmw"));
                context.SaveChanges();
            }
        }
Пример #17
0
        public async Task <IActionResult> DeleteOrder(string id)
        {
            Order order = await context.Orders.FindAsync(id);

            if (order != null)
            {
                context.Orders.Remove(order);
                context.SaveChanges();
                return(RedirectToAction("UserOrders"));
            }
            else
            {
                ModelState.AddModelError("", "Order not found");
                return(RedirectToAction("UserOrders"));
            }
        }
        public static string ImportCustomers(CarContext context, string xmlString)
        {
            var sb = new StringBuilder();

            var serializer            = new XmlSerializer(typeof(CustomerDto[]), new XmlRootAttribute("customers"));
            var deserializedCustomers = (CustomerDto[])serializer.Deserialize(new MemoryStream(Encoding.UTF8.GetBytes(xmlString)));

            var validCustomers = new List <Customer>();

            foreach (var obj in deserializedCustomers)
            {
                if (!IsValid(obj))
                {
                    sb.AppendLine(FailureMessage);
                    continue;
                }

                DateTime birthDate;
                try
                {
                    birthDate = DateTime.Parse(obj.BirthDate);
                }
                catch (Exception)
                {
                    sb.AppendLine(FailureMessage);
                    continue;
                }

                var customer = new Customer
                {
                    Name          = obj.Name,
                    BirthDate     = birthDate,
                    IsYoungDriver = obj.IsYoungDriver
                };

                validCustomers.Add(customer);
                sb.AppendLine(String.Format(SuccessCustomerMessage, obj.Name));
            }


            context.AddRange(validCustomers);
            context.SaveChanges();

            return(sb.ToString().Trim());
        }
Пример #19
0
        static void Main(string[] args)
        {
            using (CarContext db = new CarContext())
            {
                Car c = new Car();
                c.Targa   = "abc";
                c.Modello = "Jeep Renegade";

                Person p = new Person();
                p.FirstName = "Antonio";
                p.LastName  = "Pelleriti";
                c.Person    = p;

                db.Cars.Add(c);
                db.People.Add(p);
                db.SaveChanges();
            }
        }
Пример #20
0
        public IActionResult AddNewBrand(string submit, string cancel, Brand brand)
        {
            var button = submit ?? cancel;

            if (button == "Cancel")
            {
                return(RedirectToAction("AddNewBrand"));
            }

            if (DataBase.Brands.Any(x => ((x.Name == brand.Name) || (x.Name == "Enter"))))
            {
                return(BadRequest());
            }

            DataBase.Brands.Add(brand);
            DataBase.SaveChanges();
            return(RedirectToAction("Index"));
        }
Пример #21
0
        public IActionResult AddNewCar(string submit, string cancel, Car car)
        {
            var button = submit ?? cancel;

            if (button == "Cancel")
            {
                return(RedirectToAction("AddNewCar"));
            }

            if (DataBase.Cars.Any(x => x.Name == car.Name))
            {
                return(BadRequest());
            }

            DataBase.Cars.Add(car);
            DataBase.SaveChanges();
            return(Redirect("~/Home/Index"));
        }
Пример #22
0
        public static void Initialize(TestContext tc)
        {
            //Initialize our context
            var options = new DbContextOptionsBuilder <CarContext>().UseInMemoryDatabase(databaseName: "DealershipTestDB").Options;

            dealershipContext = new CarContext(options);


            //Add records to context and save
            Dealership dealership1 = new Dealership {
                ID = 1, Name = "Toyota Dealership", Email = "*****@*****.**", PhoneNumber = "9057899456"
            };
            Dealership dealership2 = new Dealership {
                ID = 2, Name = "Honda Dealership", Email = "*****@*****.**", PhoneNumber = "1234567891"
            };

            dealershipContext.Dealership.AddRange(dealership1, dealership2);
            dealershipContext.SaveChanges();
        }
Пример #23
0
        private void YesBt_Click(object sender, RoutedEventArgs e)
        {
            using (TripContext db = new TripContext())
            {
                Trip trip = db.Trips.Where(t => t.Id == id).FirstOrDefault();

                if (trip != null)
                {
                    if (b)
                    {
                        trip.State = "Завершена";
                    }
                    else
                    {
                        trip.State = "Отменена";
                    }
                }
                db.SaveChanges();

                using (UserContext udb = new UserContext())
                {
                    User user = udb.Users.Where(u => u.Name == trip.Name).FirstOrDefault();
                    if (user != null)
                    {
                        user.state = "Свободен";
                    }
                    udb.SaveChanges();
                }

                using (CarContext cdb = new CarContext())
                {
                    Car car = cdb.Cars.Where(c => c.CarName == trip.CarName).FirstOrDefault();
                    if (car != null)
                    {
                        car.State = "Свободна";
                    }
                    cdb.SaveChanges();
                }
            }
            em.UpdateTripsList();
            this.Close();
        }
Пример #24
0
        static void Main(string[] args)
        {
            using (CarContext db = new CarContext())
            {
                //db.Database.Connection.ConnectionString = @"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=EFCodeFirst.CarContext;Integrated Security=True;MultipleActiveResultSets=True";
                Car c = new Car();
                c.Targa   = "abc";
                c.Modello = "Alfa Romeo GT";

                Person p = new Person();
                p.FirstName = "Antonio";
                p.LastName  = "Pelleriti";
                c.Person    = p;

                db.Cars.Add(c);
                db.People.Add(p);

                db.SaveChanges();
            }
        }
        public static string ImportParts(CarContext context, string xmlString)
        {
            var sb = new StringBuilder();

            var serializer        = new XmlSerializer(typeof(PartDto[]), new XmlRootAttribute("parts"));
            var deserializedParts = (PartDto[])serializer.Deserialize(new MemoryStream(Encoding.UTF8.GetBytes(xmlString)));

            var suppliers = context.Suppliers.ToArray();
            var rnd       = new Random();

            var validParts = new List <Part>();

            foreach (var obj in deserializedParts)
            {
                if (!IsValid(obj))
                {
                    sb.AppendLine(FailureMessage);
                    continue;
                }

                int index = rnd.Next(0, suppliers.Length - 1);

                var part = new Part()
                {
                    Name     = obj.Name,
                    Price    = obj.Price,
                    Quantity = obj.Quantity,
                    Supplier = suppliers[index]
                };

                validParts.Add(part);

                sb.AppendLine(String.Format(SuccessCustomerMessage, part.Name));
            }

            context.AddRange(validParts);
            context.SaveChanges();

            return(sb.ToString().Trim());
        }
        public static void ImportSales(CarContext context)
        {
            var discounts = new decimal[]
            {
                0m,
                0.5m,
                0.10m,
                0.15m,
                0.20m,
                0.30m,
                0.40m,
                0.50m
            };

            var rnd = new Random();

            var cars       = context.Cars.ToArray();
            var customers  = context.Customers.ToArray();
            var validSales = new List <Sale>();

            foreach (var customer in customers)
            {
                var index         = rnd.Next(0, cars.Length - 1);
                var discountIndex = rnd.Next(0, discounts.Length - 1);

                var sale = new Sale
                {
                    Customer = customer,
                    Discount = discounts[discountIndex],
                    Car      = cars[index]
                };

                validSales.Add(sale);
            }



            context.AddRange(validSales);
            context.SaveChanges();
        }
Пример #27
0
        public static void Fill()
        {
            using (var p = new PersonContext()) {
                p.Persons.Add(new Person { City="Basel", Name="David" });
                p.Persons.Add(new Person { City="Basel", Name="Bettina" });
                p.Persons.Add(new Person { City="Basel", Name="Sergio" });
                p.Persons.Add(new Person { City="Thun", Name="Kim" });
                p.SaveChanges();
            }

            Services.Providers.Message("Persons Filled.");

            using (var c = new CarContext()) {
                c.Cars.Add(new Car { Model = "Audi" });
                c.Cars.Add(new Car { Model = "BMW" });
                c.Cars.Add(new Car { Model = "Mercedes" });
                c.Cars.Add(new Car { Model = "Fiat" });
                c.SaveChanges();
            }

            Services.Providers.Message("Cars filled.");
        }
Пример #28
0
        public IActionResult AssignManagerToRequest(int?requestId, string managerId)
        {
            if (requestId == null)
            {
                return(NotFound());
            }

            var request = _context.PurchaseRequests.FirstOrDefault(pr => pr.Id == requestId);

            if (request == null)
            {
                return(NotFound());
            }

            request.ManagerId = string.IsNullOrEmpty(managerId) ? _userManager.GetUserId(User) : managerId;

            request.State = PurchaseRequest.RequestState.Processing;
            _context.Update(request);
            _context.SaveChanges();

            return(Content(_userManager.Users.First(u => u.Id == request.ManagerId).UserName));
        }
        public static string ImportParts(CarContext context, string jsonString)
        {
            var sb = new StringBuilder();

            var deserialisedParts = JsonConvert.DeserializeObject <PartDto[]>(jsonString);

            var validParts = new List <Part>();
            var rnd        = new Random();

            var suppliers = context.Suppliers.ToArray();

            foreach (var obj in deserialisedParts)
            {
                if (!IsValid(obj))
                {
                    sb.AppendLine(FailureMessage);
                    continue;
                }

                int index = rnd.Next(0, suppliers.Length - 1);

                var part = new Part
                {
                    Name     = obj.Name,
                    Price    = obj.Price,
                    Quantity = obj.Quantity,
                    Supplier = suppliers[index]
                };

                validParts.Add(part);

                sb.AppendLine(String.Format(SuccessMessage, "part", obj.Name));
            }

            context.AddRange(validParts);
            context.SaveChanges();

            return(sb.ToString());
        }
Пример #30
0
 private void InitDb()
 {
     _context.Cars.Add(new Car
     {
         Name       = "Giulia",
         Year       = 2015,
         ProducerId = _context.Producers.First(n => n.Name == "Alfa Romeo").Id
     });
     _context.Cars.Add(new Car
     {
         Name       = "Stelvio",
         Year       = 2017,
         ProducerId = _context.Producers.First(n => n.Name == "Alfa Romeo").Id
     });
     _context.Cars.Add(new Car
     {
         Name       = "GT",
         Year       = 2007,
         ProducerId = _context.Producers.First(n => n.Name == "Alfa Romeo").Id
     });
     _context.SaveChanges();
 }
        public static void ImportCarParts(CarContext context)
        {
            var carParts = new List <PartCar>();

            var cars  = context.Cars.ToArray();
            var parts = context.Parts.ToArray();

            var rnd = new Random();

            foreach (var car in cars)
            {
                int[] indexes = new int[10];

                for (int i = 0; i < 10; i++)
                {
                    while (true)
                    {
                        int index = rnd.Next(0, parts.Length - 1);
                        if (!indexes.Contains(index))
                        {
                            var carPart = new PartCar
                            {
                                Car  = car,
                                Part = parts[index]
                            };

                            indexes[i] = index;
                            carParts.Add(carPart);

                            break;
                        }
                    }
                }
            }

            context.AddRange(carParts);
            context.SaveChanges();
        }