GetInputStreamAt() public method

public GetInputStreamAt ( [ position ) : IInputStream
position [
return IInputStream
Example #1
0
 public IInputStream GetInputStreamAt(ulong position)
 {
     System.Diagnostics.Debug.WriteLine("GetInputStreamAt: " + position.ToString());
     if (internalStream.Size > position)
     {
         return(internalStream.GetInputStreamAt(position));
     }
     return(null);
 }
		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;
		}
Example #3
0
 private static async Task<IInputStream> GetStreamForByteArray(string content2)
 {
     var ras = new InMemoryRandomAccessStream();
     var datawriter = new DataWriter(ras);
     datawriter.WriteString(content2);
     //datawriter.WriteBytes(content2);
     await datawriter.StoreAsync();
     await datawriter.FlushAsync();
     return ras.GetInputStreamAt(0);
 }
Example #4
0
        public async Task<string> Decrypt(IBuffer buffProtected, BinaryStringEncoding encoding)
        {
            try
            {
                // Create a DataProtectionProvider object.
                DataProtectionProvider Provider = new DataProtectionProvider();

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

                // Create a random access stream to contain the decrypted data.
                InMemoryRandomAccessStream unprotectedData = new InMemoryRandomAccessStream();

                // Retrieve an IOutputStream object and fill it with the input (encrypted) data.
                IOutputStream outputStream = inputData.GetOutputStreamAt(0);
                DataWriter writer = new DataWriter(outputStream);
                writer.WriteBuffer(buffProtected);
                await writer.StoreAsync();
                await outputStream.FlushAsync();

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

                // Retrieve an IOutputStream object and fill it with decrypted data.
                IOutputStream dest = unprotectedData.GetOutputStreamAt(0);
                await Provider.UnprotectStreamAsync(source, dest);
                await dest.FlushAsync();

                // Write the decrypted data to an IBuffer object.
                DataReader reader2 = new DataReader(unprotectedData.GetInputStreamAt(0));
                await reader2.LoadAsync((uint)unprotectedData.Size);
                IBuffer buffUnprotectedData = reader2.ReadBuffer((uint)unprotectedData.Size);

                // Convert the IBuffer object to a string using the same encoding that was
                // used previously to conver the plaintext string (before encryption) to an
                // IBuffer object.
                String strUnprotected = CryptographicBuffer.ConvertBinaryToString(encoding, buffUnprotectedData);

                // Return the decrypted data.
                return strUnprotected;
            }
            catch (Exception ex)
            {
                App.Telemetry.TrackException(ex);
                return "";

            }

        }
Example #5
0
        public async Task<IBuffer> Encrypt(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;
        }
        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 byte[] DrawStrokeOnSolidColorBackground(IReadOnlyList<InkStroke> strokes, int width, int height, Color color )
		{														 
			CanvasDevice device = CanvasDevice.GetSharedDevice();
			CanvasRenderTarget renderTarget = new CanvasRenderTarget(device, width, height, 96);

			using (var ds = renderTarget.CreateDrawingSession())
			{
				ds.Clear(color);
				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;
		}
Example #8
0
        public async Task<bool> downloadImage(string url, string filename)
        {
            Uri uri = new Uri(url);
            //string fname = member_id + ".png";
            var bitmapImage = new BitmapImage();
            var httpClient = new HttpClient();
            var httpResponse = await httpClient.GetAsync(uri);
            byte[] b = await httpResponse.Content.ReadAsByteArrayAsync();
            try
            {
                // create a new in memory stream and datawriter
                using (var stream = new InMemoryRandomAccessStream())
                {
                    using (DataWriter dw = new DataWriter(stream))
                    {
                        // write the raw bytes and store
                        dw.WriteBytes(b);
                        await dw.StoreAsync();

                        // set the image source
                        stream.Seek(0);
                        bitmapImage.SetSource(stream);

                        var storageFile = await ApplicationData.Current.LocalFolder.CreateFileAsync(
                            filename,
                            CreationCollisionOption.OpenIfExists);

                        using (var storageStream = await storageFile.OpenAsync(FileAccessMode.ReadWrite))
                        {
                            await RandomAccessStream.CopyAndCloseAsync(stream.GetInputStreamAt(0), storageStream.GetOutputStreamAt(0));
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Exception in downloading image : " + ex);
                return false;
            }

            return true;
        }
Example #9
0
        public static async Task<byte[]> CropImage(byte[] stream, Crop crop)
        {
            byte[] byteArray = null;

            var imageStream = new MemoryStream(stream);

            var fileStream = imageStream.AsRandomAccessStream();
            BitmapDecoder decoder = await BitmapDecoder.CreateAsync(fileStream);
            InMemoryRandomAccessStream ras = new InMemoryRandomAccessStream();
            BitmapEncoder enc = await BitmapEncoder.CreateForTranscodingAsync(ras, decoder);

            BitmapBounds bounds = new BitmapBounds();
            bounds.Height = (uint)crop.Height;
            bounds.Width = (uint)crop.Width;
            bounds.X = (uint)crop.X;
            bounds.Y = (uint)crop.Y;

            enc.BitmapTransform.Bounds = bounds;
            enc.BitmapTransform.InterpolationMode = BitmapInterpolationMode.Linear;
            enc.IsThumbnailGenerated = false;

            try
            {
                await enc.FlushAsync();
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Error croping image", ex);
            }

            byteArray = new byte[ras.Size];
            DataReader dataReader = new DataReader(ras.GetInputStreamAt(0));
            await dataReader.LoadAsync((uint)ras.Size);
            dataReader.ReadBytes(byteArray);

            return byteArray;
        }
        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);
            }
        }
Example #11
0
        /// <summary>
        /// This is the click handler for the 'RunSample' button.  It is responsible for executing the sample code.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void RunSample_Click(object sender, RoutedEventArgs e)
        {
            Certificate selectedCertificate = null;
            string verifyselection = VerifyCert.SelectionBoxItem.ToString();

            //get the selected certificate
            if (CertificateList.SelectedIndex >= 0 && CertificateList.SelectedIndex < certList.Count)
            {
                selectedCertificate = certList[CertificateList.SelectedIndex];
            }

            if (selectedCertificate == null)
            {
                ViewCertText.Text = "Please select a certificate first.";
                return;
            }

            // a certificate was selected, do the desired operation
            if (verifyselection.Equals("Verify Certificate"))
            {
                //Build the chain
                var chain = await selectedCertificate.BuildChainAsync(null, null);
                //Validate the chain
                var result = chain.Validate();
                verifytext = "\n Verification Result :" + result.ToString();
               
            }
            else if (verifyselection.Equals("Sign/Verify using certificate key"))
            {
                // get private key
                CryptographicKey keyPair = await PersistedKeyProvider.OpenKeyPairFromCertificateAsync(selectedCertificate, HashAlgorithmNames.Sha1, CryptographicPadding.RsaPkcs1V15);
                String cookie = "Some Data to sign";
                IBuffer Data = CryptographicBuffer.ConvertStringToBinary(cookie, BinaryStringEncoding.Utf16BE);

                try
                {
                    //sign the data by using the key
                    IBuffer Signed = CryptographicEngine.Sign(keyPair, Data);
                    bool bresult = CryptographicEngine.VerifySignature(keyPair, Data, Signed);

                    if (bresult == true)
                    {
                        verifytext = "\n Verification Result : Successfully signed and verified signature";
                    }
                    else
                    {
                        verifytext = "\n Verification Result : Verify Signature Failed";
                    }
                }
                catch (Exception exp)
                {
                    verifytext = "\n Verification Failed. Exception Occurred :" + exp.Message;
                }
            }
            else if (verifyselection.Equals("Sign/Verify using CMS based format"))
            {
                IInputStream pdfInputstream;
                InMemoryRandomAccessStream originalData = new InMemoryRandomAccessStream();
                //Populate the new memory stream              
                pdfInputstream = originalData.GetInputStreamAt(0);
                CmsSignerInfo signer = new CmsSignerInfo();
                signer.Certificate = selectedCertificate;
                signer.HashAlgorithmName = HashAlgorithmNames.Sha1;
                IList<CmsSignerInfo> signers = new List<CmsSignerInfo>();
               
                signers.Add(signer);
                try
                {
                   IBuffer signature = await CmsDetachedSignature.GenerateSignatureAsync(pdfInputstream, signers, null);
                   CmsDetachedSignature cmsSignedData = new CmsDetachedSignature(signature);
                   pdfInputstream = originalData.GetInputStreamAt(0);
                   SignatureValidationResult validationResult = await cmsSignedData.VerifySignatureAsync(pdfInputstream);
                   if (SignatureValidationResult.Success == validationResult)
                    {
                        verifytext = "\n Verification Result : Successfully signed and verified Signature";
                    }
                   else
                    {
                        verifytext = "\n Verification Result : Verify Signature using CMS based format Failed";
                    }
                }
                catch (Exception exp)
                {
                    verifytext = "\n Verification Failed. Exception Occurred :" + exp.Message;
                }

            }
            else if(verifyselection.Equals("Get certificate and show details"))
            {
                DisplayCertificate(selectedCertificate);
            }
            
            ViewCertText.Text += verifytext;
            verifytext = string.Empty;
        }
        public async Task UsingDataWriter()
        {
            var inMem = new InMemoryRandomAccessStream();

            var datawriter = new DataWriter(inMem);
            var starterBytes = CryptographicBuffer.GenerateRandom(32).AsBytes();
            var mStream = CryptographicBuffer.GenerateRandom(1024 * 1024).AsBytes();

            MemoryStream outStream = new System.IO.MemoryStream();
            var tinyStream = ConfigureStream(outStream, PwCompressionAlgorithm.GZip, true);
            await tinyStream.WriteAsync(starterBytes, 0, starterBytes.Length);
            await tinyStream.WriteAsync(mStream, 0, mStream.Length);
            tinyStream.Dispose();
            byte[] bb = outStream.ToArray();
            var source = bb.AsBuffer();
            var aesKey = CryptographicBuffer.GenerateRandom(32);
            var iv = CryptographicBuffer.GenerateRandom(16);
            var encrypted = EncryptDatabase(source, aesKey, iv);

            CollectionAssert.AreNotEqual(mStream, encrypted.AsBytes());

             datawriter.WriteBuffer(encrypted);
             await datawriter.StoreAsync();

            datawriter.DetachStream();
            datawriter.Dispose();
             var i = inMem.GetInputStreamAt(0);
             var datareader = new DataReader(i);
             datareader.ByteOrder = ByteOrder.LittleEndian;
            await datareader.LoadAsync((uint)inMem.Size);
             var fromStrea = datareader.ReadBuffer(datareader.UnconsumedBufferLength);

             var decryped = DecryptDatabase(fromStrea, aesKey, iv);

             Stream bigStream = ConfigureStream(new MemoryStream(decryped.AsBytes()), PwCompressionAlgorithm.GZip, false);
             System.IO.MemoryStream bigStreamOut = new System.IO.MemoryStream();
             bigStream.CopyTo(bigStreamOut);

            var buffer1 = CryptographicBuffer.CreateFromByteArray(bigStreamOut.ToArray());
            var reader = DataReader.FromBuffer(buffer1);
            var x = reader.ReadBuffer(32).AsBytes();
            CollectionAssert.AreEqual(starterBytes, x);
        }
		private static async Task<ReceivedShareItem> FetchDataFromPackageViewAsync(DataPackageView packageView)
		{
			var rval = new ReceivedShareItem()
			{
				Title = packageView.Properties.Title,
				Description = packageView.Properties.Description,
				PackageFamilyName = packageView.Properties.PackageFamilyName,
				ContentSourceWebLink = packageView.Properties.ContentSourceWebLink,
				ContentSourceApplicationLink = packageView.Properties.ContentSourceApplicationLink,
				LogoBackgroundColor = packageView.Properties.LogoBackgroundColor,

			};
			if (packageView.Properties.Square30x30Logo != null)
			{
				using (var logoStream = await packageView.Properties.Square30x30Logo.OpenReadAsync())
				{
					var logo = new MemoryStream();
					await logoStream.AsStreamForRead().CopyToAsync(logo);
					logo.Position = 0;
					var str = Convert.ToBase64String(logo.ToArray());
					//rval.Square30x30LogoBase64 = Convert.ToBase64String(logo.ToArray());
					rval.Square30x30Logo = new Models.MemoryStreamBase64Item { Base64String = str };


				}
			}
			if (packageView.Properties.Thumbnail != null)
			{
				using (var thumbnailStream = await packageView.Properties.Thumbnail.OpenReadAsync())
				{
					var thumbnail = new MemoryStream();
					await thumbnailStream.AsStreamForRead().CopyToAsync(thumbnail);
					thumbnail.Position = 0;
					var str = Convert.ToBase64String(thumbnail.ToArray());
					rval.Thumbnail = new Models.MemoryStreamBase64Item { Base64String = str };
				}
			}

			if (packageView.Contains(StandardDataFormats.WebLink))
			{
				try
				{
					var link = new WebLinkShareItem
					{
						WebLink = await packageView.GetWebLinkAsync()
					};

					rval.AvialableShareItems.Add(link);
				}
				catch (Exception ex)
				{
					//NotifyUserBackgroundThread("Failed GetWebLinkAsync - " + ex.Message, NotifyType.ErrorMessage);
				}
			}
			if (packageView.Contains(StandardDataFormats.ApplicationLink))
			{
				try
				{
					var sharedApplicationLink = new ApplicationLinkShareItem
					{
						ApplicationLink = await packageView.GetApplicationLinkAsync()
					};
					rval.AvialableShareItems.Add(sharedApplicationLink);

				}
				catch (Exception ex)
				{
					//NotifyUserBackgroundThread("Failed GetApplicationLinkAsync - " + ex.Message, NotifyType.ErrorMessage);
				}
			}
			if (packageView.Contains(StandardDataFormats.Text))
			{
				try
				{
					var sharedText = new TextShareItem { Text = await packageView.GetTextAsync() };
					rval.AvialableShareItems.Add(sharedText);
					rval.Text = await packageView.GetTextAsync();
					//rval.GetValueContainer(x => x.Text)
					//   	.GetNullObservable()
					//	.Subscribe(e => sharedText.Text = rval.Text)
					//	.DisposeWith(rval);
					sharedText.GetValueContainer(x => x.Text)
						.GetNullObservable()
						.Subscribe(e => rval.Text = sharedText.Text)
						.DisposeWith(rval);
				}
				catch (Exception ex)
				{
					//NotifyUserBackgroundThread("Failed GetTextAsync - " + ex.Message, NotifyType.ErrorMessage);
				}
			}
			if (packageView.Contains(StandardDataFormats.StorageItems))
			{
				try
				{
					var files = await packageView.GetStorageItemsAsync();
					var sharedStorageItem = new FilesShareItem
					{
						StorageFiles = new ObservableCollection<FileItem>()
						//StorageItems = 
					};
					foreach (StorageFile sf in files)
					{
						var guidString = Guid.NewGuid().ToString();
						StorageApplicationPermissions.FutureAccessList.AddOrReplace(guidString, sf, sf.Name);
						var ts = await sf.GetScaledImageAsThumbnailAsync(Windows.Storage.FileProperties.ThumbnailMode.VideosView);
						var tmbs = new MemoryStream();
						await ts.AsStreamForRead().CopyToAsync(tmbs);
						var file = new FileItem
						{
							AccessToken = guidString,
							ContentType = sf.ContentType,
							FileName = sf.DisplayName,
							PossiblePath = sf.Path,
							Thumbnail = new Models.MemoryStreamBase64Item(tmbs.ToArray())
						};

						sharedStorageItem.StorageFiles.Add(file);

					}
					//StorageApplicationPermissions.FutureAccessList.AddOrReplace()

					rval.AvialableShareItems.Add(sharedStorageItem);
				}
				catch (Exception ex)
				{
					//NotifyUserBackgroundThread("Failed GetStorageItemsAsync - " + ex.Message, NotifyType.ErrorMessage);
				}
			}
			//if (packageView.Contains(dataFormatName))
			//{
			//	try
			//	{
			//		this.sharedCustomData = await packageView.GetTextAsync(dataFormatName);
			//	}
			//	catch (Exception ex)
			//	{
			//		//NotifyUserBackgroundThread("Failed GetTextAsync(" + dataFormatName + ") - " + ex.Message, NotifyType.ErrorMessage);
			//	}
			//}
			if (packageView.Contains(StandardDataFormats.Html))
			{
				var sharedHtmlFormatItem = new HtmlShareItem();
				var sharedHtmlFormat = string.Empty;
				try
				{
					sharedHtmlFormat = await packageView.GetHtmlFormatAsync();
					//sharedHtmlFormatItem.HtmlFormat = sharedHtmlFormat;
					sharedHtmlFormatItem.HtmlFragment = HtmlFormatHelper.GetStaticFragment(sharedHtmlFormat);
				}
				catch (Exception ex)
				{
					//NotifyUserBackgroundThread("Failed GetHtmlFormatAsync - " + ex.Message, NotifyType.ErrorMessage);
				}
				//try
				//{
				//	var sharedResourceMap = await packageView.GetResourceMapAsync();
				//}
				//catch (Exception ex)
				//{
				//	//NotifyUserBackgroundThread("Failed GetResourceMapAsync - " + ex.Message, NotifyType.ErrorMessage);
				//}

				//if (packageView.Contains(StandardDataFormats.WebLink))
				//{
				//	try
				//	{
				//		sharedHtmlFormatItem.WebLink = await packageView.GetWebLinkAsync();
				//	}
				//	catch (Exception ex)
				//	{
				//		//NotifyUserBackgroundThread("Failed GetWebLinkAsync - " + ex.Message, NotifyType.ErrorMessage);
				//	}
				//}
				rval.AvialableShareItems.Add(sharedHtmlFormatItem);

			}
			if (packageView.Contains(StandardDataFormats.Bitmap))
			{
				try
				{
					var fi = await packageView.GetBitmapAsync();
					using (var imgFileStream = await fi.OpenReadAsync())
					{
						var saveTargetStream = new InMemoryRandomAccessStream();

						var bitmapSourceStream = imgFileStream;

						await ServiceLocator
								 .Instance
								 .Resolve<IImageConvertService>()
								 .ConverterBitmapToTargetStreamAsync(bitmapSourceStream, saveTargetStream);

						saveTargetStream.Seek(0);
						var sr = saveTargetStream.GetInputStreamAt(0);
						var source = sr.AsStreamForRead();

						var ms = new MemoryStream();
						await source.CopyToAsync(ms);

						var sharedBitmapStreamRef = new DelayRenderedImageShareItem
						{
							SelectedImage = new Models.MemoryStreamBase64Item(ms.ToArray())
						};

						rval.AvialableShareItems.Add(sharedBitmapStreamRef);

					}
				}
				catch (Exception ex)
				{
					//NotifyUserBackgroundThread("Failed GetBitmapAsync - " + ex.Message, NotifyType.ErrorMessage);
				}
			}

			//foreach (var item in rval.AvialableShareItems)
			//{
			//	//item.ContentSourceApplicationLink = rval.ContentSourceApplicationLink;
			//	//item.ContentSourceWebLink = rval.ContentSourceWebLink;
			//	//item.DefaultFailedDisplayText = rval.DefaultFailedDisplayText;
			//	//item.Description = rval.Description;
			//	//item.Title = rval.Title;
			//}
			return rval;
		}
Example #14
0
        async void CaptureImage_Click(object sender, RoutedEventArgs e)
        {
            // hide capture button
            this.cameraButton.Visibility = Visibility.Collapsed;

            // show progress bar
            this.processing.IsActive = true;

            //mediaCapture.SetRecordRotation(VideoRotation.None);
            ImageEncodingProperties imgFormat = ImageEncodingProperties.CreateJpeg();

            // find the time and date now
            DateTime dt = System.DateTime.Now;
            String date = dt.ToString("dd_MM_yyyy_H_mm_ss");

            // create storage file in local app storage, and name file according to date
            StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync(
                "RiverWatchImage_"+date+".jpg",
                CreationCollisionOption.ReplaceExisting);

            // take photo
            await mediaCapture.CapturePhotoToStorageFileAsync(imgFormat, file);

            // Get photo as a BitmapImage
            Uri imageURI = new Uri(file.Path);

            //rotate image back to correct orientation if required
            if (currentAngle != 90) {

                IRandomAccessStream originalImage = await file.OpenAsync(FileAccessMode.ReadWrite);
                BitmapDecoder imageDecoder = await BitmapDecoder.CreateAsync(originalImage);
                var imageStream = new InMemoryRandomAccessStream();
                BitmapEncoder imageEncoder = await BitmapEncoder.CreateForTranscodingAsync(imageStream, imageDecoder);

                //set rotation angle
                switch (currentAngle) {
                    case 0:
                        imageEncoder.BitmapTransform.Rotation = BitmapRotation.Clockwise90Degrees;
                        break;
                    case 180:
                        imageEncoder.BitmapTransform.Rotation = BitmapRotation.Clockwise270Degrees;
                        break;
                    case 270:
                        imageEncoder.BitmapTransform.Rotation = BitmapRotation.Clockwise180Degrees;
                        break;
                }

                await imageEncoder.FlushAsync();

                BitmapImage bitmapImage = new BitmapImage();
                await bitmapImage.SetSourceAsync(imageStream);

                using (var outputStream = originalImage.GetOutputStreamAt(0)) {
                    using (var inputStream = imageStream.GetInputStreamAt(0)) {
                        IBuffer storageFileBuffer = new byte[imageStream.Size].AsBuffer();
                        await inputStream.ReadAsync(storageFileBuffer, storageFileBuffer.Length, InputStreamOptions.None);
                        await outputStream.WriteAsync(storageFileBuffer);
                    }
                }

            }

            // once finished, hide progress bar
            this.processing.IsActive = false;

            Frame.Navigate(typeof(PollutionReportPage),file);
        }
Example #15
0
        private async Task<bool> SaveImage(int id, String folderName, byte[] img)
        {
            String fileName = String.Format("{0}.jpg", id);
            try
            {
                using (var streamWeb = new InMemoryRandomAccessStream())
                {
                    using (var writer = new DataWriter(streamWeb.GetOutputStreamAt(0)))
                    {
                        writer.WriteBytes(img);
                        await writer.StoreAsync();
                        var albumPic = await ApplicationData.Current.LocalFolder.CreateFolderAsync(folderName, CreationCollisionOption.OpenIfExists);

                        var file = await albumPic.CreateFileAsync(fileName, CreationCollisionOption.OpenIfExists);
                        Debug.WriteLine("Writing file " + folderName + " " + id);
                        using (var raStream = await file.OpenAsync(FileAccessMode.ReadWrite))
                        {
                            using (var thumbnailStream = streamWeb.GetInputStreamAt(0))
                            {
                                using (var stream = raStream.GetOutputStreamAt(0))
                                {
                                    await RandomAccessStream.CopyAsync(thumbnailStream, stream);
                                    await stream.FlushAsync();
                                }
                            }
                            await raStream.FlushAsync();
                        }
                        await writer.FlushAsync();
                    }
                    await streamWeb.FlushAsync();
                }
                return true;
            }
            catch (Exception e)
            {
                Debug.WriteLine("Error saving album art: " + e);
                return false;
            }
        }
Example #16
0
        public IAsyncOperationWithProgress<IInputStream, ulong> ReadAsInputStreamAsync()
        {
            return AsyncInfo.Run<IInputStream, ulong>(async (cancellationToken, progress) =>
            {
                InMemoryRandomAccessStream randomAccessStream = new InMemoryRandomAccessStream();
                DataWriter writer = new DataWriter(randomAccessStream);
                writer.WriteString(jsonValue.Stringify());

                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);
            });
        }
        private async void BtnDownloadImage_OnClick(object sender, RoutedEventArgs e)
        {
            var ms = new InMemoryRandomAccessStream();
            await _thisWebView.CapturePreviewToStreamAsync(ms);

            // Launch file picker
            var picker = new FileSavePicker();
            picker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
            picker.FileTypeChoices.Add("JPeg", new List<string> {".jpg", ".jpeg"});
            StorageFile file = await picker.PickSaveFileAsync();

            if (file == null)
                return;

            using (IRandomAccessStream fileStream1 = await file.OpenAsync(FileAccessMode.ReadWrite))
            {
                await RandomAccessStream.CopyAndCloseAsync(ms.GetInputStreamAt(0), fileStream1.GetOutputStreamAt(0));
                DisplayTextToast("Файлът е записан успешно.");
            }
        }
Example #18
0
        private async Task <string> ExecuteCommandLineString(string CommandString)
        {
            const string CommandLineProcesserExe         = "c:\\windows\\system32\\cmd.exe";
            const uint   CommandStringResponseBufferSize = 8192;
            string       currentDirectory = "C:\\";

            StringBuilder textOutput  = new StringBuilder((int)CommandStringResponseBufferSize);
            uint          bytesLoaded = 0;

            if (string.IsNullOrWhiteSpace(CommandString))
            {
                return("");
            }

            var commandLineText = CommandString.Trim();

            var standardOutput = new Windows.Storage.Streams.InMemoryRandomAccessStream();
            var standardError  = new Windows.Storage.Streams.InMemoryRandomAccessStream();
            var options        = new Windows.System.ProcessLauncherOptions {
                StandardOutput = standardOutput,
                StandardError  = standardError
            };

            try {
                var args   = "/C \"cd \"" + currentDirectory + "\" & " + commandLineText + "\"";
                var result = await Windows.System.ProcessLauncher.RunToCompletionAsync(CommandLineProcesserExe, args, options);

                //First write std out
                using (var outStreamRedirect = standardOutput.GetInputStreamAt(0)) {
                    using (var dataReader = new Windows.Storage.Streams.DataReader(outStreamRedirect)) {
                        while ((bytesLoaded = await dataReader.LoadAsync(CommandStringResponseBufferSize)) > 0)
                        {
                            textOutput.Append(dataReader.ReadString(bytesLoaded));
                        }

                        new System.Threading.ManualResetEvent(false).WaitOne(10);
                        if ((bytesLoaded = await dataReader.LoadAsync(CommandStringResponseBufferSize)) > 0)
                        {
                            textOutput.Append(dataReader.ReadString(bytesLoaded));
                        }
                    }
                }

                //Then write std err
                using (var errStreamRedirect = standardError.GetInputStreamAt(0)) {
                    using (var dataReader = new Windows.Storage.Streams.DataReader(errStreamRedirect)) {
                        while ((bytesLoaded = await dataReader.LoadAsync(CommandStringResponseBufferSize)) > 0)
                        {
                            textOutput.Append(dataReader.ReadString(bytesLoaded));
                        }

                        new System.Threading.ManualResetEvent(false).WaitOne(10);
                        if ((bytesLoaded = await dataReader.LoadAsync(CommandStringResponseBufferSize)) > 0)
                        {
                            textOutput.Append(dataReader.ReadString(bytesLoaded));
                        }
                    }
                }

                return(textOutput.ToString());
            } catch (UnauthorizedAccessException uex) {
                return("ERROR - " + uex.Message + "\n\nCmdNotEnabled");
            } catch (Exception ex) {
                return("ERROR - " + ex.Message + "\n");
            }
        }
Example #19
0
        async void cropImage(IRandomAccessStream inputStream, uint bw, uint bh, uint w, uint h, string fname, StorageFolder folder)
        {

            BitmapDecoder decoder = await BitmapDecoder.CreateAsync(inputStream);

            InMemoryRandomAccessStream ras = new InMemoryRandomAccessStream();
            BitmapEncoder enc = await BitmapEncoder.CreateForTranscodingAsync(ras, decoder);

            BitmapBounds bounds = new BitmapBounds();
            bounds.Height = h;
            bounds.Width = w;
            bounds.X = bw;
            bounds.Y = bh;
            
            enc.BitmapTransform.Bounds = bounds;

            // write out to the stream
            try
            {
                await enc.FlushAsync();
            }
            catch (Exception ex)
            {
                string s = ex.ToString();
            }

 
            ras.Seek(0);
            // render the stream to the screen
            BitmapImage bImg = new BitmapImage();
            bImg.SetSource(ras);

            imgHidden.Source = bImg; // image element in xaml


            if (folder != null)
            {

                StorageFile file1 = await folder.CreateFileAsync(fname + "."+imgFormat, CreationCollisionOption.ReplaceExisting);

                using (var fileStream1 = await file1.OpenAsync(FileAccessMode.ReadWrite))
                {
                    await RandomAccessStream.CopyAndCloseAsync(ras.GetInputStreamAt(0), fileStream1.GetOutputStreamAt(0));
                }

            }

        }
        private async Task WriteImageToFile(InMemoryRandomAccessStream stream, string fileName, bool isLockScreen)
        {
            StorageFolder localFolder = await GetImageCacheFolder(isLockScreen);
            StorageFile file = await localFolder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);

            using (var fileStream = await file.OpenAsync(FileAccessMode.ReadWrite))
            {
                await RandomAccessStream.CopyAndCloseAsync(stream.GetInputStreamAt(0), fileStream.GetOutputStreamAt(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);
        }
        public async void SampleDataProtectionStream(String descriptor)
        {
            EncryptDecryptText.Text += "*** Sample Stream Data Protection for " + descriptor + " ***\n";

            IBuffer data = CryptographicBuffer.GenerateRandom(10000);
            DataReader reader1, reader2;
            IBuffer buff1, buff2;

            DataProtectionProvider Provider = new DataProtectionProvider(descriptor);
            InMemoryRandomAccessStream originalData = new InMemoryRandomAccessStream();

            //Populate the new memory stream
            IOutputStream outputStream = originalData.GetOutputStreamAt(0);
            DataWriter writer = new DataWriter(outputStream);
            writer.WriteBuffer(data);
            await writer.StoreAsync();
            await outputStream.FlushAsync();

            //open new memory stream for read
            IInputStream source = originalData.GetInputStreamAt(0);

            //Open the output memory stream
            InMemoryRandomAccessStream protectedData = new InMemoryRandomAccessStream();
            IOutputStream dest = protectedData.GetOutputStreamAt(0);

            // Protect
            await Provider.ProtectStreamAsync(source, dest);

            //Flush the output
            if (await dest.FlushAsync())
                EncryptDecryptText.Text += "    Protected output was successfully flushed\n";


            //Verify the protected data does not match the original
            reader1 = new DataReader(originalData.GetInputStreamAt(0));
            reader2 = new DataReader(protectedData.GetInputStreamAt(0));

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

            EncryptDecryptText.Text += "    Size of original stream:  " + originalData.Size + "\n";
            EncryptDecryptText.Text += "    Size of protected stream:  " + protectedData.Size + "\n";

            if (originalData.Size == protectedData.Size)
            {
                buff1 = reader1.ReadBuffer((uint)originalData.Size);
                buff2 = reader2.ReadBuffer((uint)protectedData.Size);
                if (CryptographicBuffer.Compare(buff1, buff2))
                {
                    EncryptDecryptText.Text += "ProtectStreamAsync returned unprotected data";
                    return;
                }
            }

            EncryptDecryptText.Text += "    Stream Compare completed.  Streams did not match.\n";

            source = protectedData.GetInputStreamAt(0);

            InMemoryRandomAccessStream unprotectedData = new InMemoryRandomAccessStream();
            dest = unprotectedData.GetOutputStreamAt(0);

            // Unprotect
            DataProtectionProvider Provider2 = new DataProtectionProvider();
            await Provider2.UnprotectStreamAsync(source, dest);

            if (await dest.FlushAsync())
                EncryptDecryptText.Text += "    Unprotected output was successfully flushed\n";

            //Verify the unprotected data does match the original
            reader1 = new DataReader(originalData.GetInputStreamAt(0));
            reader2 = new DataReader(unprotectedData.GetInputStreamAt(0));

            await reader1.LoadAsync((uint)originalData.Size);
            await reader2.LoadAsync((uint)unprotectedData.Size);

            EncryptDecryptText.Text += "    Size of original stream:  " + originalData.Size + "\n";
            EncryptDecryptText.Text += "    Size of unprotected stream:  " + unprotectedData.Size + "\n";

            buff1 = reader1.ReadBuffer((uint)originalData.Size);
            buff2 = reader2.ReadBuffer((uint)unprotectedData.Size);
            if (!CryptographicBuffer.Compare(buff1, buff2))
            {
                EncryptDecryptText.Text += "UnrotectStreamAsync did not return expected data";
                return;
            }

            EncryptDecryptText.Text += "*** Done!\n";
        }
Example #23
0
        private static async Task<bool> DownloadArtistPictureFromLastFm(MusicLibraryViewModel.ArtistItem artist)
        {
            var lastFmClient = new LastFmClient();
            var lastFmArtist = await lastFmClient.GetArtistInfo(artist.Name);
            if (lastFmArtist == null) return false;
            try
            {
                var clientPic = new HttpClient();
                var imageElement = lastFmArtist.Images.LastOrDefault(node => !string.IsNullOrEmpty(node.Url));
                if (imageElement == null) return false;
                HttpResponseMessage responsePic = await clientPic.GetAsync(imageElement.Url);
                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";
                DispatchHelper.InvokeAsync(() => artist.Picture = supposedPictureUriLocal);
                return true;
            }
            catch (Exception)
            {
                Debug.WriteLine("Error getting or saving art from LastFm.");
                return false;
            }
        }
            /// <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);
            }
        private async Task WriteImageToFile(InMemoryRandomAccessStream stream, UpdateTypes type)
        {
            StorageFolder localFolder = await GetImageCacheFolder(type);
            StorageFile file = await localFolder.CreateFileAsync("cachedImage.jpg", CreationCollisionOption.GenerateUniqueName);

            using (var fileStream = await file.OpenAsync(FileAccessMode.ReadWrite))
            {
                await RandomAccessStream.CopyAndCloseAsync(stream.GetInputStreamAt(0), fileStream.GetOutputStreamAt(0));
            }
        }