Esempio n. 1
0
        /// <summary>
        /// Saves or Serializes a Cluster Collection To an Xml file
        /// </summary>
        /// <param name="myObject">A serializable object to be persisted to an Xml file</param>
        /// <param name="writeToXmlPath">The location of the Xml file tha will contain serialized data</param>
        /// <returns>True if the serialization is successful otherwise false</returns>
        public static bool Serialize(System.Object myObject, string writeToXmlPath)
        {
            bool state = true;

            System.Runtime.Serialization.IFormatter formatter = null;
            System.IO.Stream stream = null;
            try
            {
                formatter = new System.Runtime.Serialization.Formatters.Soap.SoapFormatter();
                stream    = new System.IO.FileStream(writeToXmlPath, FileMode.Create, FileAccess.Write, FileShare.None);
                formatter.Serialize(stream, myObject);
            }
            catch (System.Exception ex)
            {
                state = false;
                System.Diagnostics.Debug.WriteLine(ex.ToString());
            }
            finally
            {
                stream.Close();
                formatter = null;
                stream    = null;
            }
            return(state);
        }
Esempio n. 2
0
        SerializeToBinary
        (
            string library = "protobuf-net"
        )
        {
            System.IO.MemoryStream stream = null;

            Serialization.Artifact object_metadata = new(this);

            switch (library)
            {
            case "protobuf-net":
                stream = new System.IO.MemoryStream();
                ProtoBuf.Serializer.Serialize
                (
                    stream,
                    object_metadata
                );
                break;

            case "system-runtime-serialization":
            default:
                stream = new System.IO.MemoryStream();
                // Serialize an object into the storage medium referenced by 'stream' object.
                System.Runtime.Serialization.IFormatter formatter = null;
                formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                formatter.Serialize(stream, object_metadata);
                break;
            }

            return(stream);
        }
 /// <summary>
 /// Called when save data.
 /// </summary>
 /// <param name="Data">The data.</param>
 /// <returns>Returns true if succeeded.</returns>
 protected override bool OnSave(ref Stream DataStream, ref System.Runtime.Serialization.IFormatter DataFormater)
 {
     if (DataSerializableRef != null)
     {
         DataFormater.Serialize(DataStream, DataSerializableRef);
     }
     return(true);
 }
Esempio n. 4
0
        private static System.Runtime.Serialization.IFormatter CreateFormatterForMode(SerializationMode mode)
        {
            System.Runtime.Serialization.IFormatter RET = default;

            RET = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
            ((System.Runtime.Serialization.Formatters.Binary.BinaryFormatter)RET).AssemblyFormat = System.Runtime.Serialization.Formatters.FormatterAssemblyStyle.Simple;

            return(RET);
        }
Esempio n. 5
0
 public ContentManager(GraphicsDevice graphicsDevice, string rootDirectory)
 {
     this.RootDirectory  = rootDirectory;
     this.graphicsDevice = graphicsDevice;
     typeReaders         = new Dictionary <string, IContentTypeReader>();
     typeReadersOutput   = new Dictionary <string, IContentTypeReader>();
     assets    = new Dictionary <string, object>();
     formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
     AddAssembly(Assembly.GetExecutingAssembly());
 }
Esempio n. 6
0
        public void DeserializeObj(System.Runtime.Serialization.IFormatter formatter, System.IO.Stream ins)
        {
            List <ProgState>      prgl = (List <ProgState>)formatter.Deserialize(ins);
            ArrayList <ProgState> arl  = new ArrayList <ProgState>();

            for (int i = 0; i < prgl.Count; i++)
            {
                arl.Add(prgl.ElementAt(i));
            }

            SetPrgList(arl);
        }
Esempio n. 7
0
        void ICloudFileDataTransfer.Serialize(System.Runtime.Serialization.IFormatter dataFormatter, object objectGraph)
        {
            using (var cache = new MemoryStream())
            {
                // serialize into the cache
                dataFormatter.Serialize(cache, objectGraph);

                // go to start
                cache.Position = 0;

                // transfer the cache
                _fsEntry.GetDataTransferAccessor().Transfer(cache, nTransferDirection.nUpload);
            }
        }
Esempio n. 8
0
        object ICloudFileDataTransfer.Deserialize(System.Runtime.Serialization.IFormatter dataFormatter)
        {
            using (var cache = new MemoryStream())
            {
                // get the data
                _fsEntry.GetDataTransferAccessor().Transfer(cache, nTransferDirection.nDownload);

                // go to the start
                cache.Position = 0;

                // go ahead
                return(dataFormatter.Deserialize(cache));
            }
        }
 public void Serializer(object _object)
 {
     if (_BinaryFormatter == null)
     {
         _BinaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
     }
     using (var _MemoryStream = new System.IO.MemoryStream())
     {
         _BinaryFormatter.Serialize(_MemoryStream, _object);
         var bytes = _MemoryStream.ToArray();
         Put(bytes.Length);
         Put(bytes);
     }
 }
Esempio n. 10
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="bytesNeedDeserialized"></param>
        /// <param name="count"></param>
        /// <param name="formatType"></param>
        /// <returns></returns>
        public static object DeserializeBytesToObject(byte[] bytesNeedDeserialized, int count, SeralizeFormatType formatType)
        {
            System.Runtime.Serialization.IFormatter oFormatter = null;

            if (formatType == SeralizeFormatType.BinaryFormat)
            {
                oFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
            }
            else if (formatType == SeralizeFormatType.XmlFortmat)
            {
                oFormatter = new System.Runtime.Serialization.Formatters.Soap.SoapFormatter();
            }

            System.IO.MemoryStream oStream = new System.IO.MemoryStream(bytesNeedDeserialized, 0, count);
            object oResult = oFormatter.Deserialize(oStream);

            return(oResult);
        }
        public T Deserializer <T>()
        {
            int count = GetInt();

            if (count <= 0 || (_position + count) >= _data.Length)
            {
                return(default(T));
            }
            if (_BinaryFormatter == null)
            {
                _BinaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
            }
            T ReturnValue;

            using (var _MemoryStream = new System.IO.MemoryStream(_data, _position, count))
            {
                ReturnValue = (T)_BinaryFormatter.Deserialize(_MemoryStream);
            }
            return(ReturnValue);
        }
Esempio n. 12
0
        private static System.Runtime.Serialization.IFormatter CreateFormatterForMode(SerializationMode mode)
        {
            System.Runtime.Serialization.IFormatter RET = default(System.Runtime.Serialization.IFormatter);

            //if (mode == SerializationMode.Xml)
            //{
            //	RET = new System.Runtime.Serialization.Formatters.Soap.SoapFormatter();
            //	((System.Runtime.Serialization.Formatters.Soap.SoapFormatter)RET).AssemblyFormat = Runtime.Serialization.Formatters.FormatterAssemblyStyle.Simple;
            //}
            //else if (mode == SerializationMode.Binary)
            //{
            RET = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
            ((System.Runtime.Serialization.Formatters.Binary.BinaryFormatter)RET).AssemblyFormat = System.Runtime.Serialization.Formatters.FormatterAssemblyStyle.Simple;
            //}
            //else
            //{
            //	throw new Exception("Unknown Serialization Mode");
            //}

            //RET.Binder = Binder;

            return(RET);
        }
Esempio n. 13
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="objectNeedSerialized"></param>
        /// <param name="formatType"></param>
        /// <returns></returns>
        public static byte[] SerializeObjectToBytes(object objectNeedSerialized, SeralizeFormatType formatType)
        {
            System.Runtime.Serialization.IFormatter oFormatter = null;

            if (formatType == SeralizeFormatType.BinaryFormat)
            {
                oFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
            }
            else if (formatType == SeralizeFormatType.XmlFortmat)
            {
                oFormatter = new System.Runtime.Serialization.Formatters.Soap.SoapFormatter();
            }

            System.IO.MemoryStream oStream = new System.IO.MemoryStream();

            oFormatter.Serialize(oStream, objectNeedSerialized);

            byte[] oBuffer = new byte[oStream.Length];
            oStream.Position = 0;
            oStream.Read(oBuffer, 0, oBuffer.Length);

            return(oBuffer);
        }
Esempio n. 14
0
        private static object ManageOldVersion(string Version, string FileWhereRead, string Password)
        {
            try
            {
                switch (Version)
                {
                case "v0.0":

                    if (!System.IO.File.Exists(FileWhereRead))
                    {
                        return(null);
                    }

                    SerializationMode mode = ModeFromFname(FileWhereRead);

                    System.Runtime.Serialization.IFormatter FR = default(System.Runtime.Serialization.IFormatter);
                    if (mode == SerializationMode.Xml)
                    {
                        FR = CreateFormatterForMode(SerializationMode.Xml);
                    }
                    else if (mode == SerializationMode.Binary)
                    {
                        FR = CreateFormatterForMode(SerializationMode.Binary);
                    }
                    else
                    {
                        throw new Exception("Unknown DeSerialization Mode");
                    }

                    System.IO.FileStream FS = default(System.IO.FileStream);
                    //File Stream
                    System.Security.Cryptography.SymmetricAlgorithm DE = default(System.Security.Cryptography.SymmetricAlgorithm);
                    //Decryption Engine
                    System.Security.Cryptography.CryptoStream DS = null;
                    //Decrypted Stream

                    FS = new System.IO.FileStream(FileWhereRead, FileMode.Open, FileAccess.Read, FileShare.Read);

                    if ((Password != null))
                    {
                        DE = System.Security.Cryptography.SymmetricAlgorithm.Create();
                        DS = new System.Security.Cryptography.CryptoStream(FS, DE.CreateDecryptor(GenerateKey(Password, Convert.ToInt32(DE.KeySize / 8)), GenerateKey("Vettore di inizializzazione", 16)), System.Security.Cryptography.CryptoStreamMode.Read);
                    }

                    object Result = null;

                    if ((DS != null))
                    {
                        Result = FR.Deserialize(DS);
                        FS.Close();
                    }
                    else
                    {
                        Result = FR.Deserialize(FS);
                        FS.Close();
                    }

                    //Save in newer version
                    ObjToFile(Result, FileWhereRead, Password);


                    return(Result);
                }
            }
            catch (Exception ex)
            {
                ManageReadError(FileWhereRead, ex);
            }

            return(null);
        }
Esempio n. 15
0
        public static bool ObjToFile(object ObjectToSave, string filename, SerializationMode SerializeMode, string Password, bool Compression)
        {
            lock (ThreadLock)
            {
                Exception err = null;
                System.Security.Cryptography.SymmetricAlgorithm EE = null;
                Stream FinalStream = null;
                System.Runtime.Serialization.IFormatter SR = default(System.Runtime.Serialization.IFormatter);
                byte[] IV         = null;
                byte[] CypherKey  = null;
                string tmpfile    = null;
                string backupfile = null;

                try
                {
                    filename   = System.IO.Path.Combine(LaserGRBL.GrblCore.DataPath, filename);
                    tmpfile    = Path.GetDirectoryName(filename) + Path.DirectorySeparatorChar + "tmp_" + System.IO.Path.GetRandomFileName();
                    backupfile = filename + ".bak";

                    if (SerializeMode == SerializationMode.Auto)
                    {
                        SerializeMode = ModeFromFname(filename);
                    }
                    SR = CreateFormatterForMode(SerializeMode);
                    //CREATE FORMATTER

                    FinalStream = new FileStream(tmpfile, FileMode.CreateNew, FileAccess.Write, FileShare.None);
                    //Open a stream on the file for writing and lock the file

                    if ((Password != null))
                    {
                        EE        = System.Security.Cryptography.SymmetricAlgorithm.Create();
                        IV        = EE.IV;
                        CypherKey = GenerateKey(Password, Convert.ToInt32(EE.KeySize / 8));
                    }

                    WriteSerializerTag(FinalStream, SerializerVersion, SerializeMode, CypherKey, IV, Compression);

                    if ((Password != null))
                    {
                        FinalStream = new System.Security.Cryptography.CryptoStream(FinalStream, EE.CreateEncryptor(CypherKey, EE.IV), System.Security.Cryptography.CryptoStreamMode.Write);
                    }
                    if (Compression)
                    {
                        FinalStream = new System.IO.Compression.DeflateStream(FinalStream, System.IO.Compression.CompressionMode.Compress);
                    }


                    SR.Serialize(FinalStream, ObjectToSave);                     //WRITE DATA
                    FinalStream.Flush();
                    //If TypeOf (SS) Is System.Security.Cryptography.CryptoStream Then DirectCast(SS, System.Security.Cryptography.CryptoStream).FlushFinalBlock()
                    FinalStream.Close();
                    //CLOSE STREAM

                    if ((System.IO.File.Exists(filename)))
                    {
                        System.IO.File.Replace(tmpfile, filename, backupfile, true);
                        System.IO.File.Delete(backupfile);
                    }
                    else
                    {
                        System.IO.File.Move(tmpfile, filename);
                    }

                    return(true);
                }
                catch (Exception ex)
                {
                    err = ex;
                    try
                    {
                        FinalStream?.Close();
                    }
                    catch { }
                    try { ManageWriteError(ObjectToSave, filename, ex); }
                    catch { }
                }
                finally
                {
                    //evita di lasciare in giro file temporanei
                    if ((tmpfile != null) && System.IO.File.Exists(tmpfile))
                    {
                        try { System.IO.File.Delete(tmpfile); }
                        catch { }
                    }
                }
            }
            return(false);
        }
Esempio n. 16
0
        public static object ObjFromFile(string filename, string Password, bool AskForMissingPassword)
        {
            object rv = null;

            lock (ThreadLock)
            {
                Exception err = null;
                filename = System.IO.Path.Combine(LaserGRBL.GrblCore.DataPath, filename);

                if ((File.Exists(filename + ".bak") & !File.Exists(filename)))
                {
                    ManageOrphanTmp(filename);
                }

                if (File.Exists(filename))
                {
                    System.Security.Cryptography.SymmetricAlgorithm EE = null;
                    Stream FinalStream = null;
                    System.Runtime.Serialization.IFormatter SR = default(System.Runtime.Serialization.IFormatter);

                    bool REncrypted            = false;
                    bool RCompressed           = false;
                    SerializationMode Rmode    = default(SerializationMode);
                    string            RVersion = null;
                    byte[]            Rhash    = null;

                    byte[] IV        = null;
                    byte[] CypherKey = null;


                    try
                    {
                        //Open a stream on the file for reading (overwrite if exist) and lock the file
                        FinalStream = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read);
                        GetSerializerTag(FinalStream, ref RVersion, ref Rmode, ref REncrypted, ref IV, ref Rhash, ref RCompressed);
                        //Get serializer tag end move stream position

                        //GESTISCI LA VERSIONE CORRENTE
                        if (RVersion == SerializerVersion)
                        {
                            SR = CreateFormatterForMode(Rmode);
                            if (RCompressed)
                            {
                                FinalStream = new System.IO.Compression.DeflateStream(FinalStream, System.IO.Compression.CompressionMode.Decompress);
                            }

                            if (REncrypted && Password == null)
                            {
                                if (AskForMissingPassword)
                                {
                                    string NewKey = InputBox.Show(null, "Insert password:"******"Protected file", "", null).Text;
                                    if ((NewKey != null))
                                    {
                                        FinalStream.Close();
                                        return(ObjFromFile(filename, NewKey, AskForMissingPassword));
                                    }
                                    else
                                    {
                                        throw new MissingPasswordException(filename);
                                    }
                                }
                                else
                                {
                                    throw new MissingPasswordException(filename);
                                }
                            }

                            //GENERATE KEY AND CRYPTO SERVICE
                            if (REncrypted)
                            {
                                EE        = System.Security.Cryptography.SymmetricAlgorithm.Create();
                                EE.IV     = IV;
                                CypherKey = GenerateKey(Password, Convert.ToInt32(EE.KeySize / 8));
                            }


                            //TEST KEY VALIDITY WITH HASH COMPARE
                            if (REncrypted)
                            {
                                byte[] CurHash = GenerateHash(CypherKey);
                                if (Rhash == null || CurHash == null)
                                {
                                    throw new WrongPasswordException(filename);
                                }
                                if (!(Rhash.Length == CurHash.Length))
                                {
                                    throw new WrongPasswordException(filename);
                                }
                                for (int I = 0; I <= Rhash.Length - 1; I++)
                                {
                                    if (!(Rhash[I] == CurHash[I]))
                                    {
                                        throw new WrongPasswordException(filename);
                                    }
                                }
                            }

                            if (REncrypted)
                            {
                                FinalStream = new System.Security.Cryptography.CryptoStream(FinalStream, EE.CreateDecryptor(CypherKey, EE.IV), System.Security.Cryptography.CryptoStreamMode.Read);
                            }


                            rv = SR.Deserialize(FinalStream);                                                                                   //READ DATA
                            FinalStream.Close();
                        }
                        else
                        {
                            FinalStream?.Close();
                            rv = ManageOldVersion(RVersion, filename, Password);
                        }
                    }
                    catch (Exception ex)
                    {
                        err = ex;
                        System.Diagnostics.Debug.WriteLine(string.Format("Serialization exception in {0} Position {1}", filename, FinalStream.Position));

                        try
                        {
                            FinalStream?.Close();
                        }
                        catch
                        {
                        }
                        try
                        {
                            ManageReadError(filename, ex);
                        }
                        catch
                        {
                        }
                    }
                }
                else
                {
                    ;
                }
            }
            return(rv);
        }
Esempio n. 17
0
 public virtual void Init()
 {
     _formatter = Serializer.Instance;
     _interrupter = new IntervalInterrupter (TimeSpan.FromMilliseconds (10.0), "Test IntervalInterrupter");
     _interrupter.Start ();
 }
 /// <summary>
 /// Called when load data.
 /// </summary>
 /// <param name="Data">The data.</param>
 /// <returns>Returns true if succeeded.</returns>
 protected override bool OnLoad(ref Stream DataStream, ref System.Runtime.Serialization.IFormatter DataFormater)
 {
     DataSerializableRef = (DataSerializable)DataFormater.Deserialize(DataStream);
     return(true);
 }
Esempio n. 19
0
        public void SerializeObj(System.Runtime.Serialization.IFormatter formatter, System.IO.Stream os)
        {
            List <ProgState> prg = GetProgList();

            formatter.Serialize(os, prg);
        }