protected void BtnSave_Click(object sender, EventArgs e) { #region WebSet model = new WebSet(); model.openOrcloseWeb = RadioBtnOpenOrClose.SelectedValue.ToInt(); model.Website = TbWebSite.Text; model.WebName = TbWebName.Text; model.Email = TbMail.Text; model.Address = TbAddress.Text; model.ZipCode = TbZipCode.Text; model.Phone = TbPhone.Text; model.Copyright = TbCopyright.Text; model.DuplicateWebpage = RadioBtnDuplicateWebpage.SelectedValue; model.ICP = TbIcp.Text; model.KeyWord = TbKeyWord.Text; model.Description = TbDescirption.Text; model.Fax = TbFax.Text; model.TQ = TbTQ.Text; model.WaterMarkType = RadioWaterMarkType.SelectedValue.ToInt(); model.WaterMarkTxt = TbWaterMarkTxt.Text; model.WaterMarkPicUrl = WaterMarkPic.Url; model.WaterMarkHorizontal = RadioHorizontal.SelectedValue; model.WaterMarkVertical = RadioVertical.SelectedValue; MyXmlSerializer <WebSet> .Set(model, fileUrl); MessageDiv.InnerHtml = YK.Common.CommonClass.Alert("数据修改成功!"); #endregion }
protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { WebSet model = MyXmlSerializer <WebSet> .Get(fileUrl); RadioBtnOpenOrClose.SelectedValue = model.openOrcloseWeb.ToString(); TbWebSite.Text = model.Website; TbWebName.Text = model.WebName; TbMail.Text = model.Email; TbAddress.Text = model.Address; TbZipCode.Text = model.ZipCode; TbPhone.Text = model.Phone; TbCopyright.Text = model.Copyright; RadioBtnDuplicateWebpage.SelectedValue = model.DuplicateWebpage; TbIcp.Text = model.ICP; TbKeyWord.Text = model.KeyWord; TbDescirption.Text = model.Description; TbFax.Text = model.Fax; TbTQ.Text = model.TQ; RadioWaterMarkType.SelectedValue = model.WaterMarkType.ToStr(); TbWaterMarkTxt.Text = model.WaterMarkTxt; WaterMarkPic.Url = model.WaterMarkPicUrl; RadioHorizontal.SelectedValue = model.WaterMarkHorizontal; RadioVertical.SelectedValue = model.WaterMarkVertical; } }
private void xmlSaveToolStripMenuItem1_Click(object sender, EventArgs e) { saveFileDialog1.Filter = "Xml files(*.xml)|*.xml|All files(*.*)|*.*"; if (saveFileDialog1.ShowDialog() == DialogResult.OK) { var xs = new MyXmlSerializer(); xs.Serialize(saveFileDialog1.FileName, data); } }
private void xmlLoadToolStripMenuItem_Click(object sender, EventArgs e) { openFileDialog1.Filter = "Xml files(*.xml)|*.xml|All files(*.*)|*.*"; if (openFileDialog1.ShowDialog() == DialogResult.OK) { var xs = new MyXmlSerializer(); data = xs.Deserialize(openFileDialog1.FileName); SetUp(); } }
/// <summary> /// Initializes a new instance of the <see cref="MigrateUserDb"/> class. /// </summary> /// <param name="logger">The logger.</param> /// <param name="paths">The server application paths.</param> /// <param name="provider">The database provider.</param> /// <param name="xmlSerializer">The xml serializer.</param> public MigrateUserDb( ILogger <MigrateUserDb> logger, IServerApplicationPaths paths, JellyfinDbProvider provider, MyXmlSerializer xmlSerializer) { _logger = logger; _paths = paths; _provider = provider; _xmlSerializer = xmlSerializer; }
public void FileCollegeDataLoaderSerializerxmlTest() { IMySerializer ser = new MyXmlSerializer(); CollegeData testCollegeData = new CollegeData(settings, ser); FileCollegeDataLoader loader = new FileCollegeDataLoader("SampleData.txt", ser); var outputCollegeData = loader.LoadCollegeData(testCollegeData); string res = loader.GetSerializedErrors(); Assert.IsTrue(res.Length > 0); }
public void SerializerIncompleteObjTest() { MyXmlSerializer<PlantSettings> serializer = new MyXmlSerializer<PlantSettings>(); StringBuilder builder = new StringBuilder(); builder.Append(@"<?xml version=""1.0"" encoding=""utf-16""?>"); builder.Append(@"<PlantSettings xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">"); builder.Append(@"<PlantVisibility>OwnersOnly</PlantVisibility>"); builder.Append(@"</PlantSettings>"); PlantSettings actual = serializer.DeserializeObject(builder.ToString()); Assert.IsNull(actual.InverterEuroMapping); Assert.AreEqual(E_PlantVisibility.OwnersOnly, actual.PlantVisibility); }
protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { EmailSet model = MyXmlSerializer <EmailSet> .Get(fileUrl); RadioBtnOpenOrClose.SelectedValue = model.openOrcloseWeb.ToString(); TbEmialName.Text = model.EmailName; TbEmailPwd.Text = model.EmailPwd; TbSMTPAddress.Text = model.SMTP; TbPort.Text = model.Port; } }
protected void BtnSave_Click(object sender, EventArgs e) { #region EmailSet model = new EmailSet(); model.openOrcloseWeb = RadioBtnOpenOrClose.SelectedValue.ToInt(); model.EmailName = TbEmialName.Text.TrimEnd(); model.EmailPwd = TbEmailPwd.Text.TrimEnd(); model.SMTP = TbSMTPAddress.Text.TrimEnd(); model.Port = TbPort.Text.TrimEnd(); MyXmlSerializer <EmailSet> .Set(model, fileUrl); MessageDiv.InnerHtml = YK.Common.CommonClass.Alert("数据修改成功!"); #endregion }
public void XMLSerializerTest() { MyXmlSerializer<PlantSettings> serializer = new MyXmlSerializer<PlantSettings>(); PlantSettings settings = new PlantSettings(); settings.PlantVisibility = E_PlantVisibility.OwnersOnly; settings.InverterEuroMapping = new SerializableDictionary<int, double>(); settings.InverterEuroMapping.Add(1, 2.5); settings.InverterEuroMapping.Add(2, 3.5); string actual = serializer.SerializeObject(settings); Console.Write(actual); PlantSettings result = serializer.DeserializeObject(actual); Assert.AreEqual(E_PlantVisibility.OwnersOnly, result.PlantVisibility); }
private static MyXmlSerializer GetSerializerFromList(Type clrType) { MyXmlSerializer serializer = null; serializer = _xmlSerializerList.FirstOrDefault(a => !a.IsLock && string.Equals(a.type.FullName, clrType.FullName, StringComparison.CurrentCultureIgnoreCase)); if (serializer == null) { serializer = new MyXmlSerializer(clrType); lock (_xmlSerializerListLock) { _xmlSerializerList.Add(serializer); } } return(serializer); }
/// <summary> /// Run all needed pre-startup migrations. /// </summary> /// <param name="appPaths">Application paths.</param> /// <param name="loggerFactory">Factory for making the logger.</param> public static void RunPreStartup(ServerApplicationPaths appPaths, ILoggerFactory loggerFactory) { var logger = loggerFactory.CreateLogger <MigrationRunner>(); var migrations = _preStartupMigrationTypes .Select(m => Activator.CreateInstance(m, appPaths, loggerFactory)) .OfType <IMigrationRoutine>() .ToArray(); var xmlSerializer = new MyXmlSerializer(); var migrationConfigPath = Path.Join(appPaths.ConfigurationDirectoryPath, MigrationsListStore.StoreKey.ToLowerInvariant() + ".xml"); var migrationOptions = (MigrationOptions)xmlSerializer.DeserializeFromFile(typeof(MigrationOptions), migrationConfigPath) !; // We have to deserialize it manually since the configuration manager may overwrite it var serverConfig = (ServerConfiguration)xmlSerializer.DeserializeFromFile(typeof(ServerConfiguration), appPaths.SystemConfigurationFilePath) !; HandleStartupWizardCondition(migrations, migrationOptions, serverConfig.IsStartupWizardCompleted, logger); PerformMigrations(migrations, migrationOptions, options => xmlSerializer.SerializeToFile(options, migrationConfigPath), logger); }
static void Main(string[] args) { ServiceCollection serviceCollection = new ServiceCollection(); ConfigureServices(serviceCollection); var section = configuration.GetSection("Weights"); List <SubjectWeight> weights = section.Get <List <SubjectWeight> >(); string filepath = configuration.GetSection("FilePath").Value; string outputfileProcess = configuration.GetSection("OutputFileProcessPath").Value; string outputFileLoaderErrors = configuration.GetSection("OutputfileLoadErrors").Value; string OutputFileOverallPath = configuration.GetSection("OutputFileOverallPath").Value; IMySerializer serializer = null; foreach (var item in args) { if (item == "JSON") { serializer = new MyJsonSerializer(); } } if (serializer == null) { serializer = new MyXmlSerializer(); } FileCollegeDataLoader loader = new FileCollegeDataLoader(filepath, serializer); CollegeDataSettings settings = new CollegeDataSettings() { Subjectweights = weights }; CollegeData.Implementation.CollegeData data = new CollegeData.Implementation.CollegeData(settings, serializer); loader.LoadCollegeData(data); File.WriteAllText(Path.ChangeExtension(outputFileLoaderErrors, serializer.GetFileExtension()), loader.GetSerializedErrors()); data.Process(); File.WriteAllText(Path.ChangeExtension(outputfileProcess, serializer.GetFileExtension()), data.GetSerializedGroups()); File.WriteAllText(Path.ChangeExtension(OutputFileOverallPath, serializer.GetFileExtension()), data.GetSerializedOverall()); }
public void Test2() { LibraryManager libraryManager = new LibraryManager(new DataRepository()); libraryManager.AddNewReader("Jacek", "Kowal"); libraryManager.AddNewReader("Aneta", "Dzwon"); libraryManager.AddNewBookItem("Dziady", "Adam Mickiewicz"); libraryManager.RegisterCopies(0, 20, 10.20, "pln"); libraryManager.RegisterCopies(0, 1, 10.99, "pln"); libraryManager.RegisterBorrowing(1, 0); libraryManager.RegisterPurchase(0, 0); MyXmlSerializer.CreateFile(typeof(LibraryManager), libraryManager, "serialization.xml"); LibraryManager managerBackup = (LibraryManager)MyXmlSerializer.ReadFile(typeof(LibraryManager), "serialization.xml"); libraryManager.dataRepository.dataContext.books.Values.Last().author = "zmiana"; Assert.AreEqual("zmiana", libraryManager.dataRepository.dataContext.copyInfos.First().bookItem.author); managerBackup.dataRepository.dataContext.books.Values.Last().author = "zmiana"; Assert.AreEqual("zmiana", managerBackup.dataRepository.dataContext.copyInfos.First().bookItem.author); }
/// <summary> /// 126邮件发送 /// </summary> /// <param name="EmailList">邮件列表,以分号“;”隔开</param> /// <param name="title">标题</param> /// <param name="sendContent">发送内容</param> public static void MailSend(string EmailList, string title, string sendContent) { string fileUrl = HttpContext.Current.Server.MapPath("~/App_Data/WebSet/EmailSet.xml"); EmailSet es = MyXmlSerializer <EmailSet> .Get(fileUrl); try { MailMessage objMailMessage = new MailMessage(); // 创建邮件消息 objMailMessage.From = es.EmailName; //源邮件地址 objMailMessage.To = EmailList; //目的邮件地址,也就是发给我哈 objMailMessage.Subject = title; //发送邮件的标题 objMailMessage.Body = sendContent; //发送邮件的内容 objMailMessage.BodyFormat = MailFormat.Html; // 创建一个附件对象 //MailAttachment objMailAttachmentobjMailAttachment = new MailAttachment("");//发送邮件的附件 --"d:\\test.txt" //objMailMessage.Attachments.Add(objMailAttachment);//将附件附加到邮件消息对象中 //接着利用sina的SMTP来发送邮件,需要使用Microsoft .NET Framework SDK v1.1和它以上的版本 //基本权限 objMailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", "1"); //用户名 objMailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername", es.EmailName); //密码 objMailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword", es.EmailPwd); //如果没有上述三行代码,则出现如下错误提示:服务器拒绝了一个或多个收件人地址。服务器响应为: 554 : Client host rejected: Access denied //SMTP地址 SmtpMail.SmtpServer = es.SMTP; //开始发送邮件 SmtpMail.Send(objMailMessage); } catch (Exception ex) { //写入日志 TxtFileHelper.AppendLogTxt(ex.Message); } }
private static ISerializer SelectSerializer(string format) { ISerializer serializer; switch (format.ToUpper()) { case ".XML": { serializer = new MyXmlSerializer(); break; } case ".JSON": { serializer = new MyJsonSerializer(); break; } default: throw new ArgumentException("this format is not supported"); } return(serializer); }
protected ActionResult Xml <E>(E obj, bool igroneXmlVersion = false) { string xml = new MyXmlSerializer().Serialize(obj, igroneXmlVersion); return(Content(xml, "application/xml")); }
static void Main(string[] args) { string filePath = Assembly.GetEntryAssembly().Location + ".config"; Console.WriteLine(filePath); if (!File.Exists(filePath)) { Console.WriteLine("File not exists"); return; } Console.WriteLine("File exist"); Console.WriteLine("Folder exist: {0}", (Directory.Exists(filePath) ? "YES" : "NO")); string configFolder = Path.GetDirectoryName(filePath); Console.WriteLine(configFolder); Console.WriteLine("Folder exist: {0}", (Directory.Exists(configFolder) ? "YES" : "NO")); Console.WriteLine("File exist: {0}", (File.Exists(configFolder) ? "YES" : "NO")); Console.WriteLine("============================ Content ============================"); //string[] lines = FileUtilSimple.ReadFile(filePath); string[] lines = File.ReadAllLines(filePath); foreach (string line in lines) { Console.WriteLine(line); } Console.WriteLine(""); Console.WriteLine("Write backup..."); File.WriteAllLines(filePath + ".bak", lines, Encoding.UTF8); Console.WriteLine("============================ Get message from XML ============================"); Console.WriteLine(XMLUtil.ReadMessage(filePath)); Console.WriteLine("============================ Get message from .config ============================"); Console.WriteLine(ConfigurationManager.AppSettings["Message"]); Console.WriteLine("============================ Save using Serializer ============================"); Config cfg = new Config() { DataBaseServerAddress = "127.0.0.1", DataBaseName = "Employees", TimeOut = 100000, Devider = 3.14, ExpirationDate = new DateTime(2020, 10, 20) }; string xmlConfigPath = Path.Combine(configFolder, "config.MyXmlSerializer.xml"); MyXmlSerializer.Save <Config>(xmlConfigPath, cfg); Console.WriteLine(" {0} saved", xmlConfigPath); xmlConfigPath = Path.Combine(configFolder, "config.XmlSerializer.xml"); XmlSerializer XmlSerializer = new XmlSerializer(typeof(Config)); using (FileStream fs = new FileStream(xmlConfigPath, FileMode.OpenOrCreate)) { XmlSerializer.Serialize(fs, cfg); } Console.WriteLine(" {0} saved", xmlConfigPath); string jsonConfigPath = Path.Combine(configFolder, "config.JsonSerializer.json"); JsonSerializer jsonSerializer = new JsonSerializer(); using (StreamWriter jsonFile = new StreamWriter(jsonConfigPath)) using (JsonWriter jsonWriter = new JsonTextWriter(jsonFile)) { jsonSerializer.Serialize(jsonWriter, cfg); } Console.WriteLine(" {0} saved", jsonConfigPath); Console.WriteLine("============================ Load using Serializer ============================"); Config config = null; string jsonConfigFile = Path.Combine(configFolder, "config.json"); using (StreamReader reader = new StreamReader(jsonConfigFile)) using (JsonReader jsonReader = new JsonTextReader(reader)) { config = jsonSerializer.Deserialize <Config>(jsonReader); Console.WriteLine("Load {0}", jsonConfigFile); Console.WriteLine("config.DataBaseServerAddress = {0}", config.DataBaseServerAddress); } Console.WriteLine("============================ Reflection: show object ============================"); ReflectionUtil.ShowObjectStruct(new Point <double>()); Point <int> point = new Point <int>(); ReflectionUtil.SetFieldValue(point, "X", "10"); ReflectionUtil.ShowObjectStruct(point); Console.ReadLine(); }
static void Main(string[] args) { /* MyFormatter serializer = new MyFormatter(); * Class3 c3 = new Class3(DateTime.Now, null); * Class2 c2 = new Class2("content", c3); * Class1 c1 = new Class1(20, c2); * c3.refC1 = c1; * Stream stream = File.Open("sample.dat", FileMode.Create); * serializer.Serialize(stream, c1); * stream.Close(); * Stream stream_reader = File.Open("sample.dat", FileMode.Open); * object o = serializer.Deserialize(stream_reader); * stream.Close();*/ bool filled_in = false; LibraryManager libraryManager = new LibraryManager(new DataRepository()); Class3 c3 = new Class3(DateTime.Now, null); Class2 c2 = new Class2("content", c3); Class1 c1 = new Class1(20, c2); bool cont = true; string filename = "serialization.xml"; string menu1 = "1) Serializacja XML\n2) Serializacja wlasna\n3) Deserializacja XML\n4) Deserializacja wlasna\n5) Manager Info\n6) SampleClass Info\n0) Koniec\n"; string komunikat = ""; string output; c3.refC1 = c1; char input = 'c'; while (cont) { Console.Clear(); output = komunikat + menu1 + "Wybor: "; komunikat = ""; Console.WriteLine(output); input = Console.ReadKey().KeyChar; Console.WriteLine(); switch (input) { case '1': if (!filled_in) { Console.WriteLine("Wypelnic managera gotowymi danymi? [y/n]"); if (Console.ReadKey().KeyChar == 'y') { FillWithSampleData(libraryManager); filled_in = true; } } Console.WriteLine("Podaj nazwe pliku zapisu: "); filename = Console.ReadLine(); MyXmlSerializer.CreateFile(typeof(LibraryManager), libraryManager, filename); komunikat = "Zapisano do " + filename + '\n'; break; case '2': Console.WriteLine("Podaj nazwe pliku zapisu: "); filename = Console.ReadLine(); CustomSerialization.CreateFile(c1, filename); komunikat = "Zapisano do " + filename + '\n'; break; case '3': Console.WriteLine("Podaj nazwe pliku odczytu: "); filename = Console.ReadLine(); libraryManager = (LibraryManager)MyXmlSerializer.ReadFile(typeof(LibraryManager), filename); komunikat = "Odczytano z " + filename + '\n'; break; case '4': Console.WriteLine("Podaj nazwe pliku odczytu: "); filename = Console.ReadLine(); c1 = (Class1)CustomSerialization.ReadFile(filename); komunikat = "Odczytano z " + filename + '\n'; break; case '5': foreach (string s in libraryManager.GetInfo("events")) { komunikat += s + '\n'; } komunikat += '\n'; break; case '6': komunikat = c1.ToString() + '\n'; break; case '0': cont = false; break; } } }
public static void Serialize(Type type, XmlWriter writer, object obj) { MyXmlSerializer serializer = GetSerializerFromList(type); serializer.Serialize(writer, obj); }
protected void Page_Load(object sender, EventArgs e) { string path = Server.MapPath("~/App_Data/WebSet/WebSet.xml"); webSet = MyXmlSerializer <WebSet> .Get(path); }
public static object Deserialize(Type type, Stream s) { MyXmlSerializer serializer = GetSerializerFromList(type); return(serializer.Deserialize(s)); }
private byte[] SerializeContent(object obj) { return(MyXmlSerializer.Serialize(obj, MyPublicationSession.namespaces)); }