Sunday 31 January 2016

What is extension methods and how to use them ?




 An extension method is a static method of a static class that can be invoked using the instance method syntax. Extension methods are used to add new behaviors to an existing type without altering. In extension method "this" keyword is used with the first parameter and the type of the first parameter will be the type that is extended by extension method.
Conceptually, extension methods provides as an implementation of the decorator structural pattern. At compile time an extension method call is translated into an ordinary static method call.


Example:-

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;

namespace DempApp
{

    public static class MyExtensions
    {
        public static int WordCount(this String str)
        {
            return str.Split(new char[] { ' ', '.', ',' }).Length;
        }
    }

    class Program
    {
        public static void Main()
        {
            string s = "WCF WPF and DotNet trating program";

            //calling extension method
            int i = s.WordCount();

            Console.WriteLine(i);
            Console.ReadKey();
        }
    }
}


 Notes:-
  • An extension method is defined as static method but it is called like as instance method.
  • An extension method first parameter specifies the type of the extended object, and it is preceded by the "this" keyword.
  • An extension method having the same name and signature like as an instance method will never be called since it has low priority than instance method.
  • An extension method couldn't override the existing instance methods.
  • An extension method cannot be used with fields, properties or events.
  • The compiler doesn't cause an error if two extension methods with same name and signature are defined in two different namespaces and these namespaces are included in same class file using directives. Compiler will cause an error if you will try to call one of them extension method.





Use of Private Constructor in C# with Example



Private Constructor

Private constructor is a special instance constructor used in a class that contains static member only. If a class has one or more private constructor and no public constructor then other classes is not allowed to create instance of this class this mean we can neither create the object of the class nor it can be inherit by other class. The main purpose of creating private constructor is used to restrict the class from being instantiated when it contains every member as static.


Example:-

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Threading;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;

namespace DempApp
{

    public class Sample
    {
        public string var1, var2;
        public Sample(string a, string b)
        {
            var1 = a;
            var2 = b;
        }
        private Sample()  // Private Constructor Declaration
        {
            Console.WriteLine("Private Constructor with no prameters");
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            // Here we don't have chance to create instace for private constructor
           // Sample obj = new Sample();     //Error

            Sample obj1 = new Sample("Welcome", "to rpsingh");
            Console.WriteLine(obj1.var1 + " " + obj1.var2);
            Console.ReadLine();
        }
    }

}


Note:-

In above method we can create object of class with parameters will work fine. If create object of class without parameters it will not allow us create.


Important points of private constructor

   1.   One use of private construct is when we have only static member.
   2.   Once we provide a constructor that is either private or public or any, the compiler will not allow us to add public constructor without parameters to the class.
    3.  If we want to create object of class even if we have private constructors then we need to have public constructor along with private constructor





What is the use of static constructor in c# ?




A static constructor is used to initialize any static data, or to perform a particular action that needs to be performed once only. It is called automatically before the first instance is created or any static members are referenced.
It is basically used to initialise the static fields and properties of the class. It can be used mainly where, in our program, we want to do something before any reference for the class is created, like changing the background of the application.



Example:-


class SimpleClass
{
    // Static variable that must be initialized at run time.
    static readonly long baseline;

    // Static constructor is called at most one time, before any
    // instance constructor is invoked or member is accessed.
    static SimpleClass()
    {
        baseline = DateTime.Now.Ticks;
    }
}



Static constructors have the following properties:

  • A static constructor does not take access modifiers or have parameters.
  • A static constructor is called automatically to initialize the class before the first instance is created or any static members are referenced.
  • A static constructor cannot be called directly.
  • The user has no control on when the static constructor is executed in the program.
  • A typical use of static constructors is when the class is using a log file and the constructor is used to write entries to this file.
  • Static constructors are also useful when creating wrapper classes for unmanaged code, when the constructor can call the LoadLibrarymethod.
  • If a static constructor throws an exception, the runtime will not invoke it a second time, and the type will remain uninitialized for the lifetime of the application domain in which your program is running.



public class Bus
 {
     // Static variable used by all Bus instances.
     // Represents the time the first bus of the day starts its route.
     protected static readonly DateTime globalStartTime;
 
     // Property for the number of each bus.
     protected int RouteNumber { get; set; }
 
     // Static constructor to initialize the static variable.
     // It is invoked before the first instance constructor is run.
     static Bus()
     {
         globalStartTime = DateTime.Now;
 
         // The following statement produces the first line of output, 
         // and the line occurs only once.
         Console.WriteLine("Static constructor sets global start time to {0}",
             globalStartTime.ToLongTimeString());
     }
 
     // Instance constructor.
     public Bus(int routeNum)
     {
         RouteNumber = routeNum;
         Console.WriteLine("Bus #{0} is created.", RouteNumber);
     }
 
     // Instance method.
     public void Drive()
     {
         TimeSpan elapsedTime = DateTime.Now - globalStartTime;
 
         // For demonstration purposes we treat milliseconds as minutes to simulate
         // actual bus times. Do not do this in your actual bus schedule program!
         Console.WriteLine("{0} is starting its route {1:N2} minutes after global start time {2}.",
                                 this.RouteNumber,
                                 elapsedTime.TotalMilliseconds,
                                 globalStartTime.ToShortTimeString());
     }
 }
 
 class TestBus
 {
     static void Main()
     {
         // The creation of this instance activates the static constructor.
         Bus bus1 = new Bus(71);
 
         // Create a second bus.
         Bus bus2 = new Bus(72);
 
         // Send bus1 on its way.
         bus1.Drive();
 
         // Wait for bus2 to warm up.
         System.Threading.Thread.Sleep(25);
 
         // Send bus2 on its way.
         bus2.Drive();
 
         // Keep the console window open in debug mode.
         System.Console.WriteLine("Press any key to exit.");
         System.Console.ReadKey();
     }
 }
 /* Sample output:
     Static constructor sets global start time to 3:57:08 PM.
     Bus #71 is created.
     Bus #72 is created.
     71 is starting its route 6.00 minutes after global start time 3:57 PM.
     72 is starting its route 31.00 minutes after global start time 3:57 PM.      
*/




Friday 29 January 2016

How to use Merge Statement is Sql Server ?


Here are a few facts that you must know before starting to use Merge Statement:


1. Atomic statement combining INSERT, UPDATE and DELETE operations based on conditional logic

2. Done as a set-based operation; more efficient than multiple separate operations

3. MERGE is defined by ANSI SQL; you will find it in other database platforms as well

4. Useful in both OLTP and Data Warehouse environments
OLTP: merging recent information from external source
DW: incremental updates of fact, slowly changing dimensions.



-- -- Update existing, add missing
MERGE INTO dbo.tbl_Customers AS C
USING dbo.tbl_CustomersTemp AS CT
        ON C.CustID = CT.CustID
WHEN MATCHED THEN
    UPDATE SET
      C.CompanyName = CT.CompanyName,
      C.Phone = CT.Phone
WHEN NOT MATCHED THEN
      INSERT (CustID, CompanyName, Phone)
      VALUES (CT.CustID, CT.CompanyName, CT.Phone)







CREATE TABLE dbo.tbl_Source (id INT, name NVARCHAR(100), qty INT);
CREATE TABLE dbo.tbl_Target (id INT, name NVARCHAR(100), qty INT);

--Synchronize source data with target
MERGE INTO dbo.tbl_Target AS t
    USING dbo.tbl_Source AS s   
        ON t.id = s.id
    WHEN MATCHED AND (t.name != s.name OR t.qty!= s.qty) THEN
        --Row exists and data is different
        UPDATE SET t.name = s.name, t.qty = s.qty
    WHEN NOT MATCHED THEN
        --Row exists in source but not in target
        INSERT VALUES (s.id, s.name, s.qty)
    WHEN SOURCE NOT MATCHED THEN
        --Row exists in target but not in source
        DELETE




In this above post I explained hoiw to use  Merge Statement in Sql server. I hpe you enjoyed it so please send your feedback and queries. Thnak You.

Thursday 28 January 2016

How to Select Records from sql as Page of given size ?





DECLARE @PageNum AS INT;
DECLARE @PageSize AS INT;
SET @PageNum = 2;
SET @PageSize = 10;

WITH UserRN AS
(
    SELECT ROW_NUMBER() OVER(ORDER BY [fldSno], fldUserType) AS RowNum
          ,fldUserID,
                fldUserType,
                 fldName
         
      FROM [CRP].[tblUserReg]
)

SELECT *
  FROM UserRN
 WHERE RowNum BETWEEN (@PageNum - 1) * @PageSize + 1
                  AND @PageNum * @PageSize
 ORDER BY RowNum, fldUserType



Result as shown below:-


Monday 11 January 2016

Differences between Sql server 2000,2005, 2008, 2008r2 and 2012




Difference between Sql server 2000 and 2005

SlNo.
Sql-2000
Sql-2005
1
Query analyser and Enterprise were separate
Both were combined as SSMS(Sql Server Management Studio)
2
There was No XML data type
XML data type introduced
3
There was no Exception handling
Exception handing introduced
4
We can’t encrypt database
We can encrypt database
5
PIVOT and UNPIVOT functions were not provided.
PIVOT and UNPIVOT functions were introduced.



Difference between Sql server 2005 and 2008


SlNo.
Sql-2005
Sql-2008
1
Merge statement is not there
Merge statement is introduced
2
DateTime is used for both date and time
DateTime separated into four types- Date, Time, DateTimeOffSet and DateTime2.
3
Table-valued parameter is not there
Table-valued parameter is introduced
4
LINQ is not there
LINQ introduced
5
Back-up  encrypt is not there
Back-up  encrypt is provided



Difference between Sql server 2008 and 2008 R2

SlNo.
Sql-2008
Sql-2008 R2
1
Its support maximum 64 logical process
Its support maximum 256 logical process
2
Master Data Services not provided
Master Data Services  provided
3
Introduced goespatail data type with few comman features in ssrs2008
Introduced goespatail data type with few comman features in ssrs2008 R2 including mapping, routing and custom shapes.



Difference between Sql server 2008 and 2012

SlNo.
Sql-2008
Sql-2012
1
Query page spliting is not there in sql-2008.
Query page spliting is implemented in sql-2012.
2
String functions CONCATE and FORMAT are not available.
String functions CONCATE and FORMAT are available.
3
Its support only 1000 partitions.
Its support only 15000 partitions.
4
Analysis services in Sql server does not have BI semantic model (BISM) concept.
Analysis services will include a new BI semantic model (BISM) concept. BISM is 3 layer  model that’s include
1.Data Model
2.Business Logics
3.Data Access layer.
5
The Sql Server 2008 uses 27 bit precision for spatial data type.
The Sql Server 2008 uses 48 bit precision for spatial data type.




In this above post I explained differences among Sql server versions. I hpe you enjoyed it so please send your feedback and queries. Thnak You.