Exemplo n.º 1
0
        public static void WriteLogs(string log)
        {
            string connectionString = @"DefaultEndpointsProtocol=https;AccountName=hotelmanagerblob;AccountKey=0rIspWPXwm7U22uvlHZshW6mHeJKLw1W5Tu3OQbi8jUasSRVju61eU0teHvNHwtzuGW68vmtRH9uE/rlhoqAnQ==;EndpointSuffix=core.windows.net";
            string file = "appendBlop.txt";

            CloudStorageAccount account = CloudStorageAccount.Parse(connectionString);

            if (account == null) return;

            CloudBlobClient client = account.CreateCloudBlobClient();

            if (client == null) return;

            CloudBlobContainer container = client.GetContainerReference("hotelmanagerlog");

            try
            {
                container.CreateIfNotExists();
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.Message);
            }


            CloudAppendBlob blob = container.GetAppendBlobReference(file);

            if (!blob.Exists()) blob.CreateOrReplace();

            blob.AppendText($"{log} {Environment.NewLine}");
        }
Exemplo n.º 2
0
        public Stream CreateFile(FileDescription fileDescription, SignOptions signOptions = null,
                                 SaveOptions saveOptions = null)
        {
            CloudBlobContainer container = GetContainerReference();
            string             name      = fileDescription.GUID.ToLower();
            CloudBlockBlob     blob      = container.GetBlockBlobReference(name);

            using (MemoryStream emptyStream = new MemoryStream())
            {
                blob.UploadFromStream(emptyStream);
            }

            try
            {
                CloudAppendBlob appendBlob = container.GetAppendBlobReference(name);
                appendBlob.CreateOrReplace();
                return(appendBlob.OpenWrite(true));
            }
            catch (Microsoft.WindowsAzure.Storage.StorageException exception)
            {
                // Azure Storage Emulator does not support append BLOBs,
                // so we emulate appending
                return(new CachingAzureStream(blob));
            }
        }
Exemplo n.º 3
0
        public static void Read([QueueTrigger("customers", Connection = "AzureWebJobsStorage")] string message, TraceWriter log)
        {
            //Deserialize customer from the queue
            Customer customer = JsonConvert.DeserializeObject <Customer>(message);

#if Debug
            var builder = new ConfigurationBuilder()
                          .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true);
            IConfiguration Configuration = builder.Build();

            string con = Configuration["Values:AzureWebJobsStorage"];
#endif

            string con = System.Environment.GetEnvironmentVariable("AzureWebJobsStorage");



            CloudBlobClient blobClient = CloudStorageAccount.Parse(con).CreateCloudBlobClient();

            var folder = "files";

            CloudBlobContainer container = blobClient.GetContainerReference(folder);
            container.CreateIfNotExists();

            CloudAppendBlob blob = container.GetAppendBlobReference("customers.txt");

            if (!blob.Exists())
            {
                blob.CreateOrReplace();
            }

            blob.AppendText(customer.Name + ";" + customer.Age + ";" + customer.Phone + "\n");

            // blob.UploadText(customer.Name + ";" + customer.Age + ";" + customer.Phone);
        }
Exemplo n.º 4
0
        protected override void Write(LogEventInfo logEvent)
        {
            if (_client == null)
            {
                return;
            }

            string containerName = Container.Render(logEvent);
            string blobName      = BlobName.Render(logEvent);

            if (_container == null || _container.Name != containerName)
            {
                _container = _client.GetContainerReference(containerName);
                _blob      = null;
            }

            if (_blob == null || _blob.Name != blobName)
            {
                _blob = _container.GetAppendBlobReference(blobName);

                if (!_blob.Exists())
                {
                    try
                    {
                        _blob.Properties.ContentType = "text/plain";
                        _blob.CreateOrReplace(AccessCondition.GenerateIfNotExistsCondition(), null, null);
                    }
                    catch (StorageException)
                    { }
                }
            }
            var logMessage = this.Layout.Render(logEvent);

            _blob.AppendText(logMessage + "\r\n", Encoding.UTF8);
        }
Exemplo n.º 5
0
        public static void RunAppendBlob(CloudBlobContainer container, int times)
        {
            CloudAppendBlob appendBlob = container.GetAppendBlobReference("x/test.csv");

            appendBlob.CreateOrReplace();

            int nLabels = 10;

            string record = FillRecord("thing", nLabels);

            var watcher = Stopwatch.StartNew();

            appendBlob.AppendText(record);

            for (int i = 0; i < times; i++)
            {
                Console.WriteLine(((i + 1.0) / times) * 100 + "%");
                appendBlob.AppendText(record);
            }

            Console.WriteLine("ElapsedTime: " + watcher.Elapsed);
            Console.WriteLine("Blob length (bytes): " + appendBlob.Properties.Length);

            Console.Read();
        }
        public void UploadToAppendBlob()
        {
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("StorageConnectionString"));

            CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();

            CloudBlobContainer container = blobClient.GetContainerReference("my-append-blobs");

            container.CreateIfNotExists();

            CloudAppendBlob appendBlob = container.GetAppendBlobReference("append-blob.log");

            if (!appendBlob.Exists())
            {
                appendBlob.CreateOrReplace();
            }

            int numBlocks = 10;

            Random rnd = new Random();

            byte[] bytes = new byte[numBlocks];
            rnd.NextBytes(bytes);

            //Simulate a logging operation by writing text data and byte data to the end of the append blob.
            for (int i = 0; i < numBlocks; i++)
            {
                appendBlob.AppendText(string.Format("Timestamp: {0:u} \tLog Entry: {1}{2}", DateTime.UtcNow, bytes[i], Environment.NewLine));
            }

            Console.WriteLine(appendBlob.DownloadText());
        }
Exemplo n.º 7
0
        private void uploadToBlob(string fileName, string message)
        {
            CloudAppendBlob blob = this.container.GetAppendBlobReference(fileName);

            //make sure the file exsits
            if (!blob.Exists())
            {
                blob.CreateOrReplace();
            }
            try {
                blob.AppendText(message);
            }
            catch (StorageException e1)
            {
                //retry after sleep
                System.Threading.Thread.Sleep(10);
                try
                {
                    blob.AppendText(message);
                }
                catch (StorageException e)
                {
                    writeToLocalFile(fileName, message + "\r\n" + e.ToString() + "\r\n");
                }
            }
        }
Exemplo n.º 8
0
        public void CreateAppendBlob(string filePath)
        {
            CloudAppendBlob blockBlob = this.cloudBlobContainer.GetAppendBlobReference(filePath);

            if (!blockBlob.Exists())
            {
                blockBlob.CreateOrReplace();
            }
        }
Exemplo n.º 9
0
        public static void Run([TimerTrigger("0 0 */4 * * *")] TimerInfo myTimer, TraceWriter log)
        {
            bool found = true;

            storageAccount = CloudStorageAccount.Parse(storageAcct);
            queueClient    = storageAccount.CreateCloudQueueClient();
            loggingQueue   = queueClient.GetQueueReference(loggingQueueName);

            CloudBlobClient    blobClient    = storageAccount.CreateCloudBlobClient();
            CloudBlobContainer blobContainer = blobClient.GetContainerReference("logging");

            blobContainer.CreateIfNotExists();


            loggingQueue.FetchAttributes();
            int?cachedMessageCount = loggingQueue.ApproximateMessageCount;

            if (cachedMessageCount == 0 || cachedMessageCount == null)
            {
                return;
            }



            string          createddate = Convert.ToDateTime(DateTime.UtcNow).ToString("yyyy-MM-dd/HH-mm/");
            string          blobName    = "log/" + createddate + "telemetry.json";
            CloudAppendBlob appendBlob  = blobContainer.GetAppendBlobReference(blobName);

            appendBlob.Properties.ContentType = "text/json";

            appendBlob.CreateOrReplace();

            while (cachedMessageCount > 0 && found)
            {
                found = false;

                int?messagesToRetrieve = cachedMessageCount > 32 ? 32 : cachedMessageCount;
                cachedMessageCount = cachedMessageCount - messagesToRetrieve;

                foreach (CloudQueueMessage message in loggingQueue.GetMessages((int)messagesToRetrieve, TimeSpan.FromMinutes(2)))
                {
                    found = true;

                    try
                    {
                        appendBlob.AppendText(message.AsString + Environment.NewLine);
                        loggingQueue.DeleteMessage(message);
                    }
                    catch
                    {
                        log.Info("problem logging data");
                    }
                }
            }
        }
Exemplo n.º 10
0
        private CloudAppendBlob GetAppendBlob()
        {
            CloudAppendBlob blob = this.container.GetAppendBlobReference($"{DateTimeOffset.Now.ToString("yyyyMMdd")}/{DateTimeOffset.Now.ToString("yyyyMMddTHH")}.nm4");

            if (!blob.Exists())
            {
                blob.CreateOrReplace();
            }

            return(blob);
        }
 private CloudAppendBlob NewCloudAppendBlob(string userId)
 {
     lock (cloudAppendBlobDictionary)
     {
         CloudAppendBlob cloudAppendBlob =
             this.container.GetAppendBlobReference($"{userId}_{DateTime.Now.ToString("yyyy-MM-dd-HH-mm", CultureInfo.InvariantCulture)}.log");
         if (!cloudAppendBlob.Exists())
         {
             cloudAppendBlob.CreateOrReplace();
         }
         cloudAppendBlobDictionary[userId] = cloudAppendBlob;
         return(cloudAppendBlobDictionary[userId]);
     }
 }
Exemplo n.º 12
0
        public void AddStringToFile(string containerName, string fileName, string content)
        {
            var container = OpenOrInitializeContainer(containerName);

            CloudAppendBlob appendBlob = container.GetAppendBlobReference(fileName);

            //Create the append blob. Note that if the blob already exists, the CreateOrReplace() method will overwrite it.
            //You can check whether the blob exists to avoid overwriting it by using CloudAppendBlob.Exists().
            appendBlob.CreateOrReplace();

            appendBlob.AppendText($"Timestamp: {DateTime.UtcNow} \tLog Entry: {content}");

            appendBlob.DownloadText();
        }
Exemplo n.º 13
0
        /// <summary>
        /// Sends the events.
        /// </summary>
        /// <param name="events">The events that need to be send.</param>
        /// <remarks>
        /// <para>
        /// The subclass must override this method to process the buffered events.
        /// </para>
        /// </remarks>
        protected override void SendBuffer(LoggingEvent[] events)
        {
            CloudAppendBlob appendBlob = _cloudBlobContainer.GetAppendBlobReference(Filename(_directoryName));

            if (!appendBlob.Exists())
            {
                appendBlob.CreateOrReplace();
            }
            else
            {
                _lineFeed = Environment.NewLine;
            }

            Parallel.ForEach(events, ProcessEvent);
        }
Exemplo n.º 14
0
        private CloudAppendBlob GetBlob(DateTime eventTime)
        {
            string tagName = eventTime.ToString("yyyy-MM-dd");

            if (tagName != _currentTagName)
            {
                _currentTagName = tagName;
                _appendBlob     = _blobContainer.GetAppendBlobReference($"{_blobNamePrefix}{_currentTagName}.txt");
                if (!_appendBlob.Exists())
                {
                    _appendBlob.CreateOrReplace();
                }
            }

            return(_appendBlob);
        }
        protected override void Write(LogEventInfo logEvent)
        {
            var connectionString = ConnectionString.Render(logEvent);

            if (_client == null || !string.Equals(_connectionString, connectionString, System.StringComparison.OrdinalIgnoreCase))
            {
                _client = CloudStorageAccount.Parse(connectionString).CreateCloudBlobClient();
                InternalLogger.Debug("Initialized connection to {0}", connectionString);
            }

            string containerName = Container.Render(logEvent);
            string blobName      = BlobName.Render(logEvent);

            if (_container == null || _container.Name != containerName)
            {
                _container = _client.GetContainerReference(containerName);
                InternalLogger.Debug("Got container reference to {0}", containerName);

                if (_container.CreateIfNotExists())
                {
                    InternalLogger.Debug("Created container {0}", containerName);
                }

                _blob = null;
            }

            if (_blob == null || _blob.Name != blobName)
            {
                _blob = _container.GetAppendBlobReference(blobName);

                if (!_blob.Exists())
                {
                    try
                    {
                        _blob.Properties.ContentType = "text/plain";
                        _blob.CreateOrReplace(AccessCondition.GenerateIfNotExistsCondition());
                        InternalLogger.Debug("Created blob: {0}", blobName);
                    }
                    catch (StorageException ex) when(ex.RequestInformation.HttpStatusCode == (int)HttpStatusCode.Conflict)
                    {
                        // to be expected
                    }
                }
            }

            _blob.AppendText(Layout.Render(logEvent) + "\r\n", Encoding.UTF8);
        }
        public void Log(object data, string source, string message = null)
        {
            try
            {
                string dataString = (data != null) ? data as string : "null";
                if (dataString == null)
                {
                    dataString = JsonConvert.SerializeObject(data);
                }

                var sasUri                     = new Uri(this.configuration.ObjectLogSASUrl);
                var accountName                = sasUri.Host.TrimEndString(".blob.core.windows.net");
                StorageCredentials  creds      = new StorageCredentials(sasUri.Query);
                CloudStorageAccount strAcc     = new CloudStorageAccount(creds, accountName, endpointSuffix: null, useHttps: true);
                CloudBlobClient     blobClient = strAcc.CreateCloudBlobClient();

                //Setup our container we are going to use and create it.
                CloudBlobContainer container = blobClient.GetContainerReference(configuration.ObjectLogBlobContainer);
                container.CreateIfNotExistsAsync();

                // Build my typical log file name.
                DateTime date = DateTime.Now;

                // This creates a reference to the append blob we are going to use.
                CloudAppendBlob appBlob = container.GetAppendBlobReference(
                    $"{date.ToString("yyyy-MM")}/{date.ToString("dd")}/{date.ToString("HH")}-{source}.log");

                // Now we are going to check if todays file exists and if it doesn't we create it.
                if (!appBlob.Exists())
                {
                    appBlob.CreateOrReplace();
                }

                // Add the entry to our log.
                var logMessage = $"{date.ToString("o")}|{message}|{dataString}{Environment.NewLine}";
                using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(logMessage)))
                {
                    // Append a block.  AppendText is not safe across multiple threads & servers so use AppendBlock instead.
                    appBlob.AppendBlock(ms);
                }
            }
            catch (Exception ex)
            {
                this.logger.Error("Error logging data to the permanent store", ex);
            }
        }
Exemplo n.º 17
0
 public async Task SaveDataToBlobAsync(string data)
 {
     try
     {
         CloudAppendBlob blob = _dataContainer.GetAppendBlobReference(GetBlobName());
         if (!blob.Exists())
         {
             blob.CreateOrReplace();
         }
         await blob.AppendTextAsync(data);
     }
     catch (Exception ex)
     {
         _errorLogger.ErrorFormat("SaveDataToBlobAsync function encounter error : {0}",
                                  ex.ToString().Replace("\r\n", " "));
     }
 }
Exemplo n.º 18
0
        private void InitializeAzureStorage()
        {
            string containerName = "hackfest";

            remoteFileName = "test" + partitionID + ".txt";

            string              accName        = ConfigurationManager.AppSettings["blobStorageAccountName"];
            string              accKey         = ConfigurationManager.AppSettings["blobStorageAccountKey"];
            StorageCredentials  creds          = new StorageCredentials(accName, accKey);
            CloudStorageAccount storageAccount = new CloudStorageAccount(creds, true);
            CloudBlobClient     blobClient     = storageAccount.CreateCloudBlobClient();

            CloudBlobContainer container = blobClient.GetContainerReference(containerName);

            container.CreateIfNotExists();
            appBlob = container.GetAppendBlobReference(remoteFileName);
            appBlob.CreateOrReplace();
        }
Exemplo n.º 19
0
        /// <summary>
        /// Sends the events.
        /// </summary>
        /// <param name="events">The events that need to be send.</param>
        /// <remarks>
        /// <para>
        /// The subclass must override this method to process the buffered events.
        /// </para>
        /// </remarks>
        protected override void SendBuffer(LoggingEvent[] events)
        {
            CloudAppendBlob appendBlob = _cloudBlobContainer.GetAppendBlobReference(Filename(_directoryName, _filenamePrefixDateTimeFormat, _filenameSuffix));

            if (!appendBlob.Exists())
            {
                appendBlob.CreateOrReplace();
            }
            else
            {
                _lineFeed = Environment.NewLine;
            }

            foreach (var e in events)
            {
                ProcessEvent(e);
            }
        }
Exemplo n.º 20
0
        protected override void SendBuffer(LoggingEvent[] events)
        {
            CloudAppendBlob appendBlob = _cloudBlobContainer.GetAppendBlobReference(Filename(DirectoryName));

            if (!appendBlob.Exists())
            {
                appendBlob.CreateOrReplace();
            }

            StringBuilder sb = new StringBuilder();

            foreach (var loggingEvent in events)
            {
                sb.Append(RenderLoggingEvent(loggingEvent));
            }

            appendBlob.AppendText(sb.ToString());
        }
Exemplo n.º 21
0
        private void WriteToAppendBlob(string logLevel, string log)
        {
            DateTime date         = DateTime.Today;
            DateTime dateLogEntry = DateTime.UtcNow;

            try
            {
                CloudAppendBlob appBlob = _container.GetAppendBlobReference(string.Format("{0}{1}", date.ToString("yyyy-MM-dd"), ".log"));
                if (!appBlob.Exists())
                {
                    appBlob.CreateOrReplace();
                }
                appBlob.AppendText(string.Format("{0}\t{1}\t{2}\r\n", dateLogEntry.ToString("o"), logLevel, log));
            }
            catch (Exception)
            {
                ;
            }
        }
Exemplo n.º 22
0
        private void InstanciateStorageBlob(string formattedStorageContainerName, string formattedStorageBlobName)
        {
            if ((_appendBlob == null) || (_appendBlob.Name != formattedStorageBlobName))
            {
                _appendBlob = _blobContainer.GetAppendBlobReference(formattedStorageBlobName);

                if (!_appendBlob.Exists())
                {
                    try
                    {
                        _appendBlob.CreateOrReplace(AccessCondition.GenerateIfNotExistsCondition(), null, null);
                    }
                    catch (StorageException storageException)
                    {
                        WriteDebugError(String.Format("NLog.AzureStorage - Failed to create Azure Storage Append Blob '{0}' in the Container '{1}' - Storage Exception: {2} {3}", formattedStorageBlobName, formattedStorageContainerName, storageException.Message, GetStorageExceptionHttpStatusMessage(storageException)));
                        throw;
                    }
                }
            }
        }
Exemplo n.º 23
0
        /// <summary>
        /// Initializes the BLOB.
        /// </summary>
        /// <param name="blobName">Name of the BLOB.</param>
        private void InitializeBlob(string blobName)
        {
            if (_appendBlob == null || _appendBlob.Name != blobName)
            {
                _appendBlob = _container.GetAppendBlobReference(blobName);

                if (!_appendBlob.Exists())
                {
                    try
                    {
                        _appendBlob.Properties.ContentType = "text/plain";
                        _appendBlob.CreateOrReplace(AccessCondition.GenerateIfNotExistsCondition());
                    }
                    catch (StorageException ex)
                    {
                        InternalLogger.Error(ex, "Initialize Blob Exception");
                        throw;
                    }
                }
            }
        }
Exemplo n.º 24
0
        /// <summary>
        /// Create the blob storage refrences
        /// </summary>
        /// <param name="containerref">name of the container references
        ///</param>
        /// <param name="blockref">name of the blob reference</param>
        public StorageClient(string containerref, string blockref)
        {
            // Parse the connection string and return a reference to the storage account.
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
                CloudConfigurationManager.GetSetting("StorageConnectionString"));

            CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();

            // Retrieve a reference to a container.
            CloudBlobContainer container = blobClient.GetContainerReference(containerref);

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

            // Retrieve reference to a blob named "myblob".
            _blockBlob = container.GetAppendBlobReference(blockref);
            if (!_blockBlob.Exists())
            {
                _blockBlob.CreateOrReplace();
            }
        }
Exemplo n.º 25
0
        public static List <long> AppendToWasbContainer(CloudBlobClient blobClient, string containerName, string blobName, int numIterations, byte[] contents)
        {
            CloudBlobContainer appendContainer = blobClient.GetContainerReference(containerName);
            CloudAppendBlob    appendBlob      = appendContainer.GetAppendBlobReference(blobName);

            appendBlob.CreateOrReplace();
            appendContainer.CreateIfNotExists();
            var perfMetrics = new List <long>();

            for (int i = 0; i < numIterations; i++)
            {
                using (var stream = new MemoryStream(contents))
                {
                    var watch = Stopwatch.StartNew();
                    appendBlob.AppendBlock(stream);
                    watch.Stop();
                    perfMetrics.Add(watch.ElapsedMilliseconds);
                }
            }

            return(perfMetrics);
        }
Exemplo n.º 26
0
        /// <summary>
        /// create a new append blob with random properties and metadata
        /// </summary>
        /// <param name="container">CloudBlobContainer object</param>
        /// <param name="blobName">blob name</param>
        /// <returns>CloudAppendBlob object</returns>
        public CloudAppendBlob CreateAppendBlob(CloudBlobContainer container, string blobName, bool createBigBlob = false)
        {
            CloudAppendBlob appendBlob = container.GetAppendBlobReference(blobName);

            int size = createBigBlob ? random.Next(1024 * 1024 * 50, 1024 * 1024 * 100) : random.Next(1024 * 1024);

            appendBlob.CreateOrReplace();

            byte[] buffer = new byte[size];
            // fill in random data
            random.NextBytes(buffer);
            using (MemoryStream ms = new MemoryStream(buffer))
            {
                appendBlob.UploadFromStream(ms);
            }

            string md5sum = Convert.ToBase64String(Helper.GetMD5(buffer));

            appendBlob.Properties.ContentMD5 = md5sum;
            GenerateBlobPropertiesAndMetaData(appendBlob);
            Test.Info(string.Format("create append blob '{0}' in container '{1}', md5 = {2}", blobName, container.Name, md5sum));
            return(appendBlob);
        }
    public static void AppendToBlob(string fileName, string textToAppend)
    {
        CloudStorageAccount account = CloudStorageAccount.Parse(AmbientConnectionStringProvider.Instance.GetConnectionString("blobConnection"));

        CloudBlobClient    client    = account.CreateCloudBlobClient();
        CloudBlobContainer container = client.GetContainerReference("images");

        CloudAppendBlob appendBlob = container.GetAppendBlobReference(fileName);

        if (!appendBlob.Exists())
        {
            appendBlob.CreateOrReplace();
        }

        MemoryStream stream = new MemoryStream();
        StreamWriter writer = new StreamWriter(stream);

        writer.Write(textToAppend + Environment.NewLine);
        writer.Flush();
        stream.Position = 0;

        appendBlob.AppendBlock(stream);
    }
Exemplo n.º 28
0
        protected override void Write(LogEventInfo logEvent)
        {
            if (_client == null)
            {
                return;
            }

            string containerName = Container.Render(logEvent);
            string blobName      = BlobName.Render(logEvent);

            if (_container == null || _container.Name != containerName)
            {
                _container = _client.GetContainerReference(containerName);
                _blob      = null;
            }

            if (_blob == null || _blob.Name != blobName)
            {
                _blob = _container.GetAppendBlobReference(blobName);

                if (!_blob.Exists())
                {
                    try
                    {
                        _blob.Properties.ContentType = "text/plain";
                        _blob.CreateOrReplace(AccessCondition.GenerateIfNotExistsCondition());
                    }
                    catch (StorageException ex) when(ex.RequestInformation.HttpStatusCode == (int)HttpStatusCode.Conflict)
                    {
                        // to be expected
                    }
                }
            }

            _blob.AppendText(Layout.Render(logEvent) + "\r\n", Encoding.UTF8);
        }
Exemplo n.º 29
0
        private static async Task AppendBlobProcessAsync()
        {
            CloudStorageAccount storageAccount = null;

            CloudBlobContainer cloudBlobContainer = null;

            string sourceFile = null;

            string destinationFile = null;


            // Retrieve the connection string for use with the application. The storage connection string is stored

            // in an environment variable on the machine running the application called storageconnectionstring.

            // If the environment variable is created after the application is launched in a console or with Visual

            // Studio, the shell needs to be closed and reloaded to take the environment variable into account.

            string storageConnectionString = ConfigurationManager.AppSettings["StorageConnectionString"]; //Environment.GetEnvironmentVariable("StorageConnectionString");


            //storageAccount = CloudStorageAccount.DevelopmentStorageAccount;

            // Check whether the connection string can be parsed.

            if (CloudStorageAccount.TryParse(storageConnectionString, out storageAccount))
            {
                try

                {
                    // Create the CloudBlobClient that represents the Blob storage endpoint for the storage account.

                    ////CloudBlobClient cloudBlobClient = storageAccount.CreateCloudBlobClient();

                    //127.0.0.1:10000/devstoreaccount1/testcont

                    // Create a container called 'quickstartblobs' and append a GUID value to it to make the name unique.

                    ////cloudBlobContainer = cloudBlobClient.GetContainerReference("testcontappendblob");// "quickstartblobs" + Guid.NewGuid().ToString());

                    ////await cloudBlobContainer.CreateIfNotExistsAsync();

                    ////Console.WriteLine("Created container '{0}'", cloudBlobContainer.Name);

                    ////Console.WriteLine();



                    ////// Set the permissions so the blobs are public.

                    ////BlobContainerPermissions permissions = new BlobContainerPermissions

                    ////{

                    ////    PublicAccess = BlobContainerPublicAccessType.Blob

                    ////};

                    ////await cloudBlobContainer.SetPermissionsAsync(permissions);

                    // Get a reference to the blob address, then upload the file to the blob.

                    // Use the value of localFileName for the blob name.


                    CloudBlobClient cloudBlobClient = storageAccount.CreateCloudBlobClient();
                    cloudBlobContainer = cloudBlobClient.GetContainerReference("testcont");
                    cloudBlobContainer.CreateIfNotExists();

                    CloudAppendBlob cloudAppendBlob = cloudBlobContainer.GetAppendBlobReference("1.txt");
                    cloudAppendBlob.CreateOrReplace();
                    cloudAppendBlob.AppendText("Content added");
                    cloudAppendBlob.AppendText("More content added");
                    cloudAppendBlob.AppendText("Even more content added");

                    string appendBlobContent = cloudAppendBlob.DownloadText();


                    //cloudAppendBlob.UploadFromFile(sourceFile);



                    // List the blobs in the container.

                    Console.WriteLine("Listing blobs in container.");

                    BlobContinuationToken blobContinuationToken = null;

                    do

                    {
                        var results = await cloudBlobContainer.ListBlobsSegmentedAsync(null, blobContinuationToken);

                        // Get the value of the continuation token returned by the listing call.

                        blobContinuationToken = results.ContinuationToken;

                        foreach (IListBlobItem item in results.Results)

                        {
                            Console.WriteLine(item.Uri);
                        }
                    } while (blobContinuationToken != null); // Loop while the continuation token is not null.

                    destinationFile = sourceFile.Replace(".txt", "_DOWNLOADED.txt");

                    Console.WriteLine("Downloading blob to {0}", destinationFile);

                    Console.WriteLine();

                    await cloudAppendBlob.DownloadToFileAsync(destinationFile, FileMode.Create);


                    File.WriteAllText(sourceFile, "Hello, World, I am good, how is your health!");

                    await cloudAppendBlob.UploadFromFileAsync(sourceFile);

                    await cloudAppendBlob.DeleteAsync();
                }

                catch (StorageException ex)

                {
                    Console.WriteLine("Error returned from the service: {0}", ex.Message);
                }

                finally

                {
                    // Console.WriteLine("Press any key to delete the sample files and example container.");

                    Console.ReadLine();

                    // Clean up resources. This includes the container and the two temp files.

                    //Console.WriteLine("Deleting the container and any blobs it contains");

                    if (cloudBlobContainer != null)
                    {
                        // await cloudBlobContainer.DeleteIfExistsAsync();
                    }
                    File.Delete(sourceFile);
                    File.Delete(destinationFile);
                }
            }

            else

            {
                Console.WriteLine(

                    "A connection string has not been defined in the system environment variables. " +

                    "Add a environment variable named 'storageconnectionstring' with your storage " +

                    "connection string as a value.");
            }
        }
        public void RequestResultErrorCode()
        {
            Uri                baseAddressUri = new Uri(TestBase.TargetTenantConfig.BlobServiceEndpoint);
            CloudBlobClient    client         = new CloudBlobClient(baseAddressUri, TestBase.StorageCredentials);
            CloudBlobContainer container      = client.GetContainerReference(Guid.NewGuid().ToString("N"));

            byte[] buffer     = TestBase.GetRandomBuffer(4 * 1024 * 1024);
            MD5    md5        = MD5.Create();
            string contentMD5 = Convert.ToBase64String(md5.ComputeHash(buffer));

            try
            {
                RequestResult     requestResult;
                XmlWriterSettings settings;
                StringBuilder     sb;
                container.Create();
                CloudBlockBlob blob   = container.GetBlockBlobReference("blob1");
                List <string>  blocks = new List <string>();
                for (int i = 0; i < 2; i++)
                {
                    blocks.Add(Convert.ToBase64String(Guid.NewGuid().ToByteArray()));
                }

                // Verify the ErrorCode property is set and that it is serialized correctly
                using (MemoryStream memoryStream = new MemoryStream(buffer))
                {
                    memoryStream.Seek(0, SeekOrigin.Begin);
                    blob.PutBlock(blocks[0], memoryStream, contentMD5);

                    int offset = buffer.Length - 1024;
                    memoryStream.Seek(offset, SeekOrigin.Begin);
                    StorageException e = TestHelper.ExpectedException <StorageException>(
                        () => blob.PutBlock(blocks[1], memoryStream, contentMD5),
                        "Invalid MD5 should fail with mismatch");

                    Assert.AreEqual(e.RequestInformation.ErrorCode, StorageErrorCodeStrings.Md5Mismatch);

                    requestResult   = new RequestResult();
                    settings        = new XmlWriterSettings();
                    settings.Indent = true;
                    sb = new StringBuilder();
                    using (XmlWriter writer = XmlWriter.Create(sb, settings))
                    {
                        e.RequestInformation.WriteXml(writer);
                    }

                    using (XmlReader reader = XmlReader.Create(new StringReader(sb.ToString())))
                    {
                        requestResult.ReadXml(reader);
                    }

                    // ExtendedErrorInformation.ErrorCode will be depricated, but it should still match on a non HEAD request
                    Assert.AreEqual(e.RequestInformation.ErrorCode, requestResult.ErrorCode);
                    Assert.AreEqual(e.RequestInformation.ExtendedErrorInformation.ErrorCode, requestResult.ErrorCode);
                }

                // Verify the ErrorCode property is set on a HEAD request
                CloudAppendBlob blob2 = container.GetAppendBlobReference("blob2");
                blob2.CreateOrReplace();
                StorageException e2 = TestHelper.ExpectedException <StorageException>(
                    () => blob2.FetchAttributes(AccessCondition.GenerateIfMatchCondition("garbage")),
                    "Mismatched etag should fail");
                Assert.AreEqual(e2.RequestInformation.ErrorCode, StorageErrorCodeStrings.ConditionNotMet);

                // Verify the ErrorCode property is not set on a successful request and that it is serialized correctly
                OperationContext ctx = new OperationContext();
                blob2.FetchAttributes(operationContext: ctx);
                Assert.AreEqual(ctx.RequestResults[0].ErrorCode, null);
                requestResult   = new RequestResult();
                settings        = new XmlWriterSettings();
                settings.Indent = true;
                sb = new StringBuilder();
                using (XmlWriter writer = XmlWriter.Create(sb, settings))
                {
                    ctx.RequestResults[0].WriteXml(writer);
                }

                using (XmlReader reader = XmlReader.Create(new StringReader(sb.ToString())))
                {
                    requestResult.ReadXml(reader);
                }

                Assert.AreEqual(ctx.RequestResults[0].ErrorCode, requestResult.ErrorCode);
            }
            finally
            {
                container.DeleteIfExists();
            }
        }