Tuesday, 15 September 2015

Skip and Take Operator

In this article I am going to explain the Take and Skip operators in LINQ to SQL. The Take operator is used to return a given number of rows from a database table and the Skip operator skips over a specifed number of rows in a database table.

1. Create a Data Context Class

I create a data context class that has tables or a stored procedure. One figure shows the EMPLOYEE table in a data context class and another all employee data in the database. This EMPLOYEE object has a relationship with the EMPLOYEE table.

Image1.jpg

2. Create UI Design

I use a GridView to show employee data. This GridView code is:

<
asp:GridView ID="gridEmployee" runat="server" AutoGenerateColumns="false">
</
asp:GridView
>


3. Take Operator

The Take operator returns a specified number of contiguous rows from the starting point of the database table. The Take operator specifies how many rows we want from the start position of the table but when we define a criteria in that case this criteria is evaluated first before the start position is determined. 
It works similar to the SQL TOP keyword where we get a specific number of contiguous top rows from a database table or can get top rows according to certain criteria.

The following code gets the top 5 rows from an EMPLOYEE object. It shows the top 5 rows from the EMPLOYEE table and shows them in the GridView.
private void GetEmployee()
    {
EmployeeOperationDataContext employeeContext = new EmployeeOperationDataContext();

        var employee = (from emp in employeeContext.EMPLOYEEs                       
                        select emp).Take(5);

        gridEmployee.DataSource = employee;
        gridEmployee.DataBind();
    }
The following code gets the top 5 rows from an EMPLOYEE object. These employees have a salary greater than 1200. They are shown in a GridView.

Image2.jpg
private void GetEmployee()
    {
        EmployeeOperationDataContext employeeContext = new EmployeeOperationDataContext();

        var employee = (from emp in employeeContext.EMPLOYEEs
                        where emp.SALARY > 1200
                        select emp).Take(5);

        gridEmployee.DataSource = employee;
        gridEmployee.DataBind();
    }
Image3.jpg

Both of the code samples shown above use the Take operator to get the top rows from a result set that is created by a query.

4. Skip Operator

The Skip operator bypasses a specified number of contiguous rows from a sequence/table and returns the remaining table. It can skip rows from the top or can be for a certain criteria, in other words it can also skip rows depending on a certain criteria. It works like NOT IN in SQL.

The following code skips top 5 rows from EMPLOYEE object and getting remaining rows. It shows all rows from EMPLOYEE table except top 5 rows and showing in GridView.
public void GetEmployee()
    {
        EmployeeOperationDataContext employeeContext = new EmployeeOperationDataContext();

        var employee = (from emp in employeeContext.EMPLOYEEs                       
                        select emp).Skip(5);

        gridEmployee.DataSource = employee;
        gridEmployee.DataBind();
    }

Image4.jpg
The following code skips 2 rows in the Employee table (these employees have a salary less than 1300) and returns the remaining rows. It shows the employee data in a GridView.
private void GetEmployee()
    {
        EmployeeOperationDataContext employeeContext = new EmployeeOperationDataContext();

        var employee = (from emp in employeeContext.EMPLOYEEs
                        where emp.SALARY < 1300
                        select emp).Skip(2);

        gridEmployee.DataSource = employee;
        gridEmployee.DataBind();
    }

Image5.jpg
Both of the code samples shown above use the Skip operator to skip the specified number of contiguous rows from a result set that is created by a query and returns the remaining rows.

Thursday, 10 September 2015

Difference between layer and tire

A layer = a part of your code, if your application is a cake, this is a slice.
A tier = a physical machine, a server.
A tier hosts one or more layers.

Example of layers:
  • Presentation layer = usually all the code related to the User Interface
  • Data Access layer = all the code related to your database access
Tier:
Your code is hosted on a server = Your code is hosted on a tier.
Your code is hosted on 2 servers = Your code is hosted on 2 tiers.
For example, one machine hosting the Web Site itself (the Presentation layer), another machine more secured hosting all the more security sensitive code (real business code - business layer, database access layer, etc.).

There are so many benefits to implement a layered architecture. This is tricky and properly implementing a layered application takes time. If you have some, have a look at this post of Microsoft:http://msdn.microsoft.com/en-gb/library/ee658109.aspx


N-layers of application may reside on the same physical computor(same tier) and the components in each layer communicates with the components of other layer by well defined interfaces. Layered architecture focuses on the grouping of related functionality within an application into distinct layers that are stacked vertically on top of each other. Communication between layers is explicit and loosely coupled. With strict layering, components in one layer can interact only with components in the same layer or with components from the layer directly below it.
The main benefits of the layered architectural style are:
Abstraction,Isolation, Manageability, Performance, Reusability, Testability.
N-tier architecture usually has atleast three separate logical parts, each located on separate physical server. Each tier is responsible for a specific functionality. Each tier is completely independent from all other tiers, except for those immediately above and below it. Communication between tiers is typically asynchronous in order to support better scalability.
The main benefits of tier achitecture styles are:
  • Maintainability: Because each tier is independent of the other tiers, updates or changes can be carried out without affecting the application as a whole.
  • Scalability: Because tiers are based on the deployment of layers, scaling out an application is reasonably straightforward.
  • Flexibility: Because each tier can be managed or scaled independently, flexibility is increased.
  • Availability: Applications can exploit the modular architecture of enabling systems using easily scalable components, which increases availability.

Types Of JIT Compiler :


·        PRE JIT Compiler.
·        ECONO JIT Compiler.
·         NORMAL JIT compiler.

   (1) PRE JIT Compiler : 
 
               Pre-JIt  compiler compiles complete source(MSIL)code to Native code in a single Compilation.

(2) ECONO JIT Compiler :

                This compiler compiles only MSIL code of those methods that are called at Runtime.

3) NORMAL JIT compiler:

                 This compiler compiles only MSIL code of those methods that are called at Runtime and that converted (native) code is stored in Cache.This happens beccause,when these methods called again it will retrieve code from cache itself without sending request to CLR.Thus,inturn saves much of Executiom time

Monday, 7 September 2015

Use of Known Type in WCF

Prerequisites

You need to be familiar with the structure of the WCF Technology and C# to better understand.

Introduction

The KnownTypeAttribute class allows you to specify, in advance, the types that should be included for consideration during deserialization.
Normally, when passing parameters and return values between a client and a service, both endpoints share all of the data contracts of the data to be transmitted.
When data arrives at a receiving endpoint, the WCF runtime attempts to deserialize the data into an instance of a common language runtime (CLR) type. The type that is instantiated for deserialization is chosen by first inspecting the incoming message to determine the data contract to which the contents of the message conform. The deserialization engine then attempts to find a CLR type that implements a data contract compatible with the message contents. The set of candidate types that the deserialization engine allows for during this process is referred to as the deserializer's set of "known types."
One way to let the deserialization engine know about a type is by using the KnownTypeAttribute. The attribute cannot be applied to individual data members, only to whole data contract types. The attribute is applied to an outer type that can be a class or a structure. In its most basic usage, applying the attribute specifies a type as a "known type." This causes the known type to be a part of the set of known types whenever an object of the outer type or any object referred to through its members is being deserialized.

Let's Do A Practical Example to Follow

Create a new WCF Service Application and implement the following model:
[DataContract] 
public abstract class Person
 {
  [DataMember]
  public int Code { get; set; }
 
  [DataMember]
  public string Name { get; set; }
 }
[DataContract]  
public class Student : Person
 {
  [DataMember]
  public int StudentId { get; set; }
 }
[DataContract]
public class Teacher : Person
 {
  [DataMember]
  public int TeacherId { get; set; }
 } 
Suppose we want to create a service that can give us lists of all the entities in the system (include Students &Teachers). First, we define the contract in the following way:
[ServiceContract]
    public interface IStudentService
    {
        [OperationContract]
        IEnumerable<Person> GetAll();
    } 
As you can see, the output of GetAll method is Person (Base type of Student & Teacher). So the service we'll implement is in the following form:
public class StudentService : IStudentService
   {
       public IEnumerable<Person> GetAll()
       {
           List<Person> listOfPerson = new List<Person>();
 
           listOfPerson.Add( new Student() 
           { Code = 1, StudentId = 123, Name = "student 1" } );
           listOfPerson.Add( new Student() 
           { Code = 1, StudentId = 124, Name = "student 2"} );
           listOfPerson.Add( new Student() 
           { Code = 1, StudentId = 125, Name = "student 3"} );          
 
 
           listOfPerson.Add( new Teacher() 
           { Code = 2, TeacherId = 321, Name = "Mehran mousavi"} );
           listOfPerson.Add( new Teacher() 
           { Code = 2, TeacherId = 322, Name = "Teacher 2" } );
           listOfPerson.Add( new Teacher() 
           { Code = 2, TeacherId = 323, Name = "Teacher 3"} );
 
           return listOfPerson;
       }
To display the output of this WCF Service, create a new ConsoleApplication project and add this service byAddServiceReference to it.
Main function of our ConsoleApplication project is as follows:
class Program
   {
       static void Main( string[] args )
       {
           StudentService.StudentServiceClient client = 
             new StudentService.StudentServiceClient();
 
           client.GetAll().ToList().ForEach( _record => 
           {
               Console.Write( "Name : {0}", _record.Name );
               Console.WriteLine( "Code : {0}", _record.Code );
           } );
 
           Console.ReadLine();
       }
   } 
After build and run the ConsoleApplication, we get a error !!!

Why !!? The problem is that when you try to invoke the service the actual implementation returns a ChildModelfor WCF Deserialize Engine has no knowledge. The clients of the service neither have knowledge of this type.
So you need to explicitly indicate this class that you are using in the implementation but is not part of the contract. This could be done by using the KnownType attribute in base Class of Student & Teacher:
[DataContract]
 [KnownType( typeof( Student ) )]
 [KnownType( typeof(Teacher) )]
 public abstract class Person
 {
     [DataMember]
     public int Code { get; set; }
 
     [DataMember]
     public string Name { get; set; }
 } 
After changing your WCF Service, now you can run Client (ConsoleApplication) and see the result successfully ...

Web Farm and Web Garden

Web Farm

This is the case where you have only one web server and multiple clients requesting for resources from the same server. But when are is huge amount of incoming traffic for your web sites, one standalone server is not sufficient to process the request. You may need to use multiple servers to host the application and divide the traffic among them. This is called “Web Farm”. So when you are hosting your single web site on multiple web servers over load balancer is called “Web Farm”. The below diagram shows the overall representation of Web Farms.
Web Farms
In general web farm architecture, a single application is hosted on multiple IIS Server and those are connected with the VIP (Virtual IP) with Load Balancer. Load Balancer IPs are exposed to external world to access. So whenever some request will come to server from clients, it will first hit the Load Balancer, then based on the traffic on each server, LB distributes the request to the corresponding web server. These web servers may share the same DB server or may be they can use a replicated server in the back end.
So, in a single statement, when we host a web application over multiple web servers to distribute the load among them, it is called Web Farm.

Web Garden

Now, let’s have a look at what is Web Garden? Both the terms sound the same, but they are totally different from each other. Before starting with Web Garden, I hope you have a fundamental idea of what an Application Pool is and what a Worker Process is. If you have already read the article, “How IIS Processes ASP.NET Request ?”, then I can expect that you now have a good idea about both of them.
Just to recall, when we are talking about requesting processing within IIS, Worker Process (w3wp.exe) takes care of all of these. Worker Process runs the ASP.NET application in IIS. All the ASP.NET functionality inside IIS runs under the scope of worker process. Worker Process is responsible for handling all kinds of request, response, session data, cache data. Application Pool is the container of worker process. Application pool is used to separate sets of IIS worker processes and enables a better security, reliability, and availability for any web application.
apppools
Now, by default, each and every Application pool contains a single worker process. Application which contains the multiple worker process is called “Web Garden”. Below is the typical diagram for a web garden application.
WebGarden Basic
In the above diagram, you can see one of the applications containing the multiple worker processes, which is now a web garden.
So, a Web application hosted on multiple servers and access based on the load on servers is called Web Farms and when a single application pool contains multiple Worker processes, it is called a web garden.


Advantages of Web Farm and Web Garden

Now, let’s have a look into the advantages of both the Web Farms and Web Gardens.

Advantages of Web Farm

  • It provides high availability. If any of the servers in the farm goes down, Load balancer can redirect the requests to other servers.
  • Provides high performance response for client requests.
  • Provides better scalability of the web application and reduces the failure of the application.
  • Session and other resources can be stored in a centralized location to access by all the servers.

Advantages of Web Garden

  • Provides better application availability by sharing requests between multiple worker process.
  • Web garden uses processor affinity where application can be swapped out based on preference and tag setting.
  • Less consumption of physical space for web garden configuration.



What is Difference between Dependency Injection (DI) & Inversion of Control (IOC) in .NET?

What is Difference between Dependency Injection (DI) & Inversion of Control (IOC) in .NET?


Inversion of control is a principle and dependency injection is a way of implementing inversion of control.

Difference between Array and ArrayList

Arrays

Arrays are strongly typed collection of same datatype and these arrays are fixed length that cannot be changed during runtime. Generally in arrays we will store values with index basis that will start with zero. If we want to access values from arrays we need to pass index values.

Declaration of Arrays

Generally we will declare arrays with fixed length and store values like as shown below


string[] arr=new string[2];
arr[0] = "welcome";
arr[1] = "Aspdotnet-suresh";
In above code I declared array size 2 that means we can store only 2 string values in array.

Arraylists

Array lists are not strongly type collection. It will store values of different datatypes or same datatype. Array list size will increase or decrease dynamically it can take any size of values from any data type. These Array lists will be accessible with “System.Collections” namespace

Declaration of Arraylist

To know how to declare and store values in array lists check below code


ArrayList strarr = new ArrayList();
strarr.Add("welcome"); // Add string values
strarr.Add(10);   // Add integer values
strarr.Add(10.05); // Add float values
If you observe above code I haven’t mentioned any size in array list we can add all the required data there is no size limit and we will use add method to bind values to array list

Difference between Array and ArrayList

Arrays
ArrayLists
These are strong type collection and allow to store fixed length
Array Lists are not strong type collection and size will increase or decrease dynamically

In arrays we can store only one datatype either int, string, char etc…

In arraylist we can store all the datatype values
Arrays belong to System.Array namespace
Arraylist belongs to System.Collection namespaces