Tuesday, March 6, 2012

Hook windows keyboard - Capture keypress without focus in C#

Here is a class which hooks windows keyboard to capture all keypress events even if your C# application is not focused.

    /// 
    /// Capture any window key
    /// 
    public static class WinKeyCapture
    {
        private const int WH_KEYBOARD_LL = 13;
        private const int WM_KEYDOWN = 0x0100;
        private static LowLevelKeyboardProc _proc = HookCallback;

        public static void SetHook()
        {
            SetHook(_proc);
        }

        public static void UnHook()
        {
            UnhookWindowsHookEx(_hookID);
        }

        private static IntPtr SetHook(LowLevelKeyboardProc proc)
        {
            using (Process curProcess = Process.GetCurrentProcess())
            using (ProcessModule curModule = curProcess.MainModule)
            {
                return SetWindowsHookEx(WH_KEYBOARD_LL, proc, GetModuleHandle(curModule.ModuleName), 0);
            }
        }
        private static IntPtr _hookID = IntPtr.Zero;

        private delegate IntPtr LowLevelKeyboardProc(int nCode, IntPtr wParam, IntPtr lParam);

        private static IntPtr HookCallback(int nCode, IntPtr wParam, IntPtr lParam)
        {
            if (nCode >= 0 && wParam == (IntPtr)WM_KEYDOWN)
            {
                int vkCode = Marshal.ReadInt32(lParam);
                if (vkCode == 44)
                    ScreenCapture.Load();
            }
            return CallNextHookEx(_hookID, nCode, wParam, lParam);
        }

        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern IntPtr SetWindowsHookEx(int idHook,
            LowLevelKeyboardProc lpfn, IntPtr hMod, uint dwThreadId);

        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        private static extern bool UnhookWindowsHookEx(IntPtr hhk);

        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern IntPtr CallNextHookEx(IntPtr hhk, int nCode,
            IntPtr wParam, IntPtr lParam);

        [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern IntPtr GetModuleHandle(string lpModuleName);
    }

Wednesday, December 21, 2011

8 things your webcam can do, that you dont know


HOME SECURITY SYSTEM 

THERE ARE PLENTY of free programs you can use to turn a webcam into a remote security system. Simply install Yawcam (Windows only) from www.yawcam. com or Vitamin D (Windows and MAC) from www. vitamindinc.com. Both are free and once installed, you can configure them to live stream video and monitor the feed remotely. The software can also be set to alert you or start recording when motion is detected in the frame of view — this is great because you obviously cannot monitor the feed from the camera all the time. For general surveillance, you can setup the software to take snapshots at set intervals and upload them to a remote FTP server. For Linux users, Motion (www.lavrsen.dk) does the same thing.

 

FUN & GAMING

A WEBCAM can literally put you into the action while playing a game. At www.newgrounds. com, you will find a collection of short, quick online games and Adobe Flash applets that use your webcam. Just head to the games section and webcam games subsection on the website. You will need to allow Flash Player to access your webcam when it prompts you — this has to be done for each game. There are plenty of games available on the site that you can play using your webcam and each of them has a different theme. Our favourites are the 3D Target Shooting (the game uses the webcam to detect your location and displays a 3D effect, relative to your position), Night of the Ninja (fend off angry ninjas by hitting them), Bunny Zap (zap bunnies before they hit the ground) and Dress Up Yourself (add spectacles, thought/speech bubbles, facial hair, accessories to your face).

 

LOGIN VIA FACE RECOGNITION

SOME COMPUTERS may have this feature built in, but if you have a PC running Windows and a webcam, you can enable login via face recognition easily. Head to www. luxand.com/blink or http://bananascreen.en.softonic.com and download the free software. In the initial configuration register your face with the software and set an auto-lock for Windows. Once active, the software will recognise your face and automatically log you in to Windows without the need for a password. Since the software recognises certain points on your face, it doesn’t matter if you have a different hairstyle or if you’re wearing spectacles one day. There is an easy way to break in though – if anyone just holds up a photo of yours to the webcam, the software may log in because it can’t recognise 2D or 3D shapes. 




OPTICAL CHARACTER RECOGNITION

OCR OR Optical character recognition using a webcam is a bit tricky as the image quality of most webcams is average. However, your webcam can double up as an OCR reader in a pinch. You can take an image using the webcam and then use software like Microsoft Document imaging, Google Docs and Abbyy FineReader Online to convert images to text. You can also try Evernote (free from www.evernote. com). Evernote is recommended software for OCR since it reads the image from the webcam and converts it into searchable text in real-time. You can use it to save notes, book pages, reports and business cards. Accuracy of converted text varies between 70-90% depending on the image quality and software used for OCR conversion.


 

PHOTOS WITH FUNNY EFFECTS

IF YOU go to www.cameroid.com, you can use any webcam to take funny photos — either with various filters, distortion effects, scenes or frames. You don’t need to install anything or even sign up — just give the site permission to access your webcam through Adobe Flash when prompted. Once you take a photo, you can either save it to the Cameroid public gallery or download the JPG file to your computer. You can also try out similar effects at www.seenly.com. You can also get software to create realtime effects while you video chat with someone using Skype or Google Talk. Videoskin.net offers some freeware while www.webcammax.com and www.shiningmorning. com offer trial versions of their software with thousands of different effects.


BAR CODE READER

READING BAR codes and QR codes is easy with a smartphone and a free app. But you can do the same thing on a PC with a webcam (doesn't matter if the webcam is built in or external, although external is probably better for this purpose). Download and install bcWebCam (get it free from www.bcwebcam. de) and it will automatically connect to your webcam to show the feed. Now just place the barcode or QR code in front of the webcam, the software will take a few seconds to recognise the embedded content and show you the text/link it contains. Mac users who need similar functionality can use Evobarcode (15day trial & US$30 post that) from www.evological.com or QuickMark (US$ 3.99) from the Mac App store.

 

TIME LAPSE VIDEOS

TIME LAPSE is a photography technique wherein multiple photographs, taken at the same location over a period of time are stitched together to form a video. The resulting effect is of time passing by very quickly, hence the name. Free software called Tilaphos (http://sourceforge.net/ projects/tilaphos) or Webcam TimerShot (available on http:// download.cnet.com) can do this for you without hassling you with too many technical details. An external webcam is recommended for time lapse videos because it is easier to keep it still. Also, it is much easier to place it at a location from where a wider frame can be captured — larger coverage would result in capturing of more movements, which in turn will make the video look good. It’s important that the laptop (or webcam) is kept perfectly still and that it receives constant power. After that, it’s just a matter of setting the time interval and recording the time lapse.


 

MAKE YOUR OWN FONT
 
YOU CAN use your webcam to create a font from your own handwriting. This font can be used to send emails or create documents with a personal touch. Head over to www.pilothandwriting.com, download and print the template provided. Now fill out the boxes in the printed form with the corresponding alphabets — using your handwriting. Once done, use your webcam to take an image of the form and upload it to the website. After upload, the site will show you the template and you can edit it to make the alphabets look better. Next, the website will generate a font based on your handwriting and then you can download the font to your computer and use it with any software of your choice.

Wednesday, November 23, 2011

Sabeer Bhatia launches free SMS app Jaxtr

Sabeer Bhatia, the founder of Hotmail.com, on Tuesday launched JaxtrSMS, a mobile application that lets users send unlimited free text messages to any other phone anywhere in the world.
He claimed JaxtrSMS is the world's first mobile-based application for sending SMS that is completely open as the recipients do not need to have the app installed.

http://timesofindia.indiatimes.com/tech/personal-tech/computing/sabeer-bhatia-launches-free-sms-app-jaxtr/sabeer-jpg/thumb/10833076/sabeer-jpg.jpg?width=300&resizemode=4It is already available as a free download for all major mobile operating systems - iOS, Android, Blackberry and J2ME. In fact, users in 197 countries have already downloaded the app within a few weeks since the soft launch, said Bhatia, who is CEO & co-founded Jaxtr with Yogesh Patel in US.

JaxtrSMS is unique in that a mobile user can send a text SMS to any mobile phone in the world without requiring the receiver to have the JaxtrSMS application installed on her phone. This "open" facet of JaxtrSMS distinguishes it from other free mobile messaging applications such as Whatsapp where messages can only be sent within a closed network to people who also have the same app installed. JaxtrSMS retains the number of the user and no new number is required while signing up for the JaxtrSMS service.

"15 years ago, we gave you Hotmail.com, the world's first webmail service that freed up e-mail from the confines of the desktop and aided the creation of a global communications network which was completely open and free for users. Today, we present JaxtrSMS which does to SMS what Hotmail did for e-mail.
Now, mobile users can leverage our free and open application to send messages to their contacts anywhere across the world without having to pay anything," said Bhatia.

"JaxtrSMS was completely developed in India. I am proud to showcase this as an example of Indian innovation and ingenuity," said Yogesh Patel, president & co-founder.

Tuesday, August 16, 2011

jQuery Blink Plugin

I have created a plugin where you can apply blink effect on any dom object.
It can be div,span or anything.

Check out http://plugins.jquery.com/project/jqblink for more details

Tuesday, July 19, 2011

SQLHelper by Microsoft

using System;
using System.Data;
using System.Xml;
using System.Data.SqlClient;
using System.Collections;


namespace Microsoft.ApplicationBlocks.Data
{
    public sealed class SqlHelper
    {
        #region private utility methods & constructors

        private SqlHelper() { }

        private static void AttachParameters(SqlCommand command, SqlParameter[] commandParameters)
        {
            foreach (SqlParameter p in commandParameters)
            {
                if ((p.Direction == ParameterDirection.InputOutput) && (p.Value == null))
                {
                    p.Value = DBNull.Value;
                }

                command.Parameters.Add(p);
            }
        }

        private static void AssignParameterValues(SqlParameter[] commandParameters, object[] parameterValues)
        {
            if ((commandParameters == null) || (parameterValues == null))
            {
                return;
            }

            if (commandParameters.Length != parameterValues.Length)
            {
                throw new ArgumentException("Parameter count does not match Parameter Value count.");
            }

            for (int i = 0, j = commandParameters.Length; i < j; i++)
            {
                commandParameters[i].Value = parameterValues[i];
            }
        }

        private static void PrepareCommand(SqlCommand command, SqlConnection connection, SqlTransaction transaction, CommandType commandType, string commandText, SqlParameter[] commandParameters)
        {
            if (connection.State != ConnectionState.Open)
            {
                connection.Open();
            }

            command.Connection = connection;

            command.CommandText = commandText;

            if (transaction != null)
            {
                command.Transaction = transaction;
            }

            command.CommandType = commandType;

            if (commandParameters != null)
            {
                AttachParameters(command, commandParameters);
            }

            return;
        }


        #endregion private utility methods & constructors

        #region ExecuteNonQuery

        public static int ExecuteNonQuery(string connectionString, CommandType commandType, string commandText)
        {
            return ExecuteNonQuery(connectionString, commandType, commandText, (SqlParameter[])null);
        }

        public static int ExecuteNonQuery(string connectionString, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
        {
            using (SqlConnection cn = new SqlConnection(connectionString))
            {
                cn.Open();
                return ExecuteNonQuery(cn, commandType, commandText, commandParameters);
            }
        }

        public static int ExecuteNonQuery(string connectionString, string spName, params object[] parameterValues)
        {
            if ((parameterValues != null) && (parameterValues.Length > 0))
            {
                SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connectionString, spName);

                AssignParameterValues(commandParameters, parameterValues);

                return ExecuteNonQuery(connectionString, CommandType.StoredProcedure, spName, commandParameters);
            }
            else
            {
                return ExecuteNonQuery(connectionString, CommandType.StoredProcedure, spName);
            }
        }

        public static int ExecuteNonQuery(SqlConnection connection, CommandType commandType, string commandText)
        {
            return ExecuteNonQuery(connection, commandType, commandText, (SqlParameter[])null);
        }

        public static int ExecuteNonQuery(SqlConnection connection, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
        {
            SqlCommand cmd = new SqlCommand();
            PrepareCommand(cmd, connection, (SqlTransaction)null, commandType, commandText, commandParameters);

            int retval = cmd.ExecuteNonQuery();

            cmd.Parameters.Clear();
            return retval;
        }

        public static int ExecuteNonQuery(SqlConnection connection, string spName, params object[] parameterValues)
        {
            if ((parameterValues != null) && (parameterValues.Length > 0))
            {
                SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connection.ConnectionString, spName);

                AssignParameterValues(commandParameters, parameterValues);

                return ExecuteNonQuery(connection, CommandType.StoredProcedure, spName, commandParameters);
            }
            else
            {
                return ExecuteNonQuery(connection, CommandType.StoredProcedure, spName);
            }
        }

        public static int ExecuteNonQuery(SqlTransaction transaction, CommandType commandType, string commandText)
        {
            return ExecuteNonQuery(transaction, commandType, commandText, (SqlParameter[])null);
        }

        public static int ExecuteNonQuery(SqlTransaction transaction, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
        {
            SqlCommand cmd = new SqlCommand();
            PrepareCommand(cmd, transaction.Connection, transaction, commandType, commandText, commandParameters);

            int retval = cmd.ExecuteNonQuery();

            cmd.Parameters.Clear();
            return retval;
        }

        public static int ExecuteNonQuery(SqlTransaction transaction, string spName, params object[] parameterValues)
        {
            if ((parameterValues != null) && (parameterValues.Length > 0))
            {
                SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(transaction.Connection.ConnectionString, spName);

                AssignParameterValues(commandParameters, parameterValues);

                return ExecuteNonQuery(transaction, CommandType.StoredProcedure, spName, commandParameters);
            }
            else
            {
                return ExecuteNonQuery(transaction, CommandType.StoredProcedure, spName);
            }
        }


        #endregion ExecuteNonQuery

        #region ExecuteDataSet

        public static DataSet ExecuteDataset(string connectionString, CommandType commandType, string commandText)
        {
            return ExecuteDataset(connectionString, commandType, commandText, (SqlParameter[])null);
        }

        public static DataSet ExecuteDataset(string connectionString, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
        {
            using (SqlConnection cn = new SqlConnection(connectionString))
            {
                cn.Open();
                return ExecuteDataset(cn, commandType, commandText, commandParameters);
            }
        }

        public static DataSet ExecuteDataset(string connectionString, string spName, params object[] parameterValues)
        {
            if ((parameterValues != null) && (parameterValues.Length > 0))
            {
                SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connectionString, spName);

                AssignParameterValues(commandParameters, parameterValues);

                return ExecuteDataset(connectionString, CommandType.StoredProcedure, spName, commandParameters);
            }
            else
            {
                return ExecuteDataset(connectionString, CommandType.StoredProcedure, spName);
            }
        }

        public static DataSet ExecuteDataset(SqlConnection connection, CommandType commandType, string commandText)
        {
            return ExecuteDataset(connection, commandType, commandText, (SqlParameter[])null);
        }

        public static DataSet ExecuteDataset(SqlConnection connection, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
        {
            SqlCommand cmd = new SqlCommand();
            PrepareCommand(cmd, connection, (SqlTransaction)null, commandType, commandText, commandParameters);

            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataSet ds = new DataSet();

            da.Fill(ds);

            cmd.Parameters.Clear();

            return ds;
        }

        public static DataSet ExecuteDataset(SqlConnection connection, string spName, params object[] parameterValues)
        {
            if ((parameterValues != null) && (parameterValues.Length > 0))
            {
                SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connection.ConnectionString, spName);

                AssignParameterValues(commandParameters, parameterValues);

                return ExecuteDataset(connection, CommandType.StoredProcedure, spName, commandParameters);
            }
            else
            {
                return ExecuteDataset(connection, CommandType.StoredProcedure, spName);
            }
        }

        public static DataSet ExecuteDataset(SqlTransaction transaction, CommandType commandType, string commandText)
        {
            return ExecuteDataset(transaction, commandType, commandText, (SqlParameter[])null);
        }

        public static DataSet ExecuteDataset(SqlTransaction transaction, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
        {
            SqlCommand cmd = new SqlCommand();
            PrepareCommand(cmd, transaction.Connection, transaction, commandType, commandText, commandParameters);

            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataSet ds = new DataSet();

            da.Fill(ds);

            cmd.Parameters.Clear();

            return ds;
        }

        public static DataSet ExecuteDataset(SqlTransaction transaction, string spName, params object[] parameterValues)
        {
            if ((parameterValues != null) && (parameterValues.Length > 0))
            {
                SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(transaction.Connection.ConnectionString, spName);

                AssignParameterValues(commandParameters, parameterValues);

                return ExecuteDataset(transaction, CommandType.StoredProcedure, spName, commandParameters);
            }
            else
            {
                return ExecuteDataset(transaction, CommandType.StoredProcedure, spName);
            }
        }

        #endregion ExecuteDataSet

        #region ExecuteReader

        private enum SqlConnectionOwnership
        {
            Internal,
            External
        }

        private static SqlDataReader ExecuteReader(SqlConnection connection, SqlTransaction transaction, CommandType commandType, string commandText, SqlParameter[] commandParameters, SqlConnectionOwnership connectionOwnership)
        {
            SqlCommand cmd = new SqlCommand();
            PrepareCommand(cmd, connection, transaction, commandType, commandText, commandParameters);

            SqlDataReader dr;

            if (connectionOwnership == SqlConnectionOwnership.External)
            {
                dr = cmd.ExecuteReader();
            }
            else
            {
                dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
            }

            cmd.Parameters.Clear();

            return dr;
        }

        public static SqlDataReader ExecuteReader(string connectionString, CommandType commandType, string commandText)
        {
            return ExecuteReader(connectionString, commandType, commandText, (SqlParameter[])null);
        }

        public static SqlDataReader ExecuteReader(string connectionString, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
        {
            SqlConnection cn = new SqlConnection(connectionString);
            cn.Open();

            try
            {
                return ExecuteReader(cn, null, commandType, commandText, commandParameters, SqlConnectionOwnership.Internal);
            }
            catch
            {
                cn.Close();
                throw;
            }
        }

        public static SqlDataReader ExecuteReader(string connectionString, string spName, params object[] parameterValues)
        {
            if ((parameterValues != null) && (parameterValues.Length > 0))
            {
                SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connectionString, spName);

                AssignParameterValues(commandParameters, parameterValues);

                return ExecuteReader(connectionString, CommandType.StoredProcedure, spName, commandParameters);
            }
            else
            {
                return ExecuteReader(connectionString, CommandType.StoredProcedure, spName);
            }
        }

        public static SqlDataReader ExecuteReader(SqlConnection connection, CommandType commandType, string commandText)
        {
            return ExecuteReader(connection, commandType, commandText, (SqlParameter[])null);
        }

        public static SqlDataReader ExecuteReader(SqlConnection connection, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
        {
            return ExecuteReader(connection, (SqlTransaction)null, commandType, commandText, commandParameters, SqlConnectionOwnership.External);
        }

        public static SqlDataReader ExecuteReader(SqlConnection connection, string spName, params object[] parameterValues)
        {
            if ((parameterValues != null) && (parameterValues.Length > 0))
            {
                SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connection.ConnectionString, spName);

                AssignParameterValues(commandParameters, parameterValues);

                return ExecuteReader(connection, CommandType.StoredProcedure, spName, commandParameters);
            }
            else
            {
                return ExecuteReader(connection, CommandType.StoredProcedure, spName);
            }
        }

        public static SqlDataReader ExecuteReader(SqlTransaction transaction, CommandType commandType, string commandText)
        {
            return ExecuteReader(transaction, commandType, commandText, (SqlParameter[])null);
        }

        public static SqlDataReader ExecuteReader(SqlTransaction transaction, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
        {
            return ExecuteReader(transaction.Connection, transaction, commandType, commandText, commandParameters, SqlConnectionOwnership.External);
        }

        public static SqlDataReader ExecuteReader(SqlTransaction transaction, string spName, params object[] parameterValues)
        {
            if ((parameterValues != null) && (parameterValues.Length > 0))
            {
                SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(transaction.Connection.ConnectionString, spName);

                AssignParameterValues(commandParameters, parameterValues);

                return ExecuteReader(transaction, CommandType.StoredProcedure, spName, commandParameters);
            }
            else
            {
                return ExecuteReader(transaction, CommandType.StoredProcedure, spName);
            }
        }

        #endregion ExecuteReader

        #region ExecuteScalar

        public static object ExecuteScalar(string connectionString, CommandType commandType, string commandText)
        {
            return ExecuteScalar(connectionString, commandType, commandText, (SqlParameter[])null);
        }

        public static object ExecuteScalar(string connectionString, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
        {
            using (SqlConnection cn = new SqlConnection(connectionString))
            {
                cn.Open();
                return ExecuteScalar(cn, commandType, commandText, commandParameters);
            }
        }

        public static object ExecuteScalar(string connectionString, string spName, params object[] parameterValues)
        {
            if ((parameterValues != null) && (parameterValues.Length > 0))
            {
                SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connectionString, spName);

                AssignParameterValues(commandParameters, parameterValues);

                return ExecuteScalar(connectionString, CommandType.StoredProcedure, spName, commandParameters);
            }
            else
            {
                return ExecuteScalar(connectionString, CommandType.StoredProcedure, spName);
            }
        }

        public static object ExecuteScalar(SqlConnection connection, CommandType commandType, string commandText)
        {
            return ExecuteScalar(connection, commandType, commandText, (SqlParameter[])null);
        }

        public static object ExecuteScalar(SqlConnection connection, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
        {
            SqlCommand cmd = new SqlCommand();
            PrepareCommand(cmd, connection, (SqlTransaction)null, commandType, commandText, commandParameters);

            object retval = cmd.ExecuteScalar();

            cmd.Parameters.Clear();
            return retval;

        }

        public static object ExecuteScalar(SqlConnection connection, string spName, params object[] parameterValues)
        {
            if ((parameterValues != null) && (parameterValues.Length > 0))
            {
                SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connection.ConnectionString, spName);

                AssignParameterValues(commandParameters, parameterValues);

                return ExecuteScalar(connection, CommandType.StoredProcedure, spName, commandParameters);
            }
            else
            {
                return ExecuteScalar(connection, CommandType.StoredProcedure, spName);
            }
        }

        public static object ExecuteScalar(SqlTransaction transaction, CommandType commandType, string commandText)
        {
            return ExecuteScalar(transaction, commandType, commandText, (SqlParameter[])null);
        }

        public static object ExecuteScalar(SqlTransaction transaction, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
        {
            SqlCommand cmd = new SqlCommand();
            PrepareCommand(cmd, transaction.Connection, transaction, commandType, commandText, commandParameters);

            object retval = cmd.ExecuteScalar();

            cmd.Parameters.Clear();
            return retval;
        }

        public static object ExecuteScalar(SqlTransaction transaction, string spName, params object[] parameterValues)
        {
            if ((parameterValues != null) && (parameterValues.Length > 0))
            {
                SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(transaction.Connection.ConnectionString, spName);

                AssignParameterValues(commandParameters, parameterValues);

                return ExecuteScalar(transaction, CommandType.StoredProcedure, spName, commandParameters);
            }
            else
            {
                return ExecuteScalar(transaction, CommandType.StoredProcedure, spName);
            }
        }

        #endregion ExecuteScalar

        #region ExecuteXmlReader

        public static XmlReader ExecuteXmlReader(SqlConnection connection, CommandType commandType, string commandText)
        {
            return ExecuteXmlReader(connection, commandType, commandText, (SqlParameter[])null);
        }

        public static XmlReader ExecuteXmlReader(SqlConnection connection, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
        {
            SqlCommand cmd = new SqlCommand();
            PrepareCommand(cmd, connection, (SqlTransaction)null, commandType, commandText, commandParameters);

            XmlReader retval = cmd.ExecuteXmlReader();

            cmd.Parameters.Clear();
            return retval;
        }

        public static XmlReader ExecuteXmlReader(SqlConnection connection, string spName, params object[] parameterValues)
        {
            if ((parameterValues != null) && (parameterValues.Length > 0))
            {
                SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connection.ConnectionString, spName);

                AssignParameterValues(commandParameters, parameterValues);

                return ExecuteXmlReader(connection, CommandType.StoredProcedure, spName, commandParameters);
            }
            else
            {
                return ExecuteXmlReader(connection, CommandType.StoredProcedure, spName);
            }
        }

        public static XmlReader ExecuteXmlReader(SqlTransaction transaction, CommandType commandType, string commandText)
        {
            return ExecuteXmlReader(transaction, commandType, commandText, (SqlParameter[])null);
        }

        public static XmlReader ExecuteXmlReader(SqlTransaction transaction, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
        {
            SqlCommand cmd = new SqlCommand();
            PrepareCommand(cmd, transaction.Connection, transaction, commandType, commandText, commandParameters);

            XmlReader retval = cmd.ExecuteXmlReader();

            cmd.Parameters.Clear();
            return retval;
        }

        public static XmlReader ExecuteXmlReader(SqlTransaction transaction, string spName, params object[] parameterValues)
        {
            if ((parameterValues != null) && (parameterValues.Length > 0))
            {
                SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(transaction.Connection.ConnectionString, spName);

                AssignParameterValues(commandParameters, parameterValues);

                return ExecuteXmlReader(transaction, CommandType.StoredProcedure, spName, commandParameters);
            }
            else
            {
                return ExecuteXmlReader(transaction, CommandType.StoredProcedure, spName);
            }
        }


        #endregion ExecuteXmlReader
    }

    public sealed class SqlHelperParameterCache
    {
        #region private methods, variables, and constructors

        private SqlHelperParameterCache() { }

        private static Hashtable paramCache = Hashtable.Synchronized(new Hashtable());

        private static SqlParameter[] DiscoverSpParameterSet(string connectionString, string spName, bool includeReturnValueParameter)
        {
            using (SqlConnection cn = new SqlConnection(connectionString))
            using (SqlCommand cmd = new SqlCommand(spName, cn))
            {
                cn.Open();
                cmd.CommandType = CommandType.StoredProcedure;

                SqlCommandBuilder.DeriveParameters(cmd);

                if (!includeReturnValueParameter)
                {
                    cmd.Parameters.RemoveAt(0);
                }

                SqlParameter[] discoveredParameters = new SqlParameter[cmd.Parameters.Count]; ;

                cmd.Parameters.CopyTo(discoveredParameters, 0);

                return discoveredParameters;
            }
        }

        private static SqlParameter[] CloneParameters(SqlParameter[] originalParameters)
        {
            SqlParameter[] clonedParameters = new SqlParameter[originalParameters.Length];

            for (int i = 0, j = originalParameters.Length; i < j; i++)
            {
                clonedParameters[i] = (SqlParameter)((ICloneable)originalParameters[i]).Clone();
            }

            return clonedParameters;
        }

        #endregion private methods, variables, and constructors

        #region caching functions

        public static void CacheParameterSet(string connectionString, string commandText, params SqlParameter[] commandParameters)
        {
            string hashKey = connectionString + ":" + commandText;

            paramCache[hashKey] = commandParameters;
        }

        public static SqlParameter[] GetCachedParameterSet(string connectionString, string commandText)
        {
            string hashKey = connectionString + ":" + commandText;

            SqlParameter[] cachedParameters = (SqlParameter[])paramCache[hashKey];

            if (cachedParameters == null)
            {
                return null;
            }
            else
            {
                return CloneParameters(cachedParameters);
            }
        }

        #endregion caching functions

        #region Parameter Discovery Functions

        public static SqlParameter[] GetSpParameterSet(string connectionString, string spName)
        {
            return GetSpParameterSet(connectionString, spName, false);
        }

        public static SqlParameter[] GetSpParameterSet(string connectionString, string spName, bool includeReturnValueParameter)
        {
            string hashKey = connectionString + ":" + spName + (includeReturnValueParameter ? ":include ReturnValue Parameter" : "");

            SqlParameter[] cachedParameters;

            cachedParameters = (SqlParameter[])paramCache[hashKey];

            if (cachedParameters == null)
            {
                cachedParameters = (SqlParameter[])(paramCache[hashKey] = DiscoverSpParameterSet(connectionString, spName, includeReturnValueParameter));
            }

            return CloneParameters(cachedParameters);
        }

        #endregion Parameter Discovery Functions

    }
}

Wednesday, July 13, 2011

Invitation to be part of success story


Dear Friends,

Hope you are doing well along with your family.
2010-11 has been an excellent year for us i.e. Prakash Software.

Apart from increased number of satisfied customers, we got “Best Innovation Company 2011 Award” from GESIA.  View details

We are yet observing phenomenal growth on the road ahead and I am excited to invite you to be part of it.

I am glad to announce that as part of our growth process – we are going to hire yet more members at both our Ahmedabad & Baroda branches.

Have a look through below and follow any of contact steps to be part of our success story!
Current Openings:
1.       CODE ‘201107-MOSS-SNR’: Microsoft SharePoint – Senior Developer / Tech Lead [2-5 years relevant experience] Vacancies – 1 [Ahmedabad] JOBCODE:
2.       CODE ‘201107-MOSS-JNR’: Microsoft SharePoint – Junior Developer [1-2 years relevant experience] Vacancies – 2 [Baroda]
3.       CODE ‘201107-BDE’: Business Development Executive [1-8 years of experience] Vacancies – 4 [Ahmedabad-2, Baroda-2]
4.       CODE ‘201107-BA’: Business Analyst [1-5 years of experience] Vacancies – 1 [Ahmedabad]

Get rolling through one of below:
1.       Send your latest CV to ‘cv@prakashinfotech.com ’; please ensure to write Job Code in subject for faster processing.
2.       Call us at +91-9714882647

Saturday, April 16, 2011

Datapager: Paging in RIA Application with MVVM

PagedEntitySet

This will help creating List of Entities that can be paged.

public class PagedEntitySet : INotifyPropertyChanged, INotifyCollectionChanged, IPagedCollectionView, IEnumerable
	where T : Entity, new()
{

	#region Private Members

	private IPagedCollectionView _pagingView;

	private IEnumerable Enumerable { get { return this._entityList; } }

	private EntitySet _entityList;

	#endregion

	#region IEnumerable Members

	public IEnumerator GetEnumerator()
	{
		return this._entityList.GetEnumerator();
	}

	#endregion

	#region IEnumerable Members

	IEnumerator IEnumerable.GetEnumerator()
	{
		return this.GetEnumerator();
	}

	#endregion

	#region Constructor

	public PagedEntitySet(EntitySet entityList, IPagedCollectionView delegatePagingView)
	{
		_entityList = entityList;
		INotifyCollectionChanged collectionChanged = _entityList as INotifyCollectionChanged;
		if (collectionChanged != null)
			collectionChanged.CollectionChanged += (s, e) => CollectionChanged(this, e);
		_pagingView = delegatePagingView;
		_pagingView.PageChanging += PageChanging;
		_pagingView.PageChanged += PageChanged;
		INotifyPropertyChanged propertyChanged = _pagingView as INotifyPropertyChanged;
		if (propertyChanged != null)
			propertyChanged.PropertyChanged += (s, e) => PropertyChanged(this, e);
	}

	#endregion

	#region INotifyPropertyChanged Members

	public event PropertyChangedEventHandler PropertyChanged = delegate { };

	#endregion

	#region INotifyCollectionChanged Members

	public event NotifyCollectionChangedEventHandler CollectionChanged = delegate { };

	#endregion

	#region IPagedCollectionView Members

	public bool CanChangePage
	{
		get { return _pagingView.CanChangePage; }
	}

	public bool IsPageChanging
	{
		get { return _pagingView.IsPageChanging; }
	}

	public int ItemCount
	{
		get { return _pagingView.ItemCount; }
	}

	public bool MoveToFirstPage()
	{
		return _pagingView.MoveToFirstPage();
	}

	public bool MoveToLastPage()
	{
		return _pagingView.MoveToLastPage();
	}

	public bool MoveToNextPage()
	{
		return _pagingView.MoveToNextPage();
	}

	public bool MoveToPage(int pageIndex)
	{
		return _pagingView.MoveToPage(pageIndex);
	}

	public bool MoveToPreviousPage()
	{
		return _pagingView.MoveToPreviousPage();
	}

	public event EventHandler PageChanged = delegate { };

	public event EventHandler PageChanging = delegate { };

	public int PageIndex
	{
		get { return _pagingView.PageIndex; }
	}

	public int PageSize
	{
		get { return _pagingView.PageSize; }
		set { _pagingView.PageSize = value; }
	}

	public int TotalItemCount
	{
		get { return _pagingView.TotalItemCount; }
	}

	#endregion

}

PagedViewModelBase
This abstract class will help binding your view model to view page with paging functionality.

public abstract class PagedViewModelBase: IPagedCollectionView, INotifyPropertyChanged
{

	#region Member Properties

	private static PropertyChangedEventArgs IsPageChangingChangedEventArgs = new PropertyChangedEventArgs("IsPageChanging");

	private static PropertyChangedEventArgs ItemCountChangedEventArgs = new PropertyChangedEventArgs("ItemCount");

	private static PropertyChangedEventArgs PageIndexChangedEventArgs = new PropertyChangedEventArgs("PageIndex");

	private static PropertyChangedEventArgs PageSizeChangedEventArgs = new PropertyChangedEventArgs("PageSize");

	private static PropertyChangedEventArgs TotalItemCountChangedEventArgs = new PropertyChangedEventArgs("TotalItemCount");

	private static PropertyChangedEventArgs IsLoadingChangedEventArgs = new PropertyChangedEventArgs("IsLoading");

	private bool _isLoading;

	public bool IsLoading
	{
		get { return _isLoading; }
		set
		{
			if (_isLoading != value)
			{
				_isLoading = value;
				RaisePropertyChanged(IsLoadingChangedEventArgs);
			}
		}
	}

	#endregion

	#region Member Functions

	public abstract void LoadData();

	#endregion

	#region INotifyPropertyChanged Members

	public event PropertyChangedEventHandler PropertyChanged;

	protected void RaisePropertyChanged(PropertyChangedEventArgs args)
	{
		if (PropertyChanged != null)
			PropertyChanged(this, args);
	}

	#endregion

	#region IPagedCollectionView Members

	public bool CanChangePage
	{
		get { return true; }
	}

	bool isPageChanging;

	public bool IsPageChanging
	{
		get { return isPageChanging; }
		private set
		{
			if (isPageChanging != value)
			{
				isPageChanging = value;
				RaisePropertyChanged(IsPageChangingChangedEventArgs);
			}

		}
	}

	int itemCount;

	public int ItemCount
	{
		get { return itemCount; }
		set
		{
			if (itemCount != value)
			{
				itemCount = value;
				RaisePropertyChanged(ItemCountChangedEventArgs);
			}
		}
	}

	public bool MoveToFirstPage()
	{
		return MoveToPage(0);
	}

	public bool MoveToLastPage()
	{
		return MoveToPage(TotalItemCount / PageSize);
	}

	public bool MoveToNextPage()
	{
		return MoveToPage(PageIndex + 1);
	}

	public bool MoveToPage(int index)
	{
		if (index == PageIndex || index < 0 || index > TotalItemCount / PageSize)
		{
			return false;
		}
		PageChangingEventArgs args = new PageChangingEventArgs(index);
		try
		{
			IsPageChanging = true;
			PageChanging(this, args);
			if (!args.Cancel)
			{
				pageIndex = index;
				LoadData();
				RaisePropertyChanged(PageIndexChangedEventArgs);
				PageChanged(this, EventArgs.Empty);
				return true;
			}
			return false;
		}
		finally
		{
			IsPageChanging = false;
		}
	}

	public bool MoveToPreviousPage()
	{
		return MoveToPage(PageIndex - 1);
	}

	public event EventHandler<EventArgs> PageChanged = delegate { };

	public event EventHandler<PageChangingEventArgs> PageChanging = delegate { };

	int pageIndex;

	public int PageIndex
	{
		get { return pageIndex; }
		set
		{
			if (pageIndex < 0 || pageIndex > totalItemCount / PageSize)
			{
				throw new ArgumentOutOfRangeException("PageIndex must be greater than or equal to 0 and less than the page count");
			}
			MoveToPage(value);
		}
	}

	int pageSize = 10; //default page size to 10

	public int PageSize
	{
		get { return pageSize; }
		set
		{
			if (pageSize != value)
			{
				pageSize = value;
				RaisePropertyChanged(PageSizeChangedEventArgs);
			}
		}
	}

	int totalItemCount;

	public int TotalItemCount
	{
		get { return totalItemCount; }
		set
		{
			if (totalItemCount != value)
			{
				totalItemCount = value;
				RaisePropertyChanged(TotalItemCountChangedEventArgs);
			}
		}
	}
	
	#endregion
}

This both Class will help you to easily bind your datagrid and datapager.
Just use PagedEntitySet type for binding data in your viewmodel for both datagrid and datapager.
Use constructor to initialize data in it.

This is the easiest way I find. If you have some more smart code please share it. Hope this will save a lot of your time. Happy Coding..