public async Task TestDataProtectionProviderForStream()
        {
            const string input       = "The quick brown fox jumps over the lazy dog.";
            var          inputStream = new InMemoryRandomAccessStream();

            var stream = inputStream.GetOutputStreamAt(0);

            using (var writer = new DataWriter(stream))
            {
                writer.WriteString(input);
                await writer.StoreAsync();

                await stream.FlushAsync();
            }

            // Protected data will placed in here.
            var protectedStream = new InMemoryRandomAccessStream();

            // Protect stream
            await dppSvc.ProtectStreamAsync(inputStream.GetInputStreamAt(0),
                                            protectedStream.GetOutputStreamAt(0));

            {
                DataReader readerI = new DataReader(inputStream.GetInputStreamAt(0));
                DataReader readerP = new DataReader(protectedStream.GetInputStreamAt(0));
                await readerI.LoadAsync((uint)inputStream.Size);

                await readerP.LoadAsync((uint)protectedStream.Size);

                IBuffer bufferI = readerI.ReadBuffer((uint)inputStream.Size);
                IBuffer bufferP = readerP.ReadBuffer((uint)protectedStream.Size);

                // Verify that the protected data does not match the original
                Assert.IsFalse(CryptographicBuffer.Compare(bufferI, bufferP), "ProtectStreamAsync returned unprotected data");
            }

            // Unprotect stream
            var unprotectedStream = new InMemoryRandomAccessStream();

            // Unprotect stream
            await dppSvc.UnprotectStreamAsync(protectedStream.GetInputStreamAt(0),
                                              unprotectedStream.GetOutputStreamAt(0));

            {
                DataReader readerI = new DataReader(inputStream.GetInputStreamAt(0));
                DataReader readerP = new DataReader(unprotectedStream.GetInputStreamAt(0));
                await readerI.LoadAsync((uint)inputStream.Size);

                await readerP.LoadAsync((uint)unprotectedStream.Size);

                IBuffer bufferI = readerI.ReadBuffer((uint)inputStream.Size);
                IBuffer bufferP = readerP.ReadBuffer((uint)unprotectedStream.Size);

                // Verify that the unprotected data does match the original
                Assert.IsTrue(CryptographicBuffer.Compare(bufferI, bufferP));
            }
        }
Ejemplo n.º 2
0
        private async Task <IBuffer> SampleDataProtectionStream(
            String descriptor,
            String strMsg,
            BinaryStringEncoding encoding)
        {
            // Create a DataProtectionProvider object for the specified descriptor.
            DataProtectionProvider Provider = new DataProtectionProvider(descriptor);

            // Convert the input string to a buffer.
            IBuffer buffMsg = CryptographicBuffer.ConvertStringToBinary(strMsg, encoding);

            // Create a random access stream to contain the plaintext message.
            InMemoryRandomAccessStream inputData = new InMemoryRandomAccessStream();

            // Create a random access stream to contain the encrypted message.
            InMemoryRandomAccessStream protectedData = new InMemoryRandomAccessStream();

            // Retrieve an IOutputStream object and fill it with the input (plaintext) data.
            IOutputStream outputStream = inputData.GetOutputStreamAt(0);
            DataWriter    writer       = new DataWriter(outputStream);

            writer.WriteBuffer(buffMsg);
            await writer.StoreAsync();

            await outputStream.FlushAsync();

            // Retrieve an IInputStream object from which you can read the input data.
            IInputStream source = inputData.GetInputStreamAt(0);

            // Retrieve an IOutputStream object and fill it with encrypted data.
            IOutputStream dest = protectedData.GetOutputStreamAt(0);
            await Provider.ProtectStreamAsync(source, dest);

            await dest.FlushAsync();

            //Verify that the protected data does not match the original
            DataReader reader1 = new DataReader(inputData.GetInputStreamAt(0));
            DataReader reader2 = new DataReader(protectedData.GetInputStreamAt(0));
            await reader1.LoadAsync((uint)inputData.Size);

            await reader2.LoadAsync((uint)protectedData.Size);

            IBuffer buffOriginalData  = reader1.ReadBuffer((uint)inputData.Size);
            IBuffer buffProtectedData = reader2.ReadBuffer((uint)protectedData.Size);

            if (CryptographicBuffer.Compare(buffOriginalData, buffProtectedData))
            {
                throw new Exception("ProtectStreamAsync returned unprotected data");
            }

            // Return the encrypted data.
            return(buffProtectedData);
        }
        public void TestSerializationRoundtripThroughStream()
        {
            var command = new AppInstallRequest(new AppInstallInfo()
            {
                AppxPath = "abc", PackageFamilyName = "def", Dependencies = new List <String>()
                {
                    "ghi", "jkl"
                }
            });
            var blob = command.Serialize();

            var stream = new InMemoryRandomAccessStream();

            blob.WriteToIOutputStreamAsync(stream.GetOutputStreamAt(0)).AsTask().Wait();
            var blob2 = Blob.ReadFromIInputStreamAsync(stream.GetInputStreamAt(0)).AsTask().Result;

            Assert.AreEqual(blob2.Tag, blob.Tag);

            var command2 = blob2.MakeIRequest() as AppInstallRequest;

            Assert.IsNotNull(command2);
            Assert.AreEqual(command2.Tag, DMMessageKind.InstallApp);
            Assert.AreEqual(command2.AppInstallInfo.AppxPath, "abc");
            Assert.AreEqual(command2.AppInstallInfo.PackageFamilyName, "def");
            Assert.AreEqual(command2.AppInstallInfo.Dependencies[0], "ghi");
            Assert.AreEqual(command2.AppInstallInfo.Dependencies[1], "jkl");
        }
Ejemplo n.º 4
0
        private async Task saveElementAsync()
        {
            if (Elements.Count > 0)
            {
                using (var stream = new InMemoryRandomAccessStream())
                {
                    using (var writer = new DataWriter(stream))
                    {
                        foreach (var elem in Elements)
                        {
                            if (elem.Content != null)
                            {
                                var e = elem.ToBinary();
                                writer.WriteUInt32((uint)e.Length);
                                writer.WriteBytes(e);
                                await writer.StoreAsync();
                            }
                        }
                        using (var reader = new DataReader(stream.GetInputStreamAt(0)))
                        {
                            This.Element = new byte[stream.Size];
                            await reader.LoadAsync((uint)stream.Size);

                            reader.ReadBytes(This.Element);
                        }
                    }
                }
            }
            else
            {
                This.Element = null;
            }
        }
Ejemplo n.º 5
0
        private async Task loadElementsAsync()
        {
            Elements.Clear();
            if (This.Element != null)
            {
                using (var stream = new InMemoryRandomAccessStream())
                {
                    await stream.WriteAsync(This.Element.AsBuffer());

                    using (var reader = new DataReader(stream.GetInputStreamAt(0)))
                    {
                        await reader.LoadAsync((uint)stream.Size);

                        while (reader.UnconsumedBufferLength > 0)
                        {
                            var bytes = new byte[reader.ReadUInt32()];
                            reader.ReadBytes(bytes);
                            TextElement element;
                            if (TextElement.TryParse(bytes, out element))
                            {
                                Elements.Add(element);
                            }
                        }
                    }
                }
            }
        }
        private async Task savePreviewAsync(int maxWidth = 256, int maxHeight = 256)
        {
            if (This.Content != null)
            {
                // a4 pixel size 96 dpi = 794 x 1123
                CanvasDevice       device       = CanvasDevice.GetSharedDevice(true);
                CanvasRenderTarget renderTarget = new CanvasRenderTarget(device, 794, 1123, 96);

                var mergedStream = new InMemoryRandomAccessStream();
                using (var ds = renderTarget.CreateDrawingSession())
                {
                    ds.Clear(Colors.White);
                    var textContent = Encoding.UTF8.GetString(This.Content);
                    //CanvasSolidColorBrush textBrush = new CanvasSolidColorBrush(device, Colors.Red);
                    CanvasTextFormat textFormat = new CanvasTextFormat();
                    CanvasTextLayout textLayout = new CanvasTextLayout(device, textContent, textFormat, 600, 900);

                    ds.DrawTextLayout(textLayout, new Vector2(100, 100), Colors.Black);
                }
                await renderTarget.SaveAsync(mergedStream, CanvasBitmapFileFormat.Jpeg);

                //StorageFile between = await DownloadsFolder.CreateFileAsync("between.jpg", CreationCollisionOption.GenerateUniqueName);
                //using (var fileStream = await between.OpenAsync(FileAccessMode.ReadWrite))
                //{
                //  await RandomAccessStream.CopyAsync(mergedStream, fileStream);
                //}

                // scaling result
                BitmapDecoder decoder = await BitmapDecoder.CreateAsync(mergedStream);

                using (var previewStream = new InMemoryRandomAccessStream())
                {
                    BitmapEncoder encoder = await BitmapEncoder.CreateForTranscodingAsync(previewStream, decoder);

                    var ratioWidth  = (double)maxWidth / decoder.PixelWidth;
                    var ratioHeight = (double)maxHeight / decoder.PixelHeight;
                    var ratioScale  = Math.Min(ratioWidth, ratioHeight);

                    var aspectHeight = (uint)(ratioScale * decoder.PixelHeight);
                    var aspectWidth  = (uint)(ratioScale * decoder.PixelWidth);

                    //encoder.BitmapTransform.InterpolationMode = BitmapInterpolationMode.Linear;
                    encoder.BitmapTransform.ScaledHeight = aspectHeight;
                    encoder.BitmapTransform.ScaledWidth  = aspectWidth;
                    await encoder.FlushAsync();

                    // write result to preview
                    using (var reader = new DataReader(previewStream.GetInputStreamAt(0)))
                    {
                        This.Preview = new byte[previewStream.Size];
                        await reader.LoadAsync((uint)previewStream.Size);

                        reader.ReadBytes(This.Preview);
                    }

                    //StorageFile previewFile = await DownloadsFolder.CreateFileAsync("preview.jpg", CreationCollisionOption.GenerateUniqueName);
                    //await FileIO.WriteBytesAsync(previewFile, This.Preview);
                }
            }
        }
Ejemplo n.º 7
0
        public async void WriteXml(XmlWriter writer)
        {
            writer.WriteElementString("Title", Title);
            writer.WriteElementString("Description", Description);
            writer.WriteElementString("Status", Status.ToString());
            writer.WriteStartElement("Stokes");
            if (Strokes != null && Strokes.Count > 0)
            {
                using (InMemoryRandomAccessStream ms = new InMemoryRandomAccessStream())
                {
                    InkStrokeContainer inkCont = new InkStrokeContainer();

                    foreach (InkStroke stroke in Strokes)
                    {
                        inkCont.AddStroke(stroke.Clone());
                    }

                    await inkCont.SaveAsync(ms);

                    await ms.FlushAsync();

                    byte[] bytes = new byte[ms.Size];
                    //var dataWriter = new DataWriter(ms);
                    var reader = new DataReader(ms.GetInputStreamAt(0));
                    await reader.LoadAsync((uint)ms.Size);

                    reader.ReadBytes(bytes);

                    writer.WriteBinHex(bytes, 0, (int)ms.Size);
                }
            }
            writer.WriteEndElement();
        }
        public void TestReadFromIInputStream()
        {
            var command = new AppInstallRequest(new AppInstallInfo()
            {
                AppxPath = "abc", PackageFamilyName = "def", Dependencies = new List <String>()
                {
                    "ghi", "jkl"
                }
            });
            var dataArray     = command.Serialize().GetByteArrayForSerialization();
            var dataSizeArray = BitConverter.GetBytes((UInt32)dataArray.Length);

            var stream = new InMemoryRandomAccessStream();

            stream.WriteAsync(dataSizeArray.AsBuffer()).AsTask().Wait();
            stream.WriteAsync(dataArray.AsBuffer()).AsTask().Wait();

            var result = Blob.ReadFromIInputStreamAsync(stream.GetInputStreamAt(0)).AsTask().Result;

            Assert.AreEqual(result.Tag, DMMessageKind.InstallApp);

            var request = result.MakeIRequest() as AppInstallRequest;

            Assert.AreEqual(request.Tag, DMMessageKind.InstallApp);
            Assert.AreEqual(request.AppInstallInfo.AppxPath, "abc");
            Assert.AreEqual(request.AppInstallInfo.PackageFamilyName, "def");
            Assert.AreEqual(request.AppInstallInfo.Dependencies[0], "ghi");
            Assert.AreEqual(request.AppInstallInfo.Dependencies[1], "jkl");
        }
        private static async Task <byte[]> GetImageAsByteArray(SoftwareBitmap image)
        {
            using (var stream = new InMemoryRandomAccessStream())
            {
                var encoder = await BitmapEncoder.CreateAsync(
                    BitmapEncoder.JpegEncoderId, stream);

                encoder.SetSoftwareBitmap(image);

                // Scale the image to 720p to make sure we don't exceed API size limits
                var maxDimension = Math.Max(image.PixelHeight, image.PixelWidth);
                var sf           = 1280f / maxDimension;
                encoder.BitmapTransform.ScaledWidth  = (uint)(image.PixelHeight * sf);
                encoder.BitmapTransform.ScaledHeight = (uint)(image.PixelWidth * sf);

                await encoder.FlushAsync();

                var reader  = new DataReader(stream.GetInputStreamAt(0));
                var byteArr = new byte[stream.Size];
                await reader.LoadAsync((uint)stream.Size);

                reader.ReadBytes(byteArr);
                return(byteArr);
            }
        }
Ejemplo n.º 10
0
        public async Task <Dictionary <uint, byte[]> > LoadOverlayAsync()
        {
            var result = new Dictionary <uint, byte[]>();

            if (This.Overlay != null)
            {
                using (var stream = new InMemoryRandomAccessStream())
                {
                    await stream.WriteAsync(This.Overlay.AsBuffer());

                    using (var reader = new DataReader(stream.GetInputStreamAt(0)))
                    {
                        await reader.LoadAsync((uint)stream.Size);

                        while (0 < reader.UnconsumedBufferLength)
                        {
                            var index   = reader.ReadUInt32();
                            var length  = reader.ReadUInt32();
                            var content = reader.ReadBuffer(length);
                            result[index] = content.ToArray();
                        }
                    }
                }
            }
            return(result);
        }
Ejemplo n.º 11
0
        public async Task <string> UnprotectStringAsync(string protectedString)
        {
            var provider = this.GetDataProtectionProvider();

            IBuffer buffUnprotectedData;

            using (InMemoryRandomAccessStream unprotectedData = new InMemoryRandomAccessStream())
                using (InMemoryRandomAccessStream inputData = new InMemoryRandomAccessStream())
                {
                    IOutputStream outputStream = inputData.GetOutputStreamAt(0);
                    using (DataWriter writer = new DataWriter(outputStream))
                    {
                        writer.WriteBuffer(Convert.FromBase64String(protectedString).AsBuffer());
                        await writer.StoreAsync();

                        await outputStream.FlushAsync();
                    }

                    IInputStream source = inputData.GetInputStreamAt(0);

                    IOutputStream dest = unprotectedData.GetOutputStreamAt(0);
                    await provider.UnprotectStreamAsync(source, dest);

                    await dest.FlushAsync();

                    using (DataReader reader = new DataReader(unprotectedData.GetInputStreamAt(0)))
                    {
                        await reader.LoadAsync((uint)unprotectedData.Size);

                        buffUnprotectedData = reader.ReadBuffer((uint)unprotectedData.Size);
                    }
                }

            return(CryptographicBuffer.ConvertBinaryToString(Encoding, buffUnprotectedData));
        }
Ejemplo n.º 12
0
        // 根据当前请求的 uri 返回对应的内容流
        private async Task <IInputStream> GetContent(Uri uri)
        {
            string path           = uri.AbsolutePath;
            string responseString = "";

            switch (path)
            {
            case "/Controls/WebViewDemo/demo4.html":
                StorageFile fileRead = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx://" + path, UriKind.Absolute));

                return(await fileRead.OpenAsync(FileAccessMode.Read));

            case "/Controls/WebViewDemo/css.css":
                responseString = "b { color: red; }";
                break;

            default:
                break;
            }

            // string 转 IInputStream
            IBuffer buffer = CryptographicBuffer.ConvertStringToBinary(responseString, BinaryStringEncoding.Utf8);
            var     stream = new InMemoryRandomAccessStream();
            await stream.WriteAsync(buffer);

            return(stream.GetInputStreamAt(0));
        }
            /// <summary>
            /// Helper that produces the contents corresponding to a Uri.
            /// Uses the C# await pattern to coordinate async operations.
            /// </summary>
            /// <param name="uri"></param>
            /// <returns></returns>
            private async Task <IInputStream> GetContentAsync(Uri uri)
            {
                string path = uri.AbsolutePath;
                string contents;

                switch (path)
                {
                case "/default.html":
                    contents = await MainPage.LoadStringFromPackageFileAsync("stream_example.html");

                    contents = contents.Replace("%", Windows.ApplicationModel.Package.Current.Id.Name);
                    break;

                case "/stream.css":
                    contents = "p { color: blue; }";
                    break;

                default:
                    throw new Exception($"Could not resolve URI \"{uri}\"");
                }

                // Convert the string to a stream.
                IBuffer buffer = CryptographicBuffer.ConvertStringToBinary(contents, BinaryStringEncoding.Utf8);
                var     stream = new InMemoryRandomAccessStream();
                await stream.WriteAsync(buffer);

                return(stream.GetInputStreamAt(0));
            }
Ejemplo n.º 14
0
        /// <summary>
        /// Compresses the content and returns it as an input stream.
        /// </summary>
        /// <returns>A <see cref="IInputStream"/> implementation containing the compresssed data.</returns>
        public IAsyncOperationWithProgress <IInputStream, ulong> ReadAsInputStreamAsync()
        {
            return(AsyncInfo.Run <IInputStream, ulong>(async(cancellationToken, progress) =>
            {
                await BufferAllAsync().AsTask().ConfigureAwait(false);

                var randomAccessStream = new InMemoryRandomAccessStream();
                try
                {
                    using (var writer = new DataWriter(randomAccessStream))
                    {
                        writer.WriteBuffer(bufferedData);

                        uint bytesStored = await writer.StoreAsync().AsTask(cancellationToken);

                        // Make sure that the DataWriter destructor does not close the stream.
                        writer.DetachStream();

                        // Report progress.
                        progress.Report(randomAccessStream.Size);

                        return randomAccessStream.GetInputStreamAt(0);
                    }
                }
                catch
                {
                    randomAccessStream?.Dispose();
                    throw;
                }
            }));
        }
Ejemplo n.º 15
0
        /// <summary>
        /// Helper that cracks the path and resolves the Uri
        /// Uses the C# await pattern to coordinate async operations
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        private async Task <IInputStream> getContent(string path)
        {
            ChmFile obj;

            if (!_chmFile.TryGetTarget(out obj))
            {
                throw new Exception();
            }
            byte[] data = await obj.GetData(path);

            if (data == null || data.Length == 0)
            {
                throw new Exception();
            }
            using (var memoryStream = new InMemoryRandomAccessStream())
            {
                using (var dataWriter = new DataWriter(memoryStream))
                {
                    dataWriter.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8;
                    dataWriter.ByteOrder       = ByteOrder.LittleEndian;
                    dataWriter.WriteBytes(data);
                    if (IsHtml(path))
                    {
                        dataWriter.WriteBytes(GetInjectedContent());
                    }
                    await dataWriter.StoreAsync();

                    await dataWriter.FlushAsync();

                    dataWriter.DetachStream();
                }
                return(memoryStream.GetInputStreamAt(0));
            }
        }
Ejemplo n.º 16
0
            private async Task <IInputStream> GetInputStreamFromIOStream(Stream stream, long fileSize)
            {
                try
                {
                    using (BinaryReader binReader = new BinaryReader(stream))
                    {
                        byte[] byteArr = binReader.ReadBytes((int)fileSize);

                        using (var iMS = new InMemoryRandomAccessStream())
                        {
                            var imsOutputStream = iMS.GetOutputStreamAt(0);
                            using (DataWriter dataWriter = new DataWriter(imsOutputStream))
                            {
                                dataWriter.WriteBytes(byteArr);

                                await dataWriter.StoreAsync();

                                await imsOutputStream.FlushAsync();

                                return(iMS.GetInputStreamAt(0));
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    PlatformAdapter.SendToCustomLogger(ex, LoggingLevel.Error);
                    return(null);
                }
            }
Ejemplo n.º 17
0
        private async void ProtectStreamAsync_Click(object sender, RoutedEventArgs e)
        {
            string outputStr = "";

            Byte[] byteStream = { 1, 2, 3, 4, 5 };

            InMemoryRandomAccessStream randomAccessStream = new InMemoryRandomAccessStream();
            IOutputStream outputStream = randomAccessStream.GetOutputStreamAt(0);
            var           writer       = new DataWriter(outputStream);

            writer.WriteBytes(byteStream);
            await writer.StoreAsync();

            IInputStream source = randomAccessStream.GetInputStreamAt(0);

            m_protectedStream = new InMemoryRandomAccessStream();
            IOutputStream destination = m_protectedStream.GetOutputStreamAt(0);

            await DataProtectionManager.ProtectStreamAsync(source, Scenario1.m_enterpriseId, destination);

            var reader = new DataReader(m_protectedStream.GetInputStreamAt(0));
            await reader.LoadAsync((uint)m_protectedStream.Size);

            IBuffer protectedStreamBuffer = reader.ReadBuffer((uint)m_protectedStream.Size);

            outputStr += "\n Protected Stream buffer:" + CryptographicBuffer.EncodeToHexString(protectedStreamBuffer);

            rootPage.NotifyUser(outputStr, NotifyType.StatusMessage);
        }
Ejemplo n.º 18
0
        private async void setimg()
        {
            try
            {
                System.Xml.Linq.XDocument xmlDoc  = XDocument.Load("http://www.bing.com/HPImageArchive.aspx?format=xml&idx=0&n=1&mkt=en-US");
                IEnumerable <string>      strTest = from node in xmlDoc.Descendants("url") select node.Value;
                string strURL       = "http://www.bing.com" + strTest.First();
                Uri    source       = new Uri(strURL);
                var    bitmapImage  = new BitmapImage();
                var    httpClient   = new HttpClient();
                var    httpResponse = await httpClient.GetAsync(source);

                byte[] b = await httpResponse.Content.ReadAsByteArrayAsync();

                using (var stream = new InMemoryRandomAccessStream())
                {
                    using (DataWriter dw = new DataWriter(stream))
                    {
                        dw.WriteBytes(b);
                        await dw.StoreAsync();

                        stream.Seek(0);
                        bitmapImage.SetSource(stream);
                        Image1.Source = bitmapImage;
                        var storageFile = await KnownFolders.PicturesLibrary.CreateFileAsync("CGPA_Bing.jpg", CreationCollisionOption.ReplaceExisting);

                        using (var storageStream = await storageFile.OpenAsync(FileAccessMode.ReadWrite))
                        {
                            await RandomAccessStream.CopyAndCloseAsync(stream.GetInputStreamAt(0), storageStream.GetOutputStreamAt(0));
                        }
                    }
                }
            }
            catch (Exception) { readimg(); }
        }
Ejemplo n.º 19
0
        //public async Task OpenRemote(string pdfUrl) {
        //    var client = new System.Net.Http.HttpClient();
        //    using(var stream = await client.GetStreamAsync(pdfUrl)) {
        //        using(var memStream = new MemoryStream()) {
        //            await stream.CopyToAsync(memStream);
        //            memStream.Position = 0;
        //            _doc = await PdfDocument.LoadFromStreamAsync(memStream.AsRandomAccessStream());
        //        }
        //    }
        //}
        #endregion

        public async Task TakeAShot(PdfDocument doc, string name)
        {
            var fld = ApplicationData.Current.LocalFolder;

            if (!name.Contains(".pdf"))
            {
                name += ".pdf";
            }
            try {
                await fld.GetFileAsync(name + ".jpg");
            }
            catch (FileNotFoundException) {
                var r = new PdfPageRenderOptions {
                    DestinationHeight = 190, DestinationWidth = 160
                };
                using (var stream = new InMemoryRandomAccessStream()) {
                    try {
                        await doc.GetPage(0).RenderToStreamAsync(stream, r);

                        var fll = await fld.CreateFileAsync(name + ".jpg", CreationCollisionOption.ReplaceExisting);

                        using (var fs = await fll.OpenAsync(FileAccessMode.ReadWrite)) {
                            await RandomAccessStream.CopyAndCloseAsync(stream.GetInputStreamAt(0), fs.GetOutputStreamAt(0));
                        }
                    }
                    catch {
                        Helper.GarbageCollector();
                    }
                }
            }
        }
        public async Task <byte[]> Decrypt(byte[] encryptedBytes)
        {
            var provider = new DataProtectionProvider();

            var encryptedContentBuffer   = CryptographicBuffer.CreateFromByteArray(encryptedBytes);
            var contentInputStream       = new InMemoryRandomAccessStream();
            var unprotectedContentStream = new InMemoryRandomAccessStream();

            IOutputStream outputStream = contentInputStream.GetOutputStreamAt(0);
            var           dataWriter   = new DataWriter(outputStream);

            dataWriter.WriteBuffer(encryptedContentBuffer);
            await dataWriter.StoreAsync();

            await dataWriter.FlushAsync();

            IInputStream decodingInputStream = contentInputStream.GetInputStreamAt(0);

            IOutputStream protectedOutputStream = unprotectedContentStream.GetOutputStreamAt(0);
            await provider.UnprotectStreamAsync(decodingInputStream, protectedOutputStream);

            await protectedOutputStream.FlushAsync();

            DataReader reader2 = new DataReader(unprotectedContentStream.GetInputStreamAt(0));
            await reader2.LoadAsync((uint)unprotectedContentStream.Size);

            IBuffer unprotectedBuffer = reader2.ReadBuffer((uint)unprotectedContentStream.Size);

            return(unprotectedBuffer.ToArray());
        }
Ejemplo n.º 21
0
        public byte[] DrawStrokeOnImageBackground(IReadOnlyList <InkStroke> strokes, byte[] backgroundImageBuffer)
        {
            var stmbuffer = new InMemoryRandomAccessStream();

            stmbuffer.AsStreamForWrite().AsOutputStream().WriteAsync(backgroundImageBuffer.AsBuffer()).AsTask().Wait();

            CanvasDevice device = CanvasDevice.GetSharedDevice();
            var          canbit = CanvasBitmap.LoadAsync(device, stmbuffer, 96).AsTask().Result;


            CanvasRenderTarget renderTarget = new CanvasRenderTarget(device, canbit.SizeInPixels.Width, canbit.SizeInPixels.Height, 96);

            using (var ds = renderTarget.CreateDrawingSession())
            {
                ds.Clear(Colors.Transparent);

                if (backgroundImageBuffer != null)
                {
                    ds.DrawImage(canbit);
                }

                ds.DrawInk(strokes);
            }
            var stm = new InMemoryRandomAccessStream();

            renderTarget.SaveAsync(stm, CanvasBitmapFileFormat.Png).AsTask().Wait();
            var readfrom = stm.GetInputStreamAt(0).AsStreamForRead();
            var ms       = new MemoryStream();

            readfrom.CopyTo(ms);
            var outputBuffer = ms.ToArray();

            return(outputBuffer);
        }
Ejemplo n.º 22
0
        public static async Task <bool> GetIsMakerImageAsync()
        {
            var cmdOutput      = string.Empty;
            var standardOutput = new InMemoryRandomAccessStream();
            var options        = new ProcessLauncherOptions
            {
                StandardOutput = standardOutput
            };
            var output = await ProcessLauncher.RunToCompletionAsync(CommandLineProcesserExe, RegKeyQueryCmdArg, options);

            if (output != null && output.ExitCode == 0)
            {
                using (var outStreamRedirect = standardOutput.GetInputStreamAt(0))
                {
                    using (var dataReader = new DataReader(outStreamRedirect))
                    {
                        uint bytesLoaded = 0;
                        while ((bytesLoaded = await dataReader.LoadAsync(CmdLineBufSize)) > 0)
                        {
                            cmdOutput += dataReader.ReadString(bytesLoaded);
                        }
                    }
                }
                Match match = Regex.Match(cmdOutput, ExpectedResultPattern, RegexOptions.IgnoreCase);
                if (match.Success)
                {
                    return(true);
                }
                else
                {
                    ServiceUtil.LogService.Write("Could not get IsMakerImage. Output: " + cmdOutput);
                }
            }
            return(false);
        }
Ejemplo n.º 23
0
        async void OnCameraPreviewTapped(object sender, TappedRoutedEventArgs e)
        {
            var stream = new InMemoryRandomAccessStream();

            if (isPreviewing)
            {
                await mediaCapture.StopPreviewAsync();

                await mediaCapture.CapturePhotoToStreamAsync(ImageEncodingProperties.CreateJpeg(), stream);

                // transforma em bytes
                var reader = new DataReader(stream.GetInputStreamAt(0));
                var bytes  = new byte[stream.Size];
                await reader.LoadAsync((uint)stream.Size);

                reader.ReadBytes(bytes);

                Xamarin.Forms.DependencyService.Get <ICameraOption>().ImagemCapturada(bytes);

                isPreviewing = false;
            }
            else
            {
                await mediaCapture.StartPreviewAsync();

                isPreviewing = true;
            }
        }
Ejemplo n.º 24
0
        public async Task SaveInkToBase64(InkCanvasControl view, IReadOnlyList <object> commandArgs)
        {
            var inkCanvas = view.FindName("MyInkCanvas") as InkCanvas;

            string base64String = string.Empty;

            CanvasDevice       device       = CanvasDevice.GetSharedDevice();
            CanvasRenderTarget renderTarget = new CanvasRenderTarget(device, (int)inkCanvas.ActualWidth, (int)inkCanvas.ActualHeight, 96);

            using (var ds = renderTarget.CreateDrawingSession())
            {
                ds.Clear(Colors.White);
                ds.DrawInk(inkCanvas.InkPresenter.StrokeContainer.GetStrokes());
            }

            using (InMemoryRandomAccessStream stream = new InMemoryRandomAccessStream())
            {
                await renderTarget.SaveAsync(stream, CanvasBitmapFileFormat.Jpeg);

                var reader = new DataReader(stream.GetInputStreamAt(0));
                await reader.LoadAsync((uint)stream.Size);

                byte[] byteArray = new byte[stream.Size];
                reader.ReadBytes(byteArray);
                base64String = Convert.ToBase64String(byteArray);
            }

            InkSaved?.Invoke(view, base64String);
        }
Ejemplo n.º 25
0
        private async void UnprotectAsyncBuffer_Click(object sender, RoutedEventArgs e)
        {
            string outputStr = "";

            if (m_protectedStream != null)
            {
                IInputStream source = m_protectedStream.GetInputStreamAt(0);
                m_unprotectedStream = new InMemoryRandomAccessStream();
                await DataProtectionManager.UnprotectStreamAsync(source,
                                                                 m_unprotectedStream
                                                                 );

                var unprotectedReader = new DataReader(m_unprotectedStream.GetInputStreamAt(0));
                await unprotectedReader.LoadAsync((uint)m_unprotectedStream.Size);

                IBuffer unprotectedStreamBuffer = unprotectedReader.ReadBuffer((uint)m_unprotectedStream.Size);
                outputStr += "\n UnProtected Stream buffer:" +
                             CryptographicBuffer.EncodeToHexString(unprotectedStreamBuffer);

                rootPage.NotifyUser(outputStr, NotifyType.StatusMessage);
            }
            else
            {
                rootPage.NotifyUser("Please protect a stream to unprotect", NotifyType.ErrorMessage);
            }
        }
Ejemplo n.º 26
0
        private static async Task <bool> DownloadArtistPictureFromDeezer(MusicLibraryViewModel.ArtistItem artist)
        {
            var deezerClient = new DeezerClient();
            var deezerArtist = await deezerClient.GetArtistInfo(artist.Name);

            if (deezerArtist == null)
            {
                return(false);
            }
            if (deezerArtist.Images == null)
            {
                return(false);
            }
            try
            {
                var clientPic = new HttpClient();
                HttpResponseMessage responsePic = await clientPic.GetAsync(deezerArtist.Images.LastOrDefault().Url);

                string uri = responsePic.RequestMessage.RequestUri.AbsoluteUri;
                // A cheap hack to avoid using Deezers default image for bands.
                if (uri.Equals("http://cdn-images.deezer.com/images/artist//400x400-000000-80-0-0.jpg"))
                {
                    return(false);
                }
                byte[] img = await responsePic.Content.ReadAsByteArrayAsync();

                InMemoryRandomAccessStream streamWeb = new InMemoryRandomAccessStream();
                DataWriter writer = new DataWriter(streamWeb.GetOutputStreamAt(0));
                writer.WriteBytes(img);
                await writer.StoreAsync();

                StorageFolder artistPic = await ApplicationData.Current.LocalFolder.CreateFolderAsync("artistPic",
                                                                                                      CreationCollisionOption.OpenIfExists);

                string fileName = artist.Name + "_" + "dPi";
                var    file     = await artistPic.CreateFileAsync(fileName + ".jpg", CreationCollisionOption.OpenIfExists);

                var raStream = await file.OpenAsync(FileAccessMode.ReadWrite);

                using (var thumbnailStream = streamWeb.GetInputStreamAt(0))
                {
                    using (var stream = raStream.GetOutputStreamAt(0))
                    {
                        await RandomAccessStream.CopyAsync(thumbnailStream, stream);
                    }
                }
                StorageFolder appDataFolder           = ApplicationData.Current.LocalFolder;
                string        supposedPictureUriLocal = appDataFolder.Path + "\\artistPic\\" + artist.Name + "_" + "dPi" + ".jpg";
                await DispatchHelper.InvokeAsync(() => artist.Picture = supposedPictureUriLocal);

                return(true);
            }
            catch (Exception)
            {
                Debug.WriteLine("Error getting or saving art from deezer.");
                return(false);
            }
        }
        public async Task <byte[]> Encrypt(byte[] data)
        {
            var provider = new DataProtectionProvider(UseForAllUsers ? _localMachineDescriptor : _localUserDescriptor);

            var contentBuffer          = CryptographicBuffer.CreateFromByteArray(data);
            var contentInputStream     = new InMemoryRandomAccessStream();
            var protectedContentStream = new InMemoryRandomAccessStream();

            //storing data in the stream
            IOutputStream outputStream = contentInputStream.GetOutputStreamAt(0);
            var           dataWriter   = new DataWriter(outputStream);

            dataWriter.WriteBuffer(contentBuffer);
            await dataWriter.StoreAsync();

            await dataWriter.FlushAsync();

            //reopening in input mode
            IInputStream encodingInputStream = contentInputStream.GetInputStreamAt(0);

            IOutputStream protectedOutputStream = protectedContentStream.GetOutputStreamAt(0);
            await provider.ProtectStreamAsync(encodingInputStream, protectedOutputStream);

            await protectedOutputStream.FlushAsync();

            //verify that encryption happened
            var inputReader     = new DataReader(contentInputStream.GetInputStreamAt(0));
            var protectedReader = new DataReader(protectedContentStream.GetInputStreamAt(0));

            await inputReader.LoadAsync((uint)contentInputStream.Size);

            await protectedReader.LoadAsync((uint)protectedContentStream.Size);

            var inputBuffer     = inputReader.ReadBuffer((uint)contentInputStream.Size);
            var protectedBuffer = protectedReader.ReadBuffer((uint)protectedContentStream.Size);

            if (!CryptographicBuffer.Compare(inputBuffer, protectedBuffer))
            {
                return(protectedBuffer.ToArray());
            }
            else
            {
                return(null);
            }
        }
        public void TestWriteToOutputStream()
        {
            var command = new AppInstallRequest(new AppInstallInfo()
            {
                AppxPath = "abc", PackageFamilyName = "def", Dependencies = new List <String>()
                {
                    "ghi", "jkl"
                }
            });
            var blob = command.Serialize();

            var stream = new InMemoryRandomAccessStream();

            blob.WriteToIOutputStreamAsync(stream.GetOutputStreamAt(0)).AsTask().Wait();

            var reader = new DataReader(stream.GetInputStreamAt(0));

            reader.LoadAsync(4).AsTask().Wait();
            var bytes = new byte[4];

            reader.ReadBytes(bytes);
            var size = BitConverter.ToUInt32(bytes, 0);
            // like I said, too brittle:
            //Assert.AreEqual(size, 44U); // this is somewhat brittle.

            var reader2 = new DataReader(stream.GetInputStreamAt(4));

            reader2.LoadAsync(size).AsTask().Wait();
            var bytes2 = new byte[size];

            reader2.ReadBytes(bytes2);

            var blob2 = Blob.CreateFromByteArray(bytes2);

            Assert.AreEqual(blob.Tag, blob2.Tag);

            var command2 = blob2.MakeIRequest() as AppInstallRequest;

            Assert.AreEqual(command2.Tag, DMMessageKind.InstallApp);
            Assert.AreEqual(command2.AppInstallInfo.AppxPath, "abc");
            Assert.AreEqual(command2.AppInstallInfo.PackageFamilyName, "def");
            Assert.AreEqual(command2.AppInstallInfo.Dependencies[0], "ghi");
            Assert.AreEqual(command2.AppInstallInfo.Dependencies[1], "jkl");
        }
Ejemplo n.º 29
0
        public static async Task <ProcessLauncherOutput> RunCommandAsync(string fileName, string args)
        {
            var output = new ProcessLauncherOutput();

            try
            {
                using (var standardOutput = new InMemoryRandomAccessStream())
                    using (var standardError = new InMemoryRandomAccessStream())
                    {
                        var options = new ProcessLauncherOptions
                        {
                            StandardOutput = standardOutput,
                            StandardError  = standardError
                        };

                        var result = await ProcessLauncher.RunToCompletionAsync(
                            fileName,
                            args,
                            options);

                        output.Result = result;

                        using (IInputStream inputStream = standardOutput.GetInputStreamAt(0))
                        {
                            ulong size = standardOutput.Size;

                            using (var dataReader = new DataReader(inputStream))
                            {
                                uint bytesLoaded = await dataReader.LoadAsync((uint)size);

                                output.Output = dataReader.ReadString(bytesLoaded);
                            }
                        }

                        using (IInputStream inputStream = standardError.GetInputStreamAt(0))
                        {
                            ulong size = standardError.Size;

                            using (var dataReader = new DataReader(inputStream))
                            {
                                uint bytesLoaded = await dataReader.LoadAsync((uint)size);

                                output.Error = dataReader.ReadString(bytesLoaded);
                            }
                        }
                    }

                return(output);
            }
            catch (Exception ex)
            {
                ServiceUtil.LogService.WriteException(ex);
            }

            return(null);
        }
Ejemplo n.º 30
0
        private async Task RunProcess()
        {
            var options        = new ProcessLauncherOptions();
            var standardOutput = new InMemoryRandomAccessStream();
            var standardError  = new InMemoryRandomAccessStream();

            options.StandardOutput = standardOutput;
            options.StandardError  = standardError;

            await CoreWindow.GetForCurrentThread().Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async() =>
            {
                try
                {
                    var result = await ProcessLauncher.RunToCompletionAsync(cmd.Text, args.Text == null ? string.Empty : args.Text, options);

                    ProcessExitCode.Text += "Process Exit Code: " + result.ExitCode;

                    using (var outStreamRedirect = standardOutput.GetInputStreamAt(0))
                    {
                        var size = standardOutput.Size;
                        using (var dataReader = new DataReader(outStreamRedirect))
                        {
                            var bytesLoaded     = await dataReader.LoadAsync((uint)size);
                            var stringRead      = dataReader.ReadString(bytesLoaded);
                            StdOutputText.Text += stringRead;
                        }
                    }

                    using (var errStreamRedirect = standardError.GetInputStreamAt(0))
                    {
                        using (var dataReader = new DataReader(errStreamRedirect))
                        {
                            var size           = standardError.Size;
                            var bytesLoaded    = await dataReader.LoadAsync((uint)size);
                            var stringRead     = dataReader.ReadString(bytesLoaded);
                            StdErrorText.Text += stringRead;
                        }
                    }
                }
                catch (UnauthorizedAccessException uex)
                {
                    StdErrorText.Text += "Exception Thrown: " + uex.Message + "\n";
                    StdErrorText.Text += "\nMake sure you're allowed to run the specified exe; either\n" +
                                         "\t1) Add the exe to the AppX package, or\n" +
                                         "\t2) Add the absolute path of the exe to the allow list:\n" +
                                         "\t\tHKLM\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\EmbeddedMode\\ProcessLauncherAllowedExecutableFilesList.\n\n" +
                                         "Also, make sure the <iot:Capability Name=\"systemManagement\" /> has been added to the AppX manifest capabilities.\n";
                }
                catch (Exception ex)
                {
                    StdErrorText.Text += "Exception Thrown:" + ex.Message + "\n";
                    StdErrorText.Text += ex.StackTrace + "\n";
                }
            });
        }