Пример #1
0
        /// <summary>
        ///
        /// </summary>
        public void RunJsonSerializationExample()
        {
            PizzaService service = PizzaService.Create();

            using (MemoryStream stream = new MemoryStream(64 * 1024))
                using (StreamWriter writer = new StreamWriter(stream, Encoding.UTF8))
                {
                    // -----------------------------------------
                    // Serialize the Object "service" in the TextWriter "writer"
                    JsonSerializer jsonSerializer = new JsonSerializer();
                    jsonSerializer.Serialize(writer, service);
                    writer.Flush();
                    Console.WriteLine("[JsonSerialization] Size of JSON serialized object = {0} Bytes", stream.Length);

                    // -----------------------------------------
                    // Convert the binary encoded JSON String into a string variable
                    string jsonText = Encoding.UTF8.GetString(stream.ToArray());
                    Console.WriteLine("[JsonSerialization] Encoded into JSON = {0}...", jsonText.Substring(0, 10));

                    // -----------------------------------------
                    // Check if JSON is valid
                    try
                    {
                        JToken token = JToken.Parse(jsonText);
                        Console.WriteLine("[JsonSerialization] The given JSON is valid.");
                    }
                    catch (Exception)
                    {
                        Console.WriteLine("[JsonSerialization] The given JSON is NOT valid.");
                    }

                    // TODO
                }
        }
Пример #2
0
        /// <summary>
        ///
        /// </summary>
        public void RunXmlSerializationExample()
        {
            PizzaService service = PizzaService.Create();

            using (MemoryStream stream = new MemoryStream(64 * 1024))
            {
                // -----------------------------------------
                // Serialize into XML using the XmlSerializer
                XmlSerializer xmlSerializer = new XmlSerializer(typeof(PizzaService));
                xmlSerializer.Serialize(stream, service);

                // -----------------------------------------
                // Convert the binary encoded XML String into a string variable
                string xmlText = Encoding.UTF8.GetString(stream.ToArray());

                // -----------------------------------------
                // Using the XmlSerializer to create the object from XML
                stream.Seek(0, SeekOrigin.Begin);
                xmlSerializer = new XmlSerializer(typeof(PizzaService));
                service       = (PizzaService)xmlSerializer.Deserialize(stream);

                // -----------------------------------------
                // Check if given XML is valid
                xmlSerializer = new XmlSerializer(typeof(PizzaService));
                using (XmlReader reader = new XmlTextReader(new StringReader(xmlText)))
                {
                    bool check = xmlSerializer.CanDeserialize(reader);
                    Console.WriteLine("[XmlSerialization] Given XML is valid = {0}", check);
                }

                // -----------------------------------------
                // TODO: XmlDocument
                // TODO: XmlReader, XmlWriter
            }
        }
Пример #3
0
        /// <summary>
        ///
        /// </summary>
        public void RunBinarySerializationExample()
        {
            DateTime     current = DateTime.MinValue;
            PizzaService service = PizzaService.Create();

            using (MemoryStream stream = new MemoryStream(64 * 1024))
            {
                // -----------------------------------------
                // Serialize using the BinaryFormatter
                // - The one rule is that you need the [Serializable] attribute on the class deklaration
                // - The BinaryFormatter can ignore fields when using the [NonSerialized] attribute on the field
                BinaryFormatter formatter = new BinaryFormatter();
                formatter.Serialize(stream, service);
                Console.WriteLine("[BinaryFormatter] Size of serialized object = {0} Bytes", stream.Length);

                // -----------------------------------------
                // Deserialize using the BinaryFormatter
                stream.Seek(0, SeekOrigin.Begin);
                service = (PizzaService)formatter.Deserialize(stream);

                // -----------------------------------------
                // Implementing a custom serialization using the binary formatter
                stream.SetLength(0);
                formatter.Serialize(stream, new BinaryFormatterExample());
                stream.Seek(0, SeekOrigin.Begin);
                var example = (BinaryFormatterExample)formatter.Deserialize(stream);

                // -----------------------------------------
                // Using the context to provide addtional information or Services
                formatter.Context = new StreamingContext(StreamingContextStates.Remoting, "Hello services");
                formatter.Serialize(stream, new BinaryFormatterExample());
                stream.Seek(0, SeekOrigin.Begin);
                Console.Write("[BinaryFormatter] The additional information with in the context says = ");
                example = (BinaryFormatterExample)formatter.Deserialize(stream);
                Console.WriteLine();

                // -----------------------------------------
                // Using the SerializationBinder to provide types
                // TODO

                // formatter.AssemblyFormat
                // formatter.TypeFormat
                // formatter.FilterLevel = TypeFilterLevel.
            }
        }
Пример #4
0
        /// <summary>
        ///
        /// </summary>
        public void RunLinqClauseExamples()
        {
            // --------------------------------------------------------------------------------------------
            // - from clause https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/from-clause
            // - where clause https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/where-clause
            // - select clause https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/select-clause
            // - group clause https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/group-clause
            // - orderby clause https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/orderby-clause
            // - join clause https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/join-clause
            // - let clause https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/let-clause

            PizzaService service = PizzaService.Create();

            // --------------------------------------------------------------------------------------------
            // orderby clause example
            {
                // -----------------------------------------
                // Ascending
                var result = from pizza in service.Pizzas
                             where pizza.Ingredients.Length > 3
                             orderby pizza.Name
                             select pizza;

                var result2 = service.Pizzas
                              .Where(pizza => pizza.Ingredients.Length > 3)
                              .OrderBy(pizza => pizza.Name);

                // -----------------------------------------
                // Descending
                var result3 = from pizza in service.Pizzas
                              where pizza.Ingredients.Length > 3
                              orderby pizza.Name descending
                              select pizza;

                var result4 = service.Pizzas
                              .Where(pizza => pizza.Ingredients.Length > 3)
                              .OrderBy(pizza => pizza.Name)
                              .Reverse();
            }

            // --------------------------------------------------------------------------------------------
            // join clause example
            {
                var result = from pizza in service.Pizzas
                             join customer in service.Customers on pizza.Name equals customer.Favorite
                             select new { Pizza = pizza.Name, Customer = customer.Name };

                var result2 = service.Pizzas.Join(
                    service.Customers,
                    pizza => pizza.Name,
                    customer => customer.Favorite,
                    (pizza, customer) => new { Pizza = pizza.Name, Customer = customer.Name });
            }

            // --------------------------------------------------------------------------------------------
            // group clause example
            {
                var result = from customer in service.Customers
                             group customer by customer.Favorite;

                var result2 = service.Customers
                              .GroupBy(customer => customer.Favorite);
            }
        }
Пример #5
0
        /// <summary>
        ///
        /// </summary>
        public void RunLinqSelectExamples()
        {
            // --------------------------------------------------------------------------------------------
            // - Enumerable.Select https://docs.microsoft.com/en-us/dotnet/api/system.linq.enumerable.select
            //   TODO
            // - Select clause in C# https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/select-clause
            //   TODO

            PizzaService service = PizzaService.Create();

            // --------------------------------------------------------------------------------------------
            // Creating an anonymus object
            var result = service.Pizzas.Select(a => new {
                a.Name,
                a.Price,
            });

            Console.Write("[LinQ.Select] Results = ");
            foreach (var entry in result)
            {
                Console.Write("[Name = {0}, Price = {1}], ", entry.Name, entry.Price);
            }
            Console.WriteLine();

            // --------------------------------------------------------------------------------------------
            // Changing the property names in the anonymus object
            var result2 = service.Pizzas.Select(a => new {
                Pizza = a.Name,
                Cost  = a.Price,
            });

            Console.Write("[LinQ.Select2] Results = ");
            foreach (var entry in result2)
            {
                Console.Write("[Pizza = {0}, Cost = {1}], ", entry.Pizza, entry.Cost);
            }
            Console.WriteLine();

            // --------------------------------------------------------------------------------------------
            // Additional expressions while creating the object
            var result3 = service.Customers.Select(a => new {
                Name    = a.Name,
                Address = a.Address ?? "None",
            });

            Console.Write("[LinQ.Select3] Results = ");
            foreach (var entry in result3)
            {
                Console.Write("[Name = {0}, Address = {1}], ", entry.Name, entry.Address);
            }
            Console.WriteLine();

            // --------------------------------------------------------------------------------------------
            // Changing the names in the resulting object
            var result4 = service.Pizzas.Select(a => a.Name);

            Console.WriteLine("[LinQ.Select4] Results = {0}", string.Join(", ", result4));

            // --------------------------------------------------------------------------------------------
            // And the real deal
            var result5 = from p in service.Pizzas
                          select new {
                p.Name,
                p.Price,
            };

            Console.Write("[LinQ.Select5] Results = ");
            foreach (var entry in result5)
            {
                Console.Write("[Name = {0}, Price = {1}], ", entry.Name, entry.Price);
            }
            Console.WriteLine();
        }