Serialize() public method

public Serialize ( Stream stream, object o ) : void
stream Stream
o object
return void
Ejemplo n.º 1
0
 public static void Write(string file, Map overview)
 {
     if (string.IsNullOrEmpty(file))
         throw new Exception("File Not Empty");
     System.Xml.Serialization.XmlSerializer writer =
     new System.Xml.Serialization.XmlSerializer(typeof(Map));
     System.Xml.XmlWriterSettings setting = new System.Xml.XmlWriterSettings();
     setting.Encoding = Encoding.UTF8;
     setting.CloseOutput = true;
     setting.NewLineChars = "\r\n";
     setting.Indent = true;
     if (!File.Exists(file))
     {
         using (Stream s = File.Open(file, FileMode.OpenOrCreate))
         {
             System.Xml.XmlWriter tmp = System.Xml.XmlWriter.Create(s, setting);
             writer.Serialize(tmp, overview);
         }
     }
     else
     {
         using (Stream s = File.Open(file, FileMode.Truncate))
         {
             System.Xml.XmlWriter tmp = System.Xml.XmlWriter.Create(s, setting);
             writer.Serialize(tmp, overview);
         }
     }
 }
        static void Main(string[] args)
        {
            Person p = new Person
            {
                FirstName = "Bart",
                MiddleName = "A",
                LastName = "Simpson"
            };

            XmlSerializer x = new XmlSerializer(p.GetType());
            x.Serialize(Console.Out, p);

            var outputFile = $"Person.xml";
            using (var fs = new FileStream(outputFile, FileMode.OpenOrCreate))
            {
                x.Serialize(fs, p);
            }
            using (var fs = new FileStream(outputFile, FileMode.OpenOrCreate))
            {
                var deserialize = (Person)x.Deserialize(fs);
            }

            Console.WriteLine();
            Console.ReadLine();
        }
        protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            var orderSerializer = new XmlSerializer(typeof(PurchaseOrderType));
            var ordersSerializer = new XmlSerializer(typeof(PurchaseOrdersType));

            var responseMessage = new HttpResponseMessage();
            var stream = new MemoryStream();
            var localPath = request.RequestUri.LocalPath;

            // GET /orders/notshipped
            if (localPath.EndsWith("/orders/notshipped"))
                ordersSerializer.Serialize(stream, repository.GetNotShipped());

            // GET /orders/shipped
            if (localPath.EndsWith("/orders/shipped"))
                ordersSerializer.Serialize(stream, repository.GetShipped());

            // POST /orders/{id}/ship
            if (localPath.EndsWith("/ship") && request.Method == HttpMethod.Post)
            {
                var shipUrl = localPath;
                var shipId = shipUrl.Replace("/api/orders/", string.Empty).Replace("/ship", string.Empty);
                var shipOrder = repository.Get(shipId);
                shipOrder.shipped = true;
                repository.Update(shipOrder);
            }

            // POST /orders
            if (localPath.EndsWith("/orders") && request.Method == HttpMethod.Post)
            {
                var result = request.Content.ReadAsByteArrayAsync().GetAwaiter().GetResult();
                var xml = Encoding.UTF8.GetString(result);
                var newOrder = (PurchaseOrderType)orderSerializer.Deserialize(new StringReader(xml));
                repository.Add(newOrder);
            }

            // PUT /orders
            if (request.Method == HttpMethod.Put)
            {
                var result = request.Content.ReadAsByteArrayAsync().GetAwaiter().GetResult();
                var xml = Encoding.UTF8.GetString(result);
                var orderToUpdate = (PurchaseOrderType)orderSerializer.Deserialize(new StringReader(xml));
                repository.Update(orderToUpdate);
            }

            if (request.Method == HttpMethod.Get && !localPath.EndsWith("/orders") && !localPath.EndsWith("/orders/") && !localPath.EndsWith("shipped"))
            {
                // GET /orders/{id}
                var url = localPath;
                var id = url.Replace("/api/orders/", string.Empty);
                var order = repository.Get(id);
                orderSerializer.Serialize(stream, order);
            }

            var content = Encoding.UTF8.GetString(stream.GetBuffer());
            content = content.Substring(content.IndexOf(Environment.NewLine) + 1);
            responseMessage.Content = new StringContent(content, Encoding.UTF8, "application/xml");

            return Task.FromResult(responseMessage);
        }
        public void ParseTracker()
        {
            var generator = new Generator();
            generator.Settings.ContextNaming = ContextNaming.Preserve;
            generator.Settings.EntityNaming = EntityNaming.Singular;
            generator.Settings.RelationshipNaming = RelationshipNaming.ListSuffix;
            generator.Settings.TableNaming = TableNaming.Singular;

            var selector = GetDatabaseSchema("Tracker");
            Assert.IsNotNull(selector);

            EntityContext entityContext = generator.Generate(selector);

            Assert.IsNotNull(entityContext);

            var settings = new XmlWriterSettings { Indent = true };
            var serializer = new XmlSerializer(typeof(EntityContext));

            using (var writer = XmlWriter.Create(@"..\..\Tracker.Generated.xml", settings))
                serializer.Serialize(writer, entityContext);

            string contextDirectory = @"..\..\..\Tracker.Core";
            string mappingDirectory = @"..\..\..\Tracker.Core\Mapping";

            Synchronizer.UpdateFromSource(entityContext, contextDirectory, mappingDirectory);

            using (var writer = XmlWriter.Create(@"..\..\Tracker.Updated.xml", settings))
                serializer.Serialize(writer, entityContext);
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Sessions the info to string.
        /// </summary>
        /// <param name="sessionInfo">The session info.</param>
        /// <returns></returns>
        public static string SessionInfoToString(SessionInfo sessionInfo)
        {
            if (sessionInfo == null)
                return null;

            StringBuilder sb = new StringBuilder();
            StringWriter sw = new StringWriter(sb);

            XmlSerializer xml = new XmlSerializer(typeof(SessionInfo));
            xml.Serialize(sw, sessionInfo);
            sw.Flush();

            CryptoString cry = new CryptoString(_key, CryptoString.Method.Encrypt, sb.ToString());
            string ret = cry.Execute();
            sb.Remove(0, sb.Length);
            if (Regex.IsMatch(ret, @".*[Oo][Nn][a-zA-Z]*=*$"))
            {
                sessionInfo.ConnectionString += ';';
                xml.Serialize(sw, sessionInfo);
                sw.Flush();
                cry = new CryptoString(_key, CryptoString.Method.Encrypt, sb.ToString());
                ret = cry.Execute();
            }

            sw.Close();
            return ret;
        }
		public void Can_serialize_object()
		{
			var testObject = GetTestObject();
			var xmlSerializer = new XmlSerializer<TestObject>();
			Assert.DoesNotThrow(() =>xmlSerializer.Serialize(testObject));
			var xPathNavigable = xmlSerializer.Serialize(testObject) as XmlDocument;
			Assert.That(xPathNavigable, Is.Not.Null);
		}
Ejemplo n.º 7
0
        public void UpdateManufacturingSpec()
        {
            // [1] check xml exists
            // [2] deserialize xml file to a manufacturingDetail object
            // [3] update manufacturingDetail object with ManufacturingParamters objects
            // [4] serialize manufacturingDetail object
            char[] charsToTrim = { '{', '}' };
            string fileName = this.GUID.Trim(charsToTrim) + ".xml";

            if (!File.Exists(Location))
            {
                Trace.TraceError("Error: " + Location + " not found!");
                return;
            }

            if (!Directory.Exists(this.NewLocation))
                Directory.CreateDirectory(this.NewLocation);

            if (ManufacturingParamters.Count() > 0)             // update xml
            {
                XmlSerializer mfgDetails_Serializer = new XmlSerializer(typeof(Part.manufacturingDetails));
                Part.manufacturingDetails mfdetail = Part.manufacturingDetails.Deserialize(Location);
                StringWriter sw = new StringWriter();
                sw.NewLine = "";
                mfgDetails_Serializer.Serialize(sw, mfdetail);
                string xmldatastring = sw.ToString();

                try
                {
                    foreach (KeyValuePair<string, string> item in ManufacturingParamters)
                    {
                        xmldatastring = ReplaceParameters(item.Key, item.Value, xmldatastring);
                    }

                    var strreader = new StringReader(xmldatastring);
                    Part.manufacturingDetails mfdetails_revised = (Part.manufacturingDetails)mfgDetails_Serializer.Deserialize(strreader);

                    if (!Directory.Exists(this.NewLocation))
                        Directory.CreateDirectory(this.NewLocation);
                    StreamWriter myWriter = new StreamWriter(Path.Combine(this.NewLocation, fileName));
                    mfgDetails_Serializer.Serialize(myWriter, mfdetails_revised);


                    Trace.TraceInformation("Info: Updated manufacturing xml with manufacturing parameter from model. " + this.NewLocation + "\\" + fileName);
                }
                catch (System.InvalidOperationException ex)
                {
                    Console.WriteLine("Exception occured: {0}", ex.ToString());
                }

            }
            else                                   // copy the xml
            {
                File.Copy(Location, Path.Combine(this.NewLocation, fileName), true);
                Trace.TraceInformation("Info: Copied manufacturing xml. " + this.NewLocation + "\\" + fileName);
            }
        }
Ejemplo n.º 8
0
		public void Test()
		{
			var serializer = new XmlSerializer(typeof(Quiz));
			var quiz = new Quiz
			{
				Title = "Title",
				Id = "Id",
				Blocks = new SlideBlock[]
				{
					new MdBlock {Markdown = "This is quiz!"},
					new IsTrueBlock
					{
						Id = "1",
						Text = "Это утверждение ложно",
					},
					new ChoiceBlock
					{
						Text = "What is the \nbest color?",
						Items = new[]
						{
							new ChoiceItem {Id="1", Description = "black", IsCorrect = true},
							new ChoiceItem {Id="2", Description = "green"},
							new ChoiceItem {Id="3", Description = "red"},
						}
					},
					new ChoiceBlock
					{
						Multiple = true,
						Text = "What does the fox say?",
						Items = new[]
						{
							new ChoiceItem {Description = "Apapapapa", IsCorrect = true},
							new ChoiceItem {Description = "Ding ding ding", IsCorrect = true},
							new ChoiceItem {Description = "Mew"},
						}
					},
					new FillInBlock
					{
						Text = "What does the fox say?",
						Regexes = new[] {new RegexInfo {Pattern = "([Dd]ing )+"}, new RegexInfo {Pattern = "Ap(ap)+"}},
						Sample = "Apapap"
					},
				}
			};
			var w1 = new StringWriter();
			var ns = new XmlSerializerNamespaces();
			ns.Add("x", "http://www.w3.org/2001/XMLSchema-instance");
			serializer.Serialize(w1, quiz, ns);
			ApprovalTests.Approvals.Verify(w1.ToString());
			Console.WriteLine(w1.ToString());
			Console.WriteLine();
			var quiz2 = serializer.Deserialize(new StringReader(w1.ToString()));
			var w2 = new StringWriter();
			serializer.Serialize(w2, quiz2, ns);
			Console.WriteLine(w2.ToString());
			Assert.AreEqual(w1.ToString(), w2.ToString());
		}
Ejemplo n.º 9
0
        public void FolderPollInitTest()
        {
            FolderPollConfig testConfig = new FolderPollConfig
            {
                Poll = new Poll[]
                {
                    new Poll
                    {
                        Domain = "domain",
                        Folder = @"C:\FolderPoll",
                        Impersonation = true,
                        Username = "******",
                        Password = "******",
                        NewFile = new NewFile
                        {
                            Filter = "*.txt",
                            Copy = new NewFileCopy
                            {
                                TargetFolder = @"C:\FolderPoll"
                            },
                            Move = new NewFileMove
                            {
                                TargetFolder = @"C:\FolderPoll"
                            },
                            Launch = new NewFileLaunch
                            {
                                Application = @"C:\Windows\notepad.exe",
                                Arguments = "{0}"
                            }
                        }
                    }
                }
            };

            var serializer = new XmlSerializer(typeof(FolderPollConfig));
            TextWriter streamWriter = new StreamWriter(@"C:\FolderPoll\testConfig.xml");
            serializer.Serialize(streamWriter, testConfig);
            streamWriter.Close();

            XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
            ns.Add(string.Empty, string.Empty);
            StringWriter stringWriter = new StringWriter();
            serializer.Serialize(stringWriter, testConfig, ns);
            stringWriter.GetStringBuilder().ToString();

            var fileInitObject = new FolderPollService();
            fileInitObject.Init(@"C:\FolderPoll\testConfig.xml", true);
            var stringInitObject = new FolderPollService();
            stringInitObject.Init(stringWriter.GetStringBuilder().ToString(), false);

            var privateFileInit = new PrivateObject(fileInitObject);
            var privateStringInit = new PrivateObject(stringInitObject);

            Assert.IsNotNull(privateFileInit.GetField("folderPoll"));
            Assert.IsNotNull(privateStringInit.GetField("folderPoll"));
        }
Ejemplo n.º 10
0
        public void WriteXml(XmlWriter writer)
        {
            XmlSerializer strSerializer = new XmlSerializer(typeof(string));
            XmlSerializer epcSerializer = new XmlSerializer(typeof(EffectParamCategory));
            Type paramType = Type.GetType(ValueTypeFullName);
            XmlSerializer objSerializer = new XmlSerializer(paramType);

            strSerializer.Serialize(writer, Name);
            epcSerializer.Serialize(writer, Category);
            strSerializer.Serialize(writer, ValueTypeFullName);
            objSerializer.Serialize(writer, Value);
        }
Ejemplo n.º 11
0
        public static void Main(string[] args)
        {
            // If initial value is the same as DefaultValueAttribute for variable declaration, 
            // it is not persisted by XmlSerializer.
            Clue clue = new Clue();
            clue.text = "Nothing To See Here";

            // Buffer for writing.
            StringBuilder buffer = new StringBuilder();

            // Don't need namespaces.
            XmlSerializerNamespaces no_namespaces = new XmlSerializerNamespaces();
            no_namespaces.Add(string.Empty, string.Empty);

            // Don't need xml declaration.
            XmlWriterSettings writer_settings = new XmlWriterSettings() { OmitXmlDeclaration = true };

            // Serialise the clue...
            XmlSerializer xml_serializer = new XmlSerializer(typeof(Clue));
            StringWriter string_writer = new StringWriter(buffer);
            using (XmlWriter xml_writer = XmlWriter.Create(string_writer, writer_settings))
            {
                xml_serializer.Serialize(xml_writer, clue, no_namespaces);
            }

            string serialized = buffer.ToString();

            // Show serialised version of the clue...
            Console.WriteLine("Clue text value: {0}", clue.text);
            Console.WriteLine("Clue serialized: {0}", serialized);

            // Deserialise the clue...
            Clue clue_read;
            using (StringReader sr = new StringReader(serialized))
            {
                clue_read = (Clue)xml_serializer.Deserialize(sr);
            }

            // Show clue 2 on console
            // Reset and reuse write buffer.
            buffer.Length = 0;
            using (XmlWriter xml_writer = XmlWriter.Create(string_writer, writer_settings))
            {
                xml_serializer.Serialize(xml_writer, clue_read, no_namespaces);
            }

            string reserialized = buffer.ToString();
            Console.WriteLine("Read Clue text value: {0}", clue_read.text);
            Console.WriteLine("Read Clue serialized: {0}", reserialized);

            Debug.Assert(clue.text == clue_read.text, "Written & read clue's text should match");
        }
Ejemplo n.º 12
0
 void IXmlSerializable.WriteXml(XmlWriter writer)
 {
     XmlSerializer ss = new XmlSerializer(typeof(string));
     writer.WriteStartElement("name");
     ss.Serialize(writer, Name);
     writer.WriteEndElement();
     writer.WriteStartElement("type");
     ss.Serialize(writer, Value.GetType().AssemblyQualifiedName);
     writer.WriteEndElement();
     writer.WriteStartElement("value");
     new XmlSerializer(Value.GetType()).Serialize(writer, Value);
     writer.WriteEndElement();
 }
Ejemplo n.º 13
0
        private static void SerializationTest()
        {
            Person p1 = new Person() { Name = "Person 1", Age = 20 };
            Person p2 = new Person() { Name = "Person 2", Age = 60 };

            XmlSerializer serializer = new XmlSerializer(typeof(Person));
            serializer.Serialize(Console.OpenStandardOutput(), p1);

            Console.WriteLine();
            Console.WriteLine();

            serializer.Serialize(Console.OpenStandardOutput(), p2);
        }
Ejemplo n.º 14
0
 static void Main()
 {
     bool groups_directory_exist = false;
     bool subjects_directory_exist = false;
     DirectoryInfo current_dir_info = new DirectoryInfo(Environment.CurrentDirectory);
     foreach (DirectoryInfo cur_dir_info in current_dir_info.GetDirectories())
     {
         if (cur_dir_info.Name == "all_subjects")
         {
             subjects_directory_exist = true;
         }
         if (cur_dir_info.Name == "all_groups")
         {
             groups_directory_exist = true;
         }
     }
     if (!subjects_directory_exist)
     {
         List<subject> test_list_of_subjects = new List<subject>();
         test_list_of_subjects.Add(new subject("mathematics", new List<string> { "math_theme_1", "math_theme_2", "math_theme_3" }));
         test_list_of_subjects.Add(new subject("physics", new List<string> { "phys_theme_1", "phys_theme_2", "phys_theme_3" }));
         test_list_of_subjects.Add(new subject("biology", new List<string> { "bio_theme_1", "bio_theme_2", "bio_theme_3" }));
         Directory.CreateDirectory("all_subjects");
         XmlSerializer serializer_for_subjects = new XmlSerializer(typeof(List<subject>));
         FileStream stream_to_subjects = new FileStream(@"all_subjects\all_subjects.xml",
              FileMode.Create, FileAccess.Write);
         serializer_for_subjects.Serialize(stream_to_subjects, test_list_of_subjects);
         stream_to_subjects.Close();
     }
     if (!groups_directory_exist)
     {
         group test_group = new group("TEST_GROUP_1", new List<student> {new student("first_student_1"),
            new student("second_student_1"),new student("third_student_1")});
         group test_group_2 = new group("TEST_GROUP_2", new List<student> {new student("first_student_2"),
            new student("second_student_2"),new student("third_student_2")});
         Directory.CreateDirectory(@"all_groups\" + test_group.name_of_group + @"\all_lessons");
         Directory.CreateDirectory(@"all_groups\" + test_group_2.name_of_group + @"\all_lessons");
         FileStream stream_to_groups = new FileStream(@"all_groups\" + test_group.name_of_group +
             @"\" + test_group.name_of_group + ".xml", FileMode.Create, FileAccess.Write);
         XmlSerializer serializer_for_groups = new XmlSerializer(typeof(group));
         serializer_for_groups.Serialize(stream_to_groups, test_group);
         stream_to_groups.Close();
         FileStream stream_to_groups_2 = new FileStream(@"all_groups\" + test_group_2.name_of_group +
             @"\" + test_group_2.name_of_group + ".xml", FileMode.Create, FileAccess.Write);
         serializer_for_groups.Serialize(stream_to_groups_2, test_group_2);
         stream_to_groups_2.Close();
     }
     Application.EnableVisualStyles();
     Application.SetCompatibleTextRenderingDefault(false);
     Application.Run(new Form1());
 }
        private static void ConvertObjectToXml(PhoneBook phoneBook)
        {
            XmlSerializer xmlSerializer = new XmlSerializer(typeof(PhoneBook)); // it's better to use Form.GetType() for generics

            // save to file on the hard drive
            StreamWriter streamWriter = new StreamWriter("XML/PhoneBookRecreated.xml");
            xmlSerializer.Serialize(streamWriter, phoneBook);

            // example how to convert to string, instead of file (for debug purposes)
            using (StringWriter stringWriter = new StringWriter())
            {
                xmlSerializer.Serialize(stringWriter, phoneBook);
                string s = stringWriter.ToString();
            }
        }
        /// <summary>
        /// Test whether the constraint is satisfied by a given value
        /// </summary>
        /// <param name="actual">The value to be tested</param>
        /// <returns>True for success, false for failure</returns>
        public override bool Matches(object actual)
        {
            this.actual = actual;

            if(actual == null)
                throw new ArgumentException();

            MemoryStream stream = new MemoryStream();

            try
            {
                serializer = new XmlSerializer(actual.GetType());

                serializer.Serialize(stream, actual);

                stream.Seek(0, SeekOrigin.Begin);

                object value = serializer.Deserialize(stream);

                return value != null;
            }
            catch (NotSupportedException)
            {
                return false;
            }
            catch (InvalidOperationException)
            {
                return false;
            }
        }
Ejemplo n.º 17
0
        private void MediaProfilesTreeViewInit()
        {
            XmlSerializer serialization = new XmlSerializer(mediaProfiles.GetType());

            MemoryStream memory = new MemoryStream();
            try
            {
                serialization.Serialize(memory, mediaProfiles);
                memory.Seek(0, System.IO.SeekOrigin.Begin);

                XmlDocument xml = new XmlDocument();
                xml.Load(memory);

                MediaProfilesTreeView.Nodes.Clear();
                MediaProfilesTreeView.Nodes.Add(new TreeNode(xml.DocumentElement.Name));
                TreeNode node = new TreeNode();
                node = MediaProfilesTreeView.Nodes[0];

                AddNode(xml.DocumentElement, node);
                MediaProfilesTreeView.ExpandAll();
            }
            catch (XmlException ex)
            {
                MessageBox.Show(ex.Message);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                memory.Close();
            }
        }
Ejemplo n.º 18
0
        public static void Serialization1(Human human)
        {
            XmlSerializer serializer = new XmlSerializer(typeof(Human));
            StringBuilder sb = new StringBuilder();

            /* SERIALIZATION */
            using (StringWriter writer = new StringWriter(sb))
            {
                serializer.Serialize(writer, human);
            }
            // XML file
            //Console.WriteLine("SB: " +sb.ToString());
            /* END SERIALIZATION */



            /* DESERIALIZATION */
            Human newMartin = new Human();
            using (StringReader reader = new StringReader(sb.ToString()))
            {
                newMartin = serializer.Deserialize(reader) as Human;
            }
            Console.WriteLine(newMartin.ToString() + Environment.NewLine);
            /* END DESERIALIZATION */
        }
Ejemplo n.º 19
0
        /// <summary>
        /// Analyzes website and creates XML document
        /// </summary>
        /// <param name="config">Website's config</param>
        /// <returns>
        /// Updated website's config
        /// </returns>
        public WebsiteModel AnalyzeWebsite(WebsiteModel config)
        {
            CrawlerHelper crawlHelper = new CrawlerHelper();
            OrganizerHelper orgHelper = new OrganizerHelper();

            config.OrganizerConfig = new OrganizerModel();
            config.ExportConfig = new ExportModel();
            config.ExportConfig.Xml = string.Empty;

            var crawler = crawlHelper.ConfigureCrawler(config.CrawlerConfig);
            var list = crawler.Crawl();

            var analyzer = new WebsiteAnalyzer(config.AnalyzerConfig);
            var analyticsRunner = new AnalyticsRunner(crawler, analyzer);

            var site = analyticsRunner.Run(list);

            site.Name = config.Name;

            using (var sw = new StringWriter())
            {
                var serializer = new XmlSerializer(typeof(Site));
                serializer.Serialize(sw, site);

                config.ExportConfig.Xml = sw.ToString();
            }
                
            config.OrganizerConfig.Pages = orgHelper.AddChildren(site.Root, site);

            return config;
        }
Ejemplo n.º 20
0
 public static string Serialize(MaterialList mats)
 {
     StringWriter sw = new StringWriter();
     XmlSerializer ser = new XmlSerializer(typeof(MaterialList));
     ser.Serialize(sw, mats);
     return sw.ToString();
 }
        public void Convert(string inputFileName, string outputFileName)
        {
            var deser = new XmlSerializer(typeof(Song));
            Song zigSong;
            using (FileStream stream = new FileStream(inputFileName, FileMode.Open))
            {
                zigSong = (Song)deser.Deserialize(stream);
            }

            var guitarTrack = GetTrack(zigSong);
            if (guitarTrack == null)
            {
                throw new Exception("Couldn't find a guitar track");
            }

            var rsSong = new RsSong();
            AddSongMetadata(rsSong, zigSong);
            AddEbeats(rsSong, zigSong);
            AddNotes(rsSong, zigSong);

            deser = new XmlSerializer(typeof(RsSong));
            using (FileStream stream = new FileStream(outputFileName, FileMode.Create))
            {
                deser.Serialize(stream, rsSong);
            }
        }
Ejemplo n.º 22
0
 public static void ConvertObjectToXml(object obj, string path_to_xml)
 {
   //serialize and persist it to it's file
   FileStream fs = null;
   try
   {
     XmlSerializer ser = new XmlSerializer(obj.GetType());
     new FileInfo(path_to_xml).Directory.Create();
     fs = File.Open(
             path_to_xml,
             FileMode.Create,
             FileAccess.Write,
             FileShare.ReadWrite);
     ser.Serialize(fs, obj);
   }
   catch (Exception ex)
   {
     throw new Exception(
             "Could Not Serialize object to " + path_to_xml,
             ex);
   }
   finally
   {
     fs.Close();
   }
 }
        public override void SaveToDataStore(BlogEngine.Core.DataStore.ExtensionType exType, string exId, object settings)
        {
            XmlSerializer xs = new XmlSerializer(settings.GetType());
            string objectXML = string.Empty;
            using (StringWriter sw = new StringWriter())
            {
                xs.Serialize(sw, settings);
                objectXML = sw.ToString();
            }

            using (var mongo = new MongoDbWr())
            {
                var coll = mongo.BlogDB.GetCollection("DataStoreSettings");

                Document spec = new Document();
                spec["ExtensionType"] = exType;
                spec["ExtensionId"] = exId;

                var res = new Document();
                res["Settings"] = objectXML;
                res["ExtensionType"] = exType;
                res["ExtensionId"] = exId;

                coll.Update(res, spec, UpdateFlags.Upsert);
            }
        }
Ejemplo n.º 24
0
 public void SerializeObject(string path, SerializableObject objToSerialize)
 {
     FileStream fstream = File.Open(path, FileMode.Create);
     XmlSerializer formatter = new XmlSerializer(typeof(SerializableObject));
     formatter.Serialize(fstream, objToSerialize);
     fstream.Close();
 }
        public bool Save()
        {
            IAmazonResponse amazonResponse = amazonFactory.GetResponse();

            XmlSerializer serializer;
            TextWriter writer;

            try
            {
                if (amazonResponse.Errors.Count != 0)
                {
                    serializer = new XmlSerializer(typeof (List<string>));
                    writer = new StreamWriter(fileParameters.ErrorFileNameAndPath);
                    serializer.Serialize(writer, amazonResponse.Errors);
                    writer.Close();
                }

                serializer = new XmlSerializer(typeof (List<Review>));
                writer = new StreamWriter(fileParameters.ReviewFileNameAndPath);
                serializer.Serialize(writer, amazonResponse.Reviews);
                writer.Close();

                serializer = new XmlSerializer(typeof (List<Product>));
                writer = new StreamWriter(fileParameters.ProductFileNameAndPath);
                serializer.Serialize(writer, amazonResponse.Products);
                writer.Close();
            }
            catch
            {
                return false;
            }
            return true;
        }
Ejemplo n.º 26
0
 public void Save()
 {
     var serializer = new XmlSerializer(typeof(Project));
     var writer = new StreamWriter(GetPath(),false, Encoding.UTF8);
     serializer.Serialize(writer, this);
     writer.Close();
 }
Ejemplo n.º 27
0
 /// <summary>
 /// this is something that didnt work out for me but im going to keep it here until we know that we arent going to use it
 /// </summary>
 /// <param name="tree"></param>
 public static void SerializeToXML(Tree tree)
 {
     XmlSerializer serializer = new XmlSerializer(typeof(Tree));
     TextWriter textWriter = new StreamWriter(@"C:\Users\Chris\Desktop\xmlSerializer.xml");
     serializer.Serialize(textWriter, tree);
     textWriter.Close();
 }
Ejemplo n.º 28
0
        public static void SendFileInfo()
        {

            // Получаем тип и расширение файла
            fileDet.FILETYPE = fs.Name.Substring((int)fs.Name.Length - 3, 3);

            // Получаем длину файла
            fileDet.FILESIZE = fs.Length;

            XmlSerializer fileSerializer = new XmlSerializer(typeof(FileDetails));
            MemoryStream stream = new MemoryStream();

            // Сериализуем объект
            fileSerializer.Serialize(stream, fileDet);

            // Считываем поток в байты
            stream.Position = 0;
            Byte[] bytes = new Byte[stream.Length];
            stream.Read(bytes, 0, Convert.ToInt32(stream.Length));

            Console.WriteLine("Отправка деталей файла...");

            // Отправляем информацию о файле
            sender.Send(bytes, bytes.Length, endPoint);
            stream.Close();

        }
        public override bool Execute()
        {
            Log.LogMessage( MessageImportance.Low, "Packing M-Files Application." );

            // Make sure the collections are never null.
            References = References ?? new ITaskItem[ 0 ];
            SourceFiles = SourceFiles ?? new ITaskItem[ 0 ];
            DefaultEnvironments = DefaultEnvironments ?? new string[ 0 ];

            // Create the application package contents.
            var references = References.Select( item => new Reference( item ) ).ToList();
            var files = SourceFiles.Select( item => new PackageFile( item ) ).ToList();

            var appDef = CreateApplicationDefinition( references, files );
            var outputZip = CreatePackage( references, files );

            // Serialize the application definition file.
            var stream = new MemoryStream();
            var serializer = new XmlSerializer( typeof( ApplicationDefinition ) );
            serializer.Serialize( stream, appDef );
            stream.Flush();
            stream.Position = 0;
            outputZip.AddEntry( "appdef.xml", stream );

            // Save the zip.
            outputZip.Save();

            return true;
        }
Ejemplo n.º 30
0
        public override int Run(string[] args)
        {
            string schemaFileName = args[0];
            string outschemaFileName = args[1];

            XmlTextReader xr = new XmlTextReader(schemaFileName);
            SchemaInfo schemaInfo = SchemaManager.ReadAndValidateSchema(xr, Path.GetDirectoryName(schemaFileName));
            schemaInfo.Includes.Clear();
            schemaInfo.Classes.Sort(CompareNames);
            schemaInfo.Relations.Sort(CompareNames);

            XmlSerializer ser = new XmlSerializer(typeof(SchemaInfo));
            XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
            ns.Add("", SchemaInfo.XmlNamespace);

            using (FileStream fs = File.Create(outschemaFileName))
            {
                try
                {
                    ser.Serialize(fs, schemaInfo, ns);
                }
                finally
                {
                    fs.Flush();
                    fs.Close();
                }
            }

            return 0;
        }
        /// <summary>
        /// XML Representation of this object
        /// </summary>
        /// <returns>XML String</returns>
        public string ToXML()
        {
            StringBuilder xml = new StringBuilder(1024);

            System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(this.GetType());
            using (StringWriter sw = new StringWriter(xml))
            {
                serializer.Serialize(sw, this);
            }
            return(xml.ToString());
        }
        void saveBasePosList()
        {
            // save config
            System.Xml.Serialization.XmlSerializer writer =
                new System.Xml.Serialization.XmlSerializer(typeof(List <PointLatLngAlt>), new Type[] { typeof(Color) });

            using (StreamWriter sw = new StreamWriter(basepostlistfile))
            {
                writer.Serialize(sw, baseposList);
            }
        }
Ejemplo n.º 33
0
        public static String SerializeObject(Object pObject, Type type)
        {
            String XmlizedString = null;

            System.IO.MemoryStream memoryStream       = new System.IO.MemoryStream();
            System.Xml.Serialization.XmlSerializer xs = new System.Xml.Serialization.XmlSerializer(type);
            System.Xml.XmlTextWriter xmlTextWriter    = new System.Xml.XmlTextWriter(memoryStream, Encoding.UTF8);
            xs.Serialize(xmlTextWriter, pObject);
            memoryStream  = (System.IO.MemoryStream)xmlTextWriter.BaseStream;
            XmlizedString = YellowstonePathology.YpiConnect.Client.Helper.SerializationHelper.UTF8ByteArrayToString(memoryStream.ToArray());
            return(XmlizedString.Substring(1, XmlizedString.Length - 1));
        }
Ejemplo n.º 34
0
 /// <summary>
 /// 创建XML
 /// </summary>
 /// <param name="savePath">保存路径</param>
 /// <param name="targetObjcet">要储存的对象</param>
 /// <param name="targetType">类型</param>
 /// <param name="xmlRootName">根节点名称</param>
 public void CreateXml(string savePath, object targetObjcet, Type targetType, string xmlRootName)
 {
     if (!string.IsNullOrEmpty(savePath) && targetObjcet != null)
     {
         targetType = targetType ?? targetObjcet.GetType();
         using (StreamWriter writer = new StreamWriter(savePath))
         {
             System.Xml.Serialization.XmlSerializer xmlSerializer = string.IsNullOrEmpty(xmlRootName) ? new System.Xml.Serialization.XmlSerializer(targetType) : new System.Xml.Serialization.XmlSerializer(targetType, new XmlRootAttribute(xmlRootName));
             xmlSerializer.Serialize(writer, targetObjcet);
         }
     }
 }
Ejemplo n.º 35
0
        /// <summary>
        /// Serialize the object as XML
        /// </summary>
        /// <param name="obj">Object to serialize</param>
        /// <returns>XML as string</returns>
        public string Serialize <T>(object obj)
        {
            var ns = new XmlSerializerNamespaces();

            ns.Add(string.Empty, Namespace);
            var serializer = new System.Xml.Serialization.XmlSerializer(typeof(T), STNXmlSerializerCodec.extraTypes);
            var writer     = new EncodingStringWriter(Encoding);

            serializer.Serialize(writer, obj, ns);

            return(writer.ToString());
        }
Ejemplo n.º 36
0
        /*
         * public MIGServiceConfiguration.Interface GetInterface(string domain)
         * {
         *  MIGServiceConfiguration.Interface res = MIGService.Interfaces.Find(i => i.Domain == domain);
         *  return res;
         * }
         *
         * public MIGServiceConfiguration.Interface.Option GetInterfaceOption(string domain, string option)
         * {
         *  return GetInterfaceOptions(domain).Find(o => o.Name == option);
         * }
         *
         * public List<MIGServiceConfiguration.Interface.Option> GetInterfaceOptions(string domain)
         * {
         *  MIGServiceConfiguration.Interface mi = MIGService.Interfaces.Find(i => i.Domain == domain);
         *  return mi.Options;
         * }
         */

        public bool Update()
        {
            bool success = false;

            try
            {
                SystemConfiguration syscopy = (SystemConfiguration)this.Clone();
                foreach (ModuleParameter p in syscopy.HomeGenie.Settings)
                {
                    try
                    {
                        if (!String.IsNullOrEmpty(p.Value))
                        {
                            p.Value = StringCipher.Encrypt(p.Value, GetPassPhrase());
                        }
                        if (!String.IsNullOrEmpty(p.LastValue))
                        {
                            p.LastValue = StringCipher.Encrypt(
                                p.LastValue,
                                GetPassPhrase()
                                );
                        }
                    }
                    catch
                    {
                    }
                }


                string fname = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "systemconfig.xml");
                if (File.Exists(fname))
                {
                    File.Delete(fname);
                }
                System.Xml.XmlWriterSettings ws = new System.Xml.XmlWriterSettings();
                ws.Indent = true;
                System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(syscopy.GetType());
                System.Xml.XmlWriter wri = System.Xml.XmlWriter.Create(fname, ws);
                x.Serialize(wri, syscopy);
                wri.Close();
                success = true;
            }
            catch (Exception)
            {
            }
            //
            if (OnUpdate != null)
            {
                OnUpdate(success);
            }
            //
            return(success);
        }
Ejemplo n.º 37
0
        public static String SerializeObject <T>(T o)
        {
            String XmlizedString = null;

            System.IO.MemoryStream memoryStream       = new System.IO.MemoryStream();
            System.Xml.Serialization.XmlSerializer xs = new System.Xml.Serialization.XmlSerializer(typeof(T));
            System.Xml.XmlTextWriter xmlTextWriter    = new System.Xml.XmlTextWriter(memoryStream, Encoding.UTF8);
            xs.Serialize(xmlTextWriter, o);
            memoryStream  = (System.IO.MemoryStream)xmlTextWriter.BaseStream;
            XmlizedString = UTF8ByteArrayToString(memoryStream.ToArray());
            return(XmlizedString.Substring(1, XmlizedString.Length - 1));
        }
Ejemplo n.º 38
0
        public static void WriteLogEntryToClusterDirectory(ClusterSubmitterArgs clusterArgs)
        {
            string   directory = clusterArgs.ExternalRemoteDirectoryName;
            string   filename  = LogEntryFileName(clusterArgs.Name);
            LogEntry logEntry  = new LogEntry(clusterArgs);

            System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(LogEntry));
            using (var writer = File.Create(directory + "\\" + filename))
            {
                serializer.Serialize(writer, logEntry);
            }
        }
Ejemplo n.º 39
0
        public static void WriteXML(ListOfDoctors docs)
        {
            System.Xml.Serialization.XmlSerializer writer =
                new System.Xml.Serialization.XmlSerializer(typeof(ListOfDoctors));

            var path = Environment.CurrentDirectory + "//SerializationOverview.xml";

            System.IO.FileStream file = System.IO.File.Create(path);

            writer.Serialize(file, docs);
            file.Close();
        }
Ejemplo n.º 40
0
        /// <summary>
        /// Serialize the object as XML
        /// </summary>
        /// <param name="obj">Object to serialize</param>
        /// <returns>XML as string</returns>
        public string Serialize(object obj)
        {
            var ns = new XmlSerializerNamespaces();

            ns.Add(string.Empty, Namespace);
            var serializer = new System.Xml.Serialization.XmlSerializer(obj.GetType());
            var writer     = new EncodingStringWriter(Encoding);

            serializer.Serialize(writer, obj, ns);

            return(writer.ToString());
        }
Ejemplo n.º 41
0
        public static string Serialize(object obj)
        {
            using (var sww = new StringWriter()) {
                var xml = new System.Xml.Serialization.XmlSerializer(obj.GetType());
                xml.Serialize(sww, obj);

                var xmlString = sww.ToString();
                xmlString = xmlString.Replace("\"", Quota);

                return(xmlString);
            }
        }
Ejemplo n.º 42
0
        /// <summary>
        /// xml序列成字符串
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="entity"></param>
        /// <returns></returns>
        public static string XMLSerialize <T>(T entity)
        {
            StringBuilder buffer = new StringBuilder();

            System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(T));
            using (TextWriter writer = new StringWriter(buffer))
            {
                serializer.Serialize(writer, entity);
            }

            return(buffer.ToString());
        }
Ejemplo n.º 43
0
 /// <summary>
 /// Serialize object to XElement.
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <param name="obj">Object to serialize.</param>
 /// <returns></returns>
 public static XElement ToXElement <T>(T obj)
 {
     using (var memoryStream = new MemoryStream())
     {
         using (TextWriter streamWriter = new StreamWriter(memoryStream))
         {
             var xmlSerializer = new XmlSer.XmlSerializer(typeof(T));
             xmlSerializer.Serialize(streamWriter, obj);
             return(XElement.Parse(Encoding.UTF8.GetString(memoryStream.ToArray())));
         }
     }
 }
Ejemplo n.º 44
0
        public string Serialize(TModel model)
        {
            XmlSerializer xmlSerializer = new XmlSerializer(type);

            using (TextWriter textWriter = new StringWriter())
            {
                xmlSerializer.Serialize(textWriter, model);

                String result = textWriter.ToString();
                return(result);
            }
        }
Ejemplo n.º 45
0
        static public Stream ToKml(IFeatureCursor cursor, int maxFeatures)
        {
            KmlType kml = new KmlType();

            DocumentType document = new DocumentType();

            kml.Item = document;

            int                  counter    = 0;
            IFeature             feature    = null;
            List <PlacemarkType> placemarks = new List <PlacemarkType>();

            while ((feature = cursor.NextFeature) != null)
            {
                if (feature.Shape == null)
                {
                    continue;
                }

                PlacemarkType placemark = new PlacemarkType();
                placemark.Item_ = ToKml(feature.Shape);

                placemarks.Add(placemark);
                counter++;
                if (counter >= maxFeatures)
                {
                    break;
                }
            }

            document.Items_ = placemarks.ToArray();

            #region Serialize
            System.Xml.Serialization.XmlSerializerNamespaces namespaces = new System.Xml.Serialization.XmlSerializerNamespaces();

            //namespaces.Add("wps", "http://www.opengis.net/wps/1.0.0");
            //namespaces.Add("ows", "http://www.opengis.net/ows/1.1");
            //namespaces.Add("xlink", "http://www.w3.org/1999/xlink");
            //namespaces.Add("xsi", "http://www.w3.org/2001/XMLSchema-instance");

            MemoryStream  ms  = new MemoryStream();
            XmlSerializer ser = new System.Xml.Serialization.XmlSerializer(kml.GetType());
            ser.Serialize(ms, kml, namespaces);
            ms.Position = 0;
            return(ms);

            //byte[] bytes = new byte[ms.Length];
            //ms.Position = 0;
            //ms.Read(bytes, 0, (int)ms.Length);

            //return System.Text.Encoding.UTF8.GetString(bytes);
            #endregion
        }
Ejemplo n.º 46
0
        public void WriteXML()
        {
            System.Xml.Serialization.XmlSerializer writer =
                new System.Xml.Serialization.XmlSerializer(typeof(OrderDetails));

            var path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "//SerializationOverview.xml";

            System.IO.FileStream file = System.IO.File.Create(path);

            writer.Serialize(file, this);
            file.Close();
        }
Ejemplo n.º 47
0
        /// <summary>
        /// This methods creates xml for this control or those inheriting it.
        /// </summary>
        /// <param name="type">the type of the control you want to serialize</param>
        /// <returns>The XML Text</returns>
        public static string SerializeToXML(object obj, Type type)
        {
            var result = new StringBuilder();

            using (System.IO.StringWriter sw = new StringWriter(result))
            {
                System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(type);
                x.Serialize(sw, obj);
            }

            return(result.ToString());
        }
Ejemplo n.º 48
0
 /// <summary>
 /// Serializes the self.
 /// </summary>
 /// <param name="filePath">File path.</param>
 public void SerializeSelf(string filePath)
 {
     System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
     System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(this.GetType());
     using (System.IO.MemoryStream stream = new System.IO.MemoryStream())
     {
         serializer.Serialize(stream, this);
         stream.Position = 0;
         doc.Load(stream);
         doc.Save(filePath);
     }
 }
Ejemplo n.º 49
0
        public static void WriteXml()
        {
            //var testSale = new SalesAggregated() { VendorName = "test vendor", Date = DateTime.Now, TotalSum = 23 };
            var overview = new Book("Serialization Overview");
            var writer   = new System.Xml.Serialization.XmlSerializer(typeof(SalesAggregated));

            var file = new System.IO.StreamWriter(
                @"c:\temp\SerializationOverview.xml");

            writer.Serialize(file, overview);
            file.Close();
        }
Ejemplo n.º 50
0
    public void SavePlayer()
    {
        System.Xml.Serialization.XmlSerializer writer = new System.Xml.Serialization.XmlSerializer(typeof(PlayerInfo));

        var path = "PlayerSave" + ".xml";

        System.IO.FileStream file = System.IO.File.Create(path);
        PlayerInfo           pi   = new PlayerInfo(Goods, Money);

        writer.Serialize(file, pi);
        file.Close();
    }
Ejemplo n.º 51
0
            public static void SaveAll(List <LocalSettings> settings, string filename)
            {
                string asmPath      = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
                string settingsPath = Path.Combine(asmPath, filename);

                System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(List <LocalSettings>));

                using (TextWriter writer = File.CreateText(settingsPath))
                {
                    serializer.Serialize(writer, settings);
                }
            }
Ejemplo n.º 52
0
 public static string SerializeObject(object obj)
 {
     System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();
     System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(obj.GetType());
     using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
     {
         serializer.Serialize(ms, obj);
         ms.Position = 0;
         xmlDoc.Load(ms);
         return(xmlDoc.InnerXml);
     }
 }
Ejemplo n.º 53
0
 public static void SerializeToFile <T>(T info, string fileFullName)
 {
     if (info == null)
     {
         return;
     }
     using (XmlWriter writer = XmlWriter.Create(fileFullName))
     {
         System.Xml.Serialization.XmlSerializer xmlSerializer = new System.Xml.Serialization.XmlSerializer(info.GetType());
         xmlSerializer.Serialize(writer, info);
     }
 }
Ejemplo n.º 54
0
        public void TestMethod1()
        {
            file_path = "simple_svr_one_row_one_test.xls";
            full_path = obtain_test_path(file_path);
            Assert.IsTrue(new FileInfo(full_path).Exists);

            // загрузка книги svr
            mc21.svr_viewer.Excel.Load_SVR loaded_svr = new svr_viewer.Excel.Load_SVR(full_path);

            // в книге svr должно быть 14 листов
            Assert.AreEqual(14, loaded_svr.Worksheets.Count);

            // загрузка данных svr
            foreach (System.Data.DataTable dt in loaded_svr.Worksheets)
            {
                m.Fill_Model(dt);
            }

            // получение статистики по данным svr
            m.Obtain_Statictics();
            // инициализация фильтров

            // число позиций в модели должно быть равно 6
            Assert.AreEqual(6, m.Positions.Count);

            // инициализация вью модели отображения SVR
            vm_dysplay_svr = new svr_viewer.ViewModel.Dysplay_SVR_View_Model.Dysplay_SVR_View_Model();

            // число позиций во вьюмодели должно быть равно 6
            Assert.AreEqual(6, vm_dysplay_svr.Query_Dysplay_Checkboxes_Positions.Count);

            // после инициализации фильтров все позиции должын быть включены
            bool isPositionCheckBoxesTurnON = true;

            foreach (mc21.svr_viewer.ViewModel.Checkbox checkbox in vm_dysplay_svr.Query_Dysplay_Checkboxes_Positions)
            {
                if (checkbox.isChecked == false)
                {
                    isPositionCheckBoxesTurnON = false;
                }
                break;
            }
            Assert.IsTrue(isPositionCheckBoxesTurnON);

            // число вариантов результатов выполнения должно быть равно 3
            Assert.AreEqual(3, vm_dysplay_svr.Query_Dysplay_Checkboxes_Results.Count);

            System.Xml.Serialization.XmlSerializer ser = new System.Xml.Serialization.XmlSerializer(typeof(mc21.svr_viewer.ViewModel.Main_ViewModel));
            TextWriter tw = new StreamWriter("blend_data_1.xml");

            ser.Serialize(tw, vm);
            tw.Close();
        }
Ejemplo n.º 55
0
        public static XElement SerializeToElement <T>(T o)
        {
            String XmlizedString = null;

            System.IO.MemoryStream memoryStream       = new System.IO.MemoryStream();
            System.Xml.Serialization.XmlSerializer xs = new System.Xml.Serialization.XmlSerializer(o.GetType());
            System.Xml.XmlTextWriter xmlTextWriter    = new System.Xml.XmlTextWriter(memoryStream, Encoding.UTF8);
            xs.Serialize(xmlTextWriter, o);
            memoryStream  = (System.IO.MemoryStream)xmlTextWriter.BaseStream;
            XmlizedString = UTF8ByteArrayToString(memoryStream.ToArray());
            return(XElement.Parse(XmlizedString.Substring(1, XmlizedString.Length - 1)));
        }
Ejemplo n.º 56
0
        public void Serialize()
        {
            System.Xml.Serialization.XmlSerializer xs
                = new System.Xml.Serialization.XmlSerializer(this.GetType());
            StreamWriter writer = File.CreateText(file);

            xs.Serialize(writer, this);
            writer.Flush();
            writer.Close();

            Logger.Log("Configuration saved");
        }
Ejemplo n.º 57
0
        static void SaveFileFilterGroupToFile(string saveFilePath, FileFilterGroup filterGroup)
        {
            System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(typeof(FileFilterGroup));

            saveFilePath = saveFilePath.Replace("\\", "/");

            System.IO.TextWriter writer = new System.IO.StreamWriter(saveFilePath);
            x.Serialize(writer, filterGroup);
            writer.Close();

            Debug.Log("Build Report Tool: Saved File Filter Group at \"" + saveFilePath + "\"");
        }
Ejemplo n.º 58
0
        /// <summary>
        /// 指定したファイルパスへシリアライズします。
        /// </summary>
        /// <typeparam name="T">自分自身の型</typeparam>
        /// <param name="self">自分自身</param>
        /// <param name="extraTypes">
        /// シリアル化する追加のオブジェクト型の Type 配列。<para/>
        /// シリアル化したい型を設定すると、<see cref="object"/> 型のデータをシリアライズします。
        /// </param>
        /// <param name="filePath">出力先ファイルパス</param>
        public static void Serialize <T>(this T self, string filePath, params Type[] extraTypes)
        {
            var directory = Path.GetDirectoryName(filePath);

            FileUtility.CreateDirectory(directory);

            using (var fs = new FileStream(filePath, FileMode.Create))
            {
                var serializer = new System.Xml.Serialization.XmlSerializer(typeof(T), extraTypes);
                serializer.Serialize(fs, self);
            }
        }
Ejemplo n.º 59
0
 public string SerializeToXml <T>(T obj)
 {
     System.Xml.Serialization.XmlSerializer xmlSerializer = new System.Xml.Serialization.XmlSerializer(typeof(T));
     using (var writer = new StringWriter())
         using (var xmlWriter = XmlWriter.Create(writer, new XmlWriterSettings {
             Indent = true
         }))
         {
             xmlSerializer.Serialize(xmlWriter, obj, null);
             return(writer.ToString());
         }
 }
Ejemplo n.º 60
0
        public static void SaveSoftwares(List <software> list)
        {
            System.Xml.Serialization.XmlSerializer writer =
                new System.Xml.Serialization.XmlSerializer(typeof(List <software>), new Type[] { typeof(software) });

            using (
                StreamWriter sw =
                    new StreamWriter(Application.StartupPath + Path.DirectorySeparatorChar + "fwversions.xml"))
            {
                writer.Serialize(sw, list);
            }
        }