Ejemplo n.º 1
0
        public static List<BlobHelper> GetAll(string container, string account, string key)
        {
            List<BlobHelper> list = new List<BlobHelper>();
            CloudBlobContainer cont = StorageHelper.Container.Get(account,key, container);

            if (cont == null)
                return list;

            BlobRequestOptions opt = new BlobRequestOptions();
            opt.BlobListingDetails = BlobListingDetails.All;
            opt.UseFlatBlobListing = true;

            foreach (IListBlobItem blob in cont.ListBlobs(opt))
            {
                CloudBlockBlob b = blob as CloudBlockBlob;
                if (b == null)
                    continue;

                b.FetchAttributes(opt);

                BlobHelper bh = new BlobHelper();
                bh.Url = b.Uri.ToString();
                bh.Name = b.Uri.Segments[b.Uri.Segments.Length - 1];
                bh.Size = b.Properties.Length;
                bh.Type = b.Properties.ContentType;
                bh.BlobType = b.Properties.BlobType.ToString();
                bh.LastModfied = b.Properties.LastModifiedUtc;
                bh.ETag = b.Properties.ETag;
                list.Add(bh);
            }

            return list;
        }
Ejemplo n.º 2
0
        public virtual Uri UploadFile(
            string storageName,
            Uri blobEndpointUri,
            string storageKey,
            string filePath,
            BlobRequestOptions blobRequestOptions)
        {
            StorageCredentials credentials = new StorageCredentials(storageName, storageKey);
            CloudBlobClient client = new CloudBlobClient(blobEndpointUri, credentials);
            string blobName = string.Format(
                CultureInfo.InvariantCulture,
                "{0}_{1}",
                DateTime.UtcNow.ToString("yyyyMMdd_HHmmss", CultureInfo.InvariantCulture),
                Path.GetFileName(filePath));

            CloudBlobContainer container = client.GetContainerReference(ContainerName);
            container.CreateIfNotExists();
            CloudBlockBlob blob = container.GetBlockBlobReference(blobName);

            BlobRequestOptions uploadRequestOption = blobRequestOptions ?? new BlobRequestOptions();

            if (!uploadRequestOption.ServerTimeout.HasValue)
            {
                uploadRequestOption.ServerTimeout = TimeSpan.FromMinutes(300);
            }

            using (FileStream readStream = File.OpenRead(filePath))
            {
                blob.UploadFromStream(readStream, AccessCondition.GenerateEmptyCondition(), uploadRequestOption);
            }

            return new Uri(string.Format(CultureInfo.InvariantCulture, "{0}{1}{2}{3}", client.BaseUri, ContainerName, client.DefaultDelimiter, blobName));
        }
        public static void ParallelUpload(this CloudBlockBlob blobRef, string filename, BlobRequestOptions options)
        {
            if (null == options)
            {
                options = new BlobRequestOptions()
                {
                    Timeout = blobRef.ServiceClient.Timeout,
                    RetryPolicy = RetryPolicies.RetryExponential(RetryPolicies.DefaultClientRetryCount, RetryPolicies.DefaultClientBackoff)
                };
            }

            // get upload history if any
            UploadInfo uploadInfo = UploadInfo.LoadByUploadFilename(filename);

            using (FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read))
            {
                blobRef.ParallelUpload(fs, uploadInfo, options);
            }

            // upload completed no history needed - delete it
            if (File.Exists(uploadInfo.LogFilename))
                File.Delete(uploadInfo.LogFilename);

            Console.WriteLine("\nUpload completed.");
        }
Ejemplo n.º 4
0
        public static void Read(BlobRequestOptions mapped, CloudBlob blob, ReaderDelegate reader)
        {
            blob.FetchAttributes(mapped);
            var props = MapFetchedAttrbitues(blob);

            var compression = blob.Properties.ContentEncoding ?? "";
            var md5 = blob.Metadata[LokadHashFieldName];

            switch (compression)
            {
                case "gzip":
                    using (var stream = blob.OpenRead(mapped))
                    {
                        ReadAndVerifyHash(stream, s =>
                            {
                                // important is not to flush the decompression stream
                                using (var decompress = new GZipStream(s, CompressionMode.Decompress, true))
                                {
                                    reader(props, decompress);
                                }
                            }, md5);
                    }

                    break;
                case "":
                    using (var stream = blob.OpenRead(mapped))
                    {
                        ReadAndVerifyHash(stream, s => reader(props, s), md5);
                    }
                    break;
                default:
                    var error = string.Format("Unsupported ContentEncoding '{0}'", compression);
                    throw new InvalidOperationException(error);
            }
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Uploads a file to azure store.
        /// </summary>
        /// <param name="storageName">Store which file will be uploaded to</param>
        /// <param name="storageKey">Store access key</param>
        /// <param name="filePath">Path to file which will be uploaded</param>
        /// <param name="blobRequestOptions">The request options for blob uploading.</param>
        /// <returns>Uri which holds locates the uploaded file</returns>
        /// <remarks>The uploaded file name will be guid</remarks>
        public static Uri UploadFile(string storageName, string storageKey, string filePath, BlobRequestOptions blobRequestOptions)
        {
            string baseAddress = General.BlobEndpointUri(storageName);
            var credentials = new StorageCredentialsAccountAndKey(storageName, storageKey);
            var client = new CloudBlobClient(baseAddress, credentials);
            string blobName = Guid.NewGuid().ToString();

            CloudBlobContainer container = client.GetContainerReference(ContainerName);
            container.CreateIfNotExist();
            CloudBlob blob = container.GetBlobReference(blobName);

            using (FileStream readStream = File.OpenRead(filePath))
            {
                blob.UploadFromStream(readStream, blobRequestOptions);
            }

            return new Uri(
                string.Format(
                    CultureInfo.InvariantCulture,
                    "{0}{1}{2}{3}",
                    client.BaseUri,
                    ContainerName,
                    client.DefaultDelimiter,
                    blobName));
        }
Ejemplo n.º 6
0
		public IBlob Get(Uri uri)
		{
			IBlob blob = null;

			var options = new BlobRequestOptions { BlobListingDetails = BlobListingDetails.Metadata };

			var container = getContainer();
			var target = container.GetBlobReference(uri.ToString());

			try
			{
				target.FetchAttributes();
				blob = new Blob(target.Properties.ContentMD5, target.Properties.ETag)
					{ Content = target.DownloadByteArray(), ContentType = target.Properties.ContentType, };

				foreach (var key in target.Metadata.AllKeys)
				{
					blob.Metdata.Add(new KeyValuePair<string, string>(key, target.Metadata[key]));
				}
			}
			catch (StorageClientException s)
			{
				this.WriteErrorMessage(string.Format("An error occurred retrieving the blob from {0}", uri), s);
				blob = null;
			}

			return blob;
		}
Ejemplo n.º 7
0
        public static Uri UploadPackageToBlob(IServiceManagement channel, string storageName, string subscriptionId, string packagePath, BlobRequestOptions blobRequestOptions)
        {
            StorageService storageService = channel.GetStorageKeys(subscriptionId, storageName);
            string storageKey = storageService.StorageServiceKeys.Primary;

            return UploadFile(storageName, storageKey, packagePath, blobRequestOptions);
        }
Ejemplo n.º 8
0
        public static bool DeletePhotoBlob(Guid photoId)
        {
            try
            {
                // Delete from Azure
                CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
                    ConfigurationManager.ConnectionStrings["StorageConnectionString"].ConnectionString);

                CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();

                // Get a reference to the container.
                CloudBlobContainer container = blobClient.GetContainerReference("photos");

                // Indicate that any snapshots should be deleted.
                BlobRequestOptions options = new BlobRequestOptions();
                options.DeleteSnapshotsOption = DeleteSnapshotsOption.IncludeSnapshots;

                // Specify a flat blob listing, so that only CloudBlob objects will be returned.
                // The Delete method exists only on CloudBlob, not on IListBlobItem.
                options.UseFlatBlobListing = true;

                var blob = container.GetBlobReference(photoId.ToString());

                blob.Delete(options);

                return true;
            }
            catch
            {
            }

            return false;
        }
        public static CloudBlockBlob[] GetTarget_BatchToProcess(int processBatchSize, bool processIfLess)
        {
            //options.
            //options.AccessCondition
            //StorageSupport.CurrActiveContainer.ListBlobsSegmented()
            //    ListBlobsWithPrefix("sys/AAA/TheBall.CORE/RequestResourceUsage")
            string prefix = "sys/AAA/TheBall.CORE/RequestResourceUsage/";

            BlobRequestOptions options = new BlobRequestOptions {UseFlatBlobListing = true};
            var blobList = StorageSupport.CurrActiveContainer.ListBlobxWithPrefixSegmented(prefix, processBatchSize, null, options);
            List<CloudBlockBlob> result = new List<CloudBlockBlob>();
            foreach (var blobListItem in blobList.Results)
            {
                CloudBlockBlob blob = (CloudBlockBlob) blobListItem;
                if (blob.Name == LockLocation)
                    return null;
                result.Add(blob);
            }
            if (result.Count < processBatchSize && processIfLess == false)
                return null;
            // Acquire Lock
            string lockETag;
            bool acquiredLock = StorageSupport.AcquireLogicalLockByCreatingBlob(LockLocation, out lockETag);
            if (!acquiredLock)
                return null;
            return result.ToArray();
        }
        public static async Task<CloudBlobContainer> GetBlobContainer(string containerName)
        {
            if (String.IsNullOrEmpty(containerName))
            {
                throw new ArgumentException("containerName");
            }

            // Retrieve storage account from connection-string
            string connectionString = CloudConfigurationManager.GetSetting("CloudStorageConnectionString");
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(connectionString);

            // Create the blob client 
            CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();

            // Retrieve a reference to a container. Note that container name must use lower case
            CloudBlobContainer container = blobClient.GetContainerReference(containerName.ToLowerInvariant());

            // Create options for communicating with the blob container.
            BlobRequestOptions options = new BlobRequestOptions();

            // Create the container if it doesn't already exist
            bool result = await Task.Factory.FromAsync<BlobRequestOptions, bool>(container.BeginCreateIfNotExist, container.EndCreateIfNotExist, options, state: null);

            // Enable public access to blob
            BlobContainerPermissions permissions = container.GetPermissions();
            if (permissions.PublicAccess == BlobContainerPublicAccessType.Off)
            {
                permissions.PublicAccess = BlobContainerPublicAccessType.Blob;
                container.SetPermissions(permissions);
            }

            return container;
        }
Ejemplo n.º 11
0
 public static Uri UploadFile(
     string storageName,
     Uri blobEndpointUri,
     string storageKey,
     string filePath,
     BlobRequestOptions blobRequestOptions)
 {
     return cloudBlobUtility.UploadFile(storageName, blobEndpointUri, storageKey, filePath, blobRequestOptions);
 }
Ejemplo n.º 12
0
        public static Uri UploadPackageToBlob(IServiceManagement channel, string storageName, string subscriptionId, string packagePath, BlobRequestOptions blobRequestOptions)
        {
            StorageService storageService = channel.GetStorageKeys(subscriptionId, storageName);
            string storageKey = storageService.StorageServiceKeys.Primary;
            storageService = channel.GetStorageService(subscriptionId, storageName);
            string blobEndpointUri = storageService.StorageServiceProperties.Endpoints[0];

            return UploadFile(storageName, CreateHttpsEndpoint(blobEndpointUri), storageKey, packagePath, blobRequestOptions);
        }
Ejemplo n.º 13
0
 /// <summary>Initializes a new instance of the <see cref="ParallelUpload"/> class.</summary>
 /// <param name="source">The source stream. </param>
 /// <param name="options">The request options. </param>
 /// <param name="blockSize">The block size to use. </param>
 /// <param name="blob">The blob to upload to. </param>
 internal ParallelUpload(Stream source, BlobRequestOptions options, long blockSize, CloudBlockBlob blob)
 {
     this.sourceStream = source;
     this.blockSize = blockSize;
     this.options = options;
     this.dispensizedStreamSize = 0;
     this.blob = blob;
     this.blobHash = MD5.Create();
     this.blockList = new List<string>();
     this.parellelism = this.GetParallelismFactor();
 }
Ejemplo n.º 14
0
 public XStoreExperiment(Guid experimentId, CloudBlobClient client, string title, int requestedIterations, string instanceId)
     : base(experimentId, title, requestedIterations, instanceId)
 {
     this.instanceId = instanceId;
     this.client = client;
     this.requestOptions = new BlobRequestOptions
     {
         RetryPolicy = TrackedPolicy,
         Timeout = TimeSpan.FromMinutes(5),
     };
 }
Ejemplo n.º 15
0
 public static Uri UploadPackageToBlob(
     StorageManagementClient storageClient,
     string storageName,
     string packagePath,
     BlobRequestOptions blobRequestOptions)
 {
     return cloudBlobUtility.UploadPackageToBlob(
         storageClient,
         storageName,
         packagePath,
         blobRequestOptions);
 }
Ejemplo n.º 16
0
        /// <summary>
        /// Initializes a new instance of the BlobReadStream class. 
        /// </summary>
        /// <param name="blob">The blob used for downloads.</param>
        /// <param name="options">Modifiers to be applied to the blob. After first request, the ETag is always applied.</param>
        /// <param name="readAheadInBytes">The number of bytes to read ahead.</param>
        /// <param name="verifyBlocks">Controls whether block's signatures are verified.</param>
        internal BlobReadStream(CloudBlob blob, BlobRequestOptions options, long readAheadInBytes, bool verifyBlocks)
        {
            CommonUtils.AssertNotNull("blob", blob);
            CommonUtils.AssertNotNull("options", options);
            CommonUtils.AssertInBounds("readAheadInBytes", readAheadInBytes, 0, Protocol.Constants.MaxBlobSize);

            this.Blob = blob;
            this.IntegrityControlVerificationEnabled = verifyBlocks;
            this.options = options;
            this.ReadAheadSize = readAheadInBytes;

            this.downloadedBlocksList = new DownloadedBlockCollection();
        }
Ejemplo n.º 17
0
        /// <summary>
        /// Gets the web request.
        /// </summary>
        /// <param name="serviceClient">The service client.</param>
        /// <param name="options">The options.</param>
        /// <param name="retrieveRequest">The retrieve request.</param>
        /// <returns>The web request.</returns>
        internal static HttpWebRequest GetWebRequest(CloudBlobClient serviceClient, BlobRequestOptions options, Func<int, HttpWebRequest> retrieveRequest)
        {
            CommonUtils.AssertNotNull("options", options);

            int timeoutInSeconds = options.Timeout.RoundUpToSeconds();
            AccessCondition accessCondition = options.AccessCondition;

            var webRequest = retrieveRequest(timeoutInSeconds);
            accessCondition.ApplyCondition(webRequest);
            CommonUtils.ApplyRequestOptimizations(webRequest, -1);

            return webRequest;
        }
Ejemplo n.º 18
0
 public static Uri UploadPackageToBlob(
     IServiceManagement channel,
     string storageName,
     string subscriptionId,
     string packagePath,
     BlobRequestOptions blobRequestOptions)
 {
     return cloudBlobUtility.UploadPackageToBlob(
         channel,
         storageName,
         subscriptionId,
         packagePath,
         blobRequestOptions);
 }
Ejemplo n.º 19
0
 public virtual Uri UploadPackageToBlob(
     StorageManagementClient storageClient,
     string storageName,
     string packagePath,
     BlobRequestOptions blobRequestOptions)
 {
     StorageAccountGetKeysResponse keys = storageClient.StorageAccounts.GetKeys(storageName);
     string storageKey = keys.PrimaryKey;
     var storageService = storageClient.StorageAccounts.Get(storageName);
     Uri blobEndpointUri = storageService.StorageAccount.Properties.Endpoints[0];
     return UploadFile(storageName,
         GeneralUtilities.CreateHttpsEndpoint(blobEndpointUri.ToString()),
         storageKey, packagePath, blobRequestOptions);
 }
Ejemplo n.º 20
0
        public void UploadBlock(Stream input, long offset)
        {
            input.Seek(0, SeekOrigin.Begin);

            string blockId = this.EncodeOffset(offset);
            string contentMD5 = this.CalculateMD5(input);

            var options = new BlobRequestOptions
            {
                RetryPolicy = RetryPolicies.RetryExponential(
                RetryPolicies.DefaultClientRetryCount,
                RetryPolicies.DefaultClientBackoff)
            };
            this.blob.PutBlock(blockId, input, contentMD5, options);
        }
Ejemplo n.º 21
0
        /// <summary>Initializes a new instance of the BlobWriteStream class.</summary>
        /// <param name="blob">The blob used for uploads. </param>
        /// <param name="options">The options used for the stream. </param>
        /// <param name="blockSize">The size of the blocks to use. </param>
        internal BlobWriteStream(CloudBlockBlob blob, BlobRequestOptions options, long blockSize)
        {
            CommonUtils.AssertNotNull("blob", blob);
            CommonUtils.AssertNotNull("options", options);

            this.Blob = blob;
            this.blobHash = MD5.Create();
            this.BlockSize = blockSize;
            this.blockList = new List<string>();
            this.currentModifier = options;
            this.canWrite = true;

            var rand = new Random();
            this.blockIdSequenceNumber = (long)rand.Next() << 32;
            this.blockIdSequenceNumber += rand.Next();
        }
Ejemplo n.º 22
0
        public Dictionary<string, string> GetReferenceHashMap()
        {
            var output = new Dictionary<string, string>();

            var options = new BlobRequestOptions();
            options.UseFlatBlobListing = true;

            foreach (var item in Container.ListBlobs(options)) {
                //var reference = item.Uri.AbsolutePath.Substring(item.Uri.AbsolutePath.IndexOf('/', 1) + 1);
                var blob = ((CloudBlob)item);

                output[blob.Name] = blob.Properties.ContentMD5;
            }

            return output;
        }
Ejemplo n.º 23
0
        // The mutex must already exists
        public Mutex(CloudBlobContainer container, string mutexName, Exception e)
        {
            blob = container.GetBlobReference(mutexName);

            byte[] b1 = { 1 };
            BlobRequestOptions requestOpt = new BlobRequestOptions();
            bool keepGoing = true;
            string oldEtag = "";
            int lastChange = 0;
            do
            {
                byte[] b;
                string eTag;
                try
                {
                    blob.FetchAttributes();
                    eTag = blob.Attributes.Properties.ETag;
                    if (eTag != oldEtag)
                    {
                        lastChange = Environment.TickCount;
                        oldEtag = eTag;
                    }
                    b = blob.DownloadByteArray();
                }
                catch (Exception)
                {
                    throw e;
                }

                requestOpt.AccessCondition = AccessCondition.IfMatch(eTag);
                if (b[0] == 0 || Environment.TickCount - lastChange > 3000) // on ne peut garder un lock plus de 3 s
                {
                    try
                    {
                        blob.UploadByteArray(b1, requestOpt);
                        keepGoing = false;
                    }
                    catch (StorageClientException ex)
                    {
                        if (ex.ErrorCode != StorageErrorCode.ConditionFailed)
                            throw;
                    }
                }
                else
                    Thread.Sleep(50);   // constante arbitraire
            } while (keepGoing);
        }
Ejemplo n.º 24
0
        protected static Uri UploadFile(String path, TimeSpan timeout)
        {
            Console.WriteLine("Uploading " + path + " to " + StorageContainer + " Blob Storage Container");
            StorageCredentialsAccountAndKey credentials = new StorageCredentialsAccountAndKey(StorageAccount, StorageKey);
            string accountUri = string.Format(AzureBlobUriFormat , StorageAccount);
            CloudBlobClient blobStorage = new CloudBlobClient(accountUri, credentials);
            blobStorage.SingleBlobUploadThresholdInBytes = SingleBlobUploadThresholdInBytes;
            CloudBlobContainer container = blobStorage.GetContainerReference(StorageContainer);
            //TODO: Support container properties
            container.CreateIfNotExist();
            CloudBlob blob = container.GetBlobReference(Path.GetFileName(path));
            BlobRequestOptions options = new BlobRequestOptions();
            options.Timeout = timeout;

            blob.UploadFile(path, options);
            return blob.Uri;
        }
Ejemplo n.º 25
0
        public static List<StorageItem> GetBlobs(string containerName)
        {
            BlobRequestOptions options = new BlobRequestOptions();
            options.BlobListingDetails = BlobListingDetails.All;
            options.UseFlatBlobListing = true;

            var listBlobItems = GetContainer(containerName).ListBlobs(options);
            var blobs = new List<StorageItem>();
            foreach (var listBlobItem in listBlobItems)
            {
                var blob = new StorageItem();
                blob.Uri = listBlobItem.Uri;
                if (listBlobItem is CloudBlob)
                    blob.Name = ((CloudBlob)listBlobItem).Name;
                blobs.Add(blob);
            }
            return blobs;
        }
        public string ListBlobs()
        {
            try {
                CloudStorageAccount storageAccount = CloudStorageAccount.Parse(RoleEnvironment.GetConfigurationSettingValue("StorageConnectionString"));

                CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
                CloudBlobContainer con = blobClient.GetContainerReference("profile-pictures");

                BlobRequestOptions opts = new BlobRequestOptions();
                opts.UseFlatBlobListing = true;

                foreach (CloudBlob blob in con.ListBlobs(opts)) {
                    Response.Write(blob.Name);
                }

                return "";
            } catch (Exception e) {
                return e.Message;
            }
        }
Ejemplo n.º 27
0
        public void CopyFromBlob(string destinationSasUri, string srcBlobSasUri)
        {
            CloudBlockBlob blob = new CloudBlockBlob(srcBlobSasUri);
            string fileName = (blob.Name.Contains("/"))
                ? blob.Name.Substring(blob.Name.LastIndexOf("/"))
                : blob.Name;
            CloudBlobContainer cbc = new CloudBlobContainer(destinationSasUri);

            //UriBuilder ub = new UriBuilder(destUri);
            //ub.Path += "/" + fileName;
            //CloudBlockBlob destBlob = new CloudBlockBlob(ub.Uri);
            CloudBlockBlob destBlob = cbc.GetBlockBlobReference(fileName);
            BlobRequestOptions bro = new BlobRequestOptions();
            bro.RetryPolicy =  RetryPolicies.RetryExponential(5, TimeSpan.FromMilliseconds(150));
            destBlob.BeginCopyFromBlob(blob, bro, (result) => {  }, null);

               // destBlob.UploadFromStream(System.IO.File.OpenRead(@"D:\Install.txt"));

            System.Diagnostics.Debug.WriteLine(destBlob.Name);
        }
Ejemplo n.º 28
0
        public static AutoRenewLease GetOrThrow(CloudBlob blob)
        {
            blob.Container.CreateIfNotExist();

            // Create lock blob
            try
            {
                var requestOptions = new BlobRequestOptions
                {
                    AccessCondition = AccessCondition.IfNoneMatch("*")
                };
                blob.UploadByteArray(new byte[0], requestOptions);
            }
            catch (StorageClientException e)
            {
                if (e.ErrorCode != StorageErrorCode.BlobAlreadyExists
                    && e.StatusCode != HttpStatusCode.PreconditionFailed)
                // 412 from trying to modify a blob that's leased
                {
                    throw;
                }
            }

            string leaseId = null;
            var ex = DoUntilTrue(Try4Times, CancellationToken.None, () =>
            {
                leaseId = AcquireLease(blob);
                return !String.IsNullOrEmpty(leaseId);
            });
            if (ex != null)
                throw new InvalidOperationException("Failed to get lease", ex);

            // Either we get lease or throw timeout exception
            if (String.IsNullOrEmpty(leaseId))
                throw new InvalidOperationException();

            return new AutoRenewLease(blob, leaseId);
        }
Ejemplo n.º 29
0
        /// <summary>
        /// List all blobs in specified containers
        /// </summary>
        /// <param name="container">A cloudblobcontainer object</param>
        /// <param name="prefix">Blob prefix</param>
        /// <param name="useFlatBlobListing">Use flat blob listing(whether treat "container/" as directory)</param>
        /// <param name="blobListingDetails">Blob listing details</param>
        /// <param name="options">Blob request option</param>
        /// <param name="operationContext">Operation context</param>
        /// <returns>An enumerable collection of icloudblob</returns>
        public IEnumerable <IListBlobItem> ListBlobs(CloudBlobContainer container, string prefix, bool useFlatBlobListing, BlobListingDetails blobListingDetails, BlobRequestOptions options, OperationContext operationContext)
        {
            string containerName = container.Name;

            if (ContainerBlobs.ContainsKey(containerName))
            {
                List <ICloudBlob> blobList = ContainerBlobs[containerName];

                if (string.IsNullOrEmpty(prefix))
                {
                    return(blobList);
                }

                List <ICloudBlob> prefixBlobs = new List <ICloudBlob>();

                foreach (ICloudBlob blob in blobList)
                {
                    if (blob.Name.StartsWith(prefix))
                    {
                        prefixBlobs.Add(blob);
                    }
                }

                return(prefixBlobs);
            }
            else
            {
                return(new List <ICloudBlob>());
            }
        }
Ejemplo n.º 30
0
        // Put (create or update) a blob conditionally based on expected ETag value.
        // Return true on success, false if unable to create, throw exception on error.
        public bool PutBlobIfUnchanged(string containerName, string blobName, string content, string ExpectedETag)
        {
            try
            {
                CloudBlobContainer container = BlobClient.GetContainerReference(containerName);
                CloudBlob blob = container.GetBlobReference(blobName);
                BlobRequestOptions options = new BlobRequestOptions();
                options.AccessCondition = AccessCondition.IfMatch(ExpectedETag);
                blob.UploadText(content, new UTF8Encoding(), options);
                return true;
            }
            catch (StorageClientException ex)
            {
                if ((int)ex.StatusCode == 404 || (int)ex.StatusCode == 412)
                {
                    return false;
                }

                throw;
            }
        }
Ejemplo n.º 31
0
 /// <summary>
 /// Return a task that asynchronously get the blob reference from server
 /// </summary>
 /// <param name="container">CloudBlobContainer object</param>
 /// <param name="blobName">Blob name</param>
 /// <param name="accessCondition">Access condition</param>
 /// <param name="options">Blob request options</param>
 /// <param name="operationContext">Operation context</param>
 /// <param name="cmdletCancellationToken">Cancellation token</param>
 /// <returns>A task object that asynchronously get the blob reference from server</returns>
 public Task <ICloudBlob> GetBlobReferenceFromServerAsync(CloudBlobContainer container, string blobName, AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext, CancellationToken cmdletCancellationToken)
 {
     return(Task.Factory.StartNew(() => this.GetBlobReferenceFromServer(container, blobName, accessCondition, options, operationContext)));
 }
Ejemplo n.º 32
0
 /// <summary>
 /// Return a task that asynchronously fetch blob attributes
 /// </summary>
 /// <param name="blob">ICloud blob object</param>
 /// <param name="accessCondition">Access condition</param>
 /// <param name="options">Blob request options</param>
 /// <param name="operationContext">Operation context</param>
 /// <param name="cmdletCancellationToken">Cancellation token</param>
 /// <returns>Return a task that asynchronously fetch blob attributes</returns>
 public Task FetchBlobAttributesAsync(ICloudBlob blob, AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext, CancellationToken cmdletCancellationToken)
 {
     return(Task.Factory.StartNew(() => this.FetchBlobAttributes(blob, accessCondition, options, operationContext)));
 }
Ejemplo n.º 33
0
        async void OnUploadButtonClicked(object sender, EventArgs e)
        {
            //string man = Entername.Text;
            try
            {
                //AcountsDB IPA = new AcountsDB();
                //SQLiteConnection s;
                //s = DependencyService.Get<ISQLite>().GetConnection();
                //s.Table<AcountsDB>();
                //IPA.Category = pickcategory;
                //IPA.TotalAmount = uploadEditor.Text;
                //IPA.GSTAmount = Entername.Text;
                //IPA.Account = pickname;
                //// IPA.backgrund = themetyp;
                //AcountsQuery c = new AcountsQuery();
                //c.InsertDetails(IPA);


                //AcountsQuery IPRI = new AcountsQuery();
                //SQLiteConnection IPKI;
                //IPKI = DependencyService.Get<ISQLite>().GetConnection();
                //IPKI.Table<AcountsDB>();
                ////  var tikcount = d.ExecuteScalar<string>("SELECT TicketNum FROM TicketNumber");
                //var backnow = IPKI.ExecuteScalar<string>("SELECT Category FROM AcountsDB ORDER BY Id DESC LIMIT 1");

                // await DisplayAlert("INSERTED DETAILS", backnow, "OK");


                if (!string.IsNullOrWhiteSpace(uploadEditor.Text) && !string.IsNullOrWhiteSpace(Entername.Text))
                {
                    activityIndicator.IsRunning = true;

                    BlobRequestOptions parallelThreadCountOptions = new BlobRequestOptions();

                    string listname = "Category:" + "-" + pickcategory + Environment.NewLine + "Total Amount GST:" + "-" + uploadEditor.Text + Environment.NewLine + "GST Amount:" + "-" + Entername.Text + Environment.NewLine + "Amount:" + "-" + pickname;

                    //AcountsDB IPA = new AcountsDB();
                    //SQLiteConnection s;
                    //s = DependencyService.Get<ISQLite>().GetConnection();
                    //s.Table<AcountsDB>();
                    catdetail = pickcategory;
                    totalGST  = uploadEditor.Text;
                    //IPA.TotalAmount = uploadEditor.Text;
                    //IPA.GSTAmount = Entername.Text;
                    //IPA.Account = pickname;
                    //// IPA.backgrund = themetyp;
                    //AcountsQuery c = new AcountsQuery();
                    //c.InsertDetails(IPA);

                    //  var byteData = Encoding.UTF8.GetBytes(uploadEditor.Text);
                    var byteDatayw = Encoding.UTF8.GetBytes(listname);

                    // Allow up to four simultaneous I/O operations.
                    parallelThreadCountOptions.ParallelOperationThreadCount = 4;
                    // blob.UploadFromFile(uploadedFilename, accessCondition: null, options: parallelThreadCountOptions, operationContext: null);

                    // uploadedFilename = await AzureStorage.UploadFileAsync(ContainerType.Text, new MemoryStream(listname));
                    uploadedFilename = await AzureStorage.UploadFileAsync(ContainerType.Text, new MemoryStream(byteDatayw));

                    // downloadButton.IsEnabled = true;
                    activityIndicator.IsRunning = false;

                    //  var itemSelectedData = e.SelectedItem as AccountsModel;

                    await Navigation.PushAsync(new AccountsLastDetl());
                }

                else
                {
                    await DisplayAlert("INSERTED DETAILS", "SOME FILEDS ARE MISSING", "OK");
                }

                //await Navigation.PushAsync(new TextFileBrowserPage());
                // await Navigation.PushAsync(new AccountsLastDetl());
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Test 8");
                Debug.WriteLine(ex.ToString());
                // return null;
            }
        }
Ejemplo n.º 34
0
 /// <summary>
 /// Return a task that asynchronously abort the blob copy operation
 /// </summary>
 /// <param name="blob">ICloudBlob object</param>
 /// <param name="abortCopyId">Copy id</param>
 /// <param name="accessCondition">Access condition</param>
 /// <param name="abortRequestOption">Blob request options</param>
 /// <param name="operationContext">Operation context</param>
 /// <param name="cmdletCancellationToken">Cancellation token</param>
 /// <returns>Return a task that asynchronously abort the blob copy operation</returns>
 public Task AbortCopyAsync(ICloudBlob blob, string copyId, AccessCondition accessCondition, BlobRequestOptions requestOption, OperationContext operationContext, CancellationToken cmdletCancellationToken)
 {
     return(Task.Factory.StartNew(() => this.AbortCopy(blob, copyId, accessCondition, requestOption, operationContext)));
 }
Ejemplo n.º 35
0
        static async Task Main(string[] args)
        {
            if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
            {
                _client = new DockerClientConfiguration(new Uri("unix:///var/run/docker.sock")).CreateClient();
            }

            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                _client = new DockerClientConfiguration(new Uri("npipe://./pipe/docker_engine")).CreateClient();
            }

            IList <ContainerListResponse> containers = await _client.Containers.ListContainersAsync(
                new ContainersListParameters()
            {
                Limit = 10,
            });

            ContainerListResponse        edgeAgent   = null;
            List <ContainerListResponse> edgeModules = new List <ContainerListResponse>();

            foreach (var container in containers)
            {
                foreach (var label in container.Labels)
                {
                    if (label.Key.Contains("net.azure-devices.edge.owner"))
                    {
                        edgeModules.Add(container);
                    }
                }

                // edge case due to bug (no pun intended)
                if (container.Names.First() == "/edgeAgent")
                {
                    edgeAgent = container;
                    break;
                }
                Console.WriteLine($"{container.ID}");
            }

            TelemetryClient telemetry = new TelemetryClient();

            telemetry.InstrumentationKey = "";

            string containerName = "iotlogs";
            string blobName      = string.Format("{0}-{1}{2}", edgeAgent.Names.First().TrimStart('/'), DateTime.UtcNow.ToString("yyyy-MM-dd-hh-mm-ss"), ".log");
            string accountName   = "";
            string keyValue      = "";

            StorageCredentials  creds         = new StorageCredentials(accountName, keyValue);
            CloudStorageAccount account       = new CloudStorageAccount(creds, true);
            CloudBlobClient     blobClient    = account.CreateCloudBlobClient();
            CloudBlobContainer  blobContainer = blobClient.GetContainerReference(containerName);

            try
            {
                BlobRequestOptions requestOptions = new BlobRequestOptions()
                {
                    RetryPolicy = new NoRetry()
                };
                await blobContainer.CreateIfNotExistsAsync(requestOptions, null);
            }
            catch (StorageException)
            {
                Console.WriteLine("If you are running with the default connection string, please make sure you have started the storage emulator. Press the Windows key and type Azure Storage to select and run it from the list of applications - then restart the sample.");
                Console.ReadLine();
                throw;
            }

            CloudAppendBlob blockBlob = blobContainer.GetAppendBlobReference(blobName);

            ContainerLogsParameters logsParameters = new ContainerLogsParameters()
            {
                ShowStderr = true, ShowStdout = true, Follow = true
            };
            Stream logs = await _client.Containers.GetContainerLogsAsync(edgeAgent.ID, logsParameters, CancellationToken.None);

            List <string> logdata = new List <string>();

            using (StreamReader reader = new StreamReader(logs))
            {
                string line;
                while (true)
                {
                    line = await reader.ReadLineAsync();

                    if (!string.IsNullOrEmpty(line))
                    {
                        logdata.Add(line);
                        Console.WriteLine(line);
                    }

                    if (logdata.Count > 500)
                    {
                        if (useStorage)
                        {
                            Console.WriteLine("Uploading...");
                            string data = string.Join(System.Environment.NewLine, logdata);
                            await blockBlob.CreateOrReplaceAsync();

                            try
                            {
                                await blockBlob.AppendTextAsync(data);
                            }
                            catch (System.Exception up)
                            {
                                throw up;
                            }

                            logdata.Clear();
                        }
                        else
                        {
                            Console.WriteLine("Uploading...");

                            try
                            {
                                foreach (var msg in logdata)
                                {
                                    telemetry.TrackTrace(msg);
                                }
                            }
                            catch (System.Exception up)
                            {
                                throw up;
                            }

                            logdata.Clear();
                        }
                    }
                }
            }
        }
Ejemplo n.º 36
0
        /// <summary>
        /// Set container permissions
        /// </summary>
        /// <param name="container">A cloudblobcontainer object</param>
        /// <param name="permissions">The container's permission</param>
        /// <param name="accessCondition">Access condition</param>
        /// <param name="options">Blob request option</param>
        /// <param name="operationContext">Operation context</param>
        public void SetContainerPermissions(CloudBlobContainer container, BlobContainerPermissions permissions, AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext)
        {
            String name = container.Name;

            if (ContainerPermissions.ContainsKey(name))
            {
                ContainerPermissions[name] = permissions;
            }
            else
            {
                ContainerPermissions.Add(name, permissions);
            }
        }
Ejemplo n.º 37
0
        /// <summary>
        /// Get container permissions
        /// </summary>
        /// <param name="container">A cloudblobcontainer object</param>
        /// <param name="accessCondition">Access condition</param>
        /// <param name="options">Blob request option</param>
        /// <param name="operationContext">Operation context</param>
        /// <returns>The container's permission</returns>
        public BlobContainerPermissions GetContainerPermissions(CloudBlobContainer container, AccessCondition accessCondition = null, BlobRequestOptions options = null, OperationContext operationContext = null)
        {
            BlobContainerPermissions defaultPermission = new BlobContainerPermissions();

            defaultPermission.PublicAccess = BlobContainerPublicAccessType.Off;

            if (ContainerPermissions.ContainsKey(container.Name))
            {
                return(ContainerPermissions[container.Name]);
            }
            else
            {
                return(defaultPermission);
            }
        }
Ejemplo n.º 38
0
 /// <summary>
 /// List the blobs segmented in specified containers
 /// </summary>
 /// <param name="container">A cloudblobcontainer object</param>
 /// <param name="prefix">Blob prefix</param>
 /// <param name="useFlatBlobListing">Use flat blob listing(whether treat "container/" as directory)</param>
 /// <param name="blobListingDetails">Blob listing details</param>
 /// <param name="options">Blob request option</param>
 /// <param name="operationContext">Operation context</param>
 public Task <BlobResultSegment> ListBlobsSegmentedAsync(CloudBlobContainer container, string prefix, bool useFlatBlobListing, BlobListingDetails blobListingDetails, int?maxResults, BlobContinuationToken currentToken, BlobRequestOptions options, OperationContext operationContext, CancellationToken cancellationToken)
 {
     //BlobResultSegment is sealed without any public constructors.
     throw new NotImplementedException();
 }
Ejemplo n.º 39
0
 /// <summary>
 /// Async Get container presssions
 /// </summary>
 /// <param name="container">A cloudblobcontainer object</param>
 /// <param name="accessCondition">Access condition</param>
 /// <param name="options">Blob request option</param>
 /// <param name="operationContext">Operation context</param>
 /// <param name="cancellationToken">User cancellation token</param>
 /// <returns>A task object which retrieve the permission of the specified container</returns>
 public Task <BlobContainerPermissions> GetContainerPermissionsAsync(CloudBlobContainer container, AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext, CancellationToken cancellationToken)
 {
     return(Task.Factory.StartNew(() => this.GetContainerPermissions(container,
                                                                     accessCondition, options, operationContext)));
 }
Ejemplo n.º 40
0
 /// <summary>
 /// Return a task that asynchronously set blob meta data
 /// </summary>
 /// <param name="blob">ICloud blob object</param>
 /// <param name="accessCondition">Access condition</param>
 /// <param name="options">Blob request options</param>
 /// <param name="operationContext">An object that represents the context for the current operation.</param>
 public Task SetBlobMetadataAsync(ICloudBlob blob, AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext, CancellationToken cmdletCancellationToken)
 {
     return(Task.Factory.StartNew(() => this.SetBlobMetadata(blob, accessCondition, options, operationContext)));
 }
Ejemplo n.º 41
0
 /// <summary>
 /// Return a task that asynchronously delete the specified blob
 /// </summary>
 /// <param name="blob">ICloudBlob object</param>
 /// <param name="deleteSnapshotsOption">Snapshot delete option</param>
 /// <param name="accessCondition">Access condition</param>
 /// <param name="requestOptions">Blob request option</param>
 /// <param name="operationContext">Operation context</param>
 /// <param name="cmdletCancellationToken">Cancellation token</param>
 /// <returns>Return a task that asynchronously delete the specified blob</returns>
 public Task DeleteICloudBlobAsync(ICloudBlob blob, DeleteSnapshotsOption deleteSnapshotsOption, AccessCondition accessCondition, BlobRequestOptions requestOptions, OperationContext operationContext, CancellationToken cmdletCancellationToken)
 {
     return(Task.Factory.StartNew(() => this.DeleteICloudBlob(blob, deleteSnapshotsOption, accessCondition, requestOptions, operationContext)));
 }
Ejemplo n.º 42
0
 /// <summary>
 /// Return a task that asynchronously check whether the specified container exists.
 /// </summary>
 /// <param name="container">CloudBlobContainer object</param>
 /// <param name="requestOptions">Blob request option</param>
 /// <param name="operationContext">Operation context</param>
 /// <param name="cmdletCancellationToken">Cancellation token</param>
 /// <returns>A task object that asynchronously check whether the specified container exists </returns>
 public Task <bool> DoesContainerExistAsync(CloudBlobContainer container, BlobRequestOptions requestOptions, OperationContext operationContext, CancellationToken cmdletCancellationToken)
 {
     return(Task.Factory.StartNew(() => this.DoesContainerExist(container, requestOptions, operationContext)));
 }
Ejemplo n.º 43
0
        /// <summary>
        /// Get blob reference with properties and meta data from server
        /// </summary>
        /// <param name="container">A cloudblobcontainer object</param>
        /// <param name="blobName">Blob name</param>
        /// <param name="accessCondition">Access condition</param>
        /// <param name="options">Blob request options</param>
        /// <param name="operationContext">Operation context</param>
        /// <returns>Return an ICloudBlob if the specific blob exists on azure, otherwise return null</returns>
        public ICloudBlob GetBlobReferenceFromServer(CloudBlobContainer container, string blobName, AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext)
        {
            string containerName = container.Name;

            if (ContainerBlobs.ContainsKey(containerName))
            {
                List <ICloudBlob> blobList = ContainerBlobs[containerName];

                foreach (ICloudBlob blob in blobList)
                {
                    if (blob.Name == blobName)
                    {
                        return(blob);
                    }
                }

                return(null);
            }
            else
            {
                return(null);
            }
        }
Ejemplo n.º 44
0
 /// <summary>
 /// Return a task that asynchronously create a container if it doesn't exist.
 /// </summary>
 /// <param name="container">CloudBlobContainer object</param>
 /// <param name="accessType">Blob container public access type</param>
 /// <param name="requestOptions">Blob request options</param>
 /// <param name="operationContext">Operation context</param>
 /// <param name="cmdletCancellationToken">Cancellation token</param>
 /// <returns>Return a task that asynchronously create a container if it doesn't exist.</returns>
 public Task <bool> CreateContainerIfNotExistsAsync(CloudBlobContainer container, BlobContainerPublicAccessType accessType, BlobRequestOptions requestOptions, OperationContext operationContext, CancellationToken cmdletCancellationToken)
 {
     return(Task.Factory.StartNew(() => this.CreateContainerIfNotExists(container, requestOptions, operationContext)));
 }
Ejemplo n.º 45
0
 /// <summary>
 /// Get a list of cloudblobcontainer in azure
 /// </summary>
 /// <param name="prefix">Container prefix</param>
 /// <param name="detailsIncluded">Container listing details</param>
 /// <param name="options">Blob request option</param>
 /// <param name="operationContext">Operation context</param>
 /// <returns>An enumerable collection of cloudblobcontainer</returns>
 public ContainerResultSegment ListContainersSegmented(string prefix, ContainerListingDetails detailsIncluded, int?maxResults, BlobContinuationToken currentToken, BlobRequestOptions options, OperationContext operationContext)
 {
     throw new NotImplementedException("Can not create a ContainerResultSegment object");
 }
Ejemplo n.º 46
0
 /// <summary>
 /// Return a task that asynchronously delete the specified container.
 /// </summary>
 /// <param name="container">CloudBlobContainer object</param>
 /// <param name="accessCondition">Access condition</param>
 /// <param name="requestOptions">Blob request option</param>
 /// <param name="operationContext">Operation context</param>
 /// <param name="cmdletCancellationToken">Cancellation token</param>
 /// <returns>Return a task that asynchronously delete the specified container.</returns>
 public Task DeleteContainerAsync(CloudBlobContainer container, AccessCondition accessCondition, BlobRequestOptions requestOptions, OperationContext operationContext, CancellationToken cmdletCancellationToken)
 {
     return(Task.Factory.StartNew(() => this.DeleteContainer(container, accessCondition, requestOptions, operationContext)));
 }
Ejemplo n.º 47
0
 /// <summary>
 /// Delete container
 /// </summary>
 /// <param name="container">A cloudblobcontainer object</param>
 /// <param name="accessCondition">Access condition</param>
 /// <param name="options">Blob request option</param>
 /// <param name="operationContext">Operation context</param>
 public void DeleteContainer(CloudBlobContainer container, AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext)
 {
     foreach (CloudBlobContainer containerRef in ContainerList)
     {
         if (container.Name == containerRef.Name)
         {
             ContainerList.Remove(containerRef);
             return;
         }
     }
 }
Ejemplo n.º 48
0
 /// <summary>
 /// List part of blobs.
 /// </summary>
 /// <param name="prefix">Blob prefix</param>
 /// <param name="useFlatBlobListing">Use flat blob listing</param>
 /// <param name="blobListingDetails">Blob listing details.</param>
 /// <param name="maxResults">Max results.</param>
 /// <param name="currentToken">Current token.</param>
 /// <param name="options">Request options</param>
 /// <param name="operationContext">Operation Context.</param>
 /// <returns>BlobResultSegment object</returns>
 public BlobResultSegment ListBlobsSegmented(CloudBlobContainer container, string prefix, bool useFlatBlobListing, BlobListingDetails blobListingDetails, int?maxResults, BlobContinuationToken currentToken, BlobRequestOptions options, OperationContext operationContext)
 {
     throw new NotImplementedException("Can not create a BlobResultSegment object");
 }
Ejemplo n.º 49
0
        /// <summary>
        /// Get a list of cloudblobcontainer in azure
        /// </summary>
        /// <param name="prefix">Container prefix</param>
        /// <param name="detailsIncluded">Container listing details</param>
        /// <param name="options">Blob request option</param>
        /// <param name="operationContext">Operation context</param>
        /// <returns>An enumerable collection of cloudblobcontainer</returns>
        public IEnumerable <CloudBlobContainer> ListContainers(string prefix, ContainerListingDetails detailsIncluded, BlobRequestOptions options = null, OperationContext operationContext = null)
        {
            if (string.IsNullOrEmpty(prefix))
            {
                return(ContainerList);
            }
            else
            {
                List <CloudBlobContainer> prefixContainerList = new List <CloudBlobContainer>();

                foreach (CloudBlobContainer container in ContainerList)
                {
                    if (container.Name.StartsWith(prefix))
                    {
                        prefixContainerList.Add(container);
                    }
                }

                return(prefixContainerList);
            }
        }
Ejemplo n.º 50
0
 /// <summary>
 /// Abort copy operation on specified blob
 /// </summary>
 /// <param name="blob">ICloudBlob object</param>
 /// <param name="copyId">Copy id</param>
 /// <param name="accessCondition">Access condition</param>
 /// <param name="options">Blob request options</param>
 /// <param name="operationContext">Operation context</param>
 public void AbortCopy(ICloudBlob blob, string copyId, AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext)
 {
     return;
 }
        /// <summary>
        /// Stop copy operation by CloudBlob object
        /// </summary>
        /// <param name="blob">CloudBlob object</param>
        /// <param name="copyId">Copy id</param>
        private async Task StopCopyBlob(long taskId, IStorageBlobManagement localChannel, CloudBlob blob, string copyId, bool fetchCopyIdFromBlob = false)
        {
            ValidateBlobType(blob);

            if (UseTrack2Sdk()) // Use Track2
            {
                if (null == blob)
                {
                    throw new ArgumentException(String.Format(Resources.ObjectCannotBeNull, typeof(CloudBlob).Name));
                }

                BlobBaseClient blobBaseClient = AzureStorageBlob.GetTrack2BlobClient(blob, Channel.StorageContext, this.ClientOptions);

                string specifiedCopyId = copyId;

                if (string.IsNullOrEmpty(specifiedCopyId) && fetchCopyIdFromBlob)
                {
                    if (blob.CopyState != null)
                    {
                        specifiedCopyId = blob.CopyState.CopyId;
                    }
                }

                string abortCopyId = string.Empty;

                if (string.IsNullOrEmpty(specifiedCopyId) || Force)
                {
                    //Make sure we use the correct copy id to abort
                    //Use default retry policy for FetchBlobAttributes
                    Track2Models.BlobProperties blobProperties = blobBaseClient.GetProperties(this.BlobRequestConditions, this.CmdletCancellationToken).Value;

                    if (String.IsNullOrEmpty(blobProperties.CopyId))
                    {
                        ArgumentException e = new ArgumentException(String.Format(Resources.CopyTaskNotFound, blobBaseClient.Name, blobBaseClient.BlobContainerName));
                        OutputStream.WriteError(taskId, e);
                    }
                    else
                    {
                        abortCopyId = blobProperties.CopyId;
                    }

                    if (!Force)
                    {
                        string confirmation = String.Format(Resources.ConfirmAbortCopyOperation, blobBaseClient.Name, blobBaseClient.BlobContainerName, abortCopyId);
                        if (!await OutputStream.ConfirmAsync(confirmation).ConfigureAwait(false))
                        {
                            string cancelMessage = String.Format(Resources.StopCopyOperationCancelled, blobBaseClient.Name, blobBaseClient.BlobContainerName);
                            OutputStream.WriteVerbose(taskId, cancelMessage);
                        }
                    }
                }
                else
                {
                    abortCopyId = specifiedCopyId;
                }

                await blobBaseClient.AbortCopyFromUriAsync(abortCopyId, this.BlobRequestConditions, this.CmdletCancellationToken).ConfigureAwait(false);

                //localChannel.AbortCopyAsync(blob, abortCopyId, accessCondition, abortRequestOption, OperationContext, CmdletCancellationToken).ConfigureAwait(false);
                string message = String.Format(Resources.StopCopyBlobSuccessfully, blobBaseClient.Name, blobBaseClient.BlobContainerName);
                OutputStream.WriteObject(taskId, message);
            }
            else // use Track1
            {
                AccessCondition    accessCondition    = null;
                BlobRequestOptions abortRequestOption = RequestOptions ?? new BlobRequestOptions();

                //Set no retry to resolve the 409 conflict exception
                abortRequestOption.RetryPolicy = new NoRetry();

                if (null == blob)
                {
                    throw new ArgumentException(String.Format(Resources.ObjectCannotBeNull, typeof(CloudBlob).Name));
                }

                string specifiedCopyId = copyId;

                if (string.IsNullOrEmpty(specifiedCopyId) && fetchCopyIdFromBlob)
                {
                    if (blob.CopyState != null)
                    {
                        specifiedCopyId = blob.CopyState.CopyId;
                    }
                }

                string abortCopyId = string.Empty;

                if (string.IsNullOrEmpty(specifiedCopyId) || Force)
                {
                    //Make sure we use the correct copy id to abort
                    //Use default retry policy for FetchBlobAttributes
                    BlobRequestOptions options = RequestOptions;
                    await localChannel.FetchBlobAttributesAsync(blob, accessCondition, options, OperationContext, CmdletCancellationToken).ConfigureAwait(false);

                    if (blob.CopyState == null || String.IsNullOrEmpty(blob.CopyState.CopyId))
                    {
                        ArgumentException e = new ArgumentException(String.Format(Resources.CopyTaskNotFound, blob.Name, blob.Container.Name));
                        OutputStream.WriteError(taskId, e);
                    }
                    else
                    {
                        abortCopyId = blob.CopyState.CopyId;
                    }

                    if (!Force)
                    {
                        string confirmation = String.Format(Resources.ConfirmAbortCopyOperation, blob.Name, blob.Container.Name, abortCopyId);
                        if (!await OutputStream.ConfirmAsync(confirmation).ConfigureAwait(false))
                        {
                            string cancelMessage = String.Format(Resources.StopCopyOperationCancelled, blob.Name, blob.Container.Name);
                            OutputStream.WriteVerbose(taskId, cancelMessage);
                        }
                    }
                }
                else
                {
                    abortCopyId = specifiedCopyId;
                }

                await localChannel.AbortCopyAsync(blob, abortCopyId, accessCondition, abortRequestOption, OperationContext, CmdletCancellationToken).ConfigureAwait(false);

                string message = String.Format(Resources.StopCopyBlobSuccessfully, blob.Name, blob.Container.Name);
                OutputStream.WriteObject(taskId, message);
            }
        }
Ejemplo n.º 52
0
 /// <summary>
 /// set blob meta data
 /// </summary>
 /// <param name="blob">ICloud blob object</param>
 /// <param name="accessCondition">Access condition</param>
 /// <param name="options">blob request options</param>
 /// <param name="operationContext">An object that represents the context for the current operation.</param>
 public void SetBlobMetadata(ICloudBlob blob, AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext)
 {
     return;
 }
Ejemplo n.º 53
0
        public async Task <IActionResult> UpdatingUserRecipeAsync(int RecipeId, UpdateUserRecipe UpdateRecipe, string Content)
        {
            int? UserId = HttpContext.Session.GetInt32("UserId");
            User User   = dbContext.Users.FirstOrDefault(user => user.UserId == UserId);

            if (User != null)
            {
                UserRecipe Recipe = dbContext.UserRecipes.Include(recipe => recipe.User).FirstOrDefault(recipe => recipe.RecipeId == RecipeId);
                if (User.AdminState == 1 || User.UserId == Recipe.UserId)
                {
                    if (Request.Form["deletePicture"] == "on")
                    {
                        UpdateRecipe.UploadPicture = null;
                        Recipe.PictureURL          = null;
                    }
                    if (UpdateRecipe.UploadPicture != null)
                    {
                        var container              = Recipe.GetBlobContainer(configuration.GetSection("PictureBlobInfo:AzureStorageConnectionString").Value, "foodforumpictures");
                        var PictureContent         = ContentDispositionHeaderValue.Parse(UpdateRecipe.UploadPicture.ContentDisposition);
                        var FileName               = PictureContent.FileName.ToString().Trim('"');
                        var blockBlob              = container.GetBlockBlobReference(FileName);
                        BlobRequestOptions options = new BlobRequestOptions();
                        options.SingleBlobUploadThresholdInBytes = 16777216;
                        await blockBlob.UploadFromStreamAsync(UpdateRecipe.UploadPicture.OpenReadStream());

                        UpdateRecipe.PictureURL = blockBlob.Uri.AbsoluteUri;
                        if (UpdateRecipe.PictureURL != null && !dbContext.Recipes.Any(recipe => recipe.PictureURL == UpdateRecipe.PictureURL))
                        {
                            Recipe.PictureURL = UpdateRecipe.PictureURL;
                        }
                    }
                    Recipe.Title = UpdateRecipe.Title;
                    Recipe TitleCheck = dbContext.Recipes.FirstOrDefault(recipe => recipe.Title == Recipe.Title);
                    if (TitleCheck != null && TitleCheck.RecipeId != Recipe.RecipeId)
                    {
                        ViewBag.Recipe = Recipe;
                        ModelState.AddModelError("Title", "A recipe already has that title");
                        return(View("UpdateRecipe"));
                    }
                    Recipe.Content              = Content;
                    Recipe.IngredientOne        = UpdateRecipe.IngredientOne;
                    Recipe.IngredientTwo        = UpdateRecipe.IngredientTwo;
                    Recipe.IngredientThree      = UpdateRecipe.IngredientThree;
                    Recipe.IngredientFour       = UpdateRecipe.IngredientFour;
                    Recipe.IngredientFive       = UpdateRecipe.IngredientFive;
                    Recipe.IngredientSix        = UpdateRecipe.IngredientSix;
                    Recipe.IngredientSeven      = UpdateRecipe.IngredientSeven;
                    Recipe.IngredientEight      = UpdateRecipe.IngredientEight;
                    Recipe.IngredientNine       = UpdateRecipe.IngredientNine;
                    Recipe.IngredientTen        = UpdateRecipe.IngredientTen;
                    Recipe.IngredientEleven     = UpdateRecipe.IngredientEleven;
                    Recipe.IngredientTwelve     = UpdateRecipe.IngredientTwelve;
                    Recipe.IngredientThirteen   = UpdateRecipe.IngredientThirteen;
                    Recipe.IngredientFourteen   = UpdateRecipe.IngredientFourteen;
                    Recipe.IngredientFifteen    = UpdateRecipe.IngredientFifteen;
                    Recipe.UpdatedAt            = UpdateRecipe.CreatedAt;
                    Recipe.User.ConfirmPassword = null;
                    TryValidateModel(Recipe);
                    ModelState.Remove("User.ConfirmPassword");
                    if (UpdateRecipe.PictureURL != null && dbContext.Recipes.Any(recipe => recipe.PictureURL == Recipe.PictureURL))
                    {
                        ModelState.AddModelError("UploadPicture", "A recipe already has a picture with that file name, please rename it and try again");
                    }
                    string check = RegexCheck(Recipe, RegEx);
                    if (check != null)
                    {
                        ModelState.AddModelError(check, "Please use only letters, numbers, periods, commas, hyphens, or exclamation points");
                    }
                    if (ModelState.IsValid)
                    {
                        dbContext.SaveChanges();
                        return(RedirectToAction("UserRecipes", "Home"));
                    }
                    ViewBag.Recipe = Recipe;
                    return(View("UpdateRecipe"));
                }
                return(RedirectToAction("UserRecipe", "UserRecipes", new { Title = Recipe.Title }));
            }
            return(RedirectToAction("UserRecipes", "Home"));
        }
Ejemplo n.º 54
0
 /// <summary>
 /// fetch blob attributes
 /// </summary>
 /// <param name="accessCondition">Access condition</param>
 /// <param name="options">blob request options</param>
 /// <param name="operationContext">An object that represents the context for the current operation.</param>
 public void FetchBlobAttributes(ICloudBlob blob, AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext)
 {
     return;
 }
 public Task <bool> ExistsAsync(BlobRequestOptions options = null, OperationContext operationContext = null)
 {
     throw new NotImplementedException();
 }
Ejemplo n.º 56
0
 /// <summary>
 /// fetch container attributes
 /// </summary>
 /// <param name="container">CloudBlobContainer object</param>
 /// <param name="accessCondition">Access condition</param>
 /// <param name="options">blob request options</param>
 /// <param name="operationContext">An object that represents the context for the current operation.</param>
 public void FetchContainerAttributes(CloudBlobContainer container, AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext)
 {
     return;
 }
Ejemplo n.º 57
0
        // Enumerate the blobs in a container.
        // Return true on success, false if already exists, throw exception on error.
        public bool ListBlobs(string containerName, out List<CloudBlob> blobList)
        {
            blobList = new List<CloudBlob>();

            try
            {
                CloudBlobContainer container = BlobClient.GetContainerReference(containerName);
                BlobRequestOptions options = new BlobRequestOptions();
                options.UseFlatBlobListing = true;
                IEnumerable<IListBlobItem> blobs = container.ListBlobs(options);
                if (blobs != null)
                {
                    foreach (IListBlobItem blob in blobs)
                    {
                        if (blob is CloudBlob)
                        {
                            blobList.Add(blob as CloudBlob);
                        }
                    }
                }
                return true;
            }
            catch (StorageClientException ex)
            {
                if ((int)ex.StatusCode == 404)
                {
                    return false;
                }

                throw;
            }
        }
Ejemplo n.º 58
0
        /// <summary>
        /// Delete azure blob
        /// </summary>
        /// <param name="blob">ICloudblob object</param>
        /// <param name="deleteSnapshotsOption">Delete snapshots option</param>
        /// <param name="accessCondition">Access condition</param>
        /// <param name="operationContext">Operation context</param>
        /// <returns>An enumerable collection of icloudblob</returns>
        public void DeleteICloudBlob(ICloudBlob blob, DeleteSnapshotsOption deleteSnapshotsOption, AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext)
        {
            CloudBlobContainer container = blob.Container;

            if (!this.DoesContainerExist(container, null, null))
            {
                throw new StorageException(ContainerNotFound);
            }
            else if (ContainerBlobs.ContainsKey(container.Name))
            {
                List <ICloudBlob> blobList = ContainerBlobs[container.Name];

                foreach (ICloudBlob blobRef in blobList)
                {
                    if (blobRef.Name == blob.Name)
                    {
                        blobList.Remove(blobRef);
                        return;
                    }
                }
            }

            throw new StorageException(BlobNotFound);
        }
Ejemplo n.º 59
0
 /// <summary>
 /// Set container permissions
 /// </summary>
 /// <param name="container">A cloudblobcontainer object</param>
 /// <param name="permissions">The container's permission</param>
 /// <param name="accessCondition">Access condition</param>
 /// <param name="options">Blob request option</param>
 /// <param name="operationContext">Operation context</param>
 public Task SetContainerPermissionsAsync(CloudBlobContainer container, BlobContainerPermissions permissions, AccessCondition accessCondition, BlobRequestOptions requestOptions, OperationContext operationContext, CancellationToken cmdletCancellationToken)
 {
     return(Task.Factory.StartNew(() => this.SetContainerPermissions(container, permissions, accessCondition, requestOptions, operationContext)));
 }
Ejemplo n.º 60
0
 /// <summary>
 /// Return a task that asynchronously check whether the specified blob exists.
 /// </summary>
 /// <param name="blob">ICloudBlob object</param>
 /// <param name="options">Blob request options</param>
 /// <param name="operationContext">Operation context</param>
 /// <param name="cmdletCancellationToken">Cancellation token</param>
 /// <returns>A task object that asynchronously check whether the specified blob exists.</returns>
 public Task <bool> DoesBlobExistAsync(ICloudBlob blob, BlobRequestOptions options, OperationContext operationContext, CancellationToken cmdletCancellationToken)
 {
     return(Task.Factory.StartNew(() => this.DoesBlobExist(blob, options, operationContext)));
 }