Tuesday, 15 May 2018

Azure Service Bus Queue , Table - Send, Read


using Microsoft.ServiceBus.Messaging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;
using Newtonsoft.Json;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Table;
using FileHelpers;
using System.IO;
using Logger;


namespace AzureServiceBus_queue
{
    class Program
    {


        static void Main(string[] args)
        {
            try
            {
                string path = @"c:\users\Public\India.txt";
                if (!File.Exists(path))
                {
                    string CreateText = "I am Creating Text";
                    File.WriteAllText(path, CreateText);
                }
                else
                {
                    File.AppendAllText(path, "\nLogging Main Main");
                }
                //Connection String for Azure Queue
                var connectionString = ConfigurationManager.AppSettings["ServiceBusConnectionString"];
                QueueClient queueClient = QueueClient.CreateFromConnectionString(connectionString);

                SendtoQueue(queueClient);
                ReadfromQueue(queueClient);

                Console.WriteLine("\nData send to Azure Queue and read successfully\n");

                //Connection String for Azure Storage Table
                var StorageTableConnection = ConfigurationManager.AppSettings["TableStorage"];
                CloudStorageAccount storageAccount = CloudStorageAccount.Parse(StorageTableConnection);
                CloudTableClient tableClient = storageAccount.CreateCloudTableClient();
                CloudTable table = tableClient.GetTableReference("ProductsInfo");

                SendDatatoStorageTable(table);
                ReadDatafromStorageTable(table);

                Console.WriteLine("\nData send to Azure Storage Table and read successfully\n");
                Console.ReadLine();
            }
            catch (Exception ex)
            {
                Console.WriteLine("{0}", ex.Message);

                ErrorLog(ex);
            }
        }

        private static void ErrorLog(Exception ex)
        {
            using (StreamWriter strWritter = new StreamWriter(@"C:\users\public\Filepath.txt"))
            {
                strWritter.WriteLine(ex.Message);
            }
        }

        private static void SendtoQueue(QueueClient queueClient)
        {
            try
            {
                List<Products> tandCNoticeDetails = ListofProducts();
                string TCDetails = JsonConvert.SerializeObject(tandCNoticeDetails);
                var message = new BrokeredMessage(TCDetails);
                queueClient.Send(message);
            }
            catch (Exception ex)
            {
                Console.WriteLine("{0}", ex.Message);
                ErrorLog(ex);
            }
        }

        private static void ReadfromQueue(QueueClient queueClient)
        {
            try
            {
                var Message = queueClient.Receive(TimeSpan.FromSeconds(2));
                if (Message != null)
                {
                    var bodyJson2 = Message.GetBody<string>();
                    var Envelop = JsonConvert.DeserializeObject(bodyJson2);
                    Console.WriteLine(Envelop);
                    Message.Complete();
                }
                queueClient.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine("{0}", ex.Message);
                ErrorLog(ex);
            }
        }

        private static void SendDatatoStorageTable(CloudTable table)
        {
            try
            {
                if (table.Name != "")
                {
                    table.DeleteIfExists();
                }
                table.CreateIfNotExists();

                List<Products> ProductList = ListofProducts();

                foreach (var sDetail in ProductList)
                {
                    Products products = new Products();
                    products.PartitionKey = DateTime.Now.ToString("MM-dd-yyyy");
                    products.RowKey = Guid.NewGuid().ToString();
                    products.Timestamp = DateTime.Now;
                    products.id = sDetail.id;
                    products.name = sDetail.name;
                    products.location = sDetail.location;
                    TableOperation insertOperation = TableOperation.Insert(products);
                    table.Execute(insertOperation);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"{ex.Message}");
                ErrorLog(ex);
            }
        }

        private static void ReadDatafromStorageTable(CloudTable table)
        {
            try
            {
                List<Products> ProductsList = new List<Products>();
                TableQuery<Products> query = new TableQuery<Products>();

                // Print the fields for each Products Info
                foreach (Products entity in table.ExecuteQuery(query))
                {
                    //Console.WriteLine($"{entity.RowKey}\t{entity.PartitionKey}\t{entity.id}\t{entity.name}\t{entity.location}");
                    ProductsList.Add(new Products { id = entity.id, name = entity.name, location = entity.location });
                }

                //Sorting table values
                var sortingProducts = ProductsList.OrderBy(i => i.id).ToList();

                foreach (var item in sortingProducts)
                {
                    Console.WriteLine($"{item.id}\t{item.name}\t{item.location}");//string Interpolation
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"{ex.Message}");
                ErrorLog(ex);
            }
        }


        private static List<Products> ListofProducts()
        {
            try
            {
                List<Products> ProductsList = new List<Products>();
                ProductsList.Add(new Products { id = "1", name = "Pizzaaaa", location = "USA" });
                ProductsList.Add(new Products { id = "2", name = "Donutsaaa", location = "Cananda" });
                ProductsList.Add(new Products { id = "3", name = "Wingsaaa", location = "Africa" });
                ProductsList.Add(new Products { id = "4", name = "Fishaaa", location = "Asia" });
                ProductsList.Add(new Products { id = "5", name = "Veggieaaa", location = "France" });
                return ProductsList;
            }
            catch (Exception ex)
            {
                Console.WriteLine("{0}", ex.Message);
                ErrorLog(ex);
                return null;
            }
        }
    }
}


Create new class file for below
using Microsoft.WindowsAzure.Storage.Table;


namespace AzureServiceBus_queue
{
    public class Products : TableEntity
    {
        public string id { get; set; }
        public string name { get; set; }
        public string location { get; set; }
    }

}


Azure Connection String to be in Web Config or App Config
  //       <appSettings>   
  //  <add key = "ServiceBusConnectionString" value="Endpoint=sb://tamilnadu.servicebus.windows.net;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=V06Q5Er1IqKFsk6bT6jnwusL8/FSZqfZMHddWY7+J50=;EntityPath=cbequeue" />
  //  <add key = "TableStorage" value="DefaultEndpointsProtocol=https;TableEndpoint=https://teststorageaccounts.table.core.windows.net/;AccountName=teststorageaccounts;AccountKey=7wnJyoJjJFyBqpQlIdwEeuqbTOapSi4yBEZcJrHE/aBPSs1c8zZhuzdY/S/n8aT2iS8c9XzhDRjoVCLRG/OMmA==" />
  //</appSettings>

No comments:

Post a Comment

Azure Service Bus Queue , Table - Send, Read

using Microsoft.ServiceBus.Messaging; using System; using System.Collections.Generic; using System.Linq; using System.Text; ...