internal CompressedWriter( files.File file, IOutputStream stream ) : base(file, stream) { }
/// <exception cref="System.IO.IOException"></exception> protected virtual void Copy(Socket4Adapter sock, IOutputStream rawout, int length , bool update) { BufferedOutputStream @out = new BufferedOutputStream(rawout); byte[] buffer = new byte[BlobImpl.CopybufferLength]; int totalread = 0; while (totalread < length) { int stilltoread = length - totalread; int readsize = (stilltoread < buffer.Length ? stilltoread : buffer.Length); int curread = sock.Read(buffer, 0, readsize); if (curread < 0) { throw new IOException(); } @out.Write(buffer, 0, curread); totalread += curread; if (update) { _currentByte += curread; } } @out.Flush(); @out.Close(); }
/// <summary> /// Register output stream. /// </summary> /// <param name="output_stream"></param> public static void RegisterOutputStream( IOutputStream output_stream) { OutputStreamHost.InitializeIfNeeded(); _output_streams.Add(output_stream); }
public override void WriteTo( IOutputStream stream, Document context ) { stream.Write(value); }
/// <exception cref="System.IO.IOException"></exception> public NetworkSocketBase(Sharpen.Net.Socket socket, string hostName) { _socket = socket; _hostName = hostName; _in = _socket.GetInputStream(); _out = _socket.GetOutputStream(); }
private async Task WriteResponseAsync(string[] requestTokens, IOutputStream outstream) { // NOTE: If you change the respBody format, change the Content-Type (below) accordingly //string respBody = weatherData.HTML; //string respBody = weatherData.XML; string respBody = weatherData.JSON; string htmlCode = "200 OK"; using (Stream resp = outstream.AsStreamForWrite()) { byte[] bodyArray = Encoding.UTF8.GetBytes(respBody); MemoryStream stream = new MemoryStream(bodyArray); // NOTE: If you change the respBody format (above), change the Content-Type accordingly string header = string.Format("HTTP/1.1 {0}\r\n" + //"Content-Type: text/html\r\n" + // HTML only //"Content-Type: text/xml\r\n" + // XML only "Content-Type: text/json\r\n" + // JSON only "Content-Length: {1}\r\n" + "Connection: close\r\n\r\n", htmlCode, stream.Length); byte[] headerArray = Encoding.UTF8.GetBytes(header); await resp.WriteAsync(headerArray, 0, headerArray.Length); await stream.CopyToAsync(resp); await resp.FlushAsync(); } }
public DataWriter (IOutputStream outputStream) { if (outputStream == null) throw new ArgumentNullException ("outputStream"); throw new NotImplementedException(); }
public bool Initialize(IOutputStream _stream) { stream = _stream; Print("Controller.Initialize is success."); return true; }
public XBeeDevice(SerialDevice serialDevice) { _serialDevice = serialDevice; _serialDevice.ErrorReceived += _serialDevice_ErrorReceived; _input = _serialDevice.InputStream; _output = _serialDevice.OutputStream; Task.Run(() => ReadLoop(_cts.Token)); }
public SerialConnection(SerialDevice serialDevice) { _serialDevice = serialDevice; _input = _serialDevice.InputStream; _output = _serialDevice.OutputStream; _serialDevice.ErrorReceived += _serialDevice_ErrorReceived; _buffer = new byte[1024]; }
protected Writer( File file, IOutputStream stream ) { this.file = file; this.stream = stream; }
/// <summary> /// Encrypt an input stream and output to another stream /// </summary> /// <param name="inStream"></param> /// <param name="outStream"></param> /// <param name="userDescriptor"></param> /// <returns></returns> public static async Task ProtectStreamToStream(IInputStream inStream, IOutputStream outStream, string userDescriptor) { // Create a DataProtectionProvider object for the specified descriptor. DataProtectionProvider Provider = new DataProtectionProvider(userDescriptor); await Provider.ProtectStreamAsync(inStream, outStream); }
public override void WriteTo( IOutputStream stream, Document context ) { stream.Write(BeginChunk); base.WriteTo(stream, context); stream.Write(EndChunk); }
public IAsyncAction DownloadAsync(IRecord record, IOutputStream destination) { if (record == null) { throw new ArgumentNullException("record"); } return record.DownloadBlob(this, destination); }
void _listeningSocket_ConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args) { _socket = args.Socket; _stream = _socket.OutputStream; if (_acceptAction != null) _acceptAction(this); }
/// <summary> /// Decrypt an input stream and output to another stream /// </summary> /// <param name="readStream"></param> /// <param name="outStream"></param> /// <returns></returns> public static async Task DecryptStream(IInputStream readStream, IOutputStream outStream, string userDescriptor) { // Create a DataProtectionProvider object for the specified descriptor. DataProtectionProvider Provider = new DataProtectionProvider(userDescriptor); await Provider.UnprotectStreamAsync(readStream, outStream); // decrypt and output return; }
public void Open(IInputStream input, IOutputStream output) { m_DataReader = new DataReader(input); m_DataReader.ByteOrder = ByteOrder.LittleEndian; m_Reader.Reader = m_DataReader; m_DataWriter = new DataWriter(output); m_DataWriter.ByteOrder = ByteOrder.LittleEndian; m_Writer.Writer = m_DataWriter; }
public RemotePeer(ICommandSerializer serializer, ICommandsTransportResource transport, IOutputStream stream, HostName host, string port) { _serializer = serializer; _transport = transport; _dataWriter = new DataWriter(stream); HostName = host.RawName; Port = port; HandleActivity(); _transport.Received += _transport_Received; }
public HashedOutputStream(IOutputStream stream) { if (stream == null) throw new ArgumentNullException("stream"); _stream = stream; _sha = HashAlgorithmProvider .OpenAlgorithm(HashAlgorithmNames.Sha256) .CreateHash(); }
public SendFile(IOutputStream outputStream,string filename) { _writer = new DataWriter(outputStream); IStorageFolder local = ApplicationData.Current.LocalFolder; Task<Stream> taskStream = local.OpenStreamForReadAsync(filename); taskStream.Wait(); Stream s = taskStream.Result; _file = new byte[s.Length]; s.Read(_file, 0, _file.Length); }
public void Dispose() { if (this.outputStream != null) { this.outputStream.Dispose(); this.outputStream = null; } if (this.UnderlyingStream != null) { this.UnderlyingStream.Dispose(); this.UnderlyingStream = null; } }
private async Task WriteResponseAsync(string request, IOutputStream os) { // Show the html using (Stream resp = os.AsStreamForWrite()) { using (var file = File.OpenRead(htmlPath)) { string header = $"HTTP/1.1 200 OK\r\nContent-Length: {file.Length}\r\n" + "Content-Type:text/html\r\nConnection: close\r\n\r\n"; byte[] headerArray = Encoding.UTF8.GetBytes(header); await resp.WriteAsync(headerArray, 0, headerArray.Length); await file.CopyToAsync(resp); } } }
/// <summary> /// This method supports the framework directly and should not be used from your code /// </summary> /// <param name="handler">The handler.</param> /// <param name="context">The context.</param> /// <returns></returns> public static void Impl(IOutputStream handler, IContext context) { context.Response.ContentType = handler.ContentType; if (!string.IsNullOrWhiteSpace(handler.ContentDisposition)) { context.Response.SetHeader("Content-Disposition", handler.ContentDisposition); } if (context.Request.HttpMethod.Equals("HEAD")) return; using (var stream = handler.Output) { stream.Position = 0; stream.CopyTo(context.Response.OutputStream); } }
public static async Task CopyStreamAsync(this IInputStream src, IOutputStream outStream, uint bufferSize = 16384) { using (var rd = new DataReader(src)) { using (var wr = new DataWriter(outStream)) { do { var r = await rd.LoadAsync(bufferSize); if (r <= 0) break; var buf = new byte[r]; rd.ReadBytes(buf); wr.WriteBytes(buf); await wr.FlushAsync(); } while (true); } } }
/// <summary> /// This method supports the framework directly and should not be used from your code /// </summary> /// <param name="handler">The handler.</param> /// <param name="context">The context.</param> /// <returns></returns> public static void Impl(IOutputStream handler, IContext context) { context.Response.SetContentType(handler.ContentType); if (!string.IsNullOrWhiteSpace(handler.ContentDisposition)) { context.Response.SetHeader("Content-Disposition", handler.ContentDisposition); } if (context.Request.HttpMethod.Equals("HEAD")) return; context.Response.WriteFunction = (stream, token) => { using (var outputStream = handler.Output) { outputStream.Position = 0; outputStream.CopyTo(stream); } return TaskHelper.Completed(); }; }
private async Task WriteResponseAsync(string request, IOutputStream os) { // See if the request is for blinky.html, if yes get the new state string state = "Unspecified"; if (request.Contains("blinky.html?state=on")) { startupTask.AutoToggleBlinky = true; startupTask.UpdateAutoToggle(); state = "on"; } else if (request.Contains("blinky.html?state=off")) { startupTask.AutoToggleBlinky = false; startupTask.UpdateAutoToggle(); state = "off"; } //if (stateChanged) //{ // var updateMessage = new ValueSet(); // updateMessage.Add("State", state); // var responseStatus = await appServiceConnection.SendMessageAsync(updateMessage); //} string html = state == "On" ? enableHtmlString : disableHtmlString; // Show the html using (Stream resp = os.AsStreamForWrite()) { // Look in the Data subdirectory of the app package byte[] bodyArray = Encoding.UTF8.GetBytes(html); MemoryStream stream = new MemoryStream(bodyArray); string header = String.Format("HTTP/1.1 200 OK\r\n" + "Content-Length: {0}\r\n" + "Connection: close\r\n\r\n", stream.Length); byte[] headerArray = Encoding.UTF8.GetBytes(header); await resp.WriteAsync(headerArray, 0, headerArray.Length); await stream.CopyToAsync(resp); await resp.FlushAsync(); } }
private async Task WriteResponseAsync(IRestResponse response, IOutputStream os) { using (Stream resp = os.AsStreamForWrite()) { // Look in the Data subdirectory of the app package byte[] bodyArray = Encoding.UTF8.GetBytes(response.Data); MemoryStream stream = new MemoryStream(bodyArray); string header = string.Format("HTTP/1.1 {0} {1}\r\n" + "Content-Length: {2}\r\n" + "Content-Type: application/json\r\n" + "Connection: close\r\n\r\n", response.StatusCode, HttpHelpers.GetHttpStatusCodeText(response.StatusCode), stream.Length); byte[] headerArray = Encoding.UTF8.GetBytes(header); await resp.WriteAsync(headerArray, 0, headerArray.Length); await stream.CopyToAsync(resp); await resp.FlushAsync(); } }
/// <summary> /// This method supports the framework directly and should not be used from your code /// </summary> /// <param name="handler">The handler.</param> /// <param name="context">The context.</param> /// <returns></returns> public static void Impl(IOutputStream handler, IContext context) { context.Response.SetContentType(handler.ContentType); if (!string.IsNullOrWhiteSpace(handler.ContentDisposition)) { context.Response.SetHeader("Content-Disposition", handler.ContentDisposition); } if (context.Request.HttpMethod.Equals("HEAD")) return; if (!handler.Output.CanSeek) throw new InvalidOperationException("Output stream must support Seek operations."); context.Response.WriteFunction = (stream) => { using (var outputStream = handler.Output) { outputStream.Position = 0; outputStream.CopyTo(stream); } return TaskHelper.Completed(); }; }
/// <summary> /// 輸出的資料 /// </summary> /// <param name="request">http://網址 以後的東西 /// ex. http://1xx.xx.xx.xx/sample.html 則此參數呈現 /sample.html</param> /// <param name="os"></param> /// <returns></returns> private async Task WriteResponseAsync(string request, IOutputStream os) { string file = @"Assets\html" + request.Replace("\\", "/"); if (request == "/") { file = @"Assets\html\index.html"; } else if (!System.IO.File.Exists(file)) { file = @"Assets\html\404.html"; } using (Stream resp = os.AsStreamForWrite()) { var contentType = "text/html"; if (System.IO.Path.GetExtension(file).ToLower() == ".jpg" || System.IO.Path.GetExtension(file).ToLower() == ".png" || System.IO.Path.GetExtension(file).ToLower() == ".jpeg") { contentType = "image/jpeg"; } //很簡單的處理jpg and html 只是測試,別太講究 //Handling MIME and Head roughly. byte[] bodyArray = File.ReadAllBytes(file); MemoryStream stream = new MemoryStream(bodyArray); string header = String.Format("HTTP/1.1 200 OK\r\n" + "Content-Length: {0}\r\n" + "content-type: {1}\r\n" + "Connection: close\r\n\r\n", stream.Length, contentType); byte[] headerArray = Encoding.UTF8.GetBytes(header); await resp.WriteAsync(headerArray, 0, headerArray.Length); await stream.CopyToAsync(resp); await resp.FlushAsync(); } }
// fallback for completely unknown types public void EmitUnknown(IOutputStream o, SceneObject so) { o.AddAttribute(IOStrings.ASOType, IOStrings.TypeUnknown); o.AddAttribute(IOStrings.ASOName, so.Name); o.AddAttribute(IOStrings.ASOUuid, so.UUID); }
public async Task serveStaticFile(string path) { if (path == "/") { path = "/index.html"; } /* Security check: remove the trailing "/.." to prevent the user from accessing forbiden files. * This is probably not needed since the system should restrict access to only authorized files. */ path = path.Replace("/..", ""); // Try to determince Content-type from the extension. var startExt = path.LastIndexOf("."); if (startExt == -1) { throw new System.IO.FileNotFoundException(); } var ext = path.Substring(startExt + 1); string contentType; try { contentType = contentTypes[ext]; } catch (KeyNotFoundException) { throw new System.IO.FileNotFoundException(); } Uri uri; try { if (path.StartsWith("/thumbnails/")) { uri = getThumbnail(path); } else { uri = new Uri("ms-appx:///Assets/WebInterface" + path); } } catch { throw new System.IO.FileNotFoundException(); } StorageFile file = await StorageFile.GetFileFromApplicationUriAsync(uri); IBuffer fileBuffer = await FileIO.ReadBufferAsync(file); // Translate files if needed. if (ext == "html" || ext == "css") { fileBuffer = translateBuffer(fileBuffer); } // Fill media list if we serve the main page. if (path == "/index.html") { fileBuffer = fillMediaList(fileBuffer); } string header = String.Format("HTTP/1.1 200 OK\r\n" + "Content-Type: {0}\r\n" + "Content-Length: {1}\r\n" + "Connection: close\r\n" + "\r\n", contentType, fileBuffer.Length); using (IOutputStream output = socket.OutputStream) { byte[] headerArray = Encoding.UTF8.GetBytes(header); IBuffer buffer = headerArray.AsBuffer(); await output.WriteAsync(buffer); await output.WriteAsync(fileBuffer); } }
public NonSeekableRandomAccessStreamForWrite(Stream stream) { this.stream = stream; this.oStream = stream.AsOutputStream(); this.imrac = new InMemoryRandomAccessStream(); }
public ChunkedOutputStream(IOutputStream output) { this.output = output; }
public static void Emit(this SceneSerializer s, IOutputStream o, CylinderSO so) { o.AddAttribute(IOStrings.ASOType, IOStrings.TypeCylinder); EmitCylinderSO(s, o, so); }
public override void WriteTo(IOutputStream stream, File context) { stream.Write(RawValue.ToString(context.Configuration.RealFormat, formatInfo)); }
public static Stream AsStreamForWrite(this IOutputStream windowsruntimeStream, int bufferSize) { return(AsStreamInternal(windowsruntimeStream, bufferSize, "AsStreamForWrite", forceBufferSize: true)); }
public static void Emit(this SceneSerializer s, IOutputStream o, DMeshSO so) { o.AddAttribute(IOStrings.ASOType, IOStrings.TypeDMesh); EmitDMeshSO(s, o, so); }
public static void Emit(this SceneSerializer s, IOutputStream o, SphereSO so) { o.AddAttribute(IOStrings.ASOType, IOStrings.TypeSphere); EmitSphereSO(s, o, so); }
/// <summary> /// Emit a keyframe sequence as a KeyframeListStruct /// </summary> public static void EmitKeyframes(this SceneSerializer s, KeyframeSequence seq, IOutputStream o) { o.BeginStruct(IOStrings.KeyframeListStruct); o.AddAttribute(IOStrings.ATimeRange, (Vector2f)seq.ValidRange); int i = 0; foreach (Keyframe k in seq) { o.BeginStruct(IOStrings.KeyframeStruct, i.ToString()); i++; o.AddAttribute(IOStrings.ATime, (float)k.Time, true); o.AddAttribute(IOStrings.APosition, k.Frame.Origin, true); o.AddAttribute(IOStrings.AOrientation, k.Frame.Rotation, true); o.EndStruct(); } o.EndStruct(); }
/// <summary> /// Emit a DMesh3 as a CompressedDMeshStruct /// </summary> public static void EmitDMeshCompressed_Minimal(this SceneSerializer s, DMesh3 m, IOutputStream o) { SceneSerializer.EmitOptions opt = s.CurrentOptions; // compressed version - uuencoded byte buffers // - storing doubles uses roughly same mem as string, but string is only 8 digits precision // - storing floats saves roughly 50% // - storing triangles is worse until vertex count > 9999 // - could store as byte or short in those cases... // - edges and edge ref counts are stored, then use mesh.RebuildFromEdgeRefcounts() to rebuild 3D mesh (same as gSerialization) o.BeginStruct(IOStrings.CompressedDMeshStruct); o.AddAttribute(IOStrings.AMeshStorageMode, (int)IOStrings.MeshStorageMode.Minimal); // need compact mesh to do this if (m.IsCompactV == false) { m = new DMesh3(m, true); } o.AddAttribute(IOStrings.AMeshVertices3Compressed, BufferUtil.CompressZLib(m.VerticesBuffer.GetBytes(), opt.FastCompression)); if (opt.StoreMeshVertexNormals && m.HasVertexNormals) { o.AddAttribute(IOStrings.AMeshNormals3Compressed, BufferUtil.CompressZLib(m.NormalsBuffer.GetBytes(), opt.FastCompression)); } if (opt.StoreMeshVertexColors && m.HasVertexColors) { o.AddAttribute(IOStrings.AMeshColors3Compressed, BufferUtil.CompressZLib(m.ColorsBuffer.GetBytes(), opt.FastCompression)); } if (opt.StoreMeshVertexUVs && m.HasVertexUVs) { o.AddAttribute(IOStrings.AMeshUVs2Compressed, BufferUtil.CompressZLib(m.UVBuffer.GetBytes(), opt.FastCompression)); } int[] triangles = new int[3 * m.TriangleCount]; int k = 0; foreach (int tid in m.TriangleIndices()) { Index3i t = m.GetTriangle(tid); triangles[k++] = t.a; triangles[k++] = t.b; triangles[k++] = t.c; } o.AddAttribute(IOStrings.AMeshTrianglesCompressed, BufferUtil.CompressZLib(BufferUtil.ToBytes(triangles), opt.FastCompression)); if (opt.StoreMeshFaceGroups && m.HasTriangleGroups) { int[] groups = new int[m.TriangleCount]; k = 0; foreach (int tid in m.TriangleIndices()) { groups[k++] = m.GetTriangleGroup(tid); } o.AddAttribute(IOStrings.AMeshTriangleGroupsCompressed, BufferUtil.CompressZLib(BufferUtil.ToBytes(groups), opt.FastCompression)); } o.EndStruct(); }
public static void EmitFrame(this SceneSerializer s, IOutputStream o, string structName, Frame3f frame) { EmitFrame(s, o, structName, ref frame); }
public void Render(IOutputStream outputStream) { outputStream.Write(HTMLElements.m_openDiv); if (!string.IsNullOrEmpty(Role)) { outputStream.Write(HTMLElements.m_space); outputStream.Write(HTMLElements.m_role); outputStream.Write(HTMLElements.m_equal); outputStream.Write(HTMLElements.m_quote); outputStream.Write(Role); outputStream.Write(HTMLElements.m_quote); } if (!string.IsNullOrEmpty(AriaLabel)) { outputStream.Write(HTMLElements.m_space); outputStream.Write(HTMLElements.m_ariaLabel); outputStream.Write(HTMLElements.m_equal); outputStream.Write(HTMLElements.m_quote); outputStream.Write(AntiXssEncoder.XmlAttributeEncode(AriaLabel)); outputStream.Write(HTMLElements.m_quote); } string text = string.Empty; if (Size != null && Size.Width != null && Size.Width.GetType() == typeof(AutoScaleTo100Percent)) { text = HTMLElements.m_resize100WidthClassName; } if (Size != null && Size.Height != null && Size.Height.GetType() == typeof(AutoScaleTo100Percent)) { text = text + HTMLElements.m_spaceString + HTMLElements.m_resize100HeightClassName; } if (!string.IsNullOrEmpty(text)) { outputStream.Write(HTMLElements.m_classStyle); outputStream.Write(text); outputStream.Write(HTMLElements.m_quoteString); } outputStream.Write(HTMLElements.m_openStyle); if (Size != null) { Size.Render(outputStream); } if (BackgroundImage != null) { outputStream.Write(HTMLElements.m_space); outputStream.Write(HTMLElements.m_backgroundImage); outputStream.Write(BackgroundImage.Replace("(", "%28").Replace(")", "%29")); outputStream.Write(HTMLElements.m_closeParenthesis); outputStream.Write(HTMLElements.m_semiColon); } if (BackgroundImageSize != null) { outputStream.Write(HTMLElements.m_space); outputStream.Write(HTMLElements.m_backgroundSize); outputStream.Write(BackgroundImageSize); outputStream.Write(HTMLElements.m_semiColon); } if (BackgroundRepeat != null) { outputStream.Write(HTMLElements.m_space); outputStream.Write(HTMLElements.m_backgroundRepeat); BackgroundRepeat.Render(outputStream); outputStream.Write(HTMLElements.m_semiColon); } if (Overflow != null) { outputStream.Write(HTMLElements.m_overflow); outputStream.Write(Overflow); outputStream.Write(HTMLElements.m_semiColon); } outputStream.Write(HTMLElements.m_quoteString); outputStream.Write(HTMLElements.m_closeBracket); if (ChildElement != null) { ChildElement.Render(outputStream); } outputStream.Write(HTMLElements.m_closeDiv); }
/// <summary> /// invoked when the user clicks the save to file button /// </summary> /// <param name="sender">unused object parameter</param> /// <param name="e">unused event parameter</param> private async void BtnSaveToFile_Click(object sender, RoutedEventArgs e) { string text = this.tbData.Text; // select the file to save this data to FileSavePicker savePicker = new FileSavePicker(); savePicker.DefaultFileExtension = ".wav"; // this is the only type available savePicker.FileTypeChoices.Add("Audio file", new List <string>() { ".wav" }); StorageFile file = await savePicker.PickSaveFileAsync(); if (file != null) { this.btnSaveToFile.IsEnabled = false; // create the data stream SpeechSynthesisStream synthesisStream; try { synthesisStream = await this.synthesizer.SynthesizeTextToStreamAsync(text); } catch (Exception) { synthesisStream = null; this.btnSaveToFile.IsEnabled = true; } if (synthesisStream == null) { MessageDialog dialog = new MessageDialog("unable to synthesize text"); await dialog.ShowAsync(); return; } // open the output stream Windows.Storage.Streams.Buffer buffer = new Windows.Storage.Streams.Buffer(4096); IRandomAccessStream writeStream = (IRandomAccessStream)await file.OpenAsync(FileAccessMode.ReadWrite); IOutputStream outputStream = writeStream.GetOutputStreamAt(0); DataWriter dataWriter = new DataWriter(outputStream); // copy the stream data into the file while (synthesisStream.Position < synthesisStream.Size) { await synthesisStream.ReadAsync(buffer, 4096, InputStreamOptions.None); dataWriter.WriteBuffer(buffer); } // close the data file streams dataWriter.StoreAsync().AsTask().Wait(); outputStream.FlushAsync().AsTask().Wait(); this.btnSaveToFile.IsEnabled = true; } }
public static async Task CopyFromStream(IRandomAccessStream stream, IOutputStream output) { var buffer = await ReadIntoBuffer(stream); await output.WriteAsync(buffer); }
public bool Remove(IOutputStream stream, int resolution) { var key = new Key(stream.FileName, stream.Length, resolution); return(this.Store.TryRemove(key)); }
public static Stream AsStreamForWrite(this IOutputStream windowsruntimeStream) { return(AsStreamInternal(windowsruntimeStream, DefaultBufferSize, "AsStreamForWrite", forceBufferSize: false)); }
/** * <summary>Serializes the xref stream entries into the stream body.</summary> */ private void Flush( IOutputStream stream ) { // 1. Body. PdfArray indexArray = new PdfArray(); int[] entryFieldSizes = new int[] { EntryField0Size, GetFieldSize((int)stream.Length), // NOTE: We assume this xref stream is the last indirect object. EntryField2Size }; { // Get the stream buffer! IBuffer body = Body; // Delete the old entries! body.SetLength(0); // Serializing the entries into the stream buffer... int prevObjectNumber = -2; // Previous-entry object number. foreach (XRefEntry entry in entries.Values) { int entryNumber = entry.Number; if (entryNumber - prevObjectNumber != 1) // Current subsection terminated. { if (indexArray.Count > 0) { indexArray.Add(new PdfInteger(prevObjectNumber - ((PdfInteger)indexArray[indexArray.Count - 1]).IntValue + 1)); } // Number of entries in the previous subsection. indexArray.Add(new PdfInteger(entryNumber)); // First object number in the next subsection. } prevObjectNumber = entryNumber; switch (entry.Usage) { case XRefEntry.UsageEnum.Free: body.Append((byte)FreeEntryType); body.Append(NumberToByteArray(entry.Offset, entryFieldSizes[1])); body.Append(NumberToByteArray(entry.Generation, entryFieldSizes[2])); break; case XRefEntry.UsageEnum.InUse: body.Append((byte)InUseEntryType); body.Append(NumberToByteArray(entry.Offset, entryFieldSizes[1])); body.Append(NumberToByteArray(entry.Generation, entryFieldSizes[2])); break; case XRefEntry.UsageEnum.InUseCompressed: body.Append((byte)InUseCompressedEntryType); body.Append(NumberToByteArray(entry.StreamNumber, entryFieldSizes[1])); body.Append(NumberToByteArray(entry.Offset, entryFieldSizes[2])); break; default: throw new NotSupportedException(); } } indexArray.Add(new PdfInteger(prevObjectNumber - ((PdfInteger)indexArray[indexArray.Count - 1]).IntValue + 1)); // Number of entries in the previous subsection. } // 2. Header. { PdfDictionary header = Header; header[PdfName.Index] = indexArray; header[PdfName.Size] = new PdfInteger(file.IndirectObjects.Count + 1); header[PdfName.W] = new PdfArray( new PdfInteger(entryFieldSizes[0]), new PdfInteger(entryFieldSizes[1]), new PdfInteger(entryFieldSizes[2]) ); } }
private async void receivedConnectionHandler(StreamSocketListener s, StreamSocketListenerConnectionReceivedEventArgs e) { Interlocked.Increment(ref _activeStreams); bool serveSingleJpegOnly = false; bool serveMJpegStream = false; try { Debug.WriteLine("Got connection"); string request; using (var streamReader = new StreamReader(e.Socket.InputStream.AsStreamForRead())) { request = await streamReader.ReadLineAsync(); Debug.WriteLine(request); } if (!request.StartsWith("GET ", StringComparison.OrdinalIgnoreCase)) { throw new Exception("No HTTP GET request."); } int httpPos = request.LastIndexOf(" HTTP/"); if (httpPos < 5) { throw new Exception("No valid HTTP Requst."); } string requestUri = request.Substring(4, httpPos - 4); Debug.WriteLine("relative uri: '" + requestUri + "'"); Uri uri = new Uri("http://host" + requestUri, UriKind.Absolute); NameValueCollection query = HttpUtility.ParseQueryString(uri.Query); Debug.WriteLine("Path: {0} Query: {1}", uri.LocalPath, uri.Query); string framerateOption = query["framerate"]; if (framerateOption != null) { UInt16 fr; if (UInt16.TryParse(framerateOption, out fr)) { CalculateAndSetFrameRate(fr); } } string qualityOption = query["quality"]; if (qualityOption != null) { UInt16 fr; if (UInt16.TryParse(qualityOption, out fr)) { if (fr >= 0 && fr <= 100) { ConfigureImageQuality(fr); } } } if (uri.LocalPath.Contains("image.jpg")) { serveSingleJpegOnly = true; Debug.WriteLine("Single image requested."); } if (uri.LocalPath.Equals("/") || uri.LocalPath.Equals("/stream.mjpeg")) { serveMJpegStream = true; Debug.WriteLine("MJPEG requested."); } /*using (IInputStream input = e.Socket.InputStream) * { * var buffer = new Windows.Storage.Streams.Buffer(2); * await input.ReadAsync(buffer, buffer.Capacity, InputStreamOptions.Partial); * * * //System.Web.HttpUtility. * System.Uri uri; * //uri. * }*/ using (IOutputStream output = e.Socket.OutputStream) { using (Stream response = output.AsStreamForWrite()) { MjpegHttpStreamer mjpegHttpStreamer = new MjpegHttpStreamer(response); if (serveSingleJpegOnly) { mjpegHttpStreamer.WriteJpegHeader(); Debug.WriteLine("JPEG HTTPHeader. Now sending single JPEG."); try { InMemoryRandomAccessStream jpegStream; jpegStream = _jpegStreamBuffer; if (jpegStream != null) { mjpegHttpStreamer.WriteJpeg(jpegStream); } } catch (Exception ex) { Debug.WriteLine("JPEG HTTP sending aborted." + ex.ToString()); } } else if (serveMJpegStream) { mjpegHttpStreamer.WriteMJpegHeader(); Debug.WriteLine("MJPEG HTTPHeader sent. Now streaming JPEGs."); try { int lastStreamHash = 0; while (_isServerStarted) { int streamHash = _jpegStreamBuffer.GetHashCode(); if (streamHash == lastStreamHash) { await Task.Delay(50); continue; } lastStreamHash = streamHash; InMemoryRandomAccessStream jpegStream; jpegStream = _jpegStreamBuffer; if (jpegStream != null) { mjpegHttpStreamer.WriteMJpeg(jpegStream); } } } catch (Exception ex) { Debug.WriteLine("MJPEG HTTP Stream ended." + ex.ToString()); } } else { mjpegHttpStreamer.WriteErrorHeader(); } } } } catch (Exception ex2) { Debug.WriteLine("Connection closed by client: " + ex2.ToString()); } e.Socket.Dispose(); Interlocked.Decrement(ref _activeStreams); }
public static void Emit(this SceneSerializer s, IOutputStream o, MeshReferenceSO so) { o.AddAttribute(IOStrings.ASOType, IOStrings.TypeMeshReference); EmitMeshReferenceSO(s, o, so); }
private async Task writeResponseAsync(string request, IOutputStream os, StreamSocketInformation socketInfo) { try { string[] requestParts = request.Split('/'); // Request for the root page, so redirect to home page if (request.Equals("/")) { await redirectToPage(NavConstants.HOME_PAGE, os); } // Request for the home page else if (request.Contains(NavConstants.HOME_PAGE)) { // Generate the default config page string html = await helper.GenerateStatusPage(); await WebHelper.WriteToStream(html, os); } // Request for the settings page else if (request.Contains(NavConstants.SETTINGS_PAGE)) { // Process the GET parameters if (request.Contains("?")) { // Format the URI with the get parameters Uri uri = new Uri("http://1.2.3.4:8000" + request); // Take the parameters from the URL and put it into Settings helper.ParseUriIntoSettings(uri); await AppSettings.SaveAsync(App.Controller.XmlSettings, "Settings.xml"); // This is an event that lets us know what the controller is done restarting after the settings are applied AutoResetEvent ase = new AutoResetEvent(false); // Dispose and Initialize need to be called on UI thread because of DispatcherTimers await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async() => { try { // Restart the controller to apply new settings App.Controller.Dispose(); await App.Controller.Initialize(); // Create the settings page and add a confirmation message that the settings were applied successfully string html = helper.GeneratePage("Security System Config", "Security System Config", helper.CreateHtmlFormFromSettings(), "<span style='color:Green'>Configuration saved!</span><br><br>"); await WebHelper.WriteToStream(html, os); } catch (Exception ex) { Debug.WriteLine("Error restarting controller: " + ex.Message); } // Signal that the restart is done ase.Set(); }); // Wait for controller restart to finish ase.WaitOne(); } else { // Generate the default config page string html = helper.GeneratePage("Security System Config", "Security System Config", helper.CreateHtmlFormFromSettings()); await WebHelper.WriteToStream(html, os); } } // Request for the OneDrive page else if (request.Contains(NavConstants.ONEDRIVE_PAGE)) { // Take in the parameters and try to login to OneDrive if (request.Contains("?")) { // I just put some arbitrary IP and port just so I have a correctly formatted URI, it's not important to have an actual IP + port Uri uri = new Uri("http://1.2.3.4:8000" + request); await helper.ParseOneDriveUri(uri); var oneDrive = App.Controller.Storage as OneDrive; if (oneDrive != null) { if (oneDrive.IsLoggedIn()) { // Save tokens to settings file if we successfully logged in await AppSettings.SaveAsync(App.Controller.XmlSettings, "Settings.xml"); } } } // Generate page and write to stream string html = helper.GenerateOneDrivePage(); await WebHelper.WriteToStream(html, os); } // Request for gallery page else if (request.Contains(NavConstants.GALLERY_PAGE)) { string html = ""; var storageType = App.Controller.Storage.GetType(); // If the storage type is OneDrive, generate page with link to OneDrive if (storageType == typeof(OneDrive)) { html = helper.GeneratePage("Gallery", "Gallery", "<b>" + storageType.Name + "</b> is set as your storage provider. " + "Please view your pictures on <a href='http://www.onedrive.com' target='_blank'>OneDrive</a>.<br><br>" + "To view your pictures here, please select <b>" + StorageProvider.Local + "</b> as your storage provider."); } // Otherwise show the gallery for the files on the device else { StorageFolder folder = KnownFolders.PicturesLibrary; int page = 1; int pageSize = 30; // Parse GET parameters if (request.Contains("?")) { Uri uri = new Uri("http://1.2.3.4:8000" + request); var parameters = helper.ParseGetParametersFromUrl(uri); try { // Find the folder that's specified in the parameters folder = await StorageFolder.GetFolderFromPathAsync(parameters["folder"]); if (parameters.ContainsKey("page")) { try { page = Convert.ToInt32(parameters["page"]); } catch (Exception) { } } if (parameters.ContainsKey("pageSize")) { try { pageSize = Convert.ToInt32(parameters["pageSize"]); } catch (Exception) { } } } catch (Exception ex) { Debug.WriteLine("Exception finding folder: " + ex.Message); folder = await folder.GetFolderAsync(AppSettings.FolderName); // Log telemetry event about this exception var events = new Dictionary <string, string> { { "WebServer", ex.Message } }; TelemetryHelper.TrackEvent("FailedToGetFolderFromPath", events); } } else { folder = await folder.GetFolderAsync(AppSettings.FolderName); } // Generate gallery page and write to stream string galleryHtml = await helper.GenerateGallery(folder, page, pageSize); html = helper.GeneratePage("Gallery", "Gallery", galleryHtml); } await WebHelper.WriteToStream(html, os); } // Request for API else if (request.Contains("api")) { try { if (requestParts.Length > 2) { switch (requestParts[2].ToLower()) { // An image from the gallery was requested case "gallery": var temp = request.Split(new string[] { "gallery/" }, StringSplitOptions.None); // HTML decode the file path string decodedPath = WebUtility.UrlDecode(temp[1]); // Retrieve the file StorageFile file = await StorageFile.GetFileFromPathAsync(decodedPath); // Write the file to the stream await WebHelper.WriteFileToStream(file, os); break; } } }catch (Exception ex) { Debug.WriteLine("Exception in web API: " + ex.Message); // Log telemetry event about this exception var events = new Dictionary <string, string> { { "WebServer", ex.Message } }; TelemetryHelper.TrackEvent("FailedToProcessApiRequest", events); } } // Request for a file that is in the Assets\Web folder (e.g. logo, css file) else { using (Stream resp = os.AsStreamForWrite()) { bool exists = true; try { var folder = Windows.ApplicationModel.Package.Current.InstalledLocation; // Map the requested path to Assets\Web folder string filePath = @"Assets\Web" + request.Replace('/', '\\'); // Open the file and write it to the stream using (Stream fs = await folder.OpenStreamForReadAsync(filePath)) { string header = String.Format("HTTP/1.1 200 OK\r\n" + "Content-Length: {0}\r\n{1}" + "Connection: close\r\n\r\n", fs.Length, ((request.Contains("css")) ? "Content-Type: text/css\r\n" : "")); byte[] headerArray = Encoding.UTF8.GetBytes(header); await resp.WriteAsync(headerArray, 0, headerArray.Length); await fs.CopyToAsync(resp); } } catch (FileNotFoundException ex) { exists = false; // Log telemetry event about this exception var events = new Dictionary <string, string> { { "WebServer", ex.Message } }; TelemetryHelper.TrackEvent("FailedToOpenStream", events); } // Send 404 not found if can't find file if (!exists) { byte[] headerArray = Encoding.UTF8.GetBytes( "HTTP/1.1 404 Not Found\r\n" + "Content-Length:0\r\n" + "Connection: close\r\n\r\n"); await resp.WriteAsync(headerArray, 0, headerArray.Length); } await resp.FlushAsync(); } } }catch (Exception ex) { Debug.WriteLine("Exception in writeResponseAsync(): " + ex.Message); Debug.WriteLine(ex.StackTrace); // Log telemetry event about this exception var events = new Dictionary <string, string> { { "WebServer", ex.Message } }; TelemetryHelper.TrackEvent("FailedToWriteResponse", events); try { // Try to send an error page back if there was a problem servicing the request string html = helper.GeneratePage("Error", "Error", "There's been an error: " + ex.Message + "<br><br>" + ex.StackTrace); await WebHelper.WriteToStream(html, os); } catch (Exception e) { TelemetryHelper.TrackException(e); } } }
public void Render(IOutputStream outputStream) { outputStream.Write(HTMLElements.m_openDiv); if (!string.IsNullOrEmpty(this.Role)) { outputStream.Write(HTMLElements.m_space); outputStream.Write(HTMLElements.m_role); outputStream.Write(HTMLElements.m_equal); outputStream.Write(HTMLElements.m_quote); outputStream.Write(this.Role); outputStream.Write(HTMLElements.m_quote); } if (!string.IsNullOrEmpty(this.AriaLabel)) { outputStream.Write(HTMLElements.m_space); outputStream.Write(HTMLElements.m_ariaLabel); outputStream.Write(HTMLElements.m_equal); outputStream.Write(HTMLElements.m_quote); outputStream.Write(this.AriaLabel); outputStream.Write(HTMLElements.m_quote); } string text = string.Empty; if (this.Size != null && this.Size.Width != null && this.Size.Width.GetType() == typeof(AutoScaleTo100Percent)) { text = HTMLElements.m_resize100WidthClassName; } if (this.Size != null && this.Size.Height != null && this.Size.Height.GetType() == typeof(AutoScaleTo100Percent)) { text = text + HTMLElements.m_spaceString + HTMLElements.m_resize100HeightClassName; } if (!string.IsNullOrEmpty(text)) { outputStream.Write(HTMLElements.m_classStyle); outputStream.Write(text); outputStream.Write(HTMLElements.m_quoteString); } outputStream.Write(HTMLElements.m_openStyle); if (this.Size != null) { this.Size.Render(outputStream); } if (this.BackgroundImage != null) { outputStream.Write(HTMLElements.m_space); outputStream.Write(HTMLElements.m_backgroundImage); outputStream.Write(this.BackgroundImage); outputStream.Write(HTMLElements.m_closeParenthesis); outputStream.Write(HTMLElements.m_semiColon); } if (this.BackgroundImageSize != null) { outputStream.Write(HTMLElements.m_space); outputStream.Write(HTMLElements.m_backgroundSize); outputStream.Write(this.BackgroundImageSize); outputStream.Write(HTMLElements.m_semiColon); } if (this.BackgroundRepeat != null) { outputStream.Write(HTMLElements.m_space); outputStream.Write(HTMLElements.m_backgroundRepeat); this.BackgroundRepeat.Render(outputStream); outputStream.Write(HTMLElements.m_semiColon); } if (this.Overflow != null) { outputStream.Write(HTMLElements.m_overflow); outputStream.Write(this.Overflow); outputStream.Write(HTMLElements.m_semiColon); } outputStream.Write(HTMLElements.m_quoteString); outputStream.Write(HTMLElements.m_closeBracket); if (this.ChildElement != null) { this.ChildElement.Render(outputStream); } outputStream.Write(HTMLElements.m_closeDiv); }
private static void DoTestWrite(Func <Stream> createStreamFunc, bool mustInvokeProgressHandler) { Stream backingStream = createStreamFunc(); using (IOutputStream stream = backingStream.AsOutputStream()) { // Create test data Random rnd = new Random(20100720); // Must be a different seed than used for TestStreamProvider.ModelStreamContents byte[] modelWriteData = new byte[0xA000]; rnd.NextBytes(modelWriteData); // Start test IBuffer buffer = modelWriteData.AsBuffer(); // ibuffer.Length for IBuffer created by Array.ToBuffer(void) must equal to array.Length Assert.Equal((uint)modelWriteData.Length, buffer.Length); // ibuffer.Capacity for IBuffer created by Array.ToBuffer(void) must equal to array.Length Assert.Equal((uint)modelWriteData.Length, buffer.Capacity); IAsyncOperationWithProgress <uint, uint> writeOp = stream.WriteAsync(buffer); // Note the race. By the tie we get here, the status of the op may be started or already completed. AsyncStatus writeOpStatus = writeOp.Status; Assert.True(writeOpStatus == AsyncStatus.Completed || writeOpStatus == AsyncStatus.Started, "New writeOp must have Status = Started or Completed (race)"); uint writeOpId = writeOp.Id; bool progressCallbackInvoked = false; bool completedCallbackInvoked = false; uint resultBytesWritten = 0; EventWaitHandle waitHandle = new ManualResetEvent(false); writeOp.Progress = (asyncWriteOp, bytesCompleted) => { progressCallbackInvoked = true; // asyncWriteOp.Id in a progress callback must match the ID of the asyncWriteOp to which the callback was assigned Assert.Equal(writeOpId, asyncWriteOp.Id); // asyncWriteOp.Status must be 'Started' for an asyncWriteOp in progress Assert.Equal(AsyncStatus.Started, asyncWriteOp.Status); // bytesCompleted must be in range [0, maxBytesToWrite] asyncWriteOp in progress Assert.InRange(bytesCompleted, 0u, (uint)TestStreamProvider.ModelStreamLength); }; writeOp.Completed = (asyncWriteOp, passedStatus) => { try { completedCallbackInvoked = true; // asyncWriteOp.Id in a completion callback must match the ID of the asyncWriteOp to which the callback was assigned Assert.Equal(writeOpId, asyncWriteOp.Id); // asyncWriteOp.Status must match passedStatus for a completed asyncWriteOp Assert.Equal(passedStatus, asyncWriteOp.Status); // asyncWriteOp.Status must be 'Completed' for a completed asyncWriteOp Assert.Equal(AsyncStatus.Completed, asyncWriteOp.Status); uint bytesWritten = asyncWriteOp.GetResults(); // asyncWriteOp.GetResults() must return that all required bytes were written for a completed asyncWriteOp Assert.Equal((uint)modelWriteData.Length, bytesWritten); resultBytesWritten = bytesWritten; } finally { waitHandle.Set(); } }; // Now, let's block until the write op is complete. // We speculate that it will complete within 3500 msec, although under high load it may not be. // If the test fails we should use a better way to determine if callback is really not invoked, or if it's just too slow. waitHandle.WaitOne(500); waitHandle.WaitOne(1000); waitHandle.WaitOne(2000); if (mustInvokeProgressHandler) { Assert.True(progressCallbackInvoked, "Progress callback specified to WriteAsync callback must be invoked when reading from this kind of stream"); } Assert.True(completedCallbackInvoked, "Completion callback specified to WriteAsync callback must be invoked"); // writeOp.Status must be 'Completed' for a completed async writeOp Assert.Equal(AsyncStatus.Completed, writeOp.Status); // writeOp.GetResults() must return that all required bytes were written for a completed async writeOp Assert.Equal((uint)modelWriteData.Length, resultBytesWritten); // Check contents backingStream.Seek(0, SeekOrigin.Begin); byte[] verifyBuff = new byte[modelWriteData.Length + 1024]; int r = backingStream.Read(verifyBuff, 0, verifyBuff.Length); for (int i = 0; i < modelWriteData.Length; i++) { Assert.Equal(modelWriteData[i], verifyBuff[i]); } } }
public async void Send(byte[] fileBytes) { try { if (Speakers != null && Speakers.Count > 0 && fileBytes != null) { //iterate through the speakers and send out the media file to each speaker foreach (Speaker speaker in Speakers) { StreamSocket socket = speaker.Socket; if (socket != null) { IOutputStream outStream = socket.OutputStream; using (DataWriter dataWriter = new DataWriter(outStream)) { //write header bytes to indicate to the subscriber //information about the file to be sent dataWriter.WriteInt16((short)MessageType.Media); dataWriter.WriteInt32(fileBytes.Length); await dataWriter.StoreAsync(); //start from 0 and increase by packet size int partNumber = 0; int sourceIndex = 0; int bytesToWrite = fileBytes.Length; while (bytesToWrite > 0) { dataWriter.WriteInt32(partNumber); int packetSize = bytesToWrite; if (packetSize > MAX_PACKET_SIZE) { packetSize = MAX_PACKET_SIZE; } byte[] fragmentedPixels = new byte[packetSize]; Array.Copy(fileBytes, sourceIndex, fragmentedPixels, 0, packetSize); dataWriter.WriteBytes(fragmentedPixels); Debug.WriteLine("sent byte packet length " + packetSize); await dataWriter.StoreAsync(); sourceIndex += packetSize; bytesToWrite -= packetSize; partNumber++; Debug.WriteLine("sent total bytes " + (fileBytes.Length - bytesToWrite)); } //Finally DetachStream dataWriter.DetachStream(); } } } //check the speakers have all received the file foreach (Speaker speaker in Speakers) { StreamSocket socket = speaker.Socket; if (socket != null) { //wait for the 'I got it' message DataReader reader = new DataReader(socket.InputStream); uint x = await reader.LoadAsync(sizeof(short)); MessageType t = (MessageType)reader.ReadInt16(); if (MessageType.Ready == t) { await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { Speakers.Remove(speaker); speaker.Status = "Ready"; Speakers.Add(speaker); }); } reader.DetachStream(); } } } } catch (Exception ex) { Debug.WriteLine(ex.ToString()); } }
public override void WriteTo( IOutputStream stream ) { bool unencodedBody; byte[] bodyData; int bodyLength; // 1. Header. // Encoding. /* * NOTE: As the contract establishes that a stream instance should be kept * free from encodings in order to be editable, encoding is NOT applied to * the actual online stream, but to its serialized representation only. * That is, as encoding is just a serialization practise, it is excluded from * alive, instanced streams. */ PdfDirectObject filterObj = header[PdfName.Filter]; if (filterObj == null) // Unencoded body. { /* * NOTE: As online representation is unencoded, * header entries related to the encoded stream body are temporary * (instrumental to the current serialization process). */ unencodedBody = true; // Set the filter to apply! filterObj = PdfName.FlateDecode; // zlib/deflate filter. // Get encoded body data applying the filter to the stream! bodyData = body.Encode(Filter.Get((PdfName)filterObj), null); // Set encoded length! bodyLength = bodyData.Length; // Update 'Filter' entry! header[PdfName.Filter] = filterObj; } else // Encoded body. { unencodedBody = false; // Get encoded body data! bodyData = body.ToByteArray(); // Set encoded length! bodyLength = (int)body.Length; } // Set encoded length! header[PdfName.Length] = new PdfInteger(bodyLength); header.WriteTo(stream); // Is the body free from encodings? if (unencodedBody) { // Restore actual header entries! ((PdfInteger)header[PdfName.Length]).Value = (int)body.Length; header[PdfName.Filter] = null; } // 2. Body. stream.Write(BeginStreamBodyChunk); stream.Write(bodyData); stream.Write(EndStreamBodyChunk); }
public RemotePeer(IOutputStream outputStream, HostName hostName, string port) { this.OutputStream = outputStream; this.HostName = hostName; this.Port = port; }
/* * Store */ public void Store(IOutputStream o, FScene scene) { o.BeginScene(IOStrings.CurrentSceneVersion); foreach (SceneObject so in scene.SceneObjects) { if (so.IsTemporary) { continue; } if (SOFilterF(so) == false) { continue; } o.BeginSceneObject(); string typeIdentifier = so.Type.identifier; // serialize custom types if client has registered a serializer bool bEmitted = false; if (scene.TypeRegistry.ContainsType(typeIdentifier)) { SOEmitSerializationFunc emitter = scene.TypeRegistry.FindSerializer(typeIdentifier); if (emitter != null) { bEmitted = emitter(this, o, so); } } if (bEmitted == false) { // otherwise fall back to default handlers. // Currently these are extension methods in SceneSerializerEmitTypes.cs if (so is CylinderSO) { this.Emit(o, so as CylinderSO); } else if (so is BoxSO) { this.Emit(o, so as BoxSO); } else if (so is SphereSO) { this.Emit(o, so as SphereSO); } else if (so is PivotSO) { this.Emit(o, so as PivotSO); } else if (so is MeshSO) { this.Emit(o, so as MeshSO); } else if (so is DMeshSO) { this.Emit(o, so as DMeshSO); } else if (so is MeshReferenceSO) { this.Emit(o, so as MeshReferenceSO); } else if (so is PolyTubeSO) { this.Emit(o, so as PolyTubeSO); } else if (so is PolyCurveSO) { this.Emit(o, so as PolyCurveSO); } else { this.EmitGenericSO(o, so); } //this.EmitUnknown(o, so); } o.EndSceneObject(); } o.EndScene(); }
public OutputStreamQueueValue(IOutputStream outputStream) : this() { this.OutputStream = outputStream; }
public static void Emit(this SceneSerializer s, IOutputStream o, PolyCurveSO so) { o.AddAttribute(IOStrings.ASOType, IOStrings.TypePolyCurve); EmitPolyCurveSO(s, o, so); }
public MnsServer(IInputStream inputStream, IOutputStream outputStream) : base(inputStream, outputStream, ObexServiceUuid.MessageNotification) { }
public SocketWrapper(SocketWrapper listeningSocket) { _tokenSource = new CancellationTokenSource(); _taskFactory = new TaskFactory(_tokenSource.Token); _socket = listeningSocket._socket; _stream = _socket.OutputStream; _listeningSocket = listeningSocket._listeningSocket; }