Thursday, 7 January 2016

Use of new,override and virtual In C#

C#, provide full support for object-oriented programming including encapsulation, inheritance, and polymorphism. As a beginners perspective the most confusing concept in C# is the use of keywords new,override,virtual.These keywords used in c# for achieving polymorphism.
The override modifier extends the base class method, and the new modifier hides it.
By using new, you are asserting that you are aware that the member that it modifies hides a member that is inherited from the base class, the new keyword explicitly hides a member that is inherited from a base class. When you hide an inherited member, the derived version of the member replaces the base class version. Although you can hide members without using the new modifier, you get a compiler warning. If you use new to explicitly hide a member, it suppresses this warning.

We are going for detailed explanation and usage of new,virtual and override using some examples.

Note : Example programs are in asp.net MVC

Use of new Modifier

namespace TheCodeBehind
{
    public class TestingController : Controller
    {
       

        public ActionResult Testing()
        {

            CodeBehind cb = new CodeBehind();
            string MthodOnedata = cb.Firstmethod();
// will give : One
            InheritedOne io = new InheritedOne();
            string MthodTwodata = io.Firstmethod();
//will give : One

            return View();
        }

    }
  public   class CodeBehind
    {
      public string  Firstmethod()
      {
          return ("One");
      }
    }

  public class InheritedOne : CodeBehind
  {
  }
}

In the above code there is no issue, the issue comes when the derived class contains a function with same name, type and parameters. The below example describes it.


namespace TheCodeBehind
{
    public class TestingController : Controller
    {
      
        public ActionResult Testing()
        {

            CodeBehind cb = new CodeBehind();
            string MthodOnedata = cb.Firstmethod();
// will give :One
            InheritedOne io = new InheritedOne();
            string MthodTwodata = io.Firstmethod();
//it will give : Two
            return View();
        }

    }
  public   class CodeBehind
    {
      public string  Firstmethod()
      {
          return ("One");
      }
    }

  public class InheritedOne : CodeBehind
  {
      public string Firstmethod()
      {
          return ("Two");
      }
  }
}

Here Base class and Derived class have the same function Firstmethod().Because of inheritance the derived class get all the public,protected,internal and protected internal members from base class, in above case derived class have two methods with same type and name. So it will make confusion to the compiler, .net handles this by hiding the base class function using new modifier in derived class. If we are not using new modifiers then also .net automatically hides the base class method and  the code will compiled and executed but it shows a warning likes below.



To avoid this warning we are using the modifier new .it will hide the base class method. The following program explains how to use new modifier.

namespace TheCodeBehind
{
    public class TestingController : Controller
    {
      
        public ActionResult Testing()
        {

            CodeBehind cb = new CodeBehind();
            string MthodOnedata = cb.Firstmethod();
//One
            InheritedOne io = new InheritedOne();
            string MthodTwodata = io.Firstmethod();
//Two
            CodeBehind io1 = new InheritedOne();
            string MthodTwodata = io1.Firstmethod();
//One



            return View();
        }

    }
  public   class CodeBehind
    {
      public string  Firstmethod()
      {
          return ("One");
      }
    }

  public class InheritedOne : CodeBehind
  {
      public  new string Firstmethod()
      {
          return ("Two");
      }
  }
}

The above program will execute without any warning.

 Use of virtual and override
Virtual and override modifiers are used for achieving run time polymorphism in c#
In the above program
            CodeBehind io1 = new InheritedOne();
            string MthodTwodata = io1.Firstmethod();
//One
When we create an object for class InheritedOne with type of CodeBehind
And try to access the method using the object io1 then it will give the base class method .In order to override this base class method we are using virtual & override
Example:

namespace TheCodeBehind
{
    public class TestingController : Controller
    {
      
        public ActionResult Testing()
        {

            CodeBehind cb = new CodeBehind();
            string MthodOnedata = cb.Firstmethod();// One
            Console.WriteLine(MthodOnedata);
            InheritedOne io = new InheritedOne();
            string MthodTwodata = io.Firstmethod();//Two
            CodeBehind io1 = new InheritedOne();
            string MthodThreedata = io1.Firstmethod();//Two
          
            return View();
        }

    }
  public   class CodeBehind
    {
      public virtual string  Firstmethod()
      {
          return ("One");
      }
    }

  public class InheritedOne : CodeBehind
  {
      public  override string Firstmethod()
      {
          return ("Two");
      }
  }
}
The above example will override the base class function and results the derived class when we try to call like below

            CodeBehind io1 = new InheritedOne();
            string MthodThreedata = io1.Firstmethod();//Two

Points to remember:


  •  new modifier is used to achieve compile time polymorphism
  • virtual and override are used to achieve run time polymorphism 
  • We cannot override a non virtual method in c# until the method is not an abstract method.

Wednesday, 30 December 2015

COMBINE MULTIPLE SPIT VALUES IN SQL SERVER

Think if we have a string like below, it is actually a combination of name and state of some users.

Like arun is the name and kerala is the state. And the comma character is separate each user

'arun:kerala,anu:tamilnadu,sruthi:mumbai,prasanth:andra,sathya:kasmir
,bijoy:madyapredesh'

We want to split it using ‘,’ and ‘:’ so the results will be like

Arun
Kerala
Anu
Tamilnadu
Sruthi
Mumbai
Prasanth
Andra
Sathya
Kasmir
Bijoy
Madyapredesh

But what we need is we want to combine the results based on each user
Like below

NAME        STATE
-----------------------------
arun        kerala
anu         tamilnadu
sruthi      mumbai
prasanth    andra
sathya      kasmir
bijoy       madyapredesh

We can look how we can do it in SQL SERVER, one of the simplest method I have included here

IF OBJECT_ID('tempdb..#ResultTbl') IS NOT NULL
      DROP TABLE #ResultTbl
GO

CREATE TABLE #ResultTbl (
      NAME NVARCHAR(500)
      ,STATE NVARCHAR(500)
      )

DECLARE @SourceTbl TABLE (val NVARCHAR(500))

INSERT INTO @SourceTbl (val)
VALUES ('arun:kerala,anu:tamilnadu,sruthi:mumbai,prasanth:andra,sathya:kasmir,bijoy:madyapredesh');

WITH CTE
AS (
      SELECT Split.a.value('.', 'NVARCHAR(100)') AS Returndata
      FROM (
            SELECT CAST('<Mydata>' + REPLACE([val], ',', '</Mydata><Mydata>') + '</Mydata>' AS XML) AS Returndata
            FROM @SourceTbl
            ) AS A
      CROSS APPLY Returndata.nodes('/Mydata') AS Split(a)
      )
INSERT INTO #ResultTbl
SELECT SUBSTRING(Returndata, 0, CHARINDEX(':', Returndata))
      ,REVERSE(SUBSTRING(reverse(Returndata), 0, CHARINDEX(':', reverse(Returndata))))
FROM cte

SELECT *
FROM #ResultTbl


The result will be

NAME        STATE
-----------------------------
arun        kerala
anu         tamilnadu
sruthi      mumbai
prasanth    andra
sathya      kasmir
bijoy       madyapredesh

If you do not have split function then use the below split function

CREATE FUNCTION dbo.Split (
      @String VARCHAR(8000)
      ,@Delimiter CHAR(1)
      )
RETURNS @temptable TABLE (items VARCHAR(8000))
AS
BEGIN
      DECLARE @idx INT
      DECLARE @slice VARCHAR(8000)

      SELECT @idx = 1

      IF len(@String) < 1
            OR @String IS NULL
            RETURN

      WHILE @idx != 0
      BEGIN
            SET @idx = charindex(@Delimiter, @String)

            IF @idx != 0
                  SET @slice = left(@String, @idx - 1)
            ELSE
                  SET @slice = @String

            IF (len(@slice) > 0)
                  INSERT INTO @temptable (Items)
                  VALUES (@slice)

            SET @String = right(@String, len(@String) - @idx)

            IF len(@String) = 0
                  BREAK
      END

      RETURN
END








Saturday, 12 December 2015

Querying XML data using XQuery in SQL SERVER


In many cases we have to pass xml data as parameter to our stored procedures
And it will be very easy to handle these xml data if we can query it like normal sql tables.
Here I am explaining about how to Query XML values in Tsql.

Example 1:

 Below is a sample xml data that holds the address of a user

DECLARE @xmldata XML = '<Root>
    <Address>
    <Housename>Valiyaveetil</Housename>
    <Place>Alappuzha</Place>
    <pin>688539</pin>
    </Address>

    <Address>
    <Housename>Chaithram</Housename>
    <Place>Ernakulam</Place>
      <pin>688552</pin>
    </Address>

    <Address>
    <Housename>Prasanthi</Housename>
    <Place>Kottayam</Place>
      <pin>688536</pin>
    </Address>

    <Address>
    <Housename>RajBhavanam</Housename>
    <Place>Kollam</Place>
      <pin>688529</pin>
    </Address>


    </Root>'

We can use the following query to parse the xml look like a table format.

SELECT Housename = Adr.value('(Housename)[1]', 'nvarchar(max)')
      ,Place = Adr.value('(Place)[1]', 'nvarchar(max)')
      ,Pin = Adr.value('(pin)[1]', 'nvarchar(max)')
FROM @xmldata.nodes('/Root/Address') AS Adddress(Adr)


The result of the above query will be like below.

Housename              Place              Pin
-----------------------------------------------------------
Valiyaveetil              Alappuzha      688539
Chaithram                Ernakulam      688552
Prasanthi                  Kottayam        688536
RajBhavanam          Kollam             688529


Example 2:

In  our below example we are discussing about a different scenario, here we have a common node called Common value that is common for all other nodes, state and country are common for all users. Here I am explaining  about how we can query the xml which contains common values like below .


DECLARE @xmldatas XML = '<Root>

<CommonValue>
<state>kerala</state>
<Country>India</Country>
</CommonValue>
    <Address>
    <Housename>Valiyaveetil</Housename>
    <Place>Alappuzha</Place>
    <pin>688539</pin>
    </Address>

    <Address>
    <Housename>Chaithram</Housename>
    <Place>Ernakulam</Place>
      <pin>688552</pin>
    </Address>

    <Address>
    <Housename>Prasanthi</Housename>
    <Place>Kottayam</Place>
      <pin>688536</pin>
    </Address>

    <Address>
    <Housename>RajBhavanam</Housename>
    <Place>Kollam</Place>
      <pin>688529</pin>
    </Address>

    </Root>'


The query will be like below :

SELECT Housename = Adr.value('(Housename)[1]', 'nvarchar(max)')
,Place = Adr.value('(Place)[1]', 'nvarchar(max)')
,Pin = Adr.value('(pin)[1]', 'nvarchar(max)')
,[state] = cmnvl.value('(state)[1]', 'nvarchar(max)')
,[Country] = cmnvl.value('(Country)[1]', 'nvarchar(max)')
FROM @xmldatas.nodes('/Root/Address') AS Adddress(Adr)

CROSS APPLY @xmldatas.nodes('/Root/CommonValue') AS Commonvalues(cmnvl)


It results :

Housename              Place             Pin                  state                Country
-----------------------------------------------------------------------------------------------
Valiyaveetil             Alappuzha     688539             kerala               India
Chaithram                Ernakulam     688552            kerala               India
Prasanthi                  Kottayam       688536            kerala               India
RajBhavanam          Kollam           688529            kerala               India
https://ssl.gstatic.com/ui/v1/icons/mail/images/cleardot.gif