Esempio n. 1
0
        static void Main(string[] args)
        {
            CloudStorageAccount cuentaAlmacenamiento = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("FileConnectionString"));
            CloudFileClient     clienteArchivos      = cuentaAlmacenamiento.CreateCloudFileClient();
            CloudFileShare      archivoCompartido    = clienteArchivos.GetShareReference("platzifile");

            if (archivoCompartido.Exists())
            {
                CloudFileDirectory carpetaRaiz = archivoCompartido.GetRootDirectoryReference();
                CloudFileDirectory directorio  = carpetaRaiz.GetDirectoryReference(DIRECTORIO_NOMBRE);

                if (directorio.Exists())
                {
                    Console.WriteLine($"Archivo a leer: {ARCHIVO_NOMBRE}");
                    CloudFile archivo = directorio.GetFileReference(ARCHIVO_NOMBRE);
                    if (archivo.Exists())
                    {
                        Console.WriteLine(archivo.DownloadTextAsync().Result);
                    }
                    else
                    {
                        Console.WriteLine($"no se encontro el archivo: {ARCHIVO_NOMBRE}");
                    }
                }
                else
                {
                    Console.WriteLine($"no se encontro la carpeta: {DIRECTORIO_NOMBRE}");
                }
            }
            Console.ReadLine();
        }
Esempio n. 2
0
        private CloudFileShare ConnectionToAzureShare()
        {
            CloudFileClient fileClient = _storageAccount.CreateCloudFileClient();
            CloudFileShare  share      = fileClient.GetShareReference(Share);

            return(!share.Exists() ? null : share);
        }
Esempio n. 3
0
        public void UpdateFile(string name)
        {
            _log.WriteLine($"Parameters: {name}");

            if (!EnsureConnectionStringValid())
            {
                return;
            }

            // Parse the connection string and return a reference to the storage account.
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(_connectionString);

            // Create a CloudFileClient object for credentialed access to Azure Files.
            CloudFileClient fileClient = storageAccount.CreateCloudFileClient();
            // Get a reference to the file share we created previously.
            CloudFileShare share = fileClient.GetShareReference(FileShareName);

            // Ensure that the share exists.
            if (share.Exists())
            {
                // Get a reference to the root directory for the share.
                CloudFileDirectory rootDir = share.GetRootDirectoryReference();

                CloudFile file = rootDir.GetFileReference(name);

                file.UploadText("File content.");
            }
        }
        static void Main(string[] args)
        {
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(connection);

            CloudFileClient cloudFileClient = storageAccount.CreateCloudFileClient();

            // Get a reference to the file share we created previously.
            CloudFileShare fileShare = cloudFileClient.GetShareReference("doc2020");

            // Ensure that the share exists.
            if (fileShare.Exists())
            {
                // Get a reference to the root directory for the share.
                CloudFileDirectory fileDirectory = fileShare.GetRootDirectoryReference();

                // Get a reference to the directory we created previously.
                CloudFileDirectory customDirectory = fileDirectory.GetDirectoryReference("storage");

                // Ensure that the directory exists.
                if (customDirectory.Exists())
                {
                    // Get a reference to the file we created previously.
                    CloudFile fileInfo = customDirectory.GetFileReference("Log1.txt");

                    // Ensure that the file exists.
                    if (fileInfo.Exists())
                    {
                        // Write the contents of the file to the console window.
                        Console.WriteLine(fileInfo.DownloadTextAsync().Result);
                    }
                }

                NewFileCreate();
            }
        }
        public Stream DownloadFileContentAsStream(string fileShareName, string fileName = "")
        {
            CloudFileClient fileClient = new CloudFileClient(fileURI, creds);
            // Create a CloudFileClient object for credentialed access to Azure Files.
            Stream s = null;

            // Get a reference to the file share we created previously.
            CloudFileShare share = fileClient.GetShareReference(fileShareName);

            // Ensure that the share exists.
            if (share.Exists())
            {
                try
                {
                    // Get a reference to the root directory for the share.
                    CloudFileDirectory rootDir   = share.GetRootDirectoryReference();
                    CloudFile          cloudFile = rootDir.GetFileReference(fileName);
                    cloudFile.DownloadToStream(s);
                    return(s);
                }
                catch (Exception e)
                {
                    throw new StorageAccountException("Error while attempting to get contents", e);
                }
            }
            else
            {
                DirectoryNotFoundException e = new DirectoryNotFoundException(string.Format("The file share '{0}' does not exist.", fileShareName));
                throw new StorageAccountException("Error while attempting to get content", e);
            }
        }
Esempio n. 6
0
        private string LoadAzureStorageFileContents(string fileName)
        {
            var storageAccountCS = GetStorageAccountCS();

            if (!string.IsNullOrEmpty(storageAccountCS))
            {
                CloudStorageAccount storageAccount = CloudStorageAccount.Parse(storageAccountCS);

                // Create a CloudFileClient object for credentialed access to Azure Files.
                CloudFileClient fileClient = storageAccount.CreateCloudFileClient();
                CloudFileShare  share      = fileClient.GetShareReference("eshopmodified");

                //// Ensure that the share exists.
                if (share.Exists())
                {
                    // Get a reference to the root directory for the share.
                    CloudFileDirectory rootDir = share.GetRootDirectoryReference();

                    //Get a reference to the file we created previously.
                    CloudFile file = rootDir.GetFileReference(fileName);

                    // Ensure that the file exists.
                    if (file.Exists())
                    {
                        //download file content
                        return(file.DownloadTextAsync().Result);
                    }
                }
            }

            return(string.Empty);
        }
Esempio n. 7
0
        public void Set_the_maximum_size_for_a_file_share()
        {
            // Parse the connection string for the storage account.
            StorageCredentials  Credentials    = new StorageCredentials(this.Account, this.Key);
            CloudStorageAccount storageAccount = new CloudStorageAccount(Credentials, false);

            // Create a CloudFileClient object for credentialed access to File storage.
            CloudFileClient fileClient = storageAccount.CreateCloudFileClient();

            // Get a reference to the file share we created previously.
            CloudFileShare share = fileClient.GetShareReference("logs");

            // Ensure that the share exists.
            if (share.Exists())
            {
                // Check current usage stats for the share.
                // Note that the ShareStats object is part of the protocol layer for the File service.
                Microsoft.WindowsAzure.Storage.File.Protocol.ShareStats stats = share.GetStats();
                Console.WriteLine("Current share usage: {0} GB", stats.Usage.ToString());

                // Specify the maximum size of the share, in GB.
                // This line sets the quota to be 10 GB greater than the current usage of the share.
                share.Properties.Quota = 10 + stats.Usage;
                share.SetProperties();

                // Now check the quota for the share. Call FetchAttributes() to populate the share's properties.
                share.FetchAttributes();
                Console.WriteLine("Current share quota: {0} GB", share.Properties.Quota);
            }
        }
Esempio n. 8
0
        static void Main(string[] args)
        {
            CloudStorageAccount CuentaAlmacenamiento =
                CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("CadenaConexion"));

            CloudFileClient ClienteArchivos   = CuentaAlmacenamiento.CreateCloudFileClient();
            CloudFileShare  ArchivoCompartido = ClienteArchivos.GetShareReference("filepleon");

            if (ArchivoCompartido.Exists())
            {
                CloudFileDirectory CarpetaRaiz = ArchivoCompartido.GetRootDirectoryReference();
                CloudFileDirectory Directorio  = CarpetaRaiz.GetDirectoryReference("Archivos");

                if (Directorio.Exists())
                {
                    CloudFile Archivo = Directorio.GetFileReference("prueba.txt");

                    if (Archivo.Exists())
                    {
                        Console.WriteLine(Archivo.DownloadTextAsync().Result);
                        Console.ReadLine();
                    }
                }
            }
        }
Esempio n. 9
0
        public CloudFileDirectory GetCloudFileDirectoryByEvent(LogEvent logEvent)
        {
            var azureConfig = _azureConfigContainer.Get(logEvent);

            if (azureConfig == null)
            {
                return(null);
            }

            var storageAccount = CloudStorageAccount.Parse(azureConfig.ConnectionString);

            CloudFileClient fileClient = storageAccount.CreateCloudFileClient();

            CloudFileShare share = fileClient.GetShareReference(azureConfig.FileShare);

            if (!share.Exists())
            {
                throw new StorageException($"{azureConfig.FileDirectory} not found.");
            }

            CloudFileDirectory rootDir = share.GetRootDirectoryReference();

            CloudFileDirectory cloudFileDirectory = rootDir.GetDirectoryReference(azureConfig.FileDirectory);

            return(cloudFileDirectory);
        }
Esempio n. 10
0
        public static CloudFileDirectory BasicAzureFileOperations()
        {
            // Get Storage Account Key from Key Vault
            string saKey = EncryptionHelper.GetSAKey();

            // Retrieve storage account information from connection string
            CloudStorageAccount storageAccount = CreateStorageAccountFromConnectionString(string.Format(storageConnectionString, saKey));

            // Create a file client for interacting with the file service.
            CloudFileClient fileClient = storageAccount.CreateCloudFileClient();

            // Get the storage file share reference based on storage account
            CloudFileShare fileShare = fileClient.GetShareReference(storageFileShareName);

            // Check whether the File Share exist or not. By default, is should be created by TM team. And now, the focalpoint is: Spoelhof, Nathan (ND) <*****@*****.**>
            // who create the storage manually (blob, file, table & queue)
            // Default size of file share is 1GB and configued in web.config
            if (!fileShare.Exists())
            {
                fileShare.Properties.Quota = storageFileShareSize;
                fileShare.CreateIfNotExists();
            }

            // Get a reference to the root directory of the share.
            CloudFileDirectory root = fileShare.GetRootDirectoryReference();

            return(root);
        }
Esempio n. 11
0
        public void ValidateShareCreateableWithSasToken(CloudFileShare share, string sastoken)
        {
            Test.Info("Verify share create permission");
            string fileName   = Utility.GenNameString("file");
            string dirName    = Utility.GenNameString("dir");
            int    fileLength = 10;

            CloudStorageAccount sasAccount = TestBase.GetStorageAccountWithSasToken(share.ServiceClient.Credentials.AccountName, sastoken);
            CloudFileShare      sasShare   = sasAccount.CreateCloudFileClient().GetShareReference(share.Name);

            if (!share.Exists())
            {
                sasShare.Create();
                Test.Assert(sasShare.Exists(), "The share should  exist after Creating with sas token");
            }
            CloudFileDirectory dir    = share.GetRootDirectoryReference().GetDirectoryReference(dirName);
            CloudFileDirectory sasDir = sasShare.GetRootDirectoryReference().GetDirectoryReference(dirName);

            sasDir.Create();
            Test.Assert(dir.Exists(), "The directory should  exist after Creating with sas token");
            CloudFile file    = dir.GetFileReference(fileName);
            CloudFile sasFile = sasDir.GetFileReference(fileName);

            sasFile.Create(fileLength);
            Test.Assert(file.Exists(), "The file should  exist after Creating with sas token");
            TestBase.ExpectEqual(fileLength, file.Properties.Length, "File Lenth should match.");
        }
 private void CreatePPDMModel(DataModelParameters dmParameters, ConnectParameters connector)
 {
     try
     {
         CloudStorageAccount account    = CloudStorageAccount.Parse(connectionString);
         CloudFileClient     fileClient = account.CreateCloudFileClient();
         CloudFileShare      share      = fileClient.GetShareReference(dmParameters.FileShare);
         if (share.Exists())
         {
             CloudFileDirectory rootDir = share.GetRootDirectoryReference();
             CloudFile          file    = rootDir.GetFileReference(dmParameters.FileName);
             if (file.Exists())
             {
                 string      sql    = file.DownloadTextAsync().Result;
                 DbUtilities dbConn = new DbUtilities();
                 dbConn.OpenConnection(connector);
                 dbConn.SQLExecute(sql);
                 dbConn.CloseConnection();
             }
         }
     }
     catch (Exception ex)
     {
         Exception error = new Exception("Create PPDM Model Error: ", ex);
         throw error;
     }
 }
Esempio n. 13
0
        public async Task JokeIntent(IDialogContext context, LuisResult result)
        {
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
                Microsoft.Azure.CloudConfigurationManager.GetSetting("cosmostorageaccount_AzureStorageConnectionString"));
            CloudFileClient fileClient = storageAccount.CreateCloudFileClient();
            CloudFileShare  share      = fileClient.GetShareReference("files");

            if (share.Exists())
            {
                CloudFileDirectory rootDir   = share.GetRootDirectoryReference();
                CloudFileDirectory sampleDir = rootDir.GetDirectoryReference("AstroFiles");
                if (sampleDir.Exists())
                {
                    CloudFile sourceFile = sampleDir.GetFileReference("Joke.txt");

                    if (sourceFile.Exists())
                    {
                        if (countjoke == 0)
                        {
                            await context.PostAsync("I've got one for you: ");
                        }
                        countjoke++;
                        var    lines      = string.Format(sourceFile.DownloadText());
                        Random number     = new Random();
                        int    num        = number.Next(1, 64);
                        var    linesArray = lines.Split('.');
                        await context.PostAsync($"{linesArray[num]}");
                    }
                }
            }
        }
Esempio n. 14
0
        public static void UploadtoFileShare(string shareReference, byte[] fileStream, string fileName)
        {
            // Parse the connection string and return a reference to the storage account.
            CloudStorageAccount storageAccount = Helper.storageAccount;



            // Create a reference to the file client.
            CloudFileClient fileClient = storageAccount.CreateCloudFileClient();



            CloudFileShare share = fileClient.GetShareReference(shareReference);

            share.CreateIfNotExists();

            if (share.Exists())
            {
                CloudFileDirectory rootDir = share.GetRootDirectoryReference();
                //Create a reference to the filename that you will be uploading
                CloudFile cloudFile = rootDir.GetFileReference(fileName);


                FileStream fStream = File.OpenRead("C:\\myprojs\\images\\krishna.jpg");



                cloudFile.UploadFromByteArray(fileStream, 0, fileStream.Length);
                Console.WriteLine($"File uploaded successfully   {fileName}");
            }
        }
Esempio n. 15
0
        public async Task FactIntent(IDialogContext context, IAwaitable <IMessageActivity> activity, LuisResult result)
        {
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
                Microsoft.Azure.CloudConfigurationManager.GetSetting("cosmostorageaccount_AzureStorageConnectionString"));
            CloudFileClient fileClient = storageAccount.CreateCloudFileClient();
            CloudFileShare  share      = fileClient.GetShareReference("files");

            if (share.Exists())
            {
                CloudFileDirectory rootDir   = share.GetRootDirectoryReference();
                CloudFileDirectory sampleDir = rootDir.GetDirectoryReference("AstroFiles");
                if (sampleDir.Exists())
                {
                    CloudFile sourceFile = sampleDir.GetFileReference("Facts.txt");

                    if (sourceFile.Exists())
                    {
                        if (countfact == 0)
                        {
                            await context.PostAsync("Here's something interesting:");
                        }
                        countfact++;
                        var    lines      = string.Format(sourceFile.DownloadText());
                        var    linesArray = lines.Split('.');
                        Random number     = new Random();
                        int    num        = number.Next(1, 57);
                        await context.PostAsync($"{linesArray[num]}");
                    }
                }
            }
        }
Esempio n. 16
0
        public static BackendInfo GetCurrentProductBackendInfo()
        {
            CloudFileClient fileClient = storageAccount.CreateCloudFileClient();
            CloudFileShare  share      = fileClient.GetShareReference(BACKEND_INFO_SHARED_REFERENCE_NAME);

            if (share.Exists())
            {
                // Get a reference to the root directory for the share.
                CloudFileDirectory rootDir = share.GetRootDirectoryReference();

                CloudFile sourceFile = rootDir.GetFileReference(BACKEND_INFO_FILE_NAME);

                if (sourceFile.Exists())
                {
                    List <BackendInfo> products;
                    using (var stream = sourceFile.OpenRead())
                    {
                        using (StreamReader reader = new StreamReader(stream))
                        {
                            var str = reader.ReadToEnd();
                            products = JsonConvert.DeserializeObject <List <BackendInfo> >(str);
                        }
                    }
                    if (products != null)
                    {
                        var current = products.Where(p => p.CurrentOnProd == true).FirstOrDefault();
                        return(current);
                    }
                }
            }
            return(null);
        }
Esempio n. 17
0
        public static bool UploadPaasDBUpgradeFileToAzureFile(string buildnumber, string sourcePath, string fileName = "Microsoft.SqlServer.IntegrationServices.PaasDBUpgrade.dll")
        {
            CloudFileClient fileClient = storageAccount.CreateCloudFileClient();

            CloudFileShare share = fileClient.GetShareReference(DBFile_SHARED_REFERENCE_NAME);

            if (share.Exists())
            {
                // Get a reference to the root directory for the share.
                CloudFileDirectory rootDir = share.GetRootDirectoryReference();

                // Get a reference to the directory we created previously.
                CloudFileDirectory sampleDir = rootDir.GetDirectoryReference(DBFile_DIRECTORY_NAME + "\\" + buildnumber);

                // Create the file directory
                sampleDir.CreateIfNotExists();

                // Create file reference
                CloudFile destFile = sampleDir.GetFileReference(fileName);

                // Upload File
                destFile.UploadFromFile(sourcePath + fileName, System.IO.FileMode.Open);

                return(true);
            }
            return(false);
        }
Esempio n. 18
0
        private static void TransferFileToAzure(MemoryStream stream, string file, Agent agent)
        {
            string shortFileName = file.Substring(file.LastIndexOf('/') + 1);
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(_azureFileConnectionString);
            CloudFileClient     fileClient     = storageAccount.CreateCloudFileClient();
            CloudFileShare      fileShare      = fileClient.GetShareReference(_shareName);

            if (!fileShare.Exists())
            {
                _log.Error("Azure file share does not exist as expected.  Connection string: {0}", _azureFileConnectionString);
            }
            else
            {
                try
                {
                    CloudFileDirectory fileDirectoryRoot  = fileShare.GetRootDirectoryReference();
                    CloudFileDirectory fileAgentDirectory = fileDirectoryRoot.GetDirectoryReference(agent.Queue.ToString());
                    fileAgentDirectory.CreateIfNotExists();
                    CloudFile cloudFile = fileAgentDirectory.GetFileReference(shortFileName);
                    stream.Seek(0, SeekOrigin.Begin);
                    cloudFile.UploadFromStream(stream);
                    stream.Seek(0, SeekOrigin.Begin);
                    int recordCount = TotalLines(stream);

                    LogFile(agent.Id, file, cloudFile.StorageUri.PrimaryUri.ToString(), FileStatusEnum.UPLOADED, recordCount);
                    _log.Info("Successfully transfered file {0} to {1} by agent ID: {2}", shortFileName, cloudFile.StorageUri.PrimaryUri.ToString(), agent.Id.ToString());
                }
                catch (Exception ex)
                {
                    _log.Error(ex, "Unexpected error in TransferFileToAzure for file: {0} on site: ", agent.Url);
                    LogFile(agent.Id, file, "", FileStatusEnum.ERROR_UPLOADED, 0);
                }
            }
        }
Esempio n. 19
0
        /// <summary>
        /// Method to Copy file to Azure File share
        /// </summary>
        /// <param name="finputstream">source file inputstream</param>
        /// <param name="filename">source filename</param>
        private void CopyToFileShare(Stream finputstream, string filename)
        {
            try
            {
                CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
                    CloudConfigurationManager.GetSetting("StorageConnectionString"));

                // Create a CloudFileClient object for credentialed access to Azure Files.
                CloudFileClient fileClient = storageAccount.CreateCloudFileClient();

                // Get a reference to the file share .
                CloudFileShare share = fileClient.GetShareReference(CloudConfigurationManager.GetSetting("ShareDirectoryName"));

                // Ensure that the share exists.
                if (share.Exists())
                {
                    // Get a reference to the root directory for the share.
                    CloudFileDirectory rootDir = share.GetRootDirectoryReference();
                    // Get a reference to the destination file.
                    CloudFile destFile = rootDir.GetFileReference(filename);
                    // Start the copy operation.
                    destFile.UploadFromStream(finputstream);
                    finputstream.Dispose();
                }
            }
            catch (Exception ex)
            {
                Write(string.Format("message: {0} stacktrace: {1}", ex.Message, ex.StackTrace));
            }
        }
Esempio n. 20
0
        public void AzureFile_Crud()
        {
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
                CloudConfigurationManager.GetSetting("StorageConnectionString"));

            Assert.NotNull(storageAccount);
            // Create a CloudFileClient object for credentialed access to Azure Files.
            CloudFileClient fileClient = storageAccount.CreateCloudFileClient();

            // Get a reference to the file share we created previously.
            CloudFileShare share = fileClient.GetShareReference("bma");

            // Ensure that the share exists.
            if (share.Exists())
            {
                // Get a reference to the root directory for the share.
                CloudFileDirectory rootDir = share.GetRootDirectoryReference();

                // Get a reference to the directory we created previously.
                CloudFileDirectory sampleDir = rootDir.GetDirectoryReference("bma");

                // Ensure that the directory exists.
                if (sampleDir.Exists())
                {
                    // Get a reference to the file we created previously.
                    CloudFile file = sampleDir.GetFileReference("function.json");
                    Assert.AreEqual(true, file.Exists());
                    file.
                }
            }
        }
Esempio n. 21
0
        public async Task <List <FileContent> > GetCloudContent()
        {
            List <FileContent> lstFileContent = new List <FileContent>();

            if (_cloudFileShare == null)
            {
                throw new NullReferenceException(nameof(_cloudFileShare));
            }

            if (_cloudFileShare.Exists())
            {
                CloudFileDirectory cloudRootDirectory = _cloudFileShare.GetRootDirectoryReference();
                if (cloudRootDirectory.Exists())
                {
                    var lstFilesAndDirectories = cloudRootDirectory.ListFilesAndDirectories();
                    foreach (var file in lstFilesAndDirectories)
                    {
                        if (file is CloudFile)
                        {
                            CloudFile cloudFile   = file as CloudFile;
                            var       fileContent = await ParseFileContent(cloudFile);

                            lstFileContent.Add(fileContent);
                            MoveFileToProcessedFolder(cloudFile);
                        }
                    }
                }
            }
            return(lstFileContent);
        }
Esempio n. 22
0
        static void CreateShareFile()
        {
            try
            {
                #region Creating the Shared Files in Azure

                _storageAccount = CloudStorageAccount.Parse(
                    CloudConfigurationManager.GetSetting("StorageConnection"));

                _share = _storageAccount.CreateCloudFileClient().GetShareReference("documentos");

                if (_share.Exists())
                {
                    //Console.Clear();
                    // Check current usage stats for the share.
                    // Note that the ShareStats object is part of the protocol layer for the File service.
                    ShareStats stats = _share.GetStats();
                    //Console.WriteLine("Current share usage: {0} GB", stats.Usage.ToString());

                    // Specify the maximum size of the share, in GB.
                    // This line sets the quota to be 10 GB greater than the current usage of the share.
                    _share.Properties.Quota = 10 + stats.Usage;
                    _share.SetProperties();

                    // Now check the quota for the share. Call FetchAttributes() to populate the share's properties.
                    _share.FetchAttributes();
                    //Console.WriteLine("Current share quota: {0} GB", _share.Properties.Quota);

                    // Create a new shared access policy and define its constraints.
                    SharedAccessFilePolicy sharedPolicy = new SharedAccessFilePolicy()
                    {
                        SharedAccessExpiryTime = DateTime.UtcNow.AddHours(24),
                        Permissions            = SharedAccessFilePermissions.Read | SharedAccessFilePermissions.Write
                    };

                    // Get existing permissions for the share.
                    FileSharePermissions permissions = _share.GetPermissions();

                    if (!permissions.SharedAccessPolicies.ContainsKey("sampleSharePolicy"))
                    {
                        // Add the shared access policy to the share's policies. Note that each policy must have a unique name.
                        permissions.SharedAccessPolicies.Add("sampleSharePolicy", sharedPolicy);
                        _share.SetPermissions(permissions);
                    }

                    //Console.ReadKey();
                }
                else
                {
                    _share.CreateIfNotExists();
                }

                #endregion
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                Console.ReadKey();
            }
        }
        public void DownloadFileToLocalPath(string fileShareName, string localPath, FileMode mode, string fileName = "")
        {
            CloudFileClient fileClient = new CloudFileClient(fileURI, creds);
            // Create a CloudFileClient object for credentialed access to Azure Files.


            // Get a reference to the file share we created previously.
            CloudFileShare share = fileClient.GetShareReference(fileShareName);

            // Ensure that the share exists.
            if (share.Exists())
            {
                try
                {
                    // Get a reference to the root directory for the share.
                    CloudFileDirectory rootDir   = share.GetRootDirectoryReference();
                    CloudFile          cloudFile = rootDir.GetFileReference(fileName);
                    switch (mode)
                    {
                    case FileMode.Append:
                        cloudFile.DownloadToFile(localPath, FileMode.Append);
                        break;

                    case FileMode.Create:
                        cloudFile.DownloadToFile(localPath, FileMode.Create);
                        break;

                    case FileMode.CreateNew:
                        cloudFile.DownloadToFile(localPath, FileMode.CreateNew);
                        break;

                    case FileMode.Open:
                        cloudFile.DownloadToFile(localPath, FileMode.Open);
                        break;

                    case FileMode.OpenOrCreate:
                        cloudFile.DownloadToFile(localPath, FileMode.OpenOrCreate);
                        break;

                    case FileMode.Truncate:
                        cloudFile.DownloadToFile(localPath, FileMode.Truncate);
                        break;

                    default:
                        break;
                    }
                }
                catch (Exception e)
                {
                    throw new StorageAccountException("Error while attempting to get contents", e);
                }
            }
            else
            {
                DirectoryNotFoundException e = new DirectoryNotFoundException(string.Format("The file share '{0}' does not exist.", fileShareName));
                throw new StorageAccountException("Error while attempting to get content", e);
            }
        }
Esempio n. 24
0
        public string GetFileFromFileStorage()
        {
            try
            {
                string returnString = "No data retreived.";
                string accountName  = "storagemartin";
                string accountKey   = ConfigurationManager.AppSettings["BlobPassword"];

                StorageCredentials  creds          = new StorageCredentials(accountName, accountKey);
                CloudStorageAccount storageAccount = new CloudStorageAccount(creds, useHttps: true);

                // Create a CloudFileClient object for credentialed access to Azure Files.
                CloudFileClient fileClient = storageAccount.CreateCloudFileClient();

                // Get a reference to the file share we created previously.
                CloudFileShare share = fileClient.GetShareReference("tipslogs");

                // Ensure that the share exists.
                if (share.Exists())
                {
                    // Get a reference to the root directory for the share.
                    CloudFileDirectory rootDir = share.GetRootDirectoryReference();

                    // Get a reference to the directory we created previously.
                    CloudFileDirectory sampleDir = rootDir.GetDirectoryReference("thetipslogs");

                    // Ensure that the directory exists.
                    if (sampleDir.Exists())
                    {
                        // Get a reference to the file we created previously.
                        CloudFile file = sampleDir.GetFileReference("tipslogError.txt");

                        // Ensure that the file exists.
                        if (file.Exists())
                        {
                            // Write the contents of the file to the console window.
                            returnString = file.DownloadTextAsync().Result;

                            returnString = MakeHtmlFriendlyText(returnString);
                            return(returnString);
                        }
                    }
                }

                return(returnString);
            }
            catch (Exception e)
            {
                string inner = e.InnerException != null?e.InnerException.ToString() : "NULL";

                return(string.Format("Error in method GetFileFromFileStorage. Exception: {0}. Inner: {1}", e.Message.ToString(), inner));
            }
        }
Esempio n. 25
0
        public void ValidateShareCreatableWithSasToken(string shareName, string accountName, string sastoken)
        {
            Test.Info("Verify share create permission");
            CloudStorageAccount sasAccount = TestBase.GetStorageAccountWithSasToken(accountName, sastoken);

            //make sure the share not exist before create
            CloudFileShare sasShareReference = client.GetShareReference(shareName);

            if (sasShareReference.Exists())
            {
                sasShareReference.Delete();
                Thread.Sleep(2 * 60 * 1000); // Sleep 2 minutes to make sure the share can be created successfully
            }

            //Create Share with SAS
            CloudFileShare sasShare = sasAccount.CreateCloudFileClient().GetShareReference(shareName);

            sasShare.Create();

            //Verify and delete share
            Test.Assert(sasShareReference.Exists(), "The Share {0} should exist.", shareName);
            sasShareReference.Delete();
        }
    private static async Task CopyBlobToAzureFiles(CloudBlockBlob sourceBlob, string targetConnectionString, string fileShareName, string fileShareFolderName, string targetFileName, TraceWriter log)
    {
        // Reference: https://github.com/Azure-Samples/storage-file-dotnet-getting-started/blob/master/FileStorage/GettingStarted.cs
        CloudStorageAccount storageAccount = CloudStorageAccount.Parse(targetConnectionString);
        CloudFileClient     fileClient     = storageAccount.CreateCloudFileClient();
        CloudFileShare      share          = fileClient.GetShareReference(fileShareName);

        if (!share.Exists())
        {
            log.Info($"Creating file share since it does not exist: {fileShareName}");
            await share.CreateAsync();
        }

        CloudFileDirectory rootDir   = share.GetRootDirectoryReference();
        CloudFileDirectory targetDir = rootDir.GetDirectoryReference(fileShareFolderName);
        await targetDir.CreateIfNotExistsAsync();

        string[] sourceFolders = sourceBlob.Name.Split('/');
        if (sourceFolders.Length > 1)
        {
            for (int i = 0; i < sourceFolders.Length - 1; i++)
            {
                var subfolderName = sourceFolders[i];
                log.Info($"Creating subfolder: {subfolderName}");
                targetDir = targetDir.GetDirectoryReference(subfolderName);
                await targetDir.CreateIfNotExistsAsync();
            }

            targetFileName = sourceFolders[sourceFolders.Length - 1];
        }

        CloudFile file    = targetDir.GetFileReference(targetFileName);
        string    blobSas = sourceBlob.GetSharedAccessSignature(new SharedAccessBlobPolicy()
        {
            Permissions            = SharedAccessBlobPermissions.Read,
            SharedAccessExpiryTime = DateTime.UtcNow.AddHours(SAS_EXPIRATION_IN_HOURS)
        });

        var blobSasUri = new Uri($"{sourceBlob.StorageUri.PrimaryUri}{blobSas}");

        log.Info($"Source blob SAS URL (expires in {SAS_EXPIRATION_IN_HOURS} hours): {blobSasUri}");
        log.Info($"Copying source blob to target file share: {file.Uri.AbsoluteUri}");
        Stopwatch sw = new Stopwatch();

        sw.Start();
        await file.StartCopyAsync(blobSasUri);

        sw.Stop();
        log.Info($"Successfully copied (in {sw.ElapsedMilliseconds} msecs) source blob to target file share: {file.Uri.AbsoluteUri}");
    }
Esempio n. 27
0
        private void WriteLogLine(WriteWay writeWay, string writeLogLine, params string[] logFilePath)
        {
            if (logFilePath.Length < 2)
            {
                Console.WriteLine(invalidExistLogFilePath);
                return;
            }

            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
                string.Format(@"DefaultEndpointsProtocol=https;AccountName={0};
                AccountKey={1};EndpointSuffix=core.windows.net",
                              Constant.LOGGER_ACCOUNT_NAME, Constant.Instance.StorageAccountKey));
            CloudFileClient fileClient = storageAccount.CreateCloudFileClient();

            CloudFileShare share = fileClient.GetShareReference(logFilePath[0]);

            if (!share.Exists())
            {
                share.Create();
            }
            CloudFileDirectory sampleDir = share.GetRootDirectoryReference();

            for (int i = 1; i < logFilePath.Length - 1; i++)
            {
                CloudFileDirectory nextLevelDir = sampleDir.GetDirectoryReference("TestLogs");
                if (!sampleDir.Exists())
                {
                    sampleDir.Create();
                }
                sampleDir = nextLevelDir;
            }

            CloudFile file = sampleDir.GetFileReference(logFilePath[logFilePath.Length - 1]);

            string writenLineContent = "";

            if (file.Exists())
            {
                if (writeWay == WriteWay.Cover)
                {
                }
                else if (writeWay == WriteWay.Append)
                {
                    writenLineContent = file.DownloadTextAsync().Result;
                }
            }
            file.UploadText(writenLineContent + writeLogLine + "\n");
        }
        public static CloudFileDirectory getAssetDir(CloudStorageAccount _storageAccount, String UserName, String assetType)
        {
            CloudFileClient fileClient = _storageAccount.CreateCloudFileClient();
            CloudFileShare  share      = fileClient.GetShareReference("techmervisionuserimages");

            if (!share.Exists())
            {
                throw new Exception("User Image Share Unavailable.");
            }

            CloudFileDirectory rootDir  = share.GetRootDirectoryReference();
            CloudFileDirectory userDir  = getDirByName(rootDir, UserName);
            CloudFileDirectory assetDir = getDirByName(userDir, assetType);

            return(assetDir);
        }
Esempio n. 29
0
        private CloudFileDirectory GetRootDirectory()
        {
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(options.ConnectionString);

            CloudFileClient fileClient = storageAccount.CreateCloudFileClient();
            CloudFileShare  share      = fileClient.GetShareReference("entries");

            if (!share.Exists())
            {
                throw Ensure.Exception.InvalidOperation("Missing file share.");
            }

            CloudFileDirectory rootDir = share.GetRootDirectoryReference();

            return(rootDir);
        }
Esempio n. 30
0
        static void Main(string[] args)
        {
            string accountname = "xxx";
            string accountkey  = "xxxxxxx";
            CloudStorageAccount storageAccount = new CloudStorageAccount(new StorageCredentials(accountname, accountkey), true);

            // Create a CloudFileClient object for credentialed access to Azure Files.
            CloudFileClient fileClient = storageAccount.CreateCloudFileClient();

            // Get a reference to the file share.
            CloudFileShare share = fileClient.GetShareReference("s66");

            //if fileshare does not exist, create it.
            share.CreateIfNotExists();

            if (share.Exists())
            {
                // Get a reference to the root directory for the share.
                CloudFileDirectory rootDir = share.GetRootDirectoryReference();

                // Get a reference to the directory.
                CloudFileDirectory sampleDir = rootDir.GetDirectoryReference("CustomLogs");
                //if the directory does not exist, create it.
                sampleDir.CreateIfNotExists();

                if (sampleDir.Exists())
                {
                    // Get a reference to the file.
                    CloudFile file = sampleDir.GetFileReference("Log1.txt");

                    // if the file exists, read the content of the file.
                    if (file.Exists())
                    {
                        // Write the contents of the file to the console window.
                        Console.WriteLine(file.DownloadTextAsync().Result);
                    }
                    //if the file does not exist, create it with size == 500bytes
                    else
                    {
                        file.Create(500);
                    }
                }
            }

            Console.WriteLine("--file share test--");
            Console.ReadLine();
        }