public async Task <ActionResult> ListingUpdate(Listing listing, FormCollection form, IEnumerable <HttpPostedFileBase> files)
        {
            if (CacheHelper.Categories.Count == 0)
            {
                TempData[TempDataKeys.UserMessageAlertState] = "bg-danger";
                TempData[TempDataKeys.UserMessage]           = "[[[There are not categories available yet.]]]";

                return(RedirectToAction("Listing", new { id = listing.ID }));
            }

            bool updateCount = false;

            int nextPictureOrderId = 0;

            // Add new listing
            if (listing.ID == 0)
            {
                listing.ObjectState = Repository.Pattern.Infrastructure.ObjectState.Added;
                listing.IP          = Request.GetVisitorIP();
                listing.Expiration  = DateTime.MaxValue.AddDays(-1);
                listing.UserID      = User.Identity.GetUserId();

                updateCount = true;
                _listingService.Insert(listing);
            }
            else
            {
                // Update listing
                var listingExisting = await _listingService.FindAsync(listing.ID);

                listingExisting.Title       = listing.Title;
                listingExisting.Description = listing.Description;
                listingExisting.CategoryID  = listing.CategoryID;

                listingExisting.Enabled = listing.Enabled;
                listingExisting.Active  = listing.Active;
                listingExisting.Premium = listing.Premium;

                listingExisting.ContactEmail = listing.ContactEmail;
                listingExisting.ContactName  = listing.ContactName;
                listingExisting.ContactPhone = listing.ContactPhone;

                listingExisting.Latitude  = listing.Latitude;
                listingExisting.Longitude = listing.Longitude;
                listingExisting.Location  = listing.Location;

                listingExisting.ShowPhone = listing.ShowPhone;
                listingExisting.ShowEmail = listing.ShowEmail;

                listingExisting.UserID = listing.UserID;

                listingExisting.Price    = listing.Price;
                listingExisting.Currency = listing.Currency;

                listingExisting.ListingTypeID = listing.ListingTypeID;

                listingExisting.ObjectState = Repository.Pattern.Infrastructure.ObjectState.Modified;

                _listingService.Update(listingExisting);
            }

            // Delete existing fields on item
            var customFieldItemQuery = await _customFieldListingService.Query(x => x.ListingID == listing.ID).SelectAsync();

            var customFieldIds = customFieldItemQuery.Select(x => x.ID).ToList();

            foreach (var customFieldId in customFieldIds)
            {
                await _customFieldListingService.DeleteAsync(customFieldId);
            }

            // Get custom fields
            var customFieldCategoryQuery = await _customFieldCategoryService.Query(x => x.CategoryID == listing.CategoryID).Include(x => x.MetaField.ListingMetas).SelectAsync();

            var customFieldCategories = customFieldCategoryQuery.ToList();

            // Update custom fields
            foreach (var metaCategory in customFieldCategories)
            {
                var field       = metaCategory.MetaField;
                var controlType = (Dashoor.Model.Enum.Enum_MetaFieldControlType)field.ControlTypeID;

                string controlId = string.Format("customfield_{0}_{1}_{2}", metaCategory.ID, metaCategory.CategoryID, metaCategory.FieldID);

                var formValue = form[controlId];

                if (string.IsNullOrEmpty(formValue))
                {
                    continue;
                }

                formValue = formValue.ToString();

                var itemMeta = new ListingMeta()
                {
                    ListingID   = listing.ID,
                    Value       = formValue,
                    FieldID     = field.ID,
                    ObjectState = Repository.Pattern.Infrastructure.ObjectState.Added
                };

                _customFieldListingService.Insert(itemMeta);
            }

            await _unitOfWorkAsync.SaveChangesAsync();

            // Update photos
            if (Request.Files.Count > 0)
            {
                var itemPictureQuery = _listingPictureservice.Queryable().Where(x => x.ListingID == listing.ID);
                if (itemPictureQuery.Count() > 0)
                {
                    nextPictureOrderId = itemPictureQuery.Max(x => x.Ordering);
                }
            }

            if (files != null && files.Count() > 0)
            {
                foreach (HttpPostedFileBase file in files)
                {
                    if ((file != null) && (file.ContentLength > 0) && !string.IsNullOrEmpty(file.FileName))
                    {
                        // Picture picture and get id
                        var picture = new Picture();
                        picture.MimeType = "image/jpeg";
                        _pictureService.Insert(picture);
                        await _unitOfWorkAsync.SaveChangesAsync();

                        // Format is automatically detected though can be changed.
                        ISupportedImageFormat format = new JpegFormat {
                            Quality = 90
                        };
                        Size size = new Size(500, 0);

                        //https://naimhamadi.wordpress.com/2014/06/25/processing-images-in-c-easily-using-imageprocessor/
                        // Initialize the ImageFactory using the overload to preserve EXIF metadata.
                        using (ImageFactory imageFactory = new ImageFactory(preserveExifData: true))
                        {
                            var path = Path.Combine(Server.MapPath("~/images/listing"), string.Format("{0}.{1}", picture.ID.ToString("00000000"), "jpg"));

                            // Load, resize, set the format and quality and save an image.
                            imageFactory.Load(file.InputStream)
                            .Resize(size)
                            .Format(format)
                            .Save(path);
                        }

                        var itemPicture = new ListingPicture();
                        itemPicture.ListingID = listing.ID;
                        itemPicture.PictureID = picture.ID;
                        itemPicture.Ordering  = nextPictureOrderId;

                        _listingPictureservice.Insert(itemPicture);

                        nextPictureOrderId++;
                    }
                }
            }

            await _unitOfWorkAsync.SaveChangesAsync();

            // Update statistics count
            if (updateCount)
            {
                _sqlDbService.UpdateCategoryItemCount(listing.CategoryID);
                _dataCacheService.RemoveCachedItem(CacheKeys.Statistics);
            }

            return(RedirectToAction("Listings"));
        }
        public async Task <ActionResult> ListingUpdate(Listing listing, FormCollection form, IEnumerable <HttpPostedFileBase> files, int[] idcama, int[] cantidad)
        {
            if (CacheHelper.Categories.Count == 0)
            {
                TempData[TempDataKeys.UserMessageAlertState] = "bg-danger";
                TempData[TempDataKeys.UserMessage]           = "[[[There are not categories available yet.]]]";

                return(RedirectToAction("Listing", new { id = listing.ID }));
            }
            int  actualiza          = 0;
            bool updateCount        = false;
            int  nextPictureOrderId = 0;

            var user = await _aspNetUserService.FindAsync(listing.UserID);

            // Add new listing
            if (listing.ID == 0)
            {
                listing.ObjectState   = Repository.Pattern.Infrastructure.ObjectState.Added;
                listing.IP            = Request.GetVisitorIP();
                listing.ListingTypeID = 1;
                listing.Title         = "";
                listing.Expiration    = DateTime.MaxValue.AddDays(-1);
                listing.ContactName   = user.FullName;
                listing.ContactEmail  = user.Email;
                listing.ShowPhone     = false;
                listing.ShowEmail     = false;
                listing.UserID        = user.Id;
                updateCount           = true;

                if (listing.Children == false)
                {
                    listing.Children = true;
                }
                else
                {
                    listing.Children = false;
                }

                _listingService.Insert(listing);
                listing.Currency = "CLP";
            }
            else
            {
                // Update listing
                var listingExisting = await _listingService.FindAsync(listing.ID);

                listingExisting.Title       = listing.ID.ToString();
                listingExisting.Description = listing.Description;
                listingExisting.CategoryID  = listing.CategoryID;

                listingExisting.Enabled = listing.Enabled;
                listingExisting.Active  = listing.Active;
                listingExisting.Premium = listing.Premium;

                var propietario = UserManager.FindById(listing.UserID);
                listingExisting.ContactEmail = propietario.Email;
                listingExisting.ContactName  = propietario.FullName;
                listingExisting.ContactPhone = propietario.PhoneNumber;

                listingExisting.Latitude  = listing.Latitude;
                listingExisting.Longitude = listing.Longitude;
                listingExisting.Location  = listing.Location;

                listingExisting.ShowPhone = listing.ShowPhone;
                listingExisting.ShowEmail = listing.ShowEmail;

                listingExisting.Beds  = listing.Beds;
                listingExisting.Rooms = listing.Rooms;

                if (listing.Children == false)
                {
                    listingExisting.Children = true;
                }
                else
                {
                    listingExisting.Children = false;
                }


                listingExisting.UserID = listing.UserID;

                listingExisting.Price    = listing.Price;
                listingExisting.Currency = listing.Currency;

                listingExisting.Tv               = listing.Tv;
                listingExisting.TV_cable         = listing.TV_cable;
                listingExisting.Wifi             = listing.Wifi;
                listingExisting.Grill            = listing.Grill;
                listingExisting.Dishwasher       = listing.Dishwasher;
                listingExisting.Elevator         = listing.Elevator;
                listingExisting.ShortDescription = listing.ShortDescription;
                listingExisting.SafetyMesh       = listing.SafetyMesh;
                listingExisting.Smoker           = listing.Smoker;
                listingExisting.Pets             = listing.Pets;
                listingExisting.Terrace          = listing.Terrace;
                //listingExisting.DescribeCondominium = listing.DescribeCondominium;
                listingExisting.FirstLine        = listing.FirstLine;
                listingExisting.FloorNumber      = listing.FloorNumber;
                listingExisting.M2               = listing.M2;
                listingExisting.Max_Capacity     = listing.Max_Capacity;
                listingExisting.NroOfParking     = listing.NroOfParking;
                listingExisting.Suite            = listing.Suite;
                listingExisting.Washer           = listing.Washer;
                listingExisting.Warranty         = listing.Warranty;
                listingExisting.CleanlinessPrice = listing.CleanlinessPrice;
                listingExisting.Address          = listing.Address;
                listingExisting.Stay             = listing.Stay;

                //listingExisting.ListingTypeID = listing.ListingTypeID;

                listingExisting.ObjectState = Repository.Pattern.Infrastructure.ObjectState.Modified;

                _listingService.Update(listingExisting);
                actualiza = 1;
            }

            // Delete existing fields on item
            var customFieldItemQuery = await _customFieldListingService.Query(x => x.ListingID == listing.ID).SelectAsync();

            var customFieldIds = customFieldItemQuery.Select(x => x.ID).ToList();

            foreach (var customFieldId in customFieldIds)
            {
                await _customFieldListingService.DeleteAsync(customFieldId);
            }

            // Elimina las camas

            var listacama = await _detailBedService.Query(x => x.ListingID == listing.ID).SelectAsync();

            var lista = listacama.Select(x => x.ID).ToList();

            foreach (var id in lista)
            {
                await _detailBedService.DeleteAsync(id);
            }


            // Get custom fields
            var customFieldCategoryQuery = await _customFieldCategoryService.Query(x => x.CategoryID == listing.CategoryID).Include(x => x.MetaField.ListingMetas).SelectAsync();

            var customFieldCategories = customFieldCategoryQuery.ToList();

            // Update custom fields
            foreach (var metaCategory in customFieldCategories)
            {
                var field       = metaCategory.MetaField;
                var controlType = (BeYourMarket.Model.Enum.Enum_MetaFieldControlType)field.ControlTypeID;

                string controlId = string.Format("customfield_{0}_{1}_{2}", metaCategory.ID, metaCategory.CategoryID, metaCategory.FieldID);

                var formValue = form[controlId];

                if (string.IsNullOrEmpty(formValue))
                {
                    continue;
                }

                formValue = formValue.ToString();

                var itemMeta = new ListingMeta()
                {
                    ListingID   = listing.ID,
                    Value       = formValue,
                    FieldID     = field.ID,
                    ObjectState = Repository.Pattern.Infrastructure.ObjectState.Added
                };

                _customFieldListingService.Insert(itemMeta);
            }

            await _unitOfWorkAsync.SaveChangesAsync();


            // Update photos
            if (Request.Files.Count > 0)
            {
                var itemPictureQuery = _listingPictureservice.Queryable().Where(x => x.ListingID == listing.ID);
                if (itemPictureQuery.Count() > 0)
                {
                    nextPictureOrderId = itemPictureQuery.Max(x => x.Ordering);
                }
            }

            if (files != null && files.Count() > 0)
            {
                foreach (HttpPostedFileBase file in files)
                {
                    if ((file != null) && (file.ContentLength > 0) && !string.IsNullOrEmpty(file.FileName))
                    {
                        // Picture picture and get id
                        var picture = new Picture();
                        picture.MimeType = "image/jpeg";
                        _pictureService.Insert(picture);
                        await _unitOfWorkAsync.SaveChangesAsync();

                        // Format is automatically detected though can be changed.
                        ISupportedImageFormat format = new JpegFormat {
                            Quality = 90
                        };
                        Size size = new Size(500, 0);

                        //https://naimhamadi.wordpress.com/2014/06/25/processing-images-in-c-easily-using-imageprocessor/
                        // Initialize the ImageFactory using the overload to preserve EXIF metadata.
                        using (ImageFactory imageFactory = new ImageFactory(preserveExifData: true))
                        {
                            var path = Path.Combine(Server.MapPath("~/images/listing"), string.Format("{0}.{1}", picture.ID.ToString("00000000"), "jpg"));

                            // Load, resize, set the format and quality and save an image.
                            imageFactory.Load(file.InputStream)
                            .Resize(size)
                            .Format(format)
                            .Save(path);
                        }

                        var itemPicture = new ListingPicture();
                        itemPicture.ListingID = listing.ID;
                        itemPicture.PictureID = picture.ID;
                        itemPicture.Ordering  = nextPictureOrderId;

                        _listingPictureservice.Insert(itemPicture);

                        nextPictureOrderId++;
                    }
                }
            }
            //INSERTANDO CAMAS
            if (idcama != null)
            {
                List <int> listaid = new List <int>();
                for (int i = 0; i < idcama.Length; i++)
                {
                    if (listaid.Count != 0) //entra aca cuando no es la primera recorrida
                    {
                        if (!listaid.Contains(idcama[i]))
                        {
                            DetailBed detallecama = new DetailBed();
                            detallecama.TypeOfBedID = idcama[i];
                            detallecama.Quantity    = cantidad[i];
                            detallecama.ListingID   = listing.ID;
                            _detailBedService.Insert(detallecama);
                            listaid.Add(idcama[i]);
                        }
                    }
                    else //entra primero por no tener ninguna cama en la listaid
                    {
                        DetailBed detallecama = new DetailBed();
                        detallecama.TypeOfBedID = idcama[i];
                        detallecama.Quantity    = cantidad[i];
                        detallecama.ListingID   = listing.ID;
                        listaid.Add(idcama[i]);
                        _detailBedService.Insert(detallecama);
                    }
                }
            }   //fin insertando cama

            await _unitOfWorkAsync.SaveChangesAsync();

            if (actualiza == 0)
            {
                listing.Title = listing.ID.ToString();
                _listingService.Update(listing);
                await _unitOfWorkAsync.SaveChangesAsync();
            }

            // Update statistics count
            if (updateCount)
            {
                _sqlDbService.UpdateCategoryItemCount(listing.CategoryID);
                _dataCacheService.RemoveCachedItem(CacheKeys.Statistics);
            }

            return(RedirectToAction("Listings"));
        }
Example #3
0
        public async Task <ActionResult> ListingUpdate(Listing listing, FormCollection form, IEnumerable <HttpPostedFileBase> files)
        {
            if (CacheHelper.Categories.Count == 0)
            {
                TempData[TempDataKeys.UserMessageAlertState] = "bg-danger";
                TempData[TempDataKeys.UserMessage]           = "[[[There are not categories available yet.]]]";

                return(RedirectToAction("Listing", new { id = listing.ID }));
            }

            var userIdCurrent = User.Identity.GetUserId();

            // Register account if not login
            if (!User.Identity.IsAuthenticated)
            {
                var accountController = BeYourMarket.Core.ContainerManager.GetConfiguredContainer().Resolve <AccountController>();

                var modelRegister = new RegisterViewModel()
                {
                    Email           = listing.ContactEmail,
                    Password        = form["Password"],
                    ConfirmPassword = form["ConfirmPassword"],
                };

                // Parse first and last name
                var names = listing.ContactName.Split(' ');
                if (names.Length == 1)
                {
                    modelRegister.FirstName = names[0];
                }
                else if (names.Length == 2)
                {
                    modelRegister.FirstName = names[0];
                    modelRegister.LastName  = names[1];
                }
                else if (names.Length > 2)
                {
                    modelRegister.FirstName = names[0];
                    modelRegister.LastName  = listing.ContactName.Substring(listing.ContactName.IndexOf(" ") + 1);
                }

                // Register account
                var resultRegister = await accountController.RegisterAccount(modelRegister);

                // Add errors
                AddErrors(resultRegister);

                // Show errors if not succeed
                if (!resultRegister.Succeeded)
                {
                    var model = new ListingUpdateModel()
                    {
                        ListingItem = listing
                    };
                    // Populate model with listing
                    await PopulateListingUpdateModel(listing, model);

                    return(View("ListingUpdate", model));
                }

                // update current user id
                var user = await UserManager.FindByNameAsync(listing.ContactEmail);

                userIdCurrent = user.Id;
            }

            bool updateCount = false;

            int nextPictureOrderId = 0;

            // Set default listing type ID
            if (listing.ListingTypeID == 0)
            {
                var listingType = CacheHelper.ListingTypes.Where(x => x.CategoryListingTypes.Any(y => y.CategoryID == listing.CategoryID));

                if (listingType == null)
                {
                    TempData[TempDataKeys.UserMessageAlertState] = "bg-danger";
                    TempData[TempDataKeys.UserMessage]           = "[[[There are not listing types available yet.]]]";

                    return(RedirectToAction("Listing", new { id = listing.ID }));
                }

                listing.ListingTypeID = listingType.FirstOrDefault().ID;
            }

            if (listing.ID == 0)
            {
                listing.ObjectState = Repository.Pattern.Infrastructure.ObjectState.Added;
                listing.IP          = Request.GetVisitorIP();
                listing.Expiration  = DateTime.MaxValue.AddDays(-1);
                listing.UserID      = userIdCurrent;
                listing.Enabled     = true;
                listing.Currency    = CacheHelper.Settings.Currency;

                updateCount = true;
                _listingService.Insert(listing);
            }
            else
            {
                if (await NotMeListing(listing.ID))
                {
                    return(new HttpUnauthorizedResult());
                }

                var listingExisting = await _listingService.FindAsync(listing.ID);

                listingExisting.Title       = listing.Title;
                listingExisting.Description = listing.Description;
                listingExisting.Active      = listing.Active;
                listingExisting.Price       = listing.Price;

                listingExisting.ContactEmail = listing.ContactEmail;
                listingExisting.ContactName  = listing.ContactName;
                listingExisting.ContactPhone = listing.ContactPhone;

                listingExisting.Latitude  = listing.Latitude;
                listingExisting.Longitude = listing.Longitude;
                listingExisting.Location  = listing.Location;

                listingExisting.ShowPhone = listing.ShowPhone;
                listingExisting.ShowEmail = listing.ShowEmail;

                listingExisting.CategoryID    = listing.CategoryID;
                listingExisting.ListingTypeID = listing.ListingTypeID;

                listingExisting.ObjectState = Repository.Pattern.Infrastructure.ObjectState.Modified;

                _listingService.Update(listingExisting);
            }

            // Delete existing fields on item
            var customFieldItemQuery = await _customFieldListingService.Query(x => x.ListingID == listing.ID).SelectAsync();

            var customFieldIds = customFieldItemQuery.Select(x => x.ID).ToList();

            foreach (var customFieldId in customFieldIds)
            {
                await _customFieldListingService.DeleteAsync(customFieldId);
            }

            // Get custom fields
            var customFieldCategoryQuery = await _customFieldCategoryService.Query(x => x.CategoryID == listing.CategoryID).Include(x => x.MetaField.ListingMetas).SelectAsync();

            var customFieldCategories = customFieldCategoryQuery.ToList();

            foreach (var metaCategory in customFieldCategories)
            {
                var field       = metaCategory.MetaField;
                var controlType = (BeYourMarket.Model.Enum.Enum_MetaFieldControlType)field.ControlTypeID;

                string controlId = string.Format("customfield_{0}_{1}_{2}", metaCategory.ID, metaCategory.CategoryID, metaCategory.FieldID);

                var formValue = form[controlId];

                if (string.IsNullOrEmpty(formValue))
                {
                    continue;
                }

                formValue = formValue.ToString();

                var itemMeta = new ListingMeta()
                {
                    ListingID   = listing.ID,
                    Value       = formValue,
                    FieldID     = field.ID,
                    ObjectState = Repository.Pattern.Infrastructure.ObjectState.Added
                };

                _customFieldListingService.Insert(itemMeta);
            }

            await _unitOfWorkAsync.SaveChangesAsync();

            if (Request.Files.Count > 0)
            {
                var itemPictureQuery = _listingPictureservice.Queryable().Where(x => x.ListingID == listing.ID);
                if (itemPictureQuery.Count() > 0)
                {
                    nextPictureOrderId = itemPictureQuery.Max(x => x.Ordering);
                }
            }

            if (files != null && files.Count() > 0)
            {
                foreach (HttpPostedFileBase file in files)
                {
                    if ((file != null) && (file.ContentLength > 0) && !string.IsNullOrEmpty(file.FileName))
                    {
                        // Picture picture and get id
                        var picture = new Picture();
                        picture.MimeType = "image/jpeg";
                        _pictureService.Insert(picture);
                        await _unitOfWorkAsync.SaveChangesAsync();

                        // Format is automatically detected though can be changed.
                        ISupportedImageFormat format = new JpegFormat {
                            Quality = 90
                        };
                        Size size = new Size(500, 0);

                        //https://naimhamadi.wordpress.com/2014/06/25/processing-images-in-c-easily-using-imageprocessor/
                        // Initialize the ImageFactory using the overload to preserve EXIF metadata.
                        using (ImageFactory imageFactory = new ImageFactory(preserveExifData: true))
                        {
                            var path = Path.Combine(Server.MapPath("~/images/listing"), string.Format("{0}.{1}", picture.ID.ToString("00000000"), "jpg"));

                            // Load, resize, set the format and quality and save an image.
                            imageFactory.Load(file.InputStream)
                            .Resize(size)
                            .Format(format)
                            .Save(path);
                        }

                        var itemPicture = new ListingPicture();
                        itemPicture.ListingID = listing.ID;
                        itemPicture.PictureID = picture.ID;
                        itemPicture.Ordering  = nextPictureOrderId;

                        _listingPictureservice.Insert(itemPicture);

                        nextPictureOrderId++;
                    }
                }
            }

            await _unitOfWorkAsync.SaveChangesAsync();

            // Update statistics count
            if (updateCount)
            {
                _sqlDbService.UpdateCategoryItemCount(listing.CategoryID);
                _dataCacheService.RemoveCachedItem(CacheKeys.Statistics);
            }

            TempData[TempDataKeys.UserMessage] = "[[[Listing is updated!]]]";
            return(RedirectToAction("Listing", new { id = listing.ID }));
        }
Example #4
0
        public async Task <ActionResult> ListingUpdate(Listing listing, FormCollection form, IEnumerable <HttpPostedFileBase> files, int[] idcama, int[] cantidad)
        {
            if (CacheHelper.Categories.Count == 0)
            {
                TempData[TempDataKeys.UserMessageAlertState] = "bg-danger";
                TempData[TempDataKeys.UserMessage]           = "[[[There are not categories available yet.]]]";

                return(RedirectToAction("Listing", new { id = listing.ID }));
            }
            var userIdCurrent = User.Identity.GetUserId();

            // Register account if not login
            if (!User.Identity.IsAuthenticated)
            {
                var accountController = BeYourMarket.Core.ContainerManager.GetConfiguredContainer().Resolve <AccountController>();

                var modelRegister = new RegisterViewModel()
                {
                    Email           = listing.ContactEmail,
                    Password        = form["Password"],
                    ConfirmPassword = form["ConfirmPassword"],
                };

                // Parse first and last name
                var names = listing.ContactName.Split(' ');
                if (names.Length == 1)
                {
                    modelRegister.FirstName = names[0];
                }
                else if (names.Length == 2)
                {
                    modelRegister.FirstName = names[0];
                    modelRegister.LastName  = names[1];
                }
                else if (names.Length > 2)
                {
                    modelRegister.FirstName = names[0];
                    modelRegister.LastName  = listing.ContactName.Substring(listing.ContactName.IndexOf(" ") + 1);
                }

                // Register account
                var resultRegister = await accountController.RegisterAccount(modelRegister);

                // Add errors
                AddErrors(resultRegister);

                // Show errors if not succeed
                if (!resultRegister.Succeeded)
                {
                    var model = new ListingUpdateModel()
                    {
                        ListingItem = listing
                    };
                    // Populate model with listing
                    await PopulateListingUpdateModel(listing, model);

                    return(View("ListingUpdate", model));
                }

                // update current user id
                var user = await UserManager.FindByNameAsync(listing.ContactEmail);

                userIdCurrent = user.Id;
            }

            bool updateCount = false;

            int nextPictureOrderId = 0;

            // Set default listing type ID
            if (listing.ListingTypeID == 0)
            {
                var listingTypes = CacheHelper.ListingTypes.Where(x => x.CategoryListingTypes.Any(y => y.CategoryID == listing.CategoryID));

                if (listingTypes == null)
                {
                    TempData[TempDataKeys.UserMessageAlertState] = "bg-danger";
                    TempData[TempDataKeys.UserMessage]           = "[[[There are not listing types available yet.]]]";

                    return(RedirectToAction("Listing", new { id = listing.ID }));
                }

                listing.ListingTypeID = listingTypes.FirstOrDefault().ID;
            }

            if (listing.ID == 0)
            {
                listing.Title       = listing.ID.ToString();
                listing.ObjectState = Repository.Pattern.Infrastructure.ObjectState.Added;
                listing.IP          = Request.GetVisitorIP();
                listing.Expiration  = DateTime.MaxValue.AddDays(-1);
                listing.UserID      = userIdCurrent;
                listing.Enabled     = true;
                listing.Active      = false;
                listing.Currency    = CacheHelper.Settings.Currency;
                listing.Children    = !listing.Children;
                updateCount         = true;
                _listingService.Insert(listing);
            }
            else
            {
                if (await NotMeListing(listing.ID))
                {
                    return(new HttpUnauthorizedResult());
                }

                var listingExisting = await _listingService.FindAsync(listing.ID);

                listingExisting.Title       = listing.ID.ToString();
                listingExisting.Description = listing.Description;
                listingExisting.Price       = listing.Price;

                listingExisting.ContactEmail = listing.ContactEmail;
                listingExisting.ContactName  = listing.ContactName;
                listingExisting.ContactPhone = listing.ContactPhone;

                listingExisting.Latitude  = listing.Latitude;
                listingExisting.Longitude = listing.Longitude;
                listingExisting.Location  = listing.Location;

                listingExisting.ShowPhone = listing.ShowPhone;
                listingExisting.ShowEmail = listing.ShowEmail;

                listingExisting.CategoryID    = listing.CategoryID;
                listingExisting.ListingTypeID = listing.ListingTypeID;



                //nuevos campos
                listingExisting.Bathrooms = listing.Bathrooms;
                listingExisting.Beds      = listing.Beds;
                listingExisting.Cellar    = listing.Cellar;
                listingExisting.Children  = !listing.Children;
                //listingExisting.CleanlinessPrice = listing.CleanlinessPrice;
                listingExisting.ConditionCheckOut = listing.ConditionCheckOut;
                listingExisting.ConditionHouse    = listing.ConditionHouse;
                //listingExisting.DescribeCondominium = listing.DescribeCondominium;
                listingExisting.Description      = listing.Description;
                listingExisting.Dishwasher       = listing.Dishwasher;
                listingExisting.Elevator         = listing.Elevator;
                listingExisting.FirstLine        = listing.FirstLine;
                listingExisting.FloorNumber      = listing.FloorNumber;
                listingExisting.Grill            = listing.Grill;
                listingExisting.M2               = listing.M2;
                listingExisting.Max_Capacity     = listing.Max_Capacity;
                listingExisting.NroOfParking     = listing.NroOfParking;
                listingExisting.ParkingLot       = listing.ParkingLot;
                listingExisting.Pets             = listing.Pets;
                listingExisting.Rooms            = listing.Rooms;
                listingExisting.SafetyMesh       = listing.SafetyMesh;
                listingExisting.ShortDescription = listing.ShortDescription;
                listingExisting.Smoker           = listing.Smoker;
                listingExisting.Stay             = listing.Stay;
                listingExisting.Suite            = listing.Suite;
                listingExisting.Terrace          = listing.Terrace;
                listingExisting.Tv               = listing.Tv;
                listingExisting.TV_cable         = listing.TV_cable;
                listingExisting.TypeOfProperty   = listing.TypeOfProperty;
                //listingExisting.Warranty = listing.Warranty;
                listingExisting.Washer = listing.Washer;
                listingExisting.Wifi   = listing.Wifi;

                listingExisting.ObjectState = Repository.Pattern.Infrastructure.ObjectState.Modified;
                _listingService.Update(listingExisting);
            }


            // Elimina las fotos
            var customFieldItemQuery = await _customFieldListingService.Query(x => x.ListingID == listing.ID).SelectAsync();

            var customFieldIds = customFieldItemQuery.Select(x => x.ID).ToList();

            foreach (var customFieldId in customFieldIds)
            {
                await _customFieldListingService.DeleteAsync(customFieldId);
            }

            // Elimina las camas

            var listacama = await _detailBedService.Query(x => x.ListingID == listing.ID).SelectAsync();

            var lista = listacama.Select(x => x.ID).ToList();

            foreach (var id in lista)
            {
                await _detailBedService.DeleteAsync(id);
            }

            // Get custom fields
            var customFieldCategoryQuery = await _customFieldCategoryService.Query(x => x.CategoryID == listing.CategoryID).Include(x => x.MetaField.ListingMetas).SelectAsync();

            var customFieldCategories = customFieldCategoryQuery.ToList();

            foreach (var metaCategory in customFieldCategories)
            {
                var field       = metaCategory.MetaField;
                var controlType = (BeYourMarket.Model.Enum.Enum_MetaFieldControlType)field.ControlTypeID;

                string controlId = string.Format("customfield_{0}_{1}_{2}", metaCategory.ID, metaCategory.CategoryID, metaCategory.FieldID);

                var formValue = form[controlId];

                if (string.IsNullOrEmpty(formValue))
                {
                    continue;
                }

                formValue = formValue.ToString();

                var itemMeta = new ListingMeta()
                {
                    ListingID   = listing.ID,
                    Value       = formValue,
                    FieldID     = field.ID,
                    ObjectState = Repository.Pattern.Infrastructure.ObjectState.Added
                };

                _customFieldListingService.Insert(itemMeta);
            }

            //ACA PONGO EL TITULO COMO ID
            await _unitOfWorkAsync.SaveChangesAsync();

            if (updateCount)
            {
                listing.Title = listing.ID.ToString();
                _listingService.Update(listing);
                await _unitOfWorkAsync.SaveChangesAsync();
            }


            if (Request.Files.Count > 0)
            {
                var itemPictureQuery = _listingPictureservice.Queryable().Where(x => x.ListingID == listing.ID);
                if (itemPictureQuery.Count() > 0)
                {
                    nextPictureOrderId = itemPictureQuery.Max(x => x.Ordering);
                }
            }

            if (files != null && files.Count() > 0)
            {
                foreach (HttpPostedFileBase file in files)
                {
                    if ((file != null) && (file.ContentLength > 0) && !string.IsNullOrEmpty(file.FileName))
                    {
                        // Picture picture and get id
                        var picture = new Picture();
                        picture.MimeType = "image/jpeg";
                        _pictureService.Insert(picture);
                        await _unitOfWorkAsync.SaveChangesAsync();

                        // Format is automatically detected though can be changed.
                        ISupportedImageFormat format = new JpegFormat {
                            Quality = 90
                        };
                        Size size = new Size(500, 0);

                        //https://naimhamadi.wordpress.com/2014/06/25/processing-images-in-c-easily-using-imageprocessor/
                        // Initialize the ImageFactory using the overload to preserve EXIF metadata.
                        using (ImageFactory imageFactory = new ImageFactory(preserveExifData: true))
                        {
                            var path = Path.Combine(Server.MapPath("~/images/listing"), string.Format("{0}.{1}", picture.ID.ToString("00000000"), "jpg"));

                            // Load, resize, set the format and quality and save an image.
                            imageFactory.Load(file.InputStream)
                            .Resize(size)
                            .Format(format)
                            .Save(path);
                        }

                        var itemPicture = new ListingPicture();
                        itemPicture.ListingID = listing.ID;
                        itemPicture.PictureID = picture.ID;
                        itemPicture.Ordering  = nextPictureOrderId;

                        _listingPictureservice.Insert(itemPicture);

                        nextPictureOrderId++;
                    }
                }
            }

            await _unitOfWorkAsync.SaveChangesAsync();

            //INSERTANDO CAMAS
            if (idcama != null)
            {
                List <int> listaid = new List <int>();
                for (int i = 0; i < idcama.Length; i++)
                {
                    if (listaid.Count != 0)                     //entra aca cuando no es la primera recorrida
                    {
                        if (!listaid.Contains(idcama[i]))
                        {
                            DetailBed detallecama = new DetailBed();
                            detallecama.TypeOfBedID = idcama[i];
                            detallecama.Quantity    = cantidad[i];
                            detallecama.ListingID   = listing.ID;
                            _detailBedService.Insert(detallecama);
                            listaid.Add(idcama[i]);
                        }
                    }
                    else                     //entra primero por no tener ninguna cama en la listaid
                    {
                        DetailBed detallecama = new DetailBed();
                        detallecama.TypeOfBedID = idcama[i];
                        detallecama.Quantity    = cantidad[i];
                        detallecama.ListingID   = listing.ID;
                        listaid.Add(idcama[i]);
                        _detailBedService.Insert(detallecama);
                    }
                }
            }               //fin insertando cama

            //Enviar correo de aviso a administrador
            var emailorderquery = await _emailTemplateService.Query(x => x.Slug.ToLower() == "listingupdate").SelectAsync();

            var templateorder = emailorderquery.Single();
            var admin         = await _aspNetUserService.Query(x => x.AspNetRoles.Any(z => z.Name == "Administrator")).SelectAsync();

            dynamic emailorder = new Postal.Email("Email");

            foreach (var administradores in admin)
            {
                emailorder.To      = administradores.Email;
                emailorder.From    = CacheHelper.Settings.EmailAddress;
                emailorder.Subject = templateorder.Subject;
                emailorder.Body    = templateorder.Body;
                emailorder.Name    = administradores.FullName;
                emailorder.Id      = listing.ID;
                EmailHelper.SendEmail(emailorder);
            }

            await _unitOfWorkAsync.SaveChangesAsync();

            // Update statistics count
            if (updateCount)
            {
                _sqlDbService.UpdateCategoryItemCount(listing.CategoryID);
                _dataCacheService.RemoveCachedItem(CacheKeys.Statistics);
            }
            if (listing.Created.Day.Equals(DateTime.Now.Day))
            {
                TempData[TempDataKeys.UserMessage] = "[[[Listing is updated, contact the provider to activate the service]]]";
                Session.Add("focus", "Si");
                return(RedirectToAction("listingcalendar", "Manage", new { id = listing.ID }));
            }
            else
            {
                TempData[TempDataKeys.UserMessage] = "[[[Listing is updated!]]]";
                return(RedirectToAction("Listing", new { id = listing.ID }));
            }
        }