Esempio n. 1
0
 /// <summary>
 /// Reports the specified status to all connected clients
 /// </summary>
 /// <param name="status"></param>
 public void ReportClients(ServerStatus status)
 {
     foreach (var s in ConnectedClients)
     {
         MessageClient(s, status);
     }
 }
        public void UpdateStatus(ServerStatus status, long storageSize, long numSnapshots)
        {
            switch (status)
            {
                case ServerStatus.Running:
                    _statusDisplayMenuItem.Text = "Running...";
                    _exitMenuItem.Enabled = true;

                    if (numSnapshots == 0)
                        numSnapshots = 1; // prevent divide by zero errors

                    var averagePerSnapshot = storageSize/numSnapshots;
                    var sizeDisplay = string.Format("Size: {0} (avg {1} per snapshot)",
                                                    GetFriendlySizeString(storageSize),
                                                    GetFriendlySizeString(averagePerSnapshot));

                    _sizeDisplayMenuItem.Text = sizeDisplay;
                    break;

                case ServerStatus.Exiting:
                    _statusDisplayMenuItem.Text = "Exitting...";
                    _exitMenuItem.Enabled = false;
                    break;

                default:
                    _statusDisplayMenuItem.Text = "Status Unknown";
                    _exitMenuItem.Enabled = true;
                    break;
            }
        }
        /// <summary>
        /// Изменение окна при изменении статуса сервера
        /// </summary>
        /// <param name="serverWork">Сервер работает?</param>
        public void StatusChangeEffect(ServerStatus status)
        {
            switch (status)
            {
                case ServerStatus.Started:
                    ButtonStartServer.IsEnabled = false;
                    ButtonStartGame.IsEnabled = true;
                    TextBoxGameStatistic.AppendText(DateTime.Now.ToShortTimeString() + 
                        " Запуск сервера\n"+"Порт: "+ComboBoxServer.SelectedValue.ToString()+"\t IP: "+
                        TextBlockIP.Text+"\n");
                    ComboBoxServer.IsEnabled = false;
                    break;

                case ServerStatus.GameInProgress:
                    ButtonStartGame.IsEnabled = false;
                    ButtonStopGame.IsEnabled = true;
                    TextBoxGameStatistic.AppendText(DateTime.Now.ToShortTimeString() + " Начало игры\n");
                    break;

                case ServerStatus.Stopped:
                    ButtonStopGame.IsEnabled = false;
                    ButtonStartServer.IsEnabled = true;
                    TextBoxGameStatistic.AppendText(DateTime.Now.ToShortTimeString() + " Закрытие сервера\n");
                    ComboBoxServer.IsEnabled = true;
                    break;
            }
            
        }
Esempio n. 4
0
 internal ServerStatusEvent(ServerStatus status, string message, IList<Channel> channels)
 {
     _status = status;
     _message = message;
     if (channels != null) _channels = new ReadOnlyCollection<Channel>(channels);
     else _channels = null;
 }
Esempio n. 5
0
        public void Initiate(int port)
        {
            switch (status)
            {
                case ServerStatus.Idle:
                    break;
                case ServerStatus.WaitingConnections:
                    throw new Exception("Server already initiated.");
                case ServerStatus.GameStarted:
                    throw new Exception("Game already started.");
                default:
                    throw new ArgumentOutOfRangeException("status");
            }

            this.clientList = new List<PaxibotClient>();

            //create server socket
            serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            //get ip address
            IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
            IPAddress ipAddress = ipHostInfo.AddressList[0];
            IPEndPoint localEndPoint = new IPEndPoint(ipAddress, port);

            //start listening
            serverSocket.Bind(localEndPoint);
            serverSocket.Listen(maxListenQueue);
            status = ServerStatus.WaitingConnections;
            serverThread = new Thread(new ThreadStart(AcceptClients));
            serverThread.Start();
        }
Esempio n. 6
0
        /// <summary>
        /// Constructor.
        /// </summary>
        internal EveServer()
        {
            m_status = ServerStatus.Online;

            m_monitor = new QueryMonitor<SerializableAPIServerStatus>(APIMethods.ServerStatus);
            m_monitor.Updated += OnMonitorUpdated;
        }
        public void ReloadServers()
        {
            // make a copy to avoid locking
            var newServerStatus = new Dictionary<Server, ServerStatus>(_serverStatus);

            foreach (var server in _controller.GetCurrentConfiguration().configs)
            {
                if (!newServerStatus.ContainsKey(server))
                {
                    var status = new ServerStatus();
                    status.server = server;
                    status.lastFailure = DateTime.MinValue;
                    status.lastRead = DateTime.Now;
                    status.lastWrite = DateTime.Now;
                    status.latency = new TimeSpan(0, 0, 0, 0, 10);
                    status.lastTimeDetectLatency = DateTime.Now;
                    newServerStatus[server] = status;
                }
                else
                {
                    // update settings for existing server
                    newServerStatus[server].server = server;
                }
            }
            _serverStatus = newServerStatus;

            ChooseNewServer();
        }
Esempio n. 8
0
 private OkPayload(int affectedRowCount, long lastInsertId, ServerStatus serverStatus, int warningCount)
 {
     AffectedRowCount = affectedRowCount;
     LastInsertId = lastInsertId;
     ServerStatus = serverStatus;
     WarningCount = warningCount;
 }
Esempio n. 9
0
        public void Show(Point location, ServerStatus serverStatus, IList<ActiveRecording> activeRecordings, IList<LiveStream> liveStreams, UpcomingRecording upcomingRecording)
        {
            _serverStatus = serverStatus;
            _activeRecordings = activeRecordings;
            _liveStreams = liveStreams;
            _upcomingRecording = upcomingRecording;

            int fontHeight = SystemFonts.MessageBoxFont.Height;
            int height = _programsTop;
            if (_serverStatus != ServerStatus.NotConnected)
            {
                if (activeRecordings.Count > 0)
                {
                    height += fontHeight;
                    height += (2 * fontHeight + _programsGap) * activeRecordings.Count;
                    if (liveStreams.Count > 0
                        || upcomingRecording != null)
                    {
                        height += _programsExtraGap;
                    }
                }
                if (liveStreams.Count > 0)
                {
                    height += fontHeight;
                    height += (fontHeight + _programsGap) * liveStreams.Count;
                    if (upcomingRecording != null)
                    {
                        height += _programsExtraGap;
                    }
                }
                if (upcomingRecording != null)
                {
                    height += 2 * fontHeight + _programsGap;
                }
            }
            height += fontHeight;
            height += 10;
            this.Size = new Size(this.Width, height);

            int left = location.X;
            int top;
            Rectangle workArea = Screen.GetWorkingArea(location);
            if (workArea.Contains(location))
            {
                top = location.Y - 12 - this.Height;
            }
            else
            {
                top = int.MaxValue;
            }

            this.Opacity = 0.0;
            SetBounds(Math.Min(left, workArea.Width - this.Width - 1), Math.Min(top, workArea.Height - this.Height),
                this.Width, this.Height);

            this.Show();
        }
Esempio n. 10
0
 public void toggleActive(ServerStatus s)
 {
     if (InvokeRequired)
         Invoke(new toggleActiveDelegate(toggleActive), s);
     else
     {
         toggleInterface(s);
     }
 }
Esempio n. 11
0
        /// <summary>
        /// Constructor.
        /// </summary>
        internal EveServer()
        {
            m_status = ServerStatus.Online;

            m_serverStatusMonitor = new QueryMonitor<SerializableAPIServerStatus>(CCPAPIGenericMethods.ServerStatus,
                                                                                  OnServerStatusMonitorUpdated) { Enabled = true };

            EveMonClient.TimerTick += EveMonClient_TimerTick;
        }
Esempio n. 12
0
 public void StopServer()
 {
     if (server != null)
     {
         listenThread.Abort();
         server.Stop();
         status = ServerStatus.Stopped;
     }
 }
Esempio n. 13
0
 public void NetworkListen()
 {
     server.Start();
     status = ServerStatus.Running;
     while (true)
     {
         TcpClient client = server.AcceptTcpClient();
     }
 }
Esempio n. 14
0
        // Convenient method to prepare IrcConnection for reuse after getting disconnected
        private void Disconnected(ServerStatus status, string message, bool abortInputThread = true)
        {
            Reset(abortInputThread);

            List<Channel> chs = new List<Channel>();
            ChannelData[] cds;
            lock (Entities) cds = Entities.GetChannels();
            foreach (var cd in cds) chs.Add((Channel)cd);
            BotEnqueue(new ServerStatusEvent(status, message, new ReadOnlyCollection<Channel>(chs)));
        }
Esempio n. 15
0
        public void Reset()
        {
            TransactionStatus = ServerStatus.ProcessingClient;

            if (ServiceProxy != null)
            {
                ServiceProxy.BOCCompleted -= OnSubmitBulkOperationCompleted;
                ServiceProxy.CompleteTransactionCompleted -= OnCompleteTransactionCompleted;
            }
        }
Esempio n. 16
0
		public void PostAnalysis(DataObject data)
		{
			Status = ServerStatus.Starting;

			StopPost();

			WorkerThread = new CommThread(this, data);
			WorkerThread.Name = "PostAnalysisThread";
			WorkerThread.PostType = PostType.Analysis;
			WorkerThread.Start();
		}
Esempio n. 17
0
		public void PostAdditionalInfo(DataObject data)
		{
			Status = ServerStatus.Starting;

			StopPost();

			WorkerThread = new CommThread(this, data);
			WorkerThread.Name = "AddInfoThread";
			WorkerThread.PostType = PostType.AdditionalInformation;
			WorkerThread.Start();
		}
Esempio n. 18
0
        private void CheckServerInput()
        {
            if (Console.KeyAvailable)
            {
                ConsoleKeyInfo key = Console.ReadKey();

                //Quit requested
                if (key.Key == ConsoleKey.Escape)
                {
                    _status = ServerStatus.STOPPING;

                    Log.Write("Server shutdown requested...", LogType.SYSTEM);
                }
            }
        }
Esempio n. 19
0
        public ActionResult DownloadLog(ServerStatus Status)
        {
            string fileName = Options.LogFile;
            string ts       = DateTime.Now.ToString("_yyyyMMdd_HHmmssfff");

            try
            {
                var fs = System.IO.File.Open(fileName, FileMode.OpenOrCreate, FileAccess.Read, FileShare.ReadWrite);
                return(File(fs, "text/plain", Path.GetFileNameWithoutExtension(fileName) + ts + Path.GetExtension(fileName)));
            }
            catch (Exception /*ex*/)
            {
            }
            return(RedirectToAction("Index"));
        }
Esempio n. 20
0
        private void RaiseStatusEvent(ServerStatus status)
        {
            // Record the new status
            _Status = status;

            EventHandler <StatusEventArgs> Handler = StatusEvent;

            if (Handler != null)
            {
                Handler(this, new StatusEventArgs(status));
            }

            switch (status)
            {
            case ServerStatus.Pausing:
                RaiseAggregatedStatusMessageEvent(null, "Server(s) are pausing...");
                break;

            case ServerStatus.Resuming:
                RaiseAggregatedStatusMessageEvent(null, "Server(s) are resuming...");
                break;

            case ServerStatus.Starting:
                RaiseAggregatedStatusMessageEvent(null, "Server(s) are going online...");
                break;

            case ServerStatus.Stopping:
                RaiseAggregatedStatusMessageEvent(null, "Server(s) are going offline...");
                break;

            case ServerStatus.Paused:
                RaiseAggregatedStatusMessageEvent(null, "Server(s) are paused");
                break;

            case ServerStatus.Resumed:
                RaiseAggregatedStatusMessageEvent(null, "Server(s) have resumed");
                break;

            case ServerStatus.Started:
                RaiseAggregatedStatusMessageEvent(null, "Server(s) are online");
                break;

            case ServerStatus.Stopped:
                RaiseAggregatedStatusMessageEvent(null, "Server(s) are offline");
                FlushLog();
                break;
            }
        }
Esempio n. 21
0
        private static void Update()
        {
            Thread.Sleep(5000);

            int counter = 0;

            while (true)
            {
                if (ServerStatus.Status == ServerStatusType.SHUTDOWN_STARTED && ServerStatus.Time - TimeUtil.GetTimestamp() < 0)
                {
                    ServerStatus.SetStatus(ServerStatusType.MAINTENANCE, ServerStatus.NextTime + TimeUtil.GetTimestamp(), 0);
                }
                if (ServerStatus.Status == ServerStatusType.COOLDOWN_AFTER_MAINTENANCE && ServerStatus.Time - TimeUtil.GetTimestamp() < 0)
                {
                    ServerStatus.SetStatus(ServerStatusType.NORMAL, 0, 0);
                }

                if (counter++ % 20 == 0)
                {
                    for (int i = 0; i < EnvironmentSettings.SERVER_TYPE_COUNT; i++)
                    {
                        ServerPerformance[] entryArray = ServerManager.m_entry[i];

                        for (int j = 0; j < entryArray.Length; j++)
                        {
                            entryArray[j].SendPingMessage();
                        }
                    }

                    for (int i = 0; i < EnvironmentSettings.SERVER_TYPE_COUNT; i++)
                    {
                        ServerPerformance[] entryArray = ServerManager.m_entry[i];

                        for (int j = 0; j < entryArray.Length; j++)
                        {
                            ServerMessageManager.SendMessage(new ServerPerformanceMessage(), entryArray[j].Socket);
                        }
                    }

                    if (counter == 20)
                    {
                        counter = 1;
                    }
                }

                Thread.Sleep(500);
            }
        }
Esempio n. 22
0
        public HttpServer(string serverId = null, int port = DefaultPort, string host = "127.0.0.1")
        {
            _socketEndpoint = GetEndpoint(host, port);

            _baseEndpoint = GetBaseUri(port, host);
            _serverId = serverId ?? Util.GenerateId();
            _completedHandle = new ManualResetEvent(false);

            SetupSocket();

            _status = ServerStatus.Stopped;

            _compression = new DeflateCompressionProvider();

            RequestTimeout = TimeSpan.FromMinutes(2);
        }
Esempio n. 23
0
        public void ResetForm()
        {
            textBoxIP.Text    = "";
            textBoxIP.Enabled = true;

            buttonConnect.Text = "Connect";
            //buttonConnect.Enabled = true;

            FormClosingHandler(this, new FormClosingEventArgs(CloseReason.None, false));

            netCopy       = null;
            windowHandler = null;
            FormClosing  -= FormClosingHandler;

            serverStatus = ServerStatus.DISCONNECTED;
        }
Esempio n. 24
0
 public FrmWaiting(ServerStatus status, string TXT = "Waiting For Server")
 {
     _txt = TXT;
     InitializeComponent();
     if (status == ServerStatus.Waiting)
     {
         circularProgressBar1.Maximum = 120;
         aTimer.Tick    += new EventHandler(Timer_Tick);
         aTimer.Interval = 800;
         aTimer.Enabled  = true;
     }
     else
     {
         circularProgressBar1.Maximum = 100;
     }
 }
        public async Task IsServerStarted_NoServerProcessCreated_ReturnsServerStopped()
        {
            var dedicatedServer = PrepareDedicatedServer();
            var expectedStatus  = new ServerStatus();

            SetupServerStatusReturn(expectedStatus);

            var cancellationTokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(5));
            var serverStatus            = await dedicatedServer.GetServerStatusAsync(cancellationTokenSource.Token);

            using (new AssertionScope())
            {
                serverStatus.Should().BeEquivalentTo(expectedStatus);
                dedicatedServer.IsServerStopped.Should().BeTrue();
            }
        }
        public async Task TryStart()
        {
            using (await _lock.LockAsync())
            {
                if ((_config.userIds.All(id => _clients.Keys.Contains(id)) && _clients.Values.All(client => client.Status == PlayerStatus.Ready) || _config.Public) && _status == ServerStatus.WaitingPlayers)
                {
                    _status = ServerStatus.Starting;
                    _logger.Log(LogLevel.Trace, "gamesession", "Starting game session.", new { });
                    await Start();

                    _logger.Log(LogLevel.Trace, "gamesession", "Game session started.", new { });
                    var ctx = new GameSessionStartedCtx(_scene, _clients.Select(kvp => new Player(kvp.Value.Peer, kvp.Key)));
                    await _eventHandlers()?.RunEventHandler(eh => eh.GameSessionStarted(ctx), ex => _logger.Log(LogLevel.Error, "gameSession", "An error occured while running gameSession.Started event handlers", ex));
                }
            }
        }
 private void WriteState(object sender, SocketMessage <ServerStatus> message)
 {
     data = message.data;
     if (data.databaseNotice != "")
     {
         Debug.LogWarning("Database notice :" + data.databaseNotice);
     }
     if (data.onlineNotice != "")
     {
         Debug.LogWarning("Online notice :" + data.onlineNotice);
     }
     if (data.gameServerNotice != "")
     {
         Debug.LogWarning("GameServer notice :" + data.gameServerNotice);
     }
 }
Esempio n. 28
0
        /// <summary>
        /// Set up ENet Server prior to launch. Will set up necessary managers as well.
        /// </summary>
        private void Initialize(int max_clients = 16, bool isLive = false)
        {
            Log.Write("Initializing Server Configs...", LogType.SYSTEM);
            _configs = new ServerConfigs()
            {
                MAX_CLIENTS = max_clients,
                PORT        = 7735
            };

            // Initialize Server Managers
            InitializeManagers();

            ENet.Library.Initialize();

            _status = ServerStatus.OFF;
        }
        public ServerStatus Get()
        {
            var retVal = new ServerStatus
            {
                Identifier = _server.Identifier,
                ListeningForServerRequests        = _server.Communicator.ListeningForServerJobs,
                ListeningForRegistrationRequests  = _server.Communicator.ListeningForRegistrations,
                ListeningForAliasMessages         = _server.Communicator.ListeningForAliasMessages,
                ListeningForClientSessionMessages = _server.Communicator.ListeningForClientSessionMessages,
                Plugins = _server.GetPlugins().Select(p => p.GetType().Name).ToArray(),
                State   = _server.Communicator.State.OrderBy(e => e.Key).ToArray(),
                Uptime  = DateTime.Now - Process.GetCurrentProcess().StartTime
            };

            return(retVal);
        }
Esempio n. 30
0
 private void timer1_Tick(object sender, EventArgs e)
 {
     try
     {
         using (var client = new WebClient())
         {
             HtmlCode = client.DownloadString("https://superwow.ru/launcher/component.php");
             HtmlCode = HtmlCode + "\n" + "Server latency " + ServerStatus.PingHost("wow.superwow.ru");
         }
     }
     catch
     {
         HtmlCode = "Server Offline";
     }
     linkLabel1.Text = HtmlCode;
 }
Esempio n. 31
0
        private Task ChangeStatus(ServerStatus newStatus)
        {
            var oldStatus = this.Status;

            this.Status = newStatus;

            return(this.hubContext.Clients.All.SendAsync("server", new ServerNotification <StatusPayload>
            {
                NotificationType = NotificationType.StatusChange,
                Payload = new StatusPayload
                {
                    OldStatus = oldStatus,
                    NewStatus = newStatus
                }
            }));
        }
Esempio n. 32
0
        public int CountOnServers( )
        {
            int count = 0;

            ViewElementsMutex.WaitOne( );
            for (int i = 0; i < ViewElements.Length; i++)
            {
                ServerStatus status = ViewElements[i];
                if (!(status == ServerStatus.Off || status == ServerStatus.Unknown))
                {
                    count++;
                }
            }
            ViewElementsMutex.ReleaseMutex( );
            return(count);
        }
Esempio n. 33
0
        public MainWindow()
        {
            InitializeComponent();

            ServicePointManager.DefaultConnectionLimit = 40;
            _message = new Messaging(this);

            AddBinding();
            DisplayVersion();
            UpgradeSettings();
            CleanLog();

            ServerStatus   = new ServerStatus(this);
            DowntimeNotice = new DownTimeNotice(this);
            CouponCode     = new Coupon(this);
        }
Esempio n. 34
0
        public List <int> GetOnlineServers( )
        {
            List <int> online = new List <int>();

            ViewElementsMutex.WaitOne();
            for (int i = 0; i < ViewElements.Length; i++)
            {
                ServerStatus status = ViewElements[i];
                if (status == ServerStatus.Online)
                {
                    online.Add(i);
                }
            }
            ViewElementsMutex.ReleaseMutex();
            return(online);
        }
        /// <summary>
        /// Updates the list of <see cref="KimsufiServerStatus"/>.
        /// </summary>
        /// <param name="serverStatus">The list of <see cref="KimsufiServerStatus"/>.</param>
        public void SetKimsufiServerStatus(IList <ServerStatus> serverStatus)
        {
            this.InvokeOnUiThreadIfRequired(() =>
            {
                foreach (ServerStatus item in serverStatus)
                {
                    // Does the item already exists in the binding source ?
                    var listEnumerator = internalServerStatus.GetEnumerator();
                    bool isEdited      = false;
                    while (listEnumerator.MoveNext())
                    {
                        ServerStatus colItem = listEnumerator.Current;
                        if (colItem.Name == item.Name && colItem.GeographicZone == item.GeographicZone)
                        {
                            bool shouldAlert = false;
                            // Check alerts (if we watch a specific server, that was previously unavailable and is now available).
                            if (colItem.Watch && colItem.IsAvailable == false && item.IsAvailable == true)
                            {
                                shouldAlert = true;
                            }

                            // Perform item update.
                            colItem.GeographicZone   = item.GeographicZone;
                            colItem.IsAvailable      = item.IsAvailable;
                            colItem.Memory           = item.Memory;
                            colItem.Network          = item.Network;
                            colItem.Price            = item.Price;
                            colItem.Processor        = item.Processor;
                            colItem.ProcessorDetails = item.ProcessorDetails;
                            colItem.Storage          = item.Storage;

                            isEdited = true;

                            if (shouldAlert)
                            {
                                AlertFor(colItem);
                            }
                        }
                    }

                    if (!isEdited)
                    {
                        internalServerStatus.Add(item);
                    }
                }
            });
        }
Esempio n. 36
0
        //@Override
        public bool addPemissionAccepted(String replierId, int replierLogicalClock, String replierHostUrl, int replierHostPort, String requesterId, int requesterLogicalClock)
        {
            //the clock will manage here too

            //The first 2 objects used for correcting the clock
            //The third one used for deleting the host from the tail list ! and not from the queue
            //The last 2 objects are used for checking true answering

            //this will call by other clients to send [rep<id,clock> --to--> req<id',clock'>] actually OK message!
            //when they want to send a OK reply to our previous request they must call this function
            //this function will remove RequestObjects from the tail list
            try{
                if (!ServerStatus.getServerStatus())
                {
                    return(false);
                }

                if (currentAddRequest != null)
                {
                    long    requesterIdL = 0;
                    HostUrl hostUrl      = null;
                    try
                    {
                        requesterIdL = Convert.ToInt64(requesterId);
                        hostUrl      = new HostUrl(replierHostUrl, replierHostPort);
                    }
                    catch (Exception)
                    {
                        return(false);
                    }
                    //correcting Clock
                    ExtendedLamportClockObject ELC = new ExtendedLamportClockObject(requesterIdL, requesterLogicalClock); //for correcting logical clock after receive

                    if (currentAddRequest.getELCO().compare(ELC) == 0)                                                    //if the replier send the reply for the current request
                    {
                        lock (this)
                        {
                            currentAddRequest.removeNode(hostUrl);
                        }
                        hostUrl = null;
                        ELC     = null;
                    }
                    return(true);
                }
                return(false);
            }catch (Exception) { return(false); }
        }
Esempio n. 37
0
        /// <summary>
        /// 获取服务状态
        /// </summary>
        /// <returns></returns>

        public ServerStatus GetServerStatus()
        {
            if (RunTimeWatch.GetRunTimeMilliseconds() - _mLastGetTime > 1000)
            {
                if (System.Threading.Interlocked.CompareExchange(ref _mGetStatus, 1, 0) == 0)
                {
                    _mLastGetTime = RunTimeWatch.GetRunTimeMilliseconds();
                    ServerStatus result = new ServerStatus();
                    TimeSpan     ts     = (DateTime.Now - RunTimeWatch.StartTime);
                    result.RunTime = $"{(long)ts.Days}:{(long)ts.Hours}:{(long)ts.Minutes}:{(long)ts.Seconds}";

                    long   time   = RunTimeWatch.GetRunTimeMilliseconds();
                    double second = (double)(time - _mLastTime) / 1000d;
                    _mLastTime = time;
                    double cpuTime     = mProcess.TotalProcessorTime.TotalMilliseconds;
                    long   cpuFullTime = (long)(second * _mCpuMaxTime);
                    double useTime     = cpuTime - _mLastTotalProcessorTime;
                    _mLastTotalProcessorTime = cpuTime;
                    result.Cpu = (int)((useTime / cpuFullTime) * 10000) / 100d;

                    if (result.Cpu > 100)
                    {
                        result.Cpu = 100;
                    }
                    if (result.Cpu < 0)
                    {
                        result.Cpu = 0;
                    }
                    result.Memory = (Environment.WorkingSet / 1024) / 1024;
                    _mInfo        = result;
                    System.Threading.Interlocked.Exchange(ref _mGetStatus, 0);
                }
            }
            var metrics = memoryMetricsClient.GetMetrics();

            _mInfo.MemoryTotal    = metrics.Total;
            _mInfo.MemoryTotalUse = metrics.Used;
            _mInfo.CpuTotalUse    = GetCpuTotalUse();
            _mInfo.Drives         = AnnoDrives.GetDrivesInfo();
            if (_mInfo.Cpu > _mInfo.CpuTotalUse)
            {
                _mInfo.CpuTotalUse = _mInfo.Cpu;
            }

            _mInfo.EngineCounter = Engine.EngineCounter;
            return(_mInfo);
        }
Esempio n. 38
0
 private string ServerStatusResponseLabel(ServerStatus s)
 {
     string response;
     switch (s)
     {
         case ServerStatus.ShutdownInitiated:
             response = "Shutdown in progress";
             break;
         case ServerStatus.ShutdownCancelled:
             response = "Ready";
             break;
         default:
             response = null;
             break;
     }
     return response;
 }
Esempio n. 39
0
        /// <summary>
        /// Returns the current server status.
        /// </summary>
        /// <returns>The current server status.</returns>
        public ServerStatus GetStatus()
        {
            ServerStatus output = null;

            lock (this)
            {
                if (m_server == null)
                {
                    throw new Exception("The remote server is not currently connected.");
                }

                // initialize arguments.
                IntPtr pStatus = IntPtr.Zero;

                // invoke COM method.
                try
                {
                    ((IOPCServer)m_server).GetStatus(out pStatus);
                }
                catch (Exception e)
                {
                    throw Interop.CreateException("IOPCServer.GetStatus", e);
                }


                if (pStatus != IntPtr.Zero)
                {
                    OpcRcw.Da.OPCSERVERSTATUS status = (OpcRcw.Da.OPCSERVERSTATUS)Marshal.PtrToStructure(pStatus, typeof(OpcRcw.Da.OPCSERVERSTATUS));

                    output = new ServerStatus();

                    output.VendorInfo     = status.szVendorInfo;
                    output.ProductVersion = String.Format("{0}.{1}.{2}", status.wMajorVersion, status.wMinorVersion, status.wBuildNumber);
                    output.ServerState    = (serverState)status.dwServerState;
                    output.StatusInfo     = null;
                    output.StartTime      = Interop.GetFILETIME(HD.OPC.Client.Core.Com.Convert.GetFileTime(status.ftStartTime));
                    output.CurrentTime    = Interop.GetFILETIME(HD.OPC.Client.Core.Com.Convert.GetFileTime(status.ftCurrentTime));
                    output.LastUpdateTime = Interop.GetFILETIME(HD.OPC.Client.Core.Com.Convert.GetFileTime(status.ftLastUpdateTime));

                    Marshal.DestroyStructure(pStatus, typeof(OpcRcw.Da.OPCSERVERSTATUS));
                    Marshal.FreeCoTaskMem(pStatus);
                    pStatus = IntPtr.Zero;
                }
            }
            return(output);
        }
Esempio n. 40
0
        public INode CreateInProcessObjects()
        {
            if (_inProcessResponse == null)
            {
                _inProcessResponse = MapManager.NodeFactory.CreateNode(this, DomainParameter.GetParameterValue(Guid.Empty).V, RootMapParameter.GetParameterValue(Guid.Empty).V, NodeType, OriginalId);
                TransactionStatus  = ServerStatus.ProcessingClient;
                FacadeNode facadeNode = _inProcessResponse as FacadeNode;

                if (facadeNode != null)
                {
                    facadeNode.TransactionOrigin = this;
                    _inProcessResponse           = facadeNode;
                }
            }

            return(_inProcessResponse);
        }
Esempio n. 41
0
        public void StartGame()
        {
            switch (status)
            {
                case ServerStatus.Idle:
                    throw new Exception("Server not initiated");
                case ServerStatus.WaitingConnections:
                    break;
                case ServerStatus.GameStarted:
                    throw new Exception("Game already started.");
                default:
                    throw new ArgumentOutOfRangeException("status");
            }

            status = ServerStatus.GameStarted;
            //TODO start game process
        }
Esempio n. 42
0
        public ActionResult EmptyLog(ServerStatus Status)
        {
            ServerStatus.KillAll();
            try
            {
                if (System.IO.File.Exists(Options.LogFile))
                {
                    System.IO.File.Delete(Options.LogFile);
                }
            }
            catch { }
            ServerStatus.Start(Status.StartVisible);
            var model = new ServerStatus();

            model.StartVisible = Status.StartVisible;
            return(View("Index", model));
        }
Esempio n. 43
0
 public void Open()
 {
     SetGame(Game);
     Status        = ServerStatus.Starting;
     NetworkServer = new Lidgren.Network.NetServer(
         SetupNetwork(new Lidgren.Network.NetPeerConfiguration("MPTANKS")
     {
         ConnectionTimeout  = 15,
         AutoFlushSendQueue = false,
         Port = Configuration.Port,
         MaximumConnections = Configuration.MaxPlayers + 4 //so we can gracefully disconnect
     }));
     NetworkServer.Start();
     Status = ServerStatus.Open;
     Logger.Info($"Server started on port {Configuration.Port}. Configuration: ");
     Logger.Info(Configuration);
 }
Esempio n. 44
0
 protected override void OnUpdate()
 {
     if (Status == ServerStatus.SteamPending)
     {
         if (Attach(true))
         {
             DisableUpdates();
             steamLaunchRetryCount = 0;
         }
         else if (++steamLaunchRetryCount > STEAMMODE_MAX_RETRY)
         {
             Logger.Log(LogLevel.Error, "Server didn't start after {0} retries. Assuming it has crashed.", steamLaunchRetryCount.ToString());
             status = ServerStatus.Offline;
             DisableUpdates();
         }
     }
 }
        public Proxy.IRelationship CreateInProcessObjects()
        {
            if (_inProcessResponse == null)
            {
                _inProcessResponse = MapManager.RelationshipFactory.CreateRelationship(this, DomainParameter.GetParameterValue(Guid.Empty).V, RootMapParameter.GetParameterValue(Guid.Empty).V, ProxyNodeConnections, RelationshipType, OriginalId);
                TransactionStatus  = ServerStatus.ProcessingClient;
                FacadeRelationship facadeRelationship = _inProcessResponse as FacadeRelationship;

                if (facadeRelationship != null)
                {
                    facadeRelationship.TransactionOrigin = this;
                    _inProcessResponse = facadeRelationship;
                }
            }

            return(_inProcessResponse);
        }
Esempio n. 46
0
        //=========================================================================
        //
        //  AJAX ACTIONS
        //
        //=========================================================================

        /// <summary>
        /// Fetches the instance log by connecting to its mongod server.
        /// This is fast and cheap, but won't work if the instance is down.
        /// </summary>
        public JsonResult GetServerLog(int id)
        {
            var server = ServerStatus.Get(id);
            var mongo  = MongoServer.Create(new MongoServerSettings {
                ConnectTimeout = new TimeSpan(0, 0, 3), Server = MongoServerAddress.Parse(server.Name), SlaveOk = true
            });

            try
            {
                var result = mongo["admin"]["$cmd"].FindOne(Query.EQ("getLog", "global"));
                return(Json(new { log = HtmlizeFromLogArray(result.AsBsonDocument["log"].AsBsonArray) }, JsonRequestBehavior.AllowGet));
            }
            catch (MongoException e)
            {
                return(Json(new { error = e.Message }, JsonRequestBehavior.AllowGet));
            }
        }
Esempio n. 47
0
        internal static bool ReceiveCoreMessage(ServerCoreMessage message)
        {
            switch (message.GetMessageType())
            {
            case ServerMessageType.PING:
                ServerMessageManager.SendMessage(new PongMessage(), message.Sender);
                return(true);

            case ServerMessageType.SERVER_STATUS:
                ServerStatusMessage serverStatusMessage = (ServerStatusMessage)message;
                ServerStatus.SetStatus(serverStatusMessage.Type, serverStatusMessage.Time, serverStatusMessage.NextTime);
                return(true);

            default:
                return(false);
            }
        }
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            ServerStatus serverStatus = (ServerStatus)value;

            switch (serverStatus)
            {
            case ServerStatus.Attached:
            case ServerStatus.Connected:
                return("/MP2-ServiceMonitor1.ico");

            case ServerStatus.ClientConnected:
                return("/MP2-ServiceMonitor.ico");

            default:
                return("/MP2-ServiceMonitor0.ico");
            }
        }
Esempio n. 49
0
        public static string FriendlyName(this ServerStatus serverStatus)
        {
            string s = serverStatus.ToString();

            return(s.First() + s.Substring(1).ToLower(CultureInfo.InvariantCulture));

            switch (serverStatus)
            {
            case ServerStatus.RUNNING: return("Running");

            case ServerStatus.STARTING: return("Starting");

            case ServerStatus.STOPPED: return("Stopped");

            default: return("Horrible Failure!!!");
            }
        }
        //@Override
        public String syncRequest(String lastModificationString)
        {
            //Called by remote hosts to get list of appointments for synchronization
            //At first we wanted to optimize it by last modification time but because it was not said in the assignment sheet we
            //decided to drop this section!

            //because in C# XmlRpcServer Library stopping the servicing has an error we refuse the incoming requests if the server
            //is not in its online mode.
            if (!ServerStatus.getServerStatus())
            {
                return(null);
            }

            //Date lastModification = new Date(lastModificationString);

            return(this.appointmentsSerialize());
        }
Esempio n. 51
0
        public void Reset()
        {
            _onCompletedBound = false;

            TransactionStatus = ServerStatus.ProcessingClient;

            if (_firstLink != null)
            {
                ISoapTransactionLinkExecutor executor = _firstLink as ISoapTransactionLinkExecutor;
                executor.TransactionFailed -= OnTransactionFailed;
                executor.TransactionCompleted -= OnTransactionCompleted;
            }

            if (ServiceProxy != null)
            {
                ServiceProxy.BeginTransactionCompleted -= OnBeginTransactionCompleted;
            }
        }
Esempio n. 52
0
        private void Disconnect(ServerStatus? status, string message)
        {
            if (_disposed) return;

            try { _connectorThread.Abort(); } catch (Exception) { }
            try { _inThreadTimeout.Dispose(); } catch (Exception) { }
            try { _inThread.Abort(); } catch (Exception) { }
            try { _ircInStream.Dispose(); } catch (Exception) { }
            try { _ircOutStream.Dispose(); } catch (Exception) { }
            try { _irc.Close(); } catch (Exception) { }

            if (!status.HasValue) {
                status = (IrcAuthenticated ? ServerStatus.Disconnected : ServerStatus.ConnectFailed);
            }
            Enqueue(new ServerStatusEvent(status.Value, message, Entities.GetChannels()));

            _disposed = true;
            IrcAuthenticated = false;
        }
Esempio n. 53
0
 public DataModel(MainWindow mainWindow)
 {
     MainWindow = mainWindow;
     ServerList = new ServerList();
     ServerSession = new ServerSession(this);
     ServerStatus = new ServerStatus(this);
     Database = new Database(this);
     QuickSearch = new QuickSearch(this);
     AdvancedSearch = new AdvancedSearch(this);
     DatabaseView = new DatabaseView(this);
     StreamsCollection = new StreamsCollection();
     SavedPlaylists = new SavedPlaylists(this);
     CurrentSong = new CurrentSong(this);
     Playlist = new Playlist(this);
     OutputCollection = new OutputCollection(this);
     CustomDateNormalizer = new DateNormalizer();
     CustomDateNormalizer.ReadFromSettings();
     YearNormalizer = new DateNormalizer(new string[] {"YYYY"});
 }
Esempio n. 54
0
        private Int32 port; // the port on which the server is listening

        #endregion Fields

        #region Constructors

        /// <summary>
        /// the basic constructor which initializes a TCPServer-Object
        /// and the sets the values of the Object which therefore are 
        /// needed to start the TCPServer successfully afterwards
        /// </summary>
        public TCPServer()
        {
            // TCP Objects
            this.clientThreads = new List<Thread>();    // initializes a list of threads which contains the active clients processes
            this.clients       = new List<Object>();    // initializes a list of threads which contains the active clients

            // Status
            this.status   = new ServerStatus();         // initializes the ServerStatus-Object which represents the current status of the server
            this.status   = ServerStatus.STOPPED;       // sets the ServerStatus to STOPPED as default, because the server isn't able to start in this state

            // MaxMessageSize
            this.MaxMessageSize = 1500;                 // maximal 1500 Bytes can a recieved message have

            // MaxClients
            this.MaximalAllowedClients = new Int32();             // no limited number of allowed clients

            // Encoding
            this.MessageEncoding = new UTF8Encoding();  // the Encoding algorithmus which is uses to encode the recieved messages

            // Name of the TCPServer
            this.Name = "TCPServer";                    // sets the Name of the TCPServer as global variable
        }
Esempio n. 55
0
 /// <summary>
 /// Sets the state of the server.
 /// </summary>
 /// <param name="status">The status that the server needs to be set with.</param>
 public void SetServerState(ServerStatus status)
 {
     this.windowsServer.Status = status;
 }
Esempio n. 56
0
        /// <summary>
        ///     Поломка.
        /// </summary>
        public override void Break()
        {
            // Если резервоное копирование уже было произведено.
            if (!(BackupSupport && CrashCount == 0))
            {
                // Получение случайного времени починки.
                RepairTime = new TimeSpan(Simulation.DateTimeSpan.Ticks*Generator.Randomizer.Next(1, 10));

                Status = ServerStatus.Broken;
            }

            CrashCount++;
        }
Esempio n. 57
0
 /// <summary>
 ///     Обновление состояния.
 /// </summary>
 /// <param name="dateTime">Текущее время.</param>
 public override void Update(DateTime dateTime)
 {
     switch (Status)
     {
         case ServerStatus.Working:
         {
             TryFailure();
             break;
         }
         case ServerStatus.Broken:
         {
             Status = ServerStatus.Repairing;
             break;
         }
         case ServerStatus.Repairing:
         {
             RepairTime -= Simulation.DateTimeSpan;
             if (RepairTime == TimeSpan.Zero)
             {
                 Status = ServerStatus.Repaired;
             }
             break;
         }
         case ServerStatus.Repaired:
         {
             Status = ServerStatus.Working;
             break;
         }
     }
 }
Esempio n. 58
0
        ///<summary>
        /// starts an endless loop which accepts new clients
        ///</summary>
        protected virtual void ListenForClients()
        {
            try
            {
                this.tcpListener.Start();               // start the tcpListener
                this.status = ServerStatus.RUNNING;     // set the ServerStatus to RUNNING
            }

            // catch any SocketException
            catch (SocketException)
            {
                this.Stop();                                                                // stop the whole TCPServer
                throw new Exception("Starting server on port " + this.Port + " failed");    // throw that Exception
            }
        }
Esempio n. 59
0
        ///<summary>
        /// Stops the TCPServer
        ///</summary>
        public virtual void Stop()
        {
            // if the Server is running or paused
            if (this.status == ServerStatus.RUNNING || this.status == ServerStatus.PAUSED)
            {

                try
                {
                    // Set the status to STOPPED each endless while loop is running as long
                    // as the ServerStatus isn't STOPPED
                    this.status = ServerStatus.STOPPED;

                    // check the polymorph typ of the current object
                    switch (this.GetType().Name)
                    {

                        // if the type of the current object is "TCPServer_ByteBased"
                        case "TCPServer_ByteBased":

                            // Do for each socket in the list of clients
                            foreach (Socket socket in this.clients)
                            {
                                // if the socket is established
                                if (socket.Connected)
                                    socket.Disconnect(false);   // Disconnect from the server

                                socket.Shutdown(SocketShutdown.Both);   // Stops recieving and sending packets
                                socket.Close();                         // close the socket
                                this.clients.Remove(socket);            // remove this client from the list of clients

                            }

                            break;

                        // if the type of the current object is "TCPServer_Streambased"
                        case "TCPServer_Streambased":

                            // Do for each TcpClient in the list of clients
                            foreach (TcpClient tcpclient in this.clients)
                            {

                                // if the socket is established
                                if (tcpclient.Connected)
                                    tcpclient.Close();          // close the tcp connection

                                this.clients.Remove(tcpclient); // remove this clients form the list of clients

                            }

                            break;
                    }

                    // Do for each thread in clientThreads
                    foreach (Thread clientThread in this.clientThreads)
                    {
                        // if the clientThread is running
                        if (clientThread.IsAlive)
                            clientThread.Abort();   // abort the clientThread
                    }

                    // if the listenThread is running
                    if (this.listenThread.IsAlive)
                    {
                        this.listenThread.Abort();  // abort the listenThread
                    }

                    this.tcpListener.Stop();    // stop the tcpListener

                }

                // catch any exception
                catch (Exception ex)
                {
                    Console.WriteLine("Error by closing TCPServer \n " + ex.Message);
                }

            }
        }
Esempio n. 60
0
        ///<summary>
        /// starts the TCPServer
        ///</summary>
        public void Start()
        {
            // if the setted IPAddress isn't null and
            // the setted Port isn't 0, means not configured
            if (this.ipAddress != null && this.port != 0)
            {
                // initialize a new TCPListener with the seted IPAddress and Port
                this.tcpListener = new TcpListener(this.ipAddress, this.port);
            }

            // else throw an Exception that report that the IPAddress or Port either isn't configured
            else throw new Exception("No IPAddress or Port is setted");

            this.listenThread = new Thread(new ThreadStart(ListenForClients));  // initialize a new Thread that works as "Listen for Clients"-Thread
            this.listenThread.Start();                                          // start the listenThread; since yet the server is able to accept clients

            this.status   = ServerStatus.RUNNING;   // switch the ServerStatus to "RUNNING"
        }