상속: IStorageFile, IStorageItem, IRandomAccessStreamReference, IInputStreamReference, IStorageItemProperties
예제 #1
1
        public MusicProperties(StorageFile file)
        {
            this.File = file;
            this.Path = this.File.Path;
            this.DateCreated = this.File.DateCreated;

            var properties = Task.Run(async () => await file.Properties.RetrievePropertiesAsync(new String[]
                {
                    "System.Music.AlbumTitle",
                    "System.Music.AlbumArtist",
                    "System.Music.Artist",
                    "System.Media.Duration",
                    "System.Music.Genre",
                    "System.DRM.IsProtected",
                    "System.Rating",
                    "System.Title",
                    "System.Music.TrackNumber"
                })).Result;

            object property;
            this.Album = (properties.TryGetValue("System.Music.AlbumTitle", out property) ? (string)property : (string)null) ?? "";
            this.Artist = (properties.TryGetValue("System.Music.Artist", out property) ? ((string[])property)[0] : (string)null) ?? "Unknown Artist";
            this.AlbumArtist = (properties.TryGetValue("System.Music.AlbumArtist", out property) ? (string)property : (string)null) ?? this.Artist;
            this.Duration = properties.TryGetValue("System.Media.Duration", out property) ? new TimeSpan((long)(ulong)property) : TimeSpan.Zero;
            this.Genre = (properties.TryGetValue("System.Music.Genre", out property) ? ((string[])property)[0] : (string)null) ?? "";
            this.IsProtected = properties.TryGetValue("System.DRM.IsProtected", out property) ? (bool)property : false;
            this.Rating = properties.TryGetValue("System.Rating", out property) ? (int)(uint)property : 0;
            this.Title = (properties.TryGetValue("System.Title", out property) ? (string)property : (string)null) ?? "";
            this.TrackNumber = properties.TryGetValue("System.Music.TrackNumber", out property) ? (int)(uint)property : 0;
        }
예제 #2
0
        private async void PerformFaceAnalysis(StorageFile file)
        {
            var imageInfo = await FileHelper.GetImageInfoForRendering(file.Path);
            NewImageSizeWidth = 300;
            NewImageSizeHeight = NewImageSizeWidth*imageInfo.Item2/imageInfo.Item1;

            var newSourceFile = await FileHelper.CreateCopyOfSelectedImage(file);
            var uriSource = new Uri(newSourceFile.Path);
            SelectedFileBitmapImage = new BitmapImage(uriSource);


            // start face api detection
            var faceApi = new FaceApiHelper();
            DetectedFaces = await faceApi.StartFaceDetection(newSourceFile.Path, newSourceFile, imageInfo, "4c138b4d82b947beb2e2926c92d1e514");

            // draw rectangles 
            var color = Color.FromArgb(125, 255, 0, 0);
            var bg = new SolidColorBrush(color);

            DetectedFacesCanvas = new ObservableCollection<Canvas>();
            foreach (var detectedFace in DetectedFaces)
            {
                var margin = new Thickness(detectedFace.RectLeft, detectedFace.RectTop, 0, 0);
                var canvas = new Canvas()
                {
                    Background = bg,
                    HorizontalAlignment = HorizontalAlignment.Left,
                    VerticalAlignment = VerticalAlignment.Top,
                    Height = detectedFace.RectHeight,
                    Width = detectedFace.RectWidth,
                    Margin = margin
                };
                DetectedFacesCanvas.Add(canvas);
            }
        }
예제 #3
0
        /// <summary>
        /// Saves the specified bitmap to the specified location.
        /// </summary>
        /// <param name="source">The source bitmap image.</param>
        /// <param name="destination">The destination storage file for the image. JPEG, PNG, GIF, BMP and TIFF formats are supported.</param>
        /// <param name="width">The width of the image file.</param>
        /// <param name="height">The height of the image file.</param>
        /// <returns>True if the bitmap file was successfully saved. False otherwise.</returns>
        public async Task<bool> Save(WriteableBitmap source, StorageFile destination, int width, int height)
        {
            if (source == null || destination == null) return false;

            try
            {
                Guid encoderID = GetEncoderId(destination);

                using (IRandomAccessStream stream = await destination.OpenAsync(FileAccessMode.ReadWrite))
                {
                    Stream pixelStream = source.PixelBuffer.AsStream();
                    byte[] pixels = new byte[pixelStream.Length];
                    await pixelStream.ReadAsync(pixels, 0, pixels.Length);

                    BitmapEncoder encoder = await BitmapEncoder.CreateAsync(encoderID, stream);
                    encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, (uint)source.PixelWidth, (uint)source.PixelHeight, Constants.DPI, Constants.DPI, pixels);

                    if (source.PixelWidth != width || source.PixelHeight != height)
                    {
                        encoder.BitmapTransform.ScaledWidth = (uint)width;
                        encoder.BitmapTransform.ScaledHeight = (uint)height;
                    }

                    await encoder.FlushAsync();
                }

                return true;
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }

            return false;
        }
예제 #4
0
        private async void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
        {
            string video_name = null;
            if (NavigationContext.QueryString.TryGetValue("Video", out video_name))
            {
                StorageFolder videosFolder = KnownFolders.VideosLibrary;

                IReadOnlyList<StorageFile> fileList = await videosFolder.GetFilesAsync();
                IReadOnlyList<StorageFolder> folderList = await videosFolder.GetFoldersAsync();

                var count = fileList.Count + folderList.Count;
                foreach (StorageFile file in fileList)
                {
                    if (file.Name == video_name)
                    {
                        try {
                            path.Text = file.Path;
                            videoPlayer.Source = new Uri(file.Path, UriKind.Absolute);
                            video = file;
                            x = await video.Properties.GetVideoPropertiesAsync();
                            videoPlayer.Play();
                            //pbVideo.Maximum = (int)videoPlayer.NaturalDuration.TimeSpan.TotalSeconds;
                            changeProgressBar();
                        }
                        catch(Exception e1)
                        {
                            MessageBox.Show(e1.ToString());
                        }
                    }
                }
            }
        }
예제 #5
0
        //-------------------------------------------------------------------------------
        #region +OpenCheckList チェックリストを開く
        //-------------------------------------------------------------------------------
        //
        public async Task<bool> OpenCheckList(StorageFile file, Func<char, Task<int>> dayToDayIndexFunc, Func<int, Task<ComiketCircleAndLayout>> updateIdToCircle)
        {
            string enc_str = null;
            using (var str = await file.OpenReadAsync())
            using (StreamReader sr = new StreamReader(str.AsStreamForRead())) {
                string line = sr.ReadLine();
                enc_str = CheckList.CheckEncode(line);
                if (enc_str == null) { return false; }
                int comiketNo = CheckList.CheckComiketNo(line);
                if (comiketNo != _comiketNo) { return false; }
            }

            Encoding enc = Encoding.GetEncoding(enc_str);

            bool res;
            using (var str = await file.OpenReadAsync())
            using (StreamReader sr = new StreamReader(str.AsStreamForRead(), enc)) {
                var lines = CheckList.FileReadLine(sr);
                res = await this.ReadCSV(lines, dayToDayIndexFunc, updateIdToCircle);
            }

            if (res) {
                await this.ReadTimeFile();
            }

            return res;
        }
예제 #6
0
		public HttpPostFile(string name, StorageFile file)
		{
			Name = name;
			Filename = file.Name;
			File = file;
			CloseStream = true;
		}
예제 #7
0
        private async void previewElement_Tapped(object sender, TappedRoutedEventArgs e)
        {
            // Block multiple taps.
            if (!IsCaptureInProgress)
            {
                IsCaptureInProgress = true;

                // Create the temporary storage file.
                media = await ApplicationData.Current.LocalFolder
                    .CreateFileAsync("capture_file.jpg", CreationCollisionOption.ReplaceExisting);

                // Take the picture and store it locally as a JPEG.
                await cameraCapture.CapturePhotoToStorageFileAsync(
                    ImageEncodingProperties.CreateJpeg(), media);

                captureButtons.Visibility = Visibility.Visible;

                // Use the stored image as the preview source.
                BitmapImage tempBitmap = new BitmapImage(new Uri(media.Path));
                imagePreview.Source = tempBitmap;
                imagePreview.Visibility = Visibility.Visible;
                previewElement.Visibility = Visibility.Collapsed;
                IsCaptureInProgress = false;
            }
        }
예제 #8
0
 public static async Task UnzipFromStorage(StorageFile pSource, StorageFolder pDestinationFolder, IEnumerable<string> pIgnore)
 {
     using (var stream = await pSource.OpenStreamForReadAsync())
     {
         await UnzipFromStream(stream, pDestinationFolder,pIgnore.ToList());
     }
 }
 /// <summary>
 /// Loads the WriteableBitmap asynchronously given the storage file and the dimensions.
 /// </summary>
 /// <param name="storageFile">The storage file.</param>
 /// <param name="decodePixelWidth">Width in pixels of the decoded bitmap.</param>
 /// <param name="decodePixelHeight">Height in pixels of the decoded bitmap.</param>
 /// <returns></returns>
 public static async Task<WriteableBitmap> LoadAsync(
     StorageFile storageFile,
     uint decodePixelWidth,
     uint decodePixelHeight)
 {
     return await new WriteableBitmap(1, 1).LoadAsync(storageFile, decodePixelWidth, decodePixelHeight);
 }
예제 #10
0
파일: Photo.cs 프로젝트: shawnhar/stuart
        public async Task Save(StorageFile file)
        {
            var image = GetImage();

            // Measure the extent of the image (which may be cropped).
            Rect imageBounds;

            using (var commandList = new CanvasCommandList(sourceBitmap.Device))
            using (var drawingSession = commandList.CreateDrawingSession())
            {
                imageBounds = image.GetBounds(drawingSession);
            }

            // Rasterize the image into a rendertarget.
            using (var renderTarget = new CanvasRenderTarget(sourceBitmap.Device, (float)imageBounds.Width, (float)imageBounds.Height, 96))
            {
                using (var drawingSession = renderTarget.CreateDrawingSession())
                {
                    drawingSession.Blend = CanvasBlend.Copy;

                    drawingSession.DrawImage(image, -(float)imageBounds.X, -(float)imageBounds.Y);
                }

                // Save it out.
                var format = file.FileType.Equals(".png", StringComparison.OrdinalIgnoreCase) ? CanvasBitmapFileFormat.Png : CanvasBitmapFileFormat.Jpeg;

                using (var stream = await file.OpenAsync(FileAccessMode.ReadWrite))
                {
                    stream.Size = 0;

                    await renderTarget.SaveAsync(stream, format);
                }
            }
        }
예제 #11
0
        public async void LoadData(IEnumerable<XElement> sprites, StorageFile spriteSheetFile, string appExtensionId)
        {
            var bitmapImage = new BitmapImage();
            using (var stream = await spriteSheetFile.OpenReadAsync()) {
                await bitmapImage.SetSourceAsync(stream);
            }
            
            //xaml
            List<ImageListItem> listOfImages = new List<ImageListItem>();
            foreach (var sprite in sprites) {
                var row = int.Parse(sprite.Attributes("Row").First().Value);
                var col = int.Parse(sprite.Attributes("Column").First().Value);

                var brush = new ImageBrush();
                brush.ImageSource = bitmapImage;
                brush.Stretch = Stretch.UniformToFill;
                brush.AlignmentX = AlignmentX.Left;
                brush.AlignmentY = AlignmentY.Top;
                brush.Transform = new CompositeTransform() { ScaleX = 2.35, ScaleY = 2.35, TranslateX = col * (-140), TranslateY = row * (-87) };
                listOfImages.Add(new ImageListItem() {
                    Title = sprite.Attributes("Title").First().Value,
                    SpriteSheetBrush = brush,
                    File = sprite.Attributes("File").First().Value,
                    AppExtensionId = appExtensionId
                });
            }
            lbPictures.ItemsSource = listOfImages;
        }
예제 #12
0
 public async static Task<BitmapImage> GetImageAsync(StorageFile storageFile)
 {
     BitmapImage bitmapImage = new BitmapImage();
     FileRandomAccessStream stream = (FileRandomAccessStream)await storageFile.OpenAsync(FileAccessMode.Read);
     bitmapImage.SetSource(stream);
     return bitmapImage;
 }
예제 #13
0
        public async void ProccesImage(StorageFile imageFile)
        {
            var data = await FileIO.ReadBufferAsync(imageFile);

            // create a stream from the file
            var ms = new InMemoryRandomAccessStream();
            var dw = new DataWriter(ms);
            dw.WriteBuffer(data);
            await dw.StoreAsync();
            ms.Seek(0);

            // find out how big the image is, don't need this if you already know
            var bm = new BitmapImage();
            await bm.SetSourceAsync(ms);

            // create a writable bitmap of the right size
            var wb = new WriteableBitmap(bm.PixelWidth, bm.PixelHeight);
            ms.Seek(0);

            // load the writable bitpamp from the stream
            await wb.SetSourceAsync(ms);

            Bitmap bmp = (Bitmap)wb;

            //var filter1 = Grayscale.CommonAlgorithms.BT709;

            //bmp = filter1.Apply(bmp);

            wb = (WriteableBitmap)bmp;

            var file = await this.WriteableBitmapToStorageFile(wb, FileFormat.Jpeg);
        }
        private async void seleccionarImagen(object sender, RoutedEventArgs e)
        {
            FileOpenPicker picker = new FileOpenPicker();
            picker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
            picker.FileTypeFilter.Add(".png");
            file = await picker.PickSingleFileAsync();

            BitmapImage image = new BitmapImage();
            try
            {
                using (var stream = await file.OpenAsync(FileAccessMode.Read))
                {
                    await image.SetSourceAsync(stream);
                }
                ImageBrush brush = new ImageBrush();
                brush.Stretch = Stretch.UniformToFill;
                brush.ImageSource = image;
                imagen.Fill = brush;
            }
            catch (Exception exception)
            {

            }
            
        }
예제 #15
0
        public  async Task<RecipeBox> GetData()
        {

            if (await DoesFileExistAsync(FileName))
            {
                file = await ApplicationData.Current.LocalFolder.CreateFileAsync(FileName, CreationCollisionOption.OpenIfExists);

                IInputStream sessionInputStream = await file.OpenReadAsync();

                //Using DataContractSerializer , look at the cat-class
                // var sessionSerializer = new DataContractSerializer(typeof(List<object>), new Type[] { typeof(T) });
                //_data = (List<object>)sessionSerializer.ReadObject(sessionInputStream.AsStreamForRead());

                

                var serializer = new XmlSerializer(typeof(RecipeBox));
                var rb =(RecipeBox)serializer.Deserialize(sessionInputStream.AsStreamForRead());
                sessionInputStream.Dispose();
                return rb;
            }
            else
            {
                var rb = generateDefault();
                return rb;
            }

        }
예제 #16
0
        public static async Task<Color> GetDominantColorFromFile(StorageFile file)
        {
            //get the file

            using (var stream = await file.OpenAsync(FileAccessMode.Read))
            {
                //Create a decoder for the image
                var decoder = await BitmapDecoder.CreateAsync(stream);

                //Create a transform to get a 1x1 image
                var myTransform = new BitmapTransform { ScaledHeight = 1, ScaledWidth = 1 };

                //Get the pixel provider
                var pixels = await decoder.GetPixelDataAsync(
                    BitmapPixelFormat.Rgba8,
                    BitmapAlphaMode.Ignore,
                    myTransform,
                    ExifOrientationMode.IgnoreExifOrientation,
                    ColorManagementMode.DoNotColorManage);

                //Get the bytes of the 1x1 scaled image
                var bytes = pixels.DetachPixelData();

                //read the color 
                var myDominantColor = Color.FromArgb(255, bytes[0], bytes[1], bytes[2]);

                return myDominantColor;
            }
        }
예제 #17
0
        private async Task DisplayStorageFileAsync(StorageFile storageFile)
        {
            var bitmapImage = new BitmapImage();
            bitmapImage.SetSource(await _storageFile.OpenAsync(FileAccessMode.Read));

            ImagePhoto.Source = bitmapImage;
        }
 private async void CreateFileClicked(object sender, Windows.UI.Xaml.RoutedEventArgs e)
 {
     StorageFolder storageFolder = ApplicationData.Current.LocalFolder;
     this.sampleFile = await storageFolder.CreateFileAsync(
         MainPage.fileName, CreationCollisionOption.ReplaceExisting);
     StatusTextBlock.Text = "The file '" + sampleFile.Name + "' was created.";
 }
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            PageData data = PageData.Instance();
            if (data.MainPageStorageFile != null)
            {
                fileToEmbed = data.MainPageStorageFile;
                fileNameTextBlock.Text = "Picked photo: " + fileToEmbed.Name;
            }
            int corner = data.MainPageRadioBox;
            switch (corner)
            {
                case 1:
                    topRightButton.IsChecked = true;
                    break;
                case 2:
                    bottomLeftButton.IsChecked = true;
                    break;
                case 3:
                    bottomRightButton.IsChecked = true;
                    break;
                case 4:
                    bottomLeftButton.IsChecked = true;
                    break;
            }

            AlignElements();
        }
 private async Task<BitmapImage> LoadImage(StorageFile file)
 {
     var image  = new BitmapImage();
     FileRandomAccessStream stream = (FileRandomAccessStream)await file.OpenAsync(FileAccessMode.Read);
     image.SetSource(stream);
     return image;
 }
        public static IFlightRawDataExtractor CreateFlightRawDataExtractor(StorageFile file, FlightParameters parameters)
        {
            if (file == null)
                return null;

            var readStreamTask = file.OpenStreamForReadAsync();
            readStreamTask.Wait();
            MemoryStream stream = new MemoryStream(102400);
            byte[] bytes = new byte[readStreamTask.Result.Length];
            readStreamTask.Result.Read(bytes, 0, Convert.ToInt32(readStreamTask.Result.Length));

            stream.Write(bytes, 0, Convert.ToInt32(readStreamTask.Result.Length));

            //Task temp1 = readStreamTask.AsTask();
            //temp1.Wait();
            //var temp2 = readStreamTask.GetResults();
            BinaryReader reader = new BinaryReader(stream); //temp2.AsStreamForRead(1024000)); //readStreamTask.Result);

            var handler = new FlightDataReadingHandler(reader);

            //if (parameters != null)
            //{
            //    handler.Definition = CreateDefinition(handler.Definition, parameters);
            //}
            return handler;
        }
예제 #22
0
        /// <summary>
        /// Populates the page with content passed during navigation.  Any saved state is also
        /// provided when recreating a page from a prior session.
        /// </summary>
        /// <param name="navigationParameter">The parameter value passed to
        /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested.
        /// </param>
        /// <param name="pageState">A dictionary of state preserved by this page during an earlier
        /// session.  This will be null the first time a page is visited.</param>
        protected override async void LoadState(Object navigationParameter, Dictionary<String, Object> pageState)
        {
            IsEdit = false;
            try
            {
                var item = (JournalItem)navigationParameter;
                iTitle.Text = item.Title;
                iDesc.Text = item.Description;
                iGroupName.Text = item.Groups;
                iBabyImage.Source = new BitmapImage(item.ImageUri);
                IsEdit = true;
                LastRecord = new JournalItem
                {
                    ImageUri = item.ImageUri,
                    Title = item.Title,
                    Description = item.Description,
                    Groups = item.Groups,
                };
                string path = item.ImageUri.AbsolutePath;                
                ImageFile = await ApplicationData.Current.LocalFolder.CreateFileAsync(path.Substring(path.LastIndexOf("/") + 1), CreationCollisionOption.OpenIfExists);
                LastImageFile = ImageFile;
            }
            catch (Exception) { }

        }
예제 #23
0
        private async void onClickSiguiente(object sender, RoutedEventArgs e)
        {
            this.nombre = nombrePlan.Text;
            this.descripcion = descripcionPlan.Text;
            this.fecha = fechaPlan.Date.Day + "/" + fechaPlan.Date.Month + "/" + fechaPlan.Date.Year;
            this.hora = configurarHora(horaPlan.Time.Hours, horaPlan.Time.Minutes);

            if (nombre.Equals("") && descripcion.Equals(""))
            {
                var dialog = new Windows.UI.Popups.MessageDialog("Por favor llene los campos");
                dialog.Commands.Add(new Windows.UI.Popups.UICommand("OK") { Id = 0 });
                var result = await dialog.ShowAsync();
            }
            else
            {
                if (photo == null)
                {
                    var packageLocation = Windows.ApplicationModel.Package.Current.InstalledLocation;
                    var assetsFolder = await packageLocation.GetFolderAsync("Assets");
                    photo = await assetsFolder.GetFileAsync("fotoplan.jpg");

                }

                Plan plan = new Plan()
                {
                    NombrePlan = nombre,
                    DescripcionPlan = descripcion,
                    FechaPlan = fecha,
                    HoraPlan = hora,
                    ImagenPlan = photo
                };
                Frame rootFrame = Window.Current.Content as Frame;
                rootFrame.Navigate(typeof(AddMapa), plan);
            }
        }
예제 #24
0
		public static async Task<List<ROI>> Load(StorageFile file)
		{		
			// read content
			var lines = await Windows.Storage.FileIO.ReadLinesAsync(file);

			// Read in all the lines
			//string[] lines = System.IO.File.ReadAllLines(_fullPath);
			List<ROI> regionsOfInterest = new List<ROI>();

			foreach (var line in lines)
			{
				var fields = line.Split('\t');

				ROI roi = new ROI()
				{
					Index = Int32.Parse(fields[0]),
					Name = fields[1],
					Ident = Int32.Parse(fields[2]),
					X = Double.Parse(fields[6]),
					Y = Double.Parse(fields[7]),
					Z = Double.Parse(fields[8]),
                    TX = Double.Parse(fields[10]),
                    TY = Double.Parse(fields[11]),
                    TZ = Double.Parse(fields[12]),
				};
				
				regionsOfInterest.Add(roi);
			}

			return regionsOfInterest;
		}
        public static async Task SaveToFile(
            this WriteableBitmap writeableBitmap,
            StorageFile outputFile,
            Guid encoderId)
        {
            try
            {
                Stream stream = writeableBitmap.PixelBuffer.AsStream();
                byte[] pixels = new byte[(uint)stream.Length];
                await stream.ReadAsync(pixels, 0, pixels.Length);

                using (var writeStream = await outputFile.OpenAsync(FileAccessMode.ReadWrite))
                {
                    var encoder = await BitmapEncoder.CreateAsync(encoderId, writeStream);
                    encoder.SetPixelData(
                        BitmapPixelFormat.Bgra8,
                        BitmapAlphaMode.Premultiplied,
                        (uint)writeableBitmap.PixelWidth,
                        (uint)writeableBitmap.PixelHeight,
                        96,
                        96,
                        pixels);
                    await encoder.FlushAsync();

                    using (var outputStream = writeStream.GetOutputStreamAt(0))
                    {
                        await outputStream.FlushAsync();
                    }
                }
            }
            catch (Exception ex)
            {
                string s = ex.ToString();
            }
        }
예제 #26
0
        // Fetches all the data for the specified file
        public async static Task<FileItem> fromStorageFile(StorageFile f, CancellationToken ct)
        {
            FileItem item = new FileItem();
            item.Filename = f.DisplayName;
            
            // Block to make sure we only have one request outstanding
            await gettingFileProperties.WaitAsync();

            BasicProperties bp = null;
            try
            {
                bp = await f.GetBasicPropertiesAsync().AsTask(ct);
            }
            catch (Exception) { }
            finally
            {
                gettingFileProperties.Release();
            }

            ct.ThrowIfCancellationRequested();

            item.Size = (int)bp.Size;
            item.Key = f.FolderRelativeId;

            StorageItemThumbnail thumb = await f.GetThumbnailAsync(ThumbnailMode.SingleItem).AsTask(ct);
            ct.ThrowIfCancellationRequested();
            BitmapImage img = new BitmapImage();
            await img.SetSourceAsync(thumb).AsTask(ct);

            item.ImageData = img;
            return item;
        }
예제 #27
0
        private async Task<Uri> SaveToFile(StorageFile file)
        {
            Uri uri = null;

            if (inkCanvas.InkPresenter.StrokeContainer.GetStrokes().Count > 0)
            {
                try
                {
                    using (IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.ReadWrite))
                    {
                        await inkCanvas.InkPresenter.StrokeContainer.SaveAsync(stream);
                        uri = new Uri("ms-appdata:///local/" + file.Name);
                    }
                }
                catch (Exception ex)
                {
                    if (Debugger.IsAttached)
                    {
                        Debugger.Break();
                    }
                }
            }


            return uri;
        }
 public PictureCropControl(StorageFile file, AspectRatio aspect = AspectRatio.Custom, CropSelectionSize cropsize = CropSelectionSize.Half)
 {
     this.InitializeComponent();
     this.file = file;
     this.aspect = aspect;
     this.cropsize = cropsize;
 }
예제 #29
0
 public static async Task<WaveFile> Create(StorageFile file)
 {
     WaveFile w = new WaveFile();
     await w.Initialize(file);
     w.SmoothSamples(200);
     return w;
 }
예제 #30
0
    async void ProcessPhotoAsync()
    {
#if !UNITY_EDITOR
        Windows.Storage.StorageFolder storageFolder = Windows.Storage.KnownFolders.CameraRoll;
        Windows.Storage.StorageFile   file          = await storageFolder.GetFileAsync("terminator_analysis.jpg");

        if (file != null)
        {
            Debug.Log("File exists!!");
        }
        else
        {
            Debug.Log("File does not exists!!");
        }


        //convert filestream to byte array
        byte[] fileBytes;
        using (var fileStream = await file.OpenStreamForReadAsync())
        {
            var binaryReader = new BinaryReader(fileStream);
            fileBytes = binaryReader.ReadBytes((int)fileStream.Length);
        }

        HttpClient client = new HttpClient();
        //Ip Address of the server running face recognition service
        client.BaseAddress = new Uri("http://192.168.137.1:5000/");
        MultipartFormDataContent form = new MultipartFormDataContent();
        HttpContent content           = new StringContent("file");
        form.Add(content, "file");
        var stream = await file.OpenStreamForReadAsync();

        content = new StreamContent(stream);
        content.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
        {
            Name     = "file",
            FileName = file.Name
        };
        form.Add(content);
        String face = null;
        try
        {
            var response = await client.PostAsync("facerec", form);

            face = response.Content.ReadAsStringAsync().Result;
            Debug.Log(response.Content.ReadAsStringAsync().Result);
            Hello.text = response.Content.ReadAsStringAsync().Result;
        }
        catch (Exception e) {
            Debug.Log(e);
        }
        //Hello.text = face;
#endif
    }
예제 #31
0
 public static async Task SendToBlobAsyncStream(Windows.Storage.StorageFile Photofile, Stream Source)
 {
     try
     {
         CreateClient();
         await deviceClient.UploadToBlobAsync(Photofile.Name, Source);
     }
     catch (Exception ex)
     {
         var Exce = ex.Message;
     }
 }
    public static async System.Threading.Tasks.Task <string> CacheFileAsync(string sourceFilePath)
    {
        string fileName = Path.GetFileName(sourceFilePath);

        Windows.Storage.StorageFile   sourceStorageFile  = Crosstales.FB.FileBrowserWSAImpl.LastOpenFile;
        Windows.Storage.StorageFolder cacheStorageFolder = Windows.Storage.ApplicationData.Current.LocalCacheFolder;
        var cacheStorageFile =
            await sourceStorageFile.CopyAsync(cacheStorageFolder, fileName, Windows.Storage.NameCollisionOption.ReplaceExisting);

        string cacheFilePath = cacheStorageFile.Path;

        return(cacheFilePath);
    }
    private async System.Threading.Tasks.Task <string> SaveImageFileAsync(string imageFileName, byte[] btImageContent, bool openIt)
    {
        Windows.Storage.StorageFolder storageFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
        Windows.Storage.StorageFile   imageFile     = await storageFolder.CreateFileAsync(imageFileName,
                                                                                          Windows.Storage.CreationCollisionOption.ReplaceExisting);

        await Windows.Storage.FileIO.WriteBytesAsync(imageFile, btImageContent);

        if (openIt)
        {
            await Windows.System.Launcher.LaunchFileAsync(imageFile);
        }

        return(imageFile.Path);
    }
예제 #34
0
        private async Task <IReadOnlyList <StorageFile> > OpenDir()
        {
            FolderPicker p = new FolderPicker();

            p.FileTypeFilter.Add(".jpg");
            p.FileTypeFilter.Add(".png");
            StorageFolder folder = await p.PickSingleFolderAsync();

            _folder = folder;
            Windows.Storage.StorageFolder storageFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
            Windows.Storage.StorageFile   sampleFile    = await folder.CreateFileAsync("sample.txt", Windows.Storage.CreationCollisionOption.ReplaceExisting);

            IReadOnlyList <StorageFile> fileList = await folder.GetFilesAsync();

            return(fileList);
        }
예제 #35
0
        private async void CopyFile_OnClick(object sender, RoutedEventArgs e)
        {
            if (listBox.SelectedItem == null)
            {
                return;
            }

            ListBoxItem item = (ListBoxItem)listBox.SelectedItem;

            if (item.Tag is Windows.Storage.StorageFile)
            {
                Windows.Storage.StorageFile file = (Windows.Storage.StorageFile)item.Tag;
                await file.CopyAsync(currentFolder, fileName.Text);
            }
            ScanDir(currentFolder);
        }
예제 #36
0
        private async void Menu_Open_Click(object sender, RoutedEventArgs e)
        {
            var picker = new Windows.Storage.Pickers.FileOpenPicker();

            picker.ViewMode = Windows.Storage.Pickers.PickerViewMode.List;
            picker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.Desktop;
            picker.FileTypeFilter.Add(".txt");

            Windows.Storage.StorageFile file = await picker.PickSingleFileAsync();

            if (file != null)
            {
                strBackup     = null;
                TextBox1.Text = await Windows.Storage.FileIO.ReadTextAsync(file);
            }
        }
예제 #37
0
        private async void LoadText(object sender, RoutedEventArgs e)
        {
            // Create sample file; replace if exists.
            Windows.Storage.StorageFolder storageFolder =
                Windows.Storage.ApplicationData.Current.LocalFolder;
            Windows.Storage.StorageFile sampleFile =
                await storageFolder.CreateFileAsync("sample.Params",
                                                    Windows.Storage.CreationCollisionOption.ReplaceExisting);

            await Windows.Storage.FileIO.WriteTextAsync(sampleFile, "Swift as a shadow");

            var    file = storageFolder.GetFileAsync("sample.Params");
            string text = await Windows.Storage.FileIO.ReadTextAsync(sampleFile);

            Debug.Write(file.Id);
        }
        /* This method is used for getting existing images from phone.
         * It works like a charm, ofcourse it is asynchronous because there can
         * be a load time and we don't want to freeze the rest of the application
         */
        public static async Task <StorageFile> ExistingPhotosLibrary()
        {
            var picker = new Windows.Storage.Pickers.FileOpenPicker
            {
                ViewMode = Windows.Storage.Pickers.PickerViewMode.Thumbnail,
                SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.PicturesLibrary
            };

            picker.FileTypeFilter.Add(".jpg");
            picker.FileTypeFilter.Add(".jpeg");
            picker.FileTypeFilter.Add(".png");

            Windows.Storage.StorageFile file = await picker.PickSingleFileAsync();

            return(file);
        }
예제 #39
0
        private async void button_Click(object sender, RoutedEventArgs e)
        {
            var picker = new Windows.Storage.Pickers.FileOpenPicker();

            picker.ViewMode = Windows.Storage.Pickers.PickerViewMode.Thumbnail;
            picker.SuggestedStartLocation =
                Windows.Storage.Pickers.PickerLocationId.PicturesLibrary;
            picker.FileTypeFilter.Add("*");
            Windows.Storage.StorageFile file = await picker.PickSingleFileAsync();

            if (file != null)
            {
                Uri uri = new Uri(uploadURL);
                UploadSingleFile(uri, file);
            }
        }
예제 #40
0
        //https://docs.microsoft.com/en-us/windows/uwp/files/quickstart-reading-and-writing-files

        private async void Save_Button_Tapped(object sender, TappedRoutedEventArgs e)
        {
            // Create sample file; replace if exists.
            Windows.Storage.StorageFolder storageFolder =
                Windows.Storage.ApplicationData.Current.LocalFolder;
            Windows.Storage.StorageFile my_Saved_File = await storageFolder.CreateFileAsync("Song.txt", Windows.Storage.CreationCollisionOption.ReplaceExisting);

            using (IRandomAccessStream iRandomAccessStream = await my_Saved_File.OpenAsync(FileAccessMode.ReadWrite))
            {
                using (DataWriter writer = new DataWriter(iRandomAccessStream))
                {
                    writer.WriteString(Song_Name.Text);
                    await writer.StoreAsync();
                }
            }
        }
예제 #41
0
        public async Task <StorageFile> LoadFileAsync()
        {
            var picker = new Windows.Storage.Pickers.FileOpenPicker
            {
                ViewMode = Windows.Storage.Pickers.PickerViewMode.Thumbnail,
                SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.PicturesLibrary
            };

            picker.FileTypeFilter.Add(".rtf");
            picker.FileTypeFilter.Add(".txt");

            Windows.Storage.StorageFile file = await picker.PickSingleFileAsync();

            fileFromLastOperation = file;
            return(file);
        }
예제 #42
0
        private async Task createFile()
        {
            // Create sample file; replace if exists.
            FolderPicker p = new FolderPicker();

            p.FileTypeFilter.Add(".jpg");
            p.FileTypeFilter.Add(".png");
            StorageFolder folder = await p.PickSingleFolderAsync();

            _folder = folder;
            Windows.Storage.StorageFolder storageFolder = Windows.Storage.ApplicationData.Current.LocalFolder;

            Windows.Storage.StorageFile sampleFile = await folder.CreateFileAsync("sample.txt", Windows.Storage.CreationCollisionOption.ReplaceExisting);

            Debug.Write("" + storageFolder.Path);
        }
예제 #43
0
        public async void LogExceptions(string exception)
        {
            try
            {
                string msg = exception + Environment.NewLine;
                // msg = Environment.NewLine + msg + Environment.NewLine;
                string filename    = "Exceptionlogs.txt";
                var    localFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
                Windows.Storage.StorageFile pinfofile = await localFolder.CreateFileAsync(filename, CreationCollisionOption.OpenIfExists);

                //  await Windows.Storage.FileIO.AppendTextAsync(pinfofile, msg, Windows.Storage.Streams.UnicodeEncoding.Utf8);
                await Windows.Storage.FileIO.WriteTextAsync(pinfofile, msg, Windows.Storage.Streams.UnicodeEncoding.Utf8);
            }
            catch (Exception)
            { }
        }
예제 #44
0
        private async void Load_Settings()
        {
            try
            {
                Windows.Storage.StorageFolder storageFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
                Windows.Storage.StorageFile   sampleFile    = await storageFolder.GetFileAsync("settings.xml");

                string text = await Windows.Storage.FileIO.ReadTextAsync(sampleFile);

                text       = text.Substring(text.IndexOf("UserToken:") + 10);
                user_token = text.Substring(0, text.IndexOf(";"));
            }catch (Exception)
            {
                user_token = "400000000";
            }
        }
예제 #45
0
        private async void AppBarButton_Click(object sender, RoutedEventArgs e)
        {
            //Inicializamos la cámara.
            CameraCaptureUI cameraUI = new CameraCaptureUI();

            //Hacemos una foto a través del botón
            Windows.Storage.StorageFile capturedMedia =
                await cameraUI.CaptureFileAsync(CameraCaptureUIMode.Photo);

            //Si se ha realizado una foto, la colocamos contiguamente del icono de la cámara.
            if (capturedMedia != null)
            {
                string rutaFoto = capturedMedia.Path;
                foto.Source = new BitmapImage(new Uri(rutaFoto));
            }
        }
예제 #46
0
 async void PlayFile(Windows.Storage.StorageFile MediaFile)
 {
     await _dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async() =>
     {
         try
         {
             Windows.Storage.Streams.IRandomAccessStream stream = await MediaFile.OpenAsync(FileAccessMode.Read);
             OutputVideo.SetSource(stream, MediaFile.ContentType);
             OutputVideo.Play();
         }
         catch (Exception exception)
         {
             TranscodeError(exception.Message);
         }
     });
 }
예제 #47
0
        public async Task GetWebPages()
        {
            Windows.Storage.StorageFile pdfFile = await Windows.Storage.ApplicationData.Current.LocalFolder.GetFileAsync("windows-pdf.pdf");

            _pdfDocument = await PdfDocument.LoadFromFileAsync(pdfFile);

            var _Pages = new List <FrameworkElement>();

            if (_pdfDocument != null && _pdfDocument.PageCount > 0)
            {
                for (uint pageNum = 0; pageNum < _pdfDocument.PageCount; pageNum++)
                {
                    var  pdfPage = _pdfDocument.GetPage(pageNum);
                    Grid _Page   = new Grid();
                    var  image   = new Image
                    {
                        Height              = pdfPage.Size.Height,
                        Width               = pdfPage.Size.Width,
                        Stretch             = Stretch.Fill,
                        HorizontalAlignment = HorizontalAlignment.Center,
                        VerticalAlignment   = VerticalAlignment.Center
                    };
                    _Page.Children.Add(image);
                    if (pdfPage != null)
                    {
                        StorageFolder tempFolder = ApplicationData.Current.TemporaryFolder;
                        StorageFile   imgFile    = await tempFolder.CreateFileAsync(Guid.NewGuid().ToString() + ".png", CreationCollisionOption.ReplaceExisting);

                        if (imgFile != null)
                        {
                            using (IRandomAccessStream randomStream = await imgFile.OpenAsync(FileAccessMode.ReadWrite))
                            {
                                await pdfPage.RenderToStreamAsync(randomStream);

                                await randomStream.FlushAsync();

                                BitmapImage src = new BitmapImage();
                                src.SetSource(randomStream);
                                image.Source = src;
                            }
                            _Pages.Add(_Page);
                        }
                    }
                }
            }
            Pages = _Pages;
        }
        private async void SaveNewRekviziti5_Click(object sender, RoutedEventArgs e)
        {
            var savePicker4 = new Windows.Storage.Pickers.FileSavePicker();

            savePicker4.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.DocumentsLibrary;
            // Поле выбора типа файла в диалоге
            savePicker4.FileTypeChoices.Add("Документ", new List <string>()
            {
                ".rekv"
            });
            // Default file name if the user does not type one in or select a file to replace
            savePicker4.SuggestedFileName = "Реквизиты новой организации";
            //
            Windows.Storage.StorageFile Myfile4 = await savePicker4.PickSaveFileAsync();

            if (Myfile4 != null)
            {
                // Prevent updates to the remote version of the file until
                // we finish making changes and call CompleteUpdatesAsync.
                Windows.Storage.CachedFileManager.DeferUpdates(Myfile4);
                // write to file
                //await Windows.Storage.FileIO.WriteTextAsync(file, file.Name); //запись в файл имени

                await FileIO.WriteTextAsync(Myfile4, TextBoxFullNameKontr5.Text + ";" + TextBoxSokrNameKontr5.Text + ";" + TextBoxINN5.Text + ";" + TextBoxKPP5.Text + ";" + TextBoxOGRN5.Text + ";" + TextBoxBankRekv5.Text + ";" + TextBoxDolzhnostDirector5.Text + ";" +
                                            TextBoxVlice5.Text + ";" + TextBoxRukSokr5.Text + ";" + TextBoxUrAddr5.Text + ";" + TextBoxFactAddr5.Text + ";" + TextBoxPhone5.Text + ";" + TextBoxMobile5.Text + ";" + TextBoxEmail5.Text + ";" + TextBoxSajt5.Text + ";");


                // Let Windows know that we're finished changing the file so
                // the other app can update the remote version of the file.
                // Completing updates may require Windows to ask for user input.
                Windows.Storage.Provider.FileUpdateStatus status =
                    await Windows.Storage.CachedFileManager.CompleteUpdatesAsync(Myfile4);

                if (status == Windows.Storage.Provider.FileUpdateStatus.Complete)
                {
                    this.TextBlockStatusFile5.Text = "Файл реквизитов " + Myfile4.Name + " успешно сохранен.";
                }
                else
                {
                    this.TextBlockStatusFile5.Text = "Не удалось сохранить файл реквизитов " + Myfile4.Name + ".";
                }
            }
            else
            {
                this.TextBlockStatusFile5.Text = "Операция записи файла реквизитов была прервана.";
            }
        }
예제 #49
0
        private async void SaveChartToPngFile(object sender, RoutedEventArgs e)
        {
            RenderTargetBitmap rtb = new RenderTargetBitmap();
            await rtb.RenderAsync(LineChart);

            var pixelBuffer = await rtb.GetPixelsAsync();

            var pixels             = pixelBuffer.ToArray();
            var displayInformation = DisplayInformation.GetForCurrentView();

            var savePicker = new Windows.Storage.Pickers.FileSavePicker();

            savePicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.DocumentsLibrary;
            savePicker.FileTypeChoices.Add("PNG Bitmap", new List <string>()
            {
                ".png"
            });
            Windows.Storage.StorageFile file = await savePicker.PickSaveFileAsync();

            if (file != null)
            {
                Windows.Storage.CachedFileManager.DeferUpdates(file);
                await Windows.Storage.FileIO.WriteTextAsync(file, file.Name);

                Windows.Storage.Provider.FileUpdateStatus status = await Windows.Storage.CachedFileManager.CompleteUpdatesAsync(file);

                if (status == Windows.Storage.Provider.FileUpdateStatus.Complete)
                {
                    using (var stream = await file.OpenAsync(FileAccessMode.ReadWrite))
                    {
                        var encoder = await Windows.Graphics.Imaging.BitmapEncoder.CreateAsync(Windows.Graphics.Imaging.BitmapEncoder.PngEncoderId, stream);

                        encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied, (uint)rtb.PixelWidth, (uint)rtb.PixelHeight, displayInformation.RawDpiX, displayInformation.RawDpiY, pixels);
                        await encoder.FlushAsync();
                    }
                    this.viewModel2.Status = "Wykres zapisano";
                }
                else
                {
                    this.viewModel2.Status = "Wykres niezapisano";
                }
            }
            else
            {
                return;
            }
        }
예제 #50
0
        async void MakeGif()
        {
            List <IImageProvider> imageSourceList = new List <IImageProvider>();

            // add image sources to define sequence of GIF frames
            for (int i = 0; i < this.bitmapFrames.Length; ++i)
            {
                SoftwareBitmap softwareBitmap = this.bitmapFrames[i];
                if (softwareBitmap != null)
                {
                    SoftwareBitmapImageSource imageSource = new SoftwareBitmapImageSource(softwareBitmap);
                    imageSourceList.Add(imageSource);
                }
            }

            // use lumia imaging SDK component to create animated GIF image
            GifRenderer gifRenderer = new GifRenderer(imageSourceList);

            gifRenderer.Duration = 100;               // time for each frame in ms
            gifRenderer.NumberOfAnimationLoops = 200; // loop continuosly
            gifRenderer.ApplyDithering         = false;

            Windows.Storage.Streams.IBuffer gifBuffer = await gifRenderer.RenderAsync();


            // show animated gif in xaml preview area
            BitmapImage animBitmap = new BitmapImage();
            await animBitmap.SetSourceAsync(gifBuffer.AsStream().AsRandomAccessStream());

            // set preview animated gif
            this.imageAnimPreview.Source = animBitmap;

            bool saveImage = true;

            if (saveImage)
            {
                // write animated gif image to file
                string timeString = DateTime.Now.ToString("yyyyMMdd-HHmm_ss");
                string filename   = $"PhotoBooth_{timeString}.gif";
                Windows.Storage.StorageFile storageFile = await Windows.Storage.KnownFolders.SavedPictures.CreateFileAsync(filename, Windows.Storage.CreationCollisionOption.ReplaceExisting);

                using (var stream = await storageFile.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite))
                {
                    await stream.WriteAsync(gifBuffer);
                }
            }
        }
예제 #51
0
        private async Task <FaceRectangle> UploadAndDetectFaces(String imageFilePath)
        {
            try
            {
                Windows.Storage.StorageFolder storageFolder = await StorageFolder.GetFolderFromPathAsync(System.IO.Path.GetDirectoryName(imageFilePath));

                Windows.Storage.StorageFile sampleFile = await storageFolder.GetFileAsync(System.IO.Path.GetFileName(imageFilePath));

                var inputStream = await sampleFile.OpenReadAsync();

                Stream stream = inputStream.AsStreamForRead();

                var faces = await faceServiceClient.DetectAsync(stream);

                var faceRects = faces.Select(face => face.FaceRectangle);

                var faceIds = faces.Select(face => face.FaceId).ToArray();
                var results = await faceServiceClient.IdentifyAsync(personGroupId, faceIds);

                for (int j = 0; j < results.Length; j++)
                {
                    Debug.WriteLine("Result of face: {0}", results[j].FaceId);
                    if (results[j].Candidates.Length == 0)
                    {
                        Debug.WriteLine("No one identified");
                    }
                    else
                    {
                        var candidateId = results[j].Candidates[0].PersonId;
                        var person      = await faceServiceClient.GetPersonAsync(personGroupId, candidateId);

                        Debug.WriteLine("Identified as {0}", person.Name);

                        if (person.Name == "person1")
                        {
                            FaceRectangle rectID;
                            return(rectID = faces[j].FaceRectangle);
                        }
                    }
                }
            }
            catch (Microsoft.ProjectOxford.Face.FaceAPIException exc)
            {
                Debug.WriteLine(exc.ErrorCode);
            }
            return(null);
        }
예제 #52
0
        /// <summary>
        /// Outputs the changes to online db.
        /// </summary>
        /// <returns></returns>
        public static async Task OutputChanges()
        {
            MySqlConnection dbConnection = DbConnection.getConnection();

            Windows.Storage.StorageFolder storageFolder =
                Windows.Storage.ApplicationData.Current.LocalFolder;
            Windows.Storage.StorageFile file =
                await storageFolder.GetFileAsync("Changelog.txt");

            IList <string> data = await FileIO.ReadLinesAsync(file);

            List <string> queries = data.ToList();

            foreach (var queryItem in queries)
            {
                using (dbConnection)
                {
                    try
                    {
                        dbConnection.Open();
                        var query = dbConnection.CreateCommand();
                        query.CommandText = queryItem;
                        query.ExecuteReader();
                        dbConnection.Close();
                    }
                    catch (MySqlException)
                    {
                        break;
                    }
                }
            }

            using (dbConnection)
            {
                try
                {
                    dbConnection.Open();
                    await file.DeleteAsync(StorageDeleteOption.Default);

                    DataAccess.InitializeDatabase();
                    dbConnection.Close();
                }
                catch (Exception)
                {
                }
            }
        }
예제 #53
0
        public static async Task <StorageFile> CreateMediaFile(string filename)
        {
            var savePicker = new Windows.Storage.Pickers.FileSavePicker();

            savePicker.SuggestedStartLocation =
                Windows.Storage.Pickers.PickerLocationId.DocumentsLibrary;
            // Dropdown of file types the user can save the file as
            savePicker.FileTypeChoices.Add("Photo", new List <string>()
            {
                ".jpg"
            });
            // Default file name if the user does not type one in or select a file to replace
            savePicker.SuggestedFileName = filename;

            Windows.Storage.StorageFile file = await savePicker.PickSaveFileAsync();

            if (file != null)
            {
                return(file);
                //// Prevent updates to the remote version of the file until
                //// we finish making changes and call CompleteUpdatesAsync.
                //Windows.Storage.CachedFileManager.DeferUpdates(file);
                //// write to file
                //await Windows.Storage.FileIO.WriteTextAsync(file, file.Name);
                //// Let Windows know that we're finished changing the file so
                //// the other app can update the remote version of the file.
                //// Completing updates may require Windows to ask for user input.
                //Windows.Storage.Provider.FileUpdateStatus status =
                //    await Windows.Storage.CachedFileManager.CompleteUpdatesAsync(file);
                //if (status == Windows.Storage.Provider.FileUpdateStatus.Complete)
                //{
                //    this.textBlock.Text = "File " + file.Name + " was saved.";
                //}
                //else
                //{
                //    this.textBlock.Text = "File " + file.Name + " couldn't be saved.";
                //}
            }
            else
            {
                return(null);
                //this.textBlock.Text = "Operation cancelled.";
            }

            //StorageFolder _mediaFolder = KnownFolders.PicturesLibrary;
            //return await _mediaFolder.CreateFileAsync(filename);
        }
예제 #54
0
        //Enrollment audio requirements
        //https://westus.dev.cognitive.microsoft.com/docs/services/563309b6778daf02acc0a508/operations/5645c3271984551c84ec6797

        private async void enrollBtn_Click(object sender, RoutedEventArgs e)
        {
            var picker = new Windows.Storage.Pickers.FileOpenPicker();

            picker.ViewMode = Windows.Storage.Pickers.PickerViewMode.Thumbnail;
            picker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.Downloads;
            picker.FileTypeFilter.Add(".wav");

            Windows.Storage.StorageFile file = await picker.PickSingleFileAsync();

            if (file != null)
            {
                // Application now has read/write access to the picked file
                txtBoxOutput.Text = "Picked: " + file.Name;
            }
            else
            {
                //User has cancelled operation
                return;
            }

            //Convert to stream
            var audioStream = await file.OpenStreamForReadAsync();

            Guid speakerId = new Guid(txtBoxGuid.Text.ToString());

            try
            {
                Enrollment response = await voiceServiceClient.EnrollAsync(audioStream, speakerId);

                if (response.EnrollmentStatus == Microsoft.ProjectOxford.SpeakerRecognition.Contract.EnrollmentStatus.Enrolled)
                {
                    // enrollment successful
                    LogMessage($"Enrolled.");
                }

                if (response.EnrollmentStatus == Microsoft.ProjectOxford.SpeakerRecognition.Contract.EnrollmentStatus.Enrolling)
                {
                    // enrollment successful
                    LogMessage($"Enrolling.");
                }
            }
            catch (Exception error)
            {
                LogMessage($"{error.Message}");
            }
        }
예제 #55
0
        private async void AppBarButton_Click(object sender, RoutedEventArgs e)
        {
            var picker = new Windows.Storage.Pickers.FileOpenPicker();

            picker.ViewMode = Windows.Storage.Pickers.PickerViewMode.Thumbnail;
            picker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.PicturesLibrary;
            picker.FileTypeFilter.Add(".txt");
            picker.FileTypeFilter.Add(".dat");
            picker.FileTypeFilter.Add(".rtf");

            Windows.Storage.StorageFile file = await picker.PickSingleFileAsync();

            if (file != null)
            {
                // Application now has read/write access to the picked file
                this.nameFile.Text = "Имя файла: " + file.Name;
                char[] rowSplitter = { '\r', '\n' };

                string[] text = (await Windows.Storage.FileIO.ReadTextAsync(file)).Split(rowSplitter, StringSplitOptions.RemoveEmptyEntries);
                for (int i = 0; i < text.Length; i++)
                {
                    string[] text1 = text[i].Split('\t');
                    try
                    {
                        if (text1[3] == String.Empty || text1[3] == null || text1[4] == String.Empty || text1[4] == null || text1[1].Split('_')[1] == "Test")
                        {
                        }
                        else
                        {
                            DataColecF.Add(new ClassFileLT()
                            {
                                nomer = Convert.ToInt32(text1[0]), nameFile = text1[1], TimeOpen = text1[3], TimeClose = text1[4], nameRun = text1[5]
                            });
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageDialog messageDialog = new MessageDialog(ex.ToString());
                        await messageDialog.ShowAsync();
                    }
                }
            }
            else
            {
                this.nameFile.Text = "Файл не выбран";
            }
        }
예제 #56
0
        private async void Button_Click_5(object sender, RoutedEventArgs e)
        {
            var picker = new Windows.Storage.Pickers.FileOpenPicker();

            picker.ViewMode = Windows.Storage.Pickers.PickerViewMode.List;
            picker.FileTypeFilter.Add(".xml");
            Windows.Storage.StorageFile file = await picker.PickSingleFileAsync();

            var stream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read);

            XmlSerializer serializer = new XmlSerializer(typeof(List <personer>));
            StreamReader  reader     = new StreamReader(stream.AsStream());

            var input = serializer.Deserialize(reader);

            ListView.ItemsSource = input;
        }
예제 #57
0
    /*
     * Este método busca el archivo en la carpeta de Assets, de no encontrarlo lanza una excepción de tipo 'FileNotFoundException'
     * @param nombreArchivoParaBuscar Es el nombre del archivo a buscar
     * @return Windows.Storage.StorageFile Regresa una variable que contiene el archivo listo para ser leído, e de tipo
     */
    private async System.Threading.Tasks.Task <Windows.Storage.StorageFile> BuscarArchivoAsync(string nombreArchivoParaBuscar)
    {
        Windows.Storage.StorageFile formulario;
        try
        {
            formulario = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFileAsync(@"Assets\" + nombreArchivoParaBuscar);
        }
        catch (FileNotFoundException)
        {
            Windows.Storage.StorageFile bitacora = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFileAsync(@"Assets\bitacoraErrores.txt");

            await Windows.Storage.FileIO.AppendTextAsync(bitacora, "\nNo se halló el directorio: " + nombreArchivoParaBuscar + ", fecha: " + new DateTime());

            throw new FileNotFoundException("No se halló la fórmula necesaría");
        }
        return(formulario);
    }
예제 #58
0
        public async Task PickAndSetWallpaper()
        {
            var picker = new Windows.Storage.Pickers.FileOpenPicker();

            picker.ViewMode = Windows.Storage.Pickers.PickerViewMode.Thumbnail;
            picker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.PicturesLibrary;
            picker.FileTypeFilter.Add(".jpg");
            picker.FileTypeFilter.Add(".jpeg");
            picker.FileTypeFilter.Add(".png");

            Windows.Storage.StorageFile file = await picker.PickSingleFileAsync();

            if (file != null)
            {
                await SetAsAsync(image : file);
            }
        }
예제 #59
0
        private async void Save_Click(object sender, RoutedEventArgs e)
        {
            var savePicker = new Windows.Storage.Pickers.FileSavePicker();

            savePicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.DocumentsLibrary;
            savePicker.FileTypeChoices.Add("Plain Text", new List <String>()
            {
                ".txt"
            });
            savePicker.SuggestedFileName = selected.file.Name;
            Windows.Storage.StorageFile file = await savePicker.PickSaveFileAsync();

            if (file != null)
            {
                await selected.file.CopyAndReplaceAsync(file);
            }
        }
예제 #60
-10
 public async Task WriteDataToFileAsync(StorageFile file, byte[] data)
 {
     using (var s = await file.OpenStreamForWriteAsync())
     {
         await s.WriteAsync(data, 0, data.Length);
     }
 }