protected override void OnStop()
        {
            CDRLogger.Logger.LogInfo("OnStop()");

            if (receiveIndex != null)
            {
                receiveIndex.Stop();
                receiveIndex = null;
            }

            CDRLogger.Logger.LogInfo("KillAccountingThread();");
            KillAccountingThread();

            Webservice.ForceServiceOffline = true;

            // stop service code goes here
            base.OnStop();

            CDRLogger.Logger.LogInfo("serviceMutex.ReleaseMutex();");
            if (serviceMutex != null)
            {
                if (serviceMutex.WaitOne(TimeSpan.Zero, true))
                {
                    serviceMutex.ReleaseMutex();
                    serviceMutex = null;
                }
            }

            if (hostHealthService != null && hostHealthService.State == CommunicationState.Opened)
            {
                hostHealthService.Close(new TimeSpan(0, 0, 10)); // sluiten na max 10 seconden
            }
            if (host != null && host.State == CommunicationState.Opened)
            {
                host.Close(new TimeSpan(0, 0, 10)); // sluiten na max 10 seconden
            }

            CDRLogger.Logger.LogInfo("SMTPLogging.Close();");
            SMTPLogging.Close();
            CDRLogger.Logger.LogInfo("LogUsage.Close();");
            LogUsage.Close();
        }
        protected override void OnStart(string[] args)
        {
            int portNumber = PortNumber;

            // Eerst controleren of we al niet draaien (vooral nodig voor commandline versie)
            string AppName = System.IO.Path.GetFileName(System.IO.Path.ChangeExtension(Assembly.GetExecutingAssembly().Location, null)) + portNumber.ToString();
            bool   serviceIsAlreadyRunningOnThisComputer = false;

            serviceMutex = new System.Threading.Mutex(true, AppName, out serviceIsAlreadyRunningOnThisComputer);
            if (serviceIsAlreadyRunningOnThisComputer)
            {
                serviceMutex = null;
                return;
            }

            // Force opening of indexs
            if (LuceneIndexes.IndexSubFingerprint.Index != null)
            {
                ;
            }


            // Run the service version here
            //  NOTE: If you're task is long running as is with most
            //  services you should be invoking it on Worker Thread
            //  !!! don't take to long in this function !!!
            base.OnStart(args);
            // http://www.leastprivilege.com/PermaLink.aspx?guid=b0ed39eb-01d9-4711-8d38-92d932e2e8c3
            // http://stackoverflow.com/questions/660445/basic-authentication-with-wcf-rest-service-to-something-other-than-windows-accoun
            // http://wcfrestcontrib.codeplex.com/

            // http://bytes.com/topic/net/answers/585032-wcf-username-authentication
            try
            {
                string uri = string.Format("http://{0}:{1}/", System.Net.Dns.GetHostName(), portNumber);

                // using (ServiceHost host = new ServiceHost(typeof(Service), new Uri("http://localhost:8000/"))) // dit is voor SOAP
                host = new WebServiceHost(typeof(Webservice), new Uri(uri)); // dit is voor REST


                // http://en.csharp-online.net/WCF_Essentials%E2%80%94Enabling_Metadata_Exchange_Programmatically
                ServiceMetadataBehavior metadataBehavior = host.Description.Behaviors.Find <ServiceMetadataBehavior>();
                if (metadataBehavior == null)
                {
                    metadataBehavior = new ServiceMetadataBehavior();
                    metadataBehavior.HttpGetEnabled = true;
                    metadataBehavior.HttpGetUrl     = new Uri(uri);
                    host.Description.Behaviors.Add(metadataBehavior);
                }

                // Add our Custom Behaviour to the list of behaviours (zie http://www.thereforesystems.com/capture-xml-in-wcf-service/)
                host.Description.Behaviors.Add(new CustomBehavior());

                WebHttpBinding whb = new WebHttpBinding();
                whb.Security.Mode = WebHttpSecurityMode.TransportCredentialOnly;
                whb.Security.Transport.ClientCredentialType = HttpClientCredentialType.Basic;
                whb.Security.Transport.Realm = "FingerprintWebservice";
                // Let op volgens ms documentatie staan deze settings verschillend ingesteld,
                // maar praktijk is dat ze dezelfde waarde moeten hebben!!!
                // Is vergroot omdat POST data van torrent file niet meer verwerkt kon worden (was iets
                // groter dan 48 kb, waardoor html encodeing het waarschijnlijk over de 64kb default
                // limit gooide)
                whb.MaxBufferSize          = 1024 * 2048; // 2mb
                whb.MaxReceivedMessageSize = 1024 * 2048; // 2mb

                ServiceEndpoint ep;
                ep = host.AddServiceEndpoint(typeof(IWebserviceContract), GetWebHttpBinding(whb), uri); // Global website
                ep.Behaviors.Add(new WebHttpBehavior());
                ep.Behaviors.Add(new GZipEncoder.ContentEncodingBehavior());

                ServiceCredentials serviceCred = host.Description.Behaviors.Find <ServiceCredentials>();
                if (serviceCred == null)
                {
                    serviceCred = new ServiceCredentials();
                    serviceCred.UserNameAuthentication.UserNamePasswordValidationMode  = System.ServiceModel.Security.UserNamePasswordValidationMode.Custom;
                    serviceCred.UserNameAuthentication.CustomUserNamePasswordValidator = new CustomWebAuthenticationValidator();
                    host.Description.Behaviors.Add(serviceCred);
                }

                // Start de service
                host.Open();


                // --------------------------------------------------------------------------------------------------------------
                // zorg dat de health test urls zonder authentication beschikbaar zijn!
                // --------------------------------------------------------------------------------------------------------------
                hostHealthService = new WebServiceHost(typeof(ServiceHealthCheck), new Uri(uri + "engine/health/"));
                hostHealthService.Description.Behaviors.Add(new CustomBehavior());
                ServiceEndpoint ep2 = hostHealthService.AddServiceEndpoint(typeof(IServiceContractHealthCheck), new WebHttpBinding(), "");
                hostHealthService.Open();
                // --------------------------------------------------------------------------------------------------------------


                // add event handlers
                foreach (ChannelDispatcher dispatcher in host.ChannelDispatchers)
                {
                    foreach (var endPoint in dispatcher.Endpoints)
                    {
                        // get a list of MessageInspectors that are of type Inspector
                        var query = (from ex in endPoint.DispatchRuntime.MessageInspectors
                                     where ex.GetType() == typeof(Inspector)
                                     select ex).Cast <Inspector>();

                        // hook up the events
                        foreach (var item in query)
                        {
                            // Dit event heeft ook de grote van het reply vandaar dat we die gebruiken voor het loggen
                            item.RaiseSendingReply += new EventHandler <InspectorEventArgs>(LogReceivedRequest);
                        } //foreach
                    }     //foreach
                }         //foreach

                // Start de accouting thread (zorgt voor mailen info elke nacht)
                CreateAccountingThread();

                if (Environment.UserInteractive)
                {
                    PrintEndpoints(host);
                }

                receiveIndex = new ReceiveIndex(Path.GetDirectoryName(LuceneIndexes.SubFingerprintLocation));
            }
            catch (Exception e)
            {
                CDRLogger.Logger.LogError(e);
            }
        }