Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Monday, 22 April 2019

Quick Sorting C#

In this article we are going to see the Generic Quick Sorting implementation using C#.

Quick Sort :




Quick Sort is a Divide and conquer algorithm, It divides the collection int to two sub sets based on the pivot element selected, one subset is a collection elements which is smaller than pivot, another subset is collection of elements consists of larger than pivot.then each subsets are undergoes following steps again.Entire sort can be done in O(log n)

Steps :
1. Consider a element as Pivot from the List.
2. ReOrder the list so the elements which are lesser than pivot arrange previous in the order of the pivot and     the elements which are higher than pivot arrange next in the order of the pivot.
3. Recursively apply the above steps to each two subsets individually.


Algorithm :

function quicksort('array')
      if length('array') ≤ 1
          return 'array' 
      for each 'x' in 'array'
          if 'x' ≤ 'pivot' then append 'x' to 'less'
          else append 'x' to 'greater'

      return concatenate(quicksort('less'), list('pivot'), quicksort('greater'))


Now Let we see this implementation in C#

        First Derive a Generic List<T> which is comparable, Then add collection to it ,Add a additional method to it as Order to order a collection based on the Quick Sort by implementing the algorithm. Following type in Generic so any data type can be sorted using this.


class Quicksort<T>:List<T> where T : IComparable
    {
        public List<T> Order()
        {           
            return SortList(this.ToList<T>());
        }

        public  List<T> SortList(List<T> values)
        {
            List<T> _left = new List<T>();
            List<T> _right = new List<T>();

            if (values.Count() > 1)
            {
                T pivot = values[values.Count - 1];
                values.RemoveAt(values.Count - 1);

                foreach (T each in values)
                {
                    if (each.CompareTo(pivot) == 1)
                    {
                        _right.Add(each);
                    }
                    else
                    {
                        _left.Add(each);
                    }
                }
                return MergeList(SortList(_left), pivot, SortList(_right));
            }
            return values;
        }

        private List<T> MergeList(List<T> left, T pivot, List<T> right)
        {
            left.Add(pivot);
            left.AddRange(right);
            return left;
        }

    }


 Now create a Two list one with int type other with string type and order the collection using Quick sort.

class Program
    {
        static void Main(string[] args)
        {
            Quicksort<int> _sorting = new Quicksort<int>();
            _sorting.AddRange(new int[] { 3,1,8,45,2,5,7});
            Console.WriteLine("Ordering the numbers using Quick Sort");
            foreach (int s in _sorting.Order())
            {
                Console.WriteLine(s);
            }

            Quicksort<string> _names = new Quicksort<string>();
            _names.AddRange(new string[]{"Rajesh","Suresh","Pavi","Anna","Ganesh","Sathish","Kani","Hanish","Babu","Dilli"});
            Console.WriteLine();
            Console.WriteLine("Ordering the names using Quick Sort");
            foreach (string s in _names.Order())
            {
                Console.WriteLine(s);
            }
            Console.Read();
        }
    }



Output :



From this article you can learn the Generic Quick Sorting algorithm in C# and the process of algorithm.

Calling a method in dll using Reflection

In this article we are going to see how to execute the method present in the dll, with out reference inside the project using Reflection.Reflection is used to load the dll in runtime and expose the methods , properties etc.

first create a Dll using class library project with following code,

  public class Operation
    {
        public bool IsReadOnly
        {
            get { return false; }
        }

        public int Addition(params int []vals)
        {
            int temp = 0;
            foreach (var eachnum in vals)
            {
                temp += eachnum;
            }
            return temp;
        }

        public int Subtraction(int val1, int val2)
        {
            try
            {
                return val1 - val2;
            }
            catch
            {
                return -1;
            }
        }
    }



This class operation consists of two methods one for addition and another for subtraction, Now a dll is generated Mathematics.dll





Now create a Console application which is used to load the dll at runtime , and execute the subtracion at runtime with out adding reference.


static void Main(string[] args)
        {
            Assembly assem_refer = Assembly.LoadFrom(@"D:\Project\StyleManager\Assembly_Reference\Mathematics.dll");
            Type typ = assem_refer.GetTypes()[0];
            object obj = Activator.CreateInstance(typ);

            /* Fetch the method info */
            MethodInfo []method = typ.GetMethods();
            Console.WriteLine();
            Console.WriteLine("Methods are present in Dll exposed using Reflection");
            Console.WriteLine();
            /* Execute the method */
            foreach (MethodInfo meth in method)
            {
                Console.WriteLine(meth.Name);   
            }
            Console.WriteLine();
            //executing a method
            MethodInfo sub =method.Where(x=>x.Name=="Subtraction").First();
            Console.WriteLine("Method Name :" + sub.Name);
            object[] param = new object[] { 5, 3 };
            var result = sub.Invoke(obj, param);
            Console.WriteLine("Values passed as Parameter {0},{1} Result is {2} ", 5, 3, result);

            Console.Read();
        }





Output  :



From this article you can learn how to load dll in runtime.

Speaking the Text written in Notepad C#

In this article we are going to see how to make a text to speech in computer using the speech synthesizer in C#.

Virtual Human : Click here to download EXE

Browse the text file or type the text in textbox then hit speak button , system starts to speak ur content in your preferred voice mode male or female voice by the selection of radio button.

If you want to save the speech as wav you can save the speech by hit save , save options only enable when you stop the speech

Output:

Load the Text File.


Save the audio by hit save.

Code :

         SpeechSynthesizer speak = new SpeechSynthesizer();
         speak.Volume = 100;
         //speak.Rate = 5
         if(radioButton1.Checked)
             speak.SelectVoiceByHints(VoiceGender.Male);
         else if(radioButton2.Checked)                          
              speak.SelectVoiceByHints(VoiceGender.Female);
         else
             speak.SelectVoiceByHints(VoiceGender.Neutral);
               

           speak.SpeakAsync(Content.Text);

I Hope this article will give you detailed about speech class in c#.

Timer trigger in web job Azure

In this post we are going to see how to create the timer trigger in azure and what is the purpose of it.

TimerTrigger is the attribute which does the trigger for execute a function at certain intervals in webjob.

Code:
class Program
  {
    static void Main(string[] args)
    {
      JobHostConfiguration config = new JobHostConfiguration();
      config.NameResolver = new TriggerResolver();
      config.UseTimers();

      JobHost host = new JobHost(config);
      host.RunAndBlock();
    }

    private class TriggerResolver: INameResolver
    {
      public string Resolve(string name)
      {
        string value = ConfigurationManager.AppSettings[name];              
      }
    }
  }
  
  public class Startup
  {
    public static void ScheduleTrigger([TimerTrigger("%Schedule%")] TimerInfo timer)
    {
      
    }
  }
}



From the above code you can see the schedule information is loaded from configuration file using INameResolver interface

Configuration value:
<add key=”Schedule” value=”24:00:00″/>


in another way we can schedule the timer using the typeof a class or cron expression

public static void LoggingFunction([TimerTrigger("0 0 6 * * *", RunOnStartup = false)] 
TimerInfo timerInfo, TextWriter log) 
{

  //Do stuff every day at 6AM

}


in the above cron expression

*    *    *    *    *    *  command to be executed
{second} {minute} {hour} {day} {month} {day-of-week}


From this post you can learn Timer Trigger in Azure webjobs

Mock HttpClient Using Moq

In this Post we are going to see how to mock the HttpClient using HttpMessageHandler in Moq. For this first we will create sample console app, which retrieves the data from RestApi call.

namespace TestCaseApp
{
    public class Post
    {
        public int userId { setget; }

        public int id { setget; }

        public string title { setget; }

        public string body { setget; }
    }

}

Above class is a model class

namespace TestCaseApp
{
    public interface IPostUtility
    {
       Task<Post> GetData();
    }

}


From the below method you may see that we are consuming a rest api using Httpclient

namespace TestCaseApp
{
    public class PostUtilityIPostUtility
    {
        HttpClient _client;

        public PostUtility()
        {

        }

        public PostUtility(HttpClient client)
        {
            _client = client;
        }

        public async Task<Post> GetData()
        {

            using (var client = _client ?? new HttpClient())
            {

                HttpResponseMessage response = await client.GetAsync("https://jsonplaceholder.typicode.com/posts/1");
                response.EnsureSuccessStatusCode();

                using (HttpContent content = response.Content)
                {
                    string responseBody = await response.Content.ReadAsStringAsync();                   
                    var articles = JsonConvert.DeserializeObject<Post>(responseBody);
                    return articles;
                }

            }
        }
    }
}


Main.cs
************
class Program
    {
        static void Main(string[] args)
        {
            IPostUtility post = new PostUtility();

            var _post =  post.GetData();
            _post.Wait();
            var result = _post.Result;
            Console.WriteLine($" Id: {result.id}, body: {result.body}");
            Console.ReadLine();
        }      
    }



output:
***********
Id: 1, body: quia et suscipit



Above main method is the calling part , where we can see the result of Post Data. Now are going to write a moq for this method and mock the HttpClient

To Mock the HttpClient we need to use HttpMessageHandler class, mock this class and pass this is in constructor of HttpClient.


Test Method:
***************

using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using TestCaseApp;
using System.Net.Http;
using Moq;
using Moq.Protected;
using System.Threading.Tasks;
using System.Threading;

namespace TestCaseAppTests
{
    [TestClass]
    public class PostUtilityTests
    {
        private IPostUtility _postUtility;
        private Mock<HttpMessageHandler> _mockHttpMessageHandler;

        [TestInitialize]
        public void Initialize()
        {
            _mockHttpMessageHandler = new Mock<HttpMessageHandler>();
            _postUtility = new PostUtility(new HttpClient(_mockHttpMessageHandler.Object));
        }

        [TestMethod]
        public void GetPostData()
        {
            // Arrange          
            _mockHttpMessageHandler.Protected().Setup<Task<HttpResponseMessage>>("SendAsync",
                ItExpr.IsAny<HttpRequestMessage>(),
                ItExpr.IsAny<CancellationToken>())
                .Returns(Task.FromResult(new HttpResponseMessage() {
                    StatusCode = System.Net.HttpStatusCode.OK,Content =new StringContent(PostString())
                }));

            // Act
            var _result = _postUtility.GetData();
            _result.Wait();
            var data = _result.Result;

            // Assert
            Assert.AreEqual(data.body, "sample");
           
        }

        private string PostString()
        {
            return "{\"userId\": 1,\"id\": 1,\"title\": \"rajTitle\",\n  \"body\": \"sample\"}";
        }
    }
}








From this post you can learn how to mock the HttpClient using the  HttpMessageHandler in Moq