Saturday, December 31, 2011

ADO.Net Overview

ADO.NET Components
The two main components of ADO.NET 3.0 for accessing and manipulating data are the .NET Framework data providers and the DataSet.

.NET Framework Data Providers

The .NET Framework Data Providers are components that have been explicitly designed for data manipulation and fast, forward-only, read-only access to data. The Connection object provides connectivity to a data source. The Command object enables access to database commands to return data, modify data, run stored procedures, and send or retrieve parameter information. The DataReader provides a high-performance stream of data from the data source. Finally, the DataAdapter provides the bridge between the DataSet object and the data source. The DataAdapter uses Command objects to execute SQL commands at the data source to both load the DataSet with data and reconcile changes that were made to the data in the DataSet back to the data source. For more information, see .NET Framework Data Providers (ADO.NET) and Retrieving and Modifying Data in ADO.NET.


The DataSet

The ADO.NET DataSet is explicitly designed for data access independent of any data source. As a result, it can be used with multiple and differing data sources, used with XML data, or used to manage data local to the application. The DataSet contains a collection of one or more DataTable objects consisting of rows and columns of data, and also primary key, foreign key, constraint, and relation information about the data in the DataTable objects. For more information, see DataSets, DataTables, and DataViews (ADO.NET).


Following grid shows the description of ADO.net components. Courtesy: Ritvik Pandya (rtvk05@gmail.com)

S.N.
Class
Description
1
DataSet
The DataSet is a local bugger of tables or a collection of disconnected record sets.
2
DataTable
A DataTable is used to contain data in tabular form using rows and columns.
3
DataRow
Represents a single record or row in DataTable.
4
DataColumn
Represents a column or field of a DataTable.
5
DataRelation
Represents the relationship between different tables in a data set.
6
Constraint
Represents the constraints or limitations that apply to a particular field or column.


The following diagram illustrates the relationship between a .NET Framework data provider and a DataSet.

ADO.net Architecture


Performing Common Data Access Tasks with ADO.net
ADO.net also contains some database specific classes. This means that different database system providers may provide classes (or Drivers) optimized for their particular database system. Microsoft itself has provided the specialized and optimized classes for their SQL Server database system. The name if these classes start with “Sql” and are contained in the System.Data.SqlClient namespace.

Similarly, Oracle has also providers its classes (drivers) optimized for the Oracle DB system. Microsoft has also provided the general classes which can connect your application to any OEL supported database server. The name of these classes start with ‘OleDb’ and these are contained in the System.Data.OleDb namespace.

In fact, we can use OldeDb classes to connect to SQL Server or Oracle Database; using the database specific classes generally provides optimized performance, however.

S.N.
Class
Description
1
SqlConnection, OleDbConnection
Represents a connection to the database system.
2
SqlCommand, OleDbCommand
Represents SQL Query.
3
SqlDataAdapter, OldeDbDataAdapter
A class that connects to the database system, fetches the records and fills the dataset.
4
SqlDataReader, OleDbDataReader
A stream that reads data from the database in a connected design.
5
SqlParameter, OldeDbParameter
Represents a parameter to a stored procedure.


Access Data using ADO.net
Data access using ADO.Net involves the following steps:

·         Defining the connection string for the database server.
·         Defining the connection (SqlConnection or OleDbConnection) to the database using the connection string.
·         Defining the command (SqlCommand or OleDbCommand) or command string that contains the query.
·         Defining the data adapter (SqlDataAdapter or OleDbDataAdapter) using the command string and the connection object.)
·         Creating a new DataSet object.
·         If the command is SELECT, filling the dataset object with the result of the query through the data adapter.
·         Reading the records from the DataTables in the datasets using the DataRow and DataColumn objects.
·         If the command is UPDATE, INSERT or DELETE, then updating the dataset through the data adapter.
·         Accepting to save the changes in the dataset to the database.


AXIS2 with AXIOM

(AXis Object Model)
Refers to the information included inside the XML.
DOM and JDOM are XML models which are made up of objects, AXIOM is similar to them.

AXIOM is based on ‘Pull Parsing’. Unlike ‘push based’ XML processing frameworks (SAX and DOM), which were not efficient in terms of handling large XML documents since these framework generates complete memory model in memory. Pull parsing gives control to user, here user gives command and he/she can decide to store or discard events generated from parser. AXIOM uses StAX for pull parsing.
AXIOM is lightweight.
AXIOM does not create objects unless a need arise for them, this is called ‘Deferred building’.
AXIOM defines below interfaces to represent nodes in XML :

Interface / Class
Remark
OMElement
Represents an elemet infuset information.
 
OMText
Represents character data that appears inside an element.
 
OMComment         
For Comments
 
OMDocType
The doc type

OMProcessingInstruction

 
Processing instructions with target to process and value.
OMSourcedElement
Element whose data is backed by an arbitrary Java object.

           
AXIOM api can be implements in two ways :
1) LLOM : Linked List implementation uses linked lists to store collection of nodes.
2) DOOM (DOM over OM ) supports DOM api.
Default implementation uses factory design pattern. For each of above implementation, there are 3 factories.
For example , if we need factory to process plain XML, we’ll use OMAbstractFactory api. Here is a code snap:
// creates factory to process plain XML
OMFactory plainXMLProcessFactory = OMAbstractFactory.getOMFactory();
// Namespace can be created through createOMNamespace, It takes 2 parameters URI //and Prefix for that URI
OMNamespace nameSpace1 = plainXMLProcessFactory.createOMNamespace(“uri1”,"prefix1");
OMNamespace nameSpace2 = plainXMLProcessFactory.createOMNamespace("uri2","prefix2”);
// xmlns:prefix1=”uri1”
// Elements can be created using ‘createOMElement’ method, this is a //overloaded method
OMElement element = plainXMLProcessFactory.createOMElement("foo",namespace1);

// foo is localname here
// To create text for node AXIOM provides createOMText method

OMText text = plainXMLProcessFactory.createOMText(parentOMContainer, srcOMText);

To add child in elements OMElement provides addChild method , similarly to add attributes addAttribute method helps . Node can be removed by calling detach method on it.

Here are the steps to create an object model from an input stream
 
1)    Create InputStream object
     InputStream inStream = new FileInputStream(xmlFile);
2)    Create OMBuilder instance 
OMXMLParserWrapper builder = 
        OMXMLBuilderFactory.createOMBuilder(in);
3)    Get root elements
     OMElement documentElement = builder.getDocumentElement(); 
 
 

AXIOM uses “builder” to build the XML object model in memory. This builder builds object only when the relevant information is absolutely required.
AXIOM comes bundled with several builders:
  • StAXOMBuilder: This will build a generic memory model from any XML input source, such as a file, string, stream, etc.
  • StAXSOAPModelBuilder: This will build an object structure of SOAP XML in memory, which can be accessed using an "SOAPish" API. For example, when using it, you get a SOAPEnvelope class, with which you can call methods like getHeaders() andgetBody(). But this API is still an extension of the generic AXIOM API. This is the model mainly used within the Axis2 project.
  • MTOMBuilder: This can be regarded as the first implementation of MTOM, the new API for sending attachments using some optimization algorithms. The latest AXIOM sources have full support for MTOM.
Please note that the current AXIOM implementation lags support for processing instructions and DTD information items of the XML infoset. But there is an ongoing effort within the Axis2 team to provide these features as well.

Writing XML with AXIOM :

Here is a sample to create XML and write it to console :

package com.rtvk;
import javax.xml.stream.FactoryConfigurationError;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;
import org.apache.axiom.om.OMAbstractFactory;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.OMFactory;
import org.apache.axiom.om.OMNamespace;
public class AXIOM_Sample {
public static void main(String[] args){
//The factory to process XML
OMFactory plainXMLProcessFactory = OMAbstractFactory.getOMFactory();

// namespace
OMNamespace ns =
plainXMLProcessFactory .createOMNamespace("http://rtvk.com","rp");

//root element
OMElement rootElement =
plainXMLProcessFactory .createOMElement("rootElement", ns);

// child 1
OMElement firstElement =
plainXMLProcessFactory .createOMElement("firstElement", ns);
firstElement.setText("I am First");
firstElement.addAttribute("attrFoFirstEle", "valForFirstAttr", ns);

// child 2
OMElement secondElement =
plainXMLProcessFactory .createOMElement("secondElement", ns);
secondElement.setText("I am second");
secondElement.addAttribute("attrFoSecondEle", "valForSecondAttr", ns);
           
//adding to root
rootElement.addChild(firstElement);
rootElement.addChild(secondElement);
//to write
XMLStreamWriter writer;
try {

//write to console
writer = XMLOutputFactory.newInstance().createXMLStreamWriter(System.out);
rootElement.serialize(writer, false);
writer.flush();
} catch (XMLStreamException e) {
e.printStackTrace();
} catch (FactoryConfigurationError e) {
e.printStackTrace();
}
}
}

Output in console :
<rp:rootElement xmlns:rp="http://rtvk.com">
<rp:firstElement rp:attrFoFirstEle="valForFirstAttr">
I am First
</rp:firstElement>
<rp:secondElement rp:attrFoSecondEle="valForSecondAttr">
I am second
</rp:secondElement>
</rp:rootElement>


READING / Navigate / Travels XML With AXIOM :

package com.rtvk.services;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.Iterator;
import javax.xml.stream.FactoryConfigurationError;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import org.apache.axiom.om.OMAbstractFactory;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.impl.builder.StAXOMBuilder;
public class AXIOM_Sample_Read {
public static void main(String[] args){
FileReader fileReader;
try {
fileReader = new FileReader("Sample.xml");
XMLStreamReader streamReader = XMLInputFactory.newInstance().createXMLStreamReader(fileReader);

StAXOMBuilder builder = new StAXOMBuilder(
OMAbstractFactory.getOMFactory(),
streamReader);

OMElement documentElement = builder.getDocumentElement();

//complete XML
System.out.println(builder.getDocument().getOMDocumentElement());

// Child node text
Iterator<OMElement> iterator = documentElement.getChildElements();

while(iterator.hasNext()){
OMElement omElement = (OMElement)iterator.next();
System.out.println(omElement.getText());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (XMLStreamException e) {
e.printStackTrace();
} catch (FactoryConfigurationError e) {
e.printStackTrace();
}
}
}

Output in Console :
<rp:rootElement xmlns:rp="http://rtvk.com"><rp:firstElement rp:attrFoFirstEle="valForFirstAttr">I am First</rp:firstElement><rp:secondElement rp:attrFoSecondEle="valForSecondAttr">I am Second</rp:secondElement></rp:rootElement>
I am First
I am second
Courtesy: Ritvik Pandya (rtvk05@gmail.com )

Sunday, December 25, 2011

Exceptions in C# and .Net

Exception handling is a mechanism to handle run-time errors in .NET that would otherwise cause your software to terminate prematurely.
Programmers may define and throw an exception in the case of unexpected events. Below are some important points about the exception and exception handling mechanisms in C# and .Net
·         All exceptions in .Net are objects. The System.Exception class is the base class for all exceptions in .Net. Any method can raise or throw an exception in the case of some unexpected event during its execution using the throw keyword in C#. the throws exception can be caught or dealt within the calling method using the try…catch block.
·         The code that may throw an exception which we want to handle is put in the try block. This is called attempt to catch and exception. The code to handle the thrown exception is placed in the catch block just after the try lock. This is called catching the exception. We can define which particular class of exception we want to deal with this catch block by mentioning the name of exception after the catch keyword.
·         Multiple catch blocks can be defined for a single try block where each catch block will catch a particular class of exception.
·         The code that must always be executed after the try or try…catch block is placed in finally block, placed just after the try or try…catch blocks. This code is guaranteed to always be executed whether the exception occurs or not.
·         Since exceptions are present in .Net as classes and objects, they follow the inheritance hierarchy. This means that if you write a catch block to handle a base class exception, it will automatically handle all of its sub-class’s exceptions. Attempting to catch any of the sub-class’s exceptions explicitly after the parent class exception will cause a compile time error.
·         The finally block is optional. Exception handling requires a combination of either :-
o   Try…Catch.
o   Try…Catch…Finally.
o   Try…Finally. (if not catching the exception.)
·         If you do not catch an exception, the runtime environment (Common Language Runtime or CLR) will catch it on your behalf, causing your program to terminate.

Will post more…….Enjoy!

Friday, December 23, 2011

Nested Classes in C#

C# supports the Nested Classes concept. Nested classes in C# are similar to Java’s static inner classes, but there is no concept like Java’s non-static inner classes in C#.

Please have a look into the dummy code given below :- 

Program.cs 

class Program
    {
        static void Main(string[] args)
        {
            OuterClass outerClass = new OuterClass();
            outerClass.DisplayPosition();

            OuterClass.InnerClass innerClass = new OuterClass.InnerClass();
            innerClass.DisplayPosition();

            OuterClass outerClassArg = new OuterClass("outer arg");
            outerClassArg.DisplayPosition();

            OuterClass.InnerClass innerClassArg = new OuterClass.InnerClass("inner arg");
            innerClassArg.DisplayPosition();

            Console.ReadKey();
        }
    }



NestedClassesInCSharp.cs 

/// <summary>
    /// Outer class
    /// </summary>
    public class OuterClass
    {
        #region Constructors

        public OuterClass()
        {
            Console.WriteLine("\nI am OUTER class constructor.\n");
            _position = "Software Engineer";
        }

        public OuterClass(string arg)
        {
            Console.WriteLine("\nI am OUTER class argumented constructor.\n");
            _position = "Software Engineer";
        }

        #endregion

        #region Class Members

        private static string _position = string.Empty;

        #endregion

        #region Public Methods

        public void DisplayPosition()
        {
            Console.WriteLine("\nOuter Class Position :" + _position);
        }

        #endregion

        #region Nested Classes

        public class InnerClass
        {
            #region Constructors

            public InnerClass()
            {
                Console.WriteLine("\nI am INNER class constructor\n");
                _position = "Computer Analyst.";
            }

            public InnerClass(string arg)
            {
                Console.WriteLine("\nI am INNER class argumented constructor\n");
            }

            #endregion

            #region Public Methods

            public void DisplayPosition()
            {
                Console.WriteLine("\nNested Class Position :" + _position);
            }
            #endregion
        }

        #endregion
    }


In above example we have Inner class inside the Outer class.

There are some constraints that applied in this type of structure.



1.       The top level class can only be marked as “Public” or “Internal”.

2.       The inner or nested classes can be marked with all modifies such as “Public”, “Private”, “Internal” and “Protected”.

3.       Like all other class members the default access modifier of inner or nested classes is “Private” that means the nested class or inner class cannot be accessed or referenced outside of the containing class.

4.       Important : nested or inner class has access to all (“Public”, “Private”, “Internal” and “Protected”) STATIC members of its container class. i.e. static Member variable, static methods etc.

5.       Important : since the nested classes are instantiated with reference to the enclosing class, their access protection level always remains less than or equal to that of the enclosing class. Hence, if the access level of the enclosing class is internal and the access level of the nested class is public, the nested class would only be accessible in the current assemble (project).



Enjoy!