Monday, December 28, 2015

SQL Server Performance Tuning Tips



1)    Index Analysis

Indexes are considered valuable for performance improvements. Analyse all your indexes to identify non-performing indexes and missing indexes that can improve performance.

 

2)    TempDB Space Review

Review the size and usage of your TempDB database.

 

3)    Database Files (MDF, NDF) and Log File Inspection

Review all the files and filegroups of each of your databases and analysis them to identify any object or files that are causing bottlenecks.

 

Reduce LDF File Size Steps:

CHECKPOINT -- flushes dirty pages to disk

DBCC DROPCLEANBUFFERS -- clears data cache

DBCC FREEPROCCACHE

1.right click on the database

2.goto properties--> click option--->Recovery model change to simple

3.Then run the query in query window example

( dbcc shrinkdatabase('SchoolManagementWORKING'))

4. Then right click database --> goto properties --> click option--> Recovery model change to full

 

4)    DBCC Best Practices Implementations

There are few DBCC commands to be avoided and few very crucial for system. Understand the usage of DBCC FREEPROCCACHE, DBCC SRHINKDATABASE, DBCC SHRINKFILE, DBCC DROPCLEANBUFFER, DBCC REINDEX, as well as the usage of few system stored procedures like SP_UPDATESTATS. If you are currently using any of the above mentioned and a few other DBCC maintenance task commands carefully review their usage.

 

5)    Specify the column name instead of * in select clause

 

6)    For filtering we need to use where clause at the same time  should not use Having clause until unless

We required to use aggregate functions.

 

7)    Instead of NOT In Operator we have to use Exists Operator.

 

8)    Avoid Indexing Small Tables

 

9)    Create Multiple-Column Indexes

 

      Multiple-column indexes are natural extensions of single-column indexes. Multiple-column indexes are useful for evaluating filter expressions that match a prefix set of key columns. For example, the composite index CREATE INDEX Idx_Emp_Name ON   Employees ("Last Name" ASC, "First Name" ASC) helps evaluate the following queries:
·         ... WHERE "Last Name" = 'Doe'
·         ... WHERE "Last Name" = 'Doe' AND "First Name" = 'John'
·         ... WHERE "First Name" = 'John' AND "Last Name" = 'Doe'
However, it is not useful for this query:
·         ... WHERE "First Name" = 'John'
When you create a multiple-column index, you should put the most selective columns leftmost in the key. This makes the index more selective when matching several expressions.

 


We recommend that you always create indexes on primary keys. It is frequently useful to also create indexes on foreign keys. This is because primary keys and foreign keys are frequently used to join tables. Indexes on these keys lets the optimizer consider more efficient index join algorithms. If your query joins tables by using other columns, it is frequently helpful to create indexes on those columns for the same reason.
When primary key and foreign key constraints are created, SQL Server Compact automatically creates indexes for them and takes advantage of them when optimizing queries. Remember to keep primary keys and foreign keys small. Joins run faster this way.

Use Indexes with Filter Clauses

Indexes can be used to speed up the evaluation of certain types of filter clauses. Although all filter clauses reduce the final result set of a query, some can also help reduce the amount of data that must be scanned.
A search argument (SARG) limits a search because it specifies an exact match, a range of values, or a conjunction of two or more items joined by AND. It has one of the following forms:
·         Column operator
·         operator Column
SARG operators include =, >, <, >=, <=, IN, BETWEEN, and sometimes LIKE (in cases of prefix matching, such as LIKE 'John%'). A SARG can include multiple conditions joined with an AND. SARGs can be queries that match a specific value, such as:
·         "Customer ID" = 'ANTON'
·         'Doe' = "Last Name"
SARGs can also be queries that match a range of values, such as:
·         "Order Date" > '1/1/2002'
·         "Customer ID" > 'ABCDE' AND "Customer ID" < 'EDCBA'
·         "Customer ID" IN ('ANTON', 'AROUT')
An expression that does not use SARG operators does not improve performance, because the SQL Server Compact query processor has to evaluate every row to determine whether it meets the filter clause. Therefore, an index is not useful on expressions that do not use SARG operators. Non-SARG operators include NOT, <>, NOT EXISTS, NOT IN, NOT LIKE, and intrinsic functions.

 



Sometimes you can rewrite a subquery to use JOIN and achieve better performance. The advantage of creating a JOIN is that you can evaluate tables in a different order from that defined by the query. The advantage of using a subquery is that it is frequently not necessary to scan all rows from the subquery to evaluate the subquery expression. For example, an EXISTS subquery can return TRUE upon seeing the first qualifying row.
 Note
The SQL Server Compact query processor always rewrites the IN subquery to use JOIN. You do not have to try this approach with queries that contain the IN subquery clause.
For example, to determine all the orders that have at least one item with a 25 percent discount or more, you can use the following EXISTS subquery:
SELECT "Order ID" FROM Orders O
WHERE EXISTS (SELECT "Order ID"
FROM "Order Details" OD
WHERE O."Order ID" = OD."Order ID"
AND Discount >= 0.25)
You can also rewrite this by using JOIN:
SELECT DISTINCT O."Order ID" FROM Orders O INNER JOIN "Order Details"
OD ON O."Order ID" = OD."Order ID" WHERE Discount >= 0.25

Limit Using Outer JOINs

OUTER JOINs are treated differently from INNER JOINs in that the optimizer does not try to rearrange the join order of OUTER JOIN tables as it does to INNER JOIN tables. The outer table (the left table in LEFT OUTER JOIN and the right table in RIGHT OUTER JOIN) is accessed first, followed by the inner table. This fixed join order could lead to execution plans that are less than optimal.

 

 

12) Use Parameterized Queries

If your application runs a series of queries that are only different in some constants, you can improve performance by using a parameterized query. For example, to return orders by different customers, you can run the following query:
SELECT "Customer ID" FROM Orders WHERE "Order ID" = ?
Parameterized queries yield better performance by compiling the query only once and executing the compiled plan multiple times. Programmatically, you must hold on to the command object that contains the cached query plan. Destroying the previous command object and creating a new one destroys the cached plan. This requires the query to be re-compiled. If you must run several parameterized queries in interleaved manner, you can create several command objects, each caching the execution plan for a parameterized query. This way, you effectively avoid re-compilations for all of them.












13) While there is case to use IN or BETWEEN clauses in the query, it is always advisable to use BETWEEN for better result.

14) Always avoid the use of SUBSTRING function in the query.


Monday, December 14, 2015

Difference between for and foreach loop in c#?


This is very basic question asked in many interview. I will explain in detail.
1.       The for loop executes a statement or a block of statements repeatedly until a specified expression evaluates to false.  There is need to specify the loop bounds( minimum or maximum).
int j = 0;
for (int i = 1; i <= 5; i++)
{
j = j + i ;
}

                The foreach statement repeats a group of embedded statements for each element in an array or an object collection. You do not need to specify the loop bounds minimum or maximum.
int j = 0;
int[]  myArr = new int[] { 0, 1, 2, 3, 5, 8, 13 };
foreach (int i in myArr )
{
j = j + i ;
}
2.       foreach -> Treats everything as a collection and reduces the performance. foreach creates an instance of an enumerator (returned from GetEnumerator()) and
          that enumerator also keeps state throughout the course of the foreach loop. It then repeatedly calls for the Next() object on the enumerator and runs your code for each object it returns.
        3.  Using for loop we iterate the array in both direction, that is from index 0 to 9 and from 9 to 0.
        But using for-each loop, the iteration is possible in forward direction only.
       4. In variable declaration, foreach has five variable declarations (three Int32 integers and two arrays of Int32) while for has only three (two Int32 integers and one Int32 array).
           When it goes to loop through, foreach copies the current array to a new one for the operation. While for doesn't care of that part.

               Interviewer asked me 2  scenario based question in one interview:
         a.   for (int i = 1; i <= 5; i++)
             {
               i = i + i;
             }
                          The above code will work?
                         Yes this will work.
        b.  int[] tempArr = new int[] { 0, 1, 2, 3, 5, 8, 13 };
            foreach (int i in tempArr)
            {
                i = i + 1;
     }
Above code will work?
This code will not compile. I have pasted screenshot of error.




I hope it will help somebody in interview.

Thursday, December 10, 2015

What is WCF service behavior?

I will explain about Service behaviors and how to implement in WCF.
Service behaviors is used to increase through put, scalability and to improve performance of service applications.
There is different service behaviour that determines the performance of service.

1.       Concurrency:  
By default WCF service handle only single request at a time and all other request are queued up and processed one by one.
Client can send any request but WCF service should be able to handle all requests at a time without deadlock or fail.

There are three types of Concurrency modes.

·         Single(Default): Concurrency mode single will allows only one request at a time and other request will be put in queue and handle one by one. Only single instance of service will be created.

Ex:

[ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Single)]
public class Service : IService
{

}

·         Multiple:  This mode will allow to handle multiple request parallel. Multi threads are create to each request and handle all together.
It will improve perfomance of WCF service.

[ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Multiple)]
public class Service : IService
{

                 }
·         Re-entrant:  Some times one service calls another service internally. In that case when client make request then request is assign a thread lock and it will not be released until both services are completed.
                                So if this mode is enable client request has to finish the first service call and release the lock.
[ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Reentrant)]
public class Service : IService
{

2.       Instance Context Mode:
      Instance mode decide how WCF service instance will be created and what will  be life time of object.
Whenever client request a call instance of service is created.

·         Per Call:  Every time WCF service instance will be created when client request a service.  This will work with all type of service binding.

[ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Multiple, InstanceContextMode = InstanceContextMode.PerCall)
)]
public class Service : IService
{

                 }
·         Per Session(Default): Only one service instance is created for a client request and instance will be dispose call request end. So instance per client will be created.
                                                 This is dfault value for instancing service. It works with all bindings except basichttpbindings.
[ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Multiple, InstanceContextMode = InstanceContextMode.PerSessionl)
)]
public class Service : IService
{

                 }
·         Single:  Single service instance is created for all client. It will be disposed when service is down. It is singleton instance of service.

[ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Multiple, InstanceContextMode = InstanceContextMode.Single)
)]
public class Service : IService
{

                 }

Wednesday, December 9, 2015

What is marshaling? What is use of marshaling?


Marshaling is process of converting unmanaged data type to managed data type.
Let suppose you are using unmanaged code. Data type is different in different languages.
For example int data type in C# is Int32 and it is 32 bit.
          But windows API has INT as integer data type. when we marshal Int32 to INT then we just change the type not data.

Tuesday, December 8, 2015

Explicit Interface Tutorial:


I am going demonstrate how to explicitly implement interface members and how to access those members from the interface instances.
There are two way to implement interfaces in C#.
a.     Implicit interface

All class by default implement implicit interfaces.
    Interface IVehicle
    {
        void Driving();
    }
  
    public class CAR : IVehicle
    {

           public void Driving()   
          {
            Console.Writeline("CAR CALLED");
        }
    }

b.    Explicit interface
A class that implements an interface can explicitly implement a member of that interface. When a member is explicitly implemented, it cannot be accessed through a class instance, but only through an instance of the interface. I am explaining using two examples. The first example illustrates how to explicitly implement and access interface members. The second example shows how to implement two interfaces that have the same member names.
Example 1
This example declares an interface IVehicle, and a class Car, which explicitly implements the interface member Driving(). The members are accessed through the interface instance Vehicle.

    Interface IVehicle
    {
        void Driving();
    }
  

    public class Car : IVehicle
    {
          void IVehicle .Driving()   
          {
            Console.Writeline("CAR CALLED");
         }
    }

   public static void Main()
   {
      // Declare a class instance of Car
       Car car = new Car();
     
    // Declare an interface instance of IVehicle
         IVehicle  vechile = (IVehicle )car;
     
              
      /* The following commented lines would produce compilation
         errors because they try to access an explicitly implemented
         interface member from a class instance:                   */
      //System.Console.WriteLine(car.Driving()); //Output: Compilation Error
     
      /* Print by calling the methods from an instance of the interface:*/
      //System.Console.WriteLine(vechile.Driving());//Output: CAR CALLED
   }

Example 2

Explicit interface implementation also allows us to inherit two interfaces that share the same member names and give each interface member a separate implementation. This example displays implementation of Car. The Car class inherits two interfaces IVehicle1and IVehicle2, which have same method Driving().

    Interface IVehicle1
    {
        void Driving();
    }
  
    Interface IVehicle2
    {
        void Driving();
    }


    public class Car : IVehicle1, IVehicle2
    {
          void IVehicle1.Driving()   
          {
            Console.Writeline("IVehicle1.Car called");
         }

          void IVehicle2.Driving()   
          {
            Console.Writeline("IVehicle2.Car called ");
         }

    }


   public static void Main()
   {
      // Declare a class instance Car
       Car car = new Car();
      // Declare an instance of the IVehicle1 interface:
      IVehicle1 vechile1= (IVehicle1) car;
      // Declare an instance of the IVehicle2 interface:
      IVehicle2 vechile2 = (IVehicle2) car;

      System.Console.WriteLine(vechile1.Driving());//Output: IVehicle1.Car called

      System.Console.WriteLine(vechile2.Driving());//Output: IVehicle2.Car called
   }
}
·     


      Note:

·         Explicit interface should be avoided.
·         Explicit interfaces cannot be used by the derived classes.
·         The only time it should be used when for reasons you want to implement the interface but the hide some methods and show methods via the class.
·         It should be used when two interfaces have same member and all members need to provide different implementation.



Write a program to reverse a string? using System; namespace ConsoleApp1 {     class Program     {         static void Main(string[] args)  ...