Click here to Skip to main content
Licence CPOL
First Posted 24 Jun 2008
Views 12,017
Downloads 320
Bookmarked 24 times

TimeTracker

By | 24 Jun 2008 | Article
Tool to trace the login and logoff time for HR

Introduction

This tool can be use by any organisation to trace the employee entry and exit time. The data will be stored on the SQL database. If you want to implement this tool in your organisation, please leave me a message on the board below.

Background

There is a separate report generator engine which can be customized and can help to search the data in different ways. such as an introduction to the basic ideas presented?

Using the 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.Windows.Forms.ComponentModel.Com2Interop;
using System.Runtime.InteropServices;
using System.Net;

namespace BetaTimeTracker
{
    public partial class Form1 : Form
    {

        [DllImport("Advapi32.dll", EntryPoint = "GetUserName",ExactSpelling = false,
            SetLastError = true)]
        //Dll to lock the computer
        

        static extern bool GetUserName(
    [MarshalAs(UnmanagedType.LPArray)] byte[] lpBuffer,
    [MarshalAs(UnmanagedType.LPArray)] Int32[] nSize);


        string IP, username, machinename;
        static long transactionID;

        /// <summary />
        /// 
        /// </summary />
//public static extern int SetWindowPos(int hwnd, int hWndInsertAfter, int x, int y,
//int cx, int cy, int wFlags);
        public Form1()
        {
            InitializeComponent();
        }
       static int h, m, s;
        private void Form1_Load(object sender, EventArgs e)
        {
            h = 0;
            m = 0;
            s = 0;

            //int hWndInsertAfter;
            
            //hWndInsertAfter = HWND_TOPMOST;

            this.TopMost = true;

            //Di9splaying user name
            byte[] str = new byte[256];
            Int32[] len = new Int32[1];
            len[0] = 256;
            GetUserName(str, len);
            //MessageBox.Show(System.Text.Encoding.ASCII.GetString(str));
            string a;
            a = System.Security.Principal.WindowsIdentity.GetCurrent().Name.ToString();

            //MessageBox.Show("User Name : " +a.ToString());

            username = a.ToString();

            //Displaying Computer name


            String strHostName;
            strHostName = System.Net.Dns.GetHostName()   ;// DNS.GetHostName();
            //MessageBox.Show("Host Name= " + strHostName);

            machinename = strHostName;
            

            //Displaying IP Address;

            strHostName = "";
            strHostName = System.Net.Dns.GetHostName();
            IPHostEntry ipEntry = System.Net.Dns.GetHostEntry(strHostName);
            IPAddress[] addr = ipEntry.AddressList;
           // MessageBox.Show (addr[addr.Length - 1].ToString());
            IP = addr[addr.Length - 1].ToString();

            //Displaying the current date;

            //MessageBox.Show(DateTime.Now.Date.ToString());

            //Displaying current time

           // MessageBox.Show(DateTime.Now.TimeOfDay.ToString());
            logintime.Text =DateTime.Now.TimeOfDay.Hours  +" : " +
                DateTime.Now.TimeOfDay.Minutes + " : " + DateTime.Now.TimeOfDay.Seconds;
            lbldate.Text = DateTime.Now.Date.Day.ToString() + "\\" +
                DateTime.Now.Month.ToString() + "\\" + DateTime.Now.Year.ToString(); ;

            register();
            createentry();
            
        }
        // Open the registration form...
        private void register()
        {
            try
            {

                System.Data.SqlClient.SqlConnection con;
                System.Data.SqlClient.SqlCommand cmd;
                System.Data.SqlClient.SqlDataReader dr;
                cmd = new System.Data.SqlClient.SqlCommand();
                con = new System.Data.SqlClient.SqlConnection(
                    "Data Source=192.168.20.11;Initial Catalog=betalogintime;user id=sa;" +
                    "pwd=Passw0rd;");
                cmd.CommandText = "select * from Timer_user where username='" +
                    username + "'";
                cmd.Connection = con;
                con.Open();
                dr = cmd.ExecuteReader();

                if (dr.Read())
                {
                }
                else
                {
                    Registration reg = new Registration();
                    reg.Show();
                }
                con.Close();
            }
            catch (Exception eexx)
            {
                MessageBox.Show(this, "There is some network Problem\n" + eexx.Message,
                    "Network Error",MessageBoxButtons.OK,MessageBoxIcon.Error);
            }
        }

       
 
        private void timer1_Tick(object sender, EventArgs e)
        {
            if (s < 60)
            {
                s = s + 1;
            }
            if (s==60)
            {
                m = m + 1;
                s = 0;
            }

            if (m == 60)
            {
                h = h + 1;
                m = 0;
            }
            time.Text = h + ":" + m + ":" + s;

        }

        private void formclosed()
        {
            
        }

        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            //MessageBox.Show(time.Text);
        }

        private void Form1_Deactivate(object sender, EventArgs e)
        {
           // MessageBox.Show(time.Text);
        }

        private void Form1_Leave(object sender, EventArgs e)
        {
            //MessageBox.Show(time.Text);
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            //MessageBox.Show(time.Text);
            
           // if (MessageBox.Show(this, "Do you really want to exit?", "Exit Timer",
           //System.Windows.Forms.MessageBoxButtons.YesNo,
           //System.Windows.Forms.MessageBoxIcon.Question) == 
           //System.Windows.Forms.DialogResult.Yes)
          //  {
                logoff();
          //  }
            

        }

        private void logoff()
        {
            try
            {

                System.Data.SqlClient.SqlConnection con;
                System.Data.SqlClient.SqlCommand cmd;
                System.Data.SqlClient.SqlDataReader dr;
                cmd = new System.Data.SqlClient.SqlCommand();
                //   dr=new System.Data.SqlClient.SqlDataReader();

                con = new System.Data.SqlClient.SqlConnection(
                    "Data Source=192.168.20.11;Initial Catalog=betalogintime;user id=sa;" +
                    "pwd=Passw0rd;");
                cmd.CommandText = "select tranid," +
                   "hitcount from Timer_transaction where tranid='" + transactionID + "'";
                cmd.Connection = con;
                con.Open();
                dr = cmd.ExecuteReader();

                if (dr.Read())
                {
                    int tranid, hitcount;
                    tranid = int.Parse(dr.GetValue(0).ToString());
                    hitcount = int.Parse(dr.GetValue(1).ToString());
                    con.Close();
                    hitcount = hitcount + 1;
                    cmd.CommandText = "Update Timer_transaction set timelogoff='" +
                         string.Format("{0:t}", DateTime.Now) +
                         "', Totaltimespent='" + time.Text + "', 
                         logoffdate='" + DateTime.Parse(DateTime.Now.Date.ToString()) +
                         "' where tranid='" + tranid + "'";
                    con.Open();
                    cmd.ExecuteNonQuery();
                    con.Close();
                }
            }
            catch (Exception exxx)
            {

            }
        }

        private void Form1_Resize(object sender, EventArgs e)
        {
            if (FormWindowState.Minimized == this.WindowState)
            {
                mynotifyIcon.Visible = true;
                mynotifyIcon.ShowBalloonTip(500);
               // mynotifyIcon.BalloonTipText = "Login Date :" + lbldate.Text + " |
               // Login Time :" + time.Text + " | User :" + username;
                this.Hide();
            }
            else if (FormWindowState.Normal == this.WindowState)
            {
                mynotifyIcon.Visible = false;
            }


        }

        private void mynotifyIcon_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            this.Visible = true;
            this.Activate();
            this.WindowState = FormWindowState.Normal;
            mynotifyIcon.Visible = false;

        }

        private void button1_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void createentry()
        {
            try
            {

                System.Data.SqlClient.SqlConnection con;
                System.Data.SqlClient.SqlCommand cmd;
                System.Data.SqlClient.SqlDataReader dr;
                cmd = new System.Data.SqlClient.SqlCommand();
                con = new System.Data.SqlClient.SqlConnection(
                    "Data Source=192.168.20.11;Initial Catalog=betalogintime;user id=sa;" +
                    "pwd=Passw0rd;");
                cmd.CommandText = "select tranid, hitcount, TotalTimeSpent,
                    Timelogin from Timer_transaction where date='" + 
                    DateTime.Now.Date + "' and username='" + username + "'";
                cmd.Connection = con;
                con.Open();
                dr = cmd.ExecuteReader();

                if (dr.Read())
                {
                    int tranid, hitcount;
                    tranid = int.Parse(dr.GetValue(0).ToString());
                    hitcount = int.Parse(dr.GetValue(1).ToString());
                    extracttime(dr.GetValue(2).ToString());
                    time.Text = h + ":" + m + ":" + s;
                    logintime.Text = string.Format("{0:t}",
                        Convert.ToDateTime(dr.GetValue(3))).ToString();


                    // MessageBox.Show(dr.GetValue(2).ToString());

                    con.Close();
                    hitcount = hitcount + 1;

                    cmd.CommandText = "Update Timer_transaction set hitcount='" +
                        hitcount + "', totaltimespent='" + time.Text +
                        "' where tranid='" + tranid + "'";
                    con.Open();
                    cmd.ExecuteNonQuery();
                    con.Close();
                    fetchTransactionID();
                }
                else
                {
                    con.Close();
                    con.Open();// logintime.Text = string.Format("{0:t}",
                        Convert.ToDateTime(dr.GetValue(3))).ToString();
                    cmd.CommandText = "Insert into timer_transaction values('" +
                        username + "','" + IP + "','" + machinename + "','" +
                        DateTime.Parse(DateTime.Now.Date.ToString()) + "','" +
                        string.Format("{0:t}", DateTime.Now) + "','" +
                        string.Format("{0:t}", DateTime.Now) + "','0:0:0" + "','1','')";
                    cmd.ExecuteNonQuery();
                    fetchTransactionID();
                    logintime.Text = string.Format("{0:t}", DateTime.Now).ToString();

                }
                con.Close();

            }
            catch (Exception eexxx)
            {
                MessageBox.Show(eexxx.Message);
                this.Close();
            }
        }
        private void fetchTransactionID()
        {
            System.Data.SqlClient.SqlConnection con;
            System.Data.SqlClient.SqlCommand cmd;
            System.Data.SqlClient.SqlDataReader dr;
            cmd = new System.Data.SqlClient.SqlCommand();
            con = new System.Data.SqlClient.SqlConnection(
                "Data Source=192.168.20.11;Initial Catalog=betalogintime;user id=sa;" +
                "pwd=Passw0rd;");
            cmd.CommandText = "select tranid from Timer_transaction where date='" +
                DateTime.Now.Date + "' and username='" + username + "'";
            cmd.Connection = con;
            con.Open();
            dr = cmd.ExecuteReader();
            if (dr.Read())
            {
                transactionID =long.Parse(dr[0].ToString());
               // MessageBox.Show(transactionID.ToString());
            }

        }

        private void Refress_Tick(object sender, EventArgs e)
        {
            logoff();
        }

        private void Form1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (FormWindowState.Normal == this.WindowState)
            {
                mynotifyIcon.Visible = true;
                mynotifyIcon.BalloonTipText = "Login Date :" +
                    lbldate.Text + "\n\n Login Time :" + logintime.Text +
                    "\n\n User :" + username;
                mynotifyIcon.ShowBalloonTip(1500);
                this.Hide();
            }
            else if (FormWindowState.Normal == this.WindowState)
            {
                mynotifyIcon.Visible = false;
            }

        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show(this, "Do you really want to exit?", "Exit Timer",
                System.Windows.Forms.MessageBoxButtons.YesNo,
                System.Windows.Forms.MessageBoxIcon.Question) ==
                System.Windows.Forms.DialogResult.Yes)
            {
                logoff();
                this.Close();
            }
        }

        private void extracttime(string tim)
        {
            string str1, str2;
            string[] totaltime;
            totaltime = new string[3];// = new string(3);
            int i, j;
            j = 0;
            i = 0;
            str2 = "";
            for (i = 0; i < tim.Length; i++)
            {
                str1 = tim.Substring(i, 1);
                if (str1 != ":")
                {
                    str2 = str2 + str1;
                }
                else
                {
                    totaltime[j] = str2;
                    str2 = "";
                    j++;
                }
                totaltime[j] = str2;

            }
            //MessageBox.Show(totaltime[0] + totaltime[1] + totaltime[2]);
            try
            {

                h = int.Parse(totaltime[0]);
                m = int.Parse(totaltime[1]);
                s = int.Parse(totaltime[2]);
            }
            catch (Exception eexx)
            {
                MessageBox.Show(eexx.Message);
                h = 0;
                m = 0;
                s = 0;
            }

        }
        
        
    }
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Sanjay Gupta1011



Unknown

Member



Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
QuestionTimeTracker PinmemberMafise0:26 21 Jul '11  
GeneralMy vote of 5 PinmemberVampireBing14:54 18 Nov '10  
GeneralNeed complete abstract of your project Pinmemberparacharan3:03 12 Jul '09  
GeneralFormatting PinmemberAbhijit Jana2:18 24 Jun '08  
QuestionIs the Enter key on your keyboard missing? PinmemberZoltan Balazs1:01 24 Jun '08  

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Mobile
Web02 | 2.5.120517.1 | Last Updated 24 Jun 2008
Article Copyright 2008 by Sanjay Gupta1011
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid