Beispiel #1
0
        public static async void Save(Song song, StorageFolder folder, string fileName)
        {
            for (int trackIndex = 0; trackIndex < song.Tracks.Count(); trackIndex++)
            {
                var track        = song.Tracks[trackIndex];
                var lastBarIndex = track.GetLastNonEmptyBarIndex();
                var file         = await folder?.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);

                if (file == null)
                {
                    throw new Exception($"Failed to create file '{fileName}'");
                }

                for (int barIndex = 0; barIndex <= lastBarIndex; barIndex++)
                {
                    using (var stream = await file.OpenStreamForWriteAsync().ConfigureAwait(false))
                    {
                        var bar = track.Bars[lastBarIndex];
                        if (bar.Buffer != null)
                        {
                            var buffer = bar.Buffer.SelectMany(BitConverter.GetBytes).ToArray();
                            stream.Write(buffer, 0, bar.Track.Song.SamplesPerBar);
                            stream.Close();
                        }
                    }
                }
            }
        }
 public async Task SaveUrlAsync(StorageFolder folder, HttpClient client, string path)
 {
     var destName = path.Split('/').Last();
     var content = await client.GetByteArrayAsync(path).ConfigureAwait(false);
     var destFile = await folder.CreateFileAsync(destName, CreationCollisionOption.GenerateUniqueName)
         .AsTask()
         .ConfigureAwait(false);
     using (var destStream = await destFile.OpenStreamForWriteAsync().ConfigureAwait(false))
     {
         destStream.Write(content, 0, content.Length);
         await destStream.FlushAsync().ConfigureAwait(false);
     }
 }
Beispiel #3
0
        /// <summary>
        /// Excel fájlba exportálja a paraméterként megadott terméklistát HRP szerinti összeállításban a munkamappába, vagy a paraméterként megadott mappába.
        /// Az exportált fájl neve a beállításokban megadott fájlnévből és az aktuális dátumból képződik (YYYYMMDD).
        /// A metódus kérdezés nélkül felülírja a létező listát.
        /// </summary>
        /// <param name="_termekek">A terméklista amelyet exportálni kívánunk.</param>
        /// <param name="_elteromappa">Itt lehetséges megadni az eltérő mappát, ha nem a munkamappába kívánjuk exportálni a terméklistát.</param>
        /// <returns></returns>
        public static async Task FajlbaExportal_HRP(IList <Model.Termek> _termekek, CancellationToken _canceltoken, string _elteromappa = null)
        {
            if (_termekek == null)
            {
                throw new ArgumentNullException(nameof(_termekek));
            }
            if (_canceltoken == null)
            {
                throw new ArgumentNullException(nameof(_canceltoken));
            }

            FolyamatValtozott?.Invoke(0, 0, string.Format("{0}/{1} termék exportálva ({2:P2})", 0, 0, 0));

            XLWorkbook   wb = new XLWorkbook();
            IXLWorksheet ws = wb.AddWorksheet("Termékek");
            int          ctr = 1, osszestermekszam = Globalisok.Munkaasztal.TermekLista.Count;

            // Oszlopok szélességének beállítása
            int[] oszlopszelessegek = new int[] { 17, 17, 70, 19, 14, 8, 14, 8, 14, 8, 14,
                                                  16, 11, 10, 8, 8,
                                                  13, 8, 8, 8, 8, 15,
                                                  8, 8, 8, 8 };

            foreach (int szelesseg in oszlopszelessegek)
            {
                ws.Column(ctr++).Width = szelesseg;
            }

            // Fejléc hozzáadása
            string[] fejlec = new string[]
            {
                "ID", "Cikkszám", "Megnevezés", "Leírás", "Gyártó", "Ktg#1 ID", "Kategória #1", "Ktg#2 ID", "Kategória #2", "Ktg#3 ID", "Kategória #3",
                "Garancia mód", "Garancia idő", "Ár", "Új", "Kedvezmény",
                "Készletinfó", "Van raktáron", "Készletszám", "Külső készletszám", "Értékesítés vége", "Vonalkód",
                "Nettó súly", "Bruttó súly", "Szélesség", "Magasság", "Hossz"
            };

            ctr = 1;

            foreach (string fln in fejlec)
            {
                IXLCell cell = ws.Cell(1, ctr++);

                cell.SetValue(fln);
                cell.Style.Font.Bold            = true;
                cell.Style.Fill.BackgroundColor = XLColor.FromArgb(189, 215, 238);
            }

            // Termékek hozzáadása
            await Task.Run(async() =>
            {
                ctr = 2;

                foreach (Termek termek in _termekek)
                {
#if CSAKNOTEBOOK
                    if (!termek.ElsoKategoriaID.Equals("M001") || !termek.MasodikKategoriaID.Equals("N001"))
                    {
                        continue;
                    }
#endif

                    if (_canceltoken.IsCancellationRequested)
                    {
                        break;
                    }

                    // A sor betűinek színe szürke, ha nincs forgalmazva a termék
                    if (termek.ErtekesitesVege)
                    {
                        foreach (var cell in ws.Range(ctr, 1, ctr, 27).Cells())
                        {
                            cell.Style.Font.FontColor = XLColor.Gray;
                        }
                    }

                    // Cellák tartalmainak feltöltése
                    ws.Cell(ctr, 1).SetValue(termek.ID);
                    ws.Cell(ctr, 2).SetValue(termek.Cikkszam);
                    ws.Cell(ctr, 3).SetValue(termek.Megnevezes);
                    ws.Cell(ctr, 4).SetValue(termek.Leiras);
                    ws.Cell(ctr, 5).SetValue(termek.GyartoMegnevezes);
                    ws.Cell(ctr, 6).SetValue(termek.ElsoKategoriaID);
                    ws.Cell(ctr, 7).SetValue(termek.ElsoKategoriaMegnevezes);
                    ws.Cell(ctr, 8).SetValue(termek.MasodikKategoriaID);
                    ws.Cell(ctr, 9).SetValue(termek.MasodikKategoriaMegnevezes);
                    ws.Cell(ctr, 10).SetValue(termek.HarmadikKategoriaID);
                    ws.Cell(ctr, 11).SetValue(termek.HarmadikKategoriaMegnevezes);
                    ws.Cell(ctr, 12).SetValue(termek.GaranciaMod);
                    ws.Cell(ctr, 13).SetValue(termek.GaranciaIdo);
                    ws.Cell(ctr, 14).SetValue(termek.Ar);
                    ws.Cell(ctr, 15).SetValue(termek.Uj ? "igen" : "nem"); ws.Cell(ctr, 12).Style.Font.FontColor         = termek.Uj ? XLColor.Green : XLColor.Red;
                    ws.Cell(ctr, 16).SetValue(termek.Kedvezmeny ? "igen" : "nem"); ws.Cell(ctr, 13).Style.Font.FontColor = termek.Kedvezmeny ? XLColor.Green : XLColor.Red;
                    ws.Cell(ctr, 17).SetValue(termek.KeszletInfo);
                    ws.Cell(ctr, 18).SetValue(termek.VanRaktaron ? "igen" : "nem"); ws.Cell(ctr, 15).Style.Font.FontColor = termek.VanRaktaron ? XLColor.Green : XLColor.Red;
                    ws.Cell(ctr, 19).SetValue(termek.KeszletSzam);
                    ws.Cell(ctr, 20).SetValue(termek.KulsoKeszletSzam);
                    ws.Cell(ctr, 21).SetValue(termek.ErtekesitesVege ? "igen" : "nem"); ws.Cell(ctr, 18).Style.Font.FontColor = termek.ErtekesitesVege ? XLColor.Green : XLColor.Red;
                    ws.Cell(ctr, 22).SetValue(termek.Vonalkod);
                    ws.Cell(ctr, 23).SetValue(termek.NettoSuly.ToString());
                    ws.Cell(ctr, 24).SetValue(termek.BruttoSuly.ToString());
                    ws.Cell(ctr, 25).SetValue(termek.Szelesseg.ToString());
                    ws.Cell(ctr, 26).SetValue(termek.Magassag.ToString());
                    ws.Cell(ctr, 27).SetValue(termek.Hossz.ToString());

                    // Horizontális igazítás
                    ws.Cell(ctr, 14).Style.Alignment.Horizontal                             =
                        ws.Cell(ctr, 19).Style.Alignment.Horizontal                         =
                            ws.Cell(ctr, 20).Style.Alignment.Horizontal                     =
                                ws.Cell(ctr, 23).Style.Alignment.Horizontal                 =
                                    ws.Cell(ctr, 24).Style.Alignment.Horizontal             =
                                        ws.Cell(ctr, 25).Style.Alignment.Horizontal         =
                                            ws.Cell(ctr, 26).Style.Alignment.Horizontal     =
                                                ws.Cell(ctr, 27).Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Right;

                    // Cellaformátumok beállítása
                    ws.Cell(ctr, 14).DataType = XLDataType.Number;

                    if ((ctr - 1) % 25 == 0)
                    {
                        FolyamatValtozott?.Invoke(ctr - 1, osszestermekszam, string.Format("{0}/{1} termék exportálva ({2:P2})", ctr - 1, osszestermekszam, (double)(ctr - 1) / (double)osszestermekszam));
                    }

                    ++ctr;
                }

                // Fejléc sora rögzítve legyen
                ws.SheetView.FreezeRows(1);

                if (!_canceltoken.IsCancellationRequested)
                {
                    FolyamatValtozott?.Invoke(1, 1, "Fájlba írás...");

                    StorageFolder folder = await StorageFolder.GetFolderFromPathAsync(_elteromappa ?? Globalisok.Mappa_Termeklista);
                    StorageFile file     = await folder.CreateFileAsync(FajlnevHRP, CreationCollisionOption.ReplaceExisting);

                    using (Stream filestream = await file.OpenStreamForWriteAsync())
                    {
                        wb.SaveAs(filestream);
                        filestream.Close();
                    }

                    FolyamatValtozott?.Invoke(1, 1, "A termékek exportálása sikeresen végbement.");
                }
            });
        }
Beispiel #4
0
    public async void FileStorageTest()
    {
        ClearOutput();
        WriteLine("-- Testing File Storage --");

        WriteLine("0. Creating file client");

        // Create a file client for interacting with the file service.
        CloudFileClient fileClient = StorageAccount.CreateCloudFileClient();

        // Create a share for organizing files and directories within the storage account.
        WriteLine("1. Creating file share");
        CloudFileShare share = fileClient.GetShareReference(DemoShare);

        try
        {
            await share.CreateIfNotExistsAsync();
        }
        catch (StorageException)
        {
            WriteLine("Please make sure your storage account has storage file endpoint enabled and specified correctly in the app.config - then restart the sample.");
            throw;
        }

        // Get a reference to the root directory of the share.
        CloudFileDirectory root = share.GetRootDirectoryReference();

        // Create a directory under the root directory
        WriteLine("2. Creating a directory under the root directory");
        CloudFileDirectory dir = root.GetDirectoryReference(DemoDirectory);
        await dir.CreateIfNotExistsAsync();

        // Uploading a local file to the directory created above
        WriteLine("3. Uploading a file to directory");
        CloudFile file = dir.GetFileReference(ImageToUpload);

#if WINDOWS_UWP
        StorageFolder storageFolder = await StorageFolder.GetFolderFromPathAsync(Application.streamingAssetsPath.Replace('/', '\\'));

        StorageFile sf = await storageFolder.GetFileAsync(ImageToUpload);

        await file.UploadFromFileAsync(sf);
#else
        await file.UploadFromFileAsync(Path.Combine(Application.streamingAssetsPath, ImageToUpload));
#endif

        // List all files/directories under the root directory
        WriteLine("4. List Files/Directories in root directory");
        List <IListFileItem>  results = new List <IListFileItem>();
        FileContinuationToken token   = null;
        do
        {
            FileResultSegment resultSegment = await share.GetRootDirectoryReference().ListFilesAndDirectoriesSegmentedAsync(token);

            results.AddRange(resultSegment.Results);
            token = resultSegment.ContinuationToken;
        }while (token != null);

        // Print all files/directories listed above
        foreach (IListFileItem listItem in results)
        {
            // listItem type will be CloudFile or CloudFileDirectory
            WriteLine(string.Format("- {0} (type: {1})", listItem.Uri, listItem.GetType()));
        }

        // Download the uploaded file to your file system
        string path;
        WriteLine(string.Format("5. Download file from {0}", file.Uri.AbsoluteUri));
        string fileName = string.Format("CopyOf{0}", ImageToUpload);

#if WINDOWS_UWP
        storageFolder = ApplicationData.Current.TemporaryFolder;
        sf            = await storageFolder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);

        path = sf.Path;
        await file.DownloadToFileAsync(sf);
#else
        path = Path.Combine(Application.temporaryCachePath, fileName);
        await file.DownloadToFileAsync(path, FileMode.Create);
#endif

        WriteLine("File written to " + path);

        // Clean up after the demo
        WriteLine("6. Delete file");
        await file.DeleteAsync();

        // When you delete a share it could take several seconds before you can recreate a share with the same
        // name - hence to enable you to run the demo in quick succession the share is not deleted. If you want
        // to delete the share uncomment the line of code below.
        WriteLine("7. Delete Share -- Note that it will take a few seconds before you can recreate a share with the same name");
        await share.DeleteAsync();

        WriteLine("-- Test Complete --");
    }
        private async void BuildLocalTracksAsync()
        {
            StorageFolder folder = ApplicationData.Current.LocalFolder;
            StorageFile   file;
            bool          dbIsValid = false;

            if (await isFilePresent() == false)
            {
                file = await folder.CreateFileAsync(trackFileName);
            }
            else if (await isFilePresent() == true)
            {
                file = await folder.GetFileAsync(trackFileName);

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

                byte[]       fileBytes = new byte[stream.Size];
                ulong        size      = stream.Size;
                List <Track> loaded    = new List <Track>();

                var recievedStrings = "";
                using (var inputStream = stream.GetInputStreamAt(0))
                {
                    using (var dataReader = new DataReader(inputStream)) {
                        await dataReader.LoadAsync((uint)stream.Size);

                        while (dataReader.UnconsumedBufferLength > 0)
                        {
                            recievedStrings += dataReader.ReadString((uint)stream.Size);
                        }
                    }
                }
                stream.Dispose();

                string[] readContents = recievedStrings.Split("\n");

                foreach (string s in readContents)
                {
                    if (!s.Equals(""))
                    {
                        byte[] bytes = Convert.FromBase64String(s);
                        loaded.Add(ByteArrayToTrack(bytes));
                    }
                }

                apiCount = CheckTotalAPITrackCount();

                if (loaded.Count == apiCount)
                {
                    dbIsValid            = true;
                    MainPage.TRACK_COUNT = loaded.Count;
                    foreach (Track t in loaded)
                    {
                        MainPage.tracks.Add(t);
                    }
                }
            }

            if (dbIsValid == false)
            {
                List <Track> tracks = new List <Track>();
                int          limit  = 2000;
                int          skip   = 0;
                while (tracks.Count < apiCount)
                {
                    using (HttpClient httpClient = new HttpClient())
                    {
                        httpClient.BaseAddress = new Uri(@"http://www.monstercatstreaming.tk:8080");
                        httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                        httpClient.DefaultRequestHeaders.AcceptEncoding.Add(new StringWithQualityHeaderValue("utf-8"));
                        string endpoint = @"/api/song/" + limit + "/" + skip;
                        string json     = "";

                        try
                        {
                            HttpResponseMessage response = httpClient.GetAsync(endpoint).Result;
                            response.EnsureSuccessStatusCode();
                            json = response.Content.ReadAsStringAsync().Result;

                            JArray jArray = JArray.Parse(json);
                            foreach (JObject item in jArray)
                            {
                                JProperty songArt = (JProperty)item.First.Next.Next.Next.Next.Next.Next.Next;
                                JObject   alb     = (JObject)item.Last.First;
                                JObject   albArt  = (JObject)alb.Last.First;

                                tracks.Add(new Track
                                {
                                    id             = (string)item.GetValue("id"),
                                    tracknumber    = (int)item.GetValue("tracknumber"),
                                    title          = (string)item.GetValue("title"),
                                    genreprimary   = (string)item.GetValue("genreprimary"),
                                    genresecondary = (string)item.GetValue("genresecondary"),
                                    songURL        = (string)item.GetValue("songURL"),
                                    artist         = new Artist()
                                    {
                                        name = (string)((JObject)songArt.First).GetValue("name")
                                    },
                                    album = new Album()
                                    {
                                        id             = (string)alb.GetValue("id"),
                                        name           = (string)alb.GetValue("name"),
                                        type           = (string)alb.GetValue("type"),
                                        releaseCode    = (string)alb.GetValue("releaseCode"),
                                        genreprimary   = (string)alb.GetValue("genreprimary"),
                                        genresecondary = (string)alb.GetValue("genresecondary"),
                                        coverURL       = (string)alb.GetValue("coverURL"),
                                        artist         = new Artist()
                                        {
                                            name = (string)albArt.GetValue("name")
                                        }
                                    }
                                });
                            }
                        }
                        catch (Exception) { }

                        skip += 2000;
                    }
                }

                file = await folder.CreateFileAsync(trackFileName, CreationCollisionOption.ReplaceExisting);

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

                using (var outputStream = stream.GetOutputStreamAt(0))
                {
                    using (var dataWriter = new DataWriter(outputStream))
                    {
                        foreach (Track t in tracks)
                        {
                            string temp = Convert.ToBase64String(TrackToByteArray(t)) + "\n";
                            dataWriter.WriteString(temp);
                            await dataWriter.StoreAsync();
                        }
                    }
                }
                stream.Dispose();

                MainPage.TRACK_COUNT = tracks.Count;
                foreach (Track t in tracks)
                {
                    MainPage.tracks.Add(t);
                }
            }
        }
Beispiel #6
0
        private async Task ProcessImagesAsync(StorageFolder rootFolder, bool forceProcessing = false)
        {
            this.progressRing.IsActive = true;

            this.landingMessage.Visibility       = Visibility.Collapsed;
            this.filterTab.Visibility            = Visibility.Visible;
            this.reprocessImagesButton.IsEnabled = true;

            this.FilteredResults.Clear();
            this.AllResults.Clear();
            this.TagFilters.Clear();
            this.EmotionFilters.Clear();
            this.FaceFilters.Clear();

            List <ImageInsights> insightsList = new List <ImageInsights>();

            if (!forceProcessing)
            {
                // see if we have pre-computed results and if so load it from the json file
                try
                {
                    StorageFile insightsResultFile = (await rootFolder.TryGetItemAsync("ImageInsights.json")) as StorageFile;
                    if (insightsResultFile != null)
                    {
                        using (StreamReader reader = new StreamReader(await insightsResultFile.OpenStreamForReadAsync()))
                        {
                            insightsList = JsonConvert.DeserializeObject <List <ImageInsights> >(await reader.ReadToEndAsync());
                            foreach (var insights in insightsList)
                            {
                                await AddImageInsightsToViewModel(rootFolder, insights);
                            }
                        }
                    }
                }
                catch
                {
                    // We will just compute everything again in case of errors
                }
            }

            if (!insightsList.Any())
            {
                // start with fresh face lists
                await FaceListManager.ResetFaceLists();

                // enumerate through the images and extract the insights
                QueryOptions           fileQueryOptions = new QueryOptions(CommonFileQuery.DefaultQuery, new[] { ".png", ".jpg", ".bmp", ".jpeg", ".gif" });
                StorageFileQueryResult queryResult      = rootFolder.CreateFileQueryWithOptions(fileQueryOptions);
                var queryFileList = this.limitProcessingToggleButton.IsChecked.Value ? await queryResult.GetFilesAsync(0, 50) : await queryResult.GetFilesAsync();

                foreach (var item in queryFileList)
                {
                    // Resize (if needed) in order to reduce network latency. Then store the result in a temporary file.
                    StorageFile resizedFile = await ApplicationData.Current.TemporaryFolder.CreateFileAsync("ImageCollectionInsights.jpg", CreationCollisionOption.GenerateUniqueName);

                    var resizeTransform = await Util.ResizePhoto(await item.OpenStreamForReadAsync(), 720, resizedFile);

                    // Send the file for processing
                    ImageInsights insights = await ImageProcessor.ProcessImageAsync(resizedFile.OpenStreamForReadAsync, item.Name);

                    // Delete resized file
                    await resizedFile.DeleteAsync();

                    // Adjust all FaceInsights coordinates based on the transform function between the original and resized photos
                    foreach (var faceInsight in insights.FaceInsights)
                    {
                        faceInsight.FaceRectangle.Left   = (int)(faceInsight.FaceRectangle.Left * resizeTransform.Item1);
                        faceInsight.FaceRectangle.Top    = (int)(faceInsight.FaceRectangle.Top * resizeTransform.Item2);
                        faceInsight.FaceRectangle.Width  = (int)(faceInsight.FaceRectangle.Width * resizeTransform.Item1);
                        faceInsight.FaceRectangle.Height = (int)(faceInsight.FaceRectangle.Height * resizeTransform.Item2);
                    }

                    insightsList.Add(insights);
                    await AddImageInsightsToViewModel(rootFolder, insights);
                }

                // save to json
                StorageFile jsonFile = await rootFolder.CreateFileAsync("ImageInsights.json", CreationCollisionOption.ReplaceExisting);

                using (StreamWriter writer = new StreamWriter(await jsonFile.OpenStreamForWriteAsync()))
                {
                    string jsonStr = JsonConvert.SerializeObject(insightsList, Formatting.Indented);
                    await writer.WriteAsync(jsonStr);
                }
            }

            List <TagFilterViewModel> tagsGroupedByCountAndSorted = new List <TagFilterViewModel>();

            foreach (var group in this.TagFilters.GroupBy(t => t.Count).OrderByDescending(g => g.Key))
            {
                tagsGroupedByCountAndSorted.AddRange(group.OrderBy(t => t.Tag));
            }
            this.TagFilters.Clear();
            this.TagFilters.AddRange(tagsGroupedByCountAndSorted);

            var sortedEmotions = this.EmotionFilters.OrderByDescending(e => e.Count).ToArray();

            this.EmotionFilters.Clear();
            this.EmotionFilters.AddRange(sortedEmotions);

            var sortedFaces = this.FaceFilters.OrderByDescending(f => f.Count).ToArray();

            this.FaceFilters.Clear();
            this.FaceFilters.AddRange(sortedFaces);

            this.progressRing.IsActive = false;
        }
        public async Task Save(string filename, string contentType, MemoryStream stream)
        {
            if (Device.Idiom != TargetIdiom.Desktop)
            {
                StorageFolder local   = Windows.Storage.ApplicationData.Current.LocalFolder;
                StorageFile   outFile = await local.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting);

                using (Stream outStream = await outFile.OpenStreamForWriteAsync())
                {
                    outStream.Write(stream.ToArray(), 0, (int)stream.Length);
                }
                if (contentType != "application/html")
                {
                    await Windows.System.Launcher.LaunchFileAsync(outFile);
                }
            }
            else
            {
                StorageFile    storageFile = null;
                FileSavePicker savePicker  = new FileSavePicker();
                savePicker.SuggestedStartLocation = PickerLocationId.Desktop;
                savePicker.SuggestedFileName      = filename;
                switch (contentType)
                {
                case "application/vnd.openxmlformats-officedocument.presentationml.presentation":
                    savePicker.FileTypeChoices.Add("PowerPoint Presentation", new List <string>()
                    {
                        ".pptx",
                    });
                    break;

                case "application/msexcel":
                    savePicker.FileTypeChoices.Add("Excel Files", new List <string>()
                    {
                        ".xlsx",
                    });
                    break;

                case "application/msword":
                    savePicker.FileTypeChoices.Add("Word Document", new List <string>()
                    {
                        ".docx"
                    });
                    break;

                case "application/pdf":
                    savePicker.FileTypeChoices.Add("Adobe PDF Document", new List <string>()
                    {
                        ".pdf"
                    });
                    break;

                case "application/html":
                    savePicker.FileTypeChoices.Add("HTML Files", new List <string>()
                    {
                        ".html"
                    });
                    break;
                }
                storageFile = await savePicker.PickSaveFileAsync();

                if (storageFile != null)
                {
                    using (Stream outStream = await storageFile.OpenStreamForWriteAsync())
                    {
                        if (outStream.CanSeek)
                        {
                            outStream.SetLength(0);
                        }
                        outStream.Write(stream.ToArray(), 0, (int)stream.Length);
                        outStream.Flush();
                        outStream.Dispose();
                    }
                }
                stream.Flush();
                stream.Dispose();
                if (storageFile != null)
                {
                    await Windows.System.Launcher.LaunchFileAsync(storageFile);
                }
            }
        }
Beispiel #8
0
        public async void ExportHopkinsData()
        {
            Status = "Exporting Johns Hopkins Data";
            StorageFolder exportFolder = null;

            if (StorageApplicationPermissions.FutureAccessList.ContainsItem("ExportFolder"))
            {
                exportFolder = await StorageApplicationPermissions.FutureAccessList.GetFolderAsync("ExportFolder");
            }
            else
            {
                var picker = new Windows.Storage.Pickers.FolderPicker();
                picker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.Desktop;
                picker.FileTypeFilter.Add("*");

                exportFolder = await picker.PickSingleFolderAsync();

                if (exportFolder != null)
                {
                    StorageApplicationPermissions.FutureAccessList.AddOrReplace("ExportFolder", exportFolder);
                }
            }

            DateTime startDate = new DateTime(2020, 3, 1);
            Dictionary <string, List <CalculatedValue> > listOfFiles = null;

            listOfFiles = ProcessedJhStateData?.FirstOrDefault()?.OutputFiles;

            if (exportFolder == null || listOfFiles == null)
            {
                return;
            }

            foreach (KeyValuePair <string, List <CalculatedValue> > kvp in listOfFiles)
            {
                DateTime    currentDate = startDate;
                DateTime    latestDate  = listOfFiles.Values.FirstOrDefault().Max(cv => cv.Date);
                StorageFile csvFile     = await exportFolder?.CreateFileAsync(kvp.Key + ".csv", Windows.Storage.CreationCollisionOption.ReplaceExisting);

                using (CsvFileWriter dataWriter = new CsvFileWriter(await csvFile.OpenStreamForWriteAsync()))
                {
                    CsvRow headerRow = new CsvRow();
                    headerRow.Add("Date");
                    foreach (ProcessedJhState ps in ProcessedJhStateData)
                    {
                        headerRow.Add(ps.CoreStateData.State.Code.ToString());
                    }
                    dataWriter.WriteRow(headerRow);

                    while (currentDate.Date <= latestDate)
                    {
                        CsvRow nextRow = new CsvRow();
                        nextRow.Add(currentDate.Date.ToString("MM/dd/yyyy", CultureInfo.InvariantCulture));
                        foreach (ProcessedJhState ps in ProcessedJhStateData)
                        {
                            var calcVals = ps.OutputFiles[kvp.Key].FirstOrDefault(calcv => calcv.Date.Date == currentDate.Date);
                            if (calcVals == null)
                            {
                                nextRow.Add("0");
                            }
                            else
                            {
                                nextRow.Add(calcVals.Value.ToString("F3", CultureInfo.InvariantCulture));
                            }
                        }

                        dataWriter.WriteRow(nextRow);
                        currentDate = currentDate + new TimeSpan(1, 0, 0, 0);
                    }
                }
            }

            Status = "Done with JH Data";
        }
        private async Task <bool> ExportOnnxProject(Export exportProject, CustomVisionProjectType customVisionProjectType)
        {
            if (string.IsNullOrEmpty(exportProject?.DownloadUri))
            {
                throw new ArgumentNullException("Download Uri");
            }

            bool          success               = false;
            Guid          newModelId            = Guid.NewGuid();
            StorageFolder onnxProjectDataFolder = await CustomVisionDataLoader.GetOnnxModelStorageFolderAsync(customVisionProjectType);

            StorageFile file = await onnxProjectDataFolder.CreateFileAsync($"{newModelId.ToString()}.onnx", CreationCollisionOption.ReplaceExisting);

            switch (customVisionProjectType)
            {
            case CustomVisionProjectType.Classification:
                success = await DownloadFileAsync(exportProject.DownloadUri, file);

                break;

            case CustomVisionProjectType.ObjectDetection:
                success = await UnzipModelFileAsync(exportProject.DownloadUri, file);

                break;
            }
            if (!success)
            {
                await file.DeleteAsync();

                return(false);
            }

            string[] classLabels = this.TagsInCurrentGroup?.Select(x => x.Name)?.ToArray() ?? new string[] { };
            newExportedCustomVisionModel = new CustomVisionModelData
            {
                Id          = newModelId,
                Name        = CurrentProject.Name,
                ClassLabels = classLabels,
                ExportDate  = DateTime.UtcNow,
                FileName    = file.Name,
                FilePath    = file.Path
            };

            List <CustomVisionModelData> customVisionModelList = await CustomVisionDataLoader.GetCustomVisionModelDataAsync(customVisionProjectType);

            CustomVisionModelData customVisionModelWithSameName = customVisionModelList.FirstOrDefault(x => string.Equals(x.Name, CurrentProject.Name));

            if (customVisionModelWithSameName != null)
            {
                string titleMessage = $"There is already a “{CurrentProject.Name}” model in this device. Select “Replace” if you would like to replace it, or “Keep Both” if you would like to keep both.";
                await Util.ConfirmActionAndExecute(titleMessage,
                                                   async() =>
                {
                    // if user select Yes, we replace the model with the same name
                    bool modelEntryRemovedFromFile = customVisionModelList.Remove(customVisionModelWithSameName);
                    StorageFile modelFileToRemove  = await onnxProjectDataFolder.GetFileAsync(customVisionModelWithSameName.FileName);
                    if (modelEntryRemovedFromFile && modelFileToRemove != null)
                    {
                        await modelFileToRemove.DeleteAsync();
                    }
                    await SaveCustomVisionModelAsync(customVisionModelList, newExportedCustomVisionModel, customVisionProjectType);

                    // re-display flyout window
                    FlyoutBase.ShowAttachedFlyout(this.exportButton);
                    ShowShareStatus(customVisionProjectType);
                },
                                                   cancelAction : async() =>
                {
                    int maxNumberOfModelWithSameName = customVisionModelList
                                                       .Where(x => x.Name != null && x.Name.StartsWith(newExportedCustomVisionModel.Name, StringComparison.OrdinalIgnoreCase))
                                                       .Select(x =>
                    {
                        string modelNumberInString = x.Name.Split('_').LastOrDefault();
                        int.TryParse(modelNumberInString, out int number);
                        return(number);
                    })
                                                       .Max();

                    // if user select Cancel we just save the new model with the same name
                    newExportedCustomVisionModel.Name = $"{newExportedCustomVisionModel.Name}_{maxNumberOfModelWithSameName + 1}";
                    await SaveCustomVisionModelAsync(customVisionModelList, newExportedCustomVisionModel, customVisionProjectType);

                    // re-display flyout window
                    FlyoutBase.ShowAttachedFlyout(this.exportButton);
                    ShowShareStatus(customVisionProjectType);
                },
        private async void AppBarButton_Click(object sender, RoutedEventArgs e)
        {
            FileTextBox.Text  = "";
            Progress.IsActive = true;
            ///////////////////////////////////////////////////////////////////////////////

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

            savePicker4.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.DocumentsLibrary;
            // Поле выбора типа файла в диалоге
            savePicker4.FileTypeChoices.Add("Файл данных модуля HEADER ", new List <string>()
            {
                ".header"
            });
            // Default file name if the user does not type one in or select a file to replace
            savePicker4.SuggestedFileName = "header";
            //
            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, TextBoxSTYLEFooter.Text + "¶" + TextBoxCODEFooter.Text + "¶" +

                                            TextBoxFTPServer.Text + "¶" +
                                            TextBoxFTPUser.Text + "¶" +
                                            TextBoxFTPPass.Password + "¶");



                // 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)
                {
                    string text1 = await Windows.Storage.FileIO.ReadTextAsync(Myfile4);

                    string text02 = text1.Replace("\r\n", "  "); string text002 = text02.Replace("\n", "  "); string text2 = text002.Replace("\r", "  ");
                    await FileIO.WriteTextAsync(Myfile4, text2);

                    this.StatusFile.Text = "Файл данных модуля HEADER " + Myfile4.Name + " успешно сохранен.";

                    var messagedialog = new MessageDialog("Файл данных модуля HEADER " + Myfile4.Name + " успешно сохранен.");
                    messagedialog.Commands.Add(new UICommand("Ok"));
                    await messagedialog.ShowAsync();
                }
                else
                {
                    this.StatusFile.Text = "Не удалось сохранить файл данных модуля HEADER " + Myfile4.Name + ".";

                    var messagedialog = new MessageDialog("Не удалось сохранить файл данных модуля HEADER " + Myfile4.Name + ".");
                    messagedialog.Commands.Add(new UICommand("Ok"));
                    await messagedialog.ShowAsync();
                }
            }
            else
            {
                this.StatusFile.Text = "Операция записи файла данных модуля HEADER была прервана.";

                var messagedialog = new MessageDialog("Операция записи файла данных модуля HEADER была прервана.");
                messagedialog.Commands.Add(new UICommand("Ok"));
                await messagedialog.ShowAsync();
            }

            ///////////////////////////////////////////////////////////////////////////////

            StorageFolder localFolderUPLOAD = ApplicationData.Current.LocalFolder;
            StorageFile   UPLOADFile        = await localFolderUPLOAD.CreateFileAsync("upload.txt", CreationCollisionOption.ReplaceExisting);

            await FileIO.WriteTextAsync(UPLOADFile, TextBoxCODEFooter.Text + "\r\n");


            ///////////////////////////////////////////////////////////////////////////////

            string text11 = await Windows.Storage.FileIO.ReadTextAsync(UPLOADFile);

            string text102 = text11.Replace("\r\n", "  "); string text1002 = text102.Replace("\n", "  "); string text12 = text1002.Replace("\r", "  ");

            FileTextBox.Text = text12;

            ///////////////////////////////////////////////////////////////////////////////

            if (TextBoxFTPServer.Text != "")
            {
                Progress.IsActive = true;
                DoDownloadOrUpload(false); ////см.проект kiewic ftp client
            }

            else
            {
                StatusFile.Text   = "Ошибка. Введите адрес FTP сервера.";
                Progress.IsActive = false;

                var messagedialog = new MessageDialog("Ошибка. Введите адрес FTP сервера.");
                messagedialog.Commands.Add(new UICommand("Ok"));
                await messagedialog.ShowAsync();
            }

            Progress.IsActive = false;
        }
Beispiel #11
0
        public async Task MergeMedias(List<Media> medias, MediaGroup currentMediaGroup = null)
        {

            // Use Profile for output vid/cmp? file 


            try
            {
                List<StorageFile> mediaFiles = new List<StorageFile>();
                MediaGroup mediaGroup = new MediaGroup();
                StorageFolder localFolder = ApplicationData.Current.LocalFolder;
                MediaComposition composition = new MediaComposition();
                List<MediaClip> mediaClips = new List<MediaClip>();
                StorageFile timelineVidOutputFile;
                StorageFile timelineCMPOutputFile;
                bool deleteExistingFile = (currentMediaGroup != null) ? false : true;
                #region EmotionsMeanTemp

                double tmpAngerScoreMean = 0;
                double tmpContemptScoreMean = 0;
                double tmpDisgustScoreMean = 0;
                double tmpFearScoreMean = 0;
                double tmpHappinessScoreMean = 0;
                double tmpNeutralScoreMean = 0;
                double tmpSadnessScoreMean = 0;
                double tmpSurpriseScoreMean = 0;

                string tmpHighestEmotionMean = string.Empty;

                #endregion

                foreach (var media in medias)
                {

                    mediaFiles.Add(await StorageFile.GetFileFromApplicationUriAsync(new Uri(
                            string.Format("ms-appdata:///local/{0}", media.MediaName))));

                    tmpAngerScoreMean += media.AngerScore;
                    tmpContemptScoreMean += media.ContemptScore;
                    tmpDisgustScoreMean += media.DisgustScore;
                    tmpFearScoreMean += media.FearScore;
                    tmpHappinessScoreMean += media.HappinessScore;
                    tmpNeutralScoreMean += media.NeutralScore;
                    tmpSadnessScoreMean += media.SadnessScore;
                    tmpSurpriseScoreMean += media.SurpriseScore;
                }
                tmpAngerScoreMean = tmpAngerScoreMean / medias.Count;
                tmpContemptScoreMean = tmpContemptScoreMean / medias.Count;
                tmpDisgustScoreMean = tmpDisgustScoreMean / medias.Count;
                tmpFearScoreMean = tmpFearScoreMean / medias.Count;
                tmpHappinessScoreMean = tmpHappinessScoreMean / medias.Count;
                tmpNeutralScoreMean = tmpNeutralScoreMean / medias.Count;
                tmpSadnessScoreMean = tmpSadnessScoreMean / medias.Count;
                tmpSurpriseScoreMean = tmpSurpriseScoreMean / medias.Count;

                SortedList<string, double> tempForSortingScores = new SortedList<string, double>();
                tempForSortingScores.Add("AngerScoreMean", tmpAngerScoreMean);
                tempForSortingScores.Add("ContemptScoreMean", tmpContemptScoreMean);
                tempForSortingScores.Add("DisgustScoreMean", tmpDisgustScoreMean);
                tempForSortingScores.Add("FearScoreMean", tmpFearScoreMean);
                tempForSortingScores.Add("HappinessScoreMean", tmpHappinessScoreMean);
                tempForSortingScores.Add("NeutralScoreMean", tmpNeutralScoreMean);
                tempForSortingScores.Add("SadnessScoreMean", tmpSadnessScoreMean);
                tempForSortingScores.Add("SurpriseScoreMean", tmpSurpriseScoreMean);
                // TODO: check this.
                tmpHighestEmotionMean = tempForSortingScores.OrderByDescending(x => x.Value).FirstOrDefault().Key;

                if (currentMediaGroup == null)
                {
                    timelineVidOutputFile = await localFolder.CreateFileAsync(
                   "timelineMeOutput.mp4", CreationCollisionOption.GenerateUniqueName);

                    string CMPFileName = string.Format(timelineVidOutputFile.DisplayName + ".cmp");
                    timelineCMPOutputFile = await localFolder.CreateFileAsync(
                   CMPFileName, CreationCollisionOption.OpenIfExists);

                    for (int i = 0; i < mediaFiles.Count; i++)
                    {
                        mediaClips.Add(await MediaClip.CreateFromImageFileAsync(mediaFiles[i], TimeSpan.FromSeconds(int.Parse(localSettings.Values["DurationInSecForEachImage"].ToString()))));
                        composition.Clips.Add(mediaClips[i]);
                    }


                    using (var db = new MediaContext())
                    {
                        mediaGroup = new MediaGroup()
                        {
                            CompostionFileName = timelineVidOutputFile.DisplayName,
                            LastEditDate = DateTime.Now,
                            AngerScoreMean = tmpAngerScoreMean,
                            ContemptScoreMean = tmpContemptScoreMean,
                            DisgustScoreMean = tmpDisgustScoreMean,
                            FearScoreMean = tmpFearScoreMean,
                            HappinessScoreMean = tmpHappinessScoreMean,
                            NeutralScoreMean = tmpNeutralScoreMean,
                            SadnessScoreMean = tmpSadnessScoreMean,
                            SurpriseScoreMean = tmpSurpriseScoreMean,
                            HighestEmotionMean = tmpHighestEmotionMean

                        };

                        db.MediaGroups.Add(mediaGroup);
                        db.SaveChanges();

                    }

                    var action = composition.SaveAsync(timelineCMPOutputFile);
                    action.Completed = (info, status) =>
                    {
                        if (status != AsyncStatus.Completed)
                        {
                        //ShowErrorMessage("Error saving composition");
                    }

                    };



                }
                else
                {
                    using (var db = new MediaContext())
                    {
                        mediaGroup =
                            db.MediaGroups.Where(
                                x => x.CompostionFileName == currentMediaGroup.CompostionFileName).
                                FirstOrDefault();
                        // TODO Check this
                        mediaGroup.LastEditDate = DateTime.Now;
                        mediaGroup.AngerScoreMean = mediaGroup.AngerScoreMean + tmpAngerScoreMean / 2;
                        mediaGroup.ContemptScoreMean = mediaGroup.ContemptScoreMean + tmpContemptScoreMean / 2;
                        mediaGroup.DisgustScoreMean = mediaGroup.DisgustScoreMean + tmpDisgustScoreMean / 2;
                        mediaGroup.FearScoreMean = mediaGroup.FearScoreMean + tmpFearScoreMean / 2;
                        mediaGroup.HappinessScoreMean = mediaGroup.HappinessScoreMean + tmpHappinessScoreMean / 2;
                        mediaGroup.NeutralScoreMean = mediaGroup.NeutralScoreMean + tmpNeutralScoreMean / 2;
                        mediaGroup.SadnessScoreMean = mediaGroup.SadnessScoreMean + tmpSadnessScoreMean / 2;
                        mediaGroup.SurpriseScoreMean = mediaGroup.SurpriseScoreMean + tmpSurpriseScoreMean / 2;

                        SortedList<string, double> temptempForSortingScores = new SortedList<string, double>();
                        temptempForSortingScores.Add("AngerScoreMean", mediaGroup.AngerScoreMean);
                        temptempForSortingScores.Add("ContemptScoreMean", mediaGroup.ContemptScoreMean);
                        temptempForSortingScores.Add("DisgustScoreMean", mediaGroup.DisgustScoreMean);
                        temptempForSortingScores.Add("FearScoreMean", mediaGroup.FearScoreMean);
                        temptempForSortingScores.Add("HappinessScoreMean", mediaGroup.HappinessScoreMean);
                        temptempForSortingScores.Add("NeutralScoreMean", mediaGroup.NeutralScoreMean);
                        temptempForSortingScores.Add("SadnessScoreMean", mediaGroup.SadnessScoreMean);
                        temptempForSortingScores.Add("SurpriseScoreMean", mediaGroup.SurpriseScoreMean);
                        // TODO: check this.
                        mediaGroup.HighestEmotionMean = temptempForSortingScores.OrderByDescending(x => x.Value).FirstOrDefault().Key;

                        db.MediaGroups.Update(mediaGroup);
                        db.SaveChanges();
                    }

                    timelineVidOutputFile = await localFolder.GetFileAsync(currentMediaGroup.CompostionFileName + ".mp4");
                    timelineCMPOutputFile = await localFolder.GetFileAsync(currentMediaGroup.CompostionFileName + ".cmp");
                    composition = await MediaComposition.LoadAsync(timelineCMPOutputFile);
                    //TODO: make sure this works.
                    for (int i = 0; i < mediaFiles.Count; i++)
                    {
                        // TODO Fix this
                        mediaClips.Add(await MediaClip.CreateFromImageFileAsync(mediaFiles[i], TimeSpan.FromSeconds(int.Parse(localSettings.Values["DurationInSecForEachImage"].ToString()))));
                        composition.Clips.Add(mediaClips[i]);
                    }

                    var action = composition.SaveAsync(timelineCMPOutputFile);
                    action.Completed = (info, status) =>
                    {
                        if (status != AsyncStatus.Completed)
                        {
                        //ShowErrorMessage("Error saving composition");
                    }

                    };
                }
            }
            catch (Exception)
            {

                
            }

        }
Beispiel #12
0
    private async Task BasicStorageBlockBlobOperationsAsync()
    {
        WriteLine("Testing BlockBlob");

        const string ImageToUpload = "HelloWorld.png";

        // Create a blob client for interacting with the blob service.
        CloudBlobClient blobClient = StorageAccount.CreateCloudBlobClient();

        // Create a container for organizing blobs within the storage account.
        WriteLine("1. Creating Container");
        CloudBlobContainer container = blobClient.GetContainerReference("democontainerblockblob");

        try
        {
            await container.CreateIfNotExistsAsync();
        }
        catch (StorageException ex)
        {
            WriteLine(ex.Message);
            WriteLine("If you are running with the default configuration please make sure you have started the storage emulator. Press the Windows key and type Azure Storage to select and run it from the list of applications - then restart the sample.");
            throw;
        }

        // To view the uploaded blob in a browser, you have two options. The first option is to use a Shared Access Signature (SAS) token to delegate
        // access to the resource. See the documentation links at the top for more information on SAS. The second approach is to set permissions
        // to allow public access to blobs in this container. Uncomment the line below to use this approach. Then you can view the image
        // using: https://[InsertYourStorageAccountNameHere].blob.core.windows.net/democontainer/HelloWorld.png
        // await container.SetPermissionsAsync(new BlobContainerPermissions { PublicAccess = BlobContainerPublicAccessType.Blob });

        // Upload a BlockBlob to the newly created container
        WriteLine("2. Uploading BlockBlob");
        CloudBlockBlob blockBlob = container.GetBlockBlobReference(ImageToUpload);

#if WINDOWS_UWP
        StorageFolder storageFolder = await StorageFolder.GetFolderFromPathAsync(Application.streamingAssetsPath.Replace('/', '\\'));

        StorageFile sf = await storageFolder.GetFileAsync(ImageToUpload);

        await blockBlob.UploadFromFileAsync(sf);
#else
        await blockBlob.UploadFromFileAsync(Path.Combine(Application.streamingAssetsPath, ImageToUpload));
#endif

        // List all the blobs in the container
        WriteLine("3. List Blobs in Container");
        BlobContinuationToken token = null;
        BlobResultSegment     list  = await container.ListBlobsSegmentedAsync(token);

        foreach (IListBlobItem blob in list.Results)
        {
            // Blob type will be CloudBlockBlob, CloudPageBlob or CloudBlobDirectory
            // Use blob.GetType() and cast to appropriate type to gain access to properties specific to each type
            WriteLine(string.Format("- {0} (type: {1})", blob.Uri, blob.GetType()));
        }

        // Download a blob to your file system
        string path;
        WriteLine(string.Format("4. Download Blob from {0}", blockBlob.Uri.AbsoluteUri));
        string fileName = string.Format("CopyOf{0}", ImageToUpload);

#if WINDOWS_UWP
        storageFolder = ApplicationData.Current.TemporaryFolder;
        sf            = await storageFolder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);

        path = sf.Path;
        await blockBlob.DownloadToFileAsync(sf);
#else
        path = Path.Combine(Application.temporaryCachePath, fileName);
        await blockBlob.DownloadToFileAsync(path, FileMode.Create);
#endif

        WriteLine("File written to " + path);

        // Clean up after the demo
        WriteLine("5. Delete block Blob");
        await blockBlob.DeleteAsync();

        // When you delete a container it could take several seconds before you can recreate a container with the same
        // name - hence to enable you to run the demo in quick succession the container is not deleted. If you want
        // to delete the container uncomment the line of code below.
        WriteLine("6. Delete Container -- Note that it will take a few seconds before you can recreate a container with the same name");
        await container.DeleteAsync();

        WriteLine("-- Test Complete --");
    }
Beispiel #13
0
        private async Task HttpDownloadAsync(string stationURL, string episodeNameString, string showName)
        {
            Debug.WriteLine("Made it to Download");

            Uri uri = new Uri(stationURL);

            Debug.WriteLine("StationURL is " + stationURL);

            StorageFolder PodBlasterFolder = await KnownFolders.MusicLibrary.GetFolderAsync(@"PodBlaster\Downloads");

            Debug.WriteLine("StorageFolder allocated");

            StorageFile destinationFile = await PodBlasterFolder.CreateFileAsync(
                "_temp_" + System.IO.Path.GetFileName(uri.ToString()), CreationCollisionOption.ReplaceExisting);


            Debug.WriteLine("DestinationFile created");

            BackgroundDownloader downloader = new BackgroundDownloader();

            Debug.WriteLine("BackgroundDownloader created");
            DownloadOperation download = downloader.CreateDownload(uri, destinationFile);

            Debug.WriteLine("DownloadOperation created");

            await Add_Another_Download(System.IO.Path.GetFileName(uri.ToString()));

            Debug.WriteLine("Status Command Sent");

            await download.StartAsync();

            Debug.WriteLine("Download started...");

            await CompleteDownloading(System.IO.Path.GetFileName(uri.ToString()));

            Debug.WriteLine("Download complete...");

            //destinationFile.RenameAsync()

            Debug.WriteLine("Destination file is " + destinationFile.Name.ToString());
            showName          = showName.Replace("'", "");
            showName          = showName.Replace(":", " - ");
            episodeNameString = episodeNameString.Replace("'", "");
            episodeNameString = episodeNameString.Replace(":", " - ");

            try {
                await destinationFile.RenameAsync(showName + " - " + episodeNameString + ".mp3", NameCollisionOption.ReplaceExisting);

                //await destinationFile.RenameAsync(episodeNameString + ".mp3", NameCollisionOption.ReplaceExisting);
            }

            catch (Exception e)
            {
                Debug.WriteLine("We're in the catch");
                Debug.WriteLine(e);
                Debug.WriteLine(destinationFile.Name.ToString());
            }

            Debug.WriteLine("We're through the rename...");

            await FixUp_ID3_Tags(destinationFile, showName, episodeNameString);

            await Show_Downloaded_Episodes(PodBlasterFolder);
        }
Beispiel #14
0
        private async Task OOBE()
        {
            // If you haven't used the application before, this will bootstrap you with a sample XML file
            // and create the root folder and download subfolder.

            // Let's look for the folders...

            try {
                StorageFolder podBlasterParent = await KnownFolders.MusicLibrary.GetFolderAsync(@"PodBlaster");

                StorageFolder podBlasterDownloads = await KnownFolders.MusicLibrary.GetFolderAsync(@"PodBlaster\Downloads");
            } catch
            {
                StorageFolder musicLibrary = await KnownFolders.MusicLibrary.CreateFolderAsync(@"PodBlaster");

                StorageFolder musicLibraryDownloads = await musicLibrary.CreateFolderAsync(@"Downloads");
            }

            // Let's look for an XML file...

            try
            {
                StorageFolder podBlasterParent = await KnownFolders.MusicLibrary.GetFolderAsync(@"PodBlaster");

                StorageFile podBlasterXML = await podBlasterParent.GetFileAsync(@"stations.xml");
            } catch {
                StorageFolder podBlasterParent = await KnownFolders.MusicLibrary.GetFolderAsync(@"PodBlaster");

                XmlDocument outputXML = new XmlDocument();


                XmlElement rootElement = outputXML.CreateElement(string.Empty, "stations", string.Empty);
                outputXML.AppendChild(rootElement);

                XmlSignificantWhitespace sigws = outputXML.CreateSignificantWhitespace("\n\t");
                rootElement.InsertAfter(sigws, rootElement.FirstChild);

                List <Podcast> starterList = new List <Podcast>();
                Podcast        replyAll    = new Podcast();
                replyAll.stationName = "Reply All";
                replyAll.stationURL  = "http://feeds.gimletmedia.com/hearreplyall";

                starterList.Add(replyAll);

                foreach (Podcast thisOne in starterList)
                {
                    XmlElement stationElement = outputXML.CreateElement(string.Empty, "station", string.Empty);

                    XmlElement stationNameElement = outputXML.CreateElement(string.Empty, "stationName", string.Empty);

                    XmlText text1 = outputXML.CreateTextNode(thisOne.stationName);
                    stationNameElement.AppendChild(text1);
                    stationElement.AppendChild(stationNameElement);
                    stationElement.InsertAfter(sigws, stationNameElement);

                    XmlElement stationURLElement = outputXML.CreateElement(string.Empty, "stationURL", string.Empty);

                    XmlText text2 = outputXML.CreateTextNode(thisOne.stationURL);
                    stationURLElement.AppendChild(text2);
                    stationElement.AppendChild(stationURLElement);
                    stationElement.InsertAfter(sigws, stationURLElement);
                    rootElement.AppendChild(stationElement);
                }

                Debug.WriteLine(outputXML.InnerXml.ToString());

                string      XMLFilePath = podBlasterParent.Path + @"\stations.xml";
                StorageFile XMLFile     = await podBlasterParent.CreateFileAsync("stations.xml");

                await FileIO.WriteTextAsync(XMLFile, outputXML.InnerXml.ToString());

                Debug.WriteLine("Wrote out XML File!");
            }
        }
Beispiel #15
0
        private static async void Initial()
        {
            string filename = DateTime.Now.ToString("yyyy-MM-dd");

            logFile = await localFolder.CreateFileAsync($"BZ{filename}.log", CreationCollisionOption.OpenIfExists);
        }
Beispiel #16
0
        private async void btnGenerateExcel_Click(object sender, RoutedEventArgs e)
        {
            #region Workbook initialization
            //New instance of XlsIO is created.[Equivalent to launching MS Excel with no workbooks open].
            //The instantiation process consists of two steps.

            ExcelEngine  excelEngine = new ExcelEngine();
            IApplication application = excelEngine.Excel;

            application.DefaultVersion = ExcelVersion.Excel2013;

            Assembly  assembly     = typeof(DataSort).GetTypeInfo().Assembly;
            string    resourcePath = "Syncfusion.SampleBrowser.UWP.XlsIO.XlsIO.Tutorials.Samples.Assets.Resources.Templates.SortingData.xlsx";
            Stream    fileStream   = assembly.GetManifestResourceStream(resourcePath);
            IWorkbook workbook     = await application.Workbooks.OpenAsync(fileStream);

            //The first worksheet object in the worksheets collection is accessed.
            IWorksheet worksheet = workbook.Worksheets[0];
            worksheet.UsedRange.AutofitColumns();
            #endregion

            #region Save the Workbook
            StorageFile storageFile;
            if (!(Windows.Foundation.Metadata.ApiInformation.IsTypePresent("Windows.Phone.UI.Input.HardwareButtons")))
            {
                FileSavePicker savePicker = new FileSavePicker();
                savePicker.SuggestedStartLocation = PickerLocationId.Desktop;
                savePicker.SuggestedFileName      = "DataTemplate";
                savePicker.FileTypeChoices.Add("Excel Files", new List <string>()
                {
                    ".xlsx",
                });
                storageFile = await savePicker.PickSaveFileAsync();
            }
            else
            {
                StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder;
                storageFile = await local.CreateFileAsync("DataTemplate.xlsx", CreationCollisionOption.ReplaceExisting);
            }


            if (storageFile != null)
            {
                //Saving the workbook
                await workbook.SaveAsAsync(storageFile);

                workbook.Close();
                excelEngine.Dispose();

                MessageDialog msgDialog = new MessageDialog("Do you want to view the Document?", "File has been saved successfully.");

                UICommand yesCmd = new UICommand("Yes");
                msgDialog.Commands.Add(yesCmd);
                UICommand noCmd = new UICommand("No");
                msgDialog.Commands.Add(noCmd);
                IUICommand cmd = await msgDialog.ShowAsync();

                if (cmd == yesCmd)
                {
                    // Launch the saved file
                    bool success = await Windows.System.Launcher.LaunchFileAsync(storageFile);
                }
            }
            else
            {
                workbook.Close();
                excelEngine.Dispose();
            }
            #endregion
        }
        private async void Save(bool isDocFormat, WordDocument document)
        {
            StorageFile stgFile;

            if (!(Windows.Foundation.Metadata.ApiInformation.IsTypePresent("Windows.Phone.UI.Input.HardwareButtons")))
            {
                FileSavePicker savePicker = new FileSavePicker();
                savePicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
                // Dropdown of file types the user can save the file as
                if (isDocFormat)
                {
                    savePicker.FileTypeChoices.Add("Word Document", new List <string>()
                    {
                        ".doc"
                    });
                }
                else
                {
                    savePicker.FileTypeChoices.Add("Word Document", new List <string>()
                    {
                        ".docx"
                    });
                }
                // Default file name if the user does not type one in or select a file to replace
                savePicker.SuggestedFileName = "Sample";
                stgFile = await savePicker.PickSaveFileAsync();
            }
            else
            {
                StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder;
                stgFile = await local.CreateFileAsync("WordDocument.docx", CreationCollisionOption.ReplaceExisting);
            }
            if (stgFile != null)
            {
                MemoryStream stream = new MemoryStream();
                if (isDocFormat)
                {
                    await document.SaveAsync(stream, FormatType.Doc);
                }
                else
                {
                    await document.SaveAsync(stream, FormatType.Docx);
                }
                document.Close();
                stream.Position = 0;
                Windows.Storage.Streams.IRandomAccessStream fileStream = await stgFile.OpenAsync(FileAccessMode.ReadWrite);

                Stream st = fileStream.AsStreamForWrite();
                st.SetLength(0);
                st.Write((stream as MemoryStream).ToArray(), 0, (int)stream.Length);
                st.Flush();
                st.Dispose();
                fileStream.Dispose();

                //Save as Docx Format

                MessageDialog msgDialog = new MessageDialog("Do you want to view the Document?", "File has been created successfully.");
                UICommand     yesCmd    = new UICommand("Yes");
                msgDialog.Commands.Add(yesCmd);
                UICommand noCmd = new UICommand("No");
                msgDialog.Commands.Add(noCmd);
                IUICommand cmd = await msgDialog.ShowAsync();

                if (cmd == yesCmd)
                {
                    // Launch the retrieved file
                    bool success = await Windows.System.Launcher.LaunchFileAsync(stgFile);
                }
            }
        }
Beispiel #18
0
        public static async Task <string> LoginBilibili(string UserName, string Password)
        {
            try
            {
                //发送第一次请求,得到access_key
                WebClientClass wc  = new WebClientClass();
                string         url = "https://api.bilibili.com/login?appkey=422fd9d7289a1dd9&platform=wp&pwd=" + WebUtility.UrlEncode(Password) + "&type=json&userid=" + WebUtility.UrlEncode(UserName);


                string results = await wc.GetResults(new Uri(url));

                //Json解析及数据判断
                LoginModel model = new LoginModel();
                model = JsonConvert.DeserializeObject <LoginModel>(results);
                if (model.code == -627)
                {
                    return("登录失败,密码错误!");
                }
                if (model.code == -626)
                {
                    return("登录失败,账号不存在!");
                }
                if (model.code == -625)
                {
                    return("密码错误多次");
                }
                if (model.code == -628)
                {
                    return("未知错误");
                }
                if (model.code == -1)
                {
                    return("登录失败,程序注册失败!请联系作者!");
                }
                Windows.Web.Http.HttpClient hc = new Windows.Web.Http.HttpClient();
                if (model.code == 0)
                {
                    access_key = model.access_key;
                    Windows.Web.Http.HttpResponseMessage hr2 = await hc.GetAsync(new Uri("http://api.bilibili.com/login/sso?&access_key=" + model.access_key + "&appkey=422fd9d7289a1dd9&platform=wp"));

                    hr2.EnsureSuccessStatusCode();
                    StorageFolder folder = ApplicationData.Current.LocalFolder;
                    StorageFile   file   = await folder.CreateFileAsync("us.bili", CreationCollisionOption.OpenIfExists);

                    await FileIO.WriteTextAsync(file, model.access_key);
                }
                //看看存不存在Cookie
                HttpBaseProtocolFilter hb = new HttpBaseProtocolFilter();
                HttpCookieCollection   cookieCollection = hb.CookieManager.GetCookies(new Uri("http://bilibili.com/"));

                List <string> ls = new List <string>();
                foreach (HttpCookie item in cookieCollection)
                {
                    ls.Add(item.Name);
                }
                if (ls.Contains("DedeUserID"))
                {
                    return("登录成功");
                }
                else
                {
                    return("登录失败");
                }
            }
            catch (Exception ex)
            {
                if (ex.HResult == -2147012867)
                {
                    return("登录失败,检查你的网络连接!");
                }
                else
                {
                    return("登录发生错误");
                }
            }
        }
Beispiel #19
0
        public async void CtpToJHTransition(List <State> CtpData)
        {
            StorageFolder exportFolder = null;

            if (StorageApplicationPermissions.FutureAccessList.ContainsItem("ExportFolder"))
            {
                DateTime currentDate = new DateTime(2020, 3, 2);
                DateTime endDate     = new DateTime(2020, 4, 11);
                while (currentDate <= endDate)
                {
                    exportFolder = await StorageApplicationPermissions.FutureAccessList.GetFolderAsync("ExportFolder");

                    StorageFile csvFile = await exportFolder?.CreateFileAsync(currentDate.Date.ToString("MM-dd-yyyy", CultureInfo.InvariantCulture) + ".csv", Windows.Storage.CreationCollisionOption.ReplaceExisting);

                    using (CsvFileWriter dataWriter = new CsvFileWriter(await csvFile.OpenStreamForWriteAsync()))
                    {
                        CsvRow headerRow = new CsvRow();
                        headerRow.Add("Province_State");
                        headerRow.Add("Country_Region");
                        headerRow.Add("Last_Update");
                        headerRow.Add("Lat");
                        headerRow.Add("Long_");
                        headerRow.Add("Confirmed");
                        headerRow.Add("Deaths");
                        headerRow.Add("Recovered");
                        headerRow.Add("Active");
                        headerRow.Add("FIPS");
                        headerRow.Add("Incident_Rate");
                        headerRow.Add("Total_Test_Results");
                        headerRow.Add("People_Hospitalized");
                        headerRow.Add("Case_Fatality_Ratio");
                        headerRow.Add("UID");
                        headerRow.Add("ISO3");
                        headerRow.Add("Testing_Rate");
                        headerRow.Add("Testing_Rate");

                        dataWriter.WriteRow(headerRow);
                        foreach (State s in CtpData)
                        {
                            var dataPoint = s.CovidData.FirstOrDefault(dat => dat.Date.ToString("MM-dd-yyyy", CultureInfo.InvariantCulture) == currentDate.Date.ToString("MM-dd-yyyy", CultureInfo.InvariantCulture));
                            if (dataPoint != null)
                            {
                                CsvRow nextRow = new CsvRow();
                                nextRow.Add(StateMapHelper.StateBaseToString(s.StateBase.Name));
                                nextRow.Add("US");
                                nextRow.Add(currentDate.Date.ToString("MM-dd-yyyy", CultureInfo.InvariantCulture) + " 4:30:00 PM");
                                nextRow.Add("");
                                nextRow.Add("");

                                if (dataPoint.Positive != null)
                                {
                                    nextRow.Add(dataPoint.Positive.ToString());
                                }
                                else
                                {
                                    nextRow.Add("0");
                                }

                                if (dataPoint.Death != null)
                                {
                                    nextRow.Add(dataPoint.Death.ToString());
                                }
                                else
                                {
                                    nextRow.Add("0");
                                }

                                nextRow.Add(""); //Recovered
                                nextRow.Add(""); //active
                                nextRow.Add(""); // FIPS
                                nextRow.Add(""); // Incident_Rate

                                if (dataPoint.TotalTestResults != null)
                                {
                                    nextRow.Add(dataPoint.TotalTestResults.ToString());
                                }
                                else
                                {
                                    nextRow.Add("0");
                                }

                                if (dataPoint.Hospitalized != null)
                                {
                                    nextRow.Add(dataPoint.Hospitalized.ToString());
                                }
                                else
                                {
                                    nextRow.Add("0");
                                }

                                if (dataPoint.Positive > 0)
                                {
                                    nextRow.Add(((Convert.ToDouble(dataPoint.Death) / Convert.ToDouble(dataPoint.Positive)) * 100).ToString());
                                }
                                else
                                {
                                    nextRow.Add("0.0");
                                }
                                nextRow.Add(""); // UID
                                nextRow.Add(""); // ISO3
                                nextRow.Add(""); // TestingRate
                                nextRow.Add(""); // Hospitalization Rate

                                dataWriter.WriteRow(nextRow);
                            }
                            else
                            {
                                CsvRow nextRow = new CsvRow();
                                nextRow.Add(s.StateBase.Name.ToString());
                                nextRow.Add("US");
                                nextRow.Add(currentDate.Date.ToString("MM-dd-yyyy", CultureInfo.InvariantCulture) + " 4:30:00 PM");
                                nextRow.Add("");
                                nextRow.Add("");
                                nextRow.Add("0");
                                nextRow.Add("0");
                                nextRow.Add(""); //Recovered
                                nextRow.Add(""); //active
                                nextRow.Add(""); // FIPS
                                nextRow.Add(""); // Incident_Rate
                                nextRow.Add("0");
                                nextRow.Add("0");
                                nextRow.Add("0.0");
                                nextRow.Add(""); // UID
                                nextRow.Add(""); // ISO3
                                nextRow.Add(""); // TestingRate
                                nextRow.Add(""); // Hospitalization Rate

                                dataWriter.WriteRow(nextRow);
                            }
                        }

                        currentDate = currentDate + new TimeSpan(1, 0, 0, 0);
                    }
                }
            }
        }
    /// <summary>
    /// Recognize the text from handwriting using Microsoft Azure service.
    /// </summary>
    public async void RecognizeInking(IReadOnlyList <InkStroke> strokeList, double pageWidth, double pageHeight)
    {
        // Current bounding box for the strokes.
        double tlX = double.MaxValue;
        double tlY = double.MaxValue;
        double brX = 0;
        double brY = 0;

        inkingStatus = SERVICE_STATUS.PENDING;
        // Make a copy of this list
        List <InkStroke> newList = new List <InkStroke>();

        foreach (InkStroke ss in strokeList)
        {
            newList.Add(ss);

            tlX = Math.Min(tlX, ss.BoundingRect.Left);
            tlY = Math.Min(tlY, ss.BoundingRect.Top);
            brX = Math.Max(brX, ss.BoundingRect.Right);
            brY = Math.Max(brY, ss.BoundingRect.Bottom);
        }
        double originalCroppedWidth  = brX - tlX;
        double originalCroppedHeight = brY - tlY;

        // Create boundary
        tlX = Math.Max(0, tlX - originalCroppedWidth * 0.2);
        tlY = Math.Max(0, tlY - originalCroppedHeight * 0.4);
        brX = Math.Min(pageWidth, brX + originalCroppedWidth * 0.2);
        brY = Math.Min(pageHeight, brY + originalCroppedHeight * 0.4);
        originalCroppedWidth  = brX - tlX;
        originalCroppedHeight = brY - tlY;

        StorageFolder storageFolder = KnownFolders.CameraRoll;
        var           file          = await storageFolder.CreateFileAsync("sampleInking.jpg", CreationCollisionOption.GenerateUniqueName);

        // Render a whole image (paper size * inking scale)
        CanvasDevice       device       = CanvasDevice.GetSharedDevice();
        CanvasRenderTarget renderTarget = new CanvasRenderTarget(device, (float)pageWidth, (float)pageHeight, 96);

        //await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
        //    () =>
        //    {
        //        using (var ds = renderTarget.CreateDrawingSession())
        //        {
        //            ds.Clear(Colors.White);
        //            ds.DrawInk(strokeList);
        //        }
        //    });
        using (var ds = renderTarget.CreateDrawingSession())
        {
            ds.Clear(Colors.White);
            ds.DrawInk(newList);
        }

        // Crop the image: using same algorithm as in OCR method.
        // croppedBytes: image bytes.
        // byteData: final format, with bmp header.
        byte[] byteData = new byte[1];
        byte[] croppedBytes = new byte[1];
        uint   width = 0, height = 0;

        using (var fileStream = await file.OpenAsync(FileAccessMode.ReadWrite))
        {
            await renderTarget.SaveAsync(fileStream, CanvasBitmapFileFormat.Jpeg, 1f);

            //Debug.Log("Save to:" + file.Name);

            // Crop this image.
            // Create a decoder from the stream. With the decoder, we can get the properties of the image.
            BitmapDecoder decoder = await BitmapDecoder.CreateAsync(fileStream);

            // make sure the image is larger than 50x50 in real pixels.
            double scale = Math.Max(1.0f, Math.Max(AZURE_API_MIN_SIZE / originalCroppedWidth, AZURE_API_MIN_SIZE / originalCroppedHeight));

            uint startPointX = (uint)Math.Floor(tlX * scale);
            uint startPointY = (uint)Math.Floor(tlY * scale);
            width  = (uint)Math.Floor(originalCroppedWidth * scale);
            height = (uint)Math.Floor(originalCroppedHeight * scale);

            // The scaledSize of original image.
            uint scaledWidth  = (uint)Math.Floor(decoder.PixelWidth * scale);
            uint scaledHeight = (uint)Math.Floor(decoder.PixelHeight * scale);

            // Refine the start point and the size.
            if (startPointX + width > scaledWidth)
            {
                startPointX = scaledWidth - width;
            }

            if (startPointY + height > scaledHeight)
            {
                startPointY = scaledHeight - height;
            }

            // Get the cropped pixels.
            BitmapTransform transform = new BitmapTransform();
            BitmapBounds    bounds    = new BitmapBounds();
            bounds.X         = startPointX;
            bounds.Y         = startPointY;
            bounds.Height    = height;
            bounds.Width     = width;
            transform.Bounds = bounds;

            transform.ScaledWidth  = scaledWidth;
            transform.ScaledHeight = scaledHeight;

            // Get the cropped pixels within the bounds of transform.
            PixelDataProvider pix = await decoder.GetPixelDataAsync(
                BitmapPixelFormat.Bgra8,
                BitmapAlphaMode.Straight,
                transform,
                ExifOrientationMode.IgnoreExifOrientation,
                ColorManagementMode.ColorManageToSRgb);

            croppedBytes = pix.DetachPixelData();
            //Debug.Log(string.Format("Crop Handwritten image: start: {0},{1}, width:{2}, height:{3}", bounds.X, bounds.Y, bounds.Width, bounds.Height));
        }
        await file.DeleteAsync();

        // Again, I have to save to file stream byte[] to image.
        // https://code.msdn.microsoft.com/windowsapps/How-to-save-WriteableBitmap-bd23d455
        var tempFile = await storageFolder.CreateFileAsync("temp-sampleInking.jpg", CreationCollisionOption.GenerateUniqueName);

        using (var stream = await tempFile.OpenAsync(FileAccessMode.ReadWrite))
        {
            BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, stream);

            encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, width, height, 96, 96, croppedBytes);
            await encoder.FlushAsync();

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

            reader.ReadBytes(byteData);
        }
        await tempFile.DeleteAsync();

        //ReadHandwrittenText("");
        HttpClient client = new HttpClient();

        // Request headers.
        client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", azureKey);

        // Request parameter. Set "handwriting" to false for printed text.
        string requestParameters = "handwriting=true";

        // Assemble the URI for the REST API Call.
        string uri = azureUri + "recognizeText?" + requestParameters;

        HttpResponseMessage response = null;

        // This operation requrires two REST API calls. One to submit the image for processing,
        // the other to retrieve the text found in the image. This value stores the REST API
        // location to call to retrieve the text.
        string operationLocation = null;

        // Request body. Posts a locally stored JPEG image.
        //byte[] byteData = canvasImg;

        ByteArrayContent content = new ByteArrayContent(byteData);

        // This example uses content type "application/octet-stream".
        // You can also use "application/json" and specify an image URL.
        content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");

        // The first REST call starts the async process to analyze the written text in the image.
        response = await client.PostAsync(uri, content);

        // The response contains the URI to retrieve the result of the process.
        if (response.IsSuccessStatusCode)
        {
            operationLocation = response.Headers.GetValues("Operation-Location").FirstOrDefault();
        }
        else
        {
            // Display the JSON error data.
            string errInfo = "RecognizeInking: PosyAsync Response Error." + response.StatusCode.ToString();
            inkingResult = errInfo;
            inkingStatus = SERVICE_STATUS.ERROR;
            Debug.Log(errInfo + "\n");
            //Debug.Log(JsonPrettyPrint(await response.Content.ReadAsStringAsync()));
            return;
        }

        // The second REST call retrieves the text written in the image.
        //
        // Note: The response may not be immediately available. Handwriting recognition is an
        // async operation that can take a variable amount of time depending on the length
        // of the handwritten text. You may need to wait or retry this operation.
        //
        // This example checks once per second for ten seconds.
        string contentString;
        int    i = 0;

        do
        {
            await Task.Delay(1000);

            response = await client.GetAsync(operationLocation);

            contentString = await response.Content.ReadAsStringAsync();

            ++i;
        }while (i < 10 && contentString.IndexOf("\"status\":\"Succeeded\"") == -1);

        if (i == 10 && contentString.IndexOf("\"status\":\"Succeeded\"") == -1)
        {
            string errInfo = "RecognizeInking: Timeout Error.";
            inkingResult = errInfo;
            Debug.Log(errInfo + "\n");
            inkingStatus = SERVICE_STATUS.ERROR;
            return;
        }

        // Display the JSON response.
        //Debug.Log("\nResponse:\n");
        //Debug.Log(JsonPrettyPrint(contentString));
        // Parse to output the result.
        var result = JsonConvert.DeserializeObject <JSONInking.RootObject>(contentString).recognitionResult;
        var texts  = new List <string>();

        foreach (var line in result.lines)
        {
            texts.Add(line.text);
        }

        if (texts.Count > 0)
        {
            inkingResult = string.Join(" ", texts);
            //Debug.Log("Inking Recognition succeeded:" + inkingResult);
            inkingStatus = SERVICE_STATUS.DONE;
        }
        else
        {
            string errInfo = "Inking Recognition succeeded but the result is empty.";
            inkingResult = errInfo;
            Debug.Log(errInfo);
            inkingStatus = SERVICE_STATUS.ERROR;
        }
    }
    //public List<ARDocument> academicResult = new List<ARDocument>();
    //public string academicErrInfo = "";

    //public List<ARDocument> parseResults = null;

#if !UNITY_EDITOR
    /// <summary>
    /// Do OCR with Azure service
    /// </summary>
    /// <param name="imageName">Image path in CameraRoll</param>
    /// <param name="topLeft"></param>
    /// <param name="botRight"></param>
    public async void MakeOCRRequest(string imageName, Vector2 topLeft, Vector2 botRight)
    {
        // Check the boundary
        double widthRatio  = botRight.x - topLeft.x;
        double heightRatio = botRight.y - topLeft.y;

        ocrStatus = SERVICE_STATUS.PENDING;
        Debug.Log(string.Format("OCR on file:{0}, start point {1}, size {2}, {3}", imageName, topLeft.ToString(), widthRatio, heightRatio));

        HttpClient client = new HttpClient();

        // Request headers.
        client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", azureKey);

        // Request parameters.
        string requestParameters = "language=en&detectOrientation=true";

        // Assemble the URI for the REST API Call.
        string uri = azureUri + "ocr?" + requestParameters;

        HttpResponseMessage response;

        // Request body. Posts a locally stored JPEG image.
        byte[] byteData     = new byte[1];
        byte[] croppedBytes = new byte[1];

        /* Crop Function by Diederik Krols.
         * Refer: https://github.com/XamlBrewer/UWP-ImageCropper-/blob/master/XamlBrewer.Uwp.Controls/Helpers/CropBitmap.cs
         * */
        StorageFolder storageFolder = KnownFolders.CameraRoll;
        var           file          = (StorageFile)await storageFolder.TryGetItemAsync(imageName);

        uint width = 0, height = 0;

        if (file == null)
        {
            string errInfo = "MakeOCRRequest Error: Image File not exist." + imageName;
            Debug.Log(errInfo);
            ocrResult = errInfo;
            ocrStatus = SERVICE_STATUS.ERROR;
            return;
        }

        using (var stream = await file.OpenAsync(FileAccessMode.Read))
        {
            // Create a decoder from the stream. With the decoder, we can get the properties of the image.
            BitmapDecoder decoder = await BitmapDecoder.CreateAsync(stream);

            double originalCroppedWidth  = decoder.PixelWidth * widthRatio + 2;
            double originalCroppedHeight = decoder.PixelHeight * heightRatio + 2;
            // make sure the image is larger than 50x50 in real pixels.
            double scale = Math.Max(1.0f, Math.Max(AZURE_API_MIN_SIZE / originalCroppedWidth, AZURE_API_MIN_SIZE / originalCroppedHeight));

            uint startPointX = (uint)Math.Floor(decoder.PixelWidth * topLeft.x * scale) - 1;
            uint startPointY = (uint)Math.Floor(decoder.PixelHeight * topLeft.y * scale) - 1;
            width  = (uint)Math.Floor(originalCroppedWidth * scale);
            height = (uint)Math.Floor(originalCroppedHeight * scale);

            // The scaledSize of original image.
            uint scaledWidth  = (uint)Math.Floor(decoder.PixelWidth * scale);
            uint scaledHeight = (uint)Math.Floor(decoder.PixelHeight * scale);

            // Refine the start point and the size.
            if (startPointX + width > scaledWidth)
            {
                startPointX = scaledWidth - width;
            }

            if (startPointY + height > scaledHeight)
            {
                startPointY = scaledHeight - height;
            }

            // Get the cropped pixels.
            BitmapTransform transform = new BitmapTransform();
            BitmapBounds    bounds    = new BitmapBounds();
            bounds.X         = startPointX;
            bounds.Y         = startPointY;
            bounds.Height    = height;
            bounds.Width     = width;
            transform.Bounds = bounds;

            transform.ScaledWidth  = scaledWidth;
            transform.ScaledHeight = scaledHeight;

            // Get the cropped pixels within the bounds of transform.
            PixelDataProvider pix = await decoder.GetPixelDataAsync(
                BitmapPixelFormat.Bgra8,
                BitmapAlphaMode.Straight,
                transform,
                ExifOrientationMode.IgnoreExifOrientation,
                ColorManagementMode.ColorManageToSRgb);

            croppedBytes = pix.DetachPixelData();
        }

        // Again, I have to save to file stream

        /* byte[] to image.
         * https://code.msdn.microsoft.com/windowsapps/How-to-save-WriteableBitmap-bd23d455
         * */
        var tempFile = await storageFolder.CreateFileAsync("tempOCR.jpg", CreationCollisionOption.GenerateUniqueName);

        using (var stream = await tempFile.OpenAsync(FileAccessMode.ReadWrite))
        {
            BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, stream);

            encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, width, height, 96, 96, croppedBytes);
            await encoder.FlushAsync();

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

            reader.ReadBytes(byteData);
        }
        await tempFile.DeleteAsync();

        using (ByteArrayContent content = new ByteArrayContent(byteData))
        {
            // This example uses content type "application/octet-stream".
            // The other content types you can use are "application/json" and "multipart/form-data".
            content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");

            // Execute the REST API call.
            response = await client.PostAsync(uri, content);

            // Get the JSON response.
            string contentString = await response.Content.ReadAsStringAsync();

            // Display the JSON response.
            Debug.Log("\nResponse:\n");
            Debug.Log(JsonPrettyPrint(contentString));

            // Parse to output the result.
            var result = JsonConvert.DeserializeObject <JSONOCR.RootObject>(contentString);
            var texts  = new List <string>();
            foreach (var region in result.regions)
            {
                foreach (var line in region.lines)
                {
                    foreach (var word in line.words)
                    {
                        texts.Add(word.text);
                    }
                }
            }
            if (texts.Count > 0)
            {
                ocrResult = string.Join(" ", texts);
                Debug.Log("MakeOCRRequest succeeded:" + ocrResult);
                ocrStatus = SERVICE_STATUS.DONE;
            }
            else
            {
                string errInfo = "MakeOCRRequest succeeded but the result is empty.";
                ocrResult = errInfo;
                Debug.Log(errInfo);
                ocrStatus = SERVICE_STATUS.ERROR;
            }
        }
    }
        private async void btnCreate_Click(object sender, RoutedEventArgs e)
        {
            #region Setting output location


            StorageFile storageFile;
            if (!(Windows.Foundation.Metadata.ApiInformation.IsTypePresent("Windows.Phone.UI.Input.HardwareButtons")))
            {
                FileSavePicker savePicker = new FileSavePicker();
                savePicker.SuggestedStartLocation = PickerLocationId.Desktop;
                savePicker.SuggestedFileName      = "AutoShapesSample";
                savePicker.FileTypeChoices.Add("Excel Files", new List <string>()
                {
                    ".xlsx",
                });
                storageFile = await savePicker.PickSaveFileAsync();
            }
            else
            {
                StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder;
                storageFile = await local.CreateFileAsync("AutoShapesSample.xlsx", CreationCollisionOption.ReplaceExisting);
            }

            if (storageFile == null)
            {
                return;
            }
            #endregion

            #region Initializing Workbook
            ExcelEngine  excelEngine = new ExcelEngine();
            IApplication application = excelEngine.Excel;

            //if (this.rdBtn2013.IsChecked.Value)
            application.DefaultVersion = ExcelVersion.Excel2013;
            //else if (this.rdBtn2010.IsChecked.Value)
            //    application.DefaultVersion = ExcelVersion.Excel2010;
            //else
            //   application.DefaultVersion = ExcelVersion.Excel2007;


            IWorkbook  workbook  = application.Workbooks.Create(1);
            IWorksheet worksheet = workbook.Worksheets[0];
            #endregion

            #region AddAutoShapes
            IShape shape;
            string text;

            IFont font = workbook.CreateFont();
            font.Color  = ExcelKnownColors.White;
            font.Italic = true;
            font.Size   = 12;


            IFont font2 = workbook.CreateFont();
            font2.Color  = ExcelKnownColors.Black;
            font2.Size   = 15;
            font2.Italic = true;
            font2.Bold   = true;

            text  = "Requirement";
            shape = worksheet.Shapes.AddAutoShapes(AutoShapeType.RoundedRectangle, 2, 7, 60, 192);
            shape.TextFrame.TextRange.Text = text;
            shape.TextFrame.TextRange.RichText.SetFont(0, text.Length - 1, font);
            shape.TextFrame.TextRange.RichText.SetFont(0, 0, font2);
            shape.Fill.ForeColorIndex         = ExcelKnownColors.Light_blue;
            shape.Line.Visible                = false;
            shape.TextFrame.VerticalAlignment = ExcelVerticalAlignment.MiddleCentered;

            shape = worksheet.Shapes.AddAutoShapes(AutoShapeType.DownArrow, 5, 8, 40, 64);
            shape.Fill.ForeColorIndex = ExcelKnownColors.White;
            shape.Line.ForeColorIndex = ExcelKnownColors.Blue;
            shape.Line.Weight         = 1;

            text  = "Design";
            shape = worksheet.Shapes.AddAutoShapes(AutoShapeType.RoundedRectangle, 7, 7, 60, 192);
            shape.TextFrame.TextRange.Text = text;
            shape.TextFrame.TextRange.RichText.SetFont(0, text.Length - 1, font);
            shape.TextFrame.TextRange.RichText.SetFont(0, 0, font2);
            shape.Line.Visible                = false;
            shape.Fill.ForeColorIndex         = ExcelKnownColors.Light_orange;
            shape.TextFrame.VerticalAlignment = ExcelVerticalAlignment.MiddleCentered;


            shape = worksheet.Shapes.AddAutoShapes(AutoShapeType.DownArrow, 10, 8, 40, 64);
            shape.Fill.ForeColorIndex = ExcelKnownColors.White;
            shape.Line.ForeColorIndex = ExcelKnownColors.Blue;
            shape.Line.Weight         = 1;

            text  = "Execution";
            shape = worksheet.Shapes.AddAutoShapes(AutoShapeType.RoundedRectangle, 12, 7, 60, 192);
            shape.TextFrame.TextRange.Text = text;
            shape.TextFrame.TextRange.RichText.SetFont(0, text.Length - 1, font);
            shape.TextFrame.TextRange.RichText.SetFont(0, 0, font2);
            shape.Line.Visible                = false;
            shape.Fill.ForeColorIndex         = ExcelKnownColors.Blue;
            shape.TextFrame.VerticalAlignment = ExcelVerticalAlignment.MiddleCentered;

            shape = worksheet.Shapes.AddAutoShapes(AutoShapeType.DownArrow, 15, 8, 40, 64);
            shape.Fill.ForeColorIndex = ExcelKnownColors.White;
            shape.Line.ForeColorIndex = ExcelKnownColors.Blue;
            shape.Line.Weight         = 1;

            text  = "Testing";
            shape = worksheet.Shapes.AddAutoShapes(AutoShapeType.RoundedRectangle, 17, 7, 60, 192);
            shape.TextFrame.TextRange.Text = text;
            shape.TextFrame.TextRange.RichText.SetFont(0, text.Length - 1, font);
            shape.TextFrame.TextRange.RichText.SetFont(0, 0, font2);
            shape.Line.Visible                = false;
            shape.Fill.ForeColorIndex         = ExcelKnownColors.Green;
            shape.TextFrame.VerticalAlignment = ExcelVerticalAlignment.MiddleCentered;

            shape = worksheet.Shapes.AddAutoShapes(AutoShapeType.DownArrow, 20, 8, 40, 64);
            shape.Fill.ForeColorIndex = ExcelKnownColors.White;
            shape.Line.ForeColorIndex = ExcelKnownColors.Blue;
            shape.Line.Weight         = 1;

            text  = "Release";
            shape = worksheet.Shapes.AddAutoShapes(AutoShapeType.RoundedRectangle, 22, 7, 60, 192);
            shape.TextFrame.TextRange.Text = text;
            shape.TextFrame.TextRange.RichText.SetFont(0, text.Length - 1, font);
            shape.TextFrame.TextRange.RichText.SetFont(0, 0, font2);
            shape.Line.Visible                = false;
            shape.Fill.ForeColorIndex         = ExcelKnownColors.Lavender;
            shape.TextFrame.VerticalAlignment = ExcelVerticalAlignment.MiddleCentered;
            #endregion


            #region Saving workbook and disposing objects

            await workbook.SaveAsAsync(storageFile);

            workbook.Close();
            excelEngine.Dispose();

            #endregion

            #region Save accknowledgement and Launching of output file
            MessageDialog msgDialog = new MessageDialog("Do you want to view the Document?", "File has been created successfully.");

            UICommand yesCmd = new UICommand("Yes");
            msgDialog.Commands.Add(yesCmd);
            UICommand noCmd = new UICommand("No");
            msgDialog.Commands.Add(noCmd);
            IUICommand cmd = await msgDialog.ShowAsync();

            if (cmd == yesCmd)
            {
                // Launch the saved file
                bool success = await Windows.System.Launcher.LaunchFileAsync(storageFile);
            }
            #endregion
        }