CanDeserialize() public method

public CanDeserialize ( System.IO.XmlReader xmlReader ) : bool
xmlReader System.IO.XmlReader
return bool
        public void AddFile(string fileName)
        {
            if (!File.Exists(fileName))
            {
                throw new DeviceDetectorException("Specified browser file doesn't exist", new FileNotFoundException(string.Empty, fileName));
            }

            if (String.Compare(Path.GetExtension(fileName), ".browser", true) != 0)
            {
                throw new DeviceDetectorException("Specified file has invalid extension");
            }

            using (XmlReader xmlReader = XmlReader.Create(fileName))
            {
                XmlSerializer xmlSerializer = new XmlSerializer(typeof(browsers));
                if (!xmlSerializer.CanDeserialize(xmlReader))
                {
                    throw new DeviceDetectorException("Invalid file format");
                }

                try
                {
                    browsers browsersFile = xmlSerializer.Deserialize(xmlReader) as browsers;
                    string keyName = Path.GetFileNameWithoutExtension(fileName);
                    if (!this.browserFiles.ContainsKey(keyName))
                    {
                        this.browserFiles.Add(keyName, browsersFile);
                    }
                }
                catch (InvalidOperationException ex)
                {
                    throw new DeviceDetectorException("Cannot parse specified file \"" + fileName + "\"", ex);
                }
            }
        }
Example #2
0
        public static async Task<Rules> LoadFromAppDataAsync () {
            var d20Rules = new D20Rules() { Rules = new Rules() };
            var appPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
            var basePath = Path.Combine(appPath, "CBLoader");
            var rulesPath = Path.Combine(basePath, "combined.dnd40");

            if (!File.Exists(rulesPath)) {
                return d20Rules.Rules;
            }

            Stopwatch timer = Stopwatch.StartNew();
            try {
                d20Rules = await Task.Run<D20Rules>(() => {
                    XmlSerializer serializer = new XmlSerializer(typeof(D20Rules));
                    using (var file = new FileStream(rulesPath, FileMode.Open, FileAccess.Read, FileShare.Read, 0x1000, useAsync: true)) {
                        using (var reader = new XmlTextReader(file)) {
                            if (serializer.CanDeserialize(reader)) {
                                return serializer.Deserialize(reader) as D20Rules;
                            }
                        }
                    }
                    return d20Rules;
                }).ConfigureAwait(false);
            }
            finally {
                timer.Stop();
                Trace.TraceInformation("Deserializing D20Rules took {0}ms", timer.ElapsedMilliseconds);
            }

            return d20Rules.Rules;
        }
Example #3
0
        public static ConsultResponse Consult(this GlobalMedicalFileConsultationPortTypeClient client, CommonInputType common, RoutingType routing, RetrieveTransactionRequestType detailValue, out ArchivingInfo archivingInfo)
        {
            var detail = new BlobType();
            detail.Id = "_" + Guid.NewGuid().ToString();
            detail.ContentType = "text/xml";
            detail.ContentEncoding = "none";
            var detailStream = new MemoryStream();
            var serializer = new XmlSerializer(typeof(RetrieveTransactionRequestType));
            serializer.Serialize(detailStream, detailValue);
            detail.Value = detailStream.ToArray();

            ResponseReturnType super = client.Consult(common, routing, detail);

            archivingInfo = new ArchivingInfo();
            archivingInfo.RequestDetail = detail;
            archivingInfo.RequestXadesT = null;
            archivingInfo.ResponseDetail = super.Detail;
            archivingInfo.ResponseXadesT = super.XadesT;

            var retVal = new ConsultResponse();
            retVal.Common = super.CommonOutput;
            if (super.Detail.ContentType == "text/xml"
                && super.Detail.ContentEncoding == "none")
            {
                var reader = XmlReader.Create(new MemoryStream(super.Detail.Value));
                var deserializer = new XmlSerializer(typeof(RetrieveTransactionResponseType));
                if (deserializer.CanDeserialize(reader))
                {
                    retVal.DetailValue = deserializer.Deserialize(reader) as RetrieveTransactionResponseType;
                }
            }

            return retVal;
        }
Example #4
0
 public Config Load()
 {
     if (File.Exists(CONFIG_FILE))
     {
         StreamReader sr = new StreamReader(CONFIG_FILE);
         XmlTextReader xr = new XmlTextReader(sr);
         XmlSerializer xs = new XmlSerializer(this.GetType());
         object c;
         if (xs.CanDeserialize(xr))
         {
             c = xs.Deserialize(xr);
             Type t = this.GetType();
             PropertyInfo[] properties = t.GetProperties();
             foreach (PropertyInfo p in properties)
             {
                 p.SetValue(this, p.GetValue(c, null), null);
             }
         }
         xr.Close();
         sr.Close();
     }
     else
     {
         Logger.Warn("Configuration file not found - loading defaults.");
         Save();
     }
     return this;
 }
Example #5
0
 public static PacketsHolder Load()
 {
     PacketsHolder opts = new PacketsHolder();
     try
     {
         if (File.Exists(PacketsHolder.FileName))
         {
             using (FileStream fs = new FileStream(PacketsHolder.FileName, FileMode.Open))
             {
                 using (XmlReader xr = new XmlTextReader(fs))
                 {
                     XmlSerializer ser = new XmlSerializer(typeof(PacketsHolder));
                     if (ser.CanDeserialize(xr))
                     {
                         opts = (PacketsHolder)ser.Deserialize(xr);
                     }
                 }
             }
         }
     }
     catch (InvalidOperationException)
     {
     }
     catch (XmlException)
     {
     }
     if (opts == null)
         opts = new PacketsHolder();
     return opts;
 }
Example #6
0
        public void CanDeserializeRssFeedFromXml()
        {
            var testfeed = TestFileLoader.GetSingleRssTestFilePath(TestFileLoader.TestFileType.FileSys);
            var feed = Factory.CreateFeed(new Uri(testfeed));
            var serializer = new XmlSerializer(feed.GetType());

            using (var filestream = new FileStream(RssXmlFile, FileMode.Create))
            {
                serializer.Serialize(filestream, feed);
            }

            using (var readstream = new FileStream(RssXmlFile, FileMode.Open))
            {
                using(var reader = XmlReader.Create(readstream))
                {
                    Assert.IsTrue(serializer.CanDeserialize(reader));
                    var resultantObject = serializer.Deserialize(reader);

                    //Assert that the result object is of the expected type (some derivative of IFeed)
                    Assert.IsInstanceOf(feed.GetType(), resultantObject);

                    //Assert that the two objects are distinct instances
                    Assert.AreNotSame(feed, resultantObject);

                    //Cast the object back into an IFeed and perform some specific assertions
                    var resultantFeed = resultantObject as IFeed;
                    Assert.AreEqual(feed.Title, resultantFeed.Title);
                    Assert.AreEqual(feed.LastUpdated, resultantFeed.LastUpdated);
                    Assert.AreEqual(feed.FeedUri, resultantFeed.FeedUri);
                    Assert.AreEqual(feed.FeedType, resultantFeed.FeedType);
                    Assert.AreEqual(feed.Items.Count, resultantFeed.Items.Count);
                    Assert.Pass("THE FEED CAN BE DESERIALIZED SUCCESSFULLY");
                }
            }
        }
Example #7
0
        public void CommandTest()
        {
            XmlSerializer serializer = new XmlSerializer(typeof(Command));
            StringWriter stringWriter = new StringWriter();
            XmlWriter xmlWriter = XmlWriter.Create(stringWriter);
            Command cmd = new Command(); // TODO: Initialize to an appropriate value
            cmd.Method = "RunLine";//RunLine(float length, float speed, float acceleration)
            cmd.Parameters.Add(1.0f);
            cmd.Parameters.Add(1.0f);
            cmd.Parameters.Add(1.0f);

            serializer.Serialize(xmlWriter, cmd);
            xmlWriter.Flush();

            Debug.WriteLine(stringWriter.ToString());

            //XmlSerializer serializer = new XmlSerializer(typeof(Command));
            StringReader stringReader = new StringReader(stringWriter.ToString());
            XmlReader xmlReader = XmlReader.Create(stringReader);
            if (serializer.CanDeserialize(xmlReader))
            {
                object o = serializer.Deserialize(xmlReader);
                if (o is Command)
                {
                    Command cmdDeserialized = (Command)o;
                    Debug.WriteLine(cmdDeserialized.ToString());
                }
            }
        }
        /// <summary>
        /// Returns the shortcut from the specified file.
        /// </summary>
        /// <exception cref="FileNotFoundException">The file not found.</exception>
        /// <exception cref="ShortcutFileAccessException">The format of the shortcut was invalid</exception>
        public IShortcut ReadShortcut()
        {
            if (!File.Exists(this.FilePath))
            {
                throw new FileNotFoundException();
            }

            try
            {
                // Load the file
                var xDoc = XDocument.Load(this.FilePath);

                var serializer = new XmlSerializer(typeof(Shortcut));
                var reader = xDoc.CreateReader();
                if (!serializer.CanDeserialize(reader))
                {
                    throw new ShortcutFileFormatException();
                }

                // Deserialize the shortcut
                var shortcut = (Shortcut)serializer.Deserialize(reader);

                return shortcut;
            }
            catch (Exception)
            {
                throw new ShortcutFileFormatException();
            }
        }
Example #9
0
 public static Q3ApiReply GetReply(XmlReader r)
 {
     XmlSerializer s = new XmlSerializer(typeof(Q3ApiReply));
     if (s.CanDeserialize(r))
         return s.Deserialize(r) as Q3ApiReply;
     else
         return null;
 }
Example #10
0
 public static Package GetXmlData(string path)
 {
     var xml = XDocument.Parse(File.ReadAllText(path));
     XmlSerializer xmlSerializer = new XmlSerializer(typeof(Package));
     if (xmlSerializer.CanDeserialize(xml.CreateReader()))
     {
         Package serXml = (Package)xmlSerializer.Deserialize(xml.CreateReader());
         return serXml;
     }
     return null;
 }
Example #11
0
        private static AssemblyBinding GetRedirectList(XElement element)
        {
            var serializer = new XmlSerializer(typeof(AssemblyBinding));
            if (!serializer.CanDeserialize(element.CreateReader()))
            {
                Error("Unable to deserialize assembly bindings, please ensure xml is valid", true);

                return null;
            }

            return serializer.Deserialize(element.CreateReader()) as AssemblyBinding;
        }
Example #12
0
		/// <summary>
		/// Deserialize an object from UTF8 Xml
		/// </summary>
		/// <param name="type"></param>
		/// <param name="xml"></param>
		/// <returns></returns>
		public static object DeserializeXml(Type type, string xml)
		{
			object data = null;
			using (MemoryStream ms = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(xml)))
			{
				XmlSerializer xs = new XmlSerializer(type);
				XmlReader xr = XmlReader.Create(ms);
				if (xs.CanDeserialize(xr))
					data = xs.Deserialize(xr);
			}
			return data;
		}
        public void Will_generate_trx_xml()
        {
            //Since the generated file is through GUID, we cannot do a simply string compare.

            var transformer = new TrxXmlTransformer(GetFileSystemWrapper());
            var summary = BuildTestCaseSummary();
            var result = transformer.Transform(summary);

            XmlReader xr = new XmlTextReader(new StringReader(result));
            XmlSerializer xs = new XmlSerializer(typeof(TestRunType));

            Assert.True(xs.CanDeserialize(xr));

            TestRunType trx = (TestRunType)xs.Deserialize(xr);


            var testDefinitions =
                trx.Items.GetInstance<TestDefinitionType>(VSTSExtensions.TestRunItemType.TestDefinition).Items.Cast<UnitTestType>().ToArray();

            Assert.Equal(testDefinitions.Count(), 4);

            for (int i = 0; i < testDefinitions.Count(); i++)
            {
                var vststUnitTest = testDefinitions[i];
                var testSummary = summary.Tests[i];

                Assert.Equal(vststUnitTest.TestMethod.name, testSummary.TestName);
                Assert.Equal(vststUnitTest.TestMethod.adapterTypeName, "Microsoft.VisualStudio.TestTools.TestTypes.Unit.UnitTestAdapter");
            }

            var testResults =
                trx.Items.GetInstance<ResultsType>(VSTSExtensions.TestRunItemType.Results).Items.Cast<UnitTestResultType>().ToArray();
            Assert.Equal(testResults.Count(), 4);

            for (int i = 0; i < testResults.Count(); i++)
            {
                var vststUnitTestResult = testResults[i];
                var testSummary = summary.Tests[i];

                Assert.Equal(vststUnitTestResult.testName,testSummary.TestName);
                Assert.Equal(vststUnitTestResult.outcome,testSummary.ResultsAllPassed ? "Passed":"Failed");
                if (vststUnitTestResult.Items != null && vststUnitTestResult.Items.Any())
                    Assert.Equal(((OutputType)vststUnitTestResult.Items[0]).ErrorInfo.Message, testSummary.TestResults[0].Message);
            }

            var counters = (CountersType)
                trx.Items.GetInstance<TestRunTypeResultSummary>(VSTSExtensions.TestRunItemType.ResultSummary)
                    .Items.First();

            Assert.Equal(counters.passed,2);
            Assert.Equal(counters.failed,2);
        }
 public void XmlImportTest1()
 {
     var actual = new FeedConfigItemList();
     var serializer = new XmlSerializer(actual.GetType());
     var sr = new StringReader(Properties.Resources.XmlImportTest1);
     var xmlr = XmlReader.Create(sr);
     if (serializer.CanDeserialize(xmlr))
     {
         actual = (FeedConfigItemList)serializer.Deserialize(xmlr);
     }
     xmlr.Close();
     sr.Close();
     Assert.AreEqual(16, actual.Items.Count);
 }
        public MessageWrapper Deserialise(string xml)
        {
            var x = new XmlSerializer(typeof(MessageWrapper));

            if (x.CanDeserialize(XmlReader.Create(new StringReader(xml))))
            {
                var message = x.Deserialize(new StringReader(xml));
                return message as MessageWrapper;
            }
            else
            {
                return null;
            }
        }
Example #16
0
 public List<NqsSettingItem> Load()
 {
     var res = new List<NqsSettingItem>();
     using (var file = new StreamReader(_fileName))
     {
         using (XmlReader reader = XmlReader.Create(file))
         {
             var serilizer = new XmlSerializer(typeof (List<NqsSettingItem>));
             if (serilizer.CanDeserialize(reader))
             {
                 res = serilizer.Deserialize(reader) as List<NqsSettingItem>;
             }
         }
     }
     return res;
 }
Example #17
0
		////////////////////////////////////////////////////////////////////////////////////////////////////
		/// <summary>	Deserialize a property set definition. </summary>
		///
		/// <param name="xmlStream">	The XML stream. </param>
		///
		/// <returns>	A property set definition. </returns>
		public static PropertySetDefinition DeserializeDefinition(XmlReader xmlStream)
		{
			if (xmlStream == null)
			{
				return null;
			}

			// Deserialize the definition xml
			var serializer = new XmlSerializer(typeof(PropertySetDefinition));
			if (!serializer.CanDeserialize(xmlStream))
			{
				return null;
			}

			return serializer.Deserialize(xmlStream) as PropertySetDefinition;
		}
        /// <summary>
        /// Process response
        /// </summary>
        private void processResponse()
        {
            XmlSerializer xml = null;
            Stream stream = this.Response.GetResponseStream();
            XmlReader reader = XmlReader.Create(stream);

            //for: UploadDone
            xml = new XmlSerializer(typeof(Progress));
            if (xml.CanDeserialize(reader))
            {
                Progress progressInfo = (Progress)xml.Deserialize(reader);
                if (Progress != null)
                {
                    Progress.Invoke(this, progressInfo);
                }
            }
        }
Example #19
0
 public static List<Command> Deserialize(string message)
 {
     List<Command> cmd = null;
     XmlSerializer serializer = new XmlSerializer(typeof(List<Command>));
     XmlReader xmlReader = XmlReader.Create(new StringReader(message));
     if (serializer.CanDeserialize(xmlReader))
     {
         object o = serializer.Deserialize(xmlReader);
         if (o is List<Command>)
         {
             cmd = (List<Command>)o;
         }
     }
     else
     {
         Console.WriteLine("could not deserialize message");
     }
     return cmd;
 }
Example #20
0
        private void ProcessRequest(IAsyncResult result)
        {
            if (result.IsCompleted && request != null)
            {
                WebResponse response = request.EndGetResponse(result);
                using (Stream input = response.GetResponseStream())
                {
                    using (XmlReader rdr = XmlReader.Create(input))
                    {
                        XmlSerializer serializer = new XmlSerializer(typeof(EntryList));
                        bool success = serializer.CanDeserialize(rdr);
                        EntryList list = (EntryList)serializer.Deserialize(rdr);
                        int stupid = 0;

                    }
                }
                return;
            }
        }
Example #21
0
        /// <summary>
        /// Loads a game
        /// </summary>
        /// <param name="data">Game to load</param>
        /// <param name="path">Filepath</param>
        /// <returns>True if successful, false if failure</returns>
        public static bool LoadGame(ref GameData data, string path)
        {
            XmlSerializer serializerObj = new XmlSerializer(typeof(GameData));
            TextReader textReader = new StreamReader(path);

            if (!serializerObj.CanDeserialize(XmlReader.Create(textReader)))
            {
                textReader.Close();
                return false;
            }
            textReader.Close();
            textReader = new StreamReader(path);

            data = (GameData)serializerObj.Deserialize(textReader);
            textReader.Close();

            data.BoardStates.ForEach(b => b.ChangeToDimensionalArray());

            return true;
        }
Example #22
0
        public static AbstractMessage parse(XmlDocument message)
        {
            AbstractMessage concreteMessage;
            XmlSerializer xmlSerializer = new XmlSerializer(typeof(ChatMessage));
            StringReader xmlstring = new StringReader(message.InnerXml.ToString());

            XmlReader reader = XmlReader.Create(xmlstring);
            reader.MoveToContent();
            if (xmlSerializer.CanDeserialize(reader))
            {
                concreteMessage = xmlSerializer.Deserialize(reader) as ChatMessage;
            }
            else
            {
                throw new InvalidOperationException();
            }

            reader.Close();
            return concreteMessage;
        }
Example #23
0
        /// <summary>
        /// Загружает файл XML
        /// </summary>
        /// <param name="fname">Имя файла</param>
        /// <returns>Возвращает класс контекста</returns>
        public static Context loadXML(string fname)
        {
            Context Ctx = new Context();
            try
            {
                XmlReader xml = XmlReader.Create(fname);
                XmlSerializer XmlS = new XmlSerializer(Ctx.GetType());
                if (XmlS.CanDeserialize(xml))
                {
                    Ctx = (Context)XmlS.Deserialize(xml);
                    xml.Close();

                }
            }
            catch (Exception E)
            {
                System.Windows.Forms.MessageBox.Show(E.Message);
                Ctx = null;
            }
            return Ctx;
        }
        private Dictionary<MigrationType, long> ReadData()
        {
            List<MigrationTuple> data;

            using (var reader = new XmlTextReader(_filename))
            {
                var serializer = new XmlSerializer(typeof(List<MigrationTuple>));
                if (serializer.CanDeserialize(reader))
                {
                    data = (List<MigrationTuple>) serializer.Deserialize(reader);
                }
                else
                {
                    return new Dictionary<MigrationType, long>();
                }

            }

            return data.ToDictionary(tuple => tuple.MigrationType,
                                     tuple => tuple.Number);
        }
 public override object ConvertTo(
     ITypeDescriptorContext context,
     System.Globalization.CultureInfo culture,
     object value,
     Type destinationType)
 {
     XmlSerializer serializer = new XmlSerializer(typeof(PingDataType));
     XmlReader reader = new XmlTextReader(new StringReader(value as string));
     if (!serializer.CanDeserialize(reader))
         throw new NotSupportedException();
     IObjectDataType toRet = (IObjectDataType)serializer.Deserialize(reader);
     if (destinationType == typeof(IObjectDataType))
         return toRet;
     if (destinationType == typeof(string))
         return toRet.ToString();
     if (destinationType == typeof(bool))
         return toRet.asBoolean();
     if (destinationType == typeof(tristate))
         return toRet.asBoolean() ? tristate.yes : tristate.no;
     throw new NotSupportedException();
 }
Example #26
0
        public static void XmlToHistory(string path, out List<HistoryRecord> output)
        {
            if (!string.IsNullOrEmpty(path))
            {
                using (XmlReader reader = XmlReader.Create(path))
                {
                    XmlSerializer serialiser = new XmlSerializer(typeof(List<HistoryRecord>));

                    if (serialiser.CanDeserialize(reader))
                    {
                        var list = serialiser.Deserialize(reader) as List<HistoryRecord>;
                        if (list != null)
                        {
                            output = list;
                            return;
                        }
                    }
                }
            }

            output = new List<HistoryRecord>();
        }
		public bool ReadObject(XPathResult result, XPathNavigator node, out object value)
		{
			var rootOverride = new XmlRootAttribute(node.LocalName)
			{
				Namespace = node.NamespaceURI
			};

			var serializer = new XmlSerializer(result.Type, rootOverride);

			using (var reader = node.ReadSubtree())
			{
				reader.MoveToContent();
				if (serializer.CanDeserialize(reader))
				{
					value = serializer.Deserialize(reader);
					return true;
				}				
			}

			value = null;
			return false;
		}
        public static List<TutorialEntry> LoadTutsFromFile()
        {
            List<TutorialEntry> isis = new List<TutorialEntry>();
            XmlSerializer xs = new XmlSerializer(typeof(List<TutorialEntry>));

            XmlReader xd;
            xd = XmlReader.Create(filePath);
            if (xs.CanDeserialize(xd))
            {

                isis = xs.Deserialize(xd) as List<TutorialEntry>;
                //ManageXmlFieldsNotDeserialisable(isis);
                //ManageNewLines(isis);
                xd.Close();
            }
            else
            {
                xd.Close();
                // Bad Characters in XML
                throw new Exception("Probleme dans le fichier de configuration List<TutorialEntry>.");
            }
            return isis;
        }
        public void CanDeserializeRssFeedFromXml()
        {
            var serializer = new XmlSerializer(_rssDocument.GetType());
            using (var storage = IsolatedStorageFile.GetUserStoreForApplication())
            {
                if (!storage.FileExists(SimpleRssPath))
                {
                    using (var filestream = new IsolatedStorageFileStream(SimpleRssPath, FileMode.Create, storage))
                    {
                        serializer.Serialize(filestream, _rssDocument);
                    }
                }

                using (var filestream = storage.OpenFile(SimpleRssPath, FileMode.Open))
                {
                    using (var reader = XmlReader.Create(filestream))
                    {
                        Assert.IsTrue(serializer.CanDeserialize(reader));
                        var resultantObject = serializer.Deserialize(reader);

                        //Assert that the result object is of the expected type (some derivative of IFeed)
                        Assert.IsInstanceOfType(resultantObject, _rssDocument.GetType());

                        //Assert that the two objects are distinct instances
                        Assert.AreNotSame(_rssDocument, resultantObject);

                        //Cast the object back into an IFeed and perform some specific assertions
                        var resultantFeed = resultantObject as IFeed;
                        Assert.AreEqual(_rssDocument.Title, resultantFeed.Title);
                        Assert.AreEqual(_rssDocument.LastUpdated, resultantFeed.LastUpdated);
                        Assert.AreEqual(_rssDocument.FeedUri, resultantFeed.FeedUri);
                        Assert.AreEqual(_rssDocument.FeedType, resultantFeed.FeedType);
                        Assert.AreEqual(_rssDocument.Items.Count, resultantFeed.Items.Count);
                    }
                }
            }
        }
Example #30
0
 public Userdata(String loadpath)
 {
     try
     {
         XmlSerializer xs = new XmlSerializer(typeof(Userdata));
         XmlReader xr = XmlReader.Create(loadpath);
         if (xs.CanDeserialize(xr))
         {
             this.Copy((Userdata)xs.Deserialize(xr));
         }
         else
         {
             this.Copy(new Userdata());
         }
         xr.Close();
     }
     catch (Exception ex)
     {
         String errorlogDir = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + "\\TweetShutdown\\" + "error.log";
         String Date = DateTime.Now.ToShortDateString();
         String Time = DateTime.Now.ToShortTimeString();
         File.AppendAllText(errorlogDir, "\r\n" + Date + " " + Time + "\t" + ex.Message);
     }
 }