public async Task SharePermissionsRawPermissions(string permissionsString)
        {
            // Arrange
            await using DisposingShare test = await GetTestShareAsync();

            ShareSasBuilder blobSasBuilder = new ShareSasBuilder
            {
                StartsOn  = Recording.UtcNow.AddHours(-1),
                ExpiresOn = Recording.UtcNow.AddHours(1),
                ShareName = test.Share.Name
            };

            blobSasBuilder.SetPermissions(
                rawPermissions: permissionsString,
                normalize: true);

            StorageSharedKeyCredential sharedKeyCredential = new StorageSharedKeyCredential(TestConfigDefault.AccountName, TestConfigDefault.AccountKey);

            ShareUriBuilder blobUriBuilder = new ShareUriBuilder(test.Share.Uri)
            {
                Sas = blobSasBuilder.ToSasQueryParameters(sharedKeyCredential)
            };

            ShareClient sasShareClient = new ShareClient(blobUriBuilder.ToUri(), GetOptions());

            // Act
            await sasShareClient.GetRootDirectoryClient().GetPropertiesAsync();
        }
Ejemplo n.º 2
0
        public static ShareFileClient GetAzureFile(string folderName, string fileName)
        {
            string shareName = MyWebUtils.Application.ToLower();

            string connectionString = Properties.Settings.Default.StorageConnectionString;

            ShareClient share = new ShareClient(connectionString, shareName);

            // Create the share if it doesn't already exist
            share.CreateIfNotExists();

            if (share.Exists())
            {
                ShareDirectoryClient subFolder = share.GetRootDirectoryClient();

                foreach (string subFolderName in folderName.Split('\\'))
                {
                    subFolder = subFolder.GetSubdirectoryClient(subFolderName);
                    subFolder.CreateIfNotExists();
                }

                return(subFolder.GetFileClient(fileName));
            }

            return(null);
        }
        /// <summary>
        /// Manage share metadata
        /// </summary>
        /// <param name="shareServiceClient"></param>
        /// <returns></returns>
        private static async Task ShareMetadataSample(ShareServiceClient shareServiceClient)
        {
            Console.WriteLine();

            // Create the share name -- use a guid in the name so it's unique.
            string shareName = "demotest-" + Guid.NewGuid();

            // Create Share
            Console.WriteLine("Create Share");

            ShareClient shareClient = shareServiceClient.GetShareClient(shareName);
            await shareClient.CreateIfNotExistsAsync();

            // Set share metadata
            Console.WriteLine("Set share metadata");

            var metadata = new Dictionary <string, string> {
                { "key1", "value1" }, { "key2", "value2" }
            };
            await shareClient.SetMetadataAsync(metadata);

            try
            {
                // Create Share
                Console.WriteLine("Create Share");
                await shareClient.CreateIfNotExistsAsync();

                // Fetch share attributes
                ShareProperties shareProperties = await shareClient.GetPropertiesAsync();

                Console.WriteLine("Get share metadata:");
                foreach (var keyValue in shareProperties.Metadata)
                {
                    Console.WriteLine("    {0}: {1}", keyValue.Key, keyValue.Value);
                }
                Console.WriteLine();
            }
            catch (RequestFailedException exRequest)
            {
                Common.WriteException(exRequest);
                Console.WriteLine(
                    "Please make sure your storage account is specified correctly in the app.config - then restart the sample.");
                Console.WriteLine("Press any key to exit");
                Console.ReadLine();
                throw;
            }
            catch (Exception ex)
            {
                Console.WriteLine("    Exception thrown creating share.");
                Common.WriteException(ex);
                throw;
            }
            finally
            {
                // Delete share
                Console.WriteLine("Delete share");
                await shareClient.DeleteIfExistsAsync();
            }
        }
Ejemplo n.º 4
0
        private static (ShareClient, ShareDirectoryClient, ShareFileClient) GetFileShareClients(string connectionString, string shareName, string dirName, string fileName)
        {
            ShareClient          share     = new ShareClient(connectionString, shareName);
            ShareDirectoryClient directory = share.GetDirectoryClient(dirName);
            ShareFileClient      file      = directory.GetFileClient(fileName);

            return(share, directory, file);
        }
Ejemplo n.º 5
0
        public static async Task <FileShareScope> CreateShare(string connectionString)
        {
            var shareName   = Guid.NewGuid().ToString("D");
            var shareClient = new ShareClient(connectionString, shareName);
            await shareClient.CreateAsync().ConfigureAwait(false);

            return(new FileShareScope(shareClient, shareName));
        }
Ejemplo n.º 6
0
        private ShareClient InitializeClient()
        {
            ShareClient shareClient = new ShareClient(
                new Uri(this.uri),
                this.sasCred);

            return(shareClient);
        }
        // <snippet_CreateShare>
        //-------------------------------------------------
        // Create a file share
        //-------------------------------------------------
        public async Task CreateShareAsync(string shareName)
        {
            // <snippet_CreateShareClient>
            // Get the connection string from app settings
            string connectionString = ConfigurationManager.AppSettings["StorageConnectionString"];

            // Instantiate a ShareClient which will be used to create and manipulate the file share
            ShareClient share = new ShareClient(connectionString, shareName);
            // </snippet_CreateShareClient>

            // Create the share if it doesn't already exist
            await share.CreateIfNotExistsAsync();

            // Ensure that the share exists
            if (await share.ExistsAsync())
            {
                Console.WriteLine($"Share created: {share.Name}");

                // Get a reference to the sample directory
                ShareDirectoryClient directory = share.GetDirectoryClient("CustomLogs");

                // Create the directory if it doesn't already exist
                await directory.CreateIfNotExistsAsync();

                // Ensure that the directory exists
                if (await directory.ExistsAsync())
                {
                    // Get a reference to a file object
                    ShareFileClient file = directory.GetFileClient("Log1.txt");

                    // Ensure that the file exists
                    if (await file.ExistsAsync())
                    {
                        Console.WriteLine($"File exists: {file.Name}");

                        // Download the file
                        ShareFileDownloadInfo download = await file.DownloadAsync();

                        // Save the data to a local file, overwrite if the file already exists
                        using (FileStream stream = File.OpenWrite(@"downloadedLog1.txt"))
                        {
                            await download.Content.CopyToAsync(stream);

                            await stream.FlushAsync();

                            stream.Close();

                            // Display where the file was saved
                            Console.WriteLine($"File downloaded: {stream.Name}");
                        }
                    }
                }
            }
            else
            {
                Console.WriteLine($"CreateShareAsync failed");
            }
        }
Ejemplo n.º 8
0
        static void Main(string[] args)
        {
            string downloadDirectory = args[0];

            // Create a BlobServiceClient object which will be used to create a container client
            BlobServiceClient blobServiceClient = new BlobServiceClient(AZURE_STORAGE_CONNECTION_STRING);

            // Create a unique name for the container
            string containerName = "startupfiles";

            // Create the container and return a container client object
            BlobContainerClient containerClient = blobServiceClient.GetBlobContainerClient(containerName);

            List <BlobItem> blobs = containerClient.GetBlobs().ToList();

            // Download the blob files in parallel - maximum of 10 at a time }
            Parallel.ForEach(blobs, new ParallelOptions()
            {
                MaxDegreeOfParallelism = 10
            }, blob =>
            {
                string downloadFilePath   = Path.Combine(downloadDirectory, blob.Name);
                BlobClient blobClient     = containerClient.GetBlobClient(blob.Name);
                BlobDownloadInfo download = blobClient.Download();

                using (FileStream downloadFileStream = File.OpenWrite(downloadFilePath))
                {
                    download.Content.CopyTo(downloadFileStream);
                    downloadFileStream.Close();
                }
            });

            string shareName = "startupfiles";

            ShareClient shareClient = new ShareClient(AZURE_FILES_CONNECTION_STRING, shareName);

            if (shareClient.Exists())
            {
                ShareDirectoryClient shareDirectoryClient = shareClient.GetRootDirectoryClient();

                List <ShareFileItem> items = shareDirectoryClient.GetFilesAndDirectories().ToList();
                foreach (ShareFileItem item in items)
                {
                    if (!item.IsDirectory)
                    {
                        string                downloadFilePath = Path.Combine(downloadDirectory, item.Name);
                        ShareFileClient       shareFileClient  = shareDirectoryClient.GetFileClient(item.Name);
                        ShareFileDownloadInfo download         = shareFileClient.Download();
                        using (FileStream downloadFileStream = File.OpenWrite(downloadFilePath))
                        {
                            download.Content.CopyTo(downloadFileStream);
                            downloadFileStream.Close();
                        }
                    }
                }
            }
        }
Ejemplo n.º 9
0
        public async Task <DisposingShare> GetTestShareAsync(ShareServiceClient service = default, string shareName = default, IDictionary <string, string> metadata = default)
        {
            service ??= GetServiceClient_SharedKey();
            metadata ??= new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase);
            shareName ??= GetNewShareName();
            ShareClient share = InstrumentClient(service.GetShareClient(shareName));

            return(await DisposingShare.CreateAsync(share, metadata));
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Azure File Storage constructor
        /// </summary>
        /// <param name="constr">The connection string</param>
        /// <param name="shareName">The name of the Share</param>
        public AzureFileStorage(string constr, string shareName)
        {
            FileShare = new ShareClient(constr, shareName);

            // Ensure that the share exists.
            if (!FileShare.Exists())
            {
                throw new Exception("Cannot access Azure File Share: " + shareName + ".");
            }
        }
        public void Setup()
        {
            SharedSetup();

            ShareClient.Setup(s => s.GetRootDirectoryClient())
            .Returns((_directory = new Mock <ShareDirectoryClient>()).Object);

            _directory.Setup(s => s.GetFileClient(It.IsAny <string>()))
            .Returns((_fileClient = new Mock <ShareFileClient>()).Object);
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ShareLeaseClient"/> class.
        /// </summary>
        /// <param name="client">
        /// A <see cref="ShareClient"/> representing the share being leased.
        /// </param>
        /// <param name="leaseId">
        /// An optional lease ID.  If no lease ID is provided, a random lease
        /// ID will be created.
        /// </param>
        public ShareLeaseClient(ShareClient client, string leaseId = null)
        {
            _share  = client ?? throw Errors.ArgumentNull(nameof(client));
            LeaseId = leaseId ?? CreateUniqueLeaseId();

            ShareUriBuilder uriBuilder = new ShareUriBuilder(client.Uri)
            {
                ShareName = null
            };
        }
Ejemplo n.º 13
0
        public async Task FileSample()
        {
            // Instantiate a new FileServiceClient using a connection string.
            FileServiceClient fileServiceClient = new FileServiceClient(TestConfigurations.DefaultTargetTenant.ConnectionString);

            // Instantiate new ShareClient
            ShareClient shareClient = fileServiceClient.GetShareClient("myshare3");

            try
            {
                // Create Share in the Service
                await shareClient.CreateAsync();

                // Instantiate new DirectoryClient
                DirectoryClient directoryClient = shareClient.GetDirectoryClient("mydirectory");

                // Create Directory in the Service
                await directoryClient.CreateAsync();

                // Instantiate new FileClient
                FileClient fileClient = directoryClient.GetFileClient("myfile");

                // Create File in the Service
                await fileClient.CreateAsync(maxSize : 1024);

                // Upload data to File
                using (FileStream fileStream = File.OpenRead("Samples/SampleSource.txt"))
                {
                    await fileClient.UploadRangeAsync(
                        writeType : FileRangeWriteType.Update,
                        range : new HttpRange(0, 1024),
                        content : fileStream);
                }

                // Download file
                using (FileStream fileStream = File.Create("SampleDestination.txt"))
                {
                    Response <StorageFileDownloadInfo> downloadResponse = await fileClient.DownloadAsync();

                    await downloadResponse.Value.Content.CopyToAsync(fileStream);
                }

                // Delete File in the Service
                await fileClient.DeleteAsync();

                // Delete Directory in the Service
                await directoryClient.DeleteAsync();
            }
            finally
            {
                // Delete Share in the service
                await shareClient.DeleteAsync();
            }
        }
Ejemplo n.º 14
0
        public AzureFileShareCrawler(
            string uri,
            string path,
            string sharedAccessSignature)
        {
            this.uri  = uri;
            this.path = path;

            this.sasCred     = new AzureSasCredential(sharedAccessSignature);
            this.shareClient = InitializeClient();
        }
        public virtual Response <ShareClient> CreateShare(
            string shareName,
            IDictionary <string, string> metadata = default,
            int?quotaInGB = default,
            CancellationToken cancellationToken = default)
        {
            ShareClient          share    = GetShareClient(shareName);
            Response <ShareInfo> response = share.Create(metadata, quotaInGB, cancellationToken);

            return(Response.FromValue(share, response.GetRawResponse()));
        }
        public virtual async Task <Response <ShareClient> > CreateShareAsync(
            string shareName,
            IDictionary <string, string> metadata = default,
            int?quotaInGB = default,
            CancellationToken cancellationToken = default)
        {
            ShareClient          share    = GetShareClient(shareName);
            Response <ShareInfo> response = await share.CreateAsync(metadata, quotaInGB, cancellationToken).ConfigureAwait(false);

            return(Response.FromValue(share, response.GetRawResponse()));
        }
Ejemplo n.º 17
0
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            string connectionString = "DefaultEndpointsProtocol=https;AccountName=m10l2;AccountKey=jKxmGhpm9FWua8lWReXyt9gft5xConbXInXr8IRQj2Z1lWVL6YIWNl/pmqm3EQkdh7YgJlTRPakW8w2GiSfswg==;EndpointSuffix=core.windows.net";
            string containerName    = "test";
            string queueName        = "test";
            string shareName        = "test";
            string blobName         = $"{Guid.NewGuid().ToString()}.json";
            string fileName         = $"{Guid.NewGuid().ToString()}.json";

            BlobContainerClient container = new BlobContainerClient(connectionString, containerName);
            BlobClient          blob      = container.GetBlobClient(blobName);
            Stream uploadStream           = new MemoryStream();

            req.Body.CopyTo(uploadStream);
            uploadStream.Position = 0;
            blob.Upload(uploadStream);
            Stream      result = (await blob.DownloadAsync()).Value.Content;
            QueueClient queue  = new QueueClient(connectionString, queueName);

            Stream messageStream = new MemoryStream();

            req.Body.Position = 0;
            req.Body.CopyTo(messageStream);
            using (StreamReader sr = new StreamReader(messageStream))
            {
                queue.SendMessage(sr.ReadToEnd());
            }

            QueueMessage[] messages = (await queue.ReceiveMessagesAsync()).Value;

            ShareClient          share     = new ShareClient(connectionString, shareName);
            ShareDirectoryClient directory = share.GetRootDirectoryClient();

            Stream fileStream = new MemoryStream();

            req.Body.Position = 0;
            req.Body.CopyTo(fileStream);
            fileStream.Position = 0;
            ShareFileClient file = directory.GetFileClient(fileName);
            await file.CreateAsync(fileStream.Length);

            file.UploadRange(new HttpRange(0, fileStream.Length), fileStream);
            var downloadedFile = file.Download();

            using (StreamReader sr = new StreamReader(downloadedFile.Value.Content))
            {
                string uploadedFile = await sr.ReadToEndAsync();

                return(new OkObjectResult(uploadedFile));
            }
        }
Ejemplo n.º 18
0
        private async Task UploadSchema(ShareClient client, string schemaPath, string targetDir, string targetFile)
        {
            var schemaStream = File.OpenRead(schemaPath);

            var directoryClient = client.GetDirectoryClient(targetDir);
            await directoryClient.CreateIfNotExistsAsync();

            var fileClient = directoryClient.GetFileClient(targetFile);
            await fileClient.CreateAsync(schemaStream.Length);

            await fileClient.UploadAsync(schemaStream);
        }
Ejemplo n.º 19
0
        // private CloudFileDirectory root;

        //DefaultEndpointsProtocol=https;AccountName=storagetajamarans;AccountKey=9nNsPth/T8BKQ75uFQTvYAEz3JtPFX8aiO7/fywMk5/BlXkI46IGX98dz0zODIO4UJH/0EjvS+giZQ/M6Rn+tQ==;EndpointSuffix=core.windows.net
        //9nNsPth/T8BKQ75uFQTvYAEz3JtPFX8aiO7/fywMk5/BlXkI46IGX98dz0zODIO4UJH/0EjvS+giZQ/M6Rn+tQ==
        public ServiceStorageFile(String keys)
        {
            // String key = ;

            /*CloudStorageAccount account = CloudStorageAccount.Parse(key);
             *
             * CloudFileClient fileClient = account.CreateCloudFileClient();
             *
             * CloudFileShare shared = fileClient.GetShareReference("ejemplo");
             * this.root = shared.GetRootDirectoryReference();*/
            this.cliente = new ShareClient(keys, "ejemplo");
        }
Ejemplo n.º 20
0
        public virtual Response <ShareClient> CreateShare(
            string shareName,
            IDictionary <string, string> metadata = default,
            int?quotaInGB = default,
            CancellationToken cancellationToken = default)
        {
            ShareClient share = GetShareClient(shareName);

            Response <ShareInfo> response = share.CreateInternal(
                metadata,
                quotaInGB,
                accessTier: default,
Ejemplo n.º 21
0
        public async Task DownloadAsync()
        {
            // Create a temporary Lorem Ipsum file on disk that we can upload
            string originalPath = CreateTempFile(SampleFileContent);

            // Get a temporary path on disk where we can download the file
            string downloadPath = CreateTempPath();

            // Get a connection string to our Azure Storage account.
            string connectionString = ConnectionString;

            // Get a reference to a share named "sample-share" and then create it
            ShareClient share = new ShareClient(connectionString, Randomize("sample-share"));
            await share.CreateAsync();

            try
            {
                // Get a reference to a directory named "sample-dir" and then create it
                DirectoryClient directory = share.GetDirectoryClient(Randomize("sample-dir"));
                await directory.CreateAsync();

                // Get a reference to a file named "sample-file" in directory "sample-dir"
                FileClient file = directory.GetFileClient(Randomize("sample-file"));

                // Upload the file
                using (FileStream stream = File.OpenRead(originalPath))
                {
                    await file.CreateAsync(stream.Length);

                    await file.UploadRangeAsync(
                        FileRangeWriteType.Update,
                        new HttpRange(0, stream.Length),
                        stream);
                }

                // Download the file
                StorageFileDownloadInfo download = await file.DownloadAsync();

                using (FileStream stream = File.OpenWrite(downloadPath))
                {
                    await download.Content.CopyToAsync(stream);
                }

                // Verify the contents
                Assert.AreEqual(SampleFileContent, File.ReadAllText(downloadPath));
            }
            finally
            {
                // Clean up after the test when we're finished
                await share.DeleteAsync();
            }
        }
Ejemplo n.º 22
0
        public IActionResult UploadAzure()
        {
            try
            {
                var file       = Request.Form.Files[0];
                var folderName = Path.Combine("StaticFiles", "Images");
                var pathToSave = Path.Combine(Directory.GetCurrentDirectory(), folderName);

                if (file.Length > 0)
                {
                    var fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
                    var fullPath = Path.Combine(pathToSave, fileName);
                    var dbPath   = Path.Combine(folderName, fileName);

                    using (var stream = new FileStream(fullPath, FileMode.Create))
                    {
                        file.CopyTo(stream);
                    }

                    // Get a reference to a share and then create it
                    ShareClient share = new ShareClient("DefaultEndpointsProtocol=https;AccountName=faceidentity;AccountKey=N/gO9IA0exmgv4yH+ZISlxc0wxv2haDMWi2fZoL2/ErfqM/KHAePM4qkwMjnWEXesDvDidDVYJqKAtv3FvaXnQ==;EndpointSuffix=core.windows.net", "employeesimages");
                    // share.Create();

                    // Get a reference to a directory and create it
                    ShareDirectoryClient directory = share.GetDirectoryClient("auth");
                    // directory.Create();

                    // Get a reference to a file and upload it
                    ShareFileClient fileAzure = directory.GetFileClient(fileName);
                    using (FileStream stream = System.IO.File.OpenRead(fullPath))
                    {
                        fileAzure.Create(stream.Length);
                        fileAzure.UploadRange(
                            new HttpRange(0, stream.Length),
                            stream);
                    }

                    string fileAzurePath = fileAzure.Uri.ToString();
                    //System.IO.File.Delete(fullPath);

                    return(Ok(new { fileAzurePath }));
                }
                else
                {
                    return(BadRequest());
                }
            }
            catch (Exception ex)
            {
                return(StatusCode(500, $"Internal server error: {ex}"));
            }
        }
        public async Task Capture_Span_When_Create_File_Share()
        {
            var shareName = Guid.NewGuid().ToString();
            var client    = new ShareClient(_environment.StorageAccountConnectionString, shareName);

            await _agent.Tracer.CaptureTransaction("Create Azure File Share", ApiConstants.TypeStorage, async() =>
            {
                var response = await client.CreateAsync();
            });


            AssertSpan("Create", shareName);
        }
Ejemplo n.º 24
0
        /// <summary>
        /// Updates the remote project's schema and restarts the service
        /// </summary>
        /// <param name="project"></param>
        /// <param name="schemaPath"></param>
        /// <returns></returns>
        public async Task UpdateSchema(RemoteProject project, string schemaPath)
        {
            await InitClient();

            SchemaValidator.ValidateSchema(schemaPath);
            var shareClient = new ShareClient(project.StorageConnectionString, project.AzureFileShare);

            await UploadSchema(shareClient, schemaPath, RemoteCsdlFileDir, RemoteCsdlFileName);

            await azure.ContainerGroups.GetByResourceGroup(project.ResourceGroup, project.AppId).RestartAsync();

            project.LocalSchemaPath = schemaPath;
        }
Ejemplo n.º 25
0
        public async Task UploadAsync()
        {
            // Create a temporary Lorem Ipsum file on disk that we can upload
            string path = CreateTempFile(SampleFileContent);

            // Get a connection string to our Azure Storage account.  You can
            // obtain your connection string from the Azure Portal (click
            // Access Keys under Settings in the Portal Storage account blade)
            // or using the Azure CLI with:
            //
            //     az storage account show-connection-string --name <account_name> --resource-group <resource_group>
            //
            // And you can provide the connection string to your application
            // using an environment variable.
            string connectionString = ConnectionString;

            // Get a reference to a share named "sample-share" and then create it
            ShareClient share = new ShareClient(connectionString, Randomize("sample-share"));
            await share.CreateAsync();

            try
            {
                // Get a reference to a directory named "sample-dir" and then create it
                DirectoryClient directory = share.GetDirectoryClient(Randomize("sample-dir"));
                await directory.CreateAsync();

                // Get a reference to a file named "sample-file" in directory "sample-dir"
                FileClient file = directory.GetFileClient(Randomize("sample-file"));

                // Upload the file
                using (FileStream stream = File.OpenRead(path))
                {
                    await file.CreateAsync(stream.Length);

                    await file.UploadRangeAsync(
                        FileRangeWriteType.Update,
                        new HttpRange(0, stream.Length),
                        stream);
                }

                // Verify the file exists
                StorageFileProperties properties = await file.GetPropertiesAsync();

                Assert.AreEqual(SampleFileContent.Length, properties.ContentLength);
            }
            finally
            {
                // Clean up after the test when we're finished
                await share.DeleteAsync();
            }
        }
Ejemplo n.º 26
0
        public async Task Sample01b_HelloWorldAsync_TraverseAsync()
        {
            // Create a temporary Lorem Ipsum file on disk that we can upload
            string originalPath = CreateTempFile(SampleFileContent);

            // Get a reference to a share named "sample-share" and then create it
            string      shareName = Randomize("sample-share");
            ShareClient share     = new ShareClient(ConnectionString, shareName);
            await share.CreateAsync();

            try
            {
                // Create a bunch of directories
                ShareDirectoryClient first = await share.CreateDirectoryAsync("first");

                await first.CreateSubdirectoryAsync("a");

                await first.CreateSubdirectoryAsync("b");

                ShareDirectoryClient second = await share.CreateDirectoryAsync("second");

                await second.CreateSubdirectoryAsync("c");

                await second.CreateSubdirectoryAsync("d");

                await share.CreateDirectoryAsync("third");

                ShareDirectoryClient fourth = await share.CreateDirectoryAsync("fourth");

                ShareDirectoryClient deepest = await fourth.CreateSubdirectoryAsync("e");

                // Upload a file named "file"
                ShareFileClient file = deepest.GetFileClient("file");
                using (FileStream stream = File.OpenRead(originalPath))
                {
                    await file.CreateAsync(stream.Length);

                    await file.UploadRangeAsync(
                        ShareFileRangeWriteType.Update,
                        new HttpRange(0, stream.Length),
                        stream);
                }

                await Sample01b_HelloWorldAsync.TraverseAsync(ConnectionString, shareName);
            }
            finally
            {
                await share.DeleteAsync();
            }
        }
        /// <summary>
        /// Manage share properties
        /// </summary>
        /// <param name="shareServiceClient"></param>
        /// <returns></returns>
        private static async Task SharePropertiesSample(ShareServiceClient shareServiceClient)
        {
            Console.WriteLine();

            // Create the share name -- use a guid in the name so it's unique.
            string      shareName   = "demotest-" + Guid.NewGuid();
            ShareClient shareClient = shareServiceClient.GetShareClient(shareName);

            try
            {
                // Create Share
                Console.WriteLine("Create Share");
                await shareClient.CreateIfNotExistsAsync();

                // Set share properties
                Console.WriteLine("Set share properties");
                await shareClient.SetQuotaAsync(100);

                // Fetch share properties
                ShareProperties shareProperties = await shareClient.GetPropertiesAsync();

                Console.WriteLine("Get share properties:");
                Console.WriteLine("    Quota: {0}", shareProperties.QuotaInGB);
                Console.WriteLine("    ETag: {0}", shareProperties.ETag);
                Console.WriteLine("    Last modified: {0}", shareProperties.LastModified);
            }
            catch (RequestFailedException exRequest)
            {
                Common.WriteException(exRequest);
                Console.WriteLine(
                    "Please make sure your storage account is specified correctly in the app.config - then restart the sample.");
                Console.WriteLine("Press any key to exit");
                Console.ReadLine();
                throw;
            }
            catch (Exception ex)
            {
                Console.WriteLine("    Exception thrown creating share.");
                Common.WriteException(ex);
                throw;
            }
            finally
            {
                // Delete share
                Console.WriteLine("Delete share");
                await shareClient.DeleteIfExistsAsync();
            }

            Console.WriteLine();
        }
        public IActionResult Post(string userId)
        {
            try
            {
                IFormFileCollection files = Request.Form.Files;
                if (files.Count == 0)
                {
                    return(BadRequest());
                }

                // Get a reference to a share and then create it
                ShareClient share = new ShareClient(Secret.AzureConnectionString, Secret.AzureFileShareName);
                if (!share.Exists())
                {
                    share.Create();
                }

                // Get a reference to a directory and create it
                ShareDirectoryClient directory = share.GetDirectoryClient(Auth0Utils.GetUserFolder());
                if (!directory.Exists())
                {
                    directory.Create();
                }

                // Get a reference to a file and upload it
                ShareFileClient fileClient;

                foreach (IFormFile file in files)
                {
                    fileClient = directory.GetFileClient(file.FileName);

                    fileClient.DeleteIfExists();

                    using (Stream stream = file.OpenReadStream())
                    {
                        fileClient.Create(stream.Length);
                        fileClient.UploadRange(
                            new HttpRange(0, stream.Length),
                            stream);
                    }
                }

                return(Ok());
            }
            catch (Exception e)
            {
                return(StatusCode(500, e.Message));
            }
        }
        public async Task Setup()
        {
            SharedSetup();

            _directoryMock = new Mock <ShareDirectoryClient>();
            _input         = new Mock <IPathFilter>();

            ShareClient.Setup(s => s.GetRootDirectoryClient())
            .Returns(_directoryMock.Object);

            _directories = new[]
            {
                new [] { FilesModelFactory.StorageFileItem(true, "Recurse1", 0) },
                new [] { FilesModelFactory.StorageFileItem(true, "Recurse2", 0) },
                new [] { FilesModelFactory.StorageFileItem(true, "Recurse3", 0) },
                new [] { FilesModelFactory.StorageFileItem(true, "Recurse4", 0) },
                new [] { FilesModelFactory.StorageFileItem(true, "Recurse5", 0) },
                new [] { FilesModelFactory.StorageFileItem(true, "Collect1", 0), FilesModelFactory.StorageFileItem(true, "Collect2", 0) }
            };

            var pathActionSequence        = _input.SetupSequence(s => s.DecideAction(It.IsAny <string>()));
            var directoryContentsSequence = _directoryMock.SetupSequence(s => s.GetFilesAndDirectoriesAsync(It.IsAny <string>(), It.IsAny <CancellationToken>()));
            var pathSequence = _directoryMock.SetupSequence(s => s.Path);

            _directoryMock.Setup(s => s.GetSubdirectoryClient(It.IsAny <string>())).Returns(() => _directoryMock.Object);

            for (var i = 0; i < NumberOfDirectoriesInTree; i++)
            {
                var item = _directories[i];
                directoryContentsSequence.Returns(() => MockPageable(item).Object);
                pathActionSequence.Returns(PathAction.Recurse);
                pathSequence.Returns(string.Join("/", _directories.SelectMany(s => s.Select(x => x.Name)).Take(i)));
            }

            pathSequence.Returns(string.Join("/", _directories.SelectMany(s => s.Select(x => x.Name)).Take(5)));

            for (var i = NumberOfDirectoriesInTree; i < _directories.Length; i++)
            {
                var items = _directories[i];
                directoryContentsSequence.Returns(() => MockPageable(items).Object);

                foreach (var subItem in items)
                {
                    pathActionSequence.Returns(PathAction.Collect);
                }
            }

            _output = await ClassInTest.ListAsync(_input.Object, CancellationToken.None).AsEnumerableAsync();
        }
Ejemplo n.º 30
0
        /// <summary>
        /// Trigger a recoverable error.
        /// </summary>
        /// <param name="connectionString">
        /// A connection string to your Azure Storage account.
        /// </param>
        /// <param name="shareName">
        /// The name of an existing share
        /// </param>
        public static async Task ErrorsAsync(string connectionString, string shareName)
        {
            ShareClient share = new ShareClient(connectionString, shareName);

            try
            {
                // Try to create the share again
                await share.CreateAsync();
            }
            catch (RequestFailedException ex)
                when(ex.ErrorCode == ShareErrorCode.ShareAlreadyExists)
                {
                    // Ignore any errors if the share already exists
                }
        }