Beispiel #1
0
        // PDF generator for email
        public static void SaveHttpResponseAsFile(string RequestUrl, string FilePath)
        {
            try
            {
                HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(RequestUrl);
                httpRequest.UserAgent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows 10 Pro; Trident/5.0)";
                httpRequest.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip,deflate");
                HttpWebResponse response = null;
                try
                {
                    response = (HttpWebResponse)httpRequest.GetResponse();
                }
                catch (System.Net.WebException ex)
                {
                    if (ex.Status == WebExceptionStatus.ProtocolError)
                    {
                        response = (HttpWebResponse)ex.Response;
                    }
                }

                using (Stream responseStream = response.GetResponseStream())
                {
                    Stream FinalStream = responseStream;
                    if (response.ContentEncoding.ToLower().Contains("gzip"))
                    {
                        FinalStream = new GZipStream(FinalStream, CompressionMode.Decompress);
                    }
                    else if (response.ContentEncoding.ToLower().Contains("deflate"))
                    {
                        FinalStream = new DeflateStream(FinalStream, CompressionMode.Decompress);
                    }

                    using (var fileStream = System.IO.File.Create(FilePath))
                    {
                        FinalStream.CopyTo(fileStream);
                    }

                    response.Close();
                    FinalStream.Close();
                }
            }
            catch
            { }
        }
        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);
        }
        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);
        }