Simulate mouse click in c#

I was doing a project which was about automation of some work wherein i needed to automatically ‘do the mouseclick’ through my code or simulate a mouseclick event. I googled and found solutions but people had different views, some worked some didn’t. Finally i tweaked around one solution and got it working. So here’s how to do it:

We need to use System.Runtime.InteropServices and DllImport to directly communicate with system level events.

First you declare a class


/**
* http://webdeveloperswall.com/dot-net/simulate-mouse-click-in-csharp
**/
public class MouseOperations
    {
        [Flags]
        public enum MouseEventFlags
        {
            LeftDown = 0x00000002,
            LeftUp = 0x00000004,
            MiddleDown = 0x00000020,
            MiddleUp = 0x00000040,
            Move = 0x00000001,
            Absolute = 0x00008000,
            RightDown = 0x00000008,
            RightUp = 0x00000010
        }

        [DllImport("user32.dll", EntryPoint = "SetCursorPos")]
        [return: MarshalAs(UnmanagedType.Bool)]
        private static extern bool SetCursorPos(int X, int Y);      

        [DllImport("user32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        private static extern bool GetCursorPos(out MousePoint lpMousePoint);

        [DllImport("user32.dll")]
        private static extern void mouse_event(int dwFlags, int dx, int dy, int dwData, int dwExtraInfo);

        public static void SetCursorPosition(int X, int Y) 
        {
            SetCursorPos(X, Y);
        }

        public static MousePoint GetCursorPosition()
        {
            MousePoint currentMousePoint;
            var gotPoint = GetCursorPos(out currentMousePoint);
            if (!gotPoint) { currentMousePoint = new MousePoint(0, 0); }
            return currentMousePoint;
        }

        public static void MouseEvent(MouseEventFlags value)
        {
            MousePoint position = GetCursorPosition();

            mouse_event
                ((int)value,
                 position.X,
                 position.Y,
                 0,
                 0)
                ;
        }

        [StructLayout(LayoutKind.Sequential)]
        public struct MousePoint
        {
            public int X;
            public int Y;

            public MousePoint(int x, int y)
            {
                X = x;
                Y = x;
            }

        }

    }

And then you use it !!

MouseOperations.SetCursorPosition(x, y);
                MouseOperations.MouseEvent(MouseOperations.MouseEventFlags.LeftDown);
                MouseOperations.MouseEvent(MouseOperations.MouseEventFlags.LeftUp);

here x and y passed as the argument are obviously the x and y coordinates (int value). Notice that we need to fire 2 events – ‘LeftDown’ as well as ‘LeftUp’. If you only fire ‘LeftDown’ it will just take the mouse cursor to the coordinate but wont ‘click’ (you can use it to visibly test the x and y coordinates).

So that’s it.

Sorting a list of class or struct with IComparable

Many a times we come to a situation where we have to sort a List of user defined class or struct. The generic List class has an inbuilt sort method to do this. But this raises compile time exception (like ‘Failed to compare two elements in the array”)  if the custom class or struct that you are sorting/comparing doesn’t implement the interface IComparable.

So how do i do it?

Lets say we have a list of employees and we have to display their details. So first things first, we’ll declare the employee class

class employee
{
    public string name;
    public string designation;
    public int salary;
}

Then we make a List of employee

List allEmployees = new List();

One thing here, why do we need a list when we have the good old array? Well if you know the exact number of employee objects (size of the array) you should rather go with an array, if you dont know the size then you have to use a List

So coming back, now we have an empty List of employee, our business logic will fill it in. So you’ll do something like

employee p = new employee();

p.name = "John";
p.designation = "developer";
p.salary = 100;
allEmployees.Add(p);

Then you can iterate through the List and display the details of each employee.
Now coming to sorting, what if you have to display employee with the highest salary first and so on. So we need to sort the List of employee. If you try allEmployees.Sort(), it’ll give you a compilation error.

Implementing IComparable interface

So now we’ll change our class definition a bit, making it implement the IComparable interface. Further we’ll define a CompareTo method.

class employee : IComparable
{
    public string name;
    public string designation;
    public int salary;
    public int CompareTo(employee other)
    {
        // Default to salary sort. [high to low]
        return other.salary.CompareTo(this.salary);
    }
}

Now we can use allEmployees.Sort().
The above code will sort employees in descending order of their salaries. If you want to make it ascending order just replace return other.salary.CompareTo(this.salary); with return this.salary.CompareTo(other.salary);.
Further you can still refine you CompareTo method by adding multiple checks. For example if the salary of two employees is equal then sort based on their designation first. So your method could look like

public int CompareTo(employee other)
{
    // Alphabetic sort if salary is equal. [A to Z]
    if (this.salary == other.salary)
    {
        return other.designation.CompareTo(this.designation);
    }
    // Default to salary sort. [High to low]
    return other.salary.CompareTo(this.salary);
}

And so on you can add many checks. That’s it here.
Hope it helps…

password encryption

The sample code gives you a way of encrypting sensitive data like passwords in c#.

There are many ways of encrypting data, many algorithms, the code i am providing here is one of them. There may be many other ways of encryption which are much stronger and secure than this, but yeah this works for me. I am yet to find a way of decrypting back the original string. But then you don’t really need decryption in normal scenarios. Anyway so here’s what i use to encrypt passwords and all.

public class Encryption
    {
        private string _password;
        private int _salt;

        public Encryption()
        {
            _salt = your_secret_number;
        }

        public string EncryptPassword(string password_to_encrypt)
        {
            _password = password_to_encrypt;
            try
            {
                // Create Byte array of password string
                ASCIIEncoding encoder = new ASCIIEncoding();
                Byte[] _secretBytes = encoder.GetBytes(_password);

                // Create a new salt
                Byte[] _saltBytes = new Byte[4];
                _saltBytes[0] = (byte)(_salt >> 24);
                _saltBytes[1] = (byte)(_salt >> 16);
                _saltBytes[2] = (byte)(_salt >> 8);
                _saltBytes[3] = (byte)(_salt);

                // append the two arrays
                Byte[] toHash = new Byte[_secretBytes.Length + _saltBytes.Length];
                Array.Copy(_secretBytes, 0, toHash, 0, _secretBytes.Length);
                Array.Copy(_saltBytes, 0, toHash, _secretBytes.Length, _saltBytes.Length);

                SHA1 sha1 = SHA1.Create();
                Byte[] computedHash = sha1.ComputeHash(toHash);

                return encoder.GetString(computedHash);
            }
            catch (Exception ex)
            {
                throw;
            }
        }
    }

The code uses .net’s inbuilt cryptography classes to achieve the encrption. You can see that i’ve hardcoded the ‘salt’ value. Thats’ important, there must be one and only one salt value throughout the project, coz once you change it there’s no way of getting the previously encrypted strings’ original value.

Hope you find it useful.

connecting to a mySql database from asp.net application

asp.net to mySql connection

There are times when you want to connect to a mySql database from your asp.net code. By default the drivers for mySql are not packaged with asp.net so you need to include an external dll into your project.

MySql.data.dll

this dll contains all the necessary code required to provide the abstraction that .net developers are used to with while working on ADO.NET. You add the dll into your project and next moment you are creating instances of MySqlConnection, MySqlDataReader and hence forth things are same as you would do with your mssql database connection code.
The dll is available to download at the end of this article.

How to use

  1. download MySql.data.dll
  2. copy it to the bin folder of your application (use windows explorer to browse to the project location (bin folder as it’s generally not visible in Visual Studio)
  3. Add a reference of the said dll into your project
  4. Add using MySql.Data.MySqlClient; inside your code
  5. Make objects of MySqlConnection, MySqlDataReader, MySqlCommand and use them as you would use SqlConnection, SqlDataReader, SqlCommand respectively

sending sms from your asp.net application

send free SMS from your asp.net application/website using third party services. A sample project is available for download at the end of this article.

What is it

The provided dll contains a class Freesmsapi which defines multiple methods to send sms’es from your asp.net website. The methods uses the credentials from your account on freesmsapi.com website. In order to use this you need to first create an account on the said website [Yes, its free !! 🙂]. You get a key which you pass as a parameter to the constructor of freesmsapi class of wdw_utilities.dll. So essentially your application sends a request to the said website which validates the request against the authentication key provided and then sends the sms.

There are few restrictions though :

  • You can send only 100 sms per day (but that should be sufficient for a small app)
  • Additionally according to R.T.I norms you can’t send sms between 9 in night till 9 in morning
  • Your sms’es are not delivered to numbers registered in DND

If all these restriction doesn’t stop you form using it then go ahead download the source code and use it the way you want.

How to use

  1. create an account on freesmsapi.com and get your authentication key
  2. create a new web application project in visual studio
  3. Add wdw_utilities.dll to the bin folder of your newly created project
  4. Add a reference to the said dll into your project
  5. add using wdw_utilities; to your code file
  6. create object(s) of the freesmsapi class passing your authentication key as parameter and call the functions passing appropriate values

How to use

class freesmsapi defines 2 overloads of method sendSMS. You pass the appropriate parameters (receivers mobile no and your text message) to the method and it sends the SMS.

  1. sendSMS(string mobile_numbers, string message) : ‘mobile_numbers’ is comma separated list of mobile numbers to whom who want to send the SMS. Valid values are ‘9*********’ (just one recepient) or ‘9*********, 9*********, …’ (just many recepient)
    ‘message’ is your content of the sms.
  2. sendSMS(string[] mobile_numbers, string message) : ‘mobile_numbers’ is a string array containing list of mobile numbers to whom who want to send the SMS. e.g: [‘9*********’, ‘9*********’, …]
    ‘message’ is your content of the sms.

method returns a string value which contains the response from freesmsapi website.
Thats it in here…..
hope you find it usefull.. cheers..