private static void SmartSocket_SmartSocketConnected(object sender, EventArgs e)
 {
     if (contextMenu.InvokeRequired)
     {
         contextMenu.Invoke((Action)(() => SmartSocket_SmartSocketConnectedInInvoke(sender, e)));
     }
     else
     {
         SmartSocket_SmartSocketConnectedInInvoke(sender, e);
     }
 }
Exemple #2
0
 public void UpdateSerialStatus(SerialStateChangeEventArgs stateChangeEventArgs)
 {
     if (_menu.InvokeRequired)
     {
         _menu.Invoke(new Action(() =>
         {
             _serialStatusLabel.Text = "Serial: " + stateChangeEventArgs.State.ToString() + " " + stateChangeEventArgs.PortName;
         }));
     }
     else
     {
         _serialStatusLabel.Text = "Serial: " + stateChangeEventArgs.State.ToString() + " " + stateChangeEventArgs.PortName;
     }
 }
        /// <summary>
        /// Adds the main MySQL instance's menu itemText and its sub-items to the given context menu strip.
        /// </summary>
        /// <param name="menu">Context menu strip to add the MySQL instance's menu items to.</param>
        public void AddToContextMenu(ContextMenuStrip menu)
        {
            if (menu.InvokeRequired)
            {
                menu.Invoke(new MethodInvoker(() => AddToContextMenu(menu)));
            }
            else
            {
                var index = FindMenuItemWithinMenuStrip(menu, Resources.Actions);
                if (index < 0)
                {
                    index = 0;
                }

                InstanceMenuItem.Text = $@"{BoundInstance.DisplayConnectionSummaryText} - {BoundInstance.ConnectionStatusText}";
                menu.Items.Insert(index++, InstanceMenuItem);
                if (BoundInstance.WorkbenchConnection != null)
                {
                    if (ConfigureMenuItem != null)
                    {
                        menu.Items.Insert(index++, ConfigureMenuItem);
                    }

                    if (SqlEditorMenuItem != null)
                    {
                        menu.Items.Insert(index++, SqlEditorMenuItem);
                    }
                }

                menu.Items.Insert(index, Separator);
                menu.Refresh();
            }
        }
        /// <summary>
        /// Refreshes the menu items of this menu group.
        /// </summary>
        /// <param name="menu">The Notifier's context menu.</param>
        public void RefreshMenu(ContextMenuStrip menu)
        {
            if (menu.InvokeRequired)
            {
                menu.Invoke(new MethodInvoker(() => RefreshMenu(menu)));
            }
            else
            {
                if (!_boundService.IsRealMySqlService)
                {
                    return;
                }

                _boundService.FindMatchingWbConnections();

                int index = FindMenuItemWithinMenuStrip(menu, _boundService.ServiceId);
                if (index < 0)
                {
                    return;
                }

                // We dispose of ConfigureInstance and SQLEditor items to recreate a clear menu.
                if (menu.Items[index + 1].Text.Equals(Resources.ManageInstance))
                {
                    menu.Items.RemoveAt(index + 1);
                }

                if (menu.Items[index + 1].Text.Equals(Resources.SQLEditor))
                {
                    menu.Items.RemoveAt(index + 1);
                }

                // If Workbench is installed on the system, we add ConfigureInstance and SQLEditor items back.
                if (MySqlWorkbench.AllowsExternalConnectionsManagement)
                {
                    if (_configureMenu == null)
                    {
                        _configureMenu        = new ToolStripMenuItem(Resources.ManageInstance);
                        _configureMenu.Click += configureInstanceItem_Click;
                    }

                    CreateEditorMenus();

                    if (_configureMenu != null)
                    {
                        menu.Items.Insert(++index, _configureMenu);
                    }

                    if (_editorMenu != null)
                    {
                        menu.Items.Insert(++index, _editorMenu);
                    }
                }

                menu.Refresh();
            }
        }
Exemple #5
0
        public void Consume(object message)
        {
            if (Menu.InvokeRequired)
            {
                Menu.Invoke((MethodInvoker) delegate() { TrayColorLabel.Text = message.ToString(); });
                return;
            }

            TrayColorLabel.Text = message.ToString();
        }
        /// <summary>
        /// Removes the main MySQL instance's menu itemText and its sub-items from the given context menu strip.
        /// </summary>
        /// <param name="menu">Context menu strip to remove the MySQL instance's menu items from..</param>
        public void RemoveFromContextMenu(ContextMenuStrip menu)
        {
            if (menu.InvokeRequired)
            {
                menu.Invoke(new MethodInvoker(() => RemoveFromContextMenu(menu)));
            }
            else
            {
                var menuItemTexts = new string[4];
                var index         = FindInstanceMenuItemWithinMenuStrip(menu);

                if (index < 0)
                {
                    return;
                }

                // if index + 1 is a ConfigureInstance item, we need to dispose of the whole item.
                if (menu.Items[index + 1].Text.Equals(Resources.ManageInstance))
                {
                    // The last itemText we delete is the service name itemText which is the reference for the others.
                    menuItemTexts[0] = "Configure Menu";
                    menuItemTexts[1] = "Editor Menu";
                    menuItemTexts[2] = "Separator";
                    menuItemTexts[3] = InstanceMenuItem.Text;
                }
                else
                {
                    menuItemTexts[0] = "Separator";
                    menuItemTexts[1] = InstanceMenuItem.Text;
                }

                foreach (var itemText in menuItemTexts)
                {
                    if (string.IsNullOrEmpty(itemText))
                    {
                        continue;
                    }

                    index = FindInstanceMenuItemWithinMenuStrip(menu);
                    if (index < 0)
                    {
                        continue;
                    }

                    if (!itemText.Equals(InstanceMenuItem.Text))
                    {
                        index++;
                    }

                    menu.Items.RemoveAt(index);
                }

                menu.Refresh();
            }
        }
Exemple #7
0
 private void EnableContextMenuItems()
 {
     if (_contextMenu.InvokeRequired)
     {
         _contextMenu.Invoke(new Action(EnableContextMenuItems));
     }
     else
     {
         if (_messages.Count == 0)
         {
             _menuViewLastMessage.Enabled   = false;
             _menuDeleteAllMessages.Enabled = false;
         }
         else
         {
             _menuViewLastMessage.Enabled   = true;
             _menuDeleteAllMessages.Enabled = true;
         }
     }
 }
 public void StateChanged()
 {
     if (_mainMenu.InvokeRequired)
     {
         _mainMenu.Invoke(new Action(() => { MenuItem.Enabled = EnablementFunction(); }));
     }
     else
     {
         MenuItem.Enabled = EnablementFunction();
     }
 }
Exemple #9
0
        /// <summary>
        /// Removes all menu items related to this service menu group from the main Notifier's context menu.
        /// </summary>
        /// <param name="menu">Main Notifier's context menu.</param>
        public void RemoveFromContextMenu(ContextMenuStrip menu)
        {
            if (menu.InvokeRequired)
            {
                menu.Invoke(new MethodInvoker(() => RemoveFromContextMenu(menu)));
            }
            else
            {
                var menuItems = new string[4];

                if (_boundService?.StartupParameters == null)
                {
                    return;
                }

                if (_boundService.StartupParameters.IsForMySql &&
                    MySqlWorkbench.AllowsExternalConnectionsManagement)
                {
                    menuItems[0] = Resources.ManageInstance;
                    menuItems[1] = Resources.SQLEditor;
                    menuItems[2] = "Separator";
                    menuItems[3] = _statusMenu.Text; // the last itemText we delete is the service name itemText which is the reference for the others
                }
                else
                {
                    menuItems[0] = "Separator";
                    menuItems[1] = _statusMenu.Text;
                }

                var index = FindMenuItemWithinMenuStrip(menu, _boundService.ServiceId);
                if (index <= 0)
                {
                    return;
                }

                // Hide the separator just above this new menu item if needed.
                if (index > 0 && menu.Items[index - 1] is ToolStripSeparator)
                {
                    menu.Items[index - 1].Visible = menu.Items[index + 1].BackColor != SystemColors.MenuText;
                }

                foreach (var plusItem in from item in menuItems where !string.IsNullOrEmpty(item) select item.Equals(_statusMenu.Text) ? 0 : 1)
                {
                    menu.Items.RemoveAt(index + plusItem);
                }

                menu.Refresh();
            }
        }
        /// <summary>
        /// Refreshes the menu items of this menu group.
        /// </summary>
        /// <param name="menu">The Notifier's context menu.</param>
        public void RefreshMenu(ContextMenuStrip menu)
        {
            if (menu.InvokeRequired)
            {
                menu.Invoke(new MethodInvoker(() => RefreshMenu(menu)));
            }
            else
            {
                var index = FindMenuItemWithinMenuStrip(menu, BoundInstance.InstanceId);
                if (index < 0)
                {
                    return;
                }

                // We dispose of ConfigureInstance and SQLEditor items to recreate a clear menu.
                if (menu.Items[index + 1].Text.Equals(Resources.ManageInstance))
                {
                    menu.Items.RemoveAt(index + 1);
                }

                if (menu.Items[index + 1].Text.Equals(Resources.SQLEditor))
                {
                    menu.Items.RemoveAt(index + 1);
                }

                // If Workbench is installed on the system, we add ConfigureInstance and SQLEditor items back.
                if (MySqlWorkbench.AllowsExternalConnectionsManagement)
                {
                    if (ConfigureMenuItem == null)
                    {
                        ConfigureMenuItem        = new ToolStripMenuItem(Resources.ManageInstance);
                        ConfigureMenuItem.Click += ConfigureMenuItem_Click;
                        RecreateSqlEditorMenus();
                    }

                    if (ConfigureMenuItem != null)
                    {
                        menu.Items.Insert(++index, ConfigureMenuItem);
                    }

                    if (SqlEditorMenuItem != null)
                    {
                        menu.Items.Insert(++index, SqlEditorMenuItem);
                    }
                }

                menu.Refresh();
            }
        }
Exemple #11
0
 public void TextToolStrip(ContextMenuStrip context, string text)
 {
     if (_tsmi != null)
     {
         if (context.InvokeRequired)
         {
             delegateTextToolStrip deleg = new delegateTextToolStrip(TextToolStrip);
             context.Invoke(deleg, new object[] { context, text });
         }
         else
         {
             _tsmi.Text = text;
         }
     }
 }
        public void ConstructContextMenu(List <string> currencies)
        {
            if (_contextMenu.InvokeRequired)
            {
                var safeCallDelegate = new SafeCallDelegate(ConstructContextMenu);

                _contextMenu.Invoke(safeCallDelegate, currencies);
            }
            else
            {
                _contextMenu.Items.Clear();

                _allCurrencies = new ToolStripMenuItem("Total", null, (_, _) => ToggleCurrencyHistory())
                {
                    Checked = _formManager.IsFormShown(null)
                };

                _contextMenu.Items.Add(_allCurrencies);

                if (currencies != null && currencies.Count > 1)
                {
                    foreach (var currency in currencies.OrderBy(c => c).ToList())
                    {
                        _contextMenu.Items.Add(new ToolStripMenuItem(currency.ToUpperInvariant(), null, (_, _) => ToggleCurrencyHistory(currency))
                        {
                            Tag = currency, Checked = _formManager.IsFormShown(currency)
                        });
                    }
                }

                _contextMenu.Items.Add(new ToolStripSeparator());

                _alwaysOnTop = new ToolStripMenuItem("Keep Windows Above Others", null, (_, _) => ToggleTopMost())
                {
                    Checked = AppSettings.Instance.AlwaysOnTop
                };

                _contextMenu.Items.Add(_alwaysOnTop);

                _contextMenu.Items.Add(new ToolStripSeparator());

                _contextMenu.Items.Add(new ToolStripMenuItem("Refresh", null, (_, _) => RefreshClicked()));

                _contextMenu.Items.Add(new ToolStripSeparator());

                _contextMenu.Items.Add(new ToolStripMenuItem("Exit", null, (_, _) => ExitClicked()));
            }
        }
        /// <summary>
        /// Adds the context menu items corresponding to the bound service.
        /// </summary>
        /// <param name="menu">The Notifier's context menu.</param>
        public void AddToContextMenu(ContextMenuStrip menu)
        {
            if (menu.InvokeRequired)
            {
                menu.Invoke(new MethodInvoker(() => AddToContextMenu(menu)));
            }
            else
            {
                int index = FindMenuItemWithinMenuStrip(menu, _boundService.Host.MachineId);
                int servicesMenusCount = _boundService.Host.Services != null?_boundService.Host.Services.Sum(s => s != _boundService && s.MenuGroup != null?s.MenuGroup.MenuItemsQuantity : 0) : 0;

                index += servicesMenusCount;
                if (index < 0)
                {
                    return;
                }

                // Show the separator just above this new menu item if needed.
                if (index > 0 && menu.Items[index] is ToolStripSeparator)
                {
                    menu.Items[index].Visible = true;
                }

                index++;
                menu.Items.Insert(index, _statusMenu);
                MenuItemsQuantity++;
                if (_boundService.IsRealMySqlService)
                {
                    if (_configureMenu != null)
                    {
                        menu.Items.Insert(++index, _configureMenu);
                        MenuItemsQuantity++;
                    }

                    if (_editorMenu != null)
                    {
                        menu.Items.Insert(++index, _editorMenu);
                        MenuItemsQuantity++;
                    }
                }

                menu.Items.Insert(++index, _separator);
                _separator.Visible = menu.Items[index + 1].BackColor != SystemColors.MenuText;
                MenuItemsQuantity++;
            }
        }
 /// <summary>
 ///
 /// Thread save call by invoking if necessary
 /// </summary>
 private void SetCallCurrentNumberMenuItem()
 {
     if (_contextMenuStrip.InvokeRequired)
     {
         SetCallCurrentNumberMenuItemCallback d = new SetCallCurrentNumberMenuItemCallback(SetCallCurrentNumberMenuItem);
         _contextMenuStrip.Invoke(d);
     }
     else
     {
         _callCurrentNumberMenuItem.Text = MessageHelper.CallCurrentNumberText;
         if (_callCurrentNumberMenuItem.Text == "")
         {
             _callCurrentNumberMenuItem.Available = false;
         }
         else
         {
             _callCurrentNumberMenuItem.Available = true;
             _contextMenuStrip.PerformLayout();
         }
     }
 }
Exemple #15
0
        private static void GetServiceStatus()
        {
            if (contextMenuStrip.InvokeRequired)
            {
                contextMenuStrip.Invoke((GetServiceStatusCallback)GetServiceStatus);
                return;
            }
            try
            {
                serviceController.Refresh();
                switch (serviceController.Status)
                {
                case ServiceControllerStatus.Running:
                    notifyIcon.Icon = Resources.Running;
                    contextMenuStrip.Items[0].Enabled = true;
                    contextMenuStrip.Items[1].Enabled = false;
                    break;

                case ServiceControllerStatus.Stopped:
                    notifyIcon.Icon = Resources.Stopped;
                    contextMenuStrip.Items[0].Enabled = false;
                    contextMenuStrip.Items[1].Enabled = true;
                    break;

                case ServiceControllerStatus.ContinuePending:
                case ServiceControllerStatus.PausePending:
                case ServiceControllerStatus.StartPending:
                case ServiceControllerStatus.StopPending:
                    notifyIcon.Icon = Resources.Paused;
                    contextMenuStrip.Items[0].Enabled = false;
                    contextMenuStrip.Items[1].Enabled = false;
                    break;
                }
                ctrlPanel.SetButtonStates();
            }
            catch (Exception ex)
            {
                ExitController(ex.Message);
            }
        }
Exemple #16
0
        public void SetMenuEnabled(bool enabled)
        {
            var action = new Action(() =>
            {
                if (contextMenu.Items.Count > 0)
                {
                    for (var i = 0; i < contextMenu.Items.Count - 1; i++)
                    {
                        contextMenu.Items[i].Enabled = enabled;
                    }
                }
            });

            if (contextMenu.InvokeRequired)
            {
                contextMenu.Invoke(action);
            }
            else
            {
                action();
            }
        }
Exemple #17
0
 protected void CodeShow(string titile, string codeContent)
 {
     if (MainContextMenu.InvokeRequired)
     {
         var s = new CodeShowDel(CodeShow);
         MainContextMenu.Invoke(s, new object[] { titile, codeContent });
     }
     else
     {
         Code mf = new Code()
         {
             CodeLanguage = CodeLanguage, Text = titile, CodeContent = codeContent
         };
         mf.tbCode.ContextMenuStrip = cms;
         mf.Show(Panel);
     }
 }
Exemple #18
0
        /// <summary>
        /// ContextMenuStrip¿¡ ¾ÆÀÌÅÛ(¸ñ·Ï)À» Ãß°¡ÇÑ´Ù.
        /// </summary>
        /// <param name="cms"></param>
        /// <param name="strName"></param>
        /// <param name="strText"></param>
        /// <param name="img"></param>
        /// <param name="e"></param>
        public static void Invoke_ContextMenuStrip_ItemAdd(ContextMenuStrip cms, string strName, string strText, Image img, EventHandler e)
        {
            if (cms.InvokeRequired)
            {
                cms.Invoke(new delInvoke_ContextMenuStrip_ItemAdd(Invoke_ContextMenuStrip_ItemAdd), new object[] { cms, strName, strText, img, e });
                return;
            }

            if (strName == string.Empty && strText == string.Empty)
            {
                ToolStripSeparator Spe = new ToolStripSeparator();
                cms.Items.Add(Spe);
            }
            else
            {
                ToolStripMenuItem tsi = new ToolStripMenuItem();
                tsi.Name   = strName;
                tsi.Text   = strText;
                tsi.Image  = img;
                tsi.Click += e;
                cms.Items.Add(tsi);
            }
        }
Exemple #19
0
        private void OnServerUpdate(object sender, ServerUpdateEventArgs e)
        {
            if (TrayIconContextMenu.InvokeRequired)
            {
                TrayIconContextMenu.Invoke(new Action <object, ServerUpdateEventArgs>(OnServerUpdate), sender, e);
                return;
            }

            if (e.SendAlert)
            {
                var alertText = "goonman players needed!\n" + string.Join("\n", e.ServerInfos.Select(s => s.Info()));
                TrayIcon.ShowBalloonTip(10000, "sub.io", alertText, ToolTipIcon.Warning);
            }

            TrayIconContextMenu.Items.Clear();

            var menuItems = e.ServerInfos.Select(
                server => ServerToolStripMenuItem.GetToolStripMenuItem(server, new EventHandler(OnServerClick)
                                                                       ));

            TrayIconContextMenu.Items.AddRange(menuItems.ToArray());

            TrayIconContextMenu.Items.Add(CloseMenuItem);
        }
Exemple #20
0
 public void Invoke(Action action)
 {
     contextMenuStrip1.Invoke(action);
 }
Exemple #21
0
        public ServerNotifyIcon(ILogManager logManager,
                                IServerApplicationHost appHost,
                                IServerConfigurationManager configurationManager,
                                ILocalizationManager localization)
        {
            _logger               = logManager.GetLogger("MainWindow");
            _localization         = localization;
            _appHost              = appHost;
            _configurationManager = configurationManager;

            var components = new System.ComponentModel.Container();

            var resources = new System.ComponentModel.ComponentResourceManager(typeof(MainForm));

            contextMenuStrip1 = new ContextMenuStrip(components);
            notifyIcon1       = new NotifyIcon(components);

            cmdExit             = new ToolStripMenuItem();
            cmdCommunity        = new ToolStripMenuItem();
            toolStripSeparator1 = new ToolStripSeparator();
            cmdRestart          = new ToolStripMenuItem();
            toolStripSeparator2 = new ToolStripSeparator();
            cmdConfigure        = new ToolStripMenuItem();
            cmdBrowse           = new ToolStripMenuItem();
            cmdApiDocs          = new ToolStripMenuItem();
            cmdSwagger          = new ToolStripMenuItem();
            cmdGtihub           = new ToolStripMenuItem();

            //
            // notifyIcon1
            //
            notifyIcon1.ContextMenuStrip = contextMenuStrip1;
            notifyIcon1.Icon             = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
            notifyIcon1.Text             = "Emby";
            notifyIcon1.Visible          = true;
            //
            // contextMenuStrip1
            //
            contextMenuStrip1.Items.AddRange(new ToolStripItem[] {
                cmdBrowse,
                cmdConfigure,
                toolStripSeparator2,
                cmdRestart,
                toolStripSeparator1,
                cmdApiDocs,
                cmdCommunity,
                cmdExit
            });
            contextMenuStrip1.Name            = "contextMenuStrip1";
            contextMenuStrip1.ShowCheckMargin = true;
            contextMenuStrip1.ShowImageMargin = false;
            contextMenuStrip1.Size            = new System.Drawing.Size(209, 214);
            //
            // cmdExit
            //
            cmdExit.Name = "cmdExit";
            cmdExit.Size = new System.Drawing.Size(208, 22);
            //
            // cmdCommunity
            //
            cmdCommunity.Name = "cmdCommunity";
            cmdCommunity.Size = new System.Drawing.Size(208, 22);
            //
            // toolStripSeparator1
            //
            toolStripSeparator1.Name = "toolStripSeparator1";
            toolStripSeparator1.Size = new System.Drawing.Size(205, 6);
            //
            // cmdRestart
            //
            cmdRestart.Name = "cmdRestart";
            cmdRestart.Size = new System.Drawing.Size(208, 22);
            //
            // toolStripSeparator2
            //
            toolStripSeparator2.Name = "toolStripSeparator2";
            toolStripSeparator2.Size = new System.Drawing.Size(205, 6);
            //
            // cmdConfigure
            //
            cmdConfigure.Name = "cmdConfigure";
            cmdConfigure.Size = new System.Drawing.Size(208, 22);
            //
            // cmdBrowse
            //
            cmdBrowse.Name = "cmdBrowse";
            cmdBrowse.Size = new System.Drawing.Size(208, 22);
            //
            // cmdApiDocs
            //
            cmdApiDocs.DropDownItems.AddRange(new ToolStripItem[] {
                cmdSwagger,
                cmdGtihub
            });
            cmdApiDocs.Name = "cmdApiDocs";
            cmdApiDocs.Size = new System.Drawing.Size(208, 22);
            //
            // cmdSwagger
            //
            cmdSwagger.Name = "cmdSwagger";
            cmdSwagger.Size = new System.Drawing.Size(136, 22);
            //
            // cmdGtihub
            //
            cmdGtihub.Name = "cmdGtihub";
            cmdGtihub.Size = new System.Drawing.Size(136, 22);

            cmdExit.Click      += cmdExit_Click;
            cmdRestart.Click   += cmdRestart_Click;
            cmdConfigure.Click += cmdConfigure_Click;
            cmdCommunity.Click += cmdCommunity_Click;
            cmdBrowse.Click    += cmdBrowse_Click;

            cmdSwagger.Click += cmdSwagger_Click;
            cmdGtihub.Click  += cmdGtihub_Click;

            _configurationManager.ConfigurationUpdated += Instance_ConfigurationUpdated;

            LocalizeText();

            if (_appHost.IsFirstRun)
            {
                Action action = () => notifyIcon1.ShowBalloonTip(5000, "Emby", "Welcome to Emby Server!", ToolTipIcon.Info);

                contextMenuStrip1.Invoke(action);
            }

            notifyIcon1.DoubleClick += notifyIcon1_DoubleClick;
        }
Exemple #22
0
        private void SetEventHandlers()
        {
            AppModel.Instance.ErrorTriggered += (sender, @event) =>
            {
                using (AppLogger.Log.ErrorCall())
                {
                    if (@event.Exception is AppModel.NoDevicesException)
                    {
                        ShowNoDevices();
                    }
                    else
                    {
                        AppLogger.Log.Error("Exception managed", @event.Exception);
                        ShowError(@event.Exception.Message, @event.Exception.GetType().Name);
                    }
                }
            };
            AppModel.Instance.DefaultDeviceChanged +=
                (sender, audioChangeEvent) =>
            {
                if (audioChangeEvent.role != Role.Console)
                {
                    return;
                }

                var audioDeviceType = audioChangeEvent.device.Type;
                switch (audioDeviceType)
                {
                case AudioDeviceType.Playback:
                    ShowPlaybackChanged(audioChangeEvent.device.FriendlyName);
                    break;

                case AudioDeviceType.Recording:
                    ShowRecordingChanged(audioChangeEvent.device.FriendlyName);
                    break;

                default:
                    throw new ArgumentOutOfRangeException();
                }

                UpdateImageContextMenu(audioDeviceType, audioChangeEvent);
            };
            AppModel.Instance.SelectedDeviceChanged += (sender, deviceListChanged) => { UpdateAvailableDeviceList(); };
            AppModel.Instance.NewVersionReleased    += (sender, @event) =>
            {
                if (_settingsMenu.IsHandleCreated)
                {
                    _settingsMenu.Invoke(new Action(() => { NewReleaseAvailable(sender, @event); }));
                }
                else
                {
                    NewReleaseAvailable(sender, @event);
                }
            };


            AppModel.Instance.DeviceRemoved += (sender, @event) =>
            {
                RemoveDeviceFromContextMenu(@event);
            };

            AppModel.Instance.DeviceAdded += (sender, @event) =>
            {
                AddDeviceToContextMenu(@event);
            };

            AppModel.Instance.DeviceStateChanged += (sender, @event) =>
            {
                if (@event.newState == DeviceState.Active)
                {
                    AddDeviceToContextMenu(@event);
                }
                else
                {
                    RemoveDeviceFromContextMenu(@event);
                }
            };

            AppModel.Instance.InitializeMain();
        }
 protected object Invoke(Delegate method)
 {
     return(_contextMenu.Invoke(method));
 }
        public async void timerTickAsync(object sender, EventArgs e)
        {
            Console.WriteLine("The timer ticked at {0:HH:mm:ss.fff}", DateTime.UtcNow);

            // Get some basic settings items out of the registry
            // which are required to make an API ping call
            string Key      = Registry.Get("Key");
            string ApiKey   = Registry.Get("ApiKey");
            string Interval = Registry.Get("Interval");

            // Protect application from crashing when important
            // settings values can not be found.
            if (ApiKey == "" || Interval == "" || Key == "")
            {
                return;
            }

            string host = Dns.GetHostName();

            // Reset timer interval incase it was changed in the settings
            this.loopTimer.Interval = Int32.Parse(Interval) * 1000;

            // If the router object is still being found, skip this ping
            if (Router == null)
            {
                this.TitleMenuItem.Image = Properties.Resources.bullet_yellow;

                this.TitleMenuItem.ToolTipText = "Your router does not seem to support all required features.";
            }
            else
            {
                this.TitleMenuItem.ToolTipText = "";
            }

            // Do something if the failed number of ping attempts is to high
            if (this.FailedPings > 3)
            {
                this.TitleMenuItem.Image = Properties.Resources.bullet_red;
            }
            else
            {
                this.TitleMenuItem.Image = Properties.Resources.bullet_green;
            }

            dynamic response;

            Ping = new PingRequest();

            try
            {
                response = await Ping.SendAsync(Router, ApiKey, Key);
            }
            catch (Exception exc)
            {
                Console.WriteLine(exc.Message);

                this.FailedPings++;

                return;
            }

            // Check with router to see if port is open
            // This allows the system to detect if port is still forwarded from a previous
            try
            {
                Mapping RoutedPort = this.Router.GetSpecificMapping(Protocol.Tcp, Int32.Parse(Registry.Get("Port")));
            }
            catch (Exception exc)
            {
            }
            this.isPortOpen = Ping.IsPortMapped;

            // If account is good, make menu header icon green
            if (Ping.LifeTime > 0)
            {
                this.TitleMenuItem.Image       = Properties.Resources.bullet_green;
                this.TitleMenuItem.ToolTipText = String.Format("Your API key is valid for {0} more days", Ping.LifeTime / (60 * 60 * 24));
            }

            // Display the update available menu item if update is available
            try
            {
                this.UpdateAvailableMenuItem.Visible = Ping.Version != null && Ping.Version != StaticHelpers.GetVersion();
            }
            catch (Exception exc)
            {
                Console.WriteLine(exc.Message);
            }

            // Keep running list of discovered machines, so that expired ones can be removed after
            List <string> machineList = new List <string>();

            if (Ping.RemoteMachines != null)
            {
                foreach (KeyValuePair <string, RemoteMachine> b in Ping.RemoteMachines)
                {
                    RemoteMachine x = b.Value;

                    string menukey = "menu___" + x.host;

                    machineList.Add(menukey);

                    // Remove any existing machine from the tray icon in a thread-safe way
                    if (TrayIconContextMenu.InvokeRequired)
                    {
                        TrayIconContextMenu.Invoke(new MethodInvoker(delegate
                        {
                            TrayIconContextMenu.Items.RemoveByKey(menukey);
                        }));
                    }
                    else
                    {
                        TrayIconContextMenu.Items.RemoveByKey(menukey);
                    }

                    ToolStripMenuItem HostMenuItem = this.CreateHostMenuItem(menukey, x);

                    // Add the menu item thread-safely
                    if (TrayIconContextMenu.InvokeRequired)
                    {
                        TrayIconContextMenu.Invoke(new MethodInvoker(delegate
                        {
                            this.TrayIconContextMenu.Items.Insert(2, HostMenuItem);
                        }));
                    }
                    else
                    {
                        this.TrayIconContextMenu.Items.Insert(2, HostMenuItem);
                    }
                }
            }

            List <string> removedMenuNames = new List <string>();

            // Remove expired entries
            foreach (var b in this.TrayIconContextMenu.Items)
            {
                ToolStripMenuItem test = b as ToolStripMenuItem;
                if (test != null && test.Name.Contains("menu___") && !machineList.Contains(test.Name))
                {
                    removedMenuNames.Add(test.Name);
                }
            }

            foreach (string removedMenuName in removedMenuNames)
            {
                this.TrayIconContextMenu.Items.RemoveByKey(removedMenuName);
            }

            // If this ping request resulted in commands which were processed, then a
            // new thread should run another ping request to send any updated status
            // back to the central server
            if (Ping.CommandWasProcessed == true)
            {
                new Thread(() =>
                {
                    Thread.CurrentThread.IsBackground = true;
                    timerTickAsync(null, null);
                }).Start();
            }

            // Refresh the interval value just incase it was changed
            this.SelectIntervalSetting(Int32.Parse(Registry.Get("Interval")));

            // Once a ping sequence has been fully completed, reset the fails counter
            this.FailedPings = 0;
        }