public void Listen() { try { var localIp = IPAddress.Parse(Server.ServerIp); Listener = new TcpListener(localIp, Port); Listener.Start(); } catch (Exception e) { Server.WriteDisplay(e); Server.SetTextBtn(@"Start"); Server.SetColorDisplay(Color.White); return; } while (IsActive) { try { var s = Listener.AcceptTcpClient(); _processor = new HttpProcessor(s, this); Thread = new Thread(_processor.Process); Thread.Start(); Thread.Sleep(1); } catch (SocketException) // or whatever the exception is that you're getting { } } }
private AssetBase Get(string id, out string sha) { string hash = string.Empty; int startTime = System.Environment.TickCount; AssetMetadata metadata; lock (m_readLock) { metadata = m_DataConnector.Get(id, out hash); } sha = hash; if (metadata == null) { AssetBase asset = null; if (m_FallbackService != null) { asset = m_FallbackService.Get(id); if (asset != null) { asset.Metadata.ContentType = SLUtil.SLAssetTypeToContentType((int)asset.Type); sha = GetSHA256Hash(asset.Data); m_log.InfoFormat("[FSASSETS]: Added asset {0} from fallback to local store", id); Store(asset); } } if (asset == null && m_showStats) { // m_log.InfoFormat("[FSASSETS]: Asset {0} not found", id); m_missingAssets++; } return(asset); } AssetBase newAsset = new AssetBase(); newAsset.Metadata = metadata; try { newAsset.Data = GetFsData(hash); if (newAsset.Data.Length == 0) { AssetBase asset = null; if (m_FallbackService != null) { asset = m_FallbackService.Get(id); if (asset != null) { asset.Metadata.ContentType = SLUtil.SLAssetTypeToContentType((int)asset.Type); sha = GetSHA256Hash(asset.Data); m_log.InfoFormat("[FSASSETS]: Added asset {0} from fallback to local store", id); Store(asset); } } if (asset == null) { if (m_showStats) { m_missingAssetsFS++; } // m_log.InfoFormat("[FSASSETS]: Asset {0}, hash {1} not found in FS", id, hash); } else { // Deal with bug introduced in Oct. 20 (1eb3e6cc43e2a7b4053bc1185c7c88e22356c5e8) // Fix bad assets before sending them elsewhere if (asset.Type == (int)AssetType.Object && asset.Data != null) { string xml = ExternalRepresentationUtils.SanitizeXml(Utils.BytesToString(asset.Data)); asset.Data = Utils.StringToBytes(xml); } return(asset); } } if (m_showStats) { lock (m_statsLock) { m_readTicks += Environment.TickCount - startTime; m_readCount++; } } // Deal with bug introduced in Oct. 20 (1eb3e6cc43e2a7b4053bc1185c7c88e22356c5e8) // Fix bad assets before sending them elsewhere if (newAsset.Type == (int)AssetType.Object && newAsset.Data != null) { string xml = ExternalRepresentationUtils.SanitizeXml(Utils.BytesToString(newAsset.Data)); newAsset.Data = Utils.StringToBytes(xml); } return(newAsset); } catch (Exception exception) { m_log.Error(exception.ToString()); Thread.Sleep(5000); Environment.Exit(1); return(null); } }
public void TwoTablesNotificationsTest() { int table1InsertsReceived = 0; int table1DeletesReceived = 0; int table1TotalNotifications = 0; int table1TotalDeleted = 0; int table2InsertsReceived = 0; int table2DeletesReceived = 0; int table2TotalNotifications = 0; int table2TotalInserted = 0; using (var sqlDependencyFirstTable = new SqlDependencyEx( TEST_CONNECTION_STRING, "TestDatabase", "TestTable", "temp", SqlDependencyEx.NotificationTypes.Delete, true, 0)) { sqlDependencyFirstTable.TableChanged += (sender, args) => { if (args.NotificationType == SqlDependencyEx.NotificationTypes.Delete) { table1DeletesReceived++; table1TotalDeleted += args.Data.Element("deleted").Elements("row").Count(); } if (args.NotificationType == SqlDependencyEx.NotificationTypes.Insert) { table1InsertsReceived++; } table1TotalNotifications++; }; if (!sqlDependencyFirstTable.Active) { sqlDependencyFirstTable.Start(); } using (var sqlDependencySecondTable = new SqlDependencyEx( TEST_CONNECTION_STRING, "TestDatabase", "TestTable", "temp2", SqlDependencyEx.NotificationTypes.Insert, true, 1)) { sqlDependencySecondTable.TableChanged += (sender, args) => { if (args.NotificationType == SqlDependencyEx.NotificationTypes.Delete) { table2DeletesReceived++; } if (args.NotificationType == SqlDependencyEx.NotificationTypes.Insert) { table2InsertsReceived++; table2TotalInserted += args.Data.Element("inserted").Elements("row").Count(); } table2TotalNotifications++; }; if (!sqlDependencySecondTable.Active) { sqlDependencySecondTable.Start(); } MakeChunkedInsert(5, TEST_TABLE_1_FULL_NAME); MakeChunkedInsert(3, TEST_TABLE_2_FULL_NAME); MakeChunkedInsert(8, TEST_TABLE_2_FULL_NAME); DeleteFirstRow(TEST_TABLE_1_FULL_NAME); DeleteFirstRow(TEST_TABLE_1_FULL_NAME); DeleteFirstRow(TEST_TABLE_1_FULL_NAME); DeleteFirstRow(TEST_TABLE_1_FULL_NAME); DeleteFirstRow(TEST_TABLE_2_FULL_NAME); DeleteFirstRow(TEST_TABLE_2_FULL_NAME); MakeChunkedInsert(1, TEST_TABLE_2_FULL_NAME); MakeChunkedInsert(1, TEST_TABLE_1_FULL_NAME); DeleteFirstRow(TEST_TABLE_1_FULL_NAME); DeleteFirstRow(TEST_TABLE_2_FULL_NAME); // Wait for notification to complete Thread.Sleep(3000); } } Assert.AreEqual(5, table1DeletesReceived); Assert.AreEqual(0, table1InsertsReceived); Assert.AreEqual(5, table1TotalNotifications); Assert.AreEqual(5, table1TotalDeleted); Assert.AreEqual(3, table2InsertsReceived); Assert.AreEqual(0, table2DeletesReceived); Assert.AreEqual(3, table2TotalNotifications); Assert.AreEqual(12, table2TotalInserted); }
private void GetCID_Click(object sender, EventArgs e) { string iid = this.iidInputTextBox.Text; string convertedIID = ""; foreach (char i in iid) { if (i >= '0' && i <= '9') { convertedIID += i; } } this.iidInputTextBox.Text = convertedIID; if (convertedIID == "") { this.cidOutputTextBox.Text = "IID must by not empty!"; return; } this.iidInputTextBox.Enabled = false; this.getCIDButton.Enabled = false; this.getCIDButton.Text = "Getting CID..."; this.cidDashOutputTextBox.Text = ""; this.cidOutputTextBox.Text = ""; this.cidCommandOutputTextbox.Text = ""; this.cidTimeLabel.Enabled = true; Application.DoEvents(); string live_get = "false"; if (this.checkBox1.Checked) { live_get = "true"; } string cid = ""; Thread t = new Thread(() => { cid = Utils.GetCID(convertedIID, live_get); }); t.Start(); DateTime startTime = DateTime.Now; while (t.IsAlive) { this.UpdateCIDTimeLabel(startTime); Thread.Sleep(1); } this.iidInputTextBox.Enabled = true; this.getCIDButton.Enabled = true; this.getCIDButton.Text = "Get CID"; if (cid == "") { this.cidOutputTextBox.Text = "Connect to server fail!"; return; } this.cidOutputTextBox.Text = cid; this.updateCidDashOutput(cid); this.UpdateCIDComandOutput(null, null); }
private void keyTableRefreshClick(object sender, EventArgs e) { if (isKeyRefreshCanceling) { return; } if (isKeyRefreshing) { isKeyRefreshCanceling = true; return; } DataGridViewSelectedCellCollection selectedCells = this.keyDataGridView.SelectedCells; HashSet <DataGridViewRow> selectedRows = new HashSet <DataGridViewRow>(); for (int i = 0; i < selectedCells.Count; i++) { selectedRows.Add(this.keyDataGridView.Rows[selectedCells[i].RowIndex]); } if (selectedRows.Count == 0) { return; } isKeyRefreshing = true; string tableName = this.keyTypeComboBox.SelectedItem.ToString(); foreach (var r in selectedRows.Reverse()) { string key = r.Cells[1].Value.ToString(); r.Cells[3].Value = "Updating.."; r.Cells[4].Value = "Updating.."; r.Cells[5].Value = "Updating.."; Thread t = new Thread(() => { keyChecker.Check(key, CheckMode.ALL_DATA, keyDatabase); }); t.Start(); while (t.IsAlive) { Application.DoEvents(); Thread.Sleep(1); } KeyDetail detail = keyDatabase.GetKeyDetail(key); if (detail != null) { r.Cells[3].Value = detail.activationCount.ToString(); r.Cells[4].Value = detail.errorCode; r.Cells[5].Value = detail.time; Application.DoEvents(); } if (isKeyRefreshCanceling) { break; } } isKeyRefreshing = false; isKeyRefreshCanceling = false; }
public void NumeroDepôtSendKey(String numero) { NumeroDepôtInput.Clear(); Thread.Sleep(3000); NumeroDepôtInput.SendKeys(numero); }
private void GivenIWaitMilliseconds(int ms) { Thread.Sleep(ms); }
public static void vaoPhong(object obj)// cho 1 client vào phòng { int pos = (Int32)obj; while (true) { try { byte[] buff = new byte[1024]; int rcv = socket_vaophong[pos].Receive(buff); string sig = ""; for (int i = 0; i < rcv; i += 2) { sig += Convert.ToChar(buff[i]).ToString(); } if (sig.Contains("Create")) { string[] t = sig.Split('_'); phong temp = new phong(); numberOfRoom++; temp.betMoney = Convert.ToInt32(t[1]); temp.soPhong = numberOfRoom - 1; temp.indexOfClient.Add(pos); temp.managerOfTheGame.clientOfRoom.Add(client[pos]); temp.managerOfTheGame.numOfPlayers++; client[pos].room = temp.soPhong; dsPhong.Add(temp); socket_vaophong[pos].Send(Encoding.Unicode.GetBytes("Create" + "_" + (temp.soPhong + 1).ToString() + "_" + temp.betMoney.ToString())); Thread.Sleep(1000); socket_status[pos].Send(Encoding.Unicode.GetBytes(temp.indexOfClient.Count.ToString())); } else { string[] t = sig.Split('_'); bool check = false; foreach (phong item in dsPhong) { if (item.indexOfClient.Count < 4 && Convert.ToInt32(t[1]) == item.betMoney) { client[pos].room = item.soPhong; item.indexOfClient.Add(pos); item.managerOfTheGame.clientOfRoom.Add(client[pos]); item.managerOfTheGame.numOfPlayers++; socket_vaophong[pos].Send(Encoding.Unicode.GetBytes("Find" + "_" + (item.soPhong + 1).ToString() + "_" + item.betMoney.ToString())); Thread.Sleep(1000); foreach (int x in item.indexOfClient) socket_status[x].Send(Encoding.Unicode.GetBytes(item.indexOfClient.Count.ToString())); break; } } if (check == false) socket_vaophong[pos].Send(Encoding.Unicode.GetBytes("Not found")); } } catch { break; } } }
public static void ListenCard(object obj)//Lắng nghe bài từ client { int pos = (Int32)obj; while (true) { try { byte[] buff = new byte[1024]; int k = socket_cards[pos].Receive(buff); if (k != 0) { client[pos].arrSelCards = Deserialize(buff); } if (dsPhong[client[pos].room].flag3bich) { client[pos].arrSelCards.Sort(); if (client[pos].arrSelCards[0].Value == 3 && client[pos].arrSelCards[0].Character == 1) { dsPhong[client[pos].room].flag3bich = false; socket_signalDel[pos].Send(Encoding.Unicode.GetBytes("OK")); dsPhong[client[pos].room].managerOfTheGame.justPlayer = dsPhong[client[pos].room].indexOfClient.IndexOf(pos); client[pos].Activated = false; client[pos].numOfRemainCards -= client[pos].arrSelCards.Count; // thêm số phòng để gửi broadcast các client trong phòng BroadcastResult(client[pos].arrSelCards, client[pos].room); dsPhong[client[pos].room].managerOfTheGame.temp = client[pos].arrSelCards; dsPhong[client[pos].room].managerOfTheGame.justPlayer = dsPhong[client[pos].room].indexOfClient.IndexOf(pos); int index_next = dsPhong[client[pos].room].managerOfTheGame.NextPlayer() % 4; FindNextPlayer(index_next, pos); } else { socket_signalDel[pos].Send(Encoding.Unicode.GetBytes("Dont't del")); client[pos].money -= 100; socket_money[pos].Send(Encoding.Unicode.GetBytes(client[pos].money.ToString())); } } else if (dsPhong[client[pos].room].managerOfTheGame.temp.Count == 0 || dsPhong[client[pos].room].rule. IsWin(dsPhong[client[pos].room].managerOfTheGame.temp, client[pos].arrSelCards) != 0) { //.temp = .client[pos].arrSelCards; //thay thế mấy chỗ gán temp như ở trên thành như ở dưới if (dsPhong[client[pos].room].managerOfTheGame.temp.Count != 0 && dsPhong[client[pos].room].rule. IsWin(dsPhong[client[pos].room].managerOfTheGame.temp, client[pos].arrSelCards) == 2) { client[pos].money += dsPhong[client[pos].room].betMoney; socket_money[pos].Send(Encoding.Unicode.GetBytes(client[pos].money.ToString())); client[dsPhong[client[pos].room].managerOfTheGame.justPlayer].money -= dsPhong[client[pos].room].betMoney; socket_money[dsPhong[client[pos].room].managerOfTheGame.justPlayer].Send(Encoding.Unicode.GetBytes(client[dsPhong[client[pos].room].managerOfTheGame.justPlayer].money.ToString())); } dsPhong[client[pos].room].managerOfTheGame.temp = client[pos].arrSelCards; dsPhong[client[pos].room].managerOfTheGame.justPlayer = dsPhong[client[pos].room].indexOfClient.IndexOf(pos); BroadcastResult(client[pos].arrSelCards, client[pos].room); socket_signalDel[pos].Send(Encoding.Unicode.GetBytes("OK")); client[pos].Activated = false; client[pos].numOfRemainCards -= client[pos].arrSelCards.Count; if (client[pos].numOfRemainCards == 0) { client[pos].Status = false; dsPhong[client[pos].room].tempRank++; client[pos].Rank = dsPhong[client[pos].room].tempRank; dsPhong[client[pos].room].listRank.Add(new ClsRank("Player " + (dsPhong[client[pos].room].indexOfClient.IndexOf(pos) + 1).ToString(), client[pos].Rank)); dsPhong[client[pos].room].managerOfTheGame.dem++; if (dsPhong[client[pos].room].managerOfTheGame.dem == 3) { dsPhong[client[pos].room].managerOfTheGame.temp.RemoveRange(0, dsPhong[client[pos].room].managerOfTheGame.temp.Count); foreach (int item in dsPhong[client[pos].room].indexOfClient) { socket_Rank[item].Send(Serialize_Rank(dsPhong[client[pos].room].listRank)); } dsPhong[client[pos].room].listRank.RemoveRange(0, dsPhong[client[pos].room].listRank.Count); foreach (int item in dsPhong[client[pos].room].indexOfClient) { if (client[item].Rank == 1) { client[item].money += dsPhong[client[pos].room].betMoney * 2; socket_money[item].Send(Encoding.Unicode.GetBytes(client[item].money.ToString())); } else if (client[item].Rank == 3 || client[item].Rank == 0) { client[item].money -= dsPhong[client[pos].room].betMoney; socket_money[item].Send(Encoding.Unicode.GetBytes(client[item].money.ToString())); } } Thread.Sleep(3000); int temp_anTrang = StartNewGame(client[pos].room); while (temp_anTrang == 1) { temp_anTrang = StartNewGame(client[pos].room); } } else { int index_next = dsPhong[client[pos].room].managerOfTheGame.NextPlayer() % 4; FindNextPlayer(index_next, pos); } } else { int index_next = dsPhong[client[pos].room].managerOfTheGame.NextPlayer() % 4; FindNextPlayer(index_next, pos); } } else { socket_signalDel[pos].Send(Encoding.Unicode.GetBytes("Dont't del")); client[pos].money -= 100; socket_money[pos].Send(Encoding.Unicode.GetBytes(client[pos].money.ToString())); } } catch { Console.WriteLine("Cham dut ket noi:" + socket_status[pos].RemoteEndPoint.ToString()); socket_cards[pos].Close(); socket_cards.RemoveAt(pos); socket_status[pos].Close(); socket_status.RemoveAt(pos); dsPhong[client[pos].room].indexOfClient.Remove(pos); if (socket_status.Count != 0) foreach (int item in dsPhong[client[pos].room].indexOfClient) { socket_status[pos].Send(Encoding.Unicode.GetBytes(dsPhong[client[pos].room].indexOfClient.Count.ToString())); } break; } } }
void ShowColorPulse(Color color, int duration = 1000) { onboardLed.StartPulse(color, (uint)(duration / 2)); Thread.Sleep(duration); onboardLed.Stop(); }
private async Task SetInstallationDataPath(MCProfile p, BLInstallation i) { await Task.Run(() => { try { string LocalStateFolder = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Packages", MINECRAFT_PACKAGE_FAMILY, "LocalState"); string PackageFolder = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Packages", MINECRAFT_PACKAGE_FAMILY, "LocalState", "games", "com.mojang"); string PackageBakFolder = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Packages", MINECRAFT_PACKAGE_FAMILY, "LocalState", "games", "com.mojang.default"); string ProfileFolder = Path.GetFullPath(LauncherModel.Default.FilepathManager.GetInstallationsFolderPath(p.Name, i.DirectoryName_Full)); if (Directory.Exists(PackageFolder)) { var dir = new DirectoryInfo(PackageFolder); if (!dir.IsSymbolicLink()) dir.MoveTo(PackageBakFolder); else dir.Delete(true); } DirectoryInfo profileDir = Directory.CreateDirectory(ProfileFolder); SymLinkHelper.CreateSymbolicLink(PackageFolder, ProfileFolder, SymLinkHelper.SymbolicLinkType.Directory); DirectoryInfo pkgDir = Directory.CreateDirectory(PackageFolder); DirectoryInfo lsDir = Directory.CreateDirectory(LocalStateFolder); SecurityIdentifier owner = WindowsIdentity.GetCurrent().User; SecurityIdentifier authenticated_users_identity = new SecurityIdentifier("S-1-5-11"); FileSystemAccessRule owner_access_rules = new FileSystemAccessRule(owner, FileSystemRights.FullControl, InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit, PropagationFlags.None, AccessControlType.Allow); FileSystemAccessRule au_access_rules = new FileSystemAccessRule(authenticated_users_identity, FileSystemRights.FullControl, InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit, PropagationFlags.None, AccessControlType.Allow); var lsSecurity = lsDir.GetAccessControl(); AuthorizationRuleCollection rules = lsSecurity.GetAccessRules(true, true, typeof(NTAccount)); List<FileSystemAccessRule> needed_rules = new List<FileSystemAccessRule>(); foreach (AccessRule rule in rules) { if (rule.IdentityReference is SecurityIdentifier) { var required_rule = new FileSystemAccessRule(rule.IdentityReference, FileSystemRights.FullControl, rule.InheritanceFlags, rule.PropagationFlags, rule.AccessControlType); needed_rules.Add(required_rule); } } var pkgSecurity = pkgDir.GetAccessControl(); pkgSecurity.SetOwner(owner); pkgSecurity.AddAccessRule(au_access_rules); pkgSecurity.AddAccessRule(owner_access_rules); pkgDir.SetAccessControl(pkgSecurity); var profileSecurity = profileDir.GetAccessControl(); profileSecurity.SetOwner(owner); profileSecurity.AddAccessRule(au_access_rules); profileSecurity.AddAccessRule(owner_access_rules); needed_rules.ForEach(x => profileSecurity.AddAccessRule(x)); profileDir.SetAccessControl(profileSecurity); } catch (Exception e) { ErrorScreenShow.exceptionmsg(e); throw e; } }); Thread.Sleep(1000); }
public void Ensure_command_network_error_before_hadnshake_is_correctly_handled([Values(false, true)] bool async, [Values(false, true)] bool streamable) { var eventCapturer = new EventCapturer().Capture<ServerDescriptionChangedEvent>(); // ensure that isMaster check response is finished only after network error var hasNetworkErrorBeenTriggered = new TaskCompletionSource<bool>(); // ensure that there are no unexpected events between test ending and cluster disposing var hasClusterBeenDisposed = new TaskCompletionSource<bool>(); EndPoint initialSelectedEndpoint = null; using (var cluster = CreateAndSetupCluster(hasNetworkErrorBeenTriggered, hasClusterBeenDisposed, eventCapturer, streamable)) { ForceClusterId(cluster, __clusterId); // 0. Initial heartbeat via `connection.Open` // The next isMaster response will be delayed because the Task.WaitAny in the mock.Returns cluster.Initialize(); var selectedServer = cluster.SelectServer(CreateWritableServerAndEndPointSelector(__endPoint1), CancellationToken.None); initialSelectedEndpoint = selectedServer.EndPoint; initialSelectedEndpoint.Should().Be(__endPoint1); // make sure the next isMaster check has been called Thread.Sleep(__heartbeatInterval + TimeSpan.FromMilliseconds(50)); // 1. Trigger the command network error BEFORE handshake. At this time isMaster response is alreaady delayed until `hasNetworkErrorBeenTriggered.SetResult` Exception exception; if (async) { exception = Record.Exception(() => selectedServer.GetChannelAsync(CancellationToken.None).GetAwaiter().GetResult()); } else { exception = Record.Exception(() => selectedServer.GetChannel(CancellationToken.None)); } var e = exception.Should().BeOfType<MongoConnectionException>().Subject; e.Message.Should().Be("DnsException"); // 2. Waiting for the isMaster check hasNetworkErrorBeenTriggered.SetResult(true); // unlock the in-progress isMaster response Thread.Sleep(100); // make sure the delayed isMaster check had time to change description if there is a bug var knownServers = cluster.Description.Servers.Where(s => s.Type != ServerType.Unknown); if (knownServers.Select(s => s.EndPoint).Contains(initialSelectedEndpoint)) { throw new Exception($"The type of failed server {initialSelectedEndpoint} has not been changed to Unknown."); } // ensure that a new server can be selected selectedServer = cluster.SelectServer(WritableServerSelector.Instance, CancellationToken.None); // ensure that the selected server is not the same as the initial selectedServer.EndPoint.Should().Be(__endPoint2); // the 4th event is MongoConnectionException which will trigger the next isMaster check immediately eventCapturer.WaitForOrThrowIfTimeout(events => events.Count() >= 4, TimeSpan.FromSeconds(5)); } hasClusterBeenDisposed.SetCanceled(); // Cut off not related events. Stop waiting in the latest mock.Returns for OpenAsync // Events asserting var initialHeartbeatEvents = new[] { // endpoints can be in random order eventCapturer.Next().Should().BeOfType<ServerDescriptionChangedEvent>().Subject, eventCapturer.Next().Should().BeOfType<ServerDescriptionChangedEvent>().Subject } .OrderBy(c => GetPort(c.NewDescription.EndPoint)) .ToList(); AssertEvent(initialHeartbeatEvents[0], __endPoint1, ServerType.ShardRouter, "Heartbeat"); AssertEvent(initialHeartbeatEvents[1], __endPoint2, ServerType.ShardRouter, "Heartbeat"); // the next 27018 events will be suppressed AssertNextEvent(eventCapturer, initialSelectedEndpoint, ServerType.Unknown, "InvalidatedBecause:ChannelException during handshake: MongoDB.Driver.MongoConnectionException: DnsException"); AssertNextEvent(eventCapturer, initialSelectedEndpoint, ServerType.Unknown, "Heartbeat", typeof(MongoConnectionException)); eventCapturer.Any().Should().BeFalse(); int GetPort(EndPoint endpoint) => ((DnsEndPoint)endpoint).Port; }
/// <summary> /// 开通存管账户 /// </summary> /// <returns></returns> public async Task <bool> OpenBankAccount(AccountUsers user, WebBrowser webBrowser, Action action) { SetWebbrowser.SumitForm(12); webBrowser.ScriptErrorsSuppressed = true; OpenAccountRequest request = new OpenAccountRequest { BankCardNo = user.BankCardNo, BankCardPhone = user.CgCellPhone, BizType = "01", CertNo = user.CredentialNo, RealName = user.RealName, RegisteredCell = user.CellPhone, ReturnUrl = "http://www.baidu.com/", UserId = user.UserIdentifier, ClientType = 900, OrderId = Guid.NewGuid().ToString("N").ToUpper() }; BankSercrityInfo openAcountResponse = await this.jymService.OpenAccountAsync(request); if (openAcountResponse == null) { return(false); } string url = $"http://fsgw.hkmdev.firstpay.com/phoenixFS-fsgw/gateway?data={HttpUtility.UrlEncode(openAcountResponse.Data)}&tm={HttpUtility.UrlEncode(openAcountResponse.Tm)}&merchantId=M20000002130"; //添加一个 //WebBrowser webBrowser = new WebBrowser { Name = "wb" + Guid.NewGuid().ToString("N").ToUpper() }; webBrowser.Navigate(new Uri(url, UriKind.Absolute)); int first = 0; webBrowser.DocumentCompleted += (obj, e) => { //赋值 HtmlDocument htmlDocument = webBrowser.Document; if (first == 0) { if (htmlDocument != null) { try { Thread.Sleep(650); string html1 = htmlDocument.Body?.InnerHtml; string dkfk = html1; //webBrowser.Navigate("jajavascript:window.alert($)"); //webBrowser.Navigate("javascript:$('#payPassword').next().click();$('#confirmPayPassword').next().click();$('#payPassword').val('111111');$('#confirmPayPassword').val('111111');$('#sendSmsCode').click();$('#smsCode').val('123456');$(':submit').click()"); int a = 0; Thread th = new Thread(() => { try { Thread.Sleep(650); string html = htmlDocument.Body?.InnerHtml; HtmlElement setPwd = htmlDocument.GetElementById("payPassword"); //输入密码 HtmlElement parent = setPwd?.Parent?.GetElementsByTagName("button")[0]; parent?.InvokeMember("click"); //获取到键值为1的id HtmlElement key1 = htmlDocument.GetElementById("key11"); key1?.InvokeMember("click"); key1?.InvokeMember("click"); key1?.InvokeMember("click"); key1?.InvokeMember("click"); key1?.InvokeMember("click"); key1?.InvokeMember("click"); HtmlElement confirmSetPwd = htmlDocument.GetElementById("confirmPayPassword"); //确认密码 HtmlElement parent1 = confirmSetPwd?.Parent?.GetElementsByTagName("button")[0]; parent1?.InvokeMember("click"); //获取到键值为1的id HtmlElement key2 = htmlDocument.GetElementById("key11"); key2?.InvokeMember("click"); key2?.InvokeMember("click"); key2?.InvokeMember("click"); key2?.InvokeMember("click"); key2?.InvokeMember("click"); key2?.InvokeMember("click"); List <HtmlElement> listElements = new List <HtmlElement> { htmlDocument.GetElementById("payPassword"), htmlDocument.GetElementById("payPasswordConfirm"), htmlDocument.GetElementById("bankCode"), htmlDocument.GetElementById("bankCardNoInput"), htmlDocument.GetElementById("bankCardPhone"), htmlDocument.GetElementById("smsCode") }; foreach (HtmlElement t in listElements) { t?.SetAttribute("data-status", "true"); } HtmlElementCollection input = htmlDocument.GetElementsByTagName("input"); input[10]?.SetAttribute("data-status", "true"); //var pas = document.getElementById('confirmPayPassword'); pas.nextElementSibling.onclick(); var ke1 = document.getElementById('key11'); ke1.onclick(); ke1.onclick(); ke1.onclick(); ke1.onclick(); ke1.onclick(); ke1.onclick(); //undefined //var pas = document.getElementById('payPassword'); pas.nextElementSibling.onclick(); var ke1 = document.getElementById('key11'); ke1.onclick(); ke1.onclick(); ke1.onclick(); ke1.onclick(); ke1.onclick(); ke1.onclick(); //$('#payPassword').next().click();$('#confirmPayPassword').next().click();$('#payPassword').val('111111');$('#confirmPayPassword').val('111111');$('#sendSmsCode').click();$('#smsCode').val('123456');$(':submit').click() //webBrowser.Navigate("javascript:$(\'#payPassword\').next().click()"); //webBrowser.Navigate("javascript:$('#payPassword').next().click();$('#confirmPayPassword').next().click();$('#payPassword').val('111111');$('#confirmPayPassword').val('111111');$('#sendSmsCode').click();$('#smsCode').val('123456');"); //$(':submit').click() //setPwd?.SetAttribute("value", "111111"); //htmlDocument.GetElementById("payPasswordConfirm")?.SetAttribute("value", "111111"); htmlDocument.GetElementById("smsCode")?.SetAttribute("value", "123456"); //点击按钮 for (int ii = 0; ii < input.Count; ii++) { if (input[ii].GetAttribute("type").ToLower().Equals("submit")) { input[ii].InvokeMember("click"); } } } catch (Exception exception) { Console.WriteLine(exception); throw; } }) { IsBackground = true }; th.Start(); } catch (Exception ex) { //是失败 } } } first = first + 1; bool?contains = htmlDocument?.Body?.OuterHtml.Contains("成功开通"); if (contains != null && (bool)contains) { action(); } }; return(false); }
/// <summary> /// 获取用户流水 /// </summary> /// <returns></returns> public async Task GetUserTransactoin(string userId, string urlB, WebBrowser webBrowser = null, Action action = null) { SetWebbrowser.SumitForm(12); if (webBrowser == null) { webBrowser = new WebBrowser(); } webBrowser.ScriptErrorsSuppressed = true; //InvestmentReqeust investmentRequest = new InvestmentReqeust { Amount = 10000, CellPhone = registerSuccessInfo.CellPhone, ClientType = 900, ProductIdentifier = "33B97C6537564B3FB349B35C949A930F", ReturnUrl = "http://www.dev.ad.jinyinmao.com.cn/redirect/Home/?request=http://www.baidu.com", Pwd = registerSuccessInfo.Pwd }; BankSercrityInfo bankSercrityInfo = await this.jymService.GetInformationData(userId); //http://fsgw.hkmdev.firstpay.com/ if (bankSercrityInfo.MerchantId == null) { //标识 if (action != null) { action(); } return; } string url = $"{urlB}phoenixFS-fsgw/gateway?data={HttpUtility.UrlEncode(bankSercrityInfo.Data)}&tm={HttpUtility.UrlEncode(bankSercrityInfo.Tm)}&merchantId={bankSercrityInfo.MerchantId}"; //添加一个 string transgerUrl = ConfigurationManager.AppSettings["TransferUrl"]; webBrowser.Navigate(new Uri(url, UriKind.Absolute)); int index = 0; webBrowser.DocumentCompleted += (obj, e) => { if (webBrowser.ReadyState < WebBrowserReadyState.Complete) { return; } HtmlDocument htmlDocument = webBrowser.Document; if (index == 0) { if (htmlDocument != null) { Thread th = new Thread(() => { try { //先获取余额 HtmlElement elementsBySpan = htmlDocument.GetElementsByTagName("span")[3]; string leftAmount = elementsBySpan.InnerText.Replace(",", ""); Logger.LoadData(@"TransactionText\UserLeftAmount.txt", $"{userId},{leftAmount}"); bool isRedirect = false; do { webBrowser.Navigate("javascript:var domList = $('a.underline');$.each($(domList), function (index, dom) { dom = $(dom); if (dom.text().trim() === '查看') { window.location.href = window.location.origin + dom.attr('href')}})"); Thread.Sleep(2000); //判断 string htmlText = htmlDocument.Body?.InnerText; if (htmlText != null && htmlText.Contains("账户流水查询")) { isRedirect = true; } } while (!isRedirect); //执行第二页 string url32 = webBrowser.Url.AbsoluteUri; string htmlRqid = htmlDocument.GetElementsByTagName("input")[4].GetAttribute("value"); if (string.IsNullOrEmpty(htmlRqid)) { if (action != null) { action(); } return; } string urlBase = $"{transgerUrl}phoenixFS-web/manage/showAccountQueryforJson?reqId={htmlRqid}&timeCode=4&timeType=1&pageSize=1000"; WebClient webClient = new WebClient(); List <BankDataModel> listBankDataModels = new List <BankDataModel>(); //先获取page byte[] allData1 = webClient.DownloadData(urlBase); string jsonData1 = Encoding.UTF8.GetString(allData1); BankDataModel bankDataModel1 = StringExtensions.FromJson <BankDataModel>(jsonData1); int totalPage = bankDataModel1.totalPage; int totalNums = bankDataModel1.pageNum; if (totalPage == 0) { if (action != null) { action(); } return; } for (int j = 0; j <= totalNums; j++) { urlBase = $"{transgerUrl}phoenixFS-web/manage/showAccountQueryforJson?reqId={htmlRqid}&timeCode=4&timeType=1&pageSize=1000" + "&page=" + (j + 1); byte[] allData = webClient.DownloadData(urlBase); string jsonData = Encoding.UTF8.GetString(allData); BankDataModel bankDataModel = StringExtensions.FromJson <BankDataModel>(jsonData); listBankDataModels.Add(bankDataModel); } //保存 foreach (BankDataModel bankDataModel in listBankDataModels) { foreach (userTrades userTrade in bankDataModel.userTrades) { string dateType = userTrade.transType; string amount = userTrade.amount.Replace(",", ""); string dateTime = userTrade.gmtCreate; switch (dateType) { case "返利": Logger.LoadData(@"TransactionText\Rebate.txt", $"{userId},{amount},{dateTime}"); break; case "债转放款": Logger.LoadData(@"TransactionText\DebtGrant.txt", $"{userId},{amount},{dateTime}"); break; case "网银充值": Logger.LoadData(@"TransactionText\Recharge.txt", $"{userId},{amount},{dateTime}"); break; case "提现": Logger.LoadData(@"TransactionText\Withdraw.txt", $"{userId},{amount},{dateTime}"); break; case "资金迁移": Logger.LoadData(@"TransactionText\TransferFunds.txt", $"{userId},{amount},{dateTime}"); break; case "放款": Logger.LoadData(@"TransactionText\Grant.txt", $"{userId},{amount},{dateTime}"); break; case "收费": Logger.LoadData(@"TransactionText\FeeInfo.txt", $"{userId},{amount},{dateTime}"); break; case "快捷充值": Logger.LoadData(@"TransactionText\Recharge.txt", $"{userId},{amount},{dateTime}"); break; case "还款-利息": Logger.LoadData(@"TransactionText\RepaymentWithInterest.txt", $"{userId},{amount},{dateTime}"); break; case "还款-本金": Logger.LoadData(@"TransactionText\RepaymentWithCapital.txt", $"{userId},{amount},{dateTime}"); break; case "还款-分润": break; case "预约投资红包": break; case "放款分润": break; } } } //string jsStr = "var dataList=[];var count=0;var maxlen=1;$(\"ul.cgb-query-filter .pt15 .mr25:last-child\").click();$(\"#submit\").click();function getCurrentListData(){$.each($(\"#table_data tr\"),function(index,item){var td=$(item).find(\"td\");dataList.push({date:$(td[0]).text(),type:$(td[1]).text(),amount:$(td[2]).text()})})}function getCurrentStatus(){maxlen=$(\"#page_footer\")[0].childNodes[0].nodeValue.replace(/^\\d+\\-(\\d+)条.+/,\"$1\");if($(\"#table_data tr\").length>0&&maxlen>dataList.length){getCurrentListData();return 1}if(maxlen==dataList.length){return 2}return 0}function main(){var timer=setInterval(function(){if(count>30){count=0;clearInterval(timer);window.location.reload();return}var status=getCurrentStatus();if(status==1){count=0;$(\"#next_page\").click()}else{if(status==2){var str=\"\";for(var i=0,len=dataList.length;i<len;i++){str+=\'<li><a class=\"date\">\'+dataList[i].date+\'</a><a class=\"type\">\'+dataList[i].type+\'</a><a class=\"amount\">\'+dataList[i].amount+\"</a></li>\"}$(document.body).append(\'<div class=\"jinyinmao\"></div>\');$(\".jinyinmao\").ready(function(){$(\".jinyinmao\").html(\"<ul>\"+str+\"</ul>\");$(\".jinyinmao\").ready(function(){$(\".jinyinmao > ul\").attr(\"id\",\"jinyinmao\")})});clearInterval(timer);return}else{count++}}},1000)}main();"; //webBrowser.Navigate("javascript:" + jsStr); ////string htmlText = webBrowser.DocumentText; //HtmlElement setPwd; //Thread.Sleep(2000); //do //{ // setPwd = htmlDocument.GetElementById("jinyinmao"); // Thread.Sleep(500); //} while (setPwd == null); ////获取所有的li //HtmlElementCollection liElementCollection = setPwd.GetElementsByTagName("li"); //string htmlText = setPwd.InnerText; //foreach (HtmlElement liElement in liElementCollection) //{ // //再获取a标签 // HtmlElementCollection aElementCollection = liElement.GetElementsByTagName("a"); // //查找 // string dateTime = aElementCollection[0].InnerText; // string dateType = aElementCollection[1].InnerText; // string amount = aElementCollection[2].InnerText; // //保存到文本文件中 放款,收费,快捷充值,还款本金,还款利息 //} //获取一下 if (action != null) { action(); } } catch (Exception exception) { if (action != null) { action(); } Logger.LoadData(@"TransactionText\Error.txt", $"{userId}----{exception.Message},{exception.StackTrace}"); } }) { IsBackground = true }; th.Start(); } } ++index; //MessageBox.Show(index.ToString()); }; }
public void End() { Thread.Sleep(500); Console.WriteLine("Engine ended"); }
public static void MouseMouseRelative(IMouse mouse, int x, int y) { mouse.PutMouseEvent(x, y, 0, 0, 0); Thread.Sleep(100); }
public void SuivantButtonClick() { SuivantButton.Click(); Thread.Sleep(5000); }
private void ListenPortMapPortWithServerName(PortMapItem item) { TcpListener listener = new TcpListener(IPAddress.Any, item.LocalPort); try { listener.Start(); } catch (Exception ex) { LogUtils.Error($"【失败】端口映射:{item.LocalPort}->{item.RemoteAddress}:{item.RemotePort}{Environment.NewLine}{ex.ToString()}"); return; } ListenerList.Add(listener); LogUtils.Info($"【成功】端口映射:{item.LocalPort}->{item.RemoteAddress}:{item.RemotePort}", false); AppCenter.Instance.StartNewTask(() => { TcpManage tcpManage = null; if (item.RemotePort == 3389) { tcpManage = new TcpManage(6); } while (true) { Socket socket = listener.AcceptSocket(); string remoteAddress = ((IPEndPoint)socket.RemoteEndPoint).Address.ToString(); if (tcpManage != null) { tcpManage.AddTcp(remoteAddress); if (!tcpManage.IsAllowConnect(remoteAddress)) { LogUtils.Info($"【安全策略】阻止内网穿透:{remoteAddress}->{item.LocalPort}->{item.RemoteAddress}:{item.RemotePort}", false); socket.SafeClose(); continue; } } LogUtils.Info($"开始内网穿透:{remoteAddress}->{item.LocalPort}->{item.RemoteAddress}:{item.RemotePort}", false); P2PTcpClient tcpClient = new P2PTcpClient(socket); AppCenter.Instance.StartNewTask(() => { string token = tcpClient.Token; //获取目标tcp if (ClientCenter.Instance.TcpMap.ContainsKey(item.RemoteAddress) && ClientCenter.Instance.TcpMap[item.RemoteAddress].TcpClient.Connected) { //加入待连接集合 ClientCenter.Instance.WaiteConnetctTcp.Add(token, tcpClient); //发送p2p申请 Models.Send.Send_0x0211 packet = new Models.Send.Send_0x0211(token, item.RemotePort, tcpClient.RemoteEndPoint); ClientCenter.Instance.TcpMap[item.RemoteAddress].TcpClient.Client.Send(packet.PackData()); AppCenter.Instance.StartNewTask(() => { Thread.Sleep(ConfigCenter.Instance.P2PTimeout); //如果5秒后没有匹配成功,则关闭连接 if (ClientCenter.Instance.WaiteConnetctTcp.ContainsKey(token)) { LogUtils.Warning($"【失败】内网穿透:{ConfigCenter.Instance.P2PTimeout / 1000}秒无响应,已超时."); ClientCenter.Instance.WaiteConnetctTcp[token].SafeClose(); ClientCenter.Instance.WaiteConnetctTcp.Remove(token); } }); } else { LogUtils.Warning($"【失败】内网穿透:{item.LocalPort}->{item.RemoteAddress}:{item.RemotePort} 客户端不在线!"); tcpClient.SafeClose(); } }); } }); }
public void EditConfirmButtonClick() { Thread.Sleep(2000); EditConfirmButton.Click(); }
private void ExecutePersistencyEvent() { var token = source.Token; while (!disposed) { try { Thread.Sleep(2000); if (!token.IsCancellationRequested && (this.pullRequestEvents.TryDequeue(out IGithubEvent @event) || (this.pullRequestEvents.Count == 0 && this.pushEvents.TryDequeue(out @event)))) { var appLocated = this.appRepository.GetByAsync(app => @event.ApplicationId == app.Id && app.TeamCode == @event.TeamId && app.OrganisationId == @event.OrganisationId && app.WebHookEnabled).GetAwaiter().GetResult(); if (appLocated != null) { Domain.Entities.GithubEventResult eventResult = null; if (@event is PushEvent) { var pushEvent = (@event as PushEvent); eventResult = this.repository.GetByAsync(x => x.OrganisationId == appLocated.OrganisationId && x.TeamCode == appLocated.TeamCode && x.AppId == appLocated.Id && x.PushCommit == pushEvent.HeadCommit.Id).GetAwaiter().GetResult(); if (eventResult == null) { eventResult = new Domain.Entities.GithubEventResult { FromBranch = pushEvent.Ref.Replace("refs/heads/", ""), ToBranch = "", PushCommit = pushEvent.HeadCommit.Id, CommitMessage = pushEvent.HeadCommit.Message, OrganisationId = appLocated.OrganisationId, TeamCode = appLocated.TeamCode, AppId = appLocated.Id, }; if (!appLocated.KeyBranches.Any(b => Regex.IsMatch(eventResult.FromBranch, b.BranchPattern))) { continue; } this.repository.AddAsync(eventResult).GetAwaiter().GetResult(); } eventResult.OrganisationId = appLocated.OrganisationId; eventResult.TeamCode = appLocated.TeamCode; eventResult.AppId = appLocated.Id; eventResult.Status = "ready"; } else { var pullRequestEvent = (@event as PullRequestEvent); eventResult = this.repository.GetByAsync(x => x.PullRequestId == pullRequestEvent.PullRequest.Id && x.OrganisationId == appLocated.OrganisationId && x.TeamCode == appLocated.TeamCode && x.AppId == appLocated.Id).GetAwaiter().GetResult(); if (eventResult == null) { eventResult = new Domain.Entities.GithubEventResult { FromBranch = pullRequestEvent.PullRequest.Head.Ref, ToBranch = pullRequestEvent.PullRequest.Base.Ref, PushCommit = pullRequestEvent.PullRequest.MergeCommitSha, CommitMessage = pullRequestEvent.PullRequest.Title + "|" + pullRequestEvent.PullRequest.Body, PullRequestId = pullRequestEvent.PullRequest.Id, OrganisationId = appLocated.OrganisationId, TeamCode = appLocated.TeamCode, AppId = appLocated.Id, }; if (!appLocated.Branches.Any(b => Regex.IsMatch(eventResult.FromBranch, b.BranchPattern))) { if (!appLocated.KeyBranches.Any(b => Regex.IsMatch(eventResult.FromBranch, b.BranchPattern))) { continue; } } if (!appLocated.KeyBranches.Any(b => Regex.IsMatch(eventResult.ToBranch, b.BranchPattern))) { continue; } eventResult = this.repository.AddAsync(eventResult).GetAwaiter().GetResult(); } eventResult.OrganisationId = appLocated.OrganisationId; eventResult.TeamCode = appLocated.TeamCode; eventResult.AppId = appLocated.Id; eventResult.PullRequestId = pullRequestEvent.PullRequest.Id; eventResult.FromBranch = pullRequestEvent.PullRequest.Head.Ref; eventResult.ToBranch = pullRequestEvent.PullRequest.Base.Ref; eventResult.PushCommit = pullRequestEvent.PullRequest.MergeCommitSha; eventResult.CommitMessage = pullRequestEvent.PullRequest.Title + "|" + pullRequestEvent.PullRequest.Body; eventResult.Status = pullRequestEvent.Action == "open" ? "pending" : pullRequestEvent.Action == "closed" && !pullRequestEvent.PullRequest.Merged ? "discard" : "pending"; } this.repository.UpdateAsync(eventResult).GetAwaiter().GetResult(); } } } catch (Exception ex) { Console.WriteLine(ex); } } }
private void DealLed4Message() { #region while (isStart) { try { int total; int space; int occupy; int fixLct; int spaceBigLct; Program.mng.SelectLctofInfo(out total, out space, out occupy, out fixLct, out spaceBigLct); CMasterTask[] mtsks = Program.mng.GetAllMasterTaskOfHid(14); string dataStr = ""; CSMG hall = Program.mng.SelectSMG(14); if (hall.Available) { #region 作业 if (hall.nIsWorking != 0) { CMasterTask gmtsk = null; if (mtsks != null) { foreach (CMasterTask mtsk in mtsks) { foreach (CTask tsk in mtsk.Tasks) { if (hall.nIsWorking == tsk.ID) { gmtsk = mtsk; } } } } if (gmtsk != null) { if (gmtsk.ICCardCode != "") { if (gmtsk.Type == EnmMasterTaskType.GetCar) { dataStr = "当前取车卡号:" + gmtsk.ICCardCode; } else if (gmtsk.Type == EnmMasterTaskType.SaveCar) { dataStr = "当前存车卡号:" + gmtsk.ICCardCode; } else { dataStr = "当前作业卡号:" + gmtsk.ICCardCode; } } } } else { dataStr = outMsg; } #endregion } else { dataStr = " 正在维护,请稍后存取车"; } if (dataStr != "") { if (string.Compare(dataStr, dataStr4) != 0) { myDelegate.DisplayLed4Title(dataStr); dataStr4 = dataStr; } } if (isStart) { Thread.Sleep(1000); } } catch (Exception ex) { CWSException.WriteError(ex.ToString()); Thread.Sleep(10000); } } #endregion }
// Entry point for the application. public static void Main(string[] args) { ServiceRuntime.RegisterServiceAsync("Tailspin.Web.Survey.PublicType", context => new WebHostingService(context, "ServiceEndpoint")).GetAwaiter().GetResult(); Thread.Sleep(Timeout.Infinite); }
private void OnCheckButtonClick(object sender, EventArgs e) { if (isPIDCanceling) { return; } if (isPIDRunning) { this.checkButton.Text = "Canceling.."; this.checkButton.Enabled = false; isPIDCanceling = true; return; } string inputText = this.pidInputTextbox.Text; inputText = inputText.Replace(" ", ""); inputText = inputText.Replace("\t", ""); inputText = inputText.Replace("\r", ""); string[] lines = inputText.Split('\n'); this.validLineList = new List <string>(); foreach (string l in lines) { if (l != "") { validLineList.Add(l); } } if (validLineList.Count == 0) { this.pidOutputTextbox.Text = "Key must be not empty!"; return; } isPIDRunning = true; this.checkButton.Text = "Cancel"; this.pidInputTextbox.Enabled = false; this.threadNumComboBox.Enabled = false; this.pidOutputTextbox.Text = ""; Application.DoEvents(); DateTime startTime = DateTime.Now; this.lineIndex = 0; this.doneLineCount = 0; int threadNum = this.threadNumComboBox.SelectedIndex + 1; int keyNum = validLineList.Count; List <Thread> tList = new List <Thread>(); for (int i = 0; i < threadNum; i++) { if (i >= keyNum) { break; } Thread t = new Thread(new ParameterizedThreadStart(CheckKeyOnThread)); t.Start(this); tList.Add(t); Thread.Sleep(10); } while (true) { int doneThreadNum = 0; for (int i = 0; i < tList.Count; i++) { if (!tList[i].IsAlive) { doneThreadNum++; } } this.UpdatePIDTimeLabel(startTime, this.doneLineCount, validLineList.Count); while (this.isUpdatingResult) { } ; if (this.result.Count > 0) { this.isUpdatingResult = true; // for (int i = 0; i < this.result.Count; i++) { this.pidOutputTextbox.AppendText(this.result[i].ToString()); } this.result.Clear(); this.UpdateKeyMS(); this.isUpdatingResult = false; } if (doneThreadNum == tList.Count) { break; } Thread.Sleep(1); } this.UpdatePIDTimeLabel(startTime, this.doneLineCount, validLineList.Count); this.checkButton.Text = "Check Online"; this.checkButton.Enabled = true; this.threadNumComboBox.Enabled = true; this.pidInputTextbox.Enabled = true; isPIDRunning = false; isPIDCanceling = false; }
public QualityPartTypeEntityView Wait(int seconds) { Thread.Sleep(seconds * 1000); return(this); }
private void Writer() { m_log.Info("[ASSET]: Writer started"); while (true) { string[] files = Directory.GetFiles(m_SpoolDirectory); if (files.Length > 0) { int tickCount = Environment.TickCount; for (int i = 0; i < files.Length; i++) { string hash = Path.GetFileNameWithoutExtension(files[i]); string s = HashToFile(hash); string diskFile = Path.Combine(m_FSBase, s); bool pathOk = false; // The cure for chicken bones! while (true) { try { // Try to make the directory we need for this file Directory.CreateDirectory(Path.GetDirectoryName(diskFile)); pathOk = true; break; } catch (System.IO.IOException) { // Creating the directory failed. This can't happen unless // a part of the path already exists as a file. Sadly the // SRAS data contains such files. string d = Path.GetDirectoryName(diskFile); // Test each path component in turn. If we can successfully // make a directory, the level below must be the chicken bone. while (d.Length > 0) { Console.WriteLine(d); try { Directory.CreateDirectory(Path.GetDirectoryName(d)); } catch (System.IO.IOException) { d = Path.GetDirectoryName(d); // We failed making the directory and need to // go up a bit more continue; } // We succeeded in making the directory and (d) is // the chicken bone break; } // Is the chicken alive? if (d.Length > 0) { Console.WriteLine(d); FileAttributes attr = File.GetAttributes(d); if ((attr & FileAttributes.Directory) == 0) { // The chicken bone should be resolved. // Return to writing the file. File.Delete(d); continue; } } } // Could not resolve, skipping m_log.ErrorFormat("[ASSET]: Could not resolve path creation error for {0}", diskFile); break; } if (pathOk) { try { byte[] data = File.ReadAllBytes(files[i]); using (GZipStream gz = new GZipStream(new FileStream(diskFile + ".gz", FileMode.Create), CompressionMode.Compress)) { gz.Write(data, 0, data.Length); gz.Close(); } File.Delete(files[i]); //File.Move(files[i], diskFile); } catch (System.IO.IOException e) { if (e.Message.StartsWith("Win32 IO returned ERROR_ALREADY_EXISTS")) { File.Delete(files[i]); } else { throw; } } } } int totalTicks = System.Environment.TickCount - tickCount; if (totalTicks > 0) // Wrap? { m_log.InfoFormat("[ASSET]: Write cycle complete, {0} files, {1} ticks, avg {2:F2}", files.Length, totalTicks, (double)totalTicks / (double)files.Length); } } Thread.Sleep(1000); } }
public QualityPartTypeCollectionView Wait(int seconds) { Thread.Sleep(seconds * 1000); return(this); }
public StyxDemo(String[] args) { var _Sniper1 = new List <Double>() { 22, 22, 12, 11, 10, 09, 09, 22, 08, 19, 09, 20, 21, 22, 22 }.ToSniper(); var _ActionArrow = new ActionArrow <Double>(message => { Console.WriteLine(" I: " + message); }); _Sniper1.OnMessageAvailable += _ActionArrow.ReceiveMessage; _Sniper1.StartToFire(); var _Sniper2 = new List <Int32>() { 22, 22, 12, 11, 10, 09, 09, 22, 08, 19, 09, 20, 21, 22, 22 }. ToSniper(Autostart: true, StartAsTask: true, InitialDelay: TimeSpan.FromSeconds(3)). BandFilter <Int32>(10, 20). SameValueFilter <Int32>(). ActionArrow(message => { Console.WriteLine("II: " + message); }); //var _f1 = new List<Int32>() { 22, 22, 12, 11, 10, 09, 09, 22, 08, 19, 09, 20, 21, 22, 22 }. // ToSniper(InitialDelay: TimeSpan.FromSeconds(10)); //var _f2 = _f1. // // ActionArrow((message) => { Console.WriteLine("new: '" + message + "'"); }). // BandFilter<Int32>(10, 20). // SameValueFilter<Int32>(). // IdentityArrow(). // ActionArrow((message) => { Console.WriteLine("passed: '" + message + "'"); }); ////_f1.SendTo((sender, message) => { Console.WriteLine("bypass: '******'"); return true; }); //_f1.StartToFire(true); //_f2.ReceiveMessage(22); //_f2.ReceiveMessage(12); //_f2.ReceiveMessage(11); //_f2.ReceiveMessage(10); //_f2.ReceiveMessage(09); //_f2.ReceiveMessage(09); //_f2.ReceiveMessage(22); //_f2.ReceiveMessage(08); //_f2.ReceiveMessage(19); //_f2.ReceiveMessage(09); //_f2.ReceiveMessage(20); //_f2.ReceiveMessage(21); //_f2.ReceiveMessage(22); //_f2.ReceiveMessage(22); while (true) { Thread.Sleep(100); } var ab = new ActionArrow <String>(msg => Console.WriteLine(msg)); ab.ReceiveMessage("hello"); var c = new FuncArrow <Int64, String>(message => message.ToString()); var d = new FuncArrow <String, String>(message => ">>>" + message); var e = new IdentityArrow <String>(PrintMe_A, PrintMe_B); c.OnMessageAvailable += d.ReceiveMessage; d.OnMessageAvailable += e.ReceiveMessage; e.OnMessageAvailable += PrintMe_B; e.OnMessageAvailable += (sender, message) => Console.WriteLine("Incoming message: '" + message + "'!"); c.ReceiveMessage(new Object(), 1234); // d.OnMessageAvailable += c.ReceiveMessage; c.FuncArrow(message => message.ToUpper(), d); }
private void ProcessRTPPackets() { try { Thread.CurrentThread.Name = "rtspclient-rtp"; _lastRTPReceivedAt = DateTime.Now; _lastBWCalcAt = DateTime.Now; while (!_isClosed) { while (_rtspSession.HasRTPPacket()) { RTPPacket rtpPacket = _rtspSession.GetNextRTPPacket(); if (rtpPacket != null) { _lastRTPReceivedAt = DateTime.Now; _bytesSinceLastBWCalc += RTPHeader.MIN_HEADER_LEN + rtpPacket.Payload.Length; if (_rtpTrackingAction != null) { double bwCalcSeconds = DateTime.Now.Subtract(_lastBWCalcAt).TotalSeconds; if (bwCalcSeconds > BANDWIDTH_CALCULATION_SECONDS) { _lastBWCalc = _bytesSinceLastBWCalc * 8 / bwCalcSeconds; _lastFrameRate = _framesSinceLastCalc / bwCalcSeconds; _bytesSinceLastBWCalc = 0; _framesSinceLastCalc = 0; _lastBWCalcAt = DateTime.Now; } var abbrevURL = (_url.Length <= 50) ? _url : _url.Substring(0, 50); string rtpTrackingText = String.Format("Url: {0}\r\nRcvd At: {1}\r\nSeq Num: {2}\r\nTS: {3}\r\nPayoad: {4}\r\nFrame Size: {5}\r\nBW: {6}\r\nFrame Rate: {7}", abbrevURL, DateTime.Now.ToString("HH:mm:ss:fff"), rtpPacket.Header.SequenceNumber, rtpPacket.Header.Timestamp, ((SDPMediaFormatsEnum)rtpPacket.Header.PayloadType).ToString(), _lastFrameSize + " bytes", _lastBWCalc.ToString("0.#") + "bps", _lastFrameRate.ToString("0.##") + "fps"); _rtpTrackingAction(rtpTrackingText); } if (rtpPacket.Header.Timestamp < _lastCompleteFrameTimestamp) { System.Diagnostics.Debug.WriteLine("Ignoring RTP packet with timestamp " + rtpPacket.Header.Timestamp + " as it's earlier than the last complete frame."); } else { while (_frames.Count > MAX_FRAMES_QUEUE_LENGTH) { var oldestFrame = _frames.OrderBy(x => x.Timestamp).First(); _frames.Remove(oldestFrame); System.Diagnostics.Debug.WriteLine("Receive queue full, dropping oldest frame with timestamp " + oldestFrame.Timestamp + "."); } var frame = _frames.Where(x => x.Timestamp == rtpPacket.Header.Timestamp).SingleOrDefault(); if (frame == null) { frame = new RTPFrame() { Timestamp = rtpPacket.Header.Timestamp, HasMarker = rtpPacket.Header.MarkerBit == 1 }; frame.AddRTPPacket(rtpPacket); _frames.Add(frame); } else { frame.HasMarker = (rtpPacket.Header.MarkerBit == 1); frame.AddRTPPacket(rtpPacket); } if (frame.IsComplete) { // The frame is ready for handing over to the UI. byte[] imageBytes = frame.GetFramePayload(); _lastFrameSize = imageBytes.Length; _framesSinceLastCalc++; _lastCompleteFrameTimestamp = rtpPacket.Header.Timestamp; //System.Diagnostics.Debug.WriteLine("Frame ready " + frame.Timestamp + ", sequence numbers " + frame.StartSequenceNumber + " to " + frame.EndSequenceNumber + ", payload length " + imageBytes.Length + "."); //logger.Debug("Frame ready " + frame.Timestamp + ", sequence numbers " + frame.StartSequenceNumber + " to " + frame.EndSequenceNumber + ", payload length " + imageBytes.Length + "."); _frames.Remove(frame); // Also remove any earlier frames as we don't care about anything that's earlier than the current complete frame. foreach (var oldFrame in _frames.Where(x => x.Timestamp <= rtpPacket.Header.Timestamp).ToList()) { System.Diagnostics.Debug.WriteLine("Discarding old frame for timestamp " + oldFrame.Timestamp + "."); logger.Warn("Discarding old frame for timestamp " + oldFrame.Timestamp + "."); _frames.Remove(oldFrame); } if (OnFrameReady != null) { try { //if (frame.FramePackets.Count == 1) //{ // // REMOVE. // logger.Warn("Discarding frame as there should have been more than 1 RTP packets."); //} //else //{ //System.Diagnostics.Debug.WriteLine("RTP frame ready for timestamp " + frame.Timestamp + "."); OnFrameReady(this, frame); //} } catch (Exception frameReadyExcp) { logger.Error("Exception RTSPClient.ProcessRTPPackets OnFrameReady. " + frameReadyExcp); } } } } } } if (DateTime.Now.Subtract(_lastRTPReceivedAt).TotalSeconds > RTP_TIMEOUT_SECONDS) { logger.Warn("No RTP packets were received on RTSP session " + _rtspSession.SessionID + " for " + RTP_TIMEOUT_SECONDS + ". The session will now be closed."); Close(); } else { Thread.Sleep(1); } } } catch (Exception excp) { logger.Error("Exception RTSPClient.ProcessRTPPackets. " + excp); } }
private static void NotificationTypeTest(int insertsCount, SqlDependencyEx.NotificationTypes testType) { int elementsInDetailsCount = 0; int changesReceived = 0; int expectedElementsInDetails = 0; var notificationTypes = GetMembers(testType); foreach (var temp in notificationTypes) { switch (temp) { case SqlDependencyEx.NotificationTypes.Insert: expectedElementsInDetails += insertsCount / 2; break; case SqlDependencyEx.NotificationTypes.Update: expectedElementsInDetails += insertsCount; break; case SqlDependencyEx.NotificationTypes.Delete: expectedElementsInDetails += insertsCount / 2; break; } } using (SqlDependencyEx sqlDependency = new SqlDependencyEx( TEST_CONNECTION_STRING, TEST_DATABASE_NAME, TEST_TABLE_NAME, "temp", testType)) { sqlDependency.TableChanged += (o, e) => { changesReceived++; if (e.Data == null) { return; } var inserted = e.Data.Element("inserted"); var deleted = e.Data.Element("deleted"); elementsInDetailsCount += inserted != null ? inserted.Elements("row").Count() : 0; elementsInDetailsCount += deleted != null ? deleted.Elements("row").Count() : 0; }; sqlDependency.Start(); MakeChunkedInsertDeleteUpdate(insertsCount); // Wait a little bit to receive all changes. Thread.Sleep(1000); } Assert.AreEqual(expectedElementsInDetails, elementsInDetailsCount); Assert.AreEqual(notificationTypes.Length, changesReceived); }
public void DateInputSendKey(String date) { DateprioriteInput.Click(); Thread.Sleep(3000); DateprioriteInput.SendKeys(date); }
public DispatcherWorkerThreadDetails(Thread thread) { this.Thread = thread; Dispatcher dispatcher; // Get the Dispatcher instance for the thread do { dispatcher = Dispatcher.FromThread(thread); // The dispatcher might not have been spun up yet so, if not, sleep and try again until it is if (dispatcher == null) { Thread.Sleep(100); } } while (dispatcher == null); // Hook the events that tell us when the Dispatcher is actually doing something DispatcherHooks dispatcherHooks = dispatcher.Hooks; dispatcherHooks.DispatcherInactive += (s, a) => this.HasWork = false; dispatcherHooks.OperationPosted += (s, a) => this.HasWork = true; }
public void Start() { Thread.Sleep(2500); Console.WriteLine("Engine started"); Thread.Sleep(5000); }