Example #1
0
        /// <summary>
        /// Download the file from the current directory to a byte array.
        /// </summary>
        /// <param name="filename">The name of the file to download</param>
        /// <returns>The byte array. Any exceptions are thrown.</returns>
        public byte[] FileDownload(string filename)
        {
            byte[] fileContents = new byte[this.FileLength(filename)];

            if (!this.FileExists(filename))
            {
                throw new Exception("Failed to Download File: '" + filename + "' from '" + Directory.Name + ". File was missing.");
            }

            try
            {
                using (var stream = new MemoryStream(fileContents, true))
                {
                    ShareFileClient       file     = Directory.GetFileClient(filename);
                    ShareFileDownloadInfo download = file.Download();
                    download.Content.CopyTo(stream);
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Failed to Download File: '" + filename + "' from '" + Directory.Name + "' Error was: " + ex.Message);
            }

            return(fileContents);
        }
        // </snippet_CopyFile>

        // <snippet_CopyFileToBlob>
        //-------------------------------------------------
        // Copy a file from a share to a blob
        //-------------------------------------------------
        public async Task CopyFileToBlobAsync(string shareName, string sourceFilePath, string containerName, string blobName)
        {
            Uri fileSasUri = GetFileSasUri(shareName, sourceFilePath, DateTime.UtcNow.AddHours(24), ShareFileSasPermissions.Read);

            // Get a reference to the file we created previously
            ShareFileClient sourceFile = new ShareFileClient(fileSasUri);

            // Ensure that the source file exists
            if (await sourceFile.ExistsAsync())
            {
                // Get the connection string from app settings
                string connectionString = ConfigurationManager.AppSettings["StorageConnectionString"];

                // Get a reference to the destination container
                BlobContainerClient container = new BlobContainerClient(connectionString, containerName);

                // Create the container if it doesn't already exist
                await container.CreateIfNotExistsAsync();

                BlobClient destBlob = container.GetBlobClient(blobName);

                await destBlob.StartCopyFromUriAsync(sourceFile.Uri);

                if (await destBlob.ExistsAsync())
                {
                    Console.WriteLine($"File {sourceFile.Name} copied to blob {destBlob.Name}");
                }
            }
        }
Example #3
0
        public static bool WriteStringToAzureFileShare(string storageConnString, string shareName, string fileName, string content)
        {
            if (!azureAuthenticated)
            {
                return(false);
            }
            try
            {
                ShareClient          share     = new ShareClient(storageConnString, shareName);
                ShareDirectoryClient directory = share.GetRootDirectoryClient();
                directory.DeleteFile(fileName);
                ShareFileClient file = directory.GetFileClient(fileName);

                byte[] byteArray = Encoding.UTF8.GetBytes(content);
                using (MemoryStream stream = new MemoryStream(byteArray))
                {
                    file.Create(stream.Length);
                    file.UploadRange(
                        new HttpRange(0, stream.Length),
                        stream);
                }
                return(true);
            }
            catch (Exception _)
            {
                // Log Ex.Message here
                return(false);
            }
        }
        public void VerifyTypeOverrideSupport()
        {
            var test = new ShareFileClient(BaseUriString);

            test.RegisterType <FolderTestClass, Folder>();

            var folder = GetFolder();

            folder.MetadataUrl =
                "https://labs.sf-api.com/sf/v3/$metadata#ShareFile.Api.Models.Folder";
            folder.Children.First().MetadataUrl =
                "https://labs.sf-api.com/sf/v3/$metadata#ShareFile.Api.Models.File";

            var serializer = GetSerializer();

            StringWriter writer = new StringWriter();

            serializer.Serialize(writer, folder);

            var jsonReader = new JsonTextReader(new StringReader(writer.ToString()));

            var item = serializer.Deserialize <Item>(jsonReader);

            item.GetType().Should().Be(typeof(FolderTestClass));
        }
Example #5
0
        /// <summary>
        /// Delete the Sharefile items if Move flag is used
        /// </summary>
        private void DeleteShareFileItemRecursive(ShareFileClient client, Models.Item source, bool deleteFolder)
        {
            if (source is Models.Folder)
            {
                var children = (source as Folder).Children;
                var childFiles = children.OfType<Models.File>();
                var childFolders = children.OfType<Models.Folder>();
                
                RemoveShareFileItems(client, source, childFiles);

                if (Recursive)
                {
                    foreach (var childFolder in childFolders)
                    {
                        // KA - Fix. If we pass in 'deleteFolder' I don't know why we don't continue to use that here
                        //      This keeps the behavior of DeleteShareFileItemRecursive consistent with the deleteFolder flag
                        // DeleteShareFileItemRecursive(client, childFolder, !KeepFolders);
                        DeleteShareFileItemRecursive(client, childFolder, deleteFolder);
                    }
                }

                if (deleteFolder)
                {
                    if(!HasChildren(client, source as Models.Folder))
                    {
                        RemoveShareFileItem(client, source);
                    }
                }
            }
            
            if (source is Models.File)
            {
                RemoveShareFileItem(client, source);
            }
        }
Example #6
0
        /// <summary>
        /// Download all items recursively
        /// </summary>
        private void DownloadRecursive(ShareFileClient client, int downloadId, Models.Item source, DirectoryInfo target, ActionType actionType)
        {
            if (source is Models.Folder)
            {
                var subdir = CreateLocalFolder(target, source as Folder);

                var children = client.Items.GetChildren(source.url).Execute();

                if (children != null)
                {
                    ActionManager actionManager = new ActionManager();

                    foreach (var child in children.Feed)
                    {
                        if (child is Models.Folder && Recursive)
                        {
                            DownloadRecursive(client, downloadId, child, subdir, actionType);
                        }
                        else if (child is Models.File)
                        {
                            DownloadAction downloadAction = new DownloadAction(FileSupport, client, downloadId, (Models.File)child, subdir, actionType);
                            actionManager.AddAction(downloadAction);
                        }
                    }

                    actionManager.Execute();
                }
            }
        }
        public IActionResult DownloadFile(string userId, string fileName)
        {
            // Get a reference to a share and then create it
            ShareClient share = new ShareClient(Secret.AzureConnectionString, Secret.AzureFileShareName);

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

            // Get a reference to a directory and create it
            ShareDirectoryClient directory = share.GetDirectoryClient(Auth0Utils.GetUserFolder());

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

            // Get a reference to a file and upload it
            ShareFileClient fileClient = directory.GetFileClient(fileName);

            if (fileClient.Exists())
            {
                //ShareFileDownloadInfo download = file.Download();
                return(File(fileClient.OpenRead(), "application/octet-stream"));
            }
            else
            {
                return(NotFound());
            }
        }
Example #8
0
        public async Task UploadAsync(ConnectorConfig config, string fullFileName, MemoryStream stream)
        {
            var dirName  = Path.GetDirectoryName(fullFileName).ToString();
            var fileName = Path.GetFileName(fullFileName).ToString();

            ShareClient share = new ShareClient(config.connectionString, config.shareName);

            if (!share.Exists())
            {
                await share.CreateAsync();
            }

            ShareDirectoryClient directory = share.GetDirectoryClient(dirName);

            if (!directory.Exists())
            {
                await directory.CreateAsync();
            }

            ShareFileClient file = directory.GetFileClient(fileName);
            await file.CreateAsync(stream.Length);

            await file.UploadAsync(stream);

            /*
             * await file.UploadRange(
             *      ShareFileRangeWriteType.Update,
             *      new HttpRange(0, stream.Length),
             *      stream);*/
        }
Example #9
0
        public void UploadFile(string name, Stream file)
        {
            ShareFileClient shareFile = root.GetRootDirectoryClient().GetFileClient(name);

            shareFile.Create(file.Length);
            shareFile.Upload(file);
        }
        public IActionResult DeleteFile(string userId, string fileName)
        {
            // Get a reference to a share and then create it
            ShareClient share = new ShareClient(Secret.AzureConnectionString, Secret.AzureFileShareName);

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

            // Get a reference to a directory and create it
            ShareDirectoryClient directory = share.GetDirectoryClient(Auth0Utils.GetUserFolder());

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

            // Get a reference to a file and upload it
            ShareFileClient fileClient = directory.GetFileClient(fileName);

            fileClient.DeleteIfExists();

            return(Ok());
        }
Example #11
0
        private ShareFileClient StorageSetup(IFormFile loadedFile, string fileType)
        {
            string dirName  = fileType;
            string fileName = loadedFile.FileName;

            ShareClient share = new ShareClient(_storagekey, _storageshare);

            try
            {
                // Try to create the share again
                share.Create();
            }
            catch (RequestFailedException ex)
                when(ex.ErrorCode == ShareErrorCode.ShareAlreadyExists)
                {
                    // Ignore any errors if the share already exists
                }
            ShareDirectoryClient directory = share.GetDirectoryClient(dirName);

            try
            {
                // Try to create the share again
                directory.Create();
            }
            catch (RequestFailedException ex)
            {
                // Ignore any errors if the share already exists
            }
            ShareFileClient shareFile = directory.GetFileClient(fileName);

            return(shareFile);
        }
        private async Task DumpJson <T>(T obj, string fileName)
        {
            // Dump to local temp file (need to do this because need to know file size before copying to Azure File Share).
            var tmpFile = Path.GetTempFileName();

            using (StreamWriter sw = new StreamWriter(tmpFile))
                using (JsonWriter jtw = new JsonTextWriter(sw))
                {
                    var serializer = new JsonSerializer();
                    serializer.Serialize(jtw, obj);
                }

            try
            {
                // Copy the temp file to Azure File Share
                ShareClient          share     = new ShareClient(DataDumpStorageConnectionString, DataDumpStorageShareName);
                ShareDirectoryClient directory = share.GetDirectoryClient("/");
                ShareFileClient      file      = directory.GetFileClient(fileName);

                using (FileStream stream = File.OpenRead(tmpFile))
                {
                    await file.CreateAsync(stream.Length);

                    await file.UploadRangeAsync(new HttpRange(0, stream.Length), stream);
                }
            }
            finally
            {
                // Clean up the temp file
                File.Delete(tmpFile);
            }
        }
        public async Task UploadFileAsync(String filename, Stream stream)
        {
            ShareFileClient file = this.root.GetFileClient(filename);
            await file.CreateAsync(stream.Length);

            await file.UploadAsync(stream);
        }
        // <snippet_RestoreFileFromSnapshot>
        //-------------------------------------------------
        // Restore file from snapshot
        //-------------------------------------------------
        public async Task RestoreFileFromSnapshot(string shareName, string directoryName, string fileName, string snapshotTime)
        {
            // Get the connection string from app settings
            string connectionString = ConfigurationManager.AppSettings["StorageConnectionString"];

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

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

            // Get a ShareDirectoryClient, then a ShareFileClient to the live file
            ShareDirectoryClient liveDir  = share.GetDirectoryClient(directoryName);
            ShareFileClient      liveFile = liveDir.GetFileClient(fileName);

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

            // Get a ShareDirectoryClient, then a ShareFileClient to the snapshot file
            ShareDirectoryClient snapshotDir  = snapshot.GetDirectoryClient(directoryName);
            ShareFileClient      snapshotFile = snapshotDir.GetFileClient(fileName);

            // Restore the file from the snapshot
            ShareFileCopyInfo copyInfo = await liveFile.StartCopyAsync(snapshotFile.Uri);

            // Display the status of the operation
            Console.WriteLine($"Restore status: {copyInfo.CopyStatus}");
        }
        protected AsyncUploaderBase(ShareFileClient client, UploadSpecificationRequest uploadSpecificationRequest, IPlatformFile file, FileUploaderConfig config = null, int? expirationDays = null)
            : base(client, uploadSpecificationRequest, file, expirationDays)
        {
            Config = config ?? new FileUploaderConfig();

            HashProvider = MD5HashProviderFactory.GetHashProvider().CreateHash();
        }
Example #16
0
        /// <summary>
        /// Download a file.
        /// </summary>
        /// <param name="connectionString">
        /// A connection string to your Azure Storage account.
        /// </param>
        /// <param name="shareName">
        /// The name of the share to download from.
        /// </param>
        /// <param name="localFilePath">
        /// Path to download the local file.
        /// </param>
        public static async Task DownloadAsync(string connectionString, string shareName, string localFilePath)
        {
            #region Snippet:Azure_Storage_Files_Shares_Samples_Sample01b_HelloWorldAsync_DownloadAsync
            //@@ string connectionString = "<connection_string>";

            // Name of the share, directory, and file we'll download from
            //@@ string shareName = "sample-share";
            string dirName  = "sample-dir";
            string fileName = "sample-file";

            // Path to the save the downloaded file
            //@@ string localFilePath = @"<path_to_local_file>";

            // Get a reference to the file
            ShareClient          share     = new ShareClient(connectionString, shareName);
            ShareDirectoryClient directory = share.GetDirectoryClient(dirName);
            ShareFileClient      file      = directory.GetFileClient(fileName);

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

            using (FileStream stream = File.OpenWrite(localFilePath))
            {
                await download.Content.CopyToAsync(stream);
            }
            #endregion Snippet:Azure_Storage_Files_Shares_Samples_Sample01b_HelloWorldAsync_DownloadAsync
        }
Example #17
0
        private async Task <string> DownloadFromShareFileAsync(string shareLink, string itemName)
        {
            var uri      = new Uri(shareLink);
            var sfClient = new ShareFileClient($"https://{uri.Authority}/sf/v3");

            // Extract shareId from path /d-<shareid>
            var shareId = uri.AbsolutePath.Substring(3);

            System.Console.WriteLine("ShareId: " + shareId);

            var shareEntityUrl = sfClient.Shares.GetEntityUriFromId(shareId);
            var response       = await sfClient.Shares.Download(shareEntityUrl, redirect : false).ExecuteAsync();

            DownloadSpecification sfDownloadSpec = null;

            using (var stream = new StreamReader(response))
            {
                var bodyJson = await stream.ReadToEndAsync();

                sfDownloadSpec = JsonConvert.DeserializeObject <DownloadSpecification>(bodyJson);
            }

            Directory.CreateDirectory("temp");
            var fileName = $"temp/{itemName}";

            var webClient = new WebClient();

            webClient.DownloadFile(sfDownloadSpec.DownloadUrl, fileName);

            return(fileName);
        }
Example #18
0
        protected IShareFileClient GetShareFileClient()
        {
            try
            {
                using (var fileStream = System.IO.File.OpenRead("TestConfig.json"))
                using (var streamReader = new StreamReader(fileStream))
                {
                    var info = streamReader.ReadToEnd();
                    var userInfo = JsonConvert.DeserializeObject<UserInfo>(info);

                    var sfClient = new ShareFileClient(userInfo.GetBaseUri().ToString());

                    lock (oauthTokenLock)
                    {
                        if (token == null)
                        {
                            var oauthService = new OAuthService(sfClient, userInfo.ClientId, userInfo.ClientSecret);
                            token = oauthService.GetPasswordGrantRequestQuery(userInfo.Email, userInfo.Password, userInfo.Subdomain, userInfo.Domain).Execute();
                        }
                    }

                    sfClient.BaseUri = token.GetUri();
                    sfClient.AddOAuthCredentials(token);
                    return sfClient;
                }
            }
            catch (Exception exception)
            {
                Assert.Inconclusive(string.Format("No UserInfo found in TestConfig.json. Exception: {0}", exception));
                throw;
            }
        }
Example #19
0
        public string Download(string connectionString, string shareName, string directory, string fileName)
        {
            // Get a reference to the file
            ShareClient          share           = new ShareClient(connectionString, shareName);
            ShareDirectoryClient directoryClient = share.GetDirectoryClient(directory);
            ShareFileClient      file            = directoryClient.GetFileClient(fileName);

            string localFilePath = @"C:\audio\sales\trusted\Sales\" + file.Name;

            try
            {
                // Download the file
                ShareFileDownloadInfo download = file.Download();

                using (FileStream stream = File.OpenWrite(localFilePath))
                {
                    download.Content.CopyTo(stream);
                }
            }
            catch (Exception e)
            {
                _errors.Add(fileName + ": " + e.Message);
            }

            return(localFilePath);
        }
        public async Task DeleteFileAsync(String filename)
        {
            ShareDirectoryClient raiz = this.cliente.GetRootDirectoryClient();
            ShareFileClient      file = raiz.GetFileClient(filename);

            await file.DeleteAsync();
        }
        public async Task PathClient_CanGetParentDirectoryClient()
        {
            // Arrange
            var parentDirName = SharesClientBuilder.GetNewDirectoryName();

            await using DisposingShare test = await SharesClientBuilder.GetTestShareAsync();

            ShareDirectoryClient parentDirClient = InstrumentClient(test.Container
                                                                    .GetRootDirectoryClient()
                                                                    .GetSubdirectoryClient(parentDirName));
            await parentDirClient.CreateAsync();

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

            // Act
            parentDirClient = fileClient.GetParentShareDirectoryClient();
            // make sure that client is functional
            var dirProperties = await parentDirClient.GetPropertiesAsync();

            // Assert
            Assert.AreEqual(fileClient.Path.GetParentPath(), parentDirClient.Path);
            Assert.AreEqual(fileClient.AccountName, parentDirClient.AccountName);
            Assert.IsNotNull(dirProperties);
        }
Example #22
0
        protected AsyncUploaderBase(ShareFileClient client, UploadSpecificationRequest uploadSpecificationRequest, IPlatformFile file, FileUploaderConfig config = null, int?expirationDays = null)
            : base(client, uploadSpecificationRequest, file, expirationDays)
        {
            Config = config ?? new FileUploaderConfig();

            HashProvider = MD5HashProviderFactory.GetHashProvider().CreateHash();
        }
        /// <summary>
        /// Upload contents recursively
        /// </summary>
        private void UploadRecursive(ShareFileClient client, int uploadId, FileSystemInfo source, Models.Item target, ActionType actionType)
        {
            if (source is DirectoryInfo)
            {
                var newFolder = new Models.Folder()
                {
                    Name = source.Name
                };
                bool isExist = false;

                if (Synchronize)
                {
                    try
                    {
                        string path = String.Format("/{0}", source.Name);
                        Item   item = null;
                        try
                        {
                            item = client.Items.ByPath(target.url, path).Execute();
                        }
                        catch (ODataException e)
                        {
                            if (e.Code != System.Net.HttpStatusCode.NotFound)
                            {
                                throw e;
                            }
                        }

                        if (item != null && item is Folder)
                        {
                            isExist   = true;
                            newFolder = (Folder)item;
                        }
                    }
                    catch { }
                }

                if (!isExist)
                {
                    newFolder = client.Items.CreateFolder(target.url, newFolder, OverWrite, false).Execute();
                }

                ActionManager actionManager = new ActionManager(this, source.Name);

                foreach (var fsInfo in ((DirectoryInfo)source).EnumerateFileSystemInfos())
                {
                    if (fsInfo is DirectoryInfo && Recursive)
                    {
                        UploadRecursive(client, uploadId, fsInfo, newFolder, actionType);
                    }
                    else if (fsInfo is FileInfo)
                    {
                        IAction uploadAction = new UploadAction(FileSupport, client, fsInfo, newFolder, Details, actionType);
                        actionManager.AddAction(uploadAction);
                    }
                }

                actionManager.Execute();
            }
        }
        public async Task <string> SaveFileUri(string fileShare, string fileName, string fileContent)
        {
            ShareClient share = new ShareClient(connectionString, fileShare);

            if (!share.Exists())
            {
                share.Create();
            }
            ShareDirectoryClient rootDir = share.GetRootDirectoryClient();
            ShareFileClient      file    = rootDir.GetFileClient(fileName);

            if (!file.Exists())
            {
                file.Create(fileContent.Length);
            }

            byte[] outBuff = Encoding.ASCII.GetBytes(fileContent);
            ShareFileOpenWriteOptions options = new ShareFileOpenWriteOptions {
                MaxSize = outBuff.Length
            };
            var stream = await file.OpenWriteAsync(true, 0, options);

            stream.Write(outBuff, 0, outBuff.Length);
            stream.Flush();
            return(file.Uri.ToString());
        }
Example #25
0
        public static void WriteFile(string fullPath, string output, Boolean append)
        {
            ShareFileClient file = new ShareFileClient(CONNECTIONSTRING, SHARENAME, fullPath);

            string original = "";

            if (!append && file.Exists())
            {
                file.Delete();
            }
            if (append)
            {
                if (file.Exists())
                {
                    ShareFileDownloadInfo download = file.Download();
                    original = GetStreamContents(download.Content) + "\n";
                }
            }

            using (Stream outStream = GenerateStreamFromString(original + output)) {
//                if (!file.Exists())
                file.Create(outStream.Length);
                file.UploadRange(new HttpRange(0, outStream.Length), outStream);
            }
        }
        public static void AddDefaultHeaders(this HttpRequestMessage requestMessage, ShareFileClient client)
        {
            if (client.Configuration.SupportedCultures != null)
            {
                foreach (var cultureInfo in client.Configuration.SupportedCultures)
                {
                    requestMessage.Headers.AcceptLanguage.Add(new StringWithQualityHeaderValue(cultureInfo.Name));
                }
            }

            if (client.Configuration.ClientCapabilities != null)
            {
                var provider = ShareFileClient.GetProvider(requestMessage.RequestUri);
                IEnumerable<ClientCapability> clientCapabilities;
                if (client.Configuration.ClientCapabilities.TryGetValue(provider, out clientCapabilities))
                {
                    requestMessage.Headers.Add(BaseRequestProvider.Headers.ClientCapabilities, clientCapabilities.Select(x => x.ToString()));
                }
            }

            if (client.Configuration.UserAgent != null)
            {
                requestMessage.Headers.Add("User-Agent", client.Configuration.UserAgent);
            }

            requestMessage.TryAddCookies(client);
        }
Example #27
0
        public List <Metadata> GetMetadatas()
        {
            List <Metadata> metadatas = new List <Metadata>();

            MetadataParser parser =
                new MetadataParser(
                    new MetadataConverter());

            try
            {
                var remaining = new Queue <ShareDirectoryClient>();

                remaining.Enqueue(shareClient.GetDirectoryClient(this.path));
                while (remaining.Count > 0)
                {
                    ShareDirectoryClient dir = remaining.Dequeue();
                    foreach (ShareFileItem item in dir.GetFilesAndDirectories())
                    {
                        if (item.IsDirectory)
                        {
                            remaining.Enqueue(dir.GetSubdirectoryClient(item.Name));
                        }
                        else if (item.Name.Contains(FILE_EXTENSION))
                        {
                            Console.WriteLine($"  In {dir.Uri.AbsolutePath} found {item.Name}");

                            ShareFileClient file = dir.GetFileClient(item.Name);

                            ShareFileDownloadInfo fileContents = file.Download();
                            string json;
                            using (MemoryStream ms = new MemoryStream())
                            {
                                fileContents.Content.CopyTo(ms);
                                json = Encoding.UTF8.GetString(ms.ToArray());
                            }

                            // Parse json string
                            Metadata metadata = parser.Parse(json);

                            // Sets the dataset path relative to the Uri and Path specified in constructor
                            var filePath =
                                Path.GetRelativePath(this.path, file.Path)
                                .Replace(FILE_EXTENSION, "");

                            metadata.Dataset.DatasetPath = filePath;

                            metadatas.Add(metadata);
                        }
                    }
                }

                Console.WriteLine($"Found a total of {metadatas.Count} files");
            }
            catch (Exception e)
            {
                Console.WriteLine($"An error ocurred: {e}");
            }

            return(metadatas);
        }
        // Convert Track1 File object to Track 2 file Client
        public static ShareFileClient GetTrack2FileClient(CloudFile cloudFile, AzureStorageContext context)
        {
            ShareFileClient fileClient;

            if (cloudFile.ServiceClient.Credentials.IsSAS) //SAS
            {
                string sas     = Util.GetSASStringWithoutQuestionMark(cloudFile.ServiceClient.Credentials.SASToken);
                string fullUri = cloudFile.SnapshotQualifiedUri.ToString();
                if (cloudFile.Share.IsSnapshot)
                {
                    // Since snapshot URL already has '?', need remove '?' in the first char of sas
                    fullUri = fullUri + "&" + sas;
                }
                else
                {
                    fullUri = fullUri + "?" + sas;
                }
                fileClient = new ShareFileClient(new Uri(fullUri));
            }
            else if (cloudFile.ServiceClient.Credentials.IsSharedKey) //Shared Key
            {
                fileClient = new ShareFileClient(cloudFile.SnapshotQualifiedUri,
                                                 new StorageSharedKeyCredential(context.StorageAccountName, cloudFile.ServiceClient.Credentials.ExportBase64EncodedKey()));
            }
            else //Anonymous
            {
                fileClient = new ShareFileClient(cloudFile.SnapshotQualifiedUri);
            }

            return(fileClient);
        }
        public async Task <string> ReadFile(string fileShare, string fileName)
        {
            string      json  = "";
            ShareClient share = new ShareClient(connectionString, fileShare);

            if (!share.Exists())
            {
                Exception error = new Exception($"Fileshare {fileName} does not exist ");
                throw error;
            }
            ShareDirectoryClient directory = share.GetRootDirectoryClient();
            ShareFileClient      file      = directory.GetFileClient(fileName);

            if (file.Exists())
            {
                using (Stream fileStream = await file.OpenReadAsync())
                {
                    using (StreamReader reader = new StreamReader(fileStream))
                    {
                        json = reader.ReadToEnd();
                    }
                }
            }
            else
            {
                Exception error = new Exception($"File {fileName} does not exist in Azure storage ");
                throw error;
            }
            return(json);
        }
Example #30
0
        public static async Task CreateFileAsync(string account, string key, string share, string fileName, Stream fileContent, string folder = null)
        {
            ShareFileClient file = GetShareFileClient(account, key, share, fileName, folder);

            file.Create(fileContent.Length);
            await file.UploadRangeAsync(new HttpRange(0, fileContent.Length), fileContent);
        }
Example #31
0
        private static async Task MoveFileAsync(ShareClient share, ShareDirectoryClient directory, ShareFileClient file, string outputFolder)
        {
            try
            {
                ShareDirectoryClient outputDirectory = share.GetDirectoryClient(outputFolder);

                await outputDirectory.CreateIfNotExistsAsync();

                if (outputDirectory.Exists())
                {
                    ShareFileClient outputFile = outputDirectory.GetFileClient(file.Name);
                    await outputFile.StartCopyAsync(file.Uri);

                    if (await outputFile.ExistsAsync())
                    {
                        Log($"{file.Uri} copied to {outputFile.Uri}");
                        await DeleteFileAsync(file);
                    }
                }
            }
            catch (Exception ex)
            {
                Log(ex);
            }
        }
Example #32
0
        protected IShareFileClient GetShareFileClient()
        {
            try
            {
                using (var fileStream = System.IO.File.OpenRead("TestConfig.json"))
                    using (var streamReader = new StreamReader(fileStream))
                    {
                        var info     = streamReader.ReadToEnd();
                        var userInfo = JsonConvert.DeserializeObject <UserInfo>(info);

                        var sfClient = new ShareFileClient(userInfo.GetBaseUri().ToString());

                        lock (oauthTokenLock)
                        {
                            if (token == null)
                            {
                                var oauthService = new OAuthService(sfClient, userInfo.ClientId, userInfo.ClientSecret);
                                token = oauthService.GetPasswordGrantRequestQuery(userInfo.Email, userInfo.Password, userInfo.Subdomain, userInfo.Domain).Execute();
                            }
                        }

                        sfClient.BaseUri = token.GetUri();
                        sfClient.AddOAuthCredentials(token);
                        return(sfClient);
                    }
            }
            catch (Exception exception)
            {
                Assert.Inconclusive(string.Format("No UserInfo found in TestConfig.json. Exception: {0}", exception));
                throw;
            }
        }
        /// <summary>
        /// Delete the Sharefile items if Move flag is used
        /// </summary>
        private void DeleteShareFileItemRecursive(ShareFileClient client, Models.Item source, bool deleteFolder)
        {
            if (source is Models.Folder)
            {
                var children     = (source as Folder).Children;
                var childFiles   = children.OfType <Models.File>();
                var childFolders = children.OfType <Models.Folder>();

                RemoveShareFileItems(client, source, childFiles);

                if (Recursive)
                {
                    foreach (var childFolder in childFolders)
                    {
                        DeleteShareFileItemRecursive(client, childFolder, !KeepFolders);
                    }
                }

                if (deleteFolder)
                {
                    if (!HasChildren(client, source as Models.Folder))
                    {
                        RemoveShareFileItem(client, source);
                    }
                }
            }

            if (source is Models.File)
            {
                RemoveShareFileItem(client, source);
            }
        }
 public AsyncScalingFileUploader(ShareFileClient client, UploadSpecificationRequest uploadSpecificationRequest, IPlatformFile file, FileUploaderConfig config = null, int? expirationDays = null)
     : base(client, uploadSpecificationRequest, file, config, expirationDays)
 {
     UploadSpecificationRequest.Raw = true;
     var chunkConfig = config != null ? config.PartConfig : new FilePartConfig();
     partUploader = new ScalingPartUploader(chunkConfig, Config.NumberOfThreads,
         ExecuteChunkUploadMessage,
         OnProgress);        
 }
Example #35
0
        protected UploaderBase(ShareFileClient client, UploadSpecificationRequest uploadSpecificationRequest, IPlatformFile file, int? expirationDays)
        {
            Client = client;
            UploadSpecificationRequest = uploadSpecificationRequest;
            File = file;

            ExpirationDays = expirationDays;
            Progress = new TransferProgress(uploadSpecificationRequest.FileSize, null, Guid.NewGuid().ToString());
        }
 public ScalingFileUploader(ShareFileClient client, UploadSpecificationRequest uploadSpecificationRequest, IPlatformFile file, FileUploaderConfig config = null, int? expirationDays = null)
     : base(client, uploadSpecificationRequest, file, config, expirationDays)
 {
     UploadSpecificationRequest.Raw = true;
     var partConfig = config != null ? config.PartConfig : new FilePartConfig();
     partUploader = new ScalingPartUploader(partConfig, Config.NumberOfThreads,
         requestMessage => Task.Factory.StartNew(() => ExecuteChunkUploadMessage(requestMessage)),
         OnProgress);
 }
        public void GetAliasWithMappedAlias(ItemAlias alias, string expectedValue)
        {
            // Act
            var sfClient = new ShareFileClient("https://secure.sf-api.com/sf/v3/");
            var uri = sfClient.Items.GetAlias(alias);

            // Assert
            uri.ToString().Should().Be("https://secure.sf-api.com/sf/v3/Items(" + expectedValue + ")");
        }
Example #38
0
        protected IShareFileClient GetShareFileClient(bool registerFakeExecutors = false)
        {
            var client = new ShareFileClient(BaseUriString);

            if (registerFakeExecutors)
            {
                RequestExecutorFactory.RegisterAsyncRequestProvider(A.Fake<IAsyncRequestExecutor>());
                RequestExecutorFactory.RegisterSyncRequestProvider(A.Fake<ISyncRequestExecutor>());
            }

            return client;
        }
        public void GetAliasWithItemId()
        {
            // Arrange
            var alias = "randomId";

            // Act
            var sfClient = new ShareFileClient("https://secure.sf-api.com/sf/v3/");
            var uri = sfClient.Items.GetAlias(alias);

            // Assert
            uri.ToString().Should().Be("https://secure.sf-api.com/sf/v3/Items(randomId)");
        }
        public LoggingConverter(ShareFileClient client)
        {
            this._client = client;

            _piiBlacklist = new HashSet<string>();
            _piiBlacklist.Add("FullName");
            _piiBlacklist.Add("FirstName");
            _piiBlacklist.Add("LastName");
            _piiBlacklist.Add("Email");
            _piiBlacklist.Add("Username");
            _piiBlacklist.Add("FullNameShort");
            _piiBlacklist.Add("Name");
            _piiBlacklist.Add("FileName");
            _piiBlacklist.Add("CreatorFirstName");
            _piiBlacklist.Add("CreatorLastName");
            _piiBlacklist.Add("CreatorNameShort");
            _piiBlacklist.Add("Company");
        }
        public static void TryAddCookies(this HttpRequestMessage requestMessage, ShareFileClient client)
        {
            if (BaseRequestProvider.RuntimeRequiresCustomCookieHandling)
            {
                var cookieHeader = client.CookieContainer.GetCookieHeader(
                    new Uri("https://www." + requestMessage.RequestUri.Host + requestMessage.RequestUri.AbsolutePath));

                if (!string.IsNullOrWhiteSpace(cookieHeader))
                {
                    requestMessage.Headers.Add("Cookie", cookieHeader);
                }
                else
                {
                    cookieHeader = client.CookieContainer.GetCookieHeader(requestMessage.RequestUri);
                    if (!string.IsNullOrEmpty(cookieHeader))
                    {
                        requestMessage.Headers.Add("Cookie", cookieHeader);
                    }
                }
            }
        }
        public void VerifyTypeOverrideSupport()
        {
            var test = new ShareFileClient(BaseUriString);
            test.RegisterType<FolderTestClass, Folder>();

            var folder = GetFolder();
            folder.MetadataUrl =
                "https://labs.sf-api.com/sf/v3/$metadata#ShareFile.Api.Models.Folder";
            folder.Children.First().MetadataUrl =
                "https://labs.sf-api.com/sf/v3/$metadata#ShareFile.Api.Models.File";

            var serializer = GetSerializer();

            StringWriter writer = new StringWriter();
            serializer.Serialize(writer, folder);

            var jsonReader = new JsonTextReader(new StringReader(writer.ToString()));

            var item = serializer.Deserialize<Item>(jsonReader);
            item.GetType().Should().Be(typeof (FolderTestClass));
        }
 public AsyncStandardFileUploader(ShareFileClient client, UploadSpecificationRequest uploadSpecificationRequest, IPlatformFile file, FileUploaderConfig config = null, int? expirationDays = null) 
     : base(client, uploadSpecificationRequest, file, config, expirationDays)
 {
     UploadSpecificationRequest.Raw = true;
 }