Exemplo n.º 1
0
        public async Task <JsonResult> Restore(int id)
        {
            OperationResult result = await _productManager.Restore(id);

            var messageType = "success";
            var title       = "Completed";
            var message     = "Product successfully restored.";

            if (result.Type == ResultType.Success)
            {
                return(Json(new { messageType, title, message }));
            }

            messageType = "error";
            title       = "Attention";
            message     = result.Any(s => !string.IsNullOrWhiteSpace(s))
                ? result.BuildMessage()
                : "The product has not been restored to an uknown error.";

            return(Json(new { messageType, title, message }));
        }
        private async void OnPostAsync()
        {
            if (!editMode)
            {
                await CheckOnSpam();

                if (_isSpammer)
                {
                    return;
                }
            }

            EnablePostAndEdit(false);

            if (_isFromCamera)
            {
                var croppedPhoto = _cropView.CropImage(new SavedPhoto(null, ImageAssets[0].Item2, _cropView.ContentOffset)
                {
                    OriginalImageSize = _cropView.originalImageSize, Scale = _cropView.ZoomScale
                });
                ImageAssets.RemoveAt(0);
                ImageAssets.Add(new Tuple <NSDictionary, UIImage>(null, croppedPhoto));
            }

            await Task.Run(() =>
            {
                try
                {
                    string title        = null;
                    string description  = null;
                    IList <string> tags = null;

                    InvokeOnMainThread(() =>
                    {
                        title       = titleTextField.Text;
                        description = descriptionTextField.Text;
                        tags        = collectionviewSource.LocalTags;
                    });

                    var mre = new ManualResetEvent(false);

                    if (!editMode)
                    {
                        var shouldReturn     = false;
                        var photoUploadRetry = false;
                        OperationResult <MediaModel>[] photoUploadResponse = new OperationResult <MediaModel> [ImageAssets.Count];
                        do
                        {
                            photoUploadRetry = false;
                            for (int i = 0; i < ImageAssets.Count; i++)
                            {
                                photoUploadResponse[i] = UploadPhoto(ImageAssets[i].Item2, ImageAssets[i].Item1).Result;
                            }

                            if (photoUploadResponse.Any(r => r.IsSuccess == false))
                            {
                                InvokeOnMainThread(() =>
                                {
                                    //Remake this
                                    ShowDialog(photoUploadResponse[0].Error, LocalizationKeys.Cancel, LocalizationKeys.Retry, (arg) =>
                                    {
                                        shouldReturn = true;
                                        mre.Set();
                                    }, (arg) =>
                                    {
                                        photoUploadRetry = true;
                                        mre.Set();
                                    });
                                });

                                mre.Reset();
                                mre.WaitOne();
                            }
                        } while (photoUploadRetry);

                        if (shouldReturn)
                        {
                            return;
                        }

                        model = new PreparePostModel(AppSettings.User.UserInfo, AppSettings.AppInfo.GetModel())
                        {
                            Title       = title,
                            Description = description,
                            Device      = "iOS",

                            Tags  = tags.ToArray(),
                            Media = photoUploadResponse.Select(r => r.Result).ToArray(),
                        };
                    }
                    else
                    {
                        model.Title       = title;
                        model.Description = description;
                        model.Device      = "iOS";
                        model.Tags        = tags.ToArray();
                        model.Media       = post.Media;
                    }

                    var pushToBlockchainRetry = false;
                    do
                    {
                        pushToBlockchainRetry = false;
                        var response          = _presenter.TryCreateOrEditPost(model).Result;
                        if (!(response != null && response.IsSuccess))
                        {
                            InvokeOnMainThread(() =>
                            {
                                ShowDialog(response.Error, LocalizationKeys.Cancel, LocalizationKeys.Retry, (arg) =>
                                {
                                    mre.Set();
                                }, (arg) =>
                                {
                                    pushToBlockchainRetry = true;
                                    mre.Set();
                                });
                            });

                            mre.Reset();
                            mre.WaitOne();
                        }
                        else
                        {
                            InvokeOnMainThread(() =>
                            {
                                ShouldProfileUpdate = true;
                                NavigationController.ViewControllers = new UIViewController[] { NavigationController.ViewControllers[0], this };
                                NavigationController.PopViewController(false);
                            });
                        }
                    } while (pushToBlockchainRetry);
                }
                finally
                {
                    InvokeOnMainThread(() =>
                    {
                        EnablePostAndEdit(true);
                    });
                }
            });
        }
Exemplo n.º 3
0
        /// <summary>
        /// Изменяет сущность продукта и асинхронно сохраняет ее.
        /// </summary>
        public async Task <OperationResult> Edit(ProductCreateDTO editModel)
        {
            if (editModel?.Product == null ||
                !await Database.Products.Select(p => p.Id).ContainsAsync(editModel.Product.Id))
            {
                return(OperationResult(ResultType.Error, "Product not found."));
            }

            List <string> messages = new List <string>();

            var product = new Product
            {
                Id          = editModel.Product.Id,
                BrandId     = editModel.Product.BrandId,
                CategoryId  = editModel.Product.CategoryId,
                CountryId   = editModel.Product.CountryId,
                Description = editModel.Product.Description,
                Name        = editModel.Product.Name,
                Price       = editModel.Product.Price,
                Removed     = editModel.Product.Removed,
                Weight      = editModel.Product.Weight
            };

            if (product.CategoryId.HasValue)
            {
                bool categoryExists = await Database.Categories
                                      .Select(c => c.Id)
                                      .ContainsAsync(product.CategoryId.Value);

                if (!categoryExists)
                {
                    messages.Append("The category does not exist in the system.");
                    product.CategoryId = null;
                }
            }

            if (product.BrandId.HasValue)
            {
                bool brandExists = await Database.Brands
                                   .Select(c => c.Id)
                                   .ContainsAsync(product.BrandId.Value);

                if (!brandExists)
                {
                    messages.Append("The brand does not exist in the system.");
                    product.BrandId = null;
                }
            }

            if (product.CountryId.HasValue)
            {
                bool countryExists = await Database.Countries
                                     .Select(c => c.Id)
                                     .ContainsAsync(product.CountryId.Value);

                if (!countryExists)
                {
                    messages.Append("The country does not exist in the system.");
                    product.CountryId = null;
                }
            }

            if (editModel.ProductCharacteristics != null && editModel.ProductCharacteristics.Count > 0)
            {
                List <string> availableChars = await Database.Characteristics
                                               .Select(c => c.Name).ToListAsync();

                var validChars = new Dictionary <string, string>();

                foreach (var characteristic in editModel.ProductCharacteristics)
                {
                    if (!availableChars.Contains(characteristic.Key))
                    {
                        messages.Append($"Characteristic {characteristic} does not exists.");
                        continue;
                    }

                    validChars.Add(characteristic.Key, characteristic.Value);
                }

                product.Character = GetCharacteristicsFromDictionary(validChars);
            }

            string oldFilePath = await Database.Products.Where(p => p.Id == product.Id)
                                 .Select(p => p.Image).FirstOrDefaultAsync();

            if (!string.IsNullOrWhiteSpace(oldFilePath))
            {
                OperationResult deleteResult = Database.ProductsImages.Delete(oldFilePath);

                if (deleteResult.Type != ResultType.Success &&
                    deleteResult.Messages != null && deleteResult.Any())
                {
                    messages.AddRange(deleteResult);
                }
            }

            if (editModel.ProductImage != null && editModel.ProductImage.Length > 0)
            {
                ImageSaveResult saveResult = await Database.ProductsImages.Save(editModel.ProductImage);

                if (saveResult.Type == ResultType.Success && !string.IsNullOrWhiteSpace(saveResult.OutputPath))
                {
                    product.Image = saveResult.OutputPath;
                }
                else if (saveResult.Messages != null && saveResult.Any())
                {
                    messages.AddRange(saveResult);
                }
            }

            Database.Products.Update(product);
            await Database.SaveChangesAsync();

            ResultType type = messages.Any()
                ? ResultType.Warning
                : ResultType.Success;

            return(OperationResult(type, messages.ToArray()));
        }
Exemplo n.º 4
0
        protected virtual async void OnPostAsync(bool skipPreparationSteps)
        {
            if (!skipPreparationSteps)
            {
                await CheckOnSpam(true);

                if (_isSpammer)
                {
                    return;
                }
            }

            EnablePostAndEdit(false);

            if (_isFromCamera && !skipPreparationSteps)
            {
                var croppedPhoto = _cropView.CropImage(new SavedPhoto(null, ImageAssets[0].Item2, _cropView.ContentOffset)
                {
                    OriginalImageSize = _cropView.originalImageSize, Scale = _cropView.ZoomScale
                });
                ImageAssets.RemoveAt(0);
                ImageAssets.Add(new Tuple <NSDictionary, UIImage>(null, croppedPhoto));
            }

            await Task.Run(() =>
            {
                try
                {
                    var shouldReturn    = false;
                    string title        = null;
                    string description  = null;
                    IList <string> tags = null;

                    InvokeOnMainThread(() =>
                    {
                        title       = titleTextField.Text;
                        description = descriptionTextField.Text;
                        tags        = collectionviewSource.LocalTags;
                    });

                    mre = new ManualResetEvent(false);

                    if (!skipPreparationSteps)
                    {
                        var photoUploadRetry = false;
                        OperationResult <MediaModel>[] photoUploadResponse = new OperationResult <MediaModel> [ImageAssets.Count];
                        do
                        {
                            photoUploadRetry = false;
                            for (int i = 0; i < ImageAssets.Count; i++)
                            {
                                photoUploadResponse[i] = UploadPhoto(ImageAssets[i].Item2, ImageAssets[i].Item1).Result;
                            }

                            if (photoUploadResponse.Any(r => r.IsSuccess == false))
                            {
                                InvokeOnMainThread(() =>
                                {
                                    //Remake this
                                    ShowDialog(photoUploadResponse[0].Exception, LocalizationKeys.Cancel,
                                               LocalizationKeys.Retry, (arg) =>
                                    {
                                        shouldReturn = true;
                                        mre.Set();
                                    }, (arg) =>
                                    {
                                        photoUploadRetry = true;
                                        mre.Set();
                                    });
                                });

                                mre.Reset();
                                mre.WaitOne();
                            }
                        } while (photoUploadRetry);

                        if (shouldReturn)
                        {
                            return;
                        }

                        model = new PreparePostModel(AppSettings.User.UserInfo, AppSettings.AppInfo.GetModel())
                        {
                            Title       = title,
                            Description = description,
                            Device      = "iOS",

                            Tags  = tags.ToArray(),
                            Media = photoUploadResponse.Select(r => r.Result).ToArray(),
                        };
                    }

                    CreateOrEditPost(skipPreparationSteps);
                }
                catch (Exception ex)
                {
                    AppSettings.Logger.Warning(ex);
                }
                finally
                {
                    InvokeOnMainThread(() => { EnablePostAndEdit(true); });
                }
            });
        }