07 October 2015

Shadowing in C#


  • In Method override  both methods (base & child class methods) have the same name, same number and same type of parameter in the same order with the same return type. The overridden base method must be virtual, abstract or override

  • but without these we can do using new keyword, this mechanism is called Shadowing

  • In the shadowing or method hiding, the child class has its own version of the function, the same function is also available in the base class.

  • Using this concept we can provide a new implementation for the base class method without overriding it.

  • Showing is used to protect against subsequent base class modification, We can change the access modifier

  • There is no control of a base class on shadowing

  • We can also use shadowing and method overriding together using the virtual and new keywords



public class BaseClass 
{
public string GetMethodOwnerName()
{
return "Base Class";
}
}
public class ChildClass : BaseClass
{
public new virtual string GetMethodOwnerName()
{
return "ChildClass";
}
}
public class SecondChild : ChildClass
{
public override string GetMethodOwnerName()
{
return "Second level Child";
}
}

static void Main(string[] args)
{
ChildClass c = new ChildClass();
Console.WriteLine(c.GetMethodOwnerName());
}


Output: ChildClass

We can't use the new and override keywords together. If you do then the compiler throws a compilation error

Shadowing  Example (using new keyword in child class method)

static void Main(string[] args) 
{
BaseClass c = new ChildClass();
Console.WriteLine(c.GetMethodOwnerName());
}


Output: Base Class

10 September 2015

ref vs out in C#

While writing a code, we often come across situations where we need to return multiple values from a single function/method. But a method can only return a single value.The question is how do we overcome such situation.Answer is simple, use reference types.


Parameters are always passed by value to a method by default.If we want to pass them by reference then we can use either out or ref keyword.


Ref


The ref keyword is used to pass an argument as a reference. This means that when value of that parameter is changed in the method, it gets reflected in the calling method. An argument that is passed using a ref keyword must be initialized in the calling method before it is passed to the called method.


Ref keyword will pass parameter as a reference this means when the value of parameter is changed in called method it get reflected in calling method also. There is no "boxing" when a value type is passed by reference


Out


The out keyword is also used to pass an argument like ref keyword, but the argument can be passed without assigning any value to it. An argument that is passed using an out keyword must be initialized in the called method before it returns back to calling method.


Out keyword also will pass parameter as a reference but here out parameter must be initialized in called method before it return value to calling method



public ActionResult Index()
{
int val1 = 0; //must be initialized for ref
int val2 = 0; //optional for out
Example1(ref val1);
ViewBag.Message += val1 + "\n"; // val1=0
Example2(out val2);
ViewBag.Message += val2 + "\n"; // val1=2
return View();
}

static void Example1(ref int value) //called method
{
//value = 1; // optional
}
static void Example2(out int value) //called method
{
value = 2; //must to assign value
}

These ref and out parameters are useful whenever your method wants to return more than one value.


Both the method definition and the calling method must explicitly use the ref / out keyword


Several inbuilt methods as "TryParse" (one of my favourite) use out and not ref, may be the internal implementation of library mainly uses ref.


Properties/Indexers/Dynamic member access cannot be passed to ref or out parameters since internally they are functions/methods and not members/variables


ref tells the compiler that the object is initialized before entering the function, while out tells the compiler that the object will be initialized inside the function.


Ref and out in method overloading


Both ref and out cannot be used in method overloading simultaneously. However, ref and out are treated differently at run-time but they are treated same at compile time (CLR doesn't differentiates between the two while it created IL for ref and out). Hence methods cannot be overloaded when one method takes a ref parameter and other method takes an out parameter. The following two methods are identical in terms of compilation.



class MyClass
{
   public void Method(out int a) // compiler error “cannot define overloaded”
   {
       // method that differ only on ref and out"
   }
  public void Method(ref int a)
   {
     // method that differ only on ref and out"
  }
}

However, method overloading can be done, if one method takes a ref or out argument and the other method takes simple argument. The following example is perfectly valid to be overloaded.



class MyClass
{
          public void Method(int a)
          {
          }
          public void Method(out int a)
          {
                   // method differ in signature.
          }
}

Ex:
public static void Foo()
{
int val = 0;
Example1(val);
Console.WriteLine(val); // Still 0!
Example2(ref val);
Console.WriteLine(val); // Now 2!
Example3(out val);
Console.WriteLine(val); // Now 3!
}

static void Example1(int value)
{
value = 1;
}
static void Example2(ref int value)
{
value = 2;
}
static void Example3(out int value)
{
value = 3;
}


































RefOut
The parameter or argument must be initialized first before it is passed to ref.It is not compulsory to initialize a parameter or argument before it is passed to an out.
It is not required to assign or initialize the value of a parameter (which is passed by ref) before returning to the calling method.A called method is required to assign or initialize a value of a parameter (which is passed to an out) before returning to the calling method.
Passing a parameter value by Ref is useful when the called method is also needed to modify the pass parameter.Declaring a parameter to an out method is useful when multiple values need to be returned from a function or method.
It is not compulsory to assign a parameter value before leaving calling method.A parameter value must be assigned within the calling method before its use.
When we use REF, data can be passed bi-directionally.When we use OUT data is passed only in a unidirectional way (from the called method to the caller method).
Both ref and out are treated differently at run time and they are treated the same at compile time.
Properties are not variables, therefore it cannot be passed as an out or ref parameter.

The out and ref keywords are useful when we want to return a value in the same variables as are passed as an argument

09 September 2015

.js vs .min.js

They are both the same functionally but the .min has all unnecessary characters (white-spaces and comments stripped out, shorter variable names, ...)  removed in order to make the file size smaller.


Just to point out as well, you are better using the minified version (.min) for your live environment as Google are now checking on page loading times. Having all your JS file minified means they will load faster and will score you more brownie points.

Extension Methods in C#.Net


  • Extension methods are a new feature in C# 3.0

  • You can use extension methods to extend a class/interface, but not to override them.

  • Extension methods are static methods of a static class, and the 1st parameter is preceded by the “this” modifier (refers to class/interface/the called value), 2nd onward parameters act as passing parameters as in normal method calling

  • you need to add the "using System.Linq" directive to the top of the code

  • Extension methods allow existing classes to be extended without relying on inheritance or having to change the class's source code

  • If the class is sealed than there in no concept of extending its functionality

  • This feature is important for all developers, especially if you would like to use the dynamism of the C# enhancements in your class's design

  • An extension method must be defined in a top-level static class

  • An extension method is defined as static method but it is called like as instance method

  • Overuse of extension methods is not a good style of programming


Ex: With Multiple Parameters
public static class MyExtensions
{
static int WordCount(this String str, char[] charArray)
{
return str.Split(charArray).Length;
}
}

And it can be called from an application by using this syntax:
string str = "Hello Extension Methods";
int i = str.WordCount(new char[] { ' ', '.', '?' });

Extension methods at compile time:


An extension method with the same name and signature in an interface or class method (1st priority) will never be called.


Inherit the class and then implement the functionality in an instance method in the derived class.


Use aggregation instead of inheritance.

Aggregation example:

university owns various departments (e.g., chemistry), and each department has a number of professors. If the university closes, the departments will no longer exist, but the professors in those departments will continue to exist. Therefore, a University can be seen as a composition of departments, whereas departments have an aggregation of professors. In addition, a Professor could work in more than one department, but a department could not be part of more than one university.


Ex1: with Interface
public interface IMyInterface
{
        // Any class that implements IMyInterface must define a method 
        // that matches the following signature. 
        void MethodB();
}

public static class Extension
{
    public static void MethodA(this IMyInterface myInterface, int i)
    {
       Console.WriteLine("Extension.MethodA");
    }
}

public class A : IMyInterface
{
      public void MethodB() { Console.WriteLine("A.MethodB()"); }
}

class ExtMethodDemo
{
static void Main(string[] args)
{
A a = new A();
a.MethodA(1); //A contains no MethodA,
//so it calls the extension method that has a matching signature.
}
}

Output:
    Extension.MethodA

Ex2: with class
public class Class1
    {
        public string Display()
        {
            return ("Display");
        }

        public string Print()
        {
            return ("Print");
        }
    }

public static class XX
    {
         public static void NewMethod(this Class1 ob)
        {
            Console.WriteLine("NewMethod");
        }
    }

class Program
    {
        static void Main(string[] args)
        {
            Class1 ob = new Class1();
            ob.Display();
            ob.Print();
            ob.NewMethod();
            Console.ReadKey();
        }
    }
}

Output:
Display
Print
NewMethod

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.


One of the great reasons for Extension methods is behind LINQ. Without extension methods a lot of what you can do in LINQ would be very hard. The Where(), Contains(), Select extension methods means a lot more functionality is added to existing types without changing their structure


The biggest disadvantage is that there's no compiler error or warning if you have a regular method and an extension method with the same signature in the same context.


Extension methods fit very well into an OOP design: consider the simple method



bool empty = String.IsNullOrEmpty (myString)

in comparison to
bool empty = myString.IsNullOrEmpty ();

Ex3: With Multiple parameters in Extension Method
class Program
{
static void Main(string[] args)
{
List<Product> Products = new List<Product>()
{
new Product{ProductName = "White Shoe", ProductPrice = 10},
new Product{ProductName = "Green Shoe", ProductPrice = 5},
new Product{ProductName = "Black Shoe", ProductPrice = 15}
};

foreach (Product p in Products)
{
Console.WriteLine("{0} costs {1} (VAT: {2})",
p.ProductName, p.ProductPrice, p.CalculateVat());
}
}
}

public static class MyExtensions
{
public static double CalculateVat(this Product p)
{
return (p.ProductPrice * .25);
}
}

public class Product
{
public string ProductName { get; set; }
public double ProductPrice { get; set; }
}

However, you do not own or have control over the Product class since it is owned by someone else. So you can’t add a CalculateVat() method to the product class, And it can be done by using EXTENSION METHODS.

24 August 2015

.xlsx sheet data to datatable in C#

using System.Data.OleDb;

string qry = "Select * from [Sheet1$]";

string excelConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + _xlsheet_filepath + ";Extended Properties=\"Excel 12.0;HDR=YES;\";Persist Security Info=False";
OleDbConnection excelConnection = new OleDbConnection(excelConnectionString);
excelConnection.Open();

DataTable dt = new DataTable();
OleDbDataAdapter exDA = new OleDbDataAdapter(qry, excelConnection);
exDA.Fill(dt);
excelConnection.Close();

18 August 2015

Search a column in a table

SELECT t.name AS table_name,
SCHEMA_NAME(schema_id) AS schema_name,
c.name AS column_name
FROM sys.tables AS t
INNER JOIN sys.columns c ON t.OBJECT_ID = c.OBJECT_ID
WHERE c.name LIKE '%_ColumnName%'
ORDER BY schema_name, table_name

14 August 2015

Delegates

It is not compulsory to create delegates. It is just the easiest way in some situations to get the thing done.


If you have multiple methods with same signature (return type & number of parameters) and want to call all the methods with single object then using delegates is the best option.


C# delegates are similar to C++ function pointers and are type safe. A delegate is a reference type variable that holds the reference to a method. The reference can be changed at runtime.


All delegates are implicitly derived from the System.Delegate class. Delegates are especially used for implementing events and the call-back methods (Anonymous). Delegates allow methods to be passed as parameters. Delegate types are sealed and immutable type. Effective use of delegate improves the performance of application.


There are three types of delegates that can be used in C#.

  • Single Delegate

  • Multicast Delegate

  • Generic Delegate


Declaring Delegates


Whenever we want to create delegate methods we need to declare with delegate keyword. Delegate methods signature should match exactly with the methods signature (Parameter list) that Invokes.


For example, consider a delegate:
public delegate int MyDelegate (string s);

The preceding delegate can be used to reference any method that has a single string parameter and returns an int type variable.


Syntax for delegate declaration is:
delegate <return type> <delegate-name> <parameter list>

Singlecast Delegate


Once a delegate type is declared, a delegate object must be created with the new keyword and be associated with a particular method. When creating a delegate, the argument passed to the new expression is written similar to a method call, but without the arguments to the method.


Following example demonstrates declaration, instantiation, and use of a delegate that can be used to reference methods that take an integer parameter and returns an integer value.



using System;

delegate int NumberChanger(int n);
namespace DelegateAppl
{
class TestDelegate
{
static int num = 10;
public static int AddNum(int p)
{
num
+= p;
return num;
}

public static int MultNum(int q)
{
num
*= q;
return num;
}
public static int getNum()
{
return num;
}

static void Main(string[] args)
{
//create delegate instances
NumberChanger nc1 = new NumberChanger(AddNum);
NumberChanger nc2 = new NumberChanger(MultNum);

//calling the methods using the delegate objects
nc1
(25);
Console.WriteLine("Value of Num: {0}", getNum());
nc2
(5);
Console.WriteLine("Value of Num: {0}", getNum());
Console.ReadKey();
}
}
}

When the above code is compiled and executed, it produces the following result:
Value of Num: 35
Value of Num: 175

Multicast Delegate


It is a delegate which holds the reference of more than one method. Delegates can be chained together; for example, multiple methods can be called on a single event


Delegate objects can be composed using the "+" operator. A composed delegate calls the two delegates it was composed from. Only delegates of the same type can be composed. The "-" operator can be used to remove a component delegate from a composed delegate.


Using this property of delegates you can create an invocation list of methods that will be called when a delegate is invoked. This is called multicasting of a delegate. The following program demonstrates multicasting of a delegate:



using System;

delegate int NumberChanger(int n);
namespace DelegateAppl
{
class TestDelegate
{
static int num = 10;
public static int AddNum(int p)
{
num
+= p;
return num;
}
public static int MultNum(int q)
{
num
*= q;
return num;
}
public static int getNum()
{
return num;
}

static void Main(string[] args)
{
NumberChanger nc;
NumberChanger nc1 = new NumberChanger(AddNum);
NumberChanger nc2 = new NumberChanger(MultNum);
nc
= nc1;
nc
+= nc2;

nc
(5);//calling multicast
Console.WriteLine("Value of Num: {0}", getNum());
Console.ReadKey();
}
}
}

When the above code is compiled and executed, it produces the following result:
Value of Num: 75

Using Delegates


The following example demonstrates the use of delegate. The delegate printString can be used to reference method that takes a string as input and returns nothing.


We use this delegate to call two methods, the first prints the string to the console, and the second one prints it to a file:



using System;
using System.IO;

namespace DelegateAppl
{
class PrintString
{
static FileStream fs;
static StreamWriter sw;

public delegate void printString(string s);
public static void WriteToScreen(string str)
{
Console.WriteLine("The String is: {0}", str);
}
public static void WriteToFile(string s)
{
fs
= new FileStream("c:\\msg.txt",FileMode.Append, FileAccess.Write);
sw
= new StreamWriter(fs);
sw
.WriteLine(s);
sw
.Flush();
sw
.Close();
fs
.Close();
}
static void Main(string[] args)
{
printString ps1
= new printString(WriteToScreen);
printString ps2
= new printString(WriteToFile);
ps1("Hello World");
ps2
("Hello World");
Console.ReadKey();
}
}
}

When the above code is compiled and executed, it produces the following result:
The String is: Hello World

Generic Delegate


Generic Delegate was introduced in .NET 3.5 that don't require to define the delegate instance in order to invoke the methods.


There are three types of generic delegates:

  • Func

  • Action

  • Predicate


Func


The Func delegate defines a method that can be called on arguments and returns a result.



Action


The Action delegate defines a method that can be called on arguments that returns void. In the given code example, delegate Action<string> is defined with string as argument.



Action<string> MyAction = y => Console.Write(y);
MyAction("Hello");
Console.ReadKey();

Predicate


The Predicate delegate defines a method that can be called on arguments and always returns Boolean type result.

12 August 2015

The Global Assembly Cache (GAC)


  • Global - Applies to the entire machine

  • Assembly - code-libraries (DLLs)

  • Cache – Place to store things for common access



  1. GAC is a common place to store code libraries (assemblies), so they're accessible to all applications running on the machine.

  2. C:\Windows\assembly for .NET 2.0 ~ 3.5, C:\WINDOWS\Micorosoft.NET\assembly (for .NET 4.0)

  3. Normal Assemblies can be shared among multiple applications on the machine by registering them in global Assembly cache (GAC).

  4. A DLL is identified by 5 parts:


Name, Version, Architecture, Culture, Public Key.


Although the first 3 are generally the big ones.




  1. To install an assembly into GAC (as Administrator)


1) Drag and Drop


2) Use GacUtil.exe with Visual Studio Command Prompt


gacutil -i [Path][Assembly Name].dll


Note: To install an assembly into the GAC, the assembly must be strongly named. Otherwise you get an error like this: Failure adding assembly to the cache: Attempt to install an assembly without a strong name.




  1. To uninstall an assembly from GAC (as Administrator)


gacutil -u [Assembly Name], Version=1.0.0.0, PublickeyToken=7896a3567gh


Note: has no extention, .dll. Version and PublickeyToken can be omitted and be checked in GAC assembly.




  1. The only requirement for an assembly to be deployed in GAC is that it should have strong name. The CLR (Common Language Runtime) refers an assembly based on specific version mentioned by the calling application/method.

  2. The two tools related to GAC are GAC Tool (gacutil.exe) and Assembly Cache Viewer (shfusion.dll). GAC Tool is used to check for assembly existence, register a shared assembly, view and manipulate contents of GAC, etc. Being a system folder, it requires administrator privileges to be used.                                   Assembly Cache Viewer is used to display the details (version, culture, etc.) associated with the assemblies contained in the cache.

  3. GAC provides the benefits of code reuse, file security (due to its installation in ‘systemroot’ directory and hence deletion is only by users with Administrator privileges), side-by-side execution (allowing multiple versions of an assembly maintained in the same folder)

  4. Unlike in COM, there is no need for the assembly in GAC to be registered before its use. Each assembly is accessed globally without any conflict by identifying its name, version, architecture, culture and public key.

07 August 2015

Struct Vs Class in C#


  1. Structs may seem similar to classes

  2. Members of a class are private by default and members of struct are public by default.

  3. When deriving a struct from a class/struct, default access-specifier for a base class/struct is public. And when deriving a class, default access specifier is private.

  4. Structures can’t have modifiers like abstract, sealed, and static whereas classes can have.

  5. Both structure and class can have partial modifiers.

  6. A structure couldn't have a destructor but in class it is possible.

  7. Classes can be inherited whereas structures not. By default structures are sealed, that is the reason structures are not supporting inheritance.

  8. You will always be dealing with instance of a class. But you can’t deal with instance of a struct (but dealing directly with them).

  9. Field/Member can't be instantiated within structures but classes allow as in the following:
    struct myStructure
    {
    string x = 2;//Not allowed
    }
    class myClass
    {
    string x = 2;//Allowed
    }


  10. Process of converting structure type into object type is called boxing and process of converting object type into structure type is called unboxing.
    Ex: int a=10;
    Object ob = (object) a; //Boxing
    a= (int) obj; //Unboxing

  11. Classes are Reference types (When you instantiate a class, it will be allocated on the heap) and Structures are Values types (lives on stack). So a class variable can be assigned null. But we cannot assign null to a struct variable.
    Static Public void Main (string [] arg) {
    MyClass obj1 =new MyClass ();
    obj1.DataMember=10;
    MyClass obj2 =obj1;
    obj2.DataMember=20;

    }
    In the above program, “MyClass obj2 =obj1” instruction indicates that both variables of type MyClass obj1 and obj2 will point to the same memory location. It basically assigns the same memory location into another variable of same type.
    So if any changes that we make in any one of the objects type MyClass will have an effect on another since both are pointing to the same memory location.
    “obj1.DataMember=10” at this line both the object’s data members will contain the value of 10. obj2.DataMember=20 at this line both the object’s data member will contains the value of 20. Eventually, we are accessing datamembers of an object through pointers.
    Unlike classes, structures are value types. For example:

    Structure MyStructure {
    Public Int DataMember; //By default, accessibility of Structure data
    //members will be private. So I am making it as
    //Public which can be accessed out side of the structure.

    }

    Static Public void Main (string [] arg){
    MyStructure obj1 =new MyStructure ();
    obj1.DataMember=10;
    MyStructure obj2 =obj1;
    obj2.DataMember=20;

    }
    In the above program, instantiating the object of MyStructure type using new operator and storing address into obj variable of type MyStructure and assigning value 10 to data member of the structure using “obj1.DataMember=10”. In the next line, I am declaring another variable obj2 of type MyStructure and assigning obj1 into that. Here .NET C# compiler creates another copy of obj1 and assigns that memory location into obj2.
    So whatever change we make on obj1 will never have an effect on another variable obj2 of type MyStructrue. So that’s why we are saying Structures are value types.

  12. All struct types implicitly inherit from the class System.ValueType

  13. In general, classes can be used when you have more complex data. And if you think that these data to be modified after creating an instance of class, then classes are absolute methods.

  14. Structs can be used for small data structures. If developer feels that data members of structure cannot be modified after creating structure, then having structure will suit.

  15. The “this” keyword gives different meaning in structure and class. How?
    In class, “this” keyword is classified as value type of class.
    In structure, “this” keyword is classified as variable type of structure.

  16. Structure must always have the default parameter-less constructor defined as public but a class might have one, so you can't define a private parameter-less constructor in structure as in the following:
    struct Me
    { private Me()// compile-time error
    { } }

    class Me
    { private Me()// runs Ok
    { } }


  17. A structure can't be abstract, a class can.

  18. Structure can inherit from interface not from any class or from other structure

21 May 2015

Sql Query vs Linq to Sql Query VS Entity Query

select NAME as names from dbo.MASTER where NAME like '%value%'


IList<string> names = (from OM in dbo.MASTER where OM.NAME.Contains("value") select OM.NAME).ToList<string>();


IList<string> names = dbo.MASTER.Where(x => x.NAME.Contains("value")).Select(x => x.NAME).ToList<string>();

Left vs right join in linq to sql

Here's how you do a left join in Linq:

var results = from tbl1 in table1
join tbl2 in table2
on tbl1.User equals tbl2.User into joined
from j in joined.DefaultIfEmpty()
select new
{
UserData = tbl1,
UserGrowth = j
};

If you want to do a right join, just swap the tables that you're selecting, like so:

var results = from tbl2 in table2
join tbl1 in table1
on tbl2.User equals tbl1.User into joined
from j in joined.DefaultIfEmpty()
select new
{
UserData = j,
UserGrowth = tbl2
};

The important part of the code is the into statement, followed by the DefaultIfEmpty. This tells Linq that we want to have the default value (i.e. null) if there isn't a matching result in the other table.


A right outer join is not possible with LINQ. LINQ only supports left outer joins. If we swap the tables and do a left outer join then we can get the behavior of a right outer join.

19 May 2015

orderby in linq to sql

SELECT DISTINCT UNIVERSE FROM dbo.MASTER ORDER BY UNIVERSE

from M in dbo.MASTER
where M.UNIVERSE != null orderby M.UNIVERSE
select new { M.UNIVERSE } ).Distinct();

12 May 2015

Difference between substring and substr in JavaScript

substr takes parameters as (from, length).
substring takes parameters as (from, to).

alert("abc".substr(1,2)); // returns "bc"
alert("abc".substring(1,2)); // returns "b"

11 May 2015

Clustered & Non-Clustered Indexes in SqlServer

Suppose we have 16 million records. When we try to retrieve records for two or three customers based on their customer id, all 16 million records are taken and comparison is made to get a match on the supplied customer ids. Think about how much time that will take if it is a web application and there are 25 to 30 customers that want to access their data through internet. Does the database server do 16 million x 30 searches? The answer is no because all modern databases use the concept of index.


Index is a database object, which can be created on one or more columns (16 Max column combinations). When creating the index will read the column(s) and forms a relevant data structure to minimize the number of data comparisons. The index will improve the performance of data retrieval and adds some overhead on data modification such as create, delete and modify.


If a table has a clustered index, then the rows of that table will be stored on disk in the same exact order. All the same entries belonging of a table would be right next to each other on disk. This is the “clustering”, or grouping of similar values, which is referred to in the term “clustered” index the query will run much faster than if the rows were being stored in some random order on the disk.


Drawback with Clustered Index:


If a given row has a value updated in one of its (clustered) indexed columns what typically happens is that the database will have to move the entire row so that the table will continue to be sorted in the same order as the clustered index column. Clearly, this is a performance hit. This means that a simple UPDATE has turned into a DELETE and then an INSERT – just to maintain the order of the clustered index. For this exact reason, clustered indexes are usually created on primary keys or foreign keys, because of the fact that those values are less likely to change once they are already a part of a table.


A table can have up to 999 non-clustered indexes because they don’t affect the order in which the rows are stored on disk like clustered indexes.


Clustered index defines the way in which data is ordered physically on the disk. And there can only be one way in which you can order the data physically. Imagine if we have two clustered indexes on a single table – which index would determine the order in which the rows will be stored? Since the rows of a table can only be sorted in only one way/index, a non-clustered index has no effect on which the order of the rows will be stored. So having more than one clustered index is not allowed.


A comparison of a non-clustered index with a clustered index with an example:


Non clustered indexes store both a value and a pointer to the actual row that holds that value. Clustered indexes don’t need to store a pointer to the actual row because of the fact that the rows in the table are stored on disk in the same exact order as the clustered index – and the row-level data like EmployeeName, EmployeeAddress, etc. are stored in its leaf nodes of the clustered index. This means that with a non-clustered index, extra work is required to retrieve data, as compared to clustered index. So, reading from a clustered index is generally faster than reading from a non-clustered index.


SQL server is using the Binary-Tree techniques to represent the clustered index. The Index page in a book is Non-Clustered index and the page numbers are clustered index arranged in a binary tree.


CREATE INDEX index_name ON table_name (column_name)

CREATE UNIQUE CLUSTERED INDEX index_name ON dbo.[Package](CreateDateKey, PackageID) WITH (ONLINE = ON, DATA_COMPRESSION = ROW)

ALTER TABLE dbo.Package WITH CHECK
ADD CONSTRAINT [index_name] PRIMARY KEY (PackageID) ON [PRIMARY]

ALTER TABLE dbo.Package WITH CHECK ADD CONSTRAINT [index_name] PRIMARY KEY NONCLUSTERED (PackageID) ON [PRIMARY]

DROP INDEX table_name.index_name

06 May 2015

Serialization vs DeSerialization

Serialization is the process of converting an object into some data format such as XML or stream of bytes in order to store the object to a memory, or a database, or a file. Its main purpose is to save the state of an object in order to be able to recreate it when needed. The reverse process is called deserialization.


You can serialize an object and transport it over the internet using HTTP between a client and a server. XML serialization results in strongly typed classes with public properties and fields that are converted to a serial format for storage or transport.


Through serialization, a developer can perform actions like sending the object to a remote application by means of a Web Service, passing an object from one domain to another, passing an object through a firewall as an XML string, or maintaining security or user-specific information across applications.


System.XML.Serialization/System.Runtime.Serialization contains the classes necessary for serializing and deserializing objects into XML format and Binary format respectively


Binary format serialization is faster than XML serialization, because Binary format writes the raw data but XML format serialization needs formatting of data as per XML


In Binary format serialization all members will be serialized.




  1. XML serialization only serializes pubic fields and properties

  2. XML serialization does not include any type information

  3. We need to have a default/non-parameterized constructor in order to serialize an object

  4. ReadOnly properties are not serialized


Let's start with a basic example. Here is a simple class the need to be serialized :



public class AddressDetails
{
public int HouseNo { get; set; }
public string StreetName { get; set; }
public string City { get; set; }
private string PoAddress { get; set; }
}

Code to serialize the above class:
using System.Xml.Serialization;
using System.IO;

public static void Main(string[] args)
{
AddressDetails details = new AddressDetails();
details.HouseNo = 4;
details.StreetName = "Rohini";
details.City = "Delhi";
Serialize(details);
}
static public void Serialize(AddressDetails details)
{
XmlSerializer serializer = new XmlSerializer(typeof(AddressDetails));
using (TextWriter writer = new StreamWriter(@"C:\Xml.xml"))
{
serializer.Serialize(writer, details);
}
}

The output after the serialization is :

<?xml version="1.0" encoding="utf-8"?>

<AddressDetails>
<HouseNo>4</HouseNo>
<StreetName>Rohini</StreetName>
<City>Delhi</City>
</AddressDetails>

Serialization can be of the following types:

  1. Binary Serialization

  2. SOAP Serialization

  3. XML Serialization


If the server and client application are .NET applications, the user can make use of binary serialization. If the client and server use two different types of systems, then the user can make use of XML type serialization. XML serialization is useful when user wants full control of how the property can be serialized. It supports XSD standard.


Remoting and Web Services depend heavily on Serialization and De-serialization.


XML Serialization Attributes


XmlAttribute: This member will be serialized as an XML attribute
XmlElement: The field will be serialized as an XML element, ex: [XmlElement("Number")]
XmlIgnore: Field will be ignored while Serialization
XmlRoot: Represent XML document's root Element