public static CloudFileDirectory getDirByName(CloudFileDirectory parentDir, string dirName)
        {
            CloudFileDirectory userDir = parentDir.GetDirectoryReference(dirName);

            userDir.CreateIfNotExists();
            return(userDir);
        }
Esempio n. 2
0
        static void Main(string[] args)
        {
            string storageConnectionString = "xxxx";
            CloudStorageAccount account    = CloudStorageAccount.Parse(storageConnectionString);

            CloudFileClient fileClient = account.CreateCloudFileClient();
            CloudFileShare  fileShare  = fileClient.GetShareReference("t22");

            fileShare.CreateIfNotExists();

            CloudFileDirectory fileDirectory = fileShare.GetRootDirectoryReference();

            //here, I want to upload all the files and subfolders in the follow path.
            string source_path = @"F:\temp\1";

            //if I want to upload the folder 1, then use the following code to create a file directory in azure.
            CloudFileDirectory fileDirectory_2 = fileDirectory.GetDirectoryReference("1");

            fileDirectory_2.CreateIfNotExists();



            UploadDirectoryOptions directoryOptions = new UploadDirectoryOptions
            {
                Recursive = true
            };

            var task = TransferManager.UploadDirectoryAsync(source_path, fileDirectory_2, directoryOptions, null);

            task.Wait();

            Console.WriteLine("the upload is completed");
            Console.ReadLine();
        }
Esempio n. 3
0
        // Create & Check Directory/Folder exist or not
        public void CreateFolderUnderFileShare(string folderName)
        {
            CloudFileDirectory rootDirectory = fileShare.GetRootDirectoryReference();
            CloudFileDirectory subDirectory  = rootDirectory.GetDirectoryReference(folderName);

            subDirectory.CreateIfNotExists();
        }
Esempio n. 4
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. 5
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. 6
0
        // Create & Check Directory/Folder exist or not
        public static void CreateFolderUnderFileShare(string folderName)
        {
            CloudFileDirectory rootDirectory = BasicAzureFileOperations();
            CloudFileDirectory subDirectory  = rootDirectory.GetDirectoryReference(folderName);

            subDirectory.CreateIfNotExists();
        }
Esempio n. 7
0
        static void FileTest()
        {
            CloudStorageAccount storageAccount = ValidateConnection();

            if (storageAccount == null)
            {
                return;
            }
            CloudFileClient fileClient = storageAccount.CreateCloudFileClient();
            CloudFileShare  share      = fileClient.GetShareReference("myfiles");

            share.CreateIfNotExists();
            Console.WriteLine("share Created");
            CloudFileDirectory root = share.GetRootDirectoryReference();
            CloudFileDirectory dir  = root.GetDirectoryReference("mydirectory");//create directory

            dir.CreateIfNotExists();
            string filepath = @"d:\test.txt";
            //upload file
            CloudFile file = dir.GetFileReference("t1.txt");

            file.UploadFromFile(filepath);
            Console.WriteLine("File Uploaded");
            //download file
            file = dir.GetFileReference("t1.txt");
            file.DownloadToFile("d:\\t3.txt", FileMode.Append);
            Console.WriteLine("File downloaded");
        }
Esempio n. 8
0
        public void SaveFile(string filePath)
        {
            string fileName = Path.GetFileName(filePath);

            string accountName              = Settings.Default.AzureAccountName;
            string accountKey               = Settings.Default.AzureAccountKey;
            string storageContainer         = Settings.Default.AzureStorageContainer;
            string defaultEndpointsProtocol = Resources.AzureEndpointsProtocol;
            string fileLocation             = Resources.AzureFileLocation;
            string fileUri = Resources.AzureFileUri;

            string connectionKey = string.Concat(defaultEndpointsProtocol, "AccountName=", accountName, ";AccountKey=", accountKey, ";");

            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(connectionKey);
            CloudFileClient     fileClient     = storageAccount.CreateCloudFileClient();

            CloudFileShare share = fileClient.GetShareReference(storageContainer);

            share.CreateIfNotExists();

            CloudFileDirectory rootDir = share.GetRootDirectoryReference();

            rootDir.CreateIfNotExists();

            var cloudFileUrl = string.Concat(fileLocation, accountName, fileUri, storageContainer, "/", fileName);
            var uriToFile    = new Uri(cloudFileUrl);

            CloudFile file = new CloudFile(uriToFile, fileClient.Credentials);

            file.UploadFromFile(filePath);
        }
Esempio n. 9
0
        private void GenerateDir(DirNode dirNode, CloudFileDirectory cloudFileDir, string parentPath)
        {
            string dirPath = Path.Combine(parentPath, dirNode.Name);

            DMLibDataHelper.CreateLocalDirIfNotExists(dirPath);
            cloudFileDir.CreateIfNotExists(HelperConst.DefaultFileOptions);

            if (null != cloudFileDir.Parent)
            {
                if (null != dirNode.SMBAttributes)
                {
                    cloudFileDir.Properties.NtfsAttributes = dirNode.SMBAttributes;
                }

                if (dirNode.CreationTime.HasValue)
                {
                    cloudFileDir.Properties.CreationTime = dirNode.CreationTime;
                }
                if (dirNode.LastWriteTime.HasValue)
                {
                    cloudFileDir.Properties.LastWriteTime = dirNode.LastWriteTime;
                }
                if (null != dirNode.PortableSDDL)
                {
                    cloudFileDir.FilePermission = dirNode.PortableSDDL;
                }
                cloudFileDir.SetProperties(HelperConst.DefaultFileOptions);

                cloudFileDir.FetchAttributes(null, HelperConst.DefaultFileOptions);

                dirNode.CreationTime  = cloudFileDir.Properties.CreationTime;
                dirNode.LastWriteTime = cloudFileDir.Properties.LastWriteTime;

                if ((null != dirNode.Metadata) &&
                    (dirNode.Metadata.Count > 0))
                {
                    cloudFileDir.Metadata.Clear();

                    foreach (var keyValuePair in dirNode.Metadata)
                    {
                        cloudFileDir.Metadata.Add(keyValuePair);
                    }

                    cloudFileDir.SetMetadata(null, HelperConst.DefaultFileOptions);
                }
            }

            foreach (var subDir in dirNode.DirNodes)
            {
                CloudFileDirectory subCloudFileDir = cloudFileDir.GetDirectoryReference(subDir.Name);
                this.GenerateDir(subDir, subCloudFileDir, dirPath);
            }

            foreach (var file in dirNode.FileNodes)
            {
                CloudFile cloudFile = cloudFileDir.GetFileReference(file.Name);
                this.GenerateFile(file, cloudFile, dirPath);
            }
        }
Esempio n. 10
0
        private void Initialise(LoggingEvent loggingEvent)
        {
            if (_storageAccount == null || AzureStorageConnectionString != _thisConnectionString)
            {
                _storageAccount       = CloudStorageAccount.Parse(AzureStorageConnectionString);
                _thisConnectionString = AzureStorageConnectionString;
                _client = null;
                _share  = null;
                _folder = null;
                _file   = null;
            }

            if (_client == null)
            {
                _client = _storageAccount.CreateCloudFileClient();
                _share  = null;
                _folder = null;
                _file   = null;
            }

            if (_share == null || _share.Name != ShareName)
            {
                _share = _client.GetShareReference(ShareName);
                _share.CreateIfNotExists();
                _folder = null;
                _file   = null;
            }

            if (_folder == null || Path != _thisFolder)
            {
                var pathElements = Path.Split(new[] { '\\', '/' }, StringSplitOptions.RemoveEmptyEntries);

                _folder = _share.GetRootDirectoryReference();
                foreach (var element in pathElements)
                {
                    _folder = _folder.GetDirectoryReference(element);
                    _folder.CreateIfNotExists();
                }

                _thisFolder = Path;
                _file       = null;
            }

            var filename = Regex.Replace(File, @"\{(.+?)\}", _ => loggingEvent.TimeStamp.ToString(_.Result("$1")));

            if (_file == null || filename != _thisFile)
            {
                _file = _folder.GetFileReference(filename);
                if (!_file.Exists())
                {
                    _file.Create(0);
                }
                _thisFile = filename;
            }
        }
Esempio n. 11
0
 private void Initialize(CloudFileDirectory rootDirectory, DirectoryInfo directoryToSync, ILogger logger)
 {
     CloudDirectory = rootDirectory;
     LocalDirectory = directoryToSync;
     _logger        = logger;
     CloudDirectory.CreateIfNotExists();
     _fileScheduler      = new SyncTaskSceduler();
     _directoryScheduler = new SyncTaskSceduler();
     _cloudDirectories   = new List <CloudFileDirectory>();
     _cloudFiles         = new List <CloudFile>();
 }
Esempio n. 12
0
        private CloudFileDirectory EnsureRootDirectory(CloudFileClient fileClient)
        {
            string         storageContainer = Settings.Default.AzureStorageContainer;
            CloudFileShare share            = fileClient.GetShareReference(storageContainer);

            share.CreateIfNotExists();

            CloudFileDirectory rootDir = share.GetRootDirectoryReference();

            rootDir.CreateIfNotExists();
            return(rootDir);
        }
Esempio n. 13
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. 14
0
        static public void UploadFile(string sourceFile, string path)
        {
            CloudFileDirectory rootDir            = GetRootDirectory();
            CloudFileDirectory cloudFileDirectory = rootDir.GetDirectoryReference(path);

            cloudFileDirectory.CreateIfNotExists();

            string destFileName = Path.GetFileName(sourceFile);

            CloudFile cloudFile = cloudFileDirectory.GetFileReference(destFileName);

            using (Stream fileStream = File.OpenRead(sourceFile)) {
                cloudFile.UploadFromStreamAsync(fileStream).Wait();
            }
        }
Esempio n. 15
0
        private async void MoveFileToProcessedFolder(CloudFile cloudFile)
        {
            CloudFileDirectory rootDirectory = _cloudFileShare.GetRootDirectoryReference();

            if (rootDirectory.Exists())
            {
                CloudFileDirectory customDirectory = rootDirectory.GetDirectoryReference(_azureFileProcessedFolderName);
                customDirectory.CreateIfNotExists();
                var       fileName = $"{Path.GetFileNameWithoutExtension(cloudFile.Name)}-{DateTime.Now.ToString(_appendDateFormatInFileName)}{Path.GetExtension(cloudFile.Name)}";
                CloudFile file     = customDirectory.GetFileReference(fileName);
                Uri       fileUrl  = new Uri(cloudFile.StorageUri.PrimaryUri.ToString());
                await file.StartCopyAsync(fileUrl);

                await cloudFile.DeleteAsync();
            }
        }
Esempio n. 16
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();
        }
        private static void CreateCloudFileDirectoryRecursively(CloudFileDirectory dir)
        {
            if (null == dir)
            {
                return;
            }

            CloudFileDirectory parent = dir.Parent;

            // null == parent means dir is root directory,
            // we should not call CreateIfNotExists in that case
            if (null != parent)
            {
                CreateCloudFileDirectoryRecursively(parent);
                dir.CreateIfNotExists(Transfer_RequestOptions.DefaultFileRequestOptions);
            }
        }
Esempio n. 18
0
        // Upload file into Directory/Folder
        public void UploadFileToFolder(string folderName, string fileName, string filePath)
        {
            CloudFileDirectory rootDirectory = fileShare.GetRootDirectoryReference();

            if (string.IsNullOrEmpty(folderName))
            {
                CloudFile file = rootDirectory.GetFileReference(fileName);
                file.UploadFromFile(filePath);
            }
            else
            {
                CloudFileDirectory subDirectory = rootDirectory.GetDirectoryReference(folderName);
                subDirectory.CreateIfNotExists();
                CloudFile file = rootDirectory.GetFileReference(fileName);
                file.UploadFromFile(filePath);
            }
        }
Esempio n. 19
0
 public AzureSession(string connectionString, string shareName, string systemDir, int waitForLockMilliseconds = 5000, bool optimisticLocking = true,
   bool enableCache = true, CacheEnum objectCachingDefaultPolicy = CacheEnum.Yes)
   : base(systemDir, waitForLockMilliseconds, optimisticLocking, enableCache, objectCachingDefaultPolicy)
 {
   m_cloudStorageAccount = CloudStorageAccount.Parse(connectionString);
   if (Path.IsPathRooted(systemDir) == false)
     SystemDirectory = systemDir;
   m_shareName = shareName;
   m_cloudFileClient = m_cloudStorageAccount.CreateCloudFileClient();
   m_cloudShare = m_cloudFileClient.GetShareReference(shareName);
   if (m_cloudShare.Exists())
   {
     m_rootDir = m_cloudShare.GetRootDirectoryReference();
     m_databaseDir = m_rootDir.GetDirectoryReference(systemDir);
     m_databaseDir.CreateIfNotExists();
   }
 }
Esempio n. 20
0
        public static void SaveDocumentToAzure(XDocument doc, Configuration config, string folderDateTime)
        {
            if (IsNullOrEmpty(config.StorageAccountName) ||
                IsNullOrEmpty(config.StorageAccountKey) ||
                IsNullOrEmpty(config.StorageAccountShareReference) ||
                IsNullOrEmpty(config.StorageAccountCatalogDirectoryReference))
            {
                return;
            }

            StorageCredentials  cred           = new StorageCredentials(config.StorageAccountName, config.StorageAccountKey);
            CloudStorageAccount storageAccount = new CloudStorageAccount(cred, true);

            CloudFileClient fileClient = storageAccount.CreateCloudFileClient();
            CloudFileShare  share      = fileClient.GetShareReference(config.StorageAccountShareReference);

            share.CreateIfNotExists();


            string dirPath = Path.Combine(config.ResourcesRootPath, folderDateTime);

            CloudFileDirectory root = share.GetRootDirectoryReference();
            CloudFileDirectory dir  = root.GetDirectoryReference(dirPath);

            dir.CreateIfNotExists();

            CloudFile cloudFile = dir.GetFileReference("Resources.xml");

            using (MemoryStream stream = new MemoryStream())
            {
                XmlWriterSettings xws = new XmlWriterSettings
                {
                    OmitXmlDeclaration = false,
                    Indent             = true
                };

                using (XmlWriter xw = XmlWriter.Create(stream, xws))
                {
                    doc.WriteTo(xw);
                }

                stream.Position = 0;
                cloudFile.UploadFromStream(stream);
            }
        }
Esempio n. 21
0
        public CloudFile CreateFile(CloudFileDirectory directory, string fileName, string source = null)
        {
            string[] path = fileName.Split('/');

            for (int i = 0; i < path.Length - 1; ++i)
            {
                if (!string.IsNullOrWhiteSpace(path[i]))
                {
                    directory = directory.GetDirectoryReference(path[i]);
                    directory.CreateIfNotExists();
                }
            }

            var file = directory.GetFileReference(path[path.Length - 1]);

            PrepareFileInternal(file, source);
            return(file);
        }
Esempio n. 22
0
        private void GenerateDir(DirNode dirNode, CloudFileDirectory cloudFileDir, string parentPath)
        {
            string dirPath = Path.Combine(parentPath, dirNode.Name);

            DMLibDataHelper.CreateLocalDirIfNotExists(dirPath);
            cloudFileDir.CreateIfNotExists(HelperConst.DefaultFileOptions);

            foreach (var subDir in dirNode.DirNodes)
            {
                CloudFileDirectory subCloudFileDir = cloudFileDir.GetDirectoryReference(subDir.Name);
                this.GenerateDir(subDir, subCloudFileDir, dirPath);
            }

            foreach (var file in dirNode.FileNodes)
            {
                CloudFile cloudFile = cloudFileDir.GetFileReference(file.Name);
                this.GenerateFile(file, cloudFile, dirPath);
            }
        }
Esempio n. 23
0
        public static void Copy(string sourceFilePath, string destPath)
        {
            CloudFileDirectory rootDir    = GetRootDirectory();
            CloudFile          sourceFile = rootDir.GetFileReference(sourceFilePath);

            if (!sourceFile.Exists())
            {
                throw new Exception("I cant find the sourceFile!!!");
            }

            CloudFileDirectory destDirectory = rootDir.GetDirectoryReference(destPath);

            destDirectory.CreateIfNotExists();

            string    destFileName = Path.GetFileName(sourceFilePath);
            CloudFile destFile     = destDirectory.GetFileReference(destFileName);

            destFile.StartCopy(sourceFile);
        }
        private bool CreateWithParentHierachy(string folderPathToCreate)
        {
            bool   succeeded          = false;
            string remotePathToCreate = "";

            try
            {
                foreach (var folder in folderPathToCreate.Split("/"))
                {
                    remotePathToCreate += "/" + folder;
                    CloudFileDirectory cloudDirectory = new CloudFileDirectory(new Uri(AzureFileStorageUri + remotePathToCreate), storageCreds); //  account.FileStorageUri.PrimaryUri.ToString() ;// "https://asynccopiertesttarget.file.core.windows.net/aafc1";
                    succeeded = cloudDirectory.CreateIfNotExists(null, null);
                }
            }
            catch (Exception e)
            {
                Log.Always("exception :" + e.Message);
                throw;
            }

            return(succeeded);
        }
        public void FileOperations(string fileSharename, string Directory, string filePath)
        {
            CloudFileClient fileClient = storageAccount.CreateCloudFileClient();
            CloudFileShare  fileShare  = fileClient.GetShareReference(fileSharename);

            fileShare.CreateIfNotExists(null, null);
            CloudFileDirectory rootDirectory = fileShare.GetRootDirectoryReference();
            CloudFileDirectory fileDirectory = rootDirectory.GetDirectoryReference(Directory);

            fileDirectory.CreateIfNotExists();
            CloudFile file = fileDirectory.GetFileReference("testfile");

            //Deleting If File Exists
            file.DeleteIfExistsAsync();
            if (file.Exists() == false)
            {
                FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.ReadWrite);
                file.Create(fs.Length);
                fs.Close();
            }
            file.OpenWrite(null);
            //Upload File Operation
            file.UploadFromFile(filePath, FileMode.Open);
            //Write File Operation
            file.WriteRange(new FileStream(filePath, FileMode.Open), 0);
            Stream azureFile = file.OpenRead();

            //Read File Operation
            azureFile.Position = 0;
            byte[] buffer = new byte[azureFile.Length - 1];
            int    n      = azureFile.Read(buffer, (int)0, 14050);

            for (int i = 0; i < buffer.Length; i++)
            {
                Console.Write(buffer[i].ToString());
            }
            //Download File Operation
            file.DownloadToFile(@"D:\TestFile.pptx", FileMode.Create);
        }
        /// <summary>
        /// Creates a folder in Azure Files, epxects a forward slash based path
        /// </summary>
        /// <param name="folderPathToCreate">a simple folder path in the form folder/subfolder_level1/subfolder_level2</param>
        /// <returns></returns>
        public bool CreateFolder(string folderPathToCreate)
        {
            bool   succeeded        = false;
            bool   storageException = false;
            string uri = AzureFileStorageUri + "/" + folderPathToCreate;

            try
            {
                CloudFileDirectory cloudDirectory = new CloudFileDirectory(new Uri(uri), storageCreds);
                succeeded = cloudDirectory.CreateIfNotExists(null, null);
                if (succeeded == false)
                {
                    succeeded = cloudDirectory.Exists();
                }
            }
            catch (StorageException se)
            {
                Log.Debug(se.Message);
                storageException = true;
            }
            catch (Exception e)
            {
                Log.Always("exception :" + e.Message);
            }

            if (storageException)
            {
                // we probably started with a folder depth greater than root and need to create the parentpaths
                succeeded = CreateWithParentHierachy(folderPathToCreate);
            }

            if (succeeded == false)
            {
            }
            return(succeeded);
        }
Esempio n. 27
0
        public static void UploadFile(Stream streamfilename, string filename, string FolderPath, string ShareName)
        {
            //read connection string to store data on azure from config file with account name and key
            CloudStorageAccount cloudStorageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("StorageConnectionString"));
            CloudFileClient     cloudFileClient     = cloudStorageAccount.CreateCloudFileClient();

            //GetShareReference() take reference from cloud
            CloudFileShare cloudFileShare = cloudFileClient.GetShareReference(ShareName);

            //Create share name if not exist
            cloudFileShare.CreateIfNotExists();

            //get all directory reference located in share name
            CloudFileDirectory cloudFileDirectory = cloudFileShare.GetRootDirectoryReference();

            //Specify the nested folder
            var nestedFolderStructure = FolderPath;
            var delimiter             = new char[] { '/' };
            //split all nested folder by delimeter
            var nestedFolderArray = nestedFolderStructure.Split(delimiter);

            for (var i = 0; i < nestedFolderArray.Length; i++)
            {
                //check directory avilability if not exist then create directory
                cloudFileDirectory = cloudFileDirectory.GetDirectoryReference(nestedFolderArray[i]);
                cloudFileDirectory.CreateIfNotExists();
            }
            ////create object of file reference and get all files within directory
            CloudFile cloudFile = cloudFileDirectory.GetFileReference(filename);

            //upload file on azure
            cloudFile.UploadFromStream(streamfilename);

            Console.WriteLine("File uploaded sucessfully");
            Console.ReadLine();
        }
Esempio n. 28
0
        /// <summary>
        /// Manage share metadata
        /// </summary>
        /// <param name="cloudFileClient"></param>
        /// <returns></returns>
        private static async Task DirectoryMetadataSample(CloudFileClient cloudFileClient)
        {
            Console.WriteLine();

            // Create the share name -- use a GUID in the name so it's unique.
            string         shareName = "demotest-" + Guid.NewGuid();
            CloudFileShare share     = cloudFileClient.GetShareReference(shareName);

            try
            {
                // Create share
                Console.WriteLine("Create Share");
                await share.CreateIfNotExistsAsync();

                CloudFileDirectory rootDirectory = share.GetRootDirectoryReference();

                // Get a directory reference
                CloudFileDirectory sampleDirectory = rootDirectory.GetDirectoryReference("sample-directory");

                Console.WriteLine("Create the directory");
                sampleDirectory.CreateIfNotExists();

                // Set directory metadata
                Console.WriteLine("Set directory metadata");
                sampleDirectory.Metadata.Add("key1", "value1");
                sampleDirectory.Metadata.Add("key2", "value2");
                await sampleDirectory.SetMetadataAsync();

                // Fetch directory attributes
                // in this case this call is not need but is included for demo purposes
                await sampleDirectory.FetchAttributesAsync();

                Console.WriteLine("Get directory metadata:");
                foreach (var keyValue in sampleDirectory.Metadata)
                {
                    Console.WriteLine("    {0}: {1}", keyValue.Key, keyValue.Value);
                }
                Console.WriteLine();
            }
            catch (StorageException exStorage)
            {
                Common.WriteException(exStorage);
                Console.WriteLine(
                    "Please make sure your storage account is specified correctly in the app.config - then restart the sample.");
                Console.WriteLine("Press any key to exit");
                Console.ReadLine();
                throw;
            }
            catch (Exception ex)
            {
                Console.WriteLine("    Exception thrown creating share.");
                Common.WriteException(ex);
                throw;
            }
            finally
            {
                // Delete share
                Console.WriteLine("Delete share");
                share.DeleteIfExists();
            }
        }
Esempio n. 29
0
        public JsonResult UploadUserTaxReturn(int taxYear, string subFolder, string userId)
        {
            var curUserId = userId == null?User.Identity.GetUserId() : userId;

            bool   uploadedSuccessfully = false;
            string uploadedURI          = "";

            using (var db = new WorktripEntities())
            {
                try
                {
                    var user = db.Users.FirstOrDefault(u => u.Id == curUserId);

                    HttpPostedFileBase uploadedFile = Request.Files.Get(0);

                    var compressedStream = uploadedFile.InputStream;

                    if (uploadedFile.ContentType.StartsWith("image/"))
                    {
                        compressedStream = ResizePictureForBandwidth(uploadedFile);
                    }

                    CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
                        CloudConfigurationManager.GetSetting("StorageConnectionString"));

                    CloudFileClient fileClient = storageAccount.CreateCloudFileClient();

                    CloudFileShare share = fileClient.GetShareReference("worktripdocs");

                    CloudFileDirectory rootDir = share.GetRootDirectoryReference();

                    CloudFileDirectory userDir = rootDir.GetDirectoryReference(user.FirstName + " " + user.LastName + " " + user.PhoneNumber);

                    userDir.CreateIfNotExists();

                    if (!string.IsNullOrEmpty(subFolder))
                    {
                        userDir = userDir.GetDirectoryReference(subFolder);

                        userDir.CreateIfNotExists();
                    }

                    var newFileName   = uploadedFile.FileName;
                    var fileExtension = Path.GetExtension(newFileName);

                    CloudFile file = userDir.GetFileReference(newFileName);

                    int fileDuplicateCount = 1;

                    while (file.Exists())
                    {
                        //generate a file name that doesn't exist yet
                        newFileName = Path.GetFileNameWithoutExtension(newFileName) + "(" + (fileDuplicateCount++) + ")" + fileExtension;

                        file = userDir.GetFileReference(newFileName);;
                    }

                    file.Properties.ContentType = uploadedFile.ContentType;

                    file.UploadFromStream(compressedStream);

                    uploadedURI = file.Uri.ToString();

                    UserTaxReturn newReturn = new UserTaxReturn()
                    {
                        UserId = curUserId,
                        Date   = DateTime.UtcNow,
                        Path   = uploadedURI,
                        Year   = taxYear
                    };

                    db.UserTaxReturns.Add(newReturn);

                    db.SaveChanges();

                    uploadedSuccessfully = true;

                    UserInfoViewModel.UpdateUserActionsLog(curUserId, "uploaded " + taxYear + " " + (fileExtension == ".pdf" ? "tax return" : "tax form(s)"));
                }
                catch (Exception e)
                {
                    //Do some error logging here..
                    uploadedSuccessfully = false;
                }
            }

            if (uploadedSuccessfully)
            {
                return(Json(new { status = 0 }));
            }
            else
            {
                return(Json(new { status = -1, message = "Error in saving file" }));
            }
        }
Esempio n. 30
0
        public static bool ZipDocumentAndUploadToAzure(XmlDocumentType xmlDocumentType, XDocument doc, Configuration config, string dateTimeStamp, IDictionary <string, byte[]> files = null)
        {
            if (IsNullOrEmpty(config.StorageAccountName) ||
                IsNullOrEmpty(config.StorageAccountKey) ||
                IsNullOrEmpty(config.StorageAccountShareReference) ||
                IsNullOrEmpty(config.StorageAccountCatalogDirectoryReference) ||
                IsNullOrEmpty(config.StorageAccountResourcesDirectoryReference))
            {
                return(false);
            }

            StorageCredentials  cred           = new StorageCredentials(config.StorageAccountName, config.StorageAccountKey);
            CloudStorageAccount storageAccount = new CloudStorageAccount(cred, true);

            CloudFileClient fileClient = storageAccount.CreateCloudFileClient();
            CloudFileShare  share      = fileClient.GetShareReference(config.StorageAccountShareReference);

            share.CreateIfNotExists();

            CloudFileDirectory root = share.GetRootDirectoryReference();
            CloudFileDirectory dir  = root.GetDirectoryReference(config.GetAzureStorageDirectoryName(xmlDocumentType));

            dir.CreateIfNotExists();

            CloudFile cloudFile = dir.GetFileReference(GetZipFileName(config, xmlDocumentType, dateTimeStamp));

            using (MemoryStream stream = new MemoryStream())
            {
                XmlWriterSettings xws = new XmlWriterSettings
                {
                    OmitXmlDeclaration = false,
                    Indent             = true
                };

                using (ZipArchive archive = new ZipArchive(stream, ZipArchiveMode.Create, true))
                {
                    if (files != null)
                    {
                        foreach (KeyValuePair <string, byte[]> imageFile in files)
                        {
                            ZipArchiveEntry zipEntry = archive.CreateEntry(imageFile.Key);
                            using (Stream entryStream = zipEntry.Open())
                            {
                                entryStream.Write(imageFile.Value, 0, imageFile.Value.Length);
                            }
                        }
                    }

                    ZipArchiveEntry entry = archive.CreateEntry("catalog.xml");
                    using (Stream entryStream = entry.Open())
                    {
                        using (XmlWriter xw = XmlWriter.Create(entryStream, xws))
                        {
                            doc.WriteTo(xw);
                        }
                    }
                }
                stream.Position = 0;
                cloudFile.UploadFromStream(stream);

                switch (xmlDocumentType)
                {
                case XmlDocumentType.Catalog:
                    config.CatalogPathInCloud = cloudFile.Name;
                    break;

                default:
                    config.ResourceNameInCloud = cloudFile.Name;
                    break;
                }
                return(true);
            }
        }