コード例 #1
0
        public static void EmptyContainer(CloudBlobContainer container)
        {
            var blobInfos = container.ListBlobs(null, true, BlobListingDetails.None);


            CATFunctions.Print("Deleting old files (" + blobInfos.Count() + ")", true, false);
            CATFunctions.ShowProgress(blobInfos.Count());
            CATFunctions.StartSubProcess("Deleting old files...");



            Parallel.ForEach(blobInfos, (blobInfo) =>
            {
                CloudBlob blob = (CloudBlob)blobInfo;
                blob.Delete();

                CATFunctions.Progress();
                CATFunctions.Print("Deleting blob " + blob.Name);
            });


            CATFunctions.Print("Container is empty", true, true);



            CATFunctions.EndSubProcess();
            CATFunctions.FinishProgress();
        }
コード例 #2
0
        public void Delete <TEntity>(object key) where TEntity : class, new()
        {
            string    relativePath = GetItemPath <TEntity>(key.ToString());
            CloudBlob blob         = _container.GetBlobReference(relativePath);

            blob.Delete();
        }
コード例 #3
0
        /// <summary>
        /// Delete the specified file from the Azure container.
        /// </summary>
        /// <param name="path">the file to be deleted</param>
        public bool DeleteFile(string path)
        {
            if (!IsValidFile(path))
            {
                return(false);
            }

            // convert to azure path
            string blobPath = path.ToAzurePath();

            var container = _container;

            rootFix(ref container, ref blobPath);

            CloudBlob b = container.GetBlobReference(blobPath);

            if (b != null)
            {
                // Need AsyncCallback?
                b.Delete();
            }
            else
            {
                Console.WriteLine("Error: Get blob reference \"{0}\" failed", path);
                return(false);
            }
            return(true);
        }
コード例 #4
0
        public void Delete(string containerName, string fileName)
        {
            CloudBlobContainer container = BlobClient.GetContainerReference(containerName);
            CloudBlob          blob      = container.GetBlobReference(fileName);

            blob.Delete();
        }
コード例 #5
0
        public int Delete(BlobUrl url)
        {
            int itemsDeleted = 0;

            PrepareConnection(url);

            if (url.Kind == BlobUrlKind.Account)
            {
                throw new Exception("Deletion of storage account is not implemented.");
            }
            else if (url.Kind == BlobUrlKind.Container)
            {
                CloudBlobContainer container = this._currentClient.GetContainerReference(url.Url);
                if (container == null)
                {
                    throw new Exception(string.Format("Container '{0}' not found.", url.Url));
                }

                container.Delete();

                itemsDeleted++;
            }
            else if (url.Kind == BlobUrlKind.SubfolderOrBlob)
            {
                CloudBlob blob = this._currentClient.GetBlobReference(url.Url);

                if (blob != null && this.Exists(blob))
                {
                    blob.Delete();
                    itemsDeleted++;
                }
                else
                {
                    CloudBlobContainer container = this._currentClient.GetContainerReference(url.ContainerUrl);
                    if (container == null)
                    {
                        throw new Exception(string.Format("Container '{0}' not found.", url.ContainerUrl));
                    }

                    CloudBlobDirectory dir = container.GetDirectoryReference(url.BlobName);
                    if (dir == null)
                    {
                        throw new Exception("Directory not found. Container Url=" + container.Uri.AbsoluteUri + "; Directory=" + url.BlobName);
                    }

                    var matchedBlobs = dir.ListBlobs(new BlobRequestOptions()
                    {
                        BlobListingDetails = BlobListingDetails.None, UseFlatBlobListing = true
                    });
                    foreach (IListBlobItem listBlobItem in matchedBlobs)
                    {
                        CloudBlockBlob b = container.GetBlockBlobReference(listBlobItem.Uri.AbsoluteUri);
                        b.Delete();
                        itemsDeleted++;
                    }
                }
            }

            return(itemsDeleted);
        }
コード例 #6
0
        /// <summary>
        /// Delete the specified directory from the Azure container.
        /// </summary>
        /// <param name="path">the directory path</param>
        public bool DeleteDirectory(string path)
        {
            if (!IsValidDirectory(path))
            {
                return(false);
            }

            // cannot delete root directory
            if (path == "/")
            {
                return(false);
            }

            var allFiles = _blobClient.ListBlobs(GetFullPath(path), true);

            foreach (var file in allFiles)
            {
                string uri = file.Uri.ToString();

                CloudBlob b = _container.GetBlobReference(uri);
                if (b != null)
                {
                    // Need AsyncCallback?
                    b.Delete();
                }
                else
                {
                    Trace.WriteLine(string.Format("Get blob reference \"{0}\" failed", uri), "Error");
                    return(false);
                }
            }

            return(true);
        }
コード例 #7
0
        public void AddUserToBlob()
        {
            using (TransactionScope ts = new TransactionScope())
            {
                BlobShareDataStoreEntities context = BlobShareDataStoreEntities.CreateInstance();
                Blob blob = BlobServicesTests.CreateBlobForTest("Test Resource", context);
                User user = CreateUserForTest("testuser1", context);
                PermissionService service    = new PermissionService(context);
                Permission        permission = service.GrantPermissionToUserBlob(Privilege.Read, user, blob, DateTime.UtcNow.AddDays(1));

                Assert.IsNotNull(permission);
                Assert.AreEqual(user, permission.Users.First());
                Assert.AreEqual(blob, permission.Blob);
                Assert.AreEqual((int)Privilege.Read, permission.Privilege);

                IEnumerable <Blob> resources = service.GetBlobsByUser(user);

                Assert.IsNotNull(resources);
                Assert.AreEqual(1, resources.Count());
                Assert.AreEqual(blob.BlobId, resources.First().BlobId);

                Assert.IsTrue(service.CheckPermissionToBlob(user.NameIdentifier, user.IdentityProvider, blob.BlobId));

                BlobService blobService = new BlobService(context, CloudStorageAccount.DevelopmentStorageAccount, TestContainerName);
                CloudBlob   cloudBlob   = blobService.GetBlob(blob);
                cloudBlob.Delete();
            }
        }
コード例 #8
0
        // Delete file

        public override bool DeleteFile(String bucket, String file)
        {
            CloudBlobContainer container = this.StorageClient.GetContainerReference(bucket);
            CloudBlob          blob      = container.GetBlobReference(file);

            blob.Delete();

            return(true);
        }
コード例 #9
0
        void CopyFile(CloudBlob blob, string destinationKey, bool deleteSource = false)
        {
            CloudBlob blobCopy = Container.GetBlobReference(destinationKey);

            blobCopy.StartCopy(blob.Uri);
            if (deleteSource)
            {
                blob.Delete();
            }
        }
コード例 #10
0
        /// <summary>
        /// 删除文件
        /// </summary>
        /// <returns></returns>
        public static bool DeleteFile()
        {
            CloudBlob cloudBlob = GetContainer().GetBlobReference("a.txt");

            if (cloudBlob.Exists())
            {
                cloudBlob.Delete();
            }
            return(true);
        }
コード例 #11
0
        public void DeleteBlobById(Guid id)
        {
            var resource = this.context.Blobs.SingleOrDefault(br => br.BlobId == id);

            this.context.Blobs.DeleteObject(resource);
            this.context.SaveChanges();

            CloudBlob blob = this.GetBlob(resource);

            blob.Delete();
        }
コード例 #12
0
        // Called by AzureBlobSyncProvider.DeleteItem to help with removing blobs.
        internal void DeleteFile(
            string name,
            DateTime expectedLastModified
            )
        {
            CloudBlob blob = Container.GetBlobReference(name);

            try
            {
                blob.FetchAttributes();
            }
            catch (StorageClientException e)
            {
                // Someone may have deleted the blob in the mean time
                if (e.ErrorCode == StorageErrorCode.BlobNotFound)
                {
                    throw new ApplicationException("Concurrency Violation", e);
                }
                throw;
            }
            BlobProperties blobProperties = blob.Properties;

            bool isDirectory = bool.Parse(blob.Metadata[AzureBlobStore.IsDirectory]);

            // If this is a directory then we need to look for children.
            if (isDirectory)
            {
                IEnumerable <IListBlobItem> items = Container.ListBlobs();
                if (items.Count() > 0)
                {
                    throw new ApplicationException("Constraint Violation - Directory Not Empty");
                }
            }

            // Specify an optimistic concurrency check to prevent races with other endpoints syncing at the same time.
            BlobRequestOptions opts = new BlobRequestOptions();

            opts.AccessCondition = AccessCondition.IfNotModifiedSince(expectedLastModified);

            try
            {
                blob.Delete(opts);
            }
            catch (StorageClientException e)
            {
                // Someone must have modified the file in the mean time
                if (e.ErrorCode == StorageErrorCode.BlobNotFound || e.ErrorCode == StorageErrorCode.ConditionFailed)
                {
                    throw new ApplicationException("Concurrency Violation", e);
                }
                throw;
            }
        }
コード例 #13
0
        public void CleanupContainer(string containerName)
        {
            foreach (var listItem in client.GetContainerReference(containerName).ListBlobs(null, true, BlobListingDetails.All))
            {
                CloudBlob blob = listItem as CloudBlob;

                if (null != blob)
                {
                    blob.Delete();
                }
            }
        }
コード例 #14
0
        /// <summary>
        /// Validate the delete permission in the sas token for the the specified blob
        /// </summary>
        internal void ValidateBlobDeleteableWithSasToken(CloudBlob cloudBlob, string sasToken)
        {
            Test.Info("Verify blob delete permission");
            if (!cloudBlob.Exists())
            {
                cloudBlob = CreateRandomBlob(cloudBlob.Container, cloudBlob.Name, cloudBlob.Properties.BlobType);
            }
            CloudBlob sasBlob = GetCloudBlobBySasToken(cloudBlob, sasToken);

            sasBlob.Delete();
            Test.Assert(!cloudBlob.Exists(), "The blob should not exist after deleting with sas token");
        }
コード例 #15
0
ファイル: BlobFuService.cs プロジェクト: jalchr/BlobFu
        public bool DeleteBlob(string container, string fileName)
        {
            if (!ContainerExists(container))
            {
                return(false);
            }
            VerifyContainer(container);
            CloudBlob blob = this._container.GetBlobReference(fileName);

            blob.Delete();
            return(true);
        }
コード例 #16
0
ファイル: BlobLibrary.cs プロジェクト: valkiria88/Astoria
        public static void deleteBlob(string containerName, string blobName)
        {
            char[]             slash         = { '/' };
            string             baseUri       = "";
            CloudBlobContainer blobContainer = initContainer(containerName, ref baseUri);

            if (!Exists(blobContainer))
            {
                return;
            }


            CloudBlob blob = blobContainer.GetBlobReference(blobName);

            blob.Delete();
        }
コード例 #17
0
        public ActionResult DeleteFileFromBlob(string id)
        {
            MemoryStream ms = new MemoryStream();

            //CloudStorageAccount storageAccount = CloudStorageAccount.Parse("xxxxx");
            StorageCredentials  storageCredentials  = new StorageCredentials(singleton.storageAccountName, singleton.keyOne);
            CloudStorageAccount cloudStorageAccount = new CloudStorageAccount(storageCredentials, true);
            CloudBlobClient     BlobClient          = cloudStorageAccount.CreateCloudBlobClient();
            CloudBlobContainer  c1 = BlobClient.GetContainerReference("userstorage");

            if (c1.Exists())
            {
                CloudBlob file = c1.GetBlobReference(id);
                file.Delete();
            }

            return(Redirect("/FileStorage/Index/"));
        }
コード例 #18
0
        private void DeleteBlobToolStripMenuItemClick(object sender, EventArgs e)
        {
            var blobNode = currentNode as BlobTreeNode;

            if (blobNode == null)
            {
                return;
            }

            // Delete blob...

            CloudBlobClient    blobClient   = storageAccount.CreateCloudBlobClient();
            CloudBlobContainer containerRef = blobClient.GetContainerReference(blobNode.Blob.Container.Name);
            CloudBlob          blobRef      = containerRef.GetBlobReference(blobNode.Blob.Name);

            blobRef.Delete();
            blobNode.Remove();
        }
コード例 #19
0
        /// <summary>
        /// Delete the specified directory from the Azure container.
        /// </summary>
        /// <param name="path">the directory path</param>
        public bool DeleteDirectory(string path)
        {
            if (!IsValidDirectory(path))
            {
                return(false);
            }

            // cannot delete root directory
            if (path == "/")
            {
                return(false);
            }

            IEnumerable <IListBlobItem> allFiles = _blobClient.ListBlobs(GetFullPath(path), true);

            foreach (var file in allFiles)
            {
                string uri = file.Uri.ToString();

                CloudBlob b = _container.GetBlobReference(uri);
                if (b != null)
                {
                    // Need AsyncCallback?
                    try
                    {
                        if (b.Exists())
                        {
                            b.Delete(); // this have shown syntoms of crashing
                        }
                    }
                    catch (Exception ex)
                    {
                        Trace.TraceError(string.Format("Exception while DeleteDirectory {0}\r\n{1}", uri, ex));
                    }
                }
                else
                {
                    Trace.WriteLine(string.Format("Get blob reference \"{0}\" failed", uri), "Error");
                    return(false);
                }
            }

            return(true);
        }
コード例 #20
0
        public ActionResult DeleteFileFromBlob(string id)
        {
            MemoryStream ms = new MemoryStream();

            //CloudStorageAccount storageAccount = CloudStorageAccount.Parse("xxxxx");
            StorageCredentials  storageCredentials  = new StorageCredentials(singleton.storageAccountName, singleton.keyOne);
            CloudStorageAccount cloudStorageAccount = new CloudStorageAccount(storageCredentials, true);
            CloudBlobClient     BlobClient          = cloudStorageAccount.CreateCloudBlobClient();
            CloudBlobContainer  c1 = BlobClient.GetContainerReference("project");

            if (c1.Exists())
            {
                CloudBlob file = c1.GetBlobReference(id);
                file.Delete();
            }
            int sessionData = (int)Session["id"];

            return(Redirect("/Project/Edit/" + sessionData));
        }
コード例 #21
0
        private void ProcessQueue()
        {
            while (true)
            {
                CloudQueueMessage msg = this.inqueue.GetMessage();

                if (msg == null)
                {
                    Thread.Sleep(500);
                }
                else
                {
                    string       blobname = msg.AsString;
                    CloudBlob    blob     = this.blobContainer.GetBlobReference(blobname);
                    MemoryStream stream   = new MemoryStream();
                    blob.DownloadToStream(stream);
                    blob.Delete();
                    this.inqueue.DeleteMessage(msg);

                    string[] parameters = blobname.Split('.');
                    Guid     id         = new Guid(parameters[0]);
                    int      fromx      = Int32.Parse(parameters[1]);
                    int      fromy      = Int32.Parse(parameters[2]);
                    int      width      = Int32.Parse(parameters[3]);
                    int      height     = Int32.Parse(parameters[4]);

                    int[] values = new int[width * height];

                    stream.Seek(0, SeekOrigin.Begin);

                    BinaryReader reader = new BinaryReader(stream);

                    for (int k = 0; k < values.Length; k++)
                    {
                        values[k] = reader.ReadInt32();
                    }

                    stream.Close();

                    this.Invoke((Action <int, int, int, int, int[]>)((x, y, h, w, v) => this.DrawValues(x, y, h, w, v)), fromx, fromy, width, height, values);
                }
            }
        }
コード例 #22
0
ファイル: BlobHelper.cs プロジェクト: cristi1955/2018_Exemple
        // Delete a blob.
        // Return true on success, false if unable to create, throw exception on error.

        public bool DeleteBlob(string containerName, string blobName)
        {
            try
            {
                CloudBlobContainer container = BlobClient.GetContainerReference(containerName);
                CloudBlob          blob      = container.GetBlobReference(blobName);
                blob.Delete();
                return(true);
            }
            catch (StorageClientException ex)
            {
                if ((int)ex.StatusCode == 404)
                {
                    return(false);
                }

                throw;
            }
        }
コード例 #23
0
ファイル: StorageAzure.cs プロジェクト: melnx/Bermuda
        /// <summary>
        /// delete a blob from a container in azure
        /// </summary>
        /// <param name="PathName"></param>
        /// <param name="FileName"></param>
        /// <returns></returns>
        public bool DeleteFile(string PathName, string FileName)
        {
            try
            {
                CloudStorageAccount storageAccount = CloudStorageAccount.Parse(ConfigurationManager.AppSettings["StorageAccount"]);
                CloudBlobClient     blobClient     = storageAccount.CreateCloudBlobClient();
                CloudBlobContainer  container      = blobClient.GetContainerReference(PathName);
                container.CreateIfNotExist();
                CloudBlob blob = container.GetBlobReference(FileName);
                blob.Delete();

                return(true);
            }
            catch (Exception ex)
            {
                Trace.WriteLine(ex.ToString());
            }
            return(false);
        }
コード例 #24
0
ファイル: StorageHelper.cs プロジェクト: yarivat/Admin
        private void DeleteOld(CloudBlobContainer cloudBlobContainer, string blobName, int total)
        {
            IEnumerable <IListBlobItem> blobItems = cloudBlobContainer.ListBlobs();

            SortedDictionary <long, CloudBlob> verBlobs = GetVerBlobs(cloudBlobContainer, blobItems);

            if (verBlobs.Count <= total)
            {
                return;
            }

            CloudBlob[] blobs = verBlobs.Values.ToArray();
            for (long i = 0; i < blobs.Length - 1; i++)
            {
                if (blobs.Length - i > total)
                {
                    CloudBlob blob = blobs[i];
                    blob.Delete();
                }
            }
        }
コード例 #25
0
ファイル: BaseBlob.cs プロジェクト: xuedong/Tigwi
        public bool TryDelete()
        {
            if (blob.Attributes.Properties.ETag == null)
            {
                throw new EtagNotSet();
            }

            BlobRequestOptions reqOpt = new BlobRequestOptions();

            reqOpt.AccessCondition = AccessCondition.IfMatch(blob.Attributes.Properties.ETag);

            try
            {
                blob.Delete(reqOpt);
                return(true);
            }
            catch
            {
                return(false);
            }
        }
コード例 #26
0
        /// <summary>
        /// Renames the specified object by copying the original to a new path and deleting the original.
        /// </summary>
        /// <param name="originalPath">The original path.</param>
        /// <param name="newPath">The new path.</param>
        /// <returns></returns>
        public StorageOperationResult Rename(string originalPath, string newPath)
        {
            var u = new Uri(newPath, UriKind.RelativeOrAbsolute);
            CloudBlobContainer c = GetContainerReference(ContainerName);

            newPath = UriPathToString(u);
            if (newPath.StartsWith("/"))
            {
                newPath = newPath.Remove(0, 1);
            }

            originalPath = UriPathToString(new Uri(originalPath, UriKind.RelativeOrAbsolute));
            if (originalPath.StartsWith("/"))
            {
                originalPath = originalPath.Remove(0, 1);
            }

            CloudBlob newBlob      = c.GetBlobReference(newPath);
            CloudBlob originalBlob = c.GetBlobReference(originalPath);

            // Check if the original path exists on the provider.
            if (!CheckBlobExists(originalPath))
            {
                throw new FileNotFoundException("The path supplied does not exist on the storage provider.",
                                                originalPath);
            }

            newBlob.CopyFromBlob(originalBlob);

            try
            {
                newBlob.FetchAttributes();
                originalBlob.Delete();
                return(StorageOperationResult.Completed);
            }
            catch (StorageClientException e)
            {
                throw;
            }
        }
コード例 #27
0
        /// <summary>
        /// Removes the item, ensuring that the specified condition is met.
        /// </summary>
        public void Delete()
        {
            try
            {
                _blob.Delete();
            }
            catch (StorageClientException ex)
            {
                switch (ex.ErrorCode)
                {
                case StorageErrorCode.ContainerNotFound:
                    throw StreamErrors.ContainerNotFound(this, ex);

                case StorageErrorCode.BlobNotFound:
                case StorageErrorCode.ConditionFailed:
                    return;

                default:
                    throw;
                }
            }
        }
コード例 #28
0
        public void UploadBlob()
        {
            using (TransactionScope ts = new TransactionScope())
            {
                var service = new BlobService(CloudStorageAccount.DevelopmentStorageAccount, TestContainerName);

                var blob = new Blob()
                {
                    Name             = "Test Resource",
                    OriginalFileName = "logo-dpe.png",
                    Description      = "Test Resource",
                    UploadDateTime   = DateTime.Now
                };

                Stream stream = new FileStream("logo-dpe.png", FileMode.Open, FileAccess.Read);

                service.UploadBlob(blob, stream);

                Assert.IsNotNull(blob.BlobId);
                Assert.AreNotEqual(Guid.Empty, blob.BlobId);

                Blob newBlob = service.GetBlobById(blob.BlobId);

                Assert.IsNotNull(newBlob);
                Assert.AreEqual(blob.BlobId, newBlob.BlobId);
                Assert.AreEqual(blob.Description, newBlob.Description);
                Assert.AreEqual(blob.OriginalFileName, newBlob.OriginalFileName);
                Assert.AreEqual(blob.UploadDateTime.ToString(), newBlob.UploadDateTime.ToString());

                var resources = service.GetBlobs();

                Assert.IsNotNull(resources);
                Assert.IsTrue(resources.Count() >= 1);
                Assert.IsNotNull(resources.Where(r => r.BlobId == newBlob.BlobId).FirstOrDefault());

                CloudBlob cloudBlob = service.GetBlob(newBlob);
                cloudBlob.Delete();
            }
        }
コード例 #29
0
        public void BreakBlobLeaseWithDurationShorterThanRemainingTime()
        {
            string             containerName = Utility.GenNameString("container");
            string             blobName      = Utility.GenNameString("blob");
            int                leaseDuration = 30;
            int                breakDuration = 5;
            int                remainingTime = breakDuration;
            CloudBlobContainer container     = blobUtil.CreateContainer(containerName);

            try
            {
                CloudBlob blob = blobUtil.CreateRandomBlob(container, blobName);

                Test.Assert(CommandAgent.AcquireLease(containerName, blobName, duration: leaseDuration), Utility.GenComparisonData("Acquire Blob Lease", true));

                if (lang == Language.NodeJS)
                {
                    try
                    {
                        Test.Assert(CommandAgent.BreakLease(containerName, blobName, breakDuration), Utility.GenComparisonData("Break Blob Lease", true));

                        remainingTime = int.Parse((CommandAgent as NodeJSAgent).Output[0]["time"].ToString());
                        Test.Assert(remainingTime <= breakDuration, Utility.GenComparisonData("Validate remaining time", true));
                    }
                    catch (Exception e)
                    {
                        Test.Error(string.Format("{0} error: {1}", MethodBase.GetCurrentMethod().Name, e.Message));
                    }
                }

                Thread.Sleep((remainingTime + 1) * 1000);
                blob.Delete();
            }
            finally
            {
                blobUtil.RemoveContainer(containerName);
            }
        }
コード例 #30
0
        /// <summary>
        /// Expect sas token has the delete permission for the specified container.
        /// </summary>
        internal void ValidateContainerDeleteableWithSasToken(CloudBlobContainer container, string sastoken)
        {
            Test.Info("Verify container delete permission");
            List <CloudBlob>    randomBlobs   = CreateRandomBlob(container);
            CloudBlob           blob          = randomBlobs[0];
            CloudStorageAccount sasAccount    = TestBase.GetStorageAccountWithSasToken(container.ServiceClient.Credentials.AccountName, sastoken);
            CloudBlobClient     sasBlobClient = sasAccount.CreateCloudBlobClient();
            CloudBlobContainer  sasContainer  = sasBlobClient.GetContainerReference(container.Name);

            CloudBlob sasBlob = null;

            if (blob.BlobType == StorageBlobType.BlockBlob)
            {
                sasBlob = sasContainer.GetBlockBlobReference(blob.Name);
            }
            else
            {
                sasBlob = sasContainer.GetPageBlobReference(blob.Name);
            }

            sasBlob.Delete();
            Test.Assert(!blob.Exists(), "blob should not exist");
        }