Tuesday, February 12, 2013

Stop Watch Using Background Worker

I am showing you how to use background worker to make an interesting stop watch.
Now create new window based application named as "StopWatchDemo", change the form name with "frmMain" and design it as shown in image below...


 Now give name to the buttons sequentially as btnStart, btnStop, btnClose respectively.Give name "lblStopWatch" to label containing StopWatch. Give click events to each button. And here is complete code...

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;

namespace StopWatchDemo
{
    public partial class frmMain : Form
    {
        Stopwatch stopWatch = null;
        BackgroundWorker backgroundWorker = null;
       
        public frmMain()
        {
            InitializeComponent();

            stopWatch = new Stopwatch();
            backgroundWorker = new BackgroundWorker();

            backgroundWorker.DoWork += new DoWorkEventHandler(backgroundWorker_DoWork);
            backgroundWorker.ProgressChanged += new ProgressChangedEventHandler(backgroundWorker_ProgressChanged);
            backgroundWorker.WorkerReportsProgress = true;
            backgroundWorker.WorkerSupportsCancellation = true;

            btnStop.Enabled = false;
        }

        void backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            TimeSpan timeSpan = stopWatch.Elapsed;
            lblStopWatch.Text = String.Format("Time : {0:00}:{1:00} sec", timeSpan.Minutes, timeSpan.Seconds);
        }

        void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            while(true)
            {
                backgroundWorker.ReportProgress(0);
                System.Threading.Thread.Sleep(1000);
                if (!stopWatch.IsRunning)
                {
                    break;
                }
            }
        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            backgroundWorker.RunWorkerAsync();
            stopWatch.Start();

            btnStart.Enabled = false;
            btnStop.Enabled = true;
            btnClose.Enabled = false;
        }

        private void btnStop_Click(object sender, EventArgs e)
        {
            backgroundWorker.CancelAsync();
            stopWatch.Stop();
            stopWatch.Reset();

            btnStart.Enabled = true;
            btnStop.Enabled = false;
            btnClose.Enabled = true;
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }
    }
}

Now Start debugging, window will look like this as follows...



Now play with this....
This example shows how to use background worker facility given by .NET, it can be used in serious applications as I have used in some live projects...

Monday, February 11, 2013

Single Instace of an Application

Hi guys most of cases we don't want to make multiple instants of applications to be executed in single machine, I am providing a code span to prevent this problem as follows...

In most of the window based applications code looks like this...


[STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new frmMainForm());
        }


Now I am made some changes in above code it looks like this....


[STAThread]
        static void Main()
        {
            //Make Single Instace of an Application I am using Mutex
            bool createdNew;
            using (new System.Threading.Mutex(false, "SingleWindow", out createdNew))
            {
                if (createdNew)
                {
                    Application.EnableVisualStyles();
                    Application.SetCompatibleTextRenderingDefault(false);
                    Application.Run(new frmMainForm());
                }
            }
        }

Here "SingleWindow" is the name of exe or project name that I am making and System.Threading.Mutex function updates value of boolean veriable createdNew true if no exe is running in the machine named "SingleWindow". So, code is self explanatory that what I have done...

Sunday, February 10, 2013

XOR Cipher


Hi guys I would like to publish a simple way to create your own cipher using c#, here is complete code for it....


class Program
    {
        static void Main(string[] args)
        {
            try
            {
                //XORCipher objXORCipher = new XORCipher("dinesh", "0123456789ABCDEF");
                XORCipher objXORCipher = new XORCipher();
                String textToEncrypt = "This is Test String...";
                String encText = objXORCipher.Encrypt(textToEncrypt);
                String finalText = objXORCipher.Decrypt(encText);
                Console.Write("\n\nOriginal  Text : " + textToEncrypt);
                Console.Write("\n\nEncrypted Text : " + encText);
                Console.Write("\n\nDecrypted Text : " + finalText);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            Console.Write("\n\nDone...");
            Console.ReadKey();
        }
    }

    public class XORCipher
    {
        char[] key = new char[0];
        String cipherString = String.Empty;

        public XORCipher()
        {
            key = "DINESH".ToCharArray();
            cipherString = "0123456789ABCDEF";
        }

        public XORCipher(String key, String cipherString)
        {
            this.key = key.ToCharArray();
         
            if (cipherString.Length != 16)
            {
                throw new Exception("Invalid cipher string");
            }

            this.cipherString = cipherString;
        }

        public String Encrypt(String textToEncrypt)
        {
            String val = String.Empty;
            char[] myString = textToEncrypt.ToCharArray();

            byte[] demoString = new byte[myString.Length];

            for (int i = 0; i < demoString.Length; i++)
            {
                demoString[i] = (byte)(myString[i] ^ key[i % key.Length]);
            }

            foreach (byte ok in demoString)
            {
                String demo = DecimalToBinary((byte)ok);
                for (int i = 0; i < (demo.Length / 4); i++)
                {
                    //Console.Write(" " + demo.Substring(i * 4, 4));
                    val += cipherString.Substring(Convert.ToInt16(demo.Substring(i * 4, 4), 2), 1);
                }
            }

            return val;
        }

        public String Decrypt(String textToDecrypt)
        {
            if (textToDecrypt.Length % 2 != 0)
            {
                throw new Exception("Invalid text to decrypt");
            }

            String val = textToDecrypt;
            String decString = String.Empty;
            for (int i = 0; i < val.Length; i = i + 2)
            {
                String highNibble = DecimalToBinary((byte)(cipherString.IndexOf(val.Substring(i, 1)))).Substring(4);
                String lowNibble = DecimalToBinary((byte)(cipherString.IndexOf(val.Substring(i + 1, 1)))).Substring(4);
                char ok = (char)(Convert.ToInt16(highNibble + lowNibble, 2));
                decString += (char)(ok ^ key[(i / 2) % key.Length]);
            }

            return decString;
        }

        public String DecimalToBinary(byte decNumber)
        {
            int maxSize = (sizeof(byte)) * 8;
            String val = String.Empty;
            byte myVal = (byte)decNumber;

            for (int i = 0; i < maxSize; i++)
            {
                val = "" + (myVal % 2 == 0 ? 0 : 1) + val;
                myVal = (byte)(myVal / 2);
            }
         
            return val;
        }
    }

Age Calculator - Calculating difference between dates

Dear friends in most of the cases you need to work on dates. I had been stuck while calculating exact age of a person or total experience i...