public async Task InsertMaxAmountOfEntriesPerPageTest()
        {
            var bogus = new Bogus.Randomizer();

            using BufferSegment headerBufferSegment = new BufferSegment(Constants.PAGE_SIZE);
            var headerPage = HeaderPage.CreateHeaderPage(headerBufferSegment);

            using BufferSegment bufferSegment = new BufferSegment(Constants.PAGE_SIZE);
            PageHeader header = new PageHeader(1, PageType.Data);

            header.ToBuffer(bufferSegment.Span, 0);
            PageService pageService = new PageService(new InMemoryDiskService());
            DataService dataService = new DataService(new NopCompressionService(), pageService);

            for (int i = 0; i < 300; i++)
            {
                var address = await dataService.Insert("ABC");

                address.SlotId.ShouldBeGreaterThan((byte)0);
                address.PageId.ShouldBeGreaterThan((byte)0);

                if (i > 254)
                {
                    address.PageId.ShouldBeGreaterThan((uint)1);
                }

                var resObject = await dataService.Get <string>(address);

                resObject.ShouldBe("ABC");
            }
        }
Beispiel #2
0
        protected override void SetPicture(TagLib.File file, Tag tag)
        {
            TagLib.Ogg.File oggFile           = (TagLib.Ogg.File)file;
            GroupedComment  groupedCommentTag = (GroupedComment)tag;

            if (string.IsNullOrWhiteSpace(CoverFilePath))
            {
                return;
            }

            // Is there a way to get Ogg file header using TagLib#?
            PropertyInfo headerProp = oggFile.GetType().GetProperty("LastPageHeader", BindingFlags.Instance | BindingFlags.NonPublic);
            PageHeader   header     = (PageHeader)headerProp.GetValue(oggFile);

            // Add cover art to Vorbis Comment approved METADATA_BLOCK_PICTURE field.
            TagLib.Flac.Picture pic = new TagLib.Flac.Picture(new Picture(CoverFilePath))
            {
                Description = ""
            };
            ByteVector picData = pic.Render();

            XiphComment xiphComment = groupedCommentTag.GetComment(header.StreamSerialNumber);

            xiphComment.SetField("METADATA_BLOCK_PICTURE", Convert.ToBase64String(picData.Data));
        }
Beispiel #3
0
        public void InsertTest_Continuous()
        {
            var bogus = new Bogus.Randomizer();

            byte[] toInsert     = Encoding.UTF8.GetBytes("Hello World!");
            ushort insertLength = (ushort)toInsert.Length;

            using BufferSegment bufferSegment = new BufferSegment(Constants.PAGE_SIZE);
            PageHeader header = new PageHeader(1, PageType.Data);

            header.ToBuffer(bufferSegment.Span, 0);

            DataPage dataPage = new DataPage(bufferSegment);

            dataPage.IsFull.ShouldBeFalse();
            var ins = dataPage.Insert(insertLength, out var index);

            index.ShouldBe((byte)1);
            ins.Length.ShouldBe(insertLength);
            ins.WriteBytes(0, toInsert);
            dataPage.FreeContinuousBytes.ShouldBe((ushort)(Constants.MAX_USABLE_BYTES_IN_PAGE - insertLength));
            bufferSegment.Span.Slice(Constants.PAGE_HEADER_SIZE, insertLength).ToArray().ShouldBe(toInsert);

            ins = dataPage.Insert(insertLength, out index);
            index.ShouldBe((byte)2);
            ins.Length.ShouldBe(insertLength);
            ins.WriteBytes(0, toInsert);
            dataPage.FreeContinuousBytes.ShouldBe((ushort)(Constants.MAX_USABLE_BYTES_IN_PAGE - 4 - insertLength * 2));
            bufferSegment.Span.Slice(Constants.PAGE_HEADER_SIZE + insertLength, insertLength).ToArray().ShouldBe(toInsert);
        }
Beispiel #4
0
        public void GetBytesByIndexTest()
        {
            using BufferSegment bufferSegment = new BufferSegment(Constants.PAGE_SIZE);
            PageHeader header = new PageHeader(1, PageType.Data);

            header.ToBuffer(bufferSegment.Span, 0);
            DataPage dataPage = new DataPage(bufferSegment);

            dataPage.IsFull.ShouldBeFalse();

            for (int i = 0; i < 10; i++)
            {
                byte[] toInsert     = Encoding.UTF8.GetBytes($"Hello World {i + 1}");
                ushort insertLength = (ushort)toInsert.Length;
                dataPage.IsInsertPossible(insertLength).ShouldBeTrue();
                var ins = dataPage.Insert(insertLength, out var index);
                ins.WriteBytes(0, toInsert);
                dataPage.PageHeader.HighestSlotId.ShouldBe(index);
            }

            for (int i = 0; i < 10; i++)
            {
                var bytes = dataPage.GetDataByIndex((byte)(i + 1));
                var text  = Encoding.UTF8.GetString(bytes);
                text.ShouldBe($"Hello World {i+1}");
            }
        }
        public async Task SimpleInsertAndGetWithCheckpointTest()
        {
            var bogus = new Bogus.Randomizer();

            using BufferSegment headerBufferSegment = new BufferSegment(Constants.PAGE_SIZE);
            var headerPage = HeaderPage.CreateHeaderPage(headerBufferSegment);

            using BufferSegment bufferSegment = new BufferSegment(Constants.PAGE_SIZE);
            PageHeader header = new PageHeader(1, PageType.Data);

            header.ToBuffer(bufferSegment.Span, 0);
            PageService pageService = new PageService(new InMemoryDiskService());
            DataService dataService = new DataService(new NopCompressionService(), pageService);
            TestObject  testObject  = new TestObject();

            testObject.IntProp    = bogus.Int();
            testObject.StringProp = bogus.String2(1000);
            var address = await dataService.Insert(testObject);

            address.SlotId.ShouldBe((byte)1);
            address.PageId.ShouldBe((ushort)1);
            await pageService.CheckPoint();

            var obj = await dataService.Get <TestObject>(address);

            obj.ShouldNotBeNull();
            obj.ShouldBe(testObject);

            // there should be no second page
            var secondPage = await pageService.GetPage <BasePage>(2);

            secondPage.ShouldBeNull();
        }
Beispiel #6
0
        public async Task Init()
        {
            // create the first GAM page => only when new database
            var firstGamBuffer = await _diskService.GetBuffer(new ReadRequest(1));

            var header = PageHeader.FromBuffer(firstGamBuffer.BufferSegment.Span);

            if (header.PageId == 0)
            {
                // new database
                _globalAllocationMap = new GlobalAllocationMapPage(firstGamBuffer.BufferSegment, 1);

                var nextId  = _globalAllocationMap.AcquirePageId();
                var newInfo = await _diskService.GetBuffer(new ReadRequest(nextId));

                _allocationInformationPage = new AllocationInformationPage(newInfo.BufferSegment, nextId);
            }
            else
            {
                // existing database, search last GAM page in database
                if (header.NextPageId == 0)
                {
                    _globalAllocationMap = new GlobalAllocationMapPage(firstGamBuffer.BufferSegment, 1);
                }
                else
                {
                    while (header.NextPageId > 0)
                    {
                        var res = await _diskService.GetBuffer(new ReadRequest(header.NextPageId));

                        header = PageHeader.FromBuffer(res.BufferSegment.Span);
                    }
                }
            }
        }
Beispiel #7
0
        public void InsertTest_MaxCount()
        {
            var bogus = new Bogus.Randomizer();

            byte[] toInsert     = TestHelper.GenerateByteArray(4, 0x0F);
            ushort insertLength = (ushort)toInsert.Length;

            using BufferSegment bufferSegment = new BufferSegment(Constants.PAGE_SIZE);
            PageHeader header = new PageHeader(1, PageType.Data);

            header.ToBuffer(bufferSegment.Span, 0);

            DataPage dataPage = new DataPage(bufferSegment);

            dataPage.IsFull.ShouldBeFalse();
            byte index = 0;

            for (int i = 0; i < 255; i++)
            {
                var ins = dataPage.Insert(insertLength, out index);
                ins.WriteBytes(0, toInsert);
            }

            dataPage.IsInsertPossible(1).ShouldBe(false);
            Should.Throw <Exception>(() =>
            {
                dataPage.Insert(insertLength, out var index);
            });
            dataPage.Delete(100);
            dataPage.IsInsertPossible(1).ShouldBe(true);
            dataPage.Insert(insertLength, out index);
            index.ShouldBe((byte)100);
        }
Beispiel #8
0
        public async Task <int> CreatePageHeaderAsync(PageHeaderInputModel pageHeaderInputModel)
        {
            var pageHeaderImg = pageHeaderInputModel.Image;

            var pageHeaderForDb = new PageHeader
            {
                CreatedOn     = DateTime.UtcNow,
                PageIndicator = GlobalConstants.PageIndicatorPost,
                Title         = pageHeaderInputModel.MainTitle,
                SubTitle      = pageHeaderInputModel.SubTitle,
            };

            if (pageHeaderImg != null)
            {
                var folderName = GlobalConstants.PageHeadersFolderName;

                var cloudUrl = this.cloudinaryService.UploudPicture(pageHeaderImg, folderName);
                pageHeaderForDb.Image = new Image
                {
                    CloudUrl    = cloudUrl,
                    ContentType = pageHeaderImg.ContentType,
                    CreatedOn   = DateTime.UtcNow,
                    ImageByte   = pageHeaderImg.ImageByte,
                    ImagePath   = pageHeaderImg.ImagePath,
                    ImageTitle  = pageHeaderImg.ImageTitle,
                };
            }

            await this.pageHeaders.AddAsync(pageHeaderForDb);

            var savedChanges = await this.pageHeaders.SaveChangesAsync();

            return(pageHeaderForDb.Id);
        }
Beispiel #9
0
        // apply the style to an existing report
        public void Apply(C1Report rpt)
        {
            if (rpt == null)
            {
                return;
            }

            // default report font
            rpt.Font = Detail.Font;

            // report header
            ReportHeader.Apply(rpt.Sections.Header);

            // page header
            PageHeader.Apply(rpt.Sections.PageHeader);

            // group headers
            foreach (Group group in rpt.Groups)
            {
                GroupHeader.Apply(group.SectionHeader);
            }

            // detail
            Detail.Apply(rpt.Sections.Detail);

            // report footer
            PageFooter.Apply(rpt.Sections.PageFooter);
        }
        public void SizingIsCorrectly()
        {
            PageHeader pageHeader = (PageHeader)ControlsTestPage.Instance.FindName("StandardPageHeader");
            PageHeader pageHeaderWithoutDescriptions = (PageHeader)ControlsTestPage.Instance.FindName("HeaderWithoutDescription");

            Assert.IsTrue(pageHeader.ActualHeight > pageHeaderWithoutDescriptions.ActualHeight + 14);
        }
Beispiel #11
0
        public void Setup()
        {
            var           bogus = new Bogus.Randomizer();
            BufferSegment headerBufferSegment = new BufferSegment(Constants.PAGE_SIZE);
            var           headerPage          = HeaderPage.CreateHeaderPage(headerBufferSegment);
            BufferSegment bufferSegment       = new BufferSegment(Constants.PAGE_SIZE);
            PageHeader    header = new PageHeader(1, PageType.Data);

            header.ToBuffer(bufferSegment.Span, 0);
            File.Delete(@"C:\Neuer Ordner\test.db");
            PageService pageService = new PageService(FileDiskService.Create(new DatatentSettings()
            {
                InMemory = false, Path = @"C:\Neuer Ordner\test.db"
            }));

            _dataService = new DataService(new NopCompressionService(), pageService);

            _objects = new List <TestObject>(50);
            foreach (var i in Enumerable.Range(0, 50))
            {
                TestObject testObject = new TestObject();
                testObject.IntProp    = bogus.Int();
                testObject.StringProp = bogus.String2(1000);
                _objects.Add(testObject);
            }
        }
Beispiel #12
0
        public void GetMaxFreeSpace_End()
        {
            using BufferSegment bufferSegment = new BufferSegment(Constants.PAGE_SIZE);
            PageHeader header = new PageHeader(1, PageType.Data);

            header.ToBuffer(bufferSegment.Span, 0);
            DataPage dataPage = new DataPage(bufferSegment);

            dataPage.IsFull.ShouldBeFalse();

            byte[] toInsert     = TestHelper.GenerateByteArray(3000, 0x0F);
            ushort insertLength = (ushort)toInsert.Length;
            byte   index        = 0;

            var ins = dataPage.Insert(insertLength, out index);

            ins.WriteBytes(0, toInsert);
            ins = dataPage.Insert(insertLength, out index);
            ins.WriteBytes(0, toInsert);

            var freeSpace = dataPage.GetMaxContiguounesFreeSpace();

            freeSpace.ShouldBe((ushort)dataPage.FreeContinuousBytes);
            freeSpace.ShouldBe((ushort)(Constants.PAGE_SIZE - Constants.PAGE_HEADER_SIZE - 3000 - 3000 -
                                        2 * Constants.PAGE_DIRECTORY_ENTRY_SIZE));
        }
        public async Task LargeInsertTest()
        {
            var bogus = new Bogus.Randomizer();

            using BufferSegment headerBufferSegment = new BufferSegment(Constants.PAGE_SIZE);
            var headerPage = HeaderPage.CreateHeaderPage(headerBufferSegment);

            using BufferSegment bufferSegment = new BufferSegment(Constants.PAGE_SIZE);
            PageHeader header = new PageHeader(1, PageType.Data);

            header.ToBuffer(bufferSegment.Span, 0);
            PageService pageService = new PageService(new InMemoryDiskService());
            DataService dataService = new DataService(new NopCompressionService(), pageService);
            TestObject  testObject  = new TestObject();

            testObject.IntProp    = bogus.Int();
            testObject.StringProp = bogus.String2(1000);

            for (int i = 0; i < 10000; i++)
            {
                var address = await dataService.Insert(testObject);

                address.SlotId.ShouldBeGreaterThan((byte)0);
                address.PageId.ShouldBeGreaterThan((byte)0);

                if (i > 254)
                {
                    address.PageId.ShouldBeGreaterThan((uint)1);
                }

                var resObject = await dataService.Get <TestObject>(address);

                resObject.ShouldBe(testObject);
            }
        }
Beispiel #14
0
        public NullPage() : base()
        {
            PageHeader header = Header;

            header.PageType = PageType.Null;

            Header = header;
        }
Beispiel #15
0
        public CustomTouchActionPage()
        {
            AvaloniaXamlLoader.Load(this);
            _pageHeader = this.FindControl <PageHeader>("PageHeader");
            _menuDetail = this.FindControl <MenuDetailListItem>("Menu");

            Loc.LanguageUpdated += UpdateStrings;
        }
        public static void AddPagination(this HttpResponse response, int currentPage, int itemsPerPage, int totalItems, int totalPages)
        {
            var paginationHeader = new PageHeader(currentPage, itemsPerPage, totalItems, totalPages);

            response.Headers.Add("Pagination", JsonConvert.SerializeObject(paginationHeader));
            // CORS
            //response.Headers.Add("access-control-expose-headers", "Pagination");
        }
Beispiel #17
0
        public void GlobalSetup()
        {
            BufferSegment bufferSegment = new BufferSegment(Constants.PAGE_SIZE);
            PageHeader    header        = new PageHeader(1, PageType.Data);

            header.ToBuffer(bufferSegment.Span, 0);
            _dataPage = new DataPage(bufferSegment);
        }
Beispiel #18
0
        public FactoryResetPage()
        {
            AvaloniaXamlLoader.Load(this);

            _pageHeader  = this.FindControl <PageHeader>("PageHeader");
            _resetButton = this.FindControl <IconListItem>("FactoryReset");

            SPPMessageHandler.Instance.ResetResponse += InstanceOnResetResponse;
        }
        public static IPageHeader GetHeader(PageHeader header)
        {
            if (!headerMap.ContainsKey(header))
            {
                throw new Exception("Header not mapped!");
            }

            return(headerMap[header]);
        }
        public void comparisonTest()
        {
            PageHeader  header      = PageHeader.Instance;
            MattressPlp mattressPlp = MattressPlp.Instance;

            header.open();
            header.openMattressPlp();
            mattressPlp.addToCompare();
        }
        public static void MapHeader(PageHeader header, IPageHeader headerInterface)
        {
            if (headerMap.ContainsKey(header))
            {
                throw new Exception("This header is already mapped!");
            }

            headerMap.Add(header, headerInterface);
        }
Beispiel #22
0
        public bool IsApprenticeshipsTableVisible()
        {
            var aprenticeshipsAddedTabButtonSelector = "//a[text()='Apprenticeships added']";

            PageHeader.WaitForElementIsVisible();
            var tabs = Driver.FindElements(By.XPath(aprenticeshipsAddedTabButtonSelector));

            return(tabs.Count > 0);
        }
Beispiel #23
0
        void Build()
        {
            var app = App.Current;
            var vm  = ViewModel = app.MainViewModel;

            NavigationPage.SetHasNavigationBar(this, false);
            BackgroundColor = Colors.BgGray3.ToColor();

            Content = new Grid {
                RowSpacing     = 0,
                RowDefinitions = Rows.Define(
                    (PageRow.Header, Auto),
                    (PageRow.Body, Star)
                    ),

                Children =
                {
                    PageHeader.Create(PageMarginSize,                            nameof(vm.Title), nameof(vm.SubTitle))
                    .Row(PageRow.Header),

                    new ScrollView {
                        Content = new StackLayout {
                            Children =
                            {
                                new Button   {
                                    Text = nameof(RegistrationCodePage)
                                }.Style(FilledButton)
                                .FillExpandH().Margin(PageMarginSize)
                                .Bind(nameof(vm.ContinueToRegistrationCommand)),

                                new Button   {
                                    Text = nameof(NestedListPage)
                                }.Style(FilledButton)
                                .FillExpandH().Margin(PageMarginSize)
                                .Bind(nameof(vm.ContinueToNestedListCommand)),

                                new Label    {
                                }.FontSize(20).FormattedText(
                                    new Span {
                                    Text = "Built with "
                                },
                                    new Span {
                                    Style = Link
                                }
                                    .BindTap(nameof(vm.ContinueToCSharpForMarkupCommand))
                                    .Bind(nameof(vm.Title)),
                                    new Span {
                                    Text = " \U0001f60e"
                                }
                                    ).CenterH()
                            }
                        }
                    }.Row(PageRow.Body)
                }
            };
        }
 public ActionResult Edit([Bind(Include = "Id,Title,PageHeaderText,SelectedView")] PageHeader pageHeader)
 {
     if (ModelState.IsValid)
     {
         db.Entry(pageHeader).State = EntityState.Modified;
         db.SaveChanges();
         return(RedirectToAction("Index"));
     }
     return(View(pageHeader));
 }
        public SpatialTestPage()
        {
            AvaloniaXamlLoader.Load(this);

            _pageHeader = this.FindControl <PageHeader>("PageHeader");
            _arrow      = this.FindControl <Image>("Arrow");
            _details    = this.FindControl <TextBlock>("SpatialDetails");

            _spatialSensorManager.NewQuaternionReceived += OnNewQuaternionReceived;
        }
        public async Task <PageHeader> EditPageHeaderAsync(PageHeader header)
        {
            VerifyManagementPermission();

            var currentHeader = await _pageHeaderRepository.GetByIdAsync(header.Id);

            currentHeader.PageName = header.PageName?.Trim();

            return(await _pageHeaderRepository.UpdateSaveAsync(GetClaimId(ClaimType.UserId),
                                                               currentHeader));
        }
Beispiel #27
0
 internal void UpdateWithCurrentPageSections(Microsoft.ReportingServices.ReportRendering.PageSection header, Microsoft.ReportingServices.ReportRendering.PageSection footer)
 {
     if (header != null)
     {
         PageHeader.UpdatePageSection(header);
     }
     if (footer != null)
     {
         PageFooter.UpdatePageSection(footer);
     }
 }
 public bool IsDisplayed()
 {
     try
     {
         return(PageHeader.WaitRetry(_driver).Text.Contains("Send Form"));
     }
     catch (NoSuchElementException)
     {
         return(false);
     }
 }
Beispiel #29
0
        public void GlobalSetup()
        {
            BufferSegment bufferSegment = new BufferSegment(Constants.PAGE_SIZE);
            PageHeader    header        = new PageHeader(1, PageType.Data);

            header.ToBuffer(bufferSegment.Span, 0);
            _dataPage = new DataPage(bufferSegment);
            for (int i = 0; i < Size; i++)
            {
                _dataPage.Insert(15, out var index);
            }
        }
Beispiel #30
0
        public void DefragTest()
        {
            using BufferSegment bufferSegment = new BufferSegment(Constants.PAGE_SIZE);
            PageHeader header = new PageHeader(1, PageType.Data);

            header.ToBuffer(bufferSegment.Span, 0);
            DataPage dataPage = new DataPage(bufferSegment);

            dataPage.IsFull.ShouldBeFalse();

            byte index = 0;

            List <string> expectedData = new(Enumerable.Range(1, 20).Select(i => "H" + i));
            List <byte>   indexes      = new();

            for (int i = 1; i < 21; i++)
            {
                byte[] toInsert     = Encoding.UTF8.GetBytes($"H{i}");
                ushort insertLength = (ushort)toInsert.Length;
                if (!dataPage.IsInsertPossible(insertLength))
                {
                    continue;
                }
                var ins = dataPage.Insert(insertLength, out index);
                ins.WriteBytes(0, toInsert);
                indexes.Add(index);
                dataPage.PageHeader.HighestSlotId.ShouldBe(index);
            }
            expectedData.Remove("H" + 10);
            expectedData.Remove("H" + 11);
            expectedData.Remove("H" + 12);
            expectedData.Remove("H" + 18);
            indexes.Remove(10);
            indexes.Remove(11);
            indexes.Remove(12);
            indexes.Remove(18);
            dataPage.Delete(10);
            dataPage.Delete(11);
            dataPage.Delete(12);
            dataPage.Delete(18);

            dataPage.Defrag();

            List <string> currentData = new();

            foreach (var ind in indexes)
            {
                currentData.Add(Encoding.UTF8.GetString(dataPage.GetDataByIndex(ind)));
            }

            dataPage.PageHeader.UnalignedFreeBytes.ShouldBe((ushort)0);
            currentData.ShouldBe(expectedData, true);
        }
Beispiel #31
0
        PageHeader ReadPageHeader(long position)
        {
            // set the stream's position
            _stream.Seek(position, SeekOrigin.Begin);

            // header
            // NB: if the stream didn't have an EOS flag, this is the most likely spot for the EOF to be found...
            if (_stream.Read(_readBuffer, 0, 27) != 27) return null;

            // capture signature
            if (_readBuffer[0] != 0x4f || _readBuffer[1] != 0x67 || _readBuffer[2] != 0x67 || _readBuffer[3] != 0x53) return null;

            // check the stream version
            if (_readBuffer[4] != 0) return null;

            // start populating the header
            var hdr = new PageHeader();

            // bit flags
            hdr.Flags = (PageFlags)_readBuffer[5];

            // granulePosition
            hdr.GranulePosition = BitConverter.ToInt64(_readBuffer, 6);

            // stream serial
            hdr.StreamSerial = BitConverter.ToInt32(_readBuffer, 14);

            // sequence number
            hdr.SequenceNumber = BitConverter.ToInt32(_readBuffer, 18);

            // save off the CRC
            var crc = BitConverter.ToUInt32(_readBuffer, 22);

            // start calculating the CRC value for this page
            _crc.Reset();
            for (int i = 0; i < 22; i++)
            {
                _crc.Update(_readBuffer[i]);
            }
            _crc.Update(0);
            _crc.Update(0);
            _crc.Update(0);
            _crc.Update(0);
            _crc.Update(_readBuffer[26]);

            // figure out the length of the page
            var segCnt = (int)_readBuffer[26];
            if (_stream.Read(_readBuffer, 0, segCnt) != segCnt) return null;

            var packetSizes = new List<int>(segCnt);

            int size = 0, idx = 0;
            for (int i = 0; i < segCnt; i++)
            {
                var temp = _readBuffer[i];
                _crc.Update(temp);

                if (idx == packetSizes.Count) packetSizes.Add(0);
                packetSizes[idx] += temp;
                if (temp < 255)
                {
                    ++idx;
                    hdr.LastPacketContinues = false;
                }
                else
                {
                    hdr.LastPacketContinues = true;
                }

                size += temp;
            }
            hdr.PacketSizes = packetSizes.ToArray();
            hdr.DataOffset = position + 27 + segCnt;

            // now we have to go through every byte in the page
            if (_stream.Read(_readBuffer, 0, size) != size) return null;
            for (int i = 0; i < size; i++)
            {
                _crc.Update(_readBuffer[i]);
            }

            if (_crc.Test(crc))
            {
                _containerBits += 8 * (27 + segCnt);
                ++_pageCount;
                return hdr;
            }
            return null;
        }
        PageHeader ReadPageHeader(long position)
        {
            // set the stream's position
            _stream.Position = position;

            // header
            var hdrBuf = new byte[27];
            if (_stream.Read(hdrBuf, 0, hdrBuf.Length) != hdrBuf.Length) return null;

            // capture signature
            if (hdrBuf[0] != 0x4f || hdrBuf[1] != 0x67 || hdrBuf[2] != 0x67 || hdrBuf[3] != 0x53) return null;

            // check the stream version
            if (hdrBuf[4] != 0) return null;

            // start populating the header
            var hdr = new PageHeader();

            // bit flags
            hdr.Flags = (PageFlags)hdrBuf[5];

            // granulePosition
            hdr.GranulePosition = BitConverter.ToInt64(hdrBuf, 6);

            // stream serial
            hdr.StreamSerial = BitConverter.ToInt32(hdrBuf, 14);

            // sequence number
            hdr.SequenceNumber = BitConverter.ToInt32(hdrBuf, 18);

            // save off the CRC
            var crc = BitConverter.ToUInt32(hdrBuf, 22);

            // start calculating the CRC value for this page
            var testCRC = 0U;
            for (int i = 0; i < 22; i++)
            {
                UpdateCRC(hdrBuf[i], ref testCRC);
            }
            UpdateCRC(0, ref testCRC);
            UpdateCRC(0, ref testCRC);
            UpdateCRC(0, ref testCRC);
            UpdateCRC(0, ref testCRC);
            UpdateCRC(hdrBuf[26], ref testCRC);

            // figure out the length of the page
            var segCnt = (int)hdrBuf[26];
            var packetSizes = new int[segCnt];
            int size = 0, idx = 0;
            for (int i = 0; i < segCnt; i++)
            {
                var temp = _stream.ReadByte();
                UpdateCRC(temp, ref testCRC);

                packetSizes[idx] += temp;
                if (temp < 255)
                {
                    ++idx;
                    hdr.LastPacketContinues = false;
                }
                else
                {
                    hdr.LastPacketContinues = true;
                }

                size += temp;
            }
            if (hdr.LastPacketContinues) ++idx;
            if (idx < packetSizes.Length)
            {
                var temp = new int[idx];
                for (int i = 0; i < idx; i++)
                {
                    temp[i] = packetSizes[i];
                }
                packetSizes = temp;
            }
            hdr.PacketSizes = packetSizes;

            hdr.DataOffset = position + 27 + segCnt;

            // now we have to go through every byte in the page
            while (--size >= 0)
            {
                UpdateCRC(_stream.ReadByte(), ref testCRC);
            }

            if (testCRC == crc)
            {
                _containerBits += 8 * (27 + segCnt);
                ++_pageCount;
                return hdr;
            }
            return null;
        }
Beispiel #33
0
        bool AddPage(PageHeader hdr)
        {
            // get our packet reader (create one if we have to)
            PacketReader packetReader;
            if (!_packetReaders.TryGetValue(hdr.StreamSerial, out packetReader))
            {
                packetReader = new PacketReader(this, hdr.StreamSerial);
            }

            // save off the container bits
            packetReader.ContainerBits += _containerBits;
            _containerBits = 0;

            // get our flags prepped
            var isContinued = false;
            var isContinuation = (hdr.Flags & PageFlags.ContinuesPacket) == PageFlags.ContinuesPacket;
            var isEOS = false;
            var isResync = hdr.IsResync;

            // add all the packets, making sure to update flags as needed
            var dataOffset = hdr.DataOffset;
            var cnt = hdr.PacketSizes.Length;
            foreach (var size in hdr.PacketSizes)
            {
                var packet = new Packet(this, dataOffset, size)
                    {
                        PageGranulePosition = hdr.GranulePosition,
                        IsEndOfStream = isEOS,
                        PageSequenceNumber = hdr.SequenceNumber,
                        IsContinued = isContinued,
                        IsContinuation = isContinuation,
                        IsResync = isResync,
                    };
                packetReader.AddPacket(packet);

                // update the offset into the stream for each packet
                dataOffset += size;

                // only the first packet in a page can be a continuation or resync
                isContinuation = false;
                isResync = false;

                // only the last packet in a page can be continued or flagged end of stream
                if (--cnt == 1)
                {
                    isContinued = hdr.LastPacketContinues;
                    isEOS = (hdr.Flags & PageFlags.EndOfStream) == PageFlags.EndOfStream;
                }
            }

            // if the packet reader list doesn't include the serial in question, add it to the list and indicate a new stream to the caller
            if (!_packetReaders.ContainsKey(hdr.StreamSerial))
            {
                _packetReaders.Add(hdr.StreamSerial, packetReader);
                return true;
            }
            else
            {
                // otherwise, indicate an existing stream to the caller
                return false;
            }
        }