public static async Task <string> EncryptAsPasswordAsync(string password)
        {
            string base64String;

            string param   = UrlContact("").TrimStart('?');
            string content = await BiliClient.PostContentToWebAsync(Api.PASSPORT_KEY_ENCRYPT, param);

            JObject jobj = JObject.Parse(content);
            string  str  = jobj["data"]["hash"].ToString();
            string  str1 = jobj["data"]["key"].ToString();
            string  str2 = string.Concat(str, password);
            string  str3 = Regex.Match(str1, "BEGIN PUBLIC KEY-----(?<key>[\\s\\S]+)-----END PUBLIC KEY").Groups["key"].Value.Trim();

            byte[] numArray = Convert.FromBase64String(str3);
            AsymmetricKeyAlgorithmProvider asymmetricKeyAlgorithmProvider = AsymmetricKeyAlgorithmProvider.OpenAlgorithm(AsymmetricAlgorithmNames.RsaPkcs1);
            CryptographicKey cryptographicKey = asymmetricKeyAlgorithmProvider.ImportPublicKey(WindowsRuntimeBufferExtensions.AsBuffer(numArray), 0);
            var buffer = CryptographicEngine.Encrypt(cryptographicKey, WindowsRuntimeBufferExtensions.AsBuffer(Encoding.UTF8.GetBytes(str2)), null);

            base64String = Convert.ToBase64String(WindowsRuntimeBufferExtensions.ToArray(buffer));

            /**
             * try
             * {
             *
             * }
             * catch (Exception ex)
             * {
             *  System.Diagnostics.Debug.WriteLine(ex);
             *  base64String = password;
             * }
             */
            return(base64String);
        }
        public void CopyTo_NegativeCount_ThrowsArgumentOutOfRangeException()
        {
            IBuffer buffer = WindowsRuntimeBufferExtensions.AsBuffer(new byte[0]);

            AssertExtensions.Throws <ArgumentOutOfRangeException>("count", () => WindowsRuntimeBufferExtensions.CopyTo(new byte[0], 0, buffer, 0, -1));
            AssertExtensions.Throws <ArgumentOutOfRangeException>("count", () => WindowsRuntimeBufferExtensions.CopyTo(buffer, 0, new byte[0], 0, -1));
        }
        public async Task <int> ReadAsync(byte[] buffer, int offset, int length, CancellationToken cancellationToken)
        {
            StreamSocket socket = this._socket;

            if (null == socket)
            {
                throw new InvalidOperationException("The socket is not open");
            }
            IBuffer iBuffer  = WindowsRuntimeBufferExtensions.AsBuffer(buffer, offset, 0, length);
            IBuffer iBuffer2 = await WindowsRuntimeSystemExtensions.AsTask <IBuffer, uint>(socket.InputStream.ReadAsync(iBuffer, (uint)length, InputStreamOptions.Partial), cancellationToken).ConfigureAwait(false);

            int bytesRead = (int)iBuffer2.Length;
            int num;

            if (bytesRead <= 0)
            {
                num = 0;
            }
            else if (object.ReferenceEquals((object)iBuffer, (object)iBuffer2))
            {
                num = bytesRead;
            }
            else
            {
                Debug.Assert(bytesRead <= length, "Length out-of-range");
                WindowsRuntimeBufferExtensions.CopyTo(iBuffer2, 0U, buffer, offset, bytesRead);
                num = bytesRead;
            }
            return(num);
        }
Exemple #4
0
        int GetSampleRate()
        {
            LibmadWrapper Libmad = new LibmadWrapper();

            if (RhythmStream != null)
            {
                long currentPosition = RhythmStream.Position;
                Mp3bytes = new byte[RhythmStream.Length];
                RhythmStream.Position = 0;
                RhythmStream.Read(Mp3bytes, 0, Mp3bytes.Length);
                RhythmStream.Position = currentPosition;
            }

            IBuffer buffer = WindowsRuntimeBufferExtensions.AsBuffer(Mp3bytes, 0, Mp3bytes.Length);

            if (Libmad.DecodeMp32Pcm_Init(buffer))
            {
                int result = Libmad.ReadSamplesForSampleRate();
                Libmad.CloseFile();
                return(result);
            }
            else
            {
                return(-1);
            }
        }
Exemple #5
0
        /// <summary>
        /// Create the IBuffer to send with the image size
        /// </summary>
        /// <param name="sizeOfImage"></param>
        /// <returns>IBuffer</returns>
        public IBuffer ImageSizeCommand(int[] sizeOfImage)
        {
            if (sizeOfImage.Length != 3)
            {
                throw new ArgumentException();
            }
            int softDeviceSize  = sizeOfImage[0];
            int bootLoaderSize  = sizeOfImage[1];
            int applicationSize = sizeOfImage[2];

            if (softDeviceSize * bootLoaderSize * applicationSize < 0)
            {
                throw new ArgumentException();
            }
            //as the specification <Length of SoftDevice><Length of Bootloader><Length of Application>
            var softDeviceBytes      = BitConverter.GetBytes(softDeviceSize);
            var bootLoaderBytes      = BitConverter.GetBytes(bootLoaderSize);
            var applicationSizeBytes = BitConverter.GetBytes(applicationSize);

            byte[] temp = new byte[softDeviceBytes.Length + bootLoaderBytes.Length + applicationSizeBytes.Length];
            Array.Copy(softDeviceBytes, 0, temp, 0, softDeviceBytes.Length);
            Array.Copy(bootLoaderBytes, 0, temp, 4, bootLoaderBytes.Length);
            Array.Copy(applicationSizeBytes, 0, temp, 8, applicationSizeBytes.Length);
            var buffer = WindowsRuntimeBufferExtensions.AsBuffer(temp);

            return(buffer);
        }
        public void TestSha512ProviderConsistency()
        {
            byte[] message = System.Text.Encoding.UTF8.GetBytes(
                "abcdefghbcdefghicDEFghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu");
            int digestExpectedLength = 64; //for SHA 512, this is the expected length

            //The Bouncy Castle way
            org.whispersystems.curve25519.BouncyCastleDotNETSha512Provider provider = new org.whispersystems.curve25519.BouncyCastleDotNETSha512Provider();
            byte[] digestActual = new byte[digestExpectedLength];
            provider.calculateDigest(digestActual, message, message.Length);

            //The WinRT way
            HashAlgorithmProvider sha512Provider = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Sha512);
            IBuffer bMessage = WindowsRuntimeBufferExtensions.AsBuffer(message);
            IBuffer bDigest  = sha512Provider.HashData(bMessage);

            byte[] digestWinRT = WindowsRuntimeBufferExtensions.ToArray(bDigest);

            //The PCLCrypto way
            PCLCrypto.IHashAlgorithmProvider sha512PCLProvider = PCLCrypto.WinRTCrypto.HashAlgorithmProvider.OpenAlgorithm(PCLCrypto.HashAlgorithm.Sha512);
            byte[] digestPCL = sha512PCLProvider.HashData(message);

            //Did we get the same value for all ways?
            CollectionAssert.AreEqual(digestWinRT, digestActual);
            CollectionAssert.AreEqual(digestPCL, digestWinRT);
        }
Exemple #7
0
        public async static Task <IBuffer> ReadBuffer(this IInputStream stream, uint length)
        {
            var buff = WindowsRuntimeBufferExtensions.AsBuffer(new byte[length]);
            await stream.ReadAsync(buff, length, InputStreamOptions.Partial);

            return(buff);
        }    /*
Exemple #8
0
        void RequestFrames(UInt32 timestamp, SocketStream sock, UInt32 maxFrames, UInt32[] gotFrames)
        {
            uint count = 0;

            try
            {
                for (count = 0; count < maxFrames; count++)
                {
                    IBuffer buffer    = WindowsRuntimeBufferExtensions.AsBuffer(_buffer, 0, (Int32)(_mp3Reader.FrameLen));
                    Int32   len       = (Int32)_mp3Reader.ReadFrames(buffer, 1);
                    byte[]  byteArray = buffer.ToArray();
                    while (len > 0)
                    {
                        Int32[] sent = new Int32[1];
                        sock.Send(byteArray, (Int32)len, sent);
                        len -= sent[0];
                        byte[] byteArray2 = new byte[len];
                        Array.Copy(byteArray, sent[0], byteArray2, 0, len);
                        byteArray = byteArray2;
                    }
                }
            } catch {
                // TODO
            }
            gotFrames[0] = count;
        }
        public void CopyTo_InvalidDestinationIndexCount_ThrowsArgumentException(byte[] bytes, uint destinationIndex, uint count)
        {
            IBuffer buffer = WindowsRuntimeBufferExtensions.AsBuffer(bytes);

            AssertExtensions.Throws <ArgumentException>(null, () => WindowsRuntimeBufferExtensions.CopyTo(new byte[10], 0, buffer, destinationIndex, (int)count));
            AssertExtensions.Throws <ArgumentException>(null, () => WindowsRuntimeBufferExtensions.CopyTo(new byte[10].AsBuffer(), 0, bytes, (int)destinationIndex, (int)count));
            AssertExtensions.Throws <ArgumentException>(null, () => WindowsRuntimeBufferExtensions.CopyTo(new byte[10].AsBuffer(), 0, buffer, destinationIndex, count));
        }
        public void CopyTo_InvalidSourceIndexCount_ThrowsArgumentException(byte[] bytes, uint sourceIndex, uint count)
        {
            IBuffer buffer = WindowsRuntimeBufferExtensions.AsBuffer(bytes);

            AssertExtensions.Throws <ArgumentException>(sourceIndex >= bytes.Length ? "sourceIndex" : null, () => WindowsRuntimeBufferExtensions.CopyTo(bytes, (int)sourceIndex, buffer, 0, (int)count));
            AssertExtensions.Throws <ArgumentException>(null, () => WindowsRuntimeBufferExtensions.CopyTo(buffer, sourceIndex, buffer, 0, count));
            AssertExtensions.Throws <ArgumentException>(null, () => WindowsRuntimeBufferExtensions.CopyTo(buffer, sourceIndex, new byte[0], 0, (int)count));
        }
        public void CopyTo_LargeSourceIndex_ThrowsArgumentException()
        {
            IBuffer buffer = WindowsRuntimeBufferExtensions.AsBuffer(new byte[0]);

            AssertExtensions.Throws <ArgumentException>("sourceIndex", () => WindowsRuntimeBufferExtensions.CopyTo(new byte[0], 1, buffer, 0, 0));
            AssertExtensions.Throws <ArgumentException>(null, () => WindowsRuntimeBufferExtensions.CopyTo(buffer, 1, buffer, 0, 0));
            AssertExtensions.Throws <ArgumentException>(null, () => WindowsRuntimeBufferExtensions.CopyTo(buffer, 1, new byte[0], 0, 0));
        }
Exemple #12
0
        /// <inheritdoc />
        protected override double[] SendStreams(StreamTools.StreamSendWrapper[] streamsToSend, double maxSendTimePerKB, long totalBytesToSend)
        {
#if FREETRIAL
            if (this.ConnectionInfo.RemoteEndPoint.Address == IPAddress.Broadcast)
            {
                throw new NotSupportedException("Unable to send UDP broadcast datagram using this version of NetworkComms.Net. Please purchase a commercial license from www.networkcomms.net which supports UDP broadcast datagrams.");
            }
#endif

            if (ConnectionInfo.RemoteIPEndPoint.Address.Equals(IPAddress.Any))
            {
                throw new CommunicationException("Unable to send packet using this method as remoteEndPoint equals IPAddress.Any");
            }

            if (totalBytesToSend > maximumSingleDatagramSizeBytes)
            {
                throw new CommunicationException("Attempted to send a UDP packet whose length is " + totalBytesToSend.ToString() + " bytes. The maximum size for a single UDP send is " + maximumSingleDatagramSizeBytes.ToString() + ". Consider using a TCP connection to send this object.");
            }

            byte[]       udpDatagram       = new byte[totalBytesToSend];
            MemoryStream udpDatagramStream = new MemoryStream(udpDatagram, 0, udpDatagram.Length, true);

            for (int i = 0; i < streamsToSend.Length; i++)
            {
                if (streamsToSend[i].Length > 0)
                {
                    //Write each stream
                    streamsToSend[i].ThreadSafeStream.CopyTo(udpDatagramStream, streamsToSend[i].Start, streamsToSend[i].Length, NetworkComms.SendBufferSizeBytes, maxSendTimePerKB, MinSendTimeoutMS);

                    streamsToSend[i].ThreadSafeStream.Dispose();
                }
            }

            DateTime startTime = DateTime.Now;
#if WINDOWS_PHONE || NETFX_CORE
            var getStreamTask = socket.GetOutputStreamAsync(new HostName(ConnectionInfo.RemoteIPEndPoint.Address.ToString()), ConnectionInfo.RemoteIPEndPoint.Port.ToString()).AsTask();
            getStreamTask.Wait();

            var outputStream = getStreamTask.Result;

            outputStream.WriteAsync(WindowsRuntimeBufferExtensions.AsBuffer(udpDatagram)).AsTask().Wait();
            outputStream.FlushAsync().AsTask().Wait();
#else
            udpClient.Send(udpDatagram, udpDatagram.Length, ConnectionInfo.RemoteIPEndPoint);
#endif

            udpDatagramStream.Dispose();

            //Calculate timings based on fractional byte length
            double[] timings   = new double[streamsToSend.Length];
            double   elapsedMS = (DateTime.Now - startTime).TotalMilliseconds;
            for (int i = 0; i < streamsToSend.Length; i++)
            {
                timings[i] = elapsedMS * (streamsToSend[i].Length / (double)totalBytesToSend);
            }

            return(timings);
        }
        public void AsBuffer_InvalidOffsetLengthCapacity_ThrowsArgumentException(byte[] data, int offset, int length, int capacity)
        {
            if (capacity == 0)
            {
                AssertExtensions.Throws <ArgumentException>(null, () => WindowsRuntimeBufferExtensions.AsBuffer(data, offset, length));
            }

            AssertExtensions.Throws <ArgumentException>(null, () => WindowsRuntimeBufferExtensions.AsBuffer(data, offset, length, capacity));
        }
Exemple #14
0
        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>
        public async Task GetConfigAndParse()
        {
            displayList.Clear(); // clear the list since this function is called when the app resyncs content at mid night
            audioList.Clear();   // see above

            StorageFolder displayFolder = await Windows.Storage.ApplicationData.Current.LocalFolder.CreateFolderAsync("DigitalSignal\\Display", CreationCollisionOption.OpenIfExists);

            StorageFolder audioFolder = await Windows.Storage.ApplicationData.Current.LocalFolder.CreateFolderAsync("DigitalSignal\\Audio", CreationCollisionOption.OpenIfExists);

            try
            {
                HttpClient configClient = new HttpClient();
                string     configStr    = File.ReadAllText(currentConfigFilePath);
                XElement   xele         = XElement.Parse(configStr);

                foreach (XElement xe in xele.Elements())
                {
                    StorageFolder tmp     = xe.Name == "Audio" ? audioFolder : displayFolder;
                    List <object> tmpList = xe.Name == "Audio" ? audioList : displayList;

                    foreach (XElement fileElement in xe.Elements())                                                    // audio
                    {
                        if (fileElement.Attribute("type") != null && fileElement.Attribute("type").Value == "webpage") // the display is a webpage, not image, not video, we create and store a new Uri Object. Only url display type has type attribute
                        {
                            DisplayObject DO = new DisplayObject();
                            DO.uri      = new Uri(fileElement.Attribute("path").Value);
                            DO.duration = Convert.ToInt32(fileElement.Attribute("duration").Value);
                            tmpList.Add(DO);
                        }
                        else
                        {
                            DisplayObject DO       = new DisplayObject();
                            string        filename = fileElement.Attribute("path").Value.Substring(fileElement.Attribute("path").Value.LastIndexOf('/') + 1);
                            StorageFile   file     = await tmp.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting);

                            byte[] bytes = File.ReadAllBytes(filename);
                            await FileIO.WriteBufferAsync(file, WindowsRuntimeBufferExtensions.AsBuffer(bytes));

                            if (fileElement.Attribute("duration") != null) // this is an image
                            {
                                DO.duration = Convert.ToInt32(fileElement.Attribute("duration").Value);
                            }

                            DO.file = file;

                            tmpList.Add(DO);
                        }
                    }
                }
            }
            catch (Exception)
            {
                // use this to capture any config xml parsing error, we don't expose what they are
                // but only popup a dialog to user saying something is wrong..
            }
        }
Exemple #15
0
        /// <summary>
        /// Send a packet to the RemoteEndPoint specified in the ConnectionInfo
        /// </summary>
        /// <param name="packet">Packet to send</param>
        protected override void SendPacketSpecific(Packet packet)
        {
#if FREETRIAL
            if (this.ConnectionInfo.RemoteEndPoint.Address == IPAddress.Broadcast)
            {
                throw new NotSupportedException("Unable to send UDP broadcast datagram using this version of NetworkComms.Net. Please purchase a commerical license from www.networkcomms.net which supports UDP broadcast datagrams.");
            }
#endif

            if (ConnectionInfo.RemoteEndPoint.Address.Equals(IPAddress.Any))
            {
                throw new CommunicationException("Unable to send packet using this method as remoteEndPoint equals IPAddress.Any");
            }

            byte[] headerBytes = packet.SerialiseHeader(NetworkComms.InternalFixedSendReceiveOptions);

            //We are limited in size for the isolated send
            if (headerBytes.Length + packet.PacketData.Length > maximumSingleDatagramSizeBytes)
            {
                throw new CommunicationException("Attempted to send a udp packet whose serialised size was " + (headerBytes.Length + packet.PacketData.Length).ToString() + " bytes. The maximum size for a single UDP send is " + maximumSingleDatagramSizeBytes.ToString() + ". Consider using a TCP connection to send this object.");
            }

            if (NetworkComms.LoggingEnabled)
            {
                NetworkComms.Logger.Debug("Sending a UDP packet of type '" + packet.PacketHeader.PacketType + "' to " + ConnectionInfo.RemoteEndPoint.Address + ":" + ConnectionInfo.RemoteEndPoint.Port.ToString() + " containing " + headerBytes.Length.ToString() + " header bytes and " + packet.PacketData.Length.ToString() + " payload bytes.");
            }

            //Prepare the single byte array to send
            byte[] udpDatagram = packet.PacketData.ThreadSafeStream.ToArray(headerBytes.Length);

            //Copy the header bytes into the datagram
            Buffer.BlockCopy(headerBytes, 0, udpDatagram, 0, headerBytes.Length);

#if WINDOWS_PHONE
            var getStreamTask = socket.GetOutputStreamAsync(new HostName(ConnectionInfo.RemoteEndPoint.Address.ToString()), ConnectionInfo.RemoteEndPoint.Port.ToString()).AsTask();
            getStreamTask.Wait();

            var outputStream = getStreamTask.Result;

            outputStream.WriteAsync(WindowsRuntimeBufferExtensions.AsBuffer(udpDatagram)).AsTask().Wait();
            outputStream.FlushAsync().AsTask().Wait();
#else
            udpClientThreadSafe.Send(udpDatagram, udpDatagram.Length, ConnectionInfo.RemoteEndPoint);
#endif

            if (packet.PacketData.ThreadSafeStream.CloseStreamAfterSend)
            {
                packet.PacketData.ThreadSafeStream.Close();
            }

            if (NetworkComms.LoggingEnabled)
            {
                NetworkComms.Logger.Trace("Completed send of a UDP packet of type '" + packet.PacketHeader.PacketType + "' to " + ConnectionInfo.RemoteEndPoint.Address + ":" + ConnectionInfo.RemoteEndPoint.Port.ToString() + " containing " + headerBytes.Length.ToString() + " header bytes and " + packet.PacketData.Length.ToString() + " payload bytes.");
            }
        }
        public void CopyTo_NullDestination_ThrowsArgumentNullException()
        {
            IBuffer buffer = WindowsRuntimeBufferExtensions.AsBuffer(new byte[0]);

            AssertExtensions.Throws <ArgumentNullException>("destination", () => WindowsRuntimeBufferExtensions.CopyTo(new byte[0], null));
            AssertExtensions.Throws <ArgumentNullException>("destination", () => WindowsRuntimeBufferExtensions.CopyTo(buffer, (IBuffer)null));
            AssertExtensions.Throws <ArgumentNullException>("destination", () => WindowsRuntimeBufferExtensions.CopyTo(buffer, (byte[])null));
            AssertExtensions.Throws <ArgumentNullException>("destination", () => WindowsRuntimeBufferExtensions.CopyTo(new byte[0], 0, null, 0, 0));
            AssertExtensions.Throws <ArgumentNullException>("destination", () => WindowsRuntimeBufferExtensions.CopyTo(buffer, 0, null, 0, 0));
            AssertExtensions.Throws <ArgumentNullException>("destination", () => WindowsRuntimeBufferExtensions.CopyTo(buffer, 0, (IBuffer)null, 0, 0));
        }
        public void CopyTo_NullSource_ThrowsArgumentNullException()
        {
            IBuffer buffer = WindowsRuntimeBufferExtensions.AsBuffer(new byte[0]);

            AssertExtensions.Throws <ArgumentNullException>("source", () => WindowsRuntimeBufferExtensions.CopyTo((byte[])null, buffer));
            AssertExtensions.Throws <ArgumentNullException>("source", () => WindowsRuntimeBufferExtensions.CopyTo(null, new byte[0]));
            AssertExtensions.Throws <ArgumentNullException>("source", () => WindowsRuntimeBufferExtensions.CopyTo((IBuffer)null, buffer));
            AssertExtensions.Throws <ArgumentNullException>("source", () => WindowsRuntimeBufferExtensions.CopyTo(null, 0, buffer, 0, 0));
            AssertExtensions.Throws <ArgumentNullException>("source", () => WindowsRuntimeBufferExtensions.CopyTo(null, 0, new byte[0], 0, 0));
            AssertExtensions.Throws <ArgumentNullException>("source", () => WindowsRuntimeBufferExtensions.CopyTo((IBuffer)null, 0, buffer, 0, 0));
        }
Exemple #18
0
        async void Flush(IRandomAccessStream outs)
        {
            if (a_count > 0)
            {
                await outs.WriteAsync(WindowsRuntimeBufferExtensions.AsBuffer(new byte[] { Convert.ToByte(a_count) }));

                await outs.WriteAsync(WindowsRuntimeBufferExtensions.AsBuffer(accum, 0, a_count));

                a_count = 0;
            }
        }
Exemple #19
0
        public async void Encode(IRandomAccessStream os)
        {
            await os.WriteAsync(WindowsRuntimeBufferExtensions.AsBuffer(new byte[] { Convert.ToByte(initCodeSize) })); // write "initial code size" byte

            remaining = imgW * imgH;                                                                                   // reset navigation variables
            curPixel  = 0;

            Compress(initCodeSize + 1, os);                                                 // compress and write the pixel data

            await os.WriteAsync(WindowsRuntimeBufferExtensions.AsBuffer(new byte[] { 0 })); // write block terminator
        }
        private async Task <byte[]> PostWebData(Uri uri, byte[] data)
        {
            HttpClient          client   = new HttpClient();
            HttpBufferContent   body     = data != null ? new HttpBufferContent(WindowsRuntimeBufferExtensions.AsBuffer(data)) : (HttpBufferContent)null;
            HttpResponseMessage response = await client.PostAsync(uri, (IHttpContent)body);

            IBuffer ibuff = await response.get_Content().ReadAsBufferAsync();

            byte[] buff = WindowsRuntimeBufferExtensions.ToArray(ibuff);
            return(buff);
        }
Exemple #21
0
        public override void Append(byte[] data, int offset, int count)
        {
            if (count == 0)
            {
                return;
            }

            IBuffer buf = WindowsRuntimeBufferExtensions.AsBuffer(data, offset, count);

            hasher.Append(buf);
        }
 public IBuffer GetBuffer()
 {
     if (Data == null)
     {
         return(null);
     }
     else
     {
         return(WindowsRuntimeBufferExtensions.AsBuffer(Data));
     }
 }
        public async Task <int> WriteAsync(byte[] buffer, int offset, int length, CancellationToken cancellationToken)
        {
            StreamSocket socket = this._socket;

            if (null == socket)
            {
                throw new InvalidOperationException("The socket is not open");
            }
            IBuffer iBuffer = WindowsRuntimeBufferExtensions.AsBuffer(buffer, offset, length);

            return((int)await WindowsRuntimeSystemExtensions.AsTask <uint, uint>(socket.OutputStream.WriteAsync(iBuffer), cancellationToken).ConfigureAwait(false));
        }
Exemple #24
0
        /// <summary>
        /// byte数组转换为InMemoryRandomAccessStream
        /// </summary>
        /// <param name="bytes"></param>
        /// <returns></returns>
        private static async Task <InMemoryRandomAccessStream> BytesToStream(byte[] bytes)
        {
            InMemoryRandomAccessStream inputStream = new InMemoryRandomAccessStream();
            IBuffer postDataBuffer = WindowsRuntimeBufferExtensions.AsBuffer(bytes);

            DataWriter datawriter = new DataWriter(inputStream.GetOutputStreamAt(0));

            datawriter.WriteBuffer(postDataBuffer, 0, postDataBuffer.Length);
            await datawriter.StoreAsync();

            return(inputStream);
        }
        public void AsBuffer_Buffer_ReturnsExpected(byte[] source, int offset, int length, int capacity)
        {
            if (capacity == length)
            {
                if (offset == 0 && length == source.Length)
                {
                    Verify(WindowsRuntimeBufferExtensions.AsBuffer(source), source, offset, length, capacity);
                }

                Verify(WindowsRuntimeBufferExtensions.AsBuffer(source, offset, length), source, offset, length, capacity);
            }

            Verify(WindowsRuntimeBufferExtensions.AsBuffer(source, offset, length, capacity), source, offset, length, capacity);
        }
Exemple #26
0
    public static async Task <IBuffer> StreamToBuffer(IRandomAccessStream stream)
    {
        var s = stream.AsStreamForRead();

        if (stream != null)
        {
            s = stream.AsStreamForRead();
            int    len = (int)s.Length;
            byte[] b   = new byte[(uint)s.Length];
            await s.ReadAsync(b, 0, len);

            IBuffer buffer = WindowsRuntimeBufferExtensions.AsBuffer(b, 0, len);
            return(buffer);
        }
        return(null);
    }
Exemple #27
0
        static string RunOcrTests(string language, string file, bool spacing, bool newLines)
        {
            Language lang = null;

            foreach (Language ocrLanguage in OcrEngine.AvailableRecognizerLanguages)
            {
                if (ocrLanguage.LanguageTag.Equals(language, StringComparison.OrdinalIgnoreCase))
                {
                    lang = ocrLanguage;
                }
            }

            if (lang == null)
            {
                return(null);
            }

            using (var image = (System.Drawing.Bitmap)System.Drawing.Bitmap.FromFile(file))
            {
                IBuffer buffer = WindowsRuntimeBufferExtensions.AsBuffer(BitmapToByteArray(image));
                using (SoftwareBitmap bitmap = SoftwareBitmap.CreateCopyFromBuffer(buffer, BitmapPixelFormat.Rgba8, image.Width, image.Height))
                {
                    OcrEngine engine = OcrEngine.TryCreateFromLanguage(lang);
                    var       result = engine.RecognizeAsync(bitmap);
                    Task.WaitAll(result.AsTask <OcrResult>());

                    string    extractedText = string.Empty;
                    OcrResult ocrResult     = result.GetResults();
                    if (ocrResult != null && ocrResult.Lines != null)
                    {
                        foreach (OcrLine line in ocrResult.Lines)
                        {
                            foreach (OcrWord word in line.Words)
                            {
                                extractedText += word.Text + (spacing ? " " : string.Empty);
                            }
                            extractedText = extractedText.TrimEnd();
                            if (newLines)
                            {
                                extractedText += Environment.NewLine;
                            }
                        }
                    }
                    return(extractedText.TrimEnd());
                }
            }
        }
        public async Task TakePictureAsync(string fileName)
        {
            try
            {
                ITakePictureResponse response = await _misty.TakePictureAsync("sadf", false, false, true, 640, 480);

                if (response.Status == MistyRobotics.Common.Types.ResponseStatus.Success)
                {
                    StorageFolder sdkFolder = await StorageFolder.GetFolderFromPathAsync(@"c:\Data\Misty\SDK");

                    StorageFolder folder = null;
                    if (await sdkFolder.TryGetItemAsync("Images") == null)
                    {
                        folder = await sdkFolder.CreateFolderAsync("Images");
                    }
                    else
                    {
                        folder = await sdkFolder.GetFolderAsync("Images");
                    }

                    IBuffer buff = WindowsRuntimeBufferExtensions.AsBuffer(response.Data.Image.ToArray());
                    InMemoryRandomAccessStream ms = new InMemoryRandomAccessStream();
                    await ms.WriteAsync(buff);

                    BitmapDecoder decoder = await BitmapDecoder.CreateAsync(ms);

                    SoftwareBitmap softwareBitmap = await decoder.GetSoftwareBitmapAsync();

                    StorageFile file = await folder.CreateFileAsync(fileName);

                    using (IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.ReadWrite))
                    {
                        BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, stream);

                        encoder.SetSoftwareBitmap(softwareBitmap);
                        await encoder.FlushAsync();
                    }
                }
            }
            catch (Exception ex)
            {
                LogMessage("Failed to save picture: " + ex.Message);
            }
        }
Exemple #29
0
        private async Task _writeToUart(byte[] value)
        {
            GattCharacteristic c = GetCharacteristic(new Guid(BTValues.rxCharacteristic));

            if (c == null)
            {
                return;
            }
            GattWriteResult result = null;

            try {
                result = await c.WriteValueWithResultAsync(WindowsRuntimeBufferExtensions.AsBuffer(value));
            } catch (Exception e) {
            }
            if (result?.Status == GattCommunicationStatus.Success)
            {
                callback.onUartDataSent(value);
            }
        }
Exemple #30
0
        private void decode(object sender, RoutedEventArgs e)
        {
            IsolatedStorageFile isf    = IsolatedStorageFile.GetUserStoreForApplication();
            LibmadWrapper       Libmad = new LibmadWrapper();

            IBuffer buffer = WindowsRuntimeBufferExtensions.AsBuffer(Mp3bytes, 0, Mp3bytes.Length);

            PCMStream = isf.CreateFile("decoded_pcm.pcm");

            bool init = Libmad.DecodeMp32Pcm_Init(buffer);

            if (init)
            {
                List <short>  samples = new List <short>();
                RawPCMContent rpcc    = null;
                try
                {
                    while ((rpcc = Libmad.ReadSample()).count != 0)
                    {
                        short[] shortBytes = rpcc.PCMData.ToArray <short>();
                        byte[]  rawbytes   = new byte[shortBytes.Length * 2];
                        for (int i = 0; i < shortBytes.Length; i++)
                        {
                            rawbytes[2 * i]     = (byte)shortBytes[i];
                            rawbytes[2 * i + 1] = (byte)(shortBytes[i] >> 8);
                        }
                        PCMStream.Write(rawbytes, 0, rawbytes.Length);
                    }
                    PCMStream.Flush();
                    PCMStream.Close();
                    PCMStream.Dispose();
                    MessageBox.Show("over");
                    Libmad.CloseFile();
                }
                catch (Exception exception)
                {
                    MessageBox.Show(exception.Message);
                }
            }
            isf.Dispose();
        }