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. 2
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.");
        }
 public void Init()
 {
     _root = _share.GetRootDirectoryReference();
     if (!_root.Exists())
     {
         _root.Create();
     }
 }
Esempio n. 4
0
        public string GetNextIndexedFileName(string fileName, bool createFolder)
        {
            string extension = Path.GetExtension(fileName);
            string result    = "0001" + extension;

            bool fileDirectoryExists = fileDirectory.Exists();

            if (createFolder && !fileDirectoryExists)
            {
                fileDirectory.Create();
                fileDirectoryExists = true;
            }

            if (fileDirectoryExists)
            {
                var directoryFiles = fileDirectory.ListFilesAndDirectories();

                foreach (IListFileItem directoryFile in directoryFiles)
                {
                    string oneFile  = directoryFile.Uri.ToString();
                    string oneFile1 = directoryFile.StorageUri.ToString();
                }

                /*string lastFileName = directoryFiles. .LastOrDefault();
                 *
                 * try
                 * {
                 *  int lastIndex = Convert.ToInt32(Path.GetFileNameWithoutExtension(lastFileName));
                 *
                 *  result = (lastIndex + 1).ToString().PadLeft(4, '0') + extension;
                 * }
                 * catch (Exception ex)
                 * {
                 *  //Do nothing
                 * }
                 *
                 *
                 *
                 *
                 *
                 * // Get a reference to the file we created previously.
                 * CloudFile file = fileDirectory.GetFileReference(fileName);
                 *
                 * // Ensure that the file exists.
                 * if (file.Exists())
                 * {
                 * }*/
            }

            return(result);
        }
        public void CreateDirectory(string name)
        {
            CloudFileDirectory directory = cloudFileClient.GetShareReference(rootDir).GetRootDirectoryReference();

            string[] folders = GetArrrayOfFolders(name);

            foreach (string folder in folders)
            {
                directory = directory.GetDirectoryReference(folder);
                if (!directory.Exists())
                {
                    directory.Create();
                }
            }
        }
Esempio n. 6
0
        internal void CreateDirectoryAndShare(CloudFileDirectory dir)
        {
            var share = dir.Share;

            if (!share.Exists())
            {
                share.Create();
            }

            CreateParentDirectory(dir, share.GetRootDirectoryReference());
            if (!dir.Exists())
            {
                dir.Create();
            }
        }
Esempio n. 7
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");
        }
Esempio n. 8
0
        /*
         * GetAppendBlobReference is removed from Microsoft.WindowsAzure.Storage.Blob.CloudBlobContainer
         * So we cannot release the log function based on the append function from Microsoft.WindowsAzure.Storage.
         * stackoverflow: https://stackoverflow.com/questions/48411359/getappendblobreference-is-removed-from-microsoft-windowsazure-storage-blob-cloud
         */
        public static void MainMethod()
        {
            string accountName = "";
            string accountKey  = "";
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(string.Format(@"DefaultEndpointsProtocol=https;AccountName={0};AccountKey={1}", accountName, accountKey));
            // 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("logs");

            // If the share does not exist, create it.
            if (!share.Exists())
            {
                share.Create();
            }
            // 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("TestLogs");

            if (!sampleDir.Exists())
            {
                sampleDir.Create();
            }

            // Get a reference to the file we created previously.
            CloudFile file = sampleDir.GetFileReference("Log1.txt");

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

            Console.ReadKey();
        }
Esempio n. 9
0
        public CloudFileDirectory GetFileShare(string dirname, bool createIfDoesntExist = false)
        {
            var                storageAccount = CloudStorageAccount.Parse(ConfigurationManager.AppSettings["storagekey"]);
            var                fileClient     = storageAccount.CreateCloudFileClient();
            var                folderPath     = dirname.Split('\\'); //ex: fileupload\uploads
            CloudFileShare     share          = fileClient.GetShareReference(folderPath[0]);
            CloudFileDirectory directory      = null;

            if (!share.Exists())
            {
                throw new InvalidOperationException(string.Format("{0}share doesnt exists.", folderPath[0]));
            }

            directory = share.GetRootDirectoryReference();

            if (!createIfDoesntExist)
            {
                //Avoid loop if directory neednt be created
                if (folderPath.Length > 1)
                {
                    directory = directory.GetDirectoryReference(string.Join("/", folderPath.Skip(1)));
                }
            }
            else
            {
                //Loop if directories need to be checked for existance
                for (int i = 1; i < folderPath.Length && directory.Exists(); i++)
                {
                    directory = directory.GetDirectoryReference(folderPath[i]);
                    //Create if directory doesnt exists
                    if (!directory.Exists())
                    {
                        directory.Create();
                    }
                }
            }

            if (directory.Exists())
            {
                return(directory);
            }

            throw new InvalidOperationException(string.Format("{0} directory doesnt exists.", directory.Name));
        }
Esempio n. 10
0
        public CloudFileDirectory CreateDirectory(CloudFileDirectory parent, string name)
        {
            try
            {
                CancelOperation = false;
                CloudFileDirectory cd = parent?.GetDirectoryReference(name);
                if (cd.Exists())
                {
                    throw new Exception("Folder already exists!");
                }

                cd.Create();

                return(cd);
            } catch (Exception ex)
            {
                return(null);
            }
        }
Esempio n. 11
0
        private void CreateDirectoryRecursive(CloudFileDirectory directory, ref int index)
        {
            if (null == directory.Parent)
            {
                return;
            }
            else
            {
                CreateDirectoryRecursive(directory.Parent, ref index);
            }

            if (index < this.lastAzureFileDirectory.Count)
            {
                if (!string.Equals(this.lastAzureFileDirectory[index].Name, directory.Name, StringComparison.Ordinal))
                {
                    this.lastAzureFileDirectory.RemoveRange(index, this.lastAzureFileDirectory.Count - index);
                }
                else
                {
                    ++index;
                    return;
                }
            }

            try
            {
                directory.Create(Transfer_RequestOptions.DefaultFileRequestOptions);
            }
            catch (StorageException ex)
            {
                if ((null == ex.RequestInformation) ||
                    ((int)HttpStatusCode.Conflict != ex.RequestInformation.HttpStatusCode) ||
                    (!string.Equals("ResourceAlreadyExists", ex.RequestInformation.ErrorCode)))
                {
                    throw;
                }
            }

            this.lastAzureFileDirectory.Add(directory);
            ++index;
        }
Esempio n. 12
0
        /// <summary>
        /// Create a directory (if it doesn't exist already)
        /// </summary>
        /// <param name="directoryName"></param>
        /// <returns></returns>
        public bool CreateDirectory(string directoryName)
        {
            try
            {
                directoryName = CleanRelativeCloudDirectoryName(directoryName);

                CloudStorageAccount cloudStorageAccount = GetCloudStorageAccount();
                CloudFileClient     fileClient          = GetCloudFileClient(cloudStorageAccount);
                CloudFileShare      cloudFileShare      = GetCloudFileShareReference(fileClient);             // share

                /// 20180106 - we need a ref to the directory in order to create it - our create returns null
                /// 20180106 - modified Get/Check to return ref when not found
                // Get a reference to the root directory for the share

                /*CloudFileDirectory cloudRootShareDirectory = cloudFileShare.GetRootDirectoryReference();
                 *
                 * directoryName = CleanRelativeCloudDirectoryName(directoryName);
                 *
                 * // Get a reference to the image directory
                 * CloudFileDirectory cloudShareDirectory = cloudRootShareDirectory.GetDirectoryReference(directoryName);
                 *
                 * if (!cloudShareDirectory.Exists())
                 *      cloudRootShareDirectory.Create();
                 * ////////  */
                CloudFileDirectory shareDir = GetCloudFileDirectory(cloudFileShare, directoryName); // share,
                if ((shareDir != null) && !shareDir.Exists())                                       // (shareDir == null) ||
                {
                    shareDir.Create();
                }
                ////////

                return(true);
            }
            catch (Exception oExeption)
            {
                oExeption.Log($"CreateDirectory  - [{directoryName}]");
                return(false);
            }
        }
Esempio n. 13
0
        public void storeFile(String path, String fileName, String uploadFile)
        {
            CloudFileClient fileClient = this.storageAccount.CreateCloudFileClient();
            CloudFileShare  fileShare  = fileClient.GetShareReference(this._appSettings.AzureFIleStoreName);

            if (fileShare.Exists())
            {
                CloudFileDirectory root   = fileShare.GetRootDirectoryReference();
                CloudFileDirectory folder = root.GetDirectoryReference(path);
                if (!folder.Exists())
                {
                    folder.Create();
                }
                CloudFile file = folder.GetFileReference(fileName);
                using (AutoResetEvent waitHandle = new AutoResetEvent(false))
                {
                    ICancellableAsyncResult result = file.BeginUploadFromFile(uploadFile, ar => waitHandle.Set(), new object());
                    waitHandle.WaitOne();

                    file.EndUploadFromFile(result);
                }
            }
        }
Esempio n. 14
0
        public AzureFilePersistenceSystem(Enums.FileType fileType, Enums.FileSubType fileSubType, string folder) : base(fileType, fileSubType, folder)
        {
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("StorageConnectionString"));

            // 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 = null;

            switch (FileType)
            {
            case Enums.FileType.Photo:
                share = fileClient.GetShareReference("photos");
                break;
            }

            // 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.
                fileDirectory = rootDir.GetDirectoryReference(((int)FileSubType).ToString());
                if (!fileDirectory.Exists())
                {
                    fileDirectory.Create();
                }

                fileDirectory = fileDirectory.GetDirectoryReference(Folder);
                if (!fileDirectory.Exists())
                {
                    fileDirectory.Create();
                }
            }
        }
Esempio n. 15
0
        private void WriteLogLine(WriteWay writeWay, string writeLogLine, params string[] logFilePath)
        {
            if (logFilePath.Length < 2)
            {
                Console.WriteLine(invalidExistLogFilePath);
                return;
            }

            string connectionString            = $"DefaultEndpointsProtocol=https;AccountName={Constant.STORAGE_ACCOUNT_NAME};AccountKey={Constant.Instance.StorageAccountKey};EndpointSuffix=core.windows.net";
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(connectionString);
            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]);

            lock ("")
            {
                CloudBlobClient    blobClient    = storageAccount.CreateCloudBlobClient();
                CloudBlobContainer blobContainer = blobClient.GetContainerReference("logs");
                blobContainer.CreateIfNotExistsAsync();
                CloudBlockBlob blockBlob = blobContainer.GetBlockBlobReference("testBlob");

                List <string> blockIds = new List <string>();
                DateTime      before   = DateTime.Now;

                blockIds.AddRange(blockBlob.DownloadBlockList(BlockListingFilter.Committed).Select(b => b.Name));
                DateTime after = DateTime.Now;
                TimeSpan ts    = after.Subtract(before);
                Console.WriteLine(ts.Seconds + "_" + ts.Milliseconds);

                var newId = Convert.ToBase64String(Encoding.Default.GetBytes(blockIds.Count.ToString()));
                blockBlob.PutBlock(newId, new MemoryStream(Encoding.Default.GetBytes(writeLogLine + "\n")), null);
                blockIds.Add(newId);
                blockBlob.PutBlockList(blockIds);

                string writenLineContent = "";
                if (file.Exists())
                {
                    if (writeWay == WriteWay.Cover)
                    {
                    }
                    else if (writeWay == WriteWay.Append)
                    {
                        writenLineContent = file.DownloadTextAsync().Result;
                    }
                }
                file.UploadText(writenLineContent + writeLogLine + "\n");
            }
        }