Beispiel #1
0
        public async Task ErrorsAsync()
        {
            // 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
            {
                // Try to create the share again
                await share.CreateAsync();
            }
            catch (StorageRequestFailedException ex)
                when(ex.ErrorCode == FileErrorCode.ShareAlreadyExists)
                {
                    // Ignore any errors if the share already exists
                }
            catch (StorageRequestFailedException ex)
            {
                Assert.Fail($"Unexpected error: {ex}");
            }

            // Clean up after the test when we're finished
            await share.DeleteAsync();
        }
Beispiel #2
0
        public async Task ShareSample()
        {
            // Instantiate a new FileServiceClient using a connection string.
            FileServiceClient fileServiceClient = new FileServiceClient(TestConfigurations.DefaultTargetTenant.ConnectionString);

            // Instantiate new ShareClient
            ShareClient shareClient = fileServiceClient.GetShareClient($"myshare-{Guid.NewGuid()}");

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

                // List Shares
                await foreach (var share in fileServiceClient.GetSharesAsync())
                {
                    Console.WriteLine(share.Value.Name);
                }
            }
            finally
            {
                // Delete Share in the service
                await shareClient.DeleteAsync();
            }
        }
Beispiel #3
0
        public async Task UploadAsync(ConnectorConfig config, string fullFileName, MemoryStream stream)
        {
            var dirName  = Path.GetDirectoryName(fullFileName).ToString();
            var fileName = Path.GetFileName(fullFileName).ToString();

            ShareClient share = new ShareClient(config.connectionString, config.shareName);

            if (!share.Exists())
            {
                await share.CreateAsync();
            }

            ShareDirectoryClient directory = share.GetDirectoryClient(dirName);

            if (!directory.Exists())
            {
                await directory.CreateAsync();
            }

            ShareFileClient file = directory.GetFileClient(fileName);
            await file.CreateAsync(stream.Length);

            await file.UploadAsync(stream);

            /*
             * await file.UploadRange(
             *      ShareFileRangeWriteType.Update,
             *      new HttpRange(0, stream.Length),
             *      stream);*/
        }
Beispiel #4
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));
        }
        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()));
        }
Beispiel #6
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();
            }
        }
Beispiel #7
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();
            }
        }
        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);
        }
Beispiel #9
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();
            }
        }
        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();
            }
        }
        public override async Task SetupAsync()
        {
            await base.SetupAsync();

            // See https://docs.microsoft.com/en-us/rest/api/storageservices/naming-and-referencing-shares--directories--files--and-metadata for
            // restrictions on file share naming.
            _shareClient = new ShareClient(PerfTestEnvironment.Instance.FileSharesConnectionString, Guid.NewGuid().ToString());
            await _shareClient.CreateAsync();

            ShareDirectoryClient DirectoryClient = _shareClient.GetDirectoryClient(Path.GetRandomFileName());
            await DirectoryClient.CreateAsync();

            _fileClient = DirectoryClient.GetFileClient(Path.GetRandomFileName());
            await _fileClient.CreateAsync(_stream.Length, cancellationToken : CancellationToken.None);
        }
Beispiel #12
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
                }
        }
        public async Task Sample01b_HelloWorldAsync_ErrorsAsync()
        {
            // Get a reference to a share named "sample-share" and then create it
            string      shareName = Randomize("sample-share");
            ShareClient share     = new ShareClient(ConnectionString, shareName);

            try
            {
                await share.CreateAsync();

                await Sample01b_HelloWorldAsync.ErrorsAsync(ConnectionString, shareName);
            }
            finally
            {
                await share.DeleteAsync();
            }
        }
Beispiel #14
0
        public async Task DirectorySample()
        {
            // Instantiate a new FileServiceClient using a connection string.
            FileServiceClient fileServiceClient = new FileServiceClient(TestConfigurations.DefaultTargetTenant.ConnectionString);

            // Instantiate new ShareClient
            ShareClient shareClient = fileServiceClient.GetShareClient($"myshare2-{Guid.NewGuid()}");

            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 DirectoryClient
                DirectoryClient subDirectoryClient = directoryClient.GetSubdirectoryClient("mysubdirectory");

                // Create sub directory
                await subDirectoryClient.CreateAsync();

                // List Files and Directories
                await foreach (StorageFileItem item in directoryClient.GetFilesAndDirectoriesAsync())
                {
                    var type = item.IsDirectory ? "dir" : "file";
                    Console.WriteLine($"{type}: {item.Name}");
                }

                // Delete sub directory in the Service
                await subDirectoryClient.DeleteAsync();

                // Delete Directory in the Service
                await directoryClient.DeleteAsync();
            }
            finally
            {
                // Delete Share in the service
                await shareClient.DeleteAsync();
            }
        }
Beispiel #15
0
        public async Task DirectorySample()
        {
            // Instantiate a new FileServiceClient using a connection string.
            FileServiceClient fileServiceClient = new FileServiceClient(TestConfigurations.DefaultTargetTenant.ConnectionString);

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

            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 DirectoryClient
                DirectoryClient subDirectoryClient = directoryClient.GetDirectoryClient("mysubdirectory");

                // Create sub directory
                await subDirectoryClient.CreateAsync();

                // List Files and Directories
                Response <FilesAndDirectoriesSegment> listResponse = await directoryClient.ListFilesAndDirectoriesSegmentAsync();

                // Delete sub directory in the Service
                await subDirectoryClient.DeleteAsync();

                // Delete Directory in the Service
                await directoryClient.DeleteAsync();
            }
            finally
            {
                // Delete Share in the service
                await shareClient.DeleteAsync();
            }
        }
        public async Task Sample01b_HelloWorldAsync_Download()
        {
            string      originalPath  = CreateTempFile(SampleFileContent);
            string      localFilePath = CreateTempPath();
            string      shareName     = Randomize("sample-share");
            ShareClient share         = new ShareClient(ConnectionString, shareName);

            try
            {
                await share.CreateAsync();

                ShareDirectoryClient directory = share.GetDirectoryClient("sample-dir");
                await directory.CreateAsync();

                ShareFileClient file = directory.GetFileClient("sample-file");

                // Upload the 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.DownloadAsync(ConnectionString, shareName, localFilePath);

                // Verify the contents
                Assert.AreEqual(SampleFileContent, File.ReadAllText(localFilePath));
            }
            finally
            {
                await share.DeleteAsync();

                File.Delete(originalPath);
                File.Delete(localFilePath);
            }
        }
Beispiel #17
0
        public async Task ShareSample()
        {
            // Instantiate a new FileServiceClient using a connection string.
            FileServiceClient fileServiceClient = new FileServiceClient(TestConfigurations.DefaultTargetTenant.ConnectionString);

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

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

                // List Shares
                Response <SharesSegment> listResponse = await fileServiceClient.ListSharesSegmentAsync();
            }
            finally
            {
                // Delete Share in the service
                await shareClient.DeleteAsync();
            }
        }
Beispiel #18
0
        /// <summary>
        /// Create a share and upload a file.
        /// </summary>
        /// <param name="connectionString">
        /// A connection string to your Azure Storage account.
        /// </param>
        /// <param name="shareName">
        /// The name of the share to create and upload to.
        /// </param>
        /// <param name="localFilePath">
        /// Path of the file to upload.
        /// </param>
        public static async Task UploadAsync(string connectionString, string shareName, string localFilePath)
        {
            // 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.

            // Name of the directory and file we'll create
            string dirName  = "sample-dir";
            string fileName = "sample-file";

            // Get a reference to a share and then create it
            ShareClient share = new ShareClient(connectionString, shareName);
            await share.CreateAsync();

            // Get a reference to a directory and create it
            ShareDirectoryClient directory = share.GetDirectoryClient(dirName);
            await directory.CreateAsync();

            // Get a reference to a file and upload it
            ShareFileClient file = directory.GetFileClient(fileName);

            using (FileStream stream = File.OpenRead(localFilePath))
            {
                await file.CreateAsync(stream.Length);

                await file.UploadRangeAsync(
                    ShareFileRangeWriteType.Update,
                    new HttpRange(0, stream.Length),
                    stream);
            }
        }
Beispiel #19
0
            public static async Task <DisposingShare> CreateAsync(ShareClient share, IDictionary <string, string> metadata)
            {
                await share.CreateAsync(metadata : metadata);

                return(new DisposingShare(share));
            }
Beispiel #20
0
        /// <summary>
        /// Creates a remote service based on the specified schema and deploys it on Azure
        /// </summary>
        /// <param name="appId"></param>
        /// <param name="schema"></param>
        /// <returns></returns>
        public async Task <RemoteDeployment> Create(string appId, string schemaPath, ProjectRunArgs projectRunArgs)
        {
            await InitClient();

            SchemaValidator.ValidateSchema(schemaPath);

            var project = new RemoteProject();

            project.AppId           = appId;
            project.SubScriptionId  = azure.SubscriptionId;
            project.TenantId        = tenantId;
            project.SeedData        = projectRunArgs.SeedData;
            project.LocalSchemaPath = schemaPath;

            var deployment = new RemoteDeployment();

            deployment.Project        = project;
            deployment.StartedAt      = DateTimeOffset.Now;
            deployment.DeploymentName = $"dep{appId}";

            var rgName             = $"rg{appId}";
            var storageAccountName = $"st{appId}";
            var shareName          = $"share{appId}";

            project.ResourceGroup      = rgName;
            project.StorageAccountName = storageAccountName;
            project.AzureFileShare     = shareName;


            var region = Region.USCentral;

            project.Region = region.Name;

            await azure.ResourceGroups.Define(rgName).WithRegion(region).CreateAsync();

            // create storage account
            var storage = await azure.StorageAccounts.Define(storageAccountName).WithRegion(region)
                          .WithExistingResourceGroup(rgName)
                          .WithAccessFromAllNetworks()
                          .CreateAsync();

            var stKey = storage.GetKeys().First().Value;

            project.StorageAccountKey = stKey;

            var storageConnString = $"DefaultEndpointsProtocol=https;AccountName={storage.Name};AccountKey={stKey}";
            var shareClient       = new ShareClient(storageConnString, shareName);
            await shareClient.CreateAsync();

            // upload CSDL
            await UploadSchema(shareClient, schemaPath, RemoteCsdlFileDir, RemoteCsdlFileName);

            var template     = TemplateHelper.CreateDeploymentTemplate(project, image);
            var templateJson = JsonSerializer.Serialize(template);
            await azure.Deployments.Define(deployment.DeploymentName)
            .WithExistingResourceGroup(rgName)
            .WithTemplate(templateJson)
            .WithParameters("{}")
            .WithMode(Microsoft.Azure.Management.ResourceManager.Fluent.Models.DeploymentMode.Incremental)
            .CreateAsync();

            deployment.FinishedAt = DateTimeOffset.Now;

            return(deployment);
        }
Beispiel #21
0
        public async Task TraverseAsync()
        {
            // Create a temporary Lorem Ipsum file on disk that we can upload
            string originalPath = CreateTempFile(SampleFileContent);

            // 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
            {
                // Create a bunch of directories
                DirectoryClient first = await share.CreateDirectoryAsync("first");

                await first.CreateSubdirectoryAsync("a");

                await first.CreateSubdirectoryAsync("b");

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

                await second.CreateSubdirectoryAsync("c");

                await second.CreateSubdirectoryAsync("d");

                await share.CreateDirectoryAsync("third");

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

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

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

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

                // Keep track of all the names we encounter
                List <string> names = new List <string>();

                // Track the remaining directories to walk, starting from the root
                Queue <DirectoryClient> remaining = new Queue <DirectoryClient>();
                remaining.Enqueue(share.GetRootDirectoryClient());
                while (remaining.Count > 0)
                {
                    // Get all of the next directory's files and subdirectories
                    DirectoryClient dir = remaining.Dequeue();
                    await foreach (StorageFileItem item in dir.GetFilesAndDirectoriesAsync())
                    {
                        // Track the name of the item
                        names.Add(item.Name);

                        // Keep walking down directories
                        if (item.IsDirectory)
                        {
                            remaining.Enqueue(dir.GetSubdirectoryClient(item.Name));
                        }
                    }
                }

                // Verify we've seen everything
                Assert.AreEqual(10, names.Count);
                Assert.Contains("first", names);
                Assert.Contains("second", names);
                Assert.Contains("third", names);
                Assert.Contains("fourth", names);
                Assert.Contains("a", names);
                Assert.Contains("b", names);
                Assert.Contains("c", names);
                Assert.Contains("d", names);
                Assert.Contains("e", names);
                Assert.Contains("file", names);
            }
            finally
            {
                // Clean up after the test when we're finished
                await share.DeleteAsync();
            }
        }