private async void WriteCSVFile(string file)
        {
            try
            {
                //StorageFolder storageFolder = KnownFolders.DocumentsLibrary;
                //sampleFile = await storageFolder.CreateFileAsync(file, CreationCollisionOption.GenerateUniqueName);
                sampleFile = await DownloadsFolder.CreateFileAsync(file, CreationCollisionOption.GenerateUniqueName);

                if (sampleFile != null)
                {
                    string loggingstring = "";
                    foreach (string s in _loggingData)
                    {
                        loggingstring = loggingstring + s + "\n";
                    }

                    string userContent = loggingstring;
                    if (!String.IsNullOrEmpty(userContent))
                    {
                        await FileIO.WriteTextAsync(sampleFile, userContent);

                        //OutputTextBlock.Text = "The following text was written to '" + file.Name + "':" + Environment.NewLine + Environment.NewLine + userContent;
                    }
                    else
                    {
                        //OutputTextBlock.Text = "The text box is empty, please write something and then click 'Write' again.";
                    }
                }
            }
            catch (FileNotFoundException)
            {
                this.NotifyUserFileNotExist();
            }
        }
        private async void print()
        {
            //var success = await Windows.System.Launcher.LaunchUriAsync(uri);
            try
            {
                LoaderText.Text      = "Generando documento PDF...";
                grdLoader.Visibility = Visibility.Visible;

                JsonObject result = await Finances.printCC(UserId);

                Uri    uri      = new Uri(result.GetNamedString("url"));
                string filename = result.GetNamedString("file_name");

                StorageFile destinationFile = await DownloadsFolder.CreateFileAsync(filename, CreationCollisionOption.GenerateUniqueName);

                BackgroundDownloader downloader = new BackgroundDownloader();
                DownloadOperation    download   = downloader.CreateDownload(uri, destinationFile);
                await HandleDownloadAsync(download, true);

                await Windows.System.Launcher.LaunchFileAsync(download.ResultFile);

                grdLoader.Visibility = Visibility.Collapsed;
                LoaderText.Text      = "";
            }
            catch (Exception ex)
            {
                var dialog = new MessageDialog(ex.Message);
                await dialog.ShowAsync();
            }
        }
        public static async Task LoadFromJSONAsync()
        {
            StorageFolder storageFolder = ApplicationData.Current.LocalFolder;

            try
            {
                StorageFile ConfigFile = await storageFolder.GetFileAsync(App.configfilename);

                string configtext = await FileIO.ReadTextAsync(ConfigFile);

                ConfigData localdata = JsonConvert.DeserializeObject <ConfigData>(configtext);

                if (localdata != null)
                {
                    if (localdata.HistoricalSearch != null)
                    {
                        App.historysearch = localdata.HistoricalSearch;
                    }
                    App.MyDownLoadFolder = localdata.MyDownLoadFolder;
                    App.AutoPlay         = localdata.AutoPlay;
                    App.DeleteCache      = localdata.DeleteCache;
                    App.AutoSaveSearch   = localdata.AutoSaveSearch;
                }
            }
            catch (Exception)    // first open in user's compute
            {
                // create configdata.json
                await storageFolder.CreateFileAsync(App.configfilename);

                // init download folder, add folder in FutureAccessList with token (App.MyDownLoadFolder)
                StorageFolder newFolder = await DownloadsFolder.CreateFolderAsync("Music", CreationCollisionOption.GenerateUniqueName);

                StorageApplicationPermissions.FutureAccessList.AddOrReplace(App.MyDownLoadFolder, newFolder);
            }
        }
Esempio n. 4
0
        public async Task SaveRecordedAudio(CoreDispatcher UiDispatcher)
        {
            IRandomAccessStream audio = buffer.CloneStream();

            if (audio == null)
            {
                throw new ArgumentNullException("buffer");
            }

            //StorageFolder storageFolder = Windows.ApplicationModel.Package.Current.InstalledLocation;

            /*
             * StorageFolder storageFolder = await DownloadsFolder.;
             * if (!string.IsNullOrEmpty(filename))
             * {
             *  StorageFile original = await storageFolder.GetFileAsync(filename);
             *  await original.DeleteAsync();
             * }
             */
            await UiDispatcher.RunAsync(CoreDispatcherPriority.Normal, async() =>
            {
                //StorageFile storageFile = await storageFolder.CreateFileAsync(audioFile, CreationCollisionOption.GenerateUniqueName);
                StorageFile storageFile = await DownloadsFolder.CreateFileAsync(audioFile, CreationCollisionOption.GenerateUniqueName);
                filename = storageFile.Name;
                using (IRandomAccessStream fileStream = await storageFile.OpenAsync(FileAccessMode.ReadWrite))
                {
                    await RandomAccessStream.CopyAndCloseAsync(audio.GetInputStreamAt(0), fileStream.GetOutputStreamAt(0));
                    await audio.FlushAsync();
                    audio.Dispose();
                }
                //IRandomAccessStream stream = await storageFile.OpenAsync(FileAccessMode.Read);

                LogMessage($"File {storageFile.Name} saved to {storageFile.Path}");
            });
        }
Esempio n. 5
0
        /*
         * private async void DispatcherTimer_Tick(object sender, object e)
         * {
         *  //StopTimer();
         *
         *  try
         *  {
         *      var status = await inkRecognizer.RecognizeAsync();
         *      if (status == HttpStatusCode.OK)
         *      {
         *          var root = inkRecognizer.GetRecognizerRoot();
         *          if (root != null)
         *          {
         *              output.Text = OutputWriter.Print(root);
         *          }
         *      }
         *  }
         *  catch(Exception ex)
         *  {
         *      output.Text = OutputWriter.PrintError(ex.Message);
         *  }
         * }
         */
        private async void OnClickRecognize(object Sender, RoutedEventArgs e)
        {
            try
            {
                var status = await inkRecognizer.RecognizeAsync();

                if (status == HttpStatusCode.OK)
                {
                    var root = inkRecognizer.GetRecognizerRoot();
                    if (root != null)
                    {
                        //output.Text = OutputWriter.Print(root) + inkRecognizer.json;
                        output.Text = OutputWriter.Print(root);
                        Debug.Write(inkRecognizer.json);
                        StorageFile outputFile = await DownloadsFolder.CreateFileAsync("intermediary.json");

                        if (outputFile != null)
                        {
                            // Store file permissions for future access
                            Windows.Storage.AccessCache.StorageApplicationPermissions.FutureAccessList.Add(outputFile);

                            // Convert to Binary Buffer
                            var buffer = Windows.Security.Cryptography.CryptographicBuffer.ConvertStringToBinary(inkRecognizer.json, Windows.Security.Cryptography.BinaryStringEncoding.Utf8);
                            await Windows.Storage.FileIO.WriteBufferAsync(outputFile, buffer);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                output.Text = OutputWriter.PrintError(ex.Message);
            }
        }
Esempio n. 6
0
        /// <summary>
        /// The download.
        /// </summary>
        /// <returns>
        /// The <see cref="Task"/> to run asynchronously.
        /// </returns>
        private async Task Download()
        {
            var page       = DataManager.CurrentPage;
            var url        = page.Url.ToString();
            var nameOnDisk =
                url.Substring(url.LastIndexOf("//", StringComparison.CurrentCultureIgnoreCase) + 2)
                .Replace(".", "_")
                .Replace("/", "-");

            if (nameOnDisk.EndsWith("-"))
            {
                nameOnDisk = nameOnDisk.Substring(0, nameOnDisk.Length - 1);
            }

            var filename = string.Format("{0}.txt", nameOnDisk);
            var download = await DownloadsFolder.CreateFileAsync(filename, CreationCollisionOption.GenerateUniqueName);

            // await FileIO.WriteTextAsync(download, page.Text, Windows.Storage.Streams.UnicodeEncoding.Utf8);
            using (IRandomAccessStream stream = await download.OpenAsync(FileAccessMode.ReadWrite))
            {
                await stream.WriteAsync(Encoding.UTF8.GetBytes(page.Text).AsBuffer());

                await stream.FlushAsync();
            }

            var dialog = new MessageDialog(
                "Successfully downloaded the page as text to your Downloads folder.",
                download.Name);
            await dialog.ShowAsync();
        }
Esempio n. 7
0
        private async void Selection_Click_1(object sender, RoutedEventArgs e)
        {
            copy1.Text = "Copying....";
            StorageFolder storeFolder = null;

            try
            {
                storeFolder = await DownloadsFolder.CreateFolderAsync(storfolder.Name.ToString(), CreationCollisionOption.GenerateUniqueName);

                if (ItemGridView.SelectedItems.Count != 0)
                {
                    foreach (Item item in ItemGridView.SelectedItems)
                    {
                        //Uri uri = new Uri("ms-appdata:///local/" + item.Link);
                        String[]      filepath    = parseString(item.Link);
                        StorageFolder imageFolder = await Windows.Storage.ApplicationData.Current.LocalFolder.GetFolderAsync(filepath[0].Replace("/", "\\"));

                        StorageFile storageFile = await imageFolder.GetFileAsync(filepath[1]);

                        //StorageFile file = await Windows.Storage.StorageFile.GetFileFromApplicationUriAsync(uri);
                        await storageFile.CopyAsync(storeFolder, item.Title, NameCollisionOption.GenerateUniqueName);
                    }
                }
            }
            catch
            {
                DisplayMsg("Error copying selected files to Downloads!!!");
            }
            ItemGridView.SelectedItems.Clear();
            copy1.Text = "Copied to Downloads/ZipX/" + storeFolder.DisplayName;
        }
Esempio n. 8
0
        private static async Task InitDefaultDownloadFolder()
        {
            var futureAccessList = Windows.Storage.AccessCache.StorageApplicationPermissions.FutureAccessList;

            if (!(await DefaultDownloadFolderExists()))
            {
                bool created = false;
                int  i       = 1;
                do
                {
                    try
                    {
                        var myfolder = await DownloadsFolder.CreateFolderAsync((i == 1)? "Received" : $"Received ({i})");

                        FutureAccessListHelper.MakeSureFutureAccessListIsNotFull();
                        futureAccessList.AddOrReplace(_downloadMainFolder, myfolder);
                        created = true;
                    }
                    catch
                    {
                        i++;
                    }
                }while (!created);
            }
        }
        // ****************************************************************************************************
        // exporting all or filtered data grid records to an Excel spreadsheet in the Users Downloads folder
        // the Downloads folder does not have a -- CreationCollisionOption.ReplaceExisting -- therefore it will give an error
        // if the file already exists, we have overcome this by giving each file a unique name
        // the UWP app automatically creates a folder with the app name within the destination path

        private async void btnExportToXLS_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var options = new ExcelExportingOptions();

                string date = DateTime.Now.Year.ToString() + "-" + DateTime.Now.Month.ToString() + "-" + DateTime.Now.Day.ToString() + "-" + DateTime.Now.Hour.ToString() + "h" + DateTime.Now.Minute.ToString() + "m" + DateTime.Now.Second.ToString() + "s";

                options.ExcelVersion = ExcelVersion.Excel2010; // <----- this can be changed for Vision to -----> options.ExcelVersion = ExcelVersion.Excel2016;

                var excelEngine = dataGrid.ExportToExcel(dataGrid.View, options);

                var workBook = excelEngine.Excel.Workbooks[0];

                StorageFile storageFile = await DownloadsFolder.CreateFileAsync("Velog_" + date + ".xlsx");

                if (storageFile != null)
                {
                    await workBook.SaveAsAsync(storageFile);

                    txtFolderName.Text = "Downloads/VeLog   <--- Copy & Paste in File Explorer";
                    txtFileName.Text   = "Velog_" + date + ".xlsx    <--- File Name";
                    var messageDialog = new MessageDialog("File successfully exported.");
                    await messageDialog.ShowAsync();
                }
            }
            catch (Exception ex)
            {
                var messageDialog = new MessageDialog("File NOT exported!" + "\n" + "Error: " + ex.Message);
                await messageDialog.ShowAsync();
            }
        }
Esempio n. 10
0
        public async Task <StorageFile> GetDidacticsItemAttachmentAsync(Content content)
        {
            string requestUri = string.Format(DIDACTICS_ATTACHMENT_URL, authResponse.UserID, content.ID);

            HttpContent httpContent = await SendRequestAsync(HttpMethod.Get, requestUri, null);

            StorageFile file;

            if (httpContent.Headers.ContentDisposition == null)
            {
                if (httpContent.Headers.ContentType != null)
                {
                    file = await DownloadsFolder.CreateFileAsync(string.Format("{0}.{1}", content.Name, MimeTypesMap.GetExtension(httpContent.Headers.ContentType.MediaType)), CreationCollisionOption.GenerateUniqueName);
                }
                else
                {
                    file = await DownloadsFolder.CreateFileAsync(content.Name);
                }
            }
            else
            {
                file = await DownloadsFolder.CreateFileAsync(httpContent.Headers.ContentDisposition.FileName, CreationCollisionOption.GenerateUniqueName);
            }

            await FileIO.WriteBytesAsync(file, await httpContent.ReadAsByteArrayAsync());

            return(file);
        }
Esempio n. 11
0
        private async void Stop_Click(object sender, RoutedEventArgs e)
        {   //Send the stop command and save sample data to a csv file
            Stop.IsEnabled = false;
            Status.Text    = (await Oven.Stop()).ToString();

            try
            {
                var filename = $"{DateTime.Now:yyyy-MM-dd HHmmss}.csv";
                var file     = await DownloadsFolder.CreateFileAsync(filename);

                var lines = new List <string> {
                    "RealTime,RecipeTime (s),Temperature (°C),Ambient Temp (°C),Set Power (W)"
                };
                foreach (var sample in SampleData)
                {
                    lines.Add($"{sample.RealTime:yyyy-MM-dd HH:mm:ss},{sample.Time},{sample.Temperature},{sample.Ambient},{sample.Power}");
                }
                await FileIO.WriteLinesAsync(file, lines);

                await CachedFileManager.CompleteUpdatesAsync(file);
            }
            catch (Exception x)
            {
                await ShowError($"Error saving data file:{Environment.NewLine}{x.Message}");
            }

            Stop.IsEnabled = true;
        }
Esempio n. 12
0
        private async void WriteCSVFile(string file)
        {
            try
            {
                _sampleFile = await DownloadsFolder.CreateFileAsync(file, CreationCollisionOption.GenerateUniqueName);

                if (_sampleFile != null)
                {
                    string loggingstring = "";
                    foreach (string s in _loggingData)
                    {
                        loggingstring = loggingstring + s + "\n";
                    }

                    string userContent = loggingstring;
                    if (!String.IsNullOrEmpty(userContent))
                    {
                        await FileIO.WriteTextAsync(_sampleFile, userContent);
                    }
                    else
                    {
                    }
                }
            }
            catch (FileNotFoundException)
            {
                this.NotifyUserFileNotExist();
            }
        }
Esempio n. 13
0
 public IAsyncOperation <TData> GetAsync <TData>(Uri uri, TData obj)
     where TData : class
 {
     refineUri(ref uri);
     return(Run(async token =>
     {
         var resT = this.HttpClient.GetAsync(uri);
         token.Register(resT.Cancel);
         var resp = await resT;
         var str = await resp.Content.ReadAsStringAsync();
         try
         {
             var file = await DownloadsFolder.CreateFileAsync(uri.PathAndQuery.Replace('/', '.'), CreationCollisionOption.FailIfExists);
             await FileIO.WriteTextAsync(file, str);
         }
         catch (Exception)
         {
         }
         var res = new Response <TData>(obj);
         JsonConvert.PopulateObject(str, res, jsonSettings);
         if (!res.Success)
         {
             throw AnitamaServerException.Create(res);
         }
         return obj;
     }));
 }
Esempio n. 14
0
        private async void Button_Click(object sender, RoutedEventArgs e)
        {
            //Generate PDF

            var renderer = new HtmlToPdf
            {
                PrintOptions = new PdfPrintOptions
                {
                    PaperSize        = PdfPrintOptions.PdfPaperSize.Letter,
                    PaperOrientation = PdfPrintOptions.PdfPaperOrientation.Portrait,
                    RenderDelay      = 1000,
                    Footer           = new SimpleHeaderFooter
                    {
                        RightText = "Page {page} of {total-pages}",
                        FontSize  = 8
                    }
                }
            };

            var pdf = await renderer.RenderUrlAsPdfAsync(new Uri("https://ironpdf.com/"));


            //Save PDF to file in Downloads/IronPdfUwp/
            var newFile = await DownloadsFolder.CreateFileAsync("UWP-test.pdf", CreationCollisionOption.GenerateUniqueName);

            var fileStream = await newFile.OpenStreamForWriteAsync();

            if (fileStream.CanWrite)
            {
                await fileStream.WriteAsync(pdf.BinaryData, 0, pdf.BinaryData.Length);
            }

            fileStream.Close();
        }
Esempio n. 15
0
 public static IAsyncAction Download(Uri fileUri)
 {
     return(Run(async token =>
     {
         var d = new BackgroundDownloader {
             FailureToastNotification = failedToast
         };
         var file = await DownloadsFolder.CreateFileAsync($"{fileUri.GetHashCode():X}.TsinghuaNet.temp", CreationCollisionOption.GenerateUniqueName);
         var downloadOperation = d.CreateDownload(fileUri, file);
         downloadOperation.StartAsync().Completed = async(sender, e) =>
         {
             string name = null;
             var resI = downloadOperation.GetResponseInformation();
             if (resI != null)
             {
                 if (resI.Headers.TryGetValue("Content-Disposition", out name))
                 {
                     var h = HttpContentDispositionHeaderValue.Parse(name);
                     name = h.FileName;
                     if (string.IsNullOrWhiteSpace(name))
                     {
                         name = null;
                     }
                 }
                 name = name ?? getFileNameFromUri(resI.ActualUri);
             }
             name = name ?? getFileNameFromUri(fileUri);
             name = toValidFileName(name);
             await file.RenameAsync(name, NameCollisionOption.GenerateUniqueName);
             var fToken = StorageApplicationPermissions.MostRecentlyUsedList.Add(file);
             NotificationService.NotificationService.SendToastNotification(LocalizedStrings.Toast.DownloadSucceed, name, handler, fToken);
         };
     }));
 }
Esempio n. 16
0
        //downloads a file given the Download file
        public async Task <StorageFile> DownloadFileAsync(Download download)
        {
            //initiate a blank file
            StorageFile file = null;

            //ensure that provided Download is not empty
            if (download != null)
            {
                //create file in downloads folder, ensure file renames if there's a duplicate
                file = await DownloadsFolder.CreateFileAsync(download.DownloadName, CreationCollisionOption.GenerateUniqueName);

                //create download operation
                downloadOperation = downloader.CreateDownload(download.DownloadUrl, file);
                //initiate cancellation token
                cancellationToken = new CancellationTokenSource();

                try
                {
                    //attempt to download file
                    download.Status = "downloading";
                    await downloadOperation.StartAsync().AsTask(cancellationToken.Token);

                    download.Status = "complete";
                } catch (TaskCanceledException)
                {
                    //if download fails delete file and release downloadOperation
                    await downloadOperation.ResultFile.DeleteAsync();

                    downloadOperation = null;
                    download.Status   = "cancelled";
                }
            }
            //if download is successful, return the downloaded file.
            return(file);
        }
Esempio n. 17
0
        public async void CreatePDFAsync(string filename)
        {
            StorageFile storage_file = await DownloadsFolder.CreateFileAsync(filename, CreationCollisionOption.GenerateUniqueName);

            Debug.WriteLine("Creating PDF file - " + storage_file.DisplayName);

            writePDFAsync(storage_file);
        }
        public async void SaveFile(string url)
        {
            BackgroundDownloader _downloader = new BackgroundDownloader();;
            String       fileName            = Path.GetFileName(url);
            IStorageFile newFile             = await DownloadsFolder.CreateFileAsync(fileName, CreationCollisionOption.GenerateUniqueName);

            var newDownload = _downloader.CreateDownload(new Uri(url), newFile);
            await newDownload.StartAsync();
        }
Esempio n. 19
0
        private async void CreateFolder_Tapped(object sender, TappedRoutedEventArgs e)
        {
            var futureAccessList = Windows.Storage.AccessCache.StorageApplicationPermissions.FutureAccessList;

            var myfolder = await DownloadsFolder.CreateFolderAsync("QuickShare");

            futureAccessList.Clear();
            futureAccessList.AddOrReplace("downloadMainFolder", myfolder);
        }
        private async void LoadSettings()
        {
            if (!settings.Values.ContainsKey(SavePathKey))
            {
                var downloadFolder = await DownloadsFolder.CreateFolderAsync("SharedFiles", CreationCollisionOption.GenerateUniqueName);

                settings.Values.Add(SavePathKey, downloadFolder.Path);
            }
            SavePathField.Text = settings.Values[SavePathKey].ToString();
        }
Esempio n. 21
0
        /// <summary>
        /// Method which downloads a voicemail message.
        /// </summary>
        /// <param name="message">The voicemail message to download</param>
        /// <returns></returns>
        public async Task <StorageFile> DownloadMessage(Message message)
        {
            StorageFile file = await DownloadsFolder.CreateFileAsync(string.Format("{0} {1}.wav", message.Sender, message.DateTime.Replace(':', '-')), CreationCollisionOption.GenerateUniqueName);

            IBuffer buffer = await _client.GetBufferAsync(message.Source);

            await FileIO.WriteBufferAsync(file, buffer);

            return(file);
        }
Esempio n. 22
0
        public async void Save(string url, string filename)
        {
            StorageFile file = await DownloadsFolder.CreateFileAsync(filename + ".png", CreationCollisionOption.GenerateUniqueName);

            HttpClient client = new HttpClient();

            byte[] buffer = await client.GetByteArrayAsync(url);

            using (Stream stream = await file.OpenStreamForWriteAsync())
                stream.Write(buffer, 0, buffer.Length);
        }
Esempio n. 23
0
        public async Task <StorageFile> GetNoticeboardItemAttachmentAsync(string evtCode, int pubId, int attachNum)
        {
            string requestUri = string.Format(NOTICEBOARD_ATTACHMENT_URL, authResponse.UserID, evtCode, pubId, attachNum);

            HttpContent httpContent = await SendRequestAsync(HttpMethod.Get, requestUri, null);

            StorageFile file = await DownloadsFolder.CreateFileAsync(httpContent.Headers.ContentDisposition.FileName, CreationCollisionOption.GenerateUniqueName);

            await FileIO.WriteBytesAsync(file, await httpContent.ReadAsByteArrayAsync());

            return(file);
        }
Esempio n. 24
0
        // This method creates a new certificate which can be used for the UWP application.
        // Note that the certificate is saved at Downloads/Client.Uwp/Client.Uwp.pfx.
        // To take use of the certificate you may copy it to the Assets of the project and
        // change the "Build Action"-Property of the file (in Visual Studio) to "Content".
        private async void CreateCertificate()
        {
            var settings = new OpcCertificateSettings("Client.Uwp");

            var certificate = OpcCertificateManager.CreateCertificate(settings);
            var newFile     = await DownloadsFolder.CreateFileAsync("Client.Uwp.pfx");

            using (var stream = await newFile.OpenStreamForWriteAsync()) {
                var data = certificate.Export(X509ContentType.Pfx);
                stream.Write(data, 0, data.Length);
            }
        }
Esempio n. 25
0
        }   // Download

        private async Task DownLoadFromAs(string inputURL, string filename, string albumcover = "")
        {
            StorageFolder MyDownloadFolder;

            // 定位 folder
            try
            {
                MyDownloadFolder = await StorageApplicationPermissions.FutureAccessList.GetFolderAsync(App.MyDownLoadFolder);
            }
            catch (Exception)
            {
                MyDownloadFolder = await DownloadsFolder.CreateFolderAsync("Music", CreationCollisionOption.GenerateUniqueName);

                StorageApplicationPermissions.FutureAccessList.AddOrReplace(App.MyDownLoadFolder, MyDownloadFolder);
            }

            // check if exists music file
            try
            {
                StorageFile destinationFile = await MyDownloadFolder.CreateFileAsync(filename, CreationCollisionOption.FailIfExists);

                if (destinationFile != null)
                {
                    if (PlayArea.Height >= DefaultHeight)
                    {
                        TextBlockStatus.Text = "0%";
                        DownloadBar.Value    = 0;
                        await DownloadBoard.Fade(value : 1.0f, duration : 500, delay : 0, easingType : EasingType.Default).StartAsync();
                    }

                    Uri source = new Uri(inputURL);

                    BackgroundDownloader downloader = new BackgroundDownloader();
                    DownloadOperation    download   = downloader.CreateDownload(source, destinationFile);

                    Progress <DownloadOperation> progress = new Progress <DownloadOperation>(x => ProgressChanged(download));
                    cancellationToken = new CancellationTokenSource();

                    await download.StartAsync().AsTask(cancellationToken.Token, progress);

                    if (DownloadBoard.Opacity == 1.0)
                    {
                        await DownloadBoard.Fade(value : 0.0f, duration : 1000, delay : 1000, easingType : EasingType.Default).StartAsync();
                    }
                }
            }
            catch (Exception)
            {
                // music exist
                FlyoutBase.ShowAttachedFlyout(DownLoadButton);
            }
        }
Esempio n. 26
0
        public async void CreateLog(string filename)
        {
            try
            {
                StorageFile logFile = await DownloadsFolder.CreateFileAsync(filename + ".csv", Windows.Storage.CreationCollisionOption.GenerateUniqueName);

                Log(logFile, LogText.Text);
            }
            catch (Exception e)
            {
                Debug.WriteLine(e);
            }
        }
Esempio n. 27
0
        // region Save label
        private async Task <bool> SaveLabel()
        {
            // Create sample file; replace if exists.
            if (file != null)
            {
                string      filename = "label_" + file.Name.Replace(".jpg", ".txt");
                StorageFile output   = await DownloadsFolder.CreateFileAsync(filename);

                // Collect labels
                List <string> labels = new List <string>();
                string        lineLabels;
                for (int i = 0; i < 20; i++)
                {
                    lineLabels = string.Empty;

                    // Collect data for line
                    for (int j = 0; j < 20; j++)
                    {
                        // Get rect
                        var selected = LabelingArea.Children[20 * j + i + 1];
                        if (selected is Rectangle)
                        {
                            Rectangle rect = (Rectangle)selected;

                            // Add label to line
                            if ((rect.Fill as SolidColorBrush).Equals(background))
                            {
                                lineLabels += "0,";
                            }
                            if ((rect.Fill as SolidColorBrush).Equals(bee))
                            {
                                lineLabels += "1,";
                            }
                            if ((rect.Fill as SolidColorBrush).Equals(mite))
                            {
                                lineLabels += "2,";
                            }
                        }
                    }

                    labels.Add(lineLabels);
                }

                // Write line data to file
                await FileIO.WriteLinesAsync(output, labels);
            }

            return(true);
        }
Esempio n. 28
0
        private async Task <byte[]> getByteArrayFromStream(IRandomAccessStream stream, bool swap = false)
        {
            var result = new byte[stream.Size];

            if (swap)
            {
                using (var output = new InMemoryRandomAccessStream())
                {
                    using (var reader = new DataReader(stream.GetInputStreamAt(0)))
                    {
                        //reader.ByteOrder = ByteOrder.LittleEndian;
                        using (var writer = new DataWriter(output))
                        {
                            //writer.ByteOrder = ByteOrder.BigEndian;
                            await reader.LoadAsync((uint)stream.Size);

                            while (0 < reader.UnconsumedBufferLength)
                            {
                                var number       = reader.ReadUInt16();
                                var bytes_number = BitConverter.GetBytes(number);
                                writer.WriteBytes(bytes_number);
                            }
                            await writer.StoreAsync();

                            await writer.FlushAsync();

                            writer.DetachStream();
                            output.Seek(0);
                        }
                        reader.DetachStream();
                    }
                    await output.ReadAsync(result.AsBuffer(), (uint)stream.Size, InputStreamOptions.None);

                    var folder = await DownloadsFolder.CreateFileAsync(DateTime.UtcNow.Ticks + ".out");

                    using (var file = await folder.OpenStreamForWriteAsync())
                    {
                        await file.WriteAsync(result, 0, result.Length);

                        await file.FlushAsync();
                    }
                }
            }
            else
            {
                await stream.ReadAsync(result.AsBuffer(), (uint)stream.Size, InputStreamOptions.None);
            }
            return(result);
        }
        private async void csvButton_Click(object sender, RoutedEventArgs e)
        {
            StorageFile newFile = await DownloadsFolder.CreateFileAsync("graph.svg", CreationCollisionOption.GenerateUniqueName);

            await Task.Run(async() =>
            {
                using (Stream outputStream = await newFile.OpenStreamForWriteAsync())
                {
                    var exporter = new SvgExporter {
                        Width = 600, Height = 400
                    };
                    exporter.Export(MyModel, outputStream);
                }
            });
        }
Esempio n. 30
0
        public async void CreateSurveyFolder(object sender, RoutedEventArgs e)
        {
            App.surveyFolder = await DownloadsFolder.CreateFolderAsync(SurveyNameInput.Text, CreationCollisionOption.FailIfExists); //ApplicationData.Current.LocalFolder.CreateFolderAsync(SurveyNameInput.Text, CreationCollisionOption.FailIfExists);

            App.surveyFile = await App.surveyFolder.CreateFileAsync(SurveyNameInput.Text + ".json", CreationCollisionOption.ReplaceExisting);

            App.assetsFolder = await App.surveyFolder.CreateFolderAsync("Assets", CreationCollisionOption.FailIfExists);

            /*folderPicker.FileTypeFilter.Add("*");
             * folderPicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.Desktop;
             * App.surveyFolder = await folderPicker.PickSingleFolderAsync();*/
            if (App.surveyFolder != null)
            {
                CurrentPageFrame.Navigate(typeof(SurveyPages.TitlePage));
            }
        }