Tuesday, October 9, 2012

Programmer competency

This link here is nice tool to gauge self or whatever.

http://www.starling-software.com/employment/programmer-competency-matrix.html

Isolation Levels in SQL Server

Isolation is the database property that keeps concurrent transactions independent. There are multiple levels of isolation provided in SQL Server 2008.

1. Read Uncommitted
2. Read Committed
3. Repeatable Read
4. Serializable
5. Snapshot

We need to know two terms before we learn the details of the isolation levels.

Dirty Read is when you read uncommitted data. The select statement returns rows which are being processed by an unfinished transaction.

Phantom Read means that the the data that has been read may have been changed by another transaction since the data was last read. Another read may result in a different data being returned.

Read Uncommitted
This is the lowest isolation level that exists. This isolation level allows you to read data that is still being modified by some other unfinished transaction. It allows transactions to occur on the data even when you are reading it.

As expected, this Read Uncommitted may give out dirty reads without waiting for ongoing transactions to complete.So the transaction does not lock the data for read or reads do not lock the data for transaction.

Read Committed
In SQL Server, this is the default isolation level. It returns only the committed data. The select query (read) will wait till the any other transaction has exclusive lock on that data.

Repeatable Read 
This level adds additional guarantee to the read committed isolation level that multiple reads within the transaction will give out the same data.

This isolation level will place exclusive lock on the data that is being read in a transaction. So multiple reads within the transaction will return the same data even if other transactions are trying for read locks(shared) for the same data. Other read transactions will wait till the transaction with repeatable read isolation level completes.

Serializable
This is one step beyond repeatable read in that it ensures that no data is added (or modified) during a transaction with serializable isolation level. The query that modifies the data has to wait until the transaction with serializable level has completed. So this isolation level actually eliminates the possibility of phantom read.

Snapshot
This is the exact same thing as serializable. However this does not block any query inserting or updating. Instead, it creates a snapshot of data being read at that time for that transaction. If the data is read again in that transaction, it reads from the snapshot specific to that transaction. So you will get the same data within the transaction even if some other concurrent transaction has changed that data.

So no transactions are blocked for other transactions to run. However, on the negative side, this isolation level needs additional server resources especially when the data being handled is huge.

You can run DBCC useroptions command to get the details like date format and isolation level.

DBCC useroptions
Set Option                  Value
--------------------------- --------------
textsize                    2147483647
language                    us_english
dateformat                  mdy
datefirst                   7
lock_timeout                -1
quoted_identifier           SET
arithabort                  SET
ansi_null_dflt_on           SET
ansi_warnings               SET
ansi_padding                SET
ansi_nulls                  SET
concat_null_yields_null     SET
isolation level             read committed
Conclusion is that the higher you go in the isolation level, the lesser is the concurrency. But, the performance may be adversely affected because of additional blocking. One should use only the level that is required and stay clear of higher isolation levels if not really needed.

Thursday, August 9, 2012

Database ACID Rules

Relational databases support transactions. ACID is a set of properties that the database should support to ensure that transactions are processed reliably. Below is the short description of ACID properties.

Atomicity means that a transactions either happens or does not happen i.e. all statements of the transaction are executed (commit) or none are executed (rollback).

Consistency means that referential integrity of the database is intact at any point of time. So the database is stable before and after the transaction, even if the transaction fails.

Isolation keeps the concurrent transactions separate and independent. The row associated to the transaction cannot be accessed by any other transaction until the transaction completes.

Durability means that the committed changes survive permanently (in non volatile memory) in the database even in case of system crash (or power failure or hardware failure).

Databases support multiple levels of isolation. We will discuss the isolation levels supported by SQL Server 2008 in subsequent posts.

Thursday, July 19, 2012

Calling WCF service using JQuery

WCF services can be consumed in javascript using the JQuery api.

JQuery can invoke services exposed with all Http bindings - webHttpBinding, basicHttpBinsing, wsHttpBinding.

JQuery supports only HTTP bindings of WCF, bacause the browser can send/receive only Http (or xmlHttp) messages and JQuery is limited by browser technology. JQuery method $.ajax() supports only Http methods of GET, POST, PUT, DELETE.

GET and POST methods are the most frequently used methods.

GET request is sent via the URL string (appended to the URI with a question-mark as separator), which is visible whereas POST request is encapsulated in the body of the Http request and cannot be seen.

Since GET goes via URL, the maximum size of the GET request is limited to 255 bytes. There is no such limitation on POST request. So I prefer using POST method in all my code below. GET may also be used; both the ways are given below.

Since the web message format that we use is JSON (JSON is smaller than XML), for each operation contract in the service interface, we need to write

[OperationContract(Name = "GetMessages")]
[WebGet(UriTemplate = "/MessageId={messageId}",
            ResponseFormat = WebMessageFormat.JSON,
            RequestFormat = WebMessageFormat.JSON)]
Message GetMessages(int messageId);

OR specify different format of RESTful URI below

[OperationContract(Name = "GetMessages")]
[WebGet(UriTemplate = "/MessageId/{messageId}",
            ResponseFormat = WebMessageFormat.JSON,
            RequestFormat = WebMessageFormat.JSON)]
Message GetMessages(int messageId);

The WebGet attribute exposes the method to GET operations so that the method is directly accessible via a web browser by typing the URI on address bar of the browser and the parameters to the service method can be sent via querystring.

The WebInvoke attribute exposes the method to other Http operations like PUT, POST, DELETE

Both the above attributes have UriTemplate property to specify the format of the RESTful URI.

<serviceMetadata httpGetEnabled="true"> is added to the service config file to enable the user to view metadata through web browser and generate WSDL file.

Set includeExceptionDetailInFaults="true" allows the WCF service to throw original error (useful for debugging).

Add <webHttp/> to endpoint behavior and webHttpBinding to enable web programming model for WCF and allow the service to be accessible through web protocols (Http).

webHttpBinding

This is the ideal way of calling WCF service from JQuery. The name value pair of input parameter and value can be passed as part of the URL or as data parameter of $.ajax() method. However all the data passed can be seen as part of the URL, so it may not be always best for security considerations.

Below is the sample of the web.config for the WCF service.


<system.serviceModel>
  <behaviors>
   <serviceBehaviors>
    <behavior name="ServiceBehavior">
     <serviceMetadata httpGetEnabled="true"/>
     <serviceDebug includeExceptionDetailInFaults="true"/>
    </behavior>
   </serviceBehaviors>
   <endpointBehaviors>
    <behavior name="EndpBehavior">
     <webHttp/>
    </behavior>
   </endpointBehaviors>
  </behaviors>
  <services>
   <service behaviorConfiguration="ServiceBehavior" name="Service">
    <endpoint address="" binding="webHttpBinding" contract="IService" behaviorConfiguration="EndpBehavior"/>
   </service>
  </services>
</system.serviceModel>


The command for invoking the service in JQuery is below.

$.ajax({
                  type: "GET",
                  url: "../Services/Dashboard.svc/GetMessages?MessageId=4",  // the name value pair
                  contentType: "application/json; charset=utf-8",
                  dataType: "json",
                processData: false,
                  success: function(result) {
var messsage = result.d;
                                                   },
                  error: function() { alert("Error"); }
              });

This is the same as below statement. The name value pair input is sent as data parameter when POST method is used.

$.ajax({
                  type: "POST",
                  url: "../Services/Dashboard.svc/GetMessages",
                  contentType: "application/json; charset=utf-8",
                  dataType: "json",
                data: "{ MessageId:" + 4 + "}",  // the name value pair  input
                processData: false,
                  success: function(result) {
var messsage = result.d;
                                                   },
                  error: function() { alert("Error"); }
              });


basicHttpBinding


This is the same as 

Wednesday, July 18, 2012

Polymorphism

Polymorphism is the concept used to identify the observation that objects change behavior according to condition.

Etymology:  Poly - many,  Morph - forms  (Greek)

There are two types of polymorphism - static (or compile time) and dynamic (or runtime polymorphism).


Static polymorphism / Compile time polymorphism


Method overloading is an example of static polymorphism or compile time polymorphism.

In method overloading, same method exists with multiple signatures.

The return type has no role to play in differentiating the different method signatures.

Which method will be invoked is decided at the compile time or during the build.

Operators can also be overloaded. Operator overloading is also an example of static polymorphism.


Dynamic polymorphism / Runtime polymorphism


Inheritance makes method overriding possible. This is the example of dynamic or runtime polymorphism.

Keywords such as virtual, override, new etc. are used to implement overriding and method hiding in C#.

Variable of the type base class can point to any object of the derived class. However vice versa is not possible.

So object reference of the base class type can point to object of the derived class.

If there are two different methods of same name in two different classes derived from the same base class, the object of the base type will call the method in either of the derived classes depending on the class whose object it points to.

Also a method in the derived class may override the method in the base class of the same name. Whether the base class method or the derived class method is invoked, is decided at runtime based on what class object the variable points to.

This is dynamic or runtime polymorphism.

Private constructor, Static constructor, Static method

Private Constructor

A class that has a private constructor cannot be instantiated outside the class.

A class having a private constructor cannot be inherited, otherwise you would be able to override the base class private constructor and create objects.

Helper and utility classes generally have private constructors so that we call their methods without creating objects.


Static Constructor

Static constructor is used to initialize static fields of a class.

Static constructor cannot be overloaded.

One class can have only one static constructor that initializes all its static members.

Static constructor is always parameter-less.

Static constructor can access only static members of the class and NOT non-static members of the class.

Non static constructor can access only non-static members of the class and NOT static members of the class, so the need for a separate constructor for the static members called static constructor.

Static constructor is called sometime before the first object of the class is created to initialize all the static members of the class.

No access specifier like public, private or protected can be applied to the static constructor.


Static Method

Static methods cannot access non-static members of the class but only static members.

Static methods cannot be called on any object but directly on the class name.

Stored proc and function

It is a misconception that stored procs run faster than functions. The execution plans for both procs and functions are cached, so the performance suffers only the first time for both. For subsequent runs, the performance of both functions and the procs would be the same.

Procedures support DML statements (insert, update, delete) and create statement (DDL) whereas functions do not support any statements that modify data or create tables.

Procedures support transactions whereas functions do not support transactions.

Procedures may or may not return multiple values (excluding the out parameter) but a function has to return one and only one variable (and functions have no output parameters).

Functions can be part of the another SQL statement like in a select statement or a where statement. No such thing can be done with the stored procedure.

Functions cannot be run independently like stored procedures. Functions can be run only as part of other SQL statements like where, having, select.

Try catch block can be used in the procedures but not inside functions. So stored procedures support error handling (RAISEERROR).

Let me know if you find any errors in the above compilation. Adios.

Difference between abstract class and interface

A class can inherit from only one abstract class but it can inherit from (implement) multiple interfaces.

Abstract class can have abstract as well as non-abstract members, but in an interface all members are abstract by definition.

Abstract class has to provide default implementation of its non-abstract members. But interface cannot provide any implementation for any of its members.

A class deriving from an interface has to implement all members of an interface, whereas a class deriving from an abstract class has to implement only the abstract members of the base class and may or may not implement the non-abstract members (which are already implemented in the abstract base class).

The default implementation of the non-abstract members is present in the abstract class and so need not be implemented in the child classes.

In case the child class of abstract class decides to implement the non-abstract members of the abstract class, then that derived class member will override the corresponding base class member with same signature.

Abstract class can have private, protected or public members, but in an interface all the members are public by default.

Abstract class is used to define central functionality e.g., vehicle class is abstract base class for car, truck, bus classes.

Interface is used to impart peripheral functionality e.g., Human class implements IWalkable, IEatable, ISee etc.

Abstract class can have state, so it can have fields. Interface has no state so it cannot have fields, it can have only properties.


Tuesday, July 17, 2012

Encapsulation and Abstraction

Encapsulation and abstraction are two terms that are frequently confused. In reality they complement each other i.e., one cannot exist without the other.


Encapsulation

Internal data of a class should not be exposed to the outside world.

To effectively hide the class fields, we should implement properties like get, set.

We should not have public fields in a class but rather we should go with private fields exposed by public properties to implement encapsulation of data.

So the internal data of the class is encapsulated in the class with the methods that expose them.

By making members private, we hide the complex things from the outside world. This process of hiding is called encapsulation. It achieves abstraction i.e., the outside client sees only the simple stuff that was not hidden.


Abstraction

Abstraction is achieved by encapsulation of data.

The concept of showing only what is necessary and simple for client to understand - is called abstraction.

Only the minimal things that are actually needed by the client code need to be exposed.

This abstraction is done by encapsulation using keywords such as private, protected, public etc.

Internal workings of the class are abstracted from the client.