protected override T OnGetBody <T>(XmlDictionaryReader reader) { Fx.Assert(reader is XmlByteStreamReader, "reader should be XmlByteStreamReader"); if (this.IsDisposed) { throw FxTrace.Exception.ObjectDisposed(SR.ObjectDisposed("message")); } Type typeT = typeof(T); if (typeof(Stream) == typeT) { Stream stream = (reader as XmlByteStreamReader).ToStream(); reader.Close(); return((T)(object)stream); } else if (typeof(byte[]) == typeT) { byte[] buffer = (reader as XmlByteStreamReader).ToByteArray(); reader.Close(); return((T)(object)buffer); } throw FxTrace.Exception.AsError( new NotSupportedException(SR.ByteStreamMessageGetTypeNotSupported(typeT.FullName))); }
public void Load(string filename) { FileStream stream = new FileStream(filename, FileMode.Open); XmlDictionaryReader reader = XmlDictionaryReader.CreateTextReader(stream, new XmlDictionaryReaderQuotas()); try { DataContractSerializer serializer = new DataContractSerializer(typeof(Level)); Level thisLevel = (Level)serializer.ReadObject(reader, true); this = thisLevel; } catch (Exception e) { reader.Close(); stream.Close(); Console.WriteLine("load failed. " + e.Message); Irbis.Irbis.WriteLine("load failed. " + e.Message); Irbis.Irbis.WriteLine("Stacktrace:\n" + e.StackTrace + "\n"); Irbis.Irbis.WriteLine("attempting conversion..."); LoadOld(filename); } finally { reader.Close(); stream.Close(); } }
private static XmlRpcMessage CreateXmlRpcMessage(System.ServiceModel.Channels.Message message) { XmlDictionaryReader messageReader = message.GetReaderAtBodyContents(); string methodName; do { if (messageReader.IsStartElement(XmlRpcProtocol.MethodCall)) { messageReader.ReadStartElement(); messageReader.MoveToContent(); if (!messageReader.IsStartElement(XmlRpcProtocol.MethodName)) { throw new XmlRpcFormatException(Properties.Resources.EXCEPTION_MISSING_METHODNAME); } else { messageReader.ReadStartElement(); messageReader.MoveToContent(); if (messageReader.NodeType == XmlNodeType.Text) { methodName = messageReader.ReadString(); messageReader.ReadEndElement(); } else { throw new XmlRpcFormatException(Properties.Resources.EXCEPTION_MISSING_METHODNAME); } if (messageReader.IsStartElement(XmlRpcProtocol.Params)) { return(new XmlRpcMessage(methodName, messageReader, true)); } else { messageReader.Close(); return(new XmlRpcMessage(methodName)); } } } else if (messageReader.IsStartElement(XmlRpcProtocol.MethodResponse)) { messageReader.ReadStartElement(); messageReader.MoveToContent(); if (messageReader.IsStartElement(XmlRpcProtocol.Params)) { return(new XmlRpcMessage(messageReader)); } else { messageReader.Close(); return(new XmlRpcMessage()); } } }while (messageReader.Read()); throw new XmlRpcFormatException(Properties.Resources.EXCEPTION_INVALID_MESSAGE); }
public override Message ReadMessage(System.IO.Stream stream, int maxSizeOfHeaders, string contentType) { XmlDictionaryReader messageReader = XmlDictionaryReader.CreateTextReader(stream, _factory.ReaderQuotas); string methodName; while (messageReader.Read()) { if (messageReader.IsStartElement(XmlRpcProtocol.MethodCall)) { messageReader.ReadStartElement(); messageReader.MoveToContent(); if (!messageReader.IsStartElement(XmlRpcProtocol.MethodName)) { throw new XmlRpcFormatException("Missing method name"); } else { messageReader.ReadStartElement(); messageReader.MoveToContent(); if (messageReader.NodeType == XmlNodeType.Text) { methodName = messageReader.ReadString(); messageReader.ReadEndElement(); } else { throw new XmlRpcFormatException("Missing method name"); } if (messageReader.IsStartElement(XmlRpcProtocol.Params)) { return(new XmlRpcMessage(methodName, messageReader)); } else { messageReader.Close(); return(new XmlRpcMessage(methodName)); } } } else if (messageReader.IsStartElement(XmlRpcProtocol.MethodResponse)) { messageReader.ReadStartElement(); messageReader.MoveToContent(); if (messageReader.IsStartElement(XmlRpcProtocol.Params)) { return(new XmlRpcMessage(messageReader)); } else { messageReader.Close(); return(new XmlRpcMessage()); } } } throw new XmlRpcFormatException("Invalid Message"); }
public MessageNumberRolloverFault(FaultCode code, FaultReason reason, XmlDictionaryReader detailReader, ReliableMessagingVersion reliableMessagingVersion) : base(code, WsrmFeb2005Strings.MessageNumberRollover, reason, true, true) { try { this.SequenceID = WsrmUtilities.ReadIdentifier(detailReader, reliableMessagingVersion); if (reliableMessagingVersion == ReliableMessagingVersion.WSReliableMessaging11) { detailReader.ReadStartElement(DXD.Wsrm11Dictionary.MaxMessageNumber, WsrmIndex.GetNamespace(reliableMessagingVersion)); string maxMessageNumberString = detailReader.ReadContentAsString(); ulong maxMessageNumber; if (!UInt64.TryParse(maxMessageNumberString, out maxMessageNumber) || (maxMessageNumber <= 0)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException( SR.GetString(SR.InvalidSequenceNumber, maxMessageNumber))); } // otherwise ignore value detailReader.ReadEndElement(); } } finally { detailReader.Close(); } }
protected override void OnWriteStartBody(XmlDictionaryWriter writer) { if (this.startBodyFragment != null || this.fullBodyFragment != null) { WriteStartInnerMessageWithId(writer); return; } switch (this.state) { case BodyState.Created: case BodyState.Encrypted: this.InnerMessage.WriteStartBody(writer); return; case BodyState.Signed: case BodyState.EncryptedThenSigned: XmlDictionaryReader reader = fullBodyBuffer.GetReader(0); writer.WriteStartElement(reader.Prefix, reader.LocalName, reader.NamespaceURI); writer.WriteAttributes(reader, false); reader.Close(); return; case BodyState.SignedThenEncrypted: writer.WriteStartElement(this.bodyPrefix, XD.MessageDictionary.Body, this.Version.Envelope.DictionaryNamespace); if (this.bodyAttributes != null) { XmlAttributeHolder.WriteAttributes(this.bodyAttributes, writer); } return; default: throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateBadStateException(nameof(OnWriteStartBody))); } }
/// <summary> /// Loads the content of a WordFormatter object (style settings used for pharagraph formatting) from an XML file. /// If the deserializatoin is unsuccessful, then a WordFormatter object with the default languages and styles is returned. /// In either case, the returned Formatter is still not initialized, as it has no reference to a Colorizer or to a Word Application. /// </summary> /// <param name="filePath">The complete file path where the file will be located at</param> /// <returns>The WordFormatter object filled with the contents of the file, but without initialization</returns> public static WordFormatter Deserialize(string filePath) { WordFormatter formatter; FileStream fs = null; XmlDictionaryReader reader = null; try { fs = new FileStream(filePath, FileMode.Open); reader = XmlDictionaryReader.CreateTextReader(fs, new XmlDictionaryReaderQuotas()); DataContractSerializer ser = new DataContractSerializer(typeof(WordFormatter)); formatter = (WordFormatter)ser.ReadObject(reader, true); } catch (Exception exception) { MessageBox.Show("Couldn't load the file at:\n" + filePath + "\n the language independent style will be set to default"); formatter = new WordFormatter(); formatter.SetToDefault(); } finally { if (reader != null) { reader.Close(); } if (fs != null) { fs.Close(); } } // The WordFormatter object is still not initialized here! (It has no reference to a Colorizer and Word Application) return(formatter); }
static void Main(string[] args) { #if NORMAL (new KontrolerCLI()).Uruchom(); #else const string FileName = "C:/Users/Julia/source/repos/Serialization/XML_Serialization/example.xml"; if (File.Exists(FileName)) { Console.WriteLine("Reading saved file"); Stream fs = File.OpenRead(FileName); DataContractSerializer dcs = new DataContractSerializer(typeof(Gra.Ruch)); XmlDictionaryReader xdr = XmlDictionaryReader.CreateTextReader(fs, new XmlDictionaryReaderQuotas()); Gra.Ruch p = (Gra.Ruch)dcs.ReadObject(xdr); Console.WriteLine(String.Format("{0}, {1}, {2}, {3}", p.Czas, p.Liczba, p.StatusGry, p.Wynik)); xdr.Close(); fs.Close(); } else { throw new FileNotFoundException(); } #endif }
private Message TransformMessage2(Message oldMessage, string _security) { Message newMessage = null; MessageBuffer msgbuf = oldMessage.CreateBufferedCopy(int.MaxValue); Message tmpMessage = msgbuf.CreateMessage(); XmlDictionaryReader xdr = tmpMessage.GetReaderAtBodyContents(); XmlDocument xdoc = new XmlDocument(); xdoc.Load(xdr); xdr.Close(); XmlNamespaceManager nsmgr = new XmlNamespaceManager(xdoc.NameTable); MemoryStream ms = new MemoryStream(); XmlWriter xw = XmlWriter.Create(ms); xdoc.Save(xw); xw.Flush(); xw.Close(); ms.Position = 0; XmlReader xr = XmlReader.Create(ms); newMessage = Message.CreateMessage(oldMessage.Version, null, xr); newMessage.Headers.Add(MessageHeader.CreateHeader("Token", String.Empty, _security)); newMessage.Properties.CopyProperties(oldMessage.Properties); return(newMessage); }
private void ValidateDigestsOfTargetsInSecurityHeader(StandardSignedInfo signedInfo, SecurityTimestamp timestamp, bool isPrimarySignature, object signatureTarget, string id) { for (int i = 0; i < signedInfo.ReferenceCount; i++) { Reference reference = signedInfo[i]; base.AlgorithmSuite.EnsureAcceptableDigestAlgorithm(reference.DigestMethod); string str = reference.ExtractReferredId(); if (isPrimarySignature || (id == str)) { if ((((timestamp != null) && (timestamp.Id == str)) && (!reference.TransformChain.NeedsInclusiveContext && (timestamp.DigestAlgorithm == reference.DigestMethod))) && (timestamp.GetDigest() != null)) { reference.EnsureDigestValidity(str, timestamp.GetDigest()); base.ElementManager.SetTimestampSigned(str); } else if (signatureTarget != null) { reference.EnsureDigestValidity(id, signatureTarget); } else { XmlDictionaryReader signatureVerificationReader = base.ElementManager.GetSignatureVerificationReader(str, base.EncryptBeforeSignMode); if (signatureVerificationReader != null) { reference.EnsureDigestValidity(str, signatureVerificationReader); signatureVerificationReader.Close(); } } if (!isPrimarySignature) { return; } } } }
object IClientMessageFormatter.DeserializeReply(System.ServiceModel.Channels.Message message, object[] parameters) { object returnValue = null; XmlDictionaryReader bodyContentReader = message.GetReaderAtBodyContents(); bodyContentReader.ReadStartElement(XmlRpcProtocol.Params); if (bodyContentReader.IsStartElement(XmlRpcProtocol.Param)) { bodyContentReader.ReadStartElement(); if (bodyContentReader.IsStartElement(XmlRpcProtocol.Value)) { bodyContentReader.ReadStartElement(); if (bodyContentReader.NodeType == XmlNodeType.Text) { returnValue = bodyContentReader.ReadContentAs(_returnParameter.ParameterType, null); } else { returnValue = XmlRpcDataContractSerializationHelper.Deserialize(bodyContentReader, _returnParameter.ParameterType); } bodyContentReader.ReadEndElement(); } bodyContentReader.ReadEndElement(); } bodyContentReader.Close(); return(returnValue); }
/// <summary> /// Initializes the configuration data by reading the data from an XML configuration file /// </summary> public static void Initialize() { // temporary to write initial configuration data xml file // ConfigurationData.SaveDefaultValues(); // deserialize configuration data from file into internal object FileStream fs = null; try { fs = new FileStream("ConfigurationData.xml", FileMode.Open); XmlDictionaryReader reader = XmlDictionaryReader.CreateTextReader(fs, new XmlDictionaryReaderQuotas()); DataContractSerializer ser = new DataContractSerializer(typeof(ConfigurationData)); configurationData = (ConfigurationData)ser.ReadObject(reader, true); reader.Close(); } finally { // always close input file if (fs != null) { fs.Close(); } } }
public static T DeSerializeObject <T>(string fileName) { if (string.IsNullOrEmpty(fileName)) { return(default(T)); } T objectOut = default(T); try { FileStream fs = new FileStream(fileName, FileMode.Open); XmlDictionaryReader reader = XmlDictionaryReader.CreateTextReader(fs, new XmlDictionaryReaderQuotas()); DataContractSerializer ser = new DataContractSerializer(typeof(T)); objectOut = (T)ser.ReadObject(reader, true); reader.Close(); fs.Close(); } catch (Exception ex) { Console.WriteLine("ERROR while DEserializing object!"); Console.WriteLine(ex.Message); } return(objectOut); }
// binary serializing public static T DataContractDeepClone <T>(this T serializableObject) { T copy = default(T); if (serializableObject == null) { return(copy); } using (MemoryStream stream = new MemoryStream()) { DataContractSerializer serializer = new DataContractSerializer(serializableObject.GetType()); using (XmlDictionaryWriter binaryDictionaryWriter = XmlDictionaryWriter.CreateBinaryWriter(stream)) { serializer.WriteObject(binaryDictionaryWriter, serializableObject); binaryDictionaryWriter.Flush(); stream.Seek(0, SeekOrigin.Begin); using (XmlDictionaryReader binaryDictionaryReader = XmlDictionaryReader.CreateBinaryReader(stream, XmlDictionaryReaderQuotas.Max)) { copy = (T)serializer.ReadObject(binaryDictionaryReader); binaryDictionaryReader.Close(); } binaryDictionaryWriter.Close(); } stream.Close(); } return(copy); }
public void WriteXml(XmlWriter xmlWriter) { StringWriter textWriter = new StringWriter(CultureInfo.InvariantCulture); XmlTextWriter writer = new XmlTextWriter(textWriter); schema.Write(writer); writer.Flush(); UTF8Encoding utf8 = new UTF8Encoding(); byte[] wsdlText = utf8.GetBytes(textWriter.ToString()); XmlDictionaryReaderQuotas quota = new XmlDictionaryReaderQuotas(); quota.MaxDepth = 32; quota.MaxStringContentLength = 8192; quota.MaxArrayLength = 16384; quota.MaxBytesPerRead = 4096; quota.MaxNameTableCharCount = 16384; XmlDictionaryReader reader = XmlDictionaryReader.CreateTextReader(wsdlText, 0, wsdlText.GetLength(0), null, quota, null); if ((reader.MoveToContent() == XmlNodeType.Element) && (reader.Name == "xs:schema")) { xmlWriter.WriteNode(reader, false); } reader.Close(); }
public static string GetSubcode(XmlDictionaryReader headerReader, ReliableMessagingVersion reliableMessagingVersion) { string localName = null; try { string str3; WsrmFeb2005Dictionary dictionary = XD.WsrmFeb2005Dictionary; XmlDictionaryString namespaceUri = WsrmIndex.GetNamespace(reliableMessagingVersion); headerReader.ReadStartElement(dictionary.SequenceFault, namespaceUri); headerReader.ReadStartElement(dictionary.FaultCode, namespaceUri); XmlUtil.ReadContentAsQName(headerReader, out localName, out str3); if (str3 != WsrmIndex.GetNamespaceString(reliableMessagingVersion)) { localName = null; } headerReader.ReadEndElement(); while (headerReader.IsStartElement()) { headerReader.Skip(); } headerReader.ReadEndElement(); } finally { headerReader.Close(); } return(localName); }
public static T deserializeDataContract <T>(string path) { DeserializeEx = null; T rez; FileStream fs = null; XmlDictionaryReader reader = null; try { fs = new FileStream(path, FileMode.Open); reader = XmlDictionaryReader.CreateTextReader(fs, new XmlDictionaryReaderQuotas()); var serializer = new DataContractSerializer(typeof(T)); rez = (T)serializer.ReadObject(reader); } catch (Exception ex) { DeserializeEx = ex; return(default(T)); } finally { if (reader != null) { reader.Close(); } if (fs != null) { fs.Close(); } } return(rez); }
void IDispatchMessageFormatter.DeserializeRequest(System.ServiceModel.Channels.Message message, object[] parameters) { int paramCounter = 0; XmlDictionaryReader bodyContentReader = message.GetReaderAtBodyContents(); bodyContentReader.ReadStartElement(XmlRpcProtocol.Params); if (parameters.Length > 0) { while (bodyContentReader.IsStartElement(XmlRpcProtocol.Param) && paramCounter < parameters.Length) { bodyContentReader.ReadStartElement(); if (bodyContentReader.IsStartElement(XmlRpcProtocol.Value)) { bodyContentReader.ReadStartElement(); if (bodyContentReader.NodeType == XmlNodeType.Text && !string.IsNullOrEmpty(bodyContentReader.Value.Trim())) { parameters[paramCounter] = bodyContentReader.ReadContentAs(_parameterInfo[paramCounter].ParameterType, null); } else { parameters[paramCounter] = XmlRpcDataContractSerializationHelper.Deserialize(bodyContentReader, _parameterInfo[paramCounter].ParameterType); } bodyContentReader.ReadEndElement(); } bodyContentReader.ReadEndElement(); bodyContentReader.MoveToContent(); paramCounter++; } } bodyContentReader.ReadEndElement(); bodyContentReader.Close(); }
//Instantiates a list of SQL rules stored in the user_defined_rules.xml file //The config for each rule (containing the actual SQL code) is stored in the config file and is handled elsewhere private static IEnumerable <SQLRule> LoadSQLRules() { if (!File.Exists(sqlRulesXMLFile)) { return(new List <SQLRule>()); } IEnumerable <String> SQLRuleNames = new List <String>(); lock (sqlRulesXMLFile) { FileStream fs = new FileStream(sqlRulesXMLFile, FileMode.Open); XmlDictionaryReader reader = XmlDictionaryReader.CreateTextReader(fs, new XmlDictionaryReaderQuotas()); DataContractSerializer ser = new DataContractSerializer(typeof(IEnumerable <String>)); SQLRuleNames = (IEnumerable <String>)ser.ReadObject(reader, true); reader.Close(); fs.Close(); } IList <SQLRule> returnValue = new List <SQLRule>(); foreach (String ruleName in SQLRuleNames) { SQLRule rule = new SQLRule(); rule.RuleName.Value = ruleName; rule.RuleName.DefaultValue = ruleName; returnValue.Add(rule); } return(returnValue); }
public static void LoadProperties(IEnumerable <IConfigurable> configurables, String filePath) { lock (filePath) { List <ExecutableConfiguration> configs = new List <ExecutableConfiguration>(); //Load configurations FileStream fs = new FileStream(filePath, FileMode.Open); XmlDictionaryReader reader = XmlDictionaryReader.CreateTextReader(fs, new XmlDictionaryReaderQuotas()); DataContractSerializer ser = new DataContractSerializer(serializedType); configs = (List <ExecutableConfiguration>)ser.ReadObject(reader, true); reader.Close(); fs.Close(); //Set properties of configurables foreach (var config in configs) { var configurable = configurables.Where(c => c.GetType().ToString() == config.TypeName && ((IExecutable)c).Name == config.RuleName).FirstOrDefault(); if (configurable != null) { var propertyPairs = (from execProp in configurable.GetProperties() from configProp in config.Properties where execProp.Name == configProp.Name select new { ExecProperty = execProp, ConfigProperty = configProp }); foreach (var propertyPair in propertyPairs) { var execP = propertyPair.ExecProperty; var configP = propertyPair.ConfigProperty; execP.SetValue(configP.GetValue()); } } } } }
/// <summary> /// Writes the new import failure line. /// </summary> /// <param name="failure">The failure.</param> /// <param name="importFailuresReportFileName">Name of the import failures report file.</param> public void WriteNewImportFailureLine(ImportFailure failure, string importFailuresReportFileName) { bool reportExists = File.Exists(importFailuresReportFileName); List <ImportFailure> failures = new List <ImportFailure>(); if (reportExists) { using (FileStream fs = new FileStream(importFailuresReportFileName, FileMode.OpenOrCreate)) { XmlDictionaryReaderQuotas XRQ = new XmlDictionaryReaderQuotas(); XRQ.MaxStringContentLength = int.MaxValue; XmlDictionaryReader reader = XmlDictionaryReader.CreateTextReader(fs, XRQ); DataContractSerializer ser = new DataContractSerializer(typeof(List <ImportFailure>)); failures = (List <ImportFailure>)ser.ReadObject(reader, true); reader.Close(); fs.Close(); } } using (FileStream writer = new FileStream(importFailuresReportFileName, FileMode.OpenOrCreate)) { failures.Add(failure); DataContractSerializer ser = new DataContractSerializer(typeof(List <ImportFailure>)); //Write updated failures report ser.WriteObject(writer, failures); writer.Close(); } }
public override ArraySegment <byte> WriteMessage(Message message, int maxMessageSize, BufferManager bufferManager, int messageOffset) { String bodyContent = null; lastMessage = message.Headers.Action; XmlDictionaryReader reader = message.GetReaderAtBodyContents(); while (reader.Read()) { if (reader.Name == "request") { bodyContent = reader.ReadElementContentAsString(); break; } } reader.Close(); byte[] messageBytes = System.Text.Encoding.UTF8.GetBytes(bodyContent); int totalLength = messageBytes.Length + messageOffset; byte[] totalBytes = bufferManager.TakeBuffer(totalLength); Array.Copy(messageBytes, 0, totalBytes, messageOffset, messageBytes.Length); ArraySegment <byte> buffer = new ArraySegment <byte>( totalBytes, messageOffset, messageBytes.Length); return(buffer); }
static void DeserializeSurrogate(string filename) { // Create a new reader object. FileStream fs2 = new FileStream(filename, FileMode.Open); XmlDictionaryReader reader = XmlDictionaryReader.CreateTextReader(fs2, new XmlDictionaryReaderQuotas()); Console.WriteLine("Trying to deserialize with surrogate."); try { DataContractSerializer surrogateSerializer = CreateSurrogateSerializer(); Employee newemp = (Employee)surrogateSerializer.ReadObject(reader, false); reader.Close(); fs2.Close(); Console.WriteLine("Deserialization succeeded. \n\n"); Console.WriteLine("Deserialized Person data: \n\t {0} {1}", newemp.person.first_name, newemp.person.last_name); Console.WriteLine("\t Age: {0} \n", newemp.person.age); Console.WriteLine("\t Date Hired: {0}", newemp.date_hired.ToShortDateString()); Console.WriteLine("\t Salary: {0}", newemp.salary); Console.WriteLine("Press Enter to end or continue"); Console.ReadLine(); } catch (SerializationException serEx) { Console.WriteLine(serEx.Message); Console.WriteLine(serEx.StackTrace); } }
/** * XmlDictionaryReader: Safe by Default Example * When using a default XmlDictionaryReader, upon attempting to read the XML file it will throw an exception when it sees the DTD. */ protected void Page_Load(object sender, EventArgs e) { bool expectedSafe = true; xmlText = FixXMLBaseURI(xmlText, appPath); // makes sure that the external entity gets referenced at the correct base URI XmlDictionaryReader dict = XmlDictionaryReader.CreateTextReader(Encoding.ASCII.GetBytes(xmlText), XmlDictionaryReaderQuotas.Max); try { // parsing the XML StringBuilder sb = new StringBuilder(); while (dict.Read()) { sb.Append(dict.Value); } // testing the result if (sb.ToString().Contains("SUCCESSFUL")) { PrintResults(expectedSafe, false, sb.ToString()); // unsafe: successful XXE injection } else { PrintResults(expectedSafe, true, sb.ToString()); // safe: empty or unparsed XML } } catch (Exception ex) { PrintResults(expectedSafe, true, ex); // safe: exception thrown when parsing XML } finally { dict.Close(); } }
protected override void OnWriteBodyContents(XmlDictionaryWriter writer) { switch (this.state) { case BodyState.Created: this.InnerMessage.WriteBodyContents(writer); return; case BodyState.Signed: case BodyState.EncryptedThenSigned: XmlDictionaryReader reader = fullBodyBuffer.GetReader(0); reader.ReadStartElement(); while (reader.NodeType != XmlNodeType.EndElement) { writer.WriteNode(reader, false); } reader.ReadEndElement(); reader.Close(); return; case BodyState.Encrypted: case BodyState.SignedThenEncrypted: this.encryptedBodyContent.WriteTo(writer, ServiceModelDictionaryManager.Instance); break; default: throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateBadStateException(nameof(OnWriteBodyContents))); } }
public static T Read(string fileName) { Environment.SetEnvironmentVariable("MONO_REFLECTION_SERIALIZER", "yes"); T variable = new T(); try { using (FileStream reader = new FileStream(fileName, FileMode.Open)) { var ser = new DataContractSerializer(typeof(T)); XmlDictionaryReader xmlreader = XmlDictionaryReader.CreateTextReader(reader, new XmlDictionaryReaderQuotas()); variable = ser.ReadObject(xmlreader, true) as T; //ser.Deserialize(reader) as T; xmlreader.Close(); reader.Close(); } } catch (System.IO.FileNotFoundException e) { UnityEngine.Debug.LogWarning("Could not read from file: " + fileName + ". " + e); } catch (System.Exception e) { UnityEngine.Debug.LogWarning("Exception: " + fileName + ". " + e); } finally { } return(variable); }
public static List <T> JsonToObject <T>(string jsonData, string jsonKey) { try { object objChannelInfo = new JavaScriptSerializer().DeserializeObject(jsonData); Dictionary <string, object> list = (Dictionary <string, object>)objChannelInfo; object val = null; list.TryGetValue(jsonKey, out val); using (MemoryStream ms2 = new MemoryStream(Encoding.UTF8.GetBytes(val.ToString()))) { //Deserialize into generic List DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(List <T>)); List <T> jsonList = ser.ReadObject(ms2) as List <T>; // Serialize JSON MemoryStream to WCS XML wire format XmlDictionaryReader xdrJson = JsonReaderWriterFactory.CreateJsonReader(ms2, XmlDictionaryReaderQuotas.Max); xdrJson.Read(); string xml = xdrJson.ReadOuterXml(); xdrJson.Close(); ms2.Close(); return(jsonList); } } catch (Exception ex) { throw ex; } }
/// <summary> /// Utility to deserialize the Windows update result stored in a file /// </summary> /// <param name="filePath">Path of the file which contains <see cref="WindowsUpdateOperationResult"/></param> /// <returns>Deserialized <see cref="WindowsUpdateOperationResult"/> object</returns> public static WindowsUpdateOperationResult Deserialize(string filePath) { if (!File.Exists(filePath)) { return(null); } FileStream fs = null; try { fs = new FileStream(filePath, FileMode.Open); using (XmlDictionaryReader reader = XmlDictionaryReader.CreateTextReader(fs, new XmlDictionaryReaderQuotas())) { DataContractSerializer ser = new DataContractSerializer(typeof(WindowsUpdateOperationResult)); // Deserialize the data and read it from the instance. WindowsUpdateOperationResult result = (WindowsUpdateOperationResult)ser.ReadObject(reader, true); reader.Close(); fs.Close(); return(result); } } finally { if (fs != null) { fs.Dispose(); } } }
public AxModelSettings LoadSettings() { AxModelSettings axModelSettings = null; //XmlDocument doc = new XmlDocument(); //var xsSubmit = new DataContractSerializer(typeof(AxModelSettings)); var filePath = this.GetFilePath(); if (File.Exists(filePath)) { FileStream fs = new FileStream(filePath, FileMode.Open); XmlDictionaryReader reader = XmlDictionaryReader.CreateTextReader(fs, new XmlDictionaryReaderQuotas()); DataContractSerializer ser = new DataContractSerializer(typeof(AxModelSettings)); // Deserialize the data and read it from the instance. axModelSettings = (AxModelSettings)ser.ReadObject(reader, true); reader.Close(); fs.Close(); /* * doc.Load(filePath); * * using (TextReader reader = new StringReader(doc.InnerXml)) * { * axModelSettings = (AxModelSettings)xsSubmit.Deserialize(reader); * } */ } return(axModelSettings ?? (axModelSettings = new AxModelSettings())); }
void CacheAllHeaderIds() { int crtHeaderPosition = 0; XmlDictionaryReader reader = this.Message.Headers.GetReaderAtHeader(0); while (crtHeaderPosition < this.Message.Headers.Count) { if (reader.NodeType != XmlNodeType.Element) { reader.MoveToContent(); } reader.MoveToStartElement(); if (crtHeaderPosition != this.headerIndex) { // Look if the header has an d:Id attribute. // The headers's children are not of interest, because // only top-level SOAP header blocks (/s:Envelope/s:Header/*) can be referenced. string idValue = reader.GetAttribute(ProtocolStrings.IdAttributeName, this.DiscoveryInfo.DiscoveryNamespace); if (!String.IsNullOrEmpty(idValue)) { this.blockIds.AddHeader(idValue, crtHeaderPosition); } } reader.Skip(); crtHeaderPosition++; } reader.Close(); }