コード例 #1
0
        public static void ModifyDataJson3()
        {
            var cloudStorage = Microsoft.WindowsAzure.Storage.CloudStorageAccount.Parse(connsctionString);

            var cloudBlobClient       = cloudStorage.CreateCloudBlobClient();
            var cloudBlobContainer    = cloudBlobClient.GetContainerReference("donmablogsample");
            var resultCreateContainer = cloudBlobContainer.CreateIfNotExistsAsync().Result;

            if (resultCreateContainer)
            {
                Console.WriteLine("donmablogsample create already.");
            }


            Microsoft.WindowsAzure.Storage.Blob.CloudBlobDirectory cloudBlobDirectory =
                cloudBlobContainer.GetDirectoryReference("TEST2/TEST21/");



            var bbReference = cloudBlobDirectory.GetBlockBlobReference("sampleText3.json");

            var bFileInfo = cloudBlobDirectory.GetBlockBlobReference("sampleText3.json");

            bFileInfo.Properties.ContentType = "application/json; charset=utf-8";
            bFileInfo.UploadTextAsync("{\"data\":\"測試資料快照後修改\"}").GetAwaiter().GetResult();


            Console.Write("Success Change Data.");
        }
コード例 #2
0
        public static void CreateSnapshot()
        {
            var cloudStorage = Microsoft.WindowsAzure.Storage.CloudStorageAccount.Parse(connsctionString);

            var cloudBlobClient       = cloudStorage.CreateCloudBlobClient();
            var cloudBlobContainer    = cloudBlobClient.GetContainerReference("donmablogsample");
            var resultCreateContainer = cloudBlobContainer.CreateIfNotExistsAsync().Result;

            if (resultCreateContainer)
            {
                Console.WriteLine("donmablogsample create already.");
            }


            Microsoft.WindowsAzure.Storage.Blob.CloudBlobDirectory cloudBlobDirectory =
                cloudBlobContainer.GetDirectoryReference("TEST2/TEST21/");


            for (var i = 1; i <= 10; i++)
            {
                var bFileInfo = cloudBlobDirectory.GetBlockBlobReference("sampleText3.json");

                bFileInfo.Properties.ContentType = "application/json; charset=utf-8";
                bFileInfo.UploadTextAsync("{\"data\":\"測試資料修改" + i + "\"}").GetAwaiter().GetResult();
                var meta = new Dictionary <string, string>();
                meta.Add("tag", i.ToString());
                var result = bFileInfo.CreateSnapshotAsync(meta, null, null, null).Result;
            }

            Console.Write("Success");
        }
コード例 #3
0
        public static void CheckDataJson3Content()
        {
            var cloudStorage = Microsoft.WindowsAzure.Storage.CloudStorageAccount.Parse(connsctionString);

            var cloudBlobClient       = cloudStorage.CreateCloudBlobClient();
            var cloudBlobContainer    = cloudBlobClient.GetContainerReference("donmablogsample");
            var resultCreateContainer = cloudBlobContainer.CreateIfNotExistsAsync().Result;

            if (resultCreateContainer)
            {
                Console.WriteLine("donmablogsample create already.");
            }


            Microsoft.WindowsAzure.Storage.Blob.CloudBlobDirectory cloudBlobDirectory =
                cloudBlobContainer.GetDirectoryReference("TEST2/TEST21/");

            Console.WriteLine("Get File Content : TEST2/TEST21/sampleText3.json");

            var result = cloudBlobDirectory.GetBlockBlobReference("sampleText3.json").DownloadTextAsync().Result;

            Console.WriteLine("TEST2/TEST21/sampleText3.json content =>" + result);

            Console.WriteLine("IsSnapShot =>" + cloudBlobDirectory.GetBlockBlobReference("sampleText3.json").IsSnapshot);
        }
コード例 #4
0
        public static void GetFileUri()
        {
            var cloudStorage = Microsoft.WindowsAzure.Storage.CloudStorageAccount.Parse(connsctionString);

            var cloudBlobClient       = cloudStorage.CreateCloudBlobClient();
            var cloudBlobContainer    = cloudBlobClient.GetContainerReference("donmablogsample");
            var resultCreateContainer = cloudBlobContainer.CreateIfNotExistsAsync().Result;

            Console.WriteLine("donmablogsample create already.");

            // 設定可以開啟 60 秒,並且此簽章只能夠讀取
            var sharedPolicy = new Microsoft.WindowsAzure.Storage.Blob.SharedAccessBlobPolicy()
            {
                SharedAccessExpiryTime = DateTime.UtcNow.AddSeconds(60),
                Permissions            = Microsoft.WindowsAzure.Storage.Blob.SharedAccessBlobPermissions.Read,
            };


            var sasContainerToken = cloudBlobContainer.GetSharedAccessSignature(sharedPolicy, null);

            Microsoft.WindowsAzure.Storage.Blob.CloudBlobDirectory cloudBlobDirectory =
                cloudBlobContainer.GetDirectoryReference("TEST2/TEST21/");
            var uri = cloudBlobDirectory.GetBlockBlobReference("sampleText9.json").Uri;


            Console.WriteLine("TEST2/TEST21/sampleText9.json Download Uri =>" + uri + sasContainerToken);

            //這一行非必要 ,呼叫系統瀏覽器開始網址而已
            System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo("cmd", $"/c start " + uri + sasContainerToken.Replace("&", "^&"))
            {
                CreateNoWindow = true
            });
        }
コード例 #5
0
        public IEnumerable<PhotoMapModel> GetMapInfoList(System.Security.Principal.IPrincipal User) {
            List<PhotoMapModel> L_bStroage = new List<PhotoMapModel>();
            int idx = 0;
            DateTime dt = DateTime.Now;
            float lat = 37.5651f;
            float lng = 126.98955f;

            if(User.Identity.GetUserId() != null) {
                directory = container.GetDirectoryReference(User.Identity.GetUserId());
            } else {
                directory = container.GetDirectoryReference("sample");
            }

            foreach (IListBlobItem item in directory.ListBlobs(false, BlobListingDetails.Metadata)) {
                if (item.GetType() == typeof(CloudBlockBlob)) {
                    CloudBlockBlob blob = (CloudBlockBlob)item;
                    PhotoMapModel bStorage = new PhotoMapModel() {
                        idx = idx,
                        ContentType = blob.Properties.ContentType,
                        F_Size = blob.Properties.Length,
                        F_Name = blob.Name,
                        F_OrgName = GetBlobMetadata(blob, "orgName")?.ToString(), //blob.Metadata["OrgName"] ?? "";
                        F_Url = blob.Uri,
                        PicDate = DateTime.TryParse(GetBlobMetadata(blob, "Date")?.ToString(), out dt) ? DateTime.Parse(blob.Metadata["Date"]) : dt,
                        F_Latitude = float.TryParse(GetBlobMetadata(blob, "lat")?.ToString(), out lat) ? (float?)float.Parse(blob.Metadata["lat"]) : lat,
                        F_Longitude = float.TryParse(GetBlobMetadata(blob, "lng")?.ToString(), out lng) ? (float?)float.Parse(blob.Metadata["lng"]) : lng
                    };
                    idx++;                    
                    L_bStroage.Add(bStorage);
                }
            }

            return L_bStroage;
        }
コード例 #6
0
        public AzureStorage(CloudBlobDirectory directory, Uri baseAddress)
            : base(baseAddress)
        {
            _directory = directory;

            ResetStatistics();
        }
コード例 #7
0
        private BlobResultSegment GetNextHeartbeats(CloudBlobDirectory directory, BlobContinuationToken currentToken)
        {
            const int batchSize = 100;

            try
            {
                return directory.ListBlobsSegmented(useFlatBlobListing: true,
                    blobListingDetails: BlobListingDetails.None,
                    maxResults: batchSize,
                    currentToken: currentToken,
                    options: null,
                    operationContext: null);
            }
            catch (StorageException exception)
            {
                if (exception.IsNotFound())
                {
                    return null;
                }
                else
                {
                    throw;
                }
            }
        }
コード例 #8
0
        public static void GetFileInfo()
        {
            var cloudStorage = Microsoft.WindowsAzure.Storage.CloudStorageAccount.Parse(connsctionString);

            var cloudBlobClient       = cloudStorage.CreateCloudBlobClient();
            var cloudBlobContainer    = cloudBlobClient.GetContainerReference("donmablogsample");
            var resultCreateContainer = cloudBlobContainer.CreateIfNotExistsAsync().Result;


            Console.WriteLine("donmablogsample create already.");



            Microsoft.WindowsAzure.Storage.Blob.CloudBlobDirectory cloudBlobDirectory =
                cloudBlobContainer.GetDirectoryReference("TEST2/TEST21/IMAGES/");

            Console.WriteLine("Get File Content : TEST2/TEST21/IMAGES/hamimelon.jpg");

            var blockReference = cloudBlobDirectory.GetBlockBlobReference("hamimelon.jpg");

            blockReference.FetchAttributesAsync().GetAwaiter().GetResult();

            Console.WriteLine(" TEST2/TEST21/IMAGES/hamimelon.jpg Size =>" + blockReference.Properties.Length.ToString("#,##0") + "bytes");
            Console.WriteLine(" TEST2/TEST21/IMAGES/hamimelon.jpg ContentType =>" + blockReference.Properties.ContentType);
            Console.WriteLine(" TEST2/TEST21/IMAGES/hamimelon.jpg Created =>" + blockReference.Properties.Created.Value.ToString("yyyy-MM-dd HH:mm:ss"));
            Console.WriteLine(" TEST2/TEST21/IMAGES/hamimelon.jpg LastModified =>" + blockReference.Properties.LastModified.Value.ToString("yyyy-MM-dd HH:mm:ss"));
        }
コード例 #9
0
        public static void ListAllFilesFromDirectory()
        {
            var cloudStorage = Microsoft.WindowsAzure.Storage.CloudStorageAccount.Parse(connsctionString);

            var cloudBlobClient       = cloudStorage.CreateCloudBlobClient();
            var cloudBlobContainer    = cloudBlobClient.GetContainerReference("donmablogsample");
            var resultCreateContainer = cloudBlobContainer.CreateIfNotExistsAsync().Result;

            Console.WriteLine("donmablogsample create already.");


            Microsoft.WindowsAzure.Storage.Blob.CloudBlobDirectory cloudBlobDirectory =
                cloudBlobContainer.GetDirectoryReference("TEST2/TEST21/");

            var res = new List <string>();

            //這種方法在 Azure Storge 包括 table 很常使用
            Microsoft.WindowsAzure.Storage.Blob.BlobContinuationToken continuationToken = null;
            do
            {
                var listingResult = cloudBlobDirectory.ListBlobsSegmentedAsync(continuationToken).Result;
                continuationToken = listingResult.ContinuationToken;
                res.AddRange(listingResult.Results.Select(x => System.IO.Path.GetFileName(x.Uri.AbsolutePath)).ToList());
            }while (continuationToken != null);

            Console.WriteLine("Result: " + string.Join("\r\n", res));
        }
コード例 #10
0
 static Uri GetDirectoryUri(CloudBlobDirectory directory)
 {
     return new UriBuilder(directory.Uri)
     {
         Scheme = "http", // Convert base address to http. 'https' can be used for communication but is not part of the names.
         Port = 80
     }.Uri;
 }
コード例 #11
0
 public AzureStorageDirectory(CloudBlobContainer container, CloudBlobDirectory directory)
 {
     _container = container;
     _directory = directory;
     Uri = directory != null ? directory.Uri : container.Uri;
     Name = directory != null
                ? directory.Uri.Segments[directory.Uri.Segments.Length - 1]
                : container.Name;
 }
        /// <summary>
        /// Initializes a new instance of the <see cref="AzureBlobDirectoryLocation"/> class.
        /// </summary>
        /// <param name="blobDir">CloudBlobDirectory instance as a location in a transfer job.
        /// It could be a source, a destination.</param>
        public AzureBlobDirectoryLocation(CloudBlobDirectory blobDir)
        {
            if (null == blobDir)
            {
                throw new ArgumentNullException("blobDir");
            }

            this.blobDirectorySerializer = new SerializableCloudBlobDirectory(blobDir);
        }
コード例 #13
0
        private HostVersionReader(CloudBlobDirectory directory)
        {
            if (directory == null)
            {
                throw new ArgumentNullException("directory");
            }

            _directory = directory;
        }
コード例 #14
0
        public FunctionInstanceLookup(CloudBlobDirectory directory)
        {
            if (directory == null)
            {
                throw new ArgumentNullException("directory");
            }

            _directory = directory;
        }
コード例 #15
0
        //public String Text;

        public LogFolder(CloudBlobContainer DeploymentContainer, string folder)
        {
            Text = "";

            _server_ref = DeploymentContainer.GetDirectoryReference(folder);

           // Start();

        }
コード例 #16
0
        static Uri GetDirectoryUri(CloudBlobDirectory directory)
        {
            Uri uri = new UriBuilder(directory.Uri)
            {
                Scheme = "http",
                Port = 80
            }.Uri;

            return uri;
        }
コード例 #17
0
        /// <summary>
        /// Converting Windows Azure Blob Storage Directory Model to FileObject.
        /// </summary>
        /// <param name="directory">Blob Storage Directory</param>
        /// <returns>POJO FileObject</returns>
        public static FileObject ConvertToFileObject(CloudBlobDirectory directory)
        {
            string id = directory.Prefix;
            string name = ParseHelper.ParseName(id);
            double size = 0;
            FileObject.FileObjectType type = FileObject.FileObjectType.FOLDER;
            string extension = "";
            string updateAt = "";

            return new FileObject(id, name, size, type, extension, updateAt);
        }
コード例 #18
0
        public static void RecovertDataJson3()
        {
            var cloudStorage = Microsoft.WindowsAzure.Storage.CloudStorageAccount.Parse(connsctionString);

            var cloudBlobClient    = cloudStorage.CreateCloudBlobClient();
            var cloudBlobContainer = cloudBlobClient.GetContainerReference("donmablogsample");

            //建立如果不存在的話
            var resultCreateContainer = cloudBlobContainer.CreateIfNotExistsAsync().Result;

            Console.WriteLine("donmablogsample create already.");
            Microsoft.WindowsAzure.Storage.Blob.CloudBlobDirectory cloudBlobDirectory =
                cloudBlobContainer.GetDirectoryReference("TEST2/TEST21/");

            var bbReference = cloudBlobDirectory.GetBlockBlobReference("sampleText3.json");


            var res = new List <CloudBlockBlob>();

            Microsoft.WindowsAzure.Storage.Blob.BlobContinuationToken continuationToken = null;
            do
            {
                //只看 TEST2/TEST21/sampleText3.json 的快照
                var listingResult = cloudBlobContainer.ListBlobsSegmentedAsync("TEST2/TEST21/sampleText3.json", true, Microsoft.WindowsAzure.Storage.Blob.BlobListingDetails.Snapshots, 100, continuationToken, null, new Microsoft.WindowsAzure.Storage.OperationContext
                {
                }).Result;
                continuationToken = listingResult.ContinuationToken;
                res.AddRange(listingResult.Results.Select(x => (x as Microsoft.WindowsAzure.Storage.Blob.CloudBlockBlob)).ToList());
            }while (continuationToken != null);

            foreach (var r in res)
            {
                r.FetchAttributesAsync().GetAwaiter().GetResult();
                Console.WriteLine("Meta-tag:" + (r.Metadata.ContainsKey("tag") ? (r.Metadata["tag"]) : "") + "," + r.DownloadTextAsync().Result + ";" + " IsSnapShot:" + r.IsSnapshot);
            }

            //Recovery from tag:9
            //還原 tag 9 的快照
            var bFileInfo = cloudBlobDirectory.GetBlockBlobReference("sampleText3.json");

            foreach (var r in res)
            {
                if (r.IsSnapshot && r.Metadata.ContainsKey("tag"))
                {
                    if (r.Metadata["tag"] == "9")
                    {
                        var copyResult = bFileInfo.StartCopyAsync(r).Result;

                        Console.WriteLine("Copy Result:" + copyResult);
                    }
                }
            }
        }
コード例 #19
0
        static void DeleteBlobDirectory(CloudBlobDirectory blobDirectory)
        {
            foreach(var blobItem in blobDirectory.ListBlobs())
            {
                var subDirectory = blobItem as CloudBlobDirectory;
                if (subDirectory != null)
                    DeleteBlobDirectory(subDirectory);

                var blob = blobItem as ICloudBlob;
                if (blob != null)
                    blob.Delete();
            }
        }
コード例 #20
0
ファイル: Biz.cs プロジェクト: adrienbuffet/3NETCourse
 private static void ListBlobsOfDirectory(CloudBlobDirectory directory)
 {
     var listOfObjects = directory.ListBlobs();
     foreach (var obj in listOfObjects)
     {
         var type = obj.GetType();
         if (type == typeof(CloudBlockBlob))
         {
             Trace.TraceInformation(obj.Uri.ToString());
         }
         else if (type == typeof(CloudBlobDirectory))
         {
             ListBlobsOfDirectory((CloudBlobDirectory)obj);
         }
     }
 }
コード例 #21
0
        private static void DeleteAllBlobsDir(CloudBlobDirectory cloudBlobDirectory)
        {
            foreach (var blob in cloudBlobDirectory.ListBlobs())
            {
                var blockBlob = blob as CloudBlockBlob;
                if (blockBlob != null)
                {
                    blockBlob.DeleteIfExists();
                }

                var directory = blob as CloudBlobDirectory;
                if (directory != null)
                {
                    DeleteAllBlobsDir(directory);
                }
            }
        }
コード例 #22
0
        public AzureStorage(CloudBlobDirectory directory, Uri baseAddress)
            : base(baseAddress ?? GetDirectoryUri(directory))
        {
            _directory = directory;

            if (_directory.Container.CreateIfNotExists())
            {
                _directory.Container.SetPermissions(new BlobContainerPermissions { PublicAccess = BlobContainerPublicAccessType.Blob });

                if (Verbose)
                {
                    Trace.WriteLine(String.Format("Created '{0}' publish container", _directory.Container.Name));
                }
            }

            ResetStatistics();
        }
コード例 #23
0
ファイル: BlobManager.cs プロジェクト: sergiote/Extensions
        /// <summary>
        /// Devuelve todos los archivos contenidos en un directorio de manera recursiva o no
        /// </summary>
        /// <param name="blobDirectory"></param>
        /// <param name="isRecursive"></param>
        /// <returns></returns>
        public static IEnumerable<CloudBlockBlob> GetFilesFrom(CloudBlobDirectory blobDirectory, bool isRecursive)
        {
            foreach (var blob in blobDirectory.ListBlobs().OfType<CloudBlockBlob>())
            {
                yield return blob;
            }

            if (isRecursive == false)
                yield break;

            foreach (var blob in blobDirectory.ListBlobs().OfType<CloudBlobDirectory>())
            {
                foreach (var innerBlob in GetFilesFrom(blob, true))
                {
                    yield return innerBlob;
                }
            }
        }
コード例 #24
0
        public AzureBlobContentProvider(string connectionString, string basePath, ICacheManager<object> cacheManager)
        {
            _cacheManager = cacheManager;
            var parts = basePath.Split(new[] { "/", "\\" }, StringSplitOptions.RemoveEmptyEntries);

            _containerName = parts.FirstOrDefault();
            _baseDirectoryPath = string.Join("/", parts.Skip(1));

            if (!CloudStorageAccount.TryParse(connectionString, out _cloudStorageAccount))
            {
                throw new InvalidOperationException("Failed to get valid connection string");
            }
            _cloudBlobClient = _cloudStorageAccount.CreateCloudBlobClient();
            _container = _cloudBlobClient.GetContainerReference(_containerName);
            if (_baseDirectoryPath != null)
            {
                _directory = _container.GetDirectoryReference(_baseDirectoryPath);
            }
        }
コード例 #25
0
        public static void CheckFileExisted()
        {
            var cloudStorage = Microsoft.WindowsAzure.Storage.CloudStorageAccount.Parse(connsctionString);

            var cloudBlobClient       = cloudStorage.CreateCloudBlobClient();
            var cloudBlobContainer    = cloudBlobClient.GetContainerReference("donmablogsample");
            var resultCreateContainer = cloudBlobContainer.CreateIfNotExistsAsync().Result;

            Console.WriteLine("donmablogsample create already.");


            Microsoft.WindowsAzure.Storage.Blob.CloudBlobDirectory cloudBlobDirectory =
                cloudBlobContainer.GetDirectoryReference("TEST2/TEST21/");

            //Existed : true
            Console.WriteLine("TEST2/TEST21/sampleText1.json is Existed =>" + cloudBlobDirectory.GetBlockBlobReference("sampleText1.json").ExistsAsync().Result);

            //Existed : false
            Console.WriteLine("TEST2/TEST21/FileNotExisted.json is Existed =>" + cloudBlobDirectory.GetBlockBlobReference("FileNotExisted.json").ExistsAsync().Result);
        }
コード例 #26
0
ファイル: DeleteFile.cs プロジェクト: hangmiao/DBLike
        // delete folders
        public void deleteFolder(CloudBlobContainer container, CloudBlobDirectory tempDir)
        {
            try
            {
                IEnumerable<IListBlobItem> blobs = tempDir.ListBlobs();

                foreach (IListBlobItem item in blobs)
                {

                    // for items in subdirecories
                    // parent directory doesn't need this
                    if (item.GetType() == typeof(CloudBlockBlob))
                    {
                        CloudBlockBlob blob = (CloudBlockBlob)item;
                        //blob.Delete();
                        blob.DeleteIfExists(DeleteSnapshotsOption.IncludeSnapshots);

                    }
                    else if (item.GetType() == typeof(CloudPageBlob))
                    {
                        CloudPageBlob blob = (CloudPageBlob)item;
                        blob.DeleteIfExists(DeleteSnapshotsOption.IncludeSnapshots);
                    }
                    //else if (item.GetType() == typeof(CloudBlobDirectory))
                    //{
                    //    CloudBlobDirectory blob = (CloudBlobDirectory)item;
                    //    blob.
                    //}
                    else
                    {
                        // delete folders recursively
                        CloudBlobDirectory blobDir = (CloudBlobDirectory)item;
                        deleteFolder(container, blobDir);
                    }
                }
            }
            catch
            {
                throw;
            }
        }
コード例 #27
0
        private FunctionIndexReader(CloudBlobDirectory functionsDirectory, CloudBlobDirectory versionDirectory,
            IVersionMetadataMapper versionMapper)
        {
            if (functionsDirectory == null)
            {
                throw new ArgumentNullException("functionsDirectory");
            }
            else if (versionDirectory == null)
            {
                throw new ArgumentNullException("versionDirectory");
            }
            else if (versionMapper == null)
            {
                throw new ArgumentNullException("versionMapper");
            }

            _functionsContainer = functionsDirectory.Container;
            _functionsPrefix = functionsDirectory.Prefix;
            _versionDirectory = versionDirectory;
            _versionMapper = versionMapper;
        }
コード例 #28
0
        public static void CreateBlobDirectory()
        {
            var cloudStorage = Microsoft.WindowsAzure.Storage.CloudStorageAccount.Parse(connsctionString);

            //Check Contain is Existed.
            var cloudBlobClient       = cloudStorage.CreateCloudBlobClient();
            var cloudBlobContainer    = cloudBlobClient.GetContainerReference("donmablogsample");
            var resultCreateContainer = cloudBlobContainer.CreateIfNotExistsAsync().Result;

            //取得該檔案夾 TEST
            Microsoft.WindowsAzure.Storage.Blob.CloudBlobDirectory cloudBlobDirectory =
                cloudBlobContainer.GetDirectoryReference("TEST");

            //在該檔案夾下面建立檔案
            var bFileInfo = cloudBlobDirectory.GetBlockBlobReference("sampleText.json");

            bFileInfo.Properties.ContentType = "application/json; charset=utf-8";
            bFileInfo.UploadTextAsync("{\"data\":\"測試資料\"}").GetAwaiter().GetResult();

            Console.WriteLine("Success Update File TEST/sampleText.json");
        }
コード例 #29
0
        public static void DeleteFile()
        {
            var cloudStorage = Microsoft.WindowsAzure.Storage.CloudStorageAccount.Parse(connsctionString);

            var cloudBlobClient       = cloudStorage.CreateCloudBlobClient();
            var cloudBlobContainer    = cloudBlobClient.GetContainerReference("donmablogsample");
            var resultCreateContainer = cloudBlobContainer.CreateIfNotExistsAsync().Result;

            Console.WriteLine("donmablogsample create already.");


            //取得 TEST2/TEST21/ 目錄
            Microsoft.WindowsAzure.Storage.Blob.CloudBlobDirectory cloudBlobDirectory =
                cloudBlobContainer.GetDirectoryReference("TEST2/TEST21/");

            Console.WriteLine("Delete File : TEST2/TEST21/sampleText8.json");
            // 如果存在就刪除,如果只是單純使用 DeleteAsync 如果不存在 會 Exception
            // 如果檔案存在被刪除, result 才會為  true , 如果檔案不存在 則 result 為  false
            var result = cloudBlobDirectory.GetBlockBlobReference("sampleText8.json").DeleteIfExistsAsync().GetAwaiter().GetResult();

            Console.WriteLine(result);
        }
コード例 #30
0
        public static void CreateBlobDirectory2()
        {
            var cloudStorage = Microsoft.WindowsAzure.Storage.CloudStorageAccount.Parse(connsctionString);

            var cloudBlobClient       = cloudStorage.CreateCloudBlobClient();
            var cloudBlobContainer    = cloudBlobClient.GetContainerReference("donmablogsample");
            var resultCreateContainer = cloudBlobContainer.CreateIfNotExistsAsync().Result;

            Console.WriteLine("donmablogsample create already.");


            Microsoft.WindowsAzure.Storage.Blob.CloudBlobDirectory cloudBlobDirectory =
                cloudBlobContainer.GetDirectoryReference("TEST2/TEST21/");

            for (var i = 1; i <= 10; i++)
            {
                var bFileInfo = cloudBlobDirectory.GetBlockBlobReference("sampleText" + i + ".json");
                bFileInfo.Properties.ContentType = "application/json; charset=utf-8";
                bFileInfo.UploadTextAsync("{\"data\":\"測試資料" + i + "\"}").GetAwaiter().GetResult();
                Console.WriteLine("Success Add File TEST2/TEST21/sampleText" + i + ".json");
            }
        }
コード例 #31
0
        public AzureBlobRepository OperOrCreate(CloudBlobDirectory directory, AzureBlobShardingStrategy defaultShardingStrategy)
        {
            AzureBlobShardingStrategy sharding = defaultShardingStrategy;
            var blobs = directory.ListBlobs().ToList();
            var dataBlobs = blobs.Where(s => !s.Uri.Segments.Last().StartsWith(Sharding)).ToList();

            if (!blobs.Any())
            {
                var id = GetId(sharding);
                var factoryBlob = directory.GetPageBlobReference(Get_Factory_Blob(directory, id.ToString()));
                factoryBlob.Create(0);
            }
            else
            {
                var factory = blobs.Select(s=> s.Uri.Segments.Last()).Single(b => b.StartsWith(Sharding));

                int spearatorIndex = factory.IndexOf('-');
                var id = factory.Substring(spearatorIndex + 1);
                sharding = BuildShardingStrategy(id);
            }

            return new AzureBlobRepository(directory, sharding, _builder);
        }
コード例 #32
0
        public static void UploadImage()
        {
            var cloudStorage = Microsoft.WindowsAzure.Storage.CloudStorageAccount.Parse(connsctionString);

            var cloudBlobClient       = cloudStorage.CreateCloudBlobClient();
            var cloudBlobContainer    = cloudBlobClient.GetContainerReference("donmablogsample");
            var resultCreateContainer = cloudBlobContainer.CreateIfNotExistsAsync().Result;

            Console.WriteLine("donmablogsample create already.");



            Microsoft.WindowsAzure.Storage.Blob.CloudBlobDirectory cloudBlobDirectory =
                cloudBlobContainer.GetDirectoryReference("TEST2/TEST21/IMAGES/");

            cloudBlobDirectory.GetBlockBlobReference("hamimelon.jpg").UploadFromFileAsync(AppDomain.CurrentDomain.BaseDirectory + "sample.jpg").GetAwaiter().GetResult();

            Console.WriteLine("Upload Success");

            //開啟連結
            Console.WriteLine();

            var sharedPolicy = new Microsoft.WindowsAzure.Storage.Blob.SharedAccessBlobPolicy()
            {
                SharedAccessExpiryTime = DateTime.UtcNow.AddSeconds(60),
                Permissions            = Microsoft.WindowsAzure.Storage.Blob.SharedAccessBlobPermissions.Read,
            };

            var sasContainerToken = cloudBlobContainer.GetSharedAccessSignature(sharedPolicy, null);
            var uri = cloudBlobDirectory.GetBlockBlobReference("hamimelon.jpg").Uri;

            System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo("cmd", $"/c start " + uri + sasContainerToken.Replace("&", "^&"))
            {
                CreateNoWindow = true
            });
        }
コード例 #33
0
 public BlobConcurrentTextStore(CloudBlobDirectory directory)
 {
     _directory = directory;
 }
 private void CollectJobRun(CloudBlobDirectory root)
 {
     var allblobs = root.ListBlobs(useFlatBlobListing: false, blobListingDetails: BlobListingDetails.None);
     foreach (var blob in allblobs)
     {
         if (blob is CloudBlobDirectory) CollectJobRun(blob as CloudBlobDirectory);
         else
         {
             runs.Add(root.Prefix);
             break;
         }
     }
 }
コード例 #35
0
 /// <summary>
 /// Reads the virtual directory's properties.
 /// </summary>
 /// <param name="dir">A CloudBlobDirectory object.</param>
 private static void PrintVirtualDirectoryProperties(CloudBlobDirectory dir)
 {
     Console.WriteLine();
     Console.WriteLine("-----Virtual Directory Properties-----");
     Console.WriteLine("\t Container: {0}", dir.Container.Name);
     Console.WriteLine("\t Parent: {0}", dir.Parent);
     Console.WriteLine("\t Prefix: {0}", dir.Prefix);
     Console.WriteLine("\t Uri: {0}", dir.Uri);
     Console.WriteLine();
 }
コード例 #36
0
            private static long GetDirectorySize(CloudBlobDirectory directoryBlob) {
                long size = 0;

                foreach ( var blobItem in directoryBlob.ListBlobs() ) {
                    var blob = blobItem as CloudBlockBlob;
                    if (blob != null)
                        size += blob.Properties.Length;

                    var item = blobItem as CloudBlobDirectory;
                    if (item != null)
                        size += GetDirectorySize(item);
                }

                return size;
            }
コード例 #37
0
 public AzureBlobFolderStorage(CloudBlobDirectory blob, string rootPath) {
     _blob = blob;
     // _blob.Container.FetchAttributes();
     _rootPath = rootPath;
 }
コード例 #38
0
 /// <summary>
 /// Instantiate a new AzureFileStoreDirectory from an Azure directory.
 /// </summary>
 /// <param name="Directory">Supplies the directory.</param>
 internal AzureFileStoreDirectory(CloudBlobDirectory Directory)
 {
     this.Directory = Directory;
 }
コード例 #39
0
        public void CloudBlobDirectoryFlatListingAPM()
        {
            foreach (String delimiter in Delimiters)
            {
                CloudBlobClient client = GenerateCloudBlobClient();
                client.DefaultDelimiter = delimiter;
                string             name      = GetRandomContainerName();
                CloudBlobContainer container = client.GetContainerReference(name);

                try
                {
                    container.Create();
                    if (CloudBlobDirectorySetupWithDelimiter(container, delimiter))
                    {
                        using (AutoResetEvent waitHandle = new AutoResetEvent(false))
                        {
                            IAsyncResult          result;
                            BlobContinuationToken token     = null;
                            CloudBlobDirectory    directory = container.GetDirectoryReference("TopDir1");
                            List <IListBlobItem>  list1     = new List <IListBlobItem>();
                            do
                            {
                                result = directory.BeginListBlobsSegmented(token, ar => waitHandle.Set(), null);
                                waitHandle.WaitOne();
                                BlobResultSegment result1 = directory.EndListBlobsSegmented(result);
                                list1.AddRange(result1.Results);
                                token = result1.ContinuationToken;
                            }while(token != null);

                            Assert.IsTrue(list1.Count == 3);

                            IListBlobItem item11 = list1.ElementAt(0);
                            Assert.IsTrue(item11.Uri.Equals(container.Uri + "/TopDir1" + delimiter + "Blob1"));

                            IListBlobItem item12 = list1.ElementAt(1);
                            Assert.IsTrue(item12.Uri.Equals(container.Uri + "/TopDir1" + delimiter + "MidDir1" + delimiter));

                            IListBlobItem item13 = list1.ElementAt(2);
                            Assert.IsTrue(item13.Uri.Equals(container.Uri + "/TopDir1" + delimiter + "MidDir2" + delimiter));

                            CloudBlobDirectory midDir2 = (CloudBlobDirectory)item13;

                            List <IListBlobItem> list2 = new List <IListBlobItem>();
                            do
                            {
                                result = midDir2.BeginListBlobsSegmented(true, BlobListingDetails.None, null, token, null, null, ar => waitHandle.Set(), null);
                                waitHandle.WaitOne();
                                BlobResultSegment result2 = midDir2.EndListBlobsSegmented(result);
                                list2.AddRange(result2.Results);
                                token = result2.ContinuationToken;
                            }while (token != null);

                            Assert.IsTrue(list2.Count == 2);

                            IListBlobItem item41 = list2.ElementAt(0);
                            Assert.IsTrue(item41.Uri.Equals(container.Uri + "/TopDir1" + delimiter + "MidDir2" + delimiter + "EndDir1" + delimiter + "EndBlob1"));

                            IListBlobItem item42 = list2.ElementAt(1);
                            Assert.IsTrue(item42.Uri.Equals(container.Uri + "/TopDir1" + delimiter + "MidDir2" + delimiter + "EndDir2" + delimiter + "EndBlob2"));
                        }
                    }
                }
                finally
                {
                    container.DeleteIfExists();
                }
            }
        }
コード例 #40
0
ファイル: AzureFileSystem.cs プロジェクト: Golone/Orchard
 public AzureBlobFolderStorage(CloudBlobDirectory blob, string rootPath) {
     _blob = blob;
     _rootPath = rootPath;
 }
コード例 #41
0
        public void CloudBlobDirectoryFlatListing()
        {
            foreach (String delimiter in Delimiters)
            {
                CloudBlobClient client = GenerateCloudBlobClient();
                client.DefaultDelimiter = delimiter;
                string             name      = GetRandomContainerName();
                CloudBlobContainer container = client.GetContainerReference(name);

                try
                {
                    container.Create();
                    if (CloudBlobDirectorySetupWithDelimiter(container, delimiter))
                    {
                        IEnumerable <IListBlobItem> list1 = container.ListBlobs("TopDir1" + delimiter, false, BlobListingDetails.None, null, null);

                        List <IListBlobItem> simpleList1 = list1.ToList();
                        ////Check if for 3 because if there were more than 3, the previous assert would have failed.
                        ////So the only thing we need to make sure is that it is not less than 3.
                        Assert.IsTrue(simpleList1.Count == 3);

                        IListBlobItem item11 = simpleList1.ElementAt(0);
                        Assert.IsTrue(item11.Uri.Equals(container.Uri + "/TopDir1" + delimiter + "Blob1"));

                        IListBlobItem item12 = simpleList1.ElementAt(1);
                        Assert.IsTrue(item12.Uri.Equals(container.Uri + "/TopDir1" + delimiter + "MidDir1" + delimiter));

                        IListBlobItem item13 = simpleList1.ElementAt(2);
                        Assert.IsTrue(item13.Uri.Equals(container.Uri + "/TopDir1" + delimiter + "MidDir2" + delimiter));
                        CloudBlobDirectory midDir2 = (CloudBlobDirectory)item13;

                        IEnumerable <IListBlobItem> list2 = container.ListBlobs("TopDir1" + delimiter + "MidDir1", true, BlobListingDetails.None, null, null);

                        List <IListBlobItem> simpleList2 = list2.ToList();
                        Assert.IsTrue(simpleList2.Count == 2);

                        IListBlobItem item21 = simpleList2.ElementAt(0);
                        Assert.IsTrue(item21.Uri.Equals(container.Uri + "/TopDir1" + delimiter + "MidDir1" + delimiter + "EndDir1" + delimiter + "EndBlob1"));

                        IListBlobItem item22 = simpleList2.ElementAt(1);
                        Assert.IsTrue(item22.Uri.Equals(container.Uri + "/TopDir1" + delimiter + "MidDir1" + delimiter + "EndDir2" + delimiter + "EndBlob2"));

                        IEnumerable <IListBlobItem> list3 = container.ListBlobs("TopDir1" + delimiter + "MidDir1" + delimiter, false, BlobListingDetails.None, null, null);

                        List <IListBlobItem> simpleList3 = list3.ToList();
                        Assert.IsTrue(simpleList3.Count == 2);

                        IListBlobItem item31 = simpleList3.ElementAt(0);
                        Assert.IsTrue(item31.Uri.Equals(container.Uri + "/TopDir1" + delimiter + "MidDir1" + delimiter + "EndDir1" + delimiter));

                        IListBlobItem item32 = simpleList3.ElementAt(1);
                        Assert.IsTrue(item32.Uri.Equals(container.Uri + "/TopDir1" + delimiter + "MidDir1" + delimiter + "EndDir2" + delimiter));

                        IEnumerable <IListBlobItem> list4 = midDir2.ListBlobs(true);

                        List <IListBlobItem> simpleList4 = list4.ToList();
                        Assert.IsTrue(simpleList4.Count == 2);

                        IListBlobItem item41 = simpleList4.ElementAt(0);
                        Assert.IsTrue(item41.Uri.Equals(container.Uri + "/TopDir1" + delimiter + "MidDir2" + delimiter + "EndDir1" + delimiter + "EndBlob1"));

                        IListBlobItem item42 = simpleList4.ElementAt(1);
                        Assert.IsTrue(item42.Uri.Equals(container.Uri + "/TopDir1" + delimiter + "MidDir2" + delimiter + "EndDir2" + delimiter + "EndBlob2"));
                    }
                }
                finally
                {
                    container.DeleteIfExists();
                }
            }
        }
コード例 #42
0
ファイル: AzureFileSystem.cs プロジェクト: Golone/Orchard
            private static long GetDirectorySize(CloudBlobDirectory directoryBlob) {
                long size = 0;

                foreach (var blobItem in directoryBlob.ListBlobs()) {
                    if (blobItem is CloudBlockBlob)
                        size += ((CloudBlockBlob)blobItem).Properties.Length;

                    if (blobItem is CloudBlobDirectory)
                        size += GetDirectorySize((CloudBlobDirectory)blobItem);
                }

                return size;
            }
コード例 #43
0
 private static CloudBlockBlob GetTempBlob(CloudBlobDirectory directory)
 {
     return directory.GetBlockBlobReference(TempFileName);
 }
コード例 #44
0
 private static CloudBlockBlob CreateTempBlob(CloudBlobDirectory directory)
 {
     var blob = GetTempBlob(directory);
     blob.UploadText("data");
     return blob;
 }
コード例 #45
0
        public async Task CloudBlobDirectoryFlatListingAsync()
        {
            foreach (String delimiter in Delimiters)
            {
                CloudBlobClient client = GenerateCloudBlobClient();
                client.DefaultDelimiter = delimiter;
                string             name      = GetRandomContainerName();
                CloudBlobContainer container = client.GetContainerReference(name);

                try
                {
                    await container.CreateAsync();

                    if (await CloudBlobDirectorySetupWithDelimiterAsync(container, delimiter))
                    {
                        BlobResultSegment segment = await container.ListBlobsSegmentedAsync("TopDir1" + delimiter, false, BlobListingDetails.None, null, null, null, null);

                        List <IListBlobItem> simpleList1 = new List <IListBlobItem>();
                        simpleList1.AddRange(segment.Results);
                        while (segment.ContinuationToken != null)
                        {
                            segment = await container.ListBlobsSegmentedAsync("TopDir1" + delimiter, false, BlobListingDetails.None, null, segment.ContinuationToken, null, null);

                            simpleList1.AddRange(segment.Results);
                        }

                        Assert.IsTrue(simpleList1.Count == 3);
                        IListBlobItem item11 = simpleList1.ElementAt(0);
                        Assert.IsTrue(item11.Uri.Equals(container.Uri + "/TopDir1" + delimiter + "Blob1"));

                        IListBlobItem item12 = simpleList1.ElementAt(1);
                        Assert.IsTrue(item12.Uri.Equals(container.Uri + "/TopDir1" + delimiter + "MidDir1" + delimiter));

                        IListBlobItem item13 = simpleList1.ElementAt(2);
                        Assert.IsTrue(item13.Uri.Equals(container.Uri + "/TopDir1" + delimiter + "MidDir2" + delimiter));
                        CloudBlobDirectory midDir2 = (CloudBlobDirectory)item13;

                        BlobResultSegment segment2 = await container.ListBlobsSegmentedAsync("TopDir1" + delimiter + "MidDir1", true, BlobListingDetails.None, null, null, null, null);

                        List <IListBlobItem> simpleList2 = new List <IListBlobItem>();
                        simpleList2.AddRange(segment2.Results);
                        while (segment2.ContinuationToken != null)
                        {
                            segment2 = await container.ListBlobsSegmentedAsync("TopDir1" + delimiter + "MidDir1", true, BlobListingDetails.None, null, segment2.ContinuationToken, null, null);

                            simpleList2.AddRange(segment2.Results);
                        }

                        Assert.IsTrue(simpleList2.Count == 2);

                        IListBlobItem item21 = simpleList2.ElementAt(0);
                        Assert.IsTrue(item21.Uri.Equals(container.Uri + "/TopDir1" + delimiter + "MidDir1" + delimiter + "EndDir1" + delimiter + "EndBlob1"));

                        IListBlobItem item22 = simpleList2.ElementAt(1);
                        Assert.IsTrue(item22.Uri.Equals(container.Uri + "/TopDir1" + delimiter + "MidDir1" + delimiter + "EndDir2" + delimiter + "EndBlob2"));

                        BlobResultSegment segment3 = await container.ListBlobsSegmentedAsync("TopDir1" + delimiter + "MidDir1" + delimiter, false, BlobListingDetails.None, null, null, null, null);

                        List <IListBlobItem> simpleList3 = new List <IListBlobItem>();
                        simpleList3.AddRange(segment3.Results);
                        while (segment3.ContinuationToken != null)
                        {
                            segment3 = await container.ListBlobsSegmentedAsync("TopDir1" + delimiter + "MidDir1" + delimiter, false, BlobListingDetails.None, null, segment3.ContinuationToken, null, null);

                            simpleList3.AddRange(segment3.Results);
                        }
                        Assert.IsTrue(simpleList3.Count == 2);

                        IListBlobItem item31 = simpleList3.ElementAt(0);
                        Assert.IsTrue(item31.Uri.Equals(container.Uri + "/TopDir1" + delimiter + "MidDir1" + delimiter + "EndDir1" + delimiter));

                        IListBlobItem item32 = simpleList3.ElementAt(1);
                        Assert.IsTrue(item32.Uri.Equals(container.Uri + "/TopDir1" + delimiter + "MidDir1" + delimiter + "EndDir2" + delimiter));

                        BlobResultSegment segment4 = await midDir2.ListBlobsSegmentedAsync(true, BlobListingDetails.None, null, null, null, null);

                        List <IListBlobItem> simpleList4 = new List <IListBlobItem>();
                        simpleList4.AddRange(segment4.Results);
                        while (segment4.ContinuationToken != null)
                        {
                            segment4 = await midDir2.ListBlobsSegmentedAsync(true, BlobListingDetails.None, null, segment4.ContinuationToken, null, null);

                            simpleList4.AddRange(segment4.Results);
                        }

                        Assert.IsTrue(simpleList4.Count == 2);

                        IListBlobItem item41 = simpleList4.ElementAt(0);

                        Assert.IsTrue(item41.Uri.Equals(container.Uri + "/TopDir1" + delimiter + "MidDir2" + delimiter + "EndDir1" + delimiter + "EndBlob1"));

                        IListBlobItem item42 = simpleList4.ElementAt(1);
                        Assert.IsTrue(item42.Uri.Equals(container.Uri + "/TopDir1" + delimiter + "MidDir2" + delimiter + "EndDir2" + delimiter + "EndBlob2"));
                    }
                }
                finally
                {
                    container.DeleteIfExistsAsync().Wait();
                }
            }
        }