예제 #1
0
        public async Task <MediaObjectInfo> NewMediaObjectAsync(string blogid, string username, string password, MediaObject mediaObject)
        {
            EnsureUser(username, password);

            try
            {
                // TODO: Check extension names

                var bits = Convert.FromBase64String(mediaObject.bits);

                var pFilename = _fileNameGenerator.GetFileName(mediaObject.name);
                var filename  = await _blogImageStorage.InsertAsync(pFilename, bits);

                var imageUrl = $"{Helper.ResolveRootUrl(null, _blogConfig.GeneralSettings.CanonicalPrefix, true)}image/{filename}";

                MediaObjectInfo objectInfo = new MediaObjectInfo {
                    url = imageUrl
                };
                return(objectInfo);
            }
            catch (Exception e)
            {
                _logger.LogError(e, e.Message);
                throw new MetaWeblogException(e.Message);
            }
        }
예제 #2
0
        public void Log(string message)
        {
            var fileName = _fileNameGenerator.GetFileName();

            _fileSystem.CreateFileIfNotExists(fileName);

            if (fileName == "weekend.txt")
            {
                if (_fileSystem.GetCreationTime(fileName) < _dateTime.Today.AddDays(-2))
                {
                    _fileSystem.MoveFile(fileName, _fileNameGenerator.GetLastSaturdayFileName());
                }
            }

            _fileSystem.StringWriteLineToFile(fileName, message);
        }
예제 #3
0
 public void Write(string content, bool hasTimeStamp, FileTypeEnum fileType)
 {
     try
     {
         IFileNameGenerator generator    = FileNameGeneratorFactory.Create(fileType);
         string             fullfilename = generator.GetFileName(_fileNameFormat, fileSize);
         FileInfo           file         = new FileInfo(fullfilename);
         StringBuilder      log          = new StringBuilder();
         if (hasTimeStamp)
         {
             log.AppendFormat("{0} -- {1}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"), content);
         }
         else
         {
             log.Append(content);
         }
         //lock (locker)
         //{
         if (!writeLock.IsWriteLockHeld)
         {
             writeLock.EnterWriteLock();
         }
         try
         {
             if (!file.Exists)
             {
                 file.Create().Close();
             }
             File.AppendAllLines(file.FullName, new string[] { log.ToString() });
         }
         finally
         {
             if (writeLock.IsWriteLockHeld)
             {
                 writeLock.ExitWriteLock();
             }
         }
         //}
     }
     catch
     {
     }
 }
예제 #4
0
    public Task <MediaObjectInfo> NewMediaObjectAsync(string blogid, string username, string password, MediaObject mediaObject)
    {
        EnsureUser(username, password);

        return(TryExecuteAsync(async() =>
        {
            // TODO: Check extension names

            var bits = Convert.FromBase64String(mediaObject.bits);

            var pFilename = _fileNameGenerator.GetFileName(mediaObject.name);
            var filename = await _blogImageStorage.InsertAsync(pFilename, bits);

            var imageUrl = $"{Helper.ResolveRootUrl(null, _blogConfig.GeneralSettings.CanonicalPrefix, true)}image/{filename}";

            var objectInfo = new MediaObjectInfo {
                url = imageUrl
            };
            return objectInfo;
        }));
    }
예제 #5
0
        public async Task <IActionResult> UploadImageAsync(IFormFile file, [FromServices] IFileNameGenerator fileNameGenerator)
        {
            try
            {
                if (null == file)
                {
                    Logger.LogError("file is null.");
                    return(BadRequest());
                }

                if (file.Length <= 0)
                {
                    return(BadRequest());
                }

                var name = Path.GetFileName(file.FileName);
                if (name == null)
                {
                    return(BadRequest());
                }

                var ext = Path.GetExtension(name).ToLower();
                var allowedImageFormats = new[] { ".png", ".jpg", ".jpeg", ".bmp", ".gif" };
                if (!allowedImageFormats.Contains(ext))
                {
                    Logger.LogError($"Invalid file extension: {ext}");
                    return(BadRequest());
                }

                var primaryFileName  = fileNameGenerator.GetFileName(name);
                var secondaryFieName = fileNameGenerator.GetFileName(name, "origin");

                await using var stream = new MemoryStream();
                await file.CopyToAsync(stream);

                // Add watermark
                MemoryStream watermarkedStream = null;
                if (_blogConfig.WatermarkSettings.IsEnabled && ext != ".gif")
                {
                    using var watermarker = new ImageWatermarker(stream, ext)
                          {
                              SkipWatermarkForSmallImages = true,
                              SmallImagePixelsThreshold   = Constants.SmallImagePixelsThreshold
                          };
                    Logger.LogInformation($"Adding watermark onto image '{primaryFileName}'");

                    watermarkedStream = watermarker.AddWatermark(
                        _blogConfig.WatermarkSettings.WatermarkText,
                        Color.FromArgb(128, 128, 128, 128),
                        WatermarkPosition.BottomRight,
                        15,
                        _blogConfig.WatermarkSettings.FontSize);
                }

                var response = await _imageStorage.InsertAsync(primaryFileName,
                                                               watermarkedStream != null?
                                                               watermarkedStream.ToArray() :
                                                                   stream.ToArray());

                if (_blogConfig.WatermarkSettings.KeepOriginImage)
                {
                    var arr = stream.ToArray();
                    _ = Task.Run(async() => await _imageStorage.InsertAsync(secondaryFieName, arr));
                }

                Logger.LogInformation($"Image '{primaryFileName}' uloaded.");

                if (response.IsSuccess)
                {
                    return(Json(new
                    {
                        location = $"/uploads/{response.Item}",
                        filename = response.Item
                    }));
                }
                Logger.LogError(response.Message);
                return(ServerError());
            }
            catch (Exception e)
            {
                Logger.LogError(e, "Error uploading image.");
                return(ServerError());
            }
        }
예제 #6
0
        public async Task <ActionResult> EditAppUser(AdminModel adminModel, IFormFile Image)
        {
            string  Id   = HttpContext.Session.GetObjectFromJson <string>("UserId");
            AppUser user = userManager.Users.Where(x => x.Id == Id).First();

            user.PhoneNumber = adminModel.PhoneNumber;
            user.FirstName   = adminModel.FirstName;
            user.SecondName  = adminModel.SecondName;
            user.Birth       = adminModel.Birthday.ToUniversalTime();
            user.Adress      = adminModel.Address;
            if (ModelState.IsValid)
            {
                if (adminModel.OldPassword != null)
                {
                    IList <string> str = await userManager.GetRolesAsync(user);

                    PasswordVerificationResult result = passwordHasher.VerifyHashedPassword(user, user.PasswordHash, adminModel.OldPassword);
                    if (PasswordVerificationResult.Success == result)
                    {
                        if (Image != null)
                        {
                            if (Image.IsFilePhotoFormat())
                            {
                                string fullPath     = hostingEnvironment.GetFolder();
                                string format       = Image.GetFileFormat();
                                string fileName     = nameGenerator.GetFileName(format);
                                string fullFilePath = Path.Combine(fullPath, fileName);
                                await Image.SaveFileAsync(fullFilePath);

                                user.Photo = fileName;
                                ImageRemove.PhotoPathDelete(user.Photo, fullPath);
                                if (adminModel.NewPassword == null)
                                {
                                    ModelState.AddModelError("", "New Password empty");
                                }
                                else
                                {
                                    user.PasswordHash = passwordHasher.HashPassword(user, adminModel.NewPassword);
                                    dbContext.Update <AppUser>(user);
                                    await dbContext.SaveChangesAsync();

                                    ModelState.AddModelError("", "Succes");
                                }
                            }
                            else
                            {
                                ModelState.AddModelError("", "Photo is not Format and format (jpg,png)");
                            }
                        }
                        else
                        {
                            if (adminModel.NewPassword == null)
                            {
                                ModelState.AddModelError("", "New Password empty");
                            }
                            else
                            {
                                user.PasswordHash = passwordHasher.HashPassword(user, adminModel.NewPassword);
                                dbContext.Update <AppUser>(user);
                                await dbContext.SaveChangesAsync();

                                ModelState.AddModelError("", "Succes");
                            }
                        }
                    }
                    else
                    {
                        ModelState.AddModelError("", "Old Password Incorrect");
                    }
                }
                else
                {
                    IList <string> str = await userManager.GetRolesAsync(user);

                    if (Image != null)
                    {
                        if (Image.IsFilePhotoFormat())
                        {
                            string fullPath     = hostingEnvironment.GetFolder();
                            string format       = Image.GetFileFormat();
                            string fileName     = nameGenerator.GetFileName(format);
                            string fullFilePath = Path.Combine(fullPath, fileName);
                            ImageRemove.PhotoPathDelete(user.Photo, fullPath);
                            await Image.SaveFileAsync(fullFilePath);

                            user.Photo = fileName;

                            dbContext.Update <AppUser>(user);
                            await dbContext.SaveChangesAsync();

                            ModelState.AddModelError("", "Succes");
                        }
                        else
                        {
                            ModelState.AddModelError("", "Photo is not Format and format (jpg,png)");
                        }
                    }
                    else
                    {
                        dbContext.Update <AppUser>(user);
                        await dbContext.SaveChangesAsync();

                        ModelState.AddModelError("", "Succes");
                    }
                }
            }
            return(View(adminModel));
        }
예제 #7
0
        public async Task <ActionResult> EditEmployee(Employee employee, IFormFile Photo)
        {
            if (ModelState.IsValid)
            {
                Employee data = dbContext.Employees.Where(x => x.Email == employee.Email).FirstOrDefault();
                if (data != null)
                {
                    if (Photo != null)
                    {
                        if (Photo.IsFilePhotoFormat())
                        {
                            string fullPath     = hostingEnvironment.GetFolder();
                            string format       = Photo.GetFileFormat();
                            string fileName     = nameGenerator.GetFileName(format);
                            string fullFilePath = Path.Combine(fullPath, fileName);
                            ImageRemove.PhotoPathDelete(data.Photo, fullPath);
                            await Photo.SaveFileAsync(fullFilePath);

                            data.Name                 = employee.Name;
                            data.Surname              = employee.Surname;
                            data.FatherName           = employee.FatherName;
                            data.Gender               = employee.Gender;
                            data.IDCardExparyDate     = employee.IDCardExparyDate;
                            data.IDCardSerialNumber   = employee.IDCardSerialNumber;
                            data.MaritalStatus        = employee.MaritalStatus;
                            data.Nationally           = employee.Nationally;
                            data.Number               = employee.Number;
                            data.Photo                = fileName;
                            data.BirthDay             = employee.BirthDay;
                            data.DistrictRegistration = employee.DistrictRegistration;
                            data.Email                = employee.Email;
                            data.PlasiyerCode         = employee.PlasiyerCode;

                            dbContext.Update <Employee>(data);
                            await dbContext.SaveChangesAsync();
                        }
                        else
                        {
                            ModelState.AddModelError("", "Photo is format (jpg,png)");
                        }
                    }
                    else
                    {
                        data.Name                 = employee.Name;
                        data.Surname              = employee.Surname;
                        data.FatherName           = employee.FatherName;
                        data.Gender               = employee.Gender;
                        data.IDCardExparyDate     = employee.IDCardExparyDate;
                        data.IDCardSerialNumber   = employee.IDCardSerialNumber;
                        data.MaritalStatus        = employee.MaritalStatus;
                        data.Nationally           = employee.Nationally;
                        data.Number               = employee.Number;
                        data.BirthDay             = employee.BirthDay;
                        data.DistrictRegistration = employee.DistrictRegistration;
                        data.Email                = employee.Email;
                        data.PlasiyerCode         = employee.PlasiyerCode;

                        dbContext.Update <Employee>(data);
                        await dbContext.SaveChangesAsync();
                    }
                }
                else
                {
                    ModelState.AddModelError("", "User is not exists");
                }
            }
            return(View());
        }