Web Service via Data Access Object Pattern


Access to the data source varies depending on the source of data. Access to persistent storage, such as to a database, varies greatly depending on the type of storage and vendor implementation. The ODBC API enables applications to use SQL statements. However, even within RDBMS environments, the actual syntax and format of SQL statements vary depending on the particular database product. There is even greater variation with different types of persistent storage. Access mechanism, supported APIs, and features vary between different types of persistent storage, such as RDBMS, object-oriented databases, LDAP, flat file, XML file, and so forth. Such disparate data sources make challenges to applications, and can potentially create a direct dependency between the application and the data source code. When business components need to access a data source, they use the appropriate APIs to create connectivity and manipulate the data source. But including the data access code within business components introduces a tight coupling between the business components and the data source implementation. Such code dependencies make it difficult to migrate from one type of data source to another. When the data source changes, the business components have to be changed to handle the new type of data source.


Use the Data Access Object to do all manipulations to the data source object. The DAO manages the connection with the data source to get and store data. The DAO implements all access functionality to work with the data source. It doesn’t matter what the data source is. It could be any persistent storage such as RDBMS, a repository like LDAP, or even just XML files. The business components that rely on DAO use a simple interface exposed by DAO to its clients. The DAO doesn’t show the data source implementation and there is no need to do this. Because the DAO interface doesn’t need to change when the underlying data source changes, this ability allows DAO to adapt to different types of storage without having to handle it within the business component. You can also say that the DAO acts as an adapter between the components and the data source object.

Picture 1. Relationships in the DAO pattern
       ------------------   uses          -------------------   encapsulates    -----------
      |   BusinessObject | ------------> |  DataAccessObject | --------------> | DataSource | 
       ------------------                 -------------------                   ------------
                         \                 /
                          \               /
                           \             /  
obtains, modifies, and      \           / save the transfer object into  
creates the transfer object  \         /  persistent data storage
                              \       /
                               \     /
                                \   /
                                \/ \/
                          |  TransferObject |

Business Object

This object represents the data client. It’s the object that requires access to the data source to obtain and modify the data.

Data Access Object

This object is the underlying object in this pattern. It abstracts the data access implementation for its clients to enable transparent access to the data source. The business object delegates the data creation and stores actions to the data access object.

Data Source

This object represents a data source implementation. It could be any persistent storage, for instance, RDBMS, OODBMS, XML repository, flat file system, and so forth.

Transfer Object

This object represents a data carrier. The data access object uses this object to return the data to the client as well as to receive updates and create the data in the data source.

Sample Project

I provided this sample project with two kinds of DAO: XmlRepository and MSSql. This sample project demonstrates how easy it is to use this pattern. It also shows that any migration from one data source to another is a piece of cake.

Screenshot - Diagram.jpg

As you can see, I use the abstract factory model. DaoFactory is the abstract class for all DAO factories.

public abstract class DaoFactory 
    public abstract  CustomerDao  GetCustomerDao();
    public abstract  OrderDao   GetOrderDao();
    public static DaoFactory GetDaoFactory()
        string strDaoFactoryType = ConfigurationManager.AppSettings["DaoFactory"];
        if (String.IsNullOrEmpty(strDaoFactoryType))
            throw new NullReferenceException("DaoFactory type configuration " + 
                                             "is missing from your web.config.");

            Type DaoFactoryType = Type.GetType(strDaoFactoryType);
            if (DaoFactoryType == null)
                throw new NullReferenceException("DaoFactory type can not be found.");

            Type DaoFactoryBaseType = 
            if (!DaoFactoryBaseType.IsAssignableFrom(DaoFactoryType))
                throw new ArgumentException("DaoFactory type does not inherits " + 
                          "from AndrewGolik.DaoTraining.DataAccessLayer.DaoFactory.");

            DaoFactory daoFactory = (DaoFactory)Activator.CreateInstance(DaoFactoryType);
            return daoFactory;

The implementation of MSSqlDaoFactory:

public class MSSqlDaoFactory:DaoFactory
    public static string ConnectionString
            if (ConfigurationManager.ConnectionStrings["MsSqlDao"] == null)
                throw new NullReferenceException("MsSqlDao connectionString " + 
                          "configuration is missing from your web.config.");
            string connectionString = 
            if (String.IsNullOrEmpty(connectionString))
                throw new NullReferenceException("MsSqlDao connectionString " + 
                          "configuration is missing from your web.config.");
                return connectionString;
    public override CustomerDao GetCustomerDao() 
       return new MSSqlCustomerDao();
    public override OrderDao GetOrderDao() 
        return new MSSqlOrderDao();

The implementation for XmlDaoFactory is the same, except specific changes. XmlDaoFactory doesn’t have the connection string, but it has paths to XML files.

public class XmlDaoFactory:DaoFactory
    public static string PathToCustomersFile
         string pathToFile = HttpContext.Current.Server.MapPath(
         if (!File.Exists(pathToFile))
             XmlDocument xmlDoc = new XmlDocument();
             xmlDoc.LoadXml("<customers lastgeneratedid="\"0\"">");
         return pathToFile;
    public static string PathToOrdersFile 
            string pathToFile = HttpContext.Current.Server.MapPath(
            if (!File.Exists(pathToFile))
                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.LoadXml("<orders lastgeneratedid="\"0\"">");
            return pathToFile;
    public override  CustomerDao  GetCustomerDao()
         return new XmlCustomerDao();
    public override OrderDao GetOrderDao() 
        return new XmlOrderDao();

There are only two business objects in this project: Customer and Order. So we need to have two interfaces: CustomerDao and OrderDao.

public interface OrderDao
    int CreateOrder(Order order);
    bool DeleteOrder(int orderID);
    bool UpdateOrder(Order order);
    List<order> GetOrders();

public interface CustomerDao
     int CreateCustomer(Customer customer);
     bool DeleteCustomer(int customerID);
     bool UpdateCustomer(Customer customer);
     List<customer> GetCustomers();
     bool DeleteOrders(int customerID);

These interfaces describe the base data access functionality for all DAO implementations. Once you add a new interface method, you have to modify all DAO implementations of the interface.

The implementation of OrderDao:

public class MSSqlOrderDao:OrderDao
    public int CreateOrder(Order order)
        //using the Transact-SQL 
        //return the order id on success  
    public bool DeleteOrder(int orderID) 
       //using the Transact-SQL 
       //return the true if the order is removed, otherwise false
    public bool UpdateOrder(Order order) 
       //using the Transact-SQL 
       //return the true if the order is removed, otherwise false

    public List<order> GetOrders() 
       //using the Transact-SQL 
       //return the list of orders

The implementation of XmlOrderDao is specific because it uses XML files to store the data.

The transfer objects are used by DAO to send and receive data from the data client.

public class Customer
    private const int defaultIDValue = 0; 
    private int _customerID;
     private string _companyName; 
    private string _contactName; 
    private string _contactTitle; 
    private string _address; 
    private string _city;  
    private string _region; 
    private string _postalCode; 
    private string _country;  
    private string _phone; 
    private string _fax;

    //get and set properties.....
public class Order
    private const int defaultIDValue = 0; 
    private int _orderID;
    private int _customerID;
    private DateTime _orderDate;
    private Decimal  _freight;
    private    string _shipName;
    private string _shipAddress;
    private string _shipCity;
    private string _shipRegion;
    private string _shipPostalCode;
    private string _shipCountry;
    //get and set properties.....

It’s pretty simple to use DAO from the data client.

public bool UpdateCustomer(int customerID ,string companyName, string contactName,
                string contactTitle, string address, string city, string region,
                string postalCode, string country, string phone, string fax)

    Customer customer = new Customer(customerID , companyName, contactName,
                contactTitle, address, city, region,
                 postalCode,  country, phone, fax);

    CustomerDao customerDao = DaoFactory.GetDaoFactory().GetCustomerDao();
    return customerDao.UpdateCustomer(customer);

The Web Service classes in this project act as business objects or data clients. As you can see, the data client hasn’t any understanding what is the data source. The DAO abstracts all manipulations to the data source.

Notes: Currently, in this code, the default DAO is the XML repository as it can work standalone. It will store the XML files locally in the App_Data folder (be sure that the ASPNET user has write permissions on your machine). If you are going to use it with MS SQL, you have to modify the web.config file. You need to comment the XMLDaoFactory code and uncomment the MSSqlDaoFactory code and also specify the connection string to your database as well to execute the SQL script that is in the SqlInstall folder. That is all what you need to migrate from one data source to another.

Download source code – 29.4 KB

Referenced by: http://www.codeproject.com/KB/webservices/Data_Access_Object.aspx

Start Subversion at Boot on Ubuntu

I don’t know if I’ve extolled the virtues of Ubuntu on this blog yet, but they are many. They are, however, not the topic of this post. Every once in a while, I like to try different operating systems on my server, and at the moment, I’m just coming back to an Ubuntu server after a brief fling with Windows Server 2003.

On the list of things to do after install was to get Ubuntu to start the svnserve daemon at boot. I’ve taken the time to look this up enough times that I figured I’d just add it here. This procedure holds for anything you’d like to do at boot, I’m simply running my svn daemon.

Step 1 – Create your script.
Simply create a new file (I called mine svnserve) and type the command you’d like to run

cd /etc/init.d/ # (thanks Alfonso)
sudo touch svnserve
sudo vi svnserve
svnserve -d -r /usr/local/svn/repository_name

Step 2 – Save the script in the /etc/init.d/ folder

Step 3 – Make the script executable
sudo chmod +x svnserve

Step 4 – Add the script to the boot sequence
sudo update-rc.d svnserve defaults

That’s it. When you’re done you should see some output similar to

Adding system startup for /etc/init.d/svnserve ...
/etc/rc0.d/K20svnserve -> ../init.d/svnserve
/etc/rc1.d/K20svnserve -> ../init.d/svnserve
/etc/rc6.d/K20svnserve -> ../init.d/svnserve
/etc/rc2.d/S20svnserve -> ../init.d/svnserve
/etc/rc3.d/S20svnserve -> ../init.d/svnserve
/etc/rc4.d/S20svnserve -> ../init.d/svnserve
/etc/rc5.d/S20svnserve -> ../init.d/svnserve

Install SVN Server in Ubuntu Server


Subversion is an open source version control system. Using Subversion, you can record the history of source files and documents. It manages files and directories over time. A tree of files is placed into a central repository. The repository is much like an ordinary file server, except that it remembers every change ever made to files and directories.


To access Subversion repository using the HTTP protocol, you must install and configure a web server. Apache2 is proven to work with Subversion. Please refer to the HTTP subsection in the Apache2 section to install and configure Apache2. To access the Subversion repository using the HTTPS protocol, you must install and configure a digital certificate in your Apache 2 web server. Please refer to the HTTPS subsection in the Apache2 section to install and configure the digital certificate.

To install Subversion, run the following command from a terminal prompt:

sudo apt-get install subversion libapache2-svn

Server Configuration

This step assumes you have installed above mentioned packages on your system. This section explains how to create a Subversion repository and access the project.

Create Subversion Repository

The Subversion repository can be created using the following command from a terminal prompt:

svnadmin create /path/to/repos/project

Importing Files

Once you create the repository you can import files into the repository. To import a directory, enter the following from a terminal prompt:

svn import /path/to/import/directory file:///path/to/repos/project

Access Methods

Subversion repositories can be accessed (checked out) through many different methods –on local disk, or through various network protocols. A repository location, however, is always a URL. The table describes how different URL schemes map to the available access methods.

Table 14.1. Access Methods

Schema Access Method
file:// direct repository access (on local disk)
http:// Access via WebDAV protocol to Subversion-aware Apache2 web server
https:// Same as http://, but with SSL encryption
svn:// Access via custom protocol to an svnserve server
svn+ssh:// Same as svn://, but through an SSH tunnel

In this section, we will see how to configure Subversion for all these access methods. Here, we cover the basics. For more advanced usage details, refer to the svn book.

Direct repository access (file://)

This is the simplest of all access methods. It does not require any Subversion server process to be running. This access method is used to access Subversion from the same machine. The syntax of the command, entered at a terminal prompt, is as follows:

svn co file:///path/to/repos/project


svn co file://localhost/path/to/repos/project
If you do not specify the hostname, there are three forward slashes (///) — two for the protocol (file, in this case) plus the leading slash in the path. If you specify the hostname, you must use two forward slashes (//).

The repository permissions depend on filesystem permissions. If the user has read/write permission, he can checkout from and commit to the repository.

Access via WebDAV protocol (http://)

To access the Subversion repository via WebDAV protocol, you must configure your Apache 2 web server. You must add the following snippet in your /etc/apache2/apache2.conf file:

 <Location /svn>
  DAV svn
  SVNPath /path/to/repos
  AuthType Basic
  AuthName "Your repository name"
  AuthUserFile /etc/subversion/passwd
  Require valid-user

To import or commit files to your Subversion repository over HTTP, the repository should be owned by the HTTP user. In Ubuntu systems, normally the HTTP user is www-data. To change the ownership of the repository files enter the following command from terminal prompt:

sudo chown -R www-data:www-data /path/to/repos
By changing the ownership of repository as www-data you will not be able to import or commit files into the repository by running svn import file:/// command as any user other than www-data.

Next, you must create the /etc/subversion/passwd file. This file contains user authentication details. To add an entry, i.e. to add a user, you can run the following command from a terminal prompt:

sudo htpasswd -c /etc/subversion/passwd user_name

This command will prompt you to enter the password. Once you enter the password, the user is added. Now, to access the repository you can run the following command:

                      svn co http://servername/svn
The password is transmitted as plain text. If you are worried about password snooping, you are advised to use SSL encryption. For details, please refer next section.

Access via WebDAV protocol with SSL encryption (https://)

Accessing Subversion repository via WebDAV protocol with SSL encryption (https://) is similar to http:// except that you must install and configure the digital certificate in your Apache2 web server.

You can install a digital certificate issued by a signing authority like Verisign. Alternatively, you can install your own self-signed certificate.

This step assumes you have installed and configured a digital certificate in your Apache 2 web server. Now, to access the Subversion repository, please refer to the above section! The access methods are exactly the same, except the protocol. You must use https:// to access the Subversion repository.

Access via custom protocol (svn://)

Once the Subversion repository is created, you can configure the access control. You can edit the /path/to/repos/project/conf/svnserve.conf file to configure the access control. For example, to set up authentication, you can uncomment the following lines in the configuration file:

# [general]
# password-db = passwd

After uncommenting the above lines, you can maintain the user list in the passwd file. So, edit the file passwd in the same directory and add the new user. The syntax is as follows:

username = password

For more details, please refer to the file.

Now, to access Subversion via the svn:// custom protocol, either from the same machine or a different machine, you can run svnserver using svnserve command. The syntax is as follows:

$ svnserve -d --foreground -r /path/to/repos
# -d -- daemon mode
# --foreground -- run in foreground (useful for debugging)
# -r -- root of directory to serve

For more usage details, please refer to:
$ svnserve --help

Once you run this command, Subversion starts listening on default port (3690). To access the project repository, you must run the following command from a terminal prompt:

svn co svn://hostname/project project --username user_name

Based on server configuration, it prompts for password. Once you are authenticated, it checks out the code from Subversion repository. To synchronize the project repository with the local copy, you can run the update sub-command. The syntax of the command, entered at a terminal prompt, is as follows:

cd project_dir ; svn update

For more details about using each Subversion sub-command, you can refer to the manual. For example, to learn more about the co (checkout) command, please run the following command from a terminal prompt:

                      svn co help

Access via custom protocol with SSL encryption (svn+ssh://)

The configuration and server process is same as in the svn:// method. For details, please refer to the above section. This step assumes you have followed the above step and started the Subversion server using svnserve command.

It is also assumed that the ssh server is running on that machine and that it is allowing incoming connections. To confirm, please try to login to that machine using ssh. If you can login, everything is perfect. If you cannot login, please address it before continuing further.

The svn+ssh:// protocol is used to access the Subversion repository using SSL encryption. The data transfer is encrypted using this method. To access the project repository (for example with a checkout), you must use the following command syntax:

svn co svn+ssh://hostname/var/svn/repos/project
You must use the full path (/path/to/repos/project) to access the Subversion repository using this access method.

Based on server configuration, it prompts for password. You must enter the password you use to login via ssh. Once you are authenticated, it checks out the code from the Subversion repository.

How to install/Enable System restore on Win server 2003

System Restore’s purpose is to return your system to a workable state without requiring a complete reinstallation and without compromising your data files. The utility runs in the background and automatically creates a restore point when a trigger event occurs. Trigger events include application installations, AutoUpdate installations, Microsoft Backup Utility recoveries, unsigned- driver installations, and manual creations of restore points. The utility also creates restore points once a day by default.Currently system restore available in Windows XP/Vista this tutorial will show you how to install/enable system restore on win server 2003.
Solution 1

Note:- Take a complete backup of your registry before doing any changes

In this procedure you need to download Add System Restore from here

Extract the zip file into a folder, in this you will see two files – AddSystemRestoreEntries.reg and sr.inf

Double click on AddSystemRestoreEntries.reg and click on Yes when prompted.

Insert your Windows XP CD and Right click on sr.inf and select Install.

Point to the /i386 directory on the CD if prompted.

Reboot your win server 2003 that’s it now you are ready for your new win server 2003 feature

System restore screen

System restore tab

Solution 2

start we need a WinXP installation CD (doesn’t matter is Home Edition or Professional). In XP system restore is installed in syssetup.inf under the inf.always section. If you have XP installed, you can open up %windir%\inf\syssetup.inf and search for “[Infs.Always]“: you’ll see the section XP looks at for installing system components. You’ll notice it has sr.inf, this is the inf for system restore. For Windows 2003, if you look at syssetup.inf you won’t find sr.inf. This doesn’t mean system restore won’t work in server 2003.

Copy sr.inf file from your xp machine in to your win server 2003.Now we have to right click on sr.inf and select “Install”, to install it on Windows 2003. If you have XP installed on another machine/partition you can simply right click on it; if you don’t, extract \i386\sr.in_ from the XP CD to a folder of your choice, then right clink on it and select “Install”. It will ask you where the files are, so point to the XP CD. When done you’ll be prompted to restart the system.

After restarting the system you’ll get an error saying that the service could not start, specifically this is error 1068: this means it cannot run under the service is on. If you look at it in services.msc console, the path of the executable will be “C:\WINDOWS\system32\svchost.exe -k netsvcs”. This got me thinking so I opened up sr.inf, and found this line:
HKLM,”Software\Microsoft\Windows NT\CurrentVersion\SvcHost”,”SRGroup”

So it seems the sr.inf doesn’t register system restore to run under the network services group. Using the above registry key as an example, I opened regedit and went to:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\SvcHost. On the right side I saw netsvcs. I double clicked on it, but could not find SRService (this is the name for system restore).

at the bottom I added SRService, rebooted, and this time got no error on startup. I opened up rstrui.exe, and System Restore opened fine. I also had a System Restore tab in System Properties now, too. I was able to make a restore point fine, then restore the computer to it without any problems. So in the above registry key double click on netsvcs, and at the bottom of the list type in SRService (not sure if this is case sensitive or not).

I would personally prefer solution 1 because this is very easy and simple .

Configuring Subversion with Active Directory Authentication

Subversion with AD Auth is the holy-grail for main Microsoft-based organizations.  However, the setup can be a bit tricky and there aren’t a lot of good walk-throughs out there.  This post guides you through the process of installing Subversion and configuring AD authentication on a Windows 2003 server.

This post is NOT specific to Sublime – it applies to any Subversion installation using Apache.

Getting Ready

Before we start, you’ll need to make sure you have all required software installed.  You will need Subversion 1.5 or greater and Apache installed.  I recommend downloading the Collabnet Subversion Client and Server package for windows.  Not only does it include all prerequisites for this walk-through, but the installer sets up Apache to run as a windows service for you.

Configuring Apache

Once you have Subversion and Apahce installed, you’ll need to configure Apache to work with Subversion.  However, the first step is to ensure Apache will start on its own with no configuration changes.

  1. Open your Services management console
  2. Locate the Apache service (Apache2.2 for example)
  3. Start the service.  If there is a problem, you will get a warning or error message.

One common error on a new installation is when Apache conflicts with IIS.  If you see an error message about no listening sockets available, that probably means that IIS is already running a website on the default port 80.  You can either change Apache to run on a different port (by editing the httpd.conf file), or stop the default website in IIS.

Once you have Apache running on its own, it’s time to configure Subversion.

  1. Open the httpd.conf file (mine is located at C:\Program Files\CollabNet Subversion Server\httpd\conf\httpd.conf).
  2. Locate the Dynamic Shared Object (DSO) Support section.  This should have a bunch of lines that begin with “LoadModule …”
  3. At the bottom of the existing LoadModule lines, add the following three lines:LoadModule ldap_module   modules/mod_ldap.so
    LoadModule authnz_ldap_module   modules/mod_authnz_ldap.so
    LoadModule authz_svn_module   modules/mod_authz_svn.so
  4. Next locate the <Location> tag for the path where your repositories will be accessible from.  By default with the Collabnet install this will be /svn.  In that case you would look for <Location /svn>.  If you configured a different path, just substitute /svn for the path you configured.  It should look something like this: <Location /svn>
    DAV svn
    SVNParentPath C:/svn_repository
    The SVNParentPath should be the full path to the directory where you will store your repositories.  In this case, all repositories will be located at C:\svn_repository\<my_repo>.
  5. Add the following settings to this Location tag:SVNListParentPath On
    Set this to On if you are hosting multiple repositories and want Apache to display a list of repositories.AuthzSVNAccessFile C:/svn_repository/access.txt
    This is the full path to the file which will control access (we’ll create that next)

    AuthzLDAPAuthoritative off
    If on, this prevents another auth provider from handling authentication if ldap authentication fails.

    AuthType Basic
    Specifies basic auth.  You can change this to Digest or a different auth type if you like.

    AuthBasicProvider ldap
    Specifies that the LDAP provider will be used for authentication.

    AuthName "your.domain"
    This specifies the realm for authentication.  For simplicity, just set this to the fully qualified name of your domain.

    AuthLDAPBindDN "CN=SomeAccount,CN=Users,DC=your,DC=domain"
    This needs to be the fully qualified account name of an account that has read access to your domain.

    AuthLDAPBindPassword "password"
    This should be the password for the account specified in AuthLDAPBindDN.

    AuthLDAPURL "ldap://your.domain/DC=your,DC=domain?sAMAccountName?sub?(objectClass=*)"
    This will be used to locate users in your domain.  Everything to the left of the first question mark should be the ldap path where your users are located.  To the right of the first question mark is the user property that will be used as the username.  Typically you will use “sAMAccountName”, but if you wanted to have users use their email address as their username, you could use “mail” instead.  Leave the rest of the path unchanged.

    Require valid-user
    Specifies that a valid user account is required.

  6. Once you are done, the entire <Location / svn> section should look like this:<Location /svn>
    DAV svn
    SVNParentPath C:/svn_repository
    SVNListParentPath On
    AuthzSVNAccessFile C:/svn_repository/access.txt
    AuthzLDAPAuthoritative off
    AuthType Basic
    AuthBasicProvider ldap
    AuthName "your.domain"
    AuthLDAPBindDN "CN=account,CN=Users,DC=your,DC=domain"
    AuthLDAPBindPassword "password"
    AuthLDAPURL "ldap://your.domain/DC=your,DC=domain?sAMAccountName?sub?(objectClass=*)"
    Require valid-user
  7. Next, restart the Apache service in your Services management console.  If you get an error, check the event log and double check the settings above.  If you don’t receive any errors, move on to the next section.

Setting up Access

The final step is to set up access for your repositories. Create a new file called “access.txt” where your repositories are located. This file should be at the same path you specified for the AuthzSVNAccessFile setting in the httpd.conf file. It doesn’t have to be where your repositories are located, it can be anywhere.

For each repository, create an entry like the following:

user1 = rw
user2 = rw
user3 = r

I won’t go into the format of this file because you can find extensive documentation in the Subversion Book. However, the important thing to understand is that the username you use will be based on property specified in the AuthLDAPURL setting in your httpd.conf. For example, if you specified sAMAccountName, you will enter the account name (without the domain portion). If you specified mail, you would enter the email address.

Save the access.txt file.

That’s it. You can now try checking out a repository by running the following command:

svn co http://localhost/svn/myrepo

Referenced by: