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

05 May 2015