Thursday, February 10, 2011

DbUtils.cs

     //sql connections
        /// Returns the results of a SQL Query in the form of a DataTable
        public static DataTable SQLSelect(SqlCommand cmdSQLQuery)
        {
            //Get connection string
            //string conConnectionString = ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
            string conConnectionString=null;
            SqlConnection SQLDatabaseConnection = new SqlConnection(conConnectionString);
            //Perform Command
            cmdSQLQuery.Connection = SQLDatabaseConnection;
            DataSet dsPageInfo = new DataSet();
            SqlDataAdapter daPageInfo = new SqlDataAdapter(cmdSQLQuery);
            SQLDatabaseConnection.Open();
            daPageInfo.Fill(dsPageInfo);
            SQLDatabaseConnection.Close();
            return dsPageInfo.Tables[0];
        }
        /// Executes a SQL Command
        public static void ExecuteSQLCommand(SqlCommand CommandToExecute)
        {
            //get connection sring
           
            SqlConnection SQLDatabaseConnection = new SqlConnection(conConnectionString);
            //execute command
            CommandToExecute.Connection = SQLDatabaseConnection;
            SQLDatabaseConnection.Open();
            CommandToExecute.ExecuteNonQuery();
            SQLDatabaseConnection.Close();
        }


        //ole db connection
        /// Returns the results of a SQL Query in the form of a DataTable
        public static DataTable SQLSelect(OleDbCommand cmdOleDbCommand)
        {
            OleDbConnection OleDbDatabaseConnection = new OleDbConnection(conConnectionString);
            //Perform Command
            cmdOleDbCommand.Connection = OleDbDatabaseConnection;
            DataSet dsPageInfo = new DataSet();
            OleDbDataAdapter daPageInfo = new OleDbDataAdapter(cmdOleDbCommand);
            OleDbDatabaseConnection.Open();
            daPageInfo.Fill(dsPageInfo);
            OleDbDatabaseConnection.Close();
            return dsPageInfo.Tables[0];
        }

     public static void ExecuteSQLCommand(OleDbCommand CommandToExecute)
        {

          
            OleDbConnection OleDbDatabaseConnection = new OleDbConnection(conConnectionString);
            //execute command
            CommandToExecute.Connection = OleDbDatabaseConnection;
            OleDbDatabaseConnection.Open();
            CommandToExecute.ExecuteNonQuery();
            OleDbDatabaseConnection.Close();
        }

Enumerations

Enums are used to create and group together a list of user defined named constants. Although on the surface the enumerated types in C# and Java seem quite similar there are some significant differences in the implementation of enumerated types in both languages. In Java, enumerated types are a full fledged class which means they are typesafe and can be extended by adding methods, fields or even implementing interfaces. Whereas in C#, an enumerated type is simply syntactic sugar around an integral type (typically an int) meaning they cannot be extended and are not typesafe.
The following code sample highlights the differences between enums in both languages.
C# Code
using System;

public enum DaysOfWeek{
SUNDAY,
MONDAY,
TUESDAY,
WEDNESDAY,
THURSDAY,
FRIDAY,
SATURDAY
}

public class Test{

public static bool isWeekDay(DaysOfWeek day){
return !isWeekEnd(day);
}

public static bool isWeekEnd(DaysOfWeek day){
return (day == DaysOfWeek.SUNDAY || day == DaysOfWeek.SATURDAY);
}

public static void Main(String[] args){

DaysOfWeek sun = DaysOfWeek.SUNDAY;
Console.WriteLine("Is " + sun + " a weekend? " + isWeekEnd(sun));
Console.WriteLine("Is " + sun + " a week day? " + isWeekDay(sun));

/* Example of how C# enums are not type safe */
sun = (DaysOfWeek) 1999;
Console.WriteLine(sun);

}
}

Java Code
enum DaysOfWeek{
SUNDAY,
MONDAY,
TUESDAY,
WEDNESDAY,
THURSDAY,
FRIDAY,
SATURDAY;

public boolean isWeekDay(){
return !isWeekEnd();
}

public boolean isWeekEnd(){
return (this == SUNDAY || this == SATURDAY);
}

}

public class Test{

public static void main(String[] args) throws Exception{

DaysOfWeek sun = DaysOfWeek.SUNDAY;
System.out.println("Is " + sun + " a weekend? " + sun.isWeekEnd());
System.out.println("Is " + sun + " a week day? " + sun.isWeekDay());
}
}

Generics

Both C# and Java provide a mechanism for creating strongly typed data structures without knowing the specific types at compile time. Prior to the existence of the Generics feature set, this capability was achieved by specifying the type of the objects within the data structure as Object then casting to specific types at runtime. This technique had several drawbacks including lack of type safety, poor performance and code bloat.
The following code sample shows how one would calculate the sum of all the integers in a collection using generics and using a collection of Objects so that both approaches can be compared.

C# Code
using System;
using System.Collections;
using System.Collections.Generic;

class Test{

public static Stack GetStackB4Generics(){
Stack s = new Stack();
s.Push(2);
s.Push(4);
s.Push(5);

return s;
}

public static Stack<int> GetStackAfterGenerics(){
Stack<int> s = new Stack<int>();
s.Push(12);
s.Push(14);
s.Push(50);

return s;
}

public static void Main(String[] args){

Stack s1 = GetStackB4Generics();
int sum1 = 0;

while(s1.Count != 0){
sum1 += (int) s1.Pop(); //cast
}

Console.WriteLine("Sum of stack 1 is " + sum1);

Stack<int> s2 = GetStackAfterGenerics();
int sum2 = 0;

while(s2.Count != 0){
sum2 += s2.Pop(); //no cast
}

Console.WriteLine("Sum of stack 2 is " + sum2);
}

}
Java Code
import java.util.*;

class Test{

public static Stack GetStackB4Generics(){
Stack s = new Stack();
s.push(2);
s.push(4);
s.push(5);

return s;
}

public static Stack<Integer> GetStackAfterGenerics(){
Stack<Integer> s = new Stack<Integer>();
s.push(12);
s.push(14);
s.push(50);

return s;
}

public static void main(String[] args){

Stack s1 = GetStackB4Generics();
int sum1 = 0;

while(!s1.empty()){
sum1 += (Integer) s1.pop(); //cast
}

System.out.println("Sum of stack 1 is " + sum1);

Stack<Integer> s2 = GetStackAfterGenerics();
int sum2 = 0;

while(!s2.empty()){
sum2 += s2.pop(); //no cast
}

System.out.println("Sum of stack 2 is " + sum2);
}

}
Although similar in concept to templates in C++, the Generics feature in C# and Java is not implemented similarly. In Java, the generic functionality is implemented using type erasure. Specifically the generic type information is present only at compile time, after which it is erased by the compiler and all the type declarations are replaced with Object. The compiler then automatically inserts casts in the right places. The reason for this approach is that it provides total interoperability between generic code and legacy code that doesn't support generics. The main problem with type erasure is that the generic type information is not available at run time via reflection or run time type identification. Another consequence of this approach is that generic data structures types must always be declared using objects and not primitive types. Thus one must create Stack<Integer> instead of Stack<int> when working integers.
In C#, there is explicit support for generics in the .NET runtime's instruction language (IL). When the generic type is compiled, the generated IL contains place holders for specific types. At runtime, when an initial reference is made to a generic type (e.g. List<int>) the system looks to see if anyone already asked for the type or not. If the type has been previously requested, then the previously generated specific type is returned. If not, the JIT compiler instantiates a new type by replacing the generic type parameters in the IL with the specific type (e.g. replacing List<T> with List<int>). It should be noted that if the requested type is a reference type as opposed to a value type then the generic type parameter is replaced with Object. However there is no casting done internally by the .NET runtime when accessing the type.
In certain cases, one may need create a method that can operate on data structures containing any type as opposed to those that contain a specific type (e.g. a method to print all the objects in a data structure) while still taking advantage of the benefits of strong typing in generics. The mechanism for specifying this in C# is via a feature called generic type inferencing while in Java this is done using wildcard types. The following code samples show how both approaches lead to the same result.
C# Code
using System;
using System.Collections;
using System.Collections.Generic;

class Test{

//Prints the contents of any generic Stack by
//using generic type inference
public static void PrintStackContents<T>(Stack<T> s){
while(s.Count != 0){
Console.WriteLine(s.Pop());
}
}

public static void Main(String[] args){

Stack<int> s2 = new Stack<int>();
s2.Push(4);
s2.Push(5);
s2.Push(6);

PrintStackContents(s2);

Stack<string> s1 = new Stack<string>();
s1.Push("One");
s1.Push("Two");
s1.Push("Three");

PrintStackContents(s1);
}

}
Java Code
import java.util.*;

class Test{

//Prints the contents of any generic Stack by
//specifying wildcard type
public static void PrintStackContents(Stack<?> s){
while(!s.empty()){
System.out.println(s.pop());
}
}

public static void main(String[] args){

Stack <Integer> s2 = new Stack <Integer>();
s2.push(4);
s2.push(5);
s2.push(6);

PrintStackContents(s2);

Stack<String> s1 = new Stack<String>();
s1.push("One");
s1.push("Two");
s1.push("Three");

PrintStackContents(s1);
}

}
Both C# and Java provide mechanisms for specifying constraints on generic types. In C# there are three types of constraints that can be applied to generic types
  1. A derivation constraint indicates to the compiler that the generic type parameter derives from a base type such an interface or a particular base class
  2. A default constructor constraint indicates to the compiler that the generic type parameter exposes a public default constructor
  3. A reference/value type constraint constrains the generic type parameter to be a reference or a value type.
In Java, only the derivation constraint is supported. The following code sample shows how constraints are used in practice.
C# Code
using System;
using System.Collections;
using System.Collections.Generic;

public class Mammal {
public Mammal(){;}

public virtual void Speak(){;}
}

public class Cat : Mammal{
public Cat(){;}

public override void Speak(){
Console.WriteLine("Meow");
}
}

public class Dog : Mammal{
public Dog(){;}

public override void Speak(){
Console.WriteLine("Woof");
}
}


public class MammalHelper<T> where T: Mammal /* derivation constraint */,
new() /* default constructor constraint */{

public static T CreatePet(){
return new T();
}


public static void AnnoyNeighbors(Stack<T> pets){
while(pets.Count != 0){
Mammal m = pets.Pop();
m.Speak();
}
}
}

public class Test{

public static void Main(String[] args){

Stack<Mammal> s2 = new Stack<Mammal>();
s2.Push(MammalHelper<Dog>.CreatePet());
s2.Push(MammalHelper<Cat>.CreatePet());

MammalHelper<Mammal>.AnnoyNeighbors(s2);
}
}

Java Code
import java.util.*;

abstract class Mammal {
public abstract void speak();
}

class Cat extends Mammal{
public void speak(){
System.out.println("Meow");
}
}

class Dog extends Mammal{
public void speak(){
System.out.println("Woof");
}
}

public class Test{

//derivation constraint applied to pets parameter
public static void AnnoyNeighbors(Stack<? extends Mammal> pets){
while(!pets.empty()){
Mammal m = pets.pop();
m.speak();
}
}

public static void main(String[] args){

Stack<Mammal> s2 = new Stack<Mammal>();
s2.push(new Dog());
s2.push(new Cat());

AnnoyNeighbors(s2);
}
}
C# also includes the default operator which returns the default value for a type. The default value for reference types is null, and the default value for value types (such as integers, enum, and structures) is a zero whitewash (filling the structure with zeros). This operator is very useful when combined with generics. The following code sample excercises the functionality of this operator.
C# Code
using System;

public class Test{

public static T GetDefaultForType(){
return default(T); //return default value of type T
}

public static void Main(String[] args){

Console.WriteLine(GetDefaultForType<int>());
Console.WriteLine(GetDefaultForType<string>());
Console.WriteLine(GetDefaultForType<float>());

}
}

for-each Loop

The for-each loop is an iteration construct that is popular in a number of scripting languages (e.g. Perl, PHP, Tcl/Tk), build tools (GNU Make) and function libraries (e.g. for_each in <algorithm> in C++). The for-each loop is a less verbose way to iterate through arrays or classes that implement the the System.Collections.IEnumerable interface in C# or the java.lang.Iterable interface in Java.
In C#, the keywords foreach and in are used when creating the for-each loop while in Java the keyword for and the operator : are used.
C# Code
string[] greek_alphabet = {"alpha", "beta", "gamma", "delta", "epsilon"};

foreach(string str in greek_alphabet)
Console.WriteLine(str + " is a letter of the greek alphabet");

Java Code
String[] greek_alphabet = {"alpha", "beta", "gamma", "delta", "epsilon"};

for(String str : greek_alphabet)
System.out.println(str + " is a letter of the greek alphabet");

Metadata Annotations

Metadata annotations provide a powerful way to extend the capabilities of a programming language and the language runtime. These annotations can be directives that request the runtime to perform certain additional tasks, provide extra information about an item or extend the abilities of a type. Metadata annotations are common in a number of programming environments including Microsoft's COM and the Linux kernel.
C# attributes provide a way to add annotations (i.e. metadata) to a module, type, method, parameter or member variable. Below are descriptions of a few attributes that are intrinsic to .NET and how they are used to extend the capabilities of the C#.
  1. [MethodImpl(MethodImplOptions.Synchronized)]: is used to specify that a access to a method by multiple threads is protected by a lock to prevent concurrent access to the method and is similar to the synchronized in Java.

  2. [Serializable]: is used to mark a class as serializable and is similar to a Java class implementing the Serializable interface.

  3. [FlagsAttribute]: is used to specify that an enum should support bitwise operations. This is particularly important for enumerations where the target can have multiple values.
    C# Code
    //declaration of bit field enumeration
    [Flags]
    enum ProgrammingLanguages{
    C = 1,
    Lisp = 2,
    Basic = 4,
    All = C | Lisp | Basic
    }

    aProgrammer.KnownLanguages = ProgrammingLanguages.Lisp; //set known languages ="Lisp"
    aProgrammer.KnownLanguages |= ProgrammingLanguages.C; //set known languages ="Lisp C"
    aProgrammer.KnownLanguages &= ~ProgrammingLanguages.Lisp; //set known languages ="C"

    if((aProgrammer.KnownLanguages & ProgrammingLanguages.C) > 0){ //if programmer knows C
    //.. do something
    }
  4. [WebMethod]: is used in combination with ASP.NET to specify that a method should be available over the web as a web service automatically. Doing the same in Java involves configuring JAXP, UDDI, and J2EE as well as have to create an Enterprise Java Bean which involves at least two interfaces and one implementation class plus setting up the deployment descriptor. For more information on webservices in C#, examine the Your First C# Web Service page on CodeProject.
It is possible to access the attributes of a module, class, method or field via reflection. This is particularly useful for seeing if a class supports certain behavior at runtime or for extracting metadata about a class for usage by others. Developers can create their own custom attributes by subclassing the System.Attribute class. What follows is an example of using an attribute to provide information about the author of a class then using reflection to access that information.
C# Code
using System;
using System.Reflection;
[AttributeUsage(AttributeTargets.Class)]
public class AuthorInfoAttribute: System.Attribute{

string author;
string email;
string version;


public AuthorInfoAttribute(string author, string email){

this.author = author;
this.email = email;

}


public string Version{


get{
return version;
}

set{
version = value;
}

}


public string Email{


get{
return email;
}

}

public string Author{


get{
return author;
}

}

}



[AuthorInfo("Dare Obasanjo", "kpako@yahoo.com", Version="1.0")]
class HelloWorld{

}



class AttributeTest{

public static void Main(string[] args){

/* Get Type object of HelloWorld class */
Type t = typeof(HelloWorld);

Console.WriteLine("Author Information for " + t);
Console.WriteLine("=================================");

foreach(AuthorInfoAttribute att in t.GetCustomAttributes(typeof(AuthorInfoAttribute), false)){

Console.WriteLine("Author: " + att.Author);
Console.WriteLine("Email: " + att.Email);
Console.WriteLine("Version: " + att.Version);

}//foreach

}//Main

}
Java annotations provide a way to add annotations (i.e. metadata) to an package, type, method, parameter, member or local variable. There are only three built-in annotations provided in the Java language which are listed below.
  1. @Override: is used to specify that a method is intended to override a method in a base class. If the annotated method does not override a method in the base class then an error is issued during compilation.

  2. @Deprecated: is used to indicate that a particular method has been deprecated. If the annotated method is used then a warning is issued during compilation.

  3. @SuppressWarnings: is used to prevent particular warnings from being issued by the compiler. This annotation optionally takes the name of the specific warning to suppress as an argument.
As in C# it is possible to access the annotations on a module, class, method or field via reflection. However a key difference between C# attributes and Java annotations is that one can create meta-annotations (i.e. annotations on annotations) in Java but can not do the same in C#. Developers can create their own custom annotations by creating an annotation type which is similar to an interface except that the keyword @interface is used to define it. What follows is an example of using an attribute to provide information about the author of a class then using reflection to access that information.
Java Code
import java.lang.annotation.*;
import java.lang.reflect.*;

@Documented //we want the annotation to show up in the Javadocs
@Retention(RetentionPolicy.RUNTIME) //we want annotation metadata to be exposed at runtime
@interface AuthorInfo{
String author();
String email();
String version() default "1.0";
}

@AuthorInfo(author="Dare Obasanjo", email="kpako@yahoo.com")
class HelloWorld{

}

public class Test{

public static void main(String[] args) throws Exception{

/* Get Class object of HelloWorld class */
Class c = Class.forName("HelloWorld");
AuthorInfo a = (AuthorInfo) c.getAnnotation(AuthorInfo.class);

System.out.println("Author Information for " + c);
System.out.println("=======================================");
System.out.println("Author: " + a.author());
System.out.println("Email: " + a.email());
System.out.println("Version: " + a.version());

}
}

Calling Base Class Constructors and Constructor Chaining

C# and Java automatically call base class constructors, and both provide a way to call the constructor of the base class with specific parameters. Similarly both languages enforce that the call to the base class constructor occurs before any initializations in the derived constructor which prevents the derived constructor from using members that are yet to be initialized. The C# syntax for calling the base class constructor is reminiscent of the C++ initializer list syntax.
Both languages also provide a way to call a constructor from another which allows one to reduce the amount of code duplication that can occur in constructors. This practice is typically called constructor chaining.
C# Code

using System;

class MyException: Exception
{

private int Id;

public MyException(string message): this(message, null, 100){ }

public MyException(string message, Exception innerException):
this(message, innerException, 100){ }

public MyException(string message, Exception innerException, int id):
base(message, innerException){

this.Id = id;
}

}

Java Code


class MyException extends Exception{

private int Id;


public MyException(String message){

this(message, null, 100);
}

public MyException(String message, Exception innerException){

this(message, innerException, 100);

}

public MyException( String message,Exception innerException, int id){

super(message, innerException);
this.Id = id;

}
}

Variable Length Parameter Lists

In C and C++ it is possible to specify that a function takes a variable number of arguments. This functionality is used extensively in the printf and scanf family of functions. Both C# and Java allow one to define a parameter that indicates that a variable number of arguments are accepted by a method. In C#, the mechanism for specifying that a method accepts a variable number of arguments is by using the params keyword as a qualifier to the last argument to the method which should be an array. In Java, the same effect is achieved by appending the string "..." to the typename of the last argument to the method.
C# Code
using System;

class ParamsTest{

public static void PrintInts(string title, params int[] args){

Console.WriteLine(title + ":");

foreach(int num in args)
Console.WriteLine(num);

}


public static void Main(string[] args){

PrintInts("First Ten Numbers in Fibonacci Sequence", 0, 1, 1, 2, 3, 5, 8, 13, 21, 34);
}

}
Java Code
class Test{

public static void PrintInts(String title, Integer... args){

System.out.println(title + ":");

for(int num : args)
System.out.println(num);

}

public static void main(String[] args){

PrintInts("First Ten Numbers in Fibonacci Sequence", 0, 1, 1, 2, 3, 5, 8, 13, 21, 34);
}

}