public MainWindow() { InitializeComponent(); DataContext = this; ServerUrl = "http://localhost:8080"; Service = new LibraryAdminService(ServerUrl); ClientListener = new WebSocketClient(ServerUrl); ClientListener.NotificationReceived += ClientListenerNotified; ClientListener.ListenAsync(); Gadgets = new ObservableCollection<Gadget>(Service.GetAllGadgets()); Loans = new ObservableCollection<Loan>(Service.GetAllLoans()); InputComboCondition.ItemsSource = Enum.GetValues(typeof(domain.Condition)).Cast<domain.Condition>(); }
public void Connect() { if (_connected) return; try { ServiceUrl = "http://localhost:8080"; _libraryAdminService = new LibraryAdminService(ServiceUrl); _connected = true; LoadData(); RefreshComponents(); StatusBarInfo.Content = $"Connected to {ServiceUrl}"; StatusBar.Background = new SolidColorBrush(Color.FromArgb(0xFF, 0x07, 0x78, 0xB5)); HideLoadingScreen(); var client = new WebSocketClient(ServiceUrl); client.NotificationReceived += (o, e) => { Debug.WriteLine("WebSocket::Notification: " + e.Notification.Target + " > " + e.Notification.Type); // demonstrate how these updates could be further used if (e.Notification.Target == typeof(Gadget).Name.ToLower()) { var gadget = e.Notification.DataAs<Gadget>(); var oldGadget = Gadgets.Find(g => g.InventoryNumber == gadget.InventoryNumber); Gadgets.Remove(oldGadget); if (e.Notification.Type != WebSocketClientNotificationTypeEnum.Delete) { Gadgets.Add(gadget); } } else if (e.Notification.Target == typeof(Reservation).Name.ToLower()) { var reservation = e.Notification.DataAs<Reservation>(); var oldReservation = Reservations.Find(r => r.Id == reservation.Id); Reservations.Remove(oldReservation); reservation.Customer = Customers.Find(c => c.Studentnumber == reservation.CustomerId); reservation.Gadget = Gadgets.Find(c => c.InventoryNumber == reservation.GadgetId); if (e.Notification.Type != WebSocketClientNotificationTypeEnum.Delete) { Reservations.Add(reservation); } } else if (e.Notification.Target == typeof(Loan).Name.ToLower()) { var loan = e.Notification.DataAs<Loan>(); var oldLoans = Loans.Find(l => l.Id == loan.Id); Loans.Remove(oldLoans); loan.Customer = Customers.Find(c => c.Studentnumber == loan.CustomerId); loan.Gadget = Gadgets.Find(c => c.InventoryNumber == loan.GadgetId); if (e.Notification.Type != WebSocketClientNotificationTypeEnum.Delete) { Loans.Add(loan); } } LoadModels(); UpdateView(); HideLoadingScreen(); }; // spawn a new background thread in which the websocket client listens to notifications from the server try { var bgTask = client.ListenAsync(); } catch (WebSocketException e) { ShowErrorScreen(); } } catch (Exception e) { _connected = false; StatusBarInfo.Content = $"Can't connect to {ServiceUrl} - Click here to reconnect"; StatusBar.Background = new SolidColorBrush(Color.FromArgb(0xFF, 0xFF, 0x62, 0x1F)); } }