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>

Wednesday, 18 April 2018

Threads Vs Tasks


Threads vs. Tasks
.Net has three low-level mechanisms to run code in parallel: ThreadThreadPool, and Task. These three mechanism serve different purposes.
Thread
Thread represents an actual OS-level thread, with its own stack and kernel resources. (technically, a CLR implementation could use fibers instead, but no existing CLR does this) Thread allows the highest degree of control; you can Abort() or Suspend() or Resume() a thread (though this is a very bad idea), you can observe its state, and you can set thread-level properties like the stack size, apartment state, or culture.
The problem with Thread is that OS threads are costly. Each thread you have consumes a non-trivial amount of memory for its stack, and adds additional CPU overhead as the processor context-switch between threads. Instead, it is better to have a small pool of threads execute your code as work becomes available.
There are times when there is no alternative Thread. If you need to specify the name (for debugging purposes) or the apartment state (to show a UI), you must create your own Thread (note that having multiple UI threads is generally a bad idea). Also, if you want to maintain an object that is owned by a single thread and can only be used by that thread, it is much easier to explicitly create a Thread instance for it so you can easily check whether code trying to use it is running on the correct thread.
ThreadPool
ThreadPool is a wrapper around a pool of threads maintained by the CLR. ThreadPool gives you no control at all; you can submit work to execute at some point, and you can control the size of the pool, but you can’t set anything else. You can’t even tell when the pool will start running the work you submit to it.
Using ThreadPool avoids the overhead of creating too many threads. However, if you submit too many long-running tasks to the threadpool, it can get full, and later work that you submit can end up waiting for the earlier long-running items to finish. In addition, the ThreadPool offers no way to find out when a work item has been completed (unlike Thread.Join()), nor a way to get the result. Therefore, ThreadPool is best used for short operations where the caller does not need the result.
Task
Finally, the Task class from the Task Parallel Library offers the best of both worlds. Like the ThreadPool, a task does not create its own OS thread. Instead, tasks are executed by a TaskScheduler; the default scheduler simply runs on the ThreadPool.
Unlike the ThreadPool, Task also allows you to find out when it finishes, and (via the generic Task<T>) to return a result. You can call ContinueWith() on an existing Task to make it run more code once the task finishes (if it’s already finished, it will run the callback immediately). If the task is generic, ContinueWith() will pass you the task’s result, allowing you to run more code that uses it.
You can also synchronously wait for a task to finish by calling Wait() (or, for a generic task, by getting the Result property). Like Thread.Join(), this will block the calling thread until the task finishes. Synchronously waiting for a task is usually bad idea; it prevents the calling thread from doing any other work, and can also lead to deadlocks if the task ends up waiting (even asynchronously) for the current thread.
Since tasks still run on the ThreadPool, they should not be used for long-running operations, since they can still fill up the thread pool and block new work. Instead, Task provides a LongRunning option, which will tell the TaskScheduler to spin up a new thread rather than running on the ThreadPool.
All newer high-level concurrency APIs, including the Parallel.For*() methods, PLINQ, C# 5 await, and modern async methods in the BCL, are all built on Task.


Azure Service Bus Queue , Table - Send, Read

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