/// <inheritdoc />
        public async Task <TResultType?> Deserialize <TResultType>(Stream deserializable, CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();
            var typeInfo = (JsonTypeInfo <TResultType>)(serializerContext.GetTypeInfo(typeof(TResultType)) ?? throw new Exception($"Could not find type info for type {typeof(TResultType).Name}."));

            return(await SystemTextJsonSerializer.DeserializeAsync(deserializable, typeInfo, cancellationToken));
        }
        public async Task <List <TwitterStatus> > GetFrom(long id, bool sortAsc = false, int count = 500)
        {
            var results = await _tweets.Find(new BsonDocument("id", new BsonDocument(sortAsc ? "$gte" : "$lte", id)))
                          .Sort("{id: " + (sortAsc ? "1" : "-1") + "}")
                          .Limit(count)
                          .ToListAsync();

            List <TwitterStatus> tweets = new List <TwitterStatus>(count);

            foreach (dynamic dbTweet in results)
            {
                using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(dbTweet))))
                {
                    TwitterStatus tweet = await JsonSerializer.DeserializeAsync <TwitterStatus>(ms).ConfigureAwait(false);

                    //Fill parsed text variables
                    tweet.ParsedFullText = TweetTextParser.ParseTweetText(tweet);
                    if (tweet.OriginatingStatus != null)
                    {
                        tweet.OriginatingStatus.ParsedFullText = TweetTextParser.ParseTweetText(tweet.OriginatingStatus);
                    }
                    if (tweet.QuotedStatus != null)
                    {
                        tweet.QuotedStatus.ParsedFullText = TweetTextParser.ParseTweetText(tweet.QuotedStatus);
                    }

                    tweets.Add(tweet);
                }
            }

            return(tweets);
        }
        public async Task RunCreatesLambdaAndCallsHandle(
            TestLambdaMessage expectedResponse,
            TestLambdaMessage request,
            ServiceCollection collection,
            JsonSerializer serializer,
            ILogger logger,
            [Substitute] TestLambda lambda,
            [Substitute] LambdaScope scope,
            [Substitute] ILambdaContext context
            )
        {
            lambda.Handle(Any <TestLambdaMessage>(), Any <CancellationToken>()).Returns(expectedResponse);
            collection.AddSingleton <ISerializer>(serializer);
            collection.AddSingleton(lambda);
            collection.AddSingleton(scope);

            using var inputStream = await CreateStreamForRequest(request);

            var provider = collection.BuildServiceProvider();

            await using var host = new TestLambdaHost(lambdaHost =>
            {
                lambdaHost.ServiceProvider = provider;
                lambdaHost.Logger          = logger;
            });

            var cancellationToken = new CancellationToken(false);
            var responseStream    = await host.Run(inputStream, context, cancellationToken);

            var response = await SystemTextJsonSerializer.DeserializeAsync <TestLambdaMessage>(responseStream);

            response.Should().NotBeNull();
            response !.Id.Should().Be(expectedResponse.Id);
            await lambda.Received().Handle(Is <TestLambdaMessage>(req => req.Id == request.Id), Is(cancellationToken));
        }
Exemplo n.º 4
0
        public async Task <T> GetCurrentPrice(string investmentToolCode, string url)
        {
            _logger.LogInformation("Url is : " + url);
            if (string.IsNullOrEmpty(url))
            {
                _logger.LogInformation("Could not find Paragaranti Url to retrieve current foreign currency price");
                throw new ArgumentNullException(nameof(url));
            }
            T pgPrice = null;

            try
            {
                _logger.LogInformation("Calling provider's endpoint...");
                HttpResponseMessage response = await _client.GetAsync(url + investmentToolCode);

                if (response.IsSuccessStatusCode)
                {
                    _logger.LogInformation("Succesfully took prices from provider...");
                    var pgForeignCurrencyStream = response.Content.ReadAsStreamAsync();
                    _logger.LogInformation("Serializing prices...");
                    var pgPriceDto = await JsonSerializer.DeserializeAsync <PgForeignCurrencyCurrentPriceDto>(await pgForeignCurrencyStream);

                    _logger.LogInformation("Mapping prices...");
                    pgPrice = _mapper.Map <T>(pgPriceDto, o => o.Items["CurrencyCode"] = investmentToolCode);
                }
            }
            catch (Exception ex)
            {
                _logger.LogError($"Unexpected error occured while getting {investmentToolCode} price." + ex.Message);
            }
            _logger.LogInformation("Completed.");
            return(pgPrice);
        }
Exemplo n.º 5
0
        public async Task <T> DeserializeJsonFromStreamAsync <T>(Stream stream)
        {
            if (stream == null || stream.CanRead == false)
            {
                return(default(T));
            }

            var res = await JsonSerializer.DeserializeAsync <T>(stream);

            return(res);
        }
Exemplo n.º 6
0
        public async void DeserializeFromStreamWithBOMThenString()
        {
            var messageAsString    = ConvertToString(stream);
            var messageBodyInBytes = Encoding.UTF8.GetBytes(messageAsString);

            await using var convertedStream = new MemoryStream(messageBodyInBytes);

            var returnTestObject = await CoreJsonSerializer.DeserializeAsync <TestObject>(convertedStream);

            Assert.Equal(testObject, returnTestObject);
        }
Exemplo n.º 7
0
        public async Task <CoinDeskResponse> GetBitcoinPriceIndex()
        {
            var request = new HttpRequestMessage(HttpMethod.Get, "bpi/currentprice.json");

            var response = await _client.SendAsync(request);

            response.EnsureSuccessStatusCode();

            var responseStream = await response.Content.ReadAsStreamAsync();

            {
                return(await JsonSerializer.DeserializeAsync <CoinDeskResponse>(responseStream));
            }
        }
Exemplo n.º 8
0
        static async Task Main(string[] args)
        {
            // create an object graph
            var people = new List <Person>
            {
                new Person(30000M)
                {
                    FirstName = "Alice",
                    LastName  = "Smith", DateOfBirth = new DateTime(1974, 3, 14)
                },
                new Person(40000M)
                {
                    FirstName   = "Bob", LastName = "Jones",
                    DateOfBirth = new DateTime(1969, 11, 23)
                },
                new Person(20000M)
                {
                    FirstName   = "Charlie", LastName = "Cox",
                    DateOfBirth = new DateTime(1984, 5, 4),
                    Children    = new HashSet <Person>
                    {
                        new Person(0M)
                        {
                            FirstName   = "Sally", LastName = "Cox",
                            DateOfBirth = new DateTime(2000, 7, 12)
                        }
                    }
                }
            };

            // create object that will format a List of Persons as XML
            var xs = new XmlSerializer(typeof(List <Person>));

            // create a file to write to
            string path = Combine(CurrentDirectory, "people.xml");

            using (FileStream stream = File.Create(path))
            {
                // serialize the object graph to the stream
                xs.Serialize(stream, people);
            }

            WriteLine("Written {0:N0} bytes of XML to {1}",
                      arg0: new FileInfo(path).Length,
                      arg1: path);

            WriteLine();

            // Display the serialized object graph
            WriteLine(File.ReadAllText(path));

            // Deserializing with XML

            using (FileStream xmlLoad = File.Open(path, FileMode.Open))
            {
                // deserialize and cast the object graph into a List of Person
                var loadedPeople = (List <Person>)xs.Deserialize(xmlLoad);

                foreach (var item in loadedPeople)
                {
                    WriteLine("{0} has {1} children.",
                              item.LastName, item.Children.Count ?? 0);
                }
            }

            // create a file to write to
            string jsonPath = Combine(CurrentDirectory, "people.json");

            using (StreamWriter jsonStream = File.CreateText(jsonPath))
            {
                // create an object that will format as JSON
                var jss = new Newtonsoft.Json.JsonSerializer();

                // serialize the object graph into a string
                jss.Serialize(jsonStream, people);
            }

            WriteLine();
            WriteLine("Written {0:N0} bytes of JSON to: {1}",
                      arg0: new FileInfo(jsonPath).Length,
                      arg1: jsonPath);

            // Display the serialized object graph
            WriteLine(File.ReadAllText(jsonPath));

            // Deserializing JSON using new APIs

            using (FileStream jsonLoad = File.Open(
                       jsonPath, FileMode.Open))
            {
                // deserialize object graph into a List of Person
                var loadedPeople = (List <Person>)
                                   await NuJson.DeserializeAsync(
                    utf8Json : jsonLoad,
                    returnType : typeof(List <Person>));

                foreach (var item in loadedPeople)
                {
                    WriteLine("{0} has {1} children.",
                              item.LastName, item.Children?.Count ?? 0);
                }
            }
        }
Exemplo n.º 9
0
        static async Task Main(string[] args)
        {
            // Console.WriteLine("Hello World!");
            var people = new List <Person> {
                new Person(30000M)
                {
                    FirstName = "Alice", LastName = "Smith", DateOfBirth = new DateTime(1974, 3, 14)
                },
                new Person(40000M)
                {
                    FirstName = "Bob", LastName = "Jones", DateOfBirth = new DateTime(1969, 11, 23)
                },
                new Person(20000M)
                {
                    FirstName = "Charlie", LastName = "Cox", DateOfBirth = new DateTime(1984, 5, 4),
                    Children  = new HashSet <Person> {
                        new Person(0M)
                        {
                            FirstName = "Sally", LastName = "Cox", DateOfBirth = new DateTime(2000, 7, 12)
                        }
                    }
                }
            };
            var    xs   = new XmlSerializer(typeof(List <Person>));
            string path = Combine(CurrentDirectory, "people.xml");

            using (FileStream stream = File.Create(path)){
                xs.Serialize(stream, people);
            }
            WriteLine("Written {0:N0} bytes of XML to {1}",
                      arg0: new FileInfo(path).Length, arg1: path);
            WriteLine();
            WriteLine(File.ReadAllText(path));

            using (FileStream xmlLoad = File.Open(path, FileMode.Open)){
                var loadedPeople = (List <Person>)xs.Deserialize(xmlLoad);
                foreach (var item in loadedPeople)
                {
                    WriteLine("{0} has {1} children.",
                              item.LastName, item.Children.Count);
                }
            }

            string jsonPath = Combine(CurrentDirectory, "people.json");

            using (StreamWriter jsonStream = File.CreateText(jsonPath)){
                var jss = new Newtonsoft.Json.JsonSerializer();
                jss.Serialize(jsonStream, people);
            }
            WriteLine();
            WriteLine("Written {0:N0} bytes of JSON to: {1}",
                      arg0: new FileInfo(jsonPath).Length, arg1: jsonPath);
            WriteLine(File.ReadAllText(jsonPath));

            using (FileStream jsonLoad = File.Open(jsonPath, FileMode.Open)){
                var loadedPeople = (List <Person>) await NuJson.DeserializeAsync(
                    utf8Json : jsonLoad, returnType : typeof(List <Person>));

                foreach (var item in loadedPeople)
                {
                    WriteLine("{0} has {1} children.",
                              item.LastName, item.Children?.Count);
                }
            }
        }
Exemplo n.º 10
0
        static async Task Main(string[] args)
        {
            // XML = eXtensible Markup Language - more verbose, better supported in legacy systems
            // JSON - JavaScript Object Notation - more compact, better for web and mobile apps

            Console.WriteLine("\n\nWorkingWithSerialization running...");


            // Create an object graph
            // Notes:   An object graph is a set of objects that reference one another.
            //          Serializing an object graph is tricky (the serializer has to assign a unique ID to every object and then replace references with unique IDs)
            //          Note - when using XmlSerializer, remember only th public fields and properties are included - and the type must have a parameterless contructor.
            //          Output (xml) can be customised with attributes - there are many other ones than given here.
            var people = new List <Person>
            {
                new Person(30000M)
                {
                    FirstName     = "Alice"
                    , LastName    = "Smith"
                    , DateOfBirth = new DateTime(1974, 3, 14)
                },
                new Person(40000M)
                {
                    FirstName   = "Bob",
                    LastName    = "Jones",
                    DateOfBirth = new DateTime(1969, 11, 23)
                },
                new Person(20000M)
                {
                    FirstName   = "Charlie",
                    LastName    = "Cox",
                    DateOfBirth = new DateTime(1984, 5, 4),
                    Children    = new HashSet <Person> {
                        new Person(0M)
                        {
                            FirstName   = "Sally",
                            LastName    = "Cox",
                            DateOfBirth = new DateTime(2000, 7, 12)
                        },
                        new Person(0M)
                        {
                            FirstName   = "Ted",
                            LastName    = "Cox",
                            DateOfBirth = new DateTime(2002, 8, 1)
                        },
                    }
                }
            };

            // create object that will format a List of Persons as XML
            // NOTE:    typeof is an operator keyword which is used to get a type at the compile-time.
            //          This operator takes the Type itself as an argument and returns the marked type of the argument.
            var xmlPersonListSerializer = new XmlSerializer(typeof(List <Person>));

            // create a file to write to
            string filePath = Combine(CurrentDirectory, "people.xml");

            using (FileStream xmlFileStream = File.Create(filePath))
            {
                // serialize object graph to the stream
                xmlPersonListSerializer.Serialize(xmlFileStream, people);
            }   // remember File stream is closed and disposed of due to the using stmt

            WriteLine($"Written {new FileInfo(filePath).Length} bytes of XML to {filePath}.");

            // display the serialized object graph
            WriteLine(File.ReadAllText(filePath));


            // ------------- DESERIALIZING XML file back into live objects in memory  -----------------
            using (FileStream xmlLoad = File.Open(filePath, FileMode.Open))
            {
                // deserialize and explicitly cast the object graph into a List of Person
                var loadedPeople = (List <Person>)xmlPersonListSerializer.Deserialize(xmlLoad);

                foreach (var item in loadedPeople)
                {
                    WriteLine($"{item.FirstName} {item.LastName} has {item.Children.Count} children.");
                }
            }

            // create file to write to
            string jsonPath = Combine(CurrentDirectory, "people.json");

            using (StreamWriter jsonStream = File.CreateText(jsonPath))
            {
                // create an objec that will format as JSON
                JsonSerializer jsonSerializer = new JsonSerializer();

                // serialize the object graph into a string
                jsonSerializer.Serialize(jsonStream, people);
            }

            WriteLine("\nWritten {0:N0} bytes of Json to {1}", new FileInfo(jsonPath).Length, jsonPath);

            // display serialized object graph
            WriteLine(File.ReadAllText(jsonPath));


            // Deserializing JSON using new APIs
            using (FileStream jsonLoad = File.Open(jsonPath, FileMode.Open))
            {
                // deserialize object graph into a List of Person
                var loadedPeople = (List <Person>)
                                   await NuJson.DeserializeAsync(
                    utf8Json : jsonLoad,
                    returnType : typeof(List <Person>));

                foreach (var item in loadedPeople)
                {
                    WriteLine("{0} has {1} children.", item.LastName, item.Children?.Count);
                }
            }
        }
        static async Task Main(string[] args)
        {
            var people = new List <Person> {
                new Person(30000m)
                {
                    FirstName   = "Alice",
                    LastName    = "Jones",
                    DateOfBirth = new DateTime(1974, 3, 13)
                },
                new Person(40000m)
                {
                    FirstName   = "Bob",
                    LastName    = "Jones",
                    DateOfBirth = new DateTime(1969, 11, 13)
                },
                new Person(20000m)
                {
                    FirstName = "Charles",
                    LastName  = "Cox",
                    Children  = new HashSet <Person> {
                        new Person(0m)
                        {
                            FirstName   = "Sally",
                            LastName    = "Cox",
                            DateOfBirth = new DateTime(2000, 7, 12)
                        }
                    }
                }
            };

            // var xs = new XmlSerializer(typeof(List<Person>));
            // string path = Path.Combine(Environment.CurrentDirectory, "people.xml");

            // using(FileStream stream = File.Create(path)){
            //     xs.Serialize(stream, people);
            // }

            // Console.WriteLine("Written {0:N0} bytes of XML to {1}", new FileInfo(path).Length, path);
            // Console.WriteLine();
            // Console.WriteLine(File.ReadAllText(path));

            // using(FileStream stream = File.Open(path, FileMode.Open)){
            //     var loadedPeople = (List<Person>)xs.Deserialize(stream);

            //     foreach(var item in loadedPeople){
            //         Console.WriteLine("{0} has {1} children", item.LastName, item.Children.Count);
            //     }
            // }

            string jsonPath = Path.Combine(Environment.CurrentDirectory, "people.json");

            using (StreamWriter jsonStream = File.CreateText(jsonPath)){
                var jss = new JsonSerializer();

                jss.Serialize(jsonStream, people);
            }

            Console.WriteLine();
            Console.WriteLine("Written {0:N0} bytes of JSON to: {1}", new FileInfo(jsonPath).Length, jsonPath);

            Console.WriteLine(File.ReadAllText(jsonPath));

            using (FileStream jsonLoad = File.Open(jsonPath, FileMode.Open)){
                var loadedPeople = (List <Person>) await NuJson.DeserializeAsync(
                    utf8Json : jsonLoad,
                    returnType : typeof(List <Person>));

                foreach (var item in loadedPeople)
                {
                    Console.WriteLine("{0} has {1} children.", item.LastName, item.Children?.Count);
                }
            }
        }
Exemplo n.º 12
0
 private async Task <IEnumerable <StorageItem> > Deserialize()
 {
     await using var gunzipStream = storageCompressor.GetDecompressStream(data.ToArray());
     return(await JsonSerializer.DeserializeAsync <IEnumerable <StorageItem> >(gunzipStream));
 }
Exemplo n.º 13
0
        public async void DeserializeFromStreamWithBOM()
        {
            var returnTestObject = await CoreJsonSerializer.DeserializeAsync <TestObject>(stream);

            Assert.Equal(testObject, returnTestObject);
        }
Exemplo n.º 14
0
        static async Task Main(string[] args)
        {
            string path     = @"c:\workshops\people1.xml";
            string pathJson = @"c:\workshops\people1.json";

            using (FileStream jsonLoad = File.Open(pathJson, FileMode.Open))
            {
                // deserialize object graph into a List of Person
                var loadedPeople = (List <Person>)
                                   await NuJson.DeserializeAsync(
                    utf8Json : jsonLoad,
                    returnType : typeof(List <Person>));

                foreach (var item in loadedPeople)
                {
                }
            }

            var xs = new XmlSerializer(typeof(List <Person>));

            // create a file to write to


            using (FileStream xmlLoad = File.Open(path, FileMode.Open))
            {
                // deserialize and cast the object graph into a List of Person
                var loadedPeople = (List <Person>)xs.Deserialize(xmlLoad);
                foreach (var item in loadedPeople)
                {
                }
            }



            var people = new List <Person>
            {
                new Person(30000M)
                {
                    FirstName   = "Alice",
                    LastName    = "Smith",
                    DateOfBirth = new DateTime(1974, 3, 14)
                },
                new Person(40000M)
                {
                    FirstName   = "Bob",
                    LastName    = "Jones",
                    DateOfBirth = new DateTime(1969, 11, 23)
                },
                new Person(20000M)
                {
                    FirstName   = "Charlie",
                    LastName    = "Cox",
                    DateOfBirth = new DateTime(1984, 5, 4),
                    Children    = new HashSet <Person>
                    {
                        new Person(0M)
                        {
                            FirstName   = "Sally",
                            LastName    = "Cox",
                            DateOfBirth = new DateTime(2000, 7, 12)
                        }
                    }
                }
            };

            using (StreamWriter jsonStream = File.CreateText(pathJson))
            {
                // create an object that will format as JSON
                var jss = new Newtonsoft.Json.JsonSerializer();
                // serialize the object graph into a string
                jss.Serialize(jsonStream, people);
            }


            // create object that will format a List of Persons as XML

            using (FileStream stream = File.Create(path))
            {
                // serialize the object graph to the stream
                xs.Serialize(stream, people);
            }
        }