Codoxide Library | Updates and New Home

by Sameera 15. November 2008 21:08

I have made several updates to the Codoxide.Common Library and moved the project over to SourceForge.net.

The project's new home is codoxidelib.sourceforge.net and the new SVN repository is https://codoxidelib.svn.sourceforge.net/svnroot/codoxidelib/trunk

Codoxide.Common Library Version 0.0.1 (Concept Phase): Database Wrapper, Basic Design Patterns, Configuration Handlers

by Sameera 20. October 2008 11:18

Today I'm so excited to announce the first release of the Codoxide.Common Library. High Five! I haven't been over ambitious about the version numbering as I want you to treat this library to still be in concept stage.   Codoxide.Common Library Released

Unfortunately, this release had taken longer than expected cos of my newly cramped up schedule. Worst part of that is I'm posting this code without proper documentation (yep, excuses!). Nevertheless, there's plenty of code in here to prove useful to many. So here goes!

Features/Components

Patterns

  • SharedInstance<T>
  • Singleton<T>
  • Factory e.g. Factory.Build<T>()

Configuration

  • ConfigurationManager<T>
  • ConfigurationSectionBase

Data

  • Database<CONNECTION_TYPE, COMMAND_TYPE, ADAPTER_TYPE>
  • Map<T>

 

SharedInstance<T>

SharedInstance is actually the most basic type of generic Singleton implementation that's been around in the C# community. This implementation was both simple and efficient. But, it violated the definition of a Singleton by depending on the presence of a public constructor and thereby allowing additional instances to be created. Therefore, I have refrained from calling this a Singleton resorted to the term SharedInstance.

E.g:


SharedInstance<User>.Instance.Login("admin", "password");

User employee1 = new User();
employee1.Username = "emp001";
employee1.Password = "pass001";
employee1.Save();

Singleton<T>

More advanced implementation of the generic Singleton implementation. Uses reflection, custom attributes and "lazy initialization" to provide a powerful way to create and initialize your singletons.

E.g:


public class UserPreferences : IXmlSerializable, ISupportLazyInitialization
{
    ..

    public virtual void Initialize()
    {
        try
        {
            string location = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\Codoxide\\preference.xml";
            if (File.Exists(location))
                using (XmlReader reader = XmlReader.Create(location))
                {
                    reader.ReadToFollowing("Preferences");
                    this.ReadXml(reader);
                    reader.ReadEndElement();
                }
        }
        catch (Exception ex)
        {
            throw new InvalidConfigurationException("Exception occurred while loading the preferences from disk", ex);
        }
    }
    ..
}

...

Console.WriteLine(Singleton<UserPreferences>.Instance.BackgroundColor);

Factory.Build<T>

This one's another powerful and unique implementation. Coolest feature of this class is that you can do something like the following:


using (IDatabase db = Factory.Build<IDatabase>())
{
    ..
}

This allows developers of class libraries to write their code using interfaces or abstract classes, leaving the library users to specify the concrete classes via configuration files.

Grab the Code

There's of course, plenty more to be documented regarding the library. And you can expect the project space to be updated in coming (err..) weeks Wink.

Until then, you can:

Check out the code (using SVN): https://codoxidelib.svn.sourceforge.net/svnroot/codoxidelib/trunk

Browse the project space: http://codoxidelib.sourceforge.net/

Updating the Database Wrapper for C#

by Sameera 19. June 2008 04:52

I have made a few updates for my Generic Database Wrapper class. The update contains a bug fix along with several additional methods for supporting DbParameters.

The new source file can be downloaded here. I have also updated the file linked to the original post.

My Favorite Database Wrapper for C#

by Sameera 7. November 2007 19:28

As a guy who started programming back in the days of DAO, I have nothing but love for ADO.NET. But let's face it, you can still end up writing pretty lousy code with it. Not everybody's fully aware of the best uses of the ADO.NET. One of the most common problems I keep stumbling onto in other peoples code is the poor use of ADO.NET Connection Pooling feature.

Somewhere, down the line Microsoft probably started noticing that their cool new data access model wasn't being fully utilized. The birth of the Microsoft Enterprise Library was probably due to this.

As cool as the Enterprise Library is, I've found it to be an over kill for most of my projects. In fact one of my favorite projects featured on CodeProject, was because Enterprise Library's Offline Application Block was so clunky (and very limited).

Around the same time that I worked on on the SCOAB (Smart Client Offline Application Block), I also wrote a ADO.NET wrapper similar to the Enterprise Library. It pretty much follows the public interface of the Enterprise Library, but it's a very tiny wrapper compared to the enormous DAAB (Data Access Application Block).

You can download the .cs file here: AbstractDatabase.zip (1.88 kb)

This contains a generic abstract base class called AbstractDatabase. You can extend this class to use it with any type of relational database type. If you take a look at my SQLite Membership Provider, you'll find this class derived to be used with SQLite ADO.NET Wrapper. I have simply called that class Database, and it's code looks something like this:


public class Database : AbstractDatabase<SQLiteConnection, SQLiteCommand, SQLiteDataAdapter>
{
    protected override string  GetConnectionString()
    {
        return string.Format(ConfigurationManager.ConnectionStrings["BlogEngine"].ConnectionString,
                            HttpContext.Current.Server.MapPath("~/App_Data"));
    }
}

As you see, the only member you need to override is the GetConnectionString() method. This brings up the question as to why I made this abstract. Why not read the connection string value from the web.config? Well, I've done this because I use this class on both web and desktop projects. And in some cases, especially with WinForms applications, the database is SQLite and resides in the application directory. When that happens, I can always hard code the database file name.

Here's a example of the the Database class's usage (taken from the SQLiteBlogProvier class).


using (Database db = new Database())
    using (DbTransaction txn = db.BeginTransaction())
    {
        DbCommand cmd = db.GetSqlStringCommand("DELETE FROM be_Settings"); // SQLite doesn't support TRUNCATE
        db.ExecuteNonQuery(cmd, txn);

        cmd = db.GetSqlStringCommand(
            "INSERT INTO be_Settings (SettingName, SettingValue) VALUES (@name, @value)");
        db.AddInParameter(cmd, "@name", DbType.String, "");
        db.AddInParameter(cmd, "@value", DbType.String, "");
        foreach (string key in settings.Keys)
        {
            cmd.Parameters[0].Value = key;
            cmd.Parameters[1].Value = settings[key];
            cmd.ExecuteNonQuery();
        }
        txn.Commit();
    }

A quick rundown of the public interface of AbstractDatabase class:


void AddInParameter(System.Data.Common.DbCommand, string, System.Data.DbType, object)
void AddInParameter(System.Data.Common.DbCommand, string, System.Data.DbType, int, object)
DbTransaction BeginTransaction()
void Dispose()
DataSet ExecuteDataSet(System.Data.Common.DbCommand)
int ExecuteNonQuery(System.Data.Common.DbCommand)
ExecuteNonQuery(System.Data.Common.DbCommand, System.Data.Common.DbTransaction)
DbReader ExecuteReader(System.Data.Common.DbCommand)
ExecuteReader(System.Data.Common.DbCommand, System.Data.CommandBehavior)
T ExecuteScalar<T>(System.Data.Common.DbCommand, T)
abstract string GetConnectionString()
DbCommand GetSqlStringCommand(string)
DbCommand GetSqlStringCommand(string, params object[])
DbCommand GetStoredProcedureCommand(string)
Connection { get; }

Update (June 20, 2008): I have updated this class with a minor bug fix and have added support for other parmeter types including Output and InputOuput parameters (Thanks Yordan).

Update (Oct 20, 2008): This wrapper has been updated and made a part of the Codoxide Common Library

About Me

Sameera Perera

Sameera Perera

  • Solutions Architect
  • View Sameera Perera's profile on LinkedIn

Calendar

<<  September 2010  >>
MoTuWeThFrSaSu
303112345
6789101112
13141516171819
20212223242526
27282930123
45678910

View posts in large calendar

Disclaimer

This is a personal blog. The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

© Copyright 2010

All forms of source code published on Codoxide.com are distributed under the Apache License, Version 2.0 unless otherwise stated.
The rest of the content are published under a Creative Commons Attribution 3.0 License.
Creative Commons License