Ejemplo n.º 1
0
        public static void Main301()
        {
            Console.WriteLine("Start Main301");

            // ============ Типы структур и значения с труктур в объектном представлении ===========
            // Создадим типы записи и последовательности записей
            PType tp1 = new PTypeRecord(
                new NamedType("name", new PType(PTypeEnumeration.sstring)),
                new NamedType("age", new PType(PTypeEnumeration.integer)));
            PType tp2 = new PTypeSequence(tp1);

            // Создадим структурные значения этих типов в объектном представлении
            object val1 = new object[] { "Иванов", 22 };
            object val2 = new object[]
            {
                new object[] { "Иванов", 22 },
                new object[] { "Петров", 33 },
                new object[] { "Сидоров", 44 }
            };

            // Визуализация структур в объектном представлении
            Console.WriteLine(tp1.Interpret(val1));
            Console.WriteLine(tp2.Interpret(val2));

            // ============== Сериализация/Десериализация =============
            // Сериализация выполняет отображение структуры на поток символов (текстовая сериализация) или
            // поток байтов (бинарная сериализация). Десериализация выполняет обратное преобразование.
            Stream stream = new MemoryStream();
            // сериализация делается через текстовый райтер
            TextWriter tw = new StreamWriter(stream);

            TextFlow.Serialize(tw, val2, tp2);
            tw.Flush();
            // посмотрим что записалось
            stream.Position = 0L;
            TextReader tr  = new StreamReader(stream);
            string     sss = tr.ReadToEnd();

            Console.WriteLine("Накопилось в стриме: " + sss);

            // десериализаця делатеся через текстовый ридер
            stream.Position = 0L;
            object val = TextFlow.Deserialize(tr, tp2);

            // Теперь надо посмотреть что в объекте
            Console.WriteLine("После цикла сериализация/десериализация: " + tp2.Interpret(val));

            // Бинарная сериализация
            // bool - 1 байт
            // byte - 1 байт
            // int - 4 байта
            // long, double - 8 байтов
            // строка - набор байтов определяемый BinaryWriter.Write((string)s)
            // запись - подряд стоящие сериализации полей записи
            // последовательность - long длина последовательности, подряд стоящие развертки элементов
            //
            // Бинарная сериализация совместима с BinaryWriter и BinaryReader

            // выполняется точно также, как текстовая сериализация (пример сделаю позже)
        }
Ejemplo n.º 2
0
        //START_SOURCE_CODE
        public void Run()
        {
            Console.WriteLine("Start Task03_PolarDB");
            dbpath = System.IO.Path.GetTempPath();
            PType  tp   = new PType(PTypeEnumeration.sstring);
            PaCell cell = new PaCell(tp, dbpath + "test.pac", false);

            cell.Clear();
            cell.Fill("Привет из ячейки базы данных!");
            Console.WriteLine("Содержимое ячейки: {0}", cell.Root.Get());

            PType tp_rec = new PTypeRecord(
                new NamedType("имя", new PType(PTypeEnumeration.sstring)),
                new NamedType("возраст", new PType(PTypeEnumeration.integer)),
                new NamedType("мужчина", new PType(PTypeEnumeration.boolean)));
            object rec_value = new object[] { "Пупкин", 22, true };
            PaCell cell_rec  = new PaCell(tp_rec, dbpath + "test_rec.pac", false);

            cell_rec.Clear();
            cell_rec.Fill(rec_value);
            object from_rec = cell_rec.Root.Get();

            Console.WriteLine(tp_rec.Interpret(from_rec));

            PType  tp_seq    = new PTypeSequence(tp_rec);
            object seq_value = new object[]
            {
                new object[] { "Иванов", 24, true },
                new object[] { "Петрова", 18, false },
                new object[] { "Пупкин", 22, true }
            };
            PaCell cell_seq = new PaCell(tp_seq, dbpath + "test_seq.pac", false);

            cell_seq.Clear();
            cell_seq.Fill(seq_value);
            object from_seq = cell_seq.Root.Get();

            Console.WriteLine(tp_seq.Interpret(from_seq));

            cell_seq.Root.AppendElement(new object[] { "Сидоров", 23, true });
            Console.WriteLine(tp_seq.Interpret(cell_seq.Root.Get()));

            long v0 = cell_seq.Root.Count();
            var  v1 = cell_seq.Root.Element(2).Field(0).Get();
            var  v2 = cell_seq.Root.Element(3).Field(1).Get();

            Console.WriteLine($"{v0} {v1} {v2}");

            cell_seq.Root.Element(1).Field(1).Set(19);
            cell_seq.Root.Element(1).Field(2).Set(true);
            Console.WriteLine(tp_seq.Interpret(cell_seq.Root.Get()));
            cell_seq.Flush();
            cell_seq.Close();
            cell_rec.Flush();
            cell_rec.Close();
            cell.Flush();
            cell.Close();
        }
Ejemplo n.º 3
0
        static void Main201()
        {
            Console.WriteLine("Start Program201");
            // Определение поляровских типов
            PType tp_rec = new PTypeRecord(
                new NamedType("имя", new PType(PTypeEnumeration.sstring)),
                new NamedType("возраст", new PType(PTypeEnumeration.integer)),
                new NamedType("мужчина", new PType(PTypeEnumeration.boolean)));
            PType tp_seq = new PTypeSequence(tp_rec);
            // Задание поляровского объекта и его визуализация
            object seq_value = new object[]
            {
                new object[] { "Иванов", 24, true },
                new object[] { "Петрова", 18, false },
                new object[] { "Пупкин", 22, true }
            };

            Console.WriteLine(tp_seq.Interpret(seq_value));

            // Текстовая сериализация
            // Создадим поток байтов. Это мог бы быть файл, но сделали в памяти
            MemoryStream mstream = new MemoryStream();
            // Поработаем через текстовый интерфейс
            TextWriter tw = new StreamWriter(mstream);

            TextFlow.Serialize(tw, seq_value, tp_seq);
            tw.Flush();
            // Прочитаем то что записали
            TextReader tr = new StreamReader(mstream);

            mstream.Position = 0L;
            string instream = tr.ReadToEnd();

            Console.WriteLine($"======== instream={instream}");
            Console.WriteLine();

            // Теперь десериализуем
            object db = null;

            mstream.Position = 0L;
            db = TextFlow.Deserialize(tr, tp_seq);
            // проинтерпретируем объект и посмотрим
            Console.WriteLine(tp_seq.Interpret(db));
            Console.WriteLine();
        }
Ejemplo n.º 4
0
        public void TestSeqCell()
        {
            PType  tp_seq   = new PTypeSequence(new PType(PTypeEnumeration.integer));
            PaCell cell_seq = new PaCell(tp_seq, new MemoryStream(), false);

            cell_seq.Clear();
            cell_seq.Fill(new object[0]);
            cell_seq.Root.AppendElement(99);
            cell_seq.Root.AppendElement(98);
            cell_seq.Root.AppendElement(97);
            Assert.IsTrue(tp_seq.Interpret(cell_seq.Root.Get()) == "[99,98,97]");
        }
Ejemplo n.º 5
0
        public void TestMethod1()
        {
            // Проверка формирования комплексного типа
            PType seqtriplets = new PTypeSequence(
                new PTypeUnion(
                    new NamedType("empty", new PType(PTypeEnumeration.none)),
                    new NamedType("op",
                        new PTypeRecord(
                            new NamedType("subject", new PType(PTypeEnumeration.sstring)),
                            new NamedType("predicate", new PType(PTypeEnumeration.sstring)),
                            new NamedType("obj", new PType(PTypeEnumeration.sstring)))),
                    new NamedType("dp",
                        new PTypeRecord(
                            new NamedType("subject", new PType(PTypeEnumeration.sstring)),
                            new NamedType("predicate", new PType(PTypeEnumeration.sstring)),
                            new NamedType("data", new PType(PTypeEnumeration.sstring)),
                            new NamedType("lang", new PType(PTypeEnumeration.sstring))))));
            // Проверка конструирования объекта
            object[] testdb = new object[] {
                new object[] { 1, new object[] {"a", "b", "c"}},
                new object[] { 1, new object[] {"a1", "b1", "c1"}},
                new object[] { 2, new object[] {"da", "db", "dc", "lang"}}
            };
            // Проверка интерпретации объекта
            string result0 = "[op^{\"a\",\"b\",\"c\"},op^{\"a1\",\"b1\",\"c1\"},dp^{\"da\",\"db\",\"dc\",\"lang\"}]";
            string result = seqtriplets.Interpret(testdb);
            Assert.AreEqual(result, result0);

            string path = @"..\..\..\Databases\";
            // Создание ячейки плавающего формата
            string testpacfilename = path + "test.pac";
            if (System.IO.File.Exists(testpacfilename)) { System.IO.File.Delete(testpacfilename); }
            PaCell cell = new PaCell(seqtriplets, testpacfilename, false); // false - чтобы заполнять
            // Заполнение ячейки данными из объекта
            cell.Fill(testdb);
            // Проверка того, что имеется в ячейке
            var cell_pvalue = cell.Root.GetValue();
            Console.WriteLine(cell_pvalue.Type.Interpret(cell_pvalue.Value));
            string result2 = cell_pvalue.Type.Interpret(cell_pvalue.Value);
            Assert.AreEqual(result2, result0);
            cell.Close();
            System.IO.File.Delete(testpacfilename);
        }
Ejemplo n.º 6
0
        public static void Test()
        {
            PType tp_point = new PTypeRecord(
                new NamedType("x", new PType(PTypeEnumeration.real)),
                new NamedType("y", new PType(PTypeEnumeration.real)));
            PType tp_figure = new PTypeUnion(
                new NamedType("nothing", new PType(PTypeEnumeration.none)),
                new NamedType("point", tp_point),
                new NamedType("polygon", new PTypeSequence(tp_point)),
                new NamedType("circle", new PTypeRecord(
                                  new NamedType("center", tp_point),
                                  new NamedType("radius", new PType(PTypeEnumeration.real)))));
            PType  tp_sequ = new PTypeSequence(tp_figure);
            object sequ    = new object[]
            {
                new object[] { 1, new object[] { 3.5, 7.8 } },
                new object[] { 2, new object[] {
                                   new object[] { 0.0, 0.0 }, new object[] { 1.0, 0.0 }, new object[] { 1.0, 1.0 }, new object[] { 0.0, 1.0 }
                               } },
                new object[] { 3, new object[] { new object[] { 5.0, 5.0 }, 4.99 } }
            };

            // Выполним текстовую сериализацию
            TextFlow.Serialize(Console.Out, sequ, tp_sequ);
            Console.WriteLine();
            // Создадим Stream, сделаем бинарную сериализацию, будем считать, что это файл
            Stream stream = new MemoryStream();

            ByteFlow.Serialize(new BinaryWriter(stream), sequ, tp_sequ);
            // Десериализуем стрим (бинарный файл)
            stream.Position = 0L;
            object sequ_1 = ByteFlow.Deserialize(new BinaryReader(stream), tp_sequ);

            // Проверим полученное значение
            Console.WriteLine(tp_sequ.Interpret(sequ_1));
        }
Ejemplo n.º 7
0
        public static void Main(string[] args)
        {
            Console.WriteLine("Start PagedFileStore");
            string       path         = "";
            string       fname        = path + "fob.bin";
            bool         fob_exists   = File.Exists(fname);
            FileStream   fs           = new FileStream(fname, FileMode.OpenOrCreate, FileAccess.ReadWrite);
            FileOfBlocks fob          = new FileOfBlocks(fs);
            Stream       first_stream = fob.GetFirstAsStream();

            if (!fob_exists)
            {
                PagedStream.InitPagedStreamHead(first_stream, 8L, 0, PagedStream.HEAD_SIZE);
                fob.Flush();
            }

            PagedStream ps = new PagedStream(fob, fob.GetFirstAsStream(), 8L);

            //ps.Clear();
            Console.WriteLine("stream length={0} position={1}", ps.Length, ps.Position);

            bool towrite = false;
            bool toread  = false;

            if (towrite)
            {
                DirectoryInfo dirin = new DirectoryInfo(@"D:\Home\FactographDatabases\testdir");
                BinaryWriter  bw    = new BinaryWriter(ps);
                ps.Position = 0L;
                foreach (FileInfo f in dirin.GetFiles())
                {
                    PaCell.SetPO(new PolarDB.PType(PolarDB.PTypeEnumeration.sstring), bw, f.Name);
                    Stream stream = f.OpenRead();
                    PaCell.SetPO(new PolarDB.PType(PolarDB.PTypeEnumeration.longinteger), bw, stream.Length);
                    stream.CopyTo(ps);
                    break;
                }
                ps.Flush();
            }
            else if (toread)
            {
                string       dirout = @"D:\Home\FactographDatabases\testout\";
                BinaryReader br     = new BinaryReader(ps);
                ps.Position = 0L;
                for (;;)
                {
                    if (ps.Position >= ps.Length)
                    {
                        break;
                    }
                    string     name       = (string)PolarDB.PaCell.GetPO(new PolarDB.PType(PolarDB.PTypeEnumeration.sstring), br);
                    FileStream stream_out = new FileStream(dirout + name, FileMode.CreateNew, FileAccess.Write);
                    byte[]     buff       = new byte[1000];
                    long       len        = (long)PolarDB.PaCell.GetPO(new PolarDB.PType(PolarDB.PTypeEnumeration.longinteger), br);
                    while (len > 0)
                    {
                        int count = (int)System.Math.Min((long)buff.Length, len);
                        int n     = ps.Read(buff, 0, count);
                        if (n != count)
                        {
                            throw new Exception("Err: 2898782349");
                        }
                        stream_out.Write(buff, 0, count);
                        len -= count;
                    }
                    stream_out.Flush();
                    stream_out.Dispose();
                }
            }
            bool tomake = false;

            if (tomake)
            {
                long cell_shift = ps.Length;
                Console.WriteLine("начало ячейки: {0}", cell_shift);
                PagedStream.InitPagedStreamHead(ps, cell_shift, 0L, -1L);
                PagedStream ps_cell = new PagedStream(fob, ps, cell_shift);
                PType       tp      = new PTypeSequence(new PType(PTypeEnumeration.integer));
                PaCell      cell    = new PaCell(tp, ps_cell, false);
                cell.Fill(new object[] { 111, 222, 333, 444, 555, 666, 777, 888, 999 });
                object ob = cell.Root.Get();
                Console.WriteLine("ob={0}", tp.Interpret(ob));
            }
            bool toadd = true;

            if (toadd)
            {
                long        cell_shift = 640;
                PagedStream ps_cell    = new PagedStream(fob, ps, cell_shift);
                PType       tp         = new PTypeSequence(new PType(PTypeEnumeration.integer));
                PaCell      cell       = new PaCell(tp, ps_cell, false);
                for (int i = 0; i < 1000000; i++)
                {
                    cell.Root.AppendElement(99999);
                }
                cell.Flush();

                Console.WriteLine("n elements={0}", cell.Root.Count());
            }
            bool tolook = false;

            if (tolook)
            {
                long        cell_shift = 640;
                PagedStream ps_cell    = new PagedStream(fob, ps, cell_shift);
                PType       tp         = new PTypeSequence(new PType(PTypeEnumeration.integer));
                PaCell      cell       = new PaCell(tp, ps_cell, false);
                object      ob         = cell.Root.Get();
                Console.WriteLine("ob={0}", tp.Interpret(ob));
            }
        }
Ejemplo n.º 8
0
        public static void Demo101()
        {
            Console.WriteLine("Start Demo101");
            // === Демонстрация базовых действий со структурами ===
            // Создаем тип персоны
            PType tp_person = new PTypeRecord(
                new NamedType("id", new PType(PTypeEnumeration.integer)),
                new NamedType("name", new PType(PTypeEnumeration.sstring)),
                new NamedType("age", new PType(PTypeEnumeration.integer)));
            // делаем персону в объектном представлении
            object ivanov = new object[] { 7001, "Иванов", 20 };

            // интерпретируем объект в контексте типа
            Console.WriteLine(tp_person.Interpret(ivanov, true));
            // то же, но без имен полей
            Console.WriteLine(tp_person.Interpret(ivanov));
            Console.WriteLine();

            // Создадим поток байтов. Это мог бы быть файл:
            MemoryStream mstream = new MemoryStream();
            // Поработаем через текстовый интерфейс
            TextWriter tw = new StreamWriter(mstream);

            TextFlow.Serialize(tw, ivanov, tp_person);
            tw.Flush();
            // Прочитаем то что записали
            TextReader tr = new StreamReader(mstream);

            mstream.Position = 0L;
            string instream = tr.ReadToEnd();

            Console.WriteLine($"======== instream={instream}");
            Console.WriteLine();

            // Теперь десериализуем
            ivanov           = null;
            mstream.Position = 0L;
            ivanov           = TextFlow.Deserialize(tr, tp_person);
            // проинтерпретируем объект и посмотрим
            Console.WriteLine(tp_person.Interpret(ivanov));
            Console.WriteLine();

            // ===== Последовательности =====
            // Создаем тип последовательности персон
            PType tp_persons = new PTypeSequence(tp_person);
            // Сделаем генератор персон
            Random rnd = new Random();
            Func <int, IEnumerable <object> > GenPers = nper => Enumerable.Range(0, nper)
                                                        .Select(i => new object[] { i, "Иванов_" + i, rnd.Next(130) });

            // Сгенерируем пробу и проинтерпретируем
            object sequobj = GenPers(20).ToArray();

            Console.WriteLine(tp_persons.Interpret(sequobj));
            Console.WriteLine();

            // Чем плохо такое решение? Тем, что весь большой объект (последовательность записей) разворачивается в ОЗУ
            // Более экономным, как правило, является использование последовательностей

            string dbpath     = @"D:/Home/data/GetStarted/";
            Stream filestream = new FileStream(dbpath + "db0.bin", FileMode.OpenOrCreate, FileAccess.ReadWrite);
            UniversalSequenceBase usequence = new UniversalSequenceBase(tp_person, filestream);

            // Последовательность можно очистить, в нее можно добавлять элементы, в конце добавлений нужно сбросить буфер
            int npersons = 1_000_000;

            usequence.Clear();
            foreach (object record in GenPers(npersons))
            {
                usequence.AppendElement(record);
            }
            usequence.Flush();

            // Теперь можно сканировать последовательность
            int totalages = 0;

            usequence.Scan((off, ob) => { totalages += (int)((object[])ob)[2]; return(true); });
            Console.WriteLine($"total ages = {totalages}");

            //// Можно прочитать i-ый элемент
            //int ind = npersons * 2 / 3;
            //object ores = usequence.GetByIndex(ind);
            //Console.WriteLine($"element={tp_person.Interpret(ores)}");
            //// Но нет - облом: Размер элемента не фиксирован (есть строка), к таким элементам по индексу обращаться не надо
        }