├── .gitattributes ├── .gitignore ├── LICENSE.md ├── OneSTools.BracketsFile.Tests ├── BracketsFileParserTests.cs ├── OneSTools.BracketsFile.Tests.csproj └── StreamReaderExtensions.cs ├── OneSTools.BracketsFile.sln ├── OneSTools.BracketsFile ├── BracketsListReader.cs ├── BracketsNode.cs ├── BracketsParser.cs ├── OneSTools.BracketsFile.csproj └── StreamReaderExtensions.cs └── README.md /.gitattributes: -------------------------------------------------------------------------------- 1 | ############################################################################### 2 | # Set default behavior to automatically normalize line endings. 3 | ############################################################################### 4 | * text=auto 5 | 6 | ############################################################################### 7 | # Set default behavior for command prompt diff. 8 | # 9 | # This is need for earlier builds of msysgit that does not have it on by 10 | # default for csharp files. 11 | # Note: This is only used by command line 12 | ############################################################################### 13 | #*.cs diff=csharp 14 | 15 | ############################################################################### 16 | # Set the merge driver for project and solution files 17 | # 18 | # Merging from the command prompt will add diff markers to the files if there 19 | # are conflicts (Merging from VS is not affected by the settings below, in VS 20 | # the diff markers are never inserted). Diff markers may cause the following 21 | # file extensions to fail to load in VS. An alternative would be to treat 22 | # these files as binary and thus will always conflict and require user 23 | # intervention with every merge. To do so, just uncomment the entries below 24 | ############################################################################### 25 | #*.sln merge=binary 26 | #*.csproj merge=binary 27 | #*.vbproj merge=binary 28 | #*.vcxproj merge=binary 29 | #*.vcproj merge=binary 30 | #*.dbproj merge=binary 31 | #*.fsproj merge=binary 32 | #*.lsproj merge=binary 33 | #*.wixproj merge=binary 34 | #*.modelproj merge=binary 35 | #*.sqlproj merge=binary 36 | #*.wwaproj merge=binary 37 | 38 | ############################################################################### 39 | # behavior for image files 40 | # 41 | # image files are treated as binary by default. 42 | ############################################################################### 43 | #*.jpg binary 44 | #*.png binary 45 | #*.gif binary 46 | 47 | ############################################################################### 48 | # diff behavior for common document formats 49 | # 50 | # Convert binary document formats to text before diffing them. This feature 51 | # is only available from the command line. Turn it on by uncommenting the 52 | # entries below. 53 | ############################################################################### 54 | #*.doc diff=astextplain 55 | #*.DOC diff=astextplain 56 | #*.docx diff=astextplain 57 | #*.DOCX diff=astextplain 58 | #*.dot diff=astextplain 59 | #*.DOT diff=astextplain 60 | #*.pdf diff=astextplain 61 | #*.PDF diff=astextplain 62 | #*.rtf diff=astextplain 63 | #*.RTF diff=astextplain 64 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.rsuser 8 | *.suo 9 | *.user 10 | *.userosscache 11 | *.sln.docstates 12 | 13 | # User-specific files (MonoDevelop/Xamarin Studio) 14 | *.userprefs 15 | 16 | # Build results 17 | [Dd]ebug/ 18 | [Dd]ebugPublic/ 19 | [Rr]elease/ 20 | [Rr]eleases/ 21 | x64/ 22 | x86/ 23 | [Aa][Rr][Mm]/ 24 | [Aa][Rr][Mm]64/ 25 | bld/ 26 | [Bb]in/ 27 | [Oo]bj/ 28 | [Ll]og/ 29 | 30 | # Visual Studio 2015/2017 cache/options directory 31 | .vs/ 32 | # Uncomment if you have tasks that create the project's static files in wwwroot 33 | #wwwroot/ 34 | 35 | # Visual Studio 2017 auto generated files 36 | Generated\ Files/ 37 | 38 | # MSTest test Results 39 | [Tt]est[Rr]esult*/ 40 | [Bb]uild[Ll]og.* 41 | 42 | # NUNIT 43 | *.VisualState.xml 44 | TestResult.xml 45 | 46 | # Build Results of an ATL Project 47 | [Dd]ebugPS/ 48 | [Rr]eleasePS/ 49 | dlldata.c 50 | 51 | # Benchmark Results 52 | BenchmarkDotNet.Artifacts/ 53 | 54 | # .NET Core 55 | project.lock.json 56 | project.fragment.lock.json 57 | artifacts/ 58 | 59 | # StyleCop 60 | StyleCopReport.xml 61 | 62 | # Files built by Visual Studio 63 | *_i.c 64 | *_p.c 65 | *_h.h 66 | *.ilk 67 | *.meta 68 | *.obj 69 | *.iobj 70 | *.pch 71 | *.pdb 72 | *.ipdb 73 | *.pgc 74 | *.pgd 75 | *.rsp 76 | *.sbr 77 | *.tlb 78 | *.tli 79 | *.tlh 80 | *.tmp 81 | *.tmp_proj 82 | *_wpftmp.csproj 83 | *.log 84 | *.vspscc 85 | *.vssscc 86 | .builds 87 | *.pidb 88 | *.svclog 89 | *.scc 90 | 91 | # Chutzpah Test files 92 | _Chutzpah* 93 | 94 | # Visual C++ cache files 95 | ipch/ 96 | *.aps 97 | *.ncb 98 | *.opendb 99 | *.opensdf 100 | *.sdf 101 | *.cachefile 102 | *.VC.db 103 | *.VC.VC.opendb 104 | 105 | # Visual Studio profiler 106 | *.psess 107 | *.vsp 108 | *.vspx 109 | *.sap 110 | 111 | # Visual Studio Trace Files 112 | *.e2e 113 | 114 | # TFS 2012 Local Workspace 115 | $tf/ 116 | 117 | # Guidance Automation Toolkit 118 | *.gpState 119 | 120 | # ReSharper is a .NET coding add-in 121 | _ReSharper*/ 122 | *.[Rr]e[Ss]harper 123 | *.DotSettings.user 124 | 125 | # JustCode is a .NET coding add-in 126 | .JustCode 127 | 128 | # TeamCity is a build add-in 129 | _TeamCity* 130 | 131 | # DotCover is a Code Coverage Tool 132 | *.dotCover 133 | 134 | # AxoCover is a Code Coverage Tool 135 | .axoCover/* 136 | !.axoCover/settings.json 137 | 138 | # Visual Studio code coverage results 139 | *.coverage 140 | *.coveragexml 141 | 142 | # NCrunch 143 | _NCrunch_* 144 | .*crunch*.local.xml 145 | nCrunchTemp_* 146 | 147 | # MightyMoose 148 | *.mm.* 149 | AutoTest.Net/ 150 | 151 | # Web workbench (sass) 152 | .sass-cache/ 153 | 154 | # Installshield output folder 155 | [Ee]xpress/ 156 | 157 | # DocProject is a documentation generator add-in 158 | DocProject/buildhelp/ 159 | DocProject/Help/*.HxT 160 | DocProject/Help/*.HxC 161 | DocProject/Help/*.hhc 162 | DocProject/Help/*.hhk 163 | DocProject/Help/*.hhp 164 | DocProject/Help/Html2 165 | DocProject/Help/html 166 | 167 | # Click-Once directory 168 | publish/ 169 | 170 | # Publish Web Output 171 | *.[Pp]ublish.xml 172 | *.azurePubxml 173 | # Note: Comment the next line if you want to checkin your web deploy settings, 174 | # but database connection strings (with potential passwords) will be unencrypted 175 | *.pubxml 176 | *.publishproj 177 | 178 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 179 | # checkin your Azure Web App publish settings, but sensitive information contained 180 | # in these scripts will be unencrypted 181 | PublishScripts/ 182 | 183 | # NuGet Packages 184 | *.nupkg 185 | # The packages folder can be ignored because of Package Restore 186 | **/[Pp]ackages/* 187 | # except build/, which is used as an MSBuild target. 188 | !**/[Pp]ackages/build/ 189 | # Uncomment if necessary however generally it will be regenerated when needed 190 | #!**/[Pp]ackages/repositories.config 191 | # NuGet v3's project.json files produces more ignorable files 192 | *.nuget.props 193 | *.nuget.targets 194 | 195 | # Microsoft Azure Build Output 196 | csx/ 197 | *.build.csdef 198 | 199 | # Microsoft Azure Emulator 200 | ecf/ 201 | rcf/ 202 | 203 | # Windows Store app package directories and files 204 | AppPackages/ 205 | BundleArtifacts/ 206 | Package.StoreAssociation.xml 207 | _pkginfo.txt 208 | *.appx 209 | 210 | # Visual Studio cache files 211 | # files ending in .cache can be ignored 212 | *.[Cc]ache 213 | # but keep track of directories ending in .cache 214 | !?*.[Cc]ache/ 215 | 216 | # Others 217 | ClientBin/ 218 | ~$* 219 | *~ 220 | *.dbmdl 221 | *.dbproj.schemaview 222 | *.jfm 223 | *.pfx 224 | *.publishsettings 225 | orleans.codegen.cs 226 | 227 | # Including strong name files can present a security risk 228 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 229 | #*.snk 230 | 231 | # Since there are multiple workflows, uncomment next line to ignore bower_components 232 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 233 | #bower_components/ 234 | 235 | # RIA/Silverlight projects 236 | Generated_Code/ 237 | 238 | # Backup & report files from converting an old project file 239 | # to a newer Visual Studio version. Backup files are not needed, 240 | # because we have git ;-) 241 | _UpgradeReport_Files/ 242 | Backup*/ 243 | UpgradeLog*.XML 244 | UpgradeLog*.htm 245 | ServiceFabricBackup/ 246 | *.rptproj.bak 247 | 248 | # SQL Server files 249 | *.mdf 250 | *.ldf 251 | *.ndf 252 | 253 | # Business Intelligence projects 254 | *.rdl.data 255 | *.bim.layout 256 | *.bim_*.settings 257 | *.rptproj.rsuser 258 | *- Backup*.rdl 259 | 260 | # Microsoft Fakes 261 | FakesAssemblies/ 262 | 263 | # GhostDoc plugin setting file 264 | *.GhostDoc.xml 265 | 266 | # Node.js Tools for Visual Studio 267 | .ntvs_analysis.dat 268 | node_modules/ 269 | 270 | # Visual Studio 6 build log 271 | *.plg 272 | 273 | # Visual Studio 6 workspace options file 274 | *.opt 275 | 276 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 277 | *.vbw 278 | 279 | # Visual Studio LightSwitch build output 280 | **/*.HTMLClient/GeneratedArtifacts 281 | **/*.DesktopClient/GeneratedArtifacts 282 | **/*.DesktopClient/ModelManifest.xml 283 | **/*.Server/GeneratedArtifacts 284 | **/*.Server/ModelManifest.xml 285 | _Pvt_Extensions 286 | 287 | # Paket dependency manager 288 | .paket/paket.exe 289 | paket-files/ 290 | 291 | # FAKE - F# Make 292 | .fake/ 293 | 294 | # JetBrains Rider 295 | .idea/ 296 | *.sln.iml 297 | 298 | # CodeRush personal settings 299 | .cr/personal 300 | 301 | # Python Tools for Visual Studio (PTVS) 302 | __pycache__/ 303 | *.pyc 304 | 305 | # Cake - Uncomment if you are using it 306 | # tools/** 307 | # !tools/packages.config 308 | 309 | # Tabs Studio 310 | *.tss 311 | 312 | # Telerik's JustMock configuration file 313 | *.jmconfig 314 | 315 | # BizTalk build output 316 | *.btp.cs 317 | *.btm.cs 318 | *.odx.cs 319 | *.xsd.cs 320 | 321 | # OpenCover UI analysis results 322 | OpenCover/ 323 | 324 | # Azure Stream Analytics local run output 325 | ASALocalRun/ 326 | 327 | # MSBuild Binary and Structured Log 328 | *.binlog 329 | 330 | # NVidia Nsight GPU debugger configuration file 331 | *.nvuser 332 | 333 | # MFractors (Xamarin productivity tool) working folder 334 | .mfractor/ 335 | 336 | # Local History for Visual Studio 337 | .localhistory/ 338 | 339 | # BeatPulse healthcheck temp database 340 | healthchecksdb -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2019 Akpaev Evgeniy 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. -------------------------------------------------------------------------------- /OneSTools.BracketsFile.Tests/BracketsFileParserTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Xunit; 3 | using OneSTools.BracketsFile; 4 | using System.Text; 5 | using System.IO; 6 | using System.Collections.Generic; 7 | using System.Diagnostics; 8 | 9 | namespace OneSTools.BracketsFile.Tests 10 | { 11 | public class BracketsFileParserTests 12 | { 13 | [Fact] 14 | public void ParseBlock1Test() 15 | { 16 | // Arrange 17 | var data = "{20201005114853,U,\n" + 18 | "{243b06bad83e0,7b3156},71,36,1,13732,11,I,\"\",55,\n" + 19 | "{\"R\",490:bace0cc47a56444311eaedd56d0dbdf8},\"Отчет производства за \"\",смену Уни00023710 от 03.09.2020 14:05:56\",1,1,0,1101,0,\n" + 20 | "{0}" + 21 | "}"; 22 | 23 | // Act 24 | var parsedData = BracketsParser.ParseBlock(data); 25 | 26 | // Assert 27 | Assert.Equal(19, parsedData.Count); 28 | Assert.Equal("20201005114853", (string)parsedData[0]); 29 | Assert.Equal("U", (string)parsedData[1]); 30 | Assert.False(parsedData[2].IsValueNode); 31 | Assert.Equal("243b06bad83e0", (string)parsedData[2].Nodes[0]); 32 | Assert.Equal("7b3156", (string)parsedData[2].Nodes[1]); 33 | Assert.Equal(71, (int)parsedData[3]); 34 | Assert.Equal(36, (int)parsedData[4]); 35 | Assert.Equal(1, (int)parsedData[5]); 36 | Assert.Equal(13732, (int)parsedData[6]); 37 | Assert.Equal(11, (int)parsedData[7]); 38 | Assert.Equal("I", (string)parsedData[8]); 39 | Assert.Equal("", (string)parsedData[9]); 40 | Assert.Equal(55, (int)parsedData[10]); 41 | Assert.False(parsedData[11].IsValueNode); 42 | Assert.Equal("R", (string)parsedData[11].Nodes[0]); 43 | Assert.Equal("490:bace0cc47a56444311eaedd56d0dbdf8", (string)parsedData[11].Nodes[1]); 44 | Assert.Equal("Отчет производства за \"\",смену Уни00023710 от 03.09.2020 14:05:56", (string)parsedData[12]); 45 | Assert.Equal(1, (int)parsedData[13]); 46 | Assert.Equal(1, (int)parsedData[14]); 47 | Assert.Equal(0, (int)parsedData[15]); 48 | Assert.Equal(1101, (int)parsedData[16]); 49 | Assert.Equal(0, (int)parsedData[17]); 50 | Assert.False(parsedData[18].IsValueNode); 51 | Assert.Equal(0, (int)parsedData[18].Nodes[0]); 52 | } 53 | 54 | [Fact] 55 | public void ParseBlock2Test() 56 | { 57 | // Arrange 58 | var data = "{20201005085729,U,\n" + 59 | "{0,0},75,2,5,15446,1,I,\"\",0,\n" + 60 | "{\"P\",\n" + 61 | "{2," + 62 | "{\"S\",\"исрв\"}\n" + 63 | "}\n" + 64 | "},\"\",1,1,0,1137,0,\n" + 65 | "{0}" + 66 | "}"; 67 | 68 | // Act 69 | var parsedData = BracketsParser.ParseBlock(data); 70 | 71 | // Assert 72 | Assert.Equal(19, parsedData.Count); 73 | Assert.Equal("20201005085729", (string)parsedData[0]); 74 | Assert.Equal("U", (string)parsedData[1]); 75 | Assert.False(parsedData[2].IsValueNode); 76 | Assert.Equal("0", (string)parsedData[2].Nodes[0]); 77 | Assert.Equal("0", (string)parsedData[2].Nodes[1]); 78 | Assert.Equal(75, (int)parsedData[3]); 79 | Assert.Equal(2, (int)parsedData[4]); 80 | Assert.Equal(5, (int)parsedData[5]); 81 | Assert.Equal(15446, (int)parsedData[6]); 82 | Assert.Equal(1, (int)parsedData[7]); 83 | Assert.Equal("I", (string)parsedData[8]); 84 | Assert.Equal("", (string)parsedData[9]); 85 | Assert.Equal(0, (int)parsedData[10]); 86 | Assert.False(parsedData[11].IsValueNode); 87 | Assert.Equal("P", (string)parsedData[11].Nodes[0]); 88 | Assert.False(parsedData[11][1].IsValueNode); 89 | Assert.Equal(2, (int)parsedData[11][1][0]); 90 | Assert.False(parsedData[11][1][1].IsValueNode); 91 | Assert.Equal("S", (string)parsedData[11][1][1][0]); 92 | Assert.Equal("исрв", (string)parsedData[11][1][1][1]); 93 | Assert.Equal("", (string)parsedData[12]); 94 | Assert.Equal(1, (int)parsedData[13]); 95 | Assert.Equal(1, (int)parsedData[14]); 96 | Assert.Equal(0, (int)parsedData[15]); 97 | Assert.Equal(1137, (int)parsedData[16]); 98 | Assert.Equal(0, (int)parsedData[17]); 99 | Assert.False(parsedData[18].IsValueNode); 100 | Assert.Equal(0, (int)parsedData[18].Nodes[0]); 101 | } 102 | 103 | [Fact] 104 | public void ParseBlock3Test() 105 | { 106 | // Arrange 107 | var data = "{1,071523a4-516f-4fce-ba4b-0d11ab7a1893,\"\",1}"; 108 | 109 | // Act 110 | var parsedData = BracketsParser.ParseBlock(data); 111 | 112 | // Assert 113 | Assert.Equal(4, parsedData.Count); 114 | Assert.Equal(1, (int)parsedData[0]); 115 | Assert.True("071523a4-516f-4fce-ba4b-0d11ab7a1893".Equals((string)parsedData[1])); 116 | Assert.True(string.Empty == (string)parsedData[2]); 117 | Assert.Equal(1, (int)parsedData[3]); 118 | } 119 | 120 | [Fact] 121 | public void ParseBlock4Test() 122 | { 123 | // Arrange 124 | var value = @"{{1234,N,1234N,""123"",{0},{0,0},{""U""},""Hello, symbol is '{'"",""Symbol is '}'"",""%Symbol is """"}"""""",""symbol is ','"",""2 symbol is ','""},""}"","","",""""}"; 125 | 126 | // Act 127 | var block = BracketsParser.ParseBlock(value); 128 | 129 | // Assert 130 | Assert.Equal(4, block.Count); 131 | } 132 | 133 | [Fact] 134 | public void GetNodeEndIndexTest() 135 | { 136 | // Arrange 137 | var strBuilder = new StringBuilder(@"{3,""WSConnection"",1},"); 138 | 139 | // Act 140 | var index = BracketsParser.GetNodeEndIndex(strBuilder, 0); 141 | 142 | // Assert 143 | Assert.Equal(19, index); 144 | } 145 | 146 | [Fact] 147 | public void BracketsListReaderTest() 148 | { 149 | // Arrange 150 | const string data = "23e32 \n{1,\"WSConnection\",1},{2,\"WSConnection\",1},\n{3,\"WSConnection\",1},{п"; 151 | using var mStream = new MemoryStream(Encoding.UTF8.GetBytes(data)); 152 | using var reader = new BracketsListReader(mStream); 153 | 154 | var count = 0; 155 | 156 | var resultItems = new List(); 157 | 158 | // Act 159 | while (!reader.EndOfStream) 160 | { 161 | var item = reader.NextNodeAsStringBuilder(); 162 | 163 | if (item.Length == 0) 164 | break; 165 | 166 | count++; 167 | resultItems.Add(item.ToString()); 168 | } 169 | 170 | // Assert 171 | Assert.Equal(3, count); 172 | Assert.Equal("{1,\"WSConnection\",1}", resultItems[0]); 173 | Assert.Equal("{2,\"WSConnection\",1}", resultItems[1]); 174 | Assert.Equal("{3,\"WSConnection\",1}", resultItems[2]); 175 | Assert.Equal(71, reader.Position); 176 | } 177 | 178 | [Fact] 179 | public void BracketsParserMultilineParseTest() 180 | { 181 | const string s = @"{20210119021929,N, 182 | {0,0},1,1,3,149022,20,I,""Получен ответ Сервиса классификаторов: 183 | [{""""classifierNick"""":""""PITDeductions"""",""""classifierName"""":""""Размер вычетов НДФЛ"""",""""versionDescription"""":"""""""",""""version"""":2,""""fileUrl"""":""""https://dl03.1c.ru/public/classifier/download/30c90ee3-1c5b-11e8-80d8-0050569f1015"""",""""fileSize"""":18822,""""hashSum"""":""""33L4yNJbCmDw7SrtM3XZzw==""""},{""""classifierNick"""":""""MaxMonthlyInsurancePayout"""",""""classifierName"""":""""Максимальный размер ежемесячной страховой выплаты"""",""""versionDescription"""":""""В соответствии со статьей 12 Федерального закона от 24.07.1998 № 125-ФЗ проиндексирован размер выплаты с 1 февраля 2020 года."""",""""version"""":5,""""fileUrl"""":""""https://dl03.1c.ru/public/classifier/download/00cfae4a-3923-11ea-80ec-0050569f1015"""",""""fileSize"""":2428,""""hashSum"""":""""y28tuv/TEU12m4eVPuMnzg==""""},{""""classifierNick"""":""""EffectiveDatesOfRegulatoryActs"""",""""classifierName"""":""""Даты вступления в силу нормативных актов"""",""""versionDescription"""":""""Дата вступления в силу постановления Правления ПФР от 27 сентября 2019 № 485п."""",""""version"""":6,""""fileUrl"""":""""https://dl03.1c.ru/public/classifier/download/c939a4f2-4670-11ea-80ed-0050569f1015"""",""""fileSize"""":1433,""""hashSum"""":""""hmZgfRmYQBeLy8zAhuzfdA==""""},{""""classifierNick"""":""""Countries"""",""""classifierName"""":""""Общероссийский классификатор стран мира (ОКСМ)"""",""""versionDescription"""":""""Изменение 25/2019 ОКСМ Общероссийский классификатор стран мира ОК (МК (ИСО 3166) 004-97) 025-2001 Республика Северная Македония"""",""""version"""":3,""""fileUrl"""":""""https://dl03.1c.ru/public/classifier/download/4cce28e4-9c02-11ea-80f4-0050569f1015"""",""""fileSize"""":64730,""""hashSum"""":""""pjlupZJ96+ZRkCVR3sYreA==""""},{""""classifierNick"""":""""Currencies"""",""""classifierName"""":""""Общероссийский классификатор валют (ОКВ)"""",""""versionDescription"""":""""Сведения о валютах по состоянию на 01.06.2020"""",""""version"""":2,""""fileUrl"""":""""https://dl03.1c.ru/public/classifier/download/b41e13ae-a3e3-11ea-80f5-0050569f1015"""",""""fileSize"""":24109,""""hashSum"""":""""9CzW1kOCzFmojn1rg0Chqg==""""},{""""classifierNick"""":""""ChildAndDeathBenefits"""",""""classifierName"""":""""Размеры государственных пособий"""",""""versionDescription"""":""""Изменены размеры пособий по уоду за детьми до полутора лет"""",""""version"""":5,""""fileUrl"""":""""https://dl03.1c.ru/public/classifier/download/c15950d7-a76d-11ea-80f5-0050569f1015"""",""""fileSize"""":9611,""""hashSum"""":""""b8A6BApqFQHONAEri53Pdw==""""},{""""classifierNick"""":""""CentralBankRefinancingRate"""",""""classifierName"""":""""Ставка рефинансирования ЦБ"""",""""versionDescription"""":""""Изменение ставки рефинансирования (ключевой ставки) с 27.07.2020 в соответствии с Информацией Банка России от 24.07.2020."""",""""version"""":14,""""fileUrl"""":""""https://dl03.1c.ru/public/classifier/download/d9ecbdfc-cdb2-11ea-80f7-0050569f1015"""",""""fileSize"""":6599,""""hashSum"""":""""li/QL1zEA2isdEBOBBDguA==""""},{""""classifierNick"""":""""InsurancePaymentPercentagesR2"""",""""classifierName"""":""""Тарифы страховых взносов"""",""""versionDescription"""":""""Обновлены тарифы страховых взносов в соответствии с Федеральным законом от 31.07.2020 № 265-ФЗ."""",""""version"""":12,""""fileUrl"""":""""https://dl03.1c.ru/public/classifier/download/5f2f1bf4-0359-11eb-80f9-0050569f1015"""",""""fileSize"""":43878,""""hashSum"""":""""qG0TLoSjHf760lrvDUu/xA==""""},{""""classifierNick"""":""""MaxInsurancePaymentBasis"""",""""classifierName"""":""""Предельная величина базы страховых взносов"""",""""versionDescription"""":""""Постановление Правительства РФ от 26.11.2020 № 1935"""",""""version"""":5,""""fileUrl"""":""""https://dl03.1c.ru/public/classifier/download/f963e789-33b4-11eb-80fa-0050569f1015"""",""""fileSize"""":4067,""""hashSum"""":""""UvUg80Ot5DjmdcZ4eihSAQ==""""},{""""classifierNick"""":""""MinMonthlyWage"""",""""classifierName"""":""""Минимальная оплата труда РФ"""",""""versionDescription"""":""""В соответствии с Федеральным законом \""""О внесении изменений в отдельные законодательные акты Российской Федерации\"""" минимальный размер оплаты труда с 1 января 2021 года установлен в сумме 12792 рублей в месяц."""",""""version"""":6,""""fileUrl"""":""""https://dl03.1c.ru/public/classifier/download/82ceae1b-45b8-11eb-80fa-0050569f1015"""",""""fileSize"""":3718,""""hashSum"""":""""lzJIyURtb1/wv5SgcC0Kaw==""""},{""""classifierNick"""":""""Calendars20"""",""""classifierName"""":""""Календари"""",""""versionDescription"""":""""1. Уточнена дата праздничного дня «Сагаалган» 13 февраля 2021 года вместо 12 февраля 2021 года для Республики Бурятия, Республики Калмыкия, Республики Тыва, Забайкальского края и Усть-Ордынского Бурятского округа Иркутской области.\n\n2. Добавлены даты праздничных дней Курбан-Байрам 20 июля 2021 года и День поминовения усопших (Радоница) 11 мая 2021 года в Республике Адыгея."""",""""version"""":18,""""fileUrl"""":""""https://dl03.1c.ru/public/classifier/download/1cecd672-5966-11eb-80fa-86643b3f0aba"""",""""fileSize"""":115218,""""hashSum"""":""""7Qoi30QlTNeW8HCb7xcVCg==""""},{""""classifierNick"""":""""Banks"""",""""classifierName"""":""""Справочник по кредитным организациям"""",""""versionDescription"""":""""Сведения о кредитных организациях по состоянию на 17.01.2021*\n\n——\n* Не содержит территориальных отделений Федерального казначейства (ТОФК). Для соответствия 479-ФЗ от 27.12.2019 «О внесении изменений в Бюджетный кодекс Российской Федерации в части казначейского обслуживания и системы казначейских платежей» необходимо обновить версию программы и перейти на загрузку классификатора «Справочник БИК»."""",""""version"""":677,""""fileUrl"""":""""https://dl03.1c.ru/public/classifier/download/742655b8-5995-11eb-80fa-86643b3f0aba"""",""""fileSize"""":512094,""""hashSum"""":""""f9LNnQOixRjD+YihIN833g==""""}]"",0, 184 | {""U""},"""",1,1,0,420,0, 185 | {2,1,1,2,1} 186 | }, 187 | {20210119000237,N, 188 | {0,0},1,1,3,145991,8,I,"""",1259, 189 | {""S"",""""},"""",1,1,0,418,0, 190 | {2,1,1,2,1} 191 | }"; 192 | 193 | using var mStream = new MemoryStream(Encoding.UTF8.GetBytes(s)); 194 | using var stream = new StreamReader(mStream); 195 | var reader = new BracketsListReader(stream); 196 | 197 | // Act 198 | var item = reader.NextNodeAsStringBuilder(); 199 | var node = BracketsParser.ParseBlock(item); 200 | 201 | var item2 = reader.NextNodeAsStringBuilder(); 202 | var node2 = BracketsParser.ParseBlock(item2); 203 | 204 | // Assert 205 | Assert.Equal(19, node.Count); 206 | Assert.Equal(19, node2.Count); 207 | } 208 | } 209 | } 210 | -------------------------------------------------------------------------------- /OneSTools.BracketsFile.Tests/OneSTools.BracketsFile.Tests.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netcoreapp3.1 5 | 6 | false 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /OneSTools.BracketsFile.Tests/StreamReaderExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.IO; 4 | using System.Reflection; 5 | using System.Text; 6 | 7 | namespace OneSTools.BracketsFile 8 | { 9 | internal static class StreamReaderExtensions 10 | { 11 | readonly static FieldInfo charPosField = typeof(StreamReader).GetField("_charPos", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly); 12 | readonly static FieldInfo byteLenField = typeof(StreamReader).GetField("_byteLen", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly); 13 | readonly static FieldInfo charBufferField = typeof(StreamReader).GetField("_charBuffer", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly); 14 | 15 | public static long GetPosition(this StreamReader reader) 16 | { 17 | // shift position back from BaseStream.Position by the number of bytes read 18 | // into internal buffer. 19 | int byteLen = (int)byteLenField.GetValue(reader); 20 | var position = reader.BaseStream.Position - byteLen; 21 | 22 | // if we have consumed chars from the buffer we need to calculate how many 23 | // bytes they represent in the current encoding and add that to the position. 24 | int charPos = (int)charPosField.GetValue(reader); 25 | if (charPos > 0) 26 | { 27 | var charBuffer = (char[])charBufferField.GetValue(reader); 28 | var encoding = reader.CurrentEncoding; 29 | var bytesConsumed = encoding.GetBytes(charBuffer, 0, charPos).Length; 30 | position += bytesConsumed; 31 | } 32 | 33 | return position; 34 | } 35 | 36 | public static void SetPosition(this StreamReader reader, long position) 37 | { 38 | reader.DiscardBufferedData(); 39 | reader.BaseStream.Seek(position, SeekOrigin.Begin); 40 | 41 | if (reader.BaseStream.Position != position) 42 | throw new Exception("Couldn't set the stream position"); 43 | } 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /OneSTools.BracketsFile.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 16 4 | VisualStudioVersion = 16.0.29613.14 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "OneSTools.BracketsFile", "OneSTools.BracketsFile\OneSTools.BracketsFile.csproj", "{13BB3A23-BADC-49B1-B55A-0565EEC95B61}" 7 | EndProject 8 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "OneSTools.BracketsFile.Tests", "OneSTools.BracketsFile.Tests\OneSTools.BracketsFile.Tests.csproj", "{42D78CD0-7D65-44F3-A893-D6F83D0FB7A9}" 9 | EndProject 10 | Global 11 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 12 | Debug|Any CPU = Debug|Any CPU 13 | Release|Any CPU = Release|Any CPU 14 | EndGlobalSection 15 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 16 | {13BB3A23-BADC-49B1-B55A-0565EEC95B61}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 17 | {13BB3A23-BADC-49B1-B55A-0565EEC95B61}.Debug|Any CPU.Build.0 = Debug|Any CPU 18 | {13BB3A23-BADC-49B1-B55A-0565EEC95B61}.Release|Any CPU.ActiveCfg = Release|Any CPU 19 | {13BB3A23-BADC-49B1-B55A-0565EEC95B61}.Release|Any CPU.Build.0 = Release|Any CPU 20 | {42D78CD0-7D65-44F3-A893-D6F83D0FB7A9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 21 | {42D78CD0-7D65-44F3-A893-D6F83D0FB7A9}.Debug|Any CPU.Build.0 = Debug|Any CPU 22 | {42D78CD0-7D65-44F3-A893-D6F83D0FB7A9}.Release|Any CPU.ActiveCfg = Release|Any CPU 23 | {42D78CD0-7D65-44F3-A893-D6F83D0FB7A9}.Release|Any CPU.Build.0 = Release|Any CPU 24 | EndGlobalSection 25 | GlobalSection(SolutionProperties) = preSolution 26 | HideSolutionNode = FALSE 27 | EndGlobalSection 28 | GlobalSection(ExtensibilityGlobals) = postSolution 29 | SolutionGuid = {4F3AAE8B-F2E5-4A71-AE6F-13FB2D885712} 30 | EndGlobalSection 31 | EndGlobal 32 | -------------------------------------------------------------------------------- /OneSTools.BracketsFile/BracketsListReader.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Text; 3 | using System.IO; 4 | 5 | namespace OneSTools.BracketsFile 6 | { 7 | /// 8 | /// Represents methods for working with 1C "brackets" data that looks like a list of items 9 | /// 10 | public class BracketsListReader : IDisposable 11 | { 12 | private readonly StreamReader _stream; 13 | private bool disposedValue; 14 | 15 | /// 16 | /// Current position of the stream 17 | /// 18 | public long Position 19 | { 20 | get => _stream.GetPosition(); 21 | set => _stream.SetPosition(value); 22 | } 23 | /// 24 | /// Stream's end flag 25 | /// 26 | public bool EndOfStream => _stream.EndOfStream; 27 | 28 | public BracketsListReader(Stream stream) 29 | => _stream = new StreamReader(stream); 30 | 31 | public BracketsListReader(Stream stream, int bufferSize) 32 | => _stream = new StreamReader(stream, Encoding.UTF8, false, bufferSize); 33 | 34 | public BracketsListReader(StreamReader stream) 35 | => _stream = stream; 36 | 37 | /// 38 | /// Reads and returns data of the next "brackets" item. If there is no data or the end of the item hasn't been found than it returns null 39 | /// 40 | /// 41 | public string NextNodeAsString() 42 | { 43 | var itemBuilder = NextNodeAsStringBuilder(); 44 | 45 | if (itemBuilder.Length == 0) 46 | return null; 47 | else 48 | return itemBuilder.ToString(); 49 | } 50 | 51 | /// 52 | /// Reads and returns data of the next "brackets" item. If there is no data or the end of the item hasn't been found than it returns null 53 | /// 54 | /// 55 | public BracketsNode NextNode() 56 | { 57 | var itemBuilder = NextNodeAsStringBuilder(); 58 | 59 | if (itemBuilder.Length == 0) 60 | return null; 61 | else 62 | return BracketsParser.ParseBlock(itemBuilder); 63 | } 64 | 65 | /// 66 | /// Reads and returns a string builder of the next "brackets" item. If there is no data or the end of the item hasn't been found than it returns empty string builder 67 | /// 68 | /// 69 | public StringBuilder NextNodeAsStringBuilder() 70 | { 71 | var itemData = new StringBuilder(); 72 | 73 | var started = false; 74 | var index = 0; 75 | var quotes = 0; 76 | var brackets = 0; 77 | var endIndex = -1; 78 | var textValueBrackets = 0; 79 | 80 | while (!EndOfStream) 81 | { 82 | var currentChar = (char) _stream.Read(); 83 | 84 | if (currentChar == -1) 85 | break; 86 | 87 | if (!started && currentChar == '{') 88 | started = true; 89 | 90 | if (started) 91 | itemData.Append(currentChar); 92 | else 93 | continue; 94 | 95 | if (textValueBrackets > 0) 96 | { 97 | var textValueEndIndex = BracketsParser.GetTextValueEndIndex(itemData, itemData.Length - 1, ref textValueBrackets); 98 | 99 | if (textValueEndIndex == -1) 100 | continue; 101 | 102 | index = textValueEndIndex; 103 | textValueBrackets = 0; 104 | continue; 105 | } 106 | 107 | endIndex = BracketsParser.GetNodeEndIndex(itemData, ref index, ref quotes, ref brackets, ref textValueBrackets); 108 | 109 | if (endIndex != -1) 110 | break; 111 | } 112 | 113 | if (endIndex != -1) 114 | return itemData; 115 | 116 | // if there is no end index than set stream's position to the beginning of the item and returns empty value 117 | var itemDataBytesLength = _stream.CurrentEncoding.GetBytes(itemData.ToString()).Length; 118 | _stream.SetPosition(_stream.GetPosition() - itemDataBytesLength); 119 | 120 | return itemData.Clear(); 121 | 122 | } 123 | 124 | protected virtual void Dispose(bool disposing) 125 | { 126 | if (!disposedValue) 127 | { 128 | if (disposing) 129 | { 130 | 131 | } 132 | 133 | _stream?.Dispose(); 134 | 135 | disposedValue = true; 136 | } 137 | } 138 | 139 | ~BracketsListReader() 140 | { 141 | Dispose(disposing: false); 142 | } 143 | 144 | public void Dispose() 145 | { 146 | Dispose(disposing: true); 147 | GC.SuppressFinalize(this); 148 | } 149 | } 150 | } -------------------------------------------------------------------------------- /OneSTools.BracketsFile/BracketsNode.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections; 3 | using System.Collections.Generic; 4 | 5 | namespace OneSTools.BracketsFile 6 | { 7 | public class BracketsNode : IEnumerable 8 | { 9 | public bool IsValueNode { get; private set; } 10 | public string Text { get; private set; } 11 | public List Nodes { get; private set; } = new List(); 12 | public int Count => Nodes.Count; 13 | 14 | public BracketsNode this[int index] 15 | { 16 | get 17 | { 18 | return Nodes[index]; 19 | } 20 | } 21 | 22 | public BracketsNode() 23 | { 24 | IsValueNode = false; 25 | } 26 | 27 | public BracketsNode(string text) 28 | { 29 | Text = text; 30 | IsValueNode = true; 31 | } 32 | 33 | public BracketsNode GetNode(params int[] address) 34 | { 35 | BracketsNode currentNode = this; 36 | 37 | for (int i = 0; i < address.Length; i++) 38 | { 39 | currentNode = currentNode[address[i]]; 40 | } 41 | 42 | return currentNode; 43 | } 44 | 45 | public static implicit operator string(BracketsNode node) 46 | { 47 | return node.Text; 48 | } 49 | public static implicit operator short(BracketsNode node) 50 | { 51 | return short.Parse(node.Text); 52 | } 53 | public static implicit operator ushort(BracketsNode node) 54 | { 55 | return ushort.Parse(node.Text); 56 | } 57 | public static implicit operator int(BracketsNode node) 58 | { 59 | return int.Parse(node.Text); 60 | } 61 | public static implicit operator uint(BracketsNode node) 62 | { 63 | return uint.Parse(node.Text); 64 | } 65 | public static implicit operator long(BracketsNode node) 66 | { 67 | return long.Parse(node.Text); 68 | } 69 | public static implicit operator ulong(BracketsNode node) 70 | { 71 | return ulong.Parse(node.Text); 72 | } 73 | public static implicit operator Guid(BracketsNode node) 74 | { 75 | return Guid.Parse(node.Text); 76 | } 77 | public static implicit operator bool(BracketsNode node) 78 | { 79 | if (!node.IsValueNode) 80 | throw new ArgumentException("The node doesn't present a value"); 81 | 82 | if ((string)node == "1") 83 | return true; 84 | else if ((string)node == "0") 85 | return false; 86 | else 87 | throw new ArgumentException($"\"{node.Text}\" value can not be casted to boolean"); 88 | } 89 | 90 | public override string ToString() 91 | { 92 | if (IsValueNode) 93 | return Text; 94 | else 95 | return $"Count = {Nodes.Count}"; 96 | } 97 | 98 | public IEnumerator GetEnumerator() 99 | { 100 | return Nodes.GetEnumerator(); 101 | } 102 | 103 | IEnumerator IEnumerable.GetEnumerator() 104 | { 105 | return GetEnumerator(); 106 | } 107 | } 108 | } 109 | -------------------------------------------------------------------------------- /OneSTools.BracketsFile/BracketsParser.cs: -------------------------------------------------------------------------------- 1 | using System.Text; 2 | using System.Text.RegularExpressions; 3 | using System.Collections.Generic; 4 | using System.IO.Compression; 5 | using System.Threading.Tasks; 6 | 7 | namespace OneSTools.BracketsFile 8 | { 9 | /// 10 | /// Represents static methods for working with 1C "brackets" data 11 | /// 12 | public static class BracketsParser 13 | { 14 | /// 15 | /// Returns parsed node 16 | /// 17 | /// 18 | /// 19 | /// 20 | /// 21 | public static BracketsNode ParseBlock(string text, int startIndex = 0, int endIndex = -1) 22 | { 23 | var strBuilder = new StringBuilder(text); 24 | 25 | return ParseBlock(strBuilder, startIndex, endIndex); 26 | } 27 | 28 | /// 29 | /// Returns parsed node 30 | /// 31 | /// 32 | /// 33 | /// 34 | /// 35 | public static BracketsNode ParseBlock(StringBuilder text, int startIndex = 0, int endIndex = -1) 36 | { 37 | var node = new BracketsNode(); 38 | 39 | if (endIndex == -1) 40 | endIndex = GetNodeEndIndex(text, startIndex); 41 | if (endIndex == -1) 42 | endIndex = text.Length - 1; 43 | 44 | if (text[startIndex] == '{' && text[endIndex] == '}') 45 | { 46 | startIndex += 1; 47 | endIndex -= 1; 48 | } 49 | 50 | for (var i = startIndex; i <= endIndex; i++) 51 | { 52 | var currentChar = text[i]; 53 | 54 | switch (currentChar) 55 | { 56 | // string value 57 | case '"': 58 | { 59 | var textValueBrackets = 0; 60 | var valueEndIndex = GetTextValueEndIndex(text, i, ref textValueBrackets); 61 | var value = text.ToString(i + 1, valueEndIndex - i - 1); 62 | node.Nodes.Add(new BracketsNode(value)); 63 | 64 | i = valueEndIndex; 65 | break; 66 | } 67 | // new block 68 | case '{': 69 | { 70 | var valueEndIndex = GetNodeEndIndex(text, i); 71 | var value = ParseBlock(text, i, valueEndIndex); 72 | node.Nodes.Add(value); 73 | 74 | i = valueEndIndex; 75 | break; 76 | } 77 | default: 78 | { 79 | if (currentChar != '"' && currentChar != '}' && currentChar != ',' && !char.IsWhiteSpace(currentChar)) // another value 80 | { 81 | var valueEndIndex = GetValueEndIndex(text, i); 82 | var value = text.ToString(i, valueEndIndex - i); 83 | node.Nodes.Add(new BracketsNode(value)); 84 | 85 | i = valueEndIndex; 86 | } 87 | 88 | break; 89 | } 90 | } 91 | } 92 | 93 | return node; 94 | } 95 | 96 | /// 97 | /// Returns the last index of the block. If the end hasn't been found than returns -1 98 | /// 99 | /// 100 | /// 101 | /// 102 | public static int GetNodeEndIndex(StringBuilder text, int startIndex) 103 | { 104 | var quotes = 0; 105 | var brackets = 0; 106 | var textValueBrackets = 0; 107 | 108 | return GetNodeEndIndex(text, ref startIndex, ref quotes, ref brackets, ref textValueBrackets); 109 | } 110 | 111 | /// 112 | /// Returns the last index of the block and save counted key symbols in refs. If the end hasn't been found than returns -1 113 | /// 114 | /// 115 | /// 116 | /// 117 | /// 118 | /// 119 | /// 120 | internal static int GetNodeEndIndex(StringBuilder text, ref int index, ref int quotes, ref int brackets, ref int textValueBrackets) 121 | { 122 | while (index < text.Length) 123 | { 124 | var prevChar = index > 0 ? text[index - 1] : '\0'; 125 | var currentChar = text[index]; 126 | 127 | if (prevChar == ',' && currentChar == '"') 128 | { 129 | var textValueEndIndex = GetTextValueEndIndex(text, index, ref textValueBrackets); 130 | 131 | if (textValueEndIndex == -1) 132 | { 133 | index = textValueEndIndex; 134 | return index; 135 | } 136 | 137 | index = textValueEndIndex; 138 | index++; 139 | continue; 140 | } 141 | 142 | switch (currentChar) 143 | { 144 | case '"': 145 | quotes++; 146 | break; 147 | case '{': 148 | brackets++; 149 | break; 150 | case '}': 151 | brackets--; 152 | break; 153 | } 154 | 155 | if (brackets == 0 && (quotes == 0 || (quotes != 0 && (quotes % 2) == 0))) 156 | return index; 157 | 158 | index++; 159 | } 160 | 161 | return -1; 162 | } 163 | 164 | /// 165 | /// Returns the last index of the any value (except string value and block). If the end hasn't been found than returns -1 166 | /// 167 | /// 168 | /// 169 | /// 170 | public static int GetValueEndIndex(StringBuilder text, int startIndex) 171 | { 172 | for (var i = startIndex; i < text.Length; i++) 173 | { 174 | var c = text[i]; 175 | 176 | if (c == ',' || c == '}') 177 | return i; 178 | } 179 | 180 | return -1; 181 | } 182 | 183 | /// 184 | /// Returns the last index of the text value. If the end hasn't been found than returns -1 185 | /// 186 | /// 187 | /// 188 | /// 189 | /// 190 | public static int GetTextValueEndIndex(StringBuilder text, int startIndex, ref int textValueBrackets) 191 | { 192 | for (var i = startIndex; i < text.Length; i++) 193 | { 194 | var prevChar = i > 0 ? text[i - 1] : '\0'; 195 | var currentChar = text[i]; 196 | var nextChar = text.Length > i + 1 ? text[i + 1] : '\0'; 197 | 198 | if (currentChar == '"') 199 | textValueBrackets++; 200 | 201 | if ((prevChar == '"' && (currentChar == ',' || currentChar == '}') || currentChar == '"' && (nextChar == ',' || nextChar == '}')) && (textValueBrackets == 0 || textValueBrackets % 2 == 0)) 202 | return i; 203 | } 204 | 205 | return -1; 206 | } 207 | } 208 | } 209 | -------------------------------------------------------------------------------- /OneSTools.BracketsFile/OneSTools.BracketsFile.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netstandard2.1 5 | Akpaev Evgeniy 6 | OneSTools.BracketsFile 7 | Akpaev Evgeniy 8 | true 9 | OneSTools.BracketsFile.pfx 10 | false 11 | bfd84778-24ce-4c5f-bbd9-bc0c255f5dd9 12 | true 13 | Библиотека для парсинга внутрисистемного формата файлов 1С. 14 | Akpaev Evgeniy 15 | https://github.com/akpaevj/OneSTools.BracketsFile 16 | false 17 | LICENSE.md 18 | 2.1.9 19 | onestools_icon_nuget.png 20 | 21 | 22 | 23 | 24 | True 25 | 26 | 27 | 28 | True 29 | 30 | 31 | 32 | 33 | 34 | -------------------------------------------------------------------------------- /OneSTools.BracketsFile/StreamReaderExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.IO; 4 | using System.Reflection; 5 | using System.Text; 6 | 7 | namespace OneSTools.BracketsFile 8 | { 9 | internal static class StreamReaderExtensions 10 | { 11 | readonly static FieldInfo charPosField = typeof(StreamReader).GetField("_charPos", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly); 12 | readonly static FieldInfo byteLenField = typeof(StreamReader).GetField("_byteLen", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly); 13 | readonly static FieldInfo charBufferField = typeof(StreamReader).GetField("_charBuffer", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly); 14 | 15 | public static long GetPosition(this StreamReader reader) 16 | { 17 | // shift position back from BaseStream.Position by the number of bytes read 18 | // into internal buffer. 19 | int byteLen = (int)byteLenField.GetValue(reader); 20 | var position = reader.BaseStream.Position - byteLen; 21 | 22 | // if we have consumed chars from the buffer we need to calculate how many 23 | // bytes they represent in the current encoding and add that to the position. 24 | int charPos = (int)charPosField.GetValue(reader); 25 | if (charPos > 0) 26 | { 27 | var charBuffer = (char[])charBufferField.GetValue(reader); 28 | var encoding = reader.CurrentEncoding; 29 | var bytesConsumed = encoding.GetBytes(charBuffer, 0, charPos).Length; 30 | position += bytesConsumed; 31 | } 32 | 33 | return position; 34 | } 35 | 36 | public static void SetPosition(this StreamReader reader, long position) 37 | { 38 | reader.DiscardBufferedData(); 39 | reader.BaseStream.Seek(position, SeekOrigin.Begin); 40 | 41 | if (reader.BaseStream.Position != position) 42 | throw new Exception("Couldn't set the stream position"); 43 | } 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # OneSTools.BracketsFile 2 | [![Nuget](https://img.shields.io/nuget/v/OneSTools.BracketsFile)](https://www.nuget.org/packages/OneSTools.BracketsFile)
3 | Библиотека для парсинга внутрисистемного формата файлов 1С. 4 | 5 | Файлы данного формата размещаются либо в чистом виде, либо запакованы в raw deflate и представляют из себя дерево значений: 6 | ``` 7 | { 8 | Value, 9 | Value1, 10 | Value2, 11 | { 12 | Value3, 13 | "TextValue" 14 | }, 15 | Value5 16 | }. 17 | ``` 18 | --------------------------------------------------------------------------------