How to fix issue of zkemkeeper.dll realtime events inside windows service?

1.4k Views Asked by At

i'm setting up windows service and want it to sync the device attendance to SQL Server database using zkemkeeper real time event. i have successfully created service as well as tested the service on my local system which run windows 10 and another one window 8 service work fine and sync the attendance record to DB server at real time. Now after successful testing on local system i deployed service over production server where service successfully established the connection with device but it didn't respond to Real time event for testing purpose i have created winform app and run it over the server and find out it is working and listening to real time event but i need service to work properly not win form application any help will be appreciated thanks below is my code !

public partial class AttendanceSyncService_405 : ServiceBase
    {
        public AttendanceSyncService_405()
        {
            InitializeComponent();
        }
        System.Timers.Timer timer = new System.Timers.Timer();
        public zkemkeeper.CZKEMClass axCZKEM1 = new zkemkeeper.CZKEMClass();
        private bool bIsConnected = false;//the boolean value identifies whether the device is connected
        private int iMachineNumber = 1;//the serial number of the device.After connecting the device ,this value will be changed.

        protected override void OnStart(string[] args)
        {
            //var thread = new Thread();
            //thread.SetApartmentState(ApartmentState.STA);
            //thread.Start();
            WriteToFile("Service is started at " + DateTime.Now);
            Connect();


            // LoadCurrentMonthAtt();
            timer.Elapsed += new ElapsedEventHandler(OnElapsedTime);
            timer.Interval = 900000; //number in milisecinds  
            timer.Enabled = true;
        }

        protected override void OnStop()
        {
            WriteToFile("Service is stopped at " + DateTime.Now);
        }


        private void OnElapsedTime(object source, ElapsedEventArgs e)
        {
            if (bIsConnected == true)
            {
                WriteToFile("Service recall at " + DateTime.Now);
                WriteToFile("Device Status Connected at " + DateTime.Now);
            }
            else
            {
                WriteToFile("Device Status DisConnected at " + DateTime.Now);
                WriteToFile("Service recall at " + DateTime.Now);
                Connect();
            }
        }



        public void WriteToFile(string Message)
        {
            string path = AppDomain.CurrentDomain.BaseDirectory + "\\Logs";
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            string filepath = AppDomain.CurrentDomain.BaseDirectory + "\\Logs\\ServiceLog_" + DateTime.Now.Date.ToShortDateString().Replace('/', '_') + ".txt";
            if (!File.Exists(filepath))
            {
                // Create a file to write to.   
                using (StreamWriter sw = File.CreateText(filepath))
                {
                    sw.WriteLine(Message);
                }
            }
            else
            {
                using (StreamWriter sw = File.AppendText(filepath))
                {
                    sw.WriteLine(Message);
                }
            }
        }
        private void Connect()
        {
            try
            {

                int idwErrorCode = 0;


                bIsConnected = axCZKEM1.Connect_Net("192.168.0.177", 4370);
                if (bIsConnected == true)
                {
                    this.axCZKEM1.OnAttTransactionEx += new zkemkeeper._IZKEMEvents_OnAttTransactionExEventHandler(axCZKEM1_OnAttTransactionEx);
                    iMachineNumber = 1;
                    if (axCZKEM1.RegEvent(iMachineNumber, 65535))//Here you can register the realtime events that you want to be triggered(the parameters 65535 means registering all)
                    {
                        this.axCZKEM1.OnAttTransactionEx += new zkemkeeper._IZKEMEvents_OnAttTransactionExEventHandler(axCZKEM1_OnAttTransactionEx);
                    }
                    else
                    {
                        WriteToFile("RT Events didn't registered at " + DateTime.Now);
                    }
                    axCZKEM1.RegEvent(iMachineNumber, 65535);//Here you can register the realtime events that you want to be triggered(the parameters 65535 means registering all)
                    WriteToFile("Device Connection Established Successfully at " + DateTime.Now);
                }
                else
                {
                    axCZKEM1.GetLastError(ref idwErrorCode);
                    WriteToFile("Unable to connect the device,ErrorCode=" + idwErrorCode.ToString() + " at " + DateTime.Now);
                }
            }
            catch(Exception ex)
            {
                WriteToFile("Exception :" + ex.Message + " at " + DateTime.Now);

            }
        }

        private void axCZKEM1_OnAttTransactionEx(string sEnrollNumber, int iIsInValid, int iAttState, int iVerifyMethod, int iYear, int iMonth, int iDay, int iHour, int iMinute, int iSecond, int iWorkCode)
        {
            DateTime Attendancedate = new DateTime(iYear, iMonth, iDay, iHour, iMinute, iSecond);
            string row = sEnrollNumber + "," + Attendancedate.ToString();
            WriteToFile("Attendane :" + row + "  Marked At: " + DateTime.Now);
            if (bIsConnected == false)
            {
                Connect();
                return;
            }

            decimal empserial = decimal.Parse(sEnrollNumber);
            attInsert(empserial, Attendancedate);


        }

        private void attInsert(decimal empserial, DateTime Attendancedate)
        {
            try
            {
                WriteToFile("Attendance Entry Arrived for EMP-Serial :" + empserial + " At: " + DateTime.Now + " for Insertion");
                DBAccess db = new DBAccess();
                DataSet attCount = db.GetDataSetFromQuery("select Count(att.[todayCount]) as attCount from tblAttendance att where (att.attDate = Convert(date,GETDATE()) AND att.fkSerial ='" + empserial.ToString() + "')");
                int count = int.Parse(attCount.Tables[0].Rows[0]["attCount"].ToString());
                Boolean INOUT = (count % 2 == 0) ? true : false;
                WriteToFile("Attendane Count :" + count + " & In/Out : " + INOUT + "  Marked At: " + DateTime.Now);
                db.Parameters.AddWithValue("fkSerial", empserial);
                db.Parameters.AddWithValue("attTerminalId", "Time1");
                db.Parameters.AddWithValue("attDateTime", Attendancedate);
                db.Parameters.AddWithValue("attTgId", 3);
                db.Parameters.AddWithValue("attINOUT", INOUT);
                db.Parameters.AddWithValue("attEmpCode", "no need");
                db.ExecuteNonQuery("spInsertAttendance");
                WriteToFile("Attendance Inserted of EMP-Serial :" + empserial + " At: " + DateTime.Now);


            }
            catch (Exception ex)
            {
                WriteToFile("Exception in insert method  :" + ex.Message + " At: " + DateTime.Now);
            }

        }

    }
1

There are 1 best solutions below

0
On

Type This Code in Your IntializeComponent and it will respond to realtime events

private void InitializeComponent()
{
    Thread createComAndMessagePumpThread = new Thread(() =>
    {
        axCZKEM1 = new zkemkeeper.CZKEMClass();
        bool connSatus = axCZKEM1.Connect_Net(192.168.0.177, 4370);
        if (connSatus == true)
        {

            this.axCZKEM1.OnAttTransactionEx -= new zkemkeeper._IZKEMEvents_OnAttTransactionExEventHandler(axCZKEM1_OnAttTransactionEx);

            if (axCZKEM1.RegEvent(1, 65535))//Here you can register the realtime events that you want to be triggered(the parameters 65535 means registering all)
            {

                this.axCZKEM1.OnAttTransactionEx += new zkemkeeper._IZKEMEvents_OnAttTransactionExEventHandler(axCZKEM1_OnAttTransactionEx);

            }
        }
        Application.Run();
    });

    createComAndMessagePumpThread.SetApartmentState(ApartmentState.STA);

    createComAndMessagePumpThread.Start();
    components = new System.ComponentModel.Container();
    this.ServiceName = "Service1";
}