public void ConvertAll(string captureDirPath, int numEvents, IProgressFeedback progress) { List<BinaryReader> readers = new List<BinaryReader>(1); SortedList<uint, KeyValuePair<BinaryReader, uint>> ids = new SortedList<uint, KeyValuePair<BinaryReader, uint>>(numEvents); uint i = 0; foreach (string filePath in Directory.GetFiles(captureDirPath, "*.log", SearchOption.TopDirectoryOnly)) { FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read); BinaryReader r = new BinaryReader(fs); readers.Add(r); while (fs.Position < fs.Length) { i++; int pct = (int)(((float)i / (float)numEvents) * 100.0f); progress.ProgressUpdate("Indexing", pct); uint id = r.ReadUInt32(); uint size = r.ReadUInt32(); ids.Add(id, new KeyValuePair<BinaryReader, uint>(r, (uint)fs.Position)); fs.Seek(size, SeekOrigin.Current); } } string resultPath = String.Format("{0}\\capture.osd", captureDirPath); BZip2OutputStream outStream = new BZip2OutputStream(new FileStream(resultPath, FileMode.Create)); XmlTextWriter xtw = new XmlTextWriter(outStream, System.Text.Encoding.UTF8); xtw.Formatting = Formatting.Indented; xtw.Indentation = 4; xtw.IndentChar = ' '; xtw.WriteStartDocument(true); xtw.WriteStartElement("events"); i = 0; foreach (KeyValuePair<BinaryReader, uint> pair in ids.Values) { i++; int pct = (int)(((float)i / (float)numEvents) * 100.0f); progress.ProgressUpdate(String.Format("Converting event {0} of {1}", i, numEvents), pct); BinaryReader r = pair.Key; uint offset = pair.Value; r.BaseStream.Seek(offset, SeekOrigin.Begin); UnserializeNode(r, xtw); } xtw.WriteEndElement(); xtw.WriteEndDocument(); xtw.Close(); foreach (BinaryReader r in readers) r.Close(); }
public void StopCapture(IProgressFeedback progress) { this.progress = progress; Thread th = new Thread(StopCaptureThread); th.Start(); }
public void StartCapture(Process[] processes, IProgressFeedback progress) { this.processes = processes; this.progress = progress; Thread th = new Thread(StartCaptureThread); th.Start(); }
public void LoadCK3Scripts(ScriptLibrary lib, IProgressFeedback progressFeedback = null, bool save = true, bool load = true) { LoadingCK3Library = lib; // events... var startDir = lib.Path; //"D:/SteamLibrary/steamapps/common/Crusader Kings III/"; LoadingCK3Library.LoadLocalizations(startDir + "localization/english"); if (progressFeedback != null) { progressFeedback.StartNewJob("Loading " + lib.Name + " CK3 Scripts", (int)ScriptContext.Max); } for (var x = 0; x < (int)ScriptContext.Max; x++) { if (LoadingCK3Library.ContextData.ContainsKey((ScriptContext)x)) { if (!string.IsNullOrEmpty(LoadingCK3Library.ContextData[(ScriptContext)x].Directory)) { var info = LoadingCK3Library.ContextData[(ScriptContext)x]; if (info.Directory.EndsWith(".txt")) { var r = FileTokenizer.Instance.LoadFile( new RefFilename(info.Directory, lib == BaseCK3Library), (ScriptContext)x, save); LoadingCK3Library.Add(r, (ScriptContext)x); } else { var r = FileTokenizer.Instance.LoadDirectory( new RefFilename(info.Directory + "/", lib == BaseCK3Library), (ScriptContext)x, save, load); LoadingCK3Library.Add(r, (ScriptContext)x); } } } progressFeedback?.AddProgress(1); } progressFeedback?.StartNewJob("Initializing " + lib.Name + " CK3 Scripts", (int)Instance.DeferedInitializationList.Count); for (var i = 0; i < Instance.DeferedInitializationList.Count; i++) { var scriptObject = Instance.DeferedInitializationList[i]; scriptObject.Initialize(); progressFeedback?.AddProgress(1); } Instance.DeferedInitializationList.Clear(); LoadingCK3Library.RecalculateGroups(); }
public void StartCapture(Process[] processes, Softwall.Rule[] softwallRules, Device[] devices, IProgressFeedback progress) { this.processes = processes; this.softwallRules = softwallRules; this.devices = devices; this.progress = progress; Thread th = new Thread(StartCaptureThread); th.Start(); }
private void DoStopCapture() { progress.ProgressUpdate("Stopping capture", 100); UnprepareCapture(true); stopRequest.Reset(); progress.OperationComplete(); progress = null; stopWorkerThread = null; }
public void Load(string path, IProgressFeedback progress) { BZip2InputStream inStream = new BZip2InputStream(new FileStream(path, FileMode.Open)); XmlTextReader xtr = new XmlTextReader(inStream); tmpPath = Path.GetTempFileName(); FileStream tmpFileStream = new FileStream(tmpPath, FileMode.Create, FileAccess.ReadWrite); tmpReader = new StreamReader(tmpFileStream); StreamWriter tmpFileWriter = new StreamWriter(tmpFileStream, Encoding.UTF8); events = new SortedDictionary <uint, DumpEvent>(); int prevPct = -1, pct; while (xtr.Read()) { pct = (int)(((float)inStream.Position / (float)inStream.Length) * 100.0f); if (pct != prevPct) { prevPct = pct; progress.ProgressUpdate("Loading", pct); } if (xtr.NodeType == XmlNodeType.Element && xtr.Name == "event") { tmpFileWriter.Flush(); long startOffset = tmpFileStream.Position; XmlReader rdr = xtr.ReadSubtree(); XmlDocument doc = new XmlDocument(); doc.Load(rdr); XmlAttributeCollection attrs = doc.DocumentElement.Attributes; uint id = Convert.ToUInt32(attrs["id"].Value); DumpEventType type = (DumpEventType)Enum.Parse(typeof(DumpEventType), attrs["type"].Value); DateTime timestamp = DateTime.FromFileTimeUtc(Convert.ToInt64(attrs["timestamp"].Value)); string processName = attrs["processName"].Value; uint processId = Convert.ToUInt32(attrs["processId"].Value); uint threadId = Convert.ToUInt32(attrs["threadId"].Value); string eventStr = doc.DocumentElement.InnerXml; tmpFileWriter.Write(eventStr); events[id] = new DumpEvent(this, id, type, timestamp, processName, processId, threadId, startOffset, eventStr.Length); } } xtr.Close(); tmpFileStream.Seek(0, SeekOrigin.Begin); }
public void StartCapture(Details details, IProgressFeedback progress) { if (startWorkerThread != null || stopWorkerThread != null) { throw new InvalidOperationException(); } this.details = details; this.progress = progress; stopRequest.Reset(); startWorkerThread = new Thread(DoStartCapture); startWorkerThread.Start(); }
public void LoadMod(string mod, IProgressFeedback progressFeedback) { ModCK3Library = new ScriptLibrary(); ModCK3Library.Parent = BaseCK3Library; ModCK3Library.Name = mod; LoadingCK3Library = ModCK3Library; LoadCK3Scripts(ModCK3Library, progressFeedback, false, false); PostInitialize(progressFeedback); RePostProcessUntilComplete(); ScriptObject.ClearCachedScriptedEffects(); }
public void CreateOrLoadMod(string mod, IProgressFeedback progressFeedback) { if (Directory.Exists(Globals.CK3ModPath + mod + "/")) { LoadMod(mod, progressFeedback); return; } Directory.CreateDirectory(Globals.CK3ModPath + mod + "/"); ModCK3Library = new ScriptLibrary(); ModCK3Library.Parent = BaseCK3Library; ModCK3Library.Name = mod; PostInitialize(progressFeedback); ScriptObject.ClearCachedScriptedEffects(); }
private void ProcessBaseFileBehaviour(IProgressFeedback progressFeedback) { var binFilename = "behaviourData.bin"; binFilename = Globals.CK3EdDataPath.Replace("\\", "/") + binFilename; BinaryReader reader = null; BinaryWriter writer = null; if (File.Exists(binFilename)) { reader = new BinaryReader(File.Open(binFilename, FileMode.Open)); } else { writer = new BinaryWriter(File.Open(binFilename, FileMode.Create)); } if (reader != null) { var v = reader.ReadInt32(); if (v != Globals.DataVersion) { reader.Close(); reader = null; writer = new BinaryWriter(File.Open(binFilename, FileMode.Create)); } } if (writer != null) { writer.Write(Globals.DataVersion); } PostInitialize(progressFeedback, writer, reader); if (writer != null) { writer.Flush(); writer.Close(); } if (reader != null) { reader.Close(); } }
private void DoStartCapture() { try { PrepareCapture(); int[] processIds; if (details is CreateDetails) { CreateDetails createDetails = details as CreateDetails; int processId = DoCreation(createDetails); processIds = new int[1] { processId }; } else if (details is AttachDetails) { AttachDetails attachDetails = details as AttachDetails; DoInjection(attachDetails); processIds = attachDetails.ProcessIds; } else { throw new NotImplementedException(); } if (WaitForAllClientsToPingUs(processIds)) { progress.OperationComplete(); } else { progress.OperationFailed("Capture aborted."); } } catch (Exception e) { progress.OperationFailed(e.Message); UnprepareCapture(false); } progress = null; startWorkerThread = null; }
public void PostInitialize(IProgressFeedback progressFeedback, BinaryWriter writer = null, BinaryReader reader = null) { do { Instance.DeferedPostInitializationList = Instance.DeferedPostInitializationListNext; Instance.DeferedPostInitializationListNext = new List <ScriptObject>(); progressFeedback?.StartNewJob("Post-Processing " + LoadingCK3Library.Name + " CK3 Scripts", (int)Instance.DeferedPostInitializationList.Count); for (var i = 0; i < Instance.DeferedPostInitializationList.Count; i++) { var scriptObject = Instance.DeferedPostInitializationList[i]; scriptObject.PostInitialize(writer, reader); progressFeedback?.AddProgress(1); } Instance.DeferedPostInitializationList.Clear(); } while (Instance.DeferedPostInitializationListNext.Count > 0); }
public void Init(IProgressFeedback progressFeedback) { Wipe(); SchemaManager.Instance.Init(); BaseCK3Library = new ScriptLibrary(); BaseCK3Library.Name = "Base"; ModCK3Library = new ScriptLibrary(); ModCK3Library.Parent = BaseCK3Library; LoadingCK3Library = BaseCK3Library; EnumManager.Instance.Load(); LoadCK3Scripts(BaseCK3Library, progressFeedback); ScriptObject.ClearCachedScriptedEffects(); ProcessBaseFileBehaviour(progressFeedback); SchemaManager.Instance.SaveBinary(); }
public void StopCapture(IProgressFeedback progress) { if (stopWorkerThread != null) { throw new InvalidOperationException(); } stopRequest.Set(); // Unlikely: while (startWorkerThread != null) { Thread.Sleep(20); } this.progress = progress; stopWorkerThread = new Thread(DoStopCapture); stopWorkerThread.Start(); }
public void ConvertAll(string captureDirPath, int numEvents, IProgressFeedback progress) { List <BinaryReader> readers = new List <BinaryReader>(1); SortedList <uint, KeyValuePair <BinaryReader, uint> > ids = new SortedList <uint, KeyValuePair <BinaryReader, uint> >(numEvents); uint i = 0; foreach (string filePath in Directory.GetFiles(captureDirPath, "*.log", SearchOption.TopDirectoryOnly)) { FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read); BinaryReader r = new BinaryReader(fs); readers.Add(r); while (fs.Position < fs.Length) { i++; int pct = (int)(((float)i / (float)numEvents) * 100.0f); progress.ProgressUpdate("Indexing", pct); uint id = r.ReadUInt32(); uint size = r.ReadUInt32(); ids.Add(id, new KeyValuePair <BinaryReader, uint>(r, (uint)fs.Position)); fs.Seek(size, SeekOrigin.Current); } } string resultPath = String.Format("{0}\\capture.osd", captureDirPath); BZip2OutputStream outStream = new BZip2OutputStream(new FileStream(resultPath, FileMode.Create)); XmlTextWriter xtw = new XmlTextWriter(outStream, System.Text.Encoding.UTF8); xtw.Formatting = Formatting.Indented; xtw.Indentation = 4; xtw.IndentChar = ' '; xtw.WriteStartDocument(true); xtw.WriteStartElement("events"); i = 0; foreach (KeyValuePair <BinaryReader, uint> pair in ids.Values) { i++; int pct = (int)(((float)i / (float)numEvents) * 100.0f); progress.ProgressUpdate(String.Format("Converting event {0} of {1}", i, numEvents), pct); BinaryReader r = pair.Key; uint offset = pair.Value; r.BaseStream.Seek(offset, SeekOrigin.Begin); UnserializeNode(r, xtw); } xtw.WriteEndElement(); xtw.WriteEndDocument(); xtw.Close(); foreach (BinaryReader r in readers) { r.Close(); } }
private void AddEventsToDataSet(Capture.Event[] events, IProgressFeedback progress) { object source = dataGridView.DataSource; dataGridView.DataSource = null; dataSet.Tables[0].BeginLoadData(); DataTable tbl = dataSet.Tables["messages"]; int i = 0; foreach (Capture.Event ev in events) { i++; progress.ProgressUpdate("Loading events", (int) (((float) i / (float) events.Length) * 100.0f)); DataRow row = tbl.NewRow(); row.BeginEdit(); /* Common stuff */ row["Timestamp"] = ev.Timestamp; row["ProcessName"] = ev.ProcessName; row["ProcessId"] = ev.ProcessId; row["ThreadId"] = ev.ThreadId; row["FunctionName"] = ev.FunctionName; row["Backtrace"] = ev.Backtrace; UInt32 returnAddress = 0; string callerModName = ""; if (ev.Backtrace != null) { string[] tokens = ev.Backtrace.Split(new char[] { '\n' }, 2); if (tokens.Length >= 1) { string line = tokens[0]; string[] lineTokens = line.Split(new string[] { "::" }, 2, StringSplitOptions.None); if (lineTokens.Length == 2) { returnAddress = Convert.ToUInt32(lineTokens[1].Substring(2), 16); callerModName = lineTokens[0]; } } } row["ReturnAddress"] = returnAddress; row["CallerModuleName"] = callerModName; row["ResourceId"] = ev.ResourceId; if (ev is Capture.MessageEvent) { Capture.MessageEvent msgEvent = ev as Capture.MessageEvent; row["MsgType"] = MessageType.MESSAGE_TYPE_MESSAGE; row["MsgContext"] = msgEvent.Context; } else { Capture.PacketEvent pktEvent = ev as Capture.PacketEvent; row["MsgType"] = MessageType.MESSAGE_TYPE_PACKET; } row["Message"] = ev.Message; row["Direction"] = ev.Direction; if (ev.LocalEndpoint != null) { row["LocalAddress"] = ev.LocalEndpoint.Address.ToString(); row["LocalPort"] = ev.LocalEndpoint.Port; } if (ev.PeerEndpoint != null) { row["PeerAddress"] = ev.PeerEndpoint.Address.ToString(); row["PeerPort"] = ev.PeerEndpoint.Port; } row["Data"] = ev.Data; row.EndEdit(); tbl.Rows.Add(row); } dataSet.Tables[0].EndLoadData(); dataGridView.DataSource = source; }
private void DoStartCapture() { try { PrepareCapture(); int[] processIds; if (details is CreateDetails) { CreateDetails createDetails = details as CreateDetails; int processId = DoCreation(createDetails); processIds = new int[1] { processId }; } else if (details is AttachDetails) { AttachDetails attachDetails = details as AttachDetails; DoInjection(attachDetails); processIds = attachDetails.ProcessIds; } else { throw new NotImplementedException(); } if (WaitForAllClientsToPingUs(processIds)) progress.OperationComplete(); else progress.OperationFailed("Capture aborted."); } catch (Exception e) { progress.OperationFailed(e.Message); UnprepareCapture(false); } progress = null; startWorkerThread = null; }
public void StartCapture(Details details, IProgressFeedback progress) { if (startWorkerThread != null || stopWorkerThread != null) throw new InvalidOperationException(); this.details = details; this.progress = progress; stopRequest.Reset(); startWorkerThread = new Thread(DoStartCapture); startWorkerThread.Start(); }
public static IPSession[] ExtractAllFrom(IPPacket[] packets, TCPEvent[] events, IProgressFeedback progress) { // // Find sessions // progress.ProgressUpdate("Identifying sessions", 0); Dictionary <UInt32, IPSession> sessionById = new Dictionary <UInt32, IPSession>(); List <UInt32> sessionIds = new List <UInt32>(); int i = 0; foreach (IPPacket p in packets) { UInt32 id = p.ResourceId; IPSession session; if (sessionById.ContainsKey(id)) { session = sessionById[id]; } else { session = new IPSession(); sessionById[id] = session; sessionIds.Add(id); } session.AddPacket(p); i++; progress.ProgressUpdate("Identifying sessions", (int)((i / (float)packets.Length) * 100.0f)); } // // Add the events to the appropriate sessions // // First off, sort them by timestamp Array.Sort(events); // Then match them with the sessions foreach (TCPEvent ev in events) { if (sessionById.ContainsKey(ev.ResourceId)) { sessionById[ev.ResourceId].AddEvent(ev); } } // // Build an ordered list of sessions // List <IPSession> result = new List <IPSession>(); foreach (UInt32 id in sessionIds) { result.Add(sessionById[id]); } return(result.ToArray()); }
public void Load(string path, IProgressFeedback progress) { BZip2InputStream inStream = new BZip2InputStream(new FileStream(path, FileMode.Open)); XmlTextReader xtr = new XmlTextReader(inStream); tmpPath = Path.GetTempFileName(); FileStream tmpFileStream = new FileStream(tmpPath, FileMode.Create, FileAccess.ReadWrite); tmpReader = new StreamReader(tmpFileStream); StreamWriter tmpFileWriter = new StreamWriter(tmpFileStream, Encoding.UTF8); events = new SortedDictionary<uint, DumpEvent>(); int prevPct = -1, pct; while (xtr.Read()) { pct = (int)(((float)inStream.Position / (float)inStream.Length) * 100.0f); if (pct != prevPct) { prevPct = pct; progress.ProgressUpdate("Loading", pct); } if (xtr.NodeType == XmlNodeType.Element && xtr.Name == "event") { tmpFileWriter.Flush(); long startOffset = tmpFileStream.Position; XmlReader rdr = xtr.ReadSubtree(); XmlDocument doc = new XmlDocument(); doc.Load(rdr); XmlAttributeCollection attrs = doc.DocumentElement.Attributes; uint id = Convert.ToUInt32(attrs["id"].Value); DumpEventType type = (DumpEventType) Enum.Parse(typeof(DumpEventType), attrs["type"].Value); DateTime timestamp = DateTime.FromFileTimeUtc(Convert.ToInt64(attrs["timestamp"].Value)); string processName = attrs["processName"].Value; uint processId = Convert.ToUInt32(attrs["processId"].Value); uint threadId = Convert.ToUInt32(attrs["threadId"].Value); string eventStr = doc.DocumentElement.InnerXml; tmpFileWriter.Write(eventStr); events[id] = new DumpEvent(this, id, type, timestamp, processName, processId, threadId, startOffset, eventStr.Length); } } xtr.Close(); tmpFileStream.Seek(0, SeekOrigin.Begin); }
public void StopCapture(IProgressFeedback progress) { if (stopWorkerThread != null) throw new InvalidOperationException(); stopRequest.Set(); // Unlikely: while (startWorkerThread != null) Thread.Sleep(20); this.progress = progress; stopWorkerThread = new Thread(DoStopCapture); stopWorkerThread.Start(); }
/// <summary> /// Deletes the short segments from the provided features and stores the features. /// </summary> /// <param name="fromFeatures"></param> /// <param name="updatedGeometries"></param> /// <param name="use2DLengthOnly"></param> /// <param name="inPerimeter"></param> /// <param name="progressFeedback"></param> /// <param name="cancel"></param> /// <param name="notifications"></param> public static void DeleteShortSegments( ICollection <FeatureVertexInfo> fromFeatures, IDictionary <IFeature, IGeometry> updatedGeometries, bool use2DLengthOnly, [CanBeNull] IGeometry inPerimeter, [CanBeNull] IProgressFeedback progressFeedback, [CanBeNull] ITrackCancel cancel, [CanBeNull] NotificationCollection notifications) { if (progressFeedback != null) { progressFeedback.SetRange(0, fromFeatures.Count); } var featureCount = 0; var totalRemovedCount = 0; foreach (FeatureVertexInfo featureVertexInfo in fromFeatures) { if (cancel != null && !cancel.Continue()) { return; } if (featureVertexInfo.ShortSegments == null || featureVertexInfo.ShortSegments.Count == 0) { continue; } Assert.NotNull(featureVertexInfo.MinimumSegmentLength, "Minimum segment length not set."); var minSegmentLength = (double)featureVertexInfo.MinimumSegmentLength; try { IGeometry updateGeometry; if ( !updatedGeometries.TryGetValue(featureVertexInfo.Feature, out updateGeometry)) { updateGeometry = featureVertexInfo.Feature.ShapeCopy; } else { // the geometry was already updated - recalculate the short segments: featureVertexInfo.ShortSegments = GetShortSegments((IPolycurve)updateGeometry, inPerimeter, minSegmentLength, use2DLengthOnly); } var polycurveToUpdate = updateGeometry as IPolycurve; Assert.NotNull(polycurveToUpdate, "Feature's shape must be a polycurve"); int removeCount = DeleteShortSegments(polycurveToUpdate, featureVertexInfo, use2DLengthOnly, inPerimeter); if (removeCount > 0) { if (updatedGeometries.ContainsKey(featureVertexInfo.Feature)) { updatedGeometries[featureVertexInfo.Feature] = polycurveToUpdate; } else { updatedGeometries.Add(featureVertexInfo.Feature, polycurveToUpdate); } featureCount++; totalRemovedCount += removeCount; } } catch (Exception) { _msg.InfoFormat("Error enforcing short segment in {0}", GdbObjectUtils.ToString(featureVertexInfo.Feature)); throw; } if (progressFeedback != null) { progressFeedback.Advance( "Stored {0} of {1} features with enforced segment length", featureCount, fromFeatures.Count); } } string msgFormat = (featureCount == 1) ? "Removed {0} segment(s) from {1} geometry" : "Removed {0} segment(s) from {1} geometries"; _msg.InfoFormat(msgFormat, totalRemovedCount, featureCount); }
public static IPSession[] ExtractAllFrom(IPPacket[] packets, TCPEvent[] events, IProgressFeedback progress) { // // Find sessions // progress.ProgressUpdate("Identifying sessions", 0); Dictionary<UInt32, IPSession> sessionById = new Dictionary<UInt32, IPSession>(); List<UInt32> sessionIds = new List<UInt32>(); int i = 0; foreach (IPPacket p in packets) { UInt32 id = p.ResourceId; IPSession session; if (sessionById.ContainsKey(id)) { session = sessionById[id]; } else { session = new IPSession(); sessionById[id] = session; sessionIds.Add(id); } session.AddPacket(p); i++; progress.ProgressUpdate("Identifying sessions", (int) ((i / (float) packets.Length) * 100.0f)); } // // Add the events to the appropriate sessions // // First off, sort them by timestamp Array.Sort(events); // Then match them with the sessions foreach (TCPEvent ev in events) { if (sessionById.ContainsKey(ev.ResourceId)) sessionById[ev.ResourceId].AddEvent(ev); } // // Build an ordered list of sessions // List<IPSession> result = new List<IPSession>(); foreach (UInt32 id in sessionIds) result.Add(sessionById[id]); return result.ToArray(); }