Ejemplo n.º 1
0
        static void Main(string[] args)
        {
            //Из лабораторной  №5    выберите класс  с наследованием  и / или
            //композицией / агрегацией  для сериализации.  Выполните
            //сериализацию / десериализацию объекта используя
            //a.бинарный,
            var stone1 = new Stone {
                Color = "Белый", Price = 20, Status = ProductStatus.Ready, Weight = 100
            };
            // создаем объект BinaryFormatter
            BinaryFormatter formatter = new BinaryFormatter();

            // получаем поток, куда будем записывать сериализованный объект
            using (FileStream fs = new FileStream("Product1.dat", FileMode.OpenOrCreate))
            {
                formatter.Serialize(fs, stone1);
            }
            // десериализация
            using (FileStream fs = new FileStream("Product1.dat",
                                                  FileMode.OpenOrCreate))
            {
                Stone newStone = (Stone)formatter.Deserialize(fs);
                Console.WriteLine($"{newStone}");
            }

            //b.SOAP,
            var pStone1 = new Stone {
                Color = "Желтый", Price = 40, Status = ProductStatus.Ready, Weight = 40
            };
            SoapFormatter soapFormatter = new SoapFormatter();

            using (Stream fStream = new FileStream("Product2.soap",
                                                   FileMode.Create))
            {
                soapFormatter.Serialize(fStream, pStone1);
            }
            using (FileStream fs = new FileStream("Product2.soap",
                                                  FileMode.Open))
            {
                Stone newStone2 = (Stone)soapFormatter.Deserialize(fs);
                Console.WriteLine($"{newStone2}");
            }

            //c.JSON формат

            var ruby1 = new Stone {
                Color = "Red", Price = 57, Status = ProductStatus.None, Weight = 30
            };
            DataContractJsonSerializer jsonFormatter = new DataContractJsonSerializer(typeof(Stone));

            using (FileStream fs = new FileStream("Product3.json", FileMode.OpenOrCreate))
            {
                jsonFormatter.WriteObject(fs, ruby1);
            }
            using (FileStream fs = new FileStream("Product3.json", FileMode.OpenOrCreate))
            {
                Stone newStone3 = (Stone)jsonFormatter.ReadObject(fs);
                Console.WriteLine($"{newStone3}");
            }

            //d.XML формат
            var diamond1 = new Stone {
                Color = "Прозрачный", Price = 89, Status = ProductStatus.Ready, Weight = 28
            };
            XmlSerializer xml = new XmlSerializer(typeof(Stone));

            using (FileStream fs = new FileStream("Product4.xml", FileMode.OpenOrCreate))
            {
                xml.Serialize(fs, diamond1);
            }
            using (FileStream fs = new FileStream("Product4.xml", FileMode.OpenOrCreate))
            {
                Stone newStone4 = xml.Deserialize(fs) as Stone;
                Console.WriteLine($"{newStone4}");
            }

            //2.Создайте  коллекцию(массив)  объектов и  выполните
            //сериализацию / десериализацию.
            var s1 = new Stone {
                Color = "Розовый", Price = 57, Status = ProductStatus.None, Weight = 30
            };
            var s2 = new Stone {
                Color = "Синий", Price = 89, Status = ProductStatus.Ready, Weight = 28
            };
            var s3 = new Stone {
                Color = "Зелёный", Price = 30, Status = ProductStatus.None, Weight = 41
            };
            var s4 = new Stone {
                Color = "Чёрный", Price = 50, Status = ProductStatus.Ready, Weight = 44
            };

            Stone[] arr = new Stone[] { s1, s2, s3, s4 };

            DataContractSerializer array = new DataContractSerializer(typeof(Stone[]));

            using (FileStream fs = new FileStream("array.xml", FileMode.OpenOrCreate))
            {
                array.WriteObject(fs, arr);
            }
            using (FileStream fs = new FileStream("array.xml", FileMode.OpenOrCreate))
            {
                Stone[] newS = (Stone[])array.ReadObject(fs);
                foreach (Stone s in newS)
                {
                    Console.WriteLine($"{s}");
                }
            }

            //3.Используя XPath напишите два селектора для вашего XML документа.

            XmlDocument xDoc = new XmlDocument();

            xDoc.Load("array.xml");
            XmlElement  xRoot = xDoc.DocumentElement;
            XmlNodeList all   = xRoot.SelectNodes("*"); //выбирает все узлы

            foreach (XmlNode x in all)
            {
                Console.WriteLine(x.OuterXml);         //вывод всей разметки
            }

            XmlNode parts = xRoot.FirstChild;              //выбирает узлы Stone

            Console.WriteLine(parts.FirstChild.InnerText); //вывод значения первого узла


            //4.Используя Linq to XML(или Linq to JSON) создайте новый xml(json) - документ и напишите несколько запросов.
            XDocument  xdoc            = new XDocument();
            XElement   stoneshop       = new XElement("stoneshop"); //первый эл
            XAttribute bs_name_attr    = new XAttribute("name", "theorite");
            XElement   bs_country_elem = new XElement("country", "Belgium");
            XElement   bs_auc_elem     = new XElement("auction", "yes");

            stoneshop.Add(bs_name_attr);            //заполняем аттрибутом и элем-ми
            stoneshop.Add(bs_country_elem);
            stoneshop.Add(bs_auc_elem);

            XElement   stoneshop2       = new XElement("stoneshop"); // второй эл
            XAttribute bs_name_attr2    = new XAttribute("name", "ametrine");
            XElement   bs_country_elem2 = new XElement("country", "Bolivia");
            XElement   bs_auc_elem2     = new XElement("auction", "yes");

            stoneshop2.Add(bs_name_attr2);          //заполняем аттрибутом и элем-ми
            stoneshop2.Add(bs_country_elem2);
            stoneshop2.Add(bs_auc_elem2);

            XElement root = new XElement("root");   //корневой элемент

            root.Add(stoneshop);
            root.Add(stoneshop2);
            xdoc.Add(root);
            xdoc.Save("linq.xml");                   //сохраняем в файл

            Console.WriteLine("Где найти Аметрин?"); //1-й запрос
            var items = xdoc.Element("root").Elements("stoneshop")
                        .Where(p => p.Attribute("name").Value == "ametrine")
                        .Select(p => p);

            foreach (var item in items)
            {
                Console.WriteLine(item.Element("country").Value);
            }
            Console.WriteLine("Какие камни представлены на аукционе?");//2-й запрос
            var coun = xdoc.Element("root").Elements("stoneshop")
                       .Where(p => p.Element("auction").Value == "yes")
                       .Select(p => p);

            foreach (var c in coun)
            {
                Console.WriteLine(c.Attribute("name").Value);
            }
        }
Ejemplo n.º 2
0
        public static string SetCars()
        {
            var req = HttpWebRequest.Create("http://localhost:8080/CARS");

            req.Method      = "POST";
            req.Credentials = CredentialCache.DefaultCredentials;

            MemoryStream     stream1 = new MemoryStream();
            List <Autotruck> car     = new List <Autotruck>();

            for (int i = 0; i < 10; i++)
            {
                car.Add(new Autotruck()
                {
                    Carbrand = "Модель" + i.ToString(), CarNumber = "Номер" + i.ToString(), Code = Guid.NewGuid(), Driver = "Водила" + i.ToString(), Id = Guid.NewGuid(), isUsed = true, Shipper = Guid.NewGuid(), TrailerNumber = "tr_num" + i.ToString()
                });
            }
            DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Autotruck[]), new DataContractJsonSerializerSettings
            {
                DateTimeFormat = new DateTimeFormat("yyyy-MM-dd'T'HH:mm:ss")
            });

            ser.WriteObject(stream1, car.ToArray());
            stream1.Position = 0;



            //StringReader sr = new StringReader("{ \"login\": \"user1\" , \"password\": \"user1\"}");
            byte[] ch  = new byte[stream1.Length];
            var    cnt = stream1.Read(ch, 0, (int)stream1.Length);

            req.ContentLength = stream1.Length;
            req.ContentType   = "application/json";
            var strem = req.GetRequestStream();

            strem.Write(ch, 0, (int)stream1.Length);
            //for (int i = 0; i < cnt; i++)
            //{
            //strem.WriteByte((byte)ch[i]);
            //}
            strem.Close();
            var resp = (HttpWebResponse)req.GetResponse();

            System.Console.WriteLine("<--------------------");
            System.Console.WriteLine("ContentType:");
            System.Console.WriteLine("              " + resp.ContentType);
            System.Console.WriteLine("ContentLength:{0}", resp.ContentLength);
            System.Console.WriteLine("");
            var res_str = resp.GetResponseStream();

            byte[] br = new byte[(int)resp.ContentLength];
            res_str.Read(br, 0, (int)resp.ContentLength);
            res_str.Close();


            var memstr = new MemoryStream();
            var rdr    = new StreamReader(memstr, Encoding.UTF8);

            memstr.Write(br, 0, br.Length);
            memstr.Position = 0;
            var ret = rdr.ReadToEnd();

            rdr.Close();
            memstr.Close();
            System.Console.WriteLine(ret);
            foreach (var VARIABLE in resp.Headers)
            {
                System.Console.WriteLine(VARIABLE);
            }
            for (int i = 0; i < resp.Headers.Count; ++i)
            {
                Console.WriteLine("\nHeader Name:{0}, Header value :{1}", resp.Headers.Keys[i], resp.Headers[i]);
                if (resp.Headers.Keys[i] == "Set-Cookie")
                {
                    var token = resp.Headers[i].Split('=');
                    resp.Close();
                    return(token[1]);
                }
            }

            System.Console.WriteLine("cookies");
            foreach (Cookie cookieValue in resp.Cookies)
            {
                System.Console.WriteLine(cookieValue.ToString());
            }
            resp.Close();
            return(string.Empty);
        }
        public void Do()
        {
            //int log_2 = ((x >> 23) & 255) - 128;
            //return;
            double   d     = 0x0404cb * 2 * Math.Pow(8 * (0x1b - 3), 2);
            DateTime start = DateTime.Now;

            for (int i = 0; i < 5; i++)
            {
                Block b1 = new Block(new BlockData[] { new BlockData()
                                                       {
                                                           message = "wiadomosc1 nr: " + i.ToString()
                                                       },
                                                       new BlockData()
                                                       {
                                                           message = "wiadomosc2 nr: " + i.ToString()
                                                       },
                                                       new BlockData()
                                                       {
                                                           message = "wiadomosc3 nr: " + i.ToString()
                                                       },
                                                       new BlockData()
                                                       {
                                                           message = "wiadomosc4 nr: " + i.ToString()
                                                       },
                                                       new BlockData()
                                                       {
                                                           message = "wiadomosc5 nr: " + i.ToString()
                                                       } });
                OpenLedger.Add(b1);
            }

            MemoryStream stream1           = new MemoryStream();
            DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(BlockChain));

            ser.WriteObject(stream1, OpenLedger);
            stream1.Position = 0;
            StreamReader sr = new StreamReader(stream1);

            Console.Write("JSON form of Person object: ");
            Console.WriteLine(sr.ReadToEnd());
            bool valed = OpenLedger.Validate();

            Console.WriteLine($"ledger is valid : { valed }");
            DateTime end = DateTime.Now;

            Console.WriteLine((end - start).TotalSeconds);
            Console.ReadKey();
            //return;
            var container = BootStrap.Components();

            using (var scope = container.BeginLifetimeScope())
            {
                //bindowanie
                ISimpleWorker worker = scope.Resolve <ISimpleWorker>();
                //container.Resolve<IServerLogger>();
                // robienie tasków
                Task task1 = new Task(() => worker.Do());
                //task1.Start();
                //task1.Wait();
            }
        }