Ejemplo n.º 1
0
        public async Task <DisposingFile> GetTestFileAsync(ShareServiceClient service = default, string shareName = default, string directoryName = default, string fileName = default)
        {
            DisposingDirectory test = await GetTestDirectoryAsync(service, shareName, directoryName);

            fileName ??= GetNewFileName();
            ShareFileClient file = InstrumentClient(test.Directory.GetFileClient(fileName));

            return(await DisposingFile.CreateAsync(test, file));
        }
Ejemplo n.º 2
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.º 3
0
        public async Task UploadRangeFromUriAsync_SourceBearerTokenFail()
        {
            // Arrange
            BlobServiceClient blobServiceClient = InstrumentClient(new BlobServiceClient(
                                                                       new Uri(Tenants.TestConfigOAuth.BlobServiceEndpoint),
                                                                       Tenants.GetOAuthCredential(Tenants.TestConfigOAuth),
                                                                       GetBlobOptions()));
            BlobContainerClient containerClient = InstrumentClient(blobServiceClient.GetBlobContainerClient(GetNewShareName()));

            try
            {
                await containerClient.CreateIfNotExistsAsync();

                AppendBlobClient appendBlobClient = InstrumentClient(containerClient.GetAppendBlobClient(GetNewFileName()));
                await appendBlobClient.CreateAsync();

                byte[] data = GetRandomBuffer(Constants.KB);
                using Stream stream = new MemoryStream(data);
                await appendBlobClient.AppendBlockAsync(stream);

                ShareServiceClient serviceClient = SharesClientBuilder.GetServiceClient_OAuthAccount_SharedKey();
                await using DisposingShare test = await GetTestShareAsync(
                                service : serviceClient,
                                shareName : GetNewShareName());

                ShareDirectoryClient directoryClient = InstrumentClient(test.Share.GetDirectoryClient(GetNewDirectoryName()));
                await directoryClient.CreateAsync();

                ShareFileClient fileClient = InstrumentClient(directoryClient.GetFileClient(GetNewFileName()));
                await fileClient.CreateAsync(Constants.KB);

                HttpAuthorization sourceAuthHeader = new HttpAuthorization(
                    "Bearer",
                    "auth token");

                ShareFileUploadRangeFromUriOptions options = new ShareFileUploadRangeFromUriOptions
                {
                    SourceAuthentication = sourceAuthHeader
                };

                HttpRange range = new HttpRange(0, Constants.KB);

                // Act
                await TestHelper.AssertExpectedExceptionAsync <RequestFailedException>(
                    fileClient.UploadRangeFromUriAsync(
                        sourceUri: appendBlobClient.Uri,
                        range: range,
                        sourceRange: range,
                        options: options),
                    e => Assert.AreEqual("CannotVerifyCopySource", e.ErrorCode));
            }
            finally
            {
                await containerClient.DeleteIfExistsAsync();
            }
        }
        public async Task UploadRangeFromUriAsync_SourceBearerToken()
        {
            // Arrange
            BlobServiceClient blobServiceClient = InstrumentClient(new BlobServiceClient(
                                                                       new Uri(TestConfigOAuth.BlobServiceEndpoint),
                                                                       GetOAuthCredential(TestConfigOAuth),
                                                                       GetBlobOptions()));
            BlobContainerClient containerClient = InstrumentClient(blobServiceClient.GetBlobContainerClient(GetNewShareName()));

            try
            {
                await containerClient.CreateIfNotExistsAsync();

                AppendBlobClient appendBlobClient = InstrumentClient(containerClient.GetAppendBlobClient(GetNewFileName()));
                await appendBlobClient.CreateAsync();

                byte[] data = GetRandomBuffer(Constants.KB);
                using Stream stream = new MemoryStream(data);
                await appendBlobClient.AppendBlockAsync(stream);

                ShareServiceClient serviceClient = GetServiceClient_OAuth_SharedKey();
                await using DisposingShare test = await GetTestShareAsync(
                                service : serviceClient,
                                shareName : GetNewShareName());

                ShareDirectoryClient directoryClient = InstrumentClient(test.Share.GetDirectoryClient(GetNewDirectoryName()));
                await directoryClient.CreateAsync();

                ShareFileClient fileClient = InstrumentClient(directoryClient.GetFileClient(GetNewFileName()));
                await fileClient.CreateAsync(Constants.KB);

                string sourceBearerToken = await GetAuthToken();

                HttpAuthorization sourceAuthHeader = new HttpAuthorization(
                    "Bearer",
                    sourceBearerToken);

                ShareFileUploadRangeFromUriOptions options = new ShareFileUploadRangeFromUriOptions
                {
                    SourceAuthentication = sourceAuthHeader
                };

                HttpRange range = new HttpRange(0, Constants.KB);

                // Act
                await fileClient.UploadRangeFromUriAsync(
                    sourceUri : appendBlobClient.Uri,
                    range : range,
                    sourceRange : range,
                    options : options);
            }
            finally
            {
                await containerClient.DeleteIfExistsAsync();
            }
        }
Ejemplo n.º 5
0
        public async Task <DisposingDirectory> GetTestDirectoryAsync(ShareServiceClient service = default, string shareName = default, string directoryName = default)
        {
            DisposingShare test = await GetTestShareAsync(service, shareName);

            directoryName ??= GetNewDirectoryName();

            ShareDirectoryClient directory = InstrumentClient(test.Share.GetDirectoryClient(directoryName));

            return(await DisposingDirectory.CreateAsync(test, directory));
        }
Ejemplo n.º 6
0
        // </snippet_DeleteSnapshot>

        // <snippet_UseMetrics>
        //-------------------------------------------------
        // Use metrics
        //-------------------------------------------------
        public async Task UseMetricsAsync()
        {
            // Get the connection string from app settings
            string connectionString = ConfigurationManager.AppSettings["StorageConnectionString"];

            // Instatiate a ShareServiceClient
            ShareServiceClient shareService = new ShareServiceClient(connectionString);

            // Set metrics properties for File service
            await shareService.SetPropertiesAsync(new ShareServiceProperties()
            {
                // Set hour metrics
                HourMetrics = new ShareMetrics()
                {
                    Enabled     = true,
                    IncludeApis = true,
                    Version     = "1.0",

                    RetentionPolicy = new ShareRetentionPolicy()
                    {
                        Enabled = true,
                        Days    = 14
                    }
                },

                // Set minute metrics
                MinuteMetrics = new ShareMetrics()
                {
                    Enabled     = true,
                    IncludeApis = true,
                    Version     = "1.0",

                    RetentionPolicy = new ShareRetentionPolicy()
                    {
                        Enabled = true,
                        Days    = 7
                    }
                }
            });

            // Read the metrics properties we just set
            ShareServiceProperties serviceProperties = await shareService.GetPropertiesAsync();

            // Display the properties
            Console.WriteLine();
            Console.WriteLine($"HourMetrics.InludeApis: {serviceProperties.HourMetrics.IncludeApis}");
            Console.WriteLine($"HourMetrics.RetentionPolicy.Days: {serviceProperties.HourMetrics.RetentionPolicy.Days}");
            Console.WriteLine($"HourMetrics.Version: {serviceProperties.HourMetrics.Version}");
            Console.WriteLine();
            Console.WriteLine($"MinuteMetrics.InludeApis: {serviceProperties.MinuteMetrics.IncludeApis}");
            Console.WriteLine($"MinuteMetrics.RetentionPolicy.Days: {serviceProperties.MinuteMetrics.RetentionPolicy.Days}");
            Console.WriteLine($"MinuteMetrics.Version: {serviceProperties.MinuteMetrics.Version}");
            Console.WriteLine();
        }
 public GetSharesAsyncCollection(
     ShareServiceClient client,
     ShareTraits traits = ShareTraits.None,
     ShareStates states = ShareStates.None,
     string prefix      = default)
 {
     _client = client;
     _traits = traits;
     _states = states;
     _prefix = prefix;
 }
        public void FileUriBuilder_RoundTrip()
        {
            ShareServiceClient serviceUri = GetServiceClient_AccountSas();
            var blobUriBuilder            = new ShareUriBuilder(serviceUri.Uri);

            Uri blobUri = blobUriBuilder.ToUri();

            var expectedUri = WebUtility.UrlDecode(serviceUri.Uri.AbsoluteUri);
            var actualUri   = WebUtility.UrlDecode(blobUri.AbsoluteUri);

            Assert.AreEqual(expectedUri, actualUri, "Flaky test -- potential signature generation issue not properly encoding space and + in the output");
        }
        /// <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();
        }
        // </snippet_CreateShareSnapshot>

        // <snippet_ListShareSnapshots>
        //-------------------------------------------------
        // List the snapshots on a share
        //-------------------------------------------------
        public void ListShareSnapshots()
        {
            // Get the connection string from app settings
            string connectionString = ConfigurationManager.AppSettings["StorageConnectionString"];

            // Instatiate a ShareServiceClient
            ShareServiceClient shareServiceClient = new ShareServiceClient(connectionString);

            // Display each share and the snapshots on each share
            foreach (ShareItem item in shareServiceClient.GetShares(ShareTraits.All, ShareStates.Snapshots))
            {
                if (null != item.Snapshot)
                {
                    Console.WriteLine($"Share: {item.Name}\tSnapshot: {item.Snapshot}");
                }
            }
        }
        // </snippet_RestoreFileFromSnapshot>
        //Uri snapshotFileUri = GetFileSasUri(shareName, snapshotDir.Name + "/" + snapshotFile.Name, DateTime.UtcNow.AddHours(24), ShareFileSasPermissions.Read);

        // <snippet_DeleteSnapshot>
        //-------------------------------------------------
        // Delete a snapshot
        //-------------------------------------------------
        public async Task DeleteSnapshotAsync(string shareName, string snapshotTime)
        {
            // Get the connection string from app settings
            string connectionString = ConfigurationManager.AppSettings["StorageConnectionString"];

            // Instatiate a ShareServiceClient
            ShareServiceClient shareService = new ShareServiceClient(connectionString);

            // Get a ShareClient
            ShareClient share = shareService.GetShareClient(shareName);

            // Get as ShareClient that points to a snapshot
            ShareClient snapshot = share.WithSnapshot(snapshotTime);

            // This deletes the whole share, not just the snapshot
            await snapshot.DeleteIfExistsAsync();
        }
Ejemplo n.º 12
0
        public static async Task <List <FileShareWrapper> > ListFileSharesAsync(string account, string key)
        {
            System.Threading.CancellationToken cancellationToken = new System.Threading.CancellationToken();
            ShareServiceClient client = new ShareServiceClient(Client.GetConnectionString(account, key));

            List <FileShareWrapper> items = new List <FileShareWrapper>();

            var shares = client.GetSharesAsync(ShareTraits.None, ShareStates.None, null, cancellationToken);

            await foreach (var share in shares)
            {
                items.Add(new FileShareWrapper {
                    Name = share.Name
                });
            }

            return(items);
        }
        public async Task ConnectionStringAsync()
        {
            // 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;

            // Create a client that can authenticate with a connection string
            ShareServiceClient service = new ShareServiceClient(connectionString);

            // Make a service request to verify we've successfully authenticated
            await service.GetPropertiesAsync();
        }
        /// <summary>
        /// Query the Cross-Origin Resource Sharing (CORS) rules for the File service
        /// </summary>
        /// <param name="shareServiceClient"></param>
        private static async Task CorsSample(ShareServiceClient shareServiceClient)
        {
            Console.WriteLine();

            // Get service properties
            Console.WriteLine("Get service properties");
            ShareServiceProperties originalProperties = await shareServiceClient.GetPropertiesAsync();

            try
            {
                // Add CORS rule
                Console.WriteLine("Add CORS rule");

                var corsRule = new ShareCorsRule
                {
                    AllowedHeaders  = "*",
                    AllowedMethods  = "GET",
                    AllowedOrigins  = "*",
                    ExposedHeaders  = "*",
                    MaxAgeInSeconds = 3600
                };

                ShareServiceProperties serviceProperties = await shareServiceClient.GetPropertiesAsync();

                serviceProperties.Cors.Clear();
                serviceProperties.Cors.Add(corsRule);

                await shareServiceClient.SetPropertiesAsync(serviceProperties);

                Console.WriteLine("Set property successfully");
            }
            finally
            {
                // Revert back to original service properties
                Console.WriteLine("Revert back to original service properties");
                await shareServiceClient.SetPropertiesAsync(originalProperties);

                Console.WriteLine("Revert properties successfully.");
            }

            Console.WriteLine();
        }
        // </snippet_CopyFileToBlob>

        // <snippet_CreateShareSnapshot>
        //-------------------------------------------------
        // Create a share snapshot
        //-------------------------------------------------
        public async Task CreateShareSnapshotAsync(string shareName)
        {
            // Get the connection string from app settings
            string connectionString = ConfigurationManager.AppSettings["StorageConnectionString"];

            // Instatiate a ShareServiceClient
            ShareServiceClient shareServiceClient = new ShareServiceClient(connectionString);

            // Instantiate a ShareClient which will be used to access the file share
            ShareClient share = shareServiceClient.GetShareClient(shareName);

            // Ensure that the share exists
            if (await share.ExistsAsync())
            {
                // Create a snapshot
                ShareSnapshotInfo snapshotInfo = await share.CreateSnapshotAsync();

                Console.WriteLine($"Snapshot created: {snapshotInfo.Snapshot}");
            }
        }
        public async Task SharedAccessSignatureAuthAsync()
        {
            // Create a service level SAS that only allows reading from service
            // level APIs
            AccountSasBuilder sas = new AccountSasBuilder
            {
                // Allow access to files
                Services = AccountSasServices.Files,

                // Allow access to the service level APIs
                ResourceTypes = AccountSasResourceTypes.Service,

                // Access expires in 1 hour!
                ExpiresOn = DateTimeOffset.UtcNow.AddHours(1)
            };

            // Allow read access
            sas.SetPermissions(AccountSasPermissions.Read);

            // Create a SharedKeyCredential that we can use to sign the SAS token
            StorageSharedKeyCredential credential = new StorageSharedKeyCredential(StorageAccountName, StorageAccountKey);

            // Build a SAS URI
            UriBuilder sasUri = new UriBuilder(StorageAccountFileUri);

            sasUri.Query = sas.ToSasQueryParameters(credential).ToString();

            // Create a client that can authenticate with the SAS URI
            ShareServiceClient service = new ShareServiceClient(sasUri.Uri);

            // Make a service request to verify we've successfully authenticated
            await service.GetPropertiesAsync();

            // Try to create a new container (which is beyond our
            // delegated permission)
            RequestFailedException ex =
                Assert.ThrowsAsync <RequestFailedException>(
                    async() => await service.CreateShareAsync(Randomize("sample-share")));

            Assert.AreEqual(403, ex.Status);
        }
        // </snippet_ListShareSnapshots>

        public ShareItem GetSnapshotItem()
        {
            ShareItem result = null;

            // Get the connection string from app settings
            string connectionString = ConfigurationManager.AppSettings["StorageConnectionString"];

            // Instatiate a ShareServiceClient
            ShareServiceClient shareServiceClient = new ShareServiceClient(connectionString);

            foreach (ShareItem item in shareServiceClient.GetShares(ShareTraits.All, ShareStates.Snapshots))
            {
                if (null != item.Snapshot)
                {
                    // Return the first share with a snapshot
                    return(item);
                }
            }

            return(result);
        }
Ejemplo n.º 18
0
        // <snippet_ListSnapshotContents>
        //-------------------------------------------------
        // List the snapshots on a share
        //-------------------------------------------------
        public void ListSnapshotContents(string shareName, string snapshotTime)
        {
            // Get the connection string from app settings
            string connectionString = ConfigurationManager.AppSettings["StorageConnectionString"];

            // Instatiate a ShareServiceClient
            ShareServiceClient shareService = new ShareServiceClient(connectionString);

            // Get a ShareClient
            ShareClient share = shareService.GetShareClient(shareName);

            Console.WriteLine($"Share: {share.Name}");

            // Get as ShareClient that points to a snapshot
            ShareClient snapshot = share.WithSnapshot(snapshotTime);

            // Get the root directory in the snapshot share
            ShareDirectoryClient rootDir = snapshot.GetRootDirectoryClient();

            // Recursively list the directory tree
            ListDirTree(rootDir);
        }
        /// <summary>
        /// Test some of the file storage operations.
        /// </summary>
        public async Task RunFileStorageAdvancedOpsAsync()
        {
            //***** Setup *****//
            Console.WriteLine("Getting reference to the storage account.");

            // How to create a storage connection string - http://msdn.microsoft.com/en-us/library/azure/ee758697.aspx
            string storageConnectionString = ConfigurationManager.AppSettings.Get("StorageConnectionString");

            Console.WriteLine("Instantiating file client.");
            Console.WriteLine(string.Empty);

            // Create a share service client for interacting with the file service.
            var shareServiceClient = new ShareServiceClient(storageConnectionString);

            // List shares
            await ListSharesSample(shareServiceClient);

            // CORS Rules
            await CorsSample(shareServiceClient);

            // Share Properties
            await SharePropertiesSample(shareServiceClient);

            // Share Metadata
            await ShareMetadataSample(shareServiceClient);

            // Directory Properties
            await DirectoryPropertiesSample(shareServiceClient);

            // Directory Metadata
            await DirectoryMetadataSample(shareServiceClient);

            // File Properties
            await FilePropertiesSample(shareServiceClient);

            // File Metadata
            await FileMetadataSample(shareServiceClient);
        }
Ejemplo n.º 20
0
 public async Task <DisposingShare> GetTestShareAsync(
     ShareServiceClient service            = default,
     string shareName                      = default,
     IDictionary <string, string> metadata = default)
 => await SharesClientBuilder.GetTestShareAsync(service, shareName, metadata);
        /// <summary>
        /// Test some of the file storage operations.
        /// </summary>
        public async Task RunFileStorageOperationsAsync()
        {
            // These are used in the finally block to clean up the objects created during the demo.
            ShareClient          shareClient     = null;
            ShareFileClient      shareFileClient = null;
            ShareDirectoryClient fileDirectory   = null;

            BlobClient          targetBlob    = null;
            BlobContainerClient blobContainer = null;

            string destFile       = null;
            string downloadFolder = null;
            // Name to be used for the file when downloading it so you can inspect it locally
            string downloadFile = null;

            try
            {
                //***** Setup *****//
                Console.WriteLine("Getting reference to the storage account.");

                // How to create a storage connection string - http://msdn.microsoft.com/en-us/library/azure/ee758697.aspx
                string storageConnectionString = ConfigurationManager.AppSettings.Get("StorageConnectionString");
                string storageAccountName      = ConfigurationManager.AppSettings.Get("StorageAccountName");
                string storageAccountKey       = ConfigurationManager.AppSettings.Get("StorageAccountKey");

                Console.WriteLine("Instantiating file client.");

                // Create a share client for interacting with the file service.
                var shareServiceClient = new ShareServiceClient(storageConnectionString);

                // Create the share name -- use a guid in the name so it's unique.
                // This will also be used as the container name for blob storage when copying the file to blob storage.
                string shareName = "demotest-" + System.Guid.NewGuid().ToString();

                // Name of folder to put the files in
                string sourceFolder = "testfolder";

                // Name of file to upload and download
                string testFile = "HelloWorld.png";

                // Folder where the HelloWorld.png file resides
                string localFolder = @".\";

                // It won't let you download in the same folder as the exe file,
                //   so use a temporary folder with the same name as the share.
                downloadFolder = Path.Combine(Path.GetTempPath(), shareName);

                //***** Create a file share *****//

                // Create the share if it doesn't already exist.
                Console.WriteLine("Creating share with name {0}", shareName);
                shareClient = shareServiceClient.GetShareClient(shareName);
                try
                {
                    await shareClient.CreateIfNotExistsAsync();

                    Console.WriteLine("    Share created successfully.");
                }
                catch (RequestFailedException exRequest)
                {
                    Common.WriteException(exRequest);
                    Console.WriteLine("Please make sure your storage account has storage file endpoint enabled and 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;
                }

                //***** Create a directory on the file share *****//

                // Create a directory on the share.
                Console.WriteLine("Creating directory named {0}", sourceFolder);

                ShareDirectoryClient rootDirectory = shareClient.GetRootDirectoryClient();

                // If the source folder is null, then use the root folder.
                // If the source folder is specified, then get a reference to it.
                if (string.IsNullOrWhiteSpace(sourceFolder))
                {
                    // There is no folder specified, so return a reference to the root directory.
                    fileDirectory = rootDirectory;
                    Console.WriteLine("    Using root directory.");
                }
                else
                {
                    // There was a folder specified, so return a reference to that folder.
                    fileDirectory = rootDirectory.GetSubdirectoryClient(sourceFolder);

                    await fileDirectory.CreateIfNotExistsAsync();

                    Console.WriteLine("    Directory created successfully.");
                }

                //***** Upload a file to the file share *****//

                // Get a file client.
                shareFileClient = fileDirectory.GetFileClient(testFile);

                // Upload a file to the share.
                Console.WriteLine("Uploading file {0} to share", testFile);

                // Set up the name and path of the local file.
                string sourceFile = Path.Combine(localFolder, testFile);
                if (File.Exists(sourceFile))
                {
                    using (FileStream stream = File.OpenRead(sourceFile))
                    {
                        // Upload from the local file to the file share in azure.
                        await shareFileClient.CreateAsync(stream.Length);

                        await shareFileClient.UploadAsync(stream);
                    }
                    Console.WriteLine("    Successfully uploaded file to share.");
                }
                else
                {
                    Console.WriteLine("File not found, so not uploaded.");
                }

                //***** Get list of all files/directories on the file share*****//

                // List all files/directories under the root directory.
                Console.WriteLine("Getting list of all files/directories under the root directory of the share.");

                var fileList = rootDirectory.GetFilesAndDirectoriesAsync();

                // Print all files/directories listed above.
                await foreach (ShareFileItem listItem in fileList)
                {
                    // listItem type will be ShareClient or ShareDirectoryClient.
                    Console.WriteLine("    - {0} (type: {1})", listItem.Name, listItem.GetType());
                }

                Console.WriteLine("Getting list of all files/directories in the file directory on the share.");

                // Now get the list of all files/directories in your directory.
                // Ordinarily, you'd write something recursive to do this for all directories and subdirectories.

                fileList = fileDirectory.GetFilesAndDirectoriesAsync();

                // Print all files/directories in the folder.
                await foreach (ShareFileItem listItem in fileList)
                {
                    // listItem type will be a file or directory
                    Console.WriteLine("    - {0} (IsDirectory: {1})", listItem.Name, listItem.IsDirectory);
                }

                //***** Download a file from the file share *****//

                // Download the file to the downloadFolder in the temp directory.
                // Check and if the directory doesn't exist (which it shouldn't), create it.
                Console.WriteLine("Downloading file from share to local temp folder {0}.", downloadFolder);
                if (!Directory.Exists(downloadFolder))
                {
                    Directory.CreateDirectory(downloadFolder);
                }

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

                downloadFile = Path.Combine(downloadFolder, testFile);
                using (FileStream stream = File.OpenWrite(downloadFile))
                {
                    await download.Content.CopyToAsync(stream);
                }

                Console.WriteLine("    Successfully downloaded file from share to local temp folder.");

                //***** Copy a file from the file share to blob storage, then abort the copy *****//

                // Copies can sometimes complete before there's a chance to abort.
                // If that happens with the file you're testing with, try copying the file
                //   to a storage account in a different region. If it still finishes too fast,
                //   try using a bigger file and copying it to a different region. That will almost always
                //   take long enough to give you time to abort the copy.
                // If you want to change the file you're testing the Copy with without changing the value for the
                //   rest of the sample code, upload the file to the share, then assign the name of the file
                //   to the testFile variable right here before calling GetFileClient.
                //   Then it will use the new file for the copy and abort but the rest of the code
                //   will still use the original file.
                ShareFileClient shareFileCopy = fileDirectory.GetFileClient(testFile);

                // Upload a file to the share.
                Console.WriteLine("Uploading file {0} to share", testFile);

                // Set up the name and path of the local file.
                string sourceFileCopy = Path.Combine(localFolder, testFile);
                using (FileStream stream = File.OpenRead(sourceFile))
                {
                    // Upload from the local file to the file share in azure.
                    await shareFileCopy.CreateAsync(stream.Length);

                    await shareFileCopy.UploadAsync(stream);
                }
                Console.WriteLine("    Successfully uploaded file to share.");

                // Copy the file to blob storage.
                Console.WriteLine("Copying file to blob storage. Container name = {0}", shareName);

                // First get a blob service client.
                var blobServiceClient = new BlobServiceClient(storageConnectionString);

                // Get a blob container client and create it if it doesn't already exist.
                blobContainer = blobServiceClient.GetBlobContainerClient(shareName);
                await blobContainer.CreateIfNotExistsAsync();

                // Get a blob client to the target blob.
                targetBlob = blobContainer.GetBlobClient(testFile);

                string copyId = string.Empty;

                // Get a share file client to be copied.
                shareFileClient = fileDirectory.GetFileClient(testFile);

                // Create a SAS for the file that's valid for 24 hours.
                // Note that when you are copying a file to a blob, or a blob to a file, you must use a SAS
                // to authenticate access to the source object, even if you are copying within the same
                // storage account.
                var sas = new AccountSasBuilder
                {
                    // Allow access to Files
                    Services = AccountSasServices.Files,

                    // Allow access to the service level APIs
                    ResourceTypes = AccountSasResourceTypes.All,

                    // Access expires in 1 day!
                    ExpiresOn = DateTime.UtcNow.AddDays(1)
                };
                sas.SetPermissions(AccountSasPermissions.Read);

                var credential = new StorageSharedKeyCredential(storageAccountName, storageAccountKey);

                // Build a SAS URI
                var sasUri = new UriBuilder(shareFileClient.Uri)
                {
                    Query = sas.ToSasQueryParameters(credential).ToString()
                };
                // Start the copy of the file to the blob.
                CopyFromUriOperation operation = await targetBlob.StartCopyFromUriAsync(sasUri.Uri);

                copyId = operation.Id;

                Console.WriteLine("   File copy started successfully. copyID = {0}", copyId);

                // Now clean up after yourself.
                Console.WriteLine("Deleting the files from the file share.");

                // Delete the files because cloudFile is a different file in the range sample.
                shareFileClient = fileDirectory.GetFileClient(testFile);
                await shareFileClient.DeleteIfExistsAsync();

                Console.WriteLine("Setting up files to test WriteRange and ListRanges.");

                //***** Write 2 ranges to a file, then list the ranges *****//

                // This is the code for trying out writing data to a range in a file,
                //   and then listing those ranges.
                // Get a reference to a file and write a range of data to it      .
                // Then write another range to it.
                // Then list the ranges.

                // Start at the very beginning of the file.
                long startOffset = 0;

                // Set the destination file name -- this is the file on the file share that you're writing to.
                destFile        = "rangeops.txt";
                shareFileClient = fileDirectory.GetFileClient(destFile);

                // Create a string with 512 a's in it. This will be used to write the range.
                int    testStreamLen = 512;
                string textToStream  = string.Empty;
                textToStream = textToStream.PadRight(testStreamLen, 'a');

                using (MemoryStream ms = new MemoryStream(Encoding.Default.GetBytes(textToStream)))
                {
                    // Max size of the output file; have to specify this when you create the file
                    // I picked this number arbitrarily.
                    long maxFileSize = 65536;

                    Console.WriteLine("Write first range.");

                    // Set the stream back to the beginning, in case it's been read at all.
                    ms.Position = 0;

                    // If the file doesn't exist, create it.
                    // The maximum file size is passed in. It has to be big enough to hold
                    //   all the data you're going to write, so don't set it to 256k and try to write two 256-k blocks to it.
                    if (!shareFileClient.Exists())
                    {
                        Console.WriteLine("File doesn't exist, create empty file to write ranges to.");

                        // Create a file with a maximum file size of 64k.
                        await shareFileClient.CreateAsync(maxFileSize);

                        Console.WriteLine("    Empty file created successfully.");
                    }

                    // Write the stream to the file starting at startOffset for the length of the stream.
                    Console.WriteLine("Writing range to file.");
                    var range = new HttpRange(startOffset, textToStream.Length);
                    await shareFileClient.UploadRangeAsync(range, ms);

                    // Download the file to your temp directory so you can inspect it locally.
                    downloadFile = Path.Combine(downloadFolder, "__testrange.txt");
                    Console.WriteLine("Downloading file to examine.");
                    download = await shareFileClient.DownloadAsync();

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

                    Console.WriteLine("    Successfully downloaded file with ranges in it to examine.");
                }

                // Now add the second range, but don't make it adjacent to the first one, or it will show only
                //   one range, with the two combined. Put it like 1000 spaces away. When you get the range back, it will
                //   start at the position at the 512-multiple border prior or equal to the beginning of the data written,
                //   and it will end at the 512-multliple border after the actual end of the data.
                //For example, if you write to 2000-3000, the range will be the 512-multiple prior to 2000, which is
                //   position 1536, or offset 1535 (because it's 0-based).
                //   And the right offset of the range will be the 512-multiple after 3000, which is position 3072,
                //   or offset 3071 (because it's 0-based).
                Console.WriteLine("Getting ready to write second range to file.");

                startOffset += testStreamLen + 1000; //randomly selected number

                // Create a string with 512 b's in it. This will be used to write the range.
                textToStream = string.Empty;
                textToStream = textToStream.PadRight(testStreamLen, 'b');

                using (MemoryStream ms = new MemoryStream(Encoding.Default.GetBytes(textToStream)))
                {
                    ms.Position = 0;

                    // Write the stream to the file starting at startOffset for the length of the stream.
                    Console.WriteLine("Write second range to file.");
                    var range = new HttpRange(startOffset, textToStream.Length);
                    await shareFileClient.UploadRangeAsync(range, ms);

                    Console.WriteLine("    Successful writing second range to file.");

                    // Download the file to your temp directory so you can examine it.
                    downloadFile = Path.Combine(downloadFolder, "__testrange2.txt");
                    Console.WriteLine("Downloading file with two ranges in it to examine.");

                    download = await shareFileClient.DownloadAsync();

                    using (FileStream stream = File.OpenWrite(downloadFile))
                    {
                        await download.Content.CopyToAsync(stream);
                    }
                    Console.WriteLine("    Successfully downloaded file to examine.");
                }

                // Query and view the list of ranges.
                Console.WriteLine("Call to get the list of ranges.");
                var listOfRanges = await shareFileClient.GetRangeListAsync(new HttpRange());


                Console.WriteLine("    Successfully retrieved list of ranges.");
                foreach (HttpRange range in listOfRanges.Value.Ranges)
                {
                    Console.WriteLine("    --> filerange startOffset = {0}, endOffset = {1}", range.Offset, range.Offset + range.Length);
                }

                //***** Clean up *****//
            }
            catch (Exception ex)
            {
                Console.WriteLine("    Exception thrown. Message = {0}{1}    Strack Trace = {2}", ex.Message, Environment.NewLine, ex.StackTrace);
            }
            finally
            {
                //Clean up after you're done.

                Console.WriteLine("Removing all files, folders, shares, blobs, and containers created in this demo.");

                // ****NOTE: You can just delete the file share, and everything will be removed.
                // This samples deletes everything off of the file share first for the purpose of
                //   showing you how to delete specific files and directories.


                // Delete the file with the ranges in it.
                destFile        = "rangeops.txt";
                shareFileClient = fileDirectory.GetFileClient(destFile);
                await shareFileClient.DeleteIfExistsAsync();

                Console.WriteLine("Deleting the directory on the file share.");

                // Delete the directory.
                bool success = await fileDirectory.DeleteIfExistsAsync();

                if (success)
                {
                    Console.WriteLine("    Directory on the file share deleted successfully.");
                }
                else
                {
                    Console.WriteLine("    Directory on the file share NOT deleted successfully; may not exist.");
                }

                Console.WriteLine("Deleting the file share.");

                // Delete the share.
                await shareClient.DeleteAsync();

                Console.WriteLine("    Deleted the file share successfully.");

                Console.WriteLine("Deleting the temporary download directory and the file in it.");

                // Delete the download folder and its contents.
                Directory.Delete(downloadFolder, true);
                Console.WriteLine("    Successfully deleted the temporary download directory.");

                Console.WriteLine("Deleting the container and blob used in the Copy/Abort test.");
                await targetBlob.DeleteIfExistsAsync();

                await blobContainer.DeleteIfExistsAsync();

                Console.WriteLine("    Successfully deleted the blob and its container.");
            }
        }
        public async Task ManageFileShareSecretAsync(V1Secret secret)
        {
            byte[] accountKeyData;
            byte[] accountNameData;

            if (!secret.Data.TryGetValue(AccountKey, out accountKeyData))
            {
                Console.WriteLine($"Secret {secret.Metadata.Name} doesn't have [{AccountKey}] Data");
                return;
            }
            if (!secret.Data.TryGetValue(AccountName, out accountNameData))
            {
                Console.WriteLine($"Secret {secret.Metadata.Name} doesn't have [{AccountName}] Data");
                return;
            }

            var pvLabels = new Dictionary <string, string>
            {
                [Constants.LabelSelectorKey] = Constants.LabelSelectorValue
            };
            var mountOptions = new List <string>
            {
                "dir_mode=0777",
                "file_mode=0777",
                "uid=1000",
                "gid=1000",
                "mfsymlinks",
                "nobrl"
            };
            V1PersistentVolumeList currentPvs = await k8sClient.ListPersistentVolumeAsync(labelSelector : Constants.LabelSelector);

            var existingPvSet = new Set <V1PersistentVolume>(currentPvs.Items
                                                             .Where(pv => pv.Spec?.AzureFile?.SecretName == secret.Metadata.Name)
                                                             .ToDictionary(pv => pv.Metadata.Name));
            var desiredPvs = new ConcurrentDictionary <string, V1PersistentVolume>();

            string accountKey       = Encoding.UTF8.GetString(accountKeyData);
            string accountName      = Encoding.UTF8.GetString(accountNameData);
            string connectionString = $"DefaultEndpointsProtocol=https;AccountName={accountName};AccountKey={accountKey};EndpointSuffix=core.windows.net";

            // Open a FileShare client with secret.
            var serviceClient = new ShareServiceClient(connectionString);
            var shares        = serviceClient.GetSharesAsync(ShareTraits.Metadata, ShareStates.None);

            await foreach (var share in shares)
            {
                // Get all file shares from client that match a trait
                if ((share.Properties?.Metadata != null) &&
                    (share.Properties.Metadata.TryGetValue(Constants.LabelSelectorKey, out string labelValue)) &&
                    (labelValue == Constants.LabelSelectorValue))
                {
                    // Create a PV from secret and ShareItem
                    Console.WriteLine($"ShareItem {share.Name} found!");
                    string name        = KubeUtils.SanitizeK8sValue($"{accountName}-{share.Name}");
                    var    metadata    = new V1ObjectMeta(name: name, labels: pvLabels);
                    var    accessModes = new List <string> {
                        AccessMode
                    };
                    var azurefile = new V1AzureFilePersistentVolumeSource(secret.Metadata.Name, share.Name, readOnlyProperty: false, secret.Metadata.NamespaceProperty);
                    var capacity  = new Dictionary <string, ResourceQuantity> {
                        ["storage"] = new ResourceQuantity($"{share.Properties.QuotaInGB}Gi")
                    };
                    var spec = new V1PersistentVolumeSpec(
                        accessModes: accessModes,
                        azureFile: azurefile,
                        capacity: capacity,
                        storageClassName: StorageClassName,
                        mountOptions: mountOptions);
                    var pv = new V1PersistentVolume(metadata: metadata, spec: spec);
                    if (!desiredPvs.TryAdd(name, pv))
                    {
                        Console.WriteLine($"Duplicate share name {name}");
                    }
                }
            }

            var desiredPvSet = new Set <V1PersistentVolume>(desiredPvs);
            var diff         = desiredPvSet.Diff(existingPvSet, PvComparer);

            await this.ManagePvs(diff);
        }
Ejemplo n.º 23
0
        private void OnLogin(object obj)
        {
            IsBusy_Login  = true;
            LoginAble     = false;
            FailedMessage = string.Empty;
            string md5Password = HashHelper.ComputeStringMd5(Password);

            if (IsRememberPwd)
            {
                ShareWareSettings.Default.Password = Password;
                ShareWareSettings.Default.UserName = UserName;
                ShareWareSettings.Default.Save();
            }

            try
            {
                if (_hasLogin)
                {
                    _client.Logout();
                    _client.Close();

                    IsBusy_Login = false;
                    if (LogoutSuccess != null)
                    {
                        LogoutSuccess(this, null);
                    }
                }
                else
                {
                    Task task = new Task(() =>
                    {
                        _callBack = new CallBack(this);
                        _client   = new ShareServiceClient(new InstanceContext(_callBack));
                        _client.ClientCredentials.UserName.UserName = UserName;
                        _client.ClientCredentials.UserName.Password = HashHelper.ComputeStringMd5(Password);

                        _client.InnerChannel.Closing += InnerChannel_Closing;

                        try
                        {
                            _id = _client.Login(GetFirstMac());

                            if (_id < 0)
                            {
                                if (LoginFailed != null)
                                {
                                    LoginFailed(this, new ModelEventArgs(ModelEventType.ConnectMeesage)
                                    {
                                        FailedMessage = "用户名或密码错误"
                                    });
                                }
                                return;
                            }

                            if (LoginSuccess != null)
                            {
                                //LoginSuccess(this, null);
                                ExecuteEventAsync(this, null, LoginSuccess, null);
                            }

                            IsBusy_Login = false;
                            LoginAble    = true;
                        }
                        catch (FaultException)
                        {
                        }
                        catch (Exception)
                        {
                            ErrorOccur(this, new ModelEventArgs(ModelEventType.ConnectMeesage)
                            {
                                FailedMessage = "连接服务器出错"
                            });
                            IsBusy_Login = false;
                            LoginAble    = true;
                            return;
                        }
                    });
                    task.Start();
                }
            }
            catch (Exception e)
            {
                if (ErrorOccur != null)
                {
                    ErrorOccur(this, new ModelEventArgs(ModelEventType.Exception)
                    {
                        ModelException = e
                    });
                }
            }
        }
Ejemplo n.º 24
0
 private Controller()
 {
     this.binding  = this.CreateHttpBinding();
     this.endpoint = new EndpointAddress("http://40.115.38.250/Service/ShareService.svc");
     service       = new ShareServiceClient(binding, endpoint);
 }
        private static async Task ListSharesSample(ShareServiceClient shareServiceClient)
        {
            Console.WriteLine();

            // Keep a list of the file shares so you can compare this list
            //   against the list of shares that we retrieve .
            List <string> fileShareNames = new List <string>();

            try
            {
                // Create 3 file shares.

                // Create the share name -- use a guid in the name so it's unique.
                // This will also be used as the container name for blob storage when copying the file to blob storage.
                string baseShareName = "demotest-" + System.Guid.NewGuid().ToString();

                for (int i = 0; i < 3; i++)
                {
                    // Set the name of the share, then add it to the generic list.
                    string shareName = baseShareName + "-0" + i;
                    fileShareNames.Add(shareName);

                    // Create the share with this name.
                    Console.WriteLine("Creating share with name {0}", shareName);
                    ShareClient shareClient = shareServiceClient.GetShareClient(shareName);
                    try
                    {
                        await shareClient.CreateIfNotExistsAsync();

                        Console.WriteLine("    Share created successfully.");
                    }
                    catch (RequestFailedException exRequest)
                    {
                        Common.WriteException(exRequest);
                        Console.WriteLine(
                            "Please make sure your storage account has storage file endpoint enabled and 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;
                    }
                }

                Console.WriteLine(string.Empty);
                Console.WriteLine("List of shares in the storage account:");

                // List the file shares for this storage account
                var shareList = shareServiceClient.GetSharesAsync();
                try
                {
                    await foreach (ShareItem share in shareList)
                    {
                        Console.WriteLine("Cloud Share name = {0}", share.Name);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine("    Exception thrown listing shares.");
                    Common.WriteException(ex);
                    throw;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("    Exception thrown. Message = {0}{1}    Strack Trace = {2}", ex.Message,
                                  Environment.NewLine, ex.StackTrace);
            }
            finally
            {
                // If it created the file shares, remove them (cleanup).
                if (fileShareNames != null && shareServiceClient != null)
                {
                    // Now clean up after yourself, using the list of shares that you created in case there were other shares in the account.
                    foreach (string fileShareName in fileShareNames)
                    {
                        ShareClient share = shareServiceClient.GetShareClient(fileShareName);
                        share.DeleteIfExists();
                    }
                }
            }

            Console.WriteLine();
        }
        /// <summary>
        /// Manage file metadata
        /// </summary>
        /// <param name="shareServiceClient"></param>
        /// <returns></returns>
        private static async Task FileMetadataSample(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();

                // Create directory
                Console.WriteLine("Create directory");
                ShareDirectoryClient rootDirectory = shareClient.GetRootDirectoryClient();

                ShareFileClient file = rootDirectory.GetFileClient("demofile");

                // Create file
                Console.WriteLine("Create file");
                await file.CreateAsync(1000);

                // Set file metadata
                Console.WriteLine("Set file metadata");
                var metadata = new Dictionary <string, string> {
                    { "key1", "value1" }, { "key2", "value2" }
                };

                await file.SetMetadataAsync(metadata);

                // Fetch file attributes
                ShareFileProperties properties = await file.GetPropertiesAsync();

                Console.WriteLine("Get file metadata:");
                foreach (var keyValue in properties.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();
            }
        }
        /// <summary>
        /// Manage file properties
        /// </summary>
        /// <param name="shareServiceClient"></param>
        /// <returns></returns>
        private static async Task FilePropertiesSample(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();

                // Create directory
                Console.WriteLine("Create directory");
                ShareDirectoryClient rootDirectory = shareClient.GetRootDirectoryClient();

                ShareFileClient file = rootDirectory.GetFileClient("demofile");

                // Create file
                Console.WriteLine("Create file");
                await file.CreateAsync(1000);

                // Set file properties
                var headers = new ShareFileHttpHeaders
                {
                    ContentType     = "plain/text",
                    ContentEncoding = new string[] { "UTF-8" },
                    ContentLanguage = new string[] { "en" }
                };

                await file.SetHttpHeadersAsync(httpHeaders : headers);

                // Fetch file attributes
                ShareFileProperties shareFileProperties = await file.GetPropertiesAsync();

                Console.WriteLine("Get file properties:");
                Console.WriteLine("    Content type: {0}", shareFileProperties.ContentType);
                Console.WriteLine("    Content encoding: {0}", string.Join("", shareFileProperties.ContentEncoding));
                Console.WriteLine("    Content language: {0}", string.Join("", shareFileProperties.ContentLanguage));
                Console.WriteLine("    Length: {0}", shareFileProperties.ContentLength);
            }
            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();
        }