public async Task <IActionResult> EditItem(int?id, Announcement announcement)
        {
            //Announcement announcementFromDb = _context.Announcements.Include(announce => announce.Automobile)
            //                                                        .ThenInclude(announce => announce.Model)
            //                                                        .ThenInclude(announce => announce.Brand)
            //                                                        .Include(announce => announce.Location)
            //                                                        .Include(announce => announce.Automobile)
            //                                                        .ThenInclude(announce => announce.Color)
            //                                                        .Include(announce => announce.Automobile)
            //                                                        .ThenInclude(announce => announce.Fuel)
            //                                                        .Include(announce => announce.Automobile)
            //                                                        .ThenInclude(announce => announce.SpeedControl)
            //                                                        .FirstOrDefault(announce => announce.Id == id);

            Announcement announcementFromDb = _context.Announcements.FirstOrDefault(announce => announce.Id == id);

            if (announcementFromDb == null)
            {
                ViewBag.Brands        = _context.Brands;
                ViewBag.Models        = _context.Models;
                ViewBag.Colors        = _context.Colors;
                ViewBag.Locations     = _context.Locations;
                ViewBag.Fuels         = _context.Fuels;
                ViewBag.SpeedControls = _context.SpeedControls;
                return(NotFound());
            }

            if (!ModelState.IsValid)
            {
                ViewBag.Brands        = _context.Brands;
                ViewBag.Models        = _context.Models;
                ViewBag.Colors        = _context.Colors;
                ViewBag.Locations     = _context.Locations;
                ViewBag.Fuels         = _context.Fuels;
                ViewBag.SpeedControls = _context.SpeedControls;
                return(View(announcement));
            }

            if (announcement.Automobile.Photo != null)
            {
                if (announcement.Automobile.Photo.ContentType.Contains("image/"))
                {
                    string folderPath = Path.Combine(_env.WebRootPath, "img");
                    string fileName   = Guid.NewGuid().ToString() + "_" + announcement.Automobile.Photo.FileName;
                    string filePath   = Path.Combine(folderPath, fileName);

                    using (FileStream fileStream = new FileStream(filePath, FileMode.Create))
                    {
                        await announcement.Automobile.Photo.CopyToAsync(fileStream);
                    }

                    string currentFilePath = Path.Combine(_env.WebRootPath, "img", announcementFromDb.Automobile.MainPhotoURL);
                    if (System.IO.File.Exists(currentFilePath))
                    {
                        System.IO.File.Delete(currentFilePath);
                    }

                    announcementFromDb.Automobile.MainPhotoURL = fileName;
                    await _context.SaveChangesAsync();
                }
            }

            announcementFromDb.Automobile.Price          = announcement.Automobile.Price;
            announcementFromDb.Automobile.ModelId        = announcement.Automobile.ModelId;
            announcementFromDb.Automobile.Year           = announcement.Automobile.Year;
            announcementFromDb.Automobile.Motor          = announcement.Automobile.Motor;
            announcementFromDb.Automobile.Distance       = announcement.Automobile.Distance;
            announcementFromDb.Automobile.ColorId        = announcement.Automobile.ColorId;
            announcementFromDb.Automobile.FuelId         = announcement.Automobile.FuelId;
            announcementFromDb.Automobile.SpeedControlId = announcement.Automobile.SpeedControlId;
            announcementFromDb.Automobile.ShortInfo      = announcement.Automobile.ShortInfo;
            await _context.SaveChangesAsync();


            if (announcement.Photos != null && announcement.Photos.Count() > 0)
            {
                foreach (IFormFile photo in announcement.Photos)
                {
                    if (photo.ContentType.Contains("image/"))
                    {
                        string folderPath = Path.Combine(_env.WebRootPath, "img");
                        string fileName   = Guid.NewGuid().ToString() + "_" + photo.FileName;
                        string filePath   = Path.Combine(folderPath, fileName);

                        using (FileStream fileStream = new FileStream(filePath, FileMode.Create))
                        {
                            await photo.CopyToAsync(fileStream);
                        }

                        //foreach (var autoPhoto in announcementFromDb.Automobile.AutoPhotos)
                        //{
                        //    string currentFilePath = Path.Combine(_env.WebRootPath, "img", autoPhoto.PhotoURL);
                        //    if (System.IO.File.Exists(currentFilePath))
                        //    {
                        //        System.IO.File.Delete(currentFilePath);
                        //    }

                        //    autoPhoto.PhotoURL = fileName;
                        //    await _context.SaveChangesAsync();
                        //}

                        AutoPhoto autoPhoto = new AutoPhoto
                        {
                            PhotoURL     = fileName,
                            AutomobileId = announcementFromDb.Automobile.Id
                        };

                        await _context.AutoPhotos.AddAsync(autoPhoto);

                        await _context.SaveChangesAsync();
                    }
                }
            }


            announcementFromDb.UpdateDate = DateTime.Now;
            announcementFromDb.LocationId = announcement.LocationId;
            announcementFromDb.IsVIP      = announcement.IsVIP;
            await _context.SaveChangesAsync();

            TempData["Announcement updated"] = true;

            ViewBag.Brands        = _context.Brands;
            ViewBag.Models        = _context.Models;
            ViewBag.Colors        = _context.Colors;
            ViewBag.Locations     = _context.Locations;
            ViewBag.Fuels         = _context.Fuels;
            ViewBag.SpeedControls = _context.SpeedControls;

            return(RedirectToAction("Index", "Home"));
        }
Exemple #2
0
        private string BuildPostData(Auto auto, List <Tuple <string, string, string> > additionalFields = null)
        {
            string elasticSearchDateFormat = $"{XCarsConfiguration.ElasticSearchDateFormat}";
            string fullInfo = "";

            string postData = @"{
            ""AutoID"": " + auto.ID + @"
            ,""UserID"": " + auto.UserID + @"
            ,""DateCreated"": """ + auto.DateCreated.ToString(elasticSearchDateFormat) + @"""
            ,""DateUpdated"": """ + auto.DateUpdated.ToString(elasticSearchDateFormat) + @"""";

            if (auto.DateExpires != null)
            {
                postData += @",""DateExpires"": """ + auto.DateExpires.Value.ToString(elasticSearchDateFormat) + @"""";
            }

            if (auto.DateAppearance != null)
            {
                postData += @",""DateAppearance"": """ + auto.DateAppearance.Value.ToString(elasticSearchDateFormat) + @"""";
            }

            //string photoUrl = XCarsConfiguration.AutoNoPhotoUrl;
            //AutoPhoto photo = auto.AutoPhotoes.FirstOrDefault(p => p.IsMain);
            //if (photo != null)
            //    photoUrl = photo.Url;
            //postData += @",""AutoPhotoUrl"": """ + photoUrl + @"""";

            int       mainPhotoID = 0;
            AutoPhoto photo       = auto.AutoPhotoes.FirstOrDefault(p => p.IsMain);

            if (photo != null)
            {
                mainPhotoID = photo.ID;
            }
            postData += @",""MainPhotoID"": " + mainPhotoID + @"";

            string name = AutoStatusService.GetByID(auto.StatusID).Name;

            postData += @"
            ,""Status"": {
                ""ID"": " + auto.StatusID + @",
                ""Name"": """ + name + @"""
            }";

            City city = CityService.GetByID(auto.RegionID);

            if (city != null)
            {
                name      = city.Region.Name;
                fullInfo += name + " ";
                postData += @",""AutoRegion"": {
                    ""ID"": " + auto.RegionID + @",
                    ""Name"": """ + name + @"""
                }";

                name      = city.Name;
                fullInfo += name + " ";
                postData += @",""AutoCity"": {
                    ""ID"": " + auto.RegionID + @",
                    ""Name"": """ + name + @"""
                }";
            }

            name      = AutoTransportTypeService.GetByID(auto.TransportTypeID).Name;
            fullInfo += name + " ";
            postData += @"
            ,""AutoTransportType"": {
                ""ID"": " + auto.TransportTypeID + @",
                ""Name"": """ + name + @"""
            }";

            name      = AutoBodyTypeService.GetByID(auto.BodyTypeID).Name;
            fullInfo += name + " ";
            postData += @"
            ,""AutoBodyType"": {
                ""ID"": " + auto.BodyTypeID + @",
                ""Name"": """ + name + @"""
            }";

            name      = AutoMakeService.GetByID(auto.MakeID).Name;
            fullInfo += name + " ";
            postData += @"
            ,""AutoMake"": {
                ""ID"": " + auto.MakeID + @",
                ""Name"": """ + name + @"""
            }";

            name      = AutoModelService.GetByID(auto.ModelID).Name;
            fullInfo += name + " ";
            postData += @"
            ,""AutoModel"": {
                ""ID"": " + auto.ModelID + @",
                ""Name"": """ + name + @"""
            }";

            name      = AutoTSRegistrationService.GetByID(auto.TSRegistrationID).NameFull;
            fullInfo += name + " ";
            postData += @"
            ,""AutoTSRegistration"": {
                ""ID"": " + auto.TSRegistrationID + @",
                ""Name"": """ + name + @"""
            }";

            postData += @",""YearOfIssue"": " + auto.YearOfIssue + @"";

            if (!string.IsNullOrWhiteSpace(auto.Modification))
            {
                postData += @",""Modification"": """ + auto.Modification + @"""";
                fullInfo += auto.Modification + " ";
            }

            postData += @",""Probeg"": " + auto.Probeg + @"";

            //if (auto.PriceUSD != null)
            postData += @",""PriceUSD"": " + ((auto.PriceUSD != null) ? auto.PriceUSD : 0) + @"";
            //if (auto.PriceUAH != null)
            postData += @",""PriceUAH"": " + ((auto.PriceUAH != null) ? auto.PriceUAH : 0) + @"";

            postData += @",""PriceUSDSearch"": " + auto.PriceUSDSearch + @"";
            postData += @",""PriceUAHSearch"": " + auto.PriceUAHSearch + @"";

            string boolValue = "false";

            if (auto.IsExchangeAvailable)
            {
                boolValue = "true";
            }
            postData += @",""IsExchangeAvailable"": " + boolValue;

            boolValue = "false";
            if (auto.IsTorgAvailable)
            {
                boolValue = "true";
            }
            postData += @",""IsTorgAvailable"": " + boolValue;

            if (auto.TransmissionTypeID != null)
            {
                name      = AutoTransmissionTypeService.GetByID((int)auto.TransmissionTypeID).Name;
                fullInfo += name + " ";
                postData += @"
                    ,""AutoTransmissionType"": {
                        ""ID"": " + auto.TransmissionTypeID + @",
                        ""Name"": """ + name + @"""
                    }";
            }

            if (auto.DriveTypeID != null)
            {
                name      = AutoDriveTypeService.GetByID((int)auto.DriveTypeID).Name;
                fullInfo += name + " ";
                postData += @"
                    ,""AutoDriveType"": {
                        ""ID"": " + auto.DriveTypeID + @",
                        ""Name"": """ + name + @"""
                    }";
            }

            if (auto.NumberOfDoors != null)
            {
                postData += @",""NumberOfDoors"": " + auto.NumberOfDoors + @"";
            }

            if (auto.NumberOfSeats != null)
            {
                postData += @",""NumberOfSeats"": " + auto.NumberOfSeats + @"";
            }

            if (auto.ColorID != null)
            {
                name      = AutoColorService.GetByID((int)auto.ColorID).Name;
                fullInfo += name + " ";
                postData += @"
                    ,""AutoColor"": {
                        ""ID"": " + auto.ColorID + @",
                        ""Name"": """ + name + @"""
                    }";
            }

            boolValue = "false";
            if (auto.IsColorMetallic)
            {
                boolValue = "true";
            }
            postData += @",""IsColorMetallic"": " + boolValue;

            if (auto.FuelTypeID != null)
            {
                name      = AutoFuelTypeService.GetByID((int)auto.FuelTypeID).Name;
                fullInfo += name + " ";
                postData += @"
                    ,""AutoFuelType"": {
                        ""ID"": " + auto.FuelTypeID + @",
                        ""Name"": """ + name + @"""
                    }";
            }

            if (auto.FuelConsumptionCity != null)
            {
                string tmpDoubleVar = auto.FuelConsumptionCity.ToString();
                tmpDoubleVar = tmpDoubleVar.Replace(',', '.');
                postData    += @",""FuelConsumptionCity"": " + tmpDoubleVar + @"";
            }


            if (auto.FuelConsumptionHighway != null)
            {
                string tmpDoubleVar = auto.FuelConsumptionHighway.ToString();
                tmpDoubleVar = tmpDoubleVar.Replace(',', '.');
                postData    += @",""FuelConsumptionHighway"": " + tmpDoubleVar + @"";
            }

            if (auto.FuelConsumptionMixed != null)
            {
                string tmpDoubleVar = auto.FuelConsumptionMixed.ToString();
                tmpDoubleVar = tmpDoubleVar.Replace(',', '.');
                postData    += @",""FuelConsumptionMixed"": " + tmpDoubleVar + @"";
            }

            if (auto.EngineCapacity != null)
            {
                string tmpDoubleVar = auto.EngineCapacity.ToString();
                tmpDoubleVar = tmpDoubleVar.Replace(',', '.');
                postData    += @",""EngineCapacity"": " + tmpDoubleVar + @"";
            }

            if (auto.Power != null)
            {
                postData += @",""Power"": " + auto.Power + @"";
            }


            if (!string.IsNullOrWhiteSpace(auto.Description))
            {
                fullInfo += auto.Description + " ";
                postData += @",""Description"": """ + auto.Description + @"""";
            }


            postData += @",""Views"": " + auto.Views + @"";

            if (auto.AutoSecurities != null && auto.AutoSecurities.Count > 0)
            {
                postData += @", ""AutoSecurities"": [";
                int i = 0;
                foreach (var item in auto.AutoSecurities)
                {
                    if (i > 0)
                    {
                        postData += ",";
                    }
                    //postData += @"{""ID"": " + item.ID + @", ""Name"": """ + item.Name + @"""}";
                    postData += item.ID;
                    i++;
                }
                postData += @"]";
            }

            if (auto.AutoComforts != null && auto.AutoComforts.Count > 0)
            {
                postData += @", ""AutoComforts"": [";
                int i = 0;
                foreach (var item in auto.AutoComforts)
                {
                    if (i > 0)
                    {
                        postData += ",";
                    }
                    //postData += @"{""ID"": " + item.ID + @", ""Name"": """ + item.Name + @"""}";
                    postData += item.ID;
                    i++;
                }
                postData += @"]";
            }

            if (auto.AutoMultimedias != null && auto.AutoMultimedias.Count > 0)
            {
                postData += @", ""AutoMultimedias"": [";
                int i = 0;
                foreach (var item in auto.AutoMultimedias)
                {
                    if (i > 0)
                    {
                        postData += ",";
                    }
                    //postData += @"{""ID"": " + item.ID + @", ""Name"": """ + item.Name + @"""}";
                    postData += item.ID;
                    i++;
                }
                postData += @"]";
            }

            if (auto.AutoStates != null && auto.AutoStates.Count > 0)
            {
                postData += @", ""AutoStates"": [";
                int i = 0;
                foreach (var item in auto.AutoStates)
                {
                    if (i > 0)
                    {
                        postData += ",";
                    }
                    //postData += @"{""ID"": " + item.ID + @", ""Name"": """ + item.Name + @"""}";
                    postData += item.ID;
                    i++;
                }
                postData += @"]";
            }

            if (auto.AutoMiscs != null && auto.AutoMiscs.Count > 0)
            {
                postData += @", ""AutoMiscs"": [";
                int i = 0;
                foreach (var item in auto.AutoMiscs)
                {
                    if (i > 0)
                    {
                        postData += ",";
                    }
                    //postData += @"{""ID"": " + item.ID + @", ""Name"": """ + item.Name + @"""}";
                    postData += item.ID;
                    i++;
                }
                postData += @"]";
            }

            postData += @",""Top"": " + auto.Top;

            postData += @",""FullInfo"": """ + fullInfo + @"""";

            if (additionalFields != null)
            {
                string quot = "";
                foreach (var item in additionalFields)
                {
                    quot = @"""";
                    if (item.Item3 == "int" || item.Item3 == "bool")
                    {
                        quot = @"";
                    }
                    postData += @",""" + item.Item1 + @""" : " + quot + @"" + item.Item2 + quot;
                }
            }

            postData += @"
            }";

            return(postData);
        }
        public async Task <IActionResult> Create(AnnouncementVM announcementVM)
        {
            if (!ModelState.IsValid)
            {
                ViewBag.Brands        = _context.Brands;
                ViewBag.Models        = _context.Models;
                ViewBag.Colors        = _context.Colors;
                ViewBag.Locations     = _context.Locations;
                ViewBag.Fuels         = _context.Fuels;
                ViewBag.SpeedControls = _context.SpeedControls;
                return(View(announcementVM));
            }

            if (announcementVM.Photo == null)
            {
                ViewBag.Brands        = _context.Brands;
                ViewBag.Models        = _context.Models;
                ViewBag.Colors        = _context.Colors;
                ViewBag.Locations     = _context.Locations;
                ViewBag.Fuels         = _context.Fuels;
                ViewBag.SpeedControls = _context.SpeedControls;
                ModelState.AddModelError("Photo", "Zəhmət olmasa, şəkil yükləyin");
                return(View(announcementVM));
            }

            if (announcementVM.Photo.ContentType.Contains("image/"))
            {
                string folderPath = Path.Combine(_env.WebRootPath, "img");
                string fileName   = Guid.NewGuid().ToString() + "_" + announcementVM.Photo.FileName;
                string filePath   = Path.Combine(folderPath, fileName);

                using (FileStream fileStream = new FileStream(filePath, FileMode.Create))
                {
                    await announcementVM.Photo.CopyToAsync(fileStream);
                }

                automobile = new Automobile
                {
                    MainPhotoURL   = fileName,
                    Price          = announcementVM.Price,
                    ModelId        = announcementVM.ModelId,
                    Year           = announcementVM.Year,
                    Motor          = announcementVM.Motor,
                    Distance       = announcementVM.Distance,
                    ColorId        = announcementVM.ColorId,
                    FuelId         = announcementVM.FuelId,
                    SpeedControlId = announcementVM.SpeedControlId,
                    ShortInfo      = announcementVM.ShortInfo
                };

                await _context.Automobiles.AddAsync(automobile);

                await _context.SaveChangesAsync();
            }


            if (announcementVM.Photos != null && announcementVM.Photos.Count() > 0)
            {
                foreach (IFormFile photo in announcementVM.Photos)
                {
                    if (photo.ContentType.Contains("image/"))
                    {
                        string folderPath = Path.Combine(_env.WebRootPath, "img");
                        string fileName   = Guid.NewGuid().ToString() + "_" + photo.FileName;
                        string filePath   = Path.Combine(folderPath, fileName);

                        using (FileStream fileStream = new FileStream(filePath, FileMode.Create))
                        {
                            await photo.CopyToAsync(fileStream);
                        }

                        AutoPhoto autoPhoto = new AutoPhoto
                        {
                            PhotoURL     = fileName,
                            AutomobileId = automobile.Id
                        };

                        await _context.AutoPhotos.AddAsync(autoPhoto);

                        await _context.SaveChangesAsync();
                    }
                }
            }



            CustomUser customUserFromDb = await _userManager.FindByNameAsync(User.Identity.Name);

            Announcement announcement = new Announcement
            {
                AutomobileId = automobile.Id,
                PublishDate  = DateTime.Now,
                LocationId   = announcementVM.LocationId,
                CustomUserId = customUserFromDb.Id,
                IsVIP        = announcementVM.IsVIP
            };

            await _context.Announcements.AddAsync(announcement);

            await _context.SaveChangesAsync();

            TempData["Announcement created"] = true;

            ViewBag.Brands        = _context.Brands;
            ViewBag.Models        = _context.Models;
            ViewBag.Colors        = _context.Colors;
            ViewBag.Locations     = _context.Locations;
            ViewBag.Fuels         = _context.Fuels;
            ViewBag.SpeedControls = _context.SpeedControls;

            return(RedirectToAction("Index", "Home"));
        }