Example #1
0
        public async Task DeserializeAsync_with_in_string_provided_type()
        {
            var serializer = new JsonSerializer();
            var serializedObj = @"{""$type"":""Kephas.Serialization.Json.Tests.JsonSerializerTest+TestEntity, Kephas.Serialization.Json.Tests"",""name"":""John Doe""}";
            var obj = await serializer.DeserializeAsync(serializedObj, SerializationContext.Create<JsonFormat>());

            Assert.IsInstanceOf<TestEntity>(obj);

            var testEntity = (TestEntity)obj;

            Assert.AreEqual("John Doe", testEntity.Name);
        }
Example #2
0
        public async Task DeserializeAsync_with_runtime_provided_type()
        {
            var serializer = new JsonSerializer();
            var serializedObj = @"{""name"":""John Doe""}";
            var obj = await serializer.DeserializeAsync(serializedObj, SerializationContext.Create<JsonFormat, TestEntity>());

            Assert.IsInstanceOf<TestEntity>(obj);

            var testEntity = (TestEntity)obj;

            Assert.AreEqual("John Doe", testEntity.Name);
        }
Example #3
0
        public static async Task Update()
        {
            var clusters = new List <Cluster>();
            var routes   = new List <ProxyRoute>();
            var config   = new ServiceFabricConfig(clusters, routes);


            using (var client = new HttpClient())
            {
                var strApps = await client.GetStringAsync($"{_sfUri}/Applications?api-version=3.0");

                var appResponse = await JsonSerializer.DeserializeAsync <ServiceFabricResponse <Application> >(new MemoryStream(Encoding.UTF8.GetBytes(strApps)));

                foreach (var app in appResponse.Items)
                {
                    var appName    = app.Name.Replace("fabric:/", "");
                    var strService = await client.GetStringAsync($"{_sfUri}/Applications/{appName}/$/GetServices?api-version=3.0");

                    var serviceResponse = await JsonSerializer.DeserializeAsync <ServiceFabricResponse <Service> >(new MemoryStream(Encoding.UTF8.GetBytes(strService)));

                    foreach (var service in serviceResponse.Items)
                    {
                        var serviceName   = service.Name.Replace($"fabric:/", "");
                        var strPartitions = await client.GetStringAsync($"{_sfUri}/Applications/{appName}/$/GetServices/{serviceName}/$/GetPartitions?api-version=3.0");

                        var partitionResponse = await JsonSerializer.DeserializeAsync <ServiceFabricResponse <Partition> >(new MemoryStream(Encoding.UTF8.GetBytes(strPartitions)));

                        var cluster = new Cluster();
                        cluster.Id = serviceName;
                        clusters.Add(cluster);

                        { // Add Catch All
                            var route = new ProxyRoute();
                            route.RouteId    = serviceName + ":catch-all";
                            route.ClusterId  = serviceName;
                            route.Match.Path = serviceName + "/{**catch-all}";
                            route.Transforms = new List <IDictionary <string, string> >();
                            route.Transforms.Add(new Dictionary <string, string>()
                            {
                                { "PathRemovePrefix", serviceName }
                            });
                            route.AddTransformRequestHeader("X-Forwarded-PathBase", "/" + serviceName);

                            routes.Add(route);
                        }
                        { // Add root match
                            var route = new ProxyRoute();
                            route.RouteId    = serviceName + ":root-match";
                            route.ClusterId  = serviceName;
                            route.Match.Path = serviceName;
                            route.Transforms = new List <IDictionary <string, string> >();
                            route.Transforms.Add(new Dictionary <string, string>()
                            {
                                { "PathRemovePrefix", serviceName }
                            });
                            route.AddTransformRequestHeader("X-Forwarded-PathBase", "/" + serviceName);
                            routes.Add(route);
                        }

                        foreach (var partition in partitionResponse.Items)
                        {
                            var partitionId = partition.PartitionInformation.Id;
                            var strReplicas = await client.GetStringAsync($"{_sfUri}/Applications/{appName}/$/GetServices/{serviceName}/$/GetPartitions/{partitionId}/$/GetReplicas?api-version=3.0");

                            var replicasResponse = await JsonSerializer.DeserializeAsync <ServiceFabricResponse <Replica> >(new MemoryStream(Encoding.UTF8.GetBytes(strReplicas)));

                            foreach (var replica in replicasResponse.Items)
                            {
                                var replicaAddress = await JsonSerializer.DeserializeAsync <ReplicaAddress>(new MemoryStream(Encoding.UTF8.GetBytes(replica.Address)));

                                foreach (var endpoint in replicaAddress.Endpoints)
                                {
                                    var destination = new Destination();
                                    destination.Address = endpoint.Value;
                                    cluster.Destinations.Add($"{partitionId}:{replica.InstanceId}", destination);
                                }
                            }
                        }
                    }
                }
                var oldConfig = _config;
                _config = config;
                oldConfig.SignalChange();
            }
        }
 /// <inheritdoc />
 public ValueTask <T> DeserializeAsync <T>(Stream stream, CancellationToken cancellationToken = default)
 {
     return(JsonSerializer.DeserializeAsync <T>(stream, _jsonSerializerOptions, cancellationToken));
 }
Example #5
0
        static async Task <int> Main(string[] args)
        {
            using FileStream openStream = File.OpenRead(FilesPath);
            standardClauses             = await JsonSerializer.DeserializeAsync <Clauses>(openStream);

            if (standardClauses is null)
            {
                Console.WriteLine("Could not read list of clauses. Exiting");
                return(1);
            }

            bool dryRun = ((args.Length > 0) && (args[0].Contains("dryrun")));

            if (dryRun)
            {
                Console.WriteLine("Doing a dry run");
            }

            try
            {
                Console.WriteLine("=========================== Front Matter ===================================");
                var sectionMap = new TocSectionNumberBuilder("../standard", dryRun);
                foreach (var file in standardClauses.FrontMatter)
                {
                    Console.WriteLine($" -- {file}");
                    await sectionMap.AddFrontMatterTocEntries(file);
                }

                Console.WriteLine("================= GENERATE UPDATED SECTION NUMBERS =========================");
                Console.WriteLine("============================ Main text======================================");
                foreach (var file in standardClauses.MainBody)
                {
                    Console.WriteLine($" -- {file}");
                    await sectionMap.AddContentsToTOC(file);
                }
                Console.WriteLine("============================= Annexes ======================================");
                sectionMap.FinishMainSection();
                foreach (var file in standardClauses.Annexes)
                {
                    Console.WriteLine($" -- {file}");
                    await sectionMap.AddContentsToTOC(file);
                }
                if (!dryRun)
                {
                    Console.WriteLine("Update TOC");
                    var existingReadMe = await ReadExistingReadMe();

                    using var readme = new StreamWriter(ReadMePath, false);
                    await readme.WriteAsync(existingReadMe);

                    await readme.WriteLineAsync(TOCHeader);

                    await readme.WriteLineAsync();

                    await readme.WriteAsync(sectionMap.Toc);
                }

                Console.WriteLine("======================= UPDATE ALL REFERENCES ==============================");
                var fixup = new ReferenceUpdateProcessor("../standard", sectionMap.LinkMap, dryRun);

                Console.WriteLine("=========================== Front Matter ===================================");
                foreach (var file in standardClauses.FrontMatter)
                {
                    Console.WriteLine($" -- {file}");
                    await fixup.ReplaceReferences(file);
                }
                Console.WriteLine("============================ Main text======================================");
                foreach (var file in standardClauses.MainBody)
                {
                    Console.WriteLine($" -- {file}");
                    await fixup.ReplaceReferences(file);
                }
                Console.WriteLine("============================= Annexes ======================================");
                foreach (var file in standardClauses.Annexes)
                {
                    Console.WriteLine($" -- {file}");
                    await fixup.ReplaceReferences(file);
                }
                return(fixup.ErrorCount);
            }
            catch (InvalidOperationException e)
            {
                Console.WriteLine("\tError encountered:");
                Console.WriteLine(e.Message.ToString());
                Console.WriteLine("To recover, do the following:");
                Console.WriteLine("1. Discard all changes from the section numbering tool");
                Console.WriteLine("2. Fix the error noted above.");
                Console.WriteLine("3. Run the tool again.");
                return(1);
            }
        }
Example #6
0
        //string put =;
        static async Task Main(string[] args)
        {
            char choice_2;

            Console.WriteLine("ВОЗМОЖНО ВЫПОЛНИТЬ СЛЕДУЮЩИЕ ДЕЙСТВИЯ\n");
            do
            {
                Console.WriteLine("1) Информацию в консоль о логических дисках, именах, метке тома, размере типе файловой системы.");
                Console.WriteLine("2) Работа с файлами.");
                Console.WriteLine("3) Работа с форматом XML.");
                Console.WriteLine("4) Работа с ZIP сжатием.");
                Console.WriteLine("5) Работа с форматом JSON.");
                Console.WriteLine("0) Выход из программы.");
                Console.Write("Выберите номер команды: ");
                int choice = Convert.ToInt32(Console.ReadLine());
                switch (choice)
                {
                case 1:
                    /*Вывести информацию в консоль о логических дисках, именах, метке тома, размере типе файловой системы.*/
                {
                    Console.WriteLine("1. ИНФОРМАЦИЯ О ДИСКАХ");
                    DriveInfo[] drivers = DriveInfo.GetDrives();
                    foreach (DriveInfo drive in drivers)
                    {
                        Console.WriteLine($"Название: {drive.Name}");
                        Console.WriteLine($"Тип: {drive.DriveType}");
                        if (drive.IsReady)
                        {
                            Console.WriteLine($"Объем диска: {drive.TotalSize}");
                            Console.WriteLine($"Свободное пространство: {drive.TotalFreeSpace}");
                            Console.WriteLine($"Метка: {drive.VolumeLabel}");
                        }
                        Console.WriteLine();
                    }
                    break;
                }

                case 2:
                {
                    Console.WriteLine("2.Работа с файлами");
                    string path = @"D:\Documents\SOKOL";
                    Console.WriteLine("Введите строку для записи в файл:");
                    string text = Console.ReadLine();
                    // запись в файл
                    using (FileStream fstream = new FileStream($"{path}text.txt", FileMode.OpenOrCreate))
                    {
                        // преобразуем строку в байты
                        byte[] array = System.Text.Encoding.Default.GetBytes(text);
                        // запись массива байтов в файл
                        fstream.Write(array, 0, array.Length);
                        Console.WriteLine("Текст записан в файл");
                    }
                    // чтение из файла
                    using (FileStream fstream = File.OpenRead($"{path}text.txt"))
                    {
                        // преобразуем строку в байты
                        byte[] array = new byte[fstream.Length];
                        // считываем данные
                        fstream.Read(array, 0, array.Length);
                        // декодируем байты в строку
                        string textFromFile = System.Text.Encoding.Default.GetString(array);
                        Console.WriteLine($"Текст из файла: {textFromFile}");
                    }
                    Console.WriteLine("Удалить файл? + OR -: ");
                    switch (Console.ReadLine())
                    {
                    case "+":
                        if (File.Exists($"{path}text.txt"))
                        {
                            File.Delete($"{path}text.txt");
                            Console.WriteLine("Файл удален!");
                        }
                        else
                        {
                            Console.WriteLine("Файла не существует!");
                        }
                        break;

                    case "-":
                        break;

                    default:
                        Console.WriteLine("Введено неверное значение!");
                        break;
                    }
                    Console.WriteLine();
                    break;
                }

                case 3:
                {
                    Console.WriteLine("Работа с XML:");
                    XmlDocument xDoc = new XmlDocument();
                    XDocument   xdoc = new XDocument();
                    Console.Write("Сколько пользователей нужно ввести: ");
                    int      count = Convert.ToInt32(Console.ReadLine());
                    XElement list  = new XElement("users");
                    for (int i = 1; i <= count; i++)
                    {
                        XElement User = new XElement("user");
                        Console.Write("Введите имя пользователя: ");
                        XAttribute UserName = new XAttribute("name", Console.ReadLine());
                        Console.WriteLine();
                        Console.Write("Введите возраст пользователя: ");
                        XElement UserAge = new XElement("age", Convert.ToInt32(Console.ReadLine()));
                        Console.WriteLine();
                        Console.Write("Введите название компании: ");
                        XElement UserCompany = new XElement("company", Console.ReadLine());
                        Console.WriteLine();
                        User.Add(UserName);
                        User.Add(UserAge);
                        User.Add(UserCompany);
                        list.Add(User);
                    }
                    xdoc.Add(list);
                    xdoc.Save(@"D:\Documents\SOKOL\users.xml");

                    Console.Write("Прочитать XML файл? (+ OR -): ");
                    switch (Console.ReadLine())
                    {
                    case "+":
                        Console.WriteLine();
                        xDoc.Load(@"D:\Documents\SOKOL\users.xml");
                        XmlElement xRoot = xDoc.DocumentElement;
                        foreach (XmlNode xnode in xRoot)
                        {
                            if (xnode.Attributes.Count > 0)
                            {
                                XmlNode attr = xnode.Attributes.GetNamedItem("name");
                                if (attr != null)
                                {
                                    Console.WriteLine($"Имя: {attr.Value}");
                                }
                            }
                            foreach (XmlNode childnode in xnode.ChildNodes)
                            {
                                if (childnode.Name == "age")
                                {
                                    Console.WriteLine($"Возраст: {childnode.InnerText}");
                                }
                                if (childnode.Name == "company")
                                {
                                    Console.WriteLine($"Компания: {childnode.InnerText}");
                                }
                            }
                        }
                        Console.WriteLine();
                        break;

                    case "-":
                        break;

                    default:
                        Console.WriteLine("Введены неправильные данные!");
                        break;
                    }
                    Console.Write("Удалить созданный xml файл? (+ OR -): ");
                    switch (Console.ReadLine())
                    {
                    case "+":
                        FileInfo xmlfilecheck = new FileInfo(@"D:\Documents\SOKOL\users.xml");
                        if (xmlfilecheck.Exists)
                        {
                            xmlfilecheck.Delete();
                            Console.WriteLine("Файл удален!");
                        }
                        else
                        {
                            Console.WriteLine("Файла не существует!");
                        }
                        break;

                    case "-":
                        break;

                    default:
                        Console.WriteLine("Введено неверное зачение!");
                        break;
                    }
                    Console.WriteLine();
                    break;
                }

                case 4:
                {
                    Console.WriteLine("Работа с ZIP:");
                    string SourceFile     = @"D:\Documents\SOKOL\oop.txt";  // исходный файл
                    string CompressedFile = @"D:\Documents\SOKOL\bin.gz";   // сжатый файл
                    string TargetFile     = @"D:\Documents\SOKOL\oop1.txt"; // восстановленный файл
                                                                            // создание сжатого файла
                    Compress(SourceFile, CompressedFile);
                    // чтение из сжатого файла
                    Decompress(CompressedFile, TargetFile);
                    Console.WriteLine("Удалить файлы? (+ OR -): ");
                    switch (Console.ReadLine())
                    {
                    case "+":
                        if ((File.Exists(SourceFile) &&
                             File.Exists(CompressedFile) && File.Exists(TargetFile)) == true)
                        {
                            File.Delete(SourceFile);
                            File.Delete(CompressedFile);
                            File.Delete(TargetFile);
                            Console.WriteLine("Файлы удалены!");
                        }
                        else
                        {
                            Console.WriteLine("Ошибка в удалении файлов!\n Проверьте их наличие!");
                        }
                        break;

                    case "-":
                        break;

                    default:
                        Console.WriteLine("Введены неправильные данные! Попробуйте снова!");
                        break;
                    }
                    Console.WriteLine();
                    break;
                }

                case 5:
                {
                    Console.WriteLine("Работа с JSON:");
                    // сохранение данных
                    using (FileStream fs = new FileStream(@"D:\Documents\SOKOL\user.json", FileMode.OpenOrCreate))
                    {
                        Person Marya = new Person()
                        {
                            Name = "Marya", Age = 19
                        };
                        await JsonSerializer.SerializeAsync <Person>(fs, Marya);

                        Console.WriteLine("Данные введены автоматически и они сохранены!");
                    }

                    // чтение данных
                    using (FileStream fs = new FileStream(@"D:\Documents\SOKOL\user.json", FileMode.OpenOrCreate))
                    {
                        Person restoredPerson = await JsonSerializer.DeserializeAsync <Person>(fs);

                        Console.WriteLine($"Name: {restoredPerson.Name}  Age: {restoredPerson.Age}");
                    }
                    Console.Write("Вы хотите удалить файл? (+ OR -): ");
                    switch (Console.ReadLine())
                    {
                    case "+":
                        File.Delete(@"D:\Documents\SOKOL\user.json");
                        Console.WriteLine("\nФайл удален!");
                        break;

                    case "-":
                        break;
                    }
                    break;
                }

                default:
                    Console.WriteLine("\nВВЕДЕНЫ НЕПРАВИЛЬНЫЕ ДАННЫЕ!");
                    break;
                }
                Console.WriteLine("================================");
                Console.Write("\nХотите продолжить? + OR -: ");
                choice_2 = Convert.ToChar(Console.ReadLine());
                Console.Write('\n');
            } while (choice_2 != '-');
        }
Example #7
0
        static async Task Main(string[] args)
        {
            int num = Convert.ToInt32(Console.ReadLine());

            switch (num)
            {
            case 1:
            {
                DriveInfo[] drives = DriveInfo.GetDrives();
                foreach (DriveInfo drive in drives)
                {
                    Console.WriteLine($"Название: {drive.Name}");
                    Console.WriteLine($"Тип: {drive.DriveType}");
                    if (drive.IsReady)
                    {
                        Console.WriteLine($"Объем диска: {drive.TotalSize}");
                        Console.WriteLine($"Свободное пространство: {drive.TotalFreeSpace}");
                        Console.WriteLine($"Метка: {drive.VolumeLabel}");
                    }
                    Console.WriteLine();
                }
                Console.WriteLine("Чтобы перейти ко второму заданию введите 2");
                if (Console.ReadLine() == "2")
                {
                    goto case 2;
                }
                break;
            }

            case 2:
            {
                string   path1   = @"D:\alext.txt";
                FileInfo fileInf = new FileInfo(path1);
                {
                    if (!fileInf.Exists)
                    {
                        fileInf.Create();
                    }
                }
                using (FileStream fstream = File.Create(path1))
                {
                    string text  = "example";
                    byte[] array = System.Text.Encoding.Default.GetBytes(text);
                    fstream.Write(array, 0, array.Length);
                    Console.WriteLine("Текст записан в файл");
                }
                using (FileStream fstream = File.OpenRead(path1))
                {
                    byte[] array = new byte[fstream.Length];
                    fstream.Read(array, 0, array.Length);
                    string textFromFile = System.Text.Encoding.Default.GetString(array);
                    Console.WriteLine($"Текст из файла: {textFromFile}");
                }
                Console.WriteLine("Чтобы удалить файл нажмите 1");
                if (Console.ReadLine() == "1")
                {
                    FileInfo fileInf1 = new FileInfo(path1);
                    if (fileInf1.Exists)
                    {
                        fileInf.Delete();
                    }
                    Console.WriteLine("Файл удален");
                }
                Console.WriteLine("Чтобы перейти ко третьему заданию введите 3");
                if (Console.ReadLine() == "3")
                {
                    goto case 3;
                }
                break;
            }

            case 3:
            {
                Person tom = new Person();
                tom.Name = "Tom";
                tom.Age  = 12;
                string json = JsonSerializer.Serialize <Person>(tom);
                Console.WriteLine(json);
                Person restoredPerson = JsonSerializer.Deserialize <Person>(json);
                Console.WriteLine(restoredPerson.Name);



                {
                    // сохранениеданных
                    using (FileStream fs = new FileStream("user.json", FileMode.OpenOrCreate))
                    {
                        Person tom1 = new Person()
                        {
                            Name = "Tom", Age = 35
                        };
                        await JsonSerializer.SerializeAsync <Person>(fs, tom1);

                        Console.WriteLine("Data has been saved to file");
                    }
                    // чтениеданных
                    using (FileStream fs = new FileStream("user.json", FileMode.OpenOrCreate))
                    {
                        Person restoredPerson1 = await JsonSerializer.DeserializeAsync <Person>(fs);

                        Console.WriteLine($"Name: {restoredPerson1.Name} Age: {restoredPerson1.Age}");
                    }
                }

                {
                    Person1 tom1 = new Person1()
                    {
                        Name = "Tom", Age = 35
                    };
                    string json1 = JsonSerializer.Serialize <Person1>(tom1);
                    Console.WriteLine(json1);
                    Person1 restoredPerson1 = JsonSerializer.Deserialize <Person1>(json1);
                    Console.WriteLine($"Name: {restoredPerson1.Name} Age: {restoredPerson1.Age}");
                }
                Console.WriteLine("Чтобы перейти ко четвертому заданию введите 4");
                if (Console.ReadLine() == "4")
                {
                    goto case 4;
                }
                break;
            }

            case 4:
            {
                XDocument xdoc = new XDocument();
                // создаем первый элемент
                XElement iphone6 = new XElement("phone");
                // создаематрибут
                XAttribute iphoneNameAttr    = new XAttribute("name", "iPhone 6");
                XElement   iphoneCompanyElem = new XElement("company", "Apple");
                XElement   iphonePriceElem   = new XElement("price", "40000");
                // добавляем атрибут и элементы в первый элемент
                iphone6.Add(iphoneNameAttr);
                iphone6.Add(iphoneCompanyElem);
                iphone6.Add(iphonePriceElem);

                // создаемвторойэлемент
                XElement   galaxys5           = new XElement("phone");
                XAttribute galaxysNameAttr    = new XAttribute("name", "Samsung Galaxy S5");
                XElement   galaxysCompanyElem = new XElement("company", "Samsung");
                XElement   galaxysPriceElem   = new XElement("price", "33000");
                galaxys5.Add(galaxysNameAttr);
                galaxys5.Add(galaxysCompanyElem);
                galaxys5.Add(galaxysPriceElem);
                // создаемкорневойэлемент
                XElement phones = new XElement("phones");
                // добавляем в корневой элемент
                phones.Add(iphone6);
                phones.Add(galaxys5);
                // добавляем корневой элемент в документ
                xdoc.Add(phones);
                //сохраняем документ
                xdoc.Save("phones.xml");
                XDocument xdoc1 = XDocument.Load("phones.xml");
                foreach (XElement phoneElement in xdoc1.Element("phones").Elements("phone"))
                {
                    XAttribute nameAttribute  = phoneElement.Attribute("name");
                    XElement   companyElement = phoneElement.Element("company");
                    XElement   priceElement   = phoneElement.Element("price");

                    if (nameAttribute != null && companyElement != null && priceElement != null)
                    {
                        Console.WriteLine($"Смартфон: {nameAttribute.Value}");
                        Console.WriteLine($"Компания: {companyElement.Value}");
                        Console.WriteLine($"Цена: {priceElement.Value}");
                    }
                    Console.WriteLine();
                }
                Console.WriteLine("Чтобы перейти ко пятому заданию введите 5");
                if (Console.ReadLine() == "5")
                {
                    goto case 5;
                }

                break;
            }

            case 5:
            {
                string sourceFile     = "D://test/book.pdf";
                string compressedFile = "D://test/book.gz";
                string targetFile     = "D://test/book_new.pdf";

                Compress(sourceFile, compressedFile);

                Decompress(compressedFile, targetFile);
            public async Task ThrowOnInvalidFormatAsync(string json, Type typeToConvert)
            {
                byte[] jsonBytes = Encoding.UTF8.GetBytes(json);
                Stream stream    = new MemoryStream(jsonBytes);

                JsonException ex = await Assert.ThrowsAsync <JsonException>(async() => await JsonSerializer.DeserializeAsync(stream, typeToConvert));

                Assert.Contains(typeToConvert.ToString(), ex.Message);
            }
Example #9
0
        public static async Task <List <L2Item> > GetItems(HttpClient http)
        {
            Stream dataStream = await http.GetStreamAsync("data/items.json");

            return(await JsonSerializer.DeserializeAsync <List <L2Item> >(dataStream));
        }
 /// <summary>
 /// Deserialize the specified string into the specified object of type 'T'.
 /// </summary>
 /// <param name="utf8Json"></param>
 /// <typeparam name="T"></typeparam>
 /// <returns></returns>
 public static async Task <T> DeserializeAsync <T>(this Stream utf8Json)
 {
     return(await JsonSerializer.DeserializeAsync <T>(utf8Json, _jsonFormatOptions));
 }
Example #11
0
        async Task <int> GetGlobalCounter(int level)
        {
            var stream = await Node.GetGlobalCounterAsync(level);

            return(await JsonSerializer.DeserializeAsync <int>(stream, SerializerOptions.Default));
        }
        public async Task <TResponse?> PostAsJson <TRequest, TResponse>(string uri, TRequest requestData, CancellationToken cancellationToken = default)
        {
            Stream result = await PostAsJson(uri, requestData, cancellationToken).ConfigureAwait(false);

            return(await JsonSerializer.DeserializeAsync <TResponse>(result, cancellationToken : cancellationToken));
        }
Example #13
0
 public async Task <GetSubscriberResponse> GetDeserilizedAsync(Stream stream)
 {
     return(await JsonSerializer.DeserializeAsync <GetSubscriberResponse>(stream, JsonSerializerOptions));
 }
Example #14
0
        public async Task AddMediaInfoWithProbe(MediaSourceInfo mediaSource, bool isAudio, string cacheKey, bool addProbeDelay, CancellationToken cancellationToken)
        {
            var originalRuntime = mediaSource.RunTimeTicks;

            var now = DateTime.UtcNow;

            MediaInfo mediaInfo     = null;
            var       cacheFilePath = string.IsNullOrEmpty(cacheKey) ? null : Path.Combine(_appPaths.CachePath, "mediainfo", cacheKey.GetMD5().ToString("N", CultureInfo.InvariantCulture) + ".json");

            if (!string.IsNullOrEmpty(cacheKey))
            {
                try
                {
                    await using FileStream jsonStream = File.OpenRead(cacheFilePath);
                    mediaInfo = await JsonSerializer.DeserializeAsync <MediaInfo>(jsonStream, _jsonOptions, cancellationToken).ConfigureAwait(false);

                    // _logger.LogDebug("Found cached media info");
                }
                catch
                {
                }
            }

            if (mediaInfo == null)
            {
                if (addProbeDelay)
                {
                    var delayMs = mediaSource.AnalyzeDurationMs ?? 0;
                    delayMs = Math.Max(3000, delayMs);
                    if (delayMs > 0)
                    {
                        _logger.LogInformation("Waiting {0}ms before probing the live stream", delayMs);
                        await Task.Delay(delayMs, cancellationToken).ConfigureAwait(false);
                    }
                }

                mediaSource.AnalyzeDurationMs = 3000;

                mediaInfo = await _mediaEncoder.GetMediaInfo(
                    new MediaInfoRequest
                {
                    MediaSource     = mediaSource,
                    MediaType       = isAudio ? DlnaProfileType.Audio : DlnaProfileType.Video,
                    ExtractChapters = false
                },
                    cancellationToken).ConfigureAwait(false);

                if (cacheFilePath != null)
                {
                    Directory.CreateDirectory(Path.GetDirectoryName(cacheFilePath));
                    await using FileStream createStream = File.OpenWrite(cacheFilePath);
                    await JsonSerializer.SerializeAsync(createStream, mediaInfo, _jsonOptions, cancellationToken).ConfigureAwait(false);

                    // _logger.LogDebug("Saved media info to {0}", cacheFilePath);
                }
            }

            var mediaStreams = mediaInfo.MediaStreams;

            if (!string.IsNullOrEmpty(cacheKey))
            {
                var newList = new List <MediaStream>();
                newList.AddRange(mediaStreams.Where(i => i.Type == MediaStreamType.Video).Take(1));
                newList.AddRange(mediaStreams.Where(i => i.Type == MediaStreamType.Audio).Take(1));

                foreach (var stream in newList)
                {
                    stream.Index    = -1;
                    stream.Language = null;
                }

                mediaStreams = newList;
            }

            _logger.LogInformation("Live tv media info probe took {0} seconds", (DateTime.UtcNow - now).TotalSeconds.ToString(CultureInfo.InvariantCulture));

            mediaSource.Bitrate       = mediaInfo.Bitrate;
            mediaSource.Container     = mediaInfo.Container;
            mediaSource.Formats       = mediaInfo.Formats;
            mediaSource.MediaStreams  = mediaStreams;
            mediaSource.RunTimeTicks  = mediaInfo.RunTimeTicks;
            mediaSource.Size          = mediaInfo.Size;
            mediaSource.Timestamp     = mediaInfo.Timestamp;
            mediaSource.Video3DFormat = mediaInfo.Video3DFormat;
            mediaSource.VideoType     = mediaInfo.VideoType;

            mediaSource.DefaultSubtitleStreamIndex = null;

            // Null this out so that it will be treated like a live stream
            if (!originalRuntime.HasValue)
            {
                mediaSource.RunTimeTicks = null;
            }

            var audioStream = mediaStreams.FirstOrDefault(i => i.Type == MediaStreamType.Audio);

            if (audioStream == null || audioStream.Index == -1)
            {
                mediaSource.DefaultAudioStreamIndex = null;
            }
            else
            {
                mediaSource.DefaultAudioStreamIndex = audioStream.Index;
            }

            var videoStream = mediaStreams.FirstOrDefault(i => i.Type == MediaStreamType.Video);

            if (videoStream != null)
            {
                if (!videoStream.BitRate.HasValue)
                {
                    var width = videoStream.Width ?? 1920;

                    if (width >= 3000)
                    {
                        videoStream.BitRate = 30000000;
                    }
                    else if (width >= 1900)
                    {
                        videoStream.BitRate = 20000000;
                    }
                    else if (width >= 1200)
                    {
                        videoStream.BitRate = 8000000;
                    }
                    else if (width >= 700)
                    {
                        videoStream.BitRate = 2000000;
                    }
                }

                // This is coming up false and preventing stream copy
                videoStream.IsAVC = null;
            }

            mediaSource.AnalyzeDurationMs = 3000;

            // Try to estimate this
            mediaSource.InferTotalBitrate(true);
        }
 public async Task HighLevelEmpty()
 {
     _emptyStream.Position = 0;
     await JsonSerializer.DeserializeAsync <GraphQlModel>(_emptyStream, new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
 }
Example #16
0
        async static Task Main(string[] args)
        {
            Game[] games = new Game[] {
                new Game("Dota 2", "MMORPG", 10),
                new Game("Skyrim", "RPG", 6)
            };


            //BINARY SERIALIZATION
            BinaryFormatter MyFormatter = new BinaryFormatter();                                //Объект сериализатора

            using (FileStream InputStream = new FileStream("games.dat", FileMode.OpenOrCreate)) //Поток для записи в файл
            {
                MyFormatter.Serialize(InputStream, games);                                      //Метод Serialize принимает поток записи и объекты
            }

            using (FileStream Reader = new FileStream("games.dat", FileMode.OpenOrCreate))
            {
                Game[] gamesFromBinary = (Game[])MyFormatter.Deserialize(Reader);//Десериализуем из файла в потоке чтения
                foreach (var game in gamesFromBinary)
                {
                    Console.ForegroundColor = ConsoleColor.Cyan;
                    Console.Write("Aloha from Binary! ");
                    Console.ResetColor();
                    game.Info();
                }
            }


            //SOAP SERIALIZATION
            SoapFormatter MySoapFormatter = new SoapFormatter();

            using (FileStream SoapSerializer = new FileStream("games-soap.soap", FileMode.OpenOrCreate))
            {
                MySoapFormatter.Serialize(SoapSerializer, games);
            }

            using (FileStream SoapDeserializer = new FileStream("games-soap.soap", FileMode.Open))
            {
                Game[] gamesFromSoap = (Game[])MySoapFormatter.Deserialize(SoapDeserializer);
                foreach (var g in gamesFromSoap)
                {
                    Console.ForegroundColor = ConsoleColor.DarkYellow;
                    Console.Write("Greetings from SOAP! ");
                    Console.ResetColor();
                    g.Info();
                }
            }


            //JSON SERIALIZATION
            GameWithVersions[] gamesJson = new GameWithVersions[] {
                new GameWithVersions("Minecraft", "Sandbox", 10, new GameDescr("Sandbox game", "box of earth", "Notch"), "1.0.0", "1.0.2", "1.1.0", "2.3.5"),
                new GameWithVersions("Terraria", "Platformer", 8, new GameDescr("Flat game", "T", null), "1.0.1", "1.2.0", "1.3.1")
            };

            string json = JsonSerializer.Serialize(gamesJson,
                                                   new JsonSerializerOptions {
                IgnoreNullValues = true, WriteIndented = true
            });                                                                               //Метод возвращает строку в формате json

            using (StreamWriter JsonInput = new StreamWriter("game.json"))
            {
                JsonInput.WriteLine(json);
            }
            //Console.WriteLine(json);

            GameWithVersions[] gameFromJson;
            using (FileStream JsonReader = new FileStream("game.json", FileMode.Open))
            {
                gameFromJson = await JsonSerializer.DeserializeAsync <GameWithVersions[]>(JsonReader);
            }
            Console.WriteLine();
            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("Objects from JSON file");
            Console.ResetColor();
            foreach (var g in gameFromJson)
            {
                g.Info();
                Console.WriteLine();
            }


            //XML SERIALIZATION
            XmlSerializer MyXMLSerializer = new XmlSerializer(typeof(GameWithVersions[]));

            GameWithVersions[] gamesXml = new GameWithVersions[] {
                new GameWithVersions("GTA SA", "Quest", 8, new GameDescr("GTA Game", "Auto", "Rockstar"), "1.0.2", "1.2.2", "1.4.0"),
                new GameWithVersions("Mount&Blade", "Simulator", 7, new GameDescr("Medieval strategy", "Blade", "Paradox"), "1.0.0", "1.2.1", "1.3.0", "4.5.6")
            };
            //serialization
            using (FileStream InputXml = new FileStream("games.xml", FileMode.OpenOrCreate))
            {
                MyXMLSerializer.Serialize(InputXml, gamesXml);
            }

            //deserialization
            GameWithVersions[] gamesFromXml;
            using (FileStream XmlReader = new FileStream("games.xml", FileMode.Open))
            {
                gamesFromXml = (GameWithVersions[])MyXMLSerializer.Deserialize(XmlReader);
            }
            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("Objects from XML file");
            Console.ResetColor();
            foreach (var g in gamesFromXml)
            {
                g.Info();
                Console.WriteLine();
            }

            //XPath
            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("XPath ");
            Console.ResetColor();
            XmlDocument xmlDoc = new XmlDocument();

            xmlDoc.Load("games.xml");                           //Загружаем документ
            XmlElement xmlRoot = xmlDoc.DocumentElement;        //получаем корневой узел

            XmlNodeList xmlElements = xmlRoot.SelectNodes("*"); //Выбираем все дочерние узлы узла xmlRoot

            Console.WriteLine("Вывод всех игр");
            foreach (XmlNode node in xmlElements)
            {
                Console.WriteLine(node.OuterXml);
                Console.WriteLine();
            }

            Console.WriteLine("Вывод игр, чей разработчик Paradox");
            foreach (XmlNode node in xmlElements)
            {
                XmlNode developerParadox = node.SelectSingleNode("Description[Developer='Paradox']");
                if (developerParadox != null)
                {
                    Console.WriteLine(developerParadox.ParentNode.OuterXml);
                    Console.WriteLine();
                }
            }


            //Linq to XML
            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("Запросы Linq to XML");
            Console.ResetColor();
            XDocument xDoc = XDocument.Load("games-linq.xml");

            Console.WriteLine("Запрос на поиск разработчика Betheda");
            var query1 = from xNode in xDoc.Element("Games").Elements("Game")
                         where xNode.Element("Description").Element("Developer").Value == "Betheda"
                         select xNode;

            foreach (var item in query1)
            {
                Console.WriteLine(item);
            }

            Console.WriteLine("Запрос на по возрасту игры 10 лет");
            var query2 = from xNode in xDoc.Element("Games").Elements("Game")
                         where xNode.Element("Age").Value == "10"
                         select xNode;

            foreach (var item in query2)
            {
                Console.WriteLine(item);
            }

            Console.WriteLine("Запрос по жанру игры RPG");
            var query3 = (from xNode in xDoc.Element("Games").Elements("Game")
                          where xNode.Element("Genre").Value == "RPG"
                          select xNode).Take(1);

            foreach (var item in query3)
            {
                Console.WriteLine(item);
            }


            Console.Read();
        }
Example #17
0
        /// <summary>
        /// Load video metadata into memory.
        /// </summary>
        public async Task LoadMetadata(bool ignoreStreamErrors = false)
        {
            if (LoadedMetadata)
            {
                throw new InvalidOperationException("Video metadata is already loaded!");
            }
            var r = FFmpegWrapper.OpenOutput(ffprobe, $"-i \"{Filename}\" -v quiet -print_format json=c=1 -show_format -show_streams");

            try
            {
                var metadata = await JsonSerializer.DeserializeAsync <VideoMetadata>(r);

                try
                {
                    var videoStream = metadata.Streams.Where(x => x.CodecType.ToLower().Trim() == "video").FirstOrDefault();
                    if (videoStream != null)
                    {
                        metadata.Width         = videoStream.Width.Value;
                        metadata.Height        = videoStream.Height.Value;
                        metadata.PixelFormat   = videoStream.PixFmt;
                        metadata.Codec         = videoStream.CodecName;
                        metadata.CodecLongName = videoStream.CodecLongName;

                        metadata.BitRate = videoStream.BitRate == null ? -1 :
                                           int.Parse(videoStream.BitRate);

                        metadata.BitDepth = videoStream.BitsPerRawSample == null?
                                            tryParseBitDepth(videoStream.PixFmt) :
                                                int.Parse(videoStream.BitsPerRawSample);

                        metadata.Duration = videoStream.Duration == null?
                                            double.Parse(metadata.Format.Duration ?? "0") :
                                                double.Parse(videoStream.Duration);

                        metadata.SampleAspectRatio = videoStream.SampleAspectRatio;
                        metadata.AvgFramerateText  = videoStream.AvgFrameRate;
                        metadata.AvgFramerate      = 0.0;

                        if (videoStream.AvgFrameRate.Contains('/'))
                        {
                            var parsed = videoStream.AvgFrameRate.Split('/');
                            metadata.AvgFramerate = double.Parse(parsed[0]) / double.Parse(parsed[1]);
                        }
                        else
                        {
                            metadata.AvgFramerate = double.Parse(videoStream.AvgFrameRate);
                        }

                        metadata.PredictedFrameCount = (int)(metadata.AvgFramerate * metadata.Duration);
                    }
                }
                catch (Exception ex)
                {
                    // failed to interpret video stream settings
                    if (!ignoreStreamErrors)
                    {
                        throw new InvalidDataException("Failed to parse video stream data! " + ex.Message);
                    }
                }

                LoadedMetadata = true;
                Metadata       = metadata;
            }
            catch (JsonException ex)
            {
                throw new InvalidOperationException("Failed to interpret ffprobe video metadata output! " + ex.Message);
            }
        }
Example #18
0
        public static async Task <List <RaidbossLocation> > FetchRaidbossLocations(HttpClient http)
        {
            Stream dataStream = await http.GetStreamAsync("data/raidboss-locations.json");

            return(await JsonSerializer.DeserializeAsync <List <RaidbossLocation> >(dataStream));
        }
Example #19
0
        public T GetObjectFromApi <T>(string apiUrlParam)
        {
            var streamTask = this.ProcessAPI(apiUrlParam).Result;

            return(JsonSerializer.DeserializeAsync <T>(streamTask).Result);
        }
Example #20
0
        public static async Task <string> Generate(string outputPath, string tldJsonPath)
        {
            using (var tldJsonFile = File.OpenRead(tldJsonPath))
                using (var outputFile = new FileStream(Path.Combine(outputPath, "TLDs.cs"), FileMode.Create, FileAccess.Write))
                    using (var writer = new StreamWriter(outputFile, leaveOpen: true))
                    {
                        var tldsObject = await JsonSerializer.DeserializeAsync <TldsObject>(tldJsonFile);

                        writer.WriteLine("using System;");
                        writer.WriteLine("using System.Diagnostics;");
                        writer.WriteLine("using System.Collections.Generic;");
                        writer.WriteLine("using System.Globalization;");

                        writer.WriteLine();
                        writer.WriteLine("#pragma warning disable IDE1006 // Naming Styles");
                        writer.WriteLine("#pragma warning disable CA1720 // Identifier contains type name");
                        writer.WriteLine();

                        writer.WriteLine($"namespace DNSMadeEasy");
                        writer.WriteLine("{");
                        writer.WriteLine();
                        writer.WriteLine($"partial struct DomainName");
                        writer.WriteLine("{");

                        foreach (var(tld, description) in tldsObject.generic)
                        {
                            writer.WriteLine($"/// <summary>{description}</summary>");
                            writer.WriteLine($@"public static DomainName @{tld} => new DomainName(""{tld}"");");
                            writer.WriteLine();
                        }

                        writer.WriteLine("public static class CountryCodes");
                        writer.WriteLine("{");
                        foreach (var(tld, (country, notes)) in tldsObject.countryCodes)
                        {
                            writer.WriteLine($"/// <summary>{country}</summary>");
                            if (notes != null)
                            {
                                writer.WriteLine($"/// <remarks>{notes}</remarks>");
                            }
                            writer.WriteLine($@"public static DomainName @{tld} => new DomainName(""{tld}"");");
                            writer.WriteLine();
                        }

                        writer.WriteLine("}");

                        writer.WriteLine("public static class Geographic");
                        writer.WriteLine("{");
                        foreach (var(tld, (area, notes)) in tldsObject.geographic)
                        {
                            writer.WriteLine($"/// <summary>{area}</summary>");
                            if (notes != null)
                            {
                                writer.WriteLine($"/// <remarks>{notes}</remarks>");
                            }
                            writer.WriteLine($@"public static DomainName @{tld} => new DomainName(""{tld}"");");
                            writer.WriteLine();
                        }

                        writer.WriteLine("}");

                        var allTlds = tldsObject.generic.Select(kvp => kvp.Key)
                                      .Concat(tldsObject.countryCodes.Select(cc => cc.Key))
                                      .Concat(tldsObject.geographic.Select(g => g.Key))
                                      .OrderBy(i => i)
                                      .ToList();

                        writer.WriteLine($"private const int LongestKnownTld = {allTlds.Max(tld => tld.Length)};");
                        writer.WriteLine();
                        writer.WriteLine($"private static string[] KnownTlds {{ get; }} = {{ {string.Join(", ", allTlds.Select(tld => '"' + tld + '"'))} }};");

                        writer.WriteLine("}");

                        writer.WriteLine("}");

                        return(outputFile.Name);
                    }
        }
Example #21
0
 /// <summary>
 /// Read and deserialize the HttpContent streaming content
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <param name="content"></param>
 /// <returns></returns>
 public static async Task <T> ReadAsAsync <T>(this HttpContent content) =>
 await JsonSerializer.DeserializeAsync <T>(await content.ReadAsStreamAsync().ConfigureAwait(false)).ConfigureAwait(false);
Example #22
0
 private static ValueTask <SecurityPolicyReport?> ParseResponse(HttpRequest req)
 => JsonSerializer.DeserializeAsync <SecurityPolicyReport>(req.Body);
 /// <inheritdoc />
 public override async ValueTask <object?> DeserializeAsync(Stream stream, Type returnType, CancellationToken cancellationToken)
 {
     return(await JsonSerializer.DeserializeAsync(stream, returnType, _options, cancellationToken).ConfigureAwait(false));
 }
Example #24
0
 public async Task <IReadOnlyCollection <UbiUser> > GetAllAsync() =>
 (await JsonSerializer.DeserializeAsync <List <UbiUser> >(await GetAllUserStream())).AsReadOnly();
Example #25
0
        /// <summary>
        /// Gets the media info internal.
        /// </summary>
        /// <returns>Task{MediaInfoResult}.</returns>
        private async Task <MediaInfo> GetMediaInfoInternal(
            string inputPath,
            string primaryPath,
            MediaProtocol protocol,
            bool extractChapters,
            string probeSizeArgument,
            bool isAudio,
            VideoType?videoType,
            bool forceEnableLogging,
            CancellationToken cancellationToken)
        {
            var args = extractChapters
                ? "{0} -i {1} -threads 0 -v warning -print_format json -show_streams -show_chapters -show_format"
                : "{0} -i {1} -threads 0 -v warning -print_format json -show_streams -show_format";

            args = string.Format(args, probeSizeArgument, inputPath).Trim();

            var process = new Process
            {
                StartInfo = new ProcessStartInfo
                {
                    CreateNoWindow  = true,
                    UseShellExecute = false,

                    // Must consume both or ffmpeg may hang due to deadlocks. See comments below.
                    RedirectStandardOutput = true,

                    FileName  = _ffprobePath,
                    Arguments = args,

                    WindowStyle = ProcessWindowStyle.Hidden,
                    ErrorDialog = false,
                },
                EnableRaisingEvents = true
            };

            if (forceEnableLogging)
            {
                _logger.LogInformation("{ProcessFileName} {ProcessArgs}", process.StartInfo.FileName, process.StartInfo.Arguments);
            }
            else
            {
                _logger.LogDebug("{ProcessFileName} {ProcessArgs}", process.StartInfo.FileName, process.StartInfo.Arguments);
            }

            using (var processWrapper = new ProcessWrapper(process, this))
            {
                _logger.LogDebug("Starting ffprobe with args {Args}", args);
                StartProcess(processWrapper);

                InternalMediaInfoResult result;
                try
                {
                    result = await JsonSerializer.DeserializeAsync <InternalMediaInfoResult>(
                        process.StandardOutput.BaseStream,
                        cancellationToken : cancellationToken).ConfigureAwait(false);
                }
                catch
                {
                    StopProcess(processWrapper, 100);

                    throw;
                }

                if (result == null || (result.Streams == null && result.Format == null))
                {
                    throw new Exception("ffprobe failed - streams and format are both null.");
                }

                if (result.Streams != null)
                {
                    // Normalize aspect ratio if invalid
                    foreach (var stream in result.Streams)
                    {
                        if (string.Equals(stream.DisplayAspectRatio, "0:1", StringComparison.OrdinalIgnoreCase))
                        {
                            stream.DisplayAspectRatio = string.Empty;
                        }

                        if (string.Equals(stream.SampleAspectRatio, "0:1", StringComparison.OrdinalIgnoreCase))
                        {
                            stream.SampleAspectRatio = string.Empty;
                        }
                    }
                }

                return(new ProbeResultNormalizer(_logger, _localization).GetMediaInfo(result, videoType, isAudio, primaryPath, protocol));
            }
        }
 public static ValueTask <TValue> DeserializeAnonymousTypeAsync <TValue>(Stream stream, TValue anonymousTypeObject, JsonSerializerOptions options = default, CancellationToken cancellationToken = default)
 => JsonSerializer.DeserializeAsync <TValue>(stream, options, cancellationToken);    // Method to deserialize from a stream added for completeness
 public static async Task <T> DeserializeAsync <T>(Stream stream, JsonSerializerOptions jsonSerializerOptions = null)
 {
     return(await JsonSerializer.DeserializeAsync <T>(stream, jsonSerializerOptions));
 }
        public async ValueTask <IMessage> Unpack(object messageObj, Type typeToUnpack, CancellationToken cancellationToken)
        {
            using var memoryStream = new MemoryStream(Encoding.UTF8.GetBytes((string)messageObj));

            return((IMessage)await JsonSerializer.DeserializeAsync(memoryStream, typeToUnpack, _options, cancellationToken : cancellationToken));
        }
Example #29
0
        public static async Task <Dictionary <string, List <CapsRecord> > > GetCapsScores(DirectoryInfo cache, string chessdotcomUsername, int maxPages, int maxPagesWithCache)
        {
            if (cache == null)
            {
                throw new ArgumentNullException(nameof(cache));
            }

            Helpers.ResetDisplayCounter();
            string cacheFileName = $"{Path.Combine(cache.FullName, $"{chessdotcomUsername}Caps")}";
            Dictionary <string, List <CapsRecord> > capsScores       = new Dictionary <string, List <CapsRecord> >();
            Dictionary <string, List <CapsRecord> > capsScoresCached = new Dictionary <string, List <CapsRecord> >();

            if (File.Exists(cacheFileName))
            {
                using FileStream capsFileInStream = File.OpenRead(cacheFileName);
                capsScoresCached = await JsonSerializer.DeserializeAsync <Dictionary <string, List <CapsRecord> > >(capsFileInStream).ConfigureAwait(false);

                //If we have cached records only pull back the first few pages
                maxPages = maxPagesWithCache;
            }

            foreach (string control in new string[] { "bullet", "blitz", "rapid" })
            {
                foreach (string colour in new string[] { "white", "black" })
                {
                    string iterationKey = $"{control} {colour}";
                    capsScores.Add(iterationKey, new List <CapsRecord>());

                    for (int page = 1; page <= maxPages; page++)
                    {
                        List <double> capsScoreWhite = new List <double>();

                        using HttpClient client = new HttpClient();
                        HttpResponseMessage response = await client.GetAsync(new Uri($"https://www.chess.com/games/archive/{chessdotcomUsername}?color={colour}&gameOwner=other_game&gameType=live&gameTypeslive%5B%5D={control}&rated=rated&timeSort=desc&page={page}")).ConfigureAwait(false);

                        string pageContents = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

                        HtmlDocument pageDocument = new HtmlDocument();
                        pageDocument.LoadHtml(pageContents);

                        HtmlNodeCollection nodeCollection = pageDocument.DocumentNode.SelectNodes("//*[contains(@class,'archive-games-table')]");

                        if (nodeCollection == null || nodeCollection[0].InnerText.Contains("No results found", StringComparison.InvariantCultureIgnoreCase))
                        {
                            Helpers.ProcessedDisplay("X");
                            break;
                        }
                        else
                        {
                            foreach (HtmlNode row in nodeCollection[0].SelectNodes("//tr[contains(@class,'v-board-popover')]").Cast <HtmlNode>())
                            {
                                try
                                {
                                    CapsRecord capsRecord = new CapsRecord()
                                    {
                                        Caps = double.Parse(row.SelectNodes("td[contains(@class,'archive-games-analyze-cell')]/div")[(colour == "white") ? 0 : 1]
                                                            .InnerText, CultureInfo.InvariantCulture),
                                        GameDate = DateTime.Parse(row.SelectNodes("td[contains(@class,'archive-games-date-cell')]")[0]
                                                                  .InnerText
                                                                  .Trim(new char[] { ' ', '\n', '\r' })
                                                                  .Replace(",", "", StringComparison.InvariantCultureIgnoreCase), CultureInfo.InvariantCulture),
                                    };

                                    Helpers.ProcessedDisplay(".");
                                    capsScores[iterationKey].Add(capsRecord);
                                }
                                catch (System.NullReferenceException)
                                {
                                    //Value missing
                                    Helpers.ProcessedDisplay("-");
                                }
                                catch
                                {
                                    Helpers.ProcessedDisplay("E");
                                }
                            }
                        }
                    }
                }
            }

            //Resolve cache
            if (capsScoresCached.Count != 0)
            {
                foreach (string capsKey in capsScores.Where(x => x.Value.Count > 0).Select(x => x.Key).ToArray())
                {
                    //Remove records from the cache equal or after the new data
                    DateTime firstDate = capsScores[capsKey].Select(x => x.GameDate).Min();
                    capsScoresCached[capsKey] = capsScoresCached[capsKey].Where(x => DateTime.Compare(x.GameDate, firstDate) <= 0).ToList <CapsRecord>();
                    capsScores[capsKey]       = capsScores[capsKey].Where(x => DateTime.Compare(x.GameDate, firstDate) > 0).ToList <CapsRecord>();
                    //Merge the lists back together
                    capsScores[capsKey] = capsScores[capsKey].Concat(capsScoresCached[capsKey]).ToList <CapsRecord>();
                }
            }

            using FileStream capsFileOutStream = File.Create(cacheFileName);
            await JsonSerializer.SerializeAsync(capsFileOutStream, capsScores).ConfigureAwait(false);

            await capsFileOutStream.FlushAsync().ConfigureAwait(false);

            return(capsScores);
        }
Example #30
0
 public async Task <IEnumerable <Book> > GetAll()
 {
     return(await JsonSerializer.DeserializeAsync <IEnumerable <Book> >(
                await _httpClient.GetStreamAsync("api/books"),
                new JsonSerializerOptions { PropertyNameCaseInsensitive = true }));
 }
Example #31
0
 public async Task <Book> GetById(int bookId)
 {
     return(await JsonSerializer.DeserializeAsync <Book>(
                await _httpClient.GetStreamAsync($"api/books/{bookId}"),
                new JsonSerializerOptions { PropertyNameCaseInsensitive = true }));
 }
        public static async Task <IActionResult> RedeemInvitationCode(
            [HttpTrigger(AuthorizationLevel.Function, WebRequestMethods.Http.Post)] HttpRequest request,
            IBinder binder,
            ILogger log)
        {
            // Azure AD B2C calls into this API when a user is attempting to sign up with an invitation code.
            // We expect a JSON object in the HTTP request which contains the input claims as well as an additional
            // property "ui_locales" containing the locale being used in the user journey (browser flow).
            try
            {
                log.LogInformation("An invitation code is being redeemed.");
                // Look up the invitation code in the incoming request.
                var invitationCode = default(string);
                using (var reader = new StreamReader(request.Body))
                {
                    var requestBody = await reader.ReadToEndAsync();

                    log.LogInformation("Request body:");
                    log.LogInformation(requestBody);
                    var requestDocument = JsonDocument.Parse(requestBody);
                    log.LogInformation("Request properties:");
                    foreach (var element in requestDocument.RootElement.EnumerateObject())
                    {
                        log.LogInformation($"- {element.Name}: {element.Value.GetRawText()}");
                        if (element.Name.EndsWith("InvitationCode", StringComparison.InvariantCultureIgnoreCase)) // E.g. "extension_bd88c9da63214d09b854af9cfbbf4b15_InvitationCode"
                        {
                            invitationCode = element.Value.GetString();
                        }
                    }
                }

                if (string.IsNullOrWhiteSpace(invitationCode) || invitationCode.Length < 10)
                {
                    // No invitation code was found in the request or it was too short, return a validation error.
                    log.LogInformation($"The provided invitation code \"{invitationCode}\" is invalid.");
                    return(GetValidationErrorApiResponse("UserInvitationRedemptionFailed-Invalid", "The invitation code you provided is invalid."));
                }
                else
                {
                    // An invitation code was found in the request, look up the user invitation in persistent storage.
                    log.LogInformation($"Looking up user invitation for invitation code \"{invitationCode}\"...");
                    var blobInputStream = binder.Bind <Stream>(new BlobAttribute($"userinvitations/{invitationCode}.json", FileAccess.Read));
                    if (blobInputStream == null)
                    {
                        // The requested invitation code was not found in persistent storage.
                        log.LogWarning($"User invitation for invitation code \"{invitationCode}\" was not found.");
                        return(GetValidationErrorApiResponse("UserInvitationRedemptionFailed-NotFound", "The invitation code you provided is invalid."));
                    }
                    else
                    {
                        // The requested invitation code was found in persistent storage, look up the pre-identified information.
                        log.LogInformation($"User invitation found for invitation code \"{invitationCode}\".");
                        var invitationCodeRequest = await JsonSerializer.DeserializeAsync <InvitationCodeRequest>(blobInputStream);

                        // TODO: At this point, the blob can be deleted again.

                        return(GetContinueApiResponse("UserInvitationRedemptionSucceeded", "The invitation code you provided is valid.", invitationCodeRequest.CompanyId));
                    }
                }
            }
            catch (Exception exc)
            {
                log.LogError(exc, "Error while processing request body: " + exc.ToString());
                return(GetBlockPageApiResponse("UserInvitationRedemptionFailed-InternalError", "An error occurred while validating your invitation code, please try again later."));
            }
        }
Example #33
-1
        public async Task DeserializeAsync_with_serialized_types()
        {
            var serializer = new JsonSerializer();
            var serializedObj = @"{""$type"":""Kephas.Serialization.Json.Tests.JsonSerializerTest+TestEntity, Kephas.Serialization.Json.Tests"",""name"":""John Doe""}";
            var obj = await serializer.DeserializeAsync(serializedObj);

            Assert.IsInstanceOf<TestEntity>(obj);

            var testEntity = (TestEntity)obj;

            Assert.AreEqual("John Doe", testEntity.Name);
        }