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

Wednesday 18 October 2017

filter in angularjs

 $scope.EntityTypeChange = function (entityTypeId) {
                $scope.entityTypeId = entityTypeId.id;
                $scope.EntityTypeName = $filter('filter')($scope.EntityTypes, function (value) {
                    return value.id === $scope.entityTypeId;
                })[0].val;
                $scope.GetCustomFieldsByEntityTypeId($scope.entityTypeId);
            };

Monday 9 October 2017

Handle Max JSON Length Property In C#

Recently, I faced this problem. When the data from my client side is more than 5 MB, it does not hit my MVC Controller; instead, it steps out and shows an error because it has exceeded the max JSON length.
But finally, I got the solution. So, I thought I should share it so that more people can benefit. There are basically 3 steps to do that.

Step1 

Set in the webconfig file,

<add key="aspnet:MaxJsonDeserializerMembers" value="550000"/>

Step2

Add the below code in app_start folder, or just download the attached file and paste it in your app_start folder.
  1. public sealed class CustomJsonValueProviderFactory : ValueProviderFactory  
  2.     {  
  3.         public override IValueProvider GetValueProvider(ControllerContext controllerContext)  
  4.         {  
  5.             if (controllerContext == null)  
  6.             {  
  7.                 throw new ArgumentNullException("controllerContext");  
  8.             }  
  9.   
  10.             var jsonData = GetDeserializedObject(controllerContext);  
  11.             if (jsonData == null)  
  12.             {  
  13.                 return null;  
  14.             }  
  15.   
  16.             var backingStore = new Dictionary<stringobject>(StringComparer.OrdinalIgnoreCase);  
  17.             var backingStoreWrapper = new EntryLimitedDictionary(backingStore);  
  18.             AddToBackingStore(backingStoreWrapper, String.Empty, jsonData);  
  19.             return new DictionaryValueProvider<object>(backingStore, CultureInfo.CurrentCulture);  
  20.         }  
  21.   
  22.         private static void AddToBackingStore(EntryLimitedDictionary backingStore, string prefix, object value)  
  23.         {  
  24.             var d = value as IDictionary<stringobject>;  
  25.             if (d != null)  
  26.             {  
  27.                 foreach (var entry in d)  
  28.                 {  
  29.                     AddToBackingStore(backingStore, MakePropertyKey(prefix, entry.Key), entry.Value);  
  30.                 }  
  31.                 return;  
  32.             }  
  33.   
  34.             var l = value as IList;  
  35.             if (l != null)  
  36.             {  
  37.                 for (var i = 0; i < l.Count; i++)  
  38.                 {  
  39.                     AddToBackingStore(backingStore, MakeArrayKey(prefix, i), l[i]);  
  40.                 }  
  41.                 return;  
  42.             }  
  43.   
  44.             // primitive  
  45.             backingStore.Add(prefix, value);  
  46.         }  
  47.   
  48.         private static object GetDeserializedObject(ControllerContext controllerContext)  
  49.         {  
  50.             if (  
  51.                 !controllerContext.HttpContext.Request.ContentType.StartsWith("application/json",  
  52.                     StringComparison.OrdinalIgnoreCase))  
  53.             {  
  54.                 // not JSON request  
  55.                 return null;  
  56.             }  
  57.   
  58.             var reader = new StreamReader(controllerContext.HttpContext.Request.InputStream);  
  59.             var bodyText = reader.ReadToEnd();  
  60.             if (String.IsNullOrEmpty(bodyText))  
  61.             {  
  62.                 // no JSON data  
  63.                 return null;  
  64.             }  
  65.   
  66.             var serializer = new JavaScriptSerializer {MaxJsonLength = int.MaxValue};  
  67.   
  68.             var jsonData = serializer.DeserializeObject(bodyText);  
  69.             return jsonData;  
  70.         }  
  71.   
  72.         private static string MakeArrayKey(string prefix, int index)  
  73.         {  
  74.             return prefix + "[" + index.ToString(CultureInfo.InvariantCulture) + "]";  
  75.         }  
  76.   
  77.         private static string MakePropertyKey(string prefix, string propertyName)  
  78.         {  
  79.             return (String.IsNullOrEmpty(prefix)) ? propertyName : prefix + "." + propertyName;  
  80.         }  
  81.   
  82.         private class EntryLimitedDictionary  
  83.         {  
  84.             private readonly IDictionary<stringobject> _innerDictionary;  
  85.             private int _itemCount;  
  86.   
  87.             public EntryLimitedDictionary(IDictionary<stringobject> innerDictionary)  
  88.             {  
  89.                 _innerDictionary = innerDictionary;  
  90.             }  
  91.   
  92.             public void Add(string key, object value)  
  93.             {  
  94.                 if (++_itemCount > MaximumDepth)  
  95.                 {  
  96.                     throw new InvalidOperationException(  
  97.                         "The length of the string exceeds the value set on the maxJsonLength property.");  
  98.                 }  
  99.   
  100.                 _innerDictionary.Add(key, value);  
  101.             }  
  102.   
  103.             private static int GetMaximumDepth()  
  104.             {  
  105.                 var appSettings = ConfigurationManager.AppSettings;  
  106.   
  107.                 var valueArray = appSettings.GetValues("aspnet:MaxJsonDeserializerMembers");  
  108.                 if (valueArray != null && valueArray.Length > 0)  
  109.                 {  
  110.                     int result;  
  111.                     if (Int32.TryParse(valueArray[0], out result))  
  112.                     {  
  113.                         return result;  
  114.                     }  
  115.                 }  
  116.   
  117.                 return 1000; // Fallback default  
  118.             }  
  119.   
  120.             private static readonly int MaximumDepth = GetMaximumDepth();  
  121.         }  
  122.     }  
Step 3

Add the following code in global.asax under protected void Application_Start()
 for a better appearance. I have removed the other code.
  1. protected void Application_Start()  
  2. {  
  3.    
  4.   // Increase max Json length  
  5. foreach (var factory in ValueProviderFactories.Factories)  
  6. {  
  7.    if (factory is JsonValueProviderFactory)  
  8.    {  
  9.    ValueProviderFactories.Factories.Remove(factory as JsonValueProviderFactory);  
  10.    break;  
  11.    }  
  12. }  
  13. ValueProviderFactories.Factories.Add(new CustomJsonValueProviderFactory());  
  14.    
  15. }