static void CopyFile(string strSourceFolderPath, string strSourceFileName, string strTargetFolderPath)
        {
            log.Info("Executing Copy File");
            log.Info("Folder " + strSourceFolderPath);
            log.Info("File : " + strSourceFileName);
            log.Info("Target : " + strTargetFolderPath);

            //Copy File method.
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(storageConnectionStr);
            CloudFileClient     fileClient     = storageAccount.CreateCloudFileClient();
            CloudFileShare      share          = fileClient.GetShareReference(fileshare);
            CloudFileDirectory  rootDir        = share.GetRootDirectoryReference();
            CloudFile           sourceFile;

            if (strSourceFolderPath != "")
            {
                CloudFileDirectory sourcefolder = rootDir.GetDirectoryReference(strSourceFolderPath);
                sourceFile = sourcefolder.GetFileReference(strSourceFileName);
            }
            else
            {
                sourceFile = rootDir.GetFileReference(strSourceFileName);
            }


            CloudFileDirectory targetfolder = rootDir.GetDirectoryReference(strTargetFolderPath);
            CloudFile          destFile     = targetfolder.GetFileReference(strSourceFileName);

            log.Info("Source File : " + sourceFile.Name);
            log.Info("Target File : " + targetfolder.Name);
            destFile.StartCopyAsync(sourceFile);
            log.Info(sourceFile.Name + " copied to " + targetfolder.Name);
        }
Esempio n. 2
0
 public static CloudFileDirectory GetDirectoryReference(CloudFileDirectory parent, string path)
 {
     if (path.Contains(@"\"))
     {
         var paths = path.Split('\\');
         return(GetDirectoryReference(parent.GetDirectoryReference(paths.First()), string.Join(@"\", paths.Skip(1))));
     }
     else
     {
         return(parent.GetDirectoryReference(path));
     }
 }
Esempio n. 3
0
 /// <inheritdoc />
 public override bool CreateDirectory(string path)
 {
   var share = m_rootDir.GetDirectoryReference(path);
   if (!share.Exists())
   {
     m_rootDir = m_cloudShare.GetRootDirectoryReference();
     m_databaseDir = m_rootDir.GetDirectoryReference(path);
     m_databaseDir.CreateIfNotExists();
     return true;
   }
   return false;
 }
Esempio n. 4
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. 5
0
            private async static void UploadFolderAsync(string path, CloudFileDirectory sampleAppsFolder)
            {
                string[] files;
                string[] directories;

                files = Directory.GetFiles(path);
                foreach (string file in files)
                {
                    //Create a reference to the filename that you will be uploading
                    CloudFile cloudFile = sampleAppsFolder.GetFileReference(new FileInfo(file).Name);

                    using (Stream fileStream = File.OpenRead(file))
                    {
                        await cloudFile.UploadFromStreamAsync(fileStream);
                    }
                }

                directories = Directory.GetDirectories(path);
                foreach (string directory in directories)
                {
                    var subFolder = sampleAppsFolder.GetDirectoryReference(new DirectoryInfo(directory).Name);
                    await subFolder.CreateIfNotExistsAsync();

                    UploadFolderAsync(directory, subFolder);
                }
            }
        private static IStorageContainer CreateCloudFileContainer(this Uri uri, IStorageConfig storageConfig = null)
        {
            IStorageContainer   result = null;
            IStorageConfig      scfg   = storageConfig ?? new StorageConfig();
            CloudStorageAccount sa     = scfg.GetStorageAccountByUri(uri);
            CloudFileDirectory  dir    = new CloudFileDirectory(uri, sa.Credentials);
            CloudFileShare      share  = dir.Share;

            share.CreateIfNotExistsAsync().GetAwaiter().GetResult();
            dir = share.GetRootDirectoryReference();

            var directories = uri.Segments.Select(seg => seg.TrimEnd('/')).Where(str => !string.IsNullOrEmpty(str)).ToList();

            directories.RemoveAt(0); // remove the share, and leave only dirs
            var n = 0;

            while (n < directories.Count)
            {
                dir = dir.GetDirectoryReference(directories[n]);
                dir.CreateIfNotExistsAsync().GetAwaiter().GetResult();
                n = n + 1;
            }
            result = new CloudFileItemDirectory(dir, scfg);
            return(result);
        }
Esempio n. 7
0
        private static async Task fileShareDemo()
        {
            var client = account.CreateCloudFileClient();
            var share  = client.GetShareReference("demoshare");
            await share.CreateIfNotExistsAsync();


            CloudFileDirectory rootDir = share.GetRootDirectoryReference();
            CloudFileDirectory appDir  = rootDir.GetDirectoryReference("Application_Logs");
            await appDir.CreateIfNotExistsAsync();

            Console.WriteLine("File Share:\tCreated share and folder");

            CloudFile file = appDir.GetFileReference("log.json");
            await file.UploadTextAsync($"{{'app':'{AppDomain.CurrentDomain.FriendlyName}', 'date':'{DateTime.Now}'");

            Console.WriteLine("File Share:\tUploaded file");


            await share.FetchAttributesAsync();

            share.Properties.Quota = 24;
            await share.SetPropertiesAsync();

            Console.WriteLine("File Share:\tSet quota");
        }
        public static CloudFileDirectory getDirByName(CloudFileDirectory parentDir, string dirName)
        {
            CloudFileDirectory userDir = parentDir.GetDirectoryReference(dirName);

            userDir.CreateIfNotExists();
            return(userDir);
        }
Esempio n. 9
0
        public static async Task <bool> UploadFilesToTableStorage(string valFileName)
        {
            bool         vResult       = false;
            const string DemoShare     = "demofileshare";
            const string DemoDirectory = "demofiledirectory";

            try {
                CloudStorageAccount vStorageAccount = CreateStorageAccountFromConnectionString(Constants.vStorageConnectionString);

                CloudFileClient fileClient = vStorageAccount.CreateCloudFileClient();
                Console.WriteLine("1. Creating file share");
                CloudFileShare     share = fileClient.GetShareReference(DemoShare);
                CloudFileDirectory root  = share.GetRootDirectoryReference();

                CloudFileDirectory dir          = root.GetDirectoryReference(DemoDirectory);
                string[]           FileInfoName = valFileName.Split("\\");
                CloudFile          file         = dir.GetFileReference(FileInfoName.LastOrDefault());

                FileRequestOptions fr = new FileRequestOptions();
                OperationContext   oc = new OperationContext();
                AccessCondition    ac = new AccessCondition();
                //using (FileStream FileUpload = new FileStream(valFileName, FileMode.Open)) {
                await file.UploadFromFileAsync(valFileName);

                //await file.UploadFromStreamAsync(FileUpload, FileUpload.Length);
                //}
                vResult = true;
            } catch (Exception vEx) {
                string message = vEx.Message;
            }
            return(vResult);
            // List all files/directories under the root directory
        }
        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 async Task <FileStorage> SaveAsync(FileStorage entity)
        {
            try
            {
                CloudFileDirectory currentRootDirectory = OpenFileShareConnection();
                CloudFileDirectory currentSubdirectory  = currentRootDirectory.GetDirectoryReference(Guid.NewGuid().ToString());
                await currentSubdirectory.CreateIfNotExistsAsync();

                CloudFile currentCloudSmbFile = currentSubdirectory.GetFileReference(entity.FileName);

                await currentCloudSmbFile.UploadFromStreamAsync(entity.FileData);

                entity.RootPath = currentRootDirectory.Uri.AbsoluteUri.Replace(currentRootDirectory.Uri.LocalPath, "");
                entity.SubPath  = currentSubdirectory.Uri.AbsolutePath.Trim('/');

                _repositoryFileStorage.Save(entity);
            }
            catch (Exception fileStorageError)
            {
                _applicationLogTools.LogError(fileStorageError, new Dictionary <string, dynamic> {
                    { "ClassName", "Infrastructure.FileStorages" }
                });
                throw;
            }

            return(entity);
        }
        public static async Task <List <byte[]> > GetFiles(Guid entityItemId)
        {
            CloudFileDirectory rootDir = share.GetRootDirectoryReference();
            var dir = rootDir.GetDirectoryReference(entityItemId.ToString());

            var fileList = new List <byte[]>();

            FileContinuationToken continuationToken = null;

            try
            {
                if (await dir.ExistsAsync())
                {
                    do
                    {
                        var response = await dir.ListFilesAndDirectoriesSegmentedAsync(continuationToken);

                        continuationToken = response?.ContinuationToken;

                        foreach (var file in response?.Results.OfType <IListFileItem>())
                        {
                            //fileList.Add(file);
                        }
                    } while (continuationToken != null);
                }
            }
            catch (Exception e)
            {
                //Handle Exception
            }

            return(fileList);
        }
        public async Task DownloadFile()
        {
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(AzureStorageAccount);
            CloudFileClient     fileClient     = storageAccount.CreateCloudFileClient();

            FileContinuationToken token = null;
            ShareResultSegment    shareResultSegment = await fileClient.ListSharesSegmentedAsync("Pat", token);

            foreach (CloudFileShare share in shareResultSegment.Results)
            {
                CloudFileDirectory rootDir   = share.GetRootDirectoryReference();
                CloudFileDirectory sampleDir = rootDir.GetDirectoryReference(DateTime.Now.ToString("yyyyMMdd"));
                if (await sampleDir.ExistsAsync())
                {
                    do
                    {
                        FileResultSegment resultSegment = await sampleDir.ListFilesAndDirectoriesSegmentedAsync(token);

                        token = resultSegment.ContinuationToken;

                        List <IListFileItem> listedFileItems = new List <IListFileItem>();

                        foreach (IListFileItem listResultItem in resultSegment.Results)
                        {
                            var cloudFile = sampleDir.GetFileReference(listResultItem.Uri.ToString());
                            Console.WriteLine(cloudFile.Uri.ToString());
                            //await cloudFile.DownloadToFileAsync(cloudFile.Uri.ToString(), FileMode.Create);
                        }
                    }while (token != null);
                }
            }
        }
Esempio n. 14
0
        private Stream GetResourceXMLFromCloudShare(Dictionary <string, string> config, string fileNameInCloud)
        {
            var cred           = new StorageCredentials(config["STORAGE_NAME"], config["STORAGE_KEY"]);
            var storageAccount = new CloudStorageAccount(cred, true);

            CloudFileClient fileClient = storageAccount.CreateCloudFileClient();
            CloudFileShare  share      = fileClient.GetShareReference(config["STORAGE_SHARE_REFERENCE"]);

            share.CreateIfNotExists();

            CloudFileDirectory root = share.GetRootDirectoryReference();
            CloudFileDirectory dir  = root.GetDirectoryReference(config["STORAGE_RESOURCES_DIRECTORY_REFERENCE"]);

            var cloudFile = dir.GetFileReference(fileNameInCloud);

            var ms = new MemoryStream();

            cloudFile.DownloadToStream(ms);

            ms.Position = 0;

            ZipArchive archive = new ZipArchive(ms);
            var        xml     = archive.Entries.Last().Open();

            return(xml);
        }
Esempio n. 15
0
        void saveAzureFile(byte[] file, string filePath, CloudStorageAccount storageAccount)
        {
            string[] pathParts = filePath.Split('/');

            CloudFileClient fileClient = storageAccount.CreateCloudFileClient();

            CloudFileShare share = fileClient.GetShareReference(azureEnvirionmentInfo.AzureContainer);

            share.CreateIfNotExistsAsync().Wait();



            CloudFileDirectory cloudFileDirectory = share.GetRootDirectoryReference();

            for (int i = 0; i < pathParts.Length - 1; i++)
            {
                CloudFileDirectory nextFolder = cloudFileDirectory.GetDirectoryReference(pathParts[i]);
                nextFolder.CreateIfNotExistsAsync().Wait();
                cloudFileDirectory = nextFolder;
            }

            //Create a reference to the filename that you will be uploading
            CloudFile cloudFile = cloudFileDirectory.GetFileReference(pathParts[pathParts.Length - 1]);

            //Upload the file to Azure.
            cloudFile.UploadFromByteArrayAsync(file, 0, file.Length, null, null, null).Wait();
        }
        public static async void FileTransferAsync(string azurename, string requestBody, Account account)
        {
            string acctName         = System.Environment.GetEnvironmentVariable("AcctName", EnvironmentVariableTarget.Process);
            string acctKey          = System.Environment.GetEnvironmentVariable("AcctKey", EnvironmentVariableTarget.Process);
            string container        = System.Environment.GetEnvironmentVariable("Container", EnvironmentVariableTarget.Process);
            string directory        = System.Environment.GetEnvironmentVariable("Directory", EnvironmentVariableTarget.Process);
            string connectionString = $"DefaultEndpointsProtocol=https;AccountName={acctName};AccountKey={acctKey}";

            try
            {
                CloudStorageAccount cloudStorageAccount = CloudStorageAccount.Parse(connectionString);
                CloudFileClient     cloudFileClient     = cloudStorageAccount.CreateCloudFileClient();
                CloudFileShare      cloudFileShare      = cloudFileClient.GetShareReference(container);
                Boolean             done = await cloudFileShare.CreateIfNotExistsAsync();

                CloudFileDirectory rootDir  = cloudFileShare.GetRootDirectoryReference();
                CloudFileDirectory azureDir = rootDir.GetDirectoryReference(directory);
                await azureDir.CreateIfNotExistsAsync();

                CloudFile cloudFile = azureDir.GetFileReference(azurename);
                await cloudFile.UploadTextAsync(requestBody);
            }
            catch (Exception e)
            {
                account.fatalException = e.Message;
            }
        }
        public async Task <bool> DeleteAsync(FileStorage entity)
        {
            try
            {
                FileStorage currentWorkingObject = _repositoryFileStorage.Get(entity.Id);

                CloudFileDirectory currentRootDirectory = OpenFileShareConnection();
                CloudFileDirectory currentSubdirectory  = currentRootDirectory.GetDirectoryReference(currentWorkingObject.SubPath.Replace(_configurationManager.GetValue("CloudStorageShareName") + "/", ""));

                CloudFile currentCloudSmbFile = currentSubdirectory.GetFileReference(currentWorkingObject.FileName);

                await currentCloudSmbFile.DeleteAsync();

                await currentSubdirectory.DeleteAsync();

                _repositoryFileStorage.Delete(currentWorkingObject);
            }
            catch (Exception fileStorageError)
            {
                _applicationLogTools.LogError(fileStorageError, new Dictionary <string, dynamic> {
                    { "ClassName", "Infrastructure.FileStorages" }
                });
                return(false);
            }

            return(true);
        }
Esempio n. 18
0
        private CloudFileDirectory ConnectToDirectory(CloudFileShare share, string dir)
        {
            CloudFileDirectory rootDirectory  = share.GetRootDirectoryReference();
            CloudFileDirectory epubsDirectory = rootDirectory.GetDirectoryReference(dir);

            return(!epubsDirectory.Exists() ? null : epubsDirectory);
        }
        public async Task <FileStorage> GetAsync(long id, CancellationToken cancellationToken)
        {
            try
            {
                FileStorage currentWorkingObject = _repositoryFileStorage.Get(id);

                CloudFileDirectory currentRootDirectory = OpenFileShareConnection();
                CloudFileDirectory currentSubdirectory  = currentRootDirectory.GetDirectoryReference(currentWorkingObject.SubPath.Replace(_configurationManager.GetValue("CloudStorageShareName") + "/", ""));
                CloudFile          currentCloudSmbFile  = currentSubdirectory.GetFileReference(currentWorkingObject.FileName);

                StreamContent returnFileContent = new StreamContent(await currentCloudSmbFile.OpenReadAsync(cancellationToken));
                returnFileContent.Headers.ContentType   = new MediaTypeHeaderValue(currentWorkingObject.ContentType);
                returnFileContent.Headers.ContentLength = currentCloudSmbFile.Properties.Length;

                currentWorkingObject.FileData = await returnFileContent.ReadAsStreamAsync();

                return(currentWorkingObject);
            }
            catch (Exception fileStorageError)
            {
                _applicationLogTools.LogError(fileStorageError, new Dictionary <string, dynamic> {
                    { "ClassName", "Infrastructure.FileStorages" }
                });
                throw;
            }
        }
        static async Task <bool> FileExists(string strSourceFolderPath, string strSourceFileName)
        {
            log.Info("Checking if the file exists");
            log.Info("Folder " + strSourceFolderPath);
            log.Info("File : " + strSourceFileName);
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(storageConnectionStr);
            CloudFileClient     fileClient     = storageAccount.CreateCloudFileClient();
            CloudFileShare      share          = fileClient.GetShareReference(fileshare);
            CloudFileDirectory  rootDir        = share.GetRootDirectoryReference();
            CloudFile           sourceFile;

            if (strSourceFolderPath != "")
            {
                CloudFileDirectory sourcefolder = rootDir.GetDirectoryReference(strSourceFolderPath);
                sourceFile = sourcefolder.GetFileReference(strSourceFileName);
            }
            else
            {
                sourceFile = rootDir.GetFileReference(strSourceFileName);
            }

            log.Info(sourceFile.Uri.ToString());


            return(await sourceFile.ExistsAsync() ? true : false);
        }
Esempio n. 21
0
        private async Task <CloudFile> GetFileReferenceAsync(string fullPath, bool createParents, CancellationToken cancellationToken)
        {
            string[] parts = StoragePath.Split(fullPath);
            if (parts.Length == 0)
            {
                return(null);
            }

            string shareName = parts[0];

            CloudFileShare share = _client.GetShareReference(shareName);

            if (createParents)
            {
                await share.CreateIfNotExistsAsync(cancellationToken).ConfigureAwait(false);
            }

            CloudFileDirectory dir = share.GetRootDirectoryReference();

            for (int i = 1; i < parts.Length - 1; i++)
            {
                string sub = parts[i];
                dir = dir.GetDirectoryReference(sub);

                if (createParents)
                {
                    await dir.CreateIfNotExistsAsync().ConfigureAwait(false);
                }
            }

            return(dir.GetFileReference(parts[parts.Length - 1]));
        }
Esempio n. 22
0
        // Delete Directory/Folder
        public void DeleteFolderUnderFileShare(string folderName)
        {
            CloudFileDirectory rootDirectory = fileShare.GetRootDirectoryReference();
            CloudFileDirectory subDirectory  = rootDirectory.GetDirectoryReference(folderName);

            subDirectory.DeleteIfExists();
        }
        static void DeleteFile(string strSourceFolderPath, string strSourceFileName)
        {
            log.Info("Executing Delete File");
            log.Info("Folder " + strSourceFolderPath);
            log.Info("File : " + strSourceFileName);

            //Delete File method
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(storageConnectionStr);
            CloudFileClient     fileClient     = storageAccount.CreateCloudFileClient();
            CloudFileShare      share          = fileClient.GetShareReference(fileshare);
            CloudFileDirectory  rootDir        = share.GetRootDirectoryReference();
            CloudFile           sourceFile;

            if (strSourceFolderPath != "")
            {
                CloudFileDirectory sourcefolder = rootDir.GetDirectoryReference(strSourceFolderPath);
                sourceFile = sourcefolder.GetFileReference(strSourceFileName);
            }
            else
            {
                sourceFile = rootDir.GetFileReference(strSourceFileName);
            }
            sourceFile.DeleteIfExistsAsync();
            log.Info(sourceFile.Name + " deleted.");
        }
Esempio n. 24
0
    /// <summary>
    /// Create the references necessary to log into Azure
    /// </summary>
    private async void CreateCloudIdentityAsync()
    {
        // Retrieve storage account information from connection string
        storageAccount = CloudStorageAccount.Parse(storageConnectionString);
        // Create a file client for interacting with the file service.
        fileClient = storageAccount.CreateCloudFileClient();
        // Create a share for organizing files and directories within the storage account.
        share = fileClient.GetShareReference(fileShare);
        await share.CreateIfNotExistsAsync();

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

        // Create a directory under the root directory
        dir = root.GetDirectoryReference(storageDirectory);
        await dir.CreateIfNotExistsAsync();

        //Check if the there is a stored text file containing the list
        shapeIndexCloudFile = dir.GetFileReference("TextShapeFile");
        if (!await shapeIndexCloudFile.ExistsAsync())
        {
            // File not found, enable gaze for shapes creation
            Gaze.instance.enableGaze = true;

            azureStatusText.text = "No Shape\nFile!";
        }
        else
        {              // The file has been found, disable gaze and get the list from the file
            Gaze.instance.enableGaze = false; azureStatusText.text = "Shape File\nFound!";
            await ReplicateListFromAzureAsync();
        }
    }
Esempio n. 25
0
        // Delete Directory/Folder
        public static void DeleteFolderUnderFileShare(string folderName)
        {
            CloudFileDirectory rootDirectory = BasicAzureFileOperations();
            CloudFileDirectory subDirectory  = rootDirectory.GetDirectoryReference(folderName);

            subDirectory.DeleteIfExists();
        }
Esempio n. 26
0
        private CloudFileDirectory CreateDirectory(string fullPath)
        {
            return(Retrier.Retry <CloudFileDirectory>(5, () =>
            {
                var root = this.share.GetRootDirectoryReference();
                var segments = fullPath.Split('\\');
                CloudFileDirectory lastDir = null;
                foreach (var segment in segments)
                {
                    if (lastDir == null)
                    {
                        lastDir = root.GetDirectoryReference(segment);
                    }
                    else
                    {
                        lastDir = lastDir.GetDirectoryReference(segment);
                    }

                    if (!lastDir.ExistsAsync().Result)
                    {
                        lastDir.CreateAsync().Wait();
                    }
                }

                return lastDir;
            }));
        }
Esempio n. 27
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.
                }
            }
        }
        private CloudFile GetCloudFileReference(string path, bool createIfNotExist = false)
        {
            CloudFileDirectory directory = cloudFileClient.GetShareReference(rootDir).GetRootDirectoryReference();
            CloudFile          file      = null;

            string[] folders = GetArrrayOfFolders(path);

            for (int i = 0; i < folders.Length; i++)
            {
                if (i == folders.Length - 1)
                {
                    file = directory.GetFileReference(folders[i]);
                    if (!file.Exists() && createIfNotExist)
                    {
                        file.Create(0L);
                    }
                }
                else
                {
                    directory = directory.GetDirectoryReference(folders[i]);
                    if (!directory.Exists() && createIfNotExist)
                    {
                        directory.Create();
                    }
                }
            }

            return(file);
        }
Esempio n. 29
0
        private static async Task <string> GetDeployLogUrl(string requestId, string cloudName, CloudFileDirectory directory)
        {
            CloudFile deploymentLog;

            var deployLogDirectory = directory.GetDirectoryReference(requestId).GetDirectoryReference("devdeploy");
            var files = deployLogDirectory.ListFilesAndDirectories(string.Format("{0}.", cloudName));

            if (!await deployLogDirectory.ExistsAsync())
            {
                throw new Exception(string.Format("Directory {0} does not exist in storage file share", deployLogDirectory.Name));
            }

            if (!files.Any())
            {
                return(null);
            }

            if (files.Count() == 1)
            {
                deploymentLog = (CloudFile)files.Single();
            }
            else
            {
                throw new Exception(string.Format("Found more than one file/directory with name {0}", cloudName));
            }

            var uri = new Uri(deploymentLog.StorageUri.PrimaryUri.ToString() + deploymentLog.GetSharedAccessSignature(null, "read"));

            return(uri.ToString());
        }
Esempio n. 30
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);
                }
            }
        }