जगदीश खोलिया: May 2012

Thursday, May 31, 2012

What are the ways to do security in WCF?

In WCF there are two types of Security, transport level security and message level security.
Transport Security: Transport level security happens at the channel level. Transport level security is the easiest to implement as it happens at the communication level. WCF uses transport protocols like TCP, HTTP, MSMQ etc and every of these protocols have their own security mechanisms. One of the common implementation of transport level security is HTTPS. HTTPS is implemented over HTTP protocols with SSL providing the security mechanism. No coding change is required it’s more of using the existing security mechanism provided by the
protocol.Web config setting like the below example for transport security.See the bold lines:
<services>
            <service behaviorConfiguration="BimaExpress.Services.Service1Behavior"  name="BimaExpress.Services.Service1">
                <endpoint address="https://localhost:58946/myservice.svc" binding="wsHttpBinding"  bindingConfiguration="WSHttpBinding_IChildInsuranceService" contract="BimaExpress.Services.IService1">
               </endpoint>
                <endpoint address="mex" binding="mexHttpsBinding" contract="IMetadataExchange"/>
           </service>
</services>
<behaviors>
     <serviceBehaviors>
        <behavior name="BimaExpress.Services.Service1Behavior">
         <serviceMetadata httpsGetEnabled="true" />
         <serviceDebug includeExceptionDetailInFaults="false" />
       </serviceBehaviors>
        </behavior>
</behaviors>
<bindings>
   <wsHttpBinding>
        <binding name="WSHttpBinding_IChildInsuranceService">
          <security mode="Transport">
               <transport clientCredentialType="none"  />
           </security>
        </binding>
    </wsHttpBinding>
</bindings>

Message Security: Message level security is implemented with message data itself. Due to this it is independent of the protocol. Some of the common ways of implementing message level security is by encrypting data using some standard encryption algorithm.Check the below link for implementation:
http://pratapreddypilaka.blogspot.in/2011/10/wcf-implementing-message-level-security.html

Tuesday, May 29, 2012

Difference between "throw" and "throw ex" in .NET

When you use the throw with an empty parameter, you are re-throwing the last exception. When you throw the existing exception you are creating a new exception.  
What's the difference? Simple: the stack trace.
The empty parameter re-throw keeps the existing stack list, the parametered version creates a new stack trace to the point of the throw. For debugging, the empty version tells you where the error actually occurred, the parametered version discards that. Exception bubbling means that even though you are catching the exception and doing something with it, you want that exception to "bubble" up from your code to the calling code so it has a chance to do something with that exception. This is a fairly common scenario, but it has the potential to cause some major problems when you are debugging.
   1: try
   2: {
   3:     // do some operation that can fail
   4: }
   5: catch (Exception ex)
   6: {
   7:     // do some local cleanup
   8:     throw ex;
   9: }
This code looks perfectly reasonable and does the job. It properly catches the exception, does some local cleanup and then bubbles the exception up the chain. (A side note here is that you really shouldn't catch a general exception like this. I'm doing this for simplicity in the examples, but you should be catching specific exceptions and only those that you can do something about.)
However, how  many of you have seen code that looks like this
   1: try
   2: {
   3:     // do some operation that can fail
   4: }
   5: catch (Exception ex)
   6: {
   7:     // do some local cleanup
   8:     throw;
   9: }
There is a subtle difference between these two calls that won't be apparent until you are trying to debug the problem. That difference is in the stack trace information that gets sent with the exception.
In the first case, the stack trace is truncated below the method that failed. What this means is that when you look at the stack trace, it will look as if the exception originated in your code. This isn't always the case, particularly if you are bubbling up a CLR generated exception (like a SqlException). This is a problem known as "breaking the stack", because you no longer have the full stack trace information. This happens because you are in essence creating a new exception to throw.
By using "throw" by itself, you preserve the stack trace information. You can confirm this by looking at the IL generated for these two code blocks. This makes the difference very obvious since in the first example the IL instruction called is "throw" while in the second the instruction is called "rethrow".
Before you run and change all of your code, there are still places where "throw ex" is appropriate. There are times when you want to add information to the exception that was caught or change it into a more meaningful exception. In these instances you actually want a new exception to be thrown. Again, there are two ways you can do this. The most common way that I have seen is
   1: try
   2: {
   3:     // do some operation that can fail
   4: }
   5: catch (Exception ex)
   6: {
   7:     // do some local cleanup
   8:     throw new ApplicationException("operation failed!");
   9: }
However, this still suffers the problem of breaking the stack. Here you are generating a completely new exception and loosing any of the stack trace information from the original exception. What you really want to do is
   1: try
   2: {
   3:     // do some operation that can fail
   4: }
   5: catch (Exception ex)
   6: {
   7:     // do some local cleanup
   8:     throw new ApplicationException("operation failed!", ex);
   9: }
By passing the original exception to the ApplicationException you are preserving the original exception, and it's stack trace information, as the inner exception to your ApplicationException.
To wrap everything up
    1. Only catch exceptions if they are important to you and you need to do some sort of cleanup as a result.
    2. If you need to bubble an exception up the chain, use "throw" by itself.
    3. If you need to add information to the exception or repackage it, always pass the original exception as the inner exception.

Friday, May 25, 2012

Layered vs tiered architecture

Layers refer to logical separation of code. Logical layers help you organize your code better. For example an application can have the following layers.

1)Presentation Layer or UI Layer
2)Business Layer or Business Logic Layer
3)Data Access Layer or Data Layer


The aboove three layers reside in their own projects, may be 3 projects or even more. When we compile the project we get the respective layer DLL. So we have 3 DLL's now.

Depending upon how we deploy our application, we may have 1 to 3 tiers. As we now have 3 DLL's, if we deploy all the DLL's on the same machine, then we have only 1 physical tier but 3 logical layers.

If we choose to deploy each DLL on a seperate machine, then we have 3 tiers and 3 layers.

So, Layers are a logical separation and Tiers are a physical separation. We can also say that, tiers are the physical deployment of layers.

Serialization in .net

Serialization is a process of converting an object into a stream of data so that it can be easily transmittable over the network or can be continued in a persistent storage location.  This storage location can be a physical file, database or ASP.NET Cache.  Serialization is the technology that enables an object to be converted into a linear stream of data that can be easily passed across process boundaries and machines.  This stream of data needs to be in a format that can be understood by both ends of a communication channel so that the object can be serialized and reconstructed easily.  The advantage of serialization is the ability to transmit data across the network in a cross-platform-compatible format, as well as saving it in a persistent or non-persistent storage medium in a non-proprietary format.  Serialization is used by Remoting, Web Services SOAP for transmitting data between a server and a client.  De-serialization is the reverse; it is the process of reconstructing the same object later.  The Remoting technology of .NET makes use of serialization to pass objects by value from one application domain to another.
Serialization is a process by which we can save the state of the object by converting the object in to stream of bytes.These bytes can then be stored in database, files, memory etc.

Below is a simple code of serializing the object.

MyObject objObject = new MyObject();

objObject.Value = 100;
// Serialization using SoapFormatter

SoapFormatter formatter = new SoapFormatter();

Stream objFileStream = new FileStream("c:\\MyFile.xml", FileMode.Create,
FileAccess.Write, FileShare.None);

formatter.Serialize(objFileStream, objObject);

objFileStream.Close();

Below is simple code which shows how to deserialize an object.

//De-Serialization

Stream objNewFileStream = new FileStream("c:\\MyFile.xml", FileMode.Open,
FileAccess.Read, FileShare.Read);

MyObject objObject =(MyObject)formatter.Deserialize(objNewFileStream);

objNewFileStream.Close();

RANK v DENSE_RANK v ROW_NUMBER

RANK v DENSE_RANK v ROW_NUMBER

RANK, ROW_NUMBER and also DENSE_RANK are very useful for taking a set of rows and ordering them in a defined manner, while giving each row a “position value”. They differ based on the approach taken to define the value of their position in the set of output rows. In some circumstances, they may all give the same value however, dependent on the data, they may differ.
An example based on the Employee table,

SELECT EmpId
,      salary
,      RANK() OVER(ORDER BY salary) rank_position
,      DENSE_RANK() OVER(ORDER BY sal) dense_rank_position
,      ROW_NUMBER() OVER(ORDER BY sal) row_number_position
FROM   emp
/

EmpId        SAL RANK_POSITION DENSE_RANK_POSITION ROW_NUMBER_POSITION
---------- ---------- ------------- ------------------- -------------------
7369        800             1                   1                   1
7900        950             2                   2                   2
7876       1100             3                   3                   3
7521       1250             4                   4                   4
7654       1250             4                   4                   5
7934       1300             6                   5                   6
7844       1500             7                   6                   7
7499       1600             8                   7                   8
7782       2450             9                   8                   9
7698       2850            10                   9                  10
7566       2975            11                  10                  11
7788       3000            12                  11                  12
7902       3000            12                  11                  13
7839       5000            14                  12                  14 
 
Notice that RANK has given the two employees with SAL = 1250, the same position value of 4 and the two employees with SAL=3000, the same position value of 12. Notice also that RANK skips position values 5 and 13 as it has two entries for 4 and 12 respectively. RANK uses all numbers between 1 and 14, except 5 and 13. RANK has both repeats and gaps in it’s ordering.
DENSE_RANK is similar to RANK, in that it gives the two employees with SAL=1250, the same position value of 4, but then it does not skip over position value 5 – it simply carries on at position 5 for the next values. DENSE_RANK uses, for the position values, all numbers between 1 and 12, without leaving any out, and using 4 and 11 twice. DENSE_RANK has no gaps in it’s ordering, only repeats.
ROW_NUMBER gives each row a unique position value and consequently uses all the numbers between 1 and 14. ROW_NUMBER has no gaps or repeats in it’s ordering. Note that the position value on ROW_NUMBER is not deterministic, since the ORDER BY clause only has SAL in it. If you want to ensure the order is the same each time, you need to add further columns to the ORDER BY clause.

Tuesday, May 22, 2012

Method Overloading in WCF

By default overload operations (methods) are not supported in WSDL based operation. However by using Name property of OperationContract attribute, we can deal with operation overloading scenario.
Sample code:

[ServiceContract]
interface ICalculator
{
 [OperationContract(Name = "AddInt")]
   int Add(int arg1,int arg2);

   [OperationContract(Name = "AddDouble")]
   double Add(double arg1,double arg2);
}

Method Overloading in WebServices

Method Overloading is outside paradigm of SOA as each method within a WSDL must be unique. Hence by default Web Services do not support Method Overloading. Otherwise it leads to WSDL name clashes.

But .NET provides an alternative way to do it using the MessageName Property of the WebMethod Attribute which changes the method name in the WSDL.

Sample Code:

namespace TestOverloadingWebService
{
    [WebService(Namespace = "http://tempuri.org/")]
    public class OverloadingInWebService : System.Web.Services.WebService
    {
        [WebMethod(MessageName = "AddInt", EnableSession = true)]
        public int Add(int a, int b)
        {
            return (a + b);
        }

        [WebMethod(MessageName = "AddFloat", EnableSession = true)]
        public float Add(float a, float b)
        {
            return (a + b);
        }
    }
}

Sunday, May 20, 2012

OOPS frequently asked questions

What is Virtual method?
Virtual Method has implementation & provide the derived class with the option to override it.

Can Struct be inherited?

No, Struct can't be inherited as this is implicitly sealed.

What is Inheritance?

It provides a convenient way to reuse existing fully tested code in different context thereby saving lot of coding.

Inheritance of classes in C# is always implementation Inheritance.

What is Virtual keyword?

This keyword indicates that a member can be overridden in a child class. It can be applied to methods, properties, indexes and events

What is New modifiers?

The new modifiers hides a member of the base class.

What is Abstract Class?

Abstract class is a class that can not be instantiated, it exists extensively for inheritance and it must be inherited. There are scenarios in which it is useful to define classes that is not intended to instantiate; because such classes normally are used as base-classes in inheritance hierarchies, we call such classes abstract classes.

Abstract classes cannot be used to instantiate objects; because abstract classes are incomplete, it may contain only definition of the properties or methods and derived classes that inherit this implements it's properties or methods.

Static, Value Types & interface doesn't support abstract modifiers. Static members cannot be abstract. Classes with abstract member must also be abstract.

What is Sealed modifiers?

Sealed types cannot be inherited & are concrete.
Sealed modifiers can also be applied to instance methods, properties, events & indexes. It can't be applied to static members.

Sealed members are allowed in sealed and non-sealed classes.

What is an Interface?

An interface is a contract & defines the requisite behavior of generalization of types.

An interface mandates a set of behavior, but not the implementation. Interface must be inherited. We can't create an instance of an interface.

An interface is an array of related function that must be implemented in derived type. Members of an interface are implicitly public & abstract.

An interface can inherit from another interface.

When to use Interface over abstract class?

Abstract Classes: Classes which cannot be instantiated. This means one cannot make a object of this class or in other way cannot create object by saying ClassAbs abs = new ClassAbs(); where ClassAbs is abstract class.
Abstract classes contains have one or more abstarct methods, ie method body only no implementation.
Interfaces: These are same as abstract classes only difference is we can only define method definition and no implementation.
When to use wot depends on various reasons. One being design choice.
One reason for using abstarct classes is we can code common
functionality and force our developer to use it. I can have a complete
class but I can still mark the class as abstract.
Developing by interface helps in object based communication.

What is pure virtual function?

When you define only function prototype in a base class without and do the complete implementation in derived class. This base class is called abstract class and client won’t able to instantiate an object using this base class.

A pure virtual function is a function that must be overridden in a derived class and need not be defined. A virtual function is declared to be "pure" using the curious "=0"
syntax:
class Base {
public:
void f1(); // not virtual
virtual void f2(); // virtual, not pure
virtual void f3() = 0; // pure virtual
};

What is Protected access modifier in C#?

The protected keyword is a member access modifier. It can only be used in a declaring a function or method not in the class ie. a class can't be declared as protected class.

A protected member is accessible from within the class in which it is declared, and from within any class derived from the class that declare this member. In other words access is limited to within the class definition and any class that inherits from the class

A protected member of a base class is accessible in a derived class only if the access takes place through the derived class type.

Default Access modifiers in C#?

An enum has default modifier as public

A class has default modifiers as Internal . It can declare members (methods etc) with following access modifiers:
public
internal
private
protected internal

An interface has default modifier as public

A struct has default modifier as Internal and it can declare its members (methods etc) with following access modifiers:
public
internal
private

A methods, fields, and properties has default access modifier as "Private" if no modifier is specified.

Can we call a base class method without creating instance?

Yep. But ..

* Its possible If its a static method.

* Its possible by inheriting from that class also.

* Its possible from derived classes using base keyword.

What is a private constructor? Where will you use it?

When you declare a Constructor with Private access modifier then it is called Private Constructor. We can use the private constructor in singleton pattern.

If you declare a Constructor as private then it doesn’t allow to create object for its derived class, i.e you loose inherent facility for that class.

Can we declare private class in a Namespace?

No. If you try to create a private class in a Namespace, Compiler will throw a compile time error “Namespace elements cannot be explicitly declared as private, protected, or protected internal”.

Reason: The message says it all. Classes can only be declared as private, protected or protected internal when declared as nested classes, other than that, it doesn't make sense to declare a class with a visibility that makes it unusable, even in the same module. Top level classes cannot be private, they are "internal" by default, and you can just make them public to make them visible from outside your DLL.

What Are Attributes in DotNet?

An Attribute is a declarative tag which can be used to provide information to the compiler about the behaviour of the C# elements such as classes and assemblies.
C# provides convenient technique that will handle tasks such as performing compile time operations , changing the behaviour of a method at runtime or maybe even handle unmanaged code.
C# Provides many Built-in Attributes

Some Popular ones are

- Obsolete
- DllImport
- Conditional
- WebMethod

and Many more.
Members please keep on posting more responses providing more In-Built attributes.

What can you do to make class available for inheritance but you need to prevent it's method to come in inheritance chain?

Well, Declare a class with public access specifier and mark all it's method to sealed . As anything which is declared with sealed keyword cannot be inherited.

What's the Difference between Interface and Abstract Class

Abstract Class:
Have constructors.
Not necessarily for the class inheriting it to Implement all the Methods.
Doesn't Support Multiple Inheritance.

Where everything is Opposite in the Interfaces.

What are the various types of Constructors


Public : Accessible to All
Private: Those classes in which only static members are there and you don't want there objects to be created in any class.
Static: Used for initializing only the static members of the class. These will be invoked for the very first time the class is being loaded on the memory. They cannot accept any arguments. Static Constructors cannot have any access modifiers.
Intern: implementations of the abstract class to the assembly defining the class. A class containing an internal constructor cannot be instantiated outside of the assembly (Namespace).
and External

What are Constructors ?

Constructors are used for initializing the members of a class whenever an object is created with the default values for initialization.

If no constructor defined then the CLR will provide an implicit constructor which is called as Default Constructor.

A class can have any number of constructors provided they vary with the number of arguments that are passed, which is they should have different signatures.

Constructors do not return a value
Constructors can be overloaded

When to Use Abstract Classes and When Interfaces.


If you anticipate creating multiple versions of your component, create an abstract class. Abstract classes provide a simple and easy way to version your components. By updating the base class, all inheriting classes are automatically updated with the change. Interfaces, on the other hand, cannot be changed once created. If a new version of an interface is required, you must create a whole new interface.

If the functionality you are creating will be useful across a wide range of disparate objects, use an interface. Abstract classes should be used primarily for objects that are closely related, whereas interfaces are best suited for providing common functionality to unrelated classes.

If you are designing small, concise bits of functionality, use interfaces. If you are designing large functional units, use an abstract class.

If you want to provide common, implemented functionality among all implementations of your component, use an abstract class. Abstract classes allow you to partially implement your class, whereas interfaces contain no implementation for any members.

Diversities between an abstract method & virtual method ?


An Abstract method does not provide an implementation and forces overriding to the deriving class (unless the deriving class also an abstract class), where as the virtual method has an implementation and leaves an option to override it in the deriving class. Thus Virtual method has an implementation & provides the derived class with the option of overriding it. Abstract method does not provide an implementation & forces the derived class to override the method.

What is Early binding and late binding?


Calling a non-virtual method, decided at a compile time is known as early binding. Calling a virtual method (Pure Polymorphism), decided at a runtime is known as late binding.

Difference between ASP Session and ASP.NET Session?


Asp.net session supports cookie less session & it can span across multiple servers.

Illustrate Server.Transfer and Response.Redirect?


Server.Transfer, transfers the control of a web page, posting a form data, while Response.Redirect simply redirects a page to another page, it can not post a form data to another page. Server.Transfer is more efficient over the Response.Redirect, because Response.Redirect causes a round trip to server as the page is processed once again on the client and a request is made to server there after.
But the browser url is not changed in case of Server.Transfer i.e. Browser history is not modified in using it.

How's method overriding different from overloading?


When overriding, you change the method behavior for a derived class. Overloading simply involves having a method with the same name within the class.

Static datamembers should be initialized inside the constructor. True or False.


False. Static datamembers should not be initialised inside constructor.

Static methods can not use non static members. True or False.


True

Name the operators that cannot be overloaded.

sizeof
.
.*
.->
::
?:

What is "this" pointer?


This pointer is a pointer which points to the current object of a class. this is actually a keyword which is used as a pointer which differentiate the current object with global object.

Difference between sealed and static classes



sealed classes:

1)we can create their instances, but cannot inherit them

ex:

sealed class demo
{

}

class abc:demo
{
--Wrong
}
2)They can contain static as well as nonstatic members.

static classes:

1)we can neither create their instances, nor inherit them

ex:
static class Program
{

}

2)They can have static members only.

Differences between a structure and class


Structure:

1)It is a Value Type
2)Its variable directly contains the data on the stack
3)Each structure variable has its independent copy
of data.
4)One structure cannot inherit other
5)They do not have destructors
6)They do no have explicit parameterless constructors
7)we cannot put sealed /abstract modifiers before the structures.
8)Easier memory management
9)examples:
int, short,long,DateTime,
Point
(predefined)

Uses:
Structures are typically used for handling
small amounts of data or where inheritance, overriding is not required
example: int a=100;


Class

1)It is a reference Type
2)Its variable has references to the data(data is stored in the object created in the heap) .
3)Two Class variables can refer to the same object
4)One class can inherit the other(unless the class is sealed/static)
5)Classes have destructors
6)They can have explicit parameterless constructors
7)Sealed/abstract modifers can be put before classes.
8) Comparitively Difficult memory management
9)example: SqlConnection,DataView(predefined classes)

Classes are typically used where inheritance, overriding is required
or we need to create objects capable of handling large data
example: DataSet,ArrayList can handle large data.

Difference between a Class and an object


Class:

1)It is a datatype that contains the programming logic.

2)Class is visible in the source code and resides in hard disk.

3)Class is like a template or blueprint of the object. It implements reusability,

encapsulation, inheritance

example:Button is a class with properties like Text,BackColor,
events like click, methods like Focus

Object:

1)it is a chunk of memory that implements the class logic.

2)Object is in the RAM and not visible in source code.

3)It is the real world implementation of the class.
Each object has its own copy of data.
example: Button1, Button2 are the objects of Button class.

Define OOPS. What are its benefits?


OOPS

Object Oriented Programming Stuctures:

It is a programming methodology in which the programs are organized as collections of objects.Each object represents an instance of some class.The classes can be interrelated to each other through inheritance

OOPS revolves around these concepts:

1)Class
2)Object
3)Inheritance
4)Polymorphism
5)Abstraction
6)Encapsulation
-----------------------------------------------------
Advantages:
1)Code reusability: define a class and n number of objects implement the class
logic: example: Button class and n number of Button objects


2)Inheritance : Eliminates redundant code and extend the use of existing classes.

example: 1)we can create our own TextBox by inheriting from the TextBox class.
2)We can inherit one Windows Frorm into another.

3)Encapsulation: The programmer can hide the data and functions in a class from other classes.It is accomplished through modifiers like private, protected,
protected internal.


4)Easy to Maintain and Upgrade:
If we want to make changes in a class, we can make them and save the changes in the .dll This .dll can easily be updated in the client by using Update Reference.

5)Polymorphism provides us with methods extensibility.
we can have different methods with same name, but with different kinds of behavior

ex:
Console.WriteLine("welcome");
Console.WriteLine(100);


6)Abstraction allows us to define a common definition of a base class
that multiple derived classes can share.
For example,
create an abstract class bank with simple interest function
This function will be implemented in the derived classes of
the bank class.
ex: 1)icici class will have its own simple interest.
2)ABC class will have its own simple interest.

icici and ABC both are child classes of bank class.

Can we have an Abstract class without having any abstract method ??


Yes we can have Abstract class without having any abstract method ..

See the code below
using System;

abstract class A
{
public void Hello()
{
Console.WriteLine(" Say Hi");
}
}

class B:A
{
}

class Demo
{
public static void Main()
{
B b1 = new B();
b1.Hello();
}
}
// Output is Say HI


the class A is abstract class.. but it does not have any abstract methods..

Can we have Multiple Main Methods in one .cs file


Yes we can Have multiple Main methods in one .cs file.
The crux is we can have Multiple classes in one .cs file; and we can define one Main method in each class.

& while doing compliation we can spcify the compiler to choose the Main methods from the specific class .

for ef see the code below
using System;

class Test
{
    public static void Main()
    {
        Console.WriteLine("Test");
    }
}

class Demo
{
    public static void Main()
    {
        Console.WriteLine("Demo");
    }
}
We have got two class which we can save in single .cs file say Hello.cs

while doing compliation we can say
csc Hello.cs /main:Demo        --> In order to choose Main from the Demo class
and
csc Hello.cs /main:Test      --> In order to choose Main from the Test class

What is difference in between abstrct classes and interfaces ?


An interface offers an alternative to an abstract class for creating contract among classes and their client. The main difference in between abstract class and interface are given bellow
1. Abstract classes can have concrete methods while interfaces have no methods implemented.

2.Interface do not come in inheriting chain,while abstract classes come in inheritance .

Thursday, May 17, 2012

What is state server? how state server will be used in another system?



StateServer is one of the ASP.NET sessionState mode. StateServer mode stores session state in a process, referred to as the ASP.NET state service, that is separate from the ASP.NET worker process or IIS application pool. Using this mode ensures that session state is preserved if the Web application is restarted and also makes session state available to multiple Web servers in a Web farm.
To use StateServer mode, you must first be sure the ASP.NET state service is running on the server used for the session store. The ASP.NET state service is installed as a service when ASP.NET and the .NET Framework are installed. The ASP.Net state service is installed at the following location:
systemroot\Microsoft.NET\Framework\versionNumber\aspnet_state.exe
To configure an ASP.NET application to use StateServer mode, in the application's Web.config file do the following:
Set the mode attribute of the sessionState element to StateServer.
Set the stateConnectionString attribute to tcpip=serverName:42424.
The following example shows a configuration setting for StateServer mode where session state is stored on a remote computer named SampleStateServer:
<configuration>
  <system.web>
    <sessionState mode="StateServer"
      stateConnectionString="tcpip=SampleStateServer:42424"
      cookieless="false"
      timeout="20"/>
  </system.web>
</configuration>

Wednesday, May 16, 2012

Isolation levels significance in sql server

An isolation levels mechanism is used to isolate a resource each transaction in a multi-user
environment. Isolation can be set by obtaining locks on objects.  The correct use of the isolation levels mechanism prevents applications from introducing errors that can occur from the following situations.

1. Lost Updates: This situation occurs when two transactions attempt to update the same data. Consider the following example:
Transaction A reads row 1.
Transaction B reads row 1.
Transaction A updates row 1.
Transaction B updates row 1, overlaying changes applied by Transaction A.

In the above situation, updates performed by Transaction A are lost.

This problem could be avoided if the second Transaction could not make changes until the first Transaction had finished.

2. Dirty Reads: This situation occurs when transactions read data that has not been committed. Consider the following example:
Transaction A inserts row 1 without committing.
Transaction B reads row 1.
Transaction A rolls back row 1.
Transaction B now has a row that physically does not exist.

This problem could be avoided if no one could read the changes until the first Transaction determined that the changes were final.

3. Phantom Reads: This situation occurs when a row of data matches the first time but does not match subsequent times. Consider the following example:
Transaction A reads two rows based on a Query A where clause.
Transaction B inserts a new row that happens to fall under Transaction A Query A's where clause.
Transaction A runs Query A again and now gets back three rows.

Example:
Phantom reads occur when an insert or delete action is performed against a row that belongs to a range of rows being read by a transaction. The transaction's first read of the range of rows shows a row that no longer exists in the second or succeeding read, as a result of a deletion by a different transaction. Similarly, as the result of an insert by a different transaction, the transaction's second or succeeding read shows a row that did not exist in the original read.

System databases in sql server

master database

The Master database is the heart and soul of SQL Server. It basically records all the system level information. Every instance of SQL Server will have an independent Master database; as it captures instance level configuration information. The information which is captured in the Master database includes SQL Server instance level configurations, linked server configurations, SQL Server Logins, Service Broker Endpoints, System Level Stored Procedures, and System level Functions etc. The system and user databases related information such as name and location for user and system database are captured in Master database.

If master database is corrupted or if it is not available then the SQL Server Service will not start. In SQL Server 2005 and later versions the system objects are stored in Resource Database rather than in Master Database. The Master database is created using Simple Recovery Model.

msdb database


SQL Server Agent uses MSDB database to store information related to the configuration of SQL Server Agent Jobs, Job schedules, Alerts, Operators etc. MSDB also stores information related to configuration of Service Broker, Log Shipping, database backups and restore information, Maintenance Plan Configuration, Configuration of Database Mail, Policy Bases Information of SQL Server 2008 etc. 

If the MSDB database is corrupted or damaged then scheduling information used by SQL Server Agent will be lost. This will result in the failure of all scheduled activities.

model database

The Model database is basically used as a template when creating databases in SQL Server. Basically SQL Server takes a copy of Model database whenever a user tries to create a new database in SQL Server. This also means that if a user creates any tables, stored procedures, user defined data types or user defined functions within a Model database; then those objects will be available in every newly created database on that particular instance of SQL Server.

If the Model database is damaged or corrupted then SQL Server Service will not start up as it will not be able to create the tempdb database.

Resource database

The Resource database is a read only, hidden system database that contains all the SQL Server system objects such as sys.objects which are physically available only in the Resource database, even though they logically appear in the SYS schema of every database. The Resource Database does not contain any user data or any user metadata. By design, the Resource database is not visible under SQL Server Management Studio’s Object Explorer | Databases | System Databases Node.

The DBA shouldn’t rename or move the Resource Database file. If the files are renamed or moved from their respective locations then SQL Server will not start. The other important thing to be considered is not to put the Resource Database files in a compressed or encrypted NTFS file system folders as it will hinder the performance and will also possibly  prevent upgrades.

tempdb database

In SQL Server, TempDB database is recreated every time SQL Server Service is restarted. This also means that the some of the settings of Model database are also used when TempDB is created. Is a workspace for holding temporary objects or intermediate result sets.

Concept of polymorphism


What is Polymorphism?

  • Polymorphism means many forms.
  1. It has the ability for classes to provide different implementations of methods that are called through the same name.
  2. It allows you to invoke methods of derived class through base class reference during runtime.
    • Polymorphism is one of the primary characteristics (concept) of object-oriented programming.
    • Poly means many and morph means form. Thus, polymorphism refers to being able to use many forms of a type without regard to the details.
    • Polymorphism is the characteristic of being able to assign a different meaning specifically, to allow an entity such as a variable, a function, or an object to have more than one form.
    • Polymorphism is the ability to process objects differently depending on their data types.
    • Polymorphism is the ability to redefine methods for derived classes.

    Types of Polymorphism

    • Compile time Polymorphism
    • Run time Polymorphism

    Compile time Polymorphism

    • Compile time Polymorphism also known as method overloading
    • Method overloading means having two or more methods with the same name but with different signatures
    • Example of Compile time polymorphism

     Run time Polymorphism

    • Run time Polymorphism also known as method overriding
    • Method overriding means having two or more methods with the same name , same signature but with different implementation

    Example of Run time Polymorphism


    You can find source code at the bottom of this article.


    What is polymorphism? Poly means many. So how can we take this definition in .NET context. Well we can apply this to class's ability to share the same methods (actions) but implement them differently.
    Suppose we have a method in a class to add numbers,
    1 public class calculation
    2 {
    3 public int add(int x, int y)
    4 {
    5   return x+y;
    6 }
    7 }

    So to perform addition of three numbers, we need similar add method but with different parameter
    01 public class calculation
    02 {
    03 public int add(int x, int y)
    04 {
    05   return x+y;
    06 }
    07  public int add(int x, int y,int z)
    08 {
    09   return x+y+z;
    10 }
    11 }

    So we can that class is sharing the same methods (actions) but implement them differently.
    Now this is an example when we are sharing method name and implementing them differently, let's take a scenario where implementation is in some derived class.
    For instance, say we create a class called Shape and this class has a method called .Area () which calculates area. Then we create two subclasses, using inheritance, of this Shape class. One called Square, the other called Circle. Now obviously a square and circle are two entirely different shapes, yet both classes have the .Area() method. When the Square.Area() method is called it will calculate area of  a square. When the Circle.Area() method is called, it will calculate area of a circle. So both classes can use the same methods but implement them differently.

    Now let's dive little deeper and understand what we discussed above in more technical terms.

    1) Static or Compile time Polymorphism


    Which method is to be called is decided at compile-time only. Method Overloading is an example of this. Method overloading is a concept where we use the same method name many times in the same class, but different parameters. Depending on the parameters we pass, it is decided at compile-time only. The same method name with the same parameters is an error and it is a case of duplication of methods which c# does not permit. In Static Polymorphism decision is taken at compile time.

    public Class StaticDemo
    {
      public void display(int x)
     {
      Console.WriteLine("Area of a Square:"+x*x);
     }
      public void display(int x, int y)
     {
      Console.WriteLine("Area of a Square:"+x*y);
     }
     public static void main(String args[])
     {
      StaticDemo spd=new StaticDemo();
      Spd.display(5);
      Spd.display(10,3);
     }
    }


    2) Dynamic or Runtime Polymorphism.


    Run time Polymorphism also known as method overriding. In this Mechanism by which a call to an overridden function is resolved at a Run-Time (not at Compile-time) if a base Class contains a method that is overridden. Method overriding means having two or more methods with the same name, same signature but with different implementation. In this process, an overridden method is called through the reference variable of a superclass, the determination of the method to be called is based on the object being referred to by reference variable.
    01 Class BaseClass
    02 {
    03   Public void show ()
    04  
    05   Console.WriteLine("From base class show method");
    06   }
    07 }
    08 Public Class DynamicDemo : BaseClass
    09 {
    10   Public void show()
    11   {
    12   Console.WriteLine("From Derived Class show method");
    13   }
    14   Public static void main(String args[])
    15   {
    16   DynamicDemo dpd=new DynamicDemo ();
    17   Dpd.show();
    18    
    19   }
    20 }
    Here memory allocation will be at the run time for that particular method.

    What is Virtual Function: They implement the concept of polymorphism are the same as in C#, except that you use the override keyword with the virtual function implementation in the child class. The parent class uses the same virtual keyword. Every class that overrides the virtual method will use
    the override keyword.
    Why to use them:

    1)It is not compulsory to mark the derived/child class function with Override KeyWord while base/parent class contains a virtual method
    2)Virtual methods allow subclasses to provide their own implementation of that method using the override keyword

    3)Virtual methods can't be declared as private.

    4)You are not required to declare a method as virtual. But, if you don't, and you derive from the class, and your derived class has a method by the same name and signature, you'll get a warning that you are hiding a parent's method

    5)A virtual property or method has an implementation in the base class, and can be overriden in the derived classes.

    6)
    We will get a warning if we won't use Virtual/New keyword.

    7)Instead of Virtual we can use New Keyword
    01 class A
    02 {
    03 public void M()
    04 {
    05 Console.WriteLine("A.M() being called");
    06 }
    07
    08 public virtual void N()
    09 {
    10 Console.WriteLine("A.N() being called");
    11 }
    12 }
    13
    14 class B : A
    15 {
    16 public new void M()
    17 {
    18 Console.WriteLine("B.M() being called");
    19 }
    20
    21 public override void N()
    22 {
    23 Console.WriteLine("B.N() being called");
    24 }
    25 }



    say

    A a = new B();

    a.M();
    a.N();


    The results would be

    A.M() being called
    B.N() being called

    Override Keyword: method overriding is modifying or replacing the implementation of the parent class with a new one. Parent classes with virtual or abstract members allow derived classes to override them.
    01 class Shape
    02 {
    03   public virtual void Draw()
    04   {
    05   Console.WriteLine("Shape.Draw")  ;
    06   }
    07 }
    08
    09 class Rectangle : Shape
    10
    11 {
    12   public override void Draw()
    13   {
    14   Console.WriteLine("Rectangle.Draw");
    15   }
    16 }