Sunday, May 18, 2008

Using Microsoft .NET and C# with Oracle 9i

Oracle provides a software tool called ODP.NET that allows connectivity between the .NET languages and an Oracle database. This interface is a set of tools that allow the creation of .NET objects that connect directly to Oracle databases. Learn the basics of connecting to and performing simple queries to an Oracle database.

Prerequisites
Let’s face it -- neither Microsoft nor Oracle really wants to see their two flagship products work together. Microsoft would rather see a programmer use C# with SQL Server, Access, or just a plain XML data file before connecting to an Oracle data source. Oracle, on the other hand, has committed firmly to the J2EE development system for major development involving their databases.

However, Oracle does provide a software tool called ODP.NET that allows connectivity between the .NET languages and an Oracle database. This interface is a set of tools that allows the creation of .NET objects that connect directly to Oracle databases. This, at the very least, allows applications to connect to and make use of the power and capability of an Oracle database. It includes support for regular SQL queries and updates, stored procedures, and reading data from an Oracle record set into a .NET DataSet object, among other things. This article will cover the basics of connecting to and performing simple queries to an Oracle database using this set of objects.

First we’ll look at the set-up required to perform these tasks. If you are going to work with ODP.NET in ASP.NET applications, you will, obviously, need a web server with IIS and the .NET Framework installed and running. I will not be covering the steps needed to set up an IIS Web Application, as I will be focusing on actually working with the database.

If you are only working on a stand-alone application, you will just need the .NET Framework installed. In both cases, you will probably want some sort of development environment to allow easy editing of .NET code. Next, you will need to install the ODP.NET data provider on the web server if you are using ASP.NET or on your local machine if you are writing a stand-alone app. Also, each computer that will access the database as a client will need the Oracle client software installed. ODP.NET is a client-side library, and will need to be installed with your application if you are thinking of distributing your application widely. One of the nice things about ODP.NET is that it doesn’t require any extra configuration of the Oracle server. You can download the ODP.NET driver from the Oracle website at:

http://otn.oracle.com/software/tech/windows/odpnet/index.html

The first important thing to recognize about ODP.NET for Oracle 9i is that it contains two namespaces, first Oracle.DataAccess.Client. This contains the actual working classes for connecting to and acting on the Oracle database. The second namespace is Oracle.DataAccess.Types. This namespace has all the classes and methods required when working with specific Oracle data types. In this article, we won’t deal with the Types namespace at all. There are several classes to take note of in Oracle.DataAccess.Client and these are:

OracleConnection -- The basic class for connecting to a database

OracleCommand -- A class that represents a database command, either a text query or a stored procedure

OracleDataAdapter -- This class allows the programmer to pipe a returned Oracle record-set into a .NET DataSet

OracleParameter -- This class represents all the attributes and information in a stored procedure parameter

OracleDataReader -- This class represents a simple, read only data set, useful for quickly getting small, simple results, or data you will not want to change

Each of these classes will become very important in the future when we look a connecting to and working with an Oracle database.

Connecting to a Database
The process for connecting to an Oracle database is very straightforward, especially for anyone who has worked with the .NET database connection classes for SQL Server. Oracle basically copied the same class structure that Microsoft used in the SQL Server connection classes already present in .NET. This makes moving over from SQL Server to Oracle relatively easy. It also means that a lot of examples describing database interaction with SQL Server can easily be modified to work with Oracle. In any case, here is a quick overview of the steps required to connect to an Oracle database.

When working with a database, we must create an OracleConnection object to retain all information for communicating with the database. First, we import the required assemblies.

using Oracle.DataAccess.Client;
using System.Data;

Next, we create the connection string with the user credentials information. In this case, the Oracle schema is user1 the password is mypass and the Oracle database name either in the tnsnames file or in the Oracle Internet Directory is db.

String connString = “User id=user1;Password=mypass;source=db”;

Now, the connection object, conn, is created using the connection string.

OracleConnection conn = new OracleConnection(connString);

The last step is to begin communication with the database using the Open() method.

conn.Open();

This creates a connection to a database and opens it. The most important part is making sure the connection string is correct. Each different type of database uses a different connection string and the differences in syntax can be a problem if you don’t pay close attention to them.

Creating a Command
In this section, we look at creating the main workhorse class and its attributes and capabilities. The OracleCommand class has two main functions. First, you can give it a simple SQL query string and execute that command on the database. Secondly, you can use the OracleCommand object to execute a stored procedure on the database.

The query string is the simplest use of this command and we will look at it first.

First, create the command by using the factory method CreateCommand() method on the OracleConnection object.

OracleCommand cmd = conn.CreateCommand();

This creates a command object attached to the conn connection. Alternatively, the command object can be created using its own constructor and then set the Connection field later:

OracleCommand cmd = new OracleCommand();
cmd.Connection = conn;

After creating the command, we must set the CommandText attribute to give the object the actual string containing the SQL query it will run on the database. The code below also sets the CommandType attribute, which selects whether CommandText is a text command or the name of a stored procedure (this defaults to Text):

String query = “select * from users”;
cmd.CommandText = query;
cmd.CommandType = CommandType.Text;

The last step to complete is to run the command on the database and catch the results in an OracleDataReader object.

OracleDataReader reader = cmd.ExecuteReader();

This executes the command on the database and puts the results in reader. There is an important distinction between queries that read data and those that only update data. When your command reads data, you use the ExecuteReader() method to get this data back. However, when all your command does is insert or update data with nothing meaningful to return, you would use the ExecuteNonQuery() method which we will cover later.

The other mode that OracleCommand can operate in is for executing a stored procedure. This process works somewhat differently than when executing a straight text command.

Everything is the same as above until we set the command text string. In this case, the CommandText attribute is set to the name of the stored procedure. In the following case, this is a stored procedure to get back users in a certain range of user_id’s, called GetUsers. Notice also how the following code sets the CommandType attribute to StoredProcedure:

cmd.CommandText = “GetUsers”;
cmd.CommandType = CommandType.StoredProcedure;

After setting the stored procedure name and command type, we must add parameters to the OracleCommand object. This involves creating multiple OracleParameter objects and adding them to the OracleCommand’s Parameter member. This is done in the following manner:

cmd.Parameters.add(new OracleParameter(“start_user”,OracleDbType.Int, 202));

This code creates a parameter to the stored procedure GetUsers called start_user which is of type Int and has the value 202. This object is then added to the OracleCommand’s Parameters collection that stores all of the different parameters to the stored procedure. There are several things to note here. First of all, when creating multiple parameters, the number of parameters must match the number of parameters expected by the stored procedure. It is also a good idea to match up order so that parameter objects are added to the Parameters collection in the same order that they appear in the stored procedure definition to make debugging easier.

After adding the second parameter, ExecuteReader is called to get the results from the database.

cmd.Parameters.add(new OracleParameter(“end_user”, OracleDbType.Int, 210));
OracleDataReader reader = cmd.ExecuteReader();

This has shown the basics of reading data out of the database. The next step is to take that data and turn it into a .NET DataSet that can be bound to a data driven control or iterated over and changed to later update the database.

Creating a DataSet from and Oracle Database
The first step to creating a DataSet from an Oracle database is to make use of a new secondary class, called the OracleDataAdapter. This class basically takes the data as it comes back from Oracle and parses it into a .NET DataSet. Another useful characteristic of this class is that it takes the place of an OracleCommand object. The OracleDataAdapter contains the command string and parameter objects required to execute a command (either text or stored procedure) on the database. There are several ways to create an OracleDataAdapter object. However, the one shown below uses an OracleConnection object and a string to become the Select command.


OracleDataAdapter adapter = new OracleDataAdapter(conn, “select * from users”);
DataSet set = new DataSet();
adapter.fill(set, “users”);

After creating the OracleDataAdapter we create a DataSet object to take the results of the select statement. Then, we use the fill method to populate a DataTable object named “users” inside the DataSet with the data returned from the select statement. Now, you can do all the fun, nifty things you could always do with a DataSet, such as binding it to data driven controls, modifying the data and putting it back into the database. The OracleDataAdapter also contains data members to hold insert, update, and delete commands, so the object can even automate maintaining data in the database in the same state as the DataSet in memory. However, those functions are beyond the purview of this article.

Final Words
Overall, the ODP.NET class framework follows many of the normal conventions that any database programmer finds in other such frameworks. This makes is relatively easy to learn and pick up on for the experienced database programmer, and even for the novice, the classes are laid out in a logical way that makes understanding each ones function easy.

DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.

(http://www.aspfree.com/c/a/.NET/Using-Microsoft-dot-NET-and-C-sharp-with-Oracle-9i/)


Read more!!!

The History Of Programming Language

Prehistory
The first programming languages predate the modern computer. From the first, the languages were codes.
During a nine-month period in 1842-1843, Ada Lovelace translated Italian mathematician Luigi Menabrea's memoir on Charles Babbage's newest proposed machine, the Analytical Engine. With the article, she appended a set of notes which specified in complete detail a method for calculating Bernoulli numbers with the Engine, recognized by some historians as the world's first computer program. But some biographers debate the extent of her original contributions versus those of her husband.
The Jacquard loom used holes in punched cards to represent sewing loom arm movements in order to generate decorative patterns automatically.
Herman Hollerith realized that he could encode information on punch cards when he observed that railroad train conductors would encode the appearance of the ticket holders on the train tickets using the position of punched holes on the tickets. Hollerith then proceeded to encode the 1890 census data on punch cards.
The first computer codes were specialized for the applications. In the first decades of the twentieth century, numerical calculations were based on decimal numbers. Eventually it was realized that logic could be represented with numbers, as well as with words. For example, Alonzo Church was able to express the lambda calculus in a formulaic way. The Turing machine was an abstraction of the operation of a tape-marking machine, for example, in use at the telephone companies. However, unlike the lambda calculus, Turing's code does not serve well as a basis for higher-level languages — its principal use is in rigorous analyses of algorithmic complexity.

Like many "firsts" in history, the first modern programming language is hard to identify. From the start, the restrictions of the hardware defined the language. Punch cards allowed 80 columns, but some of the columns had to be used for a sorting number on each card. Fortran included some keywords which were the same as English words, such as "IF", "GOTO" (go to) and "CONTINUE". The use of a magnetic drum for memory meant that computer programs also had to be interleaved with the rotations of the drum. Thus the programs were more hardware dependent than today.
To some people the answer depends on how much power and human-readability is required before the status of "programming language" is granted. Jacquard looms and Charles Babbage's Difference Engine both had simple, extremely limited languages for describing the actions that these machines should perform. One can even regard the punch holes on a player piano scroll as a limited domain-specific programming language, albeit not designed for human consumption.

The 1940s
In the 1940s the first recognizably modern, electrically powered computers were created. The limited speed and memory capacity forced programmers to write hand tuned assembly language programs. It was soon discovered that programming in assembly language required a great deal of intellectual effort and was error-prone.
In 1948, Konrad Zuse published a paper about his programming language Plankalkьl. However, it was not implemented in his time and his original contributions were isolated from other developments.
Some important languages that were developed in this period include:
1943 - Plankalkьl (Konrad Zuse)
1943 - ENIAC coding system
1949 - C-10


The 1950s and 1960s
In the 1950s the first three modern programming languages whose descendants are still in widespread use today were designed:
FORTRAN, the "FORmula TRANslator, invented by John W. Backus et al.;
LISP, the "LISt Processor", invented by John McCarthy et al.;
COBOL, the COmmon Business Oriented Language, created by the Short Range Committee, heavily influenced by Grace Hopper.
Another milestone in the late 1950s was the publication, by a committee of American and European computer scientists, of "a new language for algorithms"; the Algol 60 Report (the "ALGOrithmic Language"). This report consolidated many ideas circulating at the time and featured two key innovations:
The use of Backus-Naur Form (BNF) for describing the language's syntax. Nearly all subsequent programming languages have used a variant of BNF to describe the context-free portion of their syntax.
The introduction of lexical scoping for names in arbitrarily nested scopes.
Algol 60 was particularly influential in the design of later languages, some of which soon became more popular. The Burroughs large systems were designed to be programmed in an extended subset of Algol.
Some important languages that were developed in this period include:
1951 - Regional Assembly Language
1952 - Autocode
1954 - FORTRAN
1955 - FLOW-MATIC (forerunner to COBOL)
1957 - COMTRAN (forerunner to COBOL)
1958 - LISP
1958 - ALGOL 58
1959 - COBOL
1962 - APL
1962 - Simula
1964 - BASIC
1964 - PL/I

1967-1978: establishing fundamental paradigms
The period from the late 1960s to the late 1970s brought a major flowering of programming languages. Most of the major language paradigms now in use were invented in this period:
Simula, invented in the late 1960s by Nygaard and Dahl as a superset of Algol 60, was the first language designed to support object-oriented programming.
Smalltalk (mid 1970s) provided a complete ground-up design of an object-oriented language.
C, an early systems programming language, was developed by Dennis Ritchie and Ken Thompson at Bell Labs between 1969 and 1973.
Prolog, designed in 1972 by Colmerauer, Roussel, and Kowalski, was the first logic programming language.
ML built a polymorphic type system (invented by Robin Milner in 1973) on top of Lisp, pioneering statically typed functional programming languages.
Each of these languages spawned an entire family of descendants, and most modern languages count at least one of them in their ancestry.
The 1960s and 1970s also saw considerable debate over the merits of "structured programming", which essentially meant programming without the use of GOTO. This debate was closely related to language design: some languages did not include GOTO, which forced structured programming on the programmer. Although the debate raged hotly at the time, nearly all programmers now agree that, even in languages that provide GOTO, it is bad style to use it except in rare circumstances. As a result, later generations of language designers have found the structured programming debate tedious and even bewildering.
Some important languages that were developed in this period include:
1970 - Pascal
1970 - Forth
1972 - C
1972 - Smalltalk
1972 - Prolog
1973 - ML
1978 - SQL


The 1980s: consolidation, modules, performance
The 1980s were years of relative consolidation. C++ combined object-oriented and systems programming. The United States government standardized Ada, a systems programming language intended for use by defense contractors. In Japan and elsewhere, vast sums were spent investigating so-called "fifth generation" languages that incorporated logic programming constructs. The functional languages community moved to standardize ML and Lisp. Rather than inventing new paradigms, all of these movements elaborated upon the ideas invented in the previous decade.
However, one important new trend in language design was an increased focus on programming for large-scale systems through the use of modules, or large-scale organizational units of code. Modula, Ada, and ML all developed notable module systems in the 1980s. Module systems were often wedded to generic programming constructs---generics being, in essence, parameterized modules (see also parametric polymorphism).
Although major new paradigms for programming languages did not appear, many researchers expanded on the ideas of prior languages and adapted them to new contexts. For example, the languages of the Argus and Emerald systems adapted object-oriented programming to distributed systems.
The 1980s also brought advances in programming language implementation. The RISC movement in computer architecture postulated that hardware should be designed for compilers rather than for human assembly programmers. Aided by processor speed improvements that enabled increasingly aggressive compilation techniques, the RISC movement sparked greater interest in compilation technology for high-level languages.
Language technology continued along these lines well into the 1990s.
Some important languages that were developed in this period include:
1983 - Ada
1983 - C++
1985 - Eiffel
1987 - Perl
1989 - FL (Backus)


The 1990s: the Internet age
The rapid growth of the Internet in the mid-1990s was the next major historic event in programming languages. By opening up a radically new platform for computer systems, the Internet created an opportunity for new languages to be adopted. In particular, the Java programming language rose to popularity because of its early integration with the Netscape Navigator web browser, and various scripting languages achieved widespread use in developing customized applications for web servers. Neither of these developments represented much fundamental novelty in language design; for example, the design of Java was a more conservative version of ideas explored many years earlier in the Smalltalk community, but the widespread adoption of languages that supported features like garbage collection and strong static typing was a major change in programming practice.
Some important languages that were developed in this period include:
1990 - Haskell
1990 - Python
1991 - Java
1993 - Ruby
1995 - PHP
2000 - C#


Current trends
Programming language evolution continues, in both industry and research. Some current directions:
Mechanisms for adding security and reliability verification to the language: extended static checking, information flow control, static thread safety.
Alternative mechanisms for modularity: mixins, delegates, aspects.
Component-oriented software development.
Metaprogramming, reflection or access to the abstract syntax tree
Increased emphasis on distribution and mobility.
Integration with databases, including XML and relational databases.
Open Source as a developmental philosophy for languages, including the GNU compiler collection and recent languages such as Python, Ruby, and Squeak.
Support for Unicode so that source code (program text) is not restricted to those characters contained in the ASCII character set; allowing, for example, use of non-Latin-based scripts or extended punctuation.


Read more!!!

Tuesday, May 13, 2008

Code in C# to Display a text file

/*
C#: The Complete Reference
by Herbert Schildt

Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/

/* Display a text file.

To use this program, specify the name
of the file that you want to see.
For example, to see a file called TEST.CS,
use the following command line.

ShowFile TEST.CS
*/

using System;
using System.IO;

public class ShowFile {
public static void Main(string[] args) {
int i;
FileStream fin;

try {
fin = new FileStream(args[0], FileMode.Open);
}
catch(FileNotFoundException exc) {
Console.WriteLine(exc.Message);
return;
}
catch(IndexOutOfRangeException exc) {
Console.WriteLine(exc.Message + "\nUsage: ShowFile File");
return;
}

// read bytes until EOF is encountered
do {
try {
i = fin.ReadByte();
}
catch(Exception exc) {
Console.WriteLine(exc.Message);
return;
}
if(i != -1)
Console.Write((char) i);
} while(i != -1);

fin.Close();
}
}


Read more!!!