/// <summary>
        /// Loads the configuration.
        /// </summary>
        public static void Load()
        {
            if (!File.Exists(FILE_PATH))
            {
                Save();
                return;
            }

            try
            {
                var ser = new NetDataContractSerializer();
                var fs  = File.OpenRead(FILE_PATH);
                using (var crypto = new CryptoStream(fs, _cryptoAlgorithm.CreateDecryptor(), CryptoStreamMode.Read))
                {
                    Value = ser.Deserialize(crypto) as Configuration;
                }
            }
            #region Exception Handling

            catch (Exception ex)
            {
                string date = DateTime.Now.ToString("yyyyMMdd.HHmmss");
                File.Move(FILE_PATH, FILE_PATH + "." + date);
                Value = new Configuration();
                Save();
                TraceSourceMonitorHelper.Error("Fail to load the Configuration: {0}", ex);
            }

            #endregion // Exception Handling
        }
Exemplo n.º 2
0
        /// <summary>
        ///     Deserializes a stream into an object of T.
        /// </summary>
        /// <typeparam name="T">The given type.</typeparam>
        /// <param name="stream">The stream that contains the XML to deserialize.</param>
        /// <returns>An object of type T.</returns>
        public static T Deserialize <T>(Stream stream)
            where T : class
        {
            NetDataContractSerializer serializer = new NetDataContractSerializer();

            return((T)serializer.Deserialize(stream));
        }
Exemplo n.º 3
0
        public bool Open(string fileName)
        {
            bool   ok     = true;
            Stream stream = null;

            try
            {
                stream = new FileStream(fileName, FileMode.Open);
                //SoapFormatter serializer = new SoapFormatter();
                NetDataContractSerializer serializer = new NetDataContractSerializer();

                F f = (F)serializer.Deserialize(stream);

                this.FRef = f;
            }
            catch (Exception ex)
            {
                ok = false;
                string message = ex.ToString();
                MessageBox.Show(message, "Save Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
            finally
            {
                if (stream != null)
                {
                    stream.Close();
                }
            }
            return(ok);
        }
        public CustomVariableGroup ImportVariables(VariableGroupAndVariablesAsString groupAndVariables)
        {
            try
            {
                var importedVariables = new List <CustomVariable>();

                using (var memoryStream = new MemoryStream())
                    using (var writer = new StreamWriter(memoryStream))
                    {
                        writer.Write(groupAndVariables.VariablesAsString);
                        var serializer = new NetDataContractSerializer();
                        writer.Flush();
                        memoryStream.Position = 0;
                        importedVariables     = serializer.Deserialize(memoryStream) as List <CustomVariable>;
                    }

                var group = groupAndVariables.CustomVariableGroup;
                foreach (var variable in importedVariables)
                {
                    group.CustomVariables.Add(variable);
                }

                return(Save(group));
            }
            catch (Exception ex)
            {
                Logger.LogException(ex);
                throw Helper.CreateHttpResponseException(ex, "Error Exporting Tasks");
            }
        }
Exemplo n.º 5
0
 private object Deserialize(Type type, XmlReader reader, StreamingContext context)
 {
     using (var dict = XmlDictionaryReader.CreateDictionaryReader(reader))
     {
         var serializer = new DataContractSerializer(type);
         var result     = serializer.ReadObject(dict, false, GenericResolver);
         if (context.Context == null)
         {
             return(result);
         }
         //TODO NO need for actual xml serializer now
         //implement recursive descent and provide context to all objects
         using (var cms = ChunkedMemoryStream.Create())
         {
             var ns = new NetDataContractSerializer(context);
             try
             {
                 ns.Serialize(cms, result);
                 cms.Position = 0;
                 ns.Binder    = GenericBinder;
                 return(ns.Deserialize(cms));
             }
             catch (Exception ex)
             {
                 Logger.Trace(ex.ToString());
                 cms.Position = 0;
                 Logger.Trace(() => new StreamReader(cms).ReadToEnd());
                 throw;
             }
         }
     }
 }
        protected override object DeserializeObject(ArraySegment <byte> value)
        {
            var ds = new NetDataContractSerializer();

            using (var ms = new MemoryStream(value.Array, value.Offset, value.Count))
                return(ds.Deserialize(ms));
        }
Exemplo n.º 7
0
        public Application ImportTasks(AppAndTasksAsString appDto)
        {
            try
            {
                List <TaskBase> importedTasks = new List <TaskBase>();

                using (var memoryStream = new MemoryStream())
                    using (var writer = new StreamWriter(memoryStream))
                    {
                        writer.Write(appDto.TasksAsString);
                        var serializer = new NetDataContractSerializer();
                        writer.Flush();
                        memoryStream.Position = 0;
                        importedTasks         = serializer.Deserialize(memoryStream) as List <TaskBase>;
                    }

                var app = appDto.Application;
                int newSequenceNumber = app.Tasks.Count + 1;
                foreach (var task in importedTasks.OrderBy(x => x.Sequence))
                {
                    task.Sequence = newSequenceNumber;
                    app.Tasks.Add(task);
                    newSequenceNumber++;
                }

                return(SaveApplication(app));
            }
            catch (Exception ex)
            {
                Logger.LogException(ex);
                throw Helper.CreateHttpResponseException(ex, "Error Exporting Tasks");
            }
        }
Exemplo n.º 8
0
        public static FunctionStack Load(string fileName)
        {
            NetDataContractSerializer bf = new NetDataContractSerializer();
            FunctionStack             result;

            using (Stream stream = File.OpenRead(fileName))
            {
                result = (FunctionStack)bf.Deserialize(stream);
            }

            foreach (Function function in result.Functions)
            {
                function.ResetState();

                for (int i = 0; i < function.Optimizers.Length; i++)
                {
                    function.Optimizers[i].ResetParams();
                }

                if (function is IParallelizable)
                {
                    ((IParallelizable)function).CreateKernel();
                }
            }

            return(result);
        }
        /// <summary>
        /// Reads a key value as an arbitrary object type.
        /// </summary>
        /// <param name="reader">An XML reader containing the serialized value.</param>
        /// <returns>A key value of arbitrary type.</returns>
        protected virtual TValue ReadValue(XmlReader reader)
        {
            if (reader == null)
            {
                var message = string.Format(
                    CultureInfo.CurrentCulture,
                    Properties.Resources.ExceptionReaderIsNull,
                    "ReadValue");
                var innerException = new ArgumentNullException(
                    "reader",
                    Properties.Resources.ExceptionValueIsNull);

                throw new EsbFactsException(message, innerException);
            }

            // The NetDataContractSerializer class is an XML serializer that adds/reads
            // additional type information, allowing arbitrary types to be serialised.
            var valueSerializer = new NetDataContractSerializer();

            reader.Read();

            using (var ms = new MemoryStream())
            {
                var sw = new StreamWriter(ms);
                sw.Write(reader.ReadOuterXml());
                sw.Flush();
                ms.Seek(0, SeekOrigin.Begin);

                return((TValue)valueSerializer.Deserialize(ms));
            }
        }
Exemplo n.º 10
0
        public object Deserialize(Stream s, Type target, StreamingContext context)
        {
            var serializer = new DataContractSerializer(target);
            var result     = serializer.ReadObject(s);

            if (context.Context == null)
            {
                return(result);
            }
            //TODO fix double serialization because of context
            using (var cms = ChunkedMemoryStream.Create())
            {
#if NETSTANDARD2_0
                Json.Serialize(result, cms, true);
                cms.Position = 0;
                return(Json.Deserialize(cms, target, context));
#else
                var ns = new NetDataContractSerializer(context);
                ns.Serialize(cms, result);
                ns.Binder    = GenericBinder;
                cms.Position = 0;
                return(ns.Deserialize(cms));
#endif
            }
        }
        public void ISerializationSurrogate()
        {
            dbContext.Configuration.ProxyCreationEnabled = false;
            using (Stream stream = new MemoryStream())
            {
                SurrogateSelector ss = new SurrogateSelector();

                ss.AddSurrogate(typeof(Order_Detail),
                                new StreamingContext(StreamingContextStates.All),
                                new SerializationSurrogate());

                IFormatter formatter = new NetDataContractSerializer();

                formatter.SurrogateSelector = ss;

                var orderDetails = dbContext.Order_Details.Include("Product").AsNoTracking().ToList();

                formatter.Serialize(stream, orderDetails);

                stream.Position = 0;

                List <Order_Detail> ord = (List <Order_Detail>)formatter.Deserialize(stream);

                var t = ord;
            }
        }
Exemplo n.º 12
0
        static void Main(string[] args)
        {
            List <User> users = new List <User> {
                new User {
                    Id = 0, Name = "Mary", Age = 23
                },
                new User {
                    Id = 1, Name = "Tom", Age = 12
                },
                new User {
                    Id = 2, Name = "Ann", Age = 28
                }
            };
            NetDataContractSerializer serializer = new NetDataContractSerializer();

            using (FileStream fs = File.Create("Test.xml"))
            {
                serializer.Serialize(fs, users);
            }

            List <User> clonedUsers = null;

            using (FileStream fs = File.OpenRead("Test.Xml"))
            {
                clonedUsers = (List <User>)serializer.Deserialize(fs);
            }
            foreach (User u in clonedUsers)
            {
                Console.WriteLine(u);
            }
            Console.WriteLine("Completed!");
            Console.ReadLine();
        }
Exemplo n.º 13
0
        private void load()
        {
            DownloaderState deserialized = null;

            if (File.Exists(STATE_FILE_NAME))
            {
                try
                {
                    using (var stream = File.OpenRead(STATE_FILE_NAME))
                    {
                        deserialized = netDataContractSerializer.Deserialize(stream)
                                       as DownloaderState;
                        stream.Close();
                    }
                }
                catch (XmlException e)
                {
                    deserialized = null;
                    logger.LogException(e);
                }
            }
            if (deserialized != null)
            {
                CurrentState = deserialized;
            }
            else
            {
                CurrentState = new DownloaderState();
            }
        }
Exemplo n.º 14
0
 static T DeserializeWithNetDataContractSerializer <T>(byte[] bytes)
 {
     using (var memStream = new MemoryStream(bytes))
     {
         var dcs = new NetDataContractSerializer();
         return((T)dcs.Deserialize(memStream));
     }
 }
        public void AfterReceiveReply(ref NDceRpc.ServiceModel.Channels.Message reply, object correlationState)
        {
            var stream     = new MemoryStream(reply.Fault.Detail);
            var serializer = new NetDataContractSerializer();
            var exeption   = (Exception)serializer.Deserialize(stream);

            throw exeption;
        }
Exemplo n.º 16
0
        public static T Serialize <T>(this T graph)
        {
            var serializer = new NetDataContractSerializer();

            using var stream = new MemoryStream();
            serializer.Serialize(stream, graph);
            stream.Seek(0, SeekOrigin.Begin);
            return((T)serializer.Deserialize(stream));
        }
Exemplo n.º 17
0
        private static List <TaskBase> TryGetNewTasks(string filePathAndName)
        {
            NetDataContractSerializer serializer = new NetDataContractSerializer();

            using (FileStream fileStream = new FileStream(filePathAndName, FileMode.Open))
            {
                return(serializer.Deserialize(fileStream) as List <TaskBase>);
            }
        }
Exemplo n.º 18
0
        object DeserializeObject(NetDataContractSerializer serializer, XElement e)
        {
            var stm = new MemoryStream();

            e.Save(stm);
            stm.Position = 0;

            return(serializer.Deserialize(stm));
        }
        public static object MyNetDataContractDeserializer(string str)
        {
            var s = new NetDataContractSerializer();

            byte[]       serializedData = Encoding.UTF8.GetBytes(str);
            MemoryStream ms             = new MemoryStream(serializedData);
            object       obj            = s.Deserialize(ms);

            return(obj);
        }
        public static T Serialize <T>(this T graph)
        {
            var serializer = new NetDataContractSerializer();

            using (var stream = new MemoryStream())
            {
                serializer.Serialize(stream, graph);
                stream.Dump($"Dump-{graph?.GetType().Name}-NetDataContractSerializer-{Guid.NewGuid()}.xml");
                stream.Seek(0, SeekOrigin.Begin);
                return((T)serializer.Deserialize(stream));
            }
        }
Exemplo n.º 21
0
        }//end

        private static LicenseObj DesSerializationObj1(string str)
        {
            NetDataContractSerializer net = new NetDataContractSerializer();

            System.IO.MemoryStream s = new MemoryStream();
            byte[] bs = Convert.FromBase64String(str);
            s.Write(bs, 0, bs.Length);
            s.Position = 0;
            LicenseObj list = (LicenseObj)net.Deserialize(s);

            s.Close();
            return(list);
        }
        private static JsonValue ValidateSerialization(JsonValue beforeSerialization)
        {
            Assert.NotNull(beforeSerialization);
            NetDataContractSerializer serializer = new NetDataContractSerializer();

            using (MemoryStream memStream = new MemoryStream())
            {
                serializer.Serialize(memStream, beforeSerialization);
                memStream.Position = 0;
                JsonValue afterDeserialization = (JsonValue)serializer.Deserialize(memStream);
                Assert.Equal(beforeSerialization.ToString(), afterDeserialization.ToString());
                return(afterDeserialization);
            }
        }
Exemplo n.º 23
0
        public static T DeepCopy <T>(this T objectToCopy)
        {
            MemoryStream memoryStream = new MemoryStream();
            NetDataContractSerializer netFormatter = new NetDataContractSerializer();

            netFormatter.Serialize(memoryStream, objectToCopy);

            memoryStream.Position = 0;
            T returnValue = (T)netFormatter.Deserialize(memoryStream);

            memoryStream.Close();
            memoryStream.Dispose();

            return(returnValue);
        }
Exemplo n.º 24
0
        static void Method()
        {
            // Unsafe 4
            Stream stream = new MemoryStream();
            NetDataContractSerializer netDataContractSerializer1 = new NetDataContractSerializer()
            {
                Binder = new CustomBinder()
            };
            NetDataContractSerializer netDataContractSerializer2 = new NetDataContractSerializer()
            {
                Binder = null
            };
            NetDataContractSerializer netDataContractSerializer3 = new NetDataContractSerializer();
            NetDataContractSerializer netDataContractSerializer4 = new NetDataContractSerializer();

            netDataContractSerializer4.Binder = new CustomBinder();
            netDataContractSerializer1.Deserialize(new MemoryStream());
            netDataContractSerializer2.Deserialize(new MemoryStream());
            netDataContractSerializer3.Deserialize(new MemoryStream());
            netDataContractSerializer3.Binder = new CustomBinder();
            netDataContractSerializer3.Deserialize(new MemoryStream());
            netDataContractSerializer4.Deserialize(new MemoryStream());
            netDataContractSerializer1.ReadObject(new MemoryStream());
        }
        public static T Deserialize <T>(this byte[] stream)
        {
            if (stream == null)
            {
                return(default(T));
            }

            var srlzr = new NetDataContractSerializer();

            using (MemoryStream memoryStream = new MemoryStream(stream))
            {
                var result = (T)srlzr.Deserialize(memoryStream);
                return(result);
            }
        }
Exemplo n.º 26
0
        private static T DeserealizeFromBinary <T>(string strObj)
        {
            if (string.IsNullOrEmpty(strObj))
            {
                return(default(T));
            }
            var b = Convert.FromBase64String(strObj);

            using (var stream = new MemoryStream(b))
            {
                var serializer = new NetDataContractSerializer();
                stream.Seek(0, SeekOrigin.Begin);
                return((T)serializer.Deserialize(stream));
            }
        }
Exemplo n.º 27
0
        /// <summary>
        /// Deserialize object from byte array.
        /// </summary>
        /// <param name="bytes">Byte array representing object. </param>
        /// <returns>Object.</returns>
        public static object DeserializeFromBytes(byte[] bytes, Type type)
        {
            if (bytes == null)
            {
                return(null);
            }
            NetDataContractSerializer serializer = GetByteSerializer(type);
            MemoryStream ms = new MemoryStream(bytes);
            object       o;

            lock (serializer) { o = serializer.Deserialize(ms); }
            ms.Close();
            ms = null;
            return(o);
        }
        object DeserializeObject(NetDataContractSerializer serializer, XmlElement element)
        {
            object deserializedObject = null;

            MemoryStream        stm = new MemoryStream();
            XmlDictionaryWriter wtr = XmlDictionaryWriter.CreateTextWriter(stm);

            element.WriteContentTo(wtr);
            wtr.Flush();
            stm.Position = 0;

            deserializedObject = serializer.Deserialize(stm);

            return(deserializedObject);
        }
        /*
         * Insecure NetDataContractSerializer usage
         * https://docs.microsoft.com/en-us/dotnet/api/system.runtime.serialization.netdatacontractserializer.deserialize?view=netframework-4.8#remarks
         */
        public void NetDataContractDeserialization(string json)
        {
            try
            {
                MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json));

                NetDataContractSerializer netDataContractSerializer = new NetDataContractSerializer();
                object obj = netDataContractSerializer.Deserialize(ms);
                Console.WriteLine(obj);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }
        public void GetPages(Action <List <Page>, Exception> callback)
        {
            NetDataContractSerializer serializer = new NetDataContractSerializer();

            List <Page> pages = new List <Page>();

            if (File.Exists("pages.xml"))
            {
                using (FileStream fs = File.OpenRead("pages.xml"))
                {
                    pages = (List <Page>)serializer.Deserialize(fs);
                }
            }

            callback(pages, null);
        }