// Added By JK on 01/09/12
        // Moved the code from Shell.xaml.cs to ModuleSelectionPresenter as the client wants
        // the Dispatcher to start even if the connection to backend is not established.
        private void Logon()
        {
            if (log.IsInfoEnabled) log.Info("Initiating Log on");
            int maxTime = (ConfigurationManager.AppSettings["MaxTurnTime"] == null) ? 20 : int.Parse(ConfigurationManager.AppSettings["MaxTurnTime"]);
            LogOnKioskResponse logonResponse = new LogOnKioskResponse();
            LogonServiceClient logonproxy = null;
            DateTime dtBeforeLogon, dtafterLogon, newDateTime;
            TimeSpan timeDiff;
            try
            {
                ValidateCertificate.RegisterCallback();
                logonproxy = new LogonServiceClient();

                if (log.IsInfoEnabled) log.Info("Requesting for Log on");
                dtBeforeLogon = DateTime.Now;
                logonResponse = logonproxy.LogOnKiosk(new LogOnKioskRequest
                {
                    KioskId = Int32.Parse(KioskAppConfig.KioskId),
                    StatusUpdated = DateTime.UtcNow,
                    ReleaseVersion = KioskAppConfig.CurrentVersion
                });

                dtafterLogon = DateTime.Now;
                timeDiff = dtafterLogon.Subtract(dtBeforeLogon);
                if (log.IsInfoEnabled) log.InfoFormat("Hours: {0}, Mins: {1} Sec: {2} Days:{3}", timeDiff.Hours, timeDiff.Minutes, timeDiff.Seconds, timeDiff.Days);
                if (log.IsInfoEnabled) log.Info("Requesting for Log on completed");

                if (!string.IsNullOrEmpty(logonResponse.XXX12))
                {
                    try
                    {
                        RegistryKey pRegKey = Registry.LocalMachine;
                        pRegKey = pRegKey.OpenSubKey("SOFTWARE\\USPInc");

                        SHA256 hasher = SHA256Managed.Create();
                        byte[] hashedData = hasher.ComputeHash(
                            Encoding.Unicode.GetBytes(logonResponse.XXX12));
                        StringBuilder sb = new StringBuilder();
                        foreach (byte b in hashedData)
                        {
                            sb.AppendFormat("{0:x2}", b);
                        }

                        pRegKey.SetValue("xxx23", sb.ToString(), RegistryValueKind.String);
                    }
                    catch (Exception ex)
                    {
                        if (log.IsErrorEnabled) log.ErrorFormat("Set xxx12 error : {0}", ex.Message);
                    }
                }

                logonResponse.isLoggedOn = true;
                if (logonResponse.isLoggedOn)
                {
                    if (log.IsInfoEnabled) log.Info("Kiosk Logged on");
                    //Populate Service List

                    KioskAppConfig.KioskServices = new List<Infrastructure.ObjectModel.KioskService>();
                    KioskAppConfig.KioskDevices = new List<Infrastructure.ObjectModel.KioskDevice>();
                    KioskAppConfig.KioskLocation = logonResponse.KioskLocation;
                    isMonitored = logonResponse.isMonitored;

                    if (timeDiff.Seconds >= 0 &&
                    timeDiff.Seconds <= maxTime)
                    {
                        if (log.IsInfoEnabled) log.InfoFormat("Kiosk Logged on between the turnaround time with time : {0}",logonResponse.CurrentTimeStamp);
                        timeDiff = TimeSpan.FromTicks(timeDiff.Ticks / 2);
                        newDateTime = Convert.ToDateTime(logonResponse.CurrentTimeStamp);//.ToLocalTime();
                        newDateTime.Add(timeDiff);

                        //admin Change the system time
                        if (log.IsInfoEnabled) log.Info("Synchronizing System Time");
                        SYSTEMTIME SysTime = new SYSTEMTIME();
                        SysTime.wYear = (short)newDateTime.Year;
                        SysTime.wMonth = (short)newDateTime.Month;
                        SysTime.wDay = (short)newDateTime.Day;
                        SysTime.wHour = (short)newDateTime.Hour;
                        SysTime.wMinute = (short)newDateTime.Minute;
                        SysTime.wSecond = (short)newDateTime.Second;
                        bool res = SetSystemTime(ref SysTime);

                        if (!res)
                        {
                            if (log.IsErrorEnabled) log.Error("System Time not changed Successfully");
                        }
                        else
                        {
                            if (log.IsInfoEnabled) log.Info("Changed System Time Successfully");
                        }
                    }

                       //this.Transaction.KioskServices = null;

                    foreach (MBMEKiosk.LogonProxy.KioskService service in logonResponse.BillerServiceList)
                    {
                        MBMEKiosk.Infrastructure.ObjectModel.KioskService item = new MBMEKiosk.Infrastructure.ObjectModel.KioskService()
                        {
                            BillerServiceId = service.BillerServiceId,
                            ServiceKey = service.ServiceKey,
                            ActivationDate = service.ActivationDate,
                            Available = service.Available,
                            BillerServiceName = service.BillerServiceName,
                            KioskId = service.KioskId,
                            KioskRefNum = service.KioskRefNum
                        };
                        KioskAppConfig.KioskServices.Add(item);
                    }

                    //Populate Device List
                    foreach (MBMEKiosk.LogonProxy.KioskDevice device in logonResponse.DeviceList)
                    {
                        MBMEKiosk.Infrastructure.ObjectModel.KioskDevice item = new MBMEKiosk.Infrastructure.ObjectModel.KioskDevice()
                        {
                            DeviceId = device.DeviceId,
                            //KioskDeviceId = device.KioskDeviceId,
                            DeviceKey = device.DeviceKey,
                            DeviceEnabled = device.DeviceEnabled,
                            DeviceName = device.DeviceName,
                            KioskId = device.KioskId,
                            KioskRefNum = device.KioskRefNum
                        };

                        KioskAppConfig.KioskDevices.Add(item);
                        if (log.IsInfoEnabled) log.Info("Machine Location retrieved is:" + KioskAppConfig.KioskLocation + ",MachineId:" + KioskAppConfig.KioskId);
                    }

                    // Modified By JK on 01/09/12
                    // Previously the developer had put AND condition but has been replaced with OR.
                    if ((logonResponse.BillerServiceList.Length == 0) &&
                        (logonResponse.DeviceList.Length == 0))
                    {
                        if (log.IsInfoEnabled) log.Info("Kiosk logged on not successful");
                        loggedOn = false;
                        if (log.IsInfoEnabled) log.Info("No Biller Service or Device configured for this Kiosk.");
                    }
                    else
                    {
                        loggedOn = true;
                        if (log.IsInfoEnabled) log.Info("Kiosk logged on successfull");
                        //initialize Devices
                        objKiosk.Name = ConfigurationManager.AppSettings["KDeviceId"].ToString(); ;

                        objPrinter.Name = ConfigurationManager.AppSettings["PDeviceId"].ToString();

                        objCashAcceptor.Name = ConfigurationManager.AppSettings["CADeviceId"].ToString();

                        var kioskDevice = (from A in KioskAppConfig.KioskDevices
                                           where A.DeviceName.Equals(objKiosk.Name)
                                           select A.DeviceId).SingleOrDefault();

                        objKiosk.DeviceId = kioskDevice.ToString();

                        var printerDevice = (from A in KioskAppConfig.KioskDevices
                                             where A.DeviceName.Equals(objPrinter.Name)
                                             select A.DeviceId).SingleOrDefault();

                        objPrinter.DeviceId = printerDevice.ToString();

                        var cashAcceptorDevice = (from A in KioskAppConfig.KioskDevices
                                                  where A.DeviceName.Equals(objCashAcceptor.Name)
                                                  select A.DeviceId).SingleOrDefault();

                        objCashAcceptor.DeviceId = cashAcceptorDevice.ToString();

                        if (connectivityPolling)
                        {
                            //if (isMonitored)
                            RestartConnectivityTimer();
                            //if (monitorClient == null)
                            //  monitorClient.CheckBackendConnectivityCompleted += new EventHandler<CheckBackendConnectivityCompletedEventArgs>(monitorClient_CheckBackendConnectivityCompleted);
                        }
                        if (shutdownCommandActive)
                            RestartShutdownTimer();
                    }
                }
            }
            catch (Exception ex)
            {
                loggedOn = false;
                if (logonproxy != null)
                    logonproxy.Abort();
                if (log.IsErrorEnabled) log.ErrorFormat("Kiosk logon unsuccessfull: {0} {1}", DateTime.Now.ToString(), ex.Message);
            }
            finally
            {
                if (!loggedOn)
                    RestartLogonTimer();
                if (logonproxy != null)
                    logonproxy.Close();
                ValidateCertificate.DeregisterCallback();
            }
        }
        private void LoadUtilities()
        {
            MBMEKiosk.LogonProxy.UpdateUtilityRequest utility = null;
                List<MBMEKiosk.LogonProxy.UpdateUtilityRequest> utilities = new List<LogonProxy.UpdateUtilityRequest>();
                LogonServiceClient logonproxy = null;
                try
                {
                    string relativePath = ConfigurationManager.AppSettings["ModulesPath"] != null ? ConfigurationManager.AppSettings["ModulesPath"] : "modules";
                    String[] astrLoadableFiles = Directory.GetFiles(relativePath, "*.dll");
                    ValidateCertificate.RegisterCallback();
                    logonproxy = new LogonServiceClient();

                    Assembly assembly = null;
                    foreach (String strFile in astrLoadableFiles)
                    {
                        try
                        {
            #if DEBUG
                    assembly = Assembly.LoadFrom(strFile);
            #else
                            try
                            {
                                utility = new LogonProxy.UpdateUtilityRequest();
                                assembly = Assembly.LoadFrom(strFile);

                                Version dllVersion = assembly.GetName().Version;
                                utility.Version = dllVersion.ToString();
                                utility.UtilityName = assembly.ManifestModule.Name;
                                utility.DateModified = new System.IO.FileInfo(strFile).LastWriteTime;
                                utility.Size = new System.IO.FileInfo(strFile).Length;
                                utilities.Add(utility);
                            }
                            catch (IOException ioex)
                            {
                                Trace.TraceError("Warning! Error loading file LoadUtilities \r\n\r\n{0}\r\n\r\n{1}\r\n\r\n{2}", ioex.Message, ioex.Source, ioex.StackTrace);
                                if (log.IsErrorEnabled) log.ErrorFormat(" Warning! Error loading file in LoadUtilities  {0} {1}", DateTime.Now.ToString(), ioex.Message);
                            }
                            catch (Exception ex)
                            {
                                Trace.TraceError("Error! Error loading file.\r\n\r\n{0}\r\n\r\n{1}\r\n\r\n{2}", ex.Message, ex.Source, ex.StackTrace);
                                if (log.IsErrorEnabled) log.ErrorFormat("Error! Error loading file in LoadUtilities  {0} {1}", DateTime.Now.ToString(), ex.Message);
                            }
            #endif
                        }
                        catch (BadImageFormatException ex)
                        {
                            // Assembly was not a valid assembly or it targets a later version of .NET framework than is loaded.
                            if (log.IsErrorEnabled) log.ErrorFormat("Caught BadImageFormatException in LoadUtilities  {0} {1}", DateTime.Now.ToString(), ex.Message);
                            continue;
                        }
                    }

                    if(File.Exists(CMEXEPATH))
                    {
                        assembly = Assembly.LoadFrom(CMEXEPATH);

                        utility = new LogonProxy.UpdateUtilityRequest();
                        Version dllVersion = assembly.GetName().Version;
                        utility.Version = dllVersion.ToString();
                        utility.UtilityName = assembly.ManifestModule.Name;
                        utility.DateModified = new System.IO.FileInfo(CMEXEPATH).LastWriteTime;
                        utility.Size = new System.IO.FileInfo(CMEXEPATH).Length;
                        utilities.Add(utility);
                    }
                    else
                        if (log.IsInfoEnabled) log.InfoFormat("MBMEContentManager.exe not found in LoadUtilities  {0}", DateTime.Now.ToString());

                    if(File.Exists(KIOSKEXEPATH))
                    {
                        assembly = Assembly.LoadFrom(KIOSKEXEPATH);

                        utility = new LogonProxy.UpdateUtilityRequest();
                        Version dllVersion = assembly.GetName().Version;
                        utility.Version = dllVersion.ToString();
                        utility.UtilityName = assembly.ManifestModule.Name;
                        utility.DateModified = new System.IO.FileInfo(KIOSKEXEPATH).LastWriteTime;
                        utility.Size = new System.IO.FileInfo(KIOSKEXEPATH).Length;
                        utilities.Add(utility);
                    }
                    else
                        if (log.IsInfoEnabled) log.InfoFormat("MBMEKiosk.exe not found in LoadUtilities  {0}", DateTime.Now.ToString());

                    if(File.Exists(WATCHDOGEXEPATH))
                    {
                        assembly = Assembly.LoadFrom(WATCHDOGEXEPATH);

                        utility = new LogonProxy.UpdateUtilityRequest();
                        Version dllVersion = assembly.GetName().Version;
                        utility.Version = dllVersion.ToString();
                        utility.UtilityName = assembly.ManifestModule.Name;
                        utility.DateModified = new System.IO.FileInfo(WATCHDOGEXEPATH).LastWriteTime;
                        utility.Size = new System.IO.FileInfo(WATCHDOGEXEPATH).Length;
                        utilities.Add(utility);
                    }
                    else
                        if (log.IsInfoEnabled) log.InfoFormat("MBMEWatchDog.exe not found in LoadUtilities  {0}", DateTime.Now.ToString());

                    if (logonproxy != null && utilities.Count() > 0)
                        logonproxy.LogOnUpdateUtilityAsync(Int32.Parse(KioskAppConfig.KioskId), utilities.ToArray());

                }
                catch (Exception ex)
                {
                    if (logonproxy != null)
                        logonproxy.Abort();
                    if (log.IsErrorEnabled) log.ErrorFormat("LoadUtilities  unsuccessfull: {0} {1}", DateTime.Now.ToString(), ex.Message);
                }
                finally
                {
                    if (logonproxy != null)
                        logonproxy.Close();
                    ValidateCertificate.DeregisterCallback();
                }
        }