public void StopDecrypting() { IsRunning = false; foreach (var stateObject in Sockets) { try { if (stateObject == null) { continue; } if (stateObject.Socket != null) { stateObject.Socket.Shutdown(SocketShutdown.Both); stateObject.Socket.Close(); stateObject.Socket.Dispose(); stateObject.Socket = null; } lock (stateObject.SocketLock) { stateObject.Connections = new List <NetworkConnection>(); } } catch (Exception ex) { RaiseException(Logger, ex); } } Sockets.Clear(); ServerConnections.Clear(); DroppedConnections.Clear(); }
private void LoadConnections() { FileStream connectionStream = new FileStream(@"XmlData\Connections.xml", FileMode.Open); XmlSerializer xmlSerializer = new XmlSerializer(typeof(ServerConnections)); connectionsInfo = (ServerConnections)xmlSerializer.Deserialize(connectionStream); connectionStream.Close(); }
public void AddServer(ServerModel ServerToAdd, IPAddress IpAddressToAdd) { // Add the server to the servers list. // IpConnections is also bound to the ServersComboBox IpConnections.Add(IpAddressToAdd); // Add the server Ip Address to the IpConnection list. ServerConnections.Add(ServerToAdd); }
private void BindServers() { ServerConnections connectionsInfo = ServerConnections.Load(); foreach (ConnectionInfo connection in connectionsInfo.Connections) { comboBoxServer.Items.Add(connection); } }
public void SendDataPacketsWhileDisconnecting(int numberOfClients, ShutdownType shutdowntype) { // Arrange for (var i = 0; i < numberOfClients; i++) { CreateAndStartServer(IPAddress.Any, TestPort, i, new SystemTestValidator(i)); var clientIdx = CreateAndStartClient(IPAddress.Parse(TestIpAdress), TestPort, 500, i, new SystemTestValidator(i)); // Client should be connected WaitForConnectionState(clientIdx, new TimeSpan(0, 0, 0, 5), BinaryConnectionState.Connected); } //Send messages from the clients to the server, to get the Server into the connected-state SendMessages(numberOfClients, 1, 1, Clients, "ClientIdx"); var timeout = new TimeSpan(0, 0, 2, 0); Assert.IsTrue(WaitForMessageReception(timeout, 1, ServerConnections), "Not all ServerConnections received the right number of messages"); //Reset Buffers ServerConnections.ForEach(sc => sc.Received.Clear()); // Act //Send messages from the clients to the server var clientEvents = SendMessages(numberOfClients, 1, 25000000, Clients, "ClientIdx"); //Send messages from the server to clients var serverEvents = SendMessages(numberOfClients, 1, 25000000, ServerConnections, "_serverConnection"); // Wait for each thread to initiate sending WaitHandle.WaitAll(clientEvents); WaitHandle.WaitAll(serverEvents); // Close connections if (shutdowntype == ShutdownType.ShutdownClient) { CloseClients(); CloseServer(); } else { CloseServer(); CloseClients(); } // Assert Clients.ForEach(c => Assert.AreEqual(BinaryConnectionState.Disconnected, c.LastStateChangeEvents.LastOrDefault(), "Client did not receive Disconnected-Event")); ServerConnections.ForEach(s => Assert.AreEqual(BinaryConnectionState.Disconnected, s.LastStateChangeEvents.LastOrDefault(), "Serverconnection did not receive Disconnected-Event")); }
public ServerConnectionData AddServerConnectionData(String connectionType, String connectionDataString) { var scd = new ServerConnectionData(connectionType, connectionDataString); foreach (var cnd in ServerConnections) { if (cnd.ID == scd.ID) { cnd.ParseConnectionDataString(connectionDataString); return(cnd); } } System.Diagnostics.Debug.Print("Adding server connection " + scd.ID); ServerConnections.Add(scd); return(scd); }
public SystemTray() { InitializeComponent(); System.Windows.Forms.Application.EnableVisualStyles(); //XP style logviewer = new LogViewer(); this.Resize += SystemTray_Resize; //Log Mode Log.info(String.Format("Running in {0}-bit mode.", (Environment.Is64BitProcess) ? 64: 32 )); //first time, make sure update checks are alright if (Properties.Settings.Default.firstTime) { if (MessageBox.Show("Would you like Rear View Mirror to automatically check for updates?", "Check for Updates", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { Properties.Settings.Default.checkUpdates = true; } else { Properties.Settings.Default.checkUpdates = false; } Properties.Settings.Default.firstTime = false; Properties.Settings.Default.Save(); } //upgrade our settings from previous versions if (Properties.Settings.Default.updateSettings) { Log.info("Upgrading settings from previous Rear View Mirror version"); Properties.Settings.Default.Upgrade(); Properties.Settings.Default.updateSettings = false; Properties.Settings.Default.Save(); } //load and start all video sources which were started previously VideoSource[] loadSources = Properties.Settings.Default.videoSources; //Seralizing for older versions of RearViewMirror searziled the entire // capture object which no longer works with new versions of AForge // If we have any of these saved cameras, we'll need to drop them. sources = new ArrayList(); if (loadSources != null) { foreach (VideoSource vs in loadSources) { if (vs.SerializeddDeviceString != null) { sources.Add(vs); } else { Log.warn(String.Format("Camera {0} from older version of RearViewMirror could not be restored", vs.Name)); } } } foreach (VideoSource i in sources) { if (i.SaveState == VideoSource.CameraState.Started) { i.startCamera(); } i.RemoveSelected += new VideoSource.RemoveEventHandler(r_RemoveSelected); } //Global Settings if (Properties.Settings.Default.globalVideoOptions != null) { Log.info("Loading Saved Global Properties"); globalOptions = Properties.Settings.Default.globalVideoOptions; Log.debug(globalOptions.ToString()); globalOptions.updateViewers(); } else { Log.info("No Saved Global Properties. Creating New Properties"); globalOptions = new GlobalVideoFeedOptions(); Log.debug(globalOptions.ToString()); } globalOptions.VideoSources = sources; //previous URLs for MJPEG streams recentURLs = Properties.Settings.Default.recentURLs; if (recentURLs == null) { recentURLs = new StringCollection(); } //video server videoServer = VideoServer.Instance; videoServer.Port = Properties.Settings.Default.serverPort; connectionsWindow = new ServerConnections(videoServer); //load previous server running state if (Properties.Settings.Default.serverRunning) { videoServer.startServer(); } //load global stickey showAllToolStripMenuItem.Checked = Properties.Settings.Default.showAll; foreach (VideoSource s in sources) { s.setViewerGlobalStickey(showAllToolStripMenuItem.Checked); } //check for updates if (Properties.Settings.Default.checkUpdates) { Updater.checkForUpdates(); checkForUpdatesToolStripMenuItem.Checked = true; } else { checkForUpdatesToolStripMenuItem.Checked = false; Log.info("Update check not enabled"); } }
// Disconnect the client from the currently selected Server public void DisconnectFromServer(IPAddress ipServerToDisconnect) { if (ipServerToDisconnect != null) { ServerModel serverToDisconnect = null; // From the Ip look-up the server. foreach (ServerModel server in ServerConnections) { if (server.ServerIpAddress.Equals(ipServerToDisconnect)) { serverToDisconnect = server; // Stop the serverTimer if the disconnect is called from the GUI if (serverToDisconnect.HasToStopTimer) { serverToDisconnect.ServerTimer.Stop(); } break; } } if (serverToDisconnect != null) { // I found the server I want to disconnect if (serverToDisconnect.Equals(CurrentSelectedServer)) { // I want to disconnect the currentSelectedServer serverToDisconnect.CloseClient(); // The function calls already the RemoveServer function // Remove the server information form the GUI NotificationMessage = "Server " + ipServerToDisconnect.ToString() + " disconnesso."; // If there are other servers, select the first of them if (ServerConnections.Count() > 0) { // Select the first server. CurrentSelectedServer = ServerConnections.First(); CurrentSelectedIpAddress = CurrentSelectedServer.ServerIpAddress; CurrentSelectedProcess = null; TheProcessesList = CurrentSelectedServer.TheProcesses; // Update the GUI RaisePropertyChanged("TheProcessesList"); RaisePropertyChanged("CurrentSelectedIpAddress"); RaisePropertyChanged("CurrentSelectedServer"); RaisePropertyChanged("CurrentSelectedProcess"); RaisePropertyChanged("IpConnections"); } else // There are no more connected servers. { CurrentSelectedServer = null; CurrentSelectedProcess = null; CurrentSelectedIpAddress = null; TheProcessesList = null; // Update the GUI RaisePropertyChanged("TheProcessesList"); RaisePropertyChanged("CurrentSelectedIpAddress"); RaisePropertyChanged("CurrentSelectedServer"); RaisePropertyChanged("CurrentSelectedProcess"); RaisePropertyChanged("IpConnections"); } } else { // The server I want to disconnect is just one among the others. // Close takes care of calling the removeProcessfromApplications and the remove server. serverToDisconnect.CloseClient(); // Update the GUI RaisePropertyChanged("TheProcessesList"); RaisePropertyChanged("CurrentSelectedIpAddress"); RaisePropertyChanged("CurrentSelectedServer"); RaisePropertyChanged("CurrentSelectedProcess"); RaisePropertyChanged("IpConnections"); } } else // I haven't found the server I am looking for { System.Windows.Application.Current.Dispatcher.Invoke((Action) delegate { // Open the Error Window Views.ErrorWindowView errView = new Views.ErrorWindowView(); ErrorWindowViewModel errWindViewModel = new ErrorWindowViewModel("Non è stato trovato il server da disconnettere."); errWindViewModel.ClosingRequest += errView.Close; errView.DataContext = errWindViewModel; errView.Show(); }); } } else // No server is selected { // Open the Error Window Views.ErrorWindowView errView = new Views.ErrorWindowView(); ErrorWindowViewModel errWindViewModel = new ErrorWindowViewModel("Non è selezionato nessun server."); errWindViewModel.ClosingRequest += errView.Close; errView.DataContext = errWindViewModel; errView.Show(); } }
// Remove a Server from the data structures. public void RemoveServer(ServerModel ServerToRemove, IPAddress IpAddressToRemove) { // Iterate for each process in the server and remove it from the applications listed in the applicationList of the viewModel. foreach (ProcessModel proc in ServerToRemove.TheProcesses) { ServerToRemove.RemoveProcessFromApplications(proc); // The function already iterates for all the application in the list and checks if the application has still at least a server running it. // It also takes care of raising the propertyChanged. } // Remove it from the IpConnections. if (IpConnections.Contains(IpAddressToRemove)) { System.Windows.Application.Current.Dispatcher.Invoke((Action) delegate { IpConnections.Remove(IpAddressToRemove); RaisePropertyChanged("IpConnections"); }); } // Remove it from the ServerConnectons. if (ServerConnections.Contains(ServerToRemove)) { ServerConnections.Remove(ServerToRemove); } // Check that there is the entry correspondent witht the serverIpAddress. lock (syncListOfConnectionThreads) { if (_listOfConnectionThreads != null && _currentSelectedServer != null) { if (_listOfConnectionThreads.ContainsKey(_currentSelectedServer.ServerIpAddress)) { // Abort the thread running the connection. _listOfConnectionThreads[_currentSelectedServer.ServerIpAddress].Abort(); // Remove the thread from the dictionary. _listOfConnectionThreads.Remove(_currentSelectedServer.ServerIpAddress); } } } // If there are other servers, select the first of them if (ServerConnections.Count() > 0) { // Select the first server. CurrentSelectedServer = ServerConnections.First(); CurrentSelectedIpAddress = CurrentSelectedServer.ServerIpAddress; CurrentSelectedProcess = null; TheProcessesList = CurrentSelectedServer.TheProcesses; // Update the GUI RaisePropertyChanged("TheProcessesList"); RaisePropertyChanged("CurrentSelectedIpAddress"); RaisePropertyChanged("CurrentSelectedServer"); RaisePropertyChanged("CurrentSelectedProcess"); } else { // There are no more connected servers. CurrentSelectedServer = null; CurrentSelectedProcess = null; CurrentSelectedIpAddress = null; TheProcessesList = null; RaisePropertyChanged("TheProcessesList"); } }
static void Main() { //Starting visual and text styles Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(true); SetApplicationExceptions(); //Set for logging events when the application shuts down ILogger.AddToLog(ResourceInformation.ApplicationName, "Running main form now!"); //Initialize CefSharp VoidCef.InitializeCefSharp(); //Initialize settings manager Settings.SettingsManager.InitializeValues(); OpenForm(); //Opens a new borwser window //Checks if the application exist var exists = Process.GetProcessesByName(Path.GetFileNameWithoutExtension(Assembly.GetEntryAssembly().Location)).Length > 1; if (exists) { ILogger.AddToLog(ResourceInformation.ApplicationName, "Detected another instance of the browser open! Sending client package and closing browser..."); //New TCP client to send data to local server TcpClient client = new TcpClient(); client.Connect("localhost", 6189); client.Client.Send(Encoding.UTF8.GetBytes("newpage")); //Closing application and client client.Close(); Application.Exit(); } InitializeInvokeObject(); //Initialize the invoke object for the start of the application. //Check if there is an active internet connection if (!CheckInternet.CheckForInternetConnection()) { ILogger.AddToLog("ERROR", "Connection to the internet was not found!"); MessageBox.Show("Connection to the internet was not found! this browser is currently closing.", ResourceInformation.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Error); Application.Exit(); } InitializeLocalServer(); //Loads the local server used to open a new form when a new application is open. InitializeStripe(); //Initialize the stripe API //Initializing History IHistory.LoadFromFile(); StartFormTimer(); //Starts a timer to check when no forms are open Settings.Settings.downloadItem.InitializeDownloadItems(); //Initialize download items from local storage. Thread thread = new Thread(new ThreadStart(() => { //Initializes server connections ServerConnections.InitializeServerConnections(); })); thread.Start(); //Running the application loop. Application.Run(); }
public void AddMessageData(MessageDirection direction, Message message) { var md = new MessageData(direction, message); System.Diagnostics.Trace.WriteLine("Adding " + direction + " message " + message.ID + " " + message.Type); Messages.Insert(0, md); if (Messages.Count > MESSAGE_LOG_MAX) { Messages.RemoveAt(MESSAGE_LOG_MAX); } switch (message.Type) { case MessageType.STATUS_RESPONSE: //distinguish the status response between status of a server or a connection if (message.HasValue("ServerID")) { //assign some general server properties ServerID = message.GetString("ServerID"); MaxConnections = message.GetInt("MaxConnections"); ConnectionsCount = message.GetInt("ConnectionsCount"); RemainingConnections = MaxConnections - ConnectionsCount; ServerDetails = String.Format("{0} @ {1}: {2} Connections made, {3} Remaining", ServerID, ServerConnectionString, ConnectionsCount, RemainingConnections); //remove clients by first getting a list of all 'active' clients var clients = message.GetList <String>("Connections"); List <String> clientNames = new List <String>(); foreach (var cs in clients) { var data = cs.Split(' '); var clientName = data[1]; if (clientName != null && clientName != String.Empty) { clientNames.Add(clientName); } } //and then removing any clients not on that list var clientsToRemove = new List <ClientData>(); foreach (ClientData cd in Clients) { if (!clientNames.Contains(cd.Name)) { clientsToRemove.Add(cd); } } foreach (ClientData cd in clientsToRemove) { System.Diagnostics.Trace.WriteLine("Removing client " + cd.Name); Clients.Remove(cd); } //add/remove server connections List <String> scdIDs = new List <String>(); ServerConnectionData scd; scd = AddServerConnectionData("PRIMARY", message.GetString("PrimaryConnection")); scdIDs.Add(scd.ID); foreach (var s in message.GetList <String>("SecondaryConnections")) { scd = AddServerConnectionData("SECONDARY", s); scdIDs.Add(scd.ID); } foreach (var s in message.GetList <String>("Connections")) { scd = AddServerConnectionData("CLIENT", s); scdIDs.Add(scd.ID); } //now we remove any dead connections List <ServerConnectionData> scToRemove = new List <ServerConnectionData>(); foreach (ServerConnectionData sd in ServerConnections) { if (!scdIDs.Contains(sd.ID)) { scToRemove.Add(sd); } } foreach (ServerConnectionData sd in scToRemove) { System.Diagnostics.Debug.Print("Removing server connection " + sd.ID); ServerConnections.Remove(sd); } } else if (message.HasValue("Context")) { AddClientData(message); } break; } }