Friday 29 December 2017

SOLID Principles in C#

I think this below article is really very nice........ and enough to understand about solid principle..





http://www.c-sharpcorner.com/UploadFile/damubetha/solid-principles-in-C-Sharp/

Wednesday 27 December 2017

how to cosume webapi in html

I think this is the best example to call:
how to cosume webapi in html




http://paxcel.net/blog/creating-asp-net-web-api-and-consuming-it-through-html-clients-


2/http://paxcel.net/blog/creating-asp-net-web-api-and-consuming-it-through-html-clients-2/

how to cosume webapi in my MVC application


http://www.c-sharpcorner.com/members/hamid-khan9


 private async Task<HttpResponseMessage> SendToApi<T>(string httpType, string endpoint, T payload, string accessToken = null)
        {
            using (var client = new HttpClient())
            {
                var baseUrl="http://localhost:8080";
                client.BaseAddress = new Uri(baseUrl);
                client.DefaultRequestHeaders.Accept.Clear();

             
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

             
                else if (!string.IsNullOrEmpty(accessToken))
                {
                    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer",accessToken);
                }
                HttpResponseMessage apiResponse = null;
                try
                {
                    switch (httpType)
                    {
                        case "Get":
                            apiResponse = await client.GetAsync(endpoint);
                            break;
                        case "Post":
                            apiResponse = await client.PostAsJsonAsync(endpoint, payload);
                            break;
                        case "Put":
                            apiResponse = await client.PutAsJsonAsync(endpoint, payload);
                            break;
                        case "Delete":
                            apiResponse = await client.DeleteAsync(endpoint);
                            break;
                    }
                }
                catch (HttpRequestException ex)
                {
                    // log the ex using logger so we have record of it
                    new MyCustomLogger().Log(ex);

                 
                }
                return apiResponse;
            }
        } 

Monday 25 December 2017

Object Equality Test in C#

  public class Employee
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public decimal Salary { get; set; }
}

// test1
        private static void ObjectEqualityTest()
        {
                     
            var e1 = new Employee();
            e1.Name = "hamid";

            var e2 = new Employee();
            e2.Name = "hamid";
           // o1 = o2;  // if i do it then all wil be true
            bool b1 = e1 == e2;  // f
            bool b2 = e1.Equals(e2);   // f
            bool b3 = object.ReferenceEquals(e1, e2);  // f

            //-------------------------------------------------//
            int a = 10;
            int b = 20;
           
            bool a1 = a == b; // f
            bool a2 = a.Equals(b);  //  f
            bool a3 = ReferenceEquals(a, b); // f

            b = 10;
            a1 = a == b; // t
            a2 = a.Equals(b);  //  t
            a3 = ReferenceEquals(a, b); // f

            //----------------------------------------------//

            string firstName = "Mahesh";
            string lastName = "Chand";
            string authorName = firstName + " " + lastName;

            string cloneAuthor = authorName.Clone().ToString();

            Console.WriteLine(authorName); Console.WriteLine(cloneAuthor);

            firstName = null;
           var afterValue=     String.Concat(firstName, firstName); // ""
            //------------------------------------------------------------------//

            int number = -123;
            bool bb = false;
            Object numberObject = number;
            object boolObject = bb;
            string author = "Mahesh Chand";
            Object[] objs = new Object[] { 555, 444, 999 };
            Console.WriteLine("Concatenate 1: {0}", String.Concat(numberObject));
            Console.WriteLine("Concatenate multiple: {0}", String.Concat(numberObject, boolObject, author));
            Console.WriteLine("Concatenate an array: {0}", String.Concat(objs));

            //----------------------------------------------------------------//
            string s1 = "a";
            string s2 = "a";

            bool c1 = s1 == s2;  // t
            bool c2 = s1.Equals(s2);   // t
            bool c3 = ReferenceEquals(s1, s2);  // t

            s2 = "b";
             c1 = s1 == s2;  // f
             c2 = s1.Equals(s2);   // f
             c3 = ReferenceEquals(s1, s2);  // f
   //------------..............--------------------------------------------------//

            object o = null;
            object p = null;
            object q = new Object();

         var chech= ReferenceEquals(o, p);  // t
            p = q;
            chech=ReferenceEquals(p, q);  // t
            chech= ReferenceEquals(o, p);  // f
           
//----..........---------------------------------------------------------------------//
            object o1 = null;
            object o2 = new object();

            //Technically, these should read object.ReferenceEquals for clarity, but this is redundant.
           var r1= ReferenceEquals(o1, o1); //true
               r1 = ReferenceEquals(o1, o2); //false
               r1 = ReferenceEquals(o2, o1); //false
               r1 = ReferenceEquals(o2, o2); //true


            r1= o2.Equals(o1); //false
            r1 = o2.Equals(o2); //true
            r1 = o1.Equals(o1); //NullReferenceException
            r1 = o1.Equals(o2); //NullReferenceException
        }

how to remove duplicate item from array in C#

class ArrayTest
    {
        public string[] RemoveDups(string[] s)
        {
            var count = s.Count();
            string[] arr = new String[count];
            for (int i = 0; i < count; i++)
            {
                if (!arr.Contains(s[i]))
                {
                    arr[i] = s[i];
                }
            }
            return arr;
        }

        public int[] RemoveDuplicationValues(int[] values)
        {
            var result = new ArrayList();
            foreach (int s in values)
            {
                if (!result.Contains(s))
                {
                    result.Add(s);
                }
            }
            return (int[])result.ToArray(typeof(int));
        }
    }

reverse string in different way in C#



public  class StringManipulation
    {
        string s1 = "hamid";
        String s2 = "Mahfooz";
        public static string ReverseString(string s1)
        {
            if (s1.Length <= 1)
                return s1;
            return ReverseString(s1.Substring(1)) + s1[0];
        }

        public static void ReverseString1(string s1)
        {
            string  Revstr = "";  //for storing string value
            int Length;               //for counting lenght of given string         
            Length = s1.Length - 1;            //storing the length of given string
            while (Length >= 0)                //loops the given string length
            {
                Revstr = Revstr + s1[Length];  //performimg a reverse string according to length of given string
                Length--;
            }
            Console.WriteLine("Reverse  String  Is  {0}", Revstr); // displaying output to user
        }
    }

    class StringTest
    {
        public static string ReverseString(string s)
        {
            string tmp = string.Empty;

            for (int i = s.Length - 1; i >= 0; i--)
            {
                tmp += s[i].ToString();
            }

            return tmp;
        }


       
    }

Console Application Using Windows Scheduler

I don't think I should write any thing more,
just go with this link, you will get as expected solution



http://www.c-sharpcorner.com/UploadFile/manas1/console-application-using-windows-scheduler/

get 2nd highest salary from list in C#

 private static void GetSalary()
        {
            var empList = new List<Employee>
            {
                new Employee {Id=1, Name="A", Salary=100},
                new Employee {Id=1, Name="B", Salary=200},
                new Employee {Id=1, Name="C", Salary=300},
                new Employee {Id=1, Name="D", Salary=100},
                new Employee {Id=1, Name="E", Salary=100},
                new Employee {Id=1, Name="D", Salary=400},
                new Employee {Id=1, Name="E", Salary=400},
                new Employee {Id=1, Name="D", Salary=200},
                new Employee {Id=1, Name="E", Salary=500},
            };
            var r1 = empList
                         .OrderByDescending(e => e.Salary)
                          .Skip(1)
                          .First();

            var r2 = empList
                            .GroupBy(e => e.Salary)
                            .OrderByDescending(g => g.Key)
                            .Skip(1)
                            .First();
        }

get 2nd highest salary from datatable in C#

step1:  Create a data table in C# , with some column and with their value

private static DataTable CreateDataTable()
        {
            DataTable dt = new DataTable
            {
                TableName = "dt1"
            };
            dt.Columns.Add("Id", typeof(int));
            dt.Columns.Add("Name");
            dt.Columns.Add("City");
            dt.Columns.Add("Department");
            dt.Columns.Add("Salary", typeof(int));

            dt.Rows.Add(1, "N1", "c1", "d1", 100);
            dt.Rows.Add(2, "N2", "c2", "d2", 100);
            dt.Rows.Add(3, "N3", "c3", "d3", 150);
            dt.Rows.Add(4, "N4", "c4", "d4", 120);
            dt.Rows.Add(5, "N5", "c5", "d5", 480);
         

            return dt;
        }

get the result:

 public static void DatatableTest()
        {
            var dt = CreateDataTable();           

            var x = (from r in dt.AsEnumerable()
                     orderby r.Field<int>("Salary") descending
                     select r).Take(2);

            var s1 = x.ElementAt(0)["Salary"];
            var s3 = x.ElementAt(1)["Salary"];

         
        }

Thursday 21 December 2017

Check for missing number in sequence

//There are numbers from 1 to N in an array. out of these, one of the number
        //    gets duplicated and one is missing.The task is to write
        //    a program to find out the duplicate number.

        public void MissAndDuplicateTest()
        {
            int[] Array1 =new int[] { 1, 2, 3, 1, 5,2 };
            int num = 1,  missed = 0, duplicated = 0;
            while (num <= Array1.Length)
            {
               // Console.WriteLine("nunn"+num + "array1 Value" + Array1[num - 1]);
                if (num != Array1[num - 1])
                {
                    missed = num;
                    duplicated = Array1[num - 1];
                    if (missed != 0 && duplicated != 0)
                        Console.WriteLine("Missed number is {0} Duplicated number is {1}", missed, duplicated);
                }
                num++;
            }
           
        }

        //Result :
        // Missed number is 4 Duplicated number is1
        // Missed number is 6 Duplicated number is 2

Wednesday 20 December 2017

get win loss and draw count in sql

SELECT TeamName,

SUM(CASE WHEN Result=’W’ THEN 1 ELSE 0 END) AS Wins,
SUM(CASE WHEN Result=’L’ THEN 1 ELSE 0 END) AS Losses,
SUM(CASE WHEN Result=’D’ THEN 1 ELSE 0 END) AS Draw,
Count (*) AS Total
FROM Team
GROUP BY TeamName

Perform left outer joins in linq C#

// Perform left outer joins

    class Person
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }

    class Child
    {
        public string Name { get; set; }
        public Person Owner { get; set; }
    }
    public class JoinTest
    {
        public static void LeftOuterJoinExample()
        {
            Person magnus = new Person { FirstName = "Magnus", LastName = "Hedlund" };
            Person terry = new Person { FirstName = "Terry", LastName = "Adams" };
            Person charlotte = new Person { FirstName = "Charlotte", LastName = "Weiss" };
            Person arlene = new Person { FirstName = "Arlene", LastName = "Huff" };

            Child barley = new Child { Name = "Barley", Owner = terry };
            Child boots = new Child { Name = "Boots", Owner = terry };
            Child whiskers = new Child { Name = "Whiskers", Owner = charlotte };
            Child bluemoon = new Child { Name = "Blue Moon", Owner = terry };
            Child daisy = new Child { Name = "Daisy", Owner = magnus };

            // Create two lists.
            List<Person> people = new List<Person> { magnus, terry, charlotte, arlene };
            List<Child> childs = new List<Child> { barley, boots, whiskers, bluemoon, daisy };

            var query = from person in people
                        join child in childs
                        on person equals child.Owner into gj
                        from subpet in gj.DefaultIfEmpty()
                        select new
                        {
                            person.FirstName,
                            ChildName = subpet!=null? subpet.Name:"No Child"
                        };
                           // PetName = subpet?.Name ?? String.Empty };

            foreach (var v in query)
            {
                Console.WriteLine($"{v.FirstName + ":",-25}{v.ChildName}");
            }
        }

        // This code produces the following output:
        //
        // Magnus:        Daisy
        // Terry:         Barley
        // Terry:         Boots
        // Terry:         Blue Moon
        // Charlotte:     Whiskers
        // Arlene:        No Child