Thursday, 20 September 2018

How to solve Operator '==' cannot be applied to operands of type 'T'

In this post we are going to see how to compare a field or property which have type as T Generic. Generally if you try to compare Generic types with ==,!= operator it will results in Operator == or != cannot be applied to operands of Type 'T'

For example:
********************

  public class Node<T>
    {
        private T _data;
        private Node<T> _next;
        private Node<T> _prev;

        public T Data
        {
            get { return _data; }
            set { _data = value; }
        }

        public Node<T> Next
        {
            get { return _next; }
            set { _next = value; }
        }

        public Node<T> Previous
        {
            get { return _prev; }
            set { _prev = value; }
        }

        public Node(T value):this(value,null, null)
        {
           
        }

        public Node(T value, Node<T> next, Node<T> prev)
        {
            this._data = value;
            this._next = next;
            this._prev = prev;
        }
    }


public Node<T> AddBefore(Node<T> element, T value)
   {
            var tempNode1 = new Node<T>(value);
            var tempNode2 = new Node<T>(value);

            if(tempNode1.Data == tempNode2.Data) { 
              
            }
         
   } 


In the above example if you see the line , if(tempNode1.Data == tempNode2.Data) { where we compare the two T type with == operator now this will return a compile time error.

To resolve this error we have to use EqualityComparer

if(EqualityComparer<T>.Default.Equals(tempNode1.Data,tempNode2.Data))

{

}


so the result method will be
public Node<T> AddBefore(Node<T> element, T value)
{
            var tempNode1 = new Node<T>(value);
            var tempNode2 = new Node<T>(value);

            if(EqualityComparer<T>.Default.Equals(tempNode1.Data,tempNode2.Data)) { 
              
            }
         


From this post you can learn how to solve operator '==' cannot be applied to operands of type 'T'

Sunday, 16 September 2018

Singleton deisgn pattern in c# Lazy and Eager initialization

In this post we are going to see how to create a singleton class in eager and lazy initialization concepts in c#

Key things to remember for singleton is
1. Private constructor
2. Static Property to get the instance
3. Backing field should be readonly static
4.  Singleton class should be sealed

Lazy Initialization
*************************
First we create lazy initialization of singleton class

public sealed class EmployeeSingleton
    {
        private static readonly Lazy<EmployeeSingleton> _instance = new
                    Lazy<EmployeeSingleton>(() => new EmployeeSingleton());

        private EmployeeSingleton() { }

        public static EmployeeSingleton Instance
        {
            get
            {
                return _instance.Value;
            }
        }

        public void Log(string message)
        {
            Console.WriteLine(message);
        }


    }



Eager Initialization
**************************

    public sealed class DepartmentSingleton
    {
        private static readonly DepartmentSingleton _instance = new
                                             DepartmentSingleton();

        private DepartmentSingleton()
        {

        }

        public static DepartmentSingleton Instance
        {
            get
            {
                return _instance;
            }
        }

        public void Log(string message)
        {
            Console.WriteLine(message);
        }

    }


Main program:
**************

static void Main(string[] args)
        {
            EmployeeSingleton obj1 = EmployeeSingleton.Instance;
            DepartmentSingleton obj2 = DepartmentSingleton.Instance;

            obj1.Log("test 1");
            obj2.Log("test 2");

            Console.Read();


        }

From this post you can learn how to create a singleton design pattern in c# lazy and eager initialization.



Delete a Queue in Microsoft Azure storage account.

In this post we are going to see how to delete a queue in Microsoft Azure storage account.

Install the Following package
1. WindowsAzure.Storage
2. Install-Package Microsoft.WindowsAzure.ConfigurationManager -Version 3.2.3

class Program
    {

        // Nuget Packages
        // -Install-Package Microsoft.WindowsAzure.ConfigurationManager -Version 3.2.3
        static void Main(string[] args)
        {
            CloudStorageAccount account = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("azureStorageAccount"));
            var queueClient = account.CreateCloudQueueClient();

            /* Get the reference of the queue */
            var testQueue = queueClient.GetQueueReference("testingqueue");

            /* Deleting the queue if exists */
            testQueue.DeleteIfExists();

        }

    }

From the above code you can learn how to delete a queue in Microsoft Azure storage account.

Create a Queue in Microsoft Azure storage account and send message to it

In this post we are going to see how to create a queue in Microsoft Azure storage account and send the message to that queue. First we have to configure the connectionstring of the storage account in the appsetting of app.config.

Install the Following package
1. WindowsAzure.Storage
2. Install-Package Microsoft.WindowsAzure.ConfigurationManager -Version 3.2.3

Queue name should be lower case otherwise it will return bad request.

Please see this link for Queue naming rules: https://msdn.microsoft.com/en-us/library/azure/dd179349.aspx.

After installing above two packages now start the coding.

class Program
    {

        static void Main(string[] args)
        {
            CloudStorageAccount account = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("azureStorageAccount"));

            var queueClient = account.CreateCloudQueueClient();

            /* Get the reference of the queue */
            var testQueue = queueClient.GetQueueReference("testingqueue");

            /* Create a Queue if not exists */
            testQueue.CreateIfNotExists();

            CloudQueueMessage message = new CloudQueueMessage("Hai sample");

            /* Adding a message to Queue */
            testQueue.AddMessage(message);


        }

    }

use the Microsoft Azure storage Explorer for viewing the queue message.
https://azure.microsoft.com/en-us/features/storage-explorer/


Output:
************





From this post you can learn how to create a queue in Microsoft Azure storage account and send the message to that queue.

Saturday, 15 September 2018

Create Azure Durable Functions which includes Orchestrator Function and Activity Function - Part 2

In this post we are going to see the implementation of  Durable Function which includes Orchestrtor Function and Activity Function

Please click on the below link for the Azure Durable Function source code
AzureDurableFunctions Source Code


We will take a scenario, inside the Orchsetrator Function, we will call two Activity Function, one Activity function returns the books list and second activity will save the books list to the Azure Table Storage.

1. Create a New Project
2. Select cloud in the left pane
3. Select Azure Functions in the right pane.
4. Give Azure Function name as "BookFunction" and click ok.



5. Select the HttpTrigger from the menu
6. Click ok




7. Install the following nuget package in the solution

Microsoft.Azure.WebJobs.Extensions.DurableTask




8. Change the input parameter for the function. add the OrchestrationClient Attribute with     
    DurableOrchestrationClient

[OrchestrationClient]DurableOrchestrationClient starter,



9. TestFunction.cs
******************


public static class TestFunction
    {
        [FunctionName("TestFunction")]
        public static async Task<HttpResponseMessage> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post",
                         Route = null)]HttpRequestMessage req,
            [OrchestrationClient]DurableOrchestrationClient starter,
            TraceWriter log)
        {
            log.Info("C# HTTP trigger function processed a request.");
            // Function input comes from the request content.
            string instanceId = await starter.StartNewAsync("Orchestrator", "TedTalk");

            log.Info($"Started orchestration with ID = '{instanceId}'.");
               
            return starter.CreateCheckStatusResponse(req, instanceId);
        }       
        

    }


Let we start the Program for Azure Durable Functions. From the above code you can see that we are calling a durable function Orchestrator  await starter.StartNewAsync("Orchestrator""TedTalk");


10. Add another Function named it as OrchestratorFunction , It is decorated by [OrchestrationTrigger] with DurableOrchestrationContext, Now if you see inside the function we are calling two Activity function named "GetAllData" and "SaveData"

OrchestratorFunction.cs
*********************************


    public class OrchestratorFunction
    {
        [FunctionName("Orchestrator")]
        public static async Task<string> RunOrchestrator([OrchestrationTrigger]
                 DurableOrchestrationContext context)
        {
            var name = context.GetInput<string>();

            // retrieves the list of data by invoking a separate Activity Function.
            var books = await context.CallActivityAsync<List<Book>>("GetAllData", name);
            if (books.Count > 0)
            {
                //Saving the retrieved data to table
                await context.CallActivityAsync("SaveData", books);
            }
            return context.InstanceId;
        }

    }



11. Add another Function named it as ActivityFunction, It is decorated by [ActivityTrigger] with DurableActivityContext, Now create two functions inside the file one is for "GetAllData" another one is for "SaveData", This two activity functions are called inside orchestration function.

GetAllData: This activity function will return the list of books
SaveData: This activity function will save the books list to Azure Table Storage.




ActivityFunction.cs
******************************


public static class ActivityFunction
    {
        private static CloudStorageAccount account = CloudStorageAccount.Parse(Environment.GetEnvironmentVariable("AzureWebJobsStorage",                                    EnvironmentVariableTarget.Process));

        
        [FunctionName("GetAllData")]
        public static async Task<List<Book>> GetAllData( 
                            [ActivityTrigger]DurableActivityContext context)
        {
            // retrieves the book name from the Orchestrator function
            var organizationName = context.GetInput<string>();

            return new List<Book> { new Book{ Id = 1, Name = "C#" }, 
                                    new Book{ Id = 2, Name = "Java" } };
        }



        [FunctionName("SaveData")]
        public static async Task SaveData([ActivityTrigger]DurableActivityContext context)
        {
            // retrieves a list of books from the Orchestrator function
            var books = context.GetInput<List<Book>>();

            // create a table storage client
            var client = account.CreateCloudTableClient();
            var table = client.GetTableReference("Books");

            await table.CreateIfNotExistsAsync();

            TableBatchOperation tableBatchOperations = new TableBatchOperation();

            for(int i=0; i<books.Count; i++)
            {
                tableBatchOperations.Add(TableOperation.InsertOrMerge(
                    new BookRepository(books[i].Id)
                    {
                        Name = books[i].Name
                    }));
            }

            await table.ExecuteBatchAsync(tableBatchOperations);

        }
    }

    public class BookRepository: TableEntity
    {
        public BookRepository(int id)
        {
            PartitionKey = "TechnicalBooks";
            RowKey = id.ToString();
        }

        public string Name { set; get; }
    }

    public class Book
    {
        public int Id { get; set; }

        public string Name { get; set; }


    }


Now change values in the local.settins.json for AzureWebJobsStorage to connect the azure table storage.

{
    "IsEncrypted": false,
  "Values": {
    "AzureWebJobsStorage": "UseDevelopmentStorage=true",
    "AzureWebJobsDashboard": "UseDevelopmentStorage=true"
  }

}



12. Now run the application, it will results in display the window like below




13. In the console Windows you can see the http url to hit the function, copy that url and paste that in browser. Now Orchestrator Function will be hit and two Activity Functions will be executed.




14. You see the Azure table storage , you can see the data populated from activity function.




Full source code:
*******************
Please click on the below link for the Azure Durable Function source code

AzureDurableFunctions Source Code


From this post you can learn how to use the Azure Durable Functions which includes Orchestrator Function and Activity Function.