コード例 #1
0
        public async Task CreateDeleteImmutabilityPolicy()
        {
            // create a blob container
            string            containerName = Recording.GenerateAssetName("testblob");
            BlobContainerData data          = new BlobContainerData();
            BlobContainer     container     = (await _blobContainerCollection.CreateOrUpdateAsync(containerName, new BlobContainerData())).Value;

            //create immutability policy
            ImmutabilityPolicyData immutabilityPolicyModel = new ImmutabilityPolicyData()
            {
                ImmutabilityPeriodSinceCreationInDays = 3
            };
            ImmutabilityPolicy immutabilityPolicy = (await container.GetImmutabilityPolicy().CreateOrUpdateAsync(parameters: immutabilityPolicyModel)).Value;

            //validate
            Assert.NotNull(immutabilityPolicy.Data.Id);
            Assert.NotNull(immutabilityPolicy.Data.Type);
            Assert.NotNull(immutabilityPolicy.Data.Name);
            Assert.AreEqual(3, immutabilityPolicy.Data.ImmutabilityPeriodSinceCreationInDays);
            Assert.AreEqual(ImmutabilityPolicyState.Unlocked, immutabilityPolicy.Data.State);

            //delete immutability policy
            immutabilityPolicyModel = (await immutabilityPolicy.DeleteAsync(immutabilityPolicy.Data.Etag)).Value;

            //validate
            Assert.NotNull(immutabilityPolicyModel.Type);
            Assert.NotNull(immutabilityPolicyModel.Name);
            Assert.AreEqual(0, immutabilityPolicyModel.ImmutabilityPeriodSinceCreationInDays);
        }
コード例 #2
0
        internal bool GetBlobContentsWithoutInitialization(string blobName, Stream outputStream, out BlobProperties properties)
        {
            Debug.Assert(outputStream != null);

            BlobContainer container = GetContainer();

            try
            {
                properties = container.GetBlob(blobName, new BlobContents(outputStream), false);
                Log.Write(EventKind.Information, "Getting contents of blob {0}", _info.BaseUri + _PathSeparator + _containerName + _PathSeparator + blobName);
                return(true);
            }
            catch (StorageClientException sc)
            {
                if (sc.ErrorCode == StorageErrorCode.ResourceNotFound || sc.ErrorCode == StorageErrorCode.BlobNotFound)
                {
                    properties = null;
                    return(false);
                }
                else
                {
                    throw;
                }
            }
        }
コード例 #3
0
 private BlobContainer GetContainer()
 {
     // we have to make sure that only one thread tries to create the container
     lock (_lock)
     {
         if (_container != null)
         {
             return(_container);
         }
         try
         {
             BlobContainer container = BlobStorage.Create(_info).GetBlobContainer(_containerName);
             container.Timeout     = _Timeout;
             container.RetryPolicy = _RetryPolicy;
             container.CreateContainer();
             _container = container;
             return(_container);
         }
         catch (StorageException se)
         {
             Log.Write(EventKind.Error, "Error creating container {0}: {1}", ContainerUrl, se.Message);
             throw;
         }
     }
 }
コード例 #4
0
ファイル: ImageProvider.cs プロジェクト: Lanayx/RadrugaCloud
        /// <summary>
        ///     Saves the image by URL.
        /// </summary>
        /// <param name="externalUrl">The external URL.</param>
        /// <param name="container">The container.</param>
        /// <returns>Task{System.String}.</returns>
        public async Task <OperationResult> SaveImageByUrl(string externalUrl, BlobContainer container)
        {
            var info = BlobInfo.GetInfoByUrl(externalUrl);

            var uniqueName = GetUniqueImageName(info.Extension);

            var webRequest = WebRequest.Create(externalUrl);

            using (var response = await webRequest.GetResponseAsync())
            {
                using (var content = response.GetResponseStream())
                {
                    if (content == null)
                    {
                        return(new OperationResult(
                                   OperationResultStatus.Warning,
                                   "Content of specified source is empty"));
                    }

                    var contentType = response.ContentType;

                    var manager = GetManager(container);
                    if (manager == null)
                    {
                        return(new OperationResult(OperationResultStatus.Warning, "Incorrect input"));
                    }

                    var url = await manager.AddBlockBlob(uniqueName, content, contentType);

                    return(new OperationResult(OperationResultStatus.Success, url));
                }
            }
        }
コード例 #5
0
ファイル: ImageProvider.cs プロジェクト: Lanayx/RadrugaCloud
        internal async Task SaveImagesToProductionBlobOnUpdate(
            List <string> oldUrls,
            List <string> newUrls,
            BlobContainer container)
        {
            var anyOldUrls = oldUrls.AnyValues();
            var anyNewUrls = newUrls.AnyValues();

            var notTouch =
                anyOldUrls && anyNewUrls
                ? oldUrls.Intersect(newUrls).ToIList()
                : new List <string>();

            if (anyOldUrls)
            {
                foreach (var oldUrl in oldUrls)
                {
                    if (!notTouch.Contains(oldUrl))
                    {
                        await DeleteImage(oldUrl);
                    }
                }
            }

            if (anyNewUrls)
            {
                foreach (var newUrl in newUrls)
                {
                    if (!notTouch.Contains(newUrl))
                    {
                        await SaveImageToProductionBlobOnAdd(newUrl, container);
                    }
                }
            }
        }
コード例 #6
0
        public async Task GetAllBlobContainers()
        {
            //create two blob containers
            string        containerName1 = Recording.GenerateAssetName("testblob1");
            string        containerName2 = Recording.GenerateAssetName("testblob2");
            BlobContainer container1     = (await _blobContainerCollection.CreateOrUpdateAsync(containerName1, new BlobContainerData())).Value;
            BlobContainer container2     = (await _blobContainerCollection.CreateOrUpdateAsync(containerName2, new BlobContainerData())).Value;

            //validate if there are two containers
            BlobContainer container3 = null;
            BlobContainer container4 = null;
            int           count      = 0;

            await foreach (BlobContainer container in _blobContainerCollection.GetAllAsync())
            {
                count++;
                if (container.Id.Name == containerName1)
                {
                    container3 = container;
                }
                if (container.Id.Name == containerName2)
                {
                    container4 = container;
                }
            }
            Assert.AreEqual(count, 2);
            Assert.IsNotNull(container3);
            Assert.IsNotNull(container4);
        }
コード例 #7
0
        public async Task <BlobContainer> CreateContainer(BlobContainer container)
        {
            var blobServiceClient = new BlobServiceClient(_connectionString);
            var publicAcessType   = PublicAccessType.None;

            if (container.Metadata?.Any(x => x.Key == "PublicAccessType") == true)
            {
                publicAcessType = Enum.Parse <PublicAccessType>(container.Metadata["PublicAccessType"].ToString());
            }
            IDictionary <string, string> metadata = null;

            if ((container.Metadata?.Count > 0) == true)
            {
                metadata = new Dictionary <string, string>();
                foreach (var prop in container.Metadata)
                {
                    if (prop.Key != "PublicAccessType")
                    {
                        metadata.Add(prop.Key, prop.Value.ToString());
                    }
                }
            }
            var response = (await blobServiceClient.CreateBlobContainerAsync(container.Identifier, publicAcessType, metadata)).Value;

            return(ConstructContainer(response));
        }
コード例 #8
0
        /// <summary>
        /// Put (create or update) a blob from a memory stream.
        /// </summary>
        /// <param name="stream">Memory stream to put to a blob</param>
        /// <param name="blobPath">Path to the blob</param>
        /// <param name="contentType">Content type of the blob</param>
        /// <param name="permissions">Blob Container Permissions for the blob</param>
        /// <returns></returns>
        public string PutBlob(MemoryStream stream, string blobPath, string contentType, BlobContainerPermissions permissions)
        {
            try
            {
                var blob = BlobContainer.GetBlockBlobReference(blobPath);

                // Set proper content type on the blog
                blob.Properties.ContentType = contentType;

                // Set the permissions for the file to be accessible through the internet
                BlobContainer.SetPermissions(permissions);

                // Upload to the Blob
                blob.UploadFromStream(stream);

                return(blob.Uri.ToString());
            }
            catch (StorageException ex)
            {
                if (ex.RequestInformation.HttpStatusCode == 404)
                {
                    return(string.Empty);
                }

                throw;
            }
        }
コード例 #9
0
        public static BlobContainer GetAzureContainer(string containerName)
        {
            StorageAccountInfo accountInfo = StorageAccountInfo.GetAccountInfoFromConfiguration("BlobStorageEndpoint");
            BlobStorage        blobStorage = BlobStorage.Create(accountInfo);

            //The default timeout of 30 seconds is far too short, make it 6 hours.
            blobStorage.Timeout = new TimeSpan(6, 0, 0);

            if (String.IsNullOrEmpty(containerName))
            {
                // Default name for new container; Container names have the same restrictions as DNS names
                containerName = String.Format("media{0}{1}", DateTime.Now.Year, DateTime.Now.DayOfYear);
            }
            else
            {
                //We have received a path from a media file
                containerName = containerName.Substring(0, containerName.IndexOf("/"));
            }

            BlobContainer container = blobStorage.GetBlobContainer(containerName);

            //If the Container already exists, false is returned, so go get it
            if (!container.DoesContainerExist())
            {
                container.CreateContainer(null, ContainerAccessControl.Private);
            }
            return(container);
        }
コード例 #10
0
        public AppLeaseManager(
            AzureStorageClient azureStorageClient,
            IPartitionManager partitionManager,
            string appLeaseContainerName,
            string appLeaseInfoBlobName,
            AppLeaseOptions options)
        {
            this.azureStorageClient    = azureStorageClient;
            this.partitionManager      = partitionManager;
            this.appLeaseContainerName = appLeaseContainerName;
            this.appLeaseInfoBlobName  = appLeaseInfoBlobName;
            this.options = options;

            this.storageAccountName = this.azureStorageClient.BlobAccountName;
            this.settings           = this.azureStorageClient.Settings;
            this.taskHub            = settings.TaskHubName;
            this.workerName         = settings.WorkerId;
            this.appName            = settings.AppName;
            this.appLeaseIsEnabled  = this.settings.UseAppLease;
            this.appLeaseContainer  = this.azureStorageClient.GetBlobContainerReference(this.appLeaseContainerName);
            this.appLeaseInfoBlob   = this.appLeaseContainer.GetBlobReference(this.appLeaseInfoBlobName);

            var appNameHashInBytes = BitConverter.GetBytes(Fnv1aHashHelper.ComputeHash(this.appName));

            Array.Resize(ref appNameHashInBytes, 16);
            this.appLeaseId = new Guid(appNameHashInBytes).ToString();

            this.isLeaseOwner           = false;
            this.shutdownCompletedEvent = new AsyncManualResetEvent();
        }
コード例 #11
0
        /// <summary>Returns an array of strings, one for each file in the directory. </summary>
        public override string[] ListAll()
        {
            var results = from blob in BlobContainer.ListBlobs()
                          select blob.Uri.AbsolutePath.Substring(blob.Uri.AbsolutePath.LastIndexOf('/') + 1);

            return(results.ToArray());
        }
コード例 #12
0
        /// <summary>Removes an existing file in the directory. </summary>
        public override void DeleteFile(string name)
        {
            var blobName = GetBlobName(name);
            var blob     = BlobContainer.GetBlockBlobReference(blobName);

            blob.DeleteIfExists();
        }
コード例 #13
0
        public async Task <IActionResult> GetAttachmentData(string chatId, string attachmentId)
        {
            var isMember = Database.CreateStatement <bool>($@"return (FOR u in 1..1 OUTBOUND 'Chat/{chatId}'
                        GRAPH 'ChatsUsersGraph'
                        PRUNE u._key == '{HttpContext.User.Identity.Name}'
                        FILTER u._key == '{HttpContext.User.Identity.Name}'
                        return u) != []").ToList().FirstOr(false);

            if (!isMember)
            {
                return(NotFound());
            }

            var blob = BlobContainer.GetBlockBlobReference($"chats/{chatId}/{attachmentId}");

            if (!await blob.ExistsAsync())
            {
                return(NotFound());
            }

            var sasConstraints = new SharedAccessBlobPolicy
            {
                SharedAccessStartTime  = DateTime.UtcNow.AddMinutes(-5),
                SharedAccessExpiryTime = DateTime.UtcNow.AddHours(2),
                Permissions            = SharedAccessBlobPermissions.Read
            };

            var sasBlobToken = blob.GetSharedAccessSignature(sasConstraints);

            return(Ok(new
            {
                Url = blob.Uri + sasBlobToken,
                Mime = blob.Properties.ContentType
            }));
        }
コード例 #14
0
        public async Task BlobContainerEncryptionScope()
        {
            //create encryption scope
            string scopeName1        = "testscope1";
            string scopeName2        = "testscope2";
            EncryptionScopeData data = new EncryptionScopeData()
            {
                Source = EncryptionScopeSource.MicrosoftStorage,
                State  = EncryptionScopeState.Enabled
            };
            await _storageAccount.GetEncryptionScopes().CreateOrUpdateAsync(true, scopeName1, data);

            await _storageAccount.GetEncryptionScopes().CreateOrUpdateAsync(true, scopeName2, data);

            //create container
            string        containerName = Recording.GenerateAssetName("container");
            BlobContainer blobContainer = (await _blobContainerCollection.CreateOrUpdateAsync(true, containerName, new BlobContainerData()
            {
                DefaultEncryptionScope = scopeName1, DenyEncryptionScopeOverride = false
            })).Value;

            Assert.AreEqual(scopeName1, blobContainer.Data.DefaultEncryptionScope);
            Assert.False(blobContainer.Data.DenyEncryptionScopeOverride.Value);

            //Update container not support Encryption scope
            BlobContainer blobContainer2 = (await _blobContainerCollection.CreateOrUpdateAsync(true, containerName, new BlobContainerData()
            {
                DefaultEncryptionScope = scopeName2, DenyEncryptionScopeOverride = true
            })).Value;

            Assert.AreEqual(scopeName2, blobContainer2.Data.DefaultEncryptionScope);
            Assert.True(blobContainer2.Data.DenyEncryptionScopeOverride.Value);
        }
コード例 #15
0
        public async Task SetClearLegalHold()
        {
            // create a blob container
            string            containerName = Recording.GenerateAssetName("testblob");
            BlobContainerData data          = new BlobContainerData();
            BlobContainer     container     = (await _blobContainerCollection.CreateOrUpdateAsync(containerName, new BlobContainerData())).Value;

            //set legal hold
            LegalHold legalHoldModel = new LegalHold(new List <string> {
                "tag1", "tag2", "tag3"
            });
            LegalHold legalHold = await container.SetLegalHoldAsync(legalHoldModel);

            //validate
            Assert.True(legalHold.HasLegalHold);
            Assert.AreEqual(new List <string> {
                "tag1", "tag2", "tag3"
            }, legalHold.Tags);

            //clear legal hold
            legalHold = await container.ClearLegalHoldAsync(legalHoldModel);

            //validate
            Assert.False(legalHold.HasLegalHold);
            Assert.AreEqual(0, legalHold.Tags.Count);
        }
        public void Name()
        {
            var container = new BlobContainer("container");

            Assert.Equal("container", container.Name);
            Assert.Equal("container", container.EmulatedName);
        }
コード例 #17
0
        public async Task CreateDeleteBlobContainer()
        {
            //create blob container
            string        containerName = Recording.GenerateAssetName("testblob");
            BlobContainer container1    = (await _blobContainerCollection.CreateOrUpdateAsync(containerName, new BlobContainerData())).Value;

            Assert.IsNotNull(container1);
            Assert.AreEqual(container1.Id.Name, containerName);

            //validate if created successfully
            BlobContainer container2 = await _blobContainerCollection.GetAsync(containerName);

            AssertBlobContainerEqual(container1, container2);
            Assert.IsTrue(await _blobContainerCollection.CheckIfExistsAsync(containerName));
            Assert.IsFalse(await _blobContainerCollection.CheckIfExistsAsync(containerName + "1"));
            BlobContainerData containerData = container1.Data;

            Assert.IsEmpty(containerData.Metadata);
            Assert.IsFalse(containerData.HasLegalHold);
            Assert.IsNull(containerData.PublicAccess);
            Assert.False(containerData.HasImmutabilityPolicy);

            //delete blob container
            BlobContainerDeleteOperation blobContainerDeleteOperation = await container1.DeleteAsync();

            await blobContainerDeleteOperation.WaitForCompletionResponseAsync();

            //validate if deleted successfully
            BlobContainer blobContainer3 = await _blobContainerCollection.GetIfExistsAsync(containerName);

            Assert.IsNull(blobContainer3);
            Assert.IsFalse(await _blobContainerCollection.CheckIfExistsAsync(containerName));
        }
コード例 #18
0
        public void DeleteFile(BlobContainer container, string resource)
        {
            var blobContainer = GetContainer(container);
            CloudBlockBlob blockBlob = blobContainer.GetBlockBlobReference(resource);

            blockBlob.Delete();
        }
コード例 #19
0
 public PSContainer(BlobContainer container)
 {
     this.ResourceGroupName  = ParseResourceGroupFromId(container.Id);
     this.StorageAccountName = ParseStorageAccountNameFromId(container.Id);
     this.Id                          = container.Id;
     this.Name                        = container.Name;
     this.Type                        = container.Type;
     this.Metadata                    = container.Metadata;
     this.Etag                        = container.Etag;
     this.PublicAccess                = (PSPublicAccess?)container.PublicAccess;
     this.ImmutabilityPolicy          = container.ImmutabilityPolicy == null? null : new PSImmutabilityPolicyProperties(container.ImmutabilityPolicy);
     this.LegalHold                   = container.LegalHold == null ? null : new PSLegalHoldProperties(container.LegalHold);
     this.LastModifiedTime            = container.LastModifiedTime;
     this.LeaseStatus                 = container.LeaseStatus;
     this.LeaseState                  = container.LeaseState;
     this.LeaseDuration               = container.LeaseDuration;
     this.HasLegalHold                = container.HasLegalHold;
     this.HasImmutabilityPolicy       = container.HasImmutabilityPolicy;
     this.DefaultEncryptionScope      = container.DefaultEncryptionScope;
     this.DenyEncryptionScopeOverride = container.DenyEncryptionScopeOverride;
     this.Deleted                     = container.Deleted;
     this.RemainingRetentionDays      = container.RemainingRetentionDays;
     this.DeletedTime                 = container.DeletedTime;
     this.Version                     = container.Version;
 }
コード例 #20
0
        public async Task <SlideShowPictureDto> GetAsync(string name)
        {
            if (string.IsNullOrEmpty(name) || string.IsNullOrWhiteSpace(name))
            {
                throw new ArgumentException();
            }

            var buffer = await BlobContainer.GetAllBytesOrNullAsync(name) ?? throw new FileNotFoundException();

            var xmlStr = Encoding.UTF8.GetString(buffer);
            var xmlDoc = CreateXmlDoc();

            xmlDoc.LoadXml(xmlStr);

            var slideShowElm = xmlDoc.DocumentElement;
            var imgElm       = slideShowElm.FirstChild;
            var b64txtNode   = imgElm.FirstChild as XmlText;
            var imgTypeAttr  = imgElm.Attributes.Item(0);

            if (imgTypeAttr.LocalName != "imgType")
            {
                throw new Exception();
            }

            var dto = new SlideShowPictureDto {
                Name          = slideShowElm.GetAttribute("name"),
                Uri           = slideShowElm.GetAttribute("uri"),
                Base64Picture = SetB64ImgContentType(b64txtNode.InnerText, imgTypeAttr.InnerText),
                FileName      = name
            };

            return(dto);
        }
コード例 #21
0
        protected async Task<CloudBlobContainer> GetContainer(BlobContainer container)
        {
            var blobContainer = _blobClient.GetContainerReference(container.ToString().ToLower());
            await blobContainer.CreateIfNotExistsAsync();

            return blobContainer;
        }
コード例 #22
0
        public async Task <SlideShowPictureDto> UpdateAsync(string fileName, SlideShowPictureDto dto)
        {
            if (string.IsNullOrWhiteSpace(fileName) ||
                !ImageManipulator.IsImageStream(dto.Base64Picture))
            {
                throw new ArgumentException();
            }

            var b64Part = (dto.Base64Picture == null)? null : GetBase64Part(dto.Base64Picture);

            var file = await BlobContainer.GetAllBytesOrNullAsync(fileName) ?? throw new FileNotFoundException();

            var xmlDoc   = new XmlDocument();
            var settings = GetReaderSettings();

            using var ms     = new MemoryStream(file);
            using var reader = XmlReader.Create(ms, settings);

            xmlDoc.Load(reader);

            var slideShowElm = xmlDoc.DocumentElement;
            var imgElm       = slideShowElm.FirstChild;
            var b64txtNode   = imgElm.FirstChild as XmlText;

            b64txtNode.InnerText = b64Part ?? b64txtNode.InnerText;
            slideShowElm.SetAttribute("uri", (dto.Uri == null) ? slideShowElm.GetAttribute("uri") : dto.Uri.ToString());
            slideShowElm.SetAttribute("name", dto.Name ?? slideShowElm.GetAttribute("name"));

            var bytes = Encoding.UTF8.GetBytes(xmlDoc.InnerXml);
            await BlobContainer.SaveAsync(fileName, bytes, true);

            return(await GetAsync(fileName));
        }
コード例 #23
0
        public virtual async Task <string> SaveBytesAsync(string name, byte[] bytes)
        {
            var fileName = BlobPrefix + name;
            await BlobContainer.SaveAsync(fileName, bytes);

            return(fileName);
        }
コード例 #24
0
        public void BlobContainersExtendImmutabilityPolicyTest()
        {
            var handler = new RecordedDelegatingHandler {
                StatusCodeToReturn = HttpStatusCode.OK
            };

            using (MockContext context = MockContext.Start(this.GetType().FullName))
            {
                var resourcesClient   = StorageManagementTestUtilities.GetResourceManagementClient(context, handler);
                var storageMgmtClient = StorageManagementTestUtilities.GetStorageManagementClient(context, handler);

                // Create resource group
                var rgName = StorageManagementTestUtilities.CreateResourceGroup(resourcesClient);

                // Create storage account
                string accountName = TestUtilities.GenerateName("sto");
                var    parameters  = StorageManagementTestUtilities.GetDefaultStorageAccountParameters();
                parameters.Kind = Kind.StorageV2;
                var account = storageMgmtClient.StorageAccounts.Create(rgName, accountName, parameters);
                StorageManagementTestUtilities.VerifyAccountProperties(account, false);

                // implement case
                try
                {
                    string        containerName = TestUtilities.GenerateName("container");
                    BlobContainer blobContainer = storageMgmtClient.BlobContainers.Create(rgName, accountName, containerName);
                    Assert.Null(blobContainer.Metadata);
                    Assert.Null(blobContainer.PublicAccess);

                    ImmutabilityPolicy immutabilityPolicy = storageMgmtClient.BlobContainers.CreateOrUpdateImmutabilityPolicy(rgName, accountName, containerName, ifMatch: "", immutabilityPeriodSinceCreationInDays: 3);
                    Assert.NotNull(immutabilityPolicy.Id);
                    Assert.NotNull(immutabilityPolicy.Type);
                    Assert.NotNull(immutabilityPolicy.Name);
                    Assert.Equal(3, immutabilityPolicy.ImmutabilityPeriodSinceCreationInDays);
                    Assert.Equal(ImmutabilityPolicyState.Unlocked, immutabilityPolicy.State);

                    immutabilityPolicy = storageMgmtClient.BlobContainers.LockImmutabilityPolicy(rgName, accountName, containerName, ifMatch: immutabilityPolicy.Etag);
                    Assert.NotNull(immutabilityPolicy.Id);
                    Assert.NotNull(immutabilityPolicy.Type);
                    Assert.NotNull(immutabilityPolicy.Name);
                    Assert.Equal(3, immutabilityPolicy.ImmutabilityPeriodSinceCreationInDays);
                    Assert.Equal(ImmutabilityPolicyState.Locked, immutabilityPolicy.State);

                    immutabilityPolicy = storageMgmtClient.BlobContainers.ExtendImmutabilityPolicy(rgName, accountName, containerName, ifMatch: immutabilityPolicy.Etag, immutabilityPeriodSinceCreationInDays: 100);
                    Assert.NotNull(immutabilityPolicy.Id);
                    Assert.NotNull(immutabilityPolicy.Type);
                    Assert.NotNull(immutabilityPolicy.Name);
                    Assert.Equal(100, immutabilityPolicy.ImmutabilityPeriodSinceCreationInDays);
                    Assert.Equal(ImmutabilityPolicyState.Locked, immutabilityPolicy.State);

                    storageMgmtClient.BlobContainers.Delete(rgName, accountName, containerName);
                }
                finally
                {
                    // clean up
                    storageMgmtClient.StorageAccounts.Delete(rgName, accountName);
                    resourcesClient.ResourceGroups.Delete(rgName);
                }
            }
        }
コード例 #25
0
        private static Output <string> SignedBlobReadUrl(Blob blob, BlobContainer container, StorageAccount account, ResourceGroup resourceGroup)
        {
            return(Output.Tuple <string, string, string, string>(
                       blob.Name, container.Name, account.Name, resourceGroup.Name).Apply(t =>
            {
                (string blobName, string containerName, string accountName, string resourceGroupName) = t;

                var blobSAS = ListStorageAccountServiceSAS.InvokeAsync(new ListStorageAccountServiceSASArgs
                {
                    AccountName = accountName,
                    Protocols = HttpProtocol.Https,
                    SharedAccessStartTime = "2021-01-01",
                    SharedAccessExpiryTime = "2030-01-01",
                    Resource = SignedResource.C,
                    ResourceGroupName = resourceGroupName,
                    Permissions = Permissions.R,
                    CanonicalizedResource = "/blob/" + accountName + "/" + containerName,
                    ContentType = "application/json",
                    CacheControl = "max-age=5",
                    ContentDisposition = "inline",
                    ContentEncoding = "deflate",
                });
                return Output.Format($"https://{accountName}.blob.core.windows.net/{containerName}/{blobName}?{blobSAS.Result.ServiceSasToken}");
            }));
        }
コード例 #26
0
ファイル: CloudStorage.cs プロジェクト: RFL86/Classics
        public void UploadFromStream(Stream stream, string name, string contentType)
        {
            var blockBlob = BlobContainer.GetBlockBlobReference(name);

            blockBlob.Properties.ContentType = contentType;
            blockBlob.UploadFromStream(stream);
        }
コード例 #27
0
ファイル: CloudStorage.cs プロジェクト: RFL86/Classics
        public CloudStorage(string storageConnectionString, string blobContainer, bool createIfNotExists = true)
        {
            if (string.IsNullOrWhiteSpace(blobContainer))
            {
                throw new Exception("O parâmetro 'blobContainer' não pode ser nulo, vazio ou em branco.");
            }

            if (string.IsNullOrWhiteSpace(storageConnectionString))
            {
                throw new Exception("O parâmetro 'storageConnectionString' não pode ser nulo, vazio ou em branco.");
            }

            if (blobContainer.Any(char.IsUpper))
            {
                throw new Exception("O parâmetro 'storageConnectionString' não pode conter caracteres em caixa alta.");
            }

            StorageAccount = CloudStorageAccount.Parse(storageConnectionString);
            BlobClient     = StorageAccount.CreateCloudBlobClient();
            BlobContainer  = BlobClient.GetContainerReference(blobContainer);

            if (createIfNotExists)
            {
                BlobContainer.CreateIfNotExists();
            }
        }
コード例 #28
0
            public async Task Initialize()
            {
                Store = new AzureHttpMessageStore(Table, BlobContainer, UseCompression);
                await Table.CreateIfNotExistsAsync(CancellationToken.None);

                await BlobContainer.CreateIfNotExistsAsync(CancellationToken.None);
            }
コード例 #29
0
ファイル: CloudStorage.cs プロジェクト: RFL86/Classics
        public async void UploadFromByteArrayAsync(byte[] file, string name, string contentType)
        {
            var blockBlob = BlobContainer.GetBlockBlobReference(name);

            blockBlob.Properties.ContentType = contentType;
            await blockBlob.UploadFromByteArrayAsync(file, 0, file.Length);
        }
 public bool DownloadFile(string blobName, string downloadFolder)
 {
     try
     {
         CloudBlockBlob blobSource = BlobContainer.GetBlockBlobReference(blobName);
         if (blobSource.Exists())
         {
             //blob storage uses forward slashes, windows uses backward slashes; do a replace
             //  so localPath will be right
             string localPath = Path.Combine(downloadFolder, blobSource.Name.Replace(@"/", @"\"));
             //if the directory path matching the "folders" in the blob name don't exist, create them
             string dirPath = Path.GetDirectoryName(localPath);
             if (!Directory.Exists(localPath))
             {
                 Directory.CreateDirectory(dirPath);
             }
             blobSource.DownloadToFile(localPath, FileMode.Create);
             return(true);
         }
         return(false);
     }
     catch (Exception ex)
     {
         return(false);
     }
 }
コード例 #31
0
        protected CloudBlobContainer GetContainer(BlobContainer container)
        {
            var blobContainer = _blobClient.GetContainerReference(container.ToString().ToLower());
            blobContainer.CreateIfNotExists();

            return blobContainer;
        }
コード例 #32
0
        public async Task SaveAsync(int categoryId, string base64Img)
        {
            var categoryE = await CategoryRepository.FindAsync(categoryId) ?? throw new Exception();

            if (!ImageManipulator.IsImageStream(base64Img))
            {
                throw new Exception();
            }

            var buffer = Convert.FromBase64String(base64Img);

            var resizedImgBuffer = ImageManipulator.ResizeImage(
                buffer,
                Options.CategoryThumbnail.Width,
                Options.CategoryThumbnail.Height,
                Options.CategoryThumbnail.ImageFormat);

            var hash           = Md5Hasher.GenerateBase16Hash(resizedImgBuffer);
            var randomizedHash = Randomize(hash);
            var fileName       = string.Format("{0}.{1}", randomizedHash, Options.CategoryThumbnail.ImageFormat.ToString());

            await BlobContainer.DeleteAsync(categoryE.CategoryThumbnail);

            await BlobContainer.SaveBytesAsync(fileName, resizedImgBuffer);

            categoryE.CategoryThumbnail = fileName;
            await CategoryRepository.UpdateAsync(categoryE, autoSave : true);
        }
コード例 #33
0
        protected async Task <CloudBlobContainer> GetContainer(BlobContainer container)
        {
            var blobContainer = _blobClient.GetContainerReference(container.ToString().ToLower());
            await blobContainer.CreateIfNotExistsAsync();

            return(blobContainer);
        }
コード例 #34
0
        public async Task DeleteFile(BlobContainer container, string resource)
        {
            var blobContainer = await GetContainer(container);
            CloudBlockBlob blockBlob = blobContainer.GetBlockBlobReference(resource);

            await blockBlob.DeleteAsync();
        }
コード例 #35
0
        public async Task<string> UploadFile(BlobContainer container, string fileName, string relativePath, Stream stream)
        {
            var blobContainer = await GetContainer(container);
            CloudBlockBlob blockBlob = blobContainer.GetBlockBlobReference($"{relativePath.ToLower()}/{fileName.ToLower()}");

            await blockBlob.UploadFromStreamAsync(stream);

            return
                $"http://{_conifgruation.AccountName.ToLower()}.blob.core.windows.net/{container.ToString().ToLower()}/{relativePath.ToLower()}/{fileName.ToLower()}";
        }
コード例 #36
0
        /// <summary>
        /// Executes the Service Object method and returns any data.
        /// </summary>
        /// <param name="inputs">A Property[] array containing all the allowed input properties.</param>
        /// <param name="required">A RequiredProperties collection containing the required properties.</param>
        /// <param name="returns">A Property[] array containing all the allowed return properties.</param>
        /// <param name="methodType">A MethoType indicating what type of Service Object method was called.</param>
        /// <param name="serviceObject">A ServiceObject containing populated properties for use with the method call.</param>
        public void Execute(Property[] inputs, RequiredProperties required, Property[] returns, MethodType methodType, ServiceObject serviceObject)
        {
            crmconfig = new CRMConfig
            {
                CRMURL = crmurl,
                CRMOrganization = crmorganization
            };


            #region Container


            if (serviceObject.Methods[0].Name.Equals("loadcontainer"))
            {
                BlobContainer container = new BlobContainer(serviceBroker);
                container.ExecuteLoadContainer(inputs, required, returns, methodType, serviceObject);
            }

            if (serviceObject.Methods[0].Name.Equals("listcontainers"))
            {
                BlobContainer container = new BlobContainer(serviceBroker);
                container.ExecuteListContainers(inputs, required, returns, methodType, serviceObject);
            }

            if (serviceObject.Methods[0].Name.Equals("createcontainer"))
            {
                BlobContainer container = new BlobContainer(serviceBroker);
                container.ExecuteCreateContainer(inputs, required, returns, methodType, serviceObject);
            }

            if (serviceObject.Methods[0].Name.Equals("setcontainerpermissions"))
            {
                BlobContainer container = new BlobContainer(serviceBroker);
                container.ExecuteSetPermissions(inputs, required, returns, methodType, serviceObject);
            }

            if (serviceObject.Methods[0].Name.Equals("setcontainermetadata"))
            {
                BlobContainer container = new BlobContainer(serviceBroker);
                container.ExecuteSetMetadata(inputs, required, returns, methodType, serviceObject);
            }

            if (serviceObject.Methods[0].Name.Equals("loadcontainermetadatavalue"))
            {
                BlobContainer container = new BlobContainer(serviceBroker);
                container.ExecuteLoadMetadataValue(inputs, required, returns, methodType, serviceObject);
            }

            if (serviceObject.Methods[0].Name.Equals("listcontainermetadata"))
            {
                BlobContainer container = new BlobContainer(serviceBroker);
                container.ExecuteListMetadata(inputs, required, returns, methodType, serviceObject);
            }

            if (serviceObject.Methods[0].Name.Equals("deletecontainer"))
            {
                BlobContainer container = new BlobContainer(serviceBroker);
                container.ExecuteDeleteContainer(inputs, required, returns, methodType, serviceObject);
            }

            if (serviceObject.Methods[0].Name.Equals("listcontainerfolders"))
            {
                BlobContainer container = new BlobContainer(serviceBroker);
                container.ExecuteListContainerFolders(inputs, required, returns, methodType, serviceObject);
            }

            #endregion Container


            #region Blob


            if (serviceObject.Methods[0].Name.Equals("loadblob"))
            {
                BlobBlob blob = new BlobBlob(serviceBroker);
                blob.ExecuteLoadBlob(inputs, required, returns, methodType, serviceObject);
            }

            if (serviceObject.Methods[0].Name.Equals("setblobmetadata"))
            {
                BlobBlob blob = new BlobBlob(serviceBroker);
                blob.ExecuteSetBlobMetadata(inputs, required, returns, methodType, serviceObject);
            }

            if (serviceObject.Methods[0].Name.Equals("loadblobmetadatavalue"))
            {
                BlobBlob blob = new BlobBlob(serviceBroker);
                blob.ExecuteLoadBlobMetadataValue(inputs, required, returns, methodType, serviceObject);
            }

            if (serviceObject.Methods[0].Name.Equals("listblobmetadata"))
            {
                BlobBlob blob = new BlobBlob(serviceBroker);
                blob.ExecuteListBlobMetadata(inputs, required, returns, methodType, serviceObject);
            }

            if (serviceObject.Methods[0].Name.Equals("deleteblob"))
            {
                BlobBlob blob = new BlobBlob(serviceBroker);
                blob.ExecuteDeleteBlob(inputs, required, returns, methodType, serviceObject);
            }

            if (serviceObject.Methods[0].Name.Equals("uploadblob"))
            {
                BlobBlob blob = new BlobBlob(serviceBroker);
                blob.ExecuteUploadBlob(inputs, required, returns, methodType, serviceObject);
            }

            if (serviceObject.Methods[0].Name.Equals("uploadblobfrombase64"))
            {
                BlobBlob blob = new BlobBlob(serviceBroker);
                blob.ExecuteUploadBlobFromBase64(inputs, required, returns, methodType, serviceObject);
            }

            if (serviceObject.Methods[0].Name.Equals("uploadblobfromfilesystem"))
            {
                BlobBlob blob = new BlobBlob(serviceBroker);
                blob.ExecuteUploadBlobFromFilePath(inputs, required, returns, methodType, serviceObject);
            }

            if (serviceObject.Methods[0].Name.Equals("uploadblobfromurl"))
            {
                BlobBlob blob = new BlobBlob(serviceBroker);
                blob.ExecuteUploadBlobFromUrl(inputs, required, returns, methodType, serviceObject);
            }

            if (serviceObject.Methods[0].Name.Equals("listblobs"))
            {
                BlobBlob blob = new BlobBlob(serviceBroker);
                blob.ExecuteListBlobs(inputs, required, returns, methodType, serviceObject);
            }

            if (serviceObject.Methods[0].Name.Equals("downloadblob"))
            {
                BlobBlob blob = new BlobBlob(serviceBroker);
                blob.ExecuteDownloadBlob(inputs, required, returns, methodType, serviceObject);
            }

            if (serviceObject.Methods[0].Name.Equals("downloadblobtobase64"))
            {
                BlobBlob blob = new BlobBlob(serviceBroker);
                blob.ExecuteDownloadBlobAsBase64(inputs, required, returns, methodType, serviceObject);
            }

            if (serviceObject.Methods[0].Name.Equals("downloadblobtofilesystem"))
            {
                BlobBlob blob = new BlobBlob(serviceBroker);
                blob.ExecuteDownloadBlobToFileSystem(inputs, required, returns, methodType, serviceObject);
            }

            if (serviceObject.Methods[0].Name.Equals("setblobproperties"))
            {
                BlobBlob blob = new BlobBlob(serviceBroker);
                blob.ExecuteSetBlobProperties(inputs, required, returns, methodType, serviceObject);
            }

            #endregion Blob

        }
 public BlobContainerViewModel(BlobContainer container)
 {
     this.Container = container;
     this.Container.MadeProgress += OnMadeProgress;
 }
 void OnMadeProgress(object sender, BlobContainer container)
 {
     RaisePropertyChanged("Status");
     RaisePropertyChanged("PercentageComplete");
     RaisePropertyChanged("Errors");
 }