public void GeneratePingRequest_OnValidRequest_IsSet() { // act var msg = PingHelper.GeneratePingRequest(); // assert Assert.Equal(msg.EventName, "ping"); }
public void RunPingHealthCheck() { var helper = new PingHelper(); helper.TcpPing(connectionString); Assert.Throws <Exception>(() => { helper.TcpPing("blah"); }); }
private void remoteServerHelper1_OnOffLined(string msg) { textBox1.InvokeAction(() => { textBox1.Enabled = checkBox1.Enabled = comboBox1.Enabled = skinTrackBar1.Enabled = button1.Enabled = true; skinProgressBar1.Visible = false; SizedForm(false); PingHelper.Stop(); label3.Text = ""; }); }
private void btnStartPing_Click(object sender, EventArgs e) { if (pingSqlServerCancellationTokenSource == null) { var settings = ObjectStateManager.Get <UserSettings>(); int frequency = int.Parse(tbPingFrequency.Text); var pollInterval = 60 / frequency; _pingSqlServerLog = new StringBuilder(); pingSqlServerCancellationTokenSource = PingHelper.PingSqlServerTask(settings.ConnectionString3, TimeSpan.FromSeconds(pollInterval), _pingSqlServerLog); btnStartPing.Enabled = false; btnStopPing.Enabled = true; } }
public override void Run() { LogHelper.Info("Panther.Email.Services.SendEmail.SmartSendEmail->Run()"); //ping if (!PingHelper.TryConnect("www.baidu.com") && !PingHelper.TryConnect("www.google.cn")) { LogHelper.Error("无法连接連接網絡。"); return; } while (IsStart) { List <EmailInfo> emailList = GetSendEmailList(); if (emailList == null || emailList.Count <= 0) { LogHelper.Info("本次掃描完畢,沒有符合條件的發送郵件"); } else { foreach (var emailInfo in emailList) { //获取需要发送的邮件 //EmailInfo emailInfo = GetNextEmail(); if (emailInfo == null || emailInfo.EmailID == null) { LogHelper.Info("本次掃描完畢,沒有符合條件的發送郵件2"); continue; } //检测eml是否存在 if (string.IsNullOrEmpty(emailInfo.EmailFilePath)) { //修改状态 emailInfo.EmailState = -1; EmailInfoBLL emailinfobll = new EmailInfoBLL(); emailinfobll.Update(emailInfo); LogHelper.Info("邮件正文為空,无法发送"); continue; } SendEmail(emailInfo); //var t = new Thread(s => // { // var info = s as EmailInfo; // SendEmail(info); // }); //t.Start(emailInfo); } } SleepInterval(Interval); } }
private void btnPingWebSite_Click(object sender, EventArgs e) { if (pingWebSiteArgs == null) { int frequency = int.Parse(tbPingFrequency.Text); var pollInterval = 60 / frequency; pingWebSiteArgs = new PingOptions(TimeSpan.FromSeconds(pollInterval)) { Url = "http://yourshoes.com.ua", TestIsAlive = html => html.Contains("<nav class=\"user-links navbar-right\">") }; pingWebSiteArgs = PingHelper.PingWebsiteTask(pingWebSiteArgs); btnStopPingWebSite.Enabled = true; btnPingWebSite.Enabled = false; } }
private void SendPing(string ip) { if (!string.IsNullOrEmpty(ip)) { btnPingPrimary.Enabled = btnPingSecondary.Enabled = false; TaskEx.Run(() => { PingResult pingResult = PingHelper.PingHost(ip); MessageBox.Show(pingResult.ToString(), Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Information); }, () => { btnPingPrimary.Enabled = btnPingSecondary.Enabled = true; }); } }
/// <summary> /// 点击按钮请求连接 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void button1_Click(object sender, EventArgs e) { textBox1.Enabled = checkBox1.Enabled = comboBox1.Enabled = skinTrackBar1.Enabled = button1.Enabled = false; skinProgressBar1.Visible = true; try { requestRemoteHelper1.StartSendCapture(textBox1.Text, _isHelp, _qualityLevel, _fps); label1.Text = textBox1.Text + "对方已响应了你的远程协助请求"; skinProgressBar1.Visible = false; PingHelper.Start(this._serverIP, 3000, Encoding.Default.GetBytes("Ping Data"), () => { this.InvokeAction( () => { label3.Text = " 网络连接状态:" + PingHelper.IPStatus + " 延时:" + PingHelper.RoundtripTime + "ms" + " 网络异常数:" + PingHelper.ErrorCount + "次"; }); }); PingHelper.ErrorAlert( () => { this.InvokeAction( () => { label3.Text = " 网络连接状态:" + PingHelper.IPStatus + " 延时:" + PingHelper.RoundtripTime + "ms" + " 网络异常数:" + PingHelper.ErrorCount + "次" + " 当前网络不稳定,请保持网络通畅!"; }); }); } catch (Exception ex) { MessageBox.Show(ex.Message); label1.Text = "正在等待远程协助"; textBox1.Enabled = checkBox1.Enabled = comboBox1.Enabled = skinTrackBar1.Enabled = button1.Enabled = true; skinProgressBar1.Visible = false; PingHelper.Stop(); label3.Text = ""; } }
private static void consumer_Listener(IMessage message) { string taskId = string.Empty; try { ITextMessage msg = (ITextMessage)message; Dictionary <string, object> param = MqConsumerBase.ReadMapFromJson(msg.Text); IPerfApiStation stationBll = StationFactory.GetStation(param["deviceModel"].ToString()); log.Info(msg.NMSMessageId, taskId); if (msg.NMSType == "Ping") { string ip = param["ip"].ToString(); int num; if (!int.TryParse(param["pingnum"].ToString(), out num)) { log.Error("pingnum 参数异常!"); } List <IPStatus> statusList = PingHelper.PingHost(ip, num); double PacketLoss = statusList.Where(p => p == IPStatus.Success).Count() / num; bool isSucess = false; if (PacketLoss > 0.5) { isSucess = true; } MqAgentProducer.SendResponse(msg.NMSMessageId, StepTestStatus.测试通过, "完成任务 丢包率:" + (1 - PacketLoss), param["projectId"].ToString(), param["caseId"].ToString(), param["stepId"].ToString()); } else if (msg.NMSType == "ModifyWirelessMode") { string param1 = param["modeString"].ToString(); taskId = param["taskId"].ToString(); log.Info(string.Format("执行命令,参数是{0}", param1), taskId); Thread.Sleep(1000 * 1); stationBll.ModifyWirelessMode(param1); MqAgentProducer.SendResponse(msg.NMSMessageId, StepTestStatus.测试通过, "成功", param["projectId"].ToString(), param["caseId"].ToString(), param["stepId"].ToString()); } } catch (Exception ex) { log.Info(ex.Message, taskId); } }
public override async Task Execute() { await PingHelper.NotifySites(); IEnumerable <Uri> urlsFromContent = GetUrlsFromContent(this.item.Content); foreach (Uri uri in urlsFromContent) { bool trackbackSent = false; if (this.configuration.Tracking.EnableTrackBackSend) { trackbackSent = await TrackbackHelper.Notify(this.item, uri); } if (!trackbackSent && this.configuration.Tracking.EnablePingBackSend) { await PingbackHelper.Notify(this.item, uri); } } }
private void SafeAsyncSendPings(string blogName, string blogHomepageUrl) { try { string[] pingUrls = PostEditorSettings.PingUrls; if (pingUrls.Length > 0) { PingHelper ph = new PingHelper(blogName, blogHomepageUrl, pingUrls); Thread t = ThreadHelper.NewThread(new ThreadStart(ph.ThreadStart), "AsyncPing", true, false, false); t.Start(); UpdateProgress(-1, -1, Res.Get((pingUrls.Length == 1 ? StringId.SendingPing : StringId.SendingPings))); Thread.Sleep(750); } } catch (Exception e) { Trace.Fail("Exception while running ping logic: " + e.ToString()); } }
private void startPing() { new Thread(new ThreadStart(() => { LogHelper log = new LogHelper(); int times = 0; while (true) { log.LogInfo(++times + "次"); ITargetBll tb = new ExcelTargetBll(); PingHelper.ipTable = tb.GetTargetIPList(); PingHelper.ping(); for (int i = 0; i < 2; i++) { Thread.Sleep(1000 * 60 * 1); PingHelper.Reping(); } Thread.Sleep(1000 * 60 * 3); } })).Start(); }
private void SendPing(string ip) { if (!string.IsNullOrEmpty(ip)) { btnPingPrimary.Enabled = btnPingSecondary.Enabled = false; BackgroundWorker bw = new BackgroundWorker(); bw.DoWork += (sender, e) => { PingResult pingResult = PingHelper.PingHost(ip); MessageBox.Show(pingResult.ToString(), Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Information); }; bw.RunWorkerCompleted += (sender, e) => { btnPingPrimary.Enabled = btnPingSecondary.Enabled = true; }; bw.RunWorkerAsync(); } }
public GenericResponse Ping(IGenericRequest request, GenericResponse response) { var success = "Error"; var ip = request.PayLoad.AdditionalInfo["ipAddress"]; try { if (ip != null) { if (PingHelper.Ping(ip.ToString()).Status == IPStatus.Success) { success = "success"; } } } catch (PingException e) { } response.Result.Status = success; return(response); }
private bool RemoteVerifyPrdKey(string productKey) { HttpHelper http = new HttpHelper(); var postdata = string.Format("CPUSerialNumber={0}&ProductKey={1}", MachineInfo.Instance.GetCPUSerialNumber(), productKey); string responseStr = ""; if (PingHelper.Ping()) { // 验证有效性 responseStr = http.PostPage(remoteservice + "/api/device/VerifyProductKey", postdata); } var verifyKeyReponse = JsonHelper.FromJson <VerifyKeyReponse>(responseStr); if (verifyKeyReponse != null && verifyKeyReponse.ExpirationDate.HasValue) { //验证通过 var filename = Constants.PRODUCT_KEY; var launchInfo = JsonSerializeHelper.DeSerializeJson <LaunchInfo>(filename); launchInfo.ExpirationDate = verifyKeyReponse.ExpirationDate.Value.Date; launchInfo.EncryptedText = EncryptionService.EncryptText(launchInfo.ExpirationDate.ToShortDateString()); launchInfo.ProductKey = productKey; File.Delete(filename); launchInfo.SerializeJson(filename); WindowsRegistry.SetRegistryValue(Constants.EXPIRATION_DATE, launchInfo.ExpirationDate.ToShortDateString()); WindowsRegistry.SetRegistryValue(Constants.ENCRYPTED_TEXT, launchInfo.EncryptedText); WindowsRegistry.SetRegistryValue(Constants.PRODUCT_KEY, productKey); var datediff = launchInfo.ExpirationDate.Subtract(DateTime.Now).Days; return(datediff >= 0); } else { return(false); } }
public void Run(Terminal terminal, string[] args) { for (int i = 1; i < args.Length; i++) { var maxPakets = 10; var timeout = 1000; var DontFragment = false; var ttl = 128; if (string.Compare(args[i], "-n", true) == 0) { maxPakets = int.Parse(args[i + 1]); i += 2; } if (string.Compare(args[i], "-w", true) == 0) { timeout = int.Parse(args[i + 1]); i += 2; } if (string.Compare(args[i], "-ttl", true) == 0) { ttl = int.Parse(args[i + 1]); i += 2; } if (string.Compare(args[i], "-DontFragment", true) == 0) { DontFragment = true; i += 1; } var p = new PingHelper(terminal, args[i]); p.Pakets = maxPakets; p.TimeOut = timeout; p.TimeToLive = ttl; p.DontFragment = DontFragment; p.SendPingAsync(); } }
public void Launch() { new Thread(() => { var filename = Constants.PRODUCT_KEY; var launchInfo = JsonSerializeHelper.DeSerializeJson <LaunchInfo>(filename); if (launchInfo == null) { //使用试用账号 launchInfo = new LaunchInfo { ComputerName = MachineInfo.Instance.GetComputerName(), CPUSerialNumber = MachineInfo.Instance.GetCPUSerialNumber(), MACAddress = MachineInfo.Instance.GetMacAddress(), Name = PharmacyServiceConfig.Config.CurrentStore.Name, ProductKey = Constants.DEFAULT_SECURITY_KEY, ExpirationDate = DateTime.Now.AddDays(30).Date, SystemType = MachineInfo.Instance.GetSystemType() }; launchInfo.EncryptedText = EncryptionService.EncryptText(launchInfo.ExpirationDate.ToShortDateString()); WindowsRegistry.CreateRegistry(); if (WindowsRegistry.IsRegeditKeyExist(Constants.EXPIRATION_DATE)) { CallBack(Constants.PRODUCT_KEY_NOT_AVAILABLE); } CreateRegistry(launchInfo); } launchInfo.Name = PharmacyServiceConfig.Config.CurrentStore.Name; HttpHelper http = new HttpHelper(); var postdata = string.Format("ComputerName={0}&CPUSerialNumber={1}&MACAddress={2}&Name={3}&ProductKey={4}&SystemType={5}&ExpirationDate={6}", launchInfo.ComputerName, launchInfo.CPUSerialNumber, launchInfo.MACAddress, launchInfo.Name, launchInfo.ProductKey, launchInfo.SystemType, launchInfo.ExpirationDate); try { if (PingHelper.Ping()) { Log.Error("外部网络正常"); // 发送客户端设备信息 var strPHtml = http.PostPage(remoteservice + "/api/device/launch", postdata); } else { Log.Error("外部网络不通"); } } catch (Exception) { } if (File.Exists(filename)) { File.Delete(filename); } launchInfo.SerializeJson(filename); while (true) { launchInfo = JsonSerializeHelper.DeSerializeJson <LaunchInfo>(filename); if (launchInfo == null) { CallBack(Constants.PRODUCT_KEY_NOT_AVAILABLE); } else { var networkIsNotAvailable = PingHelper.Ping(); if (networkIsNotAvailable) { try { if (RemoteVerifyPrdKey(launchInfo.ProductKey)) { CallBack(Constants.PRODUCT_KEY_AVAILABLE); } else { CallBack(Constants.PRODUCT_KEY_NOT_AVAILABLE); } } catch (WebException) { networkIsNotAvailable = false; } } if (!networkIsNotAvailable) { if (OfflineVerify(launchInfo)) { CallBack(Constants.PRODUCT_KEY_AVAILABLE); } else { CallBack(Constants.PRODUCT_KEY_NOT_AVAILABLE); } } } Thread.Sleep(new TimeSpan(0, int.Parse(verifyInterval), 0)); } }).Start(); }
/// <summary> /// Autodetects the network profile. For the moment it works only for wifi connections! /// If no connections found, it return null. /// Use /// WindowsNetworkCardManager.EnabledWindowsNetworkCardList /// WifiProfileManager.ActiveWifiProfile; /// </summary> /// /// <param name="profiles">profiles.</param> /// <returns></returns> public static NetworkProfile AutodetectNetworkProfile(List <NetworkProfile> profiles) { NetworkProfileHelper.FireNotifyEvent("Start autodetect"); if (profiles == null || profiles.Count == 0) { NetworkProfileHelper.FireNotifyEvent("There's no profiles"); NetworkProfileHelper.FireNotifyEvent("End autodetect"); return(null); } // initial setup for cards SetupNetworkCardForAutodetect(profiles); NetworkProfile selectedProfile = null; // one or more card (not only wifi) // wifi connected, WifiProfile currentWifiProfile = WifiProfileManager.ActiveWifiProfile; // enable card List <WindowsNetworkCard> enabledCardList = WindowsNetworkCardManager.EnabledWindowsNetworkCardList; if (enabledCardList.Count == 1 && enabledCardList[0].CardType == WindowsNetworkCardType.WIRELESS && currentWifiProfile.SSID != null) { WindowsNetworkCard card = enabledCardList[0]; // only a wifi connection avaible foreach (NetworkProfile item in profiles) { // select if card is right and (ssid is right or for that profile there's no ssid) if (item.NetworkCardInfo.Id.Equals(card.Id) && (currentWifiProfile.SSID.Equals(item.AssociatedWifiSSID) || string.IsNullOrWhiteSpace(item.AssociatedWifiSSID))) { // ok, we found it!!! selectedProfile = item; if (!string.IsNullOrWhiteSpace(item.AssociatedWifiSSID)) { NetworkProfileHelper.FireNotifyEvent("The card " + card.Name + " are connected with right SSID (" + currentWifiProfile.SSID + ")"); } NetworkProfileHelper.FireNotifyEvent("Selected profile " + item.Name + " without do anything else!!"); break; } } } else { // order list by maxSpeed //enabledCardList.Sort(CompareCardBySpeed); // if there's no enabled card, it's a problem! if (enabledCardList.Count == 0) { NetworkProfileHelper.FireNotifyEvent("No card enabled, found"); return(null); } List <NetworkProfile> enabledProfileList = FindValidOrderedNetworkProfiles(profiles, enabledCardList, currentWifiProfile); // assert: enabledProfile contains the right profiles. Now we have to test it. // the first with ping ok it's ok! bool pingOk; foreach (NetworkProfile item in enabledProfileList) { NetworkProfileHelper.FireNotifyEvent("Start analizing profile " + item.Name + " with card " + item.NetworkCardInfo.Name); //WindowsNetworkCardHelper.SetDeviceStatus(item.NetworkCardInfo, false); NetworkProfileHelper.RunDisableNetworkCardsSetup(item); NetworkProfileHelper.RunNetworkCardSetup(item); // wait for a while //NetworkProfileHelper.FireNotifyEvent("Wait " + (WAIT_BEFORE_PING) + " ms."); //System.Threading.Thread.Sleep(WAIT_BEFORE_PING); WindowsNetworkCardEventHandler eventHandler = new WindowsNetworkCardEventHandler(item.NetworkCardInfo); eventHandler.WaitUntilNetworkCardIsUp(); //WaitUntilNetworkCardIsUp(item.NetworkCardInfo); NetworkProfileHelper.FireNotifyEvent("Wait " + (WAIT_BEFORE_PING) + " ms."); System.Threading.Thread.Sleep(WAIT_BEFORE_PING); WindowsNetworkCard card = WindowsNetworkCardManager.RefreshStatus(item.NetworkCardInfo.Id); if (card.CardType == WindowsNetworkCardType.WIRELESS) { // get current wifi profile only for wifi card currentWifiProfile = WifiProfileManager.GetActiveWifiProfileForCard(card); if (currentWifiProfile != null && currentWifiProfile.SSID.Equals(item.AssociatedWifiSSID) && card.NetConnectionStatus == 2) { // ok, we found it!!! selectedProfile = item; NetworkProfileHelper.FireNotifyEvent("The card " + card.Name + " are connected with right SSID (" + currentWifiProfile.SSID + ")"); NetworkProfileHelper.FireNotifyEvent("Selected profile " + item.Name + " without do anything else!!"); break; } } else { pingOk = false; NetworkProfileHelper.FireNotifyEvent("The card " + card.Name + " are in status " + card.NetConnectionStatus); // test both static config or dynamic config pingOk = PingHelper.RunPing(card.GatewayAddress); pingOk = pingOk || PingHelper.RunPing(card.CurrentGatewayAddress); NetworkProfileHelper.FireNotifyEvent("For card " + card.Name + " and profile " + item.Name + ", ping to gateway are " + pingOk); if (pingOk) { selectedProfile = item; NetworkProfileHelper.FireNotifyEvent("Selected profile " + item.Name + "!!"); break; } } NetworkProfileHelper.FireNotifyEvent("Stop analizing profile " + item.Name + ", go to next profile"); } // restore initial enabled card if (selectedProfile == null) { NetworkProfileHelper.FireNotifyEvent("No profile found, so restore status card"); foreach (WindowsNetworkCard item in enabledCardList) { NetworkProfileHelper.FireNotifyEvent("Enable card " + item.Name); WindowsNetworkCardHelper.SetDeviceStatus(item, true); } } } NetworkProfileHelper.FireNotifyEvent("End autodetect"); return(selectedProfile); }
public void CreateaPingInstance() { PingHelper check = new PingHelper(); }
private void executerProcess() { try { int exitCode = 0; // commande restart .bat string output = UptimeHelper.processBatch(cheminBatchRestart, ServerIpAddress, _logWriter, ref exitCode); // 10 minutes d'attentes appconfig Thread.Sleep(1000 * AppSettings.ReadSetting <int>(AppSettingConstants.ServerResponseTimeout, 10)); if (PingHelper.CheckAddress(ServerIpAddress).Status == System.Net.NetworkInformation.IPStatus.Success) { ServerEventsApi.ServerEventsPostServerEvent(new IO.Swagger.Model.ServerEvent() { Date = DateTime.Now, Event = IO.Swagger.Model.ServerEvent.EventEnum.NUMBER_5, RestaurantId = RestaurantId, Detail = "Le serveur a repondu" }); this.Dispatcher.Invoke(DispatcherPriority.Background, new Action(() => this.windowText.Text = "Le serveur distant a bien redemarré")); //Thread.Sleep(1000 * AppSettings.ReadSetting<int>(AppSettingsConstant.XmlRpcResponseTimeout, 5) * 60); //Call XmlRpc //TODO #if DEBUG //Désactiver le vérouillage après 5 secondes pour pouvoir quitter (à être remplacé par un autre logique après) Delay(5000).ContinueWith(_ => quitterFenetre()); #endif } else { ServerEventsApi.ServerEventsPostServerEvent(new IO.Swagger.Model.ServerEvent() { Date = DateTime.Now, Event = IO.Swagger.Model.ServerEvent.EventEnum.NUMBER_6, RestaurantId = RestaurantId, Detail = "Le serveur n'a pas repondu" }); this.Dispatcher.Invoke(DispatcherPriority.Background, new Action(() => { this.windowText.Text += "\n" + "Contactez votre mainteneur!"; this.exitButton.Visibility = Visibility.Visible; })); } } catch (Exception ex) { _logWriter.LogWrite($" ClassName : bloquerWindow "); _logWriter.LogWrite($" Exception : {ex.Message}"); _logWriter.LogWrite($" Exception : {ex.StackTrace}"); throw; } // if OK call xmlRPc attendre 5 minutes is ok update ecran + update api + deblocage ecran }
private static void consumer_Listener(IMessage message) { string projectId = string.Empty; try { ITextMessage msg = (ITextMessage)message; Dictionary <string, object> param = MqConsumerBase.ReadMapFromJson(msg.Text); AgentApiStation stationBll = StationFactory.GetStation(param["deviceModel"].ToString()); projectId = param["projectId"].ToString(); log.Info(msg.NMSMessageId, projectId); StepTestStatus stepTestStatus = StepTestStatus.测试通过; if (msg.NMSType == "Ping") { string ip = param["ip"].ToString(); double packetLoss; if (!Double.TryParse(param["pingnum"].ToString(), out packetLoss)) { log.Error("丢包率限值参数异常!"); } int num; if (!int.TryParse(param["pingnum"].ToString(), out num)) { log.Error("pingnum 参数异常!"); } List <IPStatus> statusList = PingHelper.PingHost(ip, num); double PacketLoss = 1 - statusList.Where(p => p == IPStatus.Success).Count() / num; if (PacketLoss > 0.1) { stepTestStatus = StepTestStatus.测试未通过; } MqAgentProducer.SendResponse(msg.NMSMessageId, stepTestStatus, "完成任务 丢包率:" + (1 - PacketLoss), projectId, param["caseId"].ToString(), param["stepId"].ToString()); } else if (msg.NMSType == "ModifyWirelessMode") { string param1 = param["modeString"].ToString(); log.Info(string.Format("执行命令,参数是{0}", param1), projectId); Thread.Sleep(1000 * 1); try { stationBll.ModifyWirelessMode(param1); } catch (Exception ex) { log.Error(ex.Message); stepTestStatus = StepTestStatus.测试异常; } MqAgentProducer.SendResponse(msg.NMSMessageId, stepTestStatus, "成功", param["projectId"].ToString(), param["caseId"].ToString(), param["stepId"].ToString()); } else if (msg.NMSType == "UpStation") { string ssid = param["ssid"].ToString(); string pwd = param["password"].ToString(); stationBll.UpStation(ssid, pwd); Thread.Sleep(1000 * 3); MqAgentProducer.SendResponse(msg.NMSMessageId, StepTestStatus.测试通过, "回复消息,我已经完成任务!", projectId, param["caseId"].ToString(), param["stepId"].ToString()); } } catch (Exception ex) { log.Info(ex.Message, projectId); } }