Wednesday, October 2, 2019

What is SQL ?

SQL stands for Structured Query Language and it is an ANSI (American National Standards Institute) standard computer language for accessing and manipulating database systems. It is used for managing data in relational database management system which stores data in the form of tables and relationship between data is also stored in the form of tables. SQL statements are used to retrieve and update data in a database.

What is SQL

SQL statements are broadly categorized into 4 types.

1.   Data definition language (DDL)
2.   Data manipulation language (DML)
3.   Data Control Language (DCL)
4.   Transaction Control Statement (TCS)

Data definition language (DDL):
Data definition language type of SQL statement is used to define database objects like tables and index structures and example of DDL statements are Create, Alter, Delete, Truncate and Drop.

There are T-SQL example of T-SQL DDL statements to create database table and delete column name of table

CREATE TABLE OrderStatus

(
       StatusID int IDENTITY(1,1) NOT NULL PRIMARY KEY,
       StatusCode varchar(3) NOT NULL,
       StatusDescription varchar(50)    
)

GO

ALTER TABLE OrderStatus
DROP COLUMN StatusDescription;

GO

DROP TABLE OrderStatus

Data manipulation language (DML):
Data manipulation language type of SQL statement is used to managing data in database and example of DML statements are Select, Insert, Update, Delete and Merge

There are example of T-SQL DML statements to select records from table, insert data in table and update data in table based on condition

SELECT Name, Sex, Address FROM dbo.persons

GO

INSERT INTO Persons(Name, Sex, Address)
VALUES ('Smith', 'M','8693 Main ST')

GO

Update Persons SET Sex = 'F' Where Name = 'Julie'

Data Control Language (DCL):
Data Control Language type of SQL statement is used to grant the access permission on database object and control access to data stored in database and main DCL statement are Grant and Revoke.

There are example of T-SQL DCL statement to grant and revoke select permission on Person table from user

GRANT SELECT ON Person TO 'rtiwari'

GO

REVOKE SELECT ON Person FROM 'rtiwari'


Transaction Control Statement (TCS):
Transaction Control Statement (TCS) type of SQL statement is used to manage the current transaction and it includes Commit, Rollback and Begin Transaction

There are example of T-SQL TCS statement to commit the current transactions and rollback transaction

BEGIN TRANSACTION;  
Update Persons SET Sex = 'F' Where Name = 'Julie'
COMMIT TRANSACTION; 

GO

BEGIN TRANSACTION;  
DELETE FROM Persons 
    WHERE Address like 'Main%';  
ROLLBACK TRANSACTION; 

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.

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...