public async Task <ActionResult> CreateEmoticon(CreateEmoticonModel model) { if (!ModelState.IsValid) { return(JsonError(ModelState.FirstError())); } var file = Request.Files[0]; if (file == null) { return(JsonError("Image file is required.")); } model.FileStream = file.InputStream; var emoticonFile = Server.MapPath("~/Content/Images/EmoticonSet/Emoticon.json"); var result = await EmoticonWriter.CreateEmoticon(emoticonFile, model); if (!ModelState.IsWriterResultValid(result)) { return(JsonError(result.Message)); } return(JsonSuccess(result.Message)); }
public async Task <IWriterResult> CreateEmoticon(string emoticonFile, CreateEmoticonModel model) { if (!File.Exists(emoticonFile)) { return(new WriterResult(false, "Emoticon file not found.")); } var data = File.ReadAllText(emoticonFile); if (string.IsNullOrEmpty(data)) { return(new WriterResult(false, "Emoticon file not found.")); } var serializer = new JavaScriptSerializer(); var emoticons = new List <EmoticonModel>(serializer.Deserialize <List <EmoticonModel> >(data)); var code = !string.IsNullOrEmpty(model.Code) ? model.Code : GetNewCode(emoticons.Select(x => x.Code)); if (string.IsNullOrEmpty(code)) { return(new WriterResult(false, "Failed to generate emoticon code.")); } if (emoticons.Any(x => x.Code == code)) { return(new WriterResult(false, $"Code '{code}' already exists.")); } var extension = model.ForceResize ? ".PNG" : ".GIF"; var imageResult = await ImageService.SaveImage(new CreateImageModel { CanResize = model.ForceResize, PreserveAspectRatio = model.ForceResize, Directory = Path.GetDirectoryName(emoticonFile), FileStream = model.FileStream, MaxFileSize = Constant.EMOTICON_MAXSIZE, MaxHeight = Constant.EMOTICON_MAXHEIGHT, MaxWidth = Constant.EMOTICON_MAXWIDTH, Name = code, Extention = extension }).ConfigureAwait(false); if (!imageResult.Success) { return(new WriterResult(false, imageResult.Message)); } emoticons.Add(new EmoticonModel { Category = model.Category, Code = $"[{code}]", Name = model.Name, Path = code + extension }); File.WriteAllText(emoticonFile, serializer.Serialize(emoticons.OrderBy(x => x.Code).ToList())); await CacheService.InvalidateAsync(CacheKey.Emoticons()).ConfigureAwait(false); model.Code = $"[{code}]"; return(new WriterResult(true, "Successfully saved emoticon.")); }