Saturday, September 27, 2008

Implementing a Database Factory Pattern in C# ASP .NET

Introduction

Designing a C# ASP .NET web application which utilizes a database is a common and straight-forward task for developers. The web application accesses various tables, stored procedures, executes SQL script, and retrieves records. Often, developers not familiar with design patterns will use a simple design for making database calls, which relies on calling database functions straight from the user interface. While this certainly works (and provided you close and dispose of all connections when you're done with them), you achieve a far greater amount of flexibility with your C# ASP .NET web application be using a well-defined and loosely-coupled database layer.

Why Do I Need a Database Layer Anyway?

When creating software for clients, even the beginner developer recognizes the frequency of change. Requirements change, user interface pieces change, platforms change, and databases changes. Determining ways to minimize re-work in your web applications becomes a very important task and by adding a distinct database layer to your C# ASP .NET application, you can greatly increase its flexibility and adaptability to change.

In addition to adaptability, a database layer can also provide an on-the-fly means of changing connections strings and even the database type itself. By changing just a few lines in your C# ASP .NET web.config file, you can effectively change the type of database accessed by your application from MSSQL to Oracle to MySQL - all without a single change to the application code.

The Simple Method

Many developers begin by coding the user interface of a web application, as this helps move the project visually. Because of this, it's not surprising that database code for populating the fields is often mixed directly in. In a C# ASP .NET application, this is similar to adding calls to SQLConnection in your Page_Load() function, as shown below.

using System.Data.SqlClient;

protected void Page_Load(object sender, EventArgs e)
{
using (SqlConnection MyConnection = new SqlConnection(MyConnectionString))
{
using (SqlCommand MyCommand = new SqlCommand("SELECT * FROM Flowers", MyConnection))
{
using (SqlDataReader MyReader = MyCommand.ExecuteReader())
{
// read flowers and process ...
}
}
}

}

Notice in the above code, we're referencing System.Data.SqlClient directly in the user interface code. We're also making calls to the database. A program will run just fine with this method. However, managing this code becomes a problem.

The core problem with the above code is not only that business logic may be mixed in with the user interface code (business logic would appear inside the "read database information" section), but that including database accessibility logic complicates the readability of the program. Furthermore, what happens when you need to change from using the SqlClient to using ODBC? You could change the "using" statement and rename the lines from SqlConnection to OdbcConnection throughout your code, but this may waste time and is also prone to errors.

A much more clear picture of this application could be made by leaving only user interface code inside the Page_Load() function. Defer the decision on what type of database to use and instead concentrate on user interface code. Any calls to database routines would be handled by a call to a separate layer, as follows:

using MyStuff.Managers;

protected void Page_Load(object sender, EventArgs e)
{
Flowers = CommonManager.GetFlowers();
}

Notice in the above code, the database functionality has been minimized to just a single line. The details of the database logic are abstracted away in a database layer. This greatly simplifies reading and managing the code. Now that you can see the initial benefits to utilizing a database layer in your C# ASP .NET web application, let's move on to implementing it.

Putting the Web.Config to Good Use

Before defining the actual database factory classes, we can use the C# ASP .NET web application's web.config file to hold some important data about how our database factory will be used. We will be storing information such as the type of database provider (MSSQL, Oracle, MySQL), a list of possible connection strings, as well as which connection string to use. By storing this information in the web.config file, we provide the flexibility to change the database provider or connection string in real-time, without changing code in the application.

Our web.config file will look similar to the following:








In the above web.config file, we have two connection strings defined. One is for an Oracle database and another for an MSSQL database. You could have any number of connection strings. Our database factory design uses its own web.config section, defined in DatabaseFactoryConfiguration. This allows us to tell the database factory which provider class to instantiate (Oracle, MSSQL, etc) and which connection string to use. You can see the flexibility this adds, by allowing us to change any of these parts right in the web.config file.

The DatabaseFactory Web.Config Handler

Since we've added our own custom section to the web.config file for the database factory, we need to create a web.config custom section handler. The section handler is defined as follows:

using System.Configuration;

public sealed class DatabaseFactorySectionHandler : ConfigurationSection
{
[ConfigurationProperty("Name")]
public string Name
{
get { return (string)base["Name"]; }
}

[ConfigurationProperty("ConnectionStringName")]
public string ConnectionStringName
{
get { return (string)base["ConnectionStringName"]; }
}

public string ConnectionString
{
get
{
try
{
return ConfigurationManager.ConnectionStrings[ConnectionStringName].ConnectionString;
}
catch (Exception excep)
{
throw new Exception("Connection string " + ConnectionStringName + " was not found in web.config. " + excep.Message);
}
}
}
}

The only important part to note about the section handler is that it derives from the ConfigurationSection base class. When this class is instantiated, it will automatically read the line from the web.config file and populate with the values. Since we include a ConnectionString property, it will also fetch the correct connection string, so that we never have to access the ConfigurationManager.ConnectionStrings property ourselves.

It All Starts With a Database

The first part to creating a database factory design pattern is to implement your generic Database object. This is the object you will reference when calling database routines. Since this object is generic, you don't have to decide what type of physical database to actually use with it. This gives you the power to change database providers without changing any of your code. The database object is designed as follows:

using System.Data;

public abstract class Database
{
public string connectionString;

#region Abstract Functions

public abstract IDbConnection CreateConnection();
public abstract IDbCommand CreateCommand();
public abstract IDbConnection CreateOpenConnection();
public abstract IDbCommand CreateCommand(string commandText, IDbConnection connection);
public abstract IDbCommand CreateStoredProcCommand(string procName, IDbConnection connection);
public abstract IDataParameter CreateParameter(string parameterName, object parameterValue);

#endregion
}

It's important to note that we're using .NET's own abstract database factory interfaces. The interfaces can be used in exactly the same way as the concrete database classes (SqlConnection, OdbcCommand, etc), without forcing you to bind to one. This is the core piece to providing flexibility to your database layer.

The Powerful Database Factory

With the details out of the way, we can move on to the power behind the database factory design pattern, which of course, is the factory class itself. The database factory is the class we will use to instantiate the concrete provider for our generic Database class. Remember, we defined an abstract Database class which we can use without deciding on a concrete database provider. Instead, we specify the concrete provider in the web.config and let the database factory design pattern instantiate it. Note, the database factory is able to instantiate any type of concrete database by using C# .NET reflection.

The database factory is defined as follows:

using System.Reflection;
using System.Configuration;

public sealed class DatabaseFactory
{
public static DatabaseFactorySectionHandler sectionHandler = (DatabaseFactorySectionHandler)ConfigurationManager.GetSection("DatabaseFactoryConfiguration");

private DatabaseFactory() { }

public static Database CreateDatabase()
{
// Verify a DatabaseFactoryConfiguration line exists in the web.config.
if (sectionHandler.Name.Length == 0)
{
throw new Exception("Database name not defined in DatabaseFactoryConfiguration section of web.config.");
}

try
{
// Find the class
Type database = Type.GetType(sectionHandler.Name);

// Get it's constructor
ConstructorInfo constructor = database.GetConstructor(new Type[] { });

// Invoke it's constructor, which returns an instance.
Database createdObject = (Database)constructor.Invoke(null);

// Initialize the connection string property for the database.
createdObject.connectionString = sectionHandler.ConnectionString;

// Pass back the instance as a Database
return createdObject;
}
catch (Exception excep)
{
throw new Exception("Error instantiating database " + sectionHandler.Name + ". " + excep.Message);
}
}
}

It's important to note the use of .NET Reflection in the database factory. While this adds the extensibility and power for our database layer, it also adds a bit of overhead to processing. This overhead can be minimized, as you'll see below, by utilizing a static variable so that the number of times objects are instantiated by the factory is minimized.

Putting the Database Factory to Use

We've now implemented the C# ASP .NET database factory design pattern, using the built-in .NET generic database interfaces. To actually use the database factory, we'll create a data worker class to take care of handling how the database factory and generic database are used.

Our data worker class holds a static instance of the abstract Database class. In its constructor, we instantiate the concrete database (defined in the C# ASP .NET web applicaion's web.config file) by using our database factory design pattern. The data worker is defined as follows:

public class DataWorker
{
private static Database _database = null;

static DataWorker()
{
try
{
_database = DatabaseFactory.CreateDatabase();
}
catch (Exception excep)
{
throw excep;
}
}

public static Database database
{
get { return _database; }
}
}

Notice how, in the above code, there are no references to concrete database providers. Nowhere do we reference MSSQL, Oracle, or other concrete types. Everything is kept generic by using the abstract Database class and leaving the details of the concrete type inside the web.config file for the factory to access.

Now, whenever we create a manager class to perform business logic related to the database, we simply inherit from DataWorker. This gives the class instant access to the database routines. For example, we can now create a manager class as follows:

class MyDatabaseLogic : DataWorker
{
public void LoadFlowers()
{
using (IDbConnection connection = database.CreateOpenConnection())
{
using (IDbCommand command = database.CreateCommand("SELECT * FROM FLOWERS", connection))
{
using (IDataReader reader = command.ExecuteReader())
{
// read flowers and process ...
}
}
}
}
}

How About a Concrete Database Class?

Up until this point, we've created abstract and generic classes which defer the decision on which database type to actually use. Now, it's time to create a concrete implementation of the abstract Database object. You will create a concrete Database class for the type of database you plan on using (or may use in the future). If you end up needing to change the database provider, you can change the web.config to use a different concrete implementation.

For this example, we'll define an Oracle Database class as follows:

using Oracle.DataAccess.Client;

public class OracleDatabase : Database
{
public override IDbConnection CreateConnection()
{
return new OracleConnection(connectionString);
}

public override IDbCommand CreateCommand()
{
return new OracleCommand();
}

public override IDbConnection CreateOpenConnection()
{
OracleConnection connection = (OracleConnection)CreateConnection();
connection.Open();

return connection;
}

public override IDbCommand CreateCommand(string commandText, IDbConnection connection)
{
OracleCommand command = (OracleCommand)CreateCommand();

command.CommandText = commandText;
command.Connection = (OracleConnection)connection;
command.CommandType = CommandType.Text;

return command;
}

public override IDbCommand CreateStoredProcCommand(string procName, IDbConnection connection)
{
OracleCommand command = (OracleCommand)CreateCommand();

command.CommandText = procName;
command.Connection = (OracleConnection)connection;
command.CommandType = CommandType.StoredProcedure;

return command;
}

public override IDataParameter CreateParameter(string parameterName, object parameterValue)
{
return new OracleParameter(parameterName, parameterValue);
}

As you can see in the above code, we fill out the body for each abstract function defined in the Database class. You can customize the abstract and concrete classes further to perform more functionality.

Putting It All Together

Now that our C# ASP .NET database layer is complete, we can use the layer to refactor our original "Simple" database access code listed above. An example is shown below which replaces our Page_Load() database code with usage of our Manager class (which, in turn, uses the Database and factory classes).

class FlowerManager : DataWorker
{
public static void GetFlowers()
{
using (IDbConnection connection = database.CreateOpenConnection())
{
using (IDbCommand command = database.CreateCommand("SELECT * FROM FLOWERS", connection))
{
using (IDataReader reader = command.ExecuteReader())
{
// ...
}
}
}
}
}

protected void Page_Load(object sender, EventArgs e)
{
Flowers = FlowerManager.GetFlowers();

// Populate the flowers in a C# ASP .NET droplist control.
MyDropListControl.DataSource = Flowers;
MyDropListControl.DataBind();
}

Conclusion

The database layer is a powerful addition to the C# ASP .NET web application. It provides advanced extensibility, flexibility, and adaptation to change. By implementing the database layer with a database factory design pattern, we can add enhanced power to our architecture and better anticipate changes in database platforms and connections. Separating database code from application level code is a key method for providing better readability and maintenance of code in C# ASP .NET.

About the Author

This article was written by Kory Becker, founder and chief developer of Primary Objects, a software and web application development company. You can contact Primary Objects regarding your software development needs at http://www.primaryobjects.com

resource from http://www.primaryobjects.com


Read more!!!

Friday, September 19, 2008

Google Co-Founder Has Genetic Code Linked to Parkinson’s

MOUNTAIN VIEW, Calif. — Sergey Brin, a Google co-founder, said Thursday that he has a gene mutation that increases his likelihood of contracting Parkinson’s disease, a degenerative disorder of the central nervous system that can impair speech, movement and other functions.

Mr. Brin, who made the announcement on a blog, says he does not have the disease and that the exact implications of the discovery are not clear. Studies show that his likelihood of contracting Parkinson’s disease in his lifetime may be 20 percent to 80 percent, Mr. Brin said.

Mr. Brin, whose personal fortune was recently pegged at $15.9 billion by Forbes, ranking him as the 13th richest American, said that he may help provide more money for research into the disease.

Through a Google spokesman, Mr. Brin declined to be interviewed for this article.

Mr. Brin said he learned that he carries a mutation of the LRRK2 gene, known as G2019S. His mother, Eugenia Brin, also carries the gene mutation and has Parkinson’s.

Medical experts said that those who carry that gene mutation are more likely than not to live disease-free.

“Many people with this mutation never develop the disease,” said Dr. Susan B. Bressman, chairwoman of the neurology department at Beth Israel Medical Center in New York. “He is more likely to have a normal life than a Parkinson’s disease life.”

Dr. Bressman, who specializes in movement disorders and genetics, said that about 30 percent of people with the gene mutation develop the disease.

Mr. Brin said he discovered that he carried the gene mutation using a service from 23andMe, a biotechnology start-up co-founded by his wife, Anne Wojcicki. The company can map customers’ DNA and help them find information about their ancestry and their risk of getting certain diseases. Google, where Mr. Brin is president of technology, invested $3.9 million in 23andMe in May 2007.

Parkinson’s disease is typically a late-onset disorder, in which people often first exhibit symptoms in their 50s or 60s. Mr. Brin is 35. Symptoms, which can include tremors, stiffness, slowness of movement and speech impairment, can sometimes be managed through medication and surgery. While many people with the disease continue to function at a high level for many years, the disease is not curable and highly variable. Symptoms tend to become progressively worse over time.

“This leaves me in a rather unique position,” Mr. Brin wrote in his blog post. “I know early in my life something I am substantially predisposed to. I now have the opportunity to adjust my life to reduce those odds (e.g. there is evidence that exercise may be protective against Parkinson’s). I also have the opportunity to perform and support research into this disease long before it may affect me.”

Mr. Brin and his family have already endowed the Eugenia Brin Professorship in Parkinson’s Disease and Movement Disorders at the University of Maryland School of Medicine, where his mother is being treated.

Analysts said they did not believe that the news about Mr. Brin would have a negative impact on Google’s shares.


Read more!!!

Software spots the spin in political speeches

BLINK and you would have missed it. The expression of disgust on former US president Bill Clinton's face during his speech to the Democratic National Convention as he says "Obama" lasts for just a fraction of a second. But to Paul Ekman it was glaringly obvious.

"Given that he probably feels jilted that his wife Hillary didn't get the nomination, I would have to say that the entire speech was actually given very gracefully," says Ekman, who has studied people's facial expressions and how they relate to what they are thinking for over 40 years.

It seems that Clinton's micro-expression gave away more about his true feelings than he intended. Politicians do not usually give themselves away so tellingly, and many of us would like to know whether they mean what they are saying. So how are we to know when they are lying?

Technology is here to help. Software programs that analyse a person's speech, voice or facial expressions are building upon the work of researchers like Ekman to help us discover when the truth is being stretched, and even by how much. "The important thing to recognise is that politicians aren't typically good at out-and-out lies, but they are very adept at dancing around the truth," says David Skillicorn, a mathematics and computer science researcher at Queen's University in Kingston, Ontario, Canada. "The 2008 election has so far given us plenty of chances to see them in action."

Skillicorn has been watching out for verbal "spin". He has developed an algorithm that evaluates word usage within the text of a conversation or speech to determine when a person "presents themselves or their content in a way that does not necessarily reflect what they know to be true".

The algorithm counts usage of first person nouns - "I" tends to indicate less spin than "we", for example. It also searches out phrases that offer qualifications or clarifications of more general statements, since speeches that contain few such amendments tend to be high on spin. Finally, increased rates of action verbs such as "go" and "going", and negatively charged words, such as "hate" and "enemy", also indicate greater levels of spin. Skillicorn had his software tackle a database of 150 speeches from politicians involved in the 2008 US election race (see diagram).

When he analysed the speeches of John McCain, Barack Obama and Hillary Clinton, he found that even though the speeches were rehearsed, written by professionals and delivered by trained speakers, there were discernable differences between them. "It's clear that the speeches are still highly individualised," says Skillicorn. "This makes sense as the speeches have to, in some manner, reflect the speaker's own voice and opinions. Otherwise, they wouldn't be able to deliver them convincingly."

Additionally, he says, little details count: pronouns such as "we" and "I" are often substituted subconsciously, no matter what is written in the script.

Each of the candidates had made speeches containing very high and very low levels of spin, according to Skillicorn's program, depending on the occasion. In general though, Obama's speeches contain considerably higher spin than either McCain or Clinton. For example, for their speeches accepting their party's nomination for president, Obama's speech scored a spin value of 6.7 - where 0 is the average level of spin within all the political speeches analysed, and positive values represent higher spin. In contrast, McCain's speech scored -7.58, while Hillary Clinton's speech at the Democratic National Convention scored 0.15. Skillicorn also found that Sarah Palin's speeches contain slightly more spin than average.

So the analysis appears to back up McCain's claim that he is a "straight talker". However, for the purposes of political speech-making this may not be an entirely good thing for him. "Obama uses spin in his speeches very well," says Skillicorn. For example, Obama's spin level skyrockets when facing problems in the press, such as when Jeremiah Wright, the reverend of his former church, made controversial comments to the press.

"When you see these crises come along, the spin goes up," Skillicorn says. "Obama is very good at using stirring rhetoric to deal with the issues. And it seems to work if you look at what happens in the polls afterwards."

McCain does not seem as adept at using spin to his advantage, and his "straight talk" can make his speeches fall flat from a motivational point of view, according to Branka Zei Pollermann, founder of the Vox Institute in Geneva, Switzerland, who has analysed the candidates' voices for communication consultants Clearwater Advisors, based in London.

"The voice analysis profile for McCain looks very much like someone who is clinically depressed," says Pollermann, a psychologist who uses voice analysis software in her work with patients. Previous research on mirror neurons has shown that listening to depressed voices can make others feel depressed themselves, she says.
"John McCain's voice analysis profile looks like that of someone who is clinically depressed"

Pollermann uses auditory analysis software to map seven parameters of a person's speech, including pitch modulation, volume and fluency, to create a voice profile. She then compares that profile with the speaker's facial expressions, using as a guide a set of facial expressions mapped out by Ekman, called the Facial Action Coding System, to develop an overall picture of how they express themselves.

Her analysis shows that McCain's voice changes little in pitch as he speaks, and so conveys very little emotion or impact. Whether he is addressing positive prospects or discussing sad facts, his voice always sounds the same.

Additionally, McCain's voice and facial movements often do not match up, says Pollermann, and he often smiles in a manner that commonly conveys sarcasm when addressing controversial statements. "That might lead to what I would call a lack of credibility."

People are unlikely to trust statements made in a flat tone, particularly when they do not match the person's facial expressions. According to Pollermann's analysis, it may not make any difference that McCain does not pepper his speeches with spin, if the way he talks does not strike people as believable.

Obama, by comparison, speaks with greater pitch modulation, and his facial expressions correlate very well with what he is saying. His one facial foible may be a tendency to furrow his brow, she says, conveying constant concern. This is similar to the UK prime minister Gordon Brown, whose expressions tend to be limited to sadness, anger and disgust, according to the Vox Institute's analysis. But Obama's fluency, high speech rate and good use of pitch make him a dynamic speaker.

So what does all of this actually say about the honesty of politicians? "Our society treats political candidates like used-car salesmen," Ekman says. "The fact is that the candidates almost certainly believe what they are saying, even if they are giving some facts a much lighter treatment than others. In that way, actually catching someone in a blatant lie is relatively rare."

Indeed, Bill Clinton's fleeting facial slip was the only clear example that Ekman could recount of a politician saying something that they did not mean during both the Republican and Democratic national conventions.

However, facial recognition technology may one day be able to pick up on telltale signs that humans would have trouble spotting. For example, Yoshimasa Ohmoto and colleagues at the University of Tokyo in Japan are developing a facial recognition system for robots and artificial intelligence agents that analyses basic eye, nose and mouth movements, such as a slightly averted gaze when talking to someone, to detect if a person is telling a lie. In trials in which people played the bluffing game Indian poker, the system has already proved to be as reliable as humans trained to detect lies (AI & Society, vol 23, p 187).

"Technology is quickly catching up with psychology," says Pawan Sinha, who leads a team at the Massachusetts Institute of Technology that specialises in computerised facial-recognition technology. "It's not quite there yet, because the visualisation systems just can't work fast enough to replace the human eye and mind. But computer processing is getting faster and our recognition systems are getting better," he says. "Someday soon, computers may be able read us better than any psychologist. I imagine that will be a pretty scary day for politicians."


Read more!!!