ADO.Net 2.0 Mutiple Active Result Sets (MARS)

ADO.NET 2.0 Multiple Active Resut Sets per connection in Sql Server 2005 (MARS) FAQ

ADO.NET 2.0 Multiple Active Resut Sets per connection in Sql Server 2005 (MARS) FAQ
Q: What is MARS?

A: MARS is a new feature in ado.net 2.0 and Sql Server 2005 that allows for multiple forward only read only result sets.

EDIT There is a great article on MARS up at the technet site. It is a must read for basic understanding of MARS. I am specially impressed with the “Transaction Semantics” section http://www.microsoft.com/technet/prodtechnol/sql/2005/marssql05.mspx

Q: What is MARS for an ado.net developer?

A: MARS allows you to avoid seeing the dreaded “There is already an open DataReader ..” exception when executing on separate SqlCommands associated with the same connection. You can have multiple SqlDataReaders open on a single connection (again, each reader must be started on a new SqlCommand) and you don’t have to worry about Transaction isolation level scope locks.

Q: So MARS allows for better performance right?

A: I would like to say no outright, it would make my life much easier. You are trading the expense of opening new connections (almost free with pooling) for the hidden expenses of using MARS (fairly high IMO) The truth is that in some scenarios you will see actual perf improvement by using MARS, mostly thanks to Session Pooling. These scenarios are somewhat contrived and I would highly recomend that you do not modfify existing code or write new ugly code just to attempt to improve performance with MARS.

Q: What does Session Pooling mean to a SqlClient ado.net developer?

A: It means that you should _NOT_ use more than 9 SqlCommands per connection, if you do you will be forcing us to create/dispose very very expensive SqlCommands and you will definitelly notice the performance drop.

Q: What is MARS for Sql Server?

A: This has been a thorn in our side for too long. Other databases have supported this functionality for a long time and this has been one of the most important customer requested features to our model. I wish that I could explain how hard it has been to enable this behavior (completely anathema to our implementation) and how proud I am that we have driven this feature to market. That said I am concerned that this feature is going to be misused.

Q: Can I get better performance by combining MARS with ASYNC?

A: IMO, no. In ASP.NET applications you will not get better performance with MARs, and on Winform applications you should not use ASYNC with callbacks (See ASYNC FAQ) I would not mix these two features expecting to get better performance.

Q: So if MARS is not for performance what is it good for?

A: I like to use MARS in two core scenarios, 1) When using MARS results in cleaner looking code and 2) when I am using Transactions and need to execute in the same isolation level scope.

Q: What is Session Pooling?

A: This question should ideally come after I have explained the hidden costs of MARS, for now let me just explain what it does and I will blog on this with more detail at a later time. If you understand how pooling works then you are familiar with the idea of not destroying a valuable resource just because the user decides to close or dispose it. In this case the SqlCommand has become a valuable resource because we have to associate it with a Sql Server 2005 batch to enable MARS functionality. Session Pooling keeps up to 9 of these valuable disposed SqlCommands in a pool and hands them out the next time you create a command associated with the same connection.

Q: When does using MARS result in cleaner looking code?

A: The quintessential MARS example involves getting a datareader from the server and issuing insert/delete/update statements to the database as you process the reader.

Q: What are the costs of using MARS?

A: There are a lot of hidden costs associated with this feature, costs in the client, in the network layer and in the server. On the client we run into an issue where creating a new batch is not free, we kind of work around this issue by pooling mars commands but it is still expensive if you don’t used the pooled functionality. On the network layer there is a cost associated with multiplexing the TDS buffer, opening too many batches can be more expensive than opening another connection. On the server all MARS batches run in the same scope, worst case scenario your queries will end up running in the order received.

Q: Can I disable MARS?

A: Yes and No, you can disable MARS with the connection string keyword “MultipleActiveResultSets=false”. Under the covers we still use MARS headers so we will still have some of the overhead associated with MARS. You will not get better performance if you disable MARS, this option was only added to allow the developer to enable backward compatibility with applications that depend on SqlClient throwing an exception when more than one Result Set is used.

Q: What about the transaction isolation level scope?

A: Same example above but you have a transaction active and you have placed locks on the database. Please note that this behavior was _completelly_ broken before MARS! If you try to fake MARS by opening a second connection under the covers (like native SqlOledb does) you are outside of the transaction scope of the original connection. This is imo the biggest win with this feature.

Q: So OleDb may fake MARS?

A: Unfortunately yes. In what has to be one of my least favorite “features” the SqlOledb native provider will fake the ability of having multiple active result sets by opening a separate non-pooled connection to the server when unable to provide real MARS behavior. What this really means is that your code may be opening and throwing away connections that can bring your server to its knees during heavy traffic.

Q: What providers/backends support MARS?

A: The only provider/backend combination that supports the MARS feature that I am talking about in this FAQ is SqlClient talking to Sql Server 2005.

Q: Does this mean that none of the other providers support multiple DataReaders?

A: No it doesn’t. The OracleClient managed provider supports multiple DataReaders against all versions of Oracle. The OleDb managed provider is MUCH more problematic. It fully supports multiple DataReaders when talking to Sql Server 2005 when using MDAC 9. (IMPORTANT) In all other cases the OleDb managed provider will FAKE the ability of having multiple active result sets.

Q: Wait a minute; in v1.1 I was not able to open multiple DataReaders with OleDb.

A: This was an artificial restriction on the client, we have removed this restriction going forward since OleDb with the latest version of MDAC will now support true MARS behavior.

Q: What does the removal of this client side restriction mean?

A: It means that you can now shoot yourself in the foot when using the managed OleDb provider. IMHO it means that you should ONLY use SqlClient to talk to Sql Server, the risk of running into this fake MARS behavior is too great. I have seen this “feature” (fake MARS) cost hundreds of thousands of dollars an hour in lost sales as the server was inundated with unnecessary non-pooled connection open requests.

C# Interview Questions 5

What are indexers? What are their advantages over arrays?
An indexer enables you to treat an object like an array.It helps you to acces the arrays in a class using the class name. Indexer enables you to use bracket notation ([]) with an object to set and get a value from an object.They encapsulate method calls into more convenient representation of value access and value setting.

public dataType this[int index]
{
  get
  {

     //Code to get some value from a array

     if (index < 0)
                return “negative”;
            else if (index > max)
                return “Infinity”;
            else
                return arr[index];
      }
  set
  {

     arr[index]=value;

  }
}   

Indexers makes your code more readable and easier to understand.You can create mulltiple indexers for a class.  Signature of each indexer should be unique.  The signature of an indexer is considered as the number and types of its formal parameters return data type of the indexer is not part of signature.They help you to represent as array values which may have no similarities to arrays as internal representation.You are not limited to using integers as indexes. You can use strings to achieve the result used in the Hash class and many others. Use indexer only when the representation of the class data as multiple objects is proper.

How would you implement singleton pattern in C#?

Singleton Pattern Definition
The Singleton pattern ensures that a class only has one instance and provides a global point of access to it from a well-known access point. The class implemented using this pattern is responsible for keeping track of its sole instance rather than relying on global variables to single instances of objects

Often, this pattern is used to represent parts of the system that there can only be one of, like the file system or window manager. Or, parts of your application that there will only ever be one of.

C# Implementation

1. The constructor should be private.

2. Provide a static method, which returns an instance of the class.

3. Use a static variable to check whether already one instance is created or not. if already an instance is there , returns a null

using System;

class  SingleInstanceClass<o:p></o:p>

{         
private static SingleInstanceClass sic= null;   
private static bool instanceFlag = false; 
private SingleInstanceClass()       
   {          
   }         

public static SingleInstanceClass Create()     
    {     
          if(! instanceFlag)         
        { 
            sic = new SingleInstanceClass();    
            instanceFlag = true;  
            return sic;     
         }
         else    
         {
             return null;   
          }         
    }     

protected void Finalize()     
    {     
       instanceFlag = false; 
     }
}

class MyClient

{         
    public static void Main()           
      {   
         SingleInstanceClass sic1,sic2;      
         sic1 = SingleInstanceClass.Create();   
         if(sic1 != null)   
              Console.WriteLine(”OK”);
         sic2 = SingleInstanceClass.Create();   
         if(sic2 == null)   
         Console.WriteLine(”NO MORE OBJECTS”);  
      }
}

The above program returns a null value when try to create an object second time. But instead of returning null, it is possible to return already existing object ‘sic’ by changing ‘return null’ to ‘return sic’ in the above program.<o:p></o:p>

What is native image cache?
The native image cache is a reserved area of the global assembly cache. Once you create a native image for an assembly, the runtime automatically uses that native image each time it runs the assembly. You do not have to perform any additional procedures to cause the runtime to use a native image. Running Ngen.exe on an assembly allows the assembly to load and execute faster, because it restores code and data structures from the native image cache rather than generating them dynamically.
 
Important:
A native image is a file containing compiled processor-specific machine code. Note that the native image that Ngen.exe generates cannot be shared across Application Domains. Therefore, you cannot use Ngen.exe in application scenarios, such as ASP.NET, that require assemblies to be shared across application domains.
 
Note   To run Ngen.exe, you must have administrative privileges

What is called sealed classes?Can we derive sealed classes?

Sealed classes are those classes which cannot be inherited / derived by any other classes. These Classes are used to restrict the user boundaries.

In VB.Net you can create these classes using “NonInheritable” keyword.

How would you register javascript in ASP.NET through code behind?
The common way to accomplish this is to use RegisterStartupScript and the RegisterClientScriptBlock methods of the Page class.
 
Page.RegisterStartupScript -
This method adds JavaScript to the web form right before the ending </FORM>tag.
This wouls be best used when we want to initiate a javascript function when the page is loaded. It takes two parameters
— the first being the key of the script and the
–  the second being the script itself (represented as a string).
 
private void Page_Load(object sender, System.EventArgs e)
{
           —–
           —–
           Page.RegisterStartupScript(”UserScript”,
                       ” language=javascript>” +
                        “function HelloWorld() { alert(’Hello World’); }</SCRIPT> “);
          Button1.Attributes[”onclick”] = “HelloWorld()”;
          —–
          —–
}
 
Page.RegisterClientScriptBlock -
This method adds JavaScript to the web form, right after the

<FORM runat=”server”>declaration.  It also takes two parameters— the first being the key of the script and the second being the script itself (represented as a string).
 
The main difference between the two methods is that the RegisterStartupScript method places the JavaScript at the bottom of the ASP.NET page right before the closing
</FORM>

element while RegisterClientScriptBlock method places the JavaScript directly after the opening

<FORM>element in the page.

Can we use win32api dlls in .net? Explain how?

If you talk about win32dll they are written in unmanged code. PInvoke helps us to call unmanged code from manage code. It locate and invoke the code and marshal their arguments at run time. In C# we use DLLImport as attribute to call
win32api dll.

What is the difference between setting an object to null and calling dispose method of the object ?

E.g. Object obj = new Object();

obj = null

obj.dispose()

When we set any object to null, that means that object is subject to garbage collection. But we dont have any control when exactly garbage collector reclaim memory and resources from this object. So in case we have occupied some heavy resources in any object, its better to implement a Dispose() method. So on calling the dispose() method explicitly, we can free the resources.

What is the difference between Constant and Readonly?

‘const’:
Can’t be static.
Value is evaluated at compile time.
Initiailized at declaration only.
‘readonly’:
Can be either instance-level or static.
Value is evaluated at run time.
Can be initialized in declaration or by code in the constructor.

What benefit does your code receive if you decorate it with attributes demanding specific Security permissions?

Following are the benefits of using attribute based declarative security , essentially all the relevant information is stored in the asssembly metadata on compilation and based on permissions of the calling code , CLR will make sure that application or assembly doesn’t even get loaded in case doesn’t have relevant permissions vis a vis Imperative security , where everything is checked in assembly code and assembly will invariably get loaded and executed before it checks for any such issue or lack of permissions .
 
So , benefits of Declarative security are :
 
1. Inducing efficiency as all relevant information is stored in the metadata .
2. Cleaner code as security is not mixed with program logic it’s done cleanly using attributes .

How do you define pointers in c#?

Pointers in C# are syntactically used in the same way as you would use in c/c++. The only thing that is important to note is that, all code that is going to use pointers or address of operators is unsafe in .NET world and thus has to be marked with an unsafe modifier or has to be enclosed in an “unsafe” block. E.g.
unsafe modifer:-
unsafe void someFuncA(int *x)
{
//…do something
}
 
unsafe static void Main()
{
int j = 100;
someFunc(&j);
}
unsafe block:-
 
void someFunction()
{
int j = 10;
unsafe
{
int* i = &j;
}
}
 
Lastly, all source code which contains “unsafe” code has to be compiled with “/unsafe” compiler option.
 
Posted By : Sarang Datye [Microsoft MVP - Visual Basic]


Dated :- 30th May

What is shallow copying ? How does MemberWiseClone method work ?

A shallow copy creates a new instance of the same type as the original object, and then copies the nonstatic fields of the original object. If the field is a value type, a bit-by-bit copy of the field is performed. If the field is a reference type, the reference is copied but the referred object is not; therefore, the reference in the original object and the reference in the clone point to the same object. In contrast, a deep copy of an object duplicates everything directly or indirectly referenced by the fields in the object.

MemberwiseClone method, creates a new instance of the source object and then does a bit-by-bit copy of value types and for reference types only the reference is copied. As a result both the original object and the clone end-up pointing to the same objects that the original object refers. And this is exactly what a copy constructor in C++ does :)!
 
So, e.g. If X is the object in context and it reference objects Y and Z then a shallow copy A of X will refer to Y and Z!

What is the difference between a Debug and Release build? Is there a significant speed difference?

The biggest difference between these is that:
In a debug build the complete symbolic debug information is emitted to help while debugging applications and also the code optimization is not taken into account.
While in release build the symbolic debug info is not emitted and the code execution is optimized.
Also, because the symbolic info is not emitted in a release build, the size of the final executable is lesser than a debug executable.
 
One can expect to see funny errors in release builds due to compiler optimizations or differences in memory layout or initialization. These are ususally referred to as Release - Only bugs :)
 
In terms of execution speed, a release executable will execute faster for sure, but not always will this different be significant.

C# Interview Questions 4

Explain the differences between Server-side and Client-side code?
Server side code executes on the server.For this to occur page has to be submitted or posted back.Events fired by the controls are executed on the server.Client side code executes in the browser of the client without submitting the page.
e.g. In ASP.NET for webcontrols like asp:button the click event of the button is executed on the server hence the event handler for the same in a part of the code-behind (server-side code). Along the server-side code events one can also attach client side events which are executed in the clients browser i.e. javascript events.

How does VB.NET/C# achieve polymorphism?
Polymorphism is also achieved through interfaces. Like abstract classes, interfaces also describe the methods that a class needs to implement. The difference between abstract classes and interfaces is that abstract classes always act as a base class of the related classes in the class hierarchy. For example, consider a hierarchy-car and truck classes derived from four-wheeler class; the classes two-wheeler and four-wheeler derived from an abstract class vehicle. So, the class ‘vehicle’ is the base class in the class hierarchy. On the other hand dissimilar classes can implement one interface. For example, there is an interface that compares two objects. This interface can be implemented by the classes like box, person and string, which are unrelated to each other.

C# allows multiple interface inheritance. It means that a class can implement more than one interface. The methods declared in an interface are implicitly abstract. If a class implements an interface, it becomes mandatory for the class to override all the methods declared in the interface, otherwise the derived class would become abstract.

Can you explain what inheritance is and an example of when you might use it?
The savingaccount class has two data members-accno that stores account number, and trans that keeps track of the number of transactions. We can create an object of savingaccount class as shown below.

        savingaccount s = new savingaccount ( “Amar”, 5600.00f ) ;
From the constructor of savingaccount class we have called the two-argument constructor of the account class using the base keyword and passed the name and balance to this constructor using which the data member’s name and balance are initialised.

We can write our own definition of a method that already exists in a base class. This is called method overriding. We have overridden the deposit( ) and withdraw( ) methods in the savingaccount class so that we can make sure that each account maintains a minimum balance of Rs. 500 and the total number of transactions do not exceed 10. From these methods we have called the base class’s methods to update the balance using the base keyword. We have also overridden the display( ) method to display additional information, i.e. account number.

Working of currentaccount class is more or less similar to that of savingaccount class.
Using the derived class’s object, if we call a method that is not overridden in the derived class, the base class method gets executed. Using derived class’s object we can call base class’s methods, but the reverse is not allowed.

Unlike C++, C# does not support multiple inheritance. So, in C# every class has exactly one base class.
Now, suppose we declare reference to the base class and store in it the address of instance of derived class as shown below.

        account a1 = new    savingaccount ( “Amar”, 5600.00f ) ;
   account a2 = new currentaccount ( “MyCompany Pvt. Ltd.”, 126000.00f) ;
Such a situation arises when we have to decide at run-time a method of which class in a class hierarchy should get called. Using a1 and a2, suppose we call the method display( ), ideally the method of derived class should get called. But it is the method of base class that gets called. This is because the compiler considers the type of reference (account in this case) and resolves the method call. So, to call the proper method we must make a small change in our program. We must use the virtual keyword while defining the methods in base class as shown below.

        public virtual void display( )    {   }
We must declare the methods as virtual if they are going to be overridden in derived class. To override a virtual method in derived classes we must use the override keyword as given below.

        public override void display( )   {   }
Now it is ensured that when we call the methods using upcasted reference, it is the derived class’s method that would get called. Actually, when we declare a virtual method, while calling it, the compiler considers the contents of the reference rather than its type.

If we don’t want to override base class’s virtual method, we can declare it with new modifier in derived class. The new modifier indicates that the method is new to this class and is not an override of a base class method.

How would you implement inheritance using VB.NET/C#?
When we set out to implement a class using inheritance, we must first start with an existing class from which we will derive our new subclass. This existing class, or base class, may be part of the .NET system class library framework, it may be part of some other application or .NET assembly, or we may create it as part of our existing application. Once we have a base class, we can then implement one or more subclasses based on that base class. Each of our subclasses will automatically have all of the methods, properties, and events of that base class ? including the implementation behind each method, property, and event. Our subclass can add new methods, properties, and events of its own - extending the original interface with new functionality. Additionally, a subclass can replace the methods and properties of the base class with its own new
implementation - effectively overriding the original behavior and replacing it with new behaviors. Essentially inheritance is a way of merging functionality from an existing class into our new subclass. Inheritance also defines rules for how these methods, properties, and events can be merged. In VB.NET we can use implements keyword for inheritance, while in C# we can use the sign ( :: ) between subclass and baseclass.

How is a property designated as read-only?
In VB.NET:

Private mPropertyName as DataType
Public ReadOnly Property PropertyName() As DataType
    Get Return mPropertyName
    End Get
End Property

In C#

Private DataType mPropertyName;
public returntype PropertyName
{
      get{
                        //property implementation goes here
                        return mPropertyName;
            }
            // Do not write the set implementation
}

What is hiding in CSharp ?

Hiding is also called as Shadowing. This is the concept of Overriding the methods. It is a concept used in the Object Oriented Programming.

E.g.
 public class ClassA {
 public virtual void MethodA() {
  Trace.WriteLine(”ClassA Method”);
 }
}

public class ClassB : ClassA {
 public new void MethodA() {
  Trace.WriteLine(”SubClass ClassB Method”);
 }
}

public class TopLevel {
 static void Main(string[] args) {
  TextWriter tw = Console.Out;
  Trace.Listeners.Add(new TextWriterTraceListener(tw));
 
  ClassA obj = new ClassB();
  obj.MethodA(); // Outputs “Class A Method”
 
  ClassB obj1 = new ClassB();
  obj.MethodA(); // Outputs “SubClass ClassB Method”
 }
}

What is the difference between an XML “Fragment” and an XML “Document.”
An XML fragment is an XML document with no single top-level root element. To put it simple it is a part (fragment) of a well-formed xml document. (node) Where as a well-formed xml document must have only one root element.

What does it meant to say “the canonical” form of XML?
“The purpose of Canonical XML is to define a standard format for an XML document. Canonical XML is a very strict XML syntax, which lets documents in canonical XML be compared directly.
Using this strict syntax makes it easier to see whether two XML documents are the same. For example, a section of text in one document might read Black & White, whereas the same section of text might read Black & White in another document, and even in another. If you compare those three documents byte by byte, they’ll be different. But if you write them all in canonical XML, which specifies every aspect of the syntax you can use, these three documents would all have the same version of this text (which would be Black & White) and could be compared without problem.
This Comparison is especially critical when xml documents are digitally signed. The digital signal may be interpreted in different way and the document may be rejected.


Why is the XML InfoSet specification different from the Xml DOM? What does the InfoSet attempt to solve?
“The XML Information Set (Infoset) defines a data model for XML. The Infoset describes the abstract representation of an XML Document. Infoset is the generalized representation of the XML Document, which is primarily meant to act as a set of definitions used by XML technologies to formally describe what parts of an XML document they operate upon.
The Document Object Model (DOM) is one technology for representing an XML Document in memory and to programmatically read, modify and manipulate a xml document.
Infoset helps defining generalized standards on how to use XML that is not dependent or tied to a particular XML specification or API. The Infoset tells us what part of XML Document should be considered as significant information.

Contrast DTDs versus XSDs. What are their similarities and differences? Which is preferred and why?
Document Type Definition (DTD) describes a model or set of rules for an XML document. XML Schema Definition (XSD) also describes the structure of an XML document but XSDs are much more powerful.
The disadvantage with the Document Type Definition is it doesn’t support data types beyond the basic 10 primitive types. It cannot properly define the type of data contained by the tag.
An Xml Schema provides an Object Oriented approach to defining the format of an xml document. The Xml schema support most basic programming types like integer, byte, string, float etc., We can also define complex types of our own which can be used to define a xml document.
Xml Schemas are always preferred over DTDs as a document can be more precisely defined using the XML Schemas because of its rich support for data representation.

Speaking of Boolean data types, what’s different between C# and C/C++?
There’s no conversion between 0 and false, as well as any other number and true, like in C/C++.

How do you convert a string into an integer in .NET?
Int32.Parse(string)

Can you declare a C++ type destructor in C# like ~MyClass()?
Yes, but what’s the point, since it will call Finalize(), and Finalize() has no guarantees when the memory will be cleaned up,  plus, it introduces additional load on the garbage collector.

What’s different about namespace declaration when comparing that to package declaration in Java?
No semicolon.

What’s the difference between const and readonly?
The readonly keyword is different from the const keyword. A const field can only be initialized at the declaration of the field. A readonly field can be initialized either at the declaration or in a constructor. Therefore, readonly fields can have different values depending on the constructor used. Also, while a const field is a compile-time constant, the readonly field can be used for runtime constants as in the following example:
public static readonly uint l1 = (uint) DateTime.Now.Ticks;

C# Interview Questions 3

What does \a character do?
On most systems, produces a rather annoying beep.

Can you create enumerated data types in C#?
Yes.

What’s different about switch statements in C#?
No fall-throughs allowed.

What happens when you encounter a continue statement inside the for loop?
The code for the rest of the loop is ignored, the control is transferred back to the beginning of the loop.

How can you sort the elements of the array in descending order?
By calling Sort() and then Reverse() methods.

Will finally block get executed if the exception had not occurred?
Yes.

What’s the C# equivalent of C++ catch (…), which was a catch-all statement for any possible exception?
A catch block that catches the exception of type System.Exception. You can also omit the parameter data type in this case and just write catch {}.

Can multiple catch blocks be executed?
No, once the proper catch code fires off, the control is transferred to the finally block (if there are any), and then whatever follows the finally block.

Why is it a bad idea to throw your own exceptions?
Well, if at that point you know that an error has occurred, then why not write the proper code to handle that error instead of passing a new Exception object to the catch block? Throwing your own exceptions signifies some design flaws in the project.

What’s the difference between // comments, /* */ comments and /// comments?
Single-line, multi-line and XML documentation comments.

How do you generate documentation from the C# file commented properly with a command-line compiler?
Compile it with a /doc switch.

Can you change the value of a variable while debugging a C# application?
Yes, if you are debugging via Visual Studio.NET, just go to Immediate window.

What’s the implicit name of the parameter that gets passed into the class’ set method?
Value, and it’s datatype depends on whatever variable we’re changing.

How do you inherit from a class in C#?
Place a colon and then the name of the base class. Notice that it’s double colon in C++.

Does C# support multiple inheritance?
No, use interfaces instead.

So how do you retrieve the customized properties of a .NET application from XML .config file? Can you automate this process?
Initialize an instance of AppSettingsReader class. Call the GetValue method of AppSettingsReader class, passing in the name of the property and the type expected. Assign the result to the appropriate variable. In Visual Studio yes, use Dynamic Properties for automatic .config creation, storage and retrieval.

Why is it not a good idea to insert code into InitializeComponent method when working with Visual Studio?
The designer will likely through it away, most of the code inside InitializeComponent is auto-generated.

Where do you add an event handler?
It’s the Attributesproperty, the Add function inside that property.
e.g. btnSubmit.Attributes.Add(”"onMouseOver”",”"someClientCode();”")

What are jagged array?

First lets us answer the question that what an array is?
The dictionary meaning of array is an orderly arrangement or sequential arrangement of elements.
In computer science term:
An array is a data structure that contains a number of variables, which are accessed through computed indices. The variables contained in an array, also called the elements of the array, are all of the same type, and this type is called the element type of the array.

An array has a rank that determines the number of indices associated with each array element. The rank of an array is also referred to as the dimensions of the array. An array with a rank of one is called a single-dimensional array. An array with a rank greater than one is called a multi-dimensional array. Specific sized multidimensional arrays are often referred to as two-dimensional arrays, three-dimensional arrays, and so on.

Now let us answer What are jagged arrays?
 A jagged array is an array whose elements are arrays. The elements of jagged array can be of different dimensions and sizes. A jagged array is sometimes called as “array-of-arrays”. It is called jagged because each of its rows is of different size so the final or graphical representation is not a square.

 When you create a jagged array you declare the number of rows in your array. Each row will hold an array that will be on any length. Before filling the values in the inner arrays you must declare them.

Jagged array declaration in C#:

 For e.g. : int [] [] myJaggedArray = new int [3][];

Declaration of inner arrays:
 
 myJaggedArray[0] = new int[5] ;   // First inner array will be of length 5.
 myJaggedArray[1] = new int[4] ;  // Second inner array will be of length 4.
 myJaggedArray[2] = new int[3] ;   // Third inner array will be of length 3.

Now to access third element of second row we write:
  int value = myJaggedArray[1][2];

Note that while declaring the array the second dimension is not supplied because this you will declare later on in the code.

Jagged array are created out of single dimensional arrays so be careful while using them. Don’t confuse it with multi-dimensional arrays because unlike them jagged arrays are not rectangular arrays.

For more information on arrays:
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/csref/html/vclrfarrayspg.asp 

What is a delegate, why should you use it and how do you call it ?
A delegate is a reference type that refers to a Shared method of a type or to an instance method of an object. Delegate is like a function pointer in C and C++.  Pointers are used to store the address of a thing. Delegate lets some other code call your function without needing to know where your function is actually located. All events in .NET actually use delegates in the background to wire up events. Events are really just a modified form of a delegate.
It should give you an idea of some different areas in which delegates may be appropriate:

  • They enable callback functionality in multi-tier applications as demonstrated in the examples above. <o:p></o:p>
  • The CacheItemRemoveCallback delegate can be used in ASP.NET to keep cached information up to date. When the cached information is removed for any reason, the associated callback is exercised and could contain a reload of the cached information. <o:p></o:p>
  • Use delegates to facilitate asynchronous processing for methods that do not offer asynchronous behavior.
  • Events use delegates so clients can give the application events to call when the event is fired. Exposing custom events within your applications requires the use of delegates.

How does the XmlSerializer work?
XmlSerializer in the .NET Framework is a great tool to convert Xml into runtime objects and vice
versa

If you define integer variable and a object variable and a structure then how those will be plotted in memory.

Integer , structure – System.ValueType  — Allocated memory on stack , infact integer is primitive type recognized and allocated memory by compiler itself .

Infact , System.Int32 definition is as follows :

[C#]
[Serializable]
public struct Int32 : IComparable, IFormattable, IConvertible

So , it’s a struct by definition , which is the same case with various other value types .

Object – Base class , that is by default reference type , so at runtime JIT compiler allocates memory on the “Heap” Data structure .

Reference types are defined as class , derived directly or indirectly by System.ReferenceType

ADO.Net Interview Questions 3

How do you handle data concurrency in .NET ?One of the key features of the ADO.NET DataSet is that it can be a self-contained and disconnected data store. It can contain the schema and data from several rowsets in DataTable objects as well as information about how to relate the DataTable objects-all in memory. The DataSet neither knows nor cares where the data came from, nor does it need a link to an underlying data source. Because it is data source agnostic you can pass the DataSet around networks or even serialize it to XML and pass it across the Internet without losing any of its features. However, in a disconnected model, concurrency obviously becomes a much bigger problem than it is in a connected model.

In this column, I’ll explore how ADO.NET is equipped to detect and handle concurrency violations. I’ll begin by discussing scenarios in which concurrency violations can occur using the ADO.NET disconnected model. Then I will walk through an ASP.NET application that handles concurrency violations by giving the user the choice to overwrite the changes or to refresh the out-of-sync data and begin editing again. Because part of managing an optimistic concurrency model can involve keeping a timestamp (rowversion) or another type of flag that indicates when a row was last updated, I will show how to implement this type of flag and how to maintain its value after each database update.


Is Your Glass Half Full?

There are three common techniques for managing what happens when users try to modify the same data at the same time: pessimistic, optimistic, and last-in wins. They each handle concurrency issues differently.

The pessimistic approach says: “Nobody can cause a concurrency violation with my data if I do not let them get at the data while I have it.” This tactic prevents concurrency in the first place but it limits scalability because it prevents all concurrent access. Pessimistic concurrency generally locks a row from the time it is retrieved until the time updates are flushed to the database. Since this requires a connection to remain open during the entire process, pessimistic concurrency cannot successfully be implemented in a disconnected model like the ADO.NET DataSet, which opens a connection only long enough to populate the DataSet then releases and closes, so a database lock cannot be held.

Another technique for dealing with concurrency is the last-in wins approach. This model is pretty straightforward and easy to implement-whatever data modification was made last is what gets written to the database. To implement this technique you only need to put the primary key fields of the row in the UPDATE statement’s WHERE clause. No matter what is changed, the UPDATE statement will overwrite the changes with its own changes since all it is looking for is the row that matches the primary key values. Unlike the pessimistic model, the last-in wins approach allows users to read the data while it is being edited on screen. However, problems can occur when users try to modify the same data at the same time because users can overwrite each other’s changes without being notified of the collision. The last-in wins approach does not detect or notify the user of violations because it does not care. However the optimistic technique does detect violations.

In optimistic concurrency models, a row is only locked during the update to the database. Therefore the data can be retrieved and updated by other users at any time other than during the actual row update operation. Optimistic concurrency allows the data to be read simultaneously by multiple users and blocks other users less often than its pessimistic counterpart, making it a good choice for ADO.NET. In optimistic models, it is important to implement some type of concurrency violation detection that will catch any additional attempt to modify records that have already been modified but not committed. You can write your code to handle the violation by always rejecting and canceling the change request or by overwriting the request based on some business rules. Another way to handle the concurrency violation is to let the user decide what to do. The sample application that is shown in Figure 1 illustrates some of the options that can be presented to the user in the event of a concurrency violation.

Where Did My Changes Go?

When users are likely to overwrite each other’s changes, control mechanisms should be put in place. Otherwise, changes could be lost. If the technique you’re using is the last-in wins approach, then these types of overwrites are entirely possible.For example, imagine Julie wants to edit an employee’s last name to correct the spelling. She navigates to a screen which loads the employee’s information into a DataSet and has it presented to her in a Web page. Meanwhile, Scott is notified that the same employee’s phone extension has changed. While Julie is correcting the employee’s last name, Scott begins to correct his extension. Julie saves her changes first and then Scott saves his.Assuming that the application uses the last-in wins approach and updates the row using a SQL WHERE clause containing only the primary key’s value, and assuming a change to one column requires the entire row to be updated, neither Julie nor Scott may immediatelyrealize the concurrency issue that just occurred. In this particular situation, Julie’s changes were overwritten by Scott’s changes because he saved last, and the last name reverted to the misspelled version.

So as you can see, even though the users changed different fields, their changes collided and caused Julie’s changes to be lost. Without some sort of concurrency detection and handling, these types of overwrites can occur and even go unnoticed.When you run the sample application included in this column’s download, you should open two separate instances of Microsoft® Internet Explorer. When I generated the conflict, I opened two instances to simulate two users with two separate sessions so that a concurrency violation would occur in the sample application. When you do this, be careful not to use Ctrl+N because if you open one instance and then use the Ctrl+N technique to open another instance, both windows will share the same session.

Detecting Violations

The concurrency violation reported to the user in Figure 1 demonstrates what can happen when multiple users edit the same data at the same time. In Figure 1, the user attempted to modify the first name to “Joe” but since someone else had already modified the last name to “Fuller III,” a concurrency violation was detected and reported. ADO.NET detects a concurrency violation when a DataSet containing changed values is passed to a SqlDataAdapter’s Update method and no rows are actually modified. Simply using the primary key (in this case the EmployeeID) in the UPDATE statement’s WHERE clause will not cause a violation to be detected because it still updates the row (in fact, this technique has the same outcome as the last-in wins technique). Instead, more conditions must be specified in the WHERE clause in order for ADO.NET to detect the violation.

The key here is to make the WHERE clause explicit enough so that it not only checks the primary key but that it also checks for another appropriate condition. One way to accomplish this is to pass in all modifiable fields to the WHERE clause in addition to the primary key. For example, the application shown in Figure 1 could have its UPDATE statement look like the stored procedure that’s shown in Figure 2.

Notice that in the code in Figure 2 nullable columns are also checked to see if the value passed in is NULL. This technique is not only messy but it can be difficult to maintain by hand and it requires you to test for a significant number of WHERE conditions just to update a row. This yields the desired result of only updating rows where none of the values have changed since the last time the user got the data, but there are other techniques that do not require such a huge WHERE clause.

Another way to make sure that the row is only updated if it has not been modified by another user since you got the data is to add a timestamp column to the table. The SQL Server(tm) TIMESTAMP datatype automatically updates itself with a new value every time a value in its row is modified. This makes it a very simple and convenient tool to help detect concurrency violations.

A third technique is to use a DATETIME column in which to track changes to its row. In my sample application I added a column called LastUpdateDateTime to the Employees table.

ALTER TABLE Employees ADD LastUpdateDateTime DATETIME

There I update the value of the LastUpdateDateTime field automatically in the UPDATE stored procedure using the built-in SQL Server GETDATE function.

The binary TIMESTAMP column is simple to create and use since it automatically regenerates its value each time its row is modified, but since the DATETIME column technique is easier to display on screen and demonstrate when the change was made, I chose it for my sample application. Both of these are solid choices, but I prefer the TIMESTAMP technique since it does not involve any additional code to update its value.

Retrieving Row Flags

One of the keys to implementing concurrency controls is to update the timestamp or datetime field’s value back into the DataSet. If the same user wants to make more modifications, this updated value is reflected in the DataSet so it can be used again. There are a few different ways to do this. The fastest is using output parameters within the stored procedure. (This should only return if @@ROWCOUNT equals 1.) The next fastest involves selecting the row again after the UPDATE within the stored procedure. The slowest involves selecting the row from another SQL statement or stored procedure from the SqlDataAdapter’s RowUpdated event.

I prefer to use the output parameter technique since it is the fastest and incurs the least overhead. Using the RowUpdated event works well, but it requires me to make a second call from the application to the database. The following code snippet adds an output parameter to the SqlCommand object that is used to update the Employee information:

oUpdCmd.Parameters.Add(new SqlParameter(”@NewLastUpdateDateTime”,

  SqlDbType.DateTime, 8, ParameterDirection.Output,

  false, 0, 0, “LastUpdateDateTime”, DataRowVersion.Current, null));

oUpdCmd.UpdatedRowSource = UpdateRowSource.OutputParameters;

The output parameter has its sourcecolumn and sourceversion arguments set to point the output parameter’s return value back to the current value of the LastUpdateDateTime column of the DataSet. This way the updated DATETIME value is retrieved and can be returned to the user’s .aspx page.

Saving Changes

Now that the Employees table has the tracking field (LastUpdateDateTime) and the stored procedure has been created to use both the primary key and the tracking field in the WHERE clause of the UPDATE statement, let’s take a look at the role of ADO.NET. In order to trap the event when the user changes the values in the textboxes, I created an event handler for the TextChanged event for each TextBox control:

private void txtLastName_TextChanged(object sender, System.EventArgs e)

{

    // Get the employee DataRow (there is only 1 row, otherwise I could

    // do a Find)

    dsEmployee.EmployeeRow oEmpRow =

           (dsEmployee.EmployeeRow)oDsEmployee.Employee.Rows[0];

    oEmpRow.LastName = txtLastName.Text;

    // Save changes back to Session

    Session[”oDsEmployee”] = oDsEmployee;

}

This event retrieves the row and sets the appropriate field’s value from the TextBox. (Another way of getting the changed values is to grab them when the user clicks the Save button.) Each TextChanged event executes after the Page_Load event fires on a postback, so assuming the user changed the first and last names, when the user clicks the Save button, the events could fire in this order: Page_Load, txtFirstName_TextChanged, txtLastName_TextChanged, and btnSave_Click.

The Page_Load event grabs the row from the DataSet in the Session object; the TextChanged events update the DataRow with the new values; and the btnSave_Click event attempts to save the record to the database. The btnSave_Click event calls the SaveEmployee method (shown in Figure 3) and passes it a bLastInWins value of false since we want to attempt a standard save first. If the SaveEmployee method detects that changes were made to the row (using the HasChanges method on the DataSet, or alternatively using the RowState property on the row), it creates an instance of the Employee class and passes the DataSet to its SaveEmployee method. The Employee class could live in a logical or physical middle tier. (I wanted to make this a separate class so it would be easy to pull the code out and separate it from the presentation logic.)

Notice that I did not use the GetChanges method to pull out only the modified rows and pass them to the Employee object’s Save method. I skipped this step here since there is only one row. However, if there were multiple rows in the DataSet’s DataTable, it would be better to use the GetChanges method to create a DataSet that contains only the modified rows.

If the save succeeds, the Employee.SaveEmployee method returns a DataSet containing the modified row and its newly updated row version flag (in this case, the LastUpdateDateTime field’s value). This DataSet is then merged into the original DataSet so that the LastUpdateDateTime field’s value can be updated in the original DataSet. This must be done because if the user wants to make more changes she will need the current values from the database merged back into the local DataSet and shown on screen. This includes the LastUpdateDateTime value which is used in the WHERE clause. Without this field’s current value, a false concurrency violation would occur.

Reporting Violations

If a concurrency violation occurs, it will bubble up and be caught by the exception handler shown in Figure 3 in the catch block for DBConcurrencyException. This block calls the FillConcurrencyValues method, which displays both the original values in the DataSet that were attempted to be saved to the database and the values currently in the database. This method is used merely to show the user why the violation occurred. Notice that the exDBC variable is passed to the FillConcurrencyValues method. This instance of the special database concurrency exception class (DBConcurrencyException) contains the row where the violation occurred. When a concurrency violation occurs, the screen is updated to look like Figure 1.

The DataSet not only stores the schema and the current data, it also tracks changes that have been made to its data. It knows which rows and columns have been modified and it keeps track of the before and after versions of these values. When accessing a column’s value via the DataRow’s indexer, in addition to the column index you can also specify a value using the DataRowVersion enumerator. For example, after a user changes the value of the last name of an employee, the following lines of C# code will retrieve the original and current values stored in the LastName column:

string sLastName_Before = oEmpRow[”LastName”, DataRowVersion.Original];

string sLastName_After = oEmpRow[”LastName”, DataRowVersion.Current];

The FillConcurrencyValues method uses the row from the DBConcurrencyException and gets a fresh copy of the same row from the database. It then displays the values using the DataRowVersion enumerators to show the original value of the row before the update and the value in the database alongside the current values in the textboxes.

User’s Choice

Once the user has been notified of the concurrency issue, you could leave it up to her to decide how to handle it. Another alternative is to code a specific way to deal with concurrency, such as always handling the exception to let the user know (but refreshing the data from the database). In this sample application I let the user decide what to do next. She can either cancel changes, cancel and reload from the database, save changes, or save anyway.

The option to cancel changes simply calls the RejectChanges method of the DataSet and rebinds the DataSet to the controls in the ASP.NET page. The RejectChanges method reverts the changes that the user made back to its original state by setting all of the current field values to the original field values. The option to cancel changes and reload the data from the database also rejects the changes but additionally goes back to the database via the Employee class in order to get a fresh copy of the data before rebinding to the control on the ASP.NET page.

The option to save changes attempts to save the changes but will fail if a concurrency violation is encountered. Finally, I included a “save anyway” option. This option takes the values the user attempted to save and uses the last-in wins technique, overwriting whatever is in the database. It does this by calling a different command object associated with a stored procedure that only uses the primary key field (EmployeeID) in the WHERE clause of the UPDATE statement. This technique should be used with caution as it will overwrite the record.

If you want a more automatic way of dealing with the changes, you could get a fresh copy from the database. Then overwrite just the fields that the current user modified, such as the Extension field. That way, in the example I used the proper LastName would not be overwritten. Use this with caution as well, however, because if the same field was modified by both users, you may want to just back out or ask the user what to do next. What is obvious here is that there are several ways to deal with concurrency violations, each of which must be carefully weighed before you decide on the one you will use in your application.

Wrapping It Up

Setting the SqlDataAdapter’s ContinueUpdateOnError property tells the SqlDataAdapter to either throw an exception when a concurrency violation occurs or to skip the row that caused the violation and to continue with the remaining updates. By setting this property to false (its default value), it will throw an exception when it encounters a concurrency violation. This technique is ideal when only saving a single row or when you are attempting to save multiple rows and want them all to commit or all to fail.

I have split the topic of concurrency violation management into two parts. Next time I will focus on what to do when multiple rows could cause concurrency violations. I will also discuss how the DataViewRowState enumerators can be used to show what changes have been made to a DataSet.

How you will set the datarelation between two columns?
ADO.NET provides DataRelation object to set relation between two columns.It helps to enforce the following  constraints,a unique constraint, which guarantees that a column in the table  contains no duplicates and a foreign-key constraint,which can be used to maintain referential  integrity.A unique constraint is implemented either by simply setting the Unique property of a data  column to true, or by adding an instance of the UniqueConstraint class to the DataRelation object’s ParentKeyConstraint. As part of the foreign-key constraint, you can specify referential integrity  rules that are applied at three points,when a parent record is updated,when a parent record is deleted and when a change is accepted or rejected

ADO.Net Interview Questions 2

Explain what a diffgram is and its usage ?
A DiffGram is an XML format that is used to identify current and original versions of data elements. The DataSet uses the DiffGram format to load and persist its contents, and to serialize its contents for transport across a network connection. When a DataSet is written as a DiffGram, it populates the DiffGram with all the necessary information to accurately recreate the contents, though not the schema, of the DataSet, including column values from both the Original and Current row versions, row error information, and row order.

When sending and retrieving a DataSet from an XML Web service, the DiffGram format is implicitly used. Additionally, when loading the contents of a DataSet from XML using the ReadXml method, or when writing the contents of a DataSet in XML using the WriteXml method, you can select that the contents be read or written as a DiffGram.

The DiffGram format is divided into three sections: the current data, the original (or “before”) data, and an errors section, as shown in the following example.

<?xml version=”1.0″?>
<diffgr:diffgram
         xmlns:msdata=”urn:schemas-microsoft-com:xml-msdata”
         xmlns:diffgr=”urn:schemas-microsoft-com:xml-diffgram-v1″
         xmlns:xsd=”
http://www.w3.org/2001/XMLSchema“>

   <DataInstance>
   </DataInstance>

  <diffgr:before>
  </diffgr:before>

  <diffgr:errors>
  </diffgr:errors>
</diffgr:diffgram>

The DiffGram format consists of the following blocks of data:

<DataInstance>
The name of this element, DataInstance, is used for explanation purposes in this documentation. A DataInstance element represents a DataSet or a row of a DataTable. Instead of DataInstance, the element would contain the name of the DataSet or DataTable. This block of the DiffGram format contains the current data, whether it has been modified or not. An element, or row, that has been modified is identified with the diffgr:hasChanges annotation.
<diffgr:before>
This block of the DiffGram format contains the original version of a row. Elements in this block are matched to elements in the DataInstance block using the diffgr:id annotation.
<diffgr:errors>
This block of the DiffGram format contains error information for a particular row in the DataInstance block. Elements in this block are matched to elements in the DataInstance block using the diffgr:id annotation.

Which method do you invoke on the DataAdapter control to load your generated dataset with data?
You have to use the Fill method of the DataAdapter control and pass the dataset object as an argument to load the generated data.

Can you edit data in the Repeater control?
NO.

Which are the different IsolationLevels ?
Following are the various IsolationLevels:

  • Serialized   Data read by a current transaction cannot be changed by another transaction until the current transaction finishes. No new data can be inserted that would affect the current transaction. This is the safest isolation level and is the default. 
  • Repeatable Read   Data read by a current transaction cannot be changed by another transaction until the current transaction finishes. Any type of new data can be inserted during a transaction. 
  • Read Committed   A transaction cannot read data that is being modified by another transaction that has not committed. This is the default isolation level in Microsoft® SQL Server. 
  • Read Uncommitted   A transaction can read any data, even if it is being modified by another transaction. This is the least safe isolation level but allows the highest concurrency. 
  • Any   Any isolation level is supported. This setting is most commonly used by downstream components to avoid conflicts. This setting is useful because any downstream component must be configured with an isolation level that is equal to or less than the isolation level of its immediate upstream component. Therefore, a downstream component that has its isolation level configured as Any always uses the same isolation level that its immediate upstream component uses. If the root object in a transaction has its isolation level configured to Any, its isolation level becomes Serialized.

How xml files and be read and write using dataset?.
DataSet exposes method like ReadXml and WriteXml to read and write xml

What are the different rowversions available?
There are four types of Rowversions.
Current:
The current values for the row. This row version does not exist for rows with a RowState of Deleted.

Default :
The row the default version for the current DataRowState. For a DataRowState value of Added, Modified or Current, the default version is Current. For a DataRowState of Deleted, the version is Original. For a DataRowState value of Detached, the version is Proposed.

Original:
The row contains its original values.

Proposed:
The proposed values for the row. This row version exists during an edit operation on a row, or for a row that is not part of a DataRowCollection

Explain acid properties?.
The term ACID conveys the role transactions play in mission-critical applications. Coined by transaction processing pioneers, ACID stands for atomicity, consistency, isolation, and durability.

These properties ensure predictable behavior, reinforcing the role of transactions as all-or-none propositions designed to reduce the management load when there are many variables.

Atomicity
A transaction is a unit of work in which a series of operations occur between the BEGIN TRANSACTION and END TRANSACTION statements of an application. A transaction executes exactly once and is atomic — all the work is done or none of it is.

Operations associated with a transaction usually share a common intent and are interdependent. By performing only a subset of these operations, the system could compromise the overall intent of the transaction. Atomicity eliminates the chance of processing a subset of operations.

Consistency
A transaction is a unit of integrity because it preserves the consistency of data, transforming one consistent state of data into another consistent state of data.

Consistency requires that data bound by a transaction be semantically preserved. Some of the responsibility for maintaining consistency falls to the application developer who must make sure that all known integrity constraints are enforced by the application. For example, in developing an application that transfers money, you should avoid arbitrarily moving decimal points during the transfer.

Isolation
A transaction is a unit of isolation — allowing concurrent transactions to behave as though each were the only transaction running in the system.

Isolation requires that each transaction appear to be the only transaction manipulating the data store, even though other transactions may be running at the same time. A transaction should never see the intermediate stages of another transaction.

Transactions attain the highest level of isolation when they are serializable. At this level, the results obtained from a set of concurrent transactions are identical to the results obtained by running each transaction serially. Because a high degree of isolation can limit the number of concurrent transactions, some applications reduce the isolation level in exchange for better throughput.

Durability
A transaction is also a unit of recovery. If a transaction succeeds, the system guarantees that its updates will persist, even if the computer crashes immediately after the commit. Specialized logging allows the system’s restart procedure to complete unfinished operations, making the transaction durable.

Whate are different types of Commands available with DataAdapter ?
The SqlDataAdapter has SelectCommand, InsertCommand, DeleteCommand and UpdateCommand

What is a Dataset?
Datasets are the result of bringing together ADO and XML. A dataset contains one or more data of tabular XML, known as DataTables, these data can be treated separately, or can have relationships defined between them. Indeed these relationships give you ADO data SHAPING without needing to master the SHAPE language, which many people are not comfortable with.

The dataset is a disconnected in-memory cache database. The dataset object model looks like this:

Dataset
  DataTableCollection
  DataTable
   DataView
   DataRowCollection
    DataRow
   DataColumnCollection
    DataColumn
   ChildRelations
   ParentRelations
   Constraints
   PrimaryKey
DataRelationCollection

Let’s take a look at each of these:

DataTableCollection: As we say that a DataSet is an in-memory database. So it has this collection, which holds data from multiple tables in a single DataSet object.

DataTable: In the DataTableCollection, we have DataTable objects, which represents the individual tables of the dataset.

DataView: The way we have views in database, same way we can have DataViews. We can use these DataViews to do Sort, filter data.

DataRowCollection: Similar to DataTableCollection, to represent each row in each Table we have DataRowCollection.

DataRow:  To represent each and every row of the DataRowCollection, we have DataRows.

DataColumnCollection: Similar to DataTableCollection, to represent each column in each Table we have DataColumnCollection.

DataColumn: To represent each and every Column of the DataColumnCollection, we have DataColumn.

PrimaryKey: Dataset defines Primary key for the table and the primary key validation will take place without going to the database.

Constraints: We can define various constraints on the Tables, and can use Dataset.Tables(0).enforceConstraints. This will execute all the constraints, whenever we enter data in DataTable.

DataRelationCollection: as we know that we can have more than 1 table in the dataset, we can also define relationship between these tables using this collection and maintain a parent-child relationship.

Explain the ADO . Net Architecture ( .Net Data Provider)
ADO.Net is the data access model for .Net –based applications. It can be used to access relational database systems such as SQL SERVER 2000, Oracle, and many other data sources for which there is an OLD DB or ODBC provider. To a certain extent, ADO.NET represents the latest evolution of ADO technology. However, ADO.NET introduces some major changes and innovations that are aimed at the loosely coupled and inherently disconnected – nature of web applications.

A .Net Framework data provider is used to connecting to a database, executing commands, and retrieving results. Those results are either processed directly, or placed in an ADO.NET DataSet in order to be exposed to the user in an ad-hoc manner, combined with data from multiple sources, or remoted between tiers. The .NET Framework data provider is designed to be lightweight, creating a minimal layer between the data source and your code, increasing performance without sacrificing functionality.

Following are the 4 core objects of .Net Framework Data provider:

  • Connection: Establishes a connection to a specific data source
  • Command: Executes a command against a data source. Exposes Parameters and can execute within the scope of a Transaction from a Connection.
  • DataReader: Reads a forward-only, read-only stream of data from a data source.
  • DataAdapter: Populates a DataSet and resolves updates with the data source.

The .NET Framework includes the .NET Framework Data Provider for SQL Server (for Microsoft SQL Server version 7.0 or later), the .NET Framework Data Provider for OLE DB, and the .NET Framework Data Provider for ODBC.

The .NET Framework Data Provider for SQL Server:  The .NET Framework Data Provider for SQL Server uses its own protocol to communicate with SQL Server. It is lightweight and performs well because it is optimized to access a SQL Server directly without adding an OLE DB or Open Database Connectivity (ODBC) layer. The following illustration contrasts the .NET Framework Data Provider for SQL Server with the .NET Framework Data Provider for OLE DB. The .NET Framework Data Provider for OLE DB communicates to an OLE DB data source through both the OLE DB Service component, which provides connection pooling and transaction services, and the OLE DB Provider for the data source

The .NET Framework Data Provider for OLE DB: The .NET Framework Data Provider for OLE DB uses native OLE DB through COM interoperability to enable data access. The .NET Framework Data Provider for OLE DB supports both local and distributed transactions. For distributed transactions, the .NET Framework Data Provider for OLE DB, by default, automatically enlists in a transaction and obtains transaction details from Windows 2000 Component Services.

The .NET Framework Data Provider for ODBC: The .NET Framework Data Provider for ODBC uses native ODBC Driver Manager (DM) through COM interoperability to enable data access. The ODBC data provider supports both local and distributed transactions. For distributed transactions, the ODBC data provider, by default, automatically enlists in a transaction and obtains transaction details from Windows 2000 Component Services.

The .NET Framework Data Provider for Oracle: The .NET Framework Data Provider for Oracle enables data access to Oracle data sources through Oracle client connectivity software. The data provider supports Oracle client software version 8.1.7 and later. The data provider supports both local and distributed transactions (the data provider automatically enlists in existing distributed transactions, but does not currently support the EnlistDistributedTransaction method).

The .NET Framework Data Provider for Oracle requires that Oracle client software (version 8.1.7 or later) be installed on the system before you can use it to connect to an Oracle data source.
.NET Framework Data Provider for Oracle classes are located in the System.Data.OracleClient namespace and are contained in the System.Data.OracleClient.dll assembly. You will need to reference both the System.Data.dll and the System.Data.OracleClient.dll when compiling an application that uses the data provider.
Choosing a .NET Framework Data Provider

.NET Framework Data Provider for SQL Server: Recommended for middle-tier applications using Microsoft SQL Server 7.0 or later. Recommended for single-tier applications using Microsoft Data Engine (MSDE) or Microsoft SQL Server 7.0 or later.
Recommended over use of the OLE DB Provider for SQL Server (SQLOLEDB) with the .NET Framework Data Provider for OLE DB. For Microsoft SQL Server version 6.5 and earlier, you must use the OLE DB Provider for SQL Server with the .NET Framework Data Provider for OLE DB.

.NET Framework Data Provider for OLE DB: Recommended for middle-tier applications using Microsoft SQL Server 6.5 or earlier, or any OLE DB provider. For Microsoft SQL Server 7.0 or later, the .NET Framework Data Provider for SQL Server is recommended. Recommended for single-tier applications using Microsoft Access databases. Use of a Microsoft Access database for a middle-tier application is not recommended.

.NET Framework Data Provider for ODBC: Recommended for middle-tier applications using ODBC data sources. Recommended for single-tier applications using ODBC data sources.

.NET Framework Data Provider for Oracle: Recommended for middle-tier applications using Oracle data sources. Recommended for single-tier applications using Oracle data sources. Supports Oracle client software version 8.1.7 and later. The .NET Framework Data Provider for Oracle classes are located in the System.Data.OracleClient namespace and are contained in the System.Data.OracleClient.dll assembly. You need to reference both the System.Data.dll and the System.Data.OracleClient.dll when compiling an application that uses the data provider.

Can you explain the difference between an ADO.NET Dataset and an ADO Recordset?
Let’s take a look at the differences between ADO Recordset and ADO.Net DataSet:

1. Table Collection: ADO Recordset provides the ability to navigate through a single table of information. That table would have been formed with a join of multiple tables and returning columns from multiple tables. ADO.NET DataSet is capable of holding instances of multiple tables. It has got a Table Collection, which holds multiple tables in it. If the tables are having a relation, then it can be manipulated on a Parent-Child relationship. It has the ability to support multiple tables with keys, constraints and interconnected relationships. With this ability the DataSet can be considered as a small, in-memory relational database cache.

2. Navigation: Navigation in ADO Recordset is based on the cursor mode. Even though it is specified to be a client-side Recordset, still the navigation pointer will move from one location to another on cursor model only. ADO.NET DataSet is an entirely offline, in-memory, and cache of data. All of its data is available all the time. At any time, we can retrieve any row or column, constraints or relation simply by accessing it either ordinarily or by retrieving it from a name-based collection.

3. Connectivity Model: The ADO Recordset was originally designed without the ability to operate in a disconnected environment. ADO.NET DataSet is specifically designed to be a disconnected in-memory database. ADO.NET DataSet follows a pure disconnected connectivity model and this gives it much more scalability and versatility in the amount of things it can do and how easily it can do that.

4. Marshalling and Serialization: In COM, through Marshalling, we can pass data from 1 COM component to another component at any time. Marshalling involves copying and processing data so that a complex type can appear to the receiving component the same as it appeared to the sending component. Marshalling is an expensive operation. ADO.NET Dataset and DataTable components support Remoting in the form of XML serialization. Rather than doing expensive Marshalling, it uses XML and sent data across boundaries.

5. Firewalls and DCOM and Remoting: Those who have worked with DCOM know that how difficult it is to marshal a DCOM component across a router. People generally came up with workarounds to solve this issue. ADO.NET DataSet uses Remoting, through which a DataSet / DataTable component can be serialized into XML, sent across the wire to a new AppDomain, and then Desterilized back to a fully functional DataSet. As the DataSet is completely disconnected, and it has no dependency, we lose absolutely nothing by serializing and transferring it through Remoting.
 

COM and COM+ Interview Questions 1

What are different transaction options available for services components ?
There are 5 transactions types that can be used with COM+. Whenever an object is registered with COM+ it has to abide either to these 5 transaction types.

Disabled: - There is no transaction. COM+ does not provide transaction support for this component.

Not Supported: - Component does not support transactions. Hence even if the calling component in the hierarchy is transaction enabled this component will not participate in the transaction.

Supported: - Components with transaction type supported will be a part of the transaction if the calling component has an active transaction.
If the calling component is not transaction enabled this component will not start a new transaction.

Required: - Components with this attribute require a transaction i.e. either the calling should have a transaction in place else this component will start a new transaction.

Required New: - Components enabled with this transaction type always require a new transaction. Components with required new transaction type instantiate a new transaction for themselves every time.
Can we use com Components in .net?.How ?.can we use .net components in vb?.Explain how ?
COM components have different internal architecture from .NET components hence they are not innately compatible. However .NET  framework supports invocation of unmanaged code from managed code (and vice-versa) through COM/.NET interoperability. .NET application communicates with a COM component through a managed wrapper of the component called Runtime Callable Wrapper (RCW); it acts as managed proxy to the unmanaged COM component. When a method call is made to COM object, it goes onto RCW and not the object itself. RCW manages the lifetime management of the COM component. Implementation Steps -

Create Runtime Callable Wrapper out of COM component. Reference the metadata assembly Dll in the project and use its methods & properties RCW can be created using Type Library Importer utility or through VS.NET. Using VS.NET, add reference through COM tab to select the desired DLL. VS.NET automatically generates metadata assembly putting the classes provided by that component into a namespace with the same name as COM dll (XYZRCW.dll)

.NET components can be invoked by unmanaged code through COM Callable Wrapper (CCW) in COM/.NET interop. The unmanaged code will talk to this proxy, which translates call to managed environment. We can use COM components in .NET through COM/.NET interoperability. When managed code calls an unmanaged component, behind the scene, .NET creates proxy called COM Callable wrapper (CCW), which accepts commands from a COM client, and forwards it to .NET component. There are two prerequisites to creating .NET component, to be used in unmanaged code:
1. .NET class should be implement its functionality through interface. First define interface in code, then have the class to imlpement it. This way, it prevents breaking of COM client, if/when .NET component changes.

2.Secondly, .NET class, which is to be visible to COM clients must be declared public. The tools that create the CCW only define types based
on public classes. The same rule applies to methods, properties, and events that will be used by COM clients.

Implementation Steps -
1. Generate type library of .NET component, using TLBExporter utility. A type library is the COM equivalent of the metadata contained within
a .NET assembly. Type libraries are generally contained in files with the extension .tlb. A type library contains the necessary information to allow a COM client to determine which classes are located in a particular server, as well as the methods, properties, and events supported by those classes.
2. Secondly,  use Assembly Registration tool (regasm) to create the type library and register it.
3. Lastly install .NET assembly in GAC, so it is available as shared assembly.

What is Runtime Callable wrapper?.when it will created?.
The common language runtime exposes COM objects through a proxy called the runtime callable wrapper (RCW). Although the RCW appears to be an ordinary object to .NET clients, its primary function is to marshal calls between a .NET client and a COM object. This wrapper turns the COM interfaces exposed by the COM component into .NET-compatible interfaces. For oleautomation (attribute indicates that an interface is compatible with Automation) interfaces, the RCW can be generated automatically from a type library. For non-oleautomation interfaces, it may be necessary to develop a custom RCW which manually maps the types exposed by the COM interface to .NET-compatible types.

What is Com Callable wrapper?when it will created?
.NET components are accessed from COM via a COM Callable Wrapper (CCW). This is similar to a RCW, but works in the opposite direction. Again, if the wrapper cannot be automatically generated by the .NET development tools, or if the automatic behaviour is not desirable, a custom CCW can be developed. Also, for COM to ’see’ the .NET component, the .NET component must be registered in the registry.CCWs also manage the object identity and object lifetime of the managed objects they wrap.

What is a primary interop ?
A primary interop assembly is a collection of types that are deployed, versioned, and configured as a single unit. However, unlike other managed assemblies, an interop assembly contains type definitions (not implementation) of types that have already been defined in COM. These type definitions allow managed applications to bind to the COM types at compile time and provide information to the common language runtime
about how the types should be marshaled at run time.

What are tlbimp and tlbexp tools used for ?
The Type Library Exporter generates a type library that describes the types defined in a common language runtime assembly.
The Type Library Importer converts the type definitions found within a COM type library into equivalent definitions in a common language runtime assembly. The output of Tlbimp.exe is a binary file (an assembly) that contains runtime metadata for the types defined within the original type library.

What benefit do you get from using a Primary Interop Assembly (PIA)?
PIAs are important because they provide unique type identity. The PIA distinguishes the official type definitions from counterfeit definitions provided by other interop assemblies. Having a single type identity ensures type compatibility between applications that share the types defined in the PIA. Because the PIA is signed by its  publisher and labeled with the PrimaryInteropAssembly attribute, it can be differentiated from other interop assemblies that define the same types.

Web Services Interview Questions 1

Can you give an example of when it would be appropriate to use a web service as opposed to non-serviced .NET component
Web service is one of main component in Service Oriented Architecture. You could use web services when your clients and servers are running on different networks and also different platforms. This provides a loosely coupled system. And also if the client is behind the firewall it would be easy to use web service since it runs on port 80 (by default) instead of having some thing else in Service Oriented Architecture applications.

What is the standard you use to wrap up a call to a Web service
“SOAP.

What is the transport protocol you use to call a Web service SOAP
HTTP with SOAP

What does WSDL stand for?
“WSDL stands for Web Services Dsescription Langauge. There is WSDL.exe that creates a .wsdl Files which defines how an XML Web service behaves and instructs clients as to how to interact with the service.
eg: wsdl http://LocalHost/WebServiceName.asmx

Where on the Internet would you look for Web Services?
www.uddi.org

What does WSDL stand for?
Web Services Description Language

True or False: To test a Web service you must create a windows application or Web application to consume this service?
False.

What are the various ways of accessing a web service ?
1.Asynchronous Call
  Application can make a call to the Webservice and then continue todo watever oit  wants to do.When the service is ready it will notify the application.Application  can use BEGIN and END method to make asynchronous call to the webmethod.We can use  either a WaitHandle or a Delegate object when making asynchronous call.

The WaitHandle class share resources between several objects. It provides several  methods which will wait for the resources to become available

The easiest and most powerful way to to implement an asynchronous call is using a  delegate object. A delegate object wraps up a callback function. The idea is to  pass a method in the invocation of the web method. When the webmethod has finished  it will call this callback function to process the result

2.Synchronous Call
Application has to wait until execution has completed.

What are VSDISCO files?
VSDISCO files are DISCO files that support dynamic discovery of Web services. If you place the following VSDISCO file in a directory on your Web server, for example, it returns   references to all ASMX and DISCO files in the host directory and any subdirectories not noted in <EXCLUDE>elements:


            
                <DYNAMICDISCOVERY
                  xmlns=”urn:schemas-dynamicdiscovery:disco.2000-03-17″>
                  <EXCLUDE path=”_vti_cnf” />
                  <EXCLUDE path=”_vti_pvt” />
                  <EXCLUDE path=”_vti_log” />
                  <EXCLUDE path=”_vti_script” />
                  <EXCLUDE path=”_vti_txt” />
                </DYNAMICDISCOVERY>  

How does dynamic discovery work?
ASP.NET maps the file name extension VSDISCO to an HTTP handler that scans the host  directory and subdirectories for ASMX and DISCO files and returns a dynamically generated DISCO document. A client who requests a VSDISCO file gets back what appears to be a s