public Object DeserializeObject(String pXmlizedString)
 {
     XmlSerializer xs = new XmlSerializer(typeof(EntryList));
     MemoryStream memoryStream = new MemoryStream(StringToUTF8ByteArray(pXmlizedString));
     XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);
     return xs.Deserialize(memoryStream);
 }
Beispiel #2
1
 public WMIBMySQL()
 {
     string file = Variables.ConfigurationDirectory + Path.DirectorySeparatorChar + "unwrittensql.xml";
     Core.RecoverFile(file);
     if (File.Exists(file))
     {
         Syslog.WarningLog("There is a mysql dump file from previous run containing mysql rows that were never successfuly inserted, trying to recover them");
         XmlDocument document = new XmlDocument();
         using (TextReader sr = new StreamReader(file))
         {
             document.Load(sr);
             using (XmlNodeReader reader = new XmlNodeReader(document.DocumentElement))
             {
                 XmlSerializer xs = new XmlSerializer(typeof(Unwritten));
                 Unwritten un = (Unwritten)xs.Deserialize(reader);
                 lock (unwritten.PendingRows)
                 {
                     unwritten.PendingRows.AddRange(un.PendingRows);
                 }
             }
         }
     }
     Thread reco = new Thread(Exec) {Name = "MySQL/Recovery"};
     Core.ThreadManager.RegisterThread(reco);
     reco.Start();
 }
        public override TelemetryLap Get(Circuit circuit, string lapType)
        {
            try
            {
                var filename = GetFileName(circuit, lapType);
                if (!File.Exists(filename))
                    return null;

                string fastestLapData = File.ReadAllText(filename);

                using (var reader = new StringReader(fastestLapData))
                {
                    var serializer = new XmlSerializer(typeof (TelemetryLap));
                    using (var xmlReader = new XmlTextReader(reader))
                    {
                        try
                        {
                            var fastestLap = (TelemetryLap) serializer.Deserialize(xmlReader);
                            return fastestLap;
                        }
                        catch
                        {
                        }
                        return null;
                    }
                }
            } catch (Exception ex)
            {
                logger.Error("Could not retreive csv telemetry lap", ex);
                throw ex;
            }
        }
Beispiel #4
0
		public static TriviaMessage Deserialize(string dataReceived)
		{
            /*
bool correctEnding = (dataReceived.EndsWith("</TriviaMessage>"));
if (!correctEnding)
{
	throw new InvalidOperationException("Deserialization will fail...");
}
             */
			XmlSerializer serializer = new XmlSerializer(typeof(TriviaMessage));
			StringReader reader = new StringReader(dataReceived);

			TriviaMessage message = null;

            try
            {
                message = (TriviaMessage)(serializer.Deserialize(reader));
            }
            catch (Exception ex)
            {
                throw new InvalidOperationException(string.Format("Failed to deserialize this data received '{0}'", dataReceived), ex);
            }

			reader.Close();
			
			return message;
		}
        public override void Save(TelemetryLap lap)
        {
            try
            {
                if (lap == null)
                    return;

                var filename = GetFileName(lap);
                if (File.Exists(filename))
                    File.Delete(filename);

                var xmlSer = new XmlSerializer(typeof (TelemetryLap));
                using (var memStm = new MemoryStream())
                {

                    xmlSer.Serialize(memStm, lap);

                    using (var stmR = new StreamReader(memStm))
                    {
                        memStm.Position = 0;
                        File.AppendAllText(filename, stmR.ReadToEnd(), Encoding.UTF8);
                    }
                }
            } catch (Exception ex)
            {
                logger.Error("Could not save xml telemetry lap", ex);
                throw ex;
            }
        }
Beispiel #6
0
        /// <summary>
        /// Initialise the forums element from the server.
        /// </summary>
        private void Initialise()
        {
            string url = string.Format("cix.svc/user/{0}/topics.xml", _data.Name);
            WebRequest wrGeturl = WebRequest.Create(CIXOAuth.GetUri(url));
            wrGeturl.Method = "GET";

            try
            {
                Stream objStream = wrGeturl.GetResponse().GetResponseStream();
                if (objStream != null)
                {
                    using (XmlReader reader = XmlReader.Create(objStream))
                    {
                        XmlSerializer serializer = new XmlSerializer(typeof(UserTopicResultSet));
                        UserTopicResultSet listOfTopics = (UserTopicResultSet)serializer.Deserialize(reader);

                        _topics = new Topics();
                        foreach (UserTopicResultSetUserTopicsUserTopic topic in listOfTopics.UserTopics)
                        {
                            Topic newTopic = new Topic(topic, this);
                            _topics.Add(newTopic);
                        }
                    }
                }
            }
            catch (WebException e)
            {
                if (e.Message.Contains("401"))
                {
                    throw new AuthenticationException("Authentication Failed", e);
                }
            }
            _initialised = true;
        }
Beispiel #7
0
	private void Read(string filename)
	{
		XmlSerializer ser=new XmlSerializer(typeof(DataSet));
		FileStream fs=new FileStream(filename, FileMode.Open);
		DataSet ds;

		ds=(DataSet)ser.Deserialize(fs);
		fs.Close();
		
		Console.WriteLine("DataSet name: "+ds.DataSetName);
		Console.WriteLine("DataSet locale: "+ds.Locale.Name);

		foreach(DataTable t in ds.Tables) 
		{
			Console.WriteLine("Table name: "+t.TableName);
			Console.WriteLine("Table locale: "+t.Locale.Name);

			foreach(DataColumn c in t.Columns) 
			{
				Console.WriteLine("Column name: "+c.ColumnName);
				Console.WriteLine("Null allowed? "+c.AllowDBNull);
				
			}

			foreach(DataRow r in t.Rows)
			{
				Console.WriteLine("Row: "+(string)r[0]);
			}
		}
	}
 private static CassandraSharpConfig ReadConfig(XmlDocument xmlDoc)
 {
     XmlSerializer xmlSer = new XmlSerializer(typeof(CassandraSharpConfig));
     //MiniXmlSerializer xmlSer = new MiniXmlSerializer(typeof(CassandraSharpConfig));
     using (XmlReader xmlReader = new XmlNodeReader(xmlDoc))
         return (CassandraSharpConfig)xmlSer.Deserialize(xmlReader);
 }
        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;
        }
Beispiel #10
0
    public void ImportProteinSettings()
    {
        try
        {
            ////read
            serializer = new XmlSerializer(typeof(CutParametersContainer));
            stream = new FileStream(path, FileMode.Open);
            CutParametersContainer importParams = serializer.Deserialize(stream) as CutParametersContainer;
            stream.Close();

            for (int i = 0; i < importParams.CutObjectProps.Count && i < SceneManager.Get.CutObjects.Count; i++)
            {
                SceneManager.Get.CutObjects[i].IngredientCutParameters = importParams.CutObjectProps[i].ProteinTypeParameters;
                SceneManager.Get.CutObjects[i].Inverse = importParams.CutObjectProps[i].Inverse;
                SceneManager.Get.CutObjects[i].CutType = (CutType) importParams.CutObjectProps[i].CutType;

                //restore transform info
                SceneManager.Get.CutObjects[i].transform.rotation = importParams.CutObjectProps[i].rotation;
                SceneManager.Get.CutObjects[i].transform.position = importParams.CutObjectProps[i].position;
                SceneManager.Get.CutObjects[i].transform.localScale = importParams.CutObjectProps[i].scale;
            }
        }
        catch(Exception e)
        {
            Debug.Log("import failed: " + e.ToString());
            return;
        }

        Debug.Log("imported cutobject settings from " + path);
    }
Beispiel #11
0
        public config GetDefault()
        {
            config config;

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.buy4.com/api/toolbar/config.xml");

            request.KeepAlive = false;
            request.Method = "GET";
            request.ContentType = "text/xml";

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            XmlSerializer serializer = new XmlSerializer(typeof(config));
            Stream stream = response.GetResponseStream();

            using (XmlReader reader = XmlReader.Create(stream))
                {
                config = (config)serializer.Deserialize(reader);

                }

            stream.Close();

            return config;
        }
 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();
   }
 }
Beispiel #13
0
    public void ExportProteinSettings()
    {
        try
        {
            CutParametersContainer exportParams = new CutParametersContainer();

            foreach (CutObject cuto in SceneManager.Get.CutObjects)
            {
                CutObjectProperties props = new CutObjectProperties();
                props.ProteinTypeParameters = cuto.IngredientCutParameters;
                props.Inverse = cuto.Inverse;
                props.CutType = (int)cuto.CutType;
                props.rotation = cuto.transform.rotation;
                props.position = cuto.transform.position;
                props.scale = cuto.transform.localScale;
                exportParams.CutObjectProps.Add(props);            
            }

            ////write
            serializer = new XmlSerializer(typeof(CutParametersContainer));
            stream = new FileStream(path, FileMode.Create);
            serializer.Serialize(stream, exportParams);
            stream.Close();
        }
        catch(Exception e)
        {
            Debug.Log("export failed: " + e.ToString());
            return;
        }

        Debug.Log("exported cutobject settings to " + path);
    }
Beispiel #14
0
        public static Preferences Load()
        {
            XmlSerializer serializer = new XmlSerializer(typeof(Preferences));
            Preferences loadedPref;

            try
            {

                using (StreamReader prefReader = new StreamReader(PrefFile))
                {
                    loadedPref = (Preferences)serializer.Deserialize(prefReader);

                }
            }
            catch (IOException)
            {
                Errors.Error("Couldn't load preferences file, using defaults");
                loadedPref = new Preferences();
            }
            catch (InvalidOperationException)
            {
                Errors.Error("Invalid preferences file, loading defaults");
                loadedPref = new Preferences();
            }

            return loadedPref;
        }
 public async Task<SummaryTemperatureData> GetStdAsync()
 {
     // var uri = new Uri("http://jeffa.org:81/ha/SummaryData.php");
     //var uri = new Uri(App.SummaryDataUrl);
     //var client = new HttpClient();
     //var opContent = (await client.GetAsync(uri)).Content;
     //string foo = await opContent.ReadAsStringAsync();
     //var fooo = JsonConvert.DeserializeObjectAsync<SummaryTemperatureData>(foo);
     //return await fooo;
     var applicationDataSettingsService = new ApplicationDataSettingsService();
     try
     {
     // ToDo need to wrap this a bit. error checking. disposal....
     WebHeaderCollection headers = new WebHeaderCollection();
     WebRequest request = WebRequest.Create(new Uri(applicationDataSettingsService.SummaryDataUrl));
     request.ContentType = "application/xml";
     WebResponse response = await request.GetResponseAsync();
     // response.Close(); // ?? hmmm
     Debug.WriteLine("\nThe HttpHeaders are \n{0}", request.Headers);
     Stream inputStream = response.GetResponseStream();
     XmlReader xmlReader = XmlReader.Create(inputStream);
     XmlSerializer xml = new XmlSerializer(typeof(SummaryTemperatureData));
     var stdXml = (SummaryTemperatureData)xml.Deserialize(xmlReader);
     return stdXml;
     }
     catch (Exception e)
     {
         Utility.Log(this, e.ToString());
         return null;
     }
 }
        public void setFiles(List<string> filenames)
        {
            XmlSerializer serializer = new XmlSerializer(typeof(List<Vraag>));
            List<Vraag> liAll = new List<Vraag>();

            foreach (string filename in filenames)
            {
                FileStream fs = new FileStream(Path.Combine(@"c:\users\henk\Documents\vragen\", filename), FileMode.Open);
                List<Vraag> liVragen = (List<Vraag>)serializer.Deserialize(fs);
                fs.Close();
                liAll.AddRange(liVragen);
            }

            liAll = shuffleVragen(liAll);

            int i = 0;
            CurrentVragen = new Dictionary<int, Vraag>();
            foreach (Vraag v in liAll)
            {
                CurrentVragen.Add(i, v);
                i++;
            }
            VragenOver = new Dictionary<int, Vraag>();
            foreach (KeyValuePair<int, Vraag> entry in CurrentVragen)
            {
                VragenOver.Add( entry.Key, entry.Value );
            }
            NextIndex = 0;
        }
        public PipelineContinuation StripResponseElement(ICommunicationContext context)
        {
            var passedApiUrl
                = (string)context.PipelineData["ApiUrl"];

            if (string.IsNullOrEmpty(passedApiUrl))
                return PipelineContinuation.Continue;

            var xmlDocument
                = (XmlDocument)context.PipelineData["ApiXmlResponse"];

            // read and remove response header to get result
            var responseElement = xmlDocument.SelectSingleNode("/response");
            var responseStatusAttribute = responseElement.Attributes["status"];

            var innerXml = responseElement.InnerXml;
            var stringReader = new StringReader(innerXml);

            // get the type
            Type generatedType = responseStatusAttribute.InnerText == "ok"
                                 	? _typeGenerator.GenerateType(passedApiUrl)
                                 	: typeof(Error);

            var serializer = new XmlSerializer(generatedType);
            object deserialized = serializer.Deserialize(stringReader);

            if (responseStatusAttribute.InnerText == "ok")
                context.OperationResult = new OperationResult.OK(deserialized);
            else
                context.OperationResult = new OperationResult.BadRequest { ResponseResource = deserialized };

            return PipelineContinuation.Continue;
        }
	void Serialize(string filename){
		// normalizes the data to the {0.0-1.0f} interval and saves as xml
		Waveform w = new Waveform();
		w.name = filename;
		w.cycles=1;
		w.signal = signal;
		w.mode=filename;
		w.normalRate = normal;
		w.samples = dataPoints.Count;
		
		float scale = dataMax-dataMin;
		if ( scale == 0.0f )
			scale = 1.0f;
		
		w.data = new float[dataPoints.Count];
		
		for (int i=0;i< dataPoints.Count;i++){
			w.data[i]= (dataPoints[i].point-dataMin)/scale;
			
		}
		XmlSerializer serializer = new XmlSerializer(typeof(Waveform));
		FileStream stream = new FileStream(filename + ".xml", FileMode.Create);
		serializer.Serialize(stream, w);
		stream.Close();	
	}	
        /// <summary>
        /// Initializes the <see cref="ConfigurationService"/>.
        /// </summary>
        /// <remarks>
		/// Retrieves <see cref="ValidationConfigurationSection"/>from the current application's default configuration. 
		/// For that <see cref="ValidationConfigurationSection"/> it does the following.
		/// <list type="bullet">
		/// <item>
		/// Configures <see cref="ErrorMessageProvider"/> base on <see cref="ValidationConfigurationSection.ErrorMessageProvider"/>.
		/// </item>
		/// <item>
		/// Goes through each <see cref="ValidationConfigurationSection.MappingDocuments"/> and calls <see cref="AddUrl(string)"/> for each <see cref="MappingDocumentElement.Url"/>.
		/// </item>
		/// </list>
		/// Calling this only performs these action on the first call. Each successive call will be ignored.
		/// If this method is called simultaneous on two different threads one thread will obtain a lock and the other thread will have to wait. 
		/// </remarks>
		/// <exception cref="ArgumentNullException">Any <see cref="MappingDocumentElement.Url"/> is null.</exception>
		/// <exception cref="ArgumentException">Any <see cref="MappingDocumentElement.Url"/>  is a <see cref="string.Empty"/>.</exception>
		/// <exception cref="FileNotFoundException">Any <see cref="MappingDocumentElement.Url"/>  cannot be found.</exception>
		/// <exception cref="WebException">The remote filename, defined by Any <see cref="MappingDocumentElement.Url"/>, cannot be resolved.-or-An error occurred while processing the request.</exception>
		/// <exception cref="DirectoryNotFoundException">Part of the filename or directory cannot be found.</exception>
		/// <exception cref="UriFormatException">Any <see cref="MappingDocumentElement.Url"/> is not a valid URI.</exception>
		public static void Initialize()
        {
        	if (!initialized)
        	{
        		lock (initializedLock)
        		{
        			if (!initialized)
        			{
        				var section = ConfigurationManager.GetSection("validationFrameworkConfiguration");
        				if (section != null)
        				{
        					var validationConfigurationSection = (ValidationConfigurationSection) section;
        					var errorMessageProviderElement = validationConfigurationSection.ErrorMessageProvider;
        					if (errorMessageProviderElement != null)
        					{
        						var type = Type.GetType(errorMessageProviderElement.TypeName, true);
        						var errorMessageProviderXmlSerializer = new XmlSerializer(type);

        						ErrorMessageProvider = (IErrorMessageProvider) errorMessageProviderXmlSerializer.Deserialize(new StringReader(errorMessageProviderElement.InnerXml));
        					}

        					if (validationConfigurationSection.MappingDocuments != null)
        					{
        						foreach (MappingDocumentElement mappingDocument in validationConfigurationSection.MappingDocuments)
        						{
        							AddUrl(mappingDocument.Url);
        						}
        					}
        				}
        				initialized = true;
        			}
        		}
        	}
        }
 /// <summary>
 /// Creates an instance of the given type from the specified Internet resource.
 /// </summary>
 /// <param name="htmlUrl">The requested URL, such as "http://Myserver/Mypath/Myfile.asp".</param>
 /// <param name="xsltUrl">The URL that specifies the XSLT stylesheet to load.</param>
 /// <param name="xsltArgs">An <see cref="XsltArgumentList"/> containing the namespace-qualified arguments used as input to the transform.</param>
 /// <param name="type">The requested type.</param>
 /// <param name="xmlPath">A file path where the temporary XML before transformation will be saved. Mostly used for debugging purposes.</param>
 /// <returns>An newly created instance.</returns>
 public object CreateInstance(string htmlUrl, string xsltUrl, XsltArgumentList xsltArgs, Type type,
                              string xmlPath)
 {
     StringWriter sw = new StringWriter();
     XmlTextWriter writer = new XmlTextWriter(sw);
     if (xsltUrl == null)
     {
         LoadHtmlAsXml(htmlUrl, writer);
     }
     else
     {
         if (xmlPath == null)
         {
             LoadHtmlAsXml(htmlUrl, xsltUrl, xsltArgs, writer);
         }
         else
         {
             LoadHtmlAsXml(htmlUrl, xsltUrl, xsltArgs, writer, xmlPath);
         }
     }
     writer.Flush();
     StringReader sr = new StringReader(sw.ToString());
     XmlTextReader reader = new XmlTextReader(sr);
     XmlSerializer serializer = new XmlSerializer(type);
     object o;
     try
     {
         o = serializer.Deserialize(reader);
     }
     catch (InvalidOperationException ex)
     {
         throw new Exception(ex + ", --- xml:" + sw);
     }
     return o;
 }
Beispiel #21
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();
 }
        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();
            }
        }
Beispiel #23
0
        static public JadeData.Workspace.IWorkspace Read(string path)
        {
            WorkspaceType xml;
            XmlSerializer serializer = new XmlSerializer(typeof(WorkspaceType));
            TextReader tr = new StreamReader(path);
            try
            {                
                xml = (WorkspaceType)serializer.Deserialize(tr);                
            }
            finally
            {
                tr.Close();
                tr.Dispose();
            }

            JadeData.Workspace.IWorkspace result = new JadeData.Workspace.Workspace(xml.Name, path);

            foreach (FolderType f in xml.Folders)
            {
                result.AddFolder(MakeFolder(result.Directory, f));
            }
            foreach (ProjectType p in xml.Projects)
            {
                result.AddProject(MakeProject(result.Directory, p));
            }

            return result;
        }
Beispiel #24
0
 public static List<PackageInfo> LoadUpdateList(string fileName)
 {
     XmlSerializer serializer = new XmlSerializer(typeof(List<PackageInfo>));
     XmlTextReader xmlTextReader = new XmlTextReader(fileName);
     _updateList = (List<PackageInfo>)serializer.Deserialize(xmlTextReader);
     return _updateList;
 }
Beispiel #25
0
 public static UpdateFileInfo LoadUpdateFile(string fileName)
 {
     XmlSerializer serializer = new XmlSerializer(typeof(UpdateFileInfo));
     XmlTextReader xmlTextReader = new XmlTextReader(fileName);
     _updateFile = (UpdateFileInfo)serializer.Deserialize(xmlTextReader);
     return _updateFile;
 }
Beispiel #26
0
 public static UpdateFileInfo LoadUpdateFileFromStream(Stream xmlStream)
 {
     XmlSerializer serializer = new XmlSerializer(typeof(UpdateFileInfo));
     XmlTextReader xmlTextReader = new XmlTextReader(xmlStream);
     _updateFile = (UpdateFileInfo)serializer.Deserialize(xmlTextReader);
     return _updateFile;
 }
Beispiel #27
0
        protected void Page_Load(object sender, EventArgs e)
        {
            String xmlText = "";

            Account acc = new Account();
            acc.Address = "dsdsds";
            acc.Country = "india";
            acc.Id = "12312";
            acc.Name = "pravin";
            acc.Phone = "2323232";
            acc.Sex = "male";

            XmlSerializer ser = new XmlSerializer(acc.GetType());

            StringWriter stringWriter = new StringWriter();

            using (XmlWriter xmlWriter = XmlWriter.Create(stringWriter))
            {
                ser.Serialize(xmlWriter, acc);

            }

            xmlText = stringWriter.ToString();

            UCTest1.SetText(xmlText);
        }
Beispiel #28
0
        /// <summary>
        /// Reads the PAP message from the specified stream.
        /// </summary>
        /// <param name="stream">The stream.</param>
        /// <returns></returns>
        public static PapMessage Read(Stream stream)
        {
            XmlReaderSettings settings =
                new XmlReaderSettings
                {
                    CheckCharacters = true,
                    CloseInput = true,
                    ConformanceLevel = System.Xml.ConformanceLevel.Document,
                    DtdProcessing = DtdProcessing.Parse,
                    IgnoreComments = true,
                    ValidationType = ValidationType.DTD
                };
            XmlReader reader = XmlReader.Create(stream, settings);
            try
            {
                // Deserialize the data
                XmlSerializer serializer = new XmlSerializer(typeof(PapRoot));
                object resultRoot = serializer.Deserialize(reader);

                // Extract the response object from the appropriate root
                PapMessage response = null;
                if (resultRoot is PapRoot)
                {
                    response = ((PapRoot)resultRoot).Response;
                }

                return response;
            }
            finally
            {
                reader.Close();
            }
        }
        protected override byte[] ProcessRequest(string path, Stream request,
                IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
        {
            AssetBase asset;
            XmlSerializer xs = new XmlSerializer(typeof(AssetBase));

            try
            {
                asset = (AssetBase)xs.Deserialize(request);
            }
            catch (Exception)
            {
                httpResponse.StatusCode = (int)HttpStatusCode.BadRequest;
                return null;
            }

            string[] p = SplitParams(path);
            if (p.Length > 0)
            {
                string id = p[0];
                bool result = m_AssetService.UpdateContent(id, asset.Data);

                xs = new XmlSerializer(typeof(bool));
                return ServerUtils.SerializeResult(xs, result);
            }
            else
            {
                string id = m_AssetService.Store(asset);

                xs = new XmlSerializer(typeof(string));
                return ServerUtils.SerializeResult(xs, id);
            }
        }
        /// <summary>
        ///     Server constructor, starts the server and connects to all region servers.
        /// </summary>
        /// <remarks>
        ///     TODO: Make the config file be able to be in a different location. Load from command line.
        /// </remarks>
        public MasterServer()
        {
            //Load this region server's junk from xml
            XmlSerializer deserializer = new XmlSerializer(typeof(MasterConfig));
            MasterConfig masterconfig = (MasterConfig)deserializer.Deserialize(XmlReader.Create(@"C:\Users\Addie\Programming\Mobius\Mobius.Server.MasterServer\bin\Release\MasterData.xml"));
            //Start it with the name MobiusMasterServer, and let connection approvals be enabled
            var config = new NetPeerConfiguration(masterconfig.ServerName);
            config.Port = masterconfig.ServerPort;
            config.MaximumConnections = masterconfig.MaxConnections;
            config.EnableMessageType(NetIncomingMessageType.ConnectionApproval);
            LidgrenServer = new NetServer(config);

            RegionServers = new Dictionary<ushort, NetClient>();
            foreach(RegionInfo info in masterconfig.RegionServers)
            {
                NetClient region = new NetClient(new NetPeerConfiguration(info.ServerName));
                region.Start();
                region.Connect(info.ServerIp, info.ServerPort);
                RegionServers.Add(info.RegionId, region);
            }

            //Initialize our data structures
            Users = new Dictionary<Guid, User>();
            UserIdToCharacters = new Dictionary<Guid, List<Character>>();
            //Start the server
            LidgrenServer.Start();
        }
Beispiel #31
0
        public static VoxelizationInput Load(string file)
        {
            try
            {
                if (!File.Exists(file))
                {
                    return(null);
                }

                VoxelizationInput settings     = null;
                XmlSerializer     mySerializer = new XmlSerializer(typeof(VoxelizationInput));
                using (FileStream myFileStream = new FileStream(file, FileMode.Open))
                {
                    settings = (VoxelizationInput)mySerializer.Deserialize(myFileStream);
                }

                return(settings);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
                return(null);
            }
        }
Beispiel #32
0
        public static void DumpTableScriptMap()
        {
            TableMap tableMap = null;
            string   path     = "Assets/Editor/ResImporter/ImporterData/Table/Table.xml";

            try
            {
                XmlSerializer xmlSerializer = new XmlSerializer(typeof(TableMap));
                using (FileStream fileStream = new FileStream(path, FileMode.Open))
                {
                    tableMap = (xmlSerializer.Deserialize(fileStream) as TableMap);
                }
                if (tableMap != null)
                {
                    tableMap.tableScriptMap.Clear();
                    foreach (KeyValuePair <string, string> current in XTableAsyncLoader.tableScriptMap)
                    {
                        TableScriptMap tableScriptMap = new TableScriptMap();
                        tableScriptMap.table  = current.Key;
                        tableScriptMap.script = current.Value;
                        tableMap.tableScriptMap.Add(tableScriptMap);
                    }
                    using (FileStream fileStream2 = new FileStream(path, FileMode.Create))
                    {
                        StreamWriter            textWriter = new StreamWriter(fileStream2, Encoding.UTF8);
                        XmlSerializerNamespaces xmlSerializerNamespaces = new XmlSerializerNamespaces();
                        xmlSerializerNamespaces.Add(string.Empty, string.Empty);
                        xmlSerializer.Serialize(textWriter, tableMap, xmlSerializerNamespaces);
                    }
                }
            }
            catch (Exception ex)
            {
                XSingleton <XDebug> .singleton.AddWarningLog(ex.Message, null, null, null, null, null);
            }
        }
Beispiel #33
0
        public static Gpx11.gpxType Open(Stream stream, bool validate)
        {
            Gpx11.gpxType gpx = null;

            using (XmlReader xmlReader = CreateXmlReader(stream, validate))
            {
                //if (xmlReader != null)
                //{
                //  while (xmlReader.Read())
                //  {
                //    //empty loop - if Read fails it will raise an error via the
                //    //ValidationEventHandler wired to the XmlReaderSettings object
                //  }

                //  //explicitly call Close on the XmlReader to reduce strain on the GC
                //  xmlReader.Close();
                //}

                XmlSerializer serializer = new XmlSerializer(typeof(Gpx11.gpxType));
                gpx = (Gpx11.gpxType)serializer.Deserialize(xmlReader);
            }

            return(gpx);
        }
        private void RetreiveSettings()
        {
            try
            {
                if (File.Exists(GetSettingsFile()))
                {
                    using (var ms = new MemoryStream(File.ReadAllBytes(GetSettingsFile())))
                    {
                        List <Setting> setts = new List <Setting>();

                        var serializer = new XmlSerializer(setts.GetType());
                        setts = serializer.Deserialize(ms) as List <Setting>;
                        if (setts != null)
                        {
                        }

                        applyControlValues(Controls, setts);
                    }
                }
            }
            catch (Exception ee)
            {
            }
        }
        public static string ExportOldestBooks(BookShopContext context, DateTime date)
        {
            /*Export top 10 oldest books that are published before the given date and are of type science.
             * For each book select its name, date (in format "d") and pages.
             * Sort them by pages in descending order and then by date in descending order.
             * NOTE: Before the orders, materialize the query (This is issue by Microsoft in InMemory database library)!!!
             */
            var books = context
                        .Books
                        .Where(b => b.PublishedOn < date && b.Genre == Genre.Science)
                        .ToList()
                        .OrderByDescending(b => b.Pages)
                        .ThenByDescending(b => b.PublishedOn) // again ordering before because of formatting
                        .Select(b => new ExportOldestBooksDto()
            {
                Name  = b.Name,
                Date  = b.PublishedOn.ToString("d", CultureInfo.InvariantCulture),
                Pages = b.Pages
            })
                        .Take(10)
                        .ToList();

            var namespaces = new XmlSerializerNamespaces();

            namespaces.Add(string.Empty, string.Empty);

            StringBuilder sb         = new StringBuilder();
            XmlSerializer serializer = new XmlSerializer(typeof(List <ExportOldestBooksDto>), new XmlRootAttribute("Books"));

            using (StringWriter writer = new StringWriter(sb))
            {
                serializer.Serialize(writer, books, namespaces);
            }

            return(sb.ToString().TrimEnd());
        }
Beispiel #36
0
        public void CheckSerialization()
        {
            try
            {
                var files = Directory.EnumerateFiles(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\Mailbox", "*.txt", SearchOption.TopDirectoryOnly);

                foreach (string f in files)
                {
                    string[]      lines    = File.ReadAllLines(f);
                    List <string> newLines = new List <string>(lines);
                    newLines.RemoveAt(0);

                    StringBuilder sb = new StringBuilder();
                    foreach (string s in newLines)
                    {
                        sb.AppendLine(s);
                    }


                    XmlReaderSettings xmlReaderSettings = new XmlReaderSettings()
                    {
                        CheckCharacters = false
                    };
                    XmlReader xmlReader = XmlTextReader.Create(new StringReader(sb.ToString()), xmlReaderSettings);

                    XmlSerializer deser = new XmlSerializer(typeof(EAS.generated.SyncResponseNamespace.Sync));
                    EAS.generated.SyncResponseNamespace.Sync sync = (EAS.generated.SyncResponseNamespace.Sync)deser.Deserialize(xmlReader);
                }

                //EAS.generated.SyncResponseNamespace.Sync sync = (EAS.generated.SyncResponseNamespace.Sync)deser.Deserialize(streamOut);
            }
            catch (Exception ex)
            {
                Trace.WriteLine("ERROR: " + ex.Message);
            }
        }
Beispiel #37
0
 public static void Load()
 {
     try
     {
         BookmarkEntity bookmarkLib;
         XmlSerializer  serializer = new XmlSerializer(typeof(BookmarkEntity));
         if (!File.Exists(BookmarksFile))
         {
             bookmarks = new BookmarkEntity();
         }
         else
         {
             using (TextReader reader = new StreamReader(BookmarksFile))
             {
                 bookmarkLib = (BookmarkEntity)serializer.Deserialize(reader);
                 bookmarks   = bookmarkLib;
             }
         }
     }
     catch
     {
         bookmarks = new BookmarkEntity();
     }
 }
        public ShippingResult GetTrackingResult()
        {
            ShippingResult shippingResult;

            var shippingResultInString = GetTrackingInfoUSPSInString();

            using (MemoryStream memStream = new MemoryStream(Encoding.UTF8.GetBytes(shippingResultInString)))
            {
                if (shippingResultInString.Contains("<Error>") && !shippingResultInString.Contains("<TrackResponse>"))
                {
                    XmlSerializer serializer = new XmlSerializer(typeof(USPSTrackingResultError.Error));
                    var           error      = (USPSTrackingResultError.Error)serializer.Deserialize(memStream);
                    shippingResult = USPSTrackingResultErrorWrap(error);
                }
                else
                {
                    XmlSerializer serializer       = new XmlSerializer(typeof(USPSTrackingResult.TrackResponse));
                    var           resultingMessage = (USPSTrackingResult.TrackResponse)serializer.Deserialize(memStream);
                    shippingResult = UspsTrackingResultWrap(resultingMessage);
                }
            }

            return(shippingResult);
        }
Beispiel #39
0
        /// <summary>
        /// Deserializes an xml file into an object list
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public T DeSerializeObject(string fileName)
        {
            if (string.IsNullOrEmpty(fileName))
            {
                return(default(T));
            }

            var objectOut = default(T);

            try
            {
                var xmlDocument = new XmlDocument();
                xmlDocument.Load(fileName);
                var xmlString = xmlDocument.OuterXml;

                using (var read = new StringReader(xmlString))
                {
                    var outType = typeof(T);

                    var serializer = new XmlSerializer(outType);
                    using (XmlReader reader = new XmlTextReader(read))
                    {
                        objectOut = (T)serializer.Deserialize(reader);
                        reader.Close();
                    }

                    read.Close();
                }
            }
            catch (Exception ex)
            {
                //Log exception here
            }

            return(objectOut);
        }
Beispiel #40
0
    public void Load(string fileName)
    {
        CheckDataPath();

        //open xml file
        XmlSerializer serializer = new XmlSerializer(typeof(DataBase));

        //Create Stream
        if (File.Exists(dataPath + fileName))
        {
            FileStream stream = new FileStream(dataPath + fileName, FileMode.Open);

            //Deserialize DB
            dataBase = serializer.Deserialize(stream) as DataBase;

            //Close the stream
            stream.Close();
        }
        else
        {
            //Error message
            Debug.LogErrorFormat("<b><size=12><color=red>ERROR : File " + fileName + " does not exist at path : </color><color=green> " + dataPath + fileName + " </color> <color=red> (Maybe you did not save?) </color></size></b>");
        }
    }
Beispiel #41
0
        /// <summary>
        /// Writes the configuration file to disk with the specified name.
        /// </summary>
        /// <param name="fileName">The name of the file on disk to write to.</param>
        /// <param name="location">The directory to write the file to.</param>
        public virtual void SaveAs(string fileName, string location)
        {
            if (string.IsNullOrEmpty(location))
            {
                throw new ArgumentException("Location cannot be be null or empty!", nameof(location));
            }
            m_filename = fileName;
            XmlSerializer xmlSerializer = new XmlSerializer(GetType());

            if (!Directory.Exists(location))
            {
                Directory.CreateDirectory(location);
            }
            if (location[location.Length - 1] != Path.DirectorySeparatorChar)
            {
                location += Path.DirectorySeparatorChar;
            }
            location += m_filename;
            using (TextWriter textWriter = new StreamWriter(location, false, Encoding.UTF8))
            {
                xmlSerializer.Serialize(textWriter, this);
                textWriter.Close();
            }
        }
Beispiel #42
0
        public static T FromXml (string xml)
        {
            // Compensate for stupid Mono encoding bugs

            if (xml.StartsWith ("?"))
            {
                xml = xml.Substring (1);
            }

            xml = xml.Replace ("&#x0;", "");
            xml = xml.Replace ("\x00", "");

            XmlSerializer serializer = new XmlSerializer (typeof (T));

            MemoryStream stream = new MemoryStream();
            byte[] xmlBytes = Encoding.UTF8.GetBytes (xml);
            stream.Write (xmlBytes, 0, xmlBytes.Length);

            stream.Position = 0;
            T result = (T) serializer.Deserialize (stream);
            stream.Close();

            return result;
        }
        void SavePrefs()
        {
            var prefs      = new List <string> ();
            var serializer = new XmlSerializer(typeof(SelectionConstraint));

            foreach (object[] row in constraints_store)
            {
                var sw = new StringWriter();
                serializer.Serialize(sw, new SelectionConstraint((string)row[0], (double)row[1]));
                sw.Close();
                prefs.Add(sw.ToString());
            }

#if !GCONF_SHARP_2_18
            if (prefs.Count != 0)
#endif
            Preferences.Set(Preferences.CUSTOM_CROP_RATIOS, prefs.ToArray());
#if !GCONF_SHARP_2_18
            else
            {
                Preferences.Set(Preferences.CUSTOM_CROP_RATIOS, -1);
            }
#endif
        }
Beispiel #44
0
        public ObservableCollection <PersonItem> LoadData()
        {
            // XML-Datei deserialisieren
            string path = Directory.GetCurrentDirectory();
            int    i    = path.LastIndexOf("\\");

            path = path.Substring(0, i);
            i    = path.LastIndexOf("\\");
            path = path.Substring(0, i) + "\\Persons.xml";

            if (File.Exists(path))
            {
                PersonsList = new ObservableCollection <PersonItem>();
                FileStream    fs         = new FileStream(path, FileMode.Open);
                XmlSerializer serializer = new XmlSerializer(typeof(ObservableCollection <Person>));
                ObservableCollection <Person> tempList = (ObservableCollection <Person>)serializer.Deserialize(fs);
                foreach (var item in tempList)
                {
                    PersonsList.Add(new PersonItem(item));
                }
                fs.Close();
            }
            return(PersonsList);
        }
Beispiel #45
0
        /// ------------------------------------------------------------------------------------
        /// <summary>
        /// Serializes an object to an XML string.
        /// </summary>
        /// ------------------------------------------------------------------------------------
        public static string SerializeToString <T>(T data)
        {
            try
            {
                StringBuilder output = new StringBuilder();
                using (StringWriter writer = new StringWriter(output))
                {
                    XmlSerializerNamespaces nameSpace = new XmlSerializerNamespaces();
                    nameSpace.Add(string.Empty, string.Empty);
                    XmlSerializer serializer = new XmlSerializer(typeof(T));
                    serializer.Serialize(writer, data, nameSpace);
                    writer.Close();
                }

                return(output.Length == 0 ? null : output.ToString());
            }
            catch (Exception e)
            {
                //Debug.Fail(e.Message);
                throw;                 //hatton says: I'd rather deal with the problem in the client app, then swallow it and have a mystery
            }

            return(null);
        }
Beispiel #46
0
        public string Serialize(object obj)
        {
            var serializer = new XmlSerializer(obj.GetType());

            var writerSettings =
                new XmlWriterSettings
            {
                OmitXmlDeclaration = true,
                Indent             = true
            };

            var emptyNameSpace = new XmlSerializerNamespaces();

            emptyNameSpace.Add(string.Empty, string.Empty);

            var stringWriter = new StringWriter();

            using (var xmlWriter = XmlWriter.Create(stringWriter, writerSettings))
            {
                serializer.Serialize(xmlWriter, obj, emptyNameSpace);

                return(stringWriter.ToString());
            }
        }
Beispiel #47
0
        public void LoadConfigFile(string path)
        {
            try
            {
                System.IO.FileStream fs = new System.IO.FileStream(path, System.IO.FileMode.Open);
                byte[] buffer           = new byte[fs.Length];
                fs.Read(buffer, 0, (int)fs.Length);
                System.IO.MemoryStream stream = new System.IO.MemoryStream(buffer);
                Setting       camera          = new Setting();
                XmlSerializer formatter       = new XmlSerializer(camera.GetType());
                camera = (Setting)formatter.Deserialize(stream);

                // read values
                _camID  = camera.camID;
                _camURL = camera.camURL;

                _cropX      = camera.cropX;
                _cropY      = camera.cropY;
                _cropWidth  = camera.cropWidth;
                _cropHeight = camera.cropHeight;
                _savePath   = camera.savePath;

                _isResize     = camera.isResize;
                _timeout      = camera.timeout;
                _countForPass = camera.countForPass;

                _size = camera.size;

                stream.Close();
                fs.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine("Config File read error");
            }
        }
Beispiel #48
0
        public void Cargar()
        {
            var collection = new ObservableCollection <Campo>();

            if (File.Exists("config.xml"))
            {
                Config        config;
                XmlSerializer xs = new XmlSerializer(typeof(Config));
                using (StreamReader sr = new StreamReader("config.xml"))
                {
                    config = xs.Deserialize(sr) as Config;
                }
                foreach (var item in config.Campos)
                {
                    collection.Add(new Campo()
                    {
                        Nombre = item.Value,
                        Valor  = ""
                    });
                }
                Fondo = config.FondoFormulario;
            }
            Campos = collection;
        }
Beispiel #49
0
        public void Load(string filename = "Preferences.bin", FileType type = FileType.BINARY)
        {
            switch (type)
            {
            case FileType.BINARY:


                IFormatter formatter = new BinaryFormatter();
                Stream     stream    = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read);

                PreferenceList obj = (PreferenceList)formatter.Deserialize(stream);

                stream.Close();


                m_SharedPreferences = obj;
                break;


            case FileType.XML:

                PreferenceList myObject;
                // Construct an instance of the XmlSerializer with the type
                // of object that is being deserialized.
                XmlSerializer mySerializer = new XmlSerializer(typeof(PreferenceList));
                // To read the file, create a FileStream.
                FileStream myFileStream = new FileStream("Preferences.xml", FileMode.Open, FileAccess.Read, FileShare.Read);
                // Call the Deserialize method and cast to the object type.
                myObject = (PreferenceList)mySerializer.Deserialize(myFileStream);

                m_SharedPreferences = myObject;

                myFileStream.Close();
                break;
            }
        }
Beispiel #50
0
        public bool SaveXMLToData(List<ExportRecordData> listExportData)
        {
            XmlDocument xmlDoc = new XmlDocument();   //Represents an XML document, 
            // Initializes a new instance of the XmlDocument class.          
            XmlSerializer xmlSerializer = new XmlSerializer(listExportData.GetType());
            // Creates a stream whose backing store is memory. 
            using (MemoryStream xmlStream = new MemoryStream())
            {
                xmlSerializer.Serialize(xmlStream, listExportData);
                xmlStream.Position = 0;
                //Loads the XML document from the specified string.
                xmlDoc.Load(xmlStream);

                ExportRecordXML ERX = new ExportRecordXML();
                ERX.XMLData = xmlDoc.InnerXml;//.ToString();
                ERX.IsSchedular = false;
                if (RecordService.SaveXMLToData(ERX))
                {
                    return true;
                }
                return false;
                //return xmlDoc.InnerXml;
            }
        }
        public void LoadAppointmentsFromXml(string filename)
        {
            // loading AppointmentList from XML-file

            using (StreamReader sr = new StreamReader(filename))
            {
                _myAppointmentList.Clear();

                XmlSerializer xser = new XmlSerializer(typeof(Appointment[]));

                Appointment[] appointments = (Appointment[])xser.Deserialize(sr);
                foreach (Appointment appointment in appointments)
                {
                    _myAppointmentList.Add(appointment);
                }

                // inform ChangedHandler
            }
            if (changed != null)
            {
                changed(filename, EventArgs.Empty);
                hasChanged = false;
            }
        }
Beispiel #52
0
        /// <summary>
        /// Deserialize object from XML file.
        /// </summary>
        /// <param name="filename">The file name to read from.</param>
        /// <param name="type">Type of object.</param>
        /// <param name="encoding">The encoding to use (default is UTF8).</param>
        /// <returns>Object.</returns>
        public static object DeserializeFromXmlFile(string filename, Type type, Encoding encoding = null, int attempts = 1, int waitTime = 500)
        {
            // Read full file content first, so file will be locked for shorter times.
            var bytes = ReadFile(filename, attempts, waitTime);

            if (bytes == null)
            {
                return(null);
            }
            encoding = encoding ?? Encoding.UTF8;
            // Read bytes.
            var ms = new MemoryStream(bytes);
            // Use stream reader to avoid error: There is no Unicode byte order mark. Cannot switch to Unicode.
            var sr = new StreamReader(ms, encoding);
            // Deserialize
            object        o;
            XmlSerializer serializer = GetXmlSerializer(type);

            lock (serializer) { o = serializer.Deserialize(sr); }
            sr.Dispose();
            sr = null;
            ms = null;
            return(o);
        }
Beispiel #53
0
 private void SetCacheManager()
 {
     try
     {
         using (FileStream stream = File.Open(App.UserAppDataPath + @"\" + Settings.Default.CacheManagerFile, FileMode.Open))
         {
             XmlSerializer serializer = new XmlSerializer(typeof(ClientApp.CacheManager));
             this._cacheManager = (ClientApp.CacheManager)serializer.Deserialize(stream);
         }
     }
     catch (Exception exception)
     {
         Trace.WriteLine(new LogMessage("AdvertPlayer - SetCacheManager", "Unable to reuse the Cache Manager because: " + exception.Message));
         this._cacheManager = new ClientApp.CacheManager();
     }
     try
     {
         this._cacheManager.Regenerate();
     }
     catch (Exception exception2)
     {
         Trace.WriteLine(new LogMessage("AdvertPlayer - SetCacheManager", "Regenerate failed because: " + exception2.Message));
     }
 }
Beispiel #54
0
        public ServiceStopTime DeserializeTime(string path)
        {
            var xmlSerializer = new XmlSerializer(typeof(ServiceStopTime));

            try
            {
                if (File.Exists(path))
                {
                    ServiceStopTime data;
                    using (var reader = new StreamReader(path))
                    {
                        data = (ServiceStopTime)xmlSerializer.Deserialize(reader);
                        reader.Close();
                    }
                    return(data);
                }
            }
            catch (Exception ex)
            {
                LogExtension.LogError("Exception while deserializing service stop time", ex,
                                      MethodBase.GetCurrentMethod());
            }
            return(null);
        }
        public StreamSerializerDelegate GetStreamSerializer(string contentType)
        {
            StreamSerializerDelegate responseWriter;
            if (this.ContentTypeSerializers.TryGetValue(contentType, out responseWriter)||
                this.ContentTypeSerializers.TryGetValue(ContentType.GetRealContentType(contentType), out responseWriter))
            {
                return responseWriter;
            }

            var contentTypeAttr = ContentType.GetEndpointAttributes(contentType);
            switch (contentTypeAttr)
            {
                case EndpointAttributes.Xml:
                    return (r, o, s) => XmlSerializer.SerializeToStream(o, s);

                case EndpointAttributes.Json:
                    return (r, o, s) => JsonDataContractSerializer.Instance.SerializeToStream(o, s);

                case EndpointAttributes.Jsv:
                    return (r, o, s) => TypeSerializer.SerializeToStream(o, s);
            }

            return null;
        }
Beispiel #56
0
        internal static string Serialize <T>(T value)
        {
            if (value == null)
            {
                return(null);
            }

            XmlSerializer serializer = new XmlSerializer(typeof(T));

            XmlWriterSettings settings = new XmlWriterSettings();

            settings.Encoding           = new UnicodeEncoding(false, false); // no BOM in a .NET string
            settings.Indent             = false;
            settings.OmitXmlDeclaration = false;

            using (StringWriter textWriter = new StringWriter(CultureInfo.InvariantCulture))
            {
                using (XmlWriter xmlWriter = XmlWriter.Create(textWriter, settings))
                {
                    serializer.Serialize(xmlWriter, value);
                }
                return(textWriter.ToString());
            }
        }
Beispiel #57
0
        /// <summary>
        /// 将对象转换为其 XML 表示形式。
        /// </summary>
        /// <param name="writer">对象要序列化为的 <see cref="T:System.Xml.XmlWriter"/> 流。</param>
        public void WriteXml(XmlWriter writer)
        {
            writer.WriteElementString("FileName", FileName);
            writer.WriteElementString("FullName", FullName);
            writer.WriteElementString("Name", Name);
            writer.WriteElementString("Title", Title);
            writer.WriteElementString("Description", Description);
            writer.WriteElementString("Version", Version == null ? string.Empty : Version.ToString());
            writer.WriteElementString("IsExtend", IsExtend.ToString().ToLower());
            writer.WriteElementString("DisableStopAndUninstalled", DisableStopAndUninstalled.ToString().ToLower());
            writer.WriteElementString("ListOrder", ListOrder.ToString());
            writer.WriteElementString("State", State.ToString());

            writer.WriteStartElement("Reference");
            if (Reference != null)
            {
                Reference.ForEach(reference =>
                {
                    writer.WriteElementString("Assembly", reference);
                });
            }
            writer.WriteEndElement();

            writer.WriteStartElement("AbstractModules");
            if (AbstractModules != null)
            {
                AbstractModules.ForEach(module =>
                {
                    XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces();
                    namespaces.Add(string.Empty, string.Empty);
                    XmlSerializer xmlSerializer = new XmlSerializer(module.GetType());
                    xmlSerializer.Serialize(writer, module, namespaces);
                });
            }
            writer.WriteEndElement();
        }
Beispiel #58
0
 public static string Object2Xml <T>(T value, string fileName)
 {
     if (value == null)
     {
         return(string.Empty);
     }
     try
     {
         var xmlserializer    = new XmlSerializer(typeof(T));
         var stringWriter     = new StringWriterWithEncoding(Encoding.UTF8);
         var xmlWriterSetting = new XmlWriterSettings();
         xmlWriterSetting.Encoding = Encoding.UTF8;
         using (var writer = XmlWriter.Create(stringWriter, xmlWriterSetting))
         {
             xmlserializer.Serialize(writer, value);
             File.WriteAllText(@"C:\Users\Tuan Tran\Desktop\VietnamBusInfo\Data\" + fileName + ".xml", stringWriter.ToString());
             return(stringWriter.ToString());
         }
     }
     catch (Exception ex)
     {
         throw new Exception("An error occurred", ex);
     }
 }
        /// <summary>
        /// Serializes the object.
        /// </summary>
        /// <param name="serializeData">The object to serialize.</param>
        /// <param name="serializeType">The type of the object to serialize.</param>
        /// <returns>The xml serialized version of the object</returns>
        protected string SerializeObject(object serializeData, Type serializeType)
        {
            string xml = string.Empty;

            if (serializeData != null && serializeType != null)
            {
                try
                {
                    MemoryStream memoryStream = null;

                    using (memoryStream = new MemoryStream())
                    {
                        using (XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, _encodeType))
                        {
                            XmlSerializer typedSerializer = new XmlSerializer(serializeType);

                            //dump the serialized content in the writer
                            typedSerializer.Serialize(xmlTextWriter, serializeData);

                            //get a copy of the data and convert to a string
                            memoryStream = (MemoryStream)xmlTextWriter.BaseStream;
                            byte[] data = memoryStream.ToArray();
                            xml = _encodeType.GetString(data);
                        }
                    }
                }
                catch (Exception exception)
                {
                    string message = string.Format("Unable to serialize {0} to file.", GetType().FullName);

                    throw new SerializationException(message, exception);
                }
            }

            return xml;
        }
Beispiel #60
0
        public Backup(string filePath)
        {
            if (!File.Exists(filePath))
            {
                throw new FileNotFoundException();
            }

            this.Path     = filePath;
            this.fileInfo = new FileInfo(this.Path);

            var xml = File.ReadAllText(this.Path);

            if (string.IsNullOrWhiteSpace(xml))
            {
                return;
            }

            var serializer = new XmlSerializer(typeof(List <BackupEntry>));

            using (var reader = new StringReader(xml))
            {
                Entries = (List <BackupEntry>)serializer.Deserialize(reader);
            }
        }