Thursday, August 4, 2011

Data Access Layer using DbProviderFactory

 Hi,

This article is basically intended for the beginners or intermediate level of C# developers who loves 3 tier Architecture in their app. This is a wrapper class called DbHelper which can interact with any database , supported by ADO.Net framework.

Name spaces that are used by the various classes in this DbHelper class.
using System;
using System.Configuration;
using System.Data;
using System.Data.Common;
 
 This is mine custom NameSpace. You can replace it with your own. The name space has a class DbHelper which is implementing IDiposible interface , as I prefer using{ } block in my code. Why using, because the open parentheses and closing parentheses includes try - catch and calls dispose automatically. Some private members like DbConnection and DbProviderFactory are declared. Here we are using DbProviderFactory as Data providers with registered factory classes in the .NET Framework include System.Data.Odbc, System.Data.OleDb, System.Data.SqlClient, System.Data.SqlServerCe, and System.Data.OracleClient. For more details on DbProviderFactory have MSDN . Below is the entire code. I know one thing i am missing here is exception handling. Yes its true, as i generally catches exception in business layer or presentation and there I use to log it. Instead of placing try catch in each level, I use a single try-catch at presentation layer , so that I can have entire stack trace.
namespace ARSoftSys.DataAccessWrapper
{
    public sealed class DbHelper : IDisposable
    {
        #region PRIVATE MEMBER VARIABLES


        private static DbConnection _connection;
        private static bool _dispose;
        private static DbProviderFactory _provider;

        #endregion

        ///

        /// contructor, call method to open connection
        ///

        public DbHelper()
        {
            _connection = CreateConnection();
        }

        ///
        /// retrieves connection string from config
        ///

        private static string ConnectionString
        {
            get { return ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString; }
        }

        ///
        /// retrieves provider from connection string
        ///

        private static string ProviderName
        {
            get { return ConfigurationManager.ConnectionStrings["ConnectionString"].ProviderName; }
        }

        #region IDisposable Members

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        #endregion

        ///
        /// Destructor of the class. Calls method close connection that will automatically
        /// closes connection and calls class , dispose method
        ///

        ~DbHelper()
        {
            CloseConnection();
            Dispose();
        }


        // Given a provider name and connection string,
        // create the DbProviderFactory and DbConnection. Returns a DbConnection on success; null on failure.
        private static DbConnection CreateConnection()
        {
            // Assume failure.
            DbConnection connection = null;

            // Create the DbProviderFactory and DbConnection.
            if (ConnectionString != null)
            {
                try
                {
                    _provider = DbProviderFactories.GetFactory(ProviderName);

                    connection = _provider.CreateConnection();
                    connection.ConnectionString = ConnectionString;
                    connection.Open();
                }
                catch (Exception ex)
                {
                    // Set the connection to null if it was created.
                    if (connection != null)
                    {
                        connection = null;
                    }
                    Common.LogError(ex);
                }
            }
            else
            {
                throw new NullReferenceException(
                    "Invalid or missing connection string . Check if it exists in configuration file.");
            }

            // Return the connection.
            return connection;
        }


        private static void CloseConnection()
        {
            if (_connection.State == ConnectionState.Open)
            {
                _connection.Close();
                _connection.Dispose();
                _provider = null;
            }
        }


        ///
        ///
        ///

        ///
        ///
        public DbDataReader ExecuteSelect(string commandText)
        {
            return ExecuteSelect(commandText, CommandType.Text, null);
        }

        ///
        ///
        ///

        ///
        ///
        ///
        public DbDataReader ExecuteSelect(string commandText, CommandType cmdType)
        {
            return ExecuteSelect(commandText, cmdType, null);
        }


        ///
        /// Accepts command text , command type and database parameters
        /// as parameters and retrieves the table
        ///

        /// Select statement
        /// Type of command
        /// Database parameters
        ///
        public DbDataReader ExecuteSelect(string commandText, CommandType commandType, object parameters)
        {
            DbDataReader reader = null;

            // Check for valid DbConnection.
            if (_connection != null)
            {
                using (_connection)
                {
                    try
                    {
                        // Create the command.
                        var command = _connection.CreateCommand();
                        command.CommandText = commandText;
                        command.CommandType = commandType;
                        if (parameters != null)
                            command.Parameters.Add(parameters);
                        // Open the connection.
                        _connection.Open();

                        // Retrieve the data.
                        reader = command.ExecuteReader();
                        command.Parameters.Clear();
                    }

                    catch (DbException ex)
                    {
                        Common.LogError(ex);
                        throw;
                    }
                }
            }

            return reader;
        }

        ///
        ///
        ///

        ///
        ///
        public DataSet ExecuteSelectDataSet(string commandText)
        {
            return ExecuteSelectDataSet(commandText, CommandType.Text, null);
        }

        ///
        ///
        ///

        ///
        ///
        ///
        public DataSet ExecuteSelectDataSet(string commandText, CommandType cmdType)
        {
            return ExecuteSelectDataSet(commandText, cmdType, null);
        }


        ///
        /// Accepts command text , command type and database parameters
        /// as parameters and retrieves the table
        ///

        /// Select statement
        /// Type of command
        /// Database parameters
        ///
        public DataSet ExecuteSelectDataSet(string commandText, CommandType commandType, object parameters)
        {
            DataSet ds = null;

            // Check for valid DbConnection.
            if (_connection != null)
            {
                using (_connection)
                {
                    try
                    {
                        // Create the command.
                        var command = _connection.CreateCommand();
                        command.CommandText = commandText;
                        command.CommandType = commandType;
                        if (parameters != null)
                            command.Parameters.Add(parameters);
                        // Open the connection.
                        _connection.Open();
                        using (DbDataAdapter adapter = _provider.CreateDataAdapter())
                        {
                            adapter.SelectCommand = command;
                            adapter.Fill(ds);
                        }
                        command.Parameters.Clear();
                    }

                    catch (DbException ex)
                    {
                        Common.LogError(ex);
                        throw;
                    }
                }
            }

            return ds;
        }

        ///
        ///
        ///

        ///
        ///
        public object ExecuteScalar(string commandText)
        {
            return ExecuteScalar(commandText, CommandType.Text, null);
        }

        ///
        ///
        ///

        ///
        ///
        ///
        public object ExecuteScalar(string commandText, CommandType cmdType)
        {
            return ExecuteScalar(commandText, cmdType, null);
        }


        ///
        /// Accepts command text , command type and database parameters
        /// as parameters and retrieves the table
        ///

        /// Select statement
        /// Type of command
        /// Database parameters
        ///
        public object ExecuteScalar(string commandText, CommandType commandType, object parameters)
        {
            object obj = null;

            // Check for valid DbConnection.
            if (_connection != null)
            {
                using (_connection)
                {
                    try
                    {
                        // Create the command.
                        DbCommand command = _connection.CreateCommand();
                        command.CommandText = commandText;
                        command.CommandType = commandType;
                        if (parameters != null)
                            command.Parameters.Add(parameters);
                        // Open the connection.
                        _connection.Open();
                        obj = command.ExecuteScalar();
                        command.Parameters.Clear();
                    }

                    catch (DbException ex)
                    {
                        Common.LogError(ex);
                        throw;
                    }
                }
            }

            return obj;
        }

        ///
        ///
        ///

        ///
        ///
        public object ExecuteNonQuery(string commandText)
        {
            return ExecuteNonQuery(commandText, CommandType.Text, null);
        }

        ///
        ///
        ///

        ///
        ///
        ///
        public object ExecuteNonQuery(string commandText, CommandType cmdType)
        {
            return ExecuteNonQuery(commandText, cmdType, null);
        }


        ///
        /// Accepts command text , command type and database parameters
        /// as parameters and retrieves the table
        ///

        /// Select statement
        /// Type of command
        /// Database parameters
        ///
        public int ExecuteNonQuery(string commandText, CommandType commandType, object[] parameters)
        {
            int rowsAffected = 0;

            try
            {
                // Create the command.
                DbCommand command = _connection.CreateCommand();
                command.CommandText = commandText;
                command.CommandType = commandType;
                if (parameters != null)
                    command.Parameters.AddRange(parameters);
                rowsAffected = command.ExecuteNonQuery();
                command.Parameters.Clear();
            }

            catch (DbException ex)
            {
                Common.LogError(ex);
                throw;
            }

            return rowsAffected;
        }

        private static void Dispose(bool disposing)
        {
            if (_dispose) return;
            if (disposing)
            {
                if (_connection != null)
                {
                    _provider = null;
                    _connection.Dispose();
                }
            }

            _dispose = true;
        }
    }
}


Finally, please provide your valuable suggestions to make it more useful and more flexible.


Configuring Sify Broadband with your Wireless Router

Recently , I switched from my Reliance 3G data card to Sify broadband internet connection. Because of reliance poor customer service and the most important pathetic 3G speed. It was merely  between 30-60Kbps., where they were claiming it as 21Mbps. Sify cable connection is quite good as compared to it.


Anyways coming to the topic, the Sify technicians configured it via my LAN card and they left. They I thought it to connect via Wireless Modem but I failed to do so, because Sify verifies your MAC Address then allows you to connect. If it varies then you cant . That its a good part and bad as well. Good why??? because , even if some body have your user id and password he wont be able to connect. Bad because if you need to use computer other than registered , you cant????


So here are the steps to set up WiFi using any Wireless Router. 

Hardware Requirements
1. Wireless Router (Mine is Belkin G Wireless Router)
2. Laptop
3. Sify Connection

Sify's connection type is basically Cabel Modem type. As there are some local server that authenticates you. So you need a router that has Cable Modem support (generally all routers have this).
1. Switch on the router.
2. Plug the Sify LAN cable to your Router.
3. Connect your laptop using WiFi to router using 192.168.1.1 or 192.168.2.1 (type in browser address bar and press enter) , or as provided in your router manual.
4. In the Connection Type opt Static Connection.
5. Fill all the parameters , IP address, Gateway and DNS. Do not forget to add DNS other wise you will not be able to connect. Generally they provide 10.x.x.x
6. Restart your router and then check whether you are connected to internet or not. Routers generally have fields that display whether they are connected or not.
7. Definitely you will not be connected as the Sify technician has configured it on LAN and sify has got your LAN mac address. So either you need to clone the MAC address of LAN if your router has functionality. Otherwise there is a tool called Technitium MAC Address Changer . This will help in changing you MAC address. You need to make the LAN MAC as WiFi MAC and LAN MAC to some other. otherwise
8. The Last resort , call sify customer care . They will ask some question for verification purpose and release your current MAC from their address table.
9. Do the step 8 before start following this procedure. Otherwise you need to call the sify again. Also not you can register at max of 2 MAC with Sify at a time.

In case any help required please leave a comment.

Happy Surfing





















Tuesday, June 29, 2010

Viewing Skype Chats and Contacts

Yes, its possible . You can viewchat history and contacts of Skype without actually logging into it. I have created an application on that and is posted on Softpedia Server.

Actually the log files are placed in %APPDATA%/Skype/[Skype_User_Name] directory with chat1234.dbb and something like that files. Please down the app. It is free to use and distribute.
Have fun.

Download from Softpedia Server

Tuesday, June 1, 2010

Downgrading VS2008 Solution or Projects to VS2005 - manually by changing XML

Yesterday, I got stucked in a situation where I have to downgrade an existing VS2008 project to VS2005 one. I was thinking it was an easy job. Yes it is... but in case if you have VS 2005 installed otherwise its going to be a messy day, without VS2005.
I did researched a lot on google. Viewed VS 2005 project and VS2008 project and solution files in notepad and found the following difference that will help you in downgrading the project/solution manually. Lets see what are they.


1. VS 2008 Solution File(.sln) (XML):
                 // First line is a blank line do not delete it
Microsoft Visual Studio Solution File, Format Version 10.00 // your vs version
# Visual Studio 2008 // IDE
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "JabilDemo", "JabilDemo\JabilDemo.csproj", "{22E03101-7132-44CF-8246-C13E10460C45}" // Project in this solution and Its GUID
EndProject // end of project
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution // building options
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{22E03101-7132-44CF-8246-C13E10460C45}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{22E03101-7132-44CF-8246-C13E10460C45}.Debug|Any CPU.Build.0 = Debug|Any CPU
{22E03101-7132-44CF-8246-C13E10460C45}.Release|Any CPU.ActiveCfg = Release|Any CPU
{22E03101-7132-44CF-8246-C13E10460C45}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal


2. VS 2005 Solution File(.sln) (XML):


Microsoft Visual Studio Solution File, Format Version 9.00
# Visual Studio 2005
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "JabilDemo", "JabilDemo\JabilDemo.csproj", "{22E03101-7132-44CF-8246-C13E10460C45}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{22E03101-7132-44CF-8246-C13E10460C45}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{22E03101-7132-44CF-8246-C13E10460C45}.Debug|Any CPU.Build.0 = Debug|Any CPU
{22E03101-7132-44CF-8246-C13E10460C45}.Release|Any CPU.ActiveCfg = Release|Any CPU
{22E03101-7132-44CF-8246-C13E10460C45}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal


The difference between the two solution files is the first two lines last words.
One is 10.0 and 2008, and another is 9.0 and 2005. So, VS 2008 solution file conversion is pretty easy. Huh!!!! No more pain. Small change in first two lines. Rest will be same.


Now come to the messy one Project Files:


3. VS 2008 Project File to VS 2005 Project File (.csproj/.vbproj) (XML): I am using project file of a web application in c#. Open the project file in editor like Notepad or Notepad++. Search for the following tags:
VS2008                                                                                                                      VS2005
<ProductVersion>9.0.30729ProductVersion><ProductVersion>8.0.50727ProductVersion>
 <TargetFrameworkVersion>v3.5TargetFrameworkVersion> <TargetFrameworkVersion>v2.0TargetFrameworkVersion>


DataSetExtensions">
      <RequiredTargetFramework>3.5RequiredTargetFramework>
    
NA




      <RequiredTargetFramework>3.5RequiredTargetFramework>
    
    Xml.Linq">
      <RequiredTargetFramework>3.5RequiredTargetFramework>
    
NA
MSBuildExtensionsPath)\Microsoft\VisualStudio\v9.0\
WebApplications\Microsoft.WebApplication.targets" />
 na


If you replace the VS2008 tags with VS2005 one it will work. But before that be sure to make a copy (backup) of your working files. May be this trick will throw in some more gluey situtaion....


NA above means just remove the tags without leaving any blank line in between the tags.


If you want to do it using tool , you can find it below in my skydrive. 

Downgrading VS2008 Solution or Projects to VS2005

Here I am posting link of the tool that will downgrade VS2008 project to 2005 one. If you have VS2005 installed then you ca achieve the same by deleting existing solution and project file and creating new solution and project file and adding all existing directory structure to it.

If u want to convert it via some tool .. try this and leave comments

From Softpedia

Microsoft Skydrive

Tuesday, July 22, 2008

Download My Apps

Address lookUp : can be used to resolve DNS issues, when your DNS is not pinging and you want the IP of that remote machine. Must try
Download : http://www.4shared.com/file/55641098/f5eb275/AddressLookUp.html
Download : 4.2MB
Battery Monitor : A very simple tool to display the power status of your laptop, notebook or tablet PC running windows 2000 or later.
Download: http://www.4shared.com/file/56103616/57d62da6/BatteryMonitor_1001.html
Size : 3.5 MB

Feel free to request for the help or in case you need the source files.

Friday, July 18, 2008

Battery Status Monitor



This article explains how to read the power status and battery life.

PowerStatus Class
The .NET framework provides a
class named "PowerStatus" that can be used to retrieve power and battery information for notebook, laptop or tablet computers. This class contains five key properties :

§ BatteryChargeStatus. Returns the battery charging status or named charge level.
§ BatteryFullLifetime. Returns the expected duration of operation, in seconds
§ BatteryLifePercent. Returns the percentage of battery life remaining from the current charge.
§ BatteryLifeRemaining. Returns the approximate battery life, in seconds.
§ PowerLineStatus. Returns the current state of the mains power connection.
To query the power and battery status for a computer, a PowerStatus object is required. This can be obtained by querying the
static PowerStatus property of the SystemInformation class.

Application
In this article we will create a Windows Forms application that displays the current power and battery status for the computer.
Controls Used in application:
· Groupbox for placing control in desired location
· Progressbar for displaying charge level.
· Labels for displaying status.
· PictureBox for displaying Power Status , either battery is on charge or is on mains

Source Code

using System;
using System.Collections.Generic;
using System.ComponentModel;

using System.Drawing;
using System.Text;
using System.Windows.Forms;

using System.Diagnostics;

namespace BatteryMonitor
{
public partial class Form1 : Form
{
PowerStatus power = SystemInformation.PowerStatus;
public Form1()
{
InitializeComponent();
float secondsRemaining = power.BatteryLifePercent;
if (secondsRemaining >= 0)
{
ChargeRemaining.Text = (secondsRemaining * 100).ToString() + "% available.";
}
else
{
ChargeRemaining.Text = string.Empty;
}

}
private void RefreshStatus()
{
int powerPercent = (int)(power.BatteryLifePercent * 100);
if (powerPercent <= 100) BatteryIndicator.Value = powerPercent; else BatteryIndicator.Value = 0; switch (power.PowerLineStatus) { case PowerLineStatus.Online: pictureBox1.ImageLocation = "images/winamp.png"; groupBox1.Text = "Running On Mains"; float secondsRemaining = power.BatteryLifePercent; if (secondsRemaining >= 0)
{
ChargeRemaining.Text = (secondsRemaining * 100).ToString() + "% available.";
}
else
{
ChargeRemaining.Text = string.Empty;
}
BatteryStatus.Text = power.BatteryChargeStatus.ToString();
break;

case PowerLineStatus.Offline:


pictureBox1.ImageLocation = "images/oil.png";
groupBox1.Text = "Running On Battery";
BatteryStatus.Text = power.BatteryChargeStatus.ToString();
break;

case PowerLineStatus.Unknown:

break;
}

}

private void timer1_Tick(object sender, EventArgs e)
{
RefreshStatus();
}

private void Form1_Load(object sender, EventArgs e)
{
RefreshStatus();
timer1.Enabled = true;

}
}
}
You can now execute the program to see the results. If you are using a notebook computer, try removing and re-inserting the power cable to see action.

You can download full app @ http://www.4shared.com/file/56103616/57d62da6/BatteryMonitor_1001.html