/// <summary> /// Label which opens up a new form with a game. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void GameLabel_Click(object sender, EventArgs e) { var path1 = @"../../../player1.xml"; var path2 = @"../../../player2.xml"; if (File.Exists(path1) && File.Exists(path2)) { if (MessageBox.Show("Would you like to continue the previous game?", "Save", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { try { var xml = new XmlParser(); player1 = xml.Deserialize(path1); player2 = xml.Deserialize(path2); } catch (Exception) { MessageBox.Show("Your xml file was crashed!..."); return; } var gameForm = new GameForm(player1, player2); gameForm.ShowDialog(); } else { if (player1 != null && player2 != null) { var gameForm = new GameForm(player1, player2); gameForm.ShowDialog(); player1 = null; player2 = null; } else { MessageBox.Show("You haven't chosen your heroes yet!"); } } } else { if (player1 != null && player2 != null) { var gameForm = new GameForm(player1, player2); gameForm.ShowDialog(); player1 = null; player2 = null; } else { MessageBox.Show("You haven't chosen your heroes yet!"); } } }
public void GeneticAlgorithmPerformanceTest() { ex = null; GeneticAlgorithm ga = (GeneticAlgorithm)XmlParser.Deserialize(@"Test Resources\GA_TSP.hl"); ga.ExceptionOccurred += new EventHandler <EventArgs <Exception> >(ga_ExceptionOccurred); ga.SetSeedRandomly.Value = false; ga.Seed.Value = 0; ga.Prepare(); ga.Start(); if (ex != null) { throw ex; } TestContext.WriteLine("Runtime: {0}", ga.ExecutionTime.ToString()); double expectedBestQuality = 12332.0; double expectedAverageQuality = 13123.2; double expectedWorstQuality = 14538.0; double bestQuality = (ga.Results["CurrentBestQuality"].Value as DoubleValue).Value; double averageQuality = (ga.Results["CurrentAverageQuality"].Value as DoubleValue).Value; double worstQuality = (ga.Results["CurrentWorstQuality"].Value as DoubleValue).Value; TestContext.WriteLine(""); TestContext.WriteLine("CurrentBestQuality: {0} (should be {1})", bestQuality, expectedBestQuality); TestContext.WriteLine("CurrentAverageQuality: {0} (should be {1})", averageQuality, expectedAverageQuality); TestContext.WriteLine("CurrentWorstQuality: {0} (should be {1})", worstQuality, expectedWorstQuality); Assert.AreEqual(bestQuality, expectedBestQuality); Assert.AreEqual(averageQuality, expectedAverageQuality); Assert.AreEqual(worstQuality, expectedWorstQuality); }
public static T Deserialize <T>(byte[] sjob) { using (MemoryStream memStream = new MemoryStream(sjob)) { T job = XmlParser.Deserialize <T>(memStream); return(job); } }
private void openFileButton_Click(object sender, EventArgs e) { if (openFileDialog.ShowDialog(this) == DialogResult.OK) { CallAsync( () => { IContent algorithm = null; try { algorithm = XmlParser.Deserialize <IContent>(openFileDialog.FileName); } catch (Exception) { } if (algorithm != null) { Content.DataTypeName = algorithm.GetType().Name; Content.DataTypeTypeName = algorithm.GetType().AssemblyQualifiedName; data = null; } else { using (FileStream stream = new FileStream(openFileDialog.FileName, FileMode.Open, FileAccess.Read)) { data = new byte[stream.Length]; stream.Read(data, 0, data.Length); stream.Close(); } } dataViewHost.Content = algorithm; }, "Save algorithm data into file failed.", () => SetEnabledStateOfControls() ); } }
protected override IStorableContent LoadContent(string filename, out Info info) { bool useOldPersistence = XmlParser.CanOpen(filename); IStorableContent content = null; if (useOldPersistence) { var sw = new Stopwatch(); sw.Start(); content = XmlParser.Deserialize <IStorableContent>(filename); sw.Stop(); info = new Info(filename, sw.Elapsed); } else { var ser = new ProtoBufSerializer(); content = (IStorableContent)ser.Deserialize(filename, out SerializationInfo serInfo); info = new Info(filename, serInfo); } if (content == null) { throw new PersistenceException($"Cannot deserialize root element of {filename}"); } return(content); }
public rss GetNewsFromSource(int sourceId) { return(_memoryCache.GetOrCreate(sourceId, entry => { var source = _collectionRepository.GetSourceById(sourceId); if (source == null) { return null; } using (var client = new HttpClient()) { try { var resultString = client.GetStringAsync(source.Url).Result; entry.AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(60); return XmlParser.Deserialize <rss>(resultString); } catch (Exception) { return null; } } })); }
public void TestObjectGraphTraversal() { GeneticAlgorithm ga = (GeneticAlgorithm)XmlParser.Deserialize(@"Test Resources\GA_SymbReg.hl"); var objects = ga.GetObjectGraphObjects().ToList(); // Should be 3982, but count may change slightly as members are added or removed Assert.IsTrue(objects.Count > 1, "Number of objects in the object graph seems to small."); }
public void TestCloningFinishedExperiment() { Experiment experiment = (Experiment)XmlParser.Deserialize(@"Test Resources\SamplesExperimentFinished.hl"); Experiment clone = (Experiment)experiment.Clone(new Cloner()); var intersections = CheckTotalInequality(experiment, clone).Where(x => x.GetType().FullName.StartsWith("HeuristicLab")); Assert.IsTrue(ProcessEqualObjects(experiment, intersections)); }
protected T CloneByPersistence <T>(T value) { using (var serializerStream = new MemoryStream()) { XmlGenerator.Serialize(value, serializerStream); var bytes = serializerStream.GetBuffer(); using (var deserializerStream = new MemoryStream(bytes)) { return(XmlParser.Deserialize <T>(deserializerStream)); } } }
public void CollectGASample() { GeneticAlgorithm ga = (GeneticAlgorithm)XmlParser.Deserialize(@"Test Resources\GA_SymbReg.hl"); Stopwatch watch = new Stopwatch(); watch.Start(); for (int i = 0; i < 1; i++) { ga.GetObjectGraphObjects().Count(); } watch.Stop(); var objects = ga.GetObjectGraphObjects().ToList(); TestContext.WriteLine("Time elapsed {0}", watch.Elapsed); TestContext.WriteLine("Objects discovered: {0}", objects.Count()); TestContext.WriteLine("HL objects discovered: {0}", objects.Count(o => o.GetType().Namespace.StartsWith("HeuristicLab"))); TestContext.WriteLine(""); Dictionary <Type, List <object> > objs = new Dictionary <Type, List <object> >(); foreach (object o in objects) { if (!objs.ContainsKey(o.GetType())) { objs.Add(o.GetType(), new List <object>()); } objs[o.GetType()].Add(o); } foreach (string s in objects.Select(o => o.GetType().Namespace).Distinct().OrderBy(s => s)) { TestContext.WriteLine("{0}: {1}", s, objects.Count(o => o.GetType().Namespace == s)); } TestContext.WriteLine(""); TestContext.WriteLine("Analysis of contained objects per name"); foreach (var pair in objs.OrderBy(x => x.Key.ToString())) { TestContext.WriteLine("{0}: {1}", pair.Key, pair.Value.Count); } TestContext.WriteLine(""); TestContext.WriteLine("Analysis of contained objects"); foreach (var pair in from o in objs orderby o.Value.Count descending select o) { TestContext.WriteLine("{0}: {1}", pair.Key, pair.Value.Count); } TestContext.WriteLine(""); }
private IItem ConvertToItem(Value value) { if (value is BinaryValue) { IItem item = null; BinaryValue binaryValue = (BinaryValue)value; if (binaryValue.Value != null) { using (MemoryStream stream = new MemoryStream(binaryValue.Value)) { try { item = XmlParser.Deserialize <IItem>(stream); } catch (Exception) { } stream.Close(); } } return(item != null ? item : new Data.StringValue(value.DataType.Name)); } else if (value is BoolValue) { return(new Data.BoolValue(((BoolValue)value).Value)); } else if (value is FloatValue) { return(new Data.DoubleValue(((FloatValue)value).Value)); } else if (value is PercentValue) { return(new Data.PercentValue(((PercentValue)value).Value)); } else if (value is DoubleValue) { return(new Data.DoubleValue(((DoubleValue)value).Value)); } else if (value is IntValue) { return(new Data.IntValue((int)((IntValue)value).Value)); } else if (value is LongValue) { return(new Data.IntValue((int)((LongValue)value).Value)); } else if (value is StringValue) { return(new Data.StringValue(((StringValue)value).Value)); } else if (value is TimeSpanValue) { return(new Data.TimeSpanValue(TimeSpan.FromSeconds((long)((TimeSpanValue)value).Value))); } return(null); }
private void LoadItems(object state) { string[] items = Directory.GetFiles(ItemsPath); foreach (string filename in items) { try { T item = XmlParser.Deserialize <T>(filename); OnItemLoaded(item, progressBar.Maximum / items.Length); } catch (Exception) { } } OnAllItemsLoaded(); }
public void Load(long algorithmId) { if (this.algorithmId != algorithmId) { IAlgorithm algorithm; byte[] algorithmData = RunCreationClient.GetAlgorithmData(algorithmId); using (MemoryStream stream = new MemoryStream(algorithmData)) { algorithm = XmlParser.Deserialize <IAlgorithm>(stream); } this.algorithmId = algorithmId; Algorithm = algorithm; } }
public void Load(long problemId) { if (this.problemId != problemId) { IHeuristicOptimizationProblem problem; byte[] problemData = RunCreationClient.Instance.GetProblemData(problemId); using (MemoryStream stream = new MemoryStream(problemData)) { problem = XmlParser.Deserialize <IHeuristicOptimizationProblem>(stream); } if (ProblemType.IsAssignableFrom(problem.GetType())) { this.problemId = problemId; Problem = problem; } } }
protected virtual void loadProblemDataButton_Click(object sender, EventArgs e) { if (loadProblemDataFileDialog.ShowDialog(this) != DialogResult.OK) { return; } try { object hlFile = XmlParser.Deserialize(loadProblemDataFileDialog.FileName); IDataAnalysisProblemData problemData = null; if (hlFile is IDataAnalysisProblemData) { problemData = (IDataAnalysisProblemData)hlFile; } else if (hlFile is IDataAnalysisProblem) { problemData = ((IDataAnalysisProblem)hlFile).ProblemData; } else if (hlFile is IDataAnalysisSolution) { problemData = ((IDataAnalysisSolution)hlFile).ProblemData; } if (problemData == null) { throw new InvalidOperationException("The chosen HeuristicLab file does not contain a ProblemData, Problem, or DataAnalysisSolution."); } var solution = (IDataAnalysisSolution)Content.Clone(); problemData.AdjustProblemDataProperties(solution.ProblemData); solution.ProblemData = problemData; if (!solution.Name.EndsWith(" with loaded problemData")) { solution.Name += " with loaded problemData"; } MainFormManager.MainForm.ShowContent(solution); } catch (InvalidOperationException invalidOperationException) { ErrorHandling.ShowErrorDialog(this, invalidOperationException); } catch (ArgumentException argumentException) { ErrorHandling.ShowErrorDialog(this, argumentException); } }
private void LoadSample(string name, Assembly assembly, ListViewGroup group, int count) { string path = Path.GetTempFileName(); try { using (var stream = assembly.GetManifestResourceStream(name)) { WriteStreamToTempFile(stream, path); // create a file in a temporary folder (persistence cannot load these files directly from the stream) var item = XmlParser.Deserialize <INamedItem>(path); OnSampleLoaded(item, group, 1.0 / count); } } catch (Exception) { } finally { if (File.Exists(path)) { File.Delete(path); // make sure we remove the temporary file } } }
private void refreshDataButton_Click(object sender, EventArgs e) { CallAsync( () => { data = null; dataViewHost.Content = null; data = AdministrationClient.GetAlgorithmData(Content.Id); if (data != null) { using (MemoryStream stream = new MemoryStream(data)) { try { dataViewHost.Content = XmlParser.Deserialize <IContent>(stream); } catch (Exception) { } stream.Close(); } } }, "Refresh algorithm data failed.", () => SetEnabledStateOfControls() ); }
public override void Download(long solutionId) { if (SolutionId == solutionId) { return; } byte[] solutionData = RunCreationClient.Instance.GetSolutionData(solutionId); using (var stream = new MemoryStream(solutionData)) { Solution = XmlParser.Deserialize <IItem>(stream); SolutionId = solutionId; } var sol = RunCreationClient.Instance.GetSolution(solutionId); ProblemId = sol.ProblemId; var soSol = sol as SingleObjectiveSolution; if (soSol == null) { throw new InvalidOperationException(string.Format("Solution with id {0} is not a single-objective solution.", solutionId)); } Quality = soSol.Quality; }
public Data LoadFile(string fileName) { Data data = null; try { switch (Path.GetExtension(fileName)) { case ".json": { return(JsonConvert.DeserializeObject <Data>(File.ReadAllText(fileName))); } case ".xml": { return(XmlParser.Deserialize <Data>(fileName)); } case ".csv": { return(CsvParser.Deserialize(fileName)); } default: { Error?.Invoke(new Exception("Invalid file extension")); Environment.Exit(0); return(null); } } } catch (Exception ex) { Error?.Invoke(ex); } return(null); }
private static T DeserializeWithXmlParser <T>(byte[] sjob) { using (MemoryStream memStream = new MemoryStream(sjob)) { return(XmlParser.Deserialize <T>(memStream)); } }
public void TestXmlParser() { var parser = new XmlParser(); var result = parser.Deserialize <Garage>( @"C:\Users\michal\Documents\training\Anathema\Anathema\Anathema\Rhonin\TrainingThree\XML\XMLFiles\garage.xml"); }
private void ProfilePersistenceToMemory(string fileName) { var REPS = 5; var oldDeserStopwatch = new Stopwatch(); var oldSerStopwatch = new Stopwatch(); var newDeserStopwatch = new Stopwatch(); var newSerStopwatch = new Stopwatch(); long oldSize = 0, newSize = 0; var config = ConfigurationService.Instance.GetConfiguration(new XmlFormat()); int[] oldCollections = new int[3]; int[] newCollections = new int[3]; for (int i = 0; i < REPS; i++) { var original = XmlParser.Deserialize(fileName); object deserializedObject1 = null; object deserializedObject2 = null; byte[] buf; System.GC.Collect(); var collection0 = System.GC.CollectionCount(0); var collection1 = System.GC.CollectionCount(1); var collection2 = System.GC.CollectionCount(2); using (var s = new MemoryStream()) { oldSerStopwatch.Start(); // serialize manually so that the stream won't be closed var serializer = new Core.Serializer(original, config); serializer.InterleaveTypeInformation = true; using (StreamWriter writer = new StreamWriter(new GZipStream(s, CompressionMode.Compress))) { XmlGenerator generator = new XmlGenerator(); foreach (ISerializationToken token in serializer) { writer.Write(generator.Format(token)); } writer.Flush(); oldSize += s.Length; } oldSerStopwatch.Stop(); buf = s.GetBuffer(); } using (var s = new MemoryStream(buf)) { oldDeserStopwatch.Start(); deserializedObject1 = XmlParser.Deserialize(s); oldDeserStopwatch.Stop(); } System.GC.Collect(); oldCollections[0] += System.GC.CollectionCount(0) - collection0; oldCollections[1] += System.GC.CollectionCount(1) - collection1; oldCollections[2] += System.GC.CollectionCount(2) - collection2; collection0 = System.GC.CollectionCount(0); collection1 = System.GC.CollectionCount(1); collection2 = System.GC.CollectionCount(2); // Protobuf only uses Deflate using (var m = new MemoryStream()) { // using (var s = new GZipStream(m, CompressionMode.Compress)) { // same as old persistence using (var s = new DeflateStream(m, CompressionMode.Compress)) { // new format newSerStopwatch.Start(); (new ProtoBufSerializer()).Serialize(original, s, false); s.Flush(); newSerStopwatch.Stop(); newSize += m.Length; } buf = m.GetBuffer(); } using (var m = new MemoryStream(buf)) { // using (var s = new GZipStream(m, CompressionMode.Decompress)) { // same as old persistence using (var s = new DeflateStream(m, CompressionMode.Decompress)) { // new format newDeserStopwatch.Start(); deserializedObject2 = (new ProtoBufSerializer()).Deserialize(s); newDeserStopwatch.Stop(); } } //Assert.AreEqual(deserializedObject1.GetObjectGraphObjects().Count(), deserializedObject2.GetObjectGraphObjects().Count()); System.GC.Collect(); newCollections[0] += System.GC.CollectionCount(0) - collection0; newCollections[1] += System.GC.CollectionCount(1) - collection1; newCollections[2] += System.GC.CollectionCount(2) - collection2; } Console.WriteLine($"{fileName} " + $"{oldSize / (double)REPS} " + $"{newSize / (double)REPS} " + $"{oldSerStopwatch.ElapsedMilliseconds / (double)REPS} " + $"{newSerStopwatch.ElapsedMilliseconds / (double)REPS} " + $"{oldDeserStopwatch.ElapsedMilliseconds / (double)REPS} " + $"{newDeserStopwatch.ElapsedMilliseconds / (double)REPS} " + $"{oldCollections[0] / (double)REPS} " + $"{newCollections[0] / (double)REPS} " + $"{oldCollections[1] / (double)REPS} " + $"{newCollections[1] / (double)REPS} " + $"{oldCollections[2] / (double)REPS} " + $"{newCollections[2] / (double)REPS} " + $""); }
protected override IStorableContent LoadContent(string filename) { return(XmlParser.Deserialize <IStorableContent>(filename)); }
public override void DownloadData() { using (var stream = new MemoryStream(RunCreationClient.Instance.GetSolutionData(SolutionId))) { Solution = XmlParser.Deserialize <IItem>(stream); } }
private void ProfilePersistenceToDisk(string fileName) { var REPS = 5; var oldDeserStopwatch = new Stopwatch(); var oldSerStopwatch = new Stopwatch(); var newDeserStopwatch = new Stopwatch(); var newSerStopwatch = new Stopwatch(); long oldSize = 0, newSize = 0; int[] oldCollections = new int[3]; int[] newCollections = new int[3]; for (int i = 0; i < REPS; i++) { var original = XmlParser.Deserialize(fileName); System.GC.Collect(); var collection0 = System.GC.CollectionCount(0); var collection1 = System.GC.CollectionCount(1); var collection2 = System.GC.CollectionCount(2); oldSerStopwatch.Start(); XmlGenerator.Serialize(original, tempFile); oldSerStopwatch.Stop(); oldSize += new FileInfo(tempFile).Length; oldDeserStopwatch.Start(); var clone = XmlParser.Deserialize(tempFile); oldDeserStopwatch.Stop(); System.GC.Collect(); oldCollections[0] += System.GC.CollectionCount(0) - collection0; oldCollections[1] += System.GC.CollectionCount(1) - collection1; oldCollections[2] += System.GC.CollectionCount(2) - collection2; collection0 = System.GC.CollectionCount(0); collection1 = System.GC.CollectionCount(1); collection2 = System.GC.CollectionCount(2); newSerStopwatch.Start(); (new ProtoBufSerializer()).Serialize(original, tempFile); newSerStopwatch.Stop(); newSize += new FileInfo(tempFile).Length; newDeserStopwatch.Start(); var newClone = (new ProtoBufSerializer()).Deserialize(tempFile); newDeserStopwatch.Stop(); System.GC.Collect(); newCollections[0] += System.GC.CollectionCount(0) - collection0; newCollections[1] += System.GC.CollectionCount(1) - collection1; newCollections[2] += System.GC.CollectionCount(2) - collection2; } Console.WriteLine($"{fileName} " + $"{oldSize / (double)REPS} " + $"{newSize / (double)REPS} " + $"{oldSerStopwatch.ElapsedMilliseconds / (double)REPS} " + $"{newSerStopwatch.ElapsedMilliseconds / (double)REPS} " + $"{oldDeserStopwatch.ElapsedMilliseconds / (double)REPS} " + $"{newDeserStopwatch.ElapsedMilliseconds / (double)REPS} " + $"{oldCollections[0] / (double)REPS} " + $"{newCollections[0] / (double)REPS} " + $"{oldCollections[1] / (double)REPS} " + $"{newCollections[1] / (double)REPS} " + $"{oldCollections[2] / (double)REPS} " + $"{newCollections[2] / (double)REPS} " + $""); }
public void TestXmlParser() { var parser = new XmlParser(); var result = parser.Deserialize<Garage>( @"C:\Users\michal\Documents\training\Anathema\Anathema\Anathema\Rhonin\TrainingThree\XML\XMLFiles\garage.xml"); }