private void ClearRequestCountersToServiceIniFile()
        {
            try
            {
                IniFile ini = new IniFile(ServiceIniFilename);

                ini.IniRemoveKey("Statistics", "Date"); // zet stats op gisteren met allemaal 0 waardes
                ini.IniRemoveKey("Statistics", "GlobalNumberOfRequests");

                foreach (KeyValuePair <string, UserAccount> kvp in UserAccountManager.CloneUserDatabase())
                {
                    // verwijder de "key"
                    ini.IniRemoveKey("Statistics", string.Format("{0}_NumberOfRequests", kvp.Key));
                } //foreach
            }
            catch
            {
            }
        }
        private void WriteRequestCountersToServiceIniFile()
        {
            try
            {
                IniFile ini = new IniFile(ServiceIniFilename);

                ini.IniWriteValue("Statistics", "Date", DateTime.Now.ToString("yyyy-MM-dd"));
                ini.IniWriteValue("Statistics", "GlobalNumberOfRequests", UserAccountManager.GlobalNumberOfRequests.ToString());

                // Nu per gebruiker stats wegschrijven
                foreach (KeyValuePair <string, UserAccount> kvp in UserAccountManager.CloneUserDatabase())
                {
                    // voor het uitlezen hebben we genoeg aan de "clone" vane de user gegevens
                    ini.IniWriteValue("Statistics", string.Format("{0}_NumberOfRequests", kvp.Key), kvp.Value.NumberOfRequests.ToString());
                } //foreach
            }
            catch
            {
            }
        }
        /// <summary>
        /// </summary>
        /// <returns></returns>
        public Message Version()
        {
            string errorMessage;

            if (!UserAccountManager.HasAccess(UserAccountManager.CurrentAccessGroup, out errorMessage, true))
            {
                return(ServiceHelper.SendErrorMessage(ResultErrorCode.AuthorizationError, errorMessage));
            }
            UserAccountManager.GlobalNumberOfRequestsInc();

            Version version = Assembly.GetExecutingAssembly().GetName().Version;

            XElement xResult = ServiceHelper.CreateRoot(ResultErrorCode.OK);

            xResult.Add(new XElement("Version", String.Format("{0:0}.{1:00}.{2:0000}", version.Major, version.Minor, version.Build)));
            xResult.Add(new XElement("ClientIP", ServiceHelper.CurrentClientIP));
            xResult.Add(new XElement("AuthenticatedUsername", UserAccountManager.CurrentBasicAuthenticatedUsername));
            xResult.Add(new XElement("ServerName", Environment.MachineName));

            return(Message.CreateMessage(MessageVersion.None, "", new XElementBodyWriter(xResult)));
        }
        public Message FingerprintRecognize(Stream stream)
        {
            string errorMessage;

            if (!UserAccountManager.HasAccess(UserAccountManager.CurrentAccessGroup, out errorMessage, true))
            {
                return(ServiceHelper.SendErrorMessage(ResultErrorCode.AuthorizationError, errorMessage));
            }
            UserAccountManager.GlobalNumberOfRequestsInc();

            XElement xResult = null;

            try
            {
                QueryString qs          = new QueryString(stream);
                string      fingerprint = qs["Fingerprint"];
                string      reliabilty  = qs["Reliabilities"];

                using (FingerprintSignature fsQuery = new FingerprintSignature("UNKNOWN", 0, System.Convert.FromBase64String(fingerprint), 0, true))
                {
                    fsQuery.Reliabilities = System.Convert.FromBase64String(reliabilty);

                    LuceneIndex subFingerIndex = LuceneIndexes.IndexSubFingerprint;
                    try
                    {
                        // We moeten hier al locken aangezien de audiofingerprint library geen weet heeft van onze
                        // LuceneIndex object
                        subFingerIndex.Lock();
                        using (SubFingerprintQuery query = new SubFingerprintQuery(subFingerIndex.Index))
                        {
                            Resultset answer = query.MatchAudioFingerprint(fsQuery, 2300);

                            if (answer != null)
                            {
                                xResult = ServiceHelper.CreateRoot(ResultErrorCode.OK);

                                xResult.Add(new XElement("RecognizeResult",
                                                         new XAttribute("RecognizeCode", 0),
                                                         "OK"));

                                XElement xTimeStatistics = new XElement("TimeStatistics");
                                xTimeStatistics.Add(new XElement("TotalQueryTime",
                                                                 new XAttribute("Unit", "ms"),
                                                                 (int)answer.QueryTime.TotalMilliseconds));
                                xTimeStatistics.Add(new XElement("SubFingerQueryTime",
                                                                 new XAttribute("Unit", "ms"),
                                                                 (int)answer.FingerQueryTime.TotalMilliseconds));
                                xTimeStatistics.Add(new XElement("FingerLoadTime",
                                                                 new XAttribute("Unit", "ms"),
                                                                 (int)answer.FingerLoadTime.TotalMilliseconds));
                                xTimeStatistics.Add(new XElement("MatchTime",
                                                                 new XAttribute("Unit", "ms"),
                                                                 (int)answer.MatchTime.TotalMilliseconds));
                                xResult.Add(xTimeStatistics);

                                XElement xFingerTracks = new XElement("FingerTracks",
                                                                      new XAttribute("Count", 0));
                                xResult.Add(xFingerTracks);
                                if (answer.ResultEntries.Count > 0)
                                {
                                    // Gets a NumberFormatInfo associated with the en-US culture.
                                    System.Globalization.NumberFormatInfo nfi = new System.Globalization.CultureInfo("en-US", false).NumberFormat;
                                    nfi.CurrencySymbol           = "€";
                                    nfi.CurrencyDecimalDigits    = 2;
                                    nfi.CurrencyDecimalSeparator = ".";
                                    nfi.NumberGroupSeparator     = "";
                                    nfi.NumberDecimalSeparator   = ".";

                                    Dictionary <string, ResultEntry> dict = new Dictionary <string, ResultEntry>();
                                    int count = 0;
                                    foreach (ResultEntry item in answer.ResultEntries)
                                    {
                                        XElement xFingerTrack = new XElement("FingerTrack");
                                        xFingerTracks.Add(xFingerTrack);

                                        xFingerTrack.Add(new XAttribute("BER", item.Similarity.ToString()));
                                        xFingerTrack.Add(new XElement("DetectPosition",
                                                                      new XAttribute("Unit", "ms"),
                                                                      new XAttribute("InSec", string.Format(nfi, "{0:#0.000}", (item.Time.TotalMilliseconds / 1000))),
                                                                      (int)item.Time.TotalMilliseconds));

                                        XElement xSearchStrategy = new XElement("SearchStrategy");
                                        xFingerTrack.Add(xSearchStrategy);
                                        xSearchStrategy.Add(new XElement("IndexNumberInMatchList", item.IndexNumberInMatchList));
                                        xSearchStrategy.Add(new XElement("SubFingerCountHitInFingerprint", item.SubFingerCountHitInFingerprint));
                                        xSearchStrategy.Add(new XElement("SearchName", item.SearchStrategy.ToString()));
                                        xSearchStrategy.Add(new XElement("SearchIteration", item.SearchIteration));

                                        xFingerTrack.Add(new XElement("Reference", item.Reference.ToString()));
                                        xFingerTrack.Add(new XElement("FingerTrackID", item.FingerTrackID.ToString()));
                                        count++;
                                    } //foreach
                                    xFingerTracks.Attribute("Count").Value = count.ToString();
                                }
                            }
                            else
                            {
                                // Query geeft null waarde terug. Betekent dat er iets goed fout is gegaan
                                xResult = ServiceHelper.CreateRoot(ResultErrorCode.FAILED);
                            }

                            if (xResult != null)
                            {
                                return(Message.CreateMessage(MessageVersion.None, "", new XElementBodyWriter(xResult)));
                            }

                            // Als we hier komen dan hebben we geen resultaat
                            return(ServiceHelper.SendErrorMessage(ResultErrorCode.NoResultset, "No resultset"));
                        } //using
                    }
                    finally
                    {
                        subFingerIndex.UnLock();
                    }
                } //using
            }
            catch (Exception e)
            {
                CDRLogger.Logger.LogError(e);
                return(ServiceHelper.SendErrorMessage(ResultErrorCode.Exception, e.Message));
            }
            finally
            {
                GC.Collect();
            }
        }
        public void ExecuteTask()
        {
            while (UserAccountManager.WritingToUserDatabase)
            {
                Thread.Sleep(50);
            }

            accountingThreadStarted = true;
            IniFile ini = null;

            try
            {
                // Om maar 1x per uur robot task te draaien
                string webServiceURL = string.Format("http://{0}:{1}/", System.Net.Dns.GetHostName(), PortNumber).ToLower();

                // Lees de statistieken die we bij afsluiten programma hebben weggeschreven
                ini = new IniFile(ServiceIniFilename);
                try
                {
                    UserAccountManager.GlobalNumberOfRequests = Convert.ToInt64(ini.IniReadValue("Statistics", "GlobalNumberOfRequests"));

                    foreach (KeyValuePair <string, UserAccount> kvp in UserAccountManager.CloneUserDatabase())
                    {
                        // voor het uitlezen hebben we genoeg aan de "clone" vane de user gegevens
                        Int64 v = Convert.ToInt64(ini.IniReadValue("Statistics", string.Format("{0}_NumberOfRequests", kvp.Key)));
                        // Nu deze gebruiker gegevens opslaan
                        UserAccount ua = UserAccountManager.Account(kvp.Key);
                        if (ua != null)
                        {
                            ua.NumberOfRequests = v;
                        }
                    } //foreach
                }
                catch
                {
                }
                ini = null;
                ClearRequestCountersToServiceIniFile();

                // Vertel dat we verzoeken kunnen ontvangen. Is voornamelijk voor haproxy!
                Webservice.ForceServiceOffline = false;

                DateTime lastCheckIndex = DateTime.MinValue;
                DateTime lastReboot     = DateTime.Now.Date;
                while (accountingThreadStarted)
                {
                    try
                    {
                        if (Environment.UserInteractive)
                        {
                            // Laat op het scherm zien hoeveel request we binnen hebben.
                            int cLeft = Console.CursorLeft;
                            int cTop  = Console.CursorTop;
                            try
                            {
                                Console.WriteLine(string.Format("Global number of WebService Request : {0,-18}", UserAccountManager.GlobalNumberOfRequests));
                            }
                            finally
                            {
                                Console.CursorLeft = cLeft;
                                Console.CursorTop  = cTop;
                            }
                        }

                        if ((DateTime.Now - lastCheckIndex).TotalDays > 1)
                        {
                            lastCheckIndex = DateTime.Now.Date;

                            /*
                             * if ((DateTime.Now - ReceiveIndex.DateTimeOfIndex).TotalDays > 9)
                             * {
                             *  // Verstuur een mail dat de index te "oud" is
                             *  string message = string.Format("SubFingerindex on {0} is {1} days old", Environment.MachineName, (DateTime.Now - ReceiveIndex.DateTimeOfIndex).TotalDays);
                             *
                             *  Mail.SendMail(Mail.EMail_Automatisering, message, message);
                             * }
                             */
                        }

                        // ==========================================================================================================
                        // Moet de computer worden herstart?
                        // ==========================================================================================================
                        if ((DateTime.Now - lastReboot).TotalDays >= 7 && (DateTime.Now.DayOfWeek == DayOfWeek.Wednesday || DateTime.Now.DayOfWeek == DayOfWeek.Thursday))
                        {
                            Console.WriteLine();
                            Console.WriteLine("Rebooting computer...");
                            Program.RestartApplication = true; // zorg dat deze service wordt gestopt!
                            // Wacht 10 seconden
                            DateTime dt = DateTime.Now;
                            while (accountingThreadStarted && Program.ApplicationState != ApplicationState.Stopped)
                            {
                                Thread.Sleep(100);
                                if ((DateTime.Now - dt).TotalMilliseconds >= (10 * 1000))
                                {
                                    // Hoe dan ook stoppen na 10 seconden
                                    break;
                                }
                            } //while

                            accountingThreadStarted = false;
                            // Wacht 4 seconden!
                            Thread.Sleep(4 * 1000);
                            Console.WriteLine("Reboot signal send.");
                            RebootWindows.Reboot();
                            break;
                        }
                        // ==========================================================================================================

                        if (accountingThreadStarted)
                        {
                            waitEvent.WaitOne(5000, false); // na 5 seconden komen we hoe dan ook even tot leven
                        }
                    }
                    catch (Exception e)
                    {
                        CDRLogger.Logger.LogError(e);
                    }
                } //while

                // Save usage statistics for next run
                WriteRequestCountersToServiceIniFile();
            }
            finally
            {
                Thread.CurrentThread.Abort();
            }

            CDRLogger.Logger.LogInfo("Ending ExecuteTask();");
        }