जगदीश खोलिया

Monday, June 4, 2012

Schemabinding View

Schemabinding View Restirct you to made any change in tables you used in your View.
Example:

Suppose I have an table Employee(EmpID,EmpName, DOJ,Managerid,DepartID)

Now am Creating a view

Create View EmployeeDetails
with Schemabinding
as
Select EmPid, EmpName,DOj,ManagerId,DepartID from Employee

after it just try to execute delete table and alter table and delete column of employee table.

Sql server will not allow to change table schema. Because you are having Schema dependency.First you need to delete View then only database will allow to modify table.

If you are using Normal View. Sytem will Allow you to delete or modify table but when you run your View next time it will display error.

Chain constructor or constructor chaining

We can chain the call of constructor from child class to base class depending on our requirement. This concept makes sure that the matching base class constructor must be called based on the parameter passed to the child class constructor.

Example:

namespace ConsoleApplication1

{

    class A

    {

        public A(){

            Console.WriteLine("Constructor A.");

        }

        public A(string s){

            Console.WriteLine("Constructor A with parameter = {0}",s);

        }

        public A(string s,string t){

            Console.WriteLine("Constructor A with parameter = {0} & {1}", s,t);

        }

    }



    class B:A

    {

        public B():base(){

            Console.WriteLine("Constructor B.");

        }

        public B(string s):base(s){

            Console.WriteLine("Constructor B with parameter = {0}", s);

        }

        public B(string s, string t):base(s,t){

            Console.WriteLine("Constructor B with parameter = {0} & {1}", s, t);

        }

    }

    class Program

    {

        static void Main(string[] args)

        {

            B b1 = new B();

            B b2 = new B("First Parameter ", "Second Parameter");



            Console.Read();

        }

    }

}

Output:
Constructor A.
Constructor B.
Constructor A with parameter = First Parameter & Second Parameter
Constructor B with parameter = First Parameter & Second Parameter

Difference between Abstraction and Encapsulation????


Abstraction
Encapsulation
1. Abstraction solves the problem in the design level.

1. Encapsulation solves the problem in the implementation level.

2. Abstraction is used for hiding the unwanted data and giving relevant data.

2. Encapsulation means hiding the code and data into a single unit to protect the data from outside world.


3. Abstraction lets you focus on what the object does instead of how it does it

3. Encapsulation means hiding the internal details or mechanics of how an object does something.

4. Abstraction- Outer layout, used in terms of design.
For Example:-
 Outer Look of a Mobile Phone, like it has a display screen and keypad buttons to dial a number.

4. Encapsulation- Inner layout, used in terms of implementation.
For Example:- Inner Implementation detail of a Mobile Phone, how keypad button and Display Screen are connect with each other using circuits.




"Encapsulation is accomplished by using Class. - Keeping data and methods that accesses that data into a single unit" 
"Abstraction is accomplished by using Interface. - Just giving the abstract information about what it can do without specifying the back ground details" 
"Information/Data hiding is accomplished by using Modifiers - By keeping the instance variables private or protected."

Address header in WCF

Address Header contains the information which is sent with every request, it can be used by either end point service or any intermediate device for determining any routing logic or processing logic.

WCF provides AddressHeader class for this purpose.

Example :

AddressHeader addressHeader= AddressHeader.CreateAddressHeader("Name of the header", "Information included in header ");

Once the AddressHeader instance is created, it can be associated with end point instance as follows :

EndpointAddress endpoint = new EndpointAddress(new Uri("http://myserver/myservice"), addressHeader);

Isolation levels 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. Nonrepeatable Reads: This situation occurs when a transaction reads the same query multiple times and results are not the same each time. Consider the following example:
Transaction A reads a row of data.
Transaction B modifies this row and commits.
Transaction A re-reads the same row and sets back different data values.  (When the record was read for the second time by Transaction A, it has changed).

This problem could be avoided if the Transaction A could read the row only after the Transaction B has finished writing it.

4. 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.

Example2:

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.

The above four phenomenon demonstrate that there is a need to utilize a mechanism called ISOLATION LEVELS.

Difference between event and delegate

Class1 c = new Class1();
c.MyDeleageteCallback = new Class1.DomSomethingDelegate(this.Calculate);

This piece of code will work just fine with class1, but if we were to try to use it on class2, where there is the event keyword declared, we would get a compilation error.

In conclusion: an event declaration adds a layer of protection on the delegate instance. This protection prevents clients of the delegate from resetting the delegate and its invocation list, and only allows adding or removing targets from the invocation list.

Three main differences:
events can be included in interfaces
events can only be invoked by the containing class
events' signatures are constrained (depends on language and CLS compliance)


event:

1) It is a data member of a type(class/structure)

2)It is declared inside a type(class/structure)

3) It is used to generate notifications which are then passed to methods though
delegates.

 
delegate:

1)It is a datatype(reference type) that holds references of methods with
some signatures.also called as function pointer.

2)It may or may not be declared inside a class.

3)It is used as the return type of an event and used in passing messages from event to methods.

event-->delegate-->method
example: 1
namespace dd
{
//delegate declaration
delegate void first();
class cc
{
//event declaration
public first myevent;
}
}

example 2:
button1.Click+=new EventHandler(this.button1_Click);

Click is the event that returns an instance of the EventHandler delegate.
EventHandler delegate has the reference of button1_Click event and that
helps in the communication betwen the Click event and button1_Click method.

Dead letter queues in WCF

The main use of queue is that you do not need the client and the server running at one time. Therefore, it is possible that a message will lie in queue for long time until the server or client picks it up. But there are scenarios where a message is of no use after a certain time. Therefore, these kinds of messages if not delivered within that time span it should not be sent to the user.
Below is the config snippet, which defines for how much time the message should be in queue.
 
<bindings>
<netMsmqBinding>
<binding name="MyBindings"
deadLetterQueue="Custom"
customDeadLetterQueue="net.msmq://localhost/private/ServiceModelSamples" 
timeToLive="00:00:02"/>
</netMsmqBinding>

Volatile queues in WCF

There are scenarios in the project when you want the message to deliver in proper time. The timely delivery of message is more important than losing message. In these scenarios, Volatile queues are used.
Below is the code snippet, which shows how to configure Volatile queues. You can see the binding Configuration property set to Volatile Binding. This code will assure that message will deliver on time but there is a possibility that you can lose data.
 

<appSettings>
<!-- use appSetting to configure MSMQ queue name -->
<add key="queueName" value=".\private$\ServiceModelSamplesVolatile" />
</appSettings>

<system.serviceModel>
<services>
<service name="Samples.StockTickerServ"
behaviorConfiguration="CalculatorServiceBehavior">
...
<!-- Define NetMsmqEndpoint -->
<endpoint address="net.msmq://localhost/private/ServiceModelSamplesVolatile"
binding="netMsmqBinding"
bindingConfiguration="volatileBinding" 
contract="Samples.InterfaceStockTicker" />
...
</service>
</services>

<bindings>
<netMsmqBinding>
<binding name="volatileBinding" 
durable="false"
exactlyOnce="false"/>
</netMsmqBinding>
</bindings>
...
</system.serviceModel>

Friday, June 1, 2012

Type of serialization

.NET provides 2 ways for serializtion 1) XmlSerializer and 2) BinaryFormatter/SoapFormatter

XmlSerializer is used for Web Services. The BinaryFormatter & SoapFormatter is used for Remoting. While using XmlSerializer, it is required that the target class has parameter less constructors, has public read-write properties and has fields that can be serialized. The XmlSerializer has good support for XML documents. It can be used to construct objects from existing XML documents. The XmlSerializer enables us to serialize and deserialize objects to an XML format.

SoapFormatter enables us to serialize & deserialize objects to SOAP format. They can serialize private and public fields of a class. The target class must be marked with the Serializable attribute. On deserialization, the constructor of the new object is not invoked.

BinaryFormatter has the same features as the SoapFormatter except that it formats data into binary format. The BinaryForamatter (and the SoapFormatter) has two main methods. Serialize and Deserialize. To serialize an object, we pass an instance of the stream and the object to the Serialize method. To Deserialize an object, you pass an instance of a stream to the Deserialize method.

You can use the BinaryFormatter to serialize many, but not all, classes in the .NET Framework. For example, you can serialize ArrayLists, DataSets, and Arrays but not other objects, such as DataReaders or TextBox controls. To serialize a class, the class must have the Serializable attribute or implement the ISerializable interface.

Note that the XmlSerializer captures only the public members of the class, whereas the BinaryFormatter & the SoapFormatter captures both the public & private members of the class. The output using the BinaryFormatter is quite compact, as the information is in binary format, whereas the XmlSerializer format is filled with XML tags.

Serialization and Deserialization

Serialization: -“Serialization” is a process of converting an object into a stream of bytes.

Deserialization: – “Deserialization” is reverse of “serialization”, where stream of bytes are converted back in to an object.
Let’s see a simple example how exactly we can do “serialization” and
“deserialization”.
It’s very simple four steps procedure as follows.
Step1: – create a new “window application” like below diagram.

Step2: – Now create a customer class in “Form1.cs” file.
[Serializable]
public class Customer
{
public string CustomerCode;
public string CustomerName;
}
Step3: – Now, we will see how exactly “serialization” is done.
Import the following namespace 
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

private void Serialize_Click(object sender, EventArgs e)
{
Customer obj = new Customer();// created instance of the customer class
obj.CustomerCode = textBox1.Text;
obj.CustomerName = textBox2.Text;
IFormatter formatter = new BinaryFormatter();
Stream stream = new FileStream("E:\\Customer.bin", FileMode.Create,
 FileAccess.Write, FileShare.None);
formatter.Serialize(stream, obj);
stream.Close();
textBox1.Text = "";
textBox2.Text = "";
}
Step4: – Similarly, we will do for “deserialization”.
private void Deserialize_Click(object sender, EventArgs e)
{
IFormatter formatter = new BinaryFormatter();
Stream stream = new FileStream("E:\\Customer.bin", FileMode.Open, 
FileAccess.Read, FileShare.Read);
Customer obj = (Customer)formatter.Deserialize(stream);
stream.Close();
textBox1.Text = obj.CustomerCode;
textBox2.Text = obj.CustomerName;
}