private static AbstractPersistentData Deserialize(string filePath, string importedBuildPath) { var deserializer = new IPersistentDataDeserializer[] { new PersistentDataDeserializerUpTo230(), new PersistentDataDeserializerCurrent() }; var xmlString = File.ReadAllText(filePath); var version = XmlSerializationUtils.DeserializeString <XmlPersistentDataVersion>(xmlString).AppVersion; IPersistentDataDeserializer suitableDeserializer; if (version == null) { suitableDeserializer = deserializer.FirstOrDefault(c => c.MinimumDeserializableVersion == null); } else { var v = new Version(version); suitableDeserializer = deserializer.FirstOrDefault(c => v.CompareTo(c.MinimumDeserializableVersion) >= 0 && v.CompareTo(c.MaximumDeserializableVersion) <= 0); } if (suitableDeserializer == null) { throw new Exception( $"No converter available that can deserialize a PersistentData file with version {version}"); } var data = new PersistentData(suitableDeserializer, importedBuildPath); suitableDeserializer.DeserializePersistentDataFile(xmlString); return(data); }
public void Given_ValidAESKeyPOCO_When_SerializeAndDeserialize_Then_POCOContentIsTheSame() { // Arrange var aesKeyXmlPoco = new EnvCryptKey() { Name = "My AES Key", Aes = new[] { new EnvCryptKeyAes() { Iv = "aesIV", Key = "aesKey" } }, Encryption = "Aes", Type = null }; // Act var xmlUtil = new XmlSerializationUtils <EnvCryptKey>(); var serialized = xmlUtil.Serialize(aesKeyXmlPoco); var deserialized = xmlUtil.Deserialize(serialized); // Assert deserialized.Should().NotBeNull(); deserialized.Name.Should().Be(aesKeyXmlPoco.Name); deserialized.Encryption.Should().Be(aesKeyXmlPoco.Encryption); deserialized.Type.Should().BeNull(); deserialized.Aes.Should().HaveCount(1); deserialized.Aes[0].Iv.Should().Be("aesIV"); deserialized.Aes[0].Key.Should().Be("aesKey"); }
private static void SerializeBuild(string path, PoEBuild build) { var xmlBuild = ToXmlBuild(build); XmlSerializationUtils.SerializeToFile(xmlBuild, path + BuildFileExtension); build.KeepChanges(); }
public TasksResponse Execute() { var xml = XmlSerializationUtils.Serialize(this._Wrapper); var url = this.MakeUrl(); if (_boolSwitch.Enabled) { Trace.WriteLine("Post URL:"); Trace.WriteLine(url); Trace.WriteLine("Request XML:"); Trace.WriteLine(xml); } var result = HttpUtils.Post(this.MakeUrl(), xml); if (_boolSwitch.Enabled) { Trace.WriteLine("Response XML:"); Trace.WriteLine(result); } var tasksResponse = (TasksResponse)XmlSerializationUtils.Deserialize(typeof(TasksResponse), result); CheckErrors(tasksResponse.Errors); return(tasksResponse); }
public virtual EntityDto GetByUid(int uid) { string url = this.MakeUrl() + "&uid=" + uid; string result = HttpUtils.Get(url); ResponseDto response = (ResponseDto)XmlSerializationUtils.Deserialize(this.ResponseDtoType, result); this.CheckErrors(response.Errors); return(this.ExtractContentFromGetByUidResponse(response)); }
public virtual void DeleteByUid(int uid) { string url = this.MakeUrl() + "&uid=" + uid; string result = HttpUtils.Delete(url); CrudResponseDto response = (CrudResponseDto)XmlSerializationUtils.Deserialize( this.ResponseDtoType, result); this.CheckErrors(response.Errors); }
private static async Task <T?> DeserializeAsync <T>(string path) where T : class { try { return(await XmlSerializationUtils.DeserializeFileAsync <T>(path, true).ConfigureAwait(false)); } catch (Exception e) { Log.Error(e, $"Could not deserialize file from {path} as type {typeof(T)}"); return(default);
public override void DeserializePersistentDataFile(string xmlString) { var obj = XmlSerializationUtils.DeserializeString <XmlPersistentData>(xmlString); PersistentData.Options = obj.Options; obj.StashBookmarks?.ForEach(PersistentData.StashBookmarks.Add); obj.LeagueStashes?.ForEach(l => PersistentData.LeagueStashes[l.Name] = l.Bookmarks); _currentBuildPath = obj.CurrentBuildPath; _selectedBuildPath = obj.SelectedBuildPath; }
public async Task <IBuild?> FromBase64Async(string input) { var compressed = Convert.FromBase64String(input.Replace('-', '+').Replace('_', '/')); await using var ms = new MemoryStream(compressed); // Skip compression type header ms.Seek(2, SeekOrigin.Begin); await using var deflateStream = new DeflateStream(ms, CompressionMode.Decompress); var xmlBuild = await XmlSerializationUtils.DeserializeAsync <XmlPathOfBuilding>(new StreamReader(deflateStream)); return(ConvertXmlBuild(xmlBuild)); }
/// <summary> /// Imports the build located at <paramref name="buildPath"/>. <see cref="IPersistentData.SaveBuild"/> may be /// called by this method. /// </summary> public async Task ImportBuildFromFileAsync(string buildPath) { const string extension = SerializationConstants.BuildFileExtension; if (!File.Exists(buildPath) || Path.GetExtension(buildPath) != extension) { Log.Error($"Could not import build file from {buildPath}"); var message = string.Format( L10n.Message( "Could not import build file, only existing files with the extension {0} can be imported."), extension); await DialogCoordinator.ShowErrorAsync(PersistentData, message, title : L10n.Message("Import failed")); return; } var unifiedBuildsSavePath = PersistentData.Options.BuildsSavePath.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar); var unifiedPath = buildPath.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar); if (unifiedPath.StartsWith(unifiedBuildsSavePath)) { // If BuildsSavePath is part of buildPath, just set it as current and selected build // Remove BuildsSavePath var relativePath = unifiedPath.Remove(0, unifiedBuildsSavePath.Length + 1); // Remove extension var path = relativePath.Remove(relativePath.Length - extension.Length); var build = BuildForPath(path) as PoEBuild; if (build == null) { Log.Warn($"Import failed, build with path {path} not found"); return; } PersistentData.CurrentBuild = build; PersistentData.SelectedBuild = build; } else { // Else, proper import var build = await ImportBuildAsync( async() => await XmlSerializationUtils.DeserializeFileAsync <XmlBuild>(buildPath)); if (build != null) { build.Name = Util.FindDistinctName(build.Name, PersistentData.RootBuild.Builds.Select(b => b.Name)); PersistentData.RootBuild.Builds.Add(build); PersistentData.CurrentBuild = build; PersistentData.SelectedBuild = build; PersistentData.SaveBuild(PersistentData.RootBuild); } } }
private static void SerializeFolder(string path, BuildFolder folder) { var xmlFolder = new XmlBuildFolder { Version = BuildVersion.ToString(), IsExpanded = folder.IsExpanded, Builds = folder.Builds.Select(b => b.Name).ToList() }; Directory.CreateDirectory(path); XmlSerializationUtils.SerializeToFile(xmlFolder, Path.Combine(path, BuildFolderFileName)); }
/// <summary> /// Search contact by contact id (not contact uid). /// </summary> /// <param name="contactID"></param> /// <returns></returns> private contactListResponse SearchByContactID(string contactID) { NameValueCollection queries = new NameValueCollection(); queries.Add("contactid", contactID); string url = RestProxy.MakeUrl("ContactList"); url += "&" + Util.ToQueryString(queries); string xmlFragment = HttpUtils.Get(url); contactListResponse response = (contactListResponse)XmlSerializationUtils.Deserialize(typeof(contactListResponse), xmlFragment); return(response); }
public override void DeserializePersistentDataFile(string xmlString) { var obj = XmlSerializationUtils.DeserializeString <XmlPersistentData>(xmlString); PersistentData.Options = obj.Options; PersistentData.CurrentBuild = ConvertFromXmlBuild(obj.CurrentBuild) ?? CreateDefaultCurrentBuild(); obj.StashBookmarks?.ForEach(PersistentData.StashBookmarks.Add); PersistentData.RootBuild.Builds.AddRange(obj.Builds.Select(ConvertFromXmlBuild)); if (!SelectCurrentBuildByName(PersistentData.CurrentBuild.Name)) { PersistentData.RootBuild.Builds.Add(PersistentData.CurrentBuild); } RenameBuilds(); }
public async Task UpdateAsync() { var mods = await LoadMods(); var uniqueTasks = RelevantWikiClasses.Select(c => LoadAsync(c, mods)) .Append(LoadJewelsAsync(mods)); var results = await Task.WhenAll(uniqueTasks).ConfigureAwait(false); var uniqueList = new XmlUniqueList { Uniques = results.Flatten().ToArray() }; XmlSerializationUtils.SerializeToFile(uniqueList, _savePath); }
/// <summary> /// Search contact, Carl O'Neil from O'Neil Capital. /// </summary> /// <returns></returns> private contactListResponse SearchCarl() { NameValueCollection queries = new NameValueCollection(); queries.Add("givenname", "carl"); // AKA first name. queries.Add("familyName", "o'neil"); // AKA last name. queries.Add("organisationName", "o'neil capital"); // AKA organisation, company. string url = RestProxy.MakeUrl("ContactList"); url += "&" + Util.ToQueryString(queries); string xmlFragment = HttpUtils.Get(url); contactListResponse response = (contactListResponse)XmlSerializationUtils.Deserialize(typeof(contactListResponse), xmlFragment); return(response); }
public void GetInventoryItemList() { string url = "http://localhost/restapi/inventoryitemlist?wsaccesskey=4962-A8E9-D414-4DCA-80F2-4A77-CEE6-7DBD&fileuid=1697"; // string url = "https://secure.saasu.com/alpha/webservices/rest/r1/inventoryitemlist?wsaccesskey=4962-A8E9-D414-4DCA-80F2-4A77-CEE6-7DBD&fileuid=1697"; string xmlFragment = HttpUtils.Get(url); inventoryItemListResponse response = (inventoryItemListResponse)XmlSerializationUtils.Deserialize(typeof(inventoryItemListResponse), xmlFragment); inventoryItemListResponseInventoryItemList list = response.Items[0]; Console.WriteLine("Number of items: {0}", list.inventoryItemListItem.Length); foreach (inventoryItemListResponseInventoryItemListInventoryItemListItem item in list.inventoryItemListItem) { // Console.WriteLine("Inventory item uid: {0}", item.inventoryItemUid); this.Count(item.code); } }
public void Given_ValidDatXML_When_Parsed_Then_CountsCorrect() { // Arrange var serializationUtil = new XmlSerializationUtils <EnvCryptEncryptedData>(); // Act var res = serializationUtil.Deserialize(@"<EnvCryptEncryptedData> <Category Name=""Prod ReadOnly""> <!-- EnvCrypt always stores Strings --> <Entry Name=""ComLib""> <!-- Hash of only part of the key because KeyName is not unique --> <Decryption KeyName=""first key"" Hash=""123456"" Algo=""RSA"" /> <!-- 2nd decryption should be ignored. This should not be allowed. --> <Decryption KeyName=""asdasdsad RO Key"" Hash=""0"" Algo=""RSA"" /> <EncryptedValue>...</EncryptedValue> <!-- Value to be encrypted may spill over max that can be encrypted in one go (RSA) --> <EncryptedValue>...</EncryptedValue> </Entry> <Entry Name=""ComLibConnectionString""> <!-- No encryption --> <EncryptedValue>...</EncryptedValue> </Entry> </Category> <Category Name=""Prod ReadWrite""> <Entry Name=""ComLib""> <!-- Hash of only part of the key because KeyName is not unique --> <Decryption KeyName=""Prod RW Key"" Hash=""1"" Algo=""AES""/> <EncryptedValue>...</EncryptedValue> </Entry> <Entry Name=""ComLibConnectionString""> <!-- No encryption --> <EncryptedValue>...</EncryptedValue> </Entry> </Category> </EnvCryptEncryptedData>"); // Assert res.Items.Should().HaveCount(2); // 2 categories res.Items[0].Entry.Should().HaveCount(2); // 2 entries in 1st category res.Items[0].Entry[0].Decryption.KeyName.Should().Be("first key"); res.Items[0].Entry[0].Decryption.Hash.Should().Be(123456); }
/// <summary> /// Serializes all files except builds to <paramref name="filePath"/>. /// </summary> public void Serialize(string filePath) { var stashes = new List <XmlLeagueStash>(_persistentData.LeagueStashes.Select( p => new XmlLeagueStash { Name = p.Key, Bookmarks = new List <StashBookmark>(p.Value) })); var xmlPersistentData = new XmlPersistentData { AppVersion = SerializationUtils.AssemblyFileVersion, CurrentBuildPath = PathFor(_persistentData.CurrentBuild, false), Options = _persistentData.Options, SelectedBuildPath = PathFor(_persistentData.SelectedBuild, false), StashBookmarks = _persistentData.StashBookmarks.ToList(), LeagueStashes = stashes }; XmlSerializationUtils.SerializeToFile(xmlPersistentData, filePath); SerializeStash(); }
public List <T> FindList <T>(string nodeXPath, params string[] parametersAndValues) where T : EntityDto, new() { NameValueCollection parameters = null; if (parametersAndValues != null) { for (int i = 0; i < parametersAndValues.Length; i += 2) { if (parameters == null) { parameters = new NameValueCollection(); } parameters.Add(parametersAndValues[i], parametersAndValues[i + 1]); } } XmlDocument document = Find(parameters); XmlElement root = document.DocumentElement; XmlNodeList itemsNode = root.SelectNodes(nodeXPath); List <T> list = new List <T>(); foreach (XmlNode itemNode in itemsNode) { try { T dto = (T)XmlSerializationUtils.Deserialize(typeof(T), itemNode.OuterXml); list.Add(dto); } catch (Exception ex) { throw new ApplicationException("Could not deserialize:" + itemNode.OuterXml, ex); } } return(list); }
// [Test] public void InsertJournal_MoreThan2Decimals() { string xml = @"<?xml version=""1.0"" encoding=""utf-16""?> <tasks xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd="" http://www.w3.org/2001/XMLSchema""> <insertJournal> <journal uid=""0""> <utcLastModified>0001-01-01T00:00:00</utcLastModified> <date>2012-07-03</date> <summary>Pay run for pay period ending: 06/07/2012</summary> <requiresFollowUp>false</requiresFollowUp> <autoPopulateFxRate>true</autoPopulateFxRate> <fcToBcFxRate>0</fcToBcFxRate> <reference>233</reference> <journalItems> <journalItem> <accountUid>299019</accountUid> <amount>9761.66000</amount> <type>Credit</type> </journalItem> <journalItem> <accountUid>744</accountUid> <taxCode>W1</taxCode> <amount>13300.98648</amount> <type>Debit</type> </journalItem> <journalItem> <accountUid>744</accountUid> <taxCode>W1</taxCode> <amount>0</amount> <type>Credit</type> </journalItem> <journalItem> <accountUid>744</accountUid> <taxCode>W1</taxCode> <amount>0</amount> <type>Credit</type> </journalItem> <journalItem> <accountUid>744</accountUid> <taxCode>W1</taxCode> <amount>0</amount> <type>Credit</type> </journalItem> <journalItem> <accountUid>744</accountUid> <taxCode>W1</taxCode> <amount>0</amount> <type>Credit</type> </journalItem> <journalItem> <accountUid>744</accountUid> <taxCode>W1</taxCode> <amount>0</amount> <type>Credit</type> </journalItem> <journalItem> <accountUid>744</accountUid> <taxCode>W1</taxCode> <amount>0</amount> <type>Credit</type> </journalItem> <journalItem> <accountUid>2361</accountUid> <taxCode>W1</taxCode> <amount>0</amount> <type>Credit</type> </journalItem> <journalItem> <accountUid>299028</accountUid> <taxCode>W1</taxCode> <amount>301.92000</amount> <type>Debit</type> </journalItem> <journalItem> <accountUid>299028</accountUid> <taxCode>W1</taxCode> <amount>0</amount> <type>Credit</type> </journalItem> <journalItem> <accountUid>744</accountUid> <taxCode>W1</taxCode> <amount>0</amount> <type>Credit</type> </journalItem> <journalItem> <accountUid>744</accountUid> <taxCode>W1</taxCode> <amount>969.24648</amount> <type>Credit</type> </journalItem> <journalItem> <accountUid>741</accountUid> <amount>2872.00000</amount> <type>Credit</type> </journalItem> <journalItem> <accountUid>745</accountUid> <amount>1197.08000</amount> <type>Debit</type> </journalItem> <journalItem> <accountUid>743</accountUid> <amount>1197.08000</amount> <type>Credit</type> </journalItem> <journalItem> <accountUid>744</accountUid> <amount>969.23000</amount> <type>Debit</type> </journalItem> <journalItem> <accountUid>2374</accountUid> <amount>969.23000</amount> <type>Credit</type> </journalItem> <journalItem> <accountUid>2371</accountUid> <taxCode>W1</taxCode> <amount>2872.00000</amount> <type>Credit</type> </journalItem> <journalItem> <accountUid>2371</accountUid> <taxCode>W1,W2</taxCode> <amount>2872.00000</amount> <type>Debit</type> </journalItem> </journalItems> </journal> </insertJournal> </tasks> "; string url = RestProxy.MakeUrl("Tasks"); string result = HttpUtils.Post(url, xml); Console.WriteLine("Result:"); Console.WriteLine(result); var tasksResponse = (TasksResponse)XmlSerializationUtils.Deserialize(typeof(TasksResponse), result); Assert.AreEqual(0, tasksResponse.Errors.Count, "Should save successfully."); }
/// <summary> /// Serializes the given build to a xml string and returns that string. /// </summary> public string ExportBuildToString(PoEBuild build) { var xmlBuild = ToXmlBuild(build); return(XmlSerializationUtils.SerializeToString(xmlBuild)); }
protected override Task CompleteSavingAsync() { XmlSerializationUtils.SerializeToFile(Data, SavePath); return(Task.WhenAll()); }
public static Task <T> LoadXmlAsync <T>(string fileName, bool deserializeOnThreadPool = false) => XmlSerializationUtils.DeserializeAsync <T>(CreateResourceStreamReader(fileName), deserializeOnThreadPool);
/// <summary> /// Imports the build given as a xml string. <see cref="IPersistentData.SaveBuild"/> may be /// called by this method. /// </summary> public Task <PoEBuild?> ImportBuildFromStringAsync(string buildXml) { return(ImportBuildAsync( () => Task.FromResult(XmlSerializationUtils.DeserializeString <XmlBuild>(buildXml)))); }