/// <summary>
        /// Processes NeighbourhoodChangedNotificationRequest message from LOC server.
        /// <para>Adds, changes, or deletes neighbor and possibly adds new neighborhood action to the database.</para>
        /// </summary>
        /// <param name="Client">TCP client who received the message.</param>
        /// <param name="RequestMessage">Full request message.</param>
        /// <returns>Response message to be sent to the client.</returns>
        public async Task <LocProtocolMessage> ProcessMessageNeighbourhoodChangedNotificationRequestAsync(LocClient Client, LocProtocolMessage RequestMessage)
        {
            log.Trace("()");

            LocProtocolMessage res     = Client.MessageBuilder.CreateErrorInternalResponse(RequestMessage);
            bool signalActionProcessor = false;

            NeighbourhoodChangedNotificationRequest neighbourhoodChangedNotificationRequest = RequestMessage.Request.LocalService.NeighbourhoodChanged;

            using (UnitOfWork unitOfWork = new UnitOfWork())
            {
                DatabaseLock[] lockObjects = new DatabaseLock[] { UnitOfWork.NeighborLock, UnitOfWork.NeighborhoodActionLock };
                using (IDbContextTransaction transaction = await unitOfWork.BeginTransactionWithLockAsync(lockObjects))
                {
                    bool success = false;
                    bool saveDb  = false;
                    try
                    {
                        int neighborhoodSize = await unitOfWork.NeighborRepository.CountAsync();

                        foreach (NeighbourhoodChange change in neighbourhoodChangedNotificationRequest.Changes)
                        {
                            // We do ignore errors here for each individual change and just continue processing the next item from the list.
                            log.Trace("Neighborhood change type is {0}.", change.ChangeTypeCase);
                            switch (change.ChangeTypeCase)
                            {
                            case NeighbourhoodChange.ChangeTypeOneofCase.AddedNodeInfo:
                            case NeighbourhoodChange.ChangeTypeOneofCase.UpdatedNodeInfo:
                            {
                                bool     isAdd    = change.ChangeTypeCase == NeighbourhoodChange.ChangeTypeOneofCase.AddedNodeInfo;
                                NodeInfo nodeInfo = isAdd ? change.AddedNodeInfo : change.UpdatedNodeInfo;

                                // Check whether a proximity server is running on this node.
                                // If not, it is not interesting for us at all, skip it.
                                int    proximityServerPort;
                                byte[] proximityServerId;
                                if (!HasProximityServerService(nodeInfo, out proximityServerPort, out proximityServerId))
                                {
                                    break;
                                }

                                NodeContact            contact   = nodeInfo.Contact;
                                IPAddress              ipAddress = new IPAddress(contact.IpAddress.ToByteArray());
                                Iop.Locnet.GpsLocation location  = nodeInfo.Location;
                                int latitude  = location.Latitude;
                                int longitude = location.Longitude;

                                AddOrChangeNeighborResult addChangeRes = await AddOrChangeNeighborAsync(unitOfWork, proximityServerId, ipAddress, proximityServerPort, latitude, longitude, neighborhoodSize);

                                neighborhoodSize = addChangeRes.NeighborhoodSize;

                                if (addChangeRes.SaveDb)
                                {
                                    saveDb = true;
                                }

                                if (addChangeRes.SignalActionProcessor)
                                {
                                    signalActionProcessor = true;
                                }

                                break;
                            }

                            case NeighbourhoodChange.ChangeTypeOneofCase.RemovedNodeId:
                            {
                                byte[] serverId = change.RemovedNodeId.ToByteArray();

                                bool serverIdValid = serverId.Length == ProtocolHelper.NetworkIdentifierLength;
                                if (!serverIdValid)
                                {
                                    log.Error("Received invalid neighbor server ID '{0}' from LOC server.", serverId.ToHex());
                                    break;
                                }

                                // Data processing.
                                Neighbor existingNeighbor = (await unitOfWork.NeighborRepository.GetAsync(n => n.NetworkId == serverId)).FirstOrDefault();
                                if (existingNeighbor != null)
                                {
                                    log.Trace("Creating neighborhood action to deleting neighbor ID '{0}' from the database.", serverId.ToHex());

                                    string neighborInfo = JsonConvert.SerializeObject(existingNeighbor);

                                    // Delete neighbor completely.
                                    // This will cause our proximity server to erase all activities of the neighbor that has been removed.
                                    bool deleted = await unitOfWork.NeighborRepository.DeleteNeighborAsync(serverId, -1, true);

                                    if (deleted)
                                    {
                                        // Add action that will contact the neighbor and ask it to stop sending updates.
                                        // Note that the neighbor information will be deleted by the time this action
                                        // is executed and this is why we have to fill in AdditionalData.
                                        NeighborhoodAction stopUpdatesAction = new NeighborhoodAction()
                                        {
                                            ServerId              = serverId,
                                            Timestamp             = DateTime.UtcNow,
                                            Type                  = NeighborhoodActionType.StopNeighborhoodUpdates,
                                            TargetActivityId      = 0,
                                            TargetActivityOwnerId = null,
                                            ExecuteAfter          = DateTime.UtcNow,
                                            AdditionalData        = neighborInfo
                                        };
                                        await unitOfWork.NeighborhoodActionRepository.InsertAsync(stopUpdatesAction);

                                        signalActionProcessor = true;
                                        saveDb = true;
                                    }
                                    else
                                    {
                                        log.Error("Failed to remove neighbor ID '{0}' from the database.", serverId.ToHex());
                                        // This is actually bad, we failed to remove a record from the database, which should never happen.
                                        // We try to insert action to remove this neighbor later, but adding the action might fail as well.
                                        NeighborhoodAction action = new NeighborhoodAction()
                                        {
                                            ServerId              = serverId,
                                            Timestamp             = DateTime.UtcNow,
                                            Type                  = NeighborhoodActionType.RemoveNeighbor,
                                            TargetActivityId      = 0,
                                            TargetActivityOwnerId = null,
                                            AdditionalData        = null
                                        };
                                        await unitOfWork.NeighborhoodActionRepository.InsertAsync(action);

                                        signalActionProcessor = true;
                                        saveDb = true;
                                    }
                                }
                                else
                                {
                                    log.Debug("Neighbor ID '{0}' not found, can not be removed.", serverId.ToHex());
                                    // It can be the case that this node has not an associated proximity server, so in that case we should ignore it.
                                    // If the node has an associated proximity server, then nothing bad really happens here if we have activities
                                    // of such a neighbor in NeighborActivity table. Those entries will expire and will be deleted.
                                }
                                break;
                            }

                            default:
                                log.Error("Invalid neighborhood change type '{0}'.", change.ChangeTypeCase);
                                break;
                            }
                        }

                        if (saveDb)
                        {
                            await unitOfWork.SaveThrowAsync();

                            transaction.Commit();
                        }
                        success = true;
                        res     = Client.MessageBuilder.CreateNeighbourhoodChangedNotificationResponse(RequestMessage);
                    }
                    catch (Exception e)
                    {
                        log.Error("Exception occurred: {0}", e.ToString());
                    }

                    if (!success)
                    {
                        log.Warn("Rolling back transaction.");
                        unitOfWork.SafeTransactionRollback(transaction);
                    }

                    unitOfWork.ReleaseLock(lockObjects);
                }
            }

            if (signalActionProcessor)
            {
                NeighborhoodActionProcessor neighborhoodActionProcessor = (NeighborhoodActionProcessor)Base.ComponentDictionary[NeighborhoodActionProcessor.ComponentName];
                neighborhoodActionProcessor.Signal();
            }

            log.Trace("(-):*.Response.Status={0}", res.Response.Status);
            return(res);
        }
        /// <summary>
        /// Obtains IP address and neighbor port from the server's network identifier.
        /// </summary>
        /// <param name="NetworkId">Network identifer of the server.</param>
        /// <param name="NotFound">If the function fails, this is set to true if the reason for failure was that the remote server was not found.</param>
        /// <param name="IgnoreDbPortValue">If set to true, the function will ignore NeighborPort value of the server even if it is set in the database
        /// and will contact the server on its primary port and then update NeighborPort in the database, if it successfully gets its value.</param>
        /// <returns>End point description or null if the function fails.</returns>
        public async Task <IPEndPoint> GetServerContactAsync(byte[] NetworkId, StrongBox <bool> NotFound, bool IgnoreDbPortValue = false)
        {
            log.Trace("(NetworkId:'{0}',IgnoreDbPortValue:{1})", NetworkId.ToHex(), IgnoreDbPortValue);

            IPEndPoint   res        = null;
            DatabaseLock lockObject = null;
            bool         unlock     = false;

            try
            {
                T remoteServer = (await GetAsync(n => n.NetworkId == NetworkId)).FirstOrDefault();
                if (remoteServer != null)
                {
                    log.Trace("{0} server found in the database.", remoteServer is Neighbor ? "Neighbor" : "Follower");
                    IPAddress addr = new IPAddress(remoteServer.IpAddress);
                    if (!IgnoreDbPortValue && (remoteServer.NeighborPort != null))
                    {
                        res = new IPEndPoint(addr, remoteServer.NeighborPort.Value);
                    }
                    else
                    {
                        NeighborhoodActionProcessor neighborhoodActionProcessor = (NeighborhoodActionProcessor)Base.ComponentDictionary[NeighborhoodActionProcessor.ComponentName];

                        // We do not know neighbor port of this server yet (or we ignore it), we have to connect to its primary port and get that information.
                        int neighborPort = await neighborhoodActionProcessor.GetServerRolePortFromPrimaryPort(addr, remoteServer.PrimaryPort, ServerRoleType.Neighbor);

                        if (neighborPort != 0)
                        {
                            lockObject = GetTableLock();
                            await unitOfWork.AcquireLockAsync(lockObject);

                            unlock = true;

                            remoteServer.NeighborPort = neighborPort;
                            Update(remoteServer);
                            if (!await unitOfWork.SaveAsync())
                            {
                                log.Error("Unable to save new neighbor port information {0} of {1} ID '{2}' to the database.", neighborPort, remoteServer is Neighbor ? "neighbor" : "follower", NetworkId.ToHex());
                            }

                            res = new IPEndPoint(addr, neighborPort);
                        }
                        else
                        {
                            log.Debug("Unable to obtain srNeighbor port from primary port of {0} ID '{1}'.", remoteServer is Neighbor ? "neighbor" : "follower", NetworkId.ToHex());
                        }
                    }
                }
                else
                {
                    log.Error("Unable to find {0} ID '{1}' in the database.", remoteServer is Neighbor ? "neighbor" : "follower", NetworkId.ToHex());
                    NotFound.Value = true;
                }
            }
            catch (Exception e)
            {
                log.Error("Exception occurred: {0}", e.ToString());
            }

            if (unlock)
            {
                unitOfWork.ReleaseLock(lockObject);
            }

            log.Trace("(-):{0}", res != null ? res.ToString() : "null");
            return(res);
        }
        /// <summary>
        /// Processes GetNeighbourNodesByDistanceResponse message received from LOC server.
        /// <para>This message contains information about proximity server's neighbors, with which it should share its activity database.</para>
        /// </summary>
        /// <param name="ResponseMessage">Full response message.</param>
        /// <param name="IsInitialization">true if the response was received to the request during the LOC initialization, false if it was received to the refresh request after the initialization.</param>
        /// <returns>true if the connection to the LOC server should remain open, false if it should be closed.</returns>
        public async Task <bool> ProcessMessageGetNeighbourNodesByDistanceResponseAsync(LocProtocolMessage ResponseMessage, bool IsInitialization)
        {
            log.Trace("(IsInitialization:{0})", IsInitialization);

            bool res = false;
            bool signalActionProcessor = false;

            GetNeighbourNodesByDistanceResponse getNeighbourNodesByDistanceResponse = ResponseMessage.Response.LocalService.GetNeighbourNodes;

            if (getNeighbourNodesByDistanceResponse.Nodes.Count > 0)
            {
                using (UnitOfWork unitOfWork = new UnitOfWork())
                {
                    DatabaseLock[] lockObjects = new DatabaseLock[] { UnitOfWork.NeighborLock, UnitOfWork.NeighborhoodActionLock };
                    using (IDbContextTransaction transaction = await unitOfWork.BeginTransactionWithLockAsync(lockObjects))
                    {
                        bool success = false;
                        bool saveDb  = false;
                        try
                        {
                            int neighborhoodSize = await unitOfWork.NeighborRepository.CountAsync();

                            foreach (NodeInfo nodeInfo in getNeighbourNodesByDistanceResponse.Nodes)
                            {
                                // Check whether a proximity server is running on this node.
                                // If not, it is not interesting for us at all, skip it.
                                int    proximityServerPort;
                                byte[] proximityServerId;
                                if (!HasProximityServerService(nodeInfo, out proximityServerPort, out proximityServerId))
                                {
                                    continue;
                                }

                                NodeContact contact   = nodeInfo.Contact;
                                byte[]      ipBytes   = contact.IpAddress.ToByteArray();
                                IPAddress   ipAddress = new IPAddress(ipBytes);

                                int latitude  = nodeInfo.Location.Latitude;
                                int longitude = nodeInfo.Location.Longitude;

                                AddOrChangeNeighborResult addChangeRes = await AddOrChangeNeighborAsync(unitOfWork, proximityServerId, ipAddress, proximityServerPort, latitude, longitude, neighborhoodSize);

                                neighborhoodSize = addChangeRes.NeighborhoodSize;

                                if (addChangeRes.SaveDb)
                                {
                                    saveDb = true;
                                }

                                if (addChangeRes.SignalActionProcessor)
                                {
                                    signalActionProcessor = true;
                                }

                                // We do ignore errors here and just continue processing another item from the list.
                            }

                            if (saveDb)
                            {
                                await unitOfWork.SaveThrowAsync();

                                transaction.Commit();
                            }
                            success = true;
                            res     = true;
                        }
                        catch (Exception e)
                        {
                            log.Error("Exception occurred: {0}", e.ToString());
                        }

                        if (!success)
                        {
                            log.Warn("Rolling back transaction.");
                            unitOfWork.SafeTransactionRollback(transaction);
                        }

                        unitOfWork.ReleaseLock(lockObjects);
                    }
                }
            }
            else
            {
                log.Debug("No neighbors announced by LOC server.");
                res = true;
            }

            if (signalActionProcessor)
            {
                NeighborhoodActionProcessor neighborhoodActionProcessor = (NeighborhoodActionProcessor)Base.ComponentDictionary[NeighborhoodActionProcessor.ComponentName];
                neighborhoodActionProcessor.Signal();
            }

            if (res && IsInitialization)
            {
                log.Debug("LOC component is now considered in sync with LOC server.");
                serverComponent.SetLocServerInitialized(true);
            }

            log.Trace("(-):{0}", res);
            return(res);
        }