Exemplo n.º 1
0
        public static Exception ToException(string exceptionString)
        {
            try
            {
                var serializer   = new NetDataContractSerializer();
                var stringReader = new StringReader(exceptionString);

                // disabling DTD processing on XML streams that are not over the network.
                var settings = new XmlReaderSettings
                {
                    DtdProcessing = DtdProcessing.Prohibit,
                    XmlResolver   = null
                };
                using (var textStream = XmlReader.Create(stringReader, settings))
                {
                    return((Exception)serializer.ReadObject(textStream));
                }
            }
            catch (Exception ex)
            {
                // add the message as service exception
                ServiceExceptionData exceptionData;
                if (TryDeserializeExceptionData(exceptionString, out exceptionData))
                {
                    return(new ServiceException(exceptionData.Type, exceptionData.Message));
                }
                throw ex;
            }
        }
Exemplo n.º 2
0
		public bool LoadObject<T>(string key, ref T dest)
		{
			Stream reader = null;
			try
			{
				reader = GetReader(key);

				if (reader != null)
				{
					NetDataContractSerializer serial = new NetDataContractSerializer();
					//XmlSerializer serial = new XmlSerializer(typeof(T));
					dest = (T)serial.ReadObject(reader);
					return true;
				}
			}
			catch (Exception e)
			{
				SLogManager.getInstance().getClassLogger(GetType()).Error(e.Message);
			}
			finally
			{
				if (reader != null) reader.Close();
			}

			return false;
		}
        private static object ReadFaultDetail(Message reply)
        {
            const string detailElementName = "Detail";

            using (var reader = reply.GetReaderAtBodyContents())
            {
                // 查找<detail>
                while (reader.Read())
                {
                    if (reader.NodeType == XmlNodeType.Element && reader.LocalName == detailElementName)
                    {
                        break;
                    }
                }

                if (reader.NodeType != XmlNodeType.Element || reader.LocalName != detailElementName || (!reader.Read()))
                {
                    return(null);
                }

                var serializer = new NetDataContractSerializer();
                try
                {
                    return(serializer.ReadObject(reader));
                }
                catch (FileNotFoundException)
                {
                    //当序列化器载入程序集出错时
                    return(null);
                }
            }
        }
Exemplo n.º 4
0
        private List <MessageDto> ParseFiles(List <FileItem> files)
        {
            var list = new List <MessageDto>();
            var ns   = new NetDataContractSerializer();

            foreach (var file in files)
            {
                try
                {
                    using (var m = new MemoryStream(file.Data))
                    {
                        var messageDto = ns.ReadObject(m) as MessageDto;
                        if (messageDto == null || string.IsNullOrEmpty(messageDto.DeviceCode) ||
                            string.IsNullOrEmpty(messageDto.SerialNumber) || !messageDto.Tags.Any())
                        {
                            continue;
                        }

                        list.Add(messageDto);
                    }
                }
                catch (Exception e)
                {
                    _logger.ErrorFormat("ParseFiles Error {0}", e, file.Path);
                }
            }

            return(list);
        }
Exemplo n.º 5
0
        static void DeserializeAndReserialize(string path)
        {
            Console.WriteLine(
                "Deserializing new version to old version");
            FileStream fs = new FileStream(path,
                                           FileMode.Open);
            XmlDictionaryReader reader = XmlDictionaryReader.
                                         CreateTextReader(fs, new XmlDictionaryReaderQuotas());

            // Create the serializer.
            NetDataContractSerializer ser =
                new NetDataContractSerializer();
            // Deserialize version 1 of the data.
            PurchaseOrder PO_V1 =
                (PurchaseOrder)ser.ReadObject(reader, false);

            Console.WriteLine("Order Date:{0}",
                              PO_V1.PurchaseDate.ToLongDateString());
            fs.Close();

            Console.WriteLine(
                "Reserialize the object with extension data intact");
            // First change the order date.
            DateTime newDate = PO_V1.PurchaseDate.AddDays(10);

            PO_V1.PurchaseDate = newDate;

            // Create a new FileStream to write with.
            FileStream writer = new FileStream(path, FileMode.Create);

            // Serialize the object with changed data.
            ser.WriteObject(writer, PO_V1);
            writer.Close();
        }
Exemplo n.º 6
0
        public static void LoadFromDevice <T>(String path, Action <T> userCallback) where T : class
        {
            if (_storageDevice == null)
            {
                Console.WriteLine("Storage Device was null");
                userCallback(null);
                return;
            }

            _storageDevice.BeginOpenContainer(Constants.Locations.ContainerName, openResult => {
                using (var sd = _storageDevice.EndOpenContainer(openResult)) {
                    if (!sd.FileExists(path))
                    {
                        userCallback(null);
                        return;
                    }

                    var serializer = new NetDataContractSerializer();
                    using (var fs = sd.OpenFile(path, FileMode.Open)) {
                        using (var reader = XmlDictionaryReader.CreateTextReader(fs, new XmlDictionaryReaderQuotas {
                            MaxDepth = Int32.MaxValue
                        })) {
                            T loadedObject = null;
                            try {
                                loadedObject = serializer.ReadObject(reader, true) as T;
                            } catch (Exception e) {
                                Console.WriteLine("Failed loading {0} from asset. {1}", path, e.StackTrace);
                            }
                            userCallback(loadedObject);
                        }
                    }
                }
            }, null);
        }
Exemplo n.º 7
0
    static void Main(string[] args)
    {
        // create a new Person object
        Person myPerson = new Person("Adam Freeman", "London");

        // open the stream to the file we want to store the data in
        Stream myStream = new MemoryStream();

        // create the serialize
        NetDataContractSerializer serializer = new NetDataContractSerializer();

        // serialize the Person object
        serializer.WriteObject(myStream, myPerson);

        // reset the cursor on the stream and read the serialized data
        myStream.Seek(0, SeekOrigin.Begin);
        StreamReader myReader = new StreamReader(myStream);

        Console.WriteLine(myReader.ReadToEnd());

        // reset the cursor and deserialize the object
        myStream.Seek(0, SeekOrigin.Begin);
        Person myDeserializedPerson = (Person)serializer.ReadObject(myStream);

        // wait for input before exiting
        Console.WriteLine("Press enter to finish");
        Console.ReadLine();
    }
Exemplo n.º 8
0
        private object Recall(string fileName)
        {
            XmlReader reader = null;

            try {
                //reader = new XmlTextReader(fileName);
                reader = XmlReader.Create(fileName);
                //reader.Namespaces = false;
                NetDataContractSerializer ser = new NetDataContractSerializer();
                //DataContractSerializer ser = new DataContractSerializer(typeof(ArrayList));
                //ser.AssemblyFormat = FormatterAssemblyStyle.Simple;
                //DataContractSerializer ser = new DataContractSerializer(typeof(ArrayList));
                object deserializedObj = ser.ReadObject(reader, false);
                return(deserializedObj);
            }
            catch (Exception) {
                throw;
            }
            finally {
                if (reader != null)
                {
                    reader.Close();
                }
            }
        }
Exemplo n.º 9
0
        private object Recall(string fileName)
        {
            Stream        stream = null;
            XmlTextReader reader = null;

            try {
                stream = new FileStream(fileName, FileMode.Open);
                //reader = XmlDictionaryReader.CreateTextReader(stream, new XmlDictionaryReaderQuotas());
                reader = new XmlTextReader(stream);
                //reader.Namespaces = false;
                NetDataContractSerializer ser = new NetDataContractSerializer();
                ser.AssemblyFormat = FormatterAssemblyStyle.Simple;
                //object deserializedObj = ser.Deserialize(stream);
                object deserializedObj = ser.ReadObject(reader, false);
                return(deserializedObj);
            }
            catch (Exception) {
                throw;
            }
            finally {
                //if (reader != null) {
                //   reader.Close();
                //}
                if (stream != null)
                {
                    stream.Close();
                }
            }
        }
Exemplo n.º 10
0
        public override void Uninstall(IDictionary savedState)
        {
            this.PrintStartText(Res.GetString("InstallActivityUninstalling"));
            string installStatePath = this.GetInstallStatePath(this.Path);

            if ((installStatePath != null) && File.Exists(installStatePath))
            {
                FileStream        input    = new FileStream(installStatePath, FileMode.Open, FileAccess.Read);
                XmlReaderSettings settings = new XmlReaderSettings
                {
                    CheckCharacters = false,
                    CloseInput      = false
                };
                XmlReader reader = null;
                if (input != null)
                {
                    reader = XmlReader.Create(input, settings);
                }
                try
                {
                    if (reader != null)
                    {
                        NetDataContractSerializer serializer = new NetDataContractSerializer();
                        savedState = (Hashtable)serializer.ReadObject(reader);
                    }
                }
                catch
                {
                    base.Context.LogMessage(Res.GetString("InstallSavedStateFileCorruptedWarning", new object[] { this.Path, installStatePath }));
                    savedState = null;
                }
                finally
                {
                    if (reader != null)
                    {
                        reader.Close();
                    }
                    if (input != null)
                    {
                        input.Close();
                    }
                }
            }
            else
            {
                savedState = null;
            }
            base.Uninstall(savedState);
            if ((installStatePath != null) && (installStatePath.Length != 0))
            {
                try
                {
                    File.Delete(installStatePath);
                }
                catch
                {
                    throw new InvalidOperationException(Res.GetString("InstallUnableDeleteFile", new object[] { installStatePath }));
                }
            }
        }
Exemplo n.º 11
0
        private void DoListen(TcpClient client)
        {
            NetworkStream stream = client.GetStream();

            using (MemoryStream memStream = new MemoryStream())
            {
                stream.CopyTo(memStream);
                StreamReader sr = new StreamReader(memStream);
                while (!sr.EndOfStream)
                {
                    var req = sr.ReadLine();
                    Debug.Print("receive " + req);
                }
                memStream.Seek(0, SeekOrigin.Begin);
                NetDataContractSerializer dcs = new NetDataContractSerializer();
                dcs.SurrogateSelector = new ActorSurrogatorSelector();
                dcs.Binder            = new ActorBinder();
                Object       obj = dcs.ReadObject(memStream);
                SerialObject so  = (SerialObject)obj;

                // no answer expected
                client.Close();

                // find hosted actor directory
                // forward msg to hostedactordirectory
                Become(new Behavior <SerialObject>(t => { return(true); }, DoProcessMessage));
                SendMessage(so);
            }
        }
Exemplo n.º 12
0
        public static T ReadObject <T>(string fileName, ExceptionHandler exceptionHandler)
        {
            var data = default(T);

            try
            {
                using (var fs = new FileStream(fileName, FileMode.Open))
                {
                    using (var reader = XmlDictionaryReader.CreateTextReader(fs, new XmlDictionaryReaderQuotas()))
                    {
                        var ser = new NetDataContractSerializer();

                        // Deserialize the data and read it from the instance.
                        data = (T)ser.ReadObject(reader, true);
                        fs.Close();
                    }
                }
            }
            catch (Exception exc)
            {
                if (exceptionHandler != null)
                {
                    exceptionHandler($"{nameof(XmlIO)}.{nameof(ReadObject)}<{typeof(T).Name}>", exc);
                }
                else
                {
                    throw;
                }
            }

            return(data);
        }
        /// <summary>
        /// Used to locate the FaultDeail of the reply message which will be used to generate the new Exception
        /// </summary>
        /// <param name="reply"></param>
        /// <returns></returns>
        public static Exception GetException(this Message reply)
        {
            using (var reader = reply.GetReaderAtBodyContents())
            {
                // Find <soap:Detail>
                while (reader.Read())
                {
                    if (reader.NodeType == XmlNodeType.Element && DetailElementName.Equals(reader.LocalName, StringComparison.InvariantCultureIgnoreCase))
                    {
                        break;
                    }
                }
                if (reader.EOF)
                {
                    return(null);
                }

                // Move to the contents of <soap:Detail>
                if (!reader.Read())
                {
                    return(null);
                }

                // Deserialize the fault
                try
                {
                    return((Exception)Serializer.ReadObject(reader));
                }
                catch (SerializationException ex)
                {
                    return(new CommunicationException("Could not deserialize the exception", ex));
                }
            }
        }
Exemplo n.º 14
0
        public static TestArtifact GetTestArtifact(this Configuration @this, MethodBase testMethod, DateTime dateTime)
        {
            var testArtifactProp       = new TestArtifactProperty(AppDomain.CurrentDomain.BaseDirectory, testMethod, dateTime);
            var testDllDirInfo         = new DirectoryInfo(testArtifactProp.TestDllDirectory);
            var testArtifactDirNameGen = testArtifactProp.GetDirectoryNameGenerator();

            if (testDllDirInfo.Exists)
            {
                foreach (var dirInfo in testDllDirInfo.EnumerateDirectories())
                {
                    if (!testArtifactDirNameGen.TryUpdate(dirInfo.Name))
                    {
                        continue;
                    }

                    var tmpTestArtifact = new TestArtifact(dirInfo.FullName, testArtifactProp);
                    using (var sr = new StreamReader(tmpTestArtifact.FullName))
                        using (var xr = new XmlTextReader(sr))
                        {
                            var ndcs         = new NetDataContractSerializer();
                            var testArtifact = (TestArtifact)ndcs.ReadObject(xr);
                            if (testArtifact.Test == testMethod)
                            {
                                tmpTestArtifact.CopyNonDataMemberTo(testArtifact);
                                return(testArtifact);
                            }
                        }
                }
            }
            return(new TestArtifact(testArtifactDirNameGen.Directory, testArtifactProp));
        }
            public object FromElement(Type type, XElement element)
            {
                var serializer   = new NetDataContractSerializer();
                var childElement = element.FirstNode.NextNode;

                return(serializer.ReadObject(XmlReader.Create(new StringReader(childElement.ToString()))));
            }
Exemplo n.º 16
0
 public static object DeserializeFromNetDataSerializer(string filename)
 {
     using (XmlReader reader = XmlReader.Create(filename))
     {
         NetDataContractSerializer serializer = new NetDataContractSerializer();
         return(serializer.ReadObject(reader));
     }
 }
Exemplo n.º 17
0
        private MGM.Game.Game Deserialize([NotNull] string serializedGame)
        {
            var contractSerializer =
                new NetDataContractSerializer(new StreamingContext(StreamingContextStates.All,
                                                                   this));

            return((MGM.Game.Game)contractSerializer.ReadObject(new XmlTextReader(new StringReader(serializedGame))));
        }
Exemplo n.º 18
0
        /// <summary>
        /// Deserialize byte array serialized with <see cref="XmlDictionaryWriter.CreateBinaryWriter(Stream)"/>.
        /// </summary>
        /// <typeparam name="T"> Expected type of object which is serialized in <paramref name="stream"/>. </typeparam>
        /// <param name="stream"> <see cref="MemoryStream"/> that holds serialized data. </param>
        /// <returns> Returns a deserialized object of type <typeparamref name="T"/>. </returns>
        public static T BinaryRead <T>(MemoryStream stream)
        {
            using (XmlDictionaryReader reader = XmlDictionaryReader.CreateBinaryReader(stream, new XmlDictionaryReaderQuotas()))
            {
                NetDataContractSerializer ser = new NetDataContractSerializer();

                return((T)ser.ReadObject(reader));
            }
        }
Exemplo n.º 19
0
 public IShape Load(string path)
 {
     using (var f = File.OpenRead(path))
     {
         var s = new NetDataContractSerializer();
         s.Binder = this;
         return(s.ReadObject(f) as IShape);
     }
 }
Exemplo n.º 20
0
        /// <summary>
        ///     Deserializes .NET object from xml
        /// </summary>
        public static T DeserializeNetObjectFromString <T>(string objectString) where T : class
        {
            var serializer = new NetDataContractSerializer();

            using (var reader = XmlReader.Create(new StringReader(objectString)))
            {
                return(serializer.ReadObject(reader) as T);
            }
        }
        public static SerialObject DeSerialize(Stream inputStream)
        {
            CheckArg.Stream(inputStream);
            inputStream.Seek(0, SeekOrigin.Begin);
            NetDataContractSerializer dcs = new NetDataContractSerializer();

            dcs.SurrogateSelector = new ActorSurrogatorSelector();
            dcs.Binder            = new ActorBinder();
            return((SerialObject)dcs.ReadObject(inputStream));
        }
 public static object DeSerializeXmlBinary(byte[] bytes)
 {
     using (var rdr = XmlDictionaryReader.CreateBinaryReader(bytes, XmlDictionaryReaderQuotas.Max))
     {
         var serializer = new NetDataContractSerializer {
             AssemblyFormat = FormatterAssemblyStyle.Simple
         };
         return(serializer.ReadObject(rdr));
     }
 }
Exemplo n.º 23
0
 public ICollection<Product> ReadProducts()
 {
     if (!File.Exists(path))
         return null;
     using (FileStream fs = new FileStream(path, FileMode.Open))
     {
         var serializer = new NetDataContractSerializer();
         return serializer.ReadObject(fs) as ISet<Product>;
     }
 }
Exemplo n.º 24
0
 public static object Deserialize(byte[] array)
 {
     using (MemoryStream memStream = new MemoryStream(array))
         using (GZipStream zipStream = new GZipStream(memStream, CompressionMode.Decompress))
             using (XmlDictionaryReader xmlDictionaryReader = XmlDictionaryReader.CreateBinaryReader(zipStream, XmlDictionaryReaderQuotas.Max))
             {
                 NetDataContractSerializer serializer = new NetDataContractSerializer();
                 return(serializer.ReadObject(xmlDictionaryReader));
             }
 }
Exemplo n.º 25
0
        /// <summary>
        /// Désérialise un stream.
        /// </summary>
        /// <param name="stream">Le stream contenant les données.</param>
        /// <param name="binder">Le lieur de types.</param>
        /// <returns>L'objet déserialisé.</returns>
        public static object Deserialize(Stream stream, SerializationBinder binder)
        {
            var rdr = XmlDictionaryReader.CreateTextReader(stream, XmlDictionaryReaderQuotas.Max);
            var ser = new NetDataContractSerializer()
            {
                Binder = binder,
            };

            return(ser.ReadObject(rdr));
        }
        //Security Warning: The following code is intentionally vulnerable to a serialization vulnerability
        public T Deserialize(string data)
        {
            var ser   = new NetDataContractSerializer();
            var bytes = Encoding.ASCII.GetBytes(data);

            using (var stream = new MemoryStream(bytes))
            {
                return((T)ser.ReadObject(stream));
            }
        }
Exemplo n.º 27
0
        /// <summary>
        /// Deserializes an object from the specified XML document.</summary>
        /// <typeparam name="T">
        /// The type of the object to deserialize.</typeparam>
        /// <param name="document">
        /// The complete XML document from which to deserialize the object.</param>
        /// <returns>
        /// The <typeparamref name="T"/> object resulting from the deserialization of <paramref
        /// name="document"/>.</returns>
        /// <exception cref="InvalidCastException">
        /// The top-level object of <paramref name="document"/> is not of type <typeparamref
        /// name="T"/>.</exception>
        /// <remarks>
        /// <b>Deserialize</b> uses a <see cref="NetDataContractSerializer"/> using <see
        /// cref="FormatterAssemblyStyle.Simple"/> assembly mode, and an <see cref="XmlReader"/>
        /// using the settings returned by <see cref="XmlUtility.CreateReaderSettings"/>.</remarks>

        public static T Deserialize <T>(string document)
        {
            var settings = XmlUtility.CreateReaderSettings();

            using (var textReader = new StringReader(document))
                using (var reader = XmlReader.Create(textReader, settings)) {
                    var serializer = new NetDataContractSerializer();
                    serializer.AssemblyFormat = FormatterAssemblyStyle.Simple;
                    return((T)serializer.ReadObject(reader));
                }
        }
Exemplo n.º 28
0
        static Root DeSerialize8(Stream fs, Stopwatch sw)
        {
            NetDataContractSerializer ser = new NetDataContractSerializer();
            XmlDictionaryReader       xr  = XmlDictionaryReader.CreateBinaryReader(fs, XmlDictionaryReaderQuotas.Max);

            sw.Start();
            var obj = (Root)ser.ReadObject(xr);

            sw.Stop();
            return(obj);
        }
Exemplo n.º 29
0
        public static Tuple <Expression, Object> Deserialize()
        {
            // Deserialize Expression & Param
            var text = File.ReadAllText(expressionfile);
            var deserializedExpression = new ExpressionSerializer(new TypeResolver(assemblies)).Deserialize(XElement.Parse(text));

            using (fs = new FileStream(paramfile, FileMode.Open, FileAccess.Read))
            {
                var param = paramSerializer.ReadObject(fs);
                return(new Tuple <Expression, Object>(deserializedExpression, param));
            }
        }
Exemplo n.º 30
0
        /// <summary>
        ///     Deserializes the object.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="stringToDeserialize">The string to deserialize.</param>
        /// <returns></returns>
        public static T DeserializeObject <T>(string stringToDeserialize)
        {
            var bytes = Encoding.UTF8.GetBytes(stringToDeserialize);

            using (var memStm = new MemoryStream(bytes))
            {
                var serializer = new NetDataContractSerializer( );
                var obj        = ( T )serializer.ReadObject(memStm);

                return(obj);
            }
        }