Пример #1
0
        void ProcessPendingRequests()
        {
            if (_pendingRequests.Count == 0)
            {
                return;
            }

            EventOccurred?.Invoke(this, new ServerEvent
            {
                EventType         = EventType.ProcessRequestBacklogStarted,
                ItemsInQueueCount = _pendingRequests.Count
            });

            var pendingIds = _pendingRequests.Select(r => r.Id).ToList();

            foreach (var id in pendingIds)
            {
                var pendingRequest = _pendingRequests.FirstOrDefault(r => r.Id == id);
                if (pendingRequest == null)
                {
                    continue;
                }

                ProcessRequest(pendingRequest);
            }

            EventOccurred?.Invoke(this, new ServerEvent
            {
                EventType         = EventType.ProcessRequestBacklogComplete,
                ItemsInQueueCount = _pendingRequests.Count
            });
        }
Пример #2
0
        void ProcessRequest(Request newRequest)
        {
            EventOccurred?.Invoke(this, new ServerEvent
            {
                EventType              = EventType.ProcessRequestStarted,
                RequestType            = newRequest.Type,
                RequestId              = newRequest.Id,
                RemoteServerIpAddress  = newRequest.RemoteServerInfo.SessionIpAddress,
                RemoteServerPortNumber = newRequest.RemoteServerInfo.PortNumber
            });

            newRequest.Status = RequestStatus.InProgress;
            HandleInProgressRequest(newRequest);

            var processRequest = _processRequestFunctions[newRequest.Type].Invoke(newRequest);

            if (processRequest.Success)
            {
                return;
            }

            newRequest.Status = RequestStatus.Error;
            HandleFailedInProgressRequest(newRequest);

            ReportError(processRequest.Error);
        }
Пример #3
0
        void HandleSuccessfulyProcessedRequest(object sender, Request processedRequest)
        {
            //var shutdownSocket = ShutdownSocket(_socket);
            //if (shutdownSocket.Failure)
            //{
            //    ReportError(shutdownSocket.Error);
            //    processedRequest.Status = RequestStatus.Error;
            //    HandleFailedInProgressRequest(processedRequest);

            //    return;
            //}

            ShutdownSocket(_socket);

            processedRequest.Status = RequestStatus.Processed;
            HandleSuccessfullyProcessedRequest(processedRequest);

            EventOccurred?.Invoke(this, new ServerEvent
            {
                EventType              = EventType.ProcessRequestComplete,
                RequestType            = processedRequest.Type,
                RemoteServerIpAddress  = processedRequest.RemoteServerInfo.SessionIpAddress,
                RemoteServerPortNumber = processedRequest.RemoteServerInfo.PortNumber
            });
        }
Пример #4
0
        async void HandleServerInfoRequest(object sender, Request serverInfoRequest)
        {
            _eventLog.Add(new ServerEvent
            {
                EventType              = EventType.ReceivedServerInfoRequest,
                RemoteServerIpAddress  = serverInfoRequest.RemoteServerInfo.SessionIpAddress,
                RemoteServerPortNumber = serverInfoRequest.RemoteServerInfo.PortNumber
            });

            EventOccurred?.Invoke(this, _eventLog.Last());

            var serverInfoResponse = new ServerInfoResponse
            {
                LocalServerInfo    = MyInfo,
                RemoteServerInfo   = serverInfoRequest.RemoteServerInfo,
                LocalIpAddress     = MyInfo.LocalIpAddress,
                PublicIpAddress    = MyInfo.PublicIpAddress,
                PortNumber         = MyInfo.PortNumber,
                Platform           = MyInfo.Platform,
                TransferFolderPath = MyInfo.TransferFolder,
                Status             = RequestStatus.InProgress,
                Direction          = TransferDirection.Outbound
            };

            var sendRequest = await _requestHandler.SendRequestAsync(serverInfoResponse);

            if (sendRequest.Failure)
            {
                ReportError(this, sendRequest.Error);
                return;
            }

            SuccessfullyProcessedRequest?.Invoke(this, serverInfoResponse);
        }
Пример #5
0
        private void TimerTick(object state)
        {
            if (nextDates == null || nextDates.Count == 0)
            {
                return;
            }

            var now = DateTime.Now;

            // minimal resolution interval of this object is 1 second, so we do not need milliseconds
            // best way to truncate them:
            // https://stackoverflow.com/questions/1004698/how-to-truncate-milliseconds-off-of-a-net-datetime

            now = now.AddTicks(-(now.Ticks % TimeSpan.TicksPerSecond));

            if (nextDates.ContainsValue(now))
            {
                var eventArgs = new List <Schedule>();

                PopulateEventArgs(eventArgs, now);

                RefreshDates(eventArgs);

                EventOccurred?.Invoke(this, new ScheduleEventArgs(eventArgs.ToArray()));
            }
        }
Пример #6
0
        void HandleRetryLimitExceeded(object sender, RetryLimitExceeded retryLimitExceeded)
        {
            var getFileTransfer = FileTransferHandler.HandleRetryLimitExceeded(retryLimitExceeded);

            if (getFileTransfer.Failure)
            {
                return;
            }

            var inboundFileTransfer = getFileTransfer.Value;

            _eventLog.Add(new ServerEvent
            {
                EventType              = EventType.ReceivedRetryLimitExceeded,
                LocalFolder            = inboundFileTransfer.LocalFolderPath,
                FileName               = inboundFileTransfer.FileName,
                FileSizeInBytes        = inboundFileTransfer.FileSizeInBytes,
                RemoteServerIpAddress  = inboundFileTransfer.RemoteServerInfo.SessionIpAddress,
                RemoteServerPortNumber = inboundFileTransfer.RemoteServerInfo.PortNumber,
                RetryCounter           = inboundFileTransfer.RetryCounter,
                RemoteServerRetryLimit = inboundFileTransfer.RemoteServerRetryLimit,
                RetryLockoutExpireTime = inboundFileTransfer.RetryLockoutExpireTime,
                FileTransferId         = inboundFileTransfer.Id
            });

            EventOccurred?.Invoke(this, _eventLog.Last());
            SuccessfullyProcessedRequest?.Invoke(this, retryLimitExceeded);
        }
Пример #7
0
        async Task <Result> ConnectToServerAsync(ServerInfo remoteServerInfo)
        {
            _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            EventOccurred?.Invoke(this, new ServerEvent
            {
                EventType              = EventType.ConnectToRemoteServerStarted,
                RemoteServerIpAddress  = remoteServerInfo.SessionIpAddress,
                RemoteServerPortNumber = remoteServerInfo.PortNumber
            });

            var connectToRemoteServer =
                await _socket.ConnectWithTimeoutAsync(
                    remoteServerInfo.SessionIpAddress,
                    remoteServerInfo.PortNumber,
                    _timeoutMs)
                .ConfigureAwait(false);

            if (connectToRemoteServer.Failure)
            {
                return(Result.Fail <Socket>(connectToRemoteServer.Error));
            }

            EventOccurred?.Invoke(this, new ServerEvent
            {
                EventType              = EventType.ConnectToRemoteServerComplete,
                RemoteServerIpAddress  = remoteServerInfo.SessionIpAddress,
                RemoteServerPortNumber = remoteServerInfo.PortNumber
            });

            return(Result.Ok());
        }
Пример #8
0
        Request DecodeRequest(byte[] encodedRequest)
        {
            EventOccurred?.Invoke(this,
                                  new ServerEvent {
                EventType = EventType.DetermineRequestTypeStarted
            });

            var requestType = RequestDecoder.ReadRequestType(encodedRequest);

            var newRequest = _decodeRequestFunctions[requestType].Invoke(encodedRequest);

            newRequest.Status    = RequestStatus.Pending;
            newRequest.Direction = TransferDirection.Inbound;

            newRequest.DecodeRequest();
            AssignIdToNewRequest(newRequest);

            EventOccurred?.Invoke(this, new ServerEvent
            {
                EventType   = EventType.DetermineRequestTypeComplete,
                RequestType = newRequest.Type
            });

            return(newRequest);
        }
Пример #9
0
        public void AddNewReceivedMessage(MessageRequest messageRequest)
        {
            var textSessionId = GetTextSessionIdForRemoteServer(messageRequest.RemoteServerInfo);
            var textSession   = GetTextSessionById(textSessionId).Value;

            var newTextMessage = new Message
            {
                SessionId        = textSessionId,
                TimeStamp        = DateTime.Now,
                RemoteServerInfo = messageRequest.RemoteServerInfo,
                Author           = TextMessageAuthor.RemoteServer,
                Text             = messageRequest.Message,
                Unread           = true
            };

            textSession.Messages.Add(newTextMessage);

            EventOccurred?.Invoke(this, new ServerEvent
            {
                EventType              = EventType.ReceivedTextMessage,
                TextMessage            = newTextMessage.Text,
                RemoteServerIpAddress  = messageRequest.RemoteServerInfo.SessionIpAddress,
                RemoteServerPortNumber = messageRequest.RemoteServerInfo.PortNumber,
                TextSessionId          = textSessionId
            });
        }
Пример #10
0
        async Task <Result <int> > ReceiveLengthOfIncomingRequest()
        {
            EventOccurred?.Invoke(this,
                                  new ServerEvent {
                EventType = EventType.ReceiveRequestLengthStarted
            });

            var readFromSocket = await
                                 _socket.ReceiveWithTimeoutAsync(
                _buffer,
                0,
                _bufferSize,
                SocketFlags.None,
                _timeoutMs)
                                 .ConfigureAwait(false);

            if (readFromSocket.Failure)
            {
                return(readFromSocket);
            }

            var lastBytesReceivedCount = readFromSocket.Value;
            var unreadBytesCount       = lastBytesReceivedCount - Constants.SizeOfInt32InBytes;
            var requestLength          = BitConverter.ToInt32(_buffer, 0);

            var requestLengthBytes = new byte[Constants.SizeOfInt32InBytes];

            _buffer.ToList().CopyTo(0, requestLengthBytes, 0, Constants.SizeOfInt32InBytes);

            SocketEventOccurred?.Invoke(this, new ServerEvent
            {
                EventType            = EventType.ReceivedRequestLengthBytesFromSocket,
                BytesReceivedCount   = lastBytesReceivedCount,
                RequestLengthInBytes = Constants.SizeOfInt32InBytes,
                UnreadBytesCount     = unreadBytesCount
            });

            if (lastBytesReceivedCount > Constants.SizeOfInt32InBytes)
            {
                var unreadBytes = new byte[unreadBytesCount];
                _buffer.ToList().CopyTo(Constants.SizeOfInt32InBytes, unreadBytes, 0, unreadBytesCount);
                _unreadBytes = unreadBytes.ToList();

                EventOccurred?.Invoke(this, new ServerEvent
                {
                    EventType        = EventType.SaveUnreadBytesAfterRequestLengthReceived,
                    UnreadBytesCount = unreadBytesCount
                });
            }

            EventOccurred?.Invoke(this, new ServerEvent
            {
                EventType            = EventType.ReceiveRequestLengthComplete,
                RequestLengthInBytes = requestLength,
                RequestLengthBytes   = requestLengthBytes
            });

            return(Result.Ok(requestLength));
        }
Пример #11
0
        public void StartEvents(int numOfEvents)
        {
            for (var i = 0; i < numOfEvents - 1; i++)
            {
                EventOccurred?.Invoke(false);
            }

            //Send true to indicate last event
            EventOccurred?.Invoke(true);
        }
Пример #12
0
        protected void HandlePendingFileTransfer(object sender, int pendingTransferCount)
        {
            _eventLog.Add(new ServerEvent
            {
                EventType         = EventType.PendingFileTransfer,
                ItemsInQueueCount = pendingTransferCount
            });

            EventOccurred?.Invoke(this, _eventLog.Last());
        }
Пример #13
0
        void ReportError(object sender, string error)
        {
            ErrorLog.Add(new ServerError(error));

            _eventLog.Add(new ServerEvent
            {
                EventType    = EventType.ErrorOccurred,
                ErrorMessage = error,
                SenderType   = sender.GetType()
            });

            EventOccurred?.Invoke(this, _eventLog.Last());
        }
Пример #14
0
        private void HandleRequestedFolderIsEmpty(object sender, Request requestedFolderIsEmpty)
        {
            _eventLog.Add(new ServerEvent
            {
                EventType              = EventType.ReceivedNotificationFolderIsEmpty,
                RemoteServerIpAddress  = requestedFolderIsEmpty.RemoteServerInfo.SessionIpAddress,
                RemoteServerPortNumber = requestedFolderIsEmpty.RemoteServerInfo.PortNumber
            });

            EventOccurred?.Invoke(this, _eventLog.Last());

            SuccessfullyProcessedRequest?.Invoke(this, requestedFolderIsEmpty);
        }
Пример #15
0
        async void ReceiveRequest(object sender, Socket socket)
        {
            var requestReceiver = new RequestReceiver(_settings);

            requestReceiver.EventOccurred       += HandleServerEvent;
            requestReceiver.SocketEventOccurred += HandleSocketEvent;
            requestReceiver.ReceivedFileBytes   += HandleFileBytesReceived;

            EventOccurred?.Invoke(this,
                                  new ServerEvent {
                EventType = EventType.ReceiveRequestFromRemoteServerStarted
            });

            var receiveRequest = await
                                 requestReceiver.ReceiveRequestAsync(socket).ConfigureAwait(false);

            if (receiveRequest.Failure)
            {
                ReportError(receiveRequest.Error);
                return;
            }

            var encodedRequest = receiveRequest.Value;

            var newRequest = DecodeRequest(encodedRequest);

            AddNewPendingRequest(newRequest);

            EventOccurred?.Invoke(this,
                                  new ServerEvent {
                EventType = EventType.ReceiveRequestFromRemoteServerComplete
            });

            if (FileTransferInProgress())
            {
                EventOccurred?.Invoke(this, new ServerEvent
                {
                    EventType         = EventType.PendingRequestInQueue,
                    ItemsInQueueCount = _pendingRequests.Count
                });

                return;
            }

            _socket = requestReceiver.GetTransferSocket();

            ProcessRequest(newRequest);
        }
Пример #16
0
        public async Task <Result> SendAsync(Request outboundRequest)
        {
            var encodeRequest = outboundRequest.EncodeRequest(_localServerInfo);

            if (encodeRequest.Failure)
            {
                return(Result.Fail(encodeRequest.Error));
            }

            var requestBytes     = encodeRequest.Value;
            var requestType      = outboundRequest.Type;
            var remoteServerInfo = outboundRequest.RemoteServerInfo;

            EventOccurred?.Invoke(this, GetSendRequestStartedEvent(requestType, remoteServerInfo));

            var connectToServer = await ConnectToServerAsync(remoteServerInfo).ConfigureAwait(false);

            if (connectToServer.Failure)
            {
                return(connectToServer);
            }

            var sendRequestLength = await SendRequestLength(requestBytes).ConfigureAwait(false);

            if (sendRequestLength.Failure)
            {
                return(sendRequestLength);
            }

            var sendRequest = await SendRequestBytes(requestBytes).ConfigureAwait(false);

            if (sendRequest.Failure)
            {
                return(sendRequest);
            }

            if (requestType != RequestType.FileTransferAccepted)
            {
                ShutdownSocket();
            }

            EventOccurred?.Invoke(this, GetSendRequestCompleteEvent(requestType, remoteServerInfo));
            SuccessfullySentRequest?.Invoke(this, outboundRequest);

            return(Result.Ok());
        }
Пример #17
0
        private void HandleFileListResponse(object sender, FileListResponse fileListResponse)
        {
            _eventLog.Add(new ServerEvent
            {
                EventType              = EventType.ReceivedFileList,
                LocalIpAddress         = MyInfo.LocalIpAddress,
                LocalPortNumber        = MyInfo.PortNumber,
                RemoteServerIpAddress  = fileListResponse.RemoteServerInfo.SessionIpAddress,
                RemoteServerPortNumber = fileListResponse.RemoteServerInfo.PortNumber,
                RemoteFolder           = fileListResponse.RemoteServerInfo.TransferFolder,
                RemoteServerFileList   = fileListResponse.FileInfoList,
            });

            EventOccurred?.Invoke(this, _eventLog.Last());

            SuccessfullyProcessedRequest?.Invoke(this, fileListResponse);
        }
Пример #18
0
        async void HandleOutboundFileTransferRequest(object sender, GetFileRequest getFileRequest)
        {
            // TODO: Create logic to check file transfers that are under lockout and if this request matches remoteserver info + localfilepath, send a new filetranserresponse = rejected_retrylimitexceeded. maybe we should penalize them for trying to subvert our lockout policy?

            _eventLog.Add(new ServerEvent
            {
                EventType              = EventType.ReceivedOutboundFileTransferRequest,
                RemoteFolder           = getFileRequest.RemoteFolderPath,
                LocalFolder            = getFileRequest.LocalFolderPath,
                FileName               = getFileRequest.FileName,
                RemoteServerIpAddress  = getFileRequest.RemoteServerInfo.SessionIpAddress,
                RemoteServerPortNumber = getFileRequest.RemoteServerInfo.PortNumber
            });

            EventOccurred?.Invoke(this, _eventLog.Last());

            var handleTransferRequest =
                FileTransferHandler.HandleOutboundFileTransferRequest(getFileRequest);

            if (handleTransferRequest.Failure)
            {
                return;
            }

            var fileTransfer = handleTransferRequest.Value;

            var sendFileRequest = new SendFileRequest
            {
                LocalServerInfo          = MyInfo,
                RemoteServerInfo         = fileTransfer.RemoteServerInfo,
                FileName                 = fileTransfer.FileName,
                FileSizeInBytes          = fileTransfer.FileSizeInBytes,
                RemoteFolderPath         = fileTransfer.RemoteFolderPath,
                LocalFolderPath          = fileTransfer.LocalFolderPath,
                FileTransferResponseCode = fileTransfer.TransferResponseCode,
                RemoteServerTransferId   = fileTransfer.RemoteServerTransferId,
                RetryLimit               = fileTransfer.RemoteServerRetryLimit,
                RetryCounter             = fileTransfer.RetryCounter,
                Status    = RequestStatus.InProgress,
                Direction = TransferDirection.Outbound
            };

            await _requestHandler.SendRequestAsync(sendFileRequest);

            SuccessfullyProcessedRequest?.Invoke(this, getFileRequest);
        }
Пример #19
0
        protected void HandleRetryLimitLockoutExpired(object sender, FileTransfer stalledFileTransfer)
        {
            _eventLog.Add(new ServerEvent
            {
                EventType              = EventType.RetryLimitLockoutExpired,
                LocalFolder            = stalledFileTransfer.LocalFolderPath,
                FileName               = stalledFileTransfer.FileName,
                FileSizeInBytes        = stalledFileTransfer.FileSizeInBytes,
                RemoteServerIpAddress  = stalledFileTransfer.RemoteServerInfo.SessionIpAddress,
                RemoteServerPortNumber = stalledFileTransfer.RemoteServerInfo.PortNumber,
                RetryCounter           = stalledFileTransfer.RetryCounter,
                RemoteServerRetryLimit = stalledFileTransfer.RemoteServerRetryLimit,
                RetryLockoutExpireTime = stalledFileTransfer.RetryLockoutExpireTime,
                FileTransferId         = stalledFileTransfer.Id
            });

            EventOccurred?.Invoke(this, _eventLog.Last());
        }
Пример #20
0
        public void Poll(CovenantAPI CovenantClient, int DelayMilliSeconds = 100)
        {
            DateTime toDate = DateTime.FromBinary(CovenantClient.ApiEventsTimeGet().Value);
            DateTime fromDate;
            bool     done = false;

            while (!done)
            {
                fromDate = toDate;
                toDate   = DateTime.FromBinary(CovenantClient.ApiEventsTimeGet().Value);
                IList <EventModel> events = CovenantClient.ApiEventsRangeByFromdateByTodateGet(fromDate.ToBinary(), toDate.ToBinary());
                foreach (var anEvent in events)
                {
                    EventOccurred?.Invoke(this, new EventOccurredArgs(anEvent));
                }
                Thread.Sleep(DelayMilliSeconds);
            }
        }
Пример #21
0
        void HandleServerInfoResponse(object sender, ServerInfoResponse serverInfoResponse)
        {
            serverInfoResponse.RemoteServerInfo.DetermineSessionIpAddress(Settings.LocalNetworkCidrIp);

            _eventLog.Add(new ServerEvent
            {
                EventType              = EventType.ReceivedServerInfo,
                RemoteServerIpAddress  = serverInfoResponse.RemoteServerInfo.SessionIpAddress,
                RemoteServerPortNumber = serverInfoResponse.RemoteServerInfo.PortNumber,
                RemoteServerPlatform   = serverInfoResponse.RemoteServerInfo.Platform,
                RemoteFolder           = serverInfoResponse.RemoteServerInfo.TransferFolder,
                LocalIpAddress         = serverInfoResponse.RemoteServerInfo.LocalIpAddress,
                PublicIpAddress        = serverInfoResponse.RemoteServerInfo.PublicIpAddress
            });

            EventOccurred?.Invoke(this, _eventLog.Last());

            SuccessfullyProcessedRequest?.Invoke(this, serverInfoResponse);
        }
Пример #22
0
        void HandleOutboundFileTransferComplete(object sender, FileTransferResponse fileTransferResponse)
        {
            _eventLog.Add(new ServerEvent
            {
                EventType              = EventType.RemoteServerConfirmedFileTransferCompleted,
                RemoteServerIpAddress  = fileTransferResponse.RemoteServerInfo.SessionIpAddress,
                RemoteServerPortNumber = fileTransferResponse.RemoteServerInfo.PortNumber,
                FileTransferId         = fileTransferResponse.Id
            });

            EventOccurred?.Invoke(this, _eventLog.Last());

            var transferComplete =
                FileTransferHandler.HandleOutboundFileTransferComplete(fileTransferResponse);

            if (transferComplete.Failure)
            {
                return;
            }

            SuccessfullyProcessedRequest?.Invoke(this, fileTransferResponse);
        }
Пример #23
0
        async void HandleOutboundFileTransferAccepted(object sender, FileTransferResponse fileTransferResponse)
        {
            _eventLog.Add(new ServerEvent
            {
                EventType              = EventType.RemoteServerAcceptedFileTransfer,
                RemoteServerIpAddress  = fileTransferResponse.RemoteServerInfo.SessionIpAddress,
                RemoteServerPortNumber = fileTransferResponse.RemoteServerInfo.PortNumber,
                FileTransferId         = fileTransferResponse.RemoteServerTransferId
            });

            EventOccurred?.Invoke(this, _eventLog.Last());

            var socket = _requestHandler.GetSocketForOutboundFileTransfer();

            if (socket == null)
            {
                var error = "Unable to retrieve transfer socket, file transfer must be aborted";
                FileTransferHandler.AbortOutboundFileTransfer(fileTransferResponse, error);

                return;
            }

            OutboundFileTransferInProgress?.Invoke(this, true);

            var sendFile = await
                           FileTransferHandler.HandleOutboundFileTransferAccepted(
                fileTransferResponse,
                socket,
                _token);

            if (sendFile.Failure)
            {
                OutboundFileTransferInProgress?.Invoke(this, false);
                return;
            }

            OutboundFileTransferInProgress?.Invoke(this, false);
            SuccessfullyProcessedRequest?.Invoke(this, fileTransferResponse);
        }
Пример #24
0
        void ShutdownListenSocket()
        {
            EventOccurred?.Invoke(this,
                                  new ServerEvent {
                EventType = EventType.ShutdownListenSocketStarted
            });

            try
            {
                _listenSocket.Shutdown(SocketShutdown.Both);
                _listenSocket.Close();
            }
            catch (SocketException ex)
            {
                EventOccurred?.Invoke(this,
                                      new ServerEvent {
                    EventType = EventType.ShutdownListenSocketCompletedWithError
                });

                EventOccurred?.Invoke(this,
                                      new ServerEvent {
                    EventType = EventType.ServerStoppedListening
                });

                ReportError(ex.GetReport());
                return;
            }

            EventOccurred?.Invoke(this,
                                  new ServerEvent {
                EventType = EventType.ShutdownListenSocketCompletedWithoutError
            });

            EventOccurred?.Invoke(this,
                                  new ServerEvent {
                EventType = EventType.ServerStoppedListening
            });
        }
Пример #25
0
 /// <summary>
 /// Delegate Method which will be used as event listener.
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 internal void EventDelegate(object sender, EventArgs e)
 {
     try
     {
         var container = new EventArgsContainer(sender, e, TrackingElement)
         {
             EventDefinition = Sequence.Recorder.Events.EventDefinition.CastOrCreate(Event)
         };
         try
         {
             Config.Instance.WriteLog(this, $"Invoking EventOccured Event for {container?.Sender?.StringRepresentation} and Event {container?.EventDefinition?.EventType}.", LogType.Info);
             EventOccurred?.Invoke(this, new EventOccuredEventArgs(sender, e, container));
         }
         catch (Exception ex)
         {
             Config.Instance.WriteLog(this, $"Exception on user defined EventOccuredAction: \r\n {ex.ToString()}".AttachCallerInformation(), LogType.Error);
         }
         EventProcessing.Instance.ProcessEvent(container);
     }catch (Exception ex)
     {
         Config.Instance.WriteLog(this, $"Exception on Processing event {e.ToString()}: \r\n {ex.ToString()}".AttachCallerInformation(), LogType.Error);
     }
 }
Пример #26
0
        void HandleRequestedFileDoesNotExist(object sender, FileTransferResponse fileTransferResponse)
        {
            _eventLog.Add(new ServerEvent
            {
                EventType              = EventType.ReceivedNotificationFileDoesNotExist,
                RemoteServerIpAddress  = fileTransferResponse.RemoteServerInfo.SessionIpAddress,
                RemoteServerPortNumber = fileTransferResponse.RemoteServerInfo.PortNumber,
                FileTransferId         = fileTransferResponse.RemoteServerTransferId
            });

            EventOccurred?.Invoke(this, _eventLog.Last());

            var rejectTransfer =
                FileTransferHandler.HandleRequestedFileDoesNotExist(
                    fileTransferResponse.RemoteServerTransferId);

            if (rejectTransfer.Failure)
            {
                return;
            }

            SuccessfullyProcessedRequest?.Invoke(this, fileTransferResponse);
        }
Пример #27
0
        async Task <Result <Socket> > AcceptConnectionFromRemoteServerAsync(CancellationToken token)
        {
            Result <Socket> acceptConnection;

            try
            {
                acceptConnection = await _listenSocket.AcceptTaskAsync(token).ConfigureAwait(false);
            }
            catch (TaskCanceledException ex)
            {
                ReportError(ex.GetReport());
                return(Result.Fail <Socket>(ex.GetReport()));
            }
            catch (SocketException ex)
            {
                ReportError(ex.GetReport());
                return(Result.Fail <Socket>(ex.GetReport()));
            }

            if (acceptConnection.Failure)
            {
                ReportError(acceptConnection.Error);
                return(Result.Fail <Socket>(acceptConnection.Error));
            }

            var socket = acceptConnection.Value;
            var remoteServerIpString  = socket.RemoteEndPoint.ToString().Split(':')[0];
            var remoteServerIpAddress = NetworkUtilities.ParseSingleIPv4Address(remoteServerIpString).Value;

            EventOccurred?.Invoke(this, new ServerEvent
            {
                EventType             = EventType.ConnectionAccepted,
                RemoteServerIpAddress = remoteServerIpAddress
            });

            return(Result.Ok(socket));
        }
Пример #28
0
        void HandleInboundFileTransferRequest(object sender, SendFileRequest sendFileRequest)
        {
            _eventLog.Add(new ServerEvent
            {
                EventType              = EventType.ReceivedInboundFileTransferRequest,
                LocalFolder            = sendFileRequest.LocalFolderPath,
                FileName               = sendFileRequest.FileName,
                FileSizeInBytes        = sendFileRequest.FileSizeInBytes,
                RemoteServerIpAddress  = sendFileRequest.RemoteServerInfo.SessionIpAddress,
                RemoteServerPortNumber = sendFileRequest.RemoteServerInfo.PortNumber
            });

            EventOccurred?.Invoke(this, _eventLog.Last());

            var handleTransferRequest =
                FileTransferHandler.HandleInboundFileTransferRequest(sendFileRequest);

            if (handleTransferRequest.Failure)
            {
                return;
            }

            SuccessfullyProcessedRequest?.Invoke(this, sendFileRequest);
        }
Пример #29
0
        private void HandleShutdownServerCommand(object sender, Request pendingRequest)
        {
            if (!MyInfo.IsEqualTo(pendingRequest.RemoteServerInfo))
            {
                var error =
                    "Server shutdown command was received, but the command was not sent " +
                    "by this server. Aborting shutdown process.";

                ReportError(this, error);
                return;
            }

            _eventLog.Add(new ServerEvent
            {
                EventType              = EventType.ReceivedShutdownServerCommand,
                RemoteServerIpAddress  = pendingRequest.RemoteServerInfo.SessionIpAddress,
                RemoteServerPortNumber = pendingRequest.RemoteServerInfo.PortNumber,
                RequestId              = pendingRequest.Id
            });

            EventOccurred?.Invoke(this, _eventLog.Last());
            ShutdownInitiated?.Invoke(this, new EventArgs());
            SuccessfullyProcessedRequest?.Invoke(this, pendingRequest);
        }
Пример #30
0
        Result Listen()
        {
            var ipEndPoint = new IPEndPoint(IPAddress.Any, MyInfo.PortNumber);

            try
            {
                _listenSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
                _listenSocket.Bind(ipEndPoint);
                _listenSocket.Listen(_settings.SocketSettings.ListenBacklogSize);
            }
            catch (SocketException ex)
            {
                _log.Error("Error raised in method Listen", ex);
                return(Result.Fail($"{ex.Message} ({ex.GetType()} raised in method AsyncFileServer.Listen)"));
            }

            EventOccurred?.Invoke(this, new ServerEvent
            {
                EventType       = EventType.ServerStartedListening,
                LocalPortNumber = MyInfo.PortNumber
            });

            return(Result.Ok());
        }