Ejemplo n.º 1
0
        private PingService CreatePingService()
        {
            var userId  = Guid.Parse(User.Identity.GetUserId());
            var service = new PingService(userId);

            return(service);
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Initializes a new instance of the <see cref="PingTaskUnitTests"/> class.
        /// </summary>
        /// <param name="testOutputHelper">The test output helper.</param>
        /// <autogeneratedoc />
        public PingTaskUnitTests(ITestOutputHelper testOutputHelper) : base(testOutputHelper)
        {
            var commonServices = CommonServices.CreateInstance(TestLoggerFactory, "PingTaskUnitTests");

            _pingService = new PingService(commonServices);
            _pingTask    = new PingService.PingTaskImpl(commonServices);
        }
Ejemplo n.º 3
0
 private void btn_Ping_val_Click(object sender, EventArgs e)
 {
     try
     {
         //初始化Ping服务
         using (PingService pingService = new PingService(tbx_Host.Text.Trim()))
         {
             if (pingService.TTLStatus)
             {
                 text_PingContent.Text = string.Empty;
                 text_PingContent.Text = $"访问花费时间(毫秒):{pingService.PingTimeOut},丢包数量:{pingService.TTL},此连接:{tbx_Host.Text.Trim()}状态良好!";
             }
             else
             {
                 text_PingContent.Text = string.Empty;
                 text_PingContent.Text = $"访问花费时间(毫秒):{pingService.PingTimeOut},丢包数量:{pingService.TTL},此连接:{tbx_Host.Text.Trim()}状态缓慢,请检查相关网络!";
             }
         }
     }
     catch (Exception ex)
     {
         text_PingContent.Text = string.Empty;
         text_PingContent.Text = $"测试连接异常,异常原因:{ex.Message}";
     }
 }
Ejemplo n.º 4
0
        protected override Server ConfigureServer()
        {
            GrpcEnvironment.SetLogger(new ConsoleLogger());

            var env         = _resolver.GetRequiredService <IHostingEnvironment>();
            var host        = Config["Hosts:Local:Host"];
            var port        = Config["Hosts:Local:Port"].ConvertTo <int>();
            var serviceName = Config["Hosts:ServiceName"];

            if (env.IsDevelopment())
            {
                IdentityModelEventSource.ShowPII = true;
            }

            if (!env.IsDevelopment())
            {
                port = Environment.GetEnvironmentVariable($"{serviceName.ToUpperInvariant()}_HOST").ConvertTo <int>();
            }

            _server = new Server
            {
                Services =
                {
                    ReviewService.BindService(new ReviewServiceImpl(_resolver)).Intercept(new AuthNInterceptor(_resolver)),
                    PingService.BindService(new PingServiceImpl(_resolver)).Intercept(new AuthNInterceptor(_resolver)),
                    Grpc.Health.V1.Health.BindService(new HealthImpl())
                },
                Ports = { new ServerPort(host, port, ServerCredentials.Insecure) }
            };

            Logger.LogInformation($"{nameof(ReviewService)} is listening on {host}:{port}.");
            return(_server);
        }
Ejemplo n.º 5
0
    /// <summary>
    /// Executes the pings from the new thread.
    /// </summary>
    /// <param name="item">
    /// The publishable item.
    /// </param>
    /// <param name="itemUrl">
    /// The item Url.
    /// </param>
    private static void Ping(IPublishable item, Uri itemUrl)
    {
        try
        {
            Thread.Sleep(2000);

            // Ping the specified ping services.
            PingService.Send(itemUrl);

            // Send trackbacks and pingbacks.
            if (!BlogSettings.Instance.EnableTrackBackSend && !BlogSettings.Instance.EnablePingBackSend)
            {
                return;
            }

            if (item.Content.ToUpperInvariant().Contains("\"HTTP"))
            {
                Manager.Send(item, itemUrl);
            }
        }
        catch (Exception)
        {
            // We need to catch this exception so the application doesn't get killed.
        }
    }
Ejemplo n.º 6
0
        public static void RunInit()
        {
            if (Settings.IsEmpty())
            {
                throw new ArgumentNullException(nameof(Settings));
            }
            ConnectedClients   = new Dictionary <Guid, Client>();
            ConnectionListener = new TcpListener(new IPEndPoint(IPAddress.Any, Settings.Port));
            ConnectionListener.Start();

            PingService = new PingService(new Dictionary <Guid, Client>());
            PingService.Start();
            MainLoopTask = new Action(() =>
            {
                while (!MainLoopAbort)
                {
                    try
                    {
                        TcpConnection conn = (TcpConnection)ConnectionListener.AcceptTcpClient();
                        Console.WriteLine("[MasterListener] accept connection");
                        // Spawn a new PacketListenerLoop
                        PacketListenerLoop.Spawn(conn, new Server_PacketHandler(conn));
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e.Message);
                    }
                }
            });
            MainLoopAbort = false;
            //Run
            Task.Run(MainLoopTask);
            Console.WriteLine("Listening for connections...");
        }
Ejemplo n.º 7
0
        private void btnPing_Clicked(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(edtHostname.Text))
            {
                var pings = new PingService().Ping(edtHostname.Text.Trim(), 10);

                gridPing.RowDefinitions = new RowDefinitionCollection();

                gridPing.ColumnDefinitions = new ColumnDefinitionCollection();

                int i = 0;
                foreach (var ping in pings)
                {
                    gridPing.Children.Add(new Label
                    {
                        Padding           = 2,
                        Text              = ping.ToString(),
                        HorizontalOptions = LayoutOptions.FillAndExpand,
                        VerticalOptions   = LayoutOptions.FillAndExpand
                    }, 0, i);
                    i++;
                }
            }
            else
            {
                gridPing.IsVisible = false;
                slMsg.IsVisible    = true;
                msg.Text           = "[IP/Hostname not identified]";
            }
        }
Ejemplo n.º 8
0
        public async Task should_handle_null_ping()
        {
            var p      = new PingService();
            var actual = await p.DoLookUp(null, AddressType.DomainName);

            Assert.IsNotNull(actual.ErrorMessage);
            Assert.AreEqual(ServiceStatus.Bad, actual.Status);
        }
Ejemplo n.º 9
0
        public async Task should_ping_domain()
        {
            var p      = new PingService();
            var actual = await p.DoLookUp("calebukle.com", AddressType.DomainName);

            Assert.IsNotNull(actual.Data);
            Assert.AreEqual(ServiceStatus.Ok, actual.Status);
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Initializes a new instance of the <see cref="PingServiceIntegrationTests"/> class.
        /// </summary>
        /// <param name="testOutputHelper">The test output helper.</param>
        /// <autogeneratedoc />
        public PingServiceIntegrationTests(ITestOutputHelper testOutputHelper) : base(testOutputHelper)
        {
            var commonServices = CommonServices.CreateInstance(TestLoggerFactory, "PingServiceIntegrationTests");

            _pingService = new PingService(commonServices);
            _pingService.OnPingReplyService += PingReplyEventHandler;
            _networkingSystem = new NetworkingSystem(TestLoggerFactory.CreatePureLogger <NetworkingSystem>());
        }
 public RestritoTwitchController(
     IConfiguration configuration,
     EnfileiradorClient enfileiradorClient,
     EmpresaSettings empresaSettings,
     PingService pingService
     ) : base(configuration, empresaSettings)
 {
     base.enfileiradorClient = enfileiradorClient;
     this.pingService        = pingService;
 }
Ejemplo n.º 12
0
        public static PingMessage SendPing()
        {
            PingMessage        pingMessage = PingService.CreatePingMessage();
            Task <PongMessage> task        = SendPingAsync(pingMessage);

            task.Wait(60000);
            PongMessage pongMessage = task.Result;

            consumer.MessageReceived -= delegates[task];
            return(pingMessage);
        }
Ejemplo n.º 13
0
        public static void Run()
        {
            LogHelper.Info("Start crawling");
            //MovieService.GrabHotMovie();
            //PositionService.GrabPositionInfo(100);
            //QDailyService.GrabIQDailynfo();
            var ping = new PingService();

            ping.PingWebsite(times);
            //PingService.PingWebsite();
            LogHelper.Info("Finish crawling");
        }
        public void 业务系统服务器是否稳定()
        {
            var host = "www.baidu.com";

            using (PingService pingService = new PingService(host))
            {
                if (pingService.TTLStatus)
                {
                    Console.WriteLine(pingService.TTLStatus);
                }
            }
        }
Ejemplo n.º 15
0
        private void InitPingService()
        {
            _pingService = new PingService();
            _pingHost    = new ServiceHost(_pingService);
            _pingHost.Open();
            _pongClientFactory = new ClientFactory <IPong>("*");
            _pongClient        = _pongClientFactory.GetClient();

            _pings = Observable.FromEventPattern <Service.Events.PingEventArgs>(handler => _pingService.PingRequest += handler,
                                                                                handler => _pingService.PingRequest -= handler)
                     .Select(_ => new PingEventArgs())
                     .ObserveOn(Scheduler.Default);
            _pings.Subscribe(OnPing);
        }
Ejemplo n.º 16
0
        public async Task When_CallPing_And_DatabaseIsUp_Should_ReturnSuccessfulPing()
        {
            var dbContextMock = new Mock <IDatabaseContext>(MockBehavior.Strict);

            dbContextMock.Setup(databaseContext => databaseContext.PingAsync()).ReturnsAsync(30.0);

            var pingService = new PingService(dbContextMock.Object);

            var pingCheckResponse = await pingService.Ping();

            Assert.IsNotNull(pingCheckResponse.ServerTime);
            Assert.AreEqual(30.0, pingCheckResponse.DatabasePing);
            Assert.IsTrue(pingCheckResponse.DatabaseStatus);
        }
Ejemplo n.º 17
0
        public async Task PingAsync([Remainder] string message = null)
        {
            IPAddress IP;

            //Validates whether argument exists
            if (string.IsNullOrEmpty(message))
            {
                await ReplyAsync("Must supply an IP address.");
            }
            else
            {
                string ipAddr = "";

                //Custom ip for minecraft
                if (message == "minecraft")
                {
                    ipAddr = Config["MinecraftIP"];
                }
                else
                {
                    ipAddr = message;
                }

                //Validates given ip address
                if (!(IPAddress.TryParse(ipAddr.Split(':')[0], out IP)))
                {
                    await ReplyAsync(ipAddr + " is not a valid IP address.");
                }
                else
                {
                    //Ping the specified server
                    PingReply reply;
                    reply = PingService.PingRequest(ipAddr);

                    if (reply.Status == IPStatus.Success)
                    {
                        await ReplyAsync("PING SUCCESSFUL");
                        await ReplyAsync("Address: " + reply.Address.ToString());
                        await ReplyAsync("RoundTrip time: " + reply.RoundtripTime + "s");
                        await ReplyAsync("Time to live: " + reply.Options.Ttl);
                        await ReplyAsync("Don't fragment: " + reply.Options.DontFragment);
                        await ReplyAsync("Buffer size: " + reply.Buffer.Length);
                    }
                    else
                    {
                        await ReplyAsync("Address " + ipAddr + " is currently unreachable.");
                    }
                }
            }
        }
Ejemplo n.º 18
0
        public async Task When_CallPing_And_DatabaseIsDown_Should_ReturnUnsuccessfulPing()
        {
            var dbContextMock = new Mock <IDatabaseContext>(MockBehavior.Strict);

            dbContextMock.Setup(databaseContext => databaseContext.PingAsync()).ReturnsAsync((double?)null);

            var pingService = new PingService(dbContextMock.Object);

            var pingCheckResponse = await pingService.Ping();

            Assert.IsNotNull(pingCheckResponse.ServerTime);
            Assert.IsNull(pingCheckResponse.DatabasePing);
            Assert.IsFalse(pingCheckResponse.DatabaseStatus);
        }
Ejemplo n.º 19
0
        // GET: Ping
        public ActionResult Index(PingListItem name, string search)
        {
            var userId  = Guid.Parse(User.Identity.GetUserId());
            var service = new PingService(userId);
            var model   = service.GetPings();

            if (search != null)
            {
                return(View(model.Where(x => x.PingLocation.StartsWith(search, StringComparison.OrdinalIgnoreCase) || search == null).ToList()));
            }
            else
            {
                return(View(model));
            }
        }
Ejemplo n.º 20
0
        private void CreateInstallInstance()
        {
            var dbProxy            = new MongoDBService();
            var appInstallerLogger = Logger.GetLogger(typeof(ModuleInstaller.Installer.ModuleInstaller).Name, _httpProxy.TransactionId, dbProxy);
            var pingService        = new PingService(new MongoDBService());
            var routings           = ZNxtApp.Core.Web.Routings.Routings.GetRoutings();

            _appInstaller = ZNxtApp.Core.AppInstaller.Installer.GetInstance(
                pingService,
                new Helpers.DataBuilderHelper(),
                appInstallerLogger,
                dbProxy,
                new EncryptionService(),
                new ModuleInstaller.Installer.ModuleInstaller(appInstallerLogger, dbProxy),
                routings);
        }
Ejemplo n.º 21
0
 public JObject Ping()
 {
     try
     {
         if (PingService.PingDb())
         {
             return(ResponseBuilder.CreateReponse(CommonConst._1_SUCCESS));
         }
         else
         {
             return(ResponseBuilder.CreateReponse(PingResponseCode._PING_FAIL));
         }
     }
     catch (Exception ex)
     {
         Logger.Error(ex.Message, ex);
         return(ResponseBuilder.CreateReponse(PingResponseCode._PING_FAIL));
     }
 }
Ejemplo n.º 22
0
 public static void Main(string[] args)
 {
     try
     {
         Grpc.Core.Server server = new Grpc.Core.Server
         {
             Services = { PingService.BindService(new PingServiceImpl()) },
             Ports    = { new ServerPort("localhost", Porta, ServerCredentials.Insecure) }
         };
         server.Start();
         Console.WriteLine("Server ouvindo na porta " + Porta);
         Console.WriteLine("Pressione qualquer tecla para parar o server...");
         Console.ReadKey();
         server.ShutdownAsync().Wait();
     }
     catch (Exception ex)
     {
         Console.WriteLine($"Erro: {ex}");
     }
 }
Ejemplo n.º 23
0
        /// <summary>
        /// Triggered when the application host is ready to start the service.
        /// </summary>
        /// <param name="cancellationToken">Indicates that the start process has been aborted.</param>
        /// <returns>Task.</returns>
        /// <autogeneratedoc />
        public Task StartAsync(CancellationToken cancellationToken)
        {
            ServiceHostStatus = ServiceHostStatus.StartPending;
            var tasks = new List <Task>
            {
                CommonServices.StartAsync(cancellationToken),
                PingService.StartAsync(cancellationToken),
                ArpService.StartAsync(cancellationToken)
            };

            return(tasks.WaitForTasks(cancellationToken,
                                      (t) =>
            {
                if (t.IsCompleted && t.Status == TaskStatus.RanToCompletion)
                {
                    ServiceHostStatus = ServiceHostStatus.Running;
                }
            },
                                      Logger));
        }
        public EnvironmentSensorClient(AppSettings settings)
        {
            var uri = new Uri($"{settings.Remote.Scheme}://{settings.Remote.Host}:{settings.Remote.Port}{settings.Remote.Path}");

            logger.Info($"Remote address: {uri}");

            this.m_listener    = new WebSocketListenerService(uri, settings.Listener.SubscriptionInterval, LogManager.GetLogger("EnvironmentWebSocketClientService"));
            this.m_pingService = new PingService(TimeSpan.FromSeconds(5), this.m_listener);
            this.m_settings    = settings;

            var storageService = new MeasurementStorageService(new AuthorizationService(),
                                                               settings.Remote.StorageUri,
                                                               settings.Listener.ApiKey,
                                                               LogManager.GetLogger(nameof(MeasurementStorageService)));

            this.m_parser = new EnvironmentSensorParserService(storageService, new ParserSettings {
                ApiKey  = settings.Listener.ApiKey,
                Sensors = settings.Listener.Sensors
            }, LogManager.GetLogger(nameof(EnvironmentSensorParserService)));
        }
Ejemplo n.º 25
0
        public void Start()
        {
            LogService.Clear();
            LogService.Log("starting up the service.");

            api = new XillioApi("http://tenant.localhost:8080/", true);
            RunAuthentication();

            //Setup other services
            watcher = new WatcherService(api);
            try
            {
                ping = new PingService(api);
            }
            catch (Exception e)
            {
                LogService.Log(e);
                throw;
            }
            LogService.Log("service started.");
        }
Ejemplo n.º 26
0
        static PingServiceCollection GetPingServiceInfo()
        {
            PingServiceCollection pingServiceCollection = new PingServiceCollection();
            string fullPath = SiteConfig.GetConfigPathFromCurrentContext() + "PingServices.xml";

            if (File.Exists(fullPath))
            {
                FileStream fileStream = FileUtils.OpenForRead(fullPath);

                if (fileStream != null)
                {
                    try
                    {
                        XmlSerializer ser    = new XmlSerializer(typeof(PingServiceCollection));
                        StreamReader  reader = new StreamReader(fileStream);
                        pingServiceCollection = (PingServiceCollection)ser.Deserialize(reader);

                        // add to cache
                        DataCache cache = CacheFactory.GetCache();
                        cache.Insert("PingServices", pingServiceCollection, new CacheDependency(fullPath));
                    }
                    catch (Exception e)
                    {
                        ErrorTrace.Trace(TraceLevel.Error, e);
                    }
                    finally
                    {
                        fileStream.Close();
                    }
                }
            }

            // add some defaults
            if (pingServiceCollection.Count == 0)
            {
                pingServiceCollection = PingService.GetDefaultPingServices();
            }

            return(pingServiceCollection);
        }
Ejemplo n.º 27
0
        /// <summary>
        /// Triggered when the application host is performing a graceful shutdown.
        /// </summary>
        /// <param name="cancellationToken">Indicates that the shutdown process should no longer be graceful.</param>
        /// <returns>Task.</returns>
        /// <autogeneratedoc />
        public Task StopAsync(CancellationToken cancellationToken)
        {
            var tasks = new List <Task>
            {
                ArpService.StopAsync(cancellationToken),
                PingService.StopAsync(cancellationToken),
                CommonServices.StopAsync(cancellationToken)
            };

            ServiceHostStatus = ServiceHostStatus.StopPending;

            var logger = CommonServices?.LoggerFactory?.CreatePureLogger <CommonNetworkServices>();

            return(tasks.WaitForTasks(cancellationToken, (t) =>
            {
                if (t.IsCompleted)
                {
                    ServiceHostStatus = ServiceHostStatus.Stopped;
                }
            }
                                      , logger));
        }
Ejemplo n.º 28
0
 public PingController(ILogger <PingController> logger, PingService pingService)
 {
     _logger      = logger;
     _pingService = pingService;
 }
Ejemplo n.º 29
0
 public void Setup()
 {
     _pingService = new PingService();
 }
Ejemplo n.º 30
0
        /// <summary>
        /// Checks that the service correctly determines status code and response time.
        /// </summary>
        /// <param name="option">Option describing the expected behavior</param>
        public async Task GeneratesCorrectDataPoint(HttpResponseOption option)
        {
            // Arrange
            var responseHandler = new ResponseHandler();

            responseHandler.AddHandler(
                new Uri("https://my.url.com"),
                option
                );

            var mockHttpFactory = new Mock <IHttpClientFactory>();

            mockHttpFactory
            .Setup(factory => factory.BuildClient())
            .Returns(new HttpClient(responseHandler));


            var metricServiceMock = new Mock <IMetricService>();

            metricServiceMock
            .Setup(mock => mock.GetOrCreateMetricAsync(Metrics.Ping, "https://my.url.com"))
            .ReturnsAsync(new Metric());

            var pingService = new PingService(
                metricServiceMock.Object,
                new Mock <ILogger <PingService> >().Object,
                mockHttpFactory.Object
                );

            // Act
            var dataPoint = await pingService.PingServerAsync(
                new PingSetting {
                ServerUrl       = "https://my.url.com",
                MaxResponseTime = new TimeSpan(0, 0, 0, 0, 500)
            }
                );

            // Assert
            switch (option)
            {
            case HttpResponseOption.Success:
                Assert.True(dataPoint.Success);
                Assert.True(dataPoint.ResponseTime < new TimeSpan(0, 0, 0, 0, 2000));
                break;

            case HttpResponseOption.Timeout:
                Assert.False(dataPoint.Success);
                Assert.Equal(new TimeSpan(0), dataPoint.ResponseTime);
                break;

            case HttpResponseOption.ServiceUnavailable:
                Assert.False(dataPoint.Success);
                Assert.True(dataPoint.ResponseTime < new TimeSpan(0, 0, 0, 0, 2000));
                break;
            }

            // Clean up
            responseHandler.RemoveHandler(
                new Uri("https://my.url.com")
                );
        }
Ejemplo n.º 31
0
        public void UntiTestDemoVanService()
        {
            var service = new PingService();

            var result = service.Hello("from a unit test");
            Assert.AreEqual("Hello from a unit test", result);
        }
Ejemplo n.º 32
0
    /**
       * CallService
       * Parms were already read. Now call the service proxy classes
       *
       */
    void CallService()
    {
        if (SERVTYPE.ECHO == servtype) // Echo
        {
          if (0 == urlSuffix.Length)
          {
        urlSuffix = ECHO_CONTEXT;
          }
          EchoService echosv = new EchoService();
          Console.WriteLine("CLIENT>> Connecting to Echo Service...");
          echosv.Url = uriString + urlSuffix;
          Console.WriteLine("CLIENT>> Connected. Sending Echo Request to "+echosv.Url+"...");
          try
          {
          echoStringInput echoParm = new echoStringInput();
          echoParm.echoInput = msg;
          Console.WriteLine("CLIENT>> Sending message '"+ msg + "' ...");
          echoStringResponse result = echosv.echoOperation(echoParm);
          Console.WriteLine("CLIENT>> The answer is '" + result.echoResponse + "'");
          }
          catch (Exception e)
          {
        Console.WriteLine(">>>ECHO SERVICE EXCEPTION<<<\n" + e);
          }
        }
        else if (SERVTYPE.ASYNC == servtype) // Async Echo
        {
          if (0 == urlSuffix.Length)
          {
        urlSuffix = ECHO_CONTEXT;
          }
          // Instantiate the service, and create the service url
          EchoService echosv = new EchoService();
          Console.WriteLine("CLIENT>> Connecting to Async Echo Service...");
          echosv.Url = uriString + urlSuffix;
          Console.WriteLine("CLIENT>> Connected. Sending Echo Request to "+echosv.Url+"...");
          try
          {
        // Create the argument object and IAsyncResult, then invoke Async
        echoStringInput echoParm = new echoStringInput();
        echoParm.echoInput = msg;
        Console.WriteLine("CLIENT>> Sending Async message '" + msg + "' ...");
        IAsyncResult ar = echosv.BeginechoOperation(echoParm, EchoCallback, echosv);
        int waiting = timeout;

        Thread.Sleep(1000);
        // Wait for completion
        while (!ar.IsCompleted)
        {
          if (waiting <= 0)
          {
            Console.WriteLine("CLIENT>> ERROR - Timeout waiting for reply.");
            break;
          }
          Console.WriteLine("CLIENT>> invocation still not complete");
          Thread.Sleep(1000 * SLEEPER);
          waiting -= SLEEPER;
        }
        Console.WriteLine("CLIENT>> Async Invocation Complete");
          }
          catch (Exception e)
          {
        Console.WriteLine(">>>ECHO SERVICE EXCEPTION<<<\n" + e);
          }
        }
        else  // must be Ping
        {
          if (0 == urlSuffix.Length)
          {
        urlSuffix = PING_CONTEXT;
          }
          PingService pingsv = new PingService();
          Console.WriteLine("CLIENT>> Connecting to Ping Service...");
          pingsv.Url = uriString + urlSuffix;
          Console.WriteLine("CLIENT>> Connected. Sending Echo Request to "+pingsv.Url+"...");
          try
          {
          pingStringInput pingParm = new pingStringInput();
          pingParm.pingInput = msg;
          Console.WriteLine("CLIENT>> Sending message '"+ msg + "' ...");
          pingsv.pingOperation(pingParm);
          Console.WriteLine("CLIENT>> Ping complete. Check server log to verify message delivery.");
          }
          catch (Exception e)
          {
        Console.WriteLine(">>>PING SERVICE EXCEPTION<<<\n" + e);
          }
        }
    }