Monday, September 30, 2019

JavaScript Array map() Method


The method map() of array always creates a new array without modify the original array and the map method calls the provided function or execute the statement for each array elements

You can use map () method to iterate of each element of array instead of using JavaScript looping function like for or foreach method and it will reduce number of lines code to compare for or foreach method

Here is an example of map method to calculate the square value for each element of array

const sqrs = [1,2,3].map(x => x * x);

console.log(sqrs);

Output: Array [1, 4, 9]

another example of map method to calculate the square root of each element in the array

const sqrs = [4, 9, 16, 25].map(Math.sqrt);

console.log(sqrs);

Output: Array [2, 3, 4, 5]



Friday, September 27, 2019

SSIS: Different way to execute SSIS Package

In this blog, we will learn about the different ways in which we can execute or run the SSIS package.

  1. Execute the SSIS Package from the command prompt by using DTExec.exe command 
  2. Execute the SSIS package in SQL Server Business Intelligence Development studio – BIDS

1. DTExec.exe command:

SQL Server includes the command line tool DTEXEC.EXE which can be used to execute an SSIS package.  DTEXEC can be run from a Command Prompt or from a batch (.BAT) file

C:\Users\rtiwari>DTEXEC /FILE {Location of SSIS package}

If you have configuration file for this ssis package

C:\Users\rtiwari>DTEXEC /FILE  {Location of SSIS Package } /CONFIGFILE {Location of configuration file}

Here is an example to run ETL SSIS package with configuration file

C:\Users\rtiwari>DTEXEC /FILE  C:\\Sample\\ETL_Extract.dtsx  /CONFIGFILE C:\\Sample\\ETLConnectionStrings.dtsConfig 


2. Execute the SSIS package in SQL Server Business Intelligence Development studio:

In visual studio to execute the SSIS package, right click the package within Solution Explorer and select Execute Package option from the drop down menu as shown in the below.

execute the SSIS package



What is ASP.NET HttpRuntime


The httpRuntime element configures ASP.NET HTTP run-time settings that determine how a request for an ASP.NET application is processed and ASP.NET creates application domain for each web application that will run on a web server.

When a request comes in, ASP.NET loads the HTTP Runtime settings into process and create HTTPRuntime Object which is used to begin ASP.NET Pipeline model that process the web request and the ProcessRequest() method of HTTP Runtime starts the ASP.NET Page life cycle processing.


ASP.NET HttpRuntime



Here are few HTTPRuntime settings, which can be configured in web.config file

xml version="1.0"?>
<configuration>
  <system.web>  
    <httpRuntime executionTimeout="300" maxRequestLength="51200" targetFramework="4.6.1" maxQueryStringLength="2048" maxUrlLength="4096" />
  </system.web>
</configuration>

executionTimeout:
The executionTimeout property indicates the maximum number of seconds a request is allowed to execute before being automatically shut down by ASP.NET. The default is 110 seconds

  <system.web>  
    <httpRuntime executionTimeout="300"/>
  </system.web>

maxRequestLength:
The property maxRequestLength indicates the maximum file upload size supported by ASP.NET. This limit can be used to prevent denial of service attacks caused by users posting large files to the server. The size specified is in kilobytes. The default is 4096 KB (4 MB)

  <system.web>  
    <httpRuntime maxRequestLength="51200"/>
  </system.web>

targetFramework:
The property targetFramework indicates the version of the .NET Framework that the current web application targets

  <system.web>  
    <httpRuntime targetFramework="4.6.1"/>
  </system.web>

maxUrlLength:
The property maxUrlLength indicates the maximum length of the URL supported by ASP.NET, in bytes. The default value is 4096.

 <system.web>  
    <httpRuntime maxUrlLength="4096" />
  </system.web>

maxQueryStringLength :
The property maxQueryStringLength indicates the maximum length of the query string supported by ASP.NET, in bytes. The default value is 2048.
  <system.web>  
    <httpRuntime maxQueryStringLength="2048" />
  </system.web>

Friday, September 20, 2019

Deferred Execution vs Immediate Execution of LINQ Query

In this blog, we will discuss about how deferred query execution and Immediate Query Execution works in LINQ, and what the difference between two are.

Deferred Execution: 

Deferred execution of LINQ query means it constructs the query/expression tree and it defers query execution until its value is requested. When value is required, it evaluate the execution tree in locally and then it send generated SQL to server. Deferred execution approach improves query execution performance by avoiding unnecessary database call.

Here is an example of Deferred LINQ query:

Deferred execution of LINQ


IQueryable<Order> orders = _dbContext.Orders.Where(x => x.OrderNumber == orderNumber);

foreach (Order item in orders)
      {
       new OrderData
       {
         OrderID = item.OrderID,
         OrderNumber = item.OrderNumber,
         OrderStatusCode = item.OrderStatu.StatusCode
       };
}



For above LINQ query, the SQL is not generated until the foreach statement executes.

Expression tree – expression tree is a data structure, which holds LINQ to SQL query, which will be sent to SQL server /database.

Immediate Execution: 

Immediate execution of LINQ means it enforces the LINQ query to execute and get the result immediately and there are many methods like ToList(),ToArray(), ToDictionary() executes the LINQ query immediately.

Here is an example of Immediate LINQ query: 


Immediate execution of LINQ

IList<Order> orders = _dbContext.Orders.Where(x => x.OrderNumber == orderNumber).ToList();

foreach (Order item in orders)
      {
       new OrderData
       {
         OrderID = item.OrderID,
         OrderNumber = item.OrderNumber,
         OrderStatusCode = item.OrderStatu.StatusCode
       };
}

Thursday, September 19, 2019

How to sort a list of lists in C#

Basically Sort() method of List<T> is used to sort the elements in a list but we need to sort a list of list elements.
Here is an example, we have a list of routes collection, and these should be sorted by distance.

Listint>> forwards = new Listint>> {
                new List<int>{1, 3000},  new List<int>{2, 5000},  new List<int>{3, 4000}, new List<int>{4, 10000}
            };

If we try to sort this list by using simply use the Sort() method of List<TType

forwards.Sort();

It throws below System.InvalidOperationException: 'Failed to compare two elements in the array.'

System.InvalidOperationException: 'Failed to compare two elements in the array.'
System.InvalidOperationException
  HResult=0x80131509
  Message=Failed to compare two elements in the array.
  Source=mscorlib
  StackTrace:
   at System.Collections.Generic.ArraySortHelper`1.Sort(T[] keys, Int32 index, Int32 length, IComparer`1 comparer)
   at System.Array.Sort[T](T[] array, Int32 index, Int32 length, IComparer`1 comparer)
   at System.Collections.Generic.List`1.Sort(Int32 index, Int32 count, IComparer`1 comparer)
   at System.Collections.Generic.List`1.Sort()
   at Sample.JobT.Main() in C:\Users\rtiwari\source\repos\PDFSharp_Merge\Sample\Program.cs:line 238

Inner Exception 1:
ArgumentException: At least one object must implement IComparable.


In this scenario, we need to define Own IComparer Interface implemented class
  
  class Comparer : IComparer<int>>
        {
            public int Compare(List<int> x, List<int> y)
            {
                if (x == null || y == null)
                {
                    return 0;
                }

                // "CompareTo()" method
                return x[1].CompareTo(y[1]);

            }
        }
  
Now the Sort() method is used to sort the elements in the entire List using the specified comparer – Comparer


forwards.Sort(new Comparer());

Here is a completed example

public static void Main()
        {

            List<List<int>> forwards = new List<List<int>> {
                new List<int>{1, 3000},  new List<int>{2, 5000},  new List<int>{3, 4000}, new List<int>{4, 10000}
            };

            foreach (var item in forwards)
            {
                string t = $"[{item[0]}, {item[1]}], ";
                Console.Write(t);
            }

            Console.WriteLine();

            Console.WriteLine("After Sorting");

            forwards.Sort(new Comparer());

            foreach (var item in forwards)
            {
                string t = $"[{item[0]}, {item[1]}], ";
                Console.Write(t);
            }

  }

Console Output: 



Here is a list of the collections of routes sorted by distance.

Wednesday, September 18, 2019

Binary Search algorithm with C# example:

In this blog, we will learn about the Binary search, it is the most popular search algorithm and more efficient and also it is most commonly used technique for search. Binary Search is also known as half-interval search, logarithmic search, or binary chop.

The Binary Search is an example of divide-and-conquer algorithm and it finds the position of a target value or key within sorted array. In binary search algorithm it compares the middle element of array to target value, if they are not equal, then half of elements in array will be eliminated and it continuous search on remaining half of array and again it will take the middle element to compare to target value and repeating until the target value is found.

Binary Search Implementation


Big O notation:

Binary Search is faster than linear search, it don’t compare to each n element of arrays, so in worst case, it makes O(logn) comparison

Here is a binary search algorithm implementation in C#

     static int BinarySearch(int[] arr, int low, int high, int key)
        {
           
            while(low <= high)
            {
                //Find middle position of array
                int m = (low + high) / 2;

                // Compare the middle element item to target value -key
                if(key == arr[m])
                {
                    return m;
                }
                else if (arr[m] > key)
                {
                    high = m-1;
                }
                else
                {
                    low = m+1;
                }
            }

            return -1;
        }


public static void Main()
        {
            #region binary search

            int[] arr = new int[] {  5, 6, 7, 10, 23 , 50 };

            foreach (var item in arr)
            {
                Console.Write(item.ToString() + ',');
            }

            Console.WriteLine();

            int key = 23;

            int index = BinarySearch(arr, 0, arr.Length - 1, key);

            Console.WriteLine($"Key : {key}  Position : {index}");

   #endregion

        Console.Read(); 
}


Console Output:

Binary Search algorithm  C#



JavaScript: Reload or refresh the current URL


This blog will discuss how to refresh or reload the current window document or current page in JavaScript by using calling Location.Reload() method

Basically location object contains the information about the current URL and we can easily access location object through the window.location property.

Here is an JavaScript example to reload the current URL by using Location.Reload() method.

         $.ajax({
                url: this.action,
                type: this.method,
                data: $(this).serialize(),
                success: function (result) {
                    if (result == "Record was saved successfully") { 
                        location.reload();
                    }
                    else {
                        $('#error).html(result);
                    }
                }

In above example, we are posting form by using Ajax Post, on success event, if record was save successfully, we are reloading the current URL.

There is optional parameter for Reload () method, we can specify the optional parameter value to true to enforce to reload () method to reload current page from server instead from cache.

location.reload(true);


SQL Server - Identify unused indexes

 In this blog, we learn about the index usage information (SYS.DM_DB_INDEX_USAGE_STATS) and analyze the index usage data (USER_SEEKS, USER_S...