private void SubscribeIcecast(CancellationToken cancellation, WebCastData info, IConnectableObservable <byte[]> observable) { Stream icecastStream = null; IObservable <byte[]> audioStream = info.Mime != "audio/mpeg" ? observable.Transcode(new PcmStream(info.Mime), Mp3Stream.Default) : observable; audioStream .SubscribeOn(TaskPoolScheduler.Default) .Subscribe(next => { try { if (icecastStream == null) { icecastStream = _iceCaster.StartStreaming(_ekklesiaConfiguration.IceCastServer, _ekklesiaConfiguration.IceCastPassword, info.MountPoint, "audio/mpeg", false, "Test", "Test stream", "http://0.0.0.0", "Undefined"); } icecastStream.Write(next, 0, next.Length); } catch (Exception e) { _logger.Warning(e, "Error streaming"); try { icecastStream?.Flush(); icecastStream?.Dispose(); icecastStream = null; } catch (Exception exception) { _logger.Warning(exception, "Error cleaning up"); } } }, error => { icecastStream?.Flush(); icecastStream?.Dispose(); }, () => { icecastStream?.Flush(); icecastStream?.Dispose(); }, cancellation); }
private void Rec_OnRecordingComplete(object sender, RecordingCompleteEventArgs e) { Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal, (Action)(() => { string filePath = e.FilePath; if (RecordToStream) { filePath = ((FileStream)_outputStream)?.Name; _outputStream?.Flush(); _outputStream?.Dispose(); } OutputResultTextBlock.Text = filePath; PauseButton.Visibility = Visibility.Hidden; RecordButton.Content = "Record"; this.StatusTextBlock.Text = "Completed"; _progressTimer?.Stop(); _progressTimer = null; _secondsElapsed = 0; IsRecording = false; ((Recorder)sender).OnRecordingComplete -= Rec_OnRecordingComplete; ((Recorder)sender).OnRecordingFailed -= Rec_OnRecordingFailed; ((Recorder)sender).OnStatusChanged -= _rec_OnStatusChanged; _rec?.Dispose(); _rec = null; })); }
public void Dispose() { _stream?.Flush(); _stream?.Dispose(); GC.SuppressFinalize(this); }
public override void Flush() { lock (this) { BaseStream?.Flush(); Send(); } }
public void Disconnect() { RecieverThread?.Abort(); Stream?.Flush(); Stream?.Close(); Client?.Close(); }
private async Task <OperationResult <MediaModel> > UploadPhoto() { Stream stream = null; try { var compression = 1f; var maxCompression = 0.1f; int maxFileSize = _photoSize * 1024; var byteArray = ImageAsset.AsJPEG(compression); while (byteArray.Count() > maxFileSize && compression > maxCompression) { compression -= 0.1f; byteArray = ImageAsset.AsJPEG(compression); } stream = byteArray.AsStream(); var request = new UploadMediaModel(BasePresenter.User.UserInfo, stream, ImageExtension); return(await _presenter.TryUploadMedia(request)); } catch (Exception ex) { AppSettings.Reporter.SendCrash(ex); return(new OperationResult <MediaModel>(new AppError(LocalizationKeys.PhotoProcessingError))); } finally { stream?.Flush(); stream?.Dispose(); } }
public override void Flush() { try { _base?.Flush(); } catch { /* squelch */ } }
public void CloseStream(Stream stream) { if (stream?.CanWrite ?? false) { stream?.Flush(); } stream?.Close(); }
/// <inheritdoc /> public void Dispose() { _logWriter?.Flush(); _logWriter?.Dispose(); _stream?.Flush(); _stream?.Dispose(); }
public new void Dispose() { _ioStream?.Flush(); _ioStream?.Close(); _ioStream?.Dispose(); _ioStream = null; base.Dispose(); }
public void connect() { try { if (connected) { throw new SocketIoClientException("already connected"); } socket = createSocket(); stream = socket.GetStream(); input = new StreamReader(stream); byte[] bytes = handshake.getHandshake(); stream.Write(bytes, 0, bytes.Length); stream.Flush(); bool handshakeComplete = false; List<string> handshakeLines = new List<string>(); string line; while(!handshakeComplete) { line = input.ReadLine().Trim(); if (line.Length>0) { handshakeLines.Add(line); } else { handshakeComplete = true; } } char[] response = new char[16]; input.ReadBlock(response, 0, response.Length); handshake.verifyServerStatusLine(handshakeLines[0]); /* Verifying handshake fails... */ //handshake.verifyServerResponse(response); handshakeLines.RemoveAt(0); Dictionary<string, string> headers = new Dictionary<string, string>(); foreach (string l in handshakeLines) { string[] keyValue = l.Split(new char[] {':'},2); headers.Add(keyValue[0].Trim(), keyValue[1].Trim()); } handshake.verifyServerHandshakeHeaders(headers); receiver = new SocketIoClientReceiver(this); connected = true; eventHandler.OnOpen(); (new Thread(receiver.run)).Start(); } catch (SocketIoClientException wse) { throw wse; } catch (IOException ioe) { throw new SocketIoClientException("error while connecting: " + ioe.StackTrace, ioe); } }
public void Dispose() { archive.Dispose(); positionStream.Dispose(); if (leaveOpen) { return; } stream?.Flush(); stream?.Dispose(); }
private void CleanupResources() { _outputStream?.Flush(); _outputStream?.Dispose(); _outputStream = null; _progressTimer?.Stop(); _progressTimer = null; _secondsElapsed = 0; _rec?.Dispose(); _rec = null; }
/// <summary> /// closes the ar file. /// </summary> public void Close() { topStream?.Flush(); #if NETSTANDARD13 topStream?.Dispose(); bottomStream?.Dispose(); #else topStream?.Close(); bottomStream?.Close(); #endif topStream = null; bottomStream = null; }
void LogEntryWrite(LogEntry entry) { try { lock (logStream) { logStream?.Write(entry); logStream?.Flush(); } } catch (Exception e) { logEntryWriteException = e; } }
public void Dispose() { _writer?.WriteEndObject(); _writer?.Flush(); _streamWriter?.Flush(); _streamWriter?.Dispose(); _gZipStream?.Dispose(); if (_leaveOpen == false) { _stream?.Flush(); _stream?.Dispose(); } }
public override void Flush() { if (!AcquireReadMutex()) { return; } try { _inStream?.Flush(); } finally { ReleaseReadMutex(); } }
public override void Flush() { if (!AcquireWriteMutex()) { return; } try { _outStream?.Flush(); } finally { ReleaseWriteMutex(); } }
private async Task <OperationResult <MediaModel> > UploadPhoto(UIImage photo, NSDictionary metadata) { Stream stream = null; try { var compression = 1f; var maxCompression = 0.1f; int maxFileSize = _photoSize * 1024; var byteArray = photo.AsJPEG(compression); while (byteArray.Count() > maxFileSize && compression > maxCompression) { compression -= 0.1f; byteArray = photo.AsJPEG(compression); } if (metadata != null) { //exif setup var editedExifData = RemakeMetadata(metadata, photo); var newImageDataWithExif = new NSMutableData(); var imageDestination = CGImageDestination.Create(newImageDataWithExif, "public.jpeg", 0); imageDestination.AddImage(new UIImage(byteArray).CGImage, editedExifData); imageDestination.Close(); stream = newImageDataWithExif.AsStream(); } else { stream = byteArray.AsStream(); } var request = new UploadMediaModel(AppSettings.User.UserInfo, stream, ImageExtension); return(await _presenter.TryUploadMedia(request)); } catch (Exception ex) { AppSettings.Reporter.SendCrash(ex); return(new OperationResult <MediaModel>(new AppError(LocalizationKeys.PhotoProcessingError))); } finally { stream?.Flush(); stream?.Dispose(); } }
public void Merge(Stream outputStream) { if (outputStream == null || !outputStream.CanWrite) throw new Exception("OutputStream is null or is read only!"); Document newDocument = null; try { newDocument = new Document(); PdfWriter pdfWriter = PdfWriter.GetInstance(newDocument, outputStream); newDocument.Open(); PdfContentByte pdfContentByte = pdfWriter.DirectContent; if (EnablePagination) documents.ForEach(delegate(PdfReader doc) { totalPages += doc.NumberOfPages; }); int currentPage = 1; foreach (PdfReader pdfReader in documents) { for (int page = 1; page <= pdfReader.NumberOfPages; page++) { newDocument.NewPage(); PdfImportedPage importedPage = pdfWriter.GetImportedPage(pdfReader, page); pdfContentByte.AddTemplate(importedPage, 0, 0); if (EnablePagination) { pdfContentByte.BeginText(); pdfContentByte.SetFontAndSize(baseFont, 9); pdfContentByte.ShowTextAligned(PdfContentByte.ALIGN_CENTER, string.Format("{0} od {1}", currentPage++, totalPages), 520, 5, 0); pdfContentByte.EndText(); } } } } finally { outputStream.Flush(); if (newDocument != null) newDocument.Close(); outputStream.Close(); } }
public void Dispose(bool failed) { Dialog.ButtonLabel = "关闭"; Stream?.Flush(); Stream?.Dispose(); if (failed) { if (System.IO.File.Exists(LocalPath)) { try { System.IO.File.Delete(LocalPath); } catch { } } } }
private void Close() { if (IsReady) { SendCloseFrame(); } IsReady = false; stream?.Flush(); stream = null; EndPoint endPoint = client?.Client?.RemoteEndPoint; OnWillClose?.Invoke(client, this); client?.Close(); OnDidClose?.Invoke(endPoint, this); client = null; }
private async Task <OperationResult <MediaModel> > UploadPhoto() { Stream stream = null; try { stream = ImageAsset.AsJpegStream(); var request = new UploadMediaModel(BasePresenter.User.UserInfo, stream, ImageExtension); return(await _presenter.TryUploadMedia(request)); } catch (Exception ex) { AppSettings.Reporter.SendCrash(ex); return(new OperationResult <MediaModel>(new ApplicationError(Localization.Errors.PhotoProcessingError))); } finally { stream?.Flush(); stream?.Dispose(); } }
public void Write( byte[] buffer, int count) { _target?.Write(buffer, 0, count); if (_target is FileStream fs) { // force disk flush to better reflect // progress, esp across network shares // also caching here in the case of // device-to-device where the user is // likely to want to to remove the target // simply means having to wait for sync // at target dismount / eject fs.Flush(true); } else { _target?.Flush(); } }
public static Bitmap SaveImage(this string imageUrl) { var client = new WebClient(); Stream stream = null; Bitmap bitmap = null; try { stream = client.OpenRead(imageUrl); bitmap = new Bitmap(stream); } catch { bitmap = null; } finally { stream?.Flush(); stream?.Close(); client?.Dispose(); } return(bitmap); }
public static void WriteData(Stream s) { BinaryWriter bw; int offset = 10; byte[] bytes = new byte[256 + offset]; for (int i=0;i<256;i++) bytes[i+offset] = (byte)i; // Test reading & writing at an offset into the user array... s.Write(bytes,offset,bytes.Length-offset); // Test WriteByte methods. s.WriteByte(0); s.WriteByte(65); s.WriteByte(255); s.Flush( ); bw = new BinaryWriter(s); for(int i=0;i<1000;i++) bw.Write(i); bw.Write(false); bw.Write(true); for(char ch='A';ch<='Z';ch++) bw.Write(ch); for(short i=-32000;i<=32000;i+=1000) bw.Write(i); for(int i=-2000000000;i<=2000000000;i+=100000000) bw.Write(i); bw.Write(0x0123456789ABCDE7L); bw.Write(0x7EDCBA9876543210L); bw.Write("Hello world"); bw.Write(Math.PI); bw.Write((float)(-2.0*Math.PI)); bw.Flush( ); }
/* Get the Size of a File */ public string getFileSize(string fileName) { string _result = null; string _fileInfo = null; try { /* Create an FTP Request */ ftpRequest = (FtpWebRequest)FtpWebRequest.Create(host + "/" + fileName); /* Log in to the FTP Server with the User Name and Password Provided */ ftpRequest.Credentials = new NetworkCredential(user, pass); /* When in doubt, use these options */ ftpRequest.UseBinary = true; ftpRequest.UsePassive = true; ftpRequest.KeepAlive = true; /* Specify the Type of FTP Request */ ftpRequest.Method = WebRequestMethods.Ftp.GetFileSize; /* Establish Return Communication with the FTP Server */ ftpResponse = (FtpWebResponse)ftpRequest.GetResponse(); /* Establish Return Communication with the FTP Server */ ftpStream = ftpResponse.GetResponseStream(); /* Get the FTP Server's Response Stream */ StreamReader _ftpReader = new StreamReader(ftpStream); /* Store the Raw Response */ /* Read the Full Response Stream */ while (_ftpReader.Peek() != -1) { _fileInfo = _ftpReader.ReadToEnd(); } _ftpReader.Close(); /* Return File Size */ _result = _fileInfo; } catch (Exception ex) { //Console.WriteLine(ex.ToString()); _result = ex.Message.ToString(); } finally { /* Resource Cleanup */ ftpStream.Flush(); ftpStream.Close(); ftpResponse.Close(); ftpRequest = null; } return _result; }
static void SendData(Stream netStream, Stream bufStream) { DateTime startTime; double networkTime, bufferedTime; // Create random data to send to the server. byte[] dataToSend = new byte[dataArraySize]; new Random().NextBytes(dataToSend); // Send the data using the NetworkStream. Console.WriteLine("Sending data using NetworkStream."); startTime = DateTime.Now; for (int i = 0; i < numberOfLoops; i++) { netStream.Write(dataToSend, 0, dataToSend.Length); } networkTime = (DateTime.Now - startTime).TotalMilliseconds; Console.WriteLine("{0} bytes sent in {1} milliseconds.\n", numberOfLoops * dataToSend.Length, networkTime.ToString("F1")); // Send the data using the BufferedStream. Console.WriteLine("Sending data using BufferedStream."); startTime = DateTime.Now; for (int i = 0; i < numberOfLoops; i++) { bufStream.Write(dataToSend, 0, dataToSend.Length); } bufStream.Flush(); bufferedTime = (DateTime.Now - startTime).TotalMilliseconds; Console.WriteLine("{0} bytes sent in {1} milliseconds.\n", numberOfLoops * dataToSend.Length, bufferedTime.ToString("F1")); // Print the ratio of write times. Console.WriteLine("Sending data using the buffered " + "network stream was {0} {1} than using the network " + "stream alone.\n", (networkTime / bufferedTime).ToString("P0"), bufferedTime < networkTime ? "faster" : "slower"); }
public override void Flush() { _stream?.Flush(); }
public override void Flush() { _outStream?.Flush(); }
// Worker thread private void WorkerThread() { _abort = new ManualResetEvent(false); // buffer to read stream var buffer = new byte[BufferSize]; // HTTP web request HttpWebRequest request = null; // web responce WebResponse response = null; // stream for JPEG downloading Stream stream = null; // random generator to add fake parameter for cache preventing var rand = new Random((int)DateTime.UtcNow.Ticks); // download start time and duration var err = 0; var connectionFactory = new ConnectionFactory(); while (!_abort.WaitOne(10) && !MainForm.ShuttingDown) { var total = 0; if (ShouldEmitFrame) { try { // set download start time var start = DateTime.UtcNow; var vss = Tokenise(_source.settings.videosourcestring); var url = vss + (vss.IndexOf('?') == -1 ? '?' : '&') + "fake=" + rand.Next(); response = connectionFactory.GetResponse(url, _cookies, _headers, _httpUserAgent, _login, _password, "GET", "", "", _useHttp10, out request); // get response stream if (response == null) { throw new Exception("Connection failed"); } stream = response.GetResponseStream(); stream.ReadTimeout = _requestTimeout; bool frameComplete = false; // loop while (!_abort.WaitOne(0)) { // check total read if (total > BufferSize - ReadSize) { total = 0; } // read next portion from stream int read; if ((read = stream.Read(buffer, total, ReadSize)) == 0) { frameComplete = true; break; } total += read; } // provide new image to clients if (frameComplete && NewFrame != null) { using (var ms = new MemoryStream(buffer, 0, total)) { using (var bitmap = (Bitmap)Image.FromStream(ms)) { NewFrame(this, new NewFrameEventArgs(bitmap)); } } } err = 0; } catch (ThreadAbortException) { break; } catch (Exception ex) { Logger.LogException(ex, "JPEG"); err++; if (err > 3) { _res = ReasonToFinishPlaying.DeviceLost; break; } _abort.WaitOne(250); } finally { request?.Abort(); stream?.Flush(); stream?.Close(); response?.Close(); } } } PlayingFinished?.Invoke(this, new PlayingFinishedEventArgs(_res)); _abort.Close(); }
/// <summary> /// CopyStream utility that is guaranteed to return the number of bytes copied (may be less then requested, /// if source stream doesn't have enough data) /// </summary> /// <param name="sourceStream">stream to read from</param> /// <param name="targetStream">stream to write to </param> /// <param name="bytesToCopy">number of bytes to be copied(use Int64.MaxValue if the whole stream needs to be copied)</param> /// <param name="bufferSize">number of bytes to be copied (usually it is 4K for scenarios where we expect a lot of data /// like in SparseMemoryStream case it could be larger </param> /// <returns>bytes copied (might be less than requested if source stream is too short</returns> /// <remarks>Neither source nor target stream are seeked; it is up to the caller to make sure that their positions are properly set. /// Target stream isn't truncated even if it has more data past the area that was copied.</remarks> internal static long CopyStream(Stream sourceStream, Stream targetStream, long bytesToCopy, int bufferSize) { Debug.Assert(sourceStream != null); Debug.Assert(targetStream != null); Debug.Assert(bytesToCopy >= 0); Debug.Assert(bufferSize > 0); byte[] buffer = new byte[bufferSize]; // let's read the whole block into our buffer long bytesLeftToCopy = bytesToCopy; while (bytesLeftToCopy > 0) { int bytesRead = sourceStream.Read(buffer, 0, (int)Math.Min(bytesLeftToCopy, (long)bufferSize)); if (bytesRead == 0) { targetStream.Flush(); return bytesToCopy - bytesLeftToCopy; } targetStream.Write(buffer, 0, bytesRead); bytesLeftToCopy -= bytesRead; } // It must not be negative Debug.Assert(bytesLeftToCopy == 0); targetStream.Flush(); return bytesToCopy; }
/// <summary> /// Decode a bytestream that was encoded by WCF's BinaryEncodingBindingElement. Will throw if the bytestream does /// not decode properly or the result is not valid XML. I/O streams are flushed but not closed. /// </summary> /// <param name="explodeNewlines">if true, the returned string will be nicely indented according to /// element depth, and each attribute will be placed on its own line</param> /// <returns></returns> public void DecodeBinaryXML(Stream binaryInput, Stream xmlOutput, bool? explodeNewlines) { // defaults var explode = explodeNewlines ?? false; // parse bytestream into the XML DOM var doc = new XmlDocument(); using (var binaryReader = XmlDictionaryReader.CreateBinaryReader(binaryInput, WcfDictionaryBuilder.Dict, XmlDictionaryReaderQuotas.Max)) { doc.Load(binaryReader); } // write document to the output stream with customized settings var settings = new XmlWriterSettings() { CheckCharacters = false, CloseOutput = false, ConformanceLevel = ConformanceLevel.Auto, Encoding = m_encoding, Indent = explode, IndentChars = "\t", NewLineChars = Environment.NewLine, NewLineHandling = explode ? NewLineHandling.Replace : NewLineHandling.None, NewLineOnAttributes = explode // QuoteChar = '"' }; using (var writer = XmlWriter.Create(xmlOutput, settings)) { doc.Save(writer); writer.Flush(); xmlOutput.Flush(); } }
private static void NegativeConsoleOutputTests(Stream stream) { //ConsoleStream.Length should throw NotSupportedException Assert.Throws<NotSupportedException>(() => { long x = stream.Length; }); //ConsoleStream.get_Position should throw NotSupportedException Assert.Throws<NotSupportedException>(() => { long x = stream.Position; }); //ConsoleStream.set_Position should throw NotSupportedException Assert.Throws<NotSupportedException>(() => stream.Position = 50L); //ConsoleStream.SetLength should throw NotSupportedException Assert.Throws<NotSupportedException>(() => stream.SetLength(50L)); // Flushing a stream is fine. stream.Flush(); //Read and write methods //ConsoleStream.Read(null) should throw ArgumentNullException Assert.Throws<ArgumentNullException>(() => stream.Read(null, 0, 1)); //ConsoleStream.Read() should throw ArgumentOutOfRangeException Assert.Throws<ArgumentOutOfRangeException>(() => stream.Read(new byte[] { 0, 1 }, -1, 0)); //ConsoleStream.Read() should throw ArgumentOutOfRangeException Assert.Throws<ArgumentOutOfRangeException>(() => stream.Read(new byte[] { 0, 1 }, 0, -1)); //ConsoleStream.Read() should throw ArgumentException Assert.Throws<ArgumentException>(() => stream.Read(new byte[] { 0, 1 }, 0, 50)); //ConsoleStream.Read() should throw NotSupportedException Assert.Throws<NotSupportedException>(() => stream.Read(new byte[] { 0, 1 }, 0, 2)); //ConsoleStream.Write() should throw ArgumentNullException Assert.Throws<ArgumentNullException>(() => stream.Write(null, 0, 1)); //ConsoleStream.Write() should throw ArgumentOutOfRangeException Assert.Throws<ArgumentOutOfRangeException>(() => stream.Write(new byte[] { 0, 1 }, -1, 0)); //ConsoleStream.Write() should throw ArgumentOutOfRangeException Assert.Throws<ArgumentOutOfRangeException>(() => stream.Write(new byte[] { 0, 1 }, 0, -1)); //ConsoleStream.Write() should throw ArgumentException Assert.Throws<ArgumentException>(() => stream.Write(new byte[] { 0, 1 }, 0, 50)); //ConsoleStream.Write() should throw NotSupportedException Assert.Throws<NotSupportedException>(() => stream.Seek(0L, SeekOrigin.Begin)); // Close the stream and make sure we can no longer read, write or flush stream.Dispose(); //ConsoleStream.Read() should throw NotSupportedException Assert.Throws<NotSupportedException>(() => stream.Read(new byte[] { 0, 1 }, 0, 1)); //ConsoleStream.Write() should throw NotSupportedException Assert.Throws<NotSupportedException>(() => stream.Write(new byte[] { 0, 1 }, 0, 1)); //ConsoleStream.Flush() should throw NotSupportedException Assert.Throws<ObjectDisposedException>(() => stream.Flush()); }
/// <summary> /// Always use UTF-8 for encoding, else you will screw it up. /// </summary> /// <param name="s"></param> /// <param name="xmlData"></param> /// <param name="transform"></param> /// <param name="args"></param> private void WriteTransformedXmlDataToStream(Stream s, string xmlData, XslCompiledTransform transform, XsltArgumentList args) { XPathDocument data = new XPathDocument(new MemoryStream(Encoding.UTF8.GetBytes(xmlData))); transform.Transform(data, args, s); s.Flush(); data = null; }
protected void Page_Load(object sender, EventArgs e) { byte[] byteData = null; try { if (context == null) { context = ContextUtil.getInstance(Server.MapPath(".")); encrypt = context.getOuterEncrypt(); } if (encoder == null) encoder = ParamEncoder.getInstance(); if (decoder == null) decoder = ParamDecoder.getInstance(); encoder.outEncoder = context.getOuterResolve(); decoder.outDecoder = context.getOuterResolve(); Stream input = Request.InputStream; if (input.CanRead) { byteData = new byte[input.Length]; input.Read(byteData, 0, (int)input.Length); input.Close(); input.Dispose(); // 解密 if (encrypt != null) byteData = encrypt.decrypt(byteData); dataVo = decoder.decoder(byteData); Type serviceCls = context.getService(context.getServiceNameSpace() + "." + dataVo.ServiceName); MethodInfo method = serviceCls.GetMethod(dataVo.MethodName); object result = method.Invoke(System.Activator.CreateInstance(serviceCls), dataVo.Param); dataVo.Result = result; dataVo.ResultStatus = "success"; byte[] resultData = encoder.encode(dataVo); if (encrypt != null) resultData = encrypt.encrypt(resultData); output = Response.OutputStream; output.Write(resultData, 0, resultData.Length); output.Flush(); output.Close(); output.Dispose(); } else { } } catch(Exception exc) { if (dataVo == null && byteData != null) dataVo = decoder.decoder(byteData); if (dataVo == null) dataVo = new DataVO(); dataVo.ResultStatus = "error"; dataVo.ErrorMessage = exc.ToString(); byte[] resultData = encoder.encode(dataVo); if (encrypt != null) resultData = encrypt.encrypt(resultData); output = Response.OutputStream; output.Write(resultData, 0, resultData.Length); output.Flush(); output.Close(); output.Dispose(); } }
public override void Flush() => _currentStream?.Flush();
/* Upload File */ public string upload(string remoteFile, string localFile) { string _result = null; try { /* Create an FTP Request */ ftpRequest = (FtpWebRequest)FtpWebRequest.Create("ftp://" + host + "/" + remoteFile); /* Log in to the FTP Server with the User Name and Password Provided */ ftpRequest.Credentials = new NetworkCredential(user, pass); /* When in doubt, use these options */ ftpRequest.UseBinary = true; ftpRequest.UsePassive = true; ftpRequest.KeepAlive = true; /* Specify the Type of FTP Request */ ftpRequest.Method = WebRequestMethods.Ftp.UploadFile; /* Establish Return Communication with the FTP Server */ ftpStream = ftpRequest.GetRequestStream(); /* Open a File Stream to Read the File for Upload */ /* use openorcreate as just open will overwrite the file if it already exists */ FileStream _localFileStream = new FileStream(localFile, FileMode.OpenOrCreate); /* Buffer for the Downloaded Data */ byte[] _byteBuffer = new byte[bufferSize]; int _bytesSent = _localFileStream.Read(_byteBuffer, 0, bufferSize); /* Upload the File by Sending the Buffered Data Until the Transfer is Complete */ //try //{ while (_bytesSent != 0) { ftpStream.Write(_byteBuffer, 0, _bytesSent); _bytesSent = _localFileStream.Read(_byteBuffer, 0, bufferSize); } //} //catch (Exception ex) { Console.WriteLine(ex.ToString()); } _localFileStream.Close(); } catch (Exception ex) { //Console.WriteLine(ex.ToString()); _result = ex.Message.ToString(); } finally { /* Resource Cleanup */ ftpStream.Flush(); ftpStream.Close(); ftpRequest = null; } return _result; }
/// <summary> /// Copy the contents of a stored file into an opened stream /// </summary> /// <param name="_zfe">Entry information of file to extract</param> /// <param name="_stream">Stream to store the uncompressed data</param> /// <returns>True if success, false if not.</returns> /// <remarks>Unique compression methods are Store and Deflate</remarks> public bool ExtractFile(ZipFileEntry _zfe, Stream _stream) { if (!_stream.CanWrite) throw new InvalidOperationException("Stream cannot be written"); // check signature byte[] signature = new byte[4]; this.ZipFileStream.Seek(_zfe.HeaderOffset, SeekOrigin.Begin); this.ZipFileStream.Read(signature, 0, 4); if (BitConverter.ToUInt32(signature, 0) != 0x04034b50) return false; // Select input stream for inflating or just reading Stream inStream; if (_zfe.Method == Compression.Store) inStream = this.ZipFileStream; else if (_zfe.Method == Compression.Deflate) inStream = new DeflateStream(this.ZipFileStream, CompressionMode.Decompress, true); else return false; // Buffered copy byte[] buffer = new byte[16384]; this.ZipFileStream.Seek(_zfe.FileOffset, SeekOrigin.Begin); uint bytesPending = _zfe.FileSize; while (bytesPending > 0) { int bytesRead = inStream.Read(buffer, 0, (int)Math.Min(bytesPending, buffer.Length)); _stream.Write(buffer, 0, bytesRead); bytesPending -= (uint)bytesRead; } _stream.Flush(); if (_zfe.Method == Compression.Deflate) inStream.Dispose(); return true; }
static IEnumerator MakeGifRoutine(List<RenderTexture> textures, float frameLength, Stream output, bool closeWhenDone) { var gifEncoder = new Gif.Components.AnimatedGifEncoder(); gifEncoder.SetQuality(10); gifEncoder.SetRepeat(0); gifEncoder.SetDelay((int)(frameLength * 1000)); gifEncoder.Start(output); int w = textures[0].width; int h = textures[0].height; var tex = new Texture2D(w,h, TextureFormat.ARGB32, false, true); var imageStart = new ManualResetEvent(false); Gif.Components.Image image = null; bool done = false; bool processed = false; var worker = new Thread(() => { while (!done) { imageStart.WaitOne(); imageStart.Reset(); gifEncoder.AddFrame(image); processed = true; } }); worker.Start(); for (int picCount = 0; picCount < textures.Count; picCount++) { var tempTex = textures[picCount]; RenderTexture.active = tempTex; tex.ReadPixels(new Rect(0, 0, w, h), 0, 0); RenderTexture.ReleaseTemporary(tempTex); image = new Gif.Components.Image(tex); processed = false; imageStart.Set(); while (!processed) { yield return null; } } done = true; textures.Clear(); gifEncoder.Finish(); DestroyImmediate(tex); output.Flush(); if (closeWhenDone) { output.Close(); } }
// Worker thread private void WorkerThread() { // buffer to read stream var buffer = new byte[BufSize]; var encoding = new ASCIIEncoding(); var res = ReasonToFinishPlaying.StoppedByUser; while (!_stopEvent.WaitOne(0, false) && !MainForm.ShuttingDown) { // reset reload event _reloadEvent.Reset(); // HTTP web request HttpWebRequest request = null; // web responce WebResponse response = null; // stream for MJPEG downloading Stream stream = null; // boundary betweeen images (string and binary versions) try { // create request request = (HttpWebRequest)WebRequest.Create(_source); // set user agent if (_userAgent != null) { request.UserAgent = _userAgent; } // set proxy if (_proxy != null) { request.Proxy = _proxy; } if (_usehttp10) { request.ProtocolVersion = HttpVersion.Version10; } // set timeout value for the request request.Timeout = request.ServicePoint.ConnectionLeaseTimeout = request.ServicePoint.MaxIdleTime = _requestTimeout; request.AllowAutoRedirect = true; // set login and password if ((_login != null) && (_password != null) && (_login != string.Empty)) { request.Credentials = new NetworkCredential(_login, _password); } // set connection group name if (_useSeparateConnectionGroup) { request.ConnectionGroupName = GetHashCode().ToString(); } // get response response = request.GetResponse(); // get response stream stream = response.GetResponseStream(); stream.ReadTimeout = _requestTimeout; byte[] boundary = encoding.GetBytes("--myboundary"); byte[] sep = encoding.GetBytes("\r\n\r\n"); // loop int startPacket = -1; int endPacket = -1; int ttl = 0; bool hasaudio = false; while ((!_stopEvent.WaitOne(0, false)) && (!_reloadEvent.WaitOne(0, false))) { int read; if ((read = stream.Read(buffer, ttl, ReadSize)) == 0) { throw new ApplicationException(); } ttl += read; if (startPacket == -1) { startPacket = ByteArrayUtils.Find(buffer, boundary, 0, ttl); } else { if (endPacket == -1) { endPacket = ByteArrayUtils.Find(buffer, boundary, startPacket + boundary.Length, ttl - (startPacket + boundary.Length)); } } var nf = NewFrame; if (startPacket > -1 && endPacket > startPacket) { int br = ByteArrayUtils.Find(buffer, sep, startPacket, 100); if (br != -1) { var arr = new byte[br]; System.Array.Copy(buffer, startPacket, arr, 0, br - startPacket); string s = Encoding.ASCII.GetString(arr); int k = s.IndexOf("Content-type: ", StringComparison.Ordinal); if (k != -1) { s = s.Substring(k + 14); s = s.Substring(0, s.IndexOf("\r\n", StringComparison.Ordinal)); s = s.Trim(); } switch (s) { case "image/jpeg": try { using (var ms = new MemoryStream(buffer, br + 4, endPacket - br - 8)) { using (var bmp = (Bitmap)Image.FromStream(ms)) { var dae = new NewFrameEventArgs(bmp); nf.Invoke(this, dae); } } } catch (Exception ex) { //sometimes corrupted packets come through... Logger.LogExceptionToFile(ex, "KinectNetwork"); } break; case "audio/raw": if (!hasaudio) { hasaudio = true; //fixed 16khz 1 channel format RecordingFormat = new WaveFormat(16000, 16, 1); _waveProvider = new BufferedWaveProvider(RecordingFormat) { DiscardOnBufferOverflow = true, BufferDuration = TimeSpan.FromMilliseconds(500) }; _sampleChannel = new SampleChannel(_waveProvider); _sampleChannel.PreVolumeMeter += SampleChannelPreVolumeMeter; if (HasAudioStream != null) { HasAudioStream(this, EventArgs.Empty); HasAudioStream = null; } } var da = DataAvailable; if (da != null) { int l = endPacket - br - 8; var data = new byte[l]; int d; using (var ms = new MemoryStream(buffer, br + 4, l)) { d = ms.Read(data, 0, l); } if (d > 0) { _waveProvider.AddSamples(data, 0, data.Length); if (Listening) { WaveOutProvider.AddSamples(data, 0, data.Length); } //forces processing of volume level without piping it out var sampleBuffer = new float[data.Length]; int r = _sampleChannel.Read(sampleBuffer, 0, data.Length); da(this, new DataAvailableEventArgs((byte[])data.Clone(), r)); } } break; case "alert/text": // code to handle alert notifications goes here if (AlertHandler != null) { int dl = endPacket - br - 8; var data2 = new byte[dl]; using (var ms = new MemoryStream(buffer, br + 4, dl)) { ms.Read(data2, 0, dl); } string alerttype = Encoding.ASCII.GetString(data2); AlertHandler(this, new AlertEventArgs(alerttype)); } break; } } ttl -= endPacket; System.Array.Copy(buffer, endPacket, buffer, 0, ttl); startPacket = -1; endPacket = -1; } } } catch (ApplicationException) { // do nothing for Application Exception, which we raised on our own // wait for a while before the next try Thread.Sleep(250); } catch (ThreadAbortException) { break; } catch (Exception ex) { // provide information to clients Logger.LogExceptionToFile(ex, "KinectNetwork"); res = ReasonToFinishPlaying.DeviceLost; break; // wait for a while before the next try //Thread.Sleep(250); } finally { request?.Abort(); stream?.Flush(); stream?.Close(); response?.Close(); } // need to stop ? if (_stopEvent.WaitOne(0, false)) { break; } } PlayingFinished?.Invoke(this, new PlayingFinishedEventArgs(res)); }
/* List Directory Contents in Detail (Name, Size, Created, etc.) */ public List<string> directoryListDetailed(string directory) { List<string> _directoryList = null; string _chr = "|"; try { /* Create an FTP Request */ ftpRequest = (FtpWebRequest)FtpWebRequest.Create(host + "/" + directory); /* Log in to the FTP Server with the User Name and Password Provided */ ftpRequest.Credentials = new NetworkCredential(user, pass); /* When in doubt, use these options */ ftpRequest.UseBinary = true; ftpRequest.UsePassive = true; ftpRequest.KeepAlive = true; /* Specify the Type of FTP Request */ ftpRequest.Method = WebRequestMethods.Ftp.ListDirectoryDetails; /* Establish Return Communication with the FTP Server */ ftpResponse = (FtpWebResponse)ftpRequest.GetResponse(); /* Establish Return Communication with the FTP Server */ ftpStream = ftpResponse.GetResponseStream(); /* Get the FTP Server's Response Stream */ StreamReader _ftpReader = new StreamReader(ftpStream); /* Store the Raw Response */ string _directoryRaw = null; /* Read Each Line of the Response and Append a Pipe to Each Line for Easy Parsing */ while (_ftpReader.Peek() != -1) { _directoryRaw += _ftpReader.ReadLine() + _chr; } _ftpReader.Close(); /* Return the Directory Listing as a string Array by Parsing 'directoryRaw' with the Delimiter you Append (I use | in This Example) */ _directoryList = _directoryRaw.Split(_chr.ToCharArray()).ToList(); } catch (Exception ex) { //Console.WriteLine(ex.ToString()); _directoryList.Add(ex.Message.ToString()); } finally { /* Resource Cleanup */ ftpStream.Flush(); ftpStream.Close(); ftpResponse.Close(); ftpRequest = null; } /* Return an Empty string Array if an Exception Occurs */ return _directoryList; }
/// <summary> /// Encode a text stream into a binary XML stream compatible with WCF's BinaryEncodingBindingElement. Will throw if /// the input stream cannot be parsed into an XML document. I/O streams are flushed but not closed. /// </summary> /// <param name="xmlInput"></param> /// <param name="binaryOutput"></param> public void EncodeBinaryXML(Stream xmlInput, Stream binaryOutput) { // parse string into the XML DOM var doc = new XmlDocument(); doc.Load(xmlInput); // write bytestream using (var binaryWriter = XmlDictionaryWriter.CreateBinaryWriter(binaryOutput, WcfDictionaryBuilder.Dict, null, false)) { doc.Save(binaryWriter); binaryWriter.Flush(); binaryOutput.Flush(); } }
private static void Decompress(Stream inputStream, Stream outputStream) { SevenZip.Compression.LZMA.Decoder coder = new SevenZip.Compression.LZMA.Decoder(); // Read decoder properties byte[] properties = new byte[5]; // 5 comes from kPropSize (LzmaEncoder.cs) inputStream.Read(properties, 0, 5); // Read the size of the output stream. byte [] fileLengthBytes = new byte[8]; inputStream.Read(fileLengthBytes, 0, 8); long fileLength = BitConverter.ToInt64(fileLengthBytes, 0); // Decode coder.SetDecoderProperties(properties); coder.Code(inputStream, outputStream, inputStream.Length, fileLength, null); outputStream.Flush(); outputStream.Close(); }
private static void Compress(Stream inputStream, Stream outputStream, LZMADictionarySize dictSize) { SevenZip.Compression.LZMA.Encoder coder = new SevenZip.Compression.LZMA.Encoder(); Int32 dictSize32 = (Int32)dictSize; coder.SetCoderProperties (new SevenZip.CoderPropID[] {SevenZip.CoderPropID.DictionarySize}, new object[] {dictSize32}); // Write encoder properties to output stream coder.WriteCoderProperties(outputStream); // Write size of input stream to output stream. outputStream.Write(BitConverter.GetBytes(inputStream.Length), 0, 8); // Encode coder.Code(inputStream, outputStream, inputStream.Length, -1, null); outputStream.Flush(); outputStream.Close(); }
private static void Compress(Stream inputStream, Stream outputStream) { SevenZip.Compression.LZMA.Encoder coder = new SevenZip.Compression.LZMA.Encoder(); // Write encoder properties to output stream coder.WriteCoderProperties(outputStream); // Write size of input stream to output stream. outputStream.Write(BitConverter.GetBytes(inputStream.Length), 0, 8); // Encode coder.Code(inputStream, outputStream, inputStream.Length, -1, null); outputStream.Flush(); outputStream.Close(); }
// Worker thread private void WorkerThread() { // buffer to read stream var buffer = new byte[BufSize]; // JPEG magic number var jpegMagic = new byte[] { 0xFF, 0xD8, 0xFF }; var encoding = new ASCIIEncoding(); while (!_abort.WaitOne(20) && !MainForm.ShuttingDown) { // HTTP web request HttpWebRequest request = null; // web response WebResponse response = null; // stream for MJPEG downloading Stream stream = null; // boundary between images (string and binary versions) string boudaryStr = null; // length of boundary // flag signaling if boundary was checked or not var boundaryIsChecked = false; // read amounts and positions int todo = 0, total = 0, pos = 0, align = 1; var start = 0; ConnectionFactory connectionFactory = new ConnectionFactory(); // align // 1 = searching for image start // 2 = searching for image end try { // create request // get response var vss = Tokenise(); response = connectionFactory.GetResponse(vss, _cookies, _headers, _httpUserAgent, _login, _password, "GET", "", "", _useHttp10, out request); if (response == null) { throw new Exception("Stream could not connect"); } // check content type var contentType = response.ContentType; var contentTypeArray = contentType.Split('/'); // "application/octet-stream" int boundaryLen; byte[] boundary; if ((contentTypeArray[0] == "application") && (contentTypeArray[1] == "octet-stream")) { boundaryLen = 0; boundary = new byte[0]; } else if ((contentTypeArray[0] == "multipart") && contentType.Contains("mixed")) { // get boundary var boundaryIndex = contentType.IndexOf("boundary", 0, StringComparison.Ordinal); if (boundaryIndex != -1) { boundaryIndex = contentType.IndexOf("=", boundaryIndex + 8, StringComparison.Ordinal); } if (boundaryIndex == -1) { // try same scenario as with octet-stream, i.e. without boundaries boundaryLen = 0; boundary = new byte[0]; } else { boudaryStr = contentType.Substring(boundaryIndex + 1); // remove spaces and double quotes, which may be added by some IP cameras boudaryStr = boudaryStr.Trim(' ', '"'); boundary = encoding.GetBytes(boudaryStr); boundaryLen = boundary.Length; boundaryIsChecked = false; } } else { throw new Exception("Invalid content type."); } // get response stream try { stream = response.GetResponseStream(); } catch (NullReferenceException) { throw new Exception("Connection failed"); } stream.ReadTimeout = _requestTimeout; // loop while (!_abort.WaitOne(0) && !MainForm.ShuttingDown) { // check total read if (total > BufSize - ReadSize) { total = pos = todo = 0; } // read next portion from stream int read; if ((read = stream.Read(buffer, total, ReadSize)) == 0) { throw new ApplicationException(); } total += read; todo += read; // increment received bytes counter _bytesReceived += read; // do we need to check boundary ? if ((boundaryLen != 0) && !boundaryIsChecked) { // some IP cameras, like AirLink, claim that boundary is "myboundary", // when it is really "--myboundary". this needs to be corrected. pos = ByteArrayUtils.Find(buffer, boundary, 0, todo); // continue reading if boudary was not found if (pos == -1) { continue; } for (var i = pos - 1; i >= 0; i--) { var ch = buffer[i]; if ((ch == (byte)'\n') || (ch == (byte)'\r')) { break; } boudaryStr = (char)ch + boudaryStr; } boundary = encoding.GetBytes(boudaryStr); boundaryLen = boundary.Length; boundaryIsChecked = true; } // search for image start if ((align == 1) && (todo >= jpegMagic.Length)) { start = ByteArrayUtils.Find(buffer, jpegMagic, pos, todo); if (start != -1) { // found JPEG start pos = start + jpegMagic.Length; todo = total - pos; align = 2; } else { // delimiter not found todo = jpegMagic.Length - 1; pos = total - todo; } } var decode = !string.IsNullOrEmpty(_decodeKey); // search for image end ( boundaryLen can be 0, so need extra check ) while ((align == 2) && (todo != 0) && (todo >= boundaryLen)) { var stop = ByteArrayUtils.Find(buffer, boundaryLen != 0 ? boundary : jpegMagic, pos, todo); if (stop != -1) { // increment frames counter _framesReceived++; var nf = NewFrame; // image at stop if (nf != null) { if (decode) { var marker = Encoding.ASCII.GetBytes(_decodeKey); using ( var ms = new MemoryStream(buffer, start + jpegMagic.Length, jpegMagic.Length + marker.Length)) { var key = new byte[marker.Length]; ms.Read(key, 0, marker.Length); if (!ByteArrayUtils.UnsafeCompare(marker, key)) { throw new Exception( "Image Decode Failed - Check the decode key matches the encode key on ispy server"); } } using ( var ms = new MemoryStream(buffer, start + marker.Length, stop - start - marker.Length)) { ms.Seek(0, SeekOrigin.Begin); ms.WriteByte(jpegMagic[0]); ms.WriteByte(jpegMagic[1]); ms.WriteByte(jpegMagic[2]); ms.Seek(0, SeekOrigin.Begin); using (var bmp = (Bitmap)Image.FromStream(ms)) { var da = new NewFrameEventArgs(bmp); nf.Invoke(this, da); } } } else { using (var ms = new MemoryStream(buffer, start, stop - start)) { using (var bmp = (Bitmap)Image.FromStream(ms)) { var da = new NewFrameEventArgs(bmp); nf.Invoke(this, da); } } } } // shift array pos = stop + boundaryLen; todo = total - pos; Array.Copy(buffer, pos, buffer, 0, todo); total = todo; pos = 0; align = 1; } else { // boundary not found if (boundaryLen != 0) { todo = boundaryLen - 1; pos = total - todo; } else { todo = 0; pos = total; } } } } } catch (ApplicationException) { // do nothing for Application Exception, which we raised on our own // wait for a while before the next try Thread.Sleep(250); } catch (ThreadAbortException) { break; } catch (Exception ex) { // provide information to clients Logger.LogException(ex, "MJPEG"); _res = ReasonToFinishPlaying.DeviceLost; break; // wait for a while before the next try //Thread.Sleep(250); } finally { // abort request request?.Abort(); stream?.Flush(); stream?.Close(); response?.Close(); } } PlayingFinished?.Invoke(this, new PlayingFinishedEventArgs(_res)); }
/// <summary> /// Copy the contents of a stored file into an opened stream /// </summary> /// <param name="zfe"> /// Entry information of file to extract /// </param> /// <param name="stream"> /// Stream to store the uncompressed data /// </param> /// <returns> /// True if success, false if not. /// </returns> /// <remarks> /// Unique compression methods are Store and Deflate /// </remarks> public bool ExtractFile(ZipFileEntry zfe, Stream stream) { if (!stream.CanWrite) { throw new InvalidOperationException("Stream cannot be written"); } // check signature var signature = new byte[4]; this.zipFileStream.Seek(zfe.HeaderOffset, SeekOrigin.Begin); this.zipFileStream.Read(signature, 0, 4); if (BitConverter.ToUInt32(signature, 0) != 0x04034b50) { return false; } // Select input stream for inflating or just reading Stream inStream = this.GetZipStream(zfe); if (inStream == null) { return false; } // Buffered copy var buffer = new byte[16384]; this.zipFileStream.Seek(zfe.FileOffset, SeekOrigin.Begin); uint bytesPending = zfe.FileSize; while (bytesPending > 0) { int bytesRead = inStream.Read(buffer, 0, (int)Math.Min(bytesPending, buffer.Length)); stream.Write(buffer, 0, bytesRead); bytesPending -= (uint)bytesRead; } stream.Flush(); if (zfe.Method == Compression.Deflate) { inStream.Dispose(); } return true; }
// Worker thread private void WorkerThread( ) { // buffer to read stream var buffer = new byte[BufferSize]; // HTTP web request HttpWebRequest request = null; // web responce WebResponse response = null; // stream for JPEG downloading Stream stream = null; // random generator to add fake parameter for cache preventing var rand = new Random((int)DateTime.UtcNow.Ticks); // download start time and duration var res = ReasonToFinishPlaying.StoppedByUser; int err = 0; while (!_stopEvent.WaitOne(0, false) && !MainForm.ShuttingDown) { int total = 0; try { // set download start time DateTime start = DateTime.UtcNow; var url = _source + ((_source.IndexOf('?') == -1) ? '?' : '&') + "fake=" + rand.Next(); response = ConnectionFactory.GetResponse(url, Cookies, Headers, HttpUserAgent, Login, Password, "GET", "", UseHttp10, out request); // get response stream try { stream = response.GetResponseStream(); } catch (NullReferenceException) { throw new Exception("Connection failed"); } stream.ReadTimeout = _requestTimeout; // loop while (!_stopEvent.WaitOne(0, false)) { // check total read if (total > BufferSize - ReadSize) { total = 0; } // read next portion from stream int read; if ((read = stream.Read(buffer, total, ReadSize)) == 0) { break; } total += read; // increment received bytes counter _bytesReceived += read; } if (!_stopEvent.WaitOne(0, false)) { // increment frames counter _framesReceived++; // provide new image to clients if (NewFrame != null) { using (var bitmap = (Bitmap)Image.FromStream(new MemoryStream(buffer, 0, total))) { // notify client NewFrame(this, new NewFrameEventArgs(bitmap)); // release the image } } } // wait for a while ? if (_frameInterval > 0) { // get download duration var span = DateTime.UtcNow.Subtract(start); // milliseconds to sleep int msec = _frameInterval - (int)span.TotalMilliseconds; if ((msec > 0) && (_stopEvent.WaitOne(msec, false))) { break; } } err = 0; } catch (ThreadAbortException) { break; } catch (Exception ex) { // provide information to clients Logger.LogExceptionToFile(ex, "JPEG"); err++; if (err > 3) { res = ReasonToFinishPlaying.DeviceLost; break; } //if ( VideoSourceError != null ) //{ // VideoSourceError( this, new VideoSourceErrorEventArgs( exception.Message ) ); //} // wait for a while before the next try Thread.Sleep(250); } finally { request?.Abort(); stream?.Flush(); stream?.Close(); response?.Close(); } // need to stop ? if (_stopEvent.WaitOne(0, false)) { break; } } PlayingFinished?.Invoke(this, new PlayingFinishedEventArgs(res)); }
public void Copy(Stream source, Stream target) { byte[] buffer = new byte[2054];//new byte[0x10000]; int bytes; try { while ((bytes = source.Read(buffer, 0, buffer.Length)) > 0) { target.Write(buffer, 0, bytes); } } finally { target.Flush(); // Or target.Close(); if you're done here already. } }