Wednesday, April 29, 2015

3 Layer architecture with program and website

I recommend you install Sql Service and attach the database to the sql server and access it that way. That would solve all your problems immediately.

If that is no option and all of your code is running in the same process then you should setup some type of sharing mechanism using locks because the file can only be open by one thread or process at a time. Here is a rough example:

using System.Threading;
using System.Data.SqlClient;
using System;

public class DatabaseHelper : IDisposable
{
   private static object lockObj = new Object();

   public SqlConnection GetConnection()
   {
      Monitor.Enter(lockObj); // this will block until it aquires a lock. There are plenty of overloads for this method
      return new SqlConnection("yourConnectionString or app.config/web.config connection string name");
   }

   public void Dispose()
   {
      Monitor.Exit(lockObj);
   }
}


public class someClientclass
{
   public void SomeMethod()
   {
      var dbHelper = new DatabaseHelper();
      var connection = dbHelper.GetConnection();
      try{
         // do stuff with your connection
      }
      finally{
         connection.Dispose(); // order is important here
         dbHelper.Dispose();
      }
   }
}


Mark as answer or vote as helpful if you find it useful | Igor

No comments:

Post a Comment