private FGManager() { _warehouse = new Warehouse(); _shoppingCart = new ShoppingCart(); _costumerRiepilogue = new CustomerRiepilogue(); _rentsRiepilogue = new RentRiepilogue(); _invoicesRiepilogue = new InvoicesRiepilogue(); _products = new List <Product>(); CheckFiles(); _products = XmlSerializerUtil.Load <List <Product> >("prodotti.xml"); foreach (Product p in _products) { _warehouse.AddProduct(p); } _costumerRiepilogue.AddAll(DatBinaryFormatter.Load <List <Customer> >("riepiloghiCustomer.dat")); _rentsRiepilogue.AddAll(DatBinaryFormatter.Load <List <Rent> >("riepiloghiRent.dat")); _invoicesRiepilogue.AddAll(DatBinaryFormatter.Load <List <Invoice> >("riepiloghiInvoice.dat")); _invoicesRiepilogue.GetAll.CollectionChanged += onInvoiceRiepilogue; _costumerRiepilogue.GetAll.CollectionChanged += onCustomerRiepilogue; _rentsRiepilogue.GetAll.CollectionChanged += onRentsRiepilogue; _warehouse.ProductList.CollectionChanged += onWarehouse; }
public override bool Init(FtpServer server, IServerConfig config) { if (!base.Init(server, config)) { return(false); } var userSettingFile = config.Options.GetValue("userSetting"); if (string.IsNullOrEmpty(userSettingFile)) { server.Logger.Error("No user setting file defined!"); return(false); } List <FtpUser> users; try { users = XmlSerializerUtil.Deserialize <List <FtpUser> >(server.GetFilePath(userSettingFile)); } catch (Exception e) { AppServer.Logger.Error("Failed to deserialize FtpUser list file!", e); return(false); } m_UserDict = users.ToDictionary(u => u.UserName, u => u, StringComparer.OrdinalIgnoreCase); return(true); }
//确定 private void button2_Click(object sender, EventArgs e) { try { ClientProduceOutputBillSave clientDmo = new ClientProduceOutputBillSave { AccountingUnit_ID = SysConfig.Current.AccountingUnit_ID.Value, Department_ID = SysConfig.Current.Department_ID ?? 0, Domain_ID = SysConfig.Current.Domain_ID, User_ID = SysConfig.Current.User_ID, CreateTime = DateTime.Now }; var clientDetail = new ClientGoods(); clientDetail.Goods_ID = mClientGoods.Goods_ID; clientDetail.Goods_Number = decimal.Parse(txtNumber.Text); clientDmo.Details.Add(clientDetail); XmlSerializerUtil.ClientXmlSerializer(clientDmo); SyncBillUtil.SyncProductOut(); MessageBox.Show("操作成功"); txtNumber.Text = ""; textBox1.Text = ""; } catch (Exception ex) { MessageBox.Show(ex.Message);; } }
private void button1_Click(object sender, EventArgs e) { ClientProduceOutputBillSave dmo = new ClientProduceOutputBillSave(); dmo.AccountingUnit_ID = SysConfig.Current.AccountingUnit_ID ?? 0; dmo.Department_ID = SysConfig.Current.Department_ID ?? 0; dmo.Domain_ID = SysConfig.Current.Domain_ID; dmo.User_ID = SysConfig.Current.User_ID; foreach (ListViewItem item in listView1.Items) { if (item.Checked) { var goods = item.Tag as ClientGoods; var detail = new ClientGoods(); detail.Goods_ID = goods.Goods_ID; decimal?number = null; try { number = decimal.Parse(item.SubItems[2].Text); } catch (Exception) { } detail.Goods_Number = number; dmo.Details.Add(detail); } } XmlSerializerUtil.ClientXmlSerializer(dmo); SyncBillUtil.SyncProductInStore(); MessageBox.Show("操作成功"); Close(); }
/// <summary> /// Exports the supplied query /// </summary> /// <param name="q">The <see cref="StoredQuery"/> to export</param> /// <param name="filename">The name of the file to export it to.</param> /// <returns>True if the query was exported, false otherwise.</returns> private bool ExportQuery(StoredQuery q, string filename) { //overwrite file? if (File.Exists(filename)) { if (!Parameters.AskYesNo("The filename " + filename + " already exists, do you want to overwrite it?")) { return(false); } } if (q.QueryScope != QueryScope.Private) { return(true); } //Create item and serialize var wiq = new WorkItemQuery { Query = q.QueryText }; XmlSerializerUtil.SerializeToXmlFile(wiq, filename, new UTF8Encoding(false)); Console.WriteLine("Exported query " + q.Name + " to file " + filename); return(true); }
public void Save() { var s = new XmlSerializer(package.GetType()); package.FileName = Path.GetFileNameWithoutExtension(ttaFile); XmlSerializerUtil.Write(ttaFile, package); }
/// <summary> /// 设置是否登录到配置中 /// </summary> /// <param name="flag"></param> private void SetAutoLogin(bool flag) { _configModel.AutoLogin = Convert.ToInt32(flag); XmlSerializerUtil.SaveToXml( GetConfigPath(), _configModel, typeof(LoginConfigModel)); }
public static Document Load(string ttaFile) { var doc = new Document { ttaFile = ttaFile, package = XmlSerializerUtil.Read <Package>(ttaFile) }; return(doc); }
/// <summary> /// 从配置中读取是否登录 /// </summary> /// <returns></returns> private bool GetAutoLogin() { _configModel = XmlSerializerUtil.LoadFromXml(GetConfigPath(), typeof(LoginConfigModel)) as LoginConfigModel; if (_configModel == null) { return(false); } return(Convert.ToBoolean(_configModel.AutoLogin)); }
public void SerializeToString_Equals_StringAfterSerialization() { // arrange var expectedString = getTestXmlArrayString(); // act var serializedList = XmlSerializerUtil.SerializeToString(getTestPersonList().PersonCollection); // asset Assert.AreEqual(expectedString, serializedList); }
private FileInfo GetOrCreateDatabaseFile() { if (!Directory.Exists(fileDirectory)) { Directory.CreateDirectory(fileDirectory); } var file = new FileInfo(fileDirectory + fileName); if (!file.Exists) { XmlSerializerUtil.SerializeToFile(new PersonList(), file.FullName); } return(file); }
public static async Task <T> Load <T>(this StorageFile file) { var s = XmlSerializerUtil.GetSerializer(typeof(T)); using (var st = await file.OpenStreamForReadAsync()) { try { return((T)s.Deserialize(st)); } catch (Exception) { return(default(T)); } } }
/// <summary> /// Parses the response, parses body elements. /// </summary> /// <typeparam name="TRes"></typeparam> /// <param name="message"></param> public static void ParseResponse <TRes>(SoapMessage message) { Logger.Instance.LogFunctionEntry("TouricoMessageHelper", "ParseResponse"); var touricoMessage = message as TouricoMessage; if (touricoMessage == null) { throw new InvalidCastException("Expected SabreMessage"); } var doc = new XmlDocument(); doc.LoadXml(message.RawResponseText); var nsMgr = new XmlNamespaceManager(doc.NameTable); nsMgr.AddNamespace("soap", "http://schemas.xmlsoap.org/soap/envelope/"); //Body var bodyNode = doc.SelectSingleNode("//soap:Body", nsMgr); if (bodyNode != null) { //Try catch here to know if body is actual response or Fault XmlReader bodyReader = XmlReader.Create(new StringReader(bodyNode.InnerXml)); Message msg = Message.CreateMessage(MessageVersion.Soap11, null, bodyReader); var converter = TypedMessageConverter.Create(typeof(TRes), null, new XmlSerializerFormatAttribute()); touricoMessage.ResponseBodyPayload = (TRes)converter.FromMessage(msg); touricoMessage.ResponseBodyText = bodyNode.InnerXml; if (touricoMessage.ResponseBodyPayload == null) { var fault = XmlSerializerUtil <WSFault> .Deserialize(touricoMessage.ResponseBodyText); if (fault != null) { throw new TouricoProviderException(fault); } throw new Exception("ResponseBodyPayload is null."); } } Logger.Instance.LogFunctionExit("TouricoMessageHelper", "ParseResponse"); }
public static async Task Save <T>(this StorageFile file, T obj) { var s = XmlSerializerUtil.GetSerializer(typeof(T)); var setting = new XmlWriterSettings { NewLineOnAttributes = true, Indent = true, }; var ns = new XmlSerializerNamespaces(); ns.Add(string.Empty, string.Empty); using (var st = await file.OpenStreamForWriteAsync()) using (var xmlWriter = XmlWriter.Create(st, setting)) { s.Serialize(xmlWriter, obj); } }
public void WriteTest() { var data = new Data { Name = "0123456789012345678901234567890123456789" }; var dataFile = TestFile("data.xml"); PathUtil.EnsureFileNotExists(dataFile); XmlSerializerUtil.Write(dataFile, data); Assert.AreEqual(data.Name, XmlSerializerUtil.Read <Data>(dataFile).Name); data = new Data { Name = "0123456789" }; XmlSerializerUtil.Write(dataFile, data); Assert.AreEqual(data.Name, XmlSerializerUtil.Read <Data>(dataFile).Name); }
public void SerializeToFile_Equals_DeserializeFromFile() { // arrange var tmpFilePath = Path.Combine(Environment.CurrentDirectory, "PersonList.xml"); var expectedList = getTestPersonList(); //String expectedString = getTestXmlArrayString(); // act XmlSerializerUtil.SerializeToFile(expectedList, tmpFilePath); var deserializePersonList = XmlSerializerUtil.DeserializeFromFile <PersonList>(tmpFilePath); // asset Assert.IsTrue(File.Exists(tmpFilePath)); deserializePersonList.ShouldBeEquivalentTo(expectedList); // clean File.Delete(tmpFilePath); }
private void ReadUserConfigFile() { if (!File.Exists(m_UserConfigFile)) { return; } var lastFileWriteTime = File.GetLastWriteTime(m_UserConfigFile); if (lastFileWriteTime <= m_LastUserFileLoadTime) { return; } var users = XmlSerializerUtil.Deserialize <List <FtpUser> >(m_UserConfigFile); m_UserDict = users.ToDictionary(u => u.UserName, u => u, StringComparer.OrdinalIgnoreCase); m_LastUserFileLoadTime = lastFileWriteTime; }
private void CheckFiles() { if (!File.Exists("prodotti.xml")) { XmlSerializerUtil.Save <List <Product> >("prodotti.xml", _warehouse.ProductList.ToList()); } if (!File.Exists("riepiloghiCustomer.dat")) { DatBinaryFormatter.Save <List <Customer> >("riepiloghiCustomer.dat", _costumerRiepilogue.GetAll.ToList()); } if (!File.Exists("riepiloghiRent.dat")) { DatBinaryFormatter.Save <List <Rent> >("riepiloghiRent.dat", _rentsRiepilogue.GetAll.ToList()); } if (!File.Exists("riepiloghiInvoice.dat")) { DatBinaryFormatter.Save <List <Invoice> >("riepiloghiInvoice.dat", _invoicesRiepilogue.GetAll.ToList()); } }
/// <summary> /// Performs the Import operation /// </summary> public override void PerformOperation() { int nrOfImportedQueries = 0; foreach (KeyValuePair <string, FileInfo> pair in _filesToImport) { FileInfo file = pair.Value; string queryName = pair.Key; //Read file var wiq = XmlSerializerUtil.DeserializeFromXmlFile <WorkItemQuery>(file.FullName); //see if query already exists StoredQuery q = GetStoredQuery(queryName); //update existing? if (q != null) { if (!Parameters.AskYesNo("The StoredQuery " + queryName + " already exists, do you want to overwrite it?")) { continue; } q.QueryText = wiq.Query; q.Update(); } else { //create new q = new StoredQuery(QueryScope.Private, queryName, wiq.Query, Parameters.QueryDescription); Project.StoredQueries.Add(q); } Console.WriteLine("Imported file " + file.Name + " as query " + queryName); nrOfImportedQueries++; } if (nrOfImportedQueries > 1) { Console.WriteLine("Imported " + nrOfImportedQueries + " queries."); } }
public string SerializeObject(ObjectToSerialize obj) { return(XmlSerializerUtil.SerializeToXml <ObjectToSerialize>(obj)); }
/* ******************************************************************* * Methods * *******************************************************************/ #region public void Save() /// <summary> /// Saves the current settings /// </summary> public void Save() { XmlSerializerUtil.SerializeToXmlFile(this, _filename); }
private static async Task Låge4(ParticipateResponse participateResponse, string xmlUrl, HttpClient httpClient) { Console.WriteLine("Parsing XML..."); XDocument xmlDocument = XDocument.Load(xmlUrl); ToyDistributionProblem parsedXml = XmlSerializerUtil.Deserialize <ToyDistributionProblem>(xmlDocument); Console.WriteLine($"Xml parsed to object...{parsedXml.Children.Count} children and {parsedXml.Toys.Count} toys..."); Console.WriteLine("Starting to distribute toys to children..."); Queue <Child> remainingChilren = new Queue <Child>(parsedXml.Children); int counter = 0; ToyDistributorHelper toyDistributor = new ToyDistributorHelper(parsedXml.Toys); //ToyDistributionResult result = new ToyDistributionResult(); List <ToyDistribution> distributionResult = new List <ToyDistribution>(); try { while (remainingChilren.Count > 0) { Console.WriteLine($"Iteration: {counter}"); Child currentChild = remainingChilren.Dequeue(); Toy foundToy; bool resolved = toyDistributor.TryResolve(currentChild, out foundToy); if (resolved) { distributionResult.Add(new ToyDistribution() { ChildName = currentChild.Name, ToyName = foundToy.Name }); toyDistributor.RemoveToy(foundToy); } else { remainingChilren.Enqueue(currentChild); } counter++; if (counter > 50) { break; } } //Console.WriteLine($"Toy distribution result: {result.ToString()}"); //List<ToyDistribution> distributionResult = new List<ToyDistribution>(); //foreach (var res in result.ToyDistribution) //{ // distributionResult.Add(new ToyDistribution() { ChildName = res.Key, ToyName = res.Value }); //} HttpResponseMessage toyDistributionResponse = await httpClient.PostAsJsonAsync("/api/toydistribution", new { id = participateResponse.Id, toyDistribution = distributionResult }); if (!toyDistributionResponse.IsSuccessStatusCode) { string reason = await toyDistributionResponse.Content.ReadAsStringAsync(); throw new ChristmasException($"{toyDistributionResponse.StatusCode}: {(await toyDistributionResponse.Content.ReadAsStringAsync())}"); } Console.WriteLine("##############################################################################"); string apiResult = await toyDistributionResponse.Content.ReadAsStringAsync(); Console.WriteLine(apiResult); } catch (Exception ex) { Console.WriteLine(ex.Message); Console.WriteLine(ex.StackTrace); } }
public void SavePersonList(ObservableCollection <Person> list) { XmlSerializerUtil.SerializeToFile(new PersonList(list), GetOrCreateDatabaseFile().FullName); }
public int GetPersonListHashCode(IEnumerable <Person> list) { return(XmlSerializerUtil.SerializeToString(list).GetHashCode()); }
public ObservableCollection <Person> LoadPersonList() { return(XmlSerializerUtil.DeserializeFromFile <PersonList>(GetOrCreateDatabaseFile().FullName).PersonCollection); }
private void onWarehouse(object sender, NotifyCollectionChangedEventArgs e) { XmlSerializerUtil.Save <List <Product> >("prodotti.xml", _warehouse.ProductList.ToList()); }