Esempio n. 1
0
        /// <summary>
        /// Dumps on the specified stream.
        /// </summary>
        /// <param name="function">The function.</param>
        /// <param name="stream">The stream.</param>
        /// <exception cref="System.ArgumentException">
        /// function arg is not a function!
        /// or
        /// stream is readonly!
        /// or
        /// function arg has upvalues other than _ENV
        /// </exception>
        public void Dump(DynValue function, Stream stream)
        {
            this.CheckScriptOwnership(function);

            if (function.Type != DataType.Function)
            {
                throw new ArgumentException("function arg is not a function!");
            }

            if (!stream.CanWrite)
            {
                throw new ArgumentException("stream is readonly!");
            }

            Closure.UpvaluesType upvaluesType = function.Function.GetUpvaluesType();

            if (upvaluesType == Closure.UpvaluesType.Closure)
            {
                throw new ArgumentException("function arg has upvalues other than _ENV");
            }

            UndisposableStream outStream = new UndisposableStream(stream);

            m_MainProcessor.Dump(outStream, function.Function.EntryPointByteCodeLocation, upvaluesType == Closure.UpvaluesType.Environment);
        }
Esempio n. 2
0
        protected override async Task SerializeToStreamAsync(Stream stream, TransportContext context)
        {
            using (var uncloseableStream = new UndisposableStream(stream))
            //using (var bufferedStream = new BufferedStream(uncloseableStream))
            {
                //var streamToUse = bufferedStream;
                var    streamToUse = uncloseableStream;
                Stream compressedStream;

                if (encodingType == "gzip")
                {
                    compressedStream = new GZipStream(streamToUse, CompressionMode.Compress, leaveOpen: true);
                }
                else if (encodingType == "deflate")
                {
                    compressedStream = new DeflateStream(streamToUse, CompressionMode.Compress, leaveOpen: true);
                }
                else
                {
                    throw new InvalidOperationException("This shouldn't happen, ever.");
                }

                await originalContent.CopyToAsync(compressedStream).ConfigureAwait(false);

                if (compressedStream != null)
                {
                    compressedStream.Dispose();
                }
            }
        }
Esempio n. 3
0
        protected override Task SerializeToStreamAsync(Stream stream, TransportContext context)
        {
            if (HasNoData())
            {
                return(new CompletedTask <bool>(true));
            }

            using (var undisposableStream = new UndisposableStream(stream))
                using (var bufferedStream = new BufferedStream(undisposableStream))
                {
                    var writer = new StreamWriter(bufferedStream, DefaultEncoding);
                    if (string.IsNullOrEmpty(Jsonp) == false)
                    {
                        writer.Write(Jsonp);
                        writer.Write("(");
                    }

                    Data.WriteTo(new JsonTextWriter(writer)
                    {
                        Formatting = IsOutputHumanReadable ? Formatting.Indented : Formatting.None,
                    }, Default.Converters);

                    if (string.IsNullOrEmpty(Jsonp) == false)
                    {
                        writer.Write(")");
                    }

                    writer.Flush();
                }

            return(new CompletedTask <bool>(true));
        }
Esempio n. 4
0
        protected override async Task SerializeToStreamAsync(Stream stream, TransportContext context)
        {
            using (var uncloseableStream = new UndisposableStream(stream))
                using (var bufferedStream = new BufferedStream(uncloseableStream))
                {
                    Stream innerStream = bufferedStream;
                    try
                    {
                        if (disableRequestCompression == false)
                        {
                            innerStream = new GZipStream(innerStream, CompressionMode.Compress, leaveOpen: true);
                        }

                        await data.CopyToAsync(innerStream).ConfigureAwait(false);

                        await innerStream.FlushAsync().ConfigureAwait(false);
                    }
                    finally
                    {
                        if (disableRequestCompression == false)
                        {
                            innerStream.Dispose();
                        }
                    }
                }
        }
Esempio n. 5
0
        /// <summary>
        /// Dumps on the specified stream.
        /// </summary>
        /// <param name="function">The function.</param>
        /// <param name="stream">The stream.</param>
        /// <exception cref="System.ArgumentException">
        /// function arg is not a function!
        /// or
        /// stream is readonly!
        /// or
        /// function arg has upvalues other than _ENV
        /// </exception>
        public void Dump(DynValue function, Stream stream)
        {
            if (!m_isAlive)
            {
                throw new InvalidOperationException(string.Format("Attempting to dump dead Script [{0}]", FriendlyName));
            }
            this.CheckScriptOwnership(function);

            if (function.Type != DataType.Function)
            {
                throw new ArgumentException("function arg is not a function!");
            }

            if (!stream.CanWrite)
            {
                throw new ArgumentException("stream is readonly!");
            }

            Closure.UpvaluesType upvaluesType = function.Function.GetUpvaluesType();

            if (upvaluesType == Closure.UpvaluesType.Closure)
            {
                throw new ArgumentException("function arg has upvalues other than _ENV");
            }

            UndisposableStream outStream = new UndisposableStream(stream);

            m_MainProcessor.Dump(outStream, function.Function.EntryPointByteCodeLocation, upvaluesType == Closure.UpvaluesType.Environment);
        }
        public void BinDumpBinaryStreams_TestStringWrites()
        {
            string[] values = new string[] { "hello", "you", "fool", "hello", "I", "love", "you" };

            using (MemoryStream ms_orig = new MemoryStream())
            {
                UndisposableStream ms = new UndisposableStream(ms_orig);

                using (BinDumpBinaryWriter bdbw = new BinDumpBinaryWriter(ms, Encoding.UTF8))
                {
                    for (int i = 0; i < values.Length; i++)
                    {
                        bdbw.Write(values[i]);
                    }
                }

                ms.Seek(0, SeekOrigin.Begin);

                using (BinDumpBinaryReader bdbr = new BinDumpBinaryReader(ms, Encoding.UTF8))
                {
                    for (int i = 0; i < values.Length; i++)
                    {
                        string v = bdbr.ReadString();
                        Assert.AreEqual(values[i], v, "i = " + i.ToString());
                    }
                }
            }
        }
        public void BinDumpBinaryStreams_TestUIntWrites()
        {
            uint[] values = new uint[] { 0, 1, 0x7F, 10, 0x7E, 32767, 32768, uint.MinValue, uint.MaxValue };

            using (MemoryStream ms_orig = new MemoryStream())
            {
                UndisposableStream ms = new UndisposableStream(ms_orig);

                using (BinDumpBinaryWriter bdbw = new BinDumpBinaryWriter(ms, Encoding.UTF8))
                {
                    for (int i = 0; i < values.Length; i++)
                    {
                        bdbw.Write(values[i]);
                    }
                }

                ms.Seek(0, SeekOrigin.Begin);

                using (BinDumpBinaryReader bdbr = new BinDumpBinaryReader(ms, Encoding.UTF8))
                {
                    for (int i = 0; i < values.Length; i++)
                    {
                        uint v = bdbr.ReadUInt32();
                        Assert.AreEqual(values[i], v, "i = " + i.ToString());
                    }
                }
            }
        }
Esempio n. 8
0
        public override Stream Open()
        {
            CheckDisposed();

            var undisposable = new UndisposableStream(ArchiveFileInfo.FileData);

            return(undisposable);
        }
Esempio n. 9
0
        /// <summary>
        /// Writes an array of bytes to the stream with compression
        /// </summary>
        /// <param name="stream">Stream to write to</param>
        /// <param name="array">Array to write</param>
        /// <param name="offset">The byte offset into the array to write</param>
        /// <param name="count">The number of bytes from the array to write</param>
        public static void WriteCompressed(this Stream stream, byte[] array, int offset, int count)
        {
            // we don't want the DeflateStream to close the input stream
            // but we have to dispose the DeflateStream in order for it to flush (according to the documentation)
            // so wrap the input stream in an UndisposableStream
            stream = new UndisposableStream(stream);

            using (BinaryWriter writer = new BinaryWriter(stream))
                writer.Write(count);
            using (DeflateStream ds = new DeflateStream(stream, CompressionMode.Compress))
                ds.Write(array, offset, count);
        }
Esempio n. 10
0
        /// <inheritdoc />
        public Stream WrapUndisposable(Stream wrap)
        {
            var undisposable = new UndisposableStream(wrap);

            if (_streams.Contains(wrap))
            {
                _parentStreams[undisposable] = wrap;
            }
            _streams.Add(undisposable);

            return(undisposable);
        }
Esempio n. 11
0
        /// <summary>
        /// Loads a Lua/MoonSharp script from a System.IO.Stream. NOTE: This will *NOT* close the stream!
        /// </summary>
        /// <param name="stream">The stream containing code.</param>
        /// <param name="globalTable">The global table to bind to this chunk.</param>
        /// <param name="codeFriendlyName">Name of the code - used to report errors, etc.</param>
        /// <returns>
        /// A DynValue containing a function which will execute the loaded code.
        /// </returns>
        public DynValue LoadStream(Stream stream, Table globalTable = null, string codeFriendlyName = null)
        {
            if (!m_isAlive)
            {
                throw new InvalidOperationException(string.Format("Attempting to loadstream on dead Script [{0}]", FriendlyName));
            }
            this.CheckScriptOwnership(globalTable);

            Stream codeStream = new UndisposableStream(stream);

            if (!Processor.IsDumpStream(codeStream))
            {
                using (StreamReader sr = new StreamReader(codeStream))
                {
                    string scriptCode = sr.ReadToEnd();
                    return(LoadString(scriptCode, globalTable, codeFriendlyName));
                }
            }
            else
            {
                string chunkName = string.Format("{0}", codeFriendlyName ?? "dump_" + m_Sources.Count.ToString());

                SourceCode source = new SourceCode(codeFriendlyName ?? chunkName,
                                                   string.Format("-- This script was decoded from a binary dump - dump_{0}", m_Sources.Count),
                                                   m_Sources.Count, this);

                m_Sources.Add(source);

                bool hasUpvalues;
                int  address = m_MainProcessor.Undump(codeStream, m_Sources.Count - 1, globalTable ?? m_GlobalTable, out hasUpvalues);

                SignalSourceCodeChange(source);
                SignalByteCodeChange();

                if (hasUpvalues)
                {
                    return(MakeClosure(address, globalTable ?? m_GlobalTable));
                }
                else
                {
                    return(MakeClosure(address));
                }
            }
        }
Esempio n. 12
0
        public bool PullFile(RoamingProfile profile, string remotePath, Stream outputStream)
        {
            FtpWebRequest ftpFileRequest = FtpRequestFactory.CreateRequest(WebRequestMethods.Ftp.DownloadFile, profile,
                                                                           new Uri(remotePath));
            int? fileSize = FtpRequestFactory.GetFileSize(ftpFileRequest);

            if (fileSize.GetValueOrDefault() <= 0)
            {
                // TODO Log
                //Trace.WriteLineIf(RoamiePlugin.TraceSwitch.TraceError, "The FTP SIZE response says the remote file length is 0 bytes. This indicates the file is corrupted. Aborting download.", "Roamie");
                return false;
            }

            using (FtpWebResponse ftpFileResponse = (FtpWebResponse) ftpFileRequest.GetResponse())
            {
                using (Stream remoteStream = ftpFileResponse.GetResponseStream(), 
                       downloadedStream = new MemoryStream())
                {
                    ProgressMediator.ChangeProgress(Resources.Text_UI_LogText_DownloadingDb, SignificantProgress.Running);

                    var source = new UndisposableStream(remoteStream, fileSize);
                    var progressCallback = (fileSize != null
                                                ? (progress => ProgressMediator.ChangeProgress(null, progress))
                                                : (StreamUtility.ProgressCallback) null);

                    StreamUtility.CopyStream(source, downloadedStream, progressCallback);

                    ProgressMediator.ChangeProgress(Resources.Text_UI_LogText_DecryptingDecompressing,
                                                    SignificantProgress.Running);
                    downloadedStream.Seek(0, SeekOrigin.Begin);
                    StreamUtility.DecryptAndDecompress(downloadedStream, outputStream, profile.DatabasePassword);
                    outputStream.Seek(0, SeekOrigin.Begin);
                }
            }

            ProgressMediator.ChangeProgress(Resources.Text_UI_LogText_Completed, SignificantProgress.Complete);
            return true;
        }
Esempio n. 13
0
        public bool PullFile(RoamingProfile profile, string remotePath, Stream outputStream)
        {
            HttpWebRequest request = HttpRequestFactory.CreateWebRequest(profile, new Uri(remotePath));

            if (!String.IsNullOrEmpty(profile.UserName))
                request.Credentials = new NetworkCredential(profile.UserName, profile.Password);

            using (HttpWebResponse response = (HttpWebResponse) request.GetResponse())
            {
                long? fileSize = response.ContentLength > 0 ? response.ContentLength : (long?) null;

                if (fileSize.GetValueOrDefault() <= 0)
                    return false;

                using (Stream remoteStream = response.GetResponseStream(),
                              downloadedStream = new MemoryStream())
                {
                    ProgressMediator.ChangeProgress(Resources.Text_UI_LogText_DownloadingDb,
                                                    SignificantProgress.Running);

                    var source = new UndisposableStream(remoteStream, fileSize);
                    var progressCallback = (fileSize != null
                                                ? (progress => ProgressMediator.ChangeProgress(null, progress))
                                                : (StreamUtility.ProgressCallback) null);

                    StreamUtility.CopyStream(source, downloadedStream, progressCallback);

                    ProgressMediator.ChangeProgress(Resources.Text_UI_LogText_CompressingEncrypting,
                                                    SignificantProgress.Running);
                    downloadedStream.Seek(0, SeekOrigin.Begin);
                    StreamUtility.DecryptAndDecompress(downloadedStream, outputStream, profile.DatabasePassword);
                    outputStream.Seek(0, SeekOrigin.Begin);
                }
            }

            ProgressMediator.ChangeProgress(Resources.Text_UI_LogText_Completed, SignificantProgress.Complete);
            return true;
        }