public static async Task <string> uploadImage(string data, string fileName)
        {
            // Retrieve storage account information from connection string
            // How to create a storage connection string - http://msdn.microsoft.com/en-us/library/azure/ee758697.aspx
            CloudStorageAccount storageAccount = CreateStorageAccountFromConnectionString(ConfigurationManager.AppSettings["StorageConnectionString"]);

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

            CloudFileShare share = fileClient.GetShareReference(ConfigurationManager.AppSettings["FileShare"]);

            try
            {
                await share.CreateIfNotExistsAsync();
            }
            catch (StorageException)
            {
                throw;
            }

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

            // Create a directory under the root directory
            CloudFileDirectory dir = root.GetDirectoryReference(Guid.NewGuid().ToString());
            await dir.CreateIfNotExistsAsync();

            CloudFile file = dir.GetFileReference(data);
            await file.UploadFromFileAsync(fileName);

            return(file.Uri.AbsoluteUri);
        }
        public async Task <ActionResult> SelectSampleDataSource(MainViewModel main)
        {
            main.SelectedDataSourceName = main.SelectedSampleDataSourceName;

            string fileName = main.SelectedDataSourceName.Split('/').Last();

            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(_configuration.GetConnectionString("StorageConnectionString"));

            // 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 cloudFileShare = fileClient.GetShareReference("samples");

            await cloudFileShare.CreateIfNotExistsAsync();

            CloudFileDirectory cloudFileDirectory = cloudFileShare.GetRootDirectoryReference();

            CloudFile cloudFile = cloudFileDirectory.GetFileReference(fileName);

            MemoryStream stream = new MemoryStream();

            await cloudFile.DownloadToStreamAsync(stream);

            stream.Position = 0;

            StreamReader reader = new StreamReader(stream);

            main.RawData = reader.ReadToEnd();

            //Copied raw data to processed data in case user skips the pre-processing/cleansing step
            main.ProcessedData = main.RawData;

            return(PartialView("_DisplayDataSource", main));
        }
Beispiel #3
0
        public async Task <bool> OpenAsync()
        {
            if (_isOpen)
            {
                return(true);
            }

            var result = await _cloudFileShare.CreateIfNotExistsAsync().ConfigureAwait(false);

            _cloudRootDirectory = _cloudFileShare.GetRootDirectoryReference();

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

            //// Get existing permissions for the share.
            //var permissions = _cloudFileShare.GetPermissions();

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

            _isOpen = true;

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

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

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

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

            while (n < directories.Count)
            {
                dir = dir.GetDirectoryReference(directories[n]);
                dir.CreateIfNotExistsAsync().GetAwaiter().GetResult();
                n = n + 1;
            }
            result = new CloudFileItemDirectory(dir, scfg);
            return(result);
        }
        public async Task SaveFile(string uniqueFileName, IFormFile file)
        {
            LogManager.LogStartFunction(MethodBase.GetCurrentMethod().DeclaringType.ToString(), MethodBase.GetCurrentMethod().Name);

            CloudFileClient fileClient = _cFileStorageAccount.CreateCloudFileClient();

            //get the share reference (on the storage)
            CloudFileShare ExistingShare = fileClient.GetShareReference(_FUSettings.ShareFolder);

            try
            {
                await ExistingShare.CreateIfNotExistsAsync();
            }
            catch (StorageException ex)
            {
                //Console.WriteLine("Please make sure your storage account has storage file endpoint enabled and specified correctly in the app.config - then restart the sample.");
                //Console.WriteLine("Press any key to exit");
                //Console.ReadLine();
                LogManager.LogError(MethodBase.GetCurrentMethod().DeclaringType.ToString(), MethodBase.GetCurrentMethod().Name, ex, "Please make sure your storage account has storage file endpoint enabled and specified correctly in the app.config - then restart the sample.");
                //throw(ex);
            }

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

            await shareRoot.GetFileReference(uniqueFileName).UploadFromStreamAsync(file.OpenReadStream());
        }
Beispiel #6
0
        void saveAzureFile(byte[] file, string filePath, CloudStorageAccount storageAccount)
        {
            string[] pathParts = filePath.Split('/');

            CloudFileClient fileClient = storageAccount.CreateCloudFileClient();

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

            share.CreateIfNotExistsAsync().Wait();



            CloudFileDirectory cloudFileDirectory = share.GetRootDirectoryReference();

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

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

            //Upload the file to Azure.
            cloudFile.UploadFromByteArrayAsync(file, 0, file.Length, null, null, null).Wait();
        }
Beispiel #7
0
        private async Task <CloudFile> GetFileReferenceAsync(string fullPath, bool createParents, CancellationToken cancellationToken)
        {
            string[] parts = StoragePath.Split(fullPath);
            if (parts.Length == 0)
            {
                return(null);
            }

            string shareName = parts[0];

            CloudFileShare share = _client.GetShareReference(shareName);

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

            CloudFileDirectory dir = share.GetRootDirectoryReference();

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

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

            return(dir.GetFileReference(parts[parts.Length - 1]));
        }
        public async Task <IActionResult> DeleteConfirmed(string id)
        {
            var sampleDataSource = await _context.SampleDataSources.FindAsync(id);

            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(_configuration.GetConnectionString("StorageConnectionString"));

            // 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 cloudFileShare = fileClient.GetShareReference("samples");
            await cloudFileShare.CreateIfNotExistsAsync();

            CloudFileDirectory cloudFileDirectory = cloudFileShare.GetRootDirectoryReference();

            string cloudFilename = sampleDataSource.Uri.Split("/").Last();

            CloudFile cloudFile = cloudFileDirectory.GetFileReference(cloudFilename);
            await cloudFile.DeleteIfExistsAsync();


            _context.SampleDataSources.Remove(sampleDataSource);

            await _context.SaveChangesAsync();

            return(RedirectToAction(nameof(Index)));
        }
        public static async void FileTransferAsync(string azurename, string requestBody, Account account)
        {
            string acctName         = System.Environment.GetEnvironmentVariable("AcctName", EnvironmentVariableTarget.Process);
            string acctKey          = System.Environment.GetEnvironmentVariable("AcctKey", EnvironmentVariableTarget.Process);
            string container        = System.Environment.GetEnvironmentVariable("Container", EnvironmentVariableTarget.Process);
            string directory        = System.Environment.GetEnvironmentVariable("Directory", EnvironmentVariableTarget.Process);
            string connectionString = $"DefaultEndpointsProtocol=https;AccountName={acctName};AccountKey={acctKey}";

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

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

                CloudFile cloudFile = azureDir.GetFileReference(azurename);
                await cloudFile.UploadTextAsync(requestBody);
            }
            catch (Exception e)
            {
                account.fatalException = e.Message;
            }
        }
    /// <summary>
    /// Create the references necessary to log into Azure
    /// </summary>
    private async void CreateCloudIdentityAsync()
    {
        // Retrieve storage account information from connection string
        storageAccount = CloudStorageAccount.Parse(storageConnectionString);
        // Create a file client for interacting with the file service.
        fileClient = storageAccount.CreateCloudFileClient();
        // Create a share for organizing files and directories within the storage account.
        share = fileClient.GetShareReference(fileShare);
        await share.CreateIfNotExistsAsync();

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

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

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

            azureStatusText.text = "No Shape\nFile!";
        }
        else
        {              // The file has been found, disable gaze and get the list from the file
            Gaze.instance.enableGaze = false; azureStatusText.text = "Shape File\nFound!";
            await ReplicateListFromAzureAsync();
        }
    }
Beispiel #11
0
        public async override Task <IContainerGroup> CreateResourceAsync(CancellationToken cancellationToken)
        {
            ContainerGroupImpl self = this;

            if (IsInCreateMode)
            {
                if (this.creatableStorageAccountKey != null && this.newFileShares != null && this.newFileShares.Count > 0)
                {
                    // Creates the new Azure file shares
                    var storageAccount = this.CreatedResource(this.creatableStorageAccountKey) as IStorageAccount;
                    if (this.Inner.Volumes == null)
                    {
                        this.Inner.Volumes = new List <Volume>();
                    }
                    var storageAccountKey = (await storageAccount.GetKeysAsync())[0].Value;
                    var sas             = $"DefaultEndpointsProtocol=https;AccountName={storageAccount.Name};AccountKey={storageAccountKey};EndpointSuffix=core.Windows.Net";
                    var cloudFileClient = CloudStorageAccount.Parse(sas).CreateCloudFileClient();
                    foreach (var fileShare in this.newFileShares)
                    {
                        CloudFileShare cloudFileShare = cloudFileClient.GetShareReference(fileShare.Value);
                        await cloudFileShare.CreateIfNotExistsAsync();

                        this.Inner.Volumes.Add(new Volume
                        {
                            Name      = fileShare.Key,
                            AzureFile = new AzureFileVolume
                            {
                                ShareName          = fileShare.Value,
                                ReadOnlyProperty   = false,
                                StorageAccountName = storageAccount.Name,
                                StorageAccountKey  = storageAccountKey
                            }
                        });
                    }
                }

                var inner = await this.Manager.Inner.ContainerGroups.CreateOrUpdateAsync(this.ResourceGroupName, this.Name, this.Inner, cancellationToken);

                SetInner(inner);
                this.InitializeChildrenFromInner();

                return(this);
            }
            else
            {
                var resourceInner = new ResourceInner();
                resourceInner.Location = this.RegionName;
                resourceInner.Tags     = this.Inner.Tags;
                var updatedInner = await this.Manager.Inner.ContainerGroups.UpdateAsync(this.ResourceGroupName, this.Name, resourceInner, cancellationToken : cancellationToken);

                // TODO: this will go away after service fixes the update bug
                updatedInner = await this.GetInnerAsync(cancellationToken);

                SetInner(updatedInner);
                this.InitializeChildrenFromInner();

                return(this);
            }
        }
    protected void Button1_Click(object sender, EventArgs e)
    {
        CloudStorageAccount account = CloudStorageAccount.Parse(this.connString);
        CloudFileClient     client  = account.CreateCloudFileClient();
        CloudFileShare      share   = client.GetShareReference("birklasor");

        share.CreateIfNotExistsAsync().Wait();
    }
Beispiel #13
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();

                // Create directory
                Console.WriteLine("Create directory");
                await rootDirectory.CreateIfNotExistsAsync();

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

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

                Console.WriteLine("Get directory metadata:");
                foreach (var keyValue in rootDirectory.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();
            }
        }
Beispiel #14
0
        /// <summary>
        /// Get a CloudFile instance with the specified name in the given share.
        /// </summary>
        /// <param name="shareName">Share name.</param>
        /// <param name="fileName">File name.</param>
        /// <returns>A <see cref="Task{T}"/> object of type <see cref="CloudFile"/> that represents the asynchronous operation.</returns>
        public static async Task <CloudFile> GetCloudFileAsync(string shareName, string fileName, string accountName, string accountKey)
        {
            CloudFileClient client = GetCloudFileClient(accountName, accountKey);
            CloudFileShare  share  = client.GetShareReference(shareName);
            await share.CreateIfNotExistsAsync();

            CloudFileDirectory rootDirectory = share.GetRootDirectoryReference();

            return(rootDirectory.GetFileReference(fileName));
        }
        public async Task <ActionResult> CreateNewDataSource(MainViewModel main, IFormFile DataFile)
        {
            DataSource dataSource = main.SelectedDataSource;

            dataSource.DataFile = DataFile;

            if (dataSource == null ||
                dataSource.DataFile == null || dataSource.DataFile.Length == 0)
            {
                return(Content("file not selected"));
            }

            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(_configuration.GetConnectionString("StorageConnectionString"));

            // 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 cloudFileShare = fileClient.GetShareReference(GetCurrentUserAsync().Result.Id);
            await cloudFileShare.CreateIfNotExistsAsync();

            CloudFileDirectory cloudFileDirectory = cloudFileShare.GetRootDirectoryReference();


            CloudFile cloudFile = cloudFileDirectory.GetFileReference(dataSource.DataFile.FileName);
            await cloudFile.DeleteIfExistsAsync();

            using (var stream = new MemoryStream())
            {
                await dataSource.DataFile.CopyToAsync(stream);

                stream.Seek(0, SeekOrigin.Begin);
                await cloudFile.UploadFromStreamAsync(stream);

                stream.Seek(0, SeekOrigin.Begin);
                StreamReader reader = new StreamReader(stream);
                main.RawData = reader.ReadToEnd();
                main.SelectedDataSourceName = dataSource.DataFile.FileName;
            }

            dataSource.Uri         = cloudFile.Uri.ToString();
            dataSource.CreatedBy   = GetCurrentUserAsync().Result;
            dataSource.CreatedDate = System.DateTime.Now;

            _context.Add(dataSource);

            await _context.SaveChangesAsync();

            main.SelectedDataSourceName = cloudFile.Uri.ToString();

            //Copied raw data to processed data in case user skips the pre-processing/cleansing step
            main.ProcessedData = main.RawData;

            return(PartialView("~/Views/Main/_DisplayDataSource.cshtml", main));
        }
Beispiel #16
0
        protected FileStore(string storageConnectionString, string storageName, IJsonConverter jsonConverter,
                            ISecurityService securityService)
        {
            _jsonConverter   = jsonConverter;
            _securityService = securityService;
            var storageAccount = CloudStorageAccount.Parse(storageConnectionString);
            var fileClient     = storageAccount.CreateCloudFileClient();

            _fileShare = fileClient.GetShareReference(storageName);
            _fileShare.CreateIfNotExistsAsync();
        }
Beispiel #17
0
        public async Task <IActionResult> Create([Bind("Id,Name,Description,Uri,TypeId,CreatedDate,DataFile")] DataSource dataSource)
        {
            if (ModelState.IsValid)
            {
                if (dataSource == null ||
                    dataSource.DataFile == null || dataSource.DataFile.Length == 0)
                {
                    return(Content("file not selected"));
                }

                CloudStorageAccount storageAccount = CloudStorageAccount.Parse(_configuration.GetConnectionString("StorageConnectionString"));

                // 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 cloudFileShare = fileClient.GetShareReference(GetCurrentUserAsync().Result.Id);
                await cloudFileShare.CreateIfNotExistsAsync();

                CloudFileDirectory cloudFileDirectory = cloudFileShare.GetRootDirectoryReference();

                CloudFile cloudFile = cloudFileDirectory.GetFileReference(dataSource.DataFile.FileName);
                await cloudFile.DeleteIfExistsAsync();

                using (var stream = new MemoryStream())
                {
                    await dataSource.DataFile.CopyToAsync(stream);

                    stream.Seek(0, SeekOrigin.Begin);
                    await cloudFile.UploadFromStreamAsync(stream);
                }

                dataSource.Uri         = cloudFile.Uri.ToString();
                dataSource.CreatedBy   = GetCurrentUserAsync().Result;
                dataSource.CreatedDate = System.DateTime.Now;

                _context.Add(dataSource);

                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            var plan         = _context.Organizations.Where(y => y.Id == GetCurrentUserAsync().Result.OrganizationId).Select(z => z.SelectedPlanId);
            var connectors   = _context.PlanDataConnectors.Where(y => y.PlanId == plan.First()).Select(z => z.DataSourceConnectorId);
            var connectorIds = String.Join(',', connectors.ToArray());

            ViewBag.AvailableDataConnectors = _context.DataSourceConnectors.Where(y => connectorIds.Contains(y.Id)).ToList();

            ViewBag.SelectedDataSource = dataSource;

            return(View(dataSource));
        }
Beispiel #18
0
        /// <summary>
        /// Manage share properties
        /// </summary>
        /// <param name="cloudFileClient"></param>
        /// <returns></returns>
        private static async Task SharePropertiesSample(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);

            // Set share properties
            Console.WriteLine("Set share properties");
            share.Properties.Quota = 100;

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

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

                Console.WriteLine("Get share properties:");
                Console.WriteLine("    Quota: {0}", share.Properties.Quota);
                Console.WriteLine("    ETag: {0}", share.Properties.ETag);
                Console.WriteLine("    Last modified: {0}", share.Properties.LastModified);
            }
            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();
            }
            Console.WriteLine();
        }
        private async Task <CloudFileShare> GetOrCreateShareAsync(CloudStorageAccount account)
        {
            CloudFileClient client = account.CreateCloudFileClient();
            CloudFileShare  share  = client.GetShareReference(storage.ShareName);

            await share.CreateIfNotExistsAsync();

            if (!await share.ExistsAsync())
            {
                throw new UploadFailedException($"Share {storage.ShareName} does not exist and could not be created.");
            }

            return(share);
        }
        public async Task SaveSignedFile(string uniqueFileName, IFormFile file)
        {
            LogManager.LogStartFunction(MethodBase.GetCurrentMethod().DeclaringType.ToString(), MethodBase.GetCurrentMethod().Name);

            CloudFileClient fileClient = _cSignedFileStorageAccount.CreateCloudFileClient();

            CloudFileShare ExistingShare = fileClient.GetShareReference(_SignedFUSettings.ShareFolder);

            await ExistingShare.CreateIfNotExistsAsync();

            CloudFileDirectory shareRoot = ExistingShare.GetRootDirectoryReference();

            await shareRoot.GetFileReference(uniqueFileName).UploadFromStreamAsync(file.OpenReadStream());
        }
Beispiel #21
0
        public async Task <List <string> > ListFiles(string shareName, string folder)
        {
            List <string> toReturn = new List <string>();

            try
            {
                CloudStorageAccount storageAccount  = CreateStorageAccountFromConnectionString(this.ConnectionString);
                CloudFileClient     cloudFileClient = storageAccount.CreateCloudFileClient();

                CloudFileShare cloudFileShare = cloudFileClient.GetShareReference(shareName);
                await cloudFileShare.CreateIfNotExistsAsync();

                CloudFileDirectory rootDirectory = cloudFileShare.GetRootDirectoryReference();
                CloudFileDirectory fileDirectory = null;
                if (!string.IsNullOrEmpty(folder))
                {
                    fileDirectory = rootDirectory.GetDirectoryReference(folder);
                }
                else
                {
                    fileDirectory = rootDirectory;
                }
                await fileDirectory.CreateIfNotExistsAsync();

                List <IListFileItem>  results = new List <IListFileItem>();
                FileContinuationToken token   = null;
                do
                {
                    FileResultSegment resultSegment = await fileDirectory.ListFilesAndDirectoriesSegmentedAsync(token);

                    results.AddRange(resultSegment.Results);
                    token = resultSegment.ContinuationToken;
                }while (token != null);

                foreach (var item in results)
                {
                    if (item.GetType() == typeof(CloudFile))
                    {
                        CloudFile file = (CloudFile)item;
                        toReturn.Add(file.Name);
                    }
                }
            }
            catch (Exception ex)
            {
                this.ErrorMessage = ex.ToString();
            }
            return(toReturn);
        }
        public AzureFileStorageTests(AzureStorageTestFixture fixture)
        {
            var storageAccount = fixture.StorageAccount;

            var storageClient = storageAccount.CreateCloudFileClient();

            var fileShareName = Guid.NewGuid().ToString();

            _fileShare = storageClient.GetShareReference(fileShareName);

            _fileShare.CreateIfNotExistsAsync()
            .GetAwaiter()
            .GetResult();

            _sut = new AzureFileStorage(storageClient, fileShareName);
        }
Beispiel #23
0
        private async Task CreateAzureFileStorage(string name, string connectionstring)
        {
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(connectionstring);
            CloudFileClient     fileClient     = storageAccount.CreateCloudFileClient();
            CloudFileShare      share          = fileClient.GetShareReference(name);

            try
            {
                await share.CreateIfNotExistsAsync();
            }
            catch (StorageException ex)
            {
                Console.WriteLine($"Error while creating storage account '{name}': {ex.Message}");
                throw;
            }
        }
Beispiel #24
0
        public async Task <bool> UploadImageToAzureStorage(HttpPostedFileBase image /*, HttpRequest request*/)
        {
            try
            {
                //Console.WriteLine("request.Files.Count: " + request.Files.Count);
                Console.WriteLine("image==null: " + image == null);
                Console.WriteLine(image == null ? "" : "image.ContentLength: " + image.ContentLength + ", image.ContentType: " + image.ContentType);

                if (/*request.Files != null && */ image != null && image.ContentLength != 0)
                {
                    string connectionString = ConfigurationManager.ConnectionStrings["AzureStorageConnectionString"].ConnectionString;
                    //Connect to Azure
                    CloudStorageAccount storageAccount = CloudStorageAccount.Parse(connectionString);

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

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

                    if (share.Exists())
                    {
                        // Generate a SAS for a file in the share
                        CloudFileDirectory rootDir            = share.GetRootDirectoryReference();
                        CloudFileDirectory cloudFileDirectory = rootDir.GetDirectoryReference("organizationlogos");
                        await cloudFileDirectory.CreateIfNotExistsAsync();

                        CloudFile cloudFile = cloudFileDirectory.GetFileReference(image.FileName);

                        Stream fileStream = image.InputStream;

                        cloudFile.UploadFromStream(fileStream);
                        fileStream.Dispose();
                    }
                }

                return(true);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.StackTrace);
                //throw ex;
                return(false);
            }
        }
        public async Task Test_Azure_File_Storage_Upload()
        {
            CloudFileShare shareReference =
                this._cloudFileClient.GetShareReference("test232323");

            bool created = await shareReference.CreateIfNotExistsAsync();

            Check.That(created).IsFalse();

            var root = shareReference.GetRootDirectoryReference();

            var file = root.GetFileReference("microsoft-logo.png");

            string filePath = System.IO.Path.Combine(@"C:\Users\jindev\Desktop", file.Name);

            await file.UploadFromFileAsync(filePath);
        }
        public async Task <IActionResult> Create([Bind("Id,Name,Description,Uri,TypeId,CreatedDate,DataFile")] SampleDataSource sampleDataSource)
        {
            if (ModelState.IsValid)
            {
                if (sampleDataSource == null ||
                    sampleDataSource.DataFile == null || sampleDataSource.DataFile.Length == 0)
                {
                    return(Content("file not selected"));
                }

                CloudStorageAccount storageAccount = CloudStorageAccount.Parse(_configuration.GetConnectionString("StorageConnectionString"));

                // 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 cloudFileShare = fileClient.GetShareReference("samples");
                await cloudFileShare.CreateIfNotExistsAsync();

                CloudFileDirectory cloudFileDirectory = cloudFileShare.GetRootDirectoryReference();

                CloudFile cloudFile = cloudFileDirectory.GetFileReference(sampleDataSource.DataFile.FileName);
                await cloudFile.DeleteIfExistsAsync();

                using (var stream = new MemoryStream())
                {
                    await sampleDataSource.DataFile.CopyToAsync(stream);

                    stream.Seek(0, SeekOrigin.Begin);
                    await cloudFile.UploadFromStreamAsync(stream);
                }

                sampleDataSource.Uri         = cloudFile.Uri.ToString();
                sampleDataSource.CreatedBy   = GetCurrentUserAsync().Result;
                sampleDataSource.CreatedDate = System.DateTime.Now;

                _context.Add(sampleDataSource);

                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            ViewBag.AvailableDataConnectors = _context.DataSourceConnectors.ToList();
            return(View(sampleDataSource));
        }
        public async Task UploadFile(Stream fileStream, string clientId, string filename)
        {
            this.Init();

            //GET share & create if needed
            CloudFileShare share = _cloudFileClient.GetShareReference(this._fileStorageOptions.ShareName);
            await share.CreateIfNotExistsAsync();

            try
            {
                //Get root directory & create if needed
                CloudFileDirectory rootDirectory = share.GetRootDirectoryReference();
                await rootDirectory.CreateIfNotExistsAsync();

                //Get clients directory & create if needed
                CloudFileDirectory clientsFolder = rootDirectory.GetDirectoryReference(clientId);
                await clientsFolder.CreateIfNotExistsAsync();

                //Get reference to file
                //If file already exists it will be overwritten
                CloudFile file = clientsFolder.GetFileReference(filename);

                //Upload file
                Stopwatch s = Stopwatch.StartNew();
                await file.UploadFromStreamAsync(fileStream);
            }
            catch (StorageException exStorage)
            {
                this._logger.LogError("Storage error ", exStorage);
                throw new ServiceOperationException("Could not upload file.[storage]");
            }
            catch (Exception ex)
            {
                this._logger.LogError("General error ", ex);
                throw new ServiceOperationException("Could not upload file.[general]");
            }
            finally
            {
                //Do cleanup if needed
            }
        }
Beispiel #28
0
        /// <summary>
        /// Get a CloudFile instance with the specified name in the given share.
        /// </summary>
        /// <param name="shareName">Share name.</param>
        /// <param name="fileName">File name.</param>
        /// <returns>A <see cref="Task{T}"/> object of type <see cref="CloudFile"/> that represents the asynchronous operation.</returns>
        public async Task <CloudFile> GetCloudFileAsync(string shareName, string fileName)
        {
            using (Operation azOp = L.Begin("Get Azure Storage file share"))
            {
                try
                {
                    CloudFileClient client = GetCloudFileClient();
                    CloudFileShare  share  = client.GetShareReference(shareName);
                    await share.CreateIfNotExistsAsync();

                    CloudFileDirectory rootDirectory = share.GetRootDirectoryReference();
                    CloudFile          file          = rootDirectory.GetFileReference(fileName);
                    azOp.Complete();
                    return(file);
                }
                catch (StorageException se)
                {
                    if (RethrowExceptions)
                    {
                        throw se;
                    }
                    else
                    {
                        L.Error(se, "A storage error occurred getting Azure Storage file {fn} from share {sn}.", fileName, shareName);
                        return(null);
                    }
                }
                catch (Exception e)
                {
                    if (RethrowExceptions)
                    {
                        throw e;
                    }
                    else
                    {
                        L.Error(e, "An error occurred getting Azure Storage file {fn} from share {sn}.", fileName, shareName);
                        return(null);
                    }
                }
            }
        }
Beispiel #29
0
        /// <summary>
        /// Save document file to Azure File
        /// </summary>
        /// <param name="shareName">Define share name</param>
        /// <param name="sourceFolder">Define folder name which created under share</param>
        /// <param name="fileName">Define file name which resided under sourcefolder </param>
        /// <param name="stream">File stream</param>
        /// <returns></returns>
        public async Task UploadFileAsync(string shareName, string sourceFolder, string fileName, Stream stream)
        {
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(settings.ConnectionString);

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

            CloudFileShare cloudFileShare = null;

            cloudFileShare = cloudFileClient.GetShareReference(shareName);

            await cloudFileShare.CreateIfNotExistsAsync();

            // First, get a reference to the root directory, because that's where you're going to put the new directory.
            CloudFileDirectory rootDirectory = cloudFileShare.GetRootDirectoryReference();

            CloudFileDirectory fileDirectory = null;
            CloudFile          cloudFile     = null;

            // Set a reference to the file directory.
            // If the source folder is null, then use the root folder.
            // If the source folder is specified, then get a reference to it.
            if (string.IsNullOrWhiteSpace(sourceFolder))
            {
                // There is no folder specified, so return a reference to the root directory.
                fileDirectory = rootDirectory;
            }
            else
            {
                // There was a folder specified, so return a reference to that folder.
                fileDirectory = rootDirectory.GetDirectoryReference(sourceFolder);
                await fileDirectory.CreateIfNotExistsAsync();
            }

            // Set a reference to the file.
            cloudFile = fileDirectory.GetFileReference(fileName);

            await cloudFile.UploadFromStreamAsync(stream);
        }
Beispiel #30
0
        public async override Task CreateIfNotExistsAsync()
        {
            CloudStorageAccount sa    = Configuration.GetStorageAccountByUri(URI);
            CloudFileDirectory  dir   = new CloudFileDirectory(URI, sa.Credentials);
            CloudFileShare      share = dir.Share;
            await share.CreateIfNotExistsAsync();

            dir = share.GetRootDirectoryReference();

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

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

            while (n < directories.Count)
            {
                dir = dir.GetDirectoryReference(directories[n]);
                await dir.CreateIfNotExistsAsync();

                n = n + 1;
            }
        }