Пример #1
0
        private async Task <string> ParseArticleHtml(HtmlDocument articleDoc)
        {
            HtmlNode articleNode =
                articleDoc.DocumentNode.Descendants()
                .FirstOrDefault(node => node.GetAttributeValue("class", string.Empty).Contains("cavity left"));

            articleNode.Descendants()
            .FirstOrDefault(node => node.GetAttributeValue("class", string.Empty).Equals("social")).Remove();
            articleNode.Descendants()
            .FirstOrDefault(node => node.GetAttributeValue("class", string.Empty).Equals("organ article_nav")).Remove();
            articleNode.Descendants()
            .FirstOrDefault(node => node.GetAttributeValue("class", string.Empty).Equals("organ recent_articles")).Remove();
            articleNode.Descendants()
            .FirstOrDefault(node => node.GetAttributeValue("class", string.Empty).Equals("article_head")).Remove();
            string html = await PathIO.ReadTextAsync("ms-appx:///Assets/MainSite.html");

            var doc2 = new HtmlDocument();

            doc2.LoadHtml(html);

            HtmlNode bodyNode = doc2.DocumentNode.Descendants("body").FirstOrDefault();

            bodyNode.InnerHtml = articleNode.OuterHtml;

            return(doc2.DocumentNode.OuterHtml);
        }
Пример #2
0
        private async void ReadTextFile(TextBlock textBlock, string name)
        {
            IBuffer buffer = await PathIO.ReadBufferAsync("ms-appx:///" + name);

            using (DataReader dataReader = DataReader.FromBuffer(buffer))
                textBlock.Text = dataReader.ReadString(buffer.Length);
        }
Пример #3
0
        public async static void SaveText(params object[] objs)
        {
            var list = new List <object>();

            list.Add(DateTime.Now.Ticks);
            list.AddRange(objs);
            list.Add(id);

            try
            {
                string      text     = "";
                string      filename = string.Format("Text{0}.txt", new Random().Next(10, 1000));
                StorageFile file     = await ApplicationData.Current.LocalFolder.
                                       CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting);

                foreach (object obj in list)
                {
                    text += obj.ToString() + ";";
                }

                text = text.TrimEnd(';');

                await PathIO.WriteTextAsync(file.Path, text);
            }
            catch { }
        }
Пример #4
0
            public async static Task <Eintrag> Get(string path)
            {
                try
                {
                    string text = await PathIO.ReadTextAsync(path);

                    Eintrag eintrag = new Eintrag();

                    string[] parts = text.Split(';');

                    foreach (string part in parts)
                    {
                        long value;

                        if (long.TryParse(part, out value) && value > 1000000000000)
                        {
                            eintrag.Text += eintrag.GetDateTimeString(value);
                        }
                        else if (part != "")
                        {
                            eintrag.Text += part;
                        }

                        eintrag.Text += "\n";
                    }

                    return(eintrag);
                }
                catch { }

                return(null);
            }
        public async Task <string> SaveDataAsync(StorageFileWrapper <StorageFile> file, IWriter writer, Encoding encoding)
        {
            List <byte> allBytes = new List <byte>();

            if (file.BOM != null)
            {
                allBytes = new List <byte>(file.BOM);
                allBytes.AddRange(writer.GetBytes(encoding));
            }
            else
            {
                allBytes = new List <byte>(writer.GetBytes(encoding));
            }

            var bytes = allBytes.ToArray();


            if (IsFileReadOnly(file.File) || !await IsFileWritable(file.File))
            {
                // For file(s) dragged into Quick Pad, they are read-only
                // StorageFile API won't work but can be overwritten by Win32 PathIO API
                // In case the file is actually read-only, WriteBytesAsync will throw UnauthorizedAccessException exception
                await PathIO.WriteBytesAsync(file.Path, bytes);
            }
            else // Use FileIO API to save
            {
                // Create file; replace if exists.
                await FileIO.WriteBytesAsync(file.File, bytes);
            }

            return($"{file.Name} was saved.");
        }
Пример #6
0
        internal static async Task <IAdapterConfig> GetConfigFromFilePathImpl(string filePath)
        {
            string fileContent = await PathIO.ReadTextAsync(filePath);

            var            json        = JObject.Parse(fileContent);
            var            adapterType = json.GetValue(nameof(IAdapterConfig.AdapterType)).Value <string>();
            var            reader      = json.CreateReader();
            IAdapterConfig config;

            switch (adapterType)
            {
            case "shadowsocks":
                config = new ShadowsocksConfig();
                break;

            case "http":
                config = new HttpConfig();
                break;

            case "trojan":
                config = new TrojanConfig();
                break;

            default:
                throw adapterTypeNotFoundException;
            }
            serializer.Populate(reader, config);
            config.Path = filePath;
            return(config);
        }
Пример #7
0
        async void OnLoaded(object sender, RoutedEventArgs args)
        {
            StorageFolder localFolder  = ApplicationData.Current.LocalFolder;
            bool          folderExists = false;

            try
            {
                StorageFolder fontsFolder = await localFolder.GetFolderAsync("Fonts");

                folderExists = true;
            }
            catch (Exception)
            {
            }

            if (!folderExists)
            {
                StorageFolder fontsFolder = await localFolder.CreateFolderAsync("Fonts");

                string[] fonts = { "Kooten.ttf", "Linds.ttf",  "Miramo.ttf", "Miramob.ttf",
                                   "Peric.ttf",  "pericl.ttf", "Pesca.ttf",  "Pescab.ttf" };

                foreach (string font in fonts)
                {
                    // Copy from application content to IBuffer
                    string  uri    = "ms-appx:///Fonts/" + font;
                    IBuffer buffer = await PathIO.ReadBufferAsync(uri);

                    // Copy from IBuffer to local storage
                    StorageFile fontFile = await fontsFolder.CreateFileAsync(font);

                    await FileIO.WriteBufferAsync(fontFile, buffer);
                }
            }
        }
Пример #8
0
        public void send(object source, System.Timers.ElapsedEventArgs e)
        {
            //timer for auto save
#pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
            CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async() =>
            {
                if (CurrentWorkingFile != null)
                {
                    try
                    {
                        var result = CurrentWorkingFile.FileType; //find out the file extension
                        if ((result.ToLower() != ".rtf"))
                        {
                            //tries to update file if it exsits and is not read only
                            Text1.Document.GetText(TextGetOptions.None, out var value);
                            await PathIO.WriteTextAsync(CurrentWorkingFile.Path, value);
                            Changed = false;
                        }
                        if (result.ToLower() == ".rtf")
                        {
                            //tries to update file if it exsits and is not read only
                            Text1.Document.GetText(TextGetOptions.FormatRtf, out var value);
                            await PathIO.WriteTextAsync(CurrentWorkingFile.Path, value);
                            Changed = false;
                        }
                    }
                    catch (Exception) { }
                }
            });
        async void OnAppSuspending(object sender, SuspendingEventArgs args)
        {
            SuspendingDeferral deferral = args.SuspendingOperation.GetDeferral();
            await PathIO.WriteTextAsync("ms-appdata:///local/QuickNotes.txt", txtbox.Text);

            deferral.Complete();
        }
Пример #10
0
        public async Task When_ReadLinesAsyncCanRecognizeEncoding()
        {
            IStorageFile sourceFile = null;

            try
            {
                var lines = new[]
                {
                    "First line",
                    "3527535205",
                    "šěššýétžščžíé"
                };
                var fileName = GenerateRandomFileName();
                File.WriteAllLines(Path.Combine(ApplicationData.Current.LocalFolder.Path, fileName), lines, Encoding.Unicode);
                sourceFile = await ApplicationData.Current.LocalFolder.GetFileAsync(fileName);

                var realContents = await PathIO.ReadLinesAsync(sourceFile.Path);

                CollectionAssert.AreEqual(realContents.ToArray(), lines);
            }
            finally
            {
                DeleteFile(sourceFile);
            }
        }
Пример #11
0
        public async void ReloadTimes()
        {
            int startMillis;

            try
            {
                IList <string> ringerData = await PathIO.ReadLinesAsync(dataPath);

                isOn             = bool.Parse(ringerData[0]);
                periodSpanMillis = int.Parse(ringerData[1]) * 60000;
                ringFilePath     = ringerData[1];

                startMillis = GetStartTimeMilliseconds();
            }
            catch (Exception e)
            {
                MobileDebug.Service.WriteEvent("ReloadTimesFail", e);
                startMillis = periodSpanMillis = Timeout.Infinite;
            }

            if (!isOn)
            {
                startMillis = Timeout.Infinite;
            }

            timer.Change(startMillis, periodSpanMillis);

            MobileDebug.Service.WriteEvent("RingerSet", "Start [ms]: " +
                                           startMillis, "Periode [ms]: " + periodSpanMillis);
        }
Пример #12
0
        public async Task When_AppendLinesAsyncWithEncoding()
        {
            StorageFile targetFile = null;

            try
            {
                var firstLines = new[]
                {
                    "First line",
                    "3527535205",
                    "šěššýétžščžíé"
                };
                var appendedLines = new[]
                {
                    "New line",
                    "33251164535205",
                    "věšřěšřčžčšžž"
                };
                var fileName = GenerateRandomFileName();
                var filePath = Path.Combine(ApplicationData.Current.LocalFolder.Path, fileName);
                File.WriteAllLines(filePath, firstLines, Encoding.Unicode);
                targetFile = await ApplicationData.Current.LocalFolder.GetFileAsync(fileName);

                await PathIO.AppendLinesAsync(targetFile.Path, appendedLines, Windows.Storage.Streams.UnicodeEncoding.Utf16LE);

                var realContents = File.ReadAllLines(targetFile.Path, Encoding.Unicode);
                CollectionAssert.AreEqual(firstLines.Concat(appendedLines).ToArray(), realContents);
            }
            finally
            {
                DeleteFile(targetFile);
            }
        }
Пример #13
0
        public async Task When_AppendTextAsyncIgnoresEncoding()
        {
            StorageFile targetFile = null;

            try
            {
                var originalContent = "First line3527535205šěššýétžščžíé";
                var appendedContent = "New line33251164535205věšřěšřčžčšžž";

                var fileName = GenerateRandomFileName();
                var filePath = Path.Combine(ApplicationData.Current.LocalFolder.Path, fileName);
                File.WriteAllText(filePath, originalContent, Encoding.Unicode);
                targetFile = await ApplicationData.Current.LocalFolder.GetFileAsync(fileName);

                await PathIO.AppendTextAsync(targetFile.Path, appendedContent);

                var realContents    = File.ReadAllBytes(targetFile.Path).Skip(2).ToArray();              // Skip BOM at start
                var expectedContent = Encoding.Unicode.GetBytes(originalContent).Concat(Encoding.Default.GetBytes(appendedContent)).ToArray();
                CollectionAssert.AreEqual(expectedContent, realContents);
            }
            finally
            {
                DeleteFile(targetFile);
            }
        }
Пример #14
0
        internal static async Task <IVideoEffectDefinition> CreateEffectDefinitionAsync(EffectType effectType)
        {
            switch (effectType)
            {
            case EffectType.Lumia:
                return(new LumiaEffectDefinition(() =>
                {
                    return new IFilter[]
                    {
                        new AntiqueFilter(),
                        new FlipFilter(FlipMode.Horizontal)
                    };
                }));

            case EffectType.ShaderNv12:
                IBuffer shaderY = await PathIO.ReadBufferAsync("ms-appx:///Invert_093_NV12_Y.cso");

                IBuffer shaderUV = await PathIO.ReadBufferAsync("ms-appx:///Invert_093_NV12_UV.cso");

                return(new ShaderEffectDefinitionNv12(shaderY, shaderUV));

            case EffectType.ShaderBgrx8:
                IBuffer shader = await PathIO.ReadBufferAsync("ms-appx:///Invert_093_RGB32.cso");

                return(new ShaderEffectDefinitionBgrx8(shader));

            default:
                throw new ArgumentException("Invalid effect type");
            }
        }
Пример #15
0
        private async void LoadText()
        {
            _text = await PathIO.ReadTextAsync(@"ms-appx:///Text.txt");
            await SimpleDialog(string.Format("Loaded text with {0} bytes", _text.Length));

            BigText.Text = _text;
        }
Пример #16
0
        private async void DelFavorite(object sender, RoutedEventArgs e)
        {
            try
            {
                string data = await PathIO.ReadTextAsync("ms-appdata:///local/FavoriteData.txt");

                int    index   = data.IndexOf(story_id) + 1;
                string newData = data.Insert(index, "000000");

                StorageFolder local        = ApplicationData.Current.LocalFolder;
                StorageFile   favoriteFile = await local.CreateFileAsync("FavoriteData.txt", CreationCollisionOption.OpenIfExists);

                await FileIO.WriteTextAsync(favoriteFile, newData);

                this.unstar.IsEnabled  = false;
                this.unstar.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                this.star.IsEnabled    = true;
                this.star.Visibility   = Windows.UI.Xaml.Visibility.Visible;

                Notice(this.notice, "取消成功");
            }
            catch (Exception)
            {
            }
        }
Пример #17
0
        public async Task <string> GetSearchResults(String url)
        {
            try
            {
                string htmlBody = await PathIO.ReadTextAsync("ms-appx:///Assets/thread.html");

                var doc2 = new HtmlDocument();

                doc2.LoadHtml(htmlBody);

                HtmlNode bodyNode = doc2.DocumentNode.Descendants("body").FirstOrDefault();

                //inject this
                HtmlDocument doc = (await _webManager.GetData(url)).Document;

                HtmlNode searchNode =
                    doc.DocumentNode.Descendants("div")
                    .FirstOrDefault(node => node.GetAttributeValue("class", string.Empty).Contains("inner"));
                url = string.Format("{0}search.php{1}", Constants.BASE_URL, searchNode.Descendants("a").FirstOrDefault().GetAttributeValue("href", string.Empty));

                doc = (await _webManager.GetData(url)).Document;
                var tableNode = doc.DocumentNode.Descendants("table")
                                .FirstOrDefault(node => node.GetAttributeValue("id", string.Empty).Contains("main_full"));

                tableNode.SetAttributeValue("style", "width: 100%");

                HtmlNode[] linkNodes = tableNode.Descendants("a").ToArray();

                if (!linkNodes.Any())
                {
                    // User has no items on their rap sheet, return nothing back.
                    return(string.Empty);
                }

                foreach (var linkNode in linkNodes)
                {
                    var divNode = HtmlNode.CreateNode(linkNode.InnerText);
                    linkNode.ParentNode.ReplaceChild(divNode.ParentNode, linkNode);
                }

                HtmlNode[] jumpPostsNodes = tableNode.Descendants("div").Where(node => node.GetAttributeValue("align", string.Empty).Equals("right")).ToArray();

                foreach (var jumpPost in jumpPostsNodes)
                {
                    jumpPost.Remove();
                }

                bodyNode.InnerHtml = tableNode.OuterHtml;
                return(WebUtility.HtmlDecode(WebUtility.HtmlDecode(doc2.DocumentNode.OuterHtml)));
            }
            catch (Exception)
            {
                // Person does not have platinum.
                return(string.Empty);
            }
        }
Пример #18
0
        public static void WriteAllBytes(string path, byte[] data)
        {
#if NETFX_CORE
            path = FixPath(path);
            var thread = PathIO.WriteBytesAsync(path, data).AsTask();
            thread.Wait();
#else
            throw new NotImplementedException();
#endif
        }
        private static async Task WriteAllTextAsync(string path, string data)
        {
            bool fileExists = await ExistsAsync(path);

            if (!fileExists)
            {
                await CreateFileAsync(path);
            }
            await PathIO.WriteTextAsync(path, data);
        }
Пример #20
0
        async void OnApplicationSuspending(object sender, SuspendingEventArgs args)
        {
            // Save application settings
            appSettings.Save();

            // Save text content
            SuspendingDeferral deferral = args.SuspendingOperation.GetDeferral();
            await PathIO.WriteTextAsync("ms-appdata:///local/XamlCruncher.xaml", editBox.Text);

            deferral.Complete();
        }
Пример #21
0
 public async Task <object> GetAsync(string key)
 {
     try
     {
         return(await PathIO.ReadBufferAsync(Path.Combine(rootFolder.Path, key)));
     }
     catch
     {
         return(null);
     }
 }
        public static string ReadAllText(string path)
        {
#if NETFX_CORE
            path = path.FixPath();
            var thread = PathIO.ReadTextAsync(path).AsTask();
            thread.Wait();
            return(thread.Result);
#else
            throw new PlatformNotSupportedException();
#endif
        }
        public static string[] ReadAllLines(string path)
        {
#if NETFX_CORE
            path = path.FixPath();
            var thread = PathIO.ReadLinesAsync(path).AsTask();
            thread.Wait();
            return(thread.Result.ToArray());
#else
            throw new PlatformNotSupportedException();
#endif
        }
Пример #24
0
 public async void LoadLog()
 {
     try
     {
         string path = Utils.AppResources.GetString("UpdateLogFile");
         textBlock.Text = await PathIO.ReadTextAsync(path);
     }
     catch (Exception)
     {
     }
 }
Пример #25
0
        private async void TestFunktion_Click4(object sender, RoutedEventArgs e)
        {
            try
            {
                string text = await PathIO.ReadTextAsync(ApplicationData.Current.LocalFolder.Path +
                                                         "\\" + "LibraryDeletedDelete.txt");

                await new Windows.UI.Popups.MessageDialog(text).ShowAsync();
            }
            catch { }
        }
Пример #26
0
        private async Task SetTaskStarted()
        {
            try
            {
                string filenameWithExtention = "Started.txt";
                string path = ApplicationData.Current.LocalFolder.Path + "\\" + filenameWithExtention;

                await PathIO.WriteTextAsync(path, DateTime.Now.Ticks.ToString());
            }
            catch { }
        }
Пример #27
0
        public async static Task <Data> Load()
        {
            try
            {
                string xmlText = await PathIO.ReadTextAsync(absolutePath);

                return(Deserialize(xmlText));
            }
            catch { }

            return(new Data());
        }
        private static async Task <byte[]> ReadAllBytesAsync(string path)
        {
            var buffer = await PathIO.ReadBufferAsync(path);

            using (var dr = DataReader.FromBuffer(buffer))
            {
                // await dr.LoadAsync(buffer.Length); <- exception happening here "The operation identifier is not valid".
                byte[] data = new byte[buffer.Length];
                dr.ReadBytes(data);
                return(data);
            }
        }
Пример #29
0
        protected async override void OnNavigatedTo(NavigationEventArgs e)
        {
            DisplayInformation.AutoRotationPreferences = DisplayOrientations.Landscape;

            await _capture.InitializeAsync(new MediaCaptureInitializationSettings
            {
                VideoDeviceId        = await GetBackOrDefaulCameraIdAsync(),
                StreamingCaptureMode = StreamingCaptureMode.Video
            });

            IBuffer shaderY = await PathIO.ReadBufferAsync("ms-appx:///Invert_093_NV12_Y.cso");

            IBuffer shaderUV = await PathIO.ReadBufferAsync("ms-appx:///Invert_093_NV12_UV.cso");

            var definition = new VideoEffects.ShaderEffectDefinitionNv12(shaderY, shaderUV);

            await _capture.AddEffectAsync(MediaStreamType.VideoRecord, definition.ActivatableClassId, definition.Properties);

            Preview.Source = _capture;
            await _capture.StartPreviewAsync();

            var previewProps = (VideoEncodingProperties)_capture.VideoDeviceController.GetMediaStreamProperties(MediaStreamType.VideoPreview);

            TextLog.Text += String.Format("Preview: {0} {1}x{2} {3}fps\n", previewProps.Subtype, previewProps.Width, previewProps.Height, previewProps.FrameRate.Numerator / (float)previewProps.FrameRate.Denominator);

            var recordProps = (VideoEncodingProperties)_capture.VideoDeviceController.GetMediaStreamProperties(MediaStreamType.VideoRecord);

            TextLog.Text += String.Format("Record: {0} {1}x{2} {3}fps\n", recordProps.Subtype, recordProps.Width, recordProps.Height, recordProps.FrameRate.Numerator / (float)recordProps.FrameRate.Denominator);

            StorageFile file = await KnownFolders.VideosLibrary.CreateFileAsync("VideoEffectRecordCaptureTestApp.mp4", CreationCollisionOption.ReplaceExisting);

            var profile = MediaEncodingProfile.CreateMp4(VideoEncodingQuality.Auto);

            profile.Audio = null;

            TextLog.Text += "Starting record\n";
            await _capture.StartRecordToStorageFileAsync(profile, file);

            TextLog.Text += "Record started to" + file.Path + "\n";

            for (int i = 0; i < 10; i++)
            {
                await Task.Delay(1000);

                TextLog.Text += i + "s\n";
            }

            TextLog.Text += "Stopping record\n";
            await _capture.StopRecordAsync();

            TextLog.Text += "Record stopped\n";
        }
Пример #30
0
        private async Task SetupMarker()
        {
            // Load marker
            var markerData = await PathIO.ReadTextAsync("ms-appx:///data/patt.hiro"); // single_buffer;80;buffer=234 221 237...

            var cfg = string.Format("single_buffer;{0};buffer={1}", 80, markerData);

            _markerId = _arWrapper.arwAddMarker(cfg);
            if (_markerId < 0)
            {
                throw new InvalidOperationException("Failed to load AR marker.");
            }
        }