public override void Install(IDictionary stateSaver) { base.Install(stateSaver); var installdir = GetParameter("targetdir"); string msg = ""; foreach (var k in Context.Parameters.Keys) msg += (k + "\n"); msg += "VALUES:\n"; foreach (var v in Context.Parameters.Values) msg += (v + "\n"); //MessageBox.Show(msg); List<string> writeableDirs = new List<string>(); string configDir = Path.Combine(Path.Combine(installdir, "Myro"), "config"); string storeDir = Path.Combine(Path.Combine(installdir, "Myro"), "store"); writeableDirs.Add(configDir); writeableDirs.Add(storeDir); writeableDirs.AddRange(Directory.GetDirectories(configDir, "*", SearchOption.AllDirectories)); writeableDirs.AddRange(Directory.GetDirectories(storeDir, "*", SearchOption.AllDirectories)); string dirs = ""; foreach (var d in writeableDirs) { dirs += (d + "\n"); if (GrantModifyAccessToFolder("Everyone", d) != true) throw new Exception("Couldn't make " + d + " writeable"); } //MessageBox.Show("Made writeable:\n" + dirs); }
public void DownloadAllVideos(PDownload pDownload) { Broadcasts broadcasts = GetBroadcasts(pDownload.User); broadcasts.broadcasts = broadcasts.broadcasts.Where(b => b.available_for_replay || b.state == "RUNNING").ToList(); if (pDownload.IsReverseOrder) broadcasts.broadcasts.Reverse(); #region Selected Videos List<int> selectedVideos = pDownload.SelectedVideos; if (selectedVideos.Any()) { List<Broadcast> selectedBroadcasts = new List<Broadcast>(); selectedBroadcasts.AddRange(selectedVideos.Select(selectedVideo => broadcasts.broadcasts[selectedVideo])); broadcasts.broadcasts = selectedBroadcasts.ToList(); } #endregion #region Selected Broadcasts List<string> selectedBroadcastsText = pDownload.SelectedBroadcasts; if (selectedBroadcastsText.Any()) { broadcasts.broadcasts = selectedBroadcastsText.Select( selectedBroadcast => broadcasts.broadcasts.First(b => b.id == selectedBroadcast)).ToList(); } #endregion Console.WriteLine(broadcasts.broadcasts.Count + " broadcasts found."); foreach (var broadcast in broadcasts.broadcasts) { DownloadVideos(broadcast, pDownload.DownloadLiveStream); } }
public byte[] GetData() { List<byte> result = new List<byte>(); byte[] byteLabel = Encoding.ASCII.GetBytes(Label); Writer.AddBytes(result, byteLabel); foreach (Frame frame in Frames) { result.AddRange(frame.GetData()); } return result.ToArray(); }
private static List<FileItem> GetFiles(DirectoryInfo directory) { List<FileItem> files = new List<FileItem>(); foreach (FileInfo file in directory.GetFiles()) { files.Add(new FileItem(file)); } foreach (DirectoryInfo dir in directory.GetDirectories()) { files.AddRange(GetFiles(dir)); } return files; }
private List<string> GenerateReport() { if (!Files.Any()) return null; var fileHelper = new FileHelper(); var days = Files.Select(fileHelper.GetEntries).ToList(); var lines = new List<string>(); var runningTotal = new TimeSpan(0, 0, 0, 0); foreach (var d in days) { lines.AddRange(d.Select(entry => entry.ToString())); var hours = d.Sum(te => te.Hours); var minutes = d.Sum(te => te.Minutes); var seconds = d.Sum(te => te.Seconds); var ts = new TimeSpan(0, hours, minutes, seconds); runningTotal = runningTotal.Add(ts); lines.Add(string.Format("---- Total Time For Day ---- {0}:{1:D2}:{2:D2} ---------------", ts.Hours, ts.Minutes, ts.Seconds)); } lines.Add(string.Format("---- Total Time For All Days Selected ---- {0}:{1:D2}:{2:D2} ---------------", (runningTotal.Days * 24 + runningTotal.Hours), runningTotal.Minutes, runningTotal.Seconds)); return lines; }
public List<byte> GetData() { List<byte> result = new List<byte>(); byte[] byteLabel = Encoding.ASCII.GetBytes(Label); Writer.AddBytes(result, byteLabel); //write the size of the rest at the end Writer.AddBytes(result, BitPlane.Width); Writer.AddBytes(result, Height); Writer.AddBytes(result, Origin.X); Writer.AddBytes(result, Origin.Y); result.Add((byte)Direction); //now write the bitmask result.AddRange(BitPlane.GetData()); //write the indexes to the palette //first the size since it will usually be less than the bitplane bit count Writer.AddBytes(result, BitPlane.GetPixelCount() - 1); //then the actual indexes result.AddRange(GetDataList()); //int size = result.Count - 2; //now insert the size Writer.WriteSizeShort(result); return result; }
private void _路线属性_VisibilityChange(bool isvisible) { ListBoxEx innerControl = this._路线属性.InnerControl as ListBoxEx; if (!isvisible) { string str = ""; new List<string>(); ListBox.SelectedObjectCollection selectedItems = innerControl.SelectedItems; int count = innerControl.Items.Count; ArrayList list = new ArrayList(count); int val = 0; for (int i = 0; i < count; i++) { if (selectedItems.Contains(innerControl.Items[i])) { ListBoxItem item = innerControl.Items[i] as ListBoxItem; val |= Convert.ToInt32(item.Tag.ToString()); str = str + item.Name.ToString() + ","; } } this.setTimeSpeedReadOnly(this.dgvSubSpeedParam.CurrentRow, val); list.Add(Convert.ToString(val, 2).PadLeft(6, '0').ToCharArray()); if (this.dgvSubSpeedParam.CurrentCell != null) { try { this.dgvSubSpeedParam.CurrentCell.Value = str.Trim(",".ToCharArray()); this.dgvSubSpeedParam.CurrentCell.Tag = list; } catch (Exception) { } } } else { innerControl.ClearSelected(); if (this.dgvSubSpeedParam.CurrentCell.Tag == null) { List<string> list2 = new List<string>(); list2.AddRange(this.dgvSubSpeedParam.CurrentCell.Value.ToString().Split(",".ToCharArray())); int num4 = innerControl.Items.Count; for (int j = 0; j < num4; j++) { ListBoxItem item2 = innerControl.Items[j] as ListBoxItem; if (list2.Contains(item2.Name)) { innerControl.SetSelected(j, true); } } } else if (this.dgvSubSpeedParam.CurrentCell.Tag != null) { ArrayList tag = this.dgvSubSpeedParam.CurrentCell.Tag as ArrayList; if ((tag[0] as char[])[0].ToString().Equals("1")) { innerControl.SetSelected(4, true); } else { innerControl.SetSelected(4, false); } if ((tag[0] as char[])[1].ToString().Equals("1")) { innerControl.SetSelected(3, true); } else { innerControl.SetSelected(3, false); } if ((tag[0] as char[])[2].ToString().Equals("1")) { innerControl.SetSelected(2, true); } else { innerControl.SetSelected(2, false); } if ((tag[0] as char[])[3].ToString().Equals("1")) { innerControl.SetSelected(1, true); } else { innerControl.SetSelected(1, false); } if ((tag[0] as char[])[5].ToString().Equals("1")) { innerControl.SetSelected(0, true); } else { innerControl.SetSelected(0, false); } } } }
public List<byte> GetData() { List<byte> result = new List<byte>(); byte[] byteLabel = Encoding.ASCII.GetBytes(Label); Writer.AddBytes(result, byteLabel); //write the size of the rest at the end Writer.AddBytes(result, Width); Writer.AddBytes(result, Height); Writer.AddBytes(result, Origin.X); Writer.AddBytes(result, Origin.Y); result.Add((byte)Direction); //then the actual indexes result.AddRange(GetDataList()); //now insert the size Writer.WriteSizeShort(result); return result; }
private void _区域属性_VisibilityChange(bool isvisible) { ListBoxEx innerControl = this._区域属性.InnerControl as ListBoxEx; if (!isvisible) { string str = ""; new List<string>(); ListBox.SelectedObjectCollection selectedItems = innerControl.SelectedItems; int count = innerControl.Items.Count; ArrayList val = new ArrayList(count); for (int i = 0; i < count; i++) { string str2 = ""; if (selectedItems.Contains(innerControl.Items[i])) { str2 = "1"; ListBoxItem item = innerControl.Items[i] as ListBoxItem; str = str + item.Name.ToString() + ","; } else { str2 = "0"; } val.Add(str2); } this.setTimeSpeedReadOnly(this.dgvArea.CurrentRow, val); if (this.dgvArea.CurrentCell != null) { this.dgvArea.CurrentCell.Value = str.Trim(",".ToCharArray()); this.dgvArea.CurrentCell.Tag = val; } } else { innerControl.ClearSelected(); if (this.dgvArea.CurrentCell.Tag == null) { List<string> list2 = new List<string>(); list2.AddRange(this.dgvArea.CurrentCell.Value.ToString().Split(",".ToCharArray())); int num3 = innerControl.Items.Count; for (int j = 0; j < num3; j++) { ListBoxItem item2 = innerControl.Items[j] as ListBoxItem; if (list2.Contains(item2.Name)) { innerControl.SetSelected(j, true); } } } else if (this.dgvArea.CurrentCell.Tag != null) { ArrayList tag = this.dgvArea.CurrentCell.Tag as ArrayList; for (int k = 0; k < innerControl.Items.Count; k++) { innerControl.SetSelected(k, tag[k].ToString().Equals("1")); } } } }
public byte[] GetData() { List<byte> result = new List<byte>(); byte[] byteLabel = Encoding.ASCII.GetBytes(Label); Writer.AddBytes(result, byteLabel); foreach (Chunk chunk in Chunks) { result.AddRange(chunk.GetData()); } //don't forget the size Writer.WriteSizeInt(result); return result.ToArray(); }
private void UpdateChunklist(Broadcast broadcast, string baseUrl, ref List<string> playlist, ref bool liveStream) { List<string> currentChunks; try { currentChunks = GetPlaylistUrls(baseUrl + "chunklist.m3u8"); } catch (Exception) { liveStream = false; return; } playlist.AddRange(currentChunks.Except(playlist)); playlist = playlist.Except(_localFileActions.GetValidFiles(broadcast.username, broadcast.id)).ToList(); }
public List<byte> GetData() { List<byte> result = new List<byte>(); byte[] byteLabel = Encoding.ASCII.GetBytes(Label); Writer.AddBytes(result, byteLabel); //write the size of the rest at the end Writer.AddBytes(result, BitPlane.Width); Writer.AddBytes(result, Height); Writer.AddBytes(result, Origin.X); Writer.AddBytes(result, Origin.Y); //now write the bitmask result.AddRange(BitPlane.GetData()); //now insert the size Writer.WriteSizeShort(result); return result; }
private void RenderPicture(Graphics g) { var angleOffset = -Math.PI / 2; var anglePerStudent = Math.PI * 2 / _students.Count; var center = new Point(_width / 2, _height / 2); var maxRadius = Math.Min(center.X, center.Y) * _ratio / 100.0f; Func<int, float, float, Point> getPoint = (id, delta, lRadius) => { var radius = maxRadius * lRadius / 100.0f; var angle = angleOffset + anglePerStudent * (id + delta / 100.0f); return center + new Size((int)(radius * Math.Cos(angle)), (int)(radius * Math.Sin(angle))); }; Func<float, Rectangle> getRectangle = lRadius => { var delta = maxRadius*lRadius/100.0f; return new Rectangle((int)(center.X - delta), (int)(center.Y - delta), (int) (2*delta), (int) (2*delta)); }; Func<double, float> toDeg = rad => (float) (rad / Math.PI * 180); // Пороговые линии for (var j = 0; j < _grades.Count; ++j) { g.DrawPie(new Pen(Color.Black, j == (_grades.Count - 1) ? 4 : 2) {DashPattern = new[] {3.0f, 5.0f}}, getRectangle(_grades[j]), 0.0f, 360.0f); } // Основные и дополнительные зависимости for (var i = 0; i < _students.Count; ++i) { var grades = _students[i].Grades; var mainGrades = (_mode == Mode.Pie || _mode == Mode.Pie) ? new[]{0.0f}.Concat(grades[0]).ToList() : Enumerable.Range(0, grades[0].Length + 1).Select(a => a * 100.0f / grades[0].Length).ToList(); // Основная зависимость for (var j = mainGrades.Count - 1; j >= 1; --j) { if (Math.Abs(mainGrades[j]) > Parameters.Tolerance) { var brush = GetBrush(j, grades); g.FillPie(brush, getRectangle(mainGrades[j]), toDeg(angleOffset + anglePerStudent * i), toDeg(anglePerStudent)); g.DrawPie(new Pen(Color.Black, 2), getRectangle(mainGrades[j]), toDeg(angleOffset + anglePerStudent * i), toDeg(anglePerStudent)); } } // Дополнительные зависимости for (var k = 1; k < grades.Length; ++k) { var addGrades = new List<float> {0.0f}; addGrades.AddRange(grades[k]); if (addGrades.All(a => a < Parameters.Tolerance)) continue; for (var j = 0; j < addGrades.Count - 1; ++j) g.DrawLine(_additionalData[(k - 1) % _additionalData.Count], getPoint(i, addGrades[j], mainGrades[j]), getPoint(i, addGrades[j + 1], mainGrades[j + 1])); } } // Разделительные линии между секторами for (var i = 0; i < _students.Count; ++i) { g.DrawLine(new Pen(Color.Black, 2), center, getPoint(i, 0, 110)); } // Разделители между секторами for (var j = 0; j < _part.Count; ++j) { g.DrawLine(new Pen(Color.Black, 6), center, getPoint(_part[j], 0, 110)); } var half = (int)Math.Ceiling(_students.Count / 2.0); // Имена студентов for (var i = 0; i < _students.Count; ++i) { var posRight = i < half; var point = getPoint(i, 50, 0.6f * maxRadius); var message = string.Format("{0} ({1})", _students[i].Name, _students[i].Info); g.DrawString(message, _font, Brushes.Black, point, posRight ? _rightFormat : _leftFormat); } var lOffset = new Point(470, 30); var lOffset2 = center + new Size(lOffset.X, lOffset.Y); const int lSize = 30; if (_mode == Mode.BlackRound || _mode == Mode.ColorRound) { lOffset = new Point(530, 30); lOffset2 = center + new Size(lOffset.X, lOffset.Y); // Дата прохождения теста g.DrawString(_localizations["passingTestDate"], _smallFont, Brushes.Black, lOffset2.X - 30, lOffset2.Y - 215); for (var j = 0; j < _dates.Count; ++j) { var rect = getRectangle(100 / _dates.Count * (j + 1)); rect.Offset(lOffset); var center2 = new Point(rect.X + rect.Width / 2, rect.Y + rect.Height / 2); g.DrawPie(new Pen(Color.Black, j == (_dates.Count - 1) ? 4 : 2) { DashPattern = new[] { 3.0f, 5.0f } }, rect, 270, 40); g.DrawString(_dates[j], _smallFont, Brushes.Black, center2 + new Size(-5, (int)(-(j + 1) * maxRadius / _dates.Count)), _leftFormat); if ((_grades.Count - 1) == j) { g.DrawLine(new Pen(Brushes.Black, 4.0f), center2, center2 + new Size((int)(maxRadius * Math.Cos(-Math.PI / 180 * 90)), (int)(maxRadius * Math.Sin(-Math.PI / 180 * 90)))); g.DrawLine(new Pen(Brushes.Black, 4.0f), center2, center2 + new Size((int)(maxRadius * Math.Cos(-Math.PI / 180 * 50)), (int)(maxRadius * Math.Sin(-Math.PI / 180 * 50)))); } } var gradeOffsetY = lOffset2.Y + (int)(1.5 * lSize); var gradeSizeY = lSize * 4; var gradeOffset = 1.0f; // Количество баллов за тест g.DrawString(_localizations["scorePerTest"], _smallFont, Brushes.Black, lOffset2.X - 30, lOffset2.Y + 15); var grades2 = new[] { 0.0f }.Concat(_grades.Take(_grades.Count - 1)).ToArray(); if (_mode == Mode.ColorRound) { for (var i = grades2.Length - 1; i >= 0; --i) { var grade = grades2[i] / 100.0f; var fullRect = getRectangle(grade * 100.0f); fullRect.Offset(lOffset); var pgb = new LinearGradientBrush( new Point { X = 0, Y = gradeOffsetY + (int)(gradeSizeY * (1 - gradeOffset)) }, new Point { X = 0, Y = gradeOffsetY + (int)(gradeSizeY * (1 - grade)) }, new HslColor(_modeParam[0], _modeParam[1], _modeParam[i + 3]), new HslColor(_modeParam[0], _modeParam[1], _modeParam[i + 2]) ); g.FillRectangle(pgb, lOffset2.X, gradeOffsetY + (int)(gradeSizeY * (1 - gradeOffset)), lSize, (int)(gradeSizeY * gradeOffset)); gradeOffset = grade; } } else { gradeOffset = 1.0f; for (var i = 100; i >= 0; i -= 10) { var fullRect = getRectangle(i); fullRect.Offset(lOffset); var pgb = TranslateGradeToHatch(i); g.FillRectangle(pgb, lOffset2.X, gradeOffsetY + (int)(gradeSizeY * (1 - gradeOffset)), lSize, (int)(gradeSizeY * (gradeOffset - i / 100.0f))); gradeOffset = i/100.0f; } } gradeOffset = 1.0f; for (var i = grades2.Length - 1; i >= 0; --i) { var grade = grades2[i] / 100.0f; var fullRect = getRectangle(grade * 100.0f); fullRect.Offset(lOffset); g.DrawString(_grades[i].ToString(), _smallFont, Brushes.Black, lOffset2.X + 2 * lSize, gradeOffsetY + (int)(gradeSizeY * (1 - gradeOffset)), _leftFormat); gradeOffset = grade; } g.DrawRectangle(Pens.Black, lOffset2.X, gradeOffsetY, lSize, gradeSizeY); } else { // Количество баллов за тест g.DrawString(_localizations["scorePerTest"], _smallFont, Brushes.Black, lOffset2.X - 30, lOffset2.Y - 215); for (var j = 0; j < _grades.Count; ++j) { var rect = getRectangle(_grades[j]); rect.Offset(lOffset); var center2 = new Point(rect.X + rect.Width / 2, rect.Y + rect.Height / 2); g.DrawPie(new Pen(Color.Black, j == (_grades.Count - 1) ? 4 : 2) { DashPattern = new[] { 3.0f, 5.0f } }, rect, 270, 40); g.DrawString(_grades[j].ToString(), _smallFont, Brushes.Black, center2 + new Size(-5, (int)(-_grades[j] * maxRadius / 100)), _leftFormat); if ((_grades.Count - 1) == j) { g.DrawLine(new Pen(Brushes.Black, 4.0f), center2, center2 + new Size((int)(maxRadius * Math.Cos(-Math.PI / 180 * 90)), (int)(maxRadius * Math.Sin(-Math.PI / 180 * 90)))); g.DrawLine(new Pen(Brushes.Black, 4.0f), center2, center2 + new Size((int)(maxRadius * Math.Cos(-Math.PI / 180 * 50)), (int)(maxRadius * Math.Sin(-Math.PI / 180 * 50)))); } } // Дата прохождения теста g.DrawString(_localizations["passingTestDate"], _smallFont, Brushes.Black, lOffset2.X - 30, lOffset2.Y + 15); for (var j = 0; j < _dates.Count; ++j) { var lYOffset = (int)(lOffset2.Y + (j + 1) * lSize * 1.5); if (_mode == 0) g.FillRectangle(_brushes[j % _brushes.Count], lOffset2.X, lYOffset, lSize, lSize); g.DrawRectangle(new Pen(Brushes.Black, 2.0f), lOffset2.X, lYOffset, lSize, lSize); g.DrawString(_dates[j], _smallFont, Brushes.Black, lOffset2.X + lSize, lYOffset); } } // Легенда дополнительных зависимостей var additionalLegendStartPoint = center + new Size((int)(-2.4 * maxRadius), -30); for (var k = 0; k < _additionalName.Count; ++k) { var nameSize = g.MeasureString(_additionalName[k], _smallFont); g.DrawLine(_additionalData[k], additionalLegendStartPoint, additionalLegendStartPoint + new Size(-(int)nameSize.Width, 0)); additionalLegendStartPoint -= new Size(0, (int)_additionalData[k].Width + 10); g.DrawString(_additionalName[k], _smallFont, Brushes.Black, additionalLegendStartPoint, _leftFormat); additionalLegendStartPoint -= new Size(0, (int)nameSize.Height + 30); } }
private void ConnectionsManagerThread() { Stopwatch connectionCheckStopwatch = new Stopwatch(); connectionCheckStopwatch.Start(); Stopwatch refreshStopwatch = new Stopwatch(); Stopwatch pushBlockDiffusionStopwatch = new Stopwatch(); pushBlockDiffusionStopwatch.Start(); Stopwatch pushBlockUploadStopwatch = new Stopwatch(); pushBlockUploadStopwatch.Start(); Stopwatch pushBlockDownloadStopwatch = new Stopwatch(); pushBlockDownloadStopwatch.Start(); Stopwatch pushMetadataUploadStopwatch = new Stopwatch(); pushMetadataUploadStopwatch.Start(); Stopwatch pushMetadataDownloadStopwatch = new Stopwatch(); pushMetadataDownloadStopwatch.Start(); for (; ; ) { Thread.Sleep(1000); if (this.State == ManagerState.Stop) return; var connectionCount = 0; lock (this.ThisLock) { connectionCount = _connectionManagers.Count; } if (connectionCount > ((this.ConnectionCountLimit / 3) * 1) && connectionCheckStopwatch.Elapsed.TotalMinutes >= 5) { connectionCheckStopwatch.Restart(); var nodeSortItems = new List<NodeSortItem>(); lock (this.ThisLock) { foreach (var connectionManager in _connectionManagers) { nodeSortItems.Add(new NodeSortItem() { Node = connectionManager.Node, Priority = _messagesManager[connectionManager.Node].Priority, LastPullTime = _messagesManager[connectionManager.Node].LastPullTime, }); } } nodeSortItems.Sort((x, y) => { int c = x.Priority.CompareTo(y.Priority); if (c != 0) return c; return x.LastPullTime.CompareTo(y.LastPullTime); }); foreach (var node in nodeSortItems.Select(n => n.Node).Take(1)) { ConnectionManager connectionManager = null; lock (this.ThisLock) { connectionManager = _connectionManagers.FirstOrDefault(n => n.Node == node); } if (connectionManager != null) { try { lock (this.ThisLock) { this.RemoveNode(connectionManager.Node); } connectionManager.PushCancel(); Debug.WriteLine("ConnectionManager: Push Cancel"); } catch (Exception) { } this.RemoveConnectionManager(connectionManager); } } } if (!refreshStopwatch.IsRunning || refreshStopwatch.Elapsed.TotalSeconds >= 30) { refreshStopwatch.Restart(); // トラストにより必要なMetadataを選択し、不要なMetadataを削除する。 ThreadPool.QueueUserWorkItem((object wstate) => { if (_refreshThreadRunning) return; _refreshThreadRunning = true; try { var lockSignatures = this.OnLockSignaturesEvent(); if (lockSignatures == null) return; var lockWikis = this.OnLockWikisEvent(); if (lockWikis == null) return; var lockChats = this.OnLockChatsEvent(); if (lockChats == null) return; // Broadcast { // Signature { var removeSignatures = new HashSet<string>(); removeSignatures.UnionWith(_settings.MetadataManager.GetBroadcastSignatures()); removeSignatures.ExceptWith(lockSignatures); var sortList = removeSignatures .OrderBy(n => { DateTime t; _broadcastSignatureLastAccessTimes.TryGetValue(n, out t); return t; }).ToList(); _settings.MetadataManager.RemoveBroadcastSignatures(sortList.Take(sortList.Count - 1024)); var liveSignatures = new HashSet<string>(_settings.MetadataManager.GetBroadcastSignatures()); foreach (var signature in _broadcastSignatureLastAccessTimes.Keys.ToArray()) { if (liveSignatures.Contains(signature)) continue; _broadcastSignatureLastAccessTimes.Remove(signature); } } } // Unicast { // Signature { var removeSignatures = new HashSet<string>(); removeSignatures.UnionWith(_settings.MetadataManager.GetUnicastSignatures()); removeSignatures.ExceptWith(lockSignatures); var sortList = removeSignatures .OrderBy(n => { DateTime t; _unicastSignatureLastAccessTimes.TryGetValue(n, out t); return t; }).ToList(); _settings.MetadataManager.RemoveUnicastSignatures(sortList.Take(sortList.Count - 1024)); var liveSignatures = new HashSet<string>(_settings.MetadataManager.GetUnicastSignatures()); foreach (var signature in _unicastSignatureLastAccessTimes.Keys.ToArray()) { if (liveSignatures.Contains(signature)) continue; _unicastSignatureLastAccessTimes.Remove(signature); } } } // Multicast { // Wiki { var removeWikis = new HashSet<Wiki>(); removeWikis.UnionWith(_settings.MetadataManager.GetMulticastWikis()); removeWikis.ExceptWith(lockWikis); var sortList = removeWikis .OrderBy(n => { DateTime t; _multicastWikiLastAccessTimes.TryGetValue(n, out t); return t; }).ToList(); _settings.MetadataManager.RemoveMulticastWikis(sortList.Take(sortList.Count - 1024)); var liveWikis = new HashSet<Wiki>(_settings.MetadataManager.GetMulticastWikis()); foreach (var tag in _multicastWikiLastAccessTimes.Keys.ToArray()) { if (liveWikis.Contains(tag)) continue; _multicastWikiLastAccessTimes.Remove(tag); } } // Chat { var removeChats = new HashSet<Chat>(); removeChats.UnionWith(_settings.MetadataManager.GetMulticastChats()); removeChats.ExceptWith(lockChats); var sortList = removeChats .OrderBy(n => { DateTime t; _multicastChatLastAccessTimes.TryGetValue(n, out t); return t; }).ToList(); _settings.MetadataManager.RemoveMulticastChats(sortList.Take(sortList.Count - 1024)); var liveChats = new HashSet<Chat>(_settings.MetadataManager.GetMulticastChats()); foreach (var tag in _multicastChatLastAccessTimes.Keys.ToArray()) { if (liveChats.Contains(tag)) continue; _multicastChatLastAccessTimes.Remove(tag); } } } // Unicast { var trustSignature = new HashSet<string>(lockSignatures); { var now = DateTime.UtcNow; var removeSignatureMessageMetadatas = new HashSet<SignatureMessageMetadata>(); foreach (var targetSignature in _settings.MetadataManager.GetUnicastSignatures()) { // SignatureMessage { var trustMetadatas = new Dictionary<string, List<SignatureMessageMetadata>>(); var untrustMetadatas = new Dictionary<string, List<SignatureMessageMetadata>>(); foreach (var metadata in _settings.MetadataManager.GetSignatureMessageMetadatas(targetSignature)) { var signature = metadata.Certificate.ToString(); if (trustSignature.Contains(signature)) { List<SignatureMessageMetadata> list; if (!trustMetadatas.TryGetValue(signature, out list)) { list = new List<SignatureMessageMetadata>(); trustMetadatas[signature] = list; } list.Add(metadata); } else { List<SignatureMessageMetadata> list; if (!untrustMetadatas.TryGetValue(signature, out list)) { list = new List<SignatureMessageMetadata>(); untrustMetadatas[signature] = list; } list.Add(metadata); } } removeSignatureMessageMetadatas.UnionWith(untrustMetadatas.Randomize().Skip(256).SelectMany(n => n.Value)); foreach (var list in CollectionUtilities.Unite(trustMetadatas.Values, untrustMetadatas.Values)) { if (list.Count <= 32) continue; list.Sort((x, y) => x.CreationTime.CompareTo(y.CreationTime)); removeSignatureMessageMetadatas.UnionWith(list.Take(list.Count - 32)); } } } foreach (var metadata in removeSignatureMessageMetadatas) { _settings.MetadataManager.RemoveMetadata(metadata); } } } // Multicast { var trustSignature = new HashSet<string>(lockSignatures); { var now = DateTime.UtcNow; var removeWikiDocumentMetadatas = new HashSet<WikiDocumentMetadata>(); foreach (var wiki in _settings.MetadataManager.GetMulticastWikis()) { // WikiDocument { var trustMetadatas = new Dictionary<string, List<WikiDocumentMetadata>>(); var untrustMetadatas = new Dictionary<string, List<WikiDocumentMetadata>>(); foreach (var metadata in _settings.MetadataManager.GetWikiDocumentMetadatas(wiki)) { var signature = metadata.Certificate.ToString(); if (trustSignature.Contains(signature)) { List<WikiDocumentMetadata> list; if (!trustMetadatas.TryGetValue(signature, out list)) { list = new List<WikiDocumentMetadata>(); trustMetadatas[signature] = list; } list.Add(metadata); } else { List<WikiDocumentMetadata> list; if (!untrustMetadatas.TryGetValue(signature, out list)) { list = new List<WikiDocumentMetadata>(); untrustMetadatas[signature] = list; } list.Add(metadata); } } removeWikiDocumentMetadatas.UnionWith(untrustMetadatas.Randomize().Skip(256).SelectMany(n => n.Value)); foreach (var list in CollectionUtilities.Unite(trustMetadatas.Values, untrustMetadatas.Values)) { if (list.Count <= 32) continue; list.Sort((x, y) => x.CreationTime.CompareTo(y.CreationTime)); removeWikiDocumentMetadatas.UnionWith(list.Take(list.Count - 32)); } } } foreach (var metadata in removeWikiDocumentMetadatas) { _settings.MetadataManager.RemoveMetadata(metadata); } } { var now = DateTime.UtcNow; var removeChatMessageMetadatas = new HashSet<ChatMessageMetadata>(); foreach (var chat in _settings.MetadataManager.GetMulticastChats()) { // ChatMessage { var trustMetadatas = new Dictionary<string, List<ChatMessageMetadata>>(); var untrustMetadatas = new Dictionary<string, List<ChatMessageMetadata>>(); foreach (var metadata in _settings.MetadataManager.GetChatMessageMetadatas(chat)) { var signature = metadata.Certificate.ToString(); if (trustSignature.Contains(signature)) { List<ChatMessageMetadata> list; if (!trustMetadatas.TryGetValue(signature, out list)) { list = new List<ChatMessageMetadata>(); trustMetadatas[signature] = list; } list.Add(metadata); } else { List<ChatMessageMetadata> list; if (!untrustMetadatas.TryGetValue(signature, out list)) { list = new List<ChatMessageMetadata>(); untrustMetadatas[signature] = list; } list.Add(metadata); } } removeChatMessageMetadatas.UnionWith(untrustMetadatas.Randomize().Skip(256).SelectMany(n => n.Value)); foreach (var list in CollectionUtilities.Unite(trustMetadatas.Values, untrustMetadatas.Values)) { if (list.Count <= 32) continue; list.Sort((x, y) => x.CreationTime.CompareTo(y.CreationTime)); removeChatMessageMetadatas.UnionWith(list.Take(list.Count - 32)); } } } foreach (var metadata in removeChatMessageMetadatas) { _settings.MetadataManager.RemoveMetadata(metadata); } } } } catch (Exception e) { Log.Error(e); } finally { _refreshThreadRunning = false; } }); } // 拡散アップロード if (connectionCount > _diffusionConnectionCountLowerLimit && pushBlockDiffusionStopwatch.Elapsed.TotalSeconds >= 60) { pushBlockDiffusionStopwatch.Restart(); // 拡散アップロードするブロック数を10000以下に抑える。 lock (this.ThisLock) { lock (_settings.DiffusionBlocksRequest.ThisLock) { if (_settings.DiffusionBlocksRequest.Count > 10000) { foreach (var key in _settings.DiffusionBlocksRequest.ToArray().Randomize() .Take(_settings.DiffusionBlocksRequest.Count - 10000).ToList()) { _settings.DiffusionBlocksRequest.Remove(key); } } } } // 存在しないブロックのKeyをRemoveする。 lock (this.ThisLock) { lock (_settings.DiffusionBlocksRequest.ThisLock) { foreach (var key in _cacheManager.ExceptFrom(_settings.DiffusionBlocksRequest.ToArray()).ToArray()) { _settings.DiffusionBlocksRequest.Remove(key); } } lock (_settings.UploadBlocksRequest.ThisLock) { foreach (var key in _cacheManager.ExceptFrom(_settings.UploadBlocksRequest.ToArray()).ToArray()) { _settings.UploadBlocksRequest.Remove(key); } } } var baseNode = this.BaseNode; var otherNodes = new List<Node>(); lock (this.ThisLock) { otherNodes.AddRange(_connectionManagers.Select(n => n.Node)); } var messageManagers = new Dictionary<Node, MessageManager>(); foreach (var node in otherNodes) { messageManagers[node] = _messagesManager[node]; } var diffusionBlocksList = new List<Key>(); { { var array = _settings.UploadBlocksRequest.ToArray(); _random.Shuffle(array); int count = 256; for (int i = 0; i < count && i < array.Length; i++) { diffusionBlocksList.Add(array[i]); } } { var array = _settings.DiffusionBlocksRequest.ToArray(); _random.Shuffle(array); int count = 256; for (int i = 0; i < count && i < array.Length; i++) { diffusionBlocksList.Add(array[i]); } } } _random.Shuffle(diffusionBlocksList); { var diffusionBlocksDictionary = new Dictionary<Node, HashSet<Key>>(); foreach (var key in diffusionBlocksList) { try { var requestNodes = new List<Node>(); // 自分より距離が遠いノードにもアップロードを試みる。 foreach (var node in Kademlia<Node>.Search(key.Hash, otherNodes, 3)) { requestNodes.Add(node); } if (requestNodes.Any(n => _messagesManager[n].StockBlocks.Contains(key))) { _settings.UploadBlocksRequest.Remove(key); _settings.DiffusionBlocksRequest.Remove(key); continue; } for (int i = 0; i < requestNodes.Count; i++) { HashSet<Key> collection; if (!diffusionBlocksDictionary.TryGetValue(requestNodes[i], out collection)) { collection = new HashSet<Key>(); diffusionBlocksDictionary[requestNodes[i]] = collection; } collection.Add(key); } } catch (Exception e) { Log.Error(e); } } lock (_diffusionBlocksDictionary.ThisLock) { _diffusionBlocksDictionary.Clear(); foreach (var pair in diffusionBlocksDictionary) { var node = pair.Key; var targets = pair.Value; _diffusionBlocksDictionary.Add(node, new Queue<Key>(targets.Randomize())); } } } } // アップロード if (connectionCount >= _uploadingConnectionCountLowerLimit && pushBlockUploadStopwatch.Elapsed.TotalSeconds >= 10) { pushBlockUploadStopwatch.Restart(); var baseNode = this.BaseNode; var otherNodes = new List<Node>(); lock (this.ThisLock) { otherNodes.AddRange(_connectionManagers.Select(n => n.Node)); } var messageManagers = new Dictionary<Node, MessageManager>(); foreach (var node in otherNodes) { messageManagers[node] = _messagesManager[node]; } { var uploadBlocksDictionary = new Dictionary<Node, List<Key>>(); foreach (var pair in messageManagers) { var node = pair.Key; var messageManager = pair.Value; uploadBlocksDictionary.Add(node, _cacheManager.IntersectFrom(messageManager.PullBlocksRequest.ToArray().Randomize()).Take(128).ToList()); } lock (_uploadBlocksDictionary.ThisLock) { _uploadBlocksDictionary.Clear(); foreach (var pair in uploadBlocksDictionary) { var node = pair.Key; var targets = pair.Value; _uploadBlocksDictionary.Add(node, new Queue<Key>(targets.Randomize())); } } } } // ダウンロード if (connectionCount >= _downloadingConnectionCountLowerLimit && pushBlockDownloadStopwatch.Elapsed.TotalSeconds >= 60) { pushBlockDownloadStopwatch.Restart(); var baseNode = this.BaseNode; var otherNodes = new List<Node>(); lock (this.ThisLock) { otherNodes.AddRange(_connectionManagers.Select(n => n.Node)); } var messageManagers = new Dictionary<Node, MessageManager>(); foreach (var node in otherNodes) { messageManagers[node] = _messagesManager[node]; } var pushBlocksLinkList = new List<Key>(); var pushBlocksRequestList = new List<Key>(); { { var array = _cacheManager.ToArray(); _random.Shuffle(array); int count = _maxBlockLinkCount; for (int i = 0; count > 0 && i < array.Length; i++) { if (!messageManagers.Values.Any(n => n.PushBlocksLink.Contains(array[i]))) { pushBlocksLinkList.Add(array[i]); count--; } } } foreach (var pair in messageManagers) { var node = pair.Key; var messageManager = pair.Value; { var array = messageManager.PullBlocksLink.ToArray(); _random.Shuffle(array); int count = (int)(_maxBlockLinkCount * ((double)12 / otherNodes.Count)); for (int i = 0; count > 0 && i < array.Length; i++) { if (!messageManagers.Values.Any(n => n.PushBlocksLink.Contains(array[i]))) { pushBlocksLinkList.Add(array[i]); count--; } } } } { var array = _cacheManager.ExceptFrom(_downloadBlocks.ToArray()).ToArray(); _random.Shuffle(array); int count = _maxBlockRequestCount; for (int i = 0; count > 0 && i < array.Length; i++) { if (!messageManagers.Values.Any(n => n.PushBlocksRequest.Contains(array[i]))) { pushBlocksRequestList.Add(array[i]); count--; } } } foreach (var pair in messageManagers) { var node = pair.Key; var messageManager = pair.Value; { var array = _cacheManager.ExceptFrom(messageManager.PullBlocksRequest.ToArray()).ToArray(); _random.Shuffle(array); int count = (int)(_maxBlockRequestCount * ((double)12 / otherNodes.Count)); for (int i = 0; count > 0 && i < array.Length; i++) { if (!messageManagers.Values.Any(n => n.PushBlocksRequest.Contains(array[i]))) { pushBlocksRequestList.Add(array[i]); count--; } } } } } _random.Shuffle(pushBlocksLinkList); _random.Shuffle(pushBlocksRequestList); { var pushBlocksLinkDictionary = new Dictionary<Node, HashSet<Key>>(); foreach (var key in pushBlocksLinkList) { try { var requestNodes = new List<Node>(); foreach (var node in Kademlia<Node>.Search(key.Hash, baseNode.Id, otherNodes, 1)) { requestNodes.Add(node); } for (int i = 0; i < requestNodes.Count; i++) { HashSet<Key> collection; if (!pushBlocksLinkDictionary.TryGetValue(requestNodes[i], out collection)) { collection = new HashSet<Key>(); pushBlocksLinkDictionary[requestNodes[i]] = collection; } if (collection.Count < _maxBlockLinkCount) { collection.Add(key); } } } catch (Exception e) { Log.Error(e); } } lock (_pushBlocksLinkDictionary.ThisLock) { _pushBlocksLinkDictionary.Clear(); foreach (var pair in pushBlocksLinkDictionary) { var node = pair.Key; var targets = pair.Value; _pushBlocksLinkDictionary.Add(node, new List<Key>(targets.Randomize())); } } } { var pushBlocksRequestDictionary = new Dictionary<Node, HashSet<Key>>(); foreach (var key in pushBlocksRequestList) { try { List<Node> requestNodes = new List<Node>(); foreach (var node in Kademlia<Node>.Search(key.Hash, baseNode.Id, otherNodes, 2)) { requestNodes.Add(node); } foreach (var pair in messageManagers) { var node = pair.Key; var messageManager = pair.Value; if (messageManager.PullBlocksLink.Contains(key)) { requestNodes.Add(node); } } for (int i = 0; i < requestNodes.Count; i++) { HashSet<Key> collection; if (!pushBlocksRequestDictionary.TryGetValue(requestNodes[i], out collection)) { collection = new HashSet<Key>(); pushBlocksRequestDictionary[requestNodes[i]] = collection; } if (collection.Count < _maxBlockRequestCount) { collection.Add(key); } } } catch (Exception e) { Log.Error(e); } } lock (_pushBlocksRequestDictionary.ThisLock) { _pushBlocksRequestDictionary.Clear(); foreach (var pair in pushBlocksRequestDictionary) { var node = pair.Key; var targets = pair.Value; _pushBlocksRequestDictionary.Add(node, new List<Key>(targets.Randomize())); } } } } // Metadataのアップロード if (connectionCount >= _uploadingConnectionCountLowerLimit && pushMetadataUploadStopwatch.Elapsed.TotalMinutes >= 3) { pushMetadataUploadStopwatch.Restart(); var baseNode = this.BaseNode; var otherNodes = new List<Node>(); lock (this.ThisLock) { otherNodes.AddRange(_connectionManagers.Select(n => n.Node)); } var messageManagers = new Dictionary<Node, MessageManager>(); foreach (var node in otherNodes) { messageManagers[node] = _messagesManager[node]; } // Broadcast foreach (var signature in _settings.MetadataManager.GetBroadcastSignatures()) { try { var requestNodes = new List<Node>(); foreach (var node in Kademlia<Node>.Search(Signature.GetHash(signature), baseNode.Id, otherNodes, 2)) { requestNodes.Add(node); } for (int i = 0; i < requestNodes.Count; i++) { messageManagers[requestNodes[i]].PullBroadcastSignaturesRequest.Add(signature); } } catch (Exception e) { Log.Error(e); } } // Unicast foreach (var signature in _settings.MetadataManager.GetUnicastSignatures()) { try { var requestNodes = new List<Node>(); foreach (var node in Kademlia<Node>.Search(Signature.GetHash(signature), baseNode.Id, otherNodes, 2)) { requestNodes.Add(node); } for (int i = 0; i < requestNodes.Count; i++) { messageManagers[requestNodes[i]].PullUnicastSignaturesRequest.Add(signature); } } catch (Exception e) { Log.Error(e); } } // Multicast { foreach (var tag in _settings.MetadataManager.GetMulticastWikis()) { try { var requestNodes = new List<Node>(); foreach (var node in Kademlia<Node>.Search(tag.Id, baseNode.Id, otherNodes, 2)) { requestNodes.Add(node); } for (int i = 0; i < requestNodes.Count; i++) { messageManagers[requestNodes[i]].PullMulticastWikisRequest.Add(tag); } } catch (Exception e) { Log.Error(e); } } foreach (var tag in _settings.MetadataManager.GetMulticastChats()) { try { var requestNodes = new List<Node>(); foreach (var node in Kademlia<Node>.Search(tag.Id, baseNode.Id, otherNodes, 2)) { requestNodes.Add(node); } for (int i = 0; i < requestNodes.Count; i++) { messageManagers[requestNodes[i]].PullMulticastChatsRequest.Add(tag); } } catch (Exception e) { Log.Error(e); } } } } // Metadataのダウンロード if (connectionCount >= _downloadingConnectionCountLowerLimit && pushMetadataDownloadStopwatch.Elapsed.TotalSeconds >= 60) { pushMetadataDownloadStopwatch.Restart(); var baseNode = this.BaseNode; var otherNodes = new List<Node>(); lock (this.ThisLock) { otherNodes.AddRange(_connectionManagers.Select(n => n.Node)); } var messageManagers = new Dictionary<Node, MessageManager>(); foreach (var node in otherNodes) { messageManagers[node] = _messagesManager[node]; } var pushBroadcastSignaturesRequestList = new List<string>(); var pushUnicastSignaturesRequestList = new List<string>(); var pushMulticastWikisRequestList = new List<Wiki>(); var pushMulticastChatsRequestList = new List<Chat>(); // Broadcast { { var array = _pushBroadcastSignaturesRequestList.ToArray(); _random.Shuffle(array); int count = _maxMetadataRequestCount; for (int i = 0; count > 0 && i < array.Length; i++) { if (!messageManagers.Values.Any(n => n.PushBroadcastSignaturesRequest.Contains(array[i]))) { pushBroadcastSignaturesRequestList.Add(array[i]); count--; } } } foreach (var pair in messageManagers) { var node = pair.Key; var messageManager = pair.Value; { var array = messageManager.PullBroadcastSignaturesRequest.ToArray(); _random.Shuffle(array); int count = _maxMetadataRequestCount; for (int i = 0; count > 0 && i < array.Length; i++) { if (!messageManagers.Values.Any(n => n.PushBroadcastSignaturesRequest.Contains(array[i]))) { pushBroadcastSignaturesRequestList.Add(array[i]); count--; } } } } } // Unicast { { var array = _pushUnicastSignaturesRequestList.ToArray(); _random.Shuffle(array); int count = _maxMetadataRequestCount; for (int i = 0; count > 0 && i < array.Length; i++) { if (!messageManagers.Values.Any(n => n.PushUnicastSignaturesRequest.Contains(array[i]))) { pushUnicastSignaturesRequestList.Add(array[i]); count--; } } } foreach (var pair in messageManagers) { var node = pair.Key; var messageManager = pair.Value; { var array = messageManager.PullUnicastSignaturesRequest.ToArray(); _random.Shuffle(array); int count = _maxMetadataRequestCount; for (int i = 0; count > 0 && i < array.Length; i++) { if (!messageManagers.Values.Any(n => n.PushUnicastSignaturesRequest.Contains(array[i]))) { pushUnicastSignaturesRequestList.Add(array[i]); count--; } } } } } // Multicast { { { var array = _pushMulticastWikisRequestList.ToArray(); _random.Shuffle(array); int count = _maxMetadataRequestCount; for (int i = 0; count > 0 && i < array.Length; i++) { if (!messageManagers.Values.Any(n => n.PushMulticastWikisRequest.Contains(array[i]))) { pushMulticastWikisRequestList.Add(array[i]); count--; } } } { var array = _pushMulticastChatsRequestList.ToArray(); _random.Shuffle(array); int count = _maxMetadataRequestCount; for (int i = 0; count > 0 && i < array.Length; i++) { if (!messageManagers.Values.Any(n => n.PushMulticastChatsRequest.Contains(array[i]))) { pushMulticastChatsRequestList.Add(array[i]); count--; } } } } foreach (var pair in messageManagers) { var node = pair.Key; var messageManager = pair.Value; { var array = messageManager.PullMulticastWikisRequest.ToArray(); _random.Shuffle(array); int count = _maxMetadataRequestCount; for (int i = 0; count > 0 && i < array.Length; i++) { if (!messageManagers.Values.Any(n => n.PushMulticastWikisRequest.Contains(array[i]))) { pushMulticastWikisRequestList.Add(array[i]); count--; } } } { var array = messageManager.PullMulticastChatsRequest.ToArray(); _random.Shuffle(array); int count = _maxMetadataRequestCount; for (int i = 0; count > 0 && i < array.Length; i++) { if (!messageManagers.Values.Any(n => n.PushMulticastChatsRequest.Contains(array[i]))) { pushMulticastChatsRequestList.Add(array[i]); count--; } } } } } _random.Shuffle(pushBroadcastSignaturesRequestList); _random.Shuffle(pushUnicastSignaturesRequestList); _random.Shuffle(pushMulticastWikisRequestList); _random.Shuffle(pushMulticastChatsRequestList); // Broadcast { var pushBroadcastSignaturesRequestDictionary = new Dictionary<Node, HashSet<string>>(); foreach (var signature in pushBroadcastSignaturesRequestList) { try { var requestNodes = new List<Node>(); foreach (var node in Kademlia<Node>.Search(Signature.GetHash(signature), baseNode.Id, otherNodes, 2)) { requestNodes.Add(node); } for (int i = 0; i < requestNodes.Count; i++) { HashSet<string> collection; if (!pushBroadcastSignaturesRequestDictionary.TryGetValue(requestNodes[i], out collection)) { collection = new HashSet<string>(); pushBroadcastSignaturesRequestDictionary[requestNodes[i]] = collection; } if (collection.Count < _maxMetadataRequestCount) { collection.Add(signature); } } } catch (Exception e) { Log.Error(e); } } lock (_pushBroadcastSignaturesRequestDictionary.ThisLock) { _pushBroadcastSignaturesRequestDictionary.Clear(); foreach (var pair in pushBroadcastSignaturesRequestDictionary) { var node = pair.Key; var targets = pair.Value; _pushBroadcastSignaturesRequestDictionary.Add(node, new List<string>(targets.Randomize())); } } } // Unicast { var pushUnicastSignaturesRequestDictionary = new Dictionary<Node, HashSet<string>>(); foreach (var signature in pushUnicastSignaturesRequestList) { try { var requestNodes = new List<Node>(); foreach (var node in Kademlia<Node>.Search(Signature.GetHash(signature), baseNode.Id, otherNodes, 2)) { requestNodes.Add(node); } for (int i = 0; i < requestNodes.Count; i++) { HashSet<string> collection; if (!pushUnicastSignaturesRequestDictionary.TryGetValue(requestNodes[i], out collection)) { collection = new HashSet<string>(); pushUnicastSignaturesRequestDictionary[requestNodes[i]] = collection; } if (collection.Count < _maxMetadataRequestCount) { collection.Add(signature); } } } catch (Exception e) { Log.Error(e); } } lock (_pushUnicastSignaturesRequestDictionary.ThisLock) { _pushUnicastSignaturesRequestDictionary.Clear(); foreach (var pair in pushUnicastSignaturesRequestDictionary) { var node = pair.Key; var targets = pair.Value; _pushUnicastSignaturesRequestDictionary.Add(node, new List<string>(targets.Randomize())); } } } // Multicast { var pushMulticastWikisRequestDictionary = new Dictionary<Node, HashSet<Wiki>>(); var pushMulticastChatsRequestDictionary = new Dictionary<Node, HashSet<Chat>>(); foreach (var tag in pushMulticastWikisRequestList) { try { var requestNodes = new List<Node>(); foreach (var node in Kademlia<Node>.Search(tag.Id, baseNode.Id, otherNodes, 2)) { requestNodes.Add(node); } for (int i = 0; i < requestNodes.Count; i++) { HashSet<Wiki> collection; if (!pushMulticastWikisRequestDictionary.TryGetValue(requestNodes[i], out collection)) { collection = new HashSet<Wiki>(); pushMulticastWikisRequestDictionary[requestNodes[i]] = collection; } if (collection.Count < _maxMetadataRequestCount) { collection.Add(tag); } } } catch (Exception e) { Log.Error(e); } } foreach (var tag in pushMulticastChatsRequestList) { try { var requestNodes = new List<Node>(); foreach (var node in Kademlia<Node>.Search(tag.Id, baseNode.Id, otherNodes, 2)) { requestNodes.Add(node); } for (int i = 0; i < requestNodes.Count; i++) { HashSet<Chat> collection; if (!pushMulticastChatsRequestDictionary.TryGetValue(requestNodes[i], out collection)) { collection = new HashSet<Chat>(); pushMulticastChatsRequestDictionary[requestNodes[i]] = collection; } if (collection.Count < _maxMetadataRequestCount) { collection.Add(tag); } } } catch (Exception e) { Log.Error(e); } } lock (_pushMulticastWikisRequestDictionary.ThisLock) { _pushMulticastWikisRequestDictionary.Clear(); foreach (var pair in pushMulticastWikisRequestDictionary) { var node = pair.Key; var targets = pair.Value; _pushMulticastWikisRequestDictionary.Add(node, new List<Wiki>(targets.Randomize())); } } lock (_pushMulticastChatsRequestDictionary.ThisLock) { _pushMulticastChatsRequestDictionary.Clear(); foreach (var pair in pushMulticastChatsRequestDictionary) { var node = pair.Key; var targets = pair.Value; _pushMulticastChatsRequestDictionary.Add(node, new List<Chat>(targets.Randomize())); } } } } } }
public void UpdateFiles() { List<FileItem> files = new List<FileItem>(); List<FileItem> filesDownload = new List<FileItem>(); FileInfo fileinfo = new FileInfo(_updatePath); foreach (FileCollection col in _downloadcollections) { files.AddRange(col.Files); } AddToLog(files.Count + " files marked for check."); _progressVerify.Maximum = files.Count; _progressVerify.Value = 0; _progressTotalDownload.Value = 0; _progressFileDownload.Value = 0; if (Library.SystemSettings.isDebuggingEnabled) { this.AddToLog("Starting file check", false); } foreach (FileItem f in files) { //build the stringname string FullPath = fileinfo.DirectoryName + f.Directory + f.Filename; if (File.Exists(FullPath)) { //initiate a CRC object CRC32 crc = new CRC32(); //check debug settings if (Library.SystemSettings.isDebuggingEnabled) { this.AddToLog(" File: " + FullPath); } else { this.AddToLog(f.Directory + f.Filename); } //the file crc string fileCRC = ""; //open a link to the file using (Stream reader = new FileStream(FullPath, FileMode.Open, FileAccess.Read)) { //go though each byte foreach (byte b in crc.ComputeHash(reader)) { //build the crc string fileCRC += b.ToString("x2").ToLower(); } } //check debug settings if (Library.SystemSettings.isDebuggingEnabled) { this.AddToLog("System CRC: " + fileCRC); this.AddToLog(" XML CRC: " + f.FileCRC); } //check if they are matching if (fileCRC != f.FileCRC) { filesDownload.Add(f); if (Library.SystemSettings.isDebuggingEnabled) { this.AddToLog(" Status: Marked for download"); this.AddToLog("", false); } } else { if (Library.SystemSettings.isDebuggingEnabled) { this.AddToLog(" Status: No action required"); this.AddToLog("", false); } } } else { filesDownload.Add(f); if (Library.SystemSettings.isDebuggingEnabled) { this.AddToLog(" File: " + FullPath); this.AddToLog(" Status: Marked for download"); this.AddToLog("", false); } else { this.AddToLog(f.Directory + f.Filename); } } _progressVerify.Value += 1; } _progressTotalDownload.Maximum = filesDownload.Count; _progressTotalDownload.Value = 0; if (Library.SystemSettings.isDebuggingEnabled) { this.AddToLog("", false); this.AddToLog("Starting file download."); } this.AddToLog(filesDownload.Count + " files marked for download."); foreach (FileItem f in filesDownload) { //Build the pathstring string FullDirPath = fileinfo.DirectoryName + f.Directory; string FullFilePath = FullDirPath + f.Filename; using (WebClient webClient = new WebClient()) { //initiate a CRC object CRC32 crc = new CRC32(); webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(webClient_DownloadProgressChanged); try { string url = (webRepository + f.Directory + f.Filename).Replace('\\', '/'); if (!Directory.Exists(FullDirPath)) { Directory.CreateDirectory(FullDirPath); } this.AddToLog("Downloading " + f.Directory + f.Filename + ".7z"); webClient.DownloadFileAsync(new Uri(url), FullFilePath+".7z"); if (Library.SystemSettings.isDebuggingEnabled) { this.AddToLog(" Waiting for download to finish"); } while (webClient.IsBusy) { } if (Library.SystemSettings.isDebuggingEnabled) { this.AddToLog(" Download finished"); } //start deflateing the file SevenZipExtractor.SetLibraryPath("7z.dll"); SevenZipExtractor zip = new SevenZipExtractor(FullFilePath + ".7z"); if (File.Exists(FullFilePath + ".7z")) { //make sure the CRC is new CRC32 crc2 = new CRC32(); //the file crc string fileCRC = ""; //log this.AddToLog("Checking local archive CRC..."); //open a link to the file using (Stream reader = new FileStream(FullFilePath + ".7z", FileMode.Open, FileAccess.Read)) { //go though each byte foreach (byte b in crc2.ComputeHash(reader)) { //build the crc string fileCRC += b.ToString("x2").ToLower(); } } if (f.ArchiveCRC == fileCRC) { try { if (Library.SystemSettings.isDebuggingEnabled) { this.AddToLog("Extracting :" + FullFilePath + ".7z"); } zip.ExtractArchive(FullDirPath); if (File.Exists(FullFilePath)) { //make sure the CRC is new CRC32 crc3 = new CRC32(); //the file crc fileCRC = ""; this.AddToLog("Checking local file CRC..."); //open a link to the file using (Stream reader = new FileStream(FullFilePath, FileMode.Open, FileAccess.Read)) { //go though each byte foreach (byte b in crc3.ComputeHash(reader)) { //build the crc string fileCRC += b.ToString("x2").ToLower(); } } //check if they are matching if (fileCRC != f.FileCRC) { this.AddToLog("[Error] File CRC did't match expected crc."); File.Delete(FullFilePath); //check debug settings if (Library.SystemSettings.isDebuggingEnabled) { this.AddToLog("System CRC: " + fileCRC); this.AddToLog(" XML CRC: " + f.FileCRC); } } } else { this.AddToLog("[Error] Unable to locate extracted file."); this.AddToLog("[Error] Local : " + FullFilePath); this.AddToLog("[Error] Remote: " + url); } } catch (Exception ex) { MessageBox.Show(ex.Message); } } else { this.AddToLog("[Error] CRC on local archive dosen't match."); this.AddToLog("[Error] System CRC: " + fileCRC); this.AddToLog("[Error] XML CRC: " + f.FileCRC); } //clean up after ourselves. File.Delete(FullFilePath + ".7z"); } } catch (WebException ex) { this.AddToLog("Error: " + ex.Message); } } _progressTotalDownload.Value += 1; } this.AddToLog(""); this.AddToLog("System update finished.."); if (this.LoggingArea.Text.Contains("error")) { this.AddToLog("The log contains errors, please check the error log."); this.AddToLog("If the system have made an CRC error, please try"); this.AddToLog("updateing the system again. If the error persist then"); this.AddToLog("please notify me though mail ([email protected])"); this.AddToLog(" or PM on the forum (msjohansen / Mark Johansen)"); } this.AddToLog(""); this.AddToLog("Did you have problems? try hitting F8 and try again."); }
private void _路线属性_VisibilityChange(bool isvisible) { ListBoxEx innerControl = this._路线属性.InnerControl as ListBoxEx; if (isvisible) { innerControl.ClearSelected(); if (this.dgvSubSpeedParam.CurrentCell.Tag == null) { List<string> strs = new List<string>(); strs.AddRange(this.dgvSubSpeedParam.CurrentCell.Value.ToString().Split(",".ToCharArray())); int count = innerControl.Items.Count; for (int i = 0; i < count; i++) { if (strs.Contains((innerControl.Items[i] as ListBoxItem).Name)) { innerControl.SetSelected(i, true); } } return; } if (this.dgvSubSpeedParam.CurrentCell.Tag != null) { ArrayList tag = this.dgvSubSpeedParam.CurrentCell.Tag as ArrayList; if (!(tag[0] as char[])[0].ToString().Equals("1")) { innerControl.SetSelected(4, false); } else { innerControl.SetSelected(4, true); } if (!(tag[0] as char[])[1].ToString().Equals("1")) { innerControl.SetSelected(3, false); } else { innerControl.SetSelected(3, true); } if (!(tag[0] as char[])[2].ToString().Equals("1")) { innerControl.SetSelected(2, false); } else { innerControl.SetSelected(2, true); } if (!(tag[0] as char[])[3].ToString().Equals("1")) { innerControl.SetSelected(1, false); } else { innerControl.SetSelected(1, true); } if ((tag[0] as char[])[5].ToString().Equals("1")) { innerControl.SetSelected(0, true); return; } innerControl.SetSelected(0, false); } } else { string str = ""; List<string> strs1 = new List<string>(); ListBox.SelectedObjectCollection selectedItems = innerControl.SelectedItems; int num = innerControl.Items.Count; ArrayList arrayLists = new ArrayList(num); int num1 = 0; for (int j = 0; j < num; j++) { if (selectedItems.Contains(innerControl.Items[j])) { ListBoxItem item = innerControl.Items[j] as ListBoxItem; num1 = num1 | Convert.ToInt32(item.Tag.ToString()); str = string.Concat(str, item.Name.ToString(), ","); } } this.setTimeSpeedReadOnly(this.dgvSubSpeedParam.CurrentRow, num1); arrayLists.Add(Convert.ToString(num1, 2).PadLeft(6, '0').ToCharArray()); if (this.dgvSubSpeedParam.CurrentCell != null) { try { this.dgvSubSpeedParam.CurrentCell.Value = str.Trim(",".ToCharArray()); this.dgvSubSpeedParam.CurrentCell.Tag = arrayLists; } catch (Exception exception) { } } } }
// Data Received Delegate Trigger void comPort_DataReceived(object sender, SerialDataReceivedEventArgs e) { try { //Thread.Sleep(2000); //byte[] ReadSerialData = new byte[comPort.BytesToRead]; //string TotalSerialData = ""; //string stringData = ""; List<byte> ListByte = new List<byte>(); byte[] ReadSerialData; do { int numOfBytes = comPort.BytesToRead; ReadSerialData = new byte[numOfBytes]; comPort.Read(ReadSerialData, 0, numOfBytes); ListByte.AddRange(ReadSerialData); //stringData = Encoding.UTF8.GetString(ReadSerialData, 0, numOfBytes); //TotalSerialData = TotalSerialData + stringData; PauseForMilliSeconds(40); } while (comPort.BytesToRead > 0); //do //{ // Byte ReadSerialData1; // ReadSerialData1 = (byte)comPort.ReadByte(); // ListByte.Add(ReadSerialData1); //} while (comPort.BytesToRead > 0); if (ListByte[ListByte.Count - 2] == 0x0d) { if (ListByte[ListByte.Count - 1] == 0x0a) { Console.WriteLine("True"); WriteEOT(); } } ReadSerialData = new byte[ListByte.Count]; ReadSerialData = ListByte.ToArray(); //do //{ //int numOfBytes = comPort.BytesToRead; //ReadSerialData = new byte[numOfBytes]; //stringData = comPort.ReadTo("\r\n"); ////stringData = Encoding.UTF8.GetString(ReadSerialData, 0, numOfBytes); //TotalSerialData = TotalSerialData + stringData; //PauseForMilliSeconds(200); //} while (comPort.BytesToRead > 0); //byte[] ReadSerialData = new byte[comPort.BytesToRead]; //comPort.Read(ReadSerialData, 0, ReadSerialData.Length); if (SerialDataReceived != null) { SerialDataReceived((ReadSerialData)); } } catch //(Exception ex) { throw; } }
private void _路线属性_VisibilityChange(bool isvisible) { ListBoxEx innerControl = this._路线属性.InnerControl as ListBoxEx; if (!isvisible) { string str = ""; new List<string>(); ListBox.SelectedObjectCollection selectedItems = innerControl.SelectedItems; int count = innerControl.Items.Count; ArrayList list = new ArrayList(count); for (int i = 0; i < count; i++) { string str2 = ""; if (selectedItems.Contains(innerControl.Items[i])) { str2 = "1"; Client.ListBoxItem item = innerControl.Items[i] as Client.ListBoxItem; str = str + item.Name.ToString() + ","; } else { str2 = "0"; } list.Add(str2); } if (this.dgvPath.CurrentCell != null) { try { this.dgvPath.CurrentCell.Value = str.Trim(",".ToCharArray()); this.dgvPath.CurrentCell.Tag = list; } catch (Exception) { } } } else { innerControl.ClearSelected(); if (this.dgvPath.CurrentCell.Tag == null) { if (this.dgvPath.CurrentCell.Value != null) { List<string> list2 = new List<string>(); list2.AddRange(this.dgvPath.CurrentCell.Value.ToString().Split(",".ToCharArray())); int num3 = innerControl.Items.Count; for (int j = 0; j < num3; j++) { Client.ListBoxItem item2 = innerControl.Items[j] as Client.ListBoxItem; if (list2.Contains(item2.Name)) { innerControl.SetSelected(j, true); } } } } else if (this.dgvPath.CurrentCell.Tag != null) { ArrayList tag = this.dgvPath.CurrentCell.Tag as ArrayList; for (int k = 0; k < innerControl.Items.Count; k++) { innerControl.SetSelected(k, tag[k].ToString().Equals("1")); } } } }