Serialize() public method

public Serialize ( Stream stream, object o ) : void
stream Stream
o object
return void
        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);
        }
        /// <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;
        }
        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();
        }
        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);
        }
Example #5
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);
         }
     }
 }
		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);
		}
Example #7
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());
		}
Example #8
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);
            }
        }
Example #9
0
        public void FolderPollInitTest()
        {
            FolderPollConfig testConfig = new FolderPollConfig
            {
                Poll = new Poll[]
                {
                    new Poll
                    {
                        Domain = "domain",
                        Folder = @"C:\FolderPoll",
                        Impersonation = true,
                        Username = "username",
                        Password = "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"));
        }
Example #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);
        }
Example #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");
        }
Example #12
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);
        }
Example #13
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();
 }
Example #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();
            }
        }
        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;
        }
Example #17
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;
        }
 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 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);
            }
        }
        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;
        }
        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();
            }
        }
Example #22
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();

        }
Example #23
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 */
        }
        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);
            }
        }
Example #25
0
 public static string Serialize(MaterialList mats)
 {
     StringWriter sw = new StringWriter();
     XmlSerializer ser = new XmlSerializer(typeof(MaterialList));
     ser.Serialize(sw, mats);
     return sw.ToString();
 }
Example #26
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();
 }
 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();
   }
 }
Example #28
0
 public void Save()
 {
     var serializer = new XmlSerializer(typeof(Project));
     var writer = new StreamWriter(GetPath(),false, Encoding.UTF8);
     serializer.Serialize(writer, this);
     writer.Close();
 }
        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>
        /// 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;
            }
        }