Пример #1
0
        public void Save(string savePath)
        {
            //ZIP書庫を作成
            if (File.Exists(savePath))
            {
                File.Delete(savePath);
            }

            AllLoad();

            using (ZipArchive zipArchive = ZipFile.Open(savePath, ZipArchiveMode.Create))
            {
                for (int i = 0; i < Data.Length; i++)
                {
                    ZipArchiveEntry entry = zipArchive.CreateEntry(i.ToString());
                    using (Stream stream = entry.Open())
                    {
                        bf.Serialize(stream, Data[i]);
                    }
                }

                ZipArchiveEntry zipLabelName = zipArchive.CreateEntry("LabelNames");
                using (Stream stream = zipLabelName.Open())
                {
                    bf.Serialize(stream, LabelNames);
                }

                ZipArchiveEntry zipShape = zipArchive.CreateEntry("Shape");
                using (Stream stream = zipShape.Open())
                {
                    bf.Serialize(stream, Shape);
                }

                ZipArchiveEntry zipLength = zipArchive.CreateEntry("Length");
                using (Stream stream = zipLength.Open())
                {
                    bf.Serialize(stream, Length);
                }

                ZipArchiveEntry entryLabel = zipArchive.CreateEntry("DataLabel");
                using (Stream stream = entryLabel.Open())
                {
                    bf.Serialize(stream, DataLabel);
                }
            }

            string classFileName = Path.Combine(Path.GetDirectoryName(savePath) ?? string.Empty, Path.GetFileNameWithoutExtension(savePath) + "Classes.txt");

            File.WriteAllLines(classFileName, LabelNames, Encoding.UTF8);
        }
        public void WriteXml(XmlWriter writer)
        {
            writer.WriteStartElement("dictionary");

            foreach (string key in Keys)
            {
                object value = this[key];
                writer.WriteStartElement("item");
                writer.WriteElementString("key", key);

                using (MemoryStream ms = new MemoryStream())
                    using (StreamReader sr = new StreamReader(ms))
                    {
                        NetDataContractSerializer ser = new NetDataContractSerializer();
                        ser.Serialize(ms, value);

                        ms.Seek(0, SeekOrigin.Begin);

                        writer.WriteElementString("value", sr.ReadToEnd());
                    }

                writer.WriteEndElement();
            }
            writer.WriteEndElement();
        }
Пример #3
0
        public string Serialize(object arg)
        {
            IFormatter formatter = new NetDataContractSerializer();

            try
            {
                using (var stream = new MemoryStream())
                {
                    formatter.Serialize(stream, arg);
                    stream.Seek(0, SeekOrigin.Begin);

                    using (var readerStream = new StreamReader(stream))
                    {
                        string result = readerStream.ReadToEnd();

                        if (result.Length > 10000)
                        {
                            result = new StringBuilder().Append(result.Take(10000)) + "...";
                        }

                        return(result);
                    }
                }
            }
            catch (InvalidDataContractException e)
            {
                return($"Not serializable [{arg.GetType()}]");
            }
            catch (Exception e)
            {
                var logger = Logger.Current;
                logger.LogInfo($"XmlSerializer error: {e}");
                throw;
            }
        }
        /// <summary>
        /// Writes a value of arbitrary type to the serializable dictionary.
        /// </summary>
        /// <param name="writer">An XML writer for the serializable dictionary.</param>
        /// <param name="value">The value to be serialized.</param>
        protected virtual void WriteValue(XmlWriter writer, TValue value)
        {
            if (writer == null)
            {
                var message = string.Format(
                    CultureInfo.CurrentCulture,
                    AssemblyProperties.Resources.ExceptionWriterIsNull,
                    "WriteValue");
                var innerException = new ArgumentNullException(
                    "writer",
                    AssemblyProperties.Resources.ExceptionValueIsNull);

                throw new XmlSerializableDictionaryException(message, innerException);
            }

            var valueSerializer = new NetDataContractSerializer();

            using (var ms = new MemoryStream())
            {
                valueSerializer.Serialize(ms, value);
                ms.Seek(0, SeekOrigin.Begin);
                var sr = new StreamReader(ms);
                writer.WriteRaw(sr.ReadToEnd());
            }
        }
        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;
            }
        }
        /// <summary>
        /// Writes a key value of arbitrary type to the serializable dictionary.
        /// </summary>
        /// <param name="writer">An XML writer for the serializable dictionary.</param>
        /// <param name="key">The key value to be serialized.</param>
        protected virtual void WriteKey(XmlWriter writer, TKey key)
        {
            if (writer == null)
            {
                var message = string.Format(
                    CultureInfo.CurrentCulture,
                    Properties.Resources.ExceptionWriterIsNull,
                    "WriteKey");
                var innerException = new ArgumentNullException(
                    "writer",
                    Properties.Resources.ExceptionValueIsNull);

                throw new EsbFactsException(message, innerException);
            }

            var keySerializer = new NetDataContractSerializer();

            using (var ms = new MemoryStream())
            {
                keySerializer.Serialize(ms, key);
                ms.Seek(0, SeekOrigin.Begin);
                var sr = new StreamReader(ms);
                writer.WriteRaw(sr.ReadToEnd());
            }
        }
Пример #7
0
 public ExceptionInfo(Exception exception)
 {
     this.originalException = exception;
     if (exception != null)
     {
         try
         {
             IFormatter netDataContractSerializer = new NetDataContractSerializer();
             using (MemoryStream memoryStream = new MemoryStream())
             {
                 netDataContractSerializer.Serialize(memoryStream, exception);
                 this.serializedException = memoryStream.ToArray();
             }
         }
         catch (Exception exception2)
         {
             Exception exception1 = exception2;
             if (Fx.IsFatal(exception1))
             {
                 throw;
             }
             Fx.Exception.TraceHandled(exception1, "ExceptionInfo..ctor", null);
         }
         if (this.serializedException == null)
         {
             MessagingClientEtwProvider.Provider.EventWriteNonSerializableException(exception.ToStringSlim());
         }
     }
 }
Пример #8
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;
             }
         }
     }
 }
Пример #9
0
 private void OnSerializing(StreamingContext context)
 {
     if ((Options & MarbleSerializationOptions.Serializable) != MarbleSerializationOptions.None)
     {
         using (var srm = new MemoryStream())
         {
             _formater.Serialize(srm, RawValue);
             srm.Seek(0, SeekOrigin.Begin);
             BinaryValue = srm.ToArray();
         }
     }
     else if ((Options & MarbleSerializationOptions.NetDataContractSerialization) != MarbleSerializationOptions.None)
     {
         using (var srm = new MemoryStream())
         {
             _ser.Serialize(srm, RawValue);
             srm.Seek(0, SeekOrigin.Begin);
             BinaryValue = srm.ToArray();
         }
     }
     else
     {
         if (RawValue != null)
         {
             StringValue = RawValue.ToString();
         }
     }
 }
Пример #10
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();
        }
Пример #11
0
        public void Save(string fileName)
        {
            FileStream fs = null;

            try
            {
                if (File.Exists(fileName))
                {
                    fs = new FileStream(fileName, FileMode.Open);
                }
                else
                {
                    fs = new FileStream(fileName, FileMode.Create);
                }

                //SoapFormatter serializer = new SoapFormatter();
                NetDataContractSerializer serializer = new NetDataContractSerializer();
                serializer.Serialize(fs, this.FRef);
            }
            catch (Exception ex)
            {
                string message = ex.ToString();
                MessageBox.Show(message, "Save Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
            finally
            {
                if (fs != null)
                {
                    fs.Flush();
                    fs.Close();
                }
            }
        }
Пример #12
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
            }
        }
Пример #13
0
        /// <summary>
        /// Serialize the current instance to the XML file specified
        /// by storeDataFile.
        /// </summary>
        private void Save()
        {
            var serializer = new NetDataContractSerializer();

            using (var stream = File.Create(_storeDataFile)) {
                serializer.Serialize(stream, this);
            }
        }
        public static void Serialize(SerialObject so, Stream outputStream)
        {
            NetDataContractSerializer dcs = new NetDataContractSerializer();

            dcs.SurrogateSelector = new ActorSurrogatorSelector();
            dcs.Binder            = new ActorBinder();
            dcs.Serialize(outputStream, so);
        }
Пример #15
0
        public static void Save(FunctionStack functionStack, string fileName)
        {
            NetDataContractSerializer bf = new NetDataContractSerializer();

            using (Stream stream = File.OpenWrite(fileName))
            {
                bf.Serialize(stream, functionStack);
            }
        }
        private void SerializeAccount(List <Account> listAccount)
        {
            NetDataContractSerializer serializer = new NetDataContractSerializer();

            using (FileStream fs = File.Create("accaunts.xml"))
            {
                serializer.Serialize(fs, listAccount);
            }
        }
Пример #17
0
 static byte[] SerializeWithNetDataContractSerializer <T>(T obj)
 {
     using (var memStream = new MemoryStream())
     {
         var dcs = new NetDataContractSerializer();
         dcs.Serialize(memStream, obj);
         return(memStream.ToArray());
     }
 }
        private void SerializeAccount(List <Page> listPage)
        {
            NetDataContractSerializer serializer = new NetDataContractSerializer();

            using (FileStream fs = File.Create("pages.xml"))
            {
                serializer.Serialize(fs, listPage);
            }
        }
Пример #19
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));
        }
Пример #20
0
        public void Serialize(List <Game> list)
        {
            NetDataContractSerializer formatter = new NetDataContractSerializer();

            using (FileStream fs = new FileStream("Games.xml", FileMode.Create))
            {
                formatter.Serialize(fs, list);
            }
        }
Пример #21
0
        internal void Save()
        {
            var serializer = new NetDataContractSerializer();

            using (var file = File.Create(FileName))
                using (var stream = new GZipStream(file, CompressionMode.Compress))
                {
                    serializer.Serialize(stream, this);
                }
        }
Пример #22
0
 private static string SerializeToBinary(object obj)
 {
     using (var stream = new MemoryStream())
     {
         var serializer = new NetDataContractSerializer();
         serializer.Serialize(stream, obj);
         stream.Flush();
         stream.Position = 0;
         return(Convert.ToBase64String(stream.ToArray()));
     }
 }
        /// <summary>
        /// Это пока не надо
        /// </summary>
        /// <param name="driver"></param>
        /// <param name="path"></param>
        private static void saveCookies(IWebDriver driver, string path)
        {
            IReadOnlyCollection <Cookie> cookes = driver.Manage().Cookies.AllCookies;

            NetDataContractSerializer serializer = new NetDataContractSerializer();

            using (FileStream fs = File.Create("cookies"))
            {
                serializer.Serialize(fs, cookes);
            }
        }
Пример #24
0
/*
 *      /// <summary>
 *      /// Converts an XElement to an XML DOM element.
 *      /// </summary>
 *      /// <param name="element">The XElement to be converted.</param>
 *      /// <returns>An XNML DOM element.</returns>
 *      public static XmlElement ConvertToXmlElement(this XElement element)
 *      {
 *          using (var xmlReader = element.CreateReader())
 *          {
 *              var xmlDoc = new AsXmlDocument();
 *              xmlDoc.Load(xmlReader);
 *              return xmlDoc.DocumentElement;
 *          }
 *      }
 */

        /// <summary>
        /// Serializes a CLR object (ref or value) to an XML representation.
        /// </summary>
        /// <param name="clrObject">The CLR object.</param>
        /// <returns>An XML representation of the serialized object.</returns>
        public static XmlElement SerializeClrObjectToXml(this object clrObject)
        {
            var xmlserializer = new NetDataContractSerializer();
            var memStream     = new MemoryStream();

            xmlserializer.Serialize(memStream, clrObject);
            var doc = new XmlDocument();

            doc.Load(memStream.StreamAtStart());
            return(doc.DocumentElement);
        }
        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));
            }
        }
Пример #26
0
        private void Serialize(NetDataContractSerializer serializer, XElement parent, string name, object value)
        {
            XElement element = new XElement(name);
            using(MemoryStream stream = new MemoryStream())
            {
                serializer.Serialize(stream, value);
                stream.Position = 0;

                element.Add(XElement.Load(stream));
            }
            parent.Add(element);
        }
Пример #27
0
        XElement SerializeObject(object o)
        {
            var s = new NetDataContractSerializer();
            var m = new MemoryStream();

            // serialize to stream
            s.Serialize(m, o);
            m.Position = 0;

            // parse serialized contents into new element
            return(XElement.Load(m));
        }
        /// <summary>
        /// Saves the configuration.
        /// </summary>
        /// <returns></returns>
        public static Exception Save()
        {
            try
            {
                ObservableCollection <DiscoveryPath> paths = Value.PluginDiscoveryPaths;
                #region Validation

                for (int i = paths.Count - 1; i >= 0; i--)
                {
                    if (string.IsNullOrWhiteSpace(paths[i].Path))
                    {
                        paths.RemoveAt(i);
                    }
                }

                #region Validation

                if (File.Exists(FILE_PATH))
                {
                    File.Delete(FILE_PATH);
                }

                #endregion // Validation

                #endregion // Validation

                var ser = new NetDataContractSerializer();
                var fs  = File.OpenWrite(FILE_PATH);
                using (var crypto = new CryptoStream(fs, _cryptoAlgorithm.CreateEncryptor(), CryptoStreamMode.Write))
                {
                    ser.Serialize(crypto, Value);
                }
                return(null);
            }
            #region Exception Handling

            catch (Exception ex)
            {
                try
                {
                    File.Move(FILE_PATH, FILE_PATH + "." + DateTime.Now.ToString("yyyy-MM-dd HHmmss"));
                }
                #region Exception Handling

                catch { }

                #endregion // Exception Handling
                TraceSourceMonitorHelper.Error("Fail to Save the Configuration: {0}", ex);
                return(ex);
            }

            #endregion // Exception Handling
        }
        private long getObjectSize(object o)
        {
            long size = 0;

            using (Stream s = new MemoryStream())
            {
                NetDataContractSerializer ser = new NetDataContractSerializer();
                ser.Serialize(s, o);
                size = s.Length;
            }
            return(size);
        }
Пример #30
0
        public static void Save(string filename, object value)
        {
            using (new JoeCulture())
            {
                string path = Path.Combine(DebugKeys.DefaultDataDirectory, filename);

                using (FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write))
                {
                    NetDataContractSerializer ser = new NetDataContractSerializer();
                    ser.Serialize(fs, value);
                }
            }
        }