Flush() public abstract méthode

public abstract Flush ( ) : void
Résultat void
Exemple #1
0
        /// <summary>
        /// // TODO
        /// </summary>
        /// <param name="stream"></param>
        /// <param name="data"></param>
        /// <param name="statusCode"></param>
        /// <param name="headers"></param>
        /// <param name="closeConnection">we don’t currently support persistent connection via Http1.1 so closeConnection:true</param>
        /// <returns></returns>
        public static int SendResponse(Stream stream, byte[] data, int statusCode, IDictionary<string,string[]> headers = null, bool closeConnection = true)
        {
            string initialLine = "HTTP/1.1 " + statusCode + " " + StatusCode.GetReasonPhrase(statusCode) + "\r\n";
            string headersPack = initialLine;

            if (headers == null)
                headers = new Dictionary<string,string[]>(StringComparer.OrdinalIgnoreCase);

            if (!headers.ContainsKey("Connection") && closeConnection)
            {
                headers.Add("Connection", new[] { "Close" });
            }

            if (!headers.ContainsKey("Content-Length"))
            {
                headers.Add("Content-Length", new [] { Convert.ToString(data.Length) });
            }

            headersPack = headers.Aggregate(headersPack, (current, header) => current + (header.Key + ": " + String.Join(",", header.Value) + "\r\n")) + "\r\n";

            int sent = stream.Write(Encoding.UTF8.GetBytes(headersPack));
            //Send headers and body separately
            //TODO It's needed for our client. Think out a way to avoid separate sending.
            stream.Flush();

            if (data.Length > 0)
                sent += stream.Write(data);

            Thread.Sleep(200);

            stream.Flush();
            return sent;
        }
        public static void CopyStream(Stream outputStream, Stream inputStream)
        {
            int bytesRead;
            var buffer = new byte[Globals.BufferSize];

            while ((bytesRead = inputStream.Read(buffer, 0, buffer.Length)) > 0)
            {
                outputStream.Write(buffer, 0, bytesRead);
                outputStream.Flush();
            }
            outputStream.Flush();
        }
Exemple #3
0
 public static void ReceiveStream(Stream stream, Stream out_stream)
 {
     long _len = ReceiveLong(stream);
     long _read = 0;
     byte[] _buffer = new byte[blocksize];
     while (_read < _len)
     {
         _read = _read + stream.Read(_buffer, 0, blocksize);
         out_stream.Write(_buffer, 0, blocksize);
         out_stream.Flush();
     }
     out_stream.Write(_buffer, 0, Convert.ToInt32(_len-_read));
     out_stream.Flush();
 }
        /// <summary>
        /// Copy the contents of one <see cref="Stream"/> to another.
        /// </summary>
        /// <param name="source">The stream to source data from.</param>
        /// <param name="destination">The stream to write data to.</param>
        /// <param name="buffer">The buffer to use during copying.</param>
        public static void Copy(Stream source, Stream destination, byte[] buffer)
        {
            if (source == null) {
                throw new ArgumentNullException(nameof(source));
            }

            if (destination == null) {
                throw new ArgumentNullException(nameof(destination));
            }

            if (buffer == null) {
                throw new ArgumentNullException(nameof(buffer));
            }

            // Ensure a reasonable size of buffer is used without being prohibitive.
            if (buffer.Length < 128) {
                throw new ArgumentException("Buffer is too small", nameof(buffer));
            }

            bool copying = true;

            while (copying) {
                int bytesRead = source.Read(buffer, 0, buffer.Length);
                if (bytesRead > 0) {
                    destination.Write(buffer, 0, bytesRead);
                } else {
                    destination.Flush();
                    copying = false;
                }
            }
        }
 private static int Gzip(Stream stream, FileStream fs)
 {
     int length = 0;
     using (var ms = new MemoryStream())
     {
         byte[] buffer = new byte[BufferSize];
         int count;
         using (var gzip = new GZipStream(ms, CompressionMode.Compress, true))
         {
             while ((count = fs.Read(buffer, 0, BufferSize)) > 0)
             {
                 gzip.Write(buffer, 0, count);
             }
             gzip.Flush();
         }
         ms.Seek(0, SeekOrigin.Begin);
         while ((count = ms.Read(buffer, 0, BufferSize)) > 0)
         {
             length += count;
             stream.Write(buffer, 0, count);
         }
         stream.Flush();
     }
     return length;
 }
 public static void Copy(Stream source, Stream destination, byte[] buffer)
 {
     if (source == null)
     {
         throw new ArgumentNullException("source");
     }
     if (destination == null)
     {
         throw new ArgumentNullException("destination");
     }
     if (buffer == null)
     {
         throw new ArgumentNullException("buffer");
     }
     if (buffer.Length < 0x80)
     {
         throw new ArgumentException("Buffer is too small", "buffer");
     }
     bool flag = true;
     while (flag)
     {
         int count = source.Read(buffer, 0, buffer.Length);
         if (count > 0)
         {
             destination.Write(buffer, 0, count);
         }
         else
         {
             destination.Flush();
             flag = false;
         }
     }
 }
        public void Serialize(Object graph, Stream output)
        {
            var buffer = (Byte[])graph;

            output.Write(buffer, 0, buffer.Length);
            output.Flush();
        }
 private void SendHttpResponse(TcpClient client, Stream stream, HttpListenerResponse response, byte[] body)
 {
     // Status line
     var statusLine = $"HTTP/1.1 {response.StatusCode} {response.StatusDescription}\r\n";
     var statusBytes = Encoding.ASCII.GetBytes(statusLine);
     stream.Write(statusBytes, 0, statusBytes.Length);
     // Headers
     foreach (var key in response.Headers.AllKeys)
     {
         var value = response.Headers[key];
         var line = $"{key}: {value}\r\n";
         var lineBytes = Encoding.ASCII.GetBytes(line);
         stream.Write(lineBytes, 0, lineBytes.Length);
     }
     // Content-Type header
     var contentType = Encoding.ASCII.GetBytes($"Content-Type: {response.ContentType}\r\n");
     stream.Write(contentType, 0, contentType.Length);
     // Content-Length header
     var contentLength = Encoding.ASCII.GetBytes($"Content-Length: {body.Length}\r\n");
     stream.Write(contentLength, 0, contentLength.Length);
     // "Connection: close", to tell the client we can't handle persistent TCP connections
     var connection = Encoding.ASCII.GetBytes("Connection: close\r\n");
     stream.Write(connection, 0, connection.Length);
     // Blank line to indicate end of headers
     stream.Write(new[] { (byte)'\r', (byte)'\n' }, 0, 2);
     // Body
     stream.Write(body, 0, body.Length);
     stream.Flush();
     // Graceful socket shutdown
     client.Client.Shutdown(SocketShutdown.Both);
     client.Dispose();
 }
Exemple #9
0
		public void SaveToStream(Stream stream) {
			if(String.IsNullOrEmpty(FileName)) {
				throw new InvalidOperationException();
			}
			stream.Write(Content, 0, Size);
			stream.Flush();
		}
Exemple #10
0
        /// <summary>
        /// Копирование из потока в поток
        /// </summary>
        /// <param name="input"></param>
        /// <param name="output"></param>
        public static void CopyStream(Stream input, Stream output)
        {
            try
            {
                int bufferSize = 4096;

                byte[] buffer = new byte[bufferSize];

                while (true)
                {
                    int read = input.Read(buffer, 0, buffer.Length);

                    if (read <= 0)
                    {
                        input.Flush();
                        input.Close();

                        return;
                    }

                    output.Write(buffer, 0, read);
                }
            }
            catch (Exception ex)
            {
                DebugHelper.WriteLogEntry(ex, "Streem copy error");
                output = null;
            }
        }
        public override void GetData(object target, Stream outgoingData)
        {
            var depthFrame = (target as DepthFrame);

            if (depthFrame == null)
                return;

            var formatter = new BinaryFormatter();
            var internalDepthFrame = new InternalDepthFrame();

            internalDepthFrame.FrameDescription = new InternalFrameDescription()
            {
                BytesPerPixel = depthFrame.FrameDescription.BytesPerPixel,
                DiagonalFieldOfView = depthFrame.FrameDescription.DiagonalFieldOfView,
                Height = depthFrame.FrameDescription.Height,
                HorizontalFieldOfView = depthFrame.FrameDescription.HorizontalFieldOfView,
                LengthInPixels = depthFrame.FrameDescription.LengthInPixels,
                VerticalFieldOfView = depthFrame.FrameDescription.VerticalFieldOfView,
                Width = depthFrame.FrameDescription.Width,
            };

            internalDepthFrame.DepthMaxReliableDistance = depthFrame.DepthMaxReliableDistance;
            internalDepthFrame.DepthMinReliableDistance = depthFrame.DepthMinReliableDistance;
            internalDepthFrame.RelativeTime = depthFrame.RelativeTime;
            internalDepthFrame.Image = depthFrame.GetPixelArrayFrame();

            formatter.Serialize(outgoingData, internalDepthFrame);

            outgoingData.Flush();
        }
Exemple #12
0
        private void Copy(NetworkStream src, Stream dest, int bufferSize)
        {
            if(!src.DataAvailable)
                return;

            try
            {
                var buffer = new byte[bufferSize];
                var bytesRead = 0;
                do
                {
                    bytesRead = src.Read(buffer, 0, buffer.Length);
                    dest.Write(buffer, 0, bytesRead);

                    PrintHexData(buffer, bytesRead);

                } while (bytesRead > 0 && src.DataAvailable);

                dest.Flush();
            }
            catch(IOException ioException)
            {
                if(ioException.InnerException is SocketException)
                {
                    var se = (SocketException)ioException.InnerException;
                    if (se.SocketErrorCode != SocketError.ConnectionAborted)
                        throw;

                }
            }
        }
        /// <summary>
        /// Returns a buffer with the contents of the given stream.
        /// <param name="stream">Source stream</param>
        /// <returns>Buffer with the contents of the given stream</returns>
        /// </summary>
        private IBuffer StreamToBuffer(Stream stream)
        {
            var memoryStream = stream as MemoryStream;

            if (memoryStream == null)
            {
                using (memoryStream = new MemoryStream())
                {
                    stream.Position = 0;
                    stream.CopyTo(memoryStream);

                    try
                    {
                        // Some stream types do not support flushing

                        stream.Flush();
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.ToString());
                    }

                    return memoryStream.GetWindowsRuntimeBuffer();
                }
            }
            else
            {
                return memoryStream.GetWindowsRuntimeBuffer();
            }
        }
    /// <summary>
    /// Reads a data block's stream and writes it to a given <paramref name="targetStream"/>.
    /// </summary>
    /// <param name="dataBlock">The data block that provides a chunk of data that should
    /// be written to the <paramref name="targetStream"/>.</param>
    /// <param name="targetStream">The target stream that receives the block's
    /// <see cref="StreamedDataBlock.Data"/>.</param>
    /// <param name="maxStreamSize">The maximum number of bytes that can be written to the destination
    /// stream. If the read stream exceeds this limit, a <see cref="DataBlockException"/> is thrown.</param>
    /// <exception cref="DataBlockException">If the data block's stream length exceeds the
    /// <paramref name="maxStreamSize"/> threshhold.</exception>
    public static void WriteTo(this StreamedDataBlock dataBlock, Stream targetStream, long maxStreamSize)
    {
      //use default byte sizes
      byte[] buffer = new byte[32768];

      long totalBytesRead = 0;

      while (true)
      {
        int bytesRead = dataBlock.Data.Read(buffer, 0, buffer.Length);
        totalBytesRead += bytesRead;

        if(totalBytesRead > maxStreamSize)
        {
          string msg = "The length of the stream of data block number [{0}] for transfer [{1}] exceeds the size limit of [{2}] bytes.";
          msg = String.Format(msg, dataBlock.BlockNumber, dataBlock.TransferTokenId, maxStreamSize);
          throw new DataBlockException(msg);
        }

        if (bytesRead > 0)
        {
          targetStream.Write(buffer, 0, bytesRead);
        }
        else
        {
          targetStream.Flush();
          break;
        }
      }
    }
        public override void GetData(object target, Stream outgoingData)
        {
            var longExposureInfraredFrame = (target as LongExposureInfraredFrame);

            if (longExposureInfraredFrame == null)
                return;

            var formatter = new BinaryFormatter();
            var internalLongExposureInfraredFrame = new InternalLongExposureInfraredFrame();

            internalLongExposureInfraredFrame.FrameDescription = new InternalFrameDescription()
            {
                BytesPerPixel = longExposureInfraredFrame.FrameDescription.BytesPerPixel,
                DiagonalFieldOfView = longExposureInfraredFrame.FrameDescription.DiagonalFieldOfView,
                Height = longExposureInfraredFrame.FrameDescription.Height,
                HorizontalFieldOfView = longExposureInfraredFrame.FrameDescription.HorizontalFieldOfView,
                LengthInPixels = longExposureInfraredFrame.FrameDescription.LengthInPixels,
                VerticalFieldOfView = longExposureInfraredFrame.FrameDescription.VerticalFieldOfView,
                Width = longExposureInfraredFrame.FrameDescription.Width,
            };

            internalLongExposureInfraredFrame.RelativeTime = longExposureInfraredFrame.RelativeTime;
            internalLongExposureInfraredFrame.Image = longExposureInfraredFrame.GetPixelArrayFrame();

            formatter.Serialize(outgoingData, internalLongExposureInfraredFrame);

            outgoingData.Flush();
        }
Exemple #16
0
        /// <summary>
        /// Читает из архива очередной файл.
        /// </summary>
        /// <param name="outputStream">
        /// Поток, в который записывается содержимое прочитанного файла.
        /// </param>
        /// <returns>Имя прочитанного файла или null, если прочесть нечего.</returns>
        public string ReadFile( Stream outputStream )
        {
            // прочитать очередную запись из архива
            ZipEntry entry = zipStream.GetNextEntry();

            // записей больше нет
            if (entry == null)
                return null;

            // прочитать имя файла
            string fileName = entry.Name;

            byte[] buffer = new byte[4096];
            while (true)
            {
                // прочитать блок из архива
                int bytesRead = zipStream.Read( buffer, 0, buffer.Length );

                string str = Encoding.UTF8.GetString(buffer);

                // если ничего не прочитано, прекратить считывание
                if (bytesRead == 0)
                    break;
                // иначе, записать блок в результирующий поток
                outputStream.Write( buffer, 0, bytesRead );
            }

            // переместить указатель результирующего потока на начало
            outputStream.Flush();
            outputStream.Seek( 0, SeekOrigin.Begin );

            return fileName;
        }
        /// <summary>
        /// Encodes a WriteableBitmap object into a PNG stream.
        /// </summary>
        /// <param name="writeableBitmap">The writeable bitmap.</param>
        /// <param name="outputStream">The image data stream.</param>
        /// <returns>The <see cref="Task"/> object representing the asynchronous operation.</returns>
        public static async Task SavePngAsync(this WriteableBitmap writeableBitmap, Stream outputStream)
        {
#if WINDOWS_PHONE
            WriteHeader(outputStream, writeableBitmap);

            WritePhysics(outputStream);

            ////WriteGamma(outputStream);

            WriteDataChunks(outputStream, writeableBitmap);

            WriteFooter(outputStream);

            outputStream.Flush();

            await Task.FromResult(0);
#else
            var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, outputStream.AsRandomAccessStream());
            var pixels = writeableBitmap.PixelBuffer.ToArray();

            encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Straight, (uint)writeableBitmap.PixelWidth, (uint)writeableBitmap.PixelHeight, ResolutionDpi, ResolutionDpi, pixels);

            await encoder.FlushAsync();
#endif
        }
 protected override Task SerializeToStreamAsync(Stream stream, TransportContext context)
 {
     var tcs = new TaskCompletionSource<object>();
     _body.Invoke(
         data =>
         {
             stream.Write(data.Array, data.Offset, data.Count);
             return false;
         },
         _ =>
         {
             stream.Flush();
             return false;
         },
         ex =>
         {
             if (ex == null)
             {
                 tcs.TrySetResult(null);
             }
             else
             {
                 tcs.TrySetException(ex);
             }
         },
         _cancellationToken);
     return tcs.Task;
 }
 /// <summary>
 /// 发送所有请求头到服务器
 /// </summary>
 /// <param name="req"></param>
 /// <param name="_stream"></param>
 private void OutHeader(RequestInfo req, Stream _stream)
 {
     var _out = new StreamWriter(_stream);
     _out.Write(String.Format("GET {0} HTTP/1.0 \r\n", req.Path));
     var host = req.Host;
     if (req.Port != 80)
     {
         host += ":" + req.Port;
     }
     _out.Write(String.Format(HEADERFORMAT, "HOST", host));
     _out.Write(String.Format(HEADERFORMAT, HtmlStaticCore.SKIPMARKHEAD, 1));
     foreach (String key in req.Headers.Keys)
     {
         var lowerKey = key.ToLower();
         if (lowerKey != "connection" && lowerKey != "host")
         {
             var val = req.Headers[key];
             _out.Write(String.Format(HEADERFORMAT, key, val));
         }
     }
     _out.Write(CONNECTION_CLOSE);
     _out.Write("\r\n");
     _out.Flush();
     _stream.Flush();
 }
 private void DownloadToStream(string url, Stream stream, bool urlIsGzipFile)
 {
     byte[] buffer = new byte[1024];
     try {
         WebRequest webRequest = WebRequest.Create(url);
         using(WebResponse webResponse = webRequest.GetResponse()) {
             using(Stream remoteStream = webResponse.GetResponseStream()) {
                 var readStream = !urlIsGzipFile ? remoteStream : new GZipStream(remoteStream, CompressionMode.Decompress);
                 try {
                     int bytesRead = 0;
                     do {
                         bytesRead = readStream.Read(buffer, 0, buffer.Length);
                         if(bytesRead > 0) stream.Write(buffer, 0, bytesRead);
                     } while(bytesRead > 0);
                     stream.Flush();
                 } finally {
                     if(urlIsGzipFile && readStream != null) readStream.Dispose();
                 }
             }
         }
     } catch(Exception ex) {
         // The standard exception is not very helpful - in particular it doesn't report the URL that we're downloading
         throw new InvalidOperationException(String.Format("Could not download {0}: {1}", url, ex.Message), ex);
     }
 }
        public void Connect(string user, string pass)
        {
            if (bConnected)
                return;
            #if UNITY_ANDROID
            _stream = new WrapperNetStream();

            #elif UNITY_STANDALONE
            TcpClient _client = null;
             _client = new TcpClient();
            _client.Connect(IPAddress.Parse("192.168.2.5"), 2594);
            _stream = _client.GetStream();
            #endif

            Debug.Log("Begin Connect called on local 2594");
            if (_stream != null && !bConnected) {
                var l = new LoginRequest();
                l.UserName = user;
                l.Password = GetSHA256Hash(pass);
                Serializer.SerializeWithLengthPrefix<LoginRequest>(_stream, l, PrefixStyle.Base128);
                _stream.Flush();
                bConnected = true;
                Debug.Log("Sent Connection auth req: " + user + " / " + l.Password);
            }
        }
        public static void Copy(Stream source, Stream destination, byte[] buffer)
        {
            if (source == null) {
                throw new ArgumentNullException("source");
            }

            if (destination == null) {
                throw new ArgumentNullException("destination");
            }

            if (buffer == null) {
                throw new ArgumentNullException("buffer");
            }

            if (buffer.Length < 128) {
                throw new ArgumentException("Buffer is too small", "buffer");
            }

            bool copying = true;

            while (copying) {
                int bytesRead = source.Read(buffer, 0, buffer.Length);
                if (bytesRead > 0) {
                    destination.Write(buffer, 0, bytesRead);
                }
                else {
                    destination.Flush();
                    copying = false;
                }
            }
        }
 public static void SendHeader(Header header, Stream stream)
 {
     string sBuffer = "";
     sBuffer = header.ToString();
     stream.Write(Encoding.ASCII.GetBytes(sBuffer), 0, sBuffer.Length);
     stream.Flush();
 }
Exemple #24
0
 private static void CopyStream(Stream input, Stream output, int size)
 {
     byte[] buffer1 = new byte[size];
     input.Read(buffer1, 0, size);
     output.Write(buffer1, 0, size);
     output.Flush();
 }
 public static void Workaround_Ladybug318918(Stream s)
 {
     // This is a workaround for this issue:
     // https://connect.microsoft.com/VisualStudio/feedback/details/318918
     // It's required only on NETCF.
     s.Flush();
 }
        public override void GetData(object target, Stream outgoingData)
        {
            var bodyFrame = (target as BodyFrame);

            if (bodyFrame == null)
                return;

            var formatter = new BinaryFormatter();
            var internalBodyFrame = new InternalBody2DFrame();
            var frameDescription = bodyFrame.GetFrameDescription();

            internalBodyFrame.FrameDescription = new InternalFrameDescription()
            {
                BytesPerPixel = frameDescription.BytesPerPixel,
                DiagonalFieldOfView = frameDescription.DiagonalFieldOfView,
                Height = frameDescription.Height,
                HorizontalFieldOfView = frameDescription.HorizontalFieldOfView,
                LengthInPixels = frameDescription.LengthInPixels,
                VerticalFieldOfView = frameDescription.VerticalFieldOfView,
                Width = frameDescription.Width,
            };

            internalBodyFrame.BodyCount = bodyFrame.BodyCount;
            internalBodyFrame.FloorClipPlane = bodyFrame.FloorClipPlane.ToInternalVector4();
            internalBodyFrame.RelativeTime = bodyFrame.RelativeTime;

            var array = bodyFrame.GetNewPixelArray();

            bodyFrame.ToBitmapSource(true, 5, 3).CopyPixels(array, frameDescription.Width * ((PixelFormats.Bgr32.BitsPerPixel + 7) / 8), 0);
            internalBodyFrame.Image = array;

            formatter.Serialize(outgoingData, internalBodyFrame);

            outgoingData.Flush();
        }
Exemple #27
0
        protected override void InternalWrite(Stream Target)
        {
            Target.Seek(0, SeekOrigin.Begin);
            Target.Write(ByteHelper.StringToByte("ID3"));
            //                Version 3.0   Flags  dummy size
            Target.Write(new byte[] { 3,0,  0,     0, 0, 0, 0  }, 0, 7);

            long totalFrameSize = 0;
            Stream frameStream = null;
            foreach(Frame f in Frames)
            {
                frameStream = FrameObjectToByteArray(f);
                totalFrameSize += frameStream.Length;
                frameStream.CopyTo(Target);
                frameStream.Flush();
            }
            Target.Seek(6, SeekOrigin.Begin);
            Target.Write(ByteHelper.GetByteArrayWith7SignificantBitsPerByteForInt((int)totalFrameSize));

            // frame fertig geschrieben jetzt müssen die daten rein =>
            // sourcestream an die stelle spulen und lesen bis endpos
            Target.Seek(DataStart, SeekOrigin.Begin);

            // Target.Copy(SourceStream, DataStart, DataEnd);

            Target.Flush();
            Target.Close();
        }
        public static WaitHandle AsyncCopy(this Stream src, Stream dst)
        {
            var evt = new ManualResetEvent(false);
            var buffer = new byte[BUFFER_SIZE];

            AsyncCallback cbk = null;
            cbk = (asyncReadResult) =>
            {
                int bytesRead = src.EndRead(asyncReadResult);
                if (bytesRead > 0)
                {
                    //Console.Write("r");
                    dst.BeginWrite(buffer, 0, bytesRead,
                        (asyncWriteResult) =>
                        {
                            //Console.Write("w");
                            dst.EndWrite(asyncWriteResult);
                            src.BeginRead(buffer, 0, buffer.Length, cbk, null);
                        }, null);
                }
                else
                {
                    Console.WriteLine();
                    dst.Flush();
                    dst.Position = 0;
                    evt.Set();
                }
            };
            src.BeginRead(buffer, 0, buffer.Length, cbk, buffer);
            return evt;
        }
Exemple #29
0
		public static void WriteGzip(XmlDocument theDoc, Stream theStream)
		{
			var ms = new MemoryStream();
		    var xmlSettings = new XmlWriterSettings
		                          {
		                              Encoding = Encoding.UTF8,
		                              ConformanceLevel = ConformanceLevel.Document,
		                              Indent = false,
		                              NewLineOnAttributes = false,
		                              CheckCharacters = true,
		                              IndentChars = string.Empty
		                          };

		    XmlWriter tw = XmlWriter.Create(ms, xmlSettings);

			theDoc.WriteTo(tw);
			tw.Flush();
			tw.Close();

			byte[] buffer = ms.GetBuffer();

			var compressedzipStream = new GZipStream(theStream, CompressionMode.Compress, true);
			compressedzipStream.Write(buffer, 0, buffer.Length);
			// Close the stream.
			compressedzipStream.Flush();
			compressedzipStream.Close();

			// Force a flush
			theStream.Flush();
		}
 public void Write(Stream stream)
 {
     writer = new StreamWriter(stream);
     writer.Write(rawData);
     writer.Flush();
     stream.Flush();
 }
Exemple #31
0
 /// <summary>
 ///   Flushes the underlying stream.
 /// </summary>
 public override void Flush()
 {
     _s.Flush();
 }
 public override void Flush()
 {
     stream.Flush();
 }
Exemple #33
0
 /// <summary>
 /// 当在派生类中重写时,将清除该流的所有缓冲区,并使得所有缓冲数据被写入到基础设备。
 /// </summary>
 /// <exception cref="T:System.IO.IOException">发生 I/O 错误。</exception>
 public override void Flush()
 {
     _innerStream.Flush();
 }
Exemple #34
0
        /// <inheritdoc />
        public override void ForwardProcessDataStream(System.IO.Stream inStream, System.IO.Stream outStream, Dictionary <string, string> options, out long writtenBytes)
        {
            if (options == null)
            {
                throw new ArgumentNullException("options");
            }
            else if (!options.ContainsKey(PasswordOption))
            {
                throw new ArgumentException("Options must contain encryption key", "options");
            }

            if (outStream == null)
            {
                throw new ArgumentNullException("outStream");
            }

#if NETFX_CORE
            inStream.Seek(0, 0);
            outStream.Seek(0, 0);

            IBuffer pwBuffer   = CryptographicBuffer.ConvertStringToBinary(options[PasswordOption], BinaryStringEncoding.Utf8);
            IBuffer saltBuffer = CryptographicBuffer.CreateFromByteArray(SALT);

            // Derive key material for password size 32 bytes for AES256 algorithm
            KeyDerivationAlgorithmProvider keyDerivationProvider = Windows.Security.Cryptography.Core.KeyDerivationAlgorithmProvider.OpenAlgorithm("PBKDF2_SHA1");
            // using salt and 1000 iterations
            KeyDerivationParameters pbkdf2Parms = KeyDerivationParameters.BuildForPbkdf2(saltBuffer, 1000);

            // create a key based on original key and derivation parmaters
            CryptographicKey keyOriginal  = keyDerivationProvider.CreateKey(pwBuffer);
            IBuffer          keyMaterial  = CryptographicEngine.DeriveKeyMaterial(keyOriginal, pbkdf2Parms, 32);
            CryptographicKey derivedPwKey = keyDerivationProvider.CreateKey(pwBuffer);

            // derive buffer to be used for encryption salt from derived password key
            IBuffer saltMaterial = CryptographicEngine.DeriveKeyMaterial(derivedPwKey, pbkdf2Parms, 16);

            // display the buffers - because KeyDerivationProvider always gets cleared after each use, they are very similar unforunately
            string keyMaterialString  = CryptographicBuffer.EncodeToBase64String(keyMaterial);
            string saltMaterialString = CryptographicBuffer.EncodeToBase64String(saltMaterial);

            SymmetricKeyAlgorithmProvider symProvider = SymmetricKeyAlgorithmProvider.OpenAlgorithm("AES_CBC_PKCS7");
            // create symmetric key from derived password key
            CryptographicKey symmKey = symProvider.CreateSymmetricKey(keyMaterial);

            using (MemoryStream ms = new MemoryStream())
            {
                inStream.CopyTo(ms);
                // encrypt data buffer using symmetric key and derived salt material
                IBuffer resultBuffer = CryptographicEngine.Encrypt(symmKey, WindowsRuntimeBufferExtensions.GetWindowsRuntimeBuffer(ms), saltMaterial);
                resultBuffer.AsStream().CopyTo(outStream);
                writtenBytes = outStream.Position;
            }
#else
            Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(options[PasswordOption], SALT);
            var key = pdb.GetBytes(32);
            pdb.Reset();
            var iv = pdb.GetBytes(16);

            using (var transform = encrypter.CreateEncryptor(key, iv))
            {
                using (MemoryStream internalStream = new MemoryStream())
                {
                    using (CryptoStream csEncrypt = new CryptoStream(internalStream, transform, CryptoStreamMode.Write))
                    {
                        StreamTools.Write(inStream, csEncrypt);
                        inStream.Flush();
                        csEncrypt.FlushFinalBlock();

                        internalStream.Seek(0, 0);
                        StreamTools.Write(internalStream, outStream);
                        writtenBytes = outStream.Position;
                    }
                }
            }
#endif
        }
Exemple #35
0
        public static void WriteExcel(
            this IDictionary <string, IEnumerable <object> > enumerables,
            System.IO.Stream outStream,
            bool excludeHeaders = false)
        {
            try
            {
                #region initial settings

                string tempPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".xlsx");

                SpreadsheetDocument spreadsheetDocument =
                    SpreadsheetDocument.Create(tempPath, SpreadsheetDocumentType.Workbook, true);

                // Add a WorkbookPart to the document.
                WorkbookPart workbookpart = spreadsheetDocument.AddWorkbookPart();
                workbookpart.AddDateStyle();
                workbookpart.Workbook = new Workbook();

                // Add Sheets to the Workbook.
                Sheets sheets =
                    spreadsheetDocument.WorkbookPart.Workbook.AppendChild <Sheets>(new Sheets());



                #endregion

                #region looping sheets

                var sheetNumber = 0;
                foreach (var enumerableSheet in enumerables)
                {
                    sheetNumber++;

                    // Add a WorksheetPart to the WorkbookPart.
                    WorksheetPart worksheetPart = workbookpart.AddNewPart <WorksheetPart>();
                    worksheetPart.Worksheet = new Worksheet(new SheetData());

                    Sheet sheet = new()
                    {
                        Id      = spreadsheetDocument.WorkbookPart.GetIdOfPart(worksheetPart),
                        SheetId = (UInt32)sheetNumber,
                        Name    = enumerableSheet.Key
                    };

                    sheets.Append(sheet);
                    if (enumerableSheet.Value == null)
                    {
                        continue;
                    }

                    SheetData sheetData = worksheetPart.Worksheet.GetFirstChild <SheetData>();

                    bool headersSet = false;

                    // looping data rows to fill excel sheet
                    foreach (var item in enumerableSheet.Value)
                    {
                        var properties = item?.GetCachedProperties()?.ToList();

                        if (properties == null || properties.Count < 1)
                        {
                            continue;
                        }

                        #region headers
                        if (!excludeHeaders && !headersSet)
                        {
                            sheetData.Append(
                                new Row(
                                    properties.Select(pInfo => new Cell()
                            {
                                CellValue = new CellValue(pInfo.Name),
                                DataType  = new EnumValue <CellValues>(CellValues.String)
                            })));
                            headersSet = true;
                        }
                        #endregion


                        Cell GetCell((string Name, PropertyInfo Info) pInfo)
                        {
                            object valueRaw = pInfo.Info.GetValue(item);

                            if (valueRaw == null)
                            {
                                return new Cell()
                                       {
                                           CellValue = new CellValue(""),
                                           DataType  = new EnumValue <CellValues>(pInfo.Info.PropertyType.GetOpenXmlType())
                                       }
                            }
                            ;

                            if (pInfo.Info.PropertyType == typeof(DateTime)
                                ||
                                pInfo.Info.PropertyType == typeof(DateTime?))
                            {
                                return new Cell()
                                       {
                                           CellValue = new CellValue(((DateTime)valueRaw)
                                                                     .ToOADate().ToString(CultureInfo.InvariantCulture)),
                                           DataType   = new EnumValue <CellValues>(CellValues.Number),
                                           StyleIndex = 1
                                       }
                            }
                            ;

                            return(new Cell()
                            {
                                CellValue = new CellValue(valueRaw.ToString()),
                                DataType = new EnumValue <CellValues>(
                                    pInfo.Info.PropertyType.GetOpenXmlType()),
                                StyleIndex = 0
                            });
                        }

                        #region data / filling cells (columns) within current row
                        sheetData.Append(new Row(properties
                                                 .Select(pInfo => GetCell(pInfo))));

                        #endregion
                    }
                }

                #endregion
                #region finalizing

                spreadsheetDocument.Close();

                spreadsheetDocument = null;
                try
                {
                    outStream.Write(File.ReadAllBytes(tempPath));
                    outStream.Flush();
                    File.Delete(tempPath);
                }
                catch { }
                #endregion
            }
            catch
            {
                throw;
            }
        }
Exemple #36
0
 public override void Flush()
 {
     m_basestream.Flush();
 }
Exemple #37
0
 public override void Flush()
 {
     parent.Flush();
 }
Exemple #38
0
 public override void Flush()
 {
     inner.Flush();
 }
 public override void Flush() => _stream.Flush();
Exemple #40
0
        private void connectToEngineStackoverFlow(string method, string directory, string data)
        {
            //private string SendData(string method, string directory, string data)

            //string page = string.Format("http://{0}/{1}", DeviceAddress, directory);

            ac.uk.brunel.contextaware.Note myNote = new ac.uk.brunel.contextaware.Note();
            myNote.btAddress = "0017833F9DF3"; //win mob sin

            //BHttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://172.16.207.128:8080/");
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://context-aware-meeting-room.appspot.com/presentationNotes");

            request.KeepAlive                 = false;
            request.ProtocolVersion           = HttpVersion.Version10;
            request.Method                    = "POST";
            request.UserAgent                 = "Windows Mobile";
            request.AllowWriteStreamBuffering = true;


            //ProtoBuf.Serializer.
            // turn our request string into a byte stream

            /*byte[] postBytes;
             *
             * if(data != null)
             * {
             *  postBytes = Encoding.UTF8.GetBytes(data);
             * }
             * else
             * {
             *  postBytes = new byte[0];
             * }
             *
             *
             *
             *
             * request.ContentType = "application/x-www-form-urlencoded";
             * request.ContentLength = postBytes.Length;*/

            System.IO.Stream requestStream = request.GetRequestStream();

            //Serializer.Serialize<ac.uk.brunel.contextaware.Note>(requestStream, myNote);


            // System.Xml.Serialization.XmlSerializer seria = new System.Xml.Serialization.XmlSerializer(myNote.GetType());
            //  seria.Serialize(requestStream,myNote);

            byte[] postBytes = this.Serialize(myNote);
            // now send it
            requestStream.Write(postBytes, 0, postBytes.Length);
            requestStream.Flush();
            requestStream.Close();

            //  textBox1.Text = "i gjennom";

            HttpWebResponse response;

            response      = (HttpWebResponse)request.GetResponse();
            textBox1.Text = "i gjennom";
            //    return GetResponseData(response);


            System.IO.Stream responseStream = response.GetResponseStream();

            /*int myByte = 0;
             * while (myByte != -1)
             * {
             *  myByte = responseStream.ReadByte();
             * }
             */
            ac.uk.brunel.contextaware.Note myNoteRec = ProtoBuf.Serializer.Deserialize <ac.uk.brunel.contextaware.Note>(responseStream);
            textBox2.Text = "igjennom 2:  " + myNoteRec.message;

            /*
             *  i første omgang sender du BluetoothAddress
             * hvis du får tilbake en gyldig meetingid (at den ikke er null eller tom) så sender du også med den i tillegg til btAddress på neste request
             * */
        }
Exemple #41
0
 static void CopyStream(System.IO.Stream input, System.IO.Stream output)
 {
     input.CopyTo(output);
     output.Flush();
 }
Exemple #42
0
 // Writes are buffered.  Anytime the buffer fills up
 // (_writePos + delta > _bufferSize) or the buffer switches to reading
 // and there is dirty data (_writePos > 0), this function must be called.
 private void FlushWrite()
 {
     _s.Write(_buffer, 0, _writePos);
     _writePos = 0;
     _s.Flush();
 }
 public override void Flush()
 {
     _stream?.Flush();
 }
Exemple #44
0
 public virtual void Flush()
 {
     OutStream.Flush();
 }
Exemple #45
0
        public ActionResult ProcessRequest()
        {
            LogHelper.WriteLog("ProcessRequest " );
            //接收从微信后台POST过来的数据
            System.IO.Stream s = Request.InputStream;
            int count = 0;
            byte[] buffer = new byte[1024];
            StringBuilder builder = new StringBuilder();
            while ((count = s.Read(buffer, 0, 1024)) > 0)
            {
                builder.Append(Encoding.UTF8.GetString(buffer, 0, count));
            }
            s.Flush();
            s.Close();
            s.Dispose();

            Log.Info(this.GetType().ToString(), "Receive data from WeChat : " + builder.ToString());

            //转换数据格式并验证签名
            WxPayData data = new WxPayData();
            try
            {
                data.FromXml(builder.ToString());
            }
            catch (WxPayException ex)
            {
                //若签名错误,则立即返回结果给微信支付后台
                WxPayData res = new WxPayData();
                res.SetValue("return_code", "FAIL");
                res.SetValue("return_msg", ex.Message);
                Log.Error(this.GetType().ToString(), "Sign check error : " + res.ToXml());
               Response.Write(res.ToXml());
                Response.End();

            }
            var notifyData = data;
            Log.Info(this.GetType().ToString(), "Check sign success");
      
            //检查openid和product_id是否返回
            if (!notifyData.IsSet("openid") || !notifyData.IsSet("product_id"))
            {
                WxPayData res = new WxPayData();
                res.SetValue("return_code", "FAIL");
                res.SetValue("return_msg", "回调数据异常");
                Log.Info(this.GetType().ToString(), "The data WeChat post is error : " + res.ToXml());
                Response.Write(res.ToXml());
                Response.End();
            }
            if (notifyData.IsSet("return_code"))
            {
                //统一下单成功,则返回成功结果给微信支付后台
                WxPayData datareturn = new WxPayData();
                datareturn.SetValue("return_code", "SUCCESS");
                datareturn.SetValue("return_msg", "OK");
                Log.Info(this.GetType().ToString(), "UnifiedOrder success , send data to WeChat : " + datareturn.ToXml());
                Response.Write(datareturn.ToXml());
                Response.End();

            }
            
            return View();
        }
Exemple #46
0
        public void ProcessRequest(HttpContext context)
        {
            string res = "{\"CODE\": \"00\", \"MSG\": \"OK\"}";// Y/N 接收成功或失败

            try
            {
                context.Response.ContentType = "application/json";
                #region 获取流数据
                System.IO.Stream s    = context.Request.InputStream;
                int           count   = 0;
                byte[]        buffer  = new byte[1024];
                StringBuilder builder = new StringBuilder();
                while ((count = s.Read(buffer, 0, 1024)) > 0)
                {
                    builder.Append(Encoding.UTF8.GetString(buffer, 0, count));
                }
                s.Flush();
                s.Close();
                s.Dispose();
                #endregion

                string rspStr = builder.ToString();
                //Task.Factory.StartNew(() =>
                //{
                //    HttpHelper.SendSoapRequest(DateTime.Now + "  收到旺财支付回调:" + rspStr, "http://182.254.242.12:56789/log/push/");
                //});
                Loggers.Debug(new DebugLogInfo()
                {
                    Message = string.Format("Receive data from PALifePay : {0}", rspStr)
                });


                LifePayRP req = rspStr.DeserializeJSONTo <LifePayRP>();

                string orderId    = req.merOrderNo;
                string resultcode = req.notifyType;
                string openId     = req.openId;

                AppOrderBLL    bll      = new AppOrderBLL(new Utility.BasicUserInfo());
                AppOrderEntity appOrder = bll.QueryByEntity(new AppOrderEntity()
                {
                    AppOrderID = orderId,
                }, null).FirstOrDefault();

                // 00 成功 01 失败 02 其他
                if (appOrder != null && resultcode == "00" && appOrder.Status != 2)
                {
                    appOrder.Status = 2;
                }

                if (appOrder != null && !(appOrder.IsNotified ?? false))
                {
                    try
                    {
                        string    msg;
                        Hashtable ht = new Hashtable();
                        ht.Add("serialNo", req.serialNo);
                        // 异步通知cpos
                        if (NotifyHandler.Notify(appOrder, out msg, ht))
                        {
                            appOrder.IsNotified = true;
                        }
                        else
                        {
                            appOrder.NextNotifyTime = DateTime.Now.AddMinutes(1);
                        }
                        //通知完成,通知次数+1
                        appOrder.NotifyCount = (appOrder.NotifyCount ?? 0) + 1;
                        bll.Update(appOrder);
                    }
                    catch (Exception ex)
                    {
                        Loggers.Exception(new ExceptionLogInfo(ex));
                    }
                }
                if ((appOrder.IsNotified ?? false) && appOrder.Status == 2)
                {
                    res = "{\"CODE\": \"00\", \"MSG\": \"OK\"}";//
                }
            }
            catch (Exception ex)
            {
                res = "{\"CODE\": \"01\", \"MSG\": \"" + ex + "\"}";//
            }
            Loggers.Debug(new DebugLogInfo()
            {
                Message = string.Format("Response data from PALifePay : {0}", res)
            });
            context.Response.Write(res);
            context.Response.End();
        }
Exemple #47
0
        /// <summary>
        /// Download a file from a remote server.
        /// </summary>
        /// <param name="localDestinationPath">The local destination file and path to write data to.</param>
        /// <param name="remoteSourceFilename">The remote source file name to read data from.</param>
        /// <param name="position">The position to start reading from.</param>
        /// <param name="asyncOperation">Should the download be execute asynchronously.</param>
        /// <returns>True if the operation was successful; else false.</returns>
        public bool DownloadFile(string localDestinationPath, string remoteSourceFilename, long position = 0, bool asyncOperation = false)
        {
            try
            {
                _localDestinationPathDownload = localDestinationPath;

                // If no async operation is requested.
                if (!asyncOperation)
                {
                    // Create the local destination file where
                    // the data will be written to.
                    _localDestinationDownload = new FileStream(localDestinationPath, FileMode.Create, FileAccess.Write, FileShare.ReadWrite);

                    // If a download position exists.
                    if (position > 0)
                    {
                        _localDestinationDownload.Position = position;
                    }

                    // Get the file size
                    long size = GetFileSize(remoteSourceFilename);

                    // Create a new request
                    _requestDownload             = System.Net.WebRequest.Create(new Uri(_remoteUri));
                    _requestDownload.Method      = "POST";
                    _requestDownload.Credentials = _networkCredential;

                    // Create the request structed data.
                    TextWriter textWriter = new StreamWriter(_requestDownload.GetRequestStream());
                    textWriter.Write(
                        "DN".PadRight(OPERATION_STRUCTURE_BUFFER_SIZE) +
                        remoteSourceFilename.PadRight(FILENAME_STRUCTURE_BUFFER_SIZE) +
                        size.ToString().PadRight(FILE_SIZE_STRUCTURE_BUFFER_SIZE) +
                        position.ToString().PadRight(FILE_POSITION_STRUCTURE_BUFFER_SIZE));
                    textWriter.Flush();

                    // Initiate the request, create the communication connection
                    _responseDownload = _requestDownload.GetResponse();

                    // Transfer the data from the server to the loacl source.
                    TransferData(_responseDownload.GetResponseStream(), _localDestinationDownload, size, _timeout);

                    // Close the local stream file.
                    _localDestinationDownload.Flush();
                    _localDestinationDownload.Close();

                    // Open the file that was downloaded and determine if
                    // the file contains the corrent text, if the file contains
                    // the error text then delete the file and report the error.
                    _localDestinationDownload = new FileStream(localDestinationPath, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite);
                    TextReader textReader = new StreamReader(_localDestinationDownload);

                    // Get the first line. Does the first line
                    // contin the 'ERROR' text
                    string error = textReader.ReadLine();
                    if (error.StartsWith("ERROR:"))
                    {
                        // Go the the top of the file and
                        // get the complete error text.
                        _localDestinationDownload.Seek(0, SeekOrigin.Begin);
                        error = textReader.ReadToEnd();

                        // Close the stream
                        textReader.Close();
                        _localDestinationDownload.Close();

                        // Throw the current error.
                        throw new Exception(error);
                    }
                }
                else
                {
                    // Start a new async download.
                    _asyncExecute.Execute <bool>(u => u.DownloadFile(localDestinationPath, remoteSourceFilename), "DownloadFile");
                }

                // return true.
                return(true);
            }
            catch (Exception ex)
            {
                // Clean-up
                if (_responseDownload != null)
                {
                    _responseDownload.Close();
                }

                // Clean-up
                if (_requestDownload != null)
                {
                    if (_requestDownload.GetRequestStream() != null)
                    {
                        _requestDownload.GetRequestStream().Close();
                    }
                }

                // Clean-up
                if (_localDestinationDownload != null)
                {
                    _localDestinationDownload.Close();
                }

                try
                {
                    // Clean-up delete the download local file.
                    File.Delete(_localDestinationPathDownload);
                }
                catch { }

                if (_asyncExecute.Exception != null)
                {
                    throw new Exception(ex.Message, new Exception(_asyncExecute.Exception.Message));
                }
                else
                {
                    throw ex;
                }
            }
            finally
            {
                // Clean-up
                if (!asyncOperation)
                {
                    if (_responseDownload != null)
                    {
                        _responseDownload.Close();
                    }
                }

                // Clean-up
                if (!asyncOperation)
                {
                    if (_requestDownload != null)
                    {
                        if (_requestDownload.GetRequestStream() != null)
                        {
                            _requestDownload.GetRequestStream().Close();
                        }
                    }
                }

                // Clean-up
                if (!asyncOperation)
                {
                    if (_localDestinationDownload != null)
                    {
                        _localDestinationDownload.Close();
                    }
                }
            }
        }
 public void Commit()
 {
   F.Flush();
 }
Exemple #49
0
 public override void Write(byte[] buffer, int offset, int count)
 {
     _stream.Write(buffer, offset, count);
     _writeStream.Write(buffer, offset, count);
     _writeStream.Flush();
 }
Exemple #50
0
        public static void Upload(Stream file, string directoryUrl, string fileUrl, string userName, string password, bool?usePassive = false)
        {
            #region Folder

            //replace last slash
            fileUrl      = fileUrl.EndsWith("/") ? fileUrl.Substring(0, fileUrl.Length - 1) : fileUrl;
            directoryUrl = directoryUrl.EndsWith("/") ? directoryUrl.Substring(0, directoryUrl.Length - 1) : directoryUrl;

#if NET452
            // Set the ftp credentials
            var credential = new NetworkCredential(userName, password);

            // Create a ftp client
            var client = new FtpClient(credential);
#elif NETCOREAPP2_2
            // Set the ftp credentials
            var config = new FtpClientConfiguration
            {
                Username = userName,
                Password = password
            };
            // Create a ftp client
            var client = new FtpClient(config);
#endif

#if NET452
            // Check for folder existence
            if (!client.DirectoryExists(new Uri(directoryUrl)))
            {
#endif
            try
            {
                // Create the ftp request object
                FtpWebRequest ftpReq = (FtpWebRequest)FtpWebRequest.Create(new Uri(directoryUrl));
                ftpReq.Credentials = new NetworkCredential(userName, password);
                ftpReq.Method      = WebRequestMethods.Ftp.MakeDirectory;

                // Create the ftp response object
                FtpWebResponse ftpRes = (FtpWebResponse)ftpReq.GetResponse();
            }
            catch (Exception)
            {
            }
#if NET452
        }
#endif

            #endregion

            #region File

            // Create FtpWebRequest object from the Uri provided
            System.Net.FtpWebRequest ftpWebRequest = (System.Net.FtpWebRequest)System.Net.FtpWebRequest.Create(new Uri(fileUrl));

            // Provide the WebPermission Credintials
            ftpWebRequest.Credentials        = new System.Net.NetworkCredential(userName, password);
            ftpWebRequest.ImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.None;

            // set timeout for 20 seconds
            ftpWebRequest.Timeout = 20000;

            // set transfer mode
            ftpWebRequest.UsePassive = true;

            // Specify the command to be executed.
            ftpWebRequest.Method = System.Net.WebRequestMethods.Ftp.UploadFile;

            // Specify the data transfer type.
            ftpWebRequest.UseBinary = true;

            // Notify the server about the size of the uploaded file
            ftpWebRequest.ContentLength = file.Length;

            // The buffer size is set to 2kb
            int buffLength = 2048;
            byte[] buff    = new byte[buffLength];

            try
            {
                // Stream to which the file to be upload is written
                System.IO.Stream stream = ftpWebRequest.GetRequestStream();

                // Read from the file stream 2kb at a time
                int contentLen = file.Read(buff, 0, buffLength);

                // Till Stream content ends
                while (contentLen != 0)
                {
                    // Write Content from the file stream to the FTP Upload Stream
                    stream.Write(buff, 0, contentLen);
                    contentLen = file.Read(buff, 0, buffLength);
                }

                // Close the file stream and the Request Stream
                stream.Flush();
                stream.Close();
                stream.Dispose();
                file.Close();
                file.Dispose();

                FtpWebResponse ftpRes = (FtpWebResponse)ftpWebRequest.GetResponse();
            }
            catch (Exception)
            {
            }


            #endregion
        }
Exemple #51
0
 public override void Flush()
 {
     _stream.Flush();
     _writeStream.Flush();
 }
Exemple #52
0
        /// <summary>
        /// Does the actual bulk inserts.
        /// </summary>
        /// <param name="table"></param>
        /// <param name="table_name"></param>
        /// <param name="batch_size"></param>
        private void BulkCopy(DataTable table, string table_name, int batch_size)
        {
            if (table != null && table.Rows.Count > 0)
            {
                // the copy command.
                NpgsqlCommand command = new NpgsqlCommand(string.Format(
                                                              "COPY {0} FROM STDIN WITH BINARY", table_name), _connection);

                // the copy in stream.
                // TODO: convert this to binary mode for speed and
                // to make sure the char ` can also be included in tags!
                NpgsqlCopyIn cin = new NpgsqlCopyIn(command, _connection);

                // copy line-by-line.
                cin.Start();
                try
                {
                    System.IO.Stream target = cin.CopyStream;
                    //Stream target = new FileInfo(@"C:\Users\ben.abelshausen\Desktop\node_osmsharp.copy").OpenWrite();

                    // write header.
                    List <byte> header = new List <byte>();
                    header.AddRange(System.Text.Encoding.ASCII.GetBytes("PGCOPY\n"));
                    header.Add((byte)255);
                    header.AddRange(System.Text.Encoding.ASCII.GetBytes("\r\n\0"));

                    header.Add((byte)0); // start of Flags field
                    header.Add((byte)0);
                    header.Add((byte)0);
                    header.Add((byte)0);
                    header.Add((byte)0); // start of Flags field
                    header.Add((byte)0);
                    header.Add((byte)0);
                    header.Add((byte)0);
                    target.Write(header.ToArray(), 0, header.Count);

                    for (int row_idx = 0; row_idx < table.Rows.Count; row_idx++)
                    { // for each row generate the binary data.
                        // write the 16-bit integer count of the number of fields
                        byte[] field_count_data = BitConverter.GetBytes((short)table.Columns.Count);
                        this.ReverseEndianness(target, field_count_data);
                        //target.Write(field_count_data, 0, field_count_data.Length);

                        for (int column_idx = 0; column_idx < table.Columns.Count; column_idx++)
                        {
                            // serialize the data.
                            byte[] field_data = null;
                            object value      = table.Rows[row_idx][column_idx];
                            bool   reverse    = false;
                            if (value == null || value == DBNull.Value)
                            {
                                // do nothing: just leave the field_data null.
                            }
                            else if (value is long)
                            { // convert the long data into bytes postgres can understand.
                                field_data = BitConverter.GetBytes((long)value);
                                reverse    = true;
                            }
                            else if (value is int)
                            { // convert the int data into bytes postgres can understand.
                                field_data = BitConverter.GetBytes((int)value);
                                reverse    = true;
                            }
                            else if (value is double)
                            { // convert the double data into bytes postgres can understand.
                                field_data = BitConverter.GetBytes((double)value);
                                reverse    = true;
                            }
                            else if (value is float)
                            { // convert the float data into bytes postgres can understand.
                                field_data = BitConverter.GetBytes((float)value);
                                reverse    = true;
                            }
                            else if (value is decimal)
                            { // convert the decimal data into bytes postgres can understand.
                                field_data = BitConverter.GetBytes((double)value);
                                reverse    = true;
                            }
                            else if (value is DateTime)
                            { // convert the string data into bytes postgres can understand.
                                long microseconds = (long)((DateTime)value - (new DateTime(2000, 01, 01))).TotalSeconds
                                                    * 1000000;
                                //field_data = System.Text.Encoding.ASCII.GetBytes(((DateTime)value).ToString(
                                //    System.Globalization.CultureInfo.InvariantCulture));
                                field_data = BitConverter.GetBytes(microseconds);
                                reverse    = true;
                            }
                            else if (value is string)
                            { // convert the string data into bytes postgres can understand.
                                field_data = System.Text.Encoding.ASCII.GetBytes(value as string);
                            }
                            else if (value is bool)
                            { // convert the bool data into bytes postgres can understand.
                                field_data = new byte[1];
                                if ((bool)value)
                                {
                                    field_data[0] = (byte)1;
                                }
                                else
                                {
                                    field_data[0] = (byte)0;
                                }
                            }
                            else
                            { // the type of the value is unsupported!
                                throw new InvalidDataException(string.Format("Data type not supported: {0}!",
                                                                             value.GetType()));
                            }

                            // write the length of the field.
                            int length = -1; // represents NULL.
                            if (field_data != null)
                            {                // the lenght is non-zero.
                                length = field_data.Length;
                            }
                            byte[] length_data = BitConverter.GetBytes(length);
                            this.ReverseEndianness(target, length_data);

                            // write the data.
                            if (field_data != null)
                            {
                                if (reverse)
                                { // write the data in reverse.
                                    this.ReverseEndianness(target, field_data);
                                }
                                else
                                { // write the data in order.
                                    target.Write(field_data, 0, field_data.Length);
                                }
                            }
                        }

                        if (row_idx % 100 == 0)
                        { // flush the data once in a while.
                            target.Flush();
                        }
                    }

                    // write the file trailer: a 16-bit integer word containing -1
                    byte[] trailer = BitConverter.GetBytes((short)-1);
                    target.Write(trailer, 0, trailer.Length);

                    // flush the stream data and close.
                    target.Flush();
                    target.Close();
                }
                catch (Exception ex)
                {
                    cin.Cancel(ex.Message);
                }
                finally
                {
                    cin.End();
                }

                OsmSharp.Logging.Log.TraceEvent("OsmSharp.Data.PostgreSQL.Osm.Streams.PostgeSQLOsmStreamTarget", OsmSharp.Logging.TraceEventType.Information,
                                                "Inserted {0} records into {1}!", table.Rows.Count, table_name);
            }
        }