Пример #1
0
      /// <summary>
      /// Rename a blob (folder, file etc.).
      /// </summary>
      /// <param name="blobStorage"></param>
      /// <param name="oldPath"></param>
      /// <param name="newPath"></param>
      /// <param name="cancellationToken"></param>
      /// <returns></returns>
      public static async Task RenameAsync(this IBlobStorage blobStorage,
         string oldPath, string newPath, CancellationToken cancellationToken = default)
      {
         if(oldPath is null)
            throw new ArgumentNullException(nameof(oldPath));
         if(newPath is null)
            throw new ArgumentNullException(nameof(newPath));

         //try to use extended client here
         if(blobStorage is IExtendedBlobStorage extendedBlobStorage)
         {
            await extendedBlobStorage.RenameAsync(oldPath, newPath, cancellationToken).ConfigureAwait(false);
         }
         else
         {
            //this needs to be done recursively
            foreach(Blob item in await blobStorage.ListAsync(oldPath, recurse: true).ConfigureAwait(false))
            {
               if(item.IsFile)
               {
                  string renamedPath = item.FullPath.Replace(oldPath, newPath);

                  await blobStorage.CopyToAsync(item, blobStorage, renamedPath, cancellationToken).ConfigureAwait(false);
                  await blobStorage.DeleteAsync(item, cancellationToken).ConfigureAwait(false);
               }
            }

            //rename self
            await blobStorage.CopyToAsync(oldPath, blobStorage, newPath, cancellationToken).ConfigureAwait(false);
            await blobStorage.DeleteAsync(oldPath, cancellationToken).ConfigureAwait(false);
         }


      }
Пример #2
0
        public async Task DisposeAsync()
        {
            try
            {
                IReadOnlyCollection <BlobId> allFiles = await _storage.ListFilesAsync(null);

                await _storage.DeleteAsync(allFiles.Select(id => id.FullPath));
            }
            catch
            {
                //just don't care
            }
        }
Пример #3
0
        public async Task <Result <int> > Handle(UploadFieldValueAttachmentCommand request, CancellationToken cancellationToken)
        {
            var tag = await _projectRepository.GetTagByTagIdAsync(request.TagId);

            var requirement = tag.Requirements.Single(r => r.Id == request.RequirementId);

            var requirementDefinition =
                await _requirementTypeRepository.GetRequirementDefinitionByIdAsync(requirement.RequirementDefinitionId);

            var attachment = requirement.GetAlreadyRecordedAttachment(request.FieldId, requirementDefinition);

            string fullBlobPath;

            if (attachment == null)
            {
                attachment = new FieldValueAttachment(_plantProvider.Plant, Guid.NewGuid(), request.FileName);
            }
            else
            {
                fullBlobPath = attachment.GetFullBlobPath(_attachmentOptions.CurrentValue.BlobContainer);
                await _blobStorage.DeleteAsync(fullBlobPath, cancellationToken);

                attachment.SetFileName(request.FileName);
            }

            fullBlobPath = attachment.GetFullBlobPath(_attachmentOptions.CurrentValue.BlobContainer);

            await _blobStorage.UploadAsync(fullBlobPath, request.Content, true, cancellationToken);

            requirement.RecordAttachment(attachment, request.FieldId, requirementDefinition);

            await _unitOfWork.SaveChangesAsync(cancellationToken);

            return(new SuccessResult <int>(attachment.Id));
        }
Пример #4
0
        /// <summary>
        /// Deletes blob/s from the storage
        /// </summary>
        /// <param name="UserBlobs">The user blobs to delete</param>
        /// <returns></returns>
        public static async Task <IApiResponse <IEnumerable <UserBlobs> > > DeleteRangeUserBlobsAsync(this BaseDbContext <AuditTrails, ExceptionLogs, UserBlobs> dbContext, IEnumerable <UserBlobs> userBlobs, IBlobStorage blobStorage, string userId, bool ignoreBlobOwner = false, string controllerName = null, string actionName = null, string remoteIpAddress = null)
        {
            if (userBlobs == null || !userBlobs.Any())
            {
                await dbContext.CreateAuditrailsAsync(userBlobs, "UserBlobs is null or empty on method DeleteRange", userId, controllerName, actionName, remoteIpAddress);

                return(new ApiResponse <IEnumerable <UserBlobs> >()
                {
                    Status = ApiResponseStatus.Failed, Message = "FileNotFound"
                });
            }
            foreach (var userBlob in userBlobs)
            {
                var isBlobOwnerAndFileExists = await dbContext.IsBlobOwnerAndFileExistsAsync(userBlob, blobStorage, userId, ignoreBlobOwner, controllerName, actionName, remoteIpAddress);

                if (isBlobOwnerAndFileExists.Status == ApiResponseStatus.Failed || !isBlobOwnerAndFileExists.Data)
                {
                    return(new ApiResponse <IEnumerable <UserBlobs> >()
                    {
                        Status = ApiResponseStatus.Failed, Message = isBlobOwnerAndFileExists.Message
                    });
                }
                await blobStorage.DeleteAsync(userBlob.FilePath);

                await dbContext.RemoveAuditedAsync(userBlob, userId, controllerName, actionName, remoteIpAddress);
            }
            var result = await dbContext.SaveChangesAsync();

            return(result.TransactionResultApiResponse(userBlobs));
        }
Пример #5
0
        public async Task <bool> DeleteFileAsync(MethodOptions methodOptions, StorageOptions storageOptions, string filePath)
        {
            EndpointOptions endpoint = FindWriteEndpoint(methodOptions, storageOptions);

            if (!endpoint.Provider.IsFullPath)
            {
                filePath = Path.Combine(endpoint.Path ?? "", filePath);
                string fileName = Path.GetFileName(filePath);
                Log.Information("Command: Remove file {file}", filePath);
                IBlobStorage storage   = _storageProvider.GetStorage(endpoint.Provider, filePath.Replace(fileName, ""));
                bool         fileExist = await storage.ExistsAsync(fileName);

                if (!fileExist)
                {
                    return(false);
                }
                await storage.DeleteAsync(fileName);
            }
            else
            {
                IBlobStorage storage = _storageProvider.GetStorage(endpoint.Provider);
                Log.Information("Command: Remove file {file}", filePath);
                bool fileExist = await storage.ExistsAsync(filePath);

                if (!fileExist)
                {
                    return(false);
                }
                await storage.DeleteAsync(filePath);
            }

            return(true);
        }
Пример #6
0
 /// <summary>
 /// Deletes a collection of blobs or folders
 /// </summary>
 public static Task DeleteAsync(
    this IBlobStorage storage,
    IEnumerable<Blob> blobs,
    CancellationToken cancellationToken = default)
 {
    return storage.DeleteAsync(blobs.Select(b => b.FullPath), cancellationToken);
 }
        public async Task Delete_create_and_delete_doesnt_exist()
        {
            string id = RandomBlobId();
            await _storage.WriteTextAsync(id, "test");

            await _storage.DeleteAsync(id);

            Assert.False(await _storage.ExistsAsync(id));
        }
Пример #8
0
        /// <summary>
        /// Deletes a blob from the storage
        /// </summary>
        /// <param name="UserBlobs">The user blob to delete</param>
        /// <returns></returns>
        public static async Task <IApiResponse <UserBlobs> > DeleteForcedUserBlobsAsync(this BaseDbContext <AuditTrails, ExceptionLogs, UserBlobs> dbContext, UserBlobs userBlobs, IBlobStorage blobStorage, string userId, string controllerName = null, string actionName = null, string remoteIpAddress = null)
        {
            await blobStorage.DeleteAsync(userBlobs.FilePath);

            await dbContext.RemoveAuditedAsync(userBlobs, userId, controllerName, actionName, remoteIpAddress);

            var result = await dbContext.SaveChangesAsync();

            return(result.TransactionResultApiResponse(userBlobs));
        }
Пример #9
0
 public void Write(string key, string value)
 {
     if (value == null)
     {
         _blobs.DeleteAsync(key).Wait();
     }
     else
     {
         _blobs.WriteTextAsync(key, value).Wait();
     }
 }
Пример #10
0
        public override async Task ExecuteAsync()
        {
            Message = $"deleting {"item".ToQuantity(_toDelete.Count)} in '{_connectedAccount.DisplayName}'";

            await _storage.DeleteAsync(_toDelete);

            Message            = $"{"item".ToQuantity(_toDelete.Count)} deleted in '{_connectedAccount.DisplayName}'";
            ProgressPercentage = 100;

            Messenger.Default.Send(new FolderUpdatedMessage(_storage, _toDelete.First().FolderPath));
        }
        private async Task DeleteBlobAsync(QueueMessage message)
        {
            if (!message.Properties.TryGetValue(QueueMessage.LargeMessageContentHeaderName, out string fileId))
            {
                return;
            }

            message.Properties.Remove(QueueMessage.LargeMessageContentHeaderName);

            await _offloadStorage.DeleteAsync(fileId);
        }
Пример #12
0
        public async Task <Result <Unit> > Handle(DeleteTagAttachmentCommand request, CancellationToken cancellationToken)
        {
            var tag = await _projectRepository.GetTagByTagIdAsync(request.TagId);

            var attachment = tag.Attachments.Single(a => a.Id == request.AttachmentId);

            attachment.SetRowVersion(request.RowVersion);

            var fullBlobPath = attachment.GetFullBlobPath(_attachmentOptions.CurrentValue.BlobContainer);

            await _blobStorage.DeleteAsync(fullBlobPath, cancellationToken);

            tag.RemoveAttachment(attachment);

            await _unitOfWork.SaveChangesAsync(cancellationToken);

            return(new SuccessResult <Unit>(Unit.Value));
        }
Пример #13
0
        /// <summary>
        /// Deletes a blob from the storage
        /// </summary>
        /// <param name="UserBlobs">The user blob to delete</param>
        /// <returns></returns>
        public static async Task <IApiResponse <UserBlobs> > DeleteUserBlobsAsync(this BaseDbContext <AuditTrails, ExceptionLogs, UserBlobs> dbContext, UserBlobs userBlobs, IBlobStorage blobStorage, string userId, bool IgnoreBlobOwner = false, string controllerName = null, string actionName = null, string remoteIpAddress = null)
        {
            var isBlobOwnerAndFileExists = await dbContext.IsBlobOwnerAndFileExistsAsync(userBlobs, blobStorage, userId, IgnoreBlobOwner, controllerName, actionName, remoteIpAddress);

            if (isBlobOwnerAndFileExists.Status == ApiResponseStatus.Failed || !isBlobOwnerAndFileExists.Data)
            {
                return(new ApiResponse <UserBlobs>()
                {
                    Status = ApiResponseStatus.Failed, Message = isBlobOwnerAndFileExists.Message
                });
            }
            await blobStorage.DeleteAsync(userBlobs.FilePath);

            await dbContext.RemoveAuditedAsync(userBlobs, userId, controllerName, actionName, remoteIpAddress);

            var result = await dbContext.SaveChangesAsync();

            return(result.TransactionResultApiResponse(userBlobs));
        }
        /// <summary>Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.</summary>
        public void Dispose()
        {
            if (_awsClient.NativeBlobClient != null)
            {
                if (_awsClient.NativeBlobClient.DoesS3BucketExistAsync(TestBucket).Result)
                {
                    foreach (var file in _blobStorage.ListAsync().Result)
                    {
                        _blobStorage.DeleteAsync(file.Id).Wait();
                    }

                    _awsClient.NativeBlobClient.DeleteBucketAsync(TestBucket).Wait();
                }
            }

            _blobStorage?.Dispose();

            Utility.ClearTestData(TestFilePath);
        }
Пример #15
0
        public async Task <IActionResult> DeletePaths(string[] pictures)
        {
            var isUser = await _noSqlStorage.Get(UserFakeDBModel.UserId, UserFakeDBModel.UserPartitonKey);

            var userPicturesList = isUser.WatermarkPaths;

            isUser.WatermarkRawPaths = string.Empty;
            foreach (var picture in pictures)
            {
                await _blobStorage.DeleteAsync(picture, EContainerName.watermarkpictures);

                userPicturesList.Remove(picture);
            }
            isUser.WatermarkPaths = userPicturesList;

            await _noSqlStorage.Update(isUser);

            return(RedirectToAction("Index"));
        }
        public async Task <Result <Unit> > Handle(DeleteAttachmentCommand request, CancellationToken cancellationToken)
        {
            var invitation = await _invitationRepository.GetByIdAsync(request.InvitationId);

            var attachment = invitation.Attachments.Single(a => a.Id == request.AttachmentId);

            attachment.SetRowVersion(request.RowVersion);

            var fullBlobPath = Path.Combine(_blobStorageOptions.CurrentValue.BlobContainer, attachment.BlobPath).Replace("\\", "/");

            await _blobStorage.DeleteAsync(fullBlobPath, cancellationToken);

            invitation.RemoveAttachment(attachment);
            _invitationRepository.RemoveAttachment(attachment);

            await _unitOfWork.SaveChangesAsync(cancellationToken);

            return(new SuccessResult <Unit>(Unit.Value));
        }
Пример #17
0
        public async Task <Result <Unit> > Handle(DeleteFieldValueAttachmentCommand request, CancellationToken cancellationToken)
        {
            var tag = await _projectRepository.GetTagByTagIdAsync(request.TagId);

            var requirement = tag.Requirements.Single(r => r.Id == request.RequirementId);

            var requirementDefinition =
                await _requirementTypeRepository.GetRequirementDefinitionByIdAsync(requirement.RequirementDefinitionId);

            var attachment = requirement.GetAlreadyRecordedAttachment(request.FieldId, requirementDefinition);

            if (attachment != null)
            {
                var fullBlobPath = attachment.GetFullBlobPath(_attachmentOptions.CurrentValue.BlobContainer);
                await _blobStorage.DeleteAsync(fullBlobPath, cancellationToken);
            }

            requirement.RecordAttachment(null, request.FieldId, requirementDefinition);

            await _unitOfWork.SaveChangesAsync(cancellationToken);

            return(new SuccessResult <Unit>(Unit.Value));
        }
 public Task DeleteAsync(string path, CancellationToken cancellationToken = default)
 {
     return(_storage.DeleteAsync(_containerName + "/" + path, cancellationToken));
 }
Пример #19
0
 public Task DeleteAsync(string path, CancellationToken cancellationToken = default)
 {
     return(_storage.DeleteAsync(path, cancellationToken));
 }
Пример #20
0
 /// <summary>
 /// Deletes a single blob
 /// </summary>
 /// <param name="provider"></param>
 /// <param name="id"></param>
 /// <param name="cancellationToken"></param>
 /// <returns></returns>
 public static Task DeleteAsync(
     this IBlobStorage provider,
     string id, CancellationToken cancellationToken = default)
 {
     return(provider.DeleteAsync(new[] { id }, cancellationToken));
 }
Пример #21
0
        public async Task <IActionResult> Delete(string fileName)
        {
            await _blobStorage.DeleteAsync(fileName, EContainerName.pictures);

            return(RedirectToAction("Index"));
        }
Пример #22
0
        /// <summary>
        /// moves file from source to destination location
        /// </summary>
        /// <param name="sourceFilepath"></param>
        /// <param name="destinationFilepath"></param>
        /// <param name="overwrite"></param>
        /// <returns></returns>
        public DbFile Move(string sourceFilepath, string destinationFilepath, bool overwrite = false)
        {
            if (string.IsNullOrWhiteSpace(sourceFilepath))
            {
                throw new ArgumentException("sourceFilepath cannot be null or empty");
            }

            if (string.IsNullOrWhiteSpace(destinationFilepath))
            {
                throw new ArgumentException("destinationFilepath cannot be null or empty");
            }

            sourceFilepath      = sourceFilepath.ToLowerInvariant();
            destinationFilepath = destinationFilepath.ToLowerInvariant();

            if (!sourceFilepath.StartsWith(FOLDER_SEPARATOR))
            {
                sourceFilepath = FOLDER_SEPARATOR + sourceFilepath;
            }

            if (!destinationFilepath.StartsWith(FOLDER_SEPARATOR))
            {
                destinationFilepath = FOLDER_SEPARATOR + destinationFilepath;
            }

            var srcFile  = Find(sourceFilepath);
            var destFile = Find(destinationFilepath);

            if (srcFile == null)
            {
                throw new Exception("Source file cannot be found.");
            }

            if (destFile != null && overwrite == false)
            {
                throw new Exception("Destination file already exists and no overwrite specified.");
            }

            using (var connection = CurrentContext.CreateConnection())
            {
                try
                {
                    connection.BeginTransaction();

                    if (destFile != null && overwrite)
                    {
                        Delete(destFile.FilePath);
                    }

                    var command = connection.CreateCommand(@"UPDATE files SET filepath = @filepath WHERE id = @id");
                    command.Parameters.Add(new NpgsqlParameter("@id", srcFile.Id));
                    command.Parameters.Add(new NpgsqlParameter("@filepath", destinationFilepath));
                    command.ExecuteNonQuery();
                    if (ErpSettings.EnableCloudBlobStorage)
                    {
                        var srcPath         = StoragePath.Combine(StoragePath.RootFolderPath, sourceFilepath);
                        var destinationPath = StoragePath.Combine(StoragePath.RootFolderPath, destinationFilepath);
                        using (IBlobStorage storage = GetBlobStorage())
                        {
                            using (Stream original = storage.OpenReadAsync(srcPath).Result)
                            {
                                if (original != null)
                                {
                                    storage.WriteAsync(destinationPath, original).Wait();
                                    storage.DeleteAsync(sourceFilepath).Wait();
                                }
                            }
                        }
                    }
                    else if (ErpSettings.EnableFileSystemStorage)
                    {
                        var srcFileName  = Path.GetFileName(sourceFilepath);
                        var destFileName = Path.GetFileName(destinationFilepath);
                        if (srcFileName != destFileName)
                        {
                            var fsSrcFilePath = GetFileSystemPath(srcFile);
                            srcFile.FilePath = destinationFilepath;
                            var fsDestFilePath = GetFileSystemPath(srcFile);
                            File.Move(fsSrcFilePath, fsDestFilePath);
                        }
                    }

                    connection.CommitTransaction();
                    return(Find(destinationFilepath));
                }
                catch
                {
                    connection.RollbackTransaction();
                    throw;
                }
            }
        }
Пример #23
0
        /// <summary>
        /// deletes file
        /// </summary>
        /// <param name="filepath"></param>
        public void Delete(string filepath)
        {
            if (string.IsNullOrWhiteSpace(filepath))
            {
                throw new ArgumentException("filepath cannot be null or empty");
            }

            //all filepaths are lowercase and all starts with folder separator
            filepath = filepath.ToLowerInvariant();
            if (!filepath.StartsWith(FOLDER_SEPARATOR))
            {
                filepath = FOLDER_SEPARATOR + filepath;
            }

            var file = Find(filepath);

            if (file == null)
            {
                return;
            }

            using (var connection = CurrentContext.CreateConnection())
            {
                try
                {
                    connection.BeginTransaction();
                    if (ErpSettings.EnableCloudBlobStorage && file.ObjectId == 0)
                    {
                        var path = GetBlobPath(file);
                        using (IBlobStorage storage = GetBlobStorage())
                        {
                            if (storage.ExistsAsync(path).Result)
                            {
                                storage.DeleteAsync(path).Wait();
                            }
                        }
                    }
                    else if (ErpSettings.EnableFileSystemStorage && file.ObjectId == 0)
                    {
                        var path = GetFileSystemPath(file);
                        if (File.Exists(path))
                        {
                            File.Delete(path);
                        }
                    }
                    else
                    {
                        if (file.ObjectId != 0)
                        {
                            new NpgsqlLargeObjectManager(connection.connection).Unlink(file.ObjectId);
                        }
                    }

                    var command = connection.CreateCommand(@"DELETE FROM files WHERE id = @id");
                    command.Parameters.Add(new NpgsqlParameter("@id", file.Id));
                    command.ExecuteNonQuery();

                    connection.CommitTransaction();
                }
                catch
                {
                    connection.RollbackTransaction();
                    throw;
                }
            }
        }
Пример #24
0
 /// <summary>
 /// Deletes a single blob or a folder recursively.
 /// </summary>
 /// <param name="storage"></param>
 /// <param name="fullPath"></param>
 /// <param name="cancellationToken"></param>
 /// <returns></returns>
 public static Task DeleteAsync(
    this IBlobStorage storage,
    string fullPath, CancellationToken cancellationToken = default)
 {
    return storage.DeleteAsync(new[] {fullPath}, cancellationToken);
 }
Пример #25
0
 public async Task <bool> DeleteAsync(string blobName)
 {
     return(await _blobStorage.DeleteAsync(blobName));
 }
Пример #26
0
 public Task DeleteAsync(IEnumerable <string> fullPaths, CancellationToken cancellationToken = default)
 {
     return(_parent.DeleteAsync(fullPaths, cancellationToken));
 }
Пример #27
0
 public async void DeletePicture(string fileName)
 {
     await _blobStorage.DeleteAsync(fileName, EContainerName.pictures);
 }
Пример #28
0
 public override async ValueTask DeleteAsync(WorkflowStorageContext context, string key, CancellationToken cancellationToken = default)
 {
     var path = GetFullPath(context, key);
     await _blobStorage.DeleteAsync(path, cancellationToken);
 }
Пример #29
0
        public override void Dispose()
        {
            IReadOnlyCollection <BlobId> allFiles = _storage.ListFilesAsync(null).Result;

            _storage.DeleteAsync(allFiles.Select(id => id.FullPath)).Wait();
        }
Пример #30
0
 public virtual Task DeleteAsync(string path, CancellationToken cancellationToken = default)
 {
     return(_blobStorage.DeleteAsync(path, cancellationToken));
 }