Ejemplo n.º 1
0
        public static void UploadtoFileShare(string shareReference, byte[] fileStream, string fileName)
        {
            // Parse the connection string and return a reference to the storage account.
            CloudStorageAccount storageAccount = Helper.storageAccount;



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



            CloudFileShare share = fileClient.GetShareReference(shareReference);

            share.CreateIfNotExists();

            if (share.Exists())
            {
                CloudFileDirectory rootDir = share.GetRootDirectoryReference();
                //Create a reference to the filename that you will be uploading
                CloudFile cloudFile = rootDir.GetFileReference(fileName);


                FileStream fStream = File.OpenRead("C:\\myprojs\\images\\krishna.jpg");



                cloudFile.UploadFromByteArray(fileStream, 0, fileStream.Length);
                Console.WriteLine($"File uploaded successfully   {fileName}");
            }
        }
Ejemplo 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();
        }
        public AzureFilesStorageFileSystem(string shareName, string rootUrl)
        {
            /* if (string.IsNullOrEmpty(rootPath))
             *  throw new ArgumentException("The argument 'rootPath' cannot be null or empty.");
             *
             * if (string.IsNullOrEmpty(rootUrl))
             *  throw new ArgumentException("The argument 'rootUrl' cannot be null or empty.");
             *
             * if (rootPath.StartsWith("~/"))
             *  throw new ArgumentException("The rootPath argument cannot be a virtual path and cannot start with '~/'");
             *
             * RootPath = rootPath;
             * _rootUrl = rootUrl; */

            CloudStorageAccount account = CloudStorageAccount.DevelopmentStorageAccount;
            CloudFileClient     client  = account.CreateCloudFileClient();
            CloudFileShare      share   = client.GetShareReference(shareName);

            share.CreateIfNotExists();

            RootPath = share.GetRootDirectoryReference().Name;
            _rootUrl = share.GetRootDirectoryReference().Uri.AbsoluteUri;

            share.GetRootDirectoryReference().GetFileReference("")
        }
Ejemplo n.º 4
0
        private Stream GetResourceXMLFromCloudShare(Dictionary <string, string> config, string fileNameInCloud)
        {
            var cred           = new StorageCredentials(config["STORAGE_NAME"], config["STORAGE_KEY"]);
            var storageAccount = new CloudStorageAccount(cred, true);

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

            share.CreateIfNotExists();

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

            var cloudFile = dir.GetFileReference(fileNameInCloud);

            var ms = new MemoryStream();

            cloudFile.DownloadToStream(ms);

            ms.Position = 0;

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

            return(xml);
        }
Ejemplo n.º 5
0
        public static CloudFileDirectory BasicAzureFileOperations()
        {
            // Get Storage Account Key from Key Vault
            string saKey = EncryptionHelper.GetSAKey();

            // Retrieve storage account information from connection string
            CloudStorageAccount storageAccount = CreateStorageAccountFromConnectionString(string.Format(storageConnectionString, saKey));

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

            // Get the storage file share reference based on storage account
            CloudFileShare fileShare = fileClient.GetShareReference(storageFileShareName);

            // Check whether the File Share exist or not. By default, is should be created by TM team. And now, the focalpoint is: Spoelhof, Nathan (ND) <*****@*****.**>
            // who create the storage manually (blob, file, table & queue)
            // Default size of file share is 1GB and configued in web.config
            if (!fileShare.Exists())
            {
                fileShare.Properties.Quota = storageFileShareSize;
                fileShare.CreateIfNotExists();
            }

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

            return(root);
        }
Ejemplo n.º 6
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");
        }
Ejemplo n.º 7
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);
        }
Ejemplo n.º 8
0
        public override bool Execute()
        {
            Log.LogMessage(MessageImportance.High, "Creating file share named '{0}' in storage account {1}.", ShareName, AccountName);

            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(String.Format("DefaultEndpointsProtocol=https;AccountName={0};AccountKey={1}", AccountName, AccountKey));
            CloudFileClient     fileClient     = storageAccount.CreateCloudFileClient();
            CloudFileShare      fileShare      = fileClient.GetShareReference(ShareName);

            fileShare.CreateIfNotExists();
            StorageUri = fileShare.Uri.ToString();

            // NOTE: by convention the tokens don't contain the leading '?' character.

            if (ReadOnlyTokenDaysValid > 0)
            {
                SharedAccessFilePolicy rFilePolicy = new SharedAccessFilePolicy();
                rFilePolicy.SharedAccessExpiryTime = DateTime.UtcNow.AddDays(ReadOnlyTokenDaysValid);
                rFilePolicy.Permissions            = SharedAccessFilePermissions.Read;
                ReadOnlyToken = fileShare.GetSharedAccessSignature(rFilePolicy).Substring(1);
            }

            if (WriteOnlyTokenDaysValid > 0)
            {
                SharedAccessFilePolicy wFilePolicy = new SharedAccessFilePolicy();
                wFilePolicy.SharedAccessExpiryTime = DateTime.UtcNow.AddDays(WriteOnlyTokenDaysValid);
                wFilePolicy.Permissions            = SharedAccessFilePermissions.Read | SharedAccessFilePermissions.Write | SharedAccessFilePermissions.List | SharedAccessFilePermissions.Delete;
                WriteOnlyToken = fileShare.GetSharedAccessSignature(wFilePolicy).Substring(1);
            }

            return(true);
        }
Ejemplo n.º 9
0
        static void CreateShareFile()
        {
            try
            {
                #region Creating the Shared Files in Azure

                _storageAccount = CloudStorageAccount.Parse(
                    CloudConfigurationManager.GetSetting("StorageConnection"));

                _share = _storageAccount.CreateCloudFileClient().GetShareReference("documentos");

                if (_share.Exists())
                {
                    //Console.Clear();
                    // Check current usage stats for the share.
                    // Note that the ShareStats object is part of the protocol layer for the File service.
                    ShareStats stats = _share.GetStats();
                    //Console.WriteLine("Current share usage: {0} GB", stats.Usage.ToString());

                    // Specify the maximum size of the share, in GB.
                    // This line sets the quota to be 10 GB greater than the current usage of the share.
                    _share.Properties.Quota = 10 + stats.Usage;
                    _share.SetProperties();

                    // Now check the quota for the share. Call FetchAttributes() to populate the share's properties.
                    _share.FetchAttributes();
                    //Console.WriteLine("Current share quota: {0} GB", _share.Properties.Quota);

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

                    // Get existing permissions for the share.
                    FileSharePermissions permissions = _share.GetPermissions();

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

                    //Console.ReadKey();
                }
                else
                {
                    _share.CreateIfNotExists();
                }

                #endregion
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                Console.ReadKey();
            }
        }
Ejemplo n.º 10
0
        public AzureOperations(string connectionString, string shareName)
        {
            var account = CloudStorageAccount.Parse(connectionString);

            client = account.CreateCloudFileClient();
            share  = client.GetShareReference(shareName);
            share.CreateIfNotExists();
            root = share.GetRootDirectoryReference();
        }
Ejemplo n.º 11
0
        static void Main(string[] args)
        {
            DateTime phDate = DateTime.UtcNow.AddHours(8);

            List <RTTripUpdates> tripUpdates = db.Database
                                               .SqlQuery <RTTripUpdates>("RTTripUpdatesGetActive @travel_date"
                                                                         , new SqlParameter("@travel_date", phDate.ToString("yyyyMMdd")))
                                               .ToList();

            FeedMessage feed = new FeedMessage();

            if (tripUpdates.Count > 0)
            {
                foreach (RTTripUpdates tripUpdate in tripUpdates)
                {
                    TripDescriptor td = new TripDescriptor();
                    td.TripId      = tripUpdate.trip_id;
                    td.RouteId     = tripUpdate.route_id;
                    td.DirectionId = (uint)tripUpdate.direction_id;
                    td.StartDate   = tripUpdate.start_date;
                    td.StartTime   = tripUpdate.start_time;

                    TripUpdate tp = new TripUpdate();
                    tp.Delay = tripUpdate.delay;
                    tp.Trip  = td;

                    FeedEntity entity = new FeedEntity();
                    entity.TripUpdate = tp;
                    entity.Id         = tripUpdate.id.ToString();

                    feed.Entities.Add(entity);
                }

                byte[] objSerialized = Functions.ProtoSerialize(feed);

                CloudStorageAccount storageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("StorageConnectionString"));
                string filename = "tripupdate.pb";


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

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

                var rootDir = share.GetRootDirectoryReference();
                using (var stream = new MemoryStream(objSerialized, writable: false))
                {
                    rootDir.GetFileReference(filename).UploadFromStream(stream);//.UploadFromByteArray(feed,);
                }
            }


            // Functions.CreatePBFile(storageAccount, filename, objSerialized);
        }
Ejemplo n.º 12
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;
            }
        }
        public bool CreateFileShareIfNotExists(string fileShareName)
        {
            CloudFileClient fileClient = new CloudFileClient(fileURI, creds);
            // Create a CloudFileClient object for credentialed access to Azure Files.


            // Get a reference to the file share we created previously.
            CloudFileShare share = fileClient.GetShareReference(fileShareName);

            return(share.CreateIfNotExists());
        }
Ejemplo n.º 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 CloudFile instance with the specified name in the given share.</returns>
        public static CloudFile GetCloudFile(string shareName, string fileName)
        {
            CloudFileClient client = GetCloudFileClient();
            CloudFileShare  share  = client.GetShareReference(shareName);

            share.CreateIfNotExists();

            CloudFileDirectory rootDirectory = share.GetRootDirectoryReference();

            return(rootDirectory.GetFileReference(fileName));
        }
Ejemplo n.º 15
0
        public FileStorageAsync(string fileShareName, string storageConnectionString)
        {
            Validate.String(fileShareName, "fileShareName");
            Validate.String(storageConnectionString, "storageConnectionString");

            var cloudStorageAccount = CloudStorageAccount.Parse(storageConnectionString);

            var fileClient = cloudStorageAccount.CreateCloudFileClient();

            cloudFileShare = fileClient.GetShareReference(fileShareName);
            cloudFileShare.CreateIfNotExists();
        }
Ejemplo n.º 16
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);
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="T:ByteDev.Azure.Storage.File.FileStorageClient" /> class.
        /// </summary>
        /// <param name="connectionString">Storage account connection string.</param>
        /// <param name="shareName">File share name.</param>
        /// <param name="createShareIfNotExist">True create the share if it does not exist; otherwise do not create.</param>
        /// <exception cref="T:System.ArgumentNullException"><paramref name="connectionString" /> is null.</exception>
        /// <exception cref="T:System.ArgumentNullException"><paramref name="shareName" /> is null.</exception>
        public FileStorageClient(string connectionString, string shareName, bool createShareIfNotExist)
        {
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(connectionString);

            CloudFileClient fileClient = storageAccount.CreateCloudFileClient();

            _share = fileClient.GetShareReference(shareName);

            if (createShareIfNotExist)
            {
                _share.CreateIfNotExists();
            }
        }
Ejemplo n.º 18
0
        private static void SetupAzureUtility()
        {
            string rawConnStr = File.ReadAllText("AzureStorageConnectionString.key");

            AzureUtility.AzureStorage    = CloudStorageAccount.Parse(rawConnStr);
            AzureUtility.AzureFileClient = AzureStorage.CreateCloudFileClient();

            CloudFileShare share = AzureFileClient.GetShareReference("apibasketball");

            share.CreateIfNotExists();

            AzureUtility.AzureRootDirectory = share.GetRootDirectoryReference();
            AzureUtility.AzureRootDirectory.CreateIfNotExists();
        }
Ejemplo n.º 19
0
        public AzureUtility(string shareReference)
        {
            string rawConnStr = File.ReadAllText("AzureStorageConnectionString.key");

            this.AzureStorage    = CloudStorageAccount.Parse(rawConnStr);
            this.AzureFileClient = AzureStorage.CreateCloudFileClient();

            //CloudFileShare share = AzureFileClient.GetShareReference("apibasketball");
            CloudFileShare share = AzureFileClient.GetShareReference(shareReference);

            share.CreateIfNotExists();

            this.AzureRootDirectory = share.GetRootDirectoryReference();
            this.AzureRootDirectory.CreateIfNotExists();
        }
Ejemplo n.º 20
0
        public static void Uploadfile()
        {
            string StorageString = ConfigurationSettings.AppSettings.Get("AzureStorageAccount");

            CloudStorageAccount cloudStorageAccount = CloudStorageAccount.Parse(StorageString);
            CloudFileClient     cloudfileClient     = cloudStorageAccount.CreateCloudFileClient();
            CloudFileShare      share = cloudfileClient.GetShareReference("test");

            share.CreateIfNotExists();
            CloudFile sourceFile = share.GetRootDirectoryReference().GetFileReference("test.txt");

            using (var filestream = System.IO.File.OpenRead(@"D:\test.txt"))
            {
                sourceFile.UploadFromStream(filestream);
            }
        }
Ejemplo n.º 21
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();
        }
Ejemplo n.º 22
0
        public void Copy_a_file_to_a_blob()
        {
            // Parse the connection string for the storage account.
            StorageCredentials  Credentials    = new StorageCredentials(this.Account, this.Key);
            CloudStorageAccount storageAccount = new CloudStorageAccount(Credentials, false);

            // Create a CloudFileClient object for credentialed access to File storage.
            CloudFileClient fileClient = storageAccount.CreateCloudFileClient();

            // Create a new file share, if it does not already exist.
            CloudFileShare share = fileClient.GetShareReference("sample-share");

            share.CreateIfNotExists();

            // Create a new file in the root directory.
            CloudFile sourceFile = share.GetRootDirectoryReference().GetFileReference("sample-file.txt");

            sourceFile.UploadText("A sample file in the root directory.");

            // Get a reference to the blob to which the file will be copied.
            CloudBlobClient    blobClient = storageAccount.CreateCloudBlobClient();
            CloudBlobContainer container  = blobClient.GetContainerReference("sample-container");

            container.CreateIfNotExists();
            CloudBlockBlob destBlob = container.GetBlockBlobReference("sample-blob.txt");

            // Create a SAS for the file that's valid for 24 hours.
            // Note that when you are copying a file to a blob, or a blob to a file, you must use a SAS
            // to authenticate access to the source object, even if you are copying within the same
            // storage account.
            string fileSas = sourceFile.GetSharedAccessSignature(new SharedAccessFilePolicy()
            {
                // Only read permissions are required for the source file.
                Permissions            = SharedAccessFilePermissions.Read,
                SharedAccessExpiryTime = DateTime.UtcNow.AddHours(24)
            });

            // Construct the URI to the source file, including the SAS token.
            Uri fileSasUri = new Uri(sourceFile.StorageUri.PrimaryUri.ToString() + fileSas);

            // Copy the file to the blob.
            destBlob.StartCopy(fileSasUri);

            // Write the contents of the file to the console window.
            Console.WriteLine("Source file contents: {0}", sourceFile.DownloadText());
            Console.WriteLine("Destination blob contents: {0}", destBlob.DownloadText());
        }
Ejemplo n.º 23
0
        public static void CreatePBFile(CloudStorageAccount storageAccount, string filename, byte[] feed)
        {
            // Create a CloudFileClient object for credentialed access to Azure Files.
            CloudFileClient fileClient = storageAccount.CreateCloudFileClient();

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

            share.CreateIfNotExists();

            var rootDir = share.GetRootDirectoryReference();

            using (var stream = new MemoryStream(feed, writable: false))
            {
                rootDir.GetFileReference(filename).UploadFromStream(stream);//.UploadFromByteArray(feed,);
            }
        }
Ejemplo n.º 24
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);
            }
        }
Ejemplo n.º 25
0
        static void Main(string[] args)
        {
            _log = new LoggerConfiguration()
                   .WriteTo.ColoredConsole(outputTemplate: "{Timestamp:HH:mm:ss} [{Level}] {Message}{NewLine}{Exception}")
                   .CreateLogger();
            _log.Information("Starting EnterprisePics.CloudSync");

            // Read config.
            var localPath = ConfigurationManager.AppSettings["LocalPath"];

            _log.Information("Local Path: {localPath}", localPath);
            var connectionString = ConfigurationManager.AppSettings["StorageConnectionString"];

            _log.Information("Connection String: {connectionString}", connectionString);
            var shareName = ConfigurationManager.AppSettings["ShareName"];

            _log.Information("ShareName: {shareName}", shareName);

            // Get the share.
            _share = CloudStorageAccount.Parse(connectionString)
                     .CreateCloudFileClient()
                     .GetShareReference("pictures");
            _share.CreateIfNotExists();
            _rootDirectory = _share.GetRootDirectoryReference();

            // Init watch.
            var watcher = new RxFileSystemWatcher.ObservableFileSystemWatcher(cfg =>
            {
                cfg.Path = localPath;
                cfg.IncludeSubdirectories = true;
            });

            watcher.Created.Subscribe(OnFileCreated);
            watcher.Changed.Throttle((eventArgs => Observable.Timer(TimeSpan.FromSeconds(1)))).Subscribe(OnFileChanged);
            watcher.Deleted.Subscribe(OnFileDeleted);
            watcher.Errors.Subscribe(OnErrors);
            watcher.Renamed.Subscribe(OnFileRenamed);
            watcher.Start();

            // Wait.
            Console.ReadLine();
        }
Ejemplo n.º 26
0
        private static bool CreateFileShare()
        {
            try
            {
                CloudFileShare fileShare = fileClient.GetShareReference(_shareName);

                fileShare.CreateIfNotExists();
            }
            catch (Exception ex)
            {
                if (_feedback != null)
                {
                    _feedback.OnException(fileClient, ex);
                }

                return(false);
            }

            return(true);
        }
        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);
        }
Ejemplo n.º 28
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();
        }
Ejemplo n.º 29
0
 public AzureFileServiceOpViaSASHelper()
 {
     sasFileUri = string.Format("https://{0}.file.core.windows.net/{1}{2}", storageAccountName, fileShareName, signature);
     fileShare  = new CloudFileShare(new Uri(sasFileUri));
     fileShare.CreateIfNotExists();
 }
Ejemplo n.º 30
0
        static void Main(string[] args)
        {
            SqlParameter parameter = new SqlParameter();

            parameter.SqlDbType     = System.Data.SqlDbType.DateTime;
            parameter.ParameterName = "@travel_date";
            parameter.Value         = DateTime.UtcNow.AddHours(8);

            List <RTServiceAlerts> serviceAlerts = db.Database
                                                   .SqlQuery <RTServiceAlerts>("RTServiceAlertsGetActive @travel_date"
                                                                               , parameter)
                                                   .ToList();

            FeedMessage feed = new FeedMessage();

            if (serviceAlerts.Count > 0)
            {
                foreach (RTServiceAlerts serviceAlert in serviceAlerts)
                {
                    EntitySelector entitySel = new EntitySelector();
                    entitySel.RouteId = serviceAlert.route_id;
                    entitySel.StopId  = serviceAlert.stop_id;

                    Alert alert = new Alert();
                    alert.HeaderText      = Functions.GenerateTranslatedString(serviceAlert.description);
                    alert.DescriptionText = Functions.GenerateTranslatedString(serviceAlert.header);
                    alert.InformedEntities.Add(entitySel);
                    //alert.Url = GenerateTranslatedString(serviceAlert.id.ToString());

                    TimeRange tr = new TimeRange();
                    tr.Start = Functions.ToEpoch(serviceAlert.start_date.AddHours(-8));
                    tr.End   = Functions.ToEpoch(serviceAlert.end_date.AddHours(-8));

                    alert.ActivePeriods.Add(tr);

                    FeedEntity entity = new FeedEntity();
                    entity.Alert = alert;
                    entity.Id    = serviceAlert.id.ToString();

                    feed.Entities.Add(entity);
                }

                byte[] objSerialized = Functions.ProtoSerialize(feed);

                CloudStorageAccount storageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("StorageConnectionString"));
                string filename = "alert.pb";


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

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

                var rootDir = share.GetRootDirectoryReference();
                using (var stream = new MemoryStream(objSerialized, writable: false))
                {
                    rootDir.GetFileReference(filename).UploadFromStream(stream);//.UploadFromByteArray(feed,);
                }
            }

            //byte[] objSerialized = Functions.ProtoSerialize(feed);

            //CloudStorageAccount storageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("StorageConnectionString"));
            //string filename = "alert.pb";
            //Functions.CreatePBFile(storageAccount, filename, objSerialized);
        }