/// <summary>
        /// This is the click handler for the 'Copy Strings' button.  Here we will parse the
        /// strings contained in the ElementsToWrite text block, write them to a stream using
        /// DataWriter, retrieve them using DataReader, and output the results in the
        /// ElementsRead text block.
        /// </summary>
        /// <param name="sender">Contains information about the button that fired the event.</param>
        /// <param name="e">Contains state information and event data associated with a routed event.</param>
        private async void TransferData(object sender, RoutedEventArgs e)
        {
            // Initialize the in-memory stream where data will be stored.
            using (var stream = new Windows.Storage.Streams.InMemoryRandomAccessStream())
            {
                // Create the data writer object backed by the in-memory stream.
                using (var dataWriter = new Windows.Storage.Streams.DataWriter(stream))
                {
                    dataWriter.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8;
                    dataWriter.ByteOrder = Windows.Storage.Streams.ByteOrder.LittleEndian;

                    // Write each element separately.
                    foreach (string inputElement in inputElements)
                    {
                        uint inputElementSize = dataWriter.MeasureString(inputElement);
                        dataWriter.WriteUInt32(inputElementSize);
                        dataWriter.WriteString(inputElement);
                    }

                    // Send the contents of the writer to the backing stream.
                    await dataWriter.StoreAsync();

                    // For the in-memory stream implementation we are using, the flushAsync call is superfluous,
                    // but other types of streams may require it.
                    await dataWriter.FlushAsync();

                    // In order to prolong the lifetime of the stream, detach it from the DataWriter so that it 
                    // will not be closed when Dispose() is called on dataWriter. Were we to fail to detach the 
                    // stream, the call to dataWriter.Dispose() would close the underlying stream, preventing 
                    // its subsequent use by the DataReader below.
                    dataWriter.DetachStream();
                }

                // Create the input stream at position 0 so that the stream can be read from the beginning.
                stream.Seek(0);
                using (var dataReader = new Windows.Storage.Streams.DataReader(stream))
                {
                    // The encoding and byte order need to match the settings of the writer we previously used.
                    dataReader.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8;
                    dataReader.ByteOrder = Windows.Storage.Streams.ByteOrder.LittleEndian;

                    // Once we have written the contents successfully we load the stream.
                    await dataReader.LoadAsync((uint)stream.Size);

                    var receivedStrings = "";

                    // Keep reading until we consume the complete stream.
                    while (dataReader.UnconsumedBufferLength > 0)
                    {
                        // Note that the call to readString requires a length of "code units" to read. This
                        // is the reason each string is preceded by its length when "on the wire".
                        uint bytesToRead = dataReader.ReadUInt32();
                        receivedStrings += dataReader.ReadString(bytesToRead) + "\n";
                    }

                    // Populate the ElementsRead text block with the items we read from the stream.
                    ElementsRead.Text = receivedStrings;
                }
            }
        }
コード例 #2
0
        async void InitializeBluetooth()
        {
            try
            {
                var service_id = RfcommServiceId.FromUuid(Guid.Parse("ff1477c2-7265-4d55-bb08-c3c32c6d635c"));
                provider = await RfcommServiceProvider.CreateAsync(service_id);

                StreamSocketListener listener = new StreamSocketListener();
                listener.ConnectionReceived += OnConnectionReceived;
                await listener.BindServiceNameAsync(
                    provider.ServiceId.AsString(),
                    SocketProtectionLevel.BluetoothEncryptionAllowNullAuthentication);

                // InitializeServiceSdpAttributes
                var writer = new Windows.Storage.Streams.DataWriter();
                writer.WriteByte(SERVICE_VERSION_ATTRIBUTE_TYPE);
                writer.WriteUInt32(SERVICE_VERSION);
                var data = writer.DetachBuffer();
                provider.SdpRawAttributes.Add(SERVICE_VERSION_ATTRIBUTE_ID, data);

                provider.StartAdvertising(listener, true);
            }
            catch (Exception error)
            {
                Debug.WriteLine(error.ToString());
            }
        }
コード例 #3
0
            /// <summary>
            /// SET_LINE_CODING CDC request.
            /// </summary>
            /// <param name="index">Interface index.</param>
            /// <param name="dteRate">Data terminal rate, in bits per second.</param>
            /// <param name="charFormat">Stop bits.</param>
            /// <param name="parityType">Parity.</param>
            /// <param name="dataBits">Data bits.</param>
            /// <returns>
            /// The result of Task contains a length of bytes actually sent to the serial port.
            /// </returns>
            private Task <uint> SetLineCoding(
                uint index,
                uint dteRate,
                byte charFormat,
                byte parityType,
                byte dataBits
                )
            {
                // SetLineCoding
                var writer = new Windows.Storage.Streams.DataWriter();

                writer.ByteOrder = Windows.Storage.Streams.ByteOrder.LittleEndian;
                writer.WriteUInt32(dteRate);
                writer.WriteByte(charFormat);
                writer.WriteByte(parityType);
                writer.WriteByte(dataBits);
                var buffer = writer.DetachBuffer();

                var requestType = new UsbControlRequestType();

                requestType.AsByte = RequestType.Set;

                return(UsbControlRequestForSet(
                           index,
                           requestType,
                           RequestCode.SetLineCoding,
                           0,
                           buffer));
            }
コード例 #4
0
        /// <summary>
        /// This is the click handler for the 'Copy Strings' button.  Here we will parse the
        /// strings contained in the ElementsToWrite text block, write them to a stream using
        /// DataWriter, retrieve them using DataReader, and output the results in the
        /// ElementsRead text block.
        /// </summary>
        /// <param name="sender">Contains information about the button that fired the event.</param>
        /// <param name="e">Contains state information and event data associated with a routed event.</param>
        private async void TransferData(object sender, RoutedEventArgs e)
        {
            // Initialize the in-memory stream where data will be stored.
            using (var stream = new Windows.Storage.Streams.InMemoryRandomAccessStream())
            {
                // Create the data writer object backed by the in-memory stream.
                using (var dataWriter = new Windows.Storage.Streams.DataWriter(stream))
                {
                    dataWriter.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8;
                    dataWriter.ByteOrder       = Windows.Storage.Streams.ByteOrder.LittleEndian;

                    // Write each element separately.
                    foreach (string inputElement in inputElements)
                    {
                        uint inputElementSize = dataWriter.MeasureString(inputElement);
                        dataWriter.WriteUInt32(inputElementSize);
                        dataWriter.WriteString(inputElement);
                    }

                    // Send the contents of the writer to the backing stream.
                    await dataWriter.StoreAsync();

                    // For the in-memory stream implementation we are using, the flushAsync call is superfluous,
                    // but other types of streams may require it.
                    await dataWriter.FlushAsync();

                    // In order to prolong the lifetime of the stream, detach it from the DataWriter so that it
                    // will not be closed when Dispose() is called on dataWriter. Were we to fail to detach the
                    // stream, the call to dataWriter.Dispose() would close the underlying stream, preventing
                    // its subsequent use by the DataReader below.
                    dataWriter.DetachStream();
                }

                // Create the input stream at position 0 so that the stream can be read from the beginning.
                stream.Seek(0);
                using (var dataReader = new Windows.Storage.Streams.DataReader(stream))
                {
                    // The encoding and byte order need to match the settings of the writer we previously used.
                    dataReader.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8;
                    dataReader.ByteOrder       = Windows.Storage.Streams.ByteOrder.LittleEndian;

                    // Once we have written the contents successfully we load the stream.
                    await dataReader.LoadAsync((uint)stream.Size);

                    var receivedStrings = "";

                    // Keep reading until we consume the complete stream.
                    while (dataReader.UnconsumedBufferLength > 0)
                    {
                        // Note that the call to readString requires a length of "code units" to read. This
                        // is the reason each string is preceded by its length when "on the wire".
                        uint bytesToRead = dataReader.ReadUInt32();
                        receivedStrings += dataReader.ReadString(bytesToRead) + "\n";
                    }

                    // Populate the ElementsRead text block with the items we read from the stream.
                    ElementsRead.Text = receivedStrings;
                }
            }
        }
コード例 #5
0
ファイル: Server.cs プロジェクト: hashikawau/cs_samples
        static void InitializeServiceSdpAttributes(RfcommServiceProvider provider)
        {
            var writer = new Windows.Storage.Streams.DataWriter();

            // First write the attribute type
            writer.WriteByte(SERVICE_VERSION_ATTRIBUTE_TYPE);
            // Then write the data
            writer.WriteUInt32(SERVICE_VERSION);

            var data = writer.DetachBuffer();

            provider.SdpRawAttributes.Add(SERVICE_VERSION_ATTRIBUTE_ID, data);
        }
コード例 #6
0
            /// <summary>
            /// SET_LINE_CODING CDC request.
            /// </summary>
            /// <param name="index">Interface index.</param>
            /// <param name="dteRate">Data terminal rate, in bits per second.</param>
            /// <param name="charFormat">Stop bits.</param>
            /// <param name="parityType">Parity.</param>
            /// <param name="dataBits">Data bits.</param>
            /// <returns>
            /// The result of Task contains a length of bytes actually sent to the serial port.
            /// </returns>
           private Task<uint> SetLineCoding(
                uint index,
                uint dteRate,
                byte charFormat,
                byte parityType,
                byte dataBits
            )
            {
                // SetLineCoding
                var writer = new Windows.Storage.Streams.DataWriter();
                writer.ByteOrder = Windows.Storage.Streams.ByteOrder.LittleEndian;
                writer.WriteUInt32(dteRate);
                writer.WriteByte(charFormat);
                writer.WriteByte(parityType);
                writer.WriteByte(dataBits);
                var buffer = writer.DetachBuffer();

                var requestType = new UsbControlRequestType();
                requestType.AsByte = RequestType.Set;

                return UsbControlRequestForSet(
                        index,
                        requestType,
                        RequestCode.SetLineCoding,
                        0,
                        buffer);
            }
コード例 #7
0
ファイル: WMF2WPF.cs プロジェクト: bbowyersmyth/WMF2WPF
        private BitmapSource ReadDeviceIndependantBitmap(BinaryReader wmfReader, uint dibSize, out int width, out int height)
        {
            #if NETFX_CORE
            var bmp = new BitmapImage();
            var memStream = new Windows.Storage.Streams.InMemoryRandomAccessStream();
            var dibBytes = wmfReader.ReadBytes((int)dibSize);
            // int imageBytesOffset = 14;

            //System.Runtime.InteropServices.GCHandle pinnedDib = System.Runtime.InteropServices.GCHandle.Alloc(dibBytes, System.Runtime.InteropServices.GCHandleType.Pinned);

            //if (dibBytes[3] == 0x0C)
            //{
            //    imageBytesOffset += 12;
            //}
            //else
            //{
            //    var infoHeader = (BITMAPINFOHEADER)System.Runtime.InteropServices.Marshal.PtrToStructure(pinnedDib.AddrOfPinnedObject(), typeof(BITMAPINFOHEADER));

            //    imageBytesOffset += (int)infoHeader.biSize;

            //    switch ((BitCount)infoHeader.biBitCount)
            //    {
            //        case BitCount.BI_BITCOUNT_1:
            //            // 1 bit - Two colors
            //            imageBytesOffset += 4 * (colorUsed == 0 ? 2 : Math.Min(colorUsed, 2));
            //            break;

            //        case BitCount.BI_BITCOUNT_2:
            //            // 4 bit - 16 colors
            //            imageBytesOffset += 4 * (colorUsed == 0 ? 16 : Math.Min(colorUsed, 16));
            //            break;

            //        case BitCount.BI_BITCOUNT_3:
            //            // 8 bit - 256 colors
            //            imageBytesOffset += 4 * (colorUsed == 0 ? 256 : Math.Min(colorUsed, 256));
            //            break;
            //    }

            //    if ((Compression)infoHeader.biCompression == Compression.BI_BITFIELDS)
            //    {
            //        imageBytesOffset += 12;
            //    }
            //}

            //pinnedDib.Free();

            using (Windows.Storage.Streams.DataWriter writer = new Windows.Storage.Streams.DataWriter(memStream.GetOutputStreamAt(0)))
            {
                writer.WriteBytes(new byte[] { 66, 77 }); // BM
                writer.WriteUInt32(dibSize + 14);
                writer.WriteBytes(new byte[] { 0, 0, 0, 0 }); // Reserved
                writer.WriteUInt32((UInt32)0);

                writer.WriteBytes(dibBytes);
                var t = writer.StoreAsync();
                t.GetResults();
            }

            // bmp.ImageFailed += bmp_ImageFailed;
            // bmp.ImageOpened += bmp_ImageOpened;
            bmp.SetSource(memStream);
            width = bmp.PixelWidth;
            height = bmp.PixelHeight;
            return bmp;
            #else
            var bmp = new BitmapImage();
            var memStream = new MemoryStream();
            var dibBytes = wmfReader.ReadBytes((int)dibSize);

            BinaryWriter writer = new BinaryWriter(memStream);
            writer.Write(new byte[] { 66, 77 }); // BM
            writer.Write(dibSize + 14);
            writer.Write(new byte[] { 0, 0, 0, 0 }); // Reserved
            writer.Write((UInt32)0);

            writer.Write(dibBytes);
            writer.Flush();

            memStream.Position = 0;
            try
            {
                bmp.BeginInit();
                bmp.StreamSource = memStream;
                bmp.EndInit();
                width = bmp.PixelWidth;
                height = bmp.PixelHeight;

                return bmp;
            }
            catch
            {
                // Bad image;
                width = 0;
                height = 0;

                return null;
            }
            #endif
        }