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

Wednesday, June 6, 2012

Few important C# question...

1.C# provides a default constructor for me. I write a constructor that takes a string as a parameter, but want to keep the no parameter one. How many constructors should I write? 
Ans.  Two. Once you write at least one constructor, C# cancels the freebie constructor, and now you have to write one yourself, even if there’s no implementation in it.


2.Can you declare the override method static while the original method is non-static?
 Ans. No, you can’t, the signature of the virtual method must remain the same, only the keyword virtual is changed to keyword override.


3.Can you prevent your class from being inherited and becoming a base class for some other classes? Ans. Yes, that’s what keyword sealed in the class definition is for. The developer trying to derive from your class will get a message: cannot inherit from Sealed class Whatever Base Class Name is.


4. When do you absolutely have to declare a class as abstract (as opposed to free-willed educated choice or decision based on UML diagram)? 
Ans. When at least one of the methods in the class is abstract. When the class itself is inherited from an abstract class, but not all base abstract methods have been over-ridden.


5. What’s the difference between System.String and System.StringBuilder classes?
Ans. System.String is immutable; System.StringBuilder was designed with the purpose of having a mutable string where a variety of operations can be performed.


6. What is the use of private constructor ?
Ans. When we declare a class constructor as private , we can not do 2 things:-
  • We can not create a object of the class.
  • We can not inherit the class.

Now the next question which the interviewer will ask , whats the use of such kind of class which can not be inherited neither instantiated.
Many times we do not want to create instances of certain classes like utility , common routine classes. Rather than calling as shown below

7.Who is faster hashtable or dictionary ?
Ans.Dictionary is faster than hashtable as dictionary is a generic strong type. Hashtable is slower as it takes object as data type which leads to boxing and unboxing.

8. What is the difference between const and readonly?

Ans.
public class Const_V_Readonly
{
  public const int I_CONST_VALUE = 2;
  public readonly int I_RO_VALUE;
  public Const_V_Readonly()
  {
     I_RO_VALUE = 3;
  }
}

AssemblyB references AssemblyA and uses these values in code. When this is compiled,
  • in the case of the const value, it is like a find-replace, the value 2 is 'baked into' the AssemblyB's IL. This means that tomorrow if I update I_CONST_VALUE to 20 in the future. Assembly B would still have 2 till I recompile it.
  • in the case of the readonly value, it is like a ref to a memory location. The value is not baked into AssemblyB's IL. This means that if the memory location is updated, Assembly B gets the new value without recompilation. So if I_RO_VALUE is updated to 30, you only need to build AssemblyA. All clients do not need to be recompiled.

9.I want to force the data reader to return only schema of the data store rather than data.
Ans. PobjDataReader = pobjCommand.ExecuteReader (CommandBehavior.SchemaOnly)




10. What are the various methods provided by the dataset object to generate XML?



 XML is one of the most important leap between classic ADO and ADO.NET. So this question is normally asked more generally how can we convert any data to XML format. Best answer is convert in to dataset and use the below methods.
• ReadXML
Read’s a XML document in to Dataset.
• GetXML
This is a function, which returns the string containing XML document.
• Writexml
This writes a XML data to disk.

11.What is the difference between “Dataset” and “Data Reader” ?

Ans.Following are the major differences between “Dataset” and “Data Reader”:-
• “Dataset” is a disconnected architecture, while “Data Reader” has live connection while reading data. If we want to cache data and pass to a different tier “Dataset” forms the best choice and it has decent XML support.

• When application needs to access data from more than one table “Dataset” forms the best choice. 

• If we need to move back while reading records, “data reader” does not support this functionality.

• However, one of the biggest drawbacks of Dataset is speed. As “Dataset” carry considerable overhead because of relations, multiple table’s etc speed is slower than “Data Reader”. Always try to use “Data Reader” wherever possible, as it is meant especially for speed performance.




12. What’s difference between “Optimistic” and “Pessimistic” locking ?


In pessimistic locking when user wants to update data it locks the record and till then no one can update data. Other user’s can only view the data when there is pessimistic locking.
In optimistic locking multiple users can open the same record for updating, thus increase maximum concurrency. Record is only locked when updating the record. This is the most preferred way of locking practically. Now a days in browser based application it is very common and having pessimistic locking is not a practical solution.


13.How many ways are there to implement locking in ADO.NET?


Following are the ways to implement locking using ADO.NET:-
• When we call “Update” method of Data Adapter it handles locking internally. If the Dataset values are not matching with current data in Database, it raises concurrency exception error. We can easily trap this error using Try. Catch block and raise appropriate error message to the user.
• Define a Date time stamp field in the table. When actually you are firing the UPDATE SQL statements, compare the current timestamp with one existing in the database. Below is a sample SQL which checks for timestamp before updating and any mismatch in timestamp it will not update the records. This I the best practice used by industries for locking.

Update table1 set field1=@test where Last Timestamp=@Current Timestamp

• Check for original values stored in SQL SERVER and actual changed values. In stored procedure check before updating that the old data is same as the current Example in the below shown SQL before updating field1 we check that is the old field1 value same. If not then some one else has updated and necessary action has to be taken.

Update table1 set field1=@test where field1 = @oldfield1value
Locking can be handled at ADO.NET side or at SQL SERVER side i.e. in stored procedures. For more details of how to implementing locking in SQL SERVER read “What are different locks in SQL SERVER?” in SQL SERVER chapter.


14.How can we perform transactions in .NET?



The most common sequence of steps that would be performed while developing a transactional application is as follows:
• Open a database connection using the Open method of the connection object.
• Begin a transaction using the Begin Transaction method of the connection object. This method provides us with a transaction object that we will use later to commit or rollback the transaction. Note that changes caused by any queries executed before calling the Begin Transaction method will be committed to the database immediately after they execute. Set the Transaction property of the command object to the above mentioned transaction object.
• Execute the SQL commands using the command object. We may use oneormorecommand objects for this purpose, as long as the Transaction property of all the objects is set to a valid transaction object.
• Commit or roll back the transaction using the Commit or Rollback method of the transaction object.
• Close the database connection.

15.What is difference between Dataset? Clone and Dataset. Copy?

Clone: - It only copies structure, does not copy data.
Copy: - Copies both structure and data.

16. What is Maximum Pool Size in ADO.NET Connection String?

Maximum pool size decides the maximum number of connection objects to be pooled. If the maximum pool size is reached and there is no usable connection available the request is queued until connections are released back in to pool. So it’s always a good habit to call the close or dispose method of the connection as soon as you have finished work with the connection object.

17. How to enable and disable connection pooling?
For .NET it is enabled by default but if you want to just make sure set Pooling=true in the connection string. To disable connection pooling set Pooling=false in connection string if it is an ADO.NET Connection. If it is an OLEDBConnection object set OLE DB Services=-4 in the connection string.



Tuesday, June 5, 2012

APPLY operator (CROSS Apply and OUTER Apply) in SQL Server

The APPLY operator let's you join a table to a table-valued-function.UDFs can be used in queries at column level, table levels and on column definition while creating tables.
They can also be joined with other tables, but not by simple joins. They have special joins called APPLY operator.There are 2 types of APPLY:
- CROSS APPLY acts as INNER JOIN, returns only rows from the outer table that produce a result set from the table-valued function.
- OUTER APPLY acts as OUTER JOIN, returns both rows that produce a result set, and rows that do not, with NULL values in the columns produced by the table-valued function.
 eg:
CREATE Procedure [dbo].[Test_Apply]
(
 ContactId varchar(50)
)
As
BEGIN
SELECT name.Customer_Id,name.CustomerName,name.Email,name.MobileNo
,name.EntryDate,name.ProductID,name.Product
FROM Test_Lead lead
INNER JOIN customer cust ON cust.CustomerId = lead.CustomerID
outer apply dbo.fn_Test_GetLatestResponse_Customerwise(lead.Customer_ID) sales
cross apply dbo.fn_Test_GetCustomerDetails(lead.Customer_ID) name
inner join LMS_UserDetails agent on agent.ID = lead.Allocated_To
WHERE lead.ProductId = name.ProductID
END


Monday, June 4, 2012

Generics in C#

Parametric Polymorphism is a well-established programming language feature. Generics offers this feature to C#.
The best way to understand generics is to study some C# code that would benefit from generics. The code stated below is about a simple Stack class with two methods: Push () and Pop (). First, without using generics example you can get a clear idea about two issues: a) Boxing and unboxing overhead and b) No strong type information at compile type. After that the same Stack class with the use of generics explains how these two issues are solved.
Example Code
Code without using generics:
public class Stack
{
object[] store; int size; public void Push(object x) {...} public object Pop() {...}
}

Boxing and unboxing overhead:
You can push a value of any type onto a stack. To retrieve, the result of the Pop method must be explicitly cast back. For example if an integer passed to the Push method, it is automatically boxed. While retrieving, it must be unboxed with an explicit type cast.
Stack stack = new Stack();
stack.Push(3);
int i = (int)stack.Pop(); //unboxing with explicit int casting
Such boxing and unboxing operations add performance overhead since they involve dynamic memory allocations and run-time type checks.
No strong Type information at Compile Time
Another issue with the Stack class: It is not possible to enforce the kind of data placed on a stack. For example, a string can be pushed on a stack and then accidentally cast to the wrong type like integer after it is retrieved:
Stack stack = new Stack();
stack.Push("SomeName");
//pushing the stringint i = (int)stack.Pop(); //run-time exception will be thrown at this point
The above code is technically correct and you will not get any compile time error. The problem does not become visible until the code is executed; at that point an InvalidCastException is thrown.
Code with generics
In C# with generics, you declare class Stack <T> {...}, where T is the type parameter. Within class Stack <T> you can use T as if it were a type. You can create a Stack as Integer by declaring Stack <int> or Stack as Customer object by declaring Stack<Customer>. Simply your type arguments get substituted for the type parameter. All of the Ts become ints or Customers, you don't have to downcast, and there is strong type checking everywhere.
public class Stack<T>
{
// items are of type T, which is kown when you create the objectT[] items; int count; public void Push(T item) {...}//type of method pop will be decided when you creat the object public T Pop()
{...}
}
In the following example, int is given as the type argument for T:
Stack<int> stack = new Stack<int>();
stack.Push(3);
int i = stack.Pop();
The Stack<int> type is called a constructed type. In the Stack<int> type, every occurrence of T is replaced with the type argument int. The Push and Pop methods of a Stack<int> operate on int values, making it a compile-time error to push values of other types onto the stack, and eliminating the need to explicitly cast values back to their original type when they are retrieved.
You can use parameterization not only for classes but also for interfaces, structs, methods and delegates.
//For Interfaces interface IComparable <T>//for structs struct HashBucket <K,D>//for methods static void Reverse <T> (T[] arr)//for delegates delegate void Action <T> (T arg)


What you can get with Generics
Generics can make the C# code more efficient, type-safe and maintainable.
Efficiency: Following points states that how performance is boosted.
  1. Instantiations of parameterized classes are loaded dynamically and the code for their methods is generated on demand [Just in Time].
  2. Where ever possible, compiled code and data representations are shared between different instantiations.
  3. Due to type specialization, the implementation never needs to box values of primitive types.
Safety: Strong type checking at compile time, hence more bugs caught at compile time itself.
Maintainability: Maintainability is achieved with fewer explicit conversions between data types and code with generics improves clarity and expressively.
Conclusion
Generics gives better performance, type safety and clarity to the C# programs. Generics will increase program reliability by adding strong type checking. Learning how to use generics is straightforward, hopefully this article has inspired you to look deeper into how you can use them.

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;
}