├── .editorconfig
├── .gitattributes
├── .github
└── workflows
│ └── dotnet.yml
├── .gitignore
├── Directory.Build.props
├── NetTopologySuite.IO.ShapeFile.sln
├── README.md
├── icon.png
├── nts.snk
├── nuget.config
├── src
├── Directory.Build.props
├── NetTopologySuite.IO.GDB
│ ├── AssemblyInfo.cs
│ ├── GDBReader.cs
│ ├── GDBWriter.cs
│ └── NetTopologySuite.IO.GDB.csproj
└── NetTopologySuite.IO.ShapeFile
│ ├── AssemblyInfo.cs
│ ├── BigEndianBinaryReader.cs
│ ├── BigEndianBinaryWriter.cs
│ ├── BitTweaks.cs
│ ├── Dbase
│ ├── ColumnStructure.cs
│ ├── DbaseEncodingUtility.cs
│ ├── DbaseFieldDescriptor.cs
│ ├── DbaseFileHeader.cs
│ ├── DbaseFileReader.FullFat.cs
│ ├── DbaseFileReader.cs
│ ├── DbaseFileWriter.cs
│ └── RowStructure.cs
│ ├── Geometries
│ └── CoordinateBuffer.cs
│ ├── Handlers
│ ├── GeometryInstantiationErrorHandling.cs
│ ├── MBRInfo.cs
│ ├── MultiLineHandler.cs
│ ├── MultiPointHandler.cs
│ ├── NullShapeHandler.cs
│ ├── PointHandler.cs
│ ├── PointMBREnumerator.cs
│ ├── PointMBRIterator.cs
│ ├── PolygonHandler.cs
│ ├── ProbeLinearRing.cs
│ ├── ShapeHandler.cs
│ ├── ShapeLocationInFileInfo.cs
│ ├── ShapeMBREnumerator.cs
│ ├── ShapeMBREnumeratorBase.cs
│ └── ShapeMBRIterator.cs
│ ├── NetTopologySuite.IO.ShapeFile.csproj
│ ├── ShapeFile.Extended
│ ├── DbaseEnumerator.cs
│ ├── DbaseReader.cs
│ ├── Entities
│ │ ├── IShapefileFeature.cs
│ │ └── ShapefileFeature.cs
│ ├── ShapeDataReader.cs
│ └── ShapeReader.cs
│ ├── ShapeFileConstants.cs
│ ├── ShapeGeometryType.cs
│ ├── ShapeReader.cs
│ ├── ShapeWriter.cs
│ ├── Shapefile.FullFat.cs
│ ├── Shapefile.cs
│ ├── ShapefileDataReader.FullFat.cs
│ ├── ShapefileDataReader.cs
│ ├── ShapefileDataWriter.cs
│ ├── ShapefileException.cs
│ ├── ShapefileHeader.cs
│ ├── ShapefileReader.FullFat.cs
│ ├── ShapefileReader.cs
│ ├── ShapefileWriter.cs
│ └── Streams
│ ├── ByteStreamProvider.cs
│ ├── ExternallyManagedStreamProvider.cs
│ ├── FileStreamProvider.cs
│ ├── IStreamProvider.cs
│ ├── IStreamProviderRegistry.cs
│ └── ShapefileStreamProviderRegistry.cs
└── test
├── Directory.Build.props
└── NetTopologySuite.IO.ShapeFile.Test
├── Attributes
└── AttributesTest.cs
├── CommonHelpers.cs
├── DbfDateTest.cs
├── Features
└── UseOfIndexAndPreparedGeometry.cs
├── Geometries
├── LineStringSamples.cs
├── MultiPointSamples.cs
├── PointSamples.cs
└── PolygonSamples.cs
├── Issue123Test.cs
├── Issue161.cs
├── Issue173Fixture.cs
├── Issue174.cs
├── Issue178Fixture.cs
├── Issue27Fixture.cs
├── Issue36Tests.cs
├── Issue46Fixture.cs
├── Issue4Fixture.cs
├── Issue56Fixture.cs
├── Issue60Fixture.cs
├── Issue64Fixture.cs
├── Issue74Fixture.cs
├── Issue79Fixture.cs
├── NetTopologySuite.IO.ShapeFile.Test.csproj
├── NtsIssueNumberAttribute.cs
├── ShapeFile.Extended
├── DbaseReaderTests.cs
├── HelperMethods.cs
├── ShapeDataReaderTests.cs
├── ShapeReaderTests.cs
├── ShapefileDataWriterTests.cs
└── TempFileWriter.cs
├── ShapeFileDataReaderTest.cs
├── ShapeFileDataWriterTest.cs
├── ShapeFileEncodingTest.cs
├── ShapeFileInvalidHeaderTest.cs
├── ShapeFileIssueNumberAttribute.cs
├── ShapeRead.cs
├── Streams
├── ByteStreamProviderFixture.cs
└── ManagedStreamProviderFixture.cs
├── TestShapefiles
├── AllNulls.dbf
├── AllNulls.shp
├── CA_Cable_region.dbf
├── CA_Cable_region.shp
├── EmptyShapeFile.shp
├── Issue167.shp
├── Sept_polygones.dbf
├── Sept_polygones.shp
├── US_DMA_region.dbf
├── US_DMA_region.shp
├── UnifiedChecksMaterial.dbf
├── UnifiedChecksMaterial.shp
├── UnifiedChecksMaterialNullAtEnd.shp
├── UnifiedChecksMaterialNullAtStart.shp
├── UnifiedChecksMaterialNullInMiddle.shp
├── Victoria North.dbf
├── Victoria North.shp
├── Victoria North.shx
├── Volume2.shp
├── __emptyShapefile.dbf
├── __emptyShapefile.shp
├── __emptyShapefile.shx
├── afvalbakken.dbf
├── afvalbakken.shp
├── chinese_encoding.dbf
├── chinese_encoding.shp
├── chinese_encoding.shx
├── christchurch-canterbury-h.shp
├── crustal_test.dbf
├── crustal_test.shp
├── crustal_test_bugged.dbf
├── crustal_test_bugged.shp
├── date.dbf
├── error_union.shp
├── line_ed50_geo.dbf
├── line_ed50_geo.shp
├── line_ed50_utm36.shp
├── line_wgs84_geo.shp
├── point_ed50_geo.dbf
├── point_ed50_geo.shp
├── polygon intersecting line.shp
├── polygon_ed50_geo.shp
├── polygon_wgs84_geo.shp
├── shape_PointZM.shp
├── shape_pointM.shp
├── shape_pointZM_MissingM values.shp
├── tnp_pol.shp
├── with_M.dbf
└── with_M.shp
├── Various
├── CascadedPolygonUnionFixture.cs
├── GraphBuilder2.cs
├── GraphBuilder2Test.cs
├── NormalizeTest.cs
├── PathFinder.cs
├── PathFinderTest.cs
└── UnionAggregateTest.cs
└── WKTReaderTests.cs
/.editorconfig:
--------------------------------------------------------------------------------
1 | root = true
2 |
3 | [*.cs]
4 | indent_style = space
5 | indent_size = 4
6 | trim_trailing_whitespace = true
7 | insert_final_newline = true
8 | dotnet_style_predefined_type_for_locals_parameters_members = true:error
9 | dotnet_style_predefined_type_for_member_access = true:error
10 | csharp_style_var_for_built_in_types = false:error
11 | csharp_style_var_when_type_is_apparent = true:error
12 | csharp_style_var_elsewhere = true:error
13 |
--------------------------------------------------------------------------------
/.gitattributes:
--------------------------------------------------------------------------------
1 | * text=auto
2 | *.cs text=auto diff=csharp
3 |
--------------------------------------------------------------------------------
/.github/workflows/dotnet.yml:
--------------------------------------------------------------------------------
1 | name: Full Continuous Integration
2 |
3 | on: [push, pull_request]
4 |
5 | jobs:
6 | pack:
7 | name: Build (${{ matrix.os }})
8 | runs-on: ${{ matrix.os }}
9 |
10 | env:
11 | DOTNET_CLI_TELEMETRY_OPTOUT: true
12 |
13 | strategy:
14 | fail-fast: false
15 | matrix:
16 | os: [ ubuntu-latest, windows-latest, macOS-latest ]
17 |
18 | steps:
19 | - name: Get source
20 | uses: actions/checkout@v2
21 |
22 | - name: Setup .NET Core 3.1
23 | uses: actions/setup-dotnet@v1
24 | with:
25 | dotnet-version: 3.1.x
26 |
27 | - name: Build
28 | run: dotnet build -c Release -v minimal -p:WarningLevel=3
29 |
30 | - name: Test
31 | run: dotnet test -c Release --no-build -v normal
32 | shell: bash # defaults disagree on how to quote the filter string
33 |
34 | - name: Pack
35 | run: dotnet pack -c Release --no-build -o artifacts -p:NoWarn=NU5105
36 |
37 | - name: Upload
38 | uses: actions/upload-artifact@v2
39 | with:
40 | name: NuGet Package Files (${{ matrix.os }})
41 | path: artifacts
42 |
43 | deployToMyGet:
44 | name: Deploy to MyGet
45 | runs-on: ubuntu-latest
46 |
47 | env:
48 | DOTNET_CLI_TELEMETRY_OPTOUT: true
49 |
50 | needs: pack
51 | if: github.event_name == 'push' && (github.ref == 'refs/heads/develop' || github.ref == 'refs/heads/master')
52 |
53 | steps:
54 | - name: Setup .NET Core 3.1
55 | uses: actions/setup-dotnet@v1
56 | with:
57 | dotnet-version: 3.1.x
58 |
59 | - name: Download Package Files
60 | uses: actions/download-artifact@v2
61 | with:
62 | name: NuGet Package Files (ubuntu-latest)
63 | path: artifacts
64 |
65 | - name: Publish Package Files to MyGet
66 | run: dotnet nuget push artifacts/*.nupkg -s https://www.myget.org/F/nettopologysuite/api/v3/index.json -k $MYGET_API_KEY
67 | shell: bash
68 | env:
69 | MYGET_API_KEY: ${{ secrets.MYGET_API_KEY }}
70 |
71 | deployToNuGet:
72 | name: Deploy to NuGet
73 | runs-on: ubuntu-latest
74 |
75 | env:
76 | DOTNET_CLI_TELEMETRY_OPTOUT: true
77 |
78 | needs: pack
79 | if: github.event_name == 'push' && github.ref == 'refs/heads/master'
80 |
81 | steps:
82 | - name: Setup .NET Core 3.1
83 | uses: actions/setup-dotnet@v1
84 | with:
85 | dotnet-version: 3.1.x
86 |
87 | - name: Download Package Files
88 | uses: actions/download-artifact@v2
89 | with:
90 | name: NuGet Package Files (ubuntu-latest)
91 | path: artifacts
92 |
93 | - name: Publish Package Files to NuGet
94 | run: dotnet nuget push artifacts/*.nupkg -s https://api.nuget.org/v3/index.json -k $NUGET_API_KEY
95 | shell: bash
96 | env:
97 | NUGET_API_KEY: ${{ secrets.NUGET_API_KEY }}
98 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Created by http://www.gitignore.io
2 |
3 | ### VisualStudio ###
4 | ## Ignore Visual Studio temporary files, build results, and
5 | ## files generated by popular Visual Studio add-ons.
6 |
7 | # User-specific files
8 | *.suo
9 | *.user
10 | *.sln.docstates
11 |
12 | # Build results
13 | [Dd]ebug/
14 | [Dd]ebugPublic/
15 | [Rr]elease/
16 | [Rr]eleases/
17 | x64/
18 | x86/
19 | build/
20 | bld/
21 | [Bb]in/
22 | [Oo]bj/
23 |
24 | # Roslyn cache directories
25 | *.ide/
26 |
27 | # MSTest test Results
28 | [Tt]est[Rr]esult*/
29 | [Bb]uild[Ll]og.*
30 |
31 | #NUNIT
32 | *.VisualState.xml
33 | TestResult.xml
34 |
35 | # Build Results of an ATL Project
36 | [Dd]ebugPS/
37 | [Rr]eleasePS/
38 | dlldata.c
39 |
40 | *_i.c
41 | *_p.c
42 | *_i.h
43 | *.ilk
44 | *.meta
45 | *.obj
46 | *.pch
47 | *.pdb
48 | *.pgc
49 | *.pgd
50 | *.rsp
51 | *.sbr
52 | *.tlb
53 | *.tli
54 | *.tlh
55 | *.tmp
56 | *.tmp_proj
57 | *.log
58 | *.vspscc
59 | *.vssscc
60 | .builds
61 | *.pidb
62 | *.svclog
63 | *.scc
64 |
65 | # Chutzpah Test files
66 | _Chutzpah*
67 |
68 | # Visual C++ cache files
69 | ipch/
70 | *.aps
71 | *.ncb
72 | *.opensdf
73 | *.sdf
74 | *.cachefile
75 |
76 | # Visual Studio profiler
77 | *.psess
78 | *.vsp
79 | *.vspx
80 |
81 | # TFS 2012 Local Workspace
82 | $tf/
83 |
84 | # Guidance Automation Toolkit
85 | *.gpState
86 |
87 | # ReSharper is a .NET coding add-in
88 | _ReSharper*/
89 | *.[Rr]e[Ss]harper
90 | *.DotSettings.user
91 |
92 | # JustCode is a .NET coding addin-in
93 | .JustCode
94 |
95 | # TeamCity is a build add-in
96 | _TeamCity*
97 |
98 | # DotCover is a Code Coverage Tool
99 | *.dotCover
100 |
101 | # NCrunch
102 | _NCrunch_*
103 | .*crunch*.local.xml
104 |
105 | # MightyMoose
106 | *.mm.*
107 | AutoTest.Net/
108 |
109 | # Web workbench (sass)
110 | .sass-cache/
111 |
112 | # Installshield output folder
113 | [Ee]xpress/
114 |
115 | # VisualStudio
116 | .vs/
117 |
118 | # DocProject is a documentation generator add-in
119 | DocProject/buildhelp/
120 | DocProject/Help/*.HxT
121 | DocProject/Help/*.HxC
122 | DocProject/Help/*.hhc
123 | DocProject/Help/*.hhk
124 | DocProject/Help/*.hhp
125 | DocProject/Help/Html2
126 | DocProject/Help/html
127 |
128 | # Click-Once directory
129 | publish/
130 |
131 | # Publish Web Output
132 | *.[Pp]ublish.xml
133 | *.azurePubxml
134 | # TODO: Comment the next line if you want to checkin your web deploy settings
135 | # but database connection strings (with potential passwords) will be unencrypted
136 | *.pubxml
137 | *.publishproj
138 |
139 | # NuGet Packages
140 | *.nupkg
141 | # The packages folder can be ignored because of Package Restore
142 | **/packages/*
143 | # except build/, which is used as an MSBuild target.
144 | !**/packages/build/
145 | # If using the old MSBuild-Integrated Package Restore, uncomment this:
146 | #!**/packages/repositories.config
147 |
148 | # Windows Azure Build Output
149 | csx/
150 | *.build.csdef
151 |
152 | # Windows Store app package directory
153 | AppPackages/
154 |
155 | # Others
156 | sql/
157 | *.Cache
158 | ClientBin/
159 | [Ss]tyle[Cc]op.*
160 | ~$*
161 | *~
162 | *.dbmdl
163 | *.dbproj.schemaview
164 | *.pfx
165 | *.publishsettings
166 | node_modules/
167 |
168 | # RIA/Silverlight projects
169 | Generated_Code/
170 |
171 | # Backup & report files from converting an old project file
172 | # to a newer Visual Studio version. Backup files are not needed,
173 | # because we have git ;-)
174 | _UpgradeReport_Files/
175 | Backup*/
176 | UpgradeLog*.XML
177 | UpgradeLog*.htm
178 |
179 | # SQL Server files
180 | *.mdf
181 | *.ldf
182 |
183 | # Business Intelligence projects
184 | *.rdl.data
185 | *.bim.layout
186 | *.bim_*.settings
187 |
188 | # Microsoft Fakes
189 | FakesAssemblies/
190 |
191 | # Others
192 | /NetTopologySuite.IO/NetTopologySuite.IO.GeoTools/NetTopologySuite.IO.GeoTools.csproj.DotSettings
193 |
--------------------------------------------------------------------------------
/Directory.Build.props:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | $(MSBuildThisFileDirectory)
6 |
7 | $(MSBuildThisFileDirectory)nts.snk
8 |
9 | icon.png
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
--------------------------------------------------------------------------------
/NetTopologySuite.IO.ShapeFile.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio 15
4 | VisualStudioVersion = 15.0.27004.2009
5 | MinimumVisualStudioVersion = 10.0.40219.1
6 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{B0923F22-AF00-46DA-B5CE-73F4D398DE37}"
7 | ProjectSection(SolutionItems) = preProject
8 | .editorconfig = .editorconfig
9 | .gitignore = .gitignore
10 | README.md = README.md
11 | EndProjectSection
12 | EndProject
13 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "NetTopologySuite.IO.ShapeFile", "src\NetTopologySuite.IO.ShapeFile\NetTopologySuite.IO.ShapeFile.csproj", "{04CAE5A6-0B7B-47F8-9899-46EE805478E7}"
14 | EndProject
15 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "NetTopologySuite.IO.GDB", "src\NetTopologySuite.IO.GDB\NetTopologySuite.IO.GDB.csproj", "{6A1DF663-838E-42C0-811A-8114C3547B01}"
16 | EndProject
17 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "NetTopologySuite.IO.ShapeFile.Test", "test\NetTopologySuite.IO.ShapeFile.Test\NetTopologySuite.IO.ShapeFile.Test.csproj", "{89254B6E-F130-41F3-8956-2F790E99C6F0}"
18 | EndProject
19 | Global
20 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
21 | Debug|Any CPU = Debug|Any CPU
22 | Release|Any CPU = Release|Any CPU
23 | EndGlobalSection
24 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
25 | {04CAE5A6-0B7B-47F8-9899-46EE805478E7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
26 | {04CAE5A6-0B7B-47F8-9899-46EE805478E7}.Debug|Any CPU.Build.0 = Debug|Any CPU
27 | {04CAE5A6-0B7B-47F8-9899-46EE805478E7}.Release|Any CPU.ActiveCfg = Release|Any CPU
28 | {04CAE5A6-0B7B-47F8-9899-46EE805478E7}.Release|Any CPU.Build.0 = Release|Any CPU
29 | {6A1DF663-838E-42C0-811A-8114C3547B01}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
30 | {6A1DF663-838E-42C0-811A-8114C3547B01}.Debug|Any CPU.Build.0 = Debug|Any CPU
31 | {6A1DF663-838E-42C0-811A-8114C3547B01}.Release|Any CPU.ActiveCfg = Release|Any CPU
32 | {6A1DF663-838E-42C0-811A-8114C3547B01}.Release|Any CPU.Build.0 = Release|Any CPU
33 | {89254B6E-F130-41F3-8956-2F790E99C6F0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
34 | {89254B6E-F130-41F3-8956-2F790E99C6F0}.Debug|Any CPU.Build.0 = Debug|Any CPU
35 | {89254B6E-F130-41F3-8956-2F790E99C6F0}.Release|Any CPU.ActiveCfg = Release|Any CPU
36 | {89254B6E-F130-41F3-8956-2F790E99C6F0}.Release|Any CPU.Build.0 = Release|Any CPU
37 | EndGlobalSection
38 | GlobalSection(SolutionProperties) = preSolution
39 | HideSolutionNode = FALSE
40 | EndGlobalSection
41 | GlobalSection(ExtensibilityGlobals) = postSolution
42 | SolutionGuid = {06DEE0C5-480C-4A70-BC80-3791D98E6A89}
43 | EndGlobalSection
44 | EndGlobal
45 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # NetTopologySuite.IO.ShapeFile
2 | The ShapeFile IO module for NTS.
3 |
4 | ## Important note
5 | The development of this project has been discontinued.
6 | Please consider [NetTopologySuite.IO.Esri](https://github.com/NetTopologySuite/NetTopologySuite.IO.Esri) as a replacement.
7 |
--------------------------------------------------------------------------------
/icon.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/NetTopologySuite/NetTopologySuite.IO.ShapeFile/d11dc5c304a20122dbc9152b5a7484c7649ecbcc/icon.png
--------------------------------------------------------------------------------
/nts.snk:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/NetTopologySuite/NetTopologySuite.IO.ShapeFile/d11dc5c304a20122dbc9152b5a7484c7649ecbcc/nts.snk
--------------------------------------------------------------------------------
/nuget.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/src/Directory.Build.props:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 | true
8 |
9 |
10 |
11 |
12 | true
13 | true
14 | ci.travis.$(TRAVIS_BUILD_NUMBER)
15 |
16 |
17 |
18 |
19 | true
20 | true
21 | ci.teamcity.$(BUILD_NUMBER)
22 |
23 |
24 |
25 |
26 | true
27 | true
28 | ci.appveyor.$(APPVEYOR_BUILD_NUMBER)
29 |
30 |
31 |
32 |
33 | true
34 | true
35 | ci.github.$(GITHUB_RUN_ID)
36 |
37 | true
38 |
39 |
40 |
41 |
42 | local
43 |
44 |
45 |
46 |
47 | 2
48 | 1
49 | 0
50 |
51 | $([System.DateTime]::UtcNow.Ticks)
52 | $([System.DateTime]::op_Subtraction($([System.DateTime]::new($(NtsBuildTimestamp)).Date),$([System.DateTime]::new(621355968000000000))).TotalDays.ToString("00000"))
53 |
54 |
59 | $([System.DateTime]::new($(NtsBuildTimestamp)).TimeOfDay.TotalMinutes.ToString("0000"))
60 |
61 | $(NtsMajorVersion).$(NtsMinorVersion).$(NtsPatchVersion)
62 | pre.$(NtsDaysSinceEpoch)$(NtsMinutesSinceStartOfUtcDay)+$(NtsBuildMetadata)
63 |
64 |
80 |
81 |
82 |
83 |
84 | $(NtsMajorVersion).0.0.0
85 | $(NtsMajorVersion).$(NtsMinorVersion).$(NtsPatchVersion).$(NtsBuildNumber)
86 |
87 | NetTopologySuite - Team
88 |
89 | $(Company)
90 | Copyright © $([System.DateTime]::UtcNow.Year) $(CopyrightPeople)
91 |
92 |
93 |
94 | true
95 | true
96 | true
97 | snupkg
98 |
99 |
100 |
101 |
102 |
103 |
104 |
105 |
106 |
--------------------------------------------------------------------------------
/src/NetTopologySuite.IO.GDB/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Runtime.InteropServices;
2 |
3 | [assembly: ComVisible(false)]
4 | [assembly: Guid("c4673b71-80df-455c-9208-03c4a01f70ba")]
5 |
--------------------------------------------------------------------------------
/src/NetTopologySuite.IO.GDB/GDBReader.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.IO;
3 | using NetTopologySuite.Geometries;
4 |
5 | namespace NetTopologySuite.IO
6 | {
7 | ///
8 | /// Read features stored as ESRI GeoDatabase binary format in a SqlServer database,
9 | /// and converts these features to format.
10 | ///
11 | public class GDBReader : ShapeReader //, IBinaryGeometryReader
12 | {
13 | ///
14 | /// Creates a GDBReader that creates objects using a basic GeometryFactory.
15 | ///
16 | public GDBReader() : base(NtsGeometryServices.Instance.CreateGeometryFactory()) { }
17 |
18 | ///
19 | /// Creates a GDBReader that creates objects using the given
20 | /// GeometryFactory.
21 | ///
22 | /// The factory used to create Geometrys.
23 | public GDBReader(GeometryFactory factory) : base(factory) { }
24 |
25 | ///
26 | /// Read VeDEx geometries.
27 | ///
28 | ///
29 | ///
30 | public Geometry Read(Stream data)
31 | {
32 | using(var reader = new BinaryReader(data))
33 | return Read(reader);
34 | }
35 |
36 | private static Ordinates GetOrdinatesFromShapeGeometryType(ShapeGeometryType sgt)
37 | {
38 | switch (sgt)
39 | {
40 | case ShapeGeometryType.Point:
41 | case ShapeGeometryType.MultiPoint:
42 | case ShapeGeometryType.LineString:
43 | case ShapeGeometryType.Polygon:
44 | return Ordinates.XY;
45 |
46 | case ShapeGeometryType.PointZ:
47 | case ShapeGeometryType.MultiPointZ:
48 | case ShapeGeometryType.LineStringZ:
49 | case ShapeGeometryType.PolygonZ:
50 | return Ordinates.XYZ;
51 |
52 | case ShapeGeometryType.PointM:
53 | case ShapeGeometryType.MultiPointM:
54 | case ShapeGeometryType.LineStringM:
55 | case ShapeGeometryType.PolygonM:
56 | return Ordinates.XYM;
57 |
58 | case ShapeGeometryType.PointZM:
59 | case ShapeGeometryType.MultiPointZM:
60 | case ShapeGeometryType.LineStringZM:
61 | case ShapeGeometryType.PolygonZM:
62 | return Ordinates.XYZM;
63 |
64 | case ShapeGeometryType.MultiPatch:
65 | throw new NotSupportedException("FeatureType " + sgt + " not supported.");
66 |
67 | default:
68 | throw new ArgumentOutOfRangeException("FeatureType " + sgt + " not recognized by the system");
69 | }
70 | }
71 | ///
72 | ///
73 | ///
74 | ///
75 | ///
76 | public Geometry Read(BinaryReader reader)
77 | {
78 | var shapeType = (ShapeGeometryType)reader.ReadInt32();
79 | var ordinates = GetOrdinatesFromShapeGeometryType(shapeType);
80 |
81 | switch (shapeType)
82 | {
83 | case ShapeGeometryType.Point:
84 | case ShapeGeometryType.PointM:
85 | case ShapeGeometryType.PointZ:
86 | case ShapeGeometryType.PointZM:
87 | return ReadPoint(reader, ordinates);
88 |
89 | case ShapeGeometryType.LineString:
90 | case ShapeGeometryType.LineStringM:
91 | case ShapeGeometryType.LineStringZ:
92 | case ShapeGeometryType.LineStringZM:
93 | return ReadLineString(reader, ordinates);
94 |
95 | case ShapeGeometryType.Polygon:
96 | case ShapeGeometryType.PolygonM:
97 | case ShapeGeometryType.PolygonZ:
98 | case ShapeGeometryType.PolygonZM:
99 | return ReadPolygon(reader, ordinates);
100 |
101 | case ShapeGeometryType.MultiPoint:
102 | case ShapeGeometryType.MultiPointM:
103 | case ShapeGeometryType.MultiPointZ:
104 | case ShapeGeometryType.MultiPointZM:
105 | return ReadMultiPoint(reader, ordinates);
106 |
107 | case ShapeGeometryType.MultiPatch:
108 | throw new NotSupportedException("FeatureType " + shapeType + " not supported.");
109 |
110 | default:
111 | throw new ArgumentOutOfRangeException("FeatureType " + shapeType + " not recognized by the system");
112 | }
113 | }
114 |
115 | ///
116 | /// Read VeDEx geometries.
117 | ///
118 | ///
119 | ///
120 | public Geometry Read(byte[] data)
121 | {
122 | using(Stream stream = new MemoryStream(data))
123 | return Read(stream);
124 | }
125 | }
126 | }
127 |
--------------------------------------------------------------------------------
/src/NetTopologySuite.IO.GDB/GDBWriter.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.IO;
3 | using NetTopologySuite.Geometries;
4 |
5 | namespace NetTopologySuite.IO
6 | {
7 | ///
8 | /// Writes features as ESRI GeoDatabase binary format in a SqlServer database,
9 | /// and converts this features to Geometry format.
10 | ///
11 | public class GDBWriter : ShapeWriter
12 | {
13 | ///
14 | /// Creates a GDBWriter that creates objects using a basic GeometryFactory.
15 | ///
16 | public GDBWriter() : base() { }
17 |
18 | ///
19 | /// Returns a byte array containing binary data for the given Geometry.
20 | ///
21 | ///
22 | /// Byte[] data
23 | public byte[] Write(Geometry geometry)
24 | {
25 | byte[] bytes = GetBytes(geometry);
26 | Write(geometry, new MemoryStream(bytes));
27 | return bytes;
28 | }
29 |
30 | ///
31 | /// Writes a Geometry into a given Stream.
32 | ///
33 | ///
34 | ///
35 | public void Write(Geometry geometry, Stream stream)
36 | {
37 | using (var writer = new BinaryWriter(stream))
38 | {
39 | Writer(geometry, writer);
40 | }
41 | }
42 |
43 | ///
44 | ///
45 | ///
46 | ///
47 | ///
48 | public void Writer(Geometry geometry, BinaryWriter writer)
49 | {
50 | if (geometry is Point)
51 | Write(geometry as Point, writer);
52 | else if (geometry is LineString)
53 | Write(geometry as LineString, writer);
54 | else if (geometry is Polygon)
55 | Write(geometry as Polygon, writer);
56 | else if (geometry is MultiPoint)
57 | Write(geometry as MultiPoint, writer);
58 | else if (geometry is MultiLineString)
59 | Write(geometry as MultiLineString, writer);
60 | else if (geometry is MultiPolygon)
61 | Write(geometry as MultiPolygon, writer);
62 | else if (geometry is GeometryCollection)
63 | throw new NotSupportedException("GeometryCollection not supported!");
64 | else throw new ArgumentException("Geometry not recognized: " + geometry.ToString());
65 | }
66 | }
67 | }
68 |
--------------------------------------------------------------------------------
/src/NetTopologySuite.IO.GDB/NetTopologySuite.IO.GDB.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | netstandard2.0
5 | NetTopologySuite.IO
6 | true
7 | false
8 |
9 |
10 |
11 |
12 |
13 |
14 |
--------------------------------------------------------------------------------
/src/NetTopologySuite.IO.ShapeFile/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Runtime.CompilerServices;
2 | using System.Runtime.InteropServices;
3 |
4 | [assembly: ComVisible(false)]
5 | [assembly: Guid("b03e19e2-1a40-48bf-8b59-4b6bf11aea9d")]
6 |
7 | [assembly: InternalsVisibleTo("NetTopologySuite.IO.ShapeFile.Test, PublicKey=" +
8 | "0024000004800000940000000602000000240000525341310004000001000100e5a9697e3d378d" +
9 | "e4bdd1607b9a6ea7884823d3909f8de55b573416d9adb0ae25eebc39007d71a7228c500d6e846d" +
10 | "54dcc2cd839056c38c0a5e86b73096d90504f753ea67c9b5e61ecfdb8edf0f1dfaf0455e9a0f9e" +
11 | "124e16777baefcda2af9a5a9e48f0c3502891c79444dc2d75aa50b75d148e16f1401dcb18bc163" +
12 | "8cc764a9")]
13 |
--------------------------------------------------------------------------------
/src/NetTopologySuite.IO.ShapeFile/BigEndianBinaryReader.cs:
--------------------------------------------------------------------------------
1 | using System.IO;
2 | using System.Text;
3 |
4 | namespace NetTopologySuite.IO
5 | {
6 | ///
7 | /// Extends the class to allow reading of integers and doubles
8 | /// in the Big Endian format.
9 | ///
10 | ///
11 | /// The BinaryReader uses Little Endian format when reading binary streams.
12 | ///
13 | public class BigEndianBinaryReader : BinaryReader
14 | {
15 | ///
16 | /// Initializes a new instance of the BigEndianBinaryReader class
17 | /// based on the supplied stream and using UTF8Encoding.
18 | ///
19 | ///
20 | public BigEndianBinaryReader(Stream stream) : base(stream) { }
21 |
22 | ///
23 | /// Initializes a new instance of the BigEndianBinaryReader class
24 | /// based on the supplied stream and a specific character encoding.
25 | ///
26 | ///
27 | ///
28 | public BigEndianBinaryReader(Stream input, Encoding encoding) : base(input, encoding) { }
29 |
30 | ///
31 | /// Reads a 4-byte signed integer using the big-endian layout
32 | /// from the current stream and advances the current position of the stream by four bytes.
33 | ///
34 | ///
35 | public int ReadInt32BE() => BitTweaks.ReverseByteOrder(this.ReadInt32());
36 |
37 | ///
38 | /// Reads a 8-byte signed double using the big-endian layout
39 | /// from the current stream and advances the current position of the stream by eight bytes.
40 | ///
41 | ///
42 | public double ReadDoubleBE() => BitTweaks.ReverseByteOrder(this.ReadDouble());
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/src/NetTopologySuite.IO.ShapeFile/BigEndianBinaryWriter.cs:
--------------------------------------------------------------------------------
1 | using System.IO;
2 | using System.Text;
3 |
4 | namespace NetTopologySuite.IO
5 | {
6 | ///
7 | /// Extends the class to allow the writing of integers
8 | /// and double values in the Big Endian format.
9 | ///
10 | public class BigEndianBinaryWriter : BinaryWriter
11 | {
12 | ///
13 | /// Initializes a new instance of the BigEndianBinaryWriter class.
14 | ///
15 | public BigEndianBinaryWriter() : base() { }
16 |
17 | ///
18 | /// Initializes a new instance of the BigEndianBinaryWriter class
19 | /// based on the supplied stream and using UTF-8 as the encoding for strings.
20 | ///
21 | /// The supplied stream.
22 | public BigEndianBinaryWriter(Stream output) : base(output) { }
23 |
24 | ///
25 | /// Initializes a new instance of the BigEndianBinaryWriter class
26 | /// based on the supplied stream and a specific character encoding.
27 | ///
28 | /// The supplied stream.
29 | /// The character encoding.
30 | public BigEndianBinaryWriter(Stream output, Encoding encoding): base(output, encoding) { }
31 |
32 | ///
33 | /// Reads a 4-byte signed integer using the big-endian layout from the current stream
34 | /// and advances the current position of the stream by two bytes.
35 | ///
36 | /// The four-byte signed integer to write.
37 | public void WriteIntBE(int value) => this.Write(BitTweaks.ReverseByteOrder(value));
38 |
39 | ///
40 | /// Reads a 8-byte signed integer using the big-endian layout from the current stream
41 | /// and advances the current position of the stream by two bytes.
42 | ///
43 | /// The four-byte signed integer to write.
44 | public void WriteDoubleBE(double value) => this.Write(BitTweaks.ReverseByteOrder(value));
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/src/NetTopologySuite.IO.ShapeFile/BitTweaks.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | namespace NetTopologySuite.IO
4 | {
5 | internal static class BitTweaks
6 | {
7 | internal static int ReverseByteOrder(int value) => unchecked((int)ReverseByteOrder((uint)value));
8 |
9 | internal static long ReverseByteOrder(long value) => unchecked((long)ReverseByteOrder((ulong)value));
10 |
11 | internal static double ReverseByteOrder(double value)
12 | {
13 | long bits = BitConverter.DoubleToInt64Bits(value);
14 | bits = ReverseByteOrder(bits);
15 | return BitConverter.Int64BitsToDouble(bits);
16 | }
17 |
18 | internal static uint ReverseByteOrder(uint value) => (value & 0x000000FF) << 24 |
19 | (value & 0x0000FF00) << 8 |
20 | (value & 0x00FF0000) >> 8 |
21 | (value & 0xFF000000) >> 24;
22 |
23 | internal static ulong ReverseByteOrder(ulong value) => (value & 0x00000000000000FF) << 56 |
24 | (value & 0x000000000000FF00) << 40 |
25 | (value & 0x0000000000FF0000) << 24 |
26 | (value & 0x00000000FF000000) << 8 |
27 | (value & 0x000000FF00000000) >> 8 |
28 | (value & 0x0000FF0000000000) >> 24 |
29 | (value & 0x00FF000000000000) >> 40 |
30 | (value & 0xFF00000000000000) >> 56;
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/src/NetTopologySuite.IO.ShapeFile/Dbase/ColumnStructure.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.ComponentModel;
3 |
4 | namespace NetTopologySuite.IO
5 | {
6 | ///
7 | /// This class is used in conjunction with RowStructure.
8 | ///
9 | ///
10 | /// For an explaination of PropertyDescriptor see http://www.devx.com/dotnet/Article/7874
11 | /// and the remarks for RowStructure. This class inherits from PropertyDescriptor.
12 | /// The PropertyDescriptor describes a property - in this case a dynamically generated property.
13 | ///
14 | internal class ColumnStructure : PropertyDescriptor
15 | {
16 | private readonly DbaseFieldDescriptor _dbaseField;
17 | private readonly int _index;
18 |
19 | ///
20 | /// Initializes a new instance of the ColumnStructure class.
21 | ///
22 | ///
23 | ///
24 | public ColumnStructure(DbaseFieldDescriptor dbaseField, int index) : base(dbaseField.Name, null)
25 | {
26 | _dbaseField = dbaseField;
27 | _index=index;
28 | }
29 |
30 | ///
31 | ///
32 | ///
33 | public override Type ComponentType => typeof(RowStructure);
34 |
35 | ///
36 | /// Gets the type of the DBase field.
37 | ///
38 | public override Type PropertyType => _dbaseField.Type;
39 |
40 | ///
41 | ///
42 | ///
43 | public override bool IsReadOnly => true;
44 |
45 | ///
46 | ///
47 | ///
48 | ///
49 | ///
50 | public override bool CanResetValue(object component)
51 | {
52 | return false;
53 | }
54 |
55 | ///
56 | ///
57 | ///
58 | ///
59 | public override void ResetValue(object component) { }
60 |
61 | ///
62 | ///
63 | ///
64 | ///
65 | ///
66 | public override bool ShouldSerializeValue(object component)
67 | {
68 | return false;
69 | }
70 |
71 | ///
72 | ///
73 | ///
74 | ///
75 | ///
76 | public override void SetValue(object component, object value) { }
77 |
78 | ///
79 | ///
80 | ///
81 | ///
82 | ///
83 | public override object GetValue(object component)
84 | {
85 | // gets the 'parent' and gets a value of out of the ColumnValues property.
86 | return ((RowStructure)component).ColumnValues[_index];
87 | }
88 |
89 | // awc: Added this propety, because when creating a DataSet from the DataReader, we need
90 | // to know how long the field length is in the dbase file so we can create a column
91 | // of the appropriate length in the database.
92 | ///
93 | ///
94 | ///
95 | public int Length => _dbaseField.Length;
96 | }
97 | }
98 |
--------------------------------------------------------------------------------
/src/NetTopologySuite.IO.ShapeFile/Dbase/DbaseFieldDescriptor.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | namespace NetTopologySuite.IO
4 | {
5 | ///
6 | /// Class for holding the information assicated with a dbase field.
7 | ///
8 | public class DbaseFieldDescriptor
9 | {
10 | // Field Name
11 | private string _name;
12 |
13 | // Field Type (C N L D or M)
14 | private char _type;
15 |
16 | // Field Data Address offset from the start of the record.
17 | private int _dataAddress;
18 |
19 | // Length of the data in bytes
20 | private int _length;
21 |
22 | // Field decimal count in Binary, indicating where the decimal is
23 | private int _decimalCount;
24 |
25 | ///
26 | ///
27 | ///
28 | ///
29 | ///
30 | public static char GetDbaseType(Type type)
31 | {
32 | if (type == typeof(char))
33 | return 'C';
34 | if (type == typeof(string))
35 | return 'C';
36 | if (type == typeof(double))
37 | return 'N';
38 | if (type == typeof(float))
39 | return 'N';
40 | if (type == typeof(short))
41 | return 'N';
42 | if (type == typeof(int))
43 | return 'N';
44 | if (type == typeof(long))
45 | return 'N';
46 | if (type == typeof(ushort))
47 | return 'N';
48 | if (type == typeof(uint))
49 | return 'N';
50 | if (type == typeof(ulong))
51 | return 'N';
52 | if (type == typeof(decimal))
53 | return 'N';
54 | if (type == typeof(bool))
55 | return 'L';
56 | if (type == typeof(DateTime))
57 | return 'D';
58 |
59 | throw new NotSupportedException(string.Format("{0} does not have a corresponding dbase type.", type.Name));
60 | }
61 |
62 | ///
63 | ///
64 | ///
65 | ///
66 | public static DbaseFieldDescriptor ShapeField()
67 | {
68 | var shpfield = new DbaseFieldDescriptor();
69 | shpfield.Name="Geometry";
70 | shpfield._type='B';
71 | return shpfield;
72 | }
73 |
74 | ///
75 | ///
76 | ///
77 | ///
78 | public static DbaseFieldDescriptor IdField()
79 | {
80 | var shpfield = new DbaseFieldDescriptor();
81 | shpfield.Name="Row";
82 | shpfield._type='I';
83 | return shpfield;
84 | }
85 |
86 | ///
87 | /// Field Name.
88 | ///
89 | public string Name
90 | {
91 | get
92 | {
93 | return _name;
94 | }
95 | set
96 | {
97 | _name = value;
98 | }
99 | }
100 |
101 | ///
102 | /// Field Type (C N L D or M).
103 | ///
104 | public char DbaseType
105 | {
106 | get
107 | {
108 | return _type;
109 | }
110 | set
111 | {
112 | _type = value;
113 | }
114 | }
115 |
116 | ///
117 | /// Field Data Address offset from the start of the record.
118 | ///
119 | public int DataAddress
120 | {
121 | get
122 | {
123 | return _dataAddress;
124 | }
125 | set
126 | {
127 | _dataAddress = value;
128 | }
129 | }
130 |
131 | ///
132 | /// Length of the data in bytes.
133 | ///
134 | public int Length
135 | {
136 | get
137 | {
138 | return _length;
139 | }
140 | set
141 | {
142 | _length = value;
143 | }
144 | }
145 |
146 | ///
147 | /// Field decimal count in Binary, indicating where the decimal is.
148 | ///
149 | public int DecimalCount
150 | {
151 | get
152 | {
153 | return _decimalCount;
154 | }
155 | set
156 | {
157 | _decimalCount = value;
158 | }
159 | }
160 |
161 | ///
162 | /// Returns the equivalent CLR type for this field.
163 | ///
164 | public Type Type
165 | {
166 | get
167 | {
168 | switch (_type)
169 | {
170 | case 'L': // logical data type, one character (T,t,F,f,Y,y,N,n)
171 | return typeof(bool);
172 | case 'C': // char or string
173 | return typeof(string);
174 | case 'D': // date
175 | return typeof(DateTime);
176 | case 'N': // numeric
177 | if (DecimalCount == 0)
178 | {
179 | // Align with the logic when creating a header which specifies a length 10 for an Int32.
180 | if (Length <= 10)
181 | return typeof (int);
182 | return typeof (long);
183 | }
184 |
185 | return typeof(double);
186 | case 'F': // double
187 | return typeof(float);
188 | case 'I':
189 | return typeof (int);
190 | case 'B': // BLOB - not a dbase but this will hold the WKB for a geometry object.
191 | return typeof(byte[]);
192 | default:
193 | throw new NotSupportedException("Do not know how to parse Field type "+_type);
194 | }
195 | }
196 | }
197 |
198 | public override string ToString()
199 | {
200 | return string.Format("[ Field '{0}' ('{1}', {2}) ]", Name.TrimEnd(), DbaseType, Length);
201 | }
202 | }
203 | }
204 |
--------------------------------------------------------------------------------
/src/NetTopologySuite.IO.ShapeFile/Dbase/DbaseFileReader.FullFat.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.IO;
3 | using System.Text;
4 | using NetTopologySuite.IO.Streams;
5 |
6 | namespace NetTopologySuite.IO
7 | {
8 | public partial class DbaseFileReader
9 | {
10 | private partial class DbaseFileEnumerator
11 | {
12 | ///
13 | /// Initializes a new instance of the class.
14 | ///
15 | ///
16 | public DbaseFileEnumerator(DbaseFileReader parent)
17 | {
18 | _parent = parent;
19 | var stream = parent._streamProvider.OpenRead();
20 | _dbfReader = new BinaryReader(stream, parent._header.Encoding);
21 | ReadHeader();
22 | }
23 |
24 | ///
25 | /// Performs application-defined tasks associated with freeing, releasing,
26 | /// or resetting unmanaged resources.
27 | ///
28 | public void Dispose()
29 | {
30 | _dbfReader.Close();
31 | }
32 | }
33 |
34 | ///
35 | /// Initializes a new instance of the DbaseFileReader class.
36 | ///
37 | /// The path to the Dbase file
38 | public DbaseFileReader(string path)
39 | : this(CreateStreamProviderRegistry(path))
40 | {
41 | }
42 |
43 | ///
44 | /// Initializes a new instance of the DbaseFileReader class.
45 | ///
46 | /// The path to the Dbase file
47 | /// The encoding to use
48 | public DbaseFileReader(string path, Encoding encoding)
49 | : this(CreateStreamProviderRegistry(path, encoding))
50 | {
51 | }
52 |
53 | ///
54 | /// Initializes a new instance of the DbaseFileReader class.
55 | ///
56 | /// A stream provider registry
57 | public DbaseFileReader(IStreamProviderRegistry streamProviderRegistry)
58 | {
59 | if (streamProviderRegistry == null)
60 | throw new ArgumentNullException("streamProviderRegistry");
61 |
62 | _streamProvider = streamProviderRegistry[StreamTypes.Data];
63 | if (_streamProvider == null)
64 | throw new ArgumentException("Stream provider registry does not provide a data stream provider", "streamProviderRegistry");
65 |
66 | if (_streamProvider.Kind != StreamTypes.Data)
67 | throw new ArgumentException(string.Format(
68 | "Misconfigured stream provider registry does provide a {0} stream provider when requested data stream provider",
69 | _streamProvider.Kind), "streamProviderRegistry");
70 |
71 | _encodingProvider = streamProviderRegistry[StreamTypes.DataEncoding];
72 | if (_encodingProvider != null && _encodingProvider.Kind != StreamTypes.DataEncoding)
73 | throw new ArgumentException(string.Format(
74 | "Misconfigured stream provider registry does provide a {0} stream provider when requested data encoding stream provider",
75 | _streamProvider.Kind), "streamProviderRegistry");
76 | }
77 |
78 | ///
79 | /// Gets the header information for the dbase file.
80 | ///
81 | /// DbaseFileHeader contain header and field information.
82 | public DbaseFileHeader GetHeader()
83 | {
84 | if (_header == null)
85 | {
86 | using (var dbfReader = new BinaryReader(_streamProvider.OpenRead()))
87 | {
88 | // read the header
89 | _header = new DbaseFileHeader();
90 | _header.ReadHeader(dbfReader, _encodingProvider);
91 | }
92 | }
93 | return _header;
94 | }
95 | }
96 | }
97 |
--------------------------------------------------------------------------------
/src/NetTopologySuite.IO.ShapeFile/Dbase/RowStructure.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections;
3 | using System.ComponentModel;
4 |
5 | namespace NetTopologySuite.IO
6 | {
7 | ///
8 | /// Implements ICustomTypeDescriptor so we can simulate a row object having a property for every field.
9 | ///
10 | ///
11 | /// For an explaination of ICustomTypeDescriptor see http://www.devx.com/dotnet/Article/7874
12 | /// By implementing this interface, we are able to simulate that an object has lots of properties.
13 | /// These properties are determined dynamically at run-time. When enumerating throught the
14 | /// ShapefileDataReader, RowStructure is the object that gets returned.
15 | ///
16 | /// foreach(object obj in shpDataReader)
17 | /// {
18 | /// if (obj.GetType().Name!="RowStructure")
19 | /// {
20 | /// // this proves the type returned by shpDataReader
21 | /// }
22 | /// }
23 | ///
24 | ///
25 | internal struct RowStructure : ICustomTypeDescriptor
26 | {
27 | private DbaseFieldDescriptor[] _dbaseFields;
28 | private ArrayList _columnValues;
29 |
30 | ///
31 | ///
32 | ///
33 | ///
34 | ///
35 | public RowStructure(DbaseFieldDescriptor[] dbaseFields, ArrayList columnValues)
36 | {
37 | _dbaseFields = dbaseFields;
38 | _columnValues = columnValues;
39 | }
40 |
41 | ///
42 | ///
43 | ///
44 | public ArrayList ColumnValues => _columnValues;
45 |
46 | ///
47 | ///
48 | ///
49 | ///
50 | public AttributeCollection GetAttributes()
51 | {
52 | return AttributeCollection.Empty;
53 | }
54 |
55 | ///
56 | ///
57 | ///
58 | ///
59 | public string GetClassName()
60 | {
61 | return null;
62 | }
63 |
64 | ///
65 | ///
66 | ///
67 | ///
68 | public string GetComponentName()
69 | {
70 | return null;
71 | }
72 |
73 | ///
74 | ///
75 | ///
76 | ///
77 | public TypeConverter GetConverter()
78 | {
79 | return null;
80 | }
81 |
82 | ///
83 | ///
84 | ///
85 | ///
86 | ///
87 | public object GetEditor(Type t)
88 | {
89 | return null;
90 | }
91 |
92 | ///
93 | ///
94 | ///
95 | ///
96 | public EventDescriptor GetDefaultEvent()
97 | {
98 | return null;
99 | }
100 |
101 | ///
102 | ///
103 | ///
104 | ///
105 | ///
106 | public EventDescriptorCollection GetEvents(Attribute[] a)
107 | {
108 | return GetEvents();
109 | }
110 |
111 | ///
112 | ///
113 | ///
114 | ///
115 | public EventDescriptorCollection GetEvents()
116 | {
117 | return EventDescriptorCollection.Empty;
118 | }
119 |
120 | ///
121 | ///
122 | ///
123 | ///
124 | ///
125 | public object GetPropertyOwner(PropertyDescriptor pd)
126 | {
127 | return null;
128 | }
129 |
130 | ///
131 | ///
132 | ///
133 | ///
134 | public PropertyDescriptor GetDefaultProperty()
135 | {
136 | return null;
137 | }
138 |
139 | ///
140 | ///
141 | ///
142 | ///
143 | ///
144 | public PropertyDescriptorCollection GetProperties(Attribute[] a)
145 | {
146 | return GetProperties();
147 | }
148 |
149 | ///
150 | ///
151 | ///
152 | ///
153 | public PropertyDescriptorCollection GetProperties()
154 | {
155 | // add an extra field at the beginning - this will hold the WKT for the Geometry object.
156 | var pd = new PropertyDescriptor[_dbaseFields.Length];
157 |
158 | // the regular fields
159 | for (int i = 0; i < _dbaseFields.Length; i++)
160 | pd[i] = new ColumnStructure( _dbaseFields[i], i );
161 | return new PropertyDescriptorCollection(pd);
162 | }
163 | }
164 | }
165 |
--------------------------------------------------------------------------------
/src/NetTopologySuite.IO.ShapeFile/Handlers/GeometryInstantiationErrorHandling.cs:
--------------------------------------------------------------------------------
1 | namespace NetTopologySuite.IO.Handlers
2 | {
3 | ///
4 | /// Possible ways of handling geometry creation issues.
5 | ///
6 | public enum GeometryInstantiationErrorHandlingOption
7 | {
8 | ///
9 | /// Let the code run into exception
10 | ///
11 | ThrowException,
12 |
13 | ///
14 | /// Create an empty geometry instead
15 | ///
16 | Empty,
17 |
18 | ///
19 | /// Try to fix the geometry
20 | ///
21 | ///
22 | /// Possible fixes are:
23 | ///
24 | /// - For LineStrings with only one point provided, duplicate that point to have at least two points.
25 | /// - For LinearRings with unclosed coordinate sequence, close the sequence by adding a clone of the first coordinate
26 | /// - ...
27 | ///
28 | TryFix,
29 |
30 | ///
31 | /// Ignore this geometry/feature altogether
32 | ///
33 | Null,
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/src/NetTopologySuite.IO.ShapeFile/Handlers/MBRInfo.cs:
--------------------------------------------------------------------------------
1 | using NetTopologySuite.Geometries;
2 |
3 | namespace NetTopologySuite.IO.Handlers
4 | {
5 | public class MBRInfo
6 | {
7 | public MBRInfo(Envelope shapeMBR, long offsetFromStartOfFile, int shapeIndex)
8 | {
9 | ShapeFileDetails = new ShapeLocationInFileInfo(offsetFromStartOfFile, shapeIndex);
10 | ShapeMBR = shapeMBR;
11 | }
12 |
13 | public ShapeLocationInFileInfo ShapeFileDetails { get; private set; }
14 | public Envelope ShapeMBR { get; private set; }
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/src/NetTopologySuite.IO.ShapeFile/Handlers/MultiPointHandler.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.IO;
4 | using NetTopologySuite.Geometries;
5 | using NetTopologySuite.Utilities;
6 |
7 | namespace NetTopologySuite.IO.Handlers
8 | {
9 | ///
10 | /// Converts a Shapefile point to a OGIS Polygon.
11 | ///
12 | public class MultiPointHandler : ShapeHandler
13 | {
14 | public MultiPointHandler() : base(ShapeGeometryType.MultiPoint) { }
15 |
16 | public MultiPointHandler(ShapeGeometryType type) : base(type) { }
17 |
18 | ///
19 | /// Reads a stream and converts the shapefile record to an equilivant geometry object.
20 | ///
21 | /// The stream to read.
22 | /// Total length of the record we are about to read
23 | /// The geometry factory to use when making the object.
24 | /// The Geometry object that represents the shape file record.
25 | public override Geometry Read(BigEndianBinaryReader file, int totalRecordLength, GeometryFactory factory)
26 | {
27 | int totalRead = 0;
28 | int shapeTypeNum = ReadInt32(file, totalRecordLength, ref totalRead);
29 |
30 | var type = (ShapeGeometryType) EnumUtility.Parse(typeof(ShapeGeometryType), shapeTypeNum.ToString());
31 | if (type == ShapeGeometryType.NullShape)
32 | return factory.CreateMultiPoint();
33 |
34 | if (type != ShapeType)
35 | throw new ShapefileException(string.Format("Encountered a '{0}' instead of a '{1}'", type, ShapeType));
36 |
37 | // Read and for now ignore bounds.
38 | int bblength = GetBoundingBoxLength();
39 | boundingBox = new double[bblength];
40 | for (; boundingBoxIndex < 4; boundingBoxIndex++)
41 | {
42 | double d = ReadDouble(file, totalRecordLength, ref totalRead);
43 | boundingBox[boundingBoxIndex] = d;
44 | }
45 |
46 | // Read points
47 | int numPoints = ReadInt32(file, totalRecordLength, ref totalRead);
48 | var buffer = new CoordinateBuffer(numPoints, NoDataBorderValue, true);
49 | var points = new Point[numPoints];
50 | var pm = factory.PrecisionModel;
51 |
52 | for (int i = 0; i < numPoints; i++)
53 | {
54 | double x = pm.MakePrecise(ReadDouble(file, totalRecordLength, ref totalRead));
55 | double y = pm.MakePrecise(ReadDouble(file, totalRecordLength, ref totalRead));
56 | buffer.AddCoordinate(x, y);
57 | buffer.AddMarker();
58 | }
59 |
60 | // Trond Benum: We have now read all the points, let's read optional Z and M values
61 | GetZMValues(file, totalRecordLength, ref totalRead, buffer);
62 |
63 | var sequences = buffer.ToSequences(factory.CoordinateSequenceFactory);
64 | for (int i = 0; i < numPoints; i++)
65 | points[i] = factory.CreatePoint(sequences[i]);
66 |
67 | geom = factory.CreateMultiPoint(points);
68 |
69 | return geom;
70 | }
71 |
72 | ///
73 | /// Writes a Geometry to the given binary wirter.
74 | ///
75 | /// The geometry to write.
76 | /// The writer to use.
77 | /// The geometry factory to use.
78 | public override void Write(Geometry geometry, BinaryWriter writer, GeometryFactory factory)
79 | {
80 | if (geometry == null)
81 | throw new ArgumentNullException("geometry");
82 |
83 | var mpoint = geometry as MultiPoint;
84 | if (mpoint == null)
85 | {
86 | string err = string.Format("Expected geometry that implements 'MultiPoint', but was '{0}'",
87 | geometry.GetType().Name);
88 | throw new ArgumentException(err, "geometry");
89 | }
90 |
91 | // Slow and maybe not useful...
92 | // if (!geometry.IsValid)
93 | // Trace.WriteLine("Invalid multiPoint being written.");
94 |
95 | writer.Write((int)ShapeType);
96 | WriteEnvelope(writer, factory.PrecisionModel, geometry.EnvelopeInternal);
97 |
98 | int numPoints = mpoint.NumPoints;
99 | writer.Write(numPoints);
100 |
101 | bool hasZ = HasZValue();
102 | var zList = hasZ ? new List() : null;
103 |
104 | bool hasM = HasMValue();
105 | var mList = hasM ? new List() : null;
106 |
107 | // write the points
108 | for (int i = 0; i < numPoints; i++)
109 | {
110 | var point = (Point) mpoint.Geometries[i];
111 |
112 | writer.Write(point.X);
113 | writer.Write(point.Y);
114 |
115 | if (hasZ) zList.Add(point.Z);
116 | if (hasM) mList.Add(point.M);
117 | }
118 |
119 | WriteZM(writer, numPoints, zList, mList);
120 | }
121 |
122 | ///
123 | /// Gets the length of the shapefile record using the geometry passed in.
124 | ///
125 | /// The geometry to get the length for.
126 | /// The length in bytes this geometry is going to use when written out as a shapefile record.
127 | public override int ComputeRequiredLengthInWords(Geometry geometry)
128 | {
129 | int numPoints = geometry.NumPoints;
130 | return ComputeRequiredLengthInWords(0, numPoints, HasMValue(), HasZValue());
131 | /*
132 | int pointFactor = 2 * sizeof(double) ; // xy (4*2)
133 | int initial = 20; // 20 => shapetype(2) + bbox (4*4) + numpoints
134 |
135 | if (HasZValue())
136 | {
137 | initial = initial + 16; // ZM 16 => bbox (4*4)
138 | pointFactor = pointFactor + 8; // ZM 8 => 4 * 2
139 | }
140 | else if (HasMValue())
141 | {
142 | initial = initial + 8; // 16 => bbox m (4*2)
143 | pointFactor = pointFactor + 4; // M 4 => 4 * 1
144 | }
145 |
146 | return (initial + geometry.NumPoints * pointFactor);
147 | */
148 | }
149 | }
150 | }
151 |
--------------------------------------------------------------------------------
/src/NetTopologySuite.IO.ShapeFile/Handlers/NullShapeHandler.cs:
--------------------------------------------------------------------------------
1 | using System.Collections.Generic;
2 | using System.IO;
3 | using NetTopologySuite.Geometries;
4 |
5 | namespace NetTopologySuite.IO.Handlers
6 | {
7 | public class NullShapeHandler : ShapeHandler
8 | {
9 | public NullShapeHandler()
10 | : base(ShapeGeometryType.NullShape)
11 | {
12 | }
13 |
14 | public override Geometry Read(BigEndianBinaryReader file,
15 | int totalRecordLength, GeometryFactory factory)
16 | {
17 | return null;
18 | }
19 |
20 | public override void Write(Geometry geometry, BinaryWriter writer, GeometryFactory factory)
21 | { }
22 |
23 | public override int ComputeRequiredLengthInWords(Geometry geometry)
24 | {
25 | return -1;
26 | }
27 |
28 | public override IEnumerable ReadMBRs(BigEndianBinaryReader reader)
29 | {
30 | reader.Close();
31 | return new MBRInfo[0];
32 | }
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/src/NetTopologySuite.IO.ShapeFile/Handlers/PointHandler.cs:
--------------------------------------------------------------------------------
1 |
2 | using System;
3 | using System.Collections.Generic;
4 | using System.IO;
5 | using NetTopologySuite.Geometries;
6 |
7 | namespace NetTopologySuite.IO.Handlers
8 | {
9 | ///
10 | /// Converts a Shapefile point to a OGIS Point.
11 | ///
12 | public class PointHandler : ShapeHandler
13 | {
14 | public PointHandler() : base(ShapeGeometryType.Point)
15 | {
16 | }
17 | public PointHandler(ShapeGeometryType type)
18 | : base(type)
19 | {
20 | }
21 |
22 | ///
23 | /// Reads a stream and converts the shapefile record to an equilivent geometry object.
24 | ///
25 | /// The stream to read.
26 | /// Total length of the record we are about to read
27 | /// The geometry factory to use when making the object.
28 | /// The Geometry object that represents the shape file record.
29 | public override Geometry Read(BigEndianBinaryReader file, int totalRecordLength, GeometryFactory factory)
30 | {
31 | int totalRead = 0;
32 | var type = (ShapeGeometryType)ReadInt32(file, totalRecordLength, ref totalRead);
33 | //type = (ShapeGeometryType) EnumUtility.Parse(typeof (ShapeGeometryType), shapeTypeNum.ToString());
34 | if (type == ShapeGeometryType.NullShape)
35 | return factory.CreatePoint((Coordinate)null);
36 |
37 | if (type != ShapeType)
38 | throw new ShapefileException(string.Format("Encountered a '{0}' instead of a '{1}'", type, ShapeType));
39 |
40 | var buffer = new CoordinateBuffer(1, NoDataBorderValue, true);
41 | var precisionModel = factory.PrecisionModel;
42 |
43 | double x = precisionModel.MakePrecise(ReadDouble(file, totalRecordLength, ref totalRead));
44 | double y = precisionModel.MakePrecise(ReadDouble(file, totalRecordLength, ref totalRead));
45 |
46 | double? z = null, m = null;
47 |
48 | // Trond Benum: Let's read optional Z and M values
49 | if (HasZValue() && totalRead < totalRecordLength)
50 | z = ReadDouble(file, totalRecordLength, ref totalRead);
51 |
52 | if ((HasMValue() || HasZValue()) &&
53 | (totalRead < totalRecordLength))
54 | m = ReadDouble(file, totalRecordLength, ref totalRead);
55 |
56 | buffer.AddCoordinate(x, y, z, m);
57 | return factory.CreatePoint(buffer.ToSequence(factory.CoordinateSequenceFactory));
58 | }
59 |
60 | ///
61 | /// Writes to the given stream the equilivent shape file record given a Geometry object.
62 | ///
63 | /// The geometry object to write.
64 | /// The stream to write to.
65 | /// The geometry factory to use.
66 | public override void Write(Geometry geometry, BinaryWriter writer, GeometryFactory factory)
67 | {
68 | if (geometry == null)
69 | throw new ArgumentNullException("geometry");
70 |
71 | var point = geometry as Point;
72 | if (point == null)
73 | {
74 | string err = string.Format("Expected geometry that implements 'Point', but was '{0}'",
75 | geometry.GetType().Name);
76 | throw new ArgumentException(err, "geometry");
77 | }
78 | writer.Write((int)ShapeType);
79 | var seq = point.CoordinateSequence;
80 |
81 | writer.Write(seq.GetX(0));
82 | writer.Write(seq.GetY(0));
83 |
84 | // If we have Z, write it.
85 | if (HasZValue())
86 | {
87 | writer.Write(seq.GetZ(0));
88 | }
89 |
90 | // If we have a Z, we also have M, this is shapefile definition
91 | if (HasMValue() || HasZValue())
92 | {
93 | writer.Write(HasMValue() ? seq.GetM(0) : NoDataValue);
94 | }
95 | }
96 |
97 | ///
98 | /// Gets the length in words (1 word = 2 bytes) the Geometry will need when written as a shape file record.
99 | ///
100 | /// The Geometry object to use.
101 | /// The length in words (1 word = 2 bytes) the Geometry will use when represented as a shape file record.
102 | public override int ComputeRequiredLengthInWords(Geometry geometry)
103 | {
104 | if (HasZValue())
105 | // 18 => shapetype(2)+ xyzm(4*4)
106 | return 18;
107 | if (HasMValue())
108 | // 14 => shapetype(2)+ xym(3*4)
109 | return 14;
110 |
111 | // 10 => shapetype(2)+ xy(2*4)
112 | return 10;
113 | }
114 |
115 | public override IEnumerable ReadMBRs(BigEndianBinaryReader reader)
116 | {
117 | return new PointMBREnumerator(reader);
118 | }
119 | }
120 | }
121 |
--------------------------------------------------------------------------------
/src/NetTopologySuite.IO.ShapeFile/Handlers/PointMBREnumerator.cs:
--------------------------------------------------------------------------------
1 | using System.Collections;
2 | using System.Collections.Generic;
3 |
4 | namespace NetTopologySuite.IO.Handlers
5 | {
6 | internal class PointMBREnumerator : IEnumerable
7 | {
8 | private readonly BigEndianBinaryReader m_Reader;
9 |
10 | public PointMBREnumerator(BigEndianBinaryReader reader)
11 | {
12 | m_Reader = reader;
13 | }
14 |
15 | public IEnumerator GetEnumerator()
16 | {
17 | return new PointMBRIterator(m_Reader);
18 | }
19 |
20 | IEnumerator IEnumerable.GetEnumerator()
21 | {
22 | return ((IEnumerable)this).GetEnumerator();
23 | }
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/src/NetTopologySuite.IO.ShapeFile/Handlers/PointMBRIterator.cs:
--------------------------------------------------------------------------------
1 | using NetTopologySuite.Geometries;
2 |
3 | namespace NetTopologySuite.IO.Handlers
4 | {
5 | internal class PointMBRIterator : ShapeMBREnumeratorBase
6 | {
7 | public PointMBRIterator(BigEndianBinaryReader reader)
8 | : base(reader)
9 | { }
10 |
11 | protected override Envelope ReadCurrentEnvelope(out int numOfBytesRead)
12 | {
13 | double x = Reader.ReadDouble();
14 | double y = Reader.ReadDouble();
15 |
16 | numOfBytesRead = 16;
17 |
18 | return new Envelope(x, x, y, y);
19 | }
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/src/NetTopologySuite.IO.ShapeFile/Handlers/ProbeLinearRing.cs:
--------------------------------------------------------------------------------
1 | using System.Collections.Generic;
2 | using NetTopologySuite.Geometries;
3 |
4 | namespace NetTopologySuite.IO.Handlers
5 | {
6 | ///
7 | /// Serves to probe linear rings
8 | ///
9 | /// Bruno.Labrecque@mddep.gouv.qc.ca
10 | internal class ProbeLinearRing : IComparer
11 | {
12 |
13 | internal enum Order
14 | {
15 | Ascending,
16 | Descending
17 | }
18 |
19 | internal ProbeLinearRing()
20 | :this(Order.Descending)
21 | {
22 | }
23 |
24 | internal ProbeLinearRing(Order order)
25 | {
26 | switch (order)
27 | {
28 | case Order.Ascending:
29 | _r1 = 1;
30 | _r2 = -1;
31 | break;
32 | case Order.Descending:
33 | _r1 = -1;
34 | _r2 = 1;
35 | break;
36 | }
37 | }
38 |
39 | private readonly int _r1;
40 |
41 | private readonly int _r2;
42 |
43 | public int Compare(LinearRing x, LinearRing y)
44 | {
45 | var pm = PrecisionModel.MostPrecise(x.PrecisionModel, y.PrecisionModel);
46 | var geometryFactory = new GeometryFactory(pm);
47 |
48 | var p1 = geometryFactory.CreatePolygon(x, null);
49 | var p2 = geometryFactory.CreatePolygon(y, null); ;
50 | if (p1.Area < p2.Area)
51 | return _r1;
52 | return p1.Area > p2.Area ? _r2 : 0;
53 | }
54 | }
55 | }
56 |
--------------------------------------------------------------------------------
/src/NetTopologySuite.IO.ShapeFile/Handlers/ShapeLocationInFileInfo.cs:
--------------------------------------------------------------------------------
1 | namespace NetTopologySuite.IO.Handlers
2 | {
3 | public class ShapeLocationInFileInfo
4 | {
5 | public ShapeLocationInFileInfo(long offsetFromStartOfFile, int shapeIndex)
6 | {
7 | OffsetFromStartOfFile = offsetFromStartOfFile;
8 | ShapeIndex = shapeIndex;
9 | }
10 |
11 | public long OffsetFromStartOfFile { get; private set; }
12 |
13 | ///
14 | /// Zero based shape index in file.
15 | ///
16 | public int ShapeIndex { get; private set; }
17 | }
18 | }
--------------------------------------------------------------------------------
/src/NetTopologySuite.IO.ShapeFile/Handlers/ShapeMBREnumerator.cs:
--------------------------------------------------------------------------------
1 | using System.Collections;
2 | using System.Collections.Generic;
3 |
4 | namespace NetTopologySuite.IO.Handlers
5 | {
6 | internal class ShapeMBREnumerator : IEnumerable
7 | {
8 | private readonly BigEndianBinaryReader m_Reader;
9 |
10 | public ShapeMBREnumerator(BigEndianBinaryReader reader)
11 | {
12 | m_Reader = reader;
13 | }
14 |
15 | public IEnumerator GetEnumerator()
16 | {
17 | return new ShapeMBRIterator(m_Reader);
18 | }
19 |
20 | IEnumerator IEnumerable.GetEnumerator()
21 | {
22 | return ((IEnumerable)this).GetEnumerator();
23 | }
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/src/NetTopologySuite.IO.ShapeFile/Handlers/ShapeMBREnumeratorBase.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.IO;
4 | using NetTopologySuite.Geometries;
5 |
6 | namespace NetTopologySuite.IO.Handlers
7 | {
8 | internal abstract class ShapeMBREnumeratorBase : IEnumerator
9 | {
10 | protected ShapeMBREnumeratorBase(BigEndianBinaryReader reader)
11 | {
12 | Reader = reader;
13 | Reset();
14 | }
15 |
16 | ~ShapeMBREnumeratorBase()
17 | {
18 | Reader.Close();
19 | }
20 |
21 | protected BigEndianBinaryReader Reader { get; private set; }
22 |
23 | public MBRInfo Current
24 | {
25 | get;
26 | private set;
27 | }
28 |
29 | public void Dispose()
30 | {
31 | Reader.Close();
32 | GC.SuppressFinalize(this);
33 | }
34 |
35 | object System.Collections.IEnumerator.Current => ((IEnumerator)this).Current;
36 |
37 | public bool MoveNext()
38 | {
39 | if (Reader.BaseStream.Position >= Reader.BaseStream.Length)
40 | {
41 | return false;
42 | }
43 |
44 | long currShapeOffset;
45 | int currShapeIndex;
46 | int currShapeLengthInWords;
47 |
48 | if (!ReadNextNonNullShape(out currShapeOffset, out currShapeIndex, out currShapeLengthInWords))
49 | {
50 | return false;
51 | }
52 |
53 | int numOfBytesRead;
54 |
55 | var currEnv = ReadCurrentEnvelope(out numOfBytesRead);
56 |
57 | Current = new MBRInfo(currEnv, currShapeOffset, currShapeIndex);
58 |
59 | // Take the total size of the shape, substract already read bytes and the size of the shape type.
60 | int numOfBytesToSkip = (currShapeLengthInWords * 2) - numOfBytesRead - 4;
61 |
62 | if (numOfBytesToSkip != 0)
63 | {
64 | Reader.BaseStream.Seek(numOfBytesToSkip, SeekOrigin.Current);
65 | }
66 |
67 | return true;
68 | }
69 |
70 | public void Reset()
71 | {
72 | Reader.BaseStream.Seek(100, SeekOrigin.Begin);
73 | }
74 |
75 | protected abstract Envelope ReadCurrentEnvelope(out int numOfBytesRead);
76 |
77 | ///
78 | /// Keep reading shapes until we find a non-null one.
79 | ///
80 | ///
81 | ///
82 | ///
83 | /// False if reached end of file without finding one, otherwise true.
84 | private bool ReadNextNonNullShape(out long CurrShapeOffset, out int CurrShapeIndex, out int CurrShapeLengthInWords)
85 | {
86 | int currShapeType;
87 |
88 | do
89 | {
90 | CurrShapeOffset = Reader.BaseStream.Position;
91 |
92 | // Read shape index - substract 1 for a 0-based index.
93 | CurrShapeIndex = Reader.ReadInt32BE() - 1;
94 |
95 | CurrShapeLengthInWords = Reader.ReadInt32BE();
96 |
97 | currShapeType = Reader.ReadInt32();
98 | } while (Reader.BaseStream.Position < Reader.BaseStream.Length &&
99 | currShapeType == (int)ShapeGeometryType.NullShape);
100 |
101 | return (Reader.BaseStream.Position < Reader.BaseStream.Length &&
102 | currShapeType != (int)ShapeGeometryType.NullShape);
103 | }
104 | }
105 | }
106 |
--------------------------------------------------------------------------------
/src/NetTopologySuite.IO.ShapeFile/Handlers/ShapeMBRIterator.cs:
--------------------------------------------------------------------------------
1 | using NetTopologySuite.Geometries;
2 |
3 | namespace NetTopologySuite.IO.Handlers
4 | {
5 | internal class ShapeMBRIterator : ShapeMBREnumeratorBase
6 | {
7 | public ShapeMBRIterator(BigEndianBinaryReader reader)
8 | : base(reader)
9 | { }
10 |
11 | protected override Envelope ReadCurrentEnvelope(out int numOfBytesRead)
12 | {
13 | double xMin = Reader.ReadDouble();
14 | double yMin = Reader.ReadDouble();
15 | double xMax = Reader.ReadDouble();
16 | double yMax = Reader.ReadDouble();
17 |
18 | numOfBytesRead = 8 * 4;
19 |
20 | return new Envelope(x1: xMin, x2: xMax, y1: yMin, y2: yMax);
21 | }
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/src/NetTopologySuite.IO.ShapeFile/NetTopologySuite.IO.ShapeFile.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | $(ProjectDir)..\
5 | netstandard2.0
6 | NetTopologySuite.IO
7 | true
8 |
9 |
10 |
11 | NetTopologySuite.IO.ShapeFile
12 |
13 |
14 |
15 | NetTopologySuite.IO.ShapeFile
16 | NTS - Topology Suite - ShapeFile IO Libraries
17 | NetTopologySuite - Team
18 | NetTopologySuite - Team
19 | LGPL-2.1-or-later
20 | This package contains several IO libraries to cope with spatial data from various sources.
21 | NTS;Shapefile
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
--------------------------------------------------------------------------------
/src/NetTopologySuite.IO.ShapeFile/ShapeFile.Extended/DbaseEnumerator.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections;
3 | using System.Collections.Generic;
4 | using NetTopologySuite.Features;
5 |
6 | namespace NetTopologySuite.IO.ShapeFile.Extended
7 | {
8 | internal class DbaseEnumerator : IEnumerator, IDisposable
9 | {
10 | private DbaseReader m_Reader;
11 | private int m_CurrentAttrTbleIndex;
12 |
13 | public DbaseEnumerator(DbaseReader reader)
14 | {
15 | m_Reader = reader.Clone();
16 | m_CurrentAttrTbleIndex = 0;
17 | }
18 |
19 | public IAttributesTable Current
20 | {
21 | get;
22 | private set;
23 | }
24 |
25 | public void Dispose()
26 | {
27 | m_Reader.Dispose();
28 | }
29 |
30 | object IEnumerator.Current => ((IEnumerator)this).Current;
31 |
32 | public bool MoveNext()
33 | {
34 | if (m_CurrentAttrTbleIndex == m_Reader.NumOfRecords)
35 | {
36 | return false;
37 | }
38 |
39 | Current = m_Reader.ReadEntry(m_CurrentAttrTbleIndex);
40 | m_CurrentAttrTbleIndex++;
41 |
42 | return true;
43 | }
44 |
45 | public void Reset()
46 | {
47 | var newReader = m_Reader.Clone();
48 | m_Reader.Dispose();
49 | m_Reader = newReader;
50 | m_CurrentAttrTbleIndex = 0;
51 | }
52 | }
53 | }
54 |
--------------------------------------------------------------------------------
/src/NetTopologySuite.IO.ShapeFile/ShapeFile.Extended/Entities/IShapefileFeature.cs:
--------------------------------------------------------------------------------
1 | using NetTopologySuite.Features;
2 |
3 | namespace NetTopologySuite.IO.ShapeFile.Extended.Entities
4 | {
5 | public interface IShapefileFeature : IFeature
6 | {
7 | long FeatureId { get; }
8 | }
9 | }
10 |
--------------------------------------------------------------------------------
/src/NetTopologySuite.IO.ShapeFile/ShapeFile.Extended/Entities/ShapefileFeature.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Threading;
3 | using System.Runtime.Serialization;
4 |
5 | using NetTopologySuite.Features;
6 | using NetTopologySuite.Geometries;
7 | using NetTopologySuite.IO.Handlers;
8 |
9 | namespace NetTopologySuite.IO.ShapeFile.Extended.Entities
10 | {
11 | [Serializable]
12 | internal class ShapefileFeature : IShapefileFeature, ISerializable
13 | {
14 |
15 | public ShapefileFeature(ShapeReader shapeReader, DbaseReader dbfReader, ShapeLocationInFileInfo shapeLocation, GeometryFactory geoFactory)
16 | {
17 | FeatureId = shapeLocation.ShapeIndex;
18 |
19 | // removed "lazy" evaluation to avoid dispose issues (see #27)
20 | var geom = shapeReader.ReadShapeAtOffset(shapeLocation.OffsetFromStartOfFile, geoFactory);
21 | var attributes = dbfReader.ReadEntry(shapeLocation.ShapeIndex);
22 |
23 | Geometry = geom;
24 | Attributes = attributes;
25 | }
26 |
27 | private ShapefileFeature(SerializationInfo info, StreamingContext context)
28 | {
29 | var geom = (Geometry)info.GetValue("Geometry", typeof(Geometry));
30 | var attributes = (IAttributesTable)info.GetValue("Attributes", typeof(IAttributesTable));
31 |
32 | FeatureId = info.GetInt64("FeatureId");
33 | Geometry = geom;
34 | Attributes = attributes;
35 | }
36 |
37 | public Geometry Geometry { get; }
38 |
39 | public Envelope BoundingBox => Geometry.EnvelopeInternal;
40 |
41 | public IAttributesTable Attributes { get; }
42 |
43 | public long FeatureId { get; }
44 |
45 | Geometry IFeature.Geometry
46 | {
47 | get => Geometry;
48 | set => throw new NotSupportedException("Setting geometry on a shapefile reader is not supported!");
49 | }
50 |
51 | Envelope IFeature.BoundingBox
52 | {
53 | get => BoundingBox;
54 | set => throw new InvalidOperationException("Setting BoundingBox not allowed for Shapefile feature");
55 | }
56 |
57 | IAttributesTable IFeature.Attributes
58 | {
59 | get => Attributes;
60 | set => throw new NotSupportedException("Setting attributes on a shapefile reader is not supported!");
61 | }
62 |
63 | void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
64 | {
65 | if (info is null)
66 | {
67 | throw new ArgumentNullException(nameof(info));
68 | }
69 |
70 | info.AddValue("Geometry", Geometry);
71 | info.AddValue("Attributes", Attributes);
72 | info.AddValue("FeatureId", FeatureId);
73 | }
74 | }
75 | }
76 |
--------------------------------------------------------------------------------
/src/NetTopologySuite.IO.ShapeFile/ShapeFileConstants.cs:
--------------------------------------------------------------------------------
1 | namespace NetTopologySuite.IO
2 | {
3 | ///
4 | /// Shapefile specific constants
5 | ///
6 | internal class ShapeFileConstants
7 | {
8 | ///
9 | /// Every value less that this is considered as not set.
10 | ///
11 | internal const double NoDataBorder = -10e38d;
12 |
13 | ///
14 | /// A value that represents an unset value
15 | ///
16 | internal const double NoDataValue = -10e38d - 1;
17 | }
18 | }
--------------------------------------------------------------------------------
/src/NetTopologySuite.IO.ShapeFile/ShapeGeometryType.cs:
--------------------------------------------------------------------------------
1 | namespace NetTopologySuite.IO
2 | {
3 | ///
4 | /// Feature type enumeration
5 | ///
6 | public enum ShapeGeometryType
7 | {
8 | ///
9 | /// Null Shape
10 | ///
11 | NullShape = 0,
12 |
13 | ///
14 | /// Point
15 | ///
16 | Point = 1,
17 |
18 | ///
19 | /// LineString
20 | ///
21 | LineString = 3,
22 |
23 | ///
24 | /// Polygon
25 | ///
26 | Polygon = 5,
27 |
28 | ///
29 | /// MultiPoint
30 | ///
31 | MultiPoint = 8,
32 |
33 | ///
34 | /// PointMZ
35 | ///
36 | PointZM = 11,
37 |
38 | ///
39 | /// PolyLineMZ
40 | ///
41 | LineStringZM = 13,
42 |
43 | ///
44 | /// PolygonMZ
45 | ///
46 | PolygonZM = 15,
47 |
48 | ///
49 | /// MultiPointMZ
50 | ///
51 | MultiPointZM = 18,
52 |
53 | ///
54 | /// PointM
55 | ///
56 | PointM = 21,
57 |
58 | ///
59 | /// LineStringM
60 | ///
61 | LineStringM = 23,
62 |
63 | ///
64 | /// PolygonM
65 | ///
66 | PolygonM = 25,
67 |
68 | ///
69 | /// MultiPointM
70 | ///
71 | MultiPointM = 28,
72 |
73 | ///
74 | /// MultiPatch
75 | ///
76 | MultiPatch = 31
77 |
78 | #if !GeoTools
79 | // These values are not officially in the shapefile spec
80 | // http://www.esri.com/library/whitepapers/pdfs/shapefile.pdf
81 |
82 | ,
83 | ///
84 | /// PointZ
85 | ///
86 | PointZ = 9,
87 |
88 | ///
89 | /// LineStringZ
90 | ///
91 | LineStringZ = 10,
92 |
93 | ///
94 | /// PolygonZ
95 | ///
96 | PolygonZ = 19,
97 |
98 | ///
99 | /// MultiPointZ
100 | ///
101 | MultiPointZ = 20
102 | #endif
103 | }
104 | }
105 |
--------------------------------------------------------------------------------
/src/NetTopologySuite.IO.ShapeFile/Shapefile.FullFat.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.ComponentModel;
3 | using System.Text;
4 | using System.Data;
5 | using NetTopologySuite.Geometries;
6 |
7 | namespace NetTopologySuite.IO
8 | {
9 | public partial class Shapefile
10 | {
11 | ///
12 | /// Creates a DataTable representing the information in a shape file.
13 | ///
14 | /// The filename (minus the . and extension) to read.
15 | /// The name to give to the table.
16 | /// The geometry factory to use when creating the objects.
17 | /// The encoding to use when writing data
18 | /// DataTable representing the data
19 | public static DataTable CreateDataTable(string filename, string tableName, GeometryFactory geometryFactory, Encoding encoding = null)
20 | {
21 | if (filename == null)
22 | throw new ArgumentNullException("filename");
23 | if (tableName == null)
24 | throw new ArgumentNullException("tableName");
25 | if (geometryFactory == null)
26 | throw new ArgumentNullException("geometryFactory");
27 |
28 | var shpfileDataReader = new ShapefileDataReader(filename, geometryFactory, encoding);
29 | var table = new DataTable(tableName);
30 |
31 | // use ICustomTypeDescriptor to get the properies/ fields. This way we can get the
32 | // length of the dbase char fields. Because the dbase char field is translated into a string
33 | // property, we lost the length of the field. We need to know the length of the
34 | // field when creating the table in the database.
35 |
36 | var enumerator = shpfileDataReader.GetEnumerator();
37 | bool moreRecords = enumerator.MoveNext();
38 | var typeDescriptor = (ICustomTypeDescriptor)enumerator.Current;
39 | foreach (PropertyDescriptor property in typeDescriptor.GetProperties())
40 | {
41 | var column = (ColumnStructure)property;
42 | var fieldType = column.PropertyType;
43 | var datacolumn = new DataColumn(column.Name, fieldType);
44 | if (fieldType == typeof(string))
45 | // use MaxLength to pass the length of the field in the dbase file
46 | datacolumn.MaxLength = column.Length;
47 | table.Columns.Add(datacolumn);
48 | }
49 |
50 | // add the rows - need a do-while loop because we read one row in order to determine the fields
51 | int iRecordCount = 0;
52 | table.BeginLoadData();
53 | object[] values = new object[shpfileDataReader.FieldCount];
54 | do
55 | {
56 | iRecordCount++;
57 | shpfileDataReader.GetValues(values);
58 | table.LoadDataRow(values, true);
59 | moreRecords = enumerator.MoveNext();
60 | }
61 | while (moreRecords);
62 | table.EndLoadData();
63 |
64 | return table;
65 | }
66 |
67 | }
68 | }
69 |
--------------------------------------------------------------------------------
/src/NetTopologySuite.IO.ShapeFile/ShapefileDataReader.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections;
3 | using System.IO;
4 | using System.Text;
5 | using NetTopologySuite.Geometries;
6 | using NetTopologySuite.IO.Streams;
7 |
8 | namespace NetTopologySuite.IO
9 | {
10 | ///
11 | /// Creates a IDataReader that can be used to enumerate through an ESRI shape file.
12 | ///
13 | ///
14 | /// To create a ShapefileDataReader, use the static methods on the Shapefile class.
15 | ///
16 | public partial class ShapefileDataReader : IDisposable
17 | {
18 | bool _open = false;
19 | readonly DbaseFieldDescriptor[] _dbaseFields;
20 | readonly DbaseFileReader _dbfReader;
21 | readonly ShapefileReader _shpReader;
22 | readonly IEnumerator _dbfEnumerator;
23 | readonly IEnumerator _shpEnumerator;
24 | readonly ShapefileHeader _shpHeader;
25 | readonly DbaseFileHeader _dbfHeader;
26 | readonly int _recordCount = 0;
27 |
28 | ///
29 | /// Initializes a new instance of the ShapefileDataReader class.
30 | ///
31 | /// The shapefile to read (minus the .shp extension)
32 | ///The GeometryFactory to use.
33 | public ShapefileDataReader(string filename, GeometryFactory geometryFactory)
34 | :this(filename, geometryFactory, null)
35 | {
36 | }
37 |
38 | ///
39 | /// Initializes a new instance of the ShapefileDataReader class.
40 | ///
41 | /// The shapefile to read (minus the .shp extension)
42 | /// The GeometryFactory to use.
43 | /// The encoding to use for reading the attribute data
44 | public ShapefileDataReader(string filename, GeometryFactory geometryFactory, Encoding encoding)
45 | {
46 | if (string.IsNullOrEmpty(filename))
47 | throw new ArgumentNullException("filename");
48 | if (geometryFactory == null)
49 | throw new ArgumentNullException("geometryFactory");
50 |
51 | _open = true;
52 |
53 | string dbfFile = Path.ChangeExtension(filename, "dbf");
54 | _dbfReader = encoding != null
55 | ? new DbaseFileReader(dbfFile, encoding)
56 | : new DbaseFileReader(dbfFile);
57 |
58 | string shpFile = Path.ChangeExtension(filename, "shp");
59 | _shpReader = new ShapefileReader(shpFile, geometryFactory);
60 |
61 | _dbfHeader = _dbfReader.GetHeader();
62 | _recordCount = _dbfHeader.NumRecords;
63 |
64 | // copy dbase fields to our own array.
65 | //Insert into the first position, the shape column
66 | _dbaseFields = new DbaseFieldDescriptor[_dbfHeader.Fields.Length + 1];
67 | _dbaseFields[0] = DbaseFieldDescriptor.ShapeField();
68 | for (int i = 0; i < _dbfHeader.Fields.Length; i++)
69 | _dbaseFields[i + 1] = _dbfHeader.Fields[i];
70 |
71 | _shpHeader = _shpReader.Header;
72 | _dbfEnumerator = _dbfReader.GetEnumerator();
73 | _shpEnumerator = _shpReader.GetEnumerator();
74 | _moreRecords = true;
75 | }
76 |
77 | public ShapefileDataReader(IStreamProviderRegistry streamProviderRegistry, GeometryFactory geometryFactory)
78 | {
79 | if (streamProviderRegistry==null)
80 | throw new ArgumentNullException("streamProviderRegistry");
81 | if (geometryFactory == null)
82 | throw new ArgumentNullException("geometryFactory");
83 | _open = true;
84 |
85 | _dbfReader = new DbaseFileReader(streamProviderRegistry);
86 | _shpReader = new ShapefileReader(streamProviderRegistry, geometryFactory);
87 |
88 | _dbfHeader = _dbfReader.GetHeader();
89 | _recordCount = _dbfHeader.NumRecords;
90 |
91 | // copy dbase fields to our own array. Insert into the first position, the shape column
92 | _dbaseFields = new DbaseFieldDescriptor[_dbfHeader.Fields.Length + 1];
93 | _dbaseFields[0] = DbaseFieldDescriptor.ShapeField();
94 | for (int i = 0; i < _dbfHeader.Fields.Length; i++)
95 | _dbaseFields[i + 1] = _dbfHeader.Fields[i];
96 |
97 | _shpHeader = _shpReader.Header;
98 | _dbfEnumerator = _dbfReader.GetEnumerator();
99 | _shpEnumerator = _shpReader.GetEnumerator();
100 | _moreRecords = true;
101 | }
102 |
103 | bool _moreRecords = false;
104 |
105 | Geometry geometry = null;
106 |
107 | public void Reset()
108 | {
109 | _dbfEnumerator.Reset();
110 | _shpEnumerator.Reset();
111 | }
112 |
113 | ///
114 | ///
115 | ///
116 | public void Dispose()
117 | {
118 | if (!IsClosed)
119 | Close();
120 | ((IDisposable)_shpEnumerator).Dispose();
121 | ((IDisposable)_dbfEnumerator).Dispose();
122 | }
123 |
124 | ///
125 | /// Gets a value indicating whether the data reader is closed.
126 | ///
127 | /// true if the data reader is closed; otherwise, false.
128 | /// IsClosed and RecordsAffected are the only properties that you can call after the IDataReader is closed.
129 | public bool IsClosed => !_open;
130 |
131 | ///
132 | /// Closes the IDataReader 0bject.
133 | ///
134 | public void Close()
135 | {
136 | _open = false;
137 | }
138 | }
139 | }
140 |
--------------------------------------------------------------------------------
/src/NetTopologySuite.IO.ShapeFile/ShapefileException.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Runtime.Serialization;
3 |
4 | namespace NetTopologySuite.IO
5 | {
6 | ///
7 | /// The exception that is thrown when a non-fatal application error occurs related to Topology functionality.
8 | ///
9 | public class ShapefileException : ApplicationException
10 | {
11 | ///
12 | /// Initializes a new instance of the ShapefileException class.
13 | ///
14 | public ShapefileException() { }
15 |
16 | ///
17 | /// Initializes a new instance of the ShapefileException class with a specified error message.
18 | ///
19 | /// A message that describes the error.
20 | public ShapefileException(string message) : base(message) { }
21 |
22 | ///
23 | /// Initializes a new instance of the ApplicationException class with serialized data.
24 | ///
25 | /// The object that holds the serialized object data.
26 | /// The contextual information about the source or destination.
27 | public ShapefileException(SerializationInfo info,StreamingContext context) : base(info, context) { }
28 |
29 | ///
30 | /// Initializes a new instance of the ApplicationException class with a specified error message and a reference to the inner exception that is the cause of this exception.
31 | ///
32 | /// The error message that explains the reason for the exception.
33 | /// The exception that is the cause of the current exception. If the innerException parameter is not a null reference, the current exception is raised in a catch block that handles the inner exception
34 | public ShapefileException(string message, Exception innerException) : base(message, innerException) { }
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/src/NetTopologySuite.IO.ShapeFile/ShapefileHeader.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Diagnostics;
3 | using NetTopologySuite.Geometries;
4 | using NetTopologySuite.Utilities;
5 |
6 | namespace NetTopologySuite.IO
7 | {
8 | ///
9 | /// Class that represents a shape file header record.
10 | ///
11 | public class ShapefileHeader
12 | {
13 | private int _fileCode = Shapefile.ShapefileId;
14 | private int _fileLength = -1;
15 | private int _version = 1000;
16 | private ShapeGeometryType _shapeType = ShapeGeometryType.NullShape;
17 | private Envelope _bounds;
18 |
19 | ///
20 | /// Initializes a new instance of the ShapefileHeader class with values read in from the stream.
21 | ///
22 | /// Reads the header information from the stream.
23 | /// BigEndianBinaryReader stream to the shapefile.
24 | public ShapefileHeader(BigEndianBinaryReader shpBinaryReader)
25 | {
26 | if (shpBinaryReader == null)
27 | throw new ArgumentNullException("shpBinaryReader");
28 |
29 | _fileCode = shpBinaryReader.ReadInt32BE();
30 | if (_fileCode != Shapefile.ShapefileId)
31 | throw new ShapefileException("The first four bytes of this file indicate this is not a shape file.");
32 |
33 | // skip 5 unsed bytes
34 | shpBinaryReader.ReadInt32BE();
35 | shpBinaryReader.ReadInt32BE();
36 | shpBinaryReader.ReadInt32BE();
37 | shpBinaryReader.ReadInt32BE();
38 | shpBinaryReader.ReadInt32BE();
39 |
40 | _fileLength = shpBinaryReader.ReadInt32BE();
41 |
42 | _version = shpBinaryReader.ReadInt32();
43 | Debug.Assert(_version == 1000, "Shapefile version", string.Format("Expecting only one version (1000), but got {0}",_version));
44 | int shapeType = shpBinaryReader.ReadInt32();
45 | _shapeType = (ShapeGeometryType) EnumUtility.Parse(typeof(ShapeGeometryType), shapeType.ToString());
46 |
47 | //read in and store the bounding box
48 | double[] coords = new double[4];
49 | for (int i = 0; i < 4; i++)
50 | coords[i] = shpBinaryReader.ReadDouble();
51 | _bounds = new Envelope(coords[0], coords[2], coords[1], coords[3]);
52 |
53 | // skip z and m bounding boxes.
54 | for (int i = 0; i < 4; i++)
55 | shpBinaryReader.ReadDouble();
56 | }
57 |
58 | ///
59 | /// Initializes a new instance of the ShapefileHeader class.
60 | ///
61 | public ShapefileHeader() { }
62 |
63 | ///
64 | /// Gets and sets the bounds of the shape file.
65 | ///
66 | public Envelope Bounds
67 | {
68 | get
69 | {
70 | return _bounds;
71 | }
72 | set
73 | {
74 | _bounds = value;
75 | }
76 | }
77 |
78 | ///
79 | /// Gets and sets the shape file type i.e. polygon, point etc...
80 | ///
81 | public ShapeGeometryType ShapeType
82 | {
83 | get
84 | {
85 | return _shapeType;
86 | }
87 | set
88 | {
89 | _shapeType = value;
90 | }
91 | }
92 |
93 | ///
94 | /// Gets and sets the shapefile version.
95 | ///
96 | public int Version
97 | {
98 | get
99 | {
100 | return _version;
101 | }
102 | set
103 | {
104 | _version = value;
105 | }
106 | }
107 |
108 | ///
109 | /// Gets and sets the length of the shape file in words.
110 | ///
111 | public int FileLength
112 | {
113 | get
114 | {
115 | return _fileLength;
116 | }
117 | set
118 | {
119 | _fileLength = value;
120 | }
121 | }
122 |
123 | ///
124 | /// Writes a shapefile header to the given stream;
125 | ///
126 | /// The binary writer to use.
127 | public void Write(BigEndianBinaryWriter file)
128 | {
129 | if (file == null)
130 | throw new ArgumentNullException("file");
131 | if (_fileLength==-1)
132 | throw new InvalidOperationException("The header properties need to be set before writing the header record.");
133 | int pos = 0;
134 | file.WriteIntBE(_fileCode);
135 | pos += 4;
136 | for (int i = 0; i < 5; i++)
137 | {
138 | file.WriteIntBE(0);//Skip unused part of header
139 | pos += 4;
140 | }
141 | file.WriteIntBE(_fileLength);
142 | pos += 4;
143 | file.Write(_version);
144 | pos += 4;
145 |
146 | string format = EnumUtility.Format(typeof(ShapeGeometryType), _shapeType, "d");
147 | file.Write(int.Parse(format));
148 |
149 | pos += 4;
150 | // Write the bounding box
151 | file.Write(_bounds.MinX);
152 | file.Write(_bounds.MinY);
153 | file.Write(_bounds.MaxX);
154 | file.Write(_bounds.MaxY);
155 | pos += 8 * 4;
156 |
157 | // Skip remaining unused bytes
158 | for (int i = 0; i < 4; i++)
159 | {
160 | file.Write(0.0); // Skip unused part of header
161 | pos += 8;
162 | }
163 | }
164 | }
165 | }
166 |
--------------------------------------------------------------------------------
/src/NetTopologySuite.IO.ShapeFile/ShapefileReader.FullFat.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using NetTopologySuite.Geometries;
3 | using NetTopologySuite.IO.Handlers;
4 | using NetTopologySuite.IO.Streams;
5 |
6 | namespace NetTopologySuite.IO
7 | {
8 | public partial class ShapefileReader
9 | {
10 | ///
11 | /// Initializes a new instance of the Shapefile class with the given parameters.
12 | ///
13 | /// The filename of the shape file to read (with .shp).
14 | /// The GeometryFactory to use when creating Geometry objects.
15 | public ShapefileReader(string filename, GeometryFactory geometryFactory)
16 | : this(new ShapefileStreamProviderRegistry(filename, true), geometryFactory)
17 | {
18 | }
19 |
20 | public ShapefileReader(IStreamProviderRegistry shapeStreamProviderRegistry, GeometryFactory geometryFactory)
21 | {
22 | if (shapeStreamProviderRegistry == null)
23 | throw new ArgumentNullException("shapeStreamProviderRegistry");
24 | if (geometryFactory == null)
25 | throw new ArgumentNullException("geometryFactory");
26 |
27 | _shapeStreamProviderRegistry = shapeStreamProviderRegistry;
28 | _geometryFactory = geometryFactory;
29 |
30 | // read header information. note, we open the file, read the header information and then
31 | // close the file. This means the file is not opened again until GetEnumerator() is requested.
32 | // For each call to GetEnumerator() a new BinaryReader is created.
33 | using (var stream = shapeStreamProviderRegistry[StreamTypes.Shape].OpenRead())
34 | {
35 | using (var shpBinaryReader = new BigEndianBinaryReader(stream))
36 | {
37 | _mainHeader = new ShapefileHeader(shpBinaryReader);
38 | }
39 | }
40 | }
41 |
42 | #region Nested type: ShapefileEnumerator
43 |
44 | ///
45 | /// Summary description for ShapefileEnumerator.
46 | ///
47 | private partial class ShapefileEnumerator
48 | {
49 | ///
50 | /// Initializes a new instance of the class.
51 | ///
52 | ///
53 | public ShapefileEnumerator(ShapefileReader shapefile)
54 | {
55 | _parent = shapefile;
56 |
57 | // create a file stream for each enumerator that is given out. This allows the same file
58 | // to have one or more enumerator. If we used the parents stream - than only one IEnumerator
59 | // could be given out.
60 | var stream = shapefile._shapeStreamProviderRegistry[StreamTypes.Shape].OpenRead();
61 | var indexStreamProvider = shapefile._shapeStreamProviderRegistry[StreamTypes.Index];
62 | var indexStream = indexStreamProvider != null ? indexStreamProvider.OpenRead() : null;
63 |
64 | _shpBinaryReader = new BigEndianBinaryReader(stream);
65 | if (indexStream != null) _idxBinaryReader = new BigEndianBinaryReader(indexStream);
66 |
67 | // skip header - since parent has already read this.
68 | _shpBinaryReader.ReadBytes(100);
69 | if (_idxBinaryReader != null) _idxBinaryReader.ReadBytes(100);
70 |
71 | var type = _parent._mainHeader.ShapeType;
72 | _handler = Shapefile.GetShapeHandler(type);
73 | if (_handler == null)
74 | throw new NotSupportedException("Unsuported shape type:" + type);
75 | _handler.GeometryInstantiationErrorHandling = GeometryInstantiationErrorHandling;
76 | }
77 |
78 | ///
79 | /// Gets or sets a way to handle geometry instantiation problems
80 | ///
81 | public GeometryInstantiationErrorHandlingOption GeometryInstantiationErrorHandling { get; set; }
82 |
83 | #region IDisposable Members
84 |
85 | ///
86 | /// Performs application-defined tasks associated with freeing,
87 | /// releasing, or resetting unmanaged resources.
88 | ///
89 | public void Dispose()
90 | {
91 | _shpBinaryReader.Close();
92 | if (_idxBinaryReader != null) _idxBinaryReader.Close();
93 | }
94 |
95 | #endregion
96 | }
97 |
98 | #endregion
99 | }
100 | }
101 |
--------------------------------------------------------------------------------
/src/NetTopologySuite.IO.ShapeFile/Streams/ExternallyManagedStreamProvider.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.IO;
4 | using System.Text;
5 |
6 | namespace NetTopologySuite.IO.Streams
7 | {
8 | ///
9 | /// A stream provider that provides s who are managed by the application.
10 | ///
11 | public class ExternallyManagedStreamProvider : IStreamProvider
12 | {
13 | ///
14 | /// Creates an instance of this class
15 | ///
16 | /// The kind of stream
17 | /// A managed by the application
18 | public ExternallyManagedStreamProvider(string kind, Stream stream)
19 | {
20 | Kind = kind;
21 | Stream = stream;
22 | }
23 |
24 | ///
25 | /// Gets a value indicating that the underlying stream is read-only
26 | ///
27 | public bool UnderlyingStreamIsReadonly => !Stream.CanWrite;
28 |
29 | protected Stream Stream { get; private set; }
30 |
31 | ///
32 | /// Function to return a Stream of the bytes
33 | ///
34 | /// An opened stream
35 | public Stream OpenRead()
36 | {
37 | return new NonDisposingStream(Stream);
38 | }
39 |
40 | ///
41 | /// Function to open the underlying stream for writing purposes
42 | ///
43 | /// If is not true
44 | /// this method shall fail
45 | /// An opened stream
46 | /// Thrown if is true or the underlying stream doesn't support seeking
47 | public Stream OpenWrite(bool truncate)
48 | {
49 | if (UnderlyingStreamIsReadonly)
50 | throw new InvalidOperationException();
51 |
52 | if (truncate) {
53 | if (!Stream.CanSeek)
54 | {
55 | throw new InvalidOperationException("The underlying stream doesn't support seeking! You are unable to truncate the data.");
56 | }
57 | Stream.SetLength(0);
58 | }
59 |
60 | return new NonDisposingStream(Stream);
61 | }
62 |
63 | ///
64 | /// Gets a value indicating the kind of stream
65 | ///
66 | public string Kind { get; private set; }
67 |
68 |
69 | private class NonDisposingStream : Stream
70 | {
71 | public NonDisposingStream(Stream stream)
72 | {
73 | Stream = stream;
74 | }
75 |
76 | protected override void Dispose(bool disposing)
77 | {
78 | Stream = null;
79 | }
80 |
81 | protected Stream Stream { get; private set; }
82 |
83 | public override bool CanRead => Stream.CanRead;
84 |
85 | public override bool CanSeek => Stream.CanSeek;
86 |
87 | public override bool CanWrite => Stream.CanWrite;
88 |
89 | public override void Flush()
90 | {
91 | Stream.Flush();
92 | }
93 |
94 | public override long Length => Stream.Length;
95 |
96 | public override long Position { get => Stream.Position; set => Stream.Position = value; }
97 |
98 | public override int Read(byte[] buffer, int offset, int count)
99 | {
100 | return Stream.Read(buffer, offset, count);
101 | }
102 |
103 | public override long Seek(long offset, SeekOrigin origin)
104 | {
105 | return Stream.Seek(offset, origin);
106 | }
107 |
108 | public override void SetLength(long value)
109 | {
110 | Stream.SetLength(value);
111 | }
112 |
113 | public override void Write(byte[] buffer, int offset, int count)
114 | {
115 | Stream.Write(buffer, offset, count);
116 | }
117 | }
118 | }
119 | }
120 |
--------------------------------------------------------------------------------
/src/NetTopologySuite.IO.ShapeFile/Streams/FileStreamProvider.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.IO;
3 |
4 | namespace NetTopologySuite.IO.Streams
5 | {
6 | ///
7 | /// An implementation of that gives acces to file streams
8 | ///
9 | public class FileStreamProvider : IStreamProvider
10 | {
11 | ///
12 | /// Creates an instance of this class
13 | ///
14 | /// The kind of stream
15 | /// The path to the stream
16 | /// A value indicating if the provided path is to be validated
17 | public FileStreamProvider(string kind, string path, bool validatePath = false)
18 | {
19 | if (path == null)
20 | throw new ArgumentNullException("path");
21 |
22 | if (string.IsNullOrWhiteSpace(path))
23 | throw new ArgumentException("Invalid Path", "path");
24 |
25 | if (validatePath && !File.Exists(path))
26 | throw new FileNotFoundException(path);
27 |
28 | Kind = kind;
29 | Path = path;
30 | }
31 |
32 | ///
33 | /// Gets a value indicating the path to the file
34 | ///
35 | public string Path { get; private set; }
36 |
37 | ///
38 | /// Gets a value indicating that the underlying stream is read-only
39 | ///
40 | public bool UnderlyingStreamIsReadonly => false;
41 |
42 | ///
43 | /// Function to open the underlying stream for reading purposes
44 | ///
45 | /// An opened stream
46 | public Stream OpenRead()
47 | {
48 | if (!File.Exists(Path)) return null;
49 | return File.Open(Path, FileMode.Open, FileAccess.Read, FileShare.Read);
50 | }
51 |
52 | ///
53 | /// Function to open the underlying stream for writing purposes
54 | ///
55 | /// If is true this method shall fail
56 | /// An opened stream
57 | public Stream OpenWrite(bool truncate)
58 | {
59 | if (truncate)
60 | {
61 | return File.Open(Path, FileMode.Create, FileAccess.Write, FileShare.None);
62 | }
63 | return File.Open(Path, FileMode.OpenOrCreate, FileAccess.Write, FileShare.ReadWrite); //jd: I would like to use FileShare.None however the GeoTools shapefilewriter writes a dummy file while holding an existing handle
64 | }
65 |
66 | ///
67 | /// Gets a value indicating the kind of stream
68 | ///
69 | public string Kind { get; private set; }
70 | }
71 | }
72 |
--------------------------------------------------------------------------------
/src/NetTopologySuite.IO.ShapeFile/Streams/IStreamProvider.cs:
--------------------------------------------------------------------------------
1 |
2 | using System.IO;
3 |
4 | namespace NetTopologySuite.IO.Streams
5 | {
6 | ///
7 | /// Interface for stream provider
8 | ///
9 | public interface IStreamProvider
10 | {
11 | ///
12 | /// Gets a value indicating that the underlying stream is read-only
13 | ///
14 | bool UnderlyingStreamIsReadonly { get; }
15 |
16 | ///
17 | /// Function to open the underlying stream for reading purposes
18 | ///
19 | /// An opened stream
20 | Stream OpenRead();
21 |
22 | ///
23 | /// Function to open the underlying stream for writing purposes
24 | ///
25 | /// If is true
26 | /// this method shall fail
27 | /// An opened stream
28 | Stream OpenWrite(bool truncate);
29 |
30 | ///
31 | /// Gets a value indicating the kind of stream
32 | ///
33 | string Kind { get; }
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/src/NetTopologySuite.IO.ShapeFile/Streams/IStreamProviderRegistry.cs:
--------------------------------------------------------------------------------
1 | namespace NetTopologySuite.IO.Streams
2 | {
3 | ///
4 | /// Interface for a registry of stream providers that -altogether- form a spatial dataset.
5 | ///
6 | public interface IStreamProviderRegistry
7 | {
8 | ///
9 | /// Indexer for a stream provider
10 | ///
11 | /// The stream type
12 | /// A stream provider
13 | ///
14 | /// If no stream provider for the requested can be provided, null is to be returned.
15 | /// Do not throw an exception!
16 | ///
17 | IStreamProvider this[string streamType] { get; }
18 | }
19 | }
--------------------------------------------------------------------------------
/test/Directory.Build.props:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
--------------------------------------------------------------------------------
/test/NetTopologySuite.IO.ShapeFile.Test/CommonHelpers.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.IO;
3 |
4 | internal sealed class CommonHelpers
5 | {
6 | public static readonly string TestShapefilesDirectory = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "TestShapefiles");
7 | }
8 |
--------------------------------------------------------------------------------
/test/NetTopologySuite.IO.ShapeFile.Test/DbfDateTest.cs:
--------------------------------------------------------------------------------
1 | using NUnit.Framework;
2 | using System;
3 | using System.Collections;
4 | using System.IO;
5 |
6 | namespace NetTopologySuite.IO.ShapeFile.Test
7 | {
8 | ///
9 | ///
10 | ///
11 | [TestFixture]
12 | public class DbfDateTest
13 | {
14 | ///
15 | /// Initializes a new instance of the class.
16 | ///
17 | public DbfDateTest()
18 | {
19 |
20 | }
21 |
22 | ///
23 | ///
24 | ///
25 | [Test]
26 | public void ReadDbfDate()
27 | {
28 | string file = Path.Combine(CommonHelpers.TestShapefilesDirectory, "date.dbf");
29 |
30 | if (!File.Exists(file))
31 | throw new FileNotFoundException("file not found at " + Path.GetDirectoryName(file));
32 |
33 | var reader = new DbaseFileReader(file);
34 | var header = reader.GetHeader();
35 | var ienum = reader.GetEnumerator();
36 | ienum.MoveNext();
37 | var items = ienum.Current as ArrayList;
38 |
39 | Assert.IsNotNull(items);
40 | Assert.AreEqual(2, items.Count);
41 |
42 | foreach (object item in items)
43 | Assert.IsNotNull(item);
44 |
45 | var date = (DateTime)items[1];
46 |
47 | Assert.AreEqual(10, date.Day);
48 | Assert.AreEqual(3, date.Month);
49 | Assert.AreEqual(2006, date.Year);
50 | }
51 | }
52 | }
53 |
--------------------------------------------------------------------------------
/test/NetTopologySuite.IO.ShapeFile.Test/Geometries/MultiPointSamples.cs:
--------------------------------------------------------------------------------
1 | using NetTopologySuite.Geometries;
2 | using System;
3 | using NetTopologySuite.Operation.Buffer;
4 |
5 | namespace NetTopologySuite.IO.ShapeFile.Test.Geometries
6 | {
7 | ///
8 | ///
9 | ///
10 | public class MultiPointSamples
11 | {
12 | private MultiPoint multiPoint = null;
13 |
14 | protected GeometryFactory Factory { get; private set; }
15 |
16 | protected WKTReader Reader { get; private set; }
17 |
18 | ///
19 | ///
20 | ///
21 | public MultiPointSamples() : base()
22 | {
23 | this.Factory = new GeometryFactory();
24 | this.Reader = new WKTReader();
25 |
26 | var coordinates = new Coordinate[]
27 | {
28 | new Coordinate(100,100),
29 | new Coordinate(200,200),
30 | new Coordinate(300,300),
31 | new Coordinate(400,400),
32 | new Coordinate(500,500),
33 | };
34 | multiPoint = Factory.CreateMultiPointFromCoords(coordinates);
35 | }
36 |
37 | ///
38 | ///
39 | ///
40 | public void Start()
41 | {
42 | try
43 | {
44 | Write(multiPoint.Area);
45 | Write(multiPoint.Boundary);
46 | Write(multiPoint.BoundaryDimension);
47 | Write(multiPoint.Centroid);
48 | Write(multiPoint.Coordinate);
49 | Write(multiPoint.Coordinates);
50 | Write(multiPoint.Dimension);
51 | Write(multiPoint.Envelope);
52 | Write(multiPoint.EnvelopeInternal);
53 | Write(multiPoint.Geometries.Length);
54 | Write(multiPoint.InteriorPoint);
55 | Write(multiPoint.IsEmpty);
56 | Write(multiPoint.IsSimple);
57 | Write(multiPoint.IsValid);
58 | Write(multiPoint.Length);
59 | Write(multiPoint.NumGeometries);
60 | Write(multiPoint.NumPoints);
61 |
62 | Write(multiPoint.Buffer(10));
63 | Write(multiPoint.Buffer(10, new BufferParameters {EndCapStyle = EndCapStyle.Flat }));
64 | Write(multiPoint.Buffer(10, new BufferParameters { EndCapStyle = EndCapStyle.Square }));
65 | Write(multiPoint.Buffer(10, 20));
66 | Write(multiPoint.Buffer(10, new BufferParameters(20) { EndCapStyle = EndCapStyle.Flat }));
67 | Write(multiPoint.Buffer(10, new BufferParameters(20) { EndCapStyle = EndCapStyle.Square }));
68 | Write(multiPoint.ConvexHull());
69 |
70 | byte[] bytes = multiPoint.AsBinary();
71 | var test1 = new WKBReader().Read(bytes);
72 | Write(test1.ToString());
73 |
74 | bytes = new GDBWriter().Write(multiPoint);
75 | test1 = new GDBReader().Read(bytes);
76 | Write(test1.ToString());
77 | }
78 | catch (Exception ex)
79 | {
80 | throw ex;
81 | }
82 | }
83 |
84 | protected void Write(object o)
85 | {
86 | Console.WriteLine(o.ToString());
87 | }
88 |
89 | protected void Write(string s)
90 | {
91 | Console.WriteLine(s);
92 | }
93 | }
94 | }
95 |
--------------------------------------------------------------------------------
/test/NetTopologySuite.IO.ShapeFile.Test/Geometries/PointSamples.cs:
--------------------------------------------------------------------------------
1 | using NetTopologySuite.Geometries;
2 | using System;
3 | using NetTopologySuite.Operation.Buffer;
4 |
5 | namespace NetTopologySuite.IO.ShapeFile.Test.Geometries
6 | {
7 | ///
8 | ///
9 | ///
10 | public class PointSamples
11 | {
12 | protected GeometryFactory Factory { get; private set; }
13 |
14 | protected WKTReader Reader { get; private set; }
15 | private Point point = null;
16 |
17 | ///
18 | ///
19 | ///
20 | public PointSamples()
21 | {
22 | this.Factory = new GeometryFactory();
23 | this.Reader = new WKTReader();
24 |
25 | point = Factory.CreatePoint(new Coordinate(100, 100));
26 | }
27 |
28 | ///
29 | ///
30 | ///
31 | public void Start()
32 | {
33 | var pInterior = Factory.CreatePoint(new Coordinate(100, 100));
34 | var pExterior = Factory.CreatePoint(new Coordinate(100, 101));
35 |
36 | try
37 | {
38 | Write(point.Area);
39 | Write(point.Boundary);
40 | Write(point.BoundaryDimension);
41 | Write(point.Centroid);
42 | Write(point.Coordinate);
43 | Write(point.Coordinates);
44 | Write(point.CoordinateSequence);
45 | Write(point.Dimension);
46 | Write(point.Envelope);
47 | Write(point.EnvelopeInternal);
48 | Write(point.Factory);
49 | Write(point.InteriorPoint);
50 | Write(point.IsEmpty);
51 | Write(point.IsSimple);
52 | Write(point.IsValid);
53 | Write(point.Length);
54 | Write(point.NumPoints);
55 | Write(point.PrecisionModel);
56 | Write(point.X);
57 | Write(point.Y);
58 |
59 | Write(point.Contains(pInterior));
60 | Write(point.Contains(pExterior));
61 |
62 | Write(point.Buffer(10));
63 | Write(point.Buffer(10, new BufferParameters { EndCapStyle = EndCapStyle.Square }));
64 | Write(point.Buffer(10, new BufferParameters { EndCapStyle = EndCapStyle.Flat }));
65 | Write(point.Buffer(10, 20));
66 | Write(point.Buffer(10, new BufferParameters(20) { EndCapStyle = EndCapStyle.Square }));
67 | Write(point.Buffer(10, new BufferParameters(20) { EndCapStyle = EndCapStyle.Flat }));
68 |
69 | Write(point.Crosses(pInterior));
70 | Write(point.Crosses(pExterior));
71 | Write(point.Difference(pInterior));
72 | Write(point.Difference(pExterior));
73 | Write(point.Disjoint(pInterior));
74 | Write(point.Disjoint(pExterior));
75 | Write(point.EqualsTopologically(pInterior));
76 | Write(point.EqualsTopologically(pExterior));
77 | Write(point.EqualsExact(pInterior));
78 | Write(point.EqualsExact(pExterior));
79 | Write(point.ConvexHull());
80 | Write(point.Intersection(pInterior));
81 | Write(point.Intersection(pExterior));
82 | Write(point.Intersects(pInterior));
83 | Write(point.Intersects(pExterior));
84 | Write(point.IsWithinDistance(pInterior, 0.001));
85 | Write(point.IsWithinDistance(pExterior, 0.001));
86 | Write(point.Overlaps(pInterior));
87 | Write(point.Overlaps(pExterior));
88 | Write(point.SymmetricDifference(pInterior));
89 | Write(point.SymmetricDifference(pExterior));
90 | Write(point.ToString());
91 | Write(point.AsText());
92 | Write(point.Touches(pInterior));
93 | Write(point.Touches(pExterior));
94 | Write(point.Union(pInterior));
95 | Write(point.Union(pExterior));
96 | Write(point.Within(pInterior));
97 | Write(point.Within(pExterior));
98 |
99 | string pointstring = "POINT (100.22 100.33)";
100 | string anotherpointstring = "POINT (12345 3654321)";
101 | var geom1 = Reader.Read(pointstring);
102 | Write(geom1.AsText());
103 | var geom2 = Reader.Read(anotherpointstring);
104 | Write(geom2.AsText());
105 |
106 | byte[] bytes = point.AsBinary();
107 | var test1 = new WKBReader().Read(bytes);
108 | Write(test1.ToString());
109 |
110 | bytes = Factory.CreatePoint(new Coordinate(double.MinValue, double.MinValue)).AsBinary();
111 | var testempty = new WKBReader().Read(bytes);
112 | Write(testempty);
113 |
114 | bytes = new GDBWriter().Write(geom1);
115 | test1 = new GDBReader().Read(bytes);
116 | Write(test1.ToString());
117 |
118 | // Test Empty Geometries
119 | Write(Point.Empty);
120 | Write(LineString.Empty);
121 | Write(Polygon.Empty);
122 | Write(MultiPoint.Empty);
123 | Write(MultiLineString.Empty);
124 | Write(MultiPolygon.Empty);
125 | Write(GeometryCollection.Empty);
126 | }
127 | catch (Exception ex)
128 | {
129 | throw ex;
130 | }
131 | }
132 |
133 | protected void Write(object o)
134 | {
135 | Console.WriteLine(o.ToString());
136 | }
137 |
138 | protected void Write(string s)
139 | {
140 | Console.WriteLine(s);
141 | }
142 | }
143 | }
144 |
--------------------------------------------------------------------------------
/test/NetTopologySuite.IO.ShapeFile.Test/Issue123Test.cs:
--------------------------------------------------------------------------------
1 | using NetTopologySuite.Geometries;
2 | using NetTopologySuite.Operation.Union;
3 | using NetTopologySuite.Operation.Valid;
4 | using NUnit.Framework;
5 | using System.Collections.Generic;
6 | using System.IO;
7 |
8 | namespace NetTopologySuite.IO.ShapeFile.Test
9 | {
10 | [TestFixture]
11 | [NtsIssueNumber(123)]
12 | public class Issue123Test
13 | {
14 | [Test]
15 | public void CascadedUnionError()
16 | {
17 | string[] wkt =
18 | {
19 | //MULTIPOLYGON (((-2.775 -37.382, -2.7694818956884695 -37.302294048833446, -4.381 -37.19, -4.379 -37.16, -2.7674053419183364 -37.272299383264858, -2.766 -37.252, -2.703 -37.257, -2.712 -37.386, -2.775 -37.382)), ((-0.558 -16.355, -0.556624473051351 -16.33528411373603, -2.168 -16.223, -2.165 -16.193, -0.55452706181921063 -16.305221219408683, -0.549 -16.226, -0.485 -16.23, -0.494 -16.36, -0.558 -16.355)))
20 | "MULTIPOLYGON (((-2.775 -37.382, -2.7694818956884695 -37.302294048833446, -4.381 -37.19, -4.379 -37.16, -2.7674053419183364 -37.272299383264858, -2.766 -37.252, -2.703 -37.257, -2.712 -37.386, -2.775 -37.382)), ((-0.558 -16.355, -0.556624473051351 -16.33528411373603, -2.168 -16.223, -2.165 -16.193, -0.55452706181921063 -16.305221219408683, -0.549 -16.226, -0.485 -16.23, -0.494 -16.36, -0.558 -16.355)))",
21 | //MULTIPOLYGON (((-4.218 -16.08, -4.216 -16.05, -2.924 -16.14, -2.926 -16.17, -4.218 -16.08)), ((-5.291 -18.097, -5.243 -17.415, -5.239 -17.352, -5.15929328747628 -17.357518157020873, -5.071 -16.091, -5.041 -16.093, -5.1292306097055169 -17.359599419328081, -5.109 -17.361, -5.114 -17.424, -5.161 -18.106, -5.291 -18.097)))
22 | "MULTIPOLYGON (((-4.218 -16.08, -4.216 -16.05, -2.924 -16.14, -2.926 -16.17, -4.218 -16.08)), ((-5.291 -18.097, -5.243 -17.415, -5.239 -17.352, -5.15929328747628 -17.357518157020873, -5.071 -16.091, -5.041 -16.093, -5.1292306097055169 -17.359599419328081, -5.109 -17.361, -5.114 -17.424, -5.161 -18.106, -5.291 -18.097)))"
23 | };
24 |
25 | IList items = new List();
26 | var factory = GeometryFactory.Default;
27 | var reader = new WKTReader(factory);
28 | var geoms = reader.Read(wkt[0]);
29 | for (int i = 0; i < geoms.NumGeometries; i++)
30 | {
31 | var geom = geoms.GetGeometryN(i);
32 | items.Add(geom);
33 | }
34 | geoms = reader.Read(wkt[1]);
35 | for (int i = 0; i < geoms.NumGeometries; i++)
36 | {
37 | var geom = geoms.GetGeometryN(i);
38 | items.Add(geom);
39 | }
40 |
41 | var op = new UnaryUnionOp(items, new GeometryFactory(new PrecisionModel(100)));
42 | var result = op.Union();
43 | Assert.IsNotNull(result);
44 | }
45 |
46 | [Test]
47 | public void CascadedUnionError2()
48 | {
49 | var sf = new ShapefileReader(Path.Combine(CommonHelpers.TestShapefilesDirectory, "error_union.shp"));
50 | var geoms = sf.ReadAll();
51 |
52 | var isValidOp = new IsValidOp(geoms);
53 | Assert.That(!isValidOp.IsValid);
54 | Assert.That(isValidOp.ValidationError.ErrorType, Is.EqualTo(TopologyValidationErrors.RingSelfIntersection));
55 |
56 | Assert.That(geoms.Union, Throws.InstanceOf());
57 | }
58 | }
59 | }
60 |
--------------------------------------------------------------------------------
/test/NetTopologySuite.IO.ShapeFile.Test/Issue161.cs:
--------------------------------------------------------------------------------
1 | using NetTopologySuite.Geometries;
2 | using NUnit.Framework;
3 | using System.IO;
4 |
5 | namespace NetTopologySuite.IO.ShapeFile.Test
6 | {
7 | class Issue161
8 | {
9 | [Test(Description =
10 | "ShapefileDataReader error 'The output char buffer is too small to contain the decoded characters'")]
11 | public void TestIssue161()
12 | {
13 | //SETUP
14 | string filePath = Path.Combine(CommonHelpers.TestShapefilesDirectory, "LSOA_2011_EW_BGC.shp");
15 | if (!File.Exists(filePath)) Assert.Ignore("File '{0}' not present", filePath);
16 |
17 | //ATTEMPT
18 | using (var reader = new ShapefileDataReader(filePath, GeometryFactory.Default))
19 | {
20 | var header = reader.ShapeHeader;
21 |
22 | while (reader.Read())//&& count++ < 3)
23 | {
24 | object val;
25 | Assert.DoesNotThrow(() => val = reader["LSOA11CD"]);
26 | }
27 | }
28 | }
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/test/NetTopologySuite.IO.ShapeFile.Test/Issue173Fixture.cs:
--------------------------------------------------------------------------------
1 | using NetTopologySuite.Geometries;
2 | using NetTopologySuite.Features;
3 | using NetTopologySuite.Geometries.Implementation;
4 | using NUnit.Framework;
5 | using System.Collections.Generic;
6 | using System.IO;
7 |
8 | namespace NetTopologySuite.IO.ShapeFile.Test
9 | {
10 | [NtsIssueNumber(173)]
11 | public class Issue173Fixture
12 | {
13 | [Test, Description("The NetTopologySuite.IO.GeoTools class method ShapeFile.GetGeometryType(Geometry geom) will always returns ShapeGeometryType.PointZM making all shapefile geometry GeometryZM.")]
14 | public void Test()
15 | {
16 | var features = new List();
17 | var seq = DotSpatialAffineCoordinateSequenceFactory.Instance.Create(1, Ordinates.XY);
18 | seq.SetOrdinate(0, Ordinate.X, -91.0454);
19 | seq.SetOrdinate(0, Ordinate.Y, 32.5907);
20 | var pt = new GeometryFactory(DotSpatialAffineCoordinateSequenceFactory.Instance).CreatePoint(seq);
21 | var attr = new AttributesTable();
22 | attr.Add("FirstName", "John");
23 | attr.Add("LastName", "Doe");
24 | features.Add(new Feature(pt, attr));
25 |
26 | string fileName = Path.GetTempFileName();
27 | fileName = fileName.Substring(0, fileName.Length - 4);
28 | var shpWriter = new ShapefileDataWriter(fileName, features[0].Geometry.Factory)
29 | {
30 | Header = ShapefileDataWriter.GetHeader(features[0], features.Count)
31 | };
32 | shpWriter.Write(features);
33 |
34 | bool isTrue;
35 | using (var reader = new ShapefileDataReader(fileName, pt.Factory))
36 | @isTrue = reader.ShapeHeader.ShapeType.ToString() == "Point";
37 |
38 | foreach (string file in Directory.GetFiles(Path.GetTempPath(), Path.GetFileName(fileName) + ".*"))
39 | {
40 | File.Delete(file);
41 | }
42 |
43 | Assert.IsTrue(@isTrue);
44 | }
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/test/NetTopologySuite.IO.ShapeFile.Test/Issue174.cs:
--------------------------------------------------------------------------------
1 | using NUnit.Framework;
2 | using System;
3 |
4 | namespace NetTopologySuite.IO.ShapeFile.Test
5 | {
6 | [NtsIssueNumber(174)]
7 | class Issue174
8 | {
9 | [Test]
10 | public void ensure_NetTopologySuite_IO_ShapeFile_assembly_is_strongly_named()
11 | {
12 | AssertStronglyNamedAssembly(typeof(ShapeReader));
13 | }
14 |
15 | [Test]
16 | public void ensure_NetTopologySuite_IO_GDB_assembly_is_strongly_named()
17 | {
18 | AssertStronglyNamedAssembly(typeof(GDBReader));
19 | }
20 |
21 | [Test]
22 | public void ensure_NetTopologySuite_IO_GeoTools_assembly_is_strongly_named()
23 | {
24 | AssertStronglyNamedAssembly(typeof(ShapefileDataReader));
25 | }
26 |
27 | private void AssertStronglyNamedAssembly(Type typeFromAssemblyToCheck)
28 | {
29 | Assert.IsNotNull(typeFromAssemblyToCheck, "Cannot determine assembly from null");
30 | var assembly = typeFromAssemblyToCheck.Assembly;
31 | StringAssert.DoesNotContain("PublicKeyToken=null", assembly.FullName, "Strongly named assembly should have a PublicKeyToken in fully qualified name");
32 | }
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/test/NetTopologySuite.IO.ShapeFile.Test/Issue178Fixture.cs:
--------------------------------------------------------------------------------
1 | using NetTopologySuite.Geometries;
2 | using NUnit.Framework;
3 | using System;
4 | using System.IO;
5 |
6 | namespace NetTopologySuite.IO.ShapeFile.Test
7 | {
8 | [TestFixture]
9 | public class Issue178Fixture
10 | {
11 | [SetUp]
12 | public void SetUp()
13 | {
14 | // Set current dir to shapefiles dir
15 | Environment.CurrentDirectory = CommonHelpers.TestShapefilesDirectory;
16 | }
17 |
18 | [Test]
19 | public void TestCorruptedShapeFile()
20 | {
21 | var factory = GeometryFactory.Default;
22 | const string filename = "christchurch-canterbury-h.shp";
23 | Assert.Throws(() =>
24 | {
25 | var reader = new ShapefileReader(filename, factory);
26 | Assert.Fail("Invalid file: code should be unreachable");
27 | });
28 |
29 | // ensure file isn't locked
30 | string path = Path.Combine(Environment.CurrentDirectory, filename);
31 | bool ok;
32 | using (var file = File.OpenRead(path))
33 | {
34 | using (var reader = new BinaryReader(file))
35 | {
36 | // read a value
37 | int val = reader.Read();
38 | Console.WriteLine("read a value: " + val);
39 | ok = true;
40 | }
41 | }
42 | Assert.That(ok, Is.True);
43 | }
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/test/NetTopologySuite.IO.ShapeFile.Test/Issue27Fixture.cs:
--------------------------------------------------------------------------------
1 | using NUnit.Framework;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using NetTopologySuite.IO.ShapeFile.Extended;
5 | using NetTopologySuite.IO.ShapeFile.Extended.Entities;
6 | using System.IO;
7 |
8 | namespace NetTopologySuite.IO.ShapeFile.Test
9 | {
10 | [TestFixture]
11 | [ShapeFileIssueNumber(27)]
12 | public class Issue27Fixture
13 | {
14 | ///
15 | ///
16 | ///
17 | [Test]
18 | public void Data_should_be_readable_after_reader_dispose()
19 | {
20 | var crustal_test = Path.Combine(CommonHelpers.TestShapefilesDirectory, "crustal_test.shp");
21 | Assert.True(File.Exists(crustal_test));
22 |
23 | List data = null;
24 | using (var reader = new ShapeDataReader(crustal_test))
25 | {
26 | var mbr = reader.ShapefileBounds;
27 | data = reader.ReadByMBRFilter(mbr).ToList();
28 | }
29 | Assert.IsNotNull(data);
30 | Assert.IsNotEmpty(data);
31 |
32 | foreach (var item in data)
33 | {
34 | Assert.IsNotNull(item.Geometry);
35 | Assert.IsNotNull(item.Attributes["ID_GTR"]);
36 | }
37 | }
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/test/NetTopologySuite.IO.ShapeFile.Test/Issue36Tests.cs:
--------------------------------------------------------------------------------
1 | using NetTopologySuite.Features;
2 | using NetTopologySuite.Geometries;
3 | using NUnit.Framework;
4 | using System;
5 | using System.Collections.Generic;
6 | using System.IO;
7 |
8 | namespace NetTopologySuite.IO.ShapeFile.Test
9 | {
10 | ///
11 | /// see: https://github.com/NetTopologySuite/NetTopologySuite/issues/36
12 | ///
13 | [TestFixture]
14 | public class Issue36Tests
15 | {
16 | private int _numPassed;
17 |
18 | [SetUp]
19 | public void SetUp()
20 | {
21 | // Set current dir to shapefiles dir
22 | Environment.CurrentDirectory = CommonHelpers.TestShapefilesDirectory;
23 |
24 | _numPassed = 0;
25 | }
26 |
27 | [Test]
28 | public void ok_when_writing_shapefile_with_features()
29 | {
30 | var header = new DbaseFileHeader();
31 | header.AddColumn("X", 'C', 10, 0);
32 | var writer = new ShapefileDataWriter(@"issue36") { Header = header };
33 |
34 | IAttributesTable attributesTable = new AttributesTable();
35 | attributesTable.Add("X", "y");
36 | IFeature feature = new Feature(new Point(1, 2), attributesTable);
37 |
38 | IList features = new List();
39 | features.Add(feature);
40 |
41 | Assert.DoesNotThrow(() => writer.Write(features));
42 |
43 | _numPassed++;
44 | }
45 |
46 | [Test]
47 | public void ok_when_writing_shapefile_with_no_features()
48 | {
49 | var header = new DbaseFileHeader();
50 | header.AddColumn("X", 'C', 10, 0);
51 | var writer = new ShapefileDataWriter(@"issue36") { Header = header };
52 |
53 | IList features = new List();
54 | Assert.DoesNotThrow(() => writer.Write(features));
55 |
56 | _numPassed++;
57 | }
58 |
59 | [TearDown]
60 | public void TearDown()
61 | {
62 | if (_numPassed < 2) return;
63 |
64 | // Clean up!
65 | File.Delete("issue36.dbf");
66 | File.Delete("issue36.shp");
67 | File.Delete("issue36.shx");
68 | }
69 | }
70 | }
71 |
--------------------------------------------------------------------------------
/test/NetTopologySuite.IO.ShapeFile.Test/Issue46Fixture.cs:
--------------------------------------------------------------------------------
1 | using NUnit.Framework;
2 | using System.IO;
3 | using NetTopologySuite.Geometries;
4 |
5 | namespace NetTopologySuite.IO.ShapeFile.Test
6 | {
7 | ///
8 | ///
9 | ///
10 | [TestFixture]
11 | [ShapeFileIssueNumber(46)]
12 | public class Issue46Fixture
13 | {
14 | [Test]
15 | public void Invalid_data_should_be_not_read_as_default()
16 | {
17 | var factory = GeometryFactory.Default;
18 |
19 | string shp_path = Path.Combine(CommonHelpers.TestShapefilesDirectory, "Victoria North.shp");
20 | Assert.True(File.Exists(shp_path));
21 |
22 | var reader = new ShapefileReader(shp_path, factory);
23 | var data = reader.ReadAll();
24 | Assert.IsNotNull(data);
25 | Assert.IsNotEmpty(data);
26 | Assert.AreEqual(2, data.Count);
27 |
28 | Assert.IsTrue(data[0].IsEmpty);
29 | Assert.IsInstanceOf(data[0]);
30 | Assert.IsTrue(factory.CreatePolygon().EqualsExact(data[0]));
31 |
32 | Assert.IsFalse(data[1].IsEmpty);
33 | Assert.IsInstanceOf(data[1]);
34 | }
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/test/NetTopologySuite.IO.ShapeFile.Test/Issue4Fixture.cs:
--------------------------------------------------------------------------------
1 | using NetTopologySuite.Geometries;
2 | using NetTopologySuite.Features;
3 | using NetTopologySuite.Geometries.Implementation;
4 | using NUnit.Framework;
5 | using System.Collections.Generic;
6 | using System.IO;
7 | using System.Linq;
8 |
9 | namespace NetTopologySuite.IO.ShapeFile.Test
10 | {
11 | [TestFixture]
12 | public class Issue4Fixture
13 | {
14 | private static string CreateShapefilePath()
15 | {
16 | string path = Path.GetTempFileName();
17 | path = Path.ChangeExtension(path, string.Empty).TrimEnd('.');
18 | return path;
19 | }
20 |
21 | private static Coordinate[] CreateCoords()
22 | {
23 | IList coordinates = new List();
24 | coordinates.Add(new Coordinate(0, 0));
25 | coordinates.Add(new Coordinate(1, 0));
26 | coordinates.Add(new Coordinate(1, 1));
27 | coordinates.Add(new Coordinate(0, 1));
28 | coordinates.Add(new Coordinate(0, 0));
29 | return coordinates.ToArray();
30 | }
31 |
32 | private static CoordinateSequence CopyToSequence(Coordinate[] coords, CoordinateSequence sequence)
33 | {
34 | for (int i = 0; i < coords.Length; i++)
35 | {
36 | sequence.SetOrdinate(i, Ordinate.X, coords[i].X);
37 | sequence.SetOrdinate(i, Ordinate.Y, coords[i].Y);
38 | }
39 | return sequence;
40 | }
41 |
42 | [Test]
43 | public void shapefile_with_empty_attributes_table_should_not_thrown_errors()
44 | {
45 | IFeature feature = new Feature(new Point(0, 0), new AttributesTable());
46 | IList features = new List { feature };
47 |
48 | string path = CreateShapefilePath();
49 | var header = ShapefileDataWriter.GetHeader(feature, features.Count);
50 | var writer = new ShapefileDataWriter(path) { Header = header };
51 | writer.Write(features);
52 | Assert.That(File.Exists(Path.ChangeExtension(path, ".shp")), Is.True);
53 | }
54 |
55 | [Test]
56 | public void create_xyonly_geom_using_sequence_and_dimension_two()
57 | {
58 | var coords = CreateCoords();
59 |
60 | var factory = CoordinateArraySequenceFactory.Instance;
61 | var sequence = CopyToSequence(coords, factory.Create(coords.Length, 2));
62 |
63 | var polygon = GeometryFactory.Default.CreatePolygon(sequence);
64 | Assert.That(polygon, Is.Not.Null);
65 | Assert.That(polygon.Shell, Is.Not.Null);
66 | Assert.That(polygon.Shell.CoordinateSequence.Dimension, Is.EqualTo(2));
67 | }
68 |
69 | [Test]
70 | public void create_xyonly_geom_using_sequence_and_ordinates_xy()
71 | {
72 | var coords = CreateCoords();
73 |
74 | var factory = CoordinateArraySequenceFactory.Instance;
75 | var sequence = CopyToSequence(coords, factory.Create(coords.Length, Ordinates.XY));
76 |
77 | var polygon = GeometryFactory.Default.CreatePolygon(sequence);
78 | Assert.That(polygon, Is.Not.Null);
79 | Assert.That(polygon.Shell, Is.Not.Null);
80 | Assert.That(polygon.Shell.CoordinateSequence.Dimension, Is.EqualTo(2));
81 | }
82 | }
83 | }
84 |
--------------------------------------------------------------------------------
/test/NetTopologySuite.IO.ShapeFile.Test/Issue56Fixture.cs:
--------------------------------------------------------------------------------
1 | using NetTopologySuite.Features;
2 | using NetTopologySuite.Geometries;
3 | using NUnit.Framework;
4 | using System.Collections.Generic;
5 | using System.IO;
6 |
7 | namespace NetTopologySuite.IO.ShapeFile.Test
8 | {
9 | [TestFixture]
10 | [ShapeFileIssueNumber(56)]
11 | public class Issue56Fixture
12 | {
13 | ///
14 | ///
15 | ///
16 | [Test]
17 | public void Data_should_be_readable_after_reader_dispose()
18 | {
19 | string test56 = Path.Combine(CommonHelpers.TestShapefilesDirectory, "test56.shp");
20 | var factory = new GeometryFactory();
21 | int intValue = 56;
22 | string key = "id";
23 | var attributes = new AttributesTable();
24 | attributes.Add(key, intValue);
25 | var feature = new Feature(factory.CreatePoint(new Coordinate(1, 2)), attributes);
26 |
27 | var writer = new ShapefileDataWriter(test56);
28 | writer.Header = ShapefileDataWriter.GetHeader(feature, 1);
29 | writer.Write(new[] { feature });
30 |
31 | using (var reader = new ShapefileDataReader(test56, factory)) {
32 |
33 | if (reader.RecordCount > 0)
34 | {
35 | while (reader.Read())
36 | {
37 | int index = reader.GetOrdinal(key);
38 | Assert.AreEqual(intValue.GetType(), reader.GetFieldType(index));
39 | }
40 | }
41 | }
42 |
43 | }
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/test/NetTopologySuite.IO.ShapeFile.Test/Issue60Fixture.cs:
--------------------------------------------------------------------------------
1 | using NetTopologySuite.Features;
2 | using NetTopologySuite.Geometries;
3 | using NUnit.Framework;
4 | using System.Collections.Generic;
5 | using System.IO;
6 |
7 | namespace NetTopologySuite.IO.ShapeFile.Test
8 | {
9 | [TestFixture]
10 | [ShapeFileIssueNumber(60)]
11 | public class Issue60Fixture
12 | {
13 | ///
14 | ///
15 | ///
16 | /// without fix results into System.OverflowException
17 | [Test]
18 | public void Feature_without_fields_should_be_written_correctly()
19 | {
20 | string test56 = Path.Combine(CommonHelpers.TestShapefilesDirectory, "test60.shp");
21 | var factory = new GeometryFactory();
22 | var attributes = new AttributesTable();
23 | var feature = new Feature(factory.CreatePoint(new Coordinate(1, 2)), attributes);
24 |
25 | var writer = new ShapefileDataWriter(test56);
26 | writer.Header = ShapefileDataWriter.GetHeader(feature, 1);
27 | writer.Write(new[] { feature });
28 |
29 | using (var reader = new ShapefileDataReader(test56, factory)) {
30 |
31 | if (reader.RecordCount > 0)
32 | {
33 | while (reader.Read())
34 | {
35 | Assert.AreEqual(feature.Geometry.AsText(), reader.Geometry.AsText());
36 | }
37 | }
38 | }
39 | }
40 |
41 | [Test]
42 | public void Header_length_should_always_be_minimal_33()
43 | {
44 | var header = new DbaseFileHeader();
45 | Assert.AreEqual(33, header.HeaderLength);
46 | }
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/test/NetTopologySuite.IO.ShapeFile.Test/Issue64Fixture.cs:
--------------------------------------------------------------------------------
1 | using NUnit.Framework;
2 | using System.Collections;
3 | using System.IO;
4 |
5 | using NetTopologySuite.IO.Streams;
6 |
7 | namespace NetTopologySuite.IO.ShapeFile.Test
8 | {
9 | [TestFixture]
10 | [ShapeFileIssueNumber(64)]
11 | public class Issue64Fixture
12 | {
13 | ///
14 | ///
15 | ///
16 | [TestCase('L', 1)]
17 | [TestCase('D', 8)]
18 | [TestCase('F', 8)]
19 | [TestCase('N', 8)]
20 | [TestCase('C', 8)]
21 | public void Dbase_Read_Null(char fieldType, int fieldLength)
22 | {
23 | using var s = new MemoryStream();
24 | var provider = new ExternallyManagedStreamProvider(StreamTypes.Data, s);
25 | var reg = new ShapefileStreamProviderRegistry(null, provider);
26 |
27 | var header = new DbaseFileHeader();
28 | header.AddColumn("TestCol", fieldType, fieldLength, 0);
29 | header.NumRecords = 1;
30 |
31 | object[] values = new[] { (object)null };
32 |
33 | using (var writer = new DbaseFileWriter(reg))
34 | {
35 | writer.Write(header);
36 | writer.Write(values);
37 | }
38 |
39 | s.Position = 0;
40 | var reader = new DbaseFileReader(reg);
41 |
42 | reader.GetHeader();
43 | s.Position = 0;
44 |
45 | foreach (ArrayList readValues in reader)
46 | {
47 | Assert.AreEqual(values[0], readValues[0]);
48 | }
49 | }
50 | }
51 | }
52 |
--------------------------------------------------------------------------------
/test/NetTopologySuite.IO.ShapeFile.Test/Issue74Fixture.cs:
--------------------------------------------------------------------------------
1 | using NetTopologySuite.Geometries;
2 | using NetTopologySuite.IO.Handlers;
3 | using NUnit.Framework;
4 | using System.IO;
5 |
6 | namespace NetTopologySuite.IO.ShapeFile.Test
7 | {
8 | [NtsIssueNumber(74)]
9 | public class Issue74Fixture
10 | {
11 | [Test, Description("Max 'M' value is always set to double.PositiveInfinity")]
12 | public void ShapeHandler_correctly_writes_BBOX_info()
13 | {
14 | var factory = GeometryFactory.Default;
15 | var pMin = factory.CreatePoint(new CoordinateZM(-1, -1, -1, -1));
16 | var pMax = factory.CreatePoint(new CoordinateZM(2, 2, 2, 2));
17 | var coll = factory.CreateMultiPoint(new[] { pMin, pMax });
18 | var handler = new MultiPointHandler(ShapeGeometryType.MultiPointZM);
19 | byte[] bytes;
20 | using (var stream = new MemoryStream())
21 | {
22 | using var writer = new BinaryWriter(stream);
23 | handler.Write(coll, writer, factory);
24 | bytes = stream.ToArray();
25 | }
26 |
27 | using var reader = new BinaryReader(new MemoryStream(bytes));
28 | Assert.AreEqual((int)ShapeGeometryType.MultiPointZM, reader.ReadInt32());
29 | Assert.AreEqual(pMin.X, reader.ReadDouble()); // MinX
30 | Assert.AreEqual(pMin.Y, reader.ReadDouble()); // MinY
31 | Assert.AreEqual(pMax.X, reader.ReadDouble()); // MaxX
32 | Assert.AreEqual(pMax.Y, reader.ReadDouble()); // MaxY
33 | Assert.AreEqual(coll.NumGeometries, reader.ReadInt32());
34 | for (int i = 0; i < 4; i++)
35 | {
36 | // Skip XY values
37 | reader.ReadDouble();
38 | }
39 | Assert.AreEqual(pMin.Z, reader.ReadDouble()); // MinZ
40 | Assert.AreEqual(pMax.Z, reader.ReadDouble()); // MaxZ
41 | for (int i = 0; i < 2; i++)
42 | {
43 | // Skip Z values
44 | reader.ReadDouble();
45 | }
46 | Assert.AreEqual(pMin.M, reader.ReadDouble()); // MinM
47 | Assert.AreEqual(pMax.M, reader.ReadDouble()); // MaxM
48 | for (int i = 0; i < 2; i++)
49 | {
50 | // Skip M values
51 | reader.ReadDouble();
52 | }
53 | }
54 | }
55 | }
56 |
57 |
--------------------------------------------------------------------------------
/test/NetTopologySuite.IO.ShapeFile.Test/Issue79Fixture.cs:
--------------------------------------------------------------------------------
1 | using NUnit.Framework;
2 | using System.IO;
3 | using NetTopologySuite.Geometries;
4 |
5 | namespace NetTopologySuite.IO.ShapeFile.Test
6 | {
7 | [TestFixture]
8 | [ShapeFileIssueNumber(79)]
9 | public class Issue79Fixture
10 | {
11 | ///
12 | ///
13 | ///
14 | [Test]
15 | public void TestReadEmptyShapefile()
16 | {
17 | string filePath = Path.Combine(
18 | CommonHelpers.TestShapefilesDirectory,
19 | "__emptyShapefile.shp");
20 | Assert.That(File.Exists(filePath), Is.True);
21 | using var shpReader = new ShapefileDataReader(
22 | Path.GetFileNameWithoutExtension(filePath),
23 | GeometryFactory.Default);
24 | bool success = shpReader.Read();
25 | Assert.That(success, Is.False);
26 | }
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/test/NetTopologySuite.IO.ShapeFile.Test/NetTopologySuite.IO.ShapeFile.Test.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | netcoreapp3.1
5 |
6 | false
7 |
8 | true
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
--------------------------------------------------------------------------------
/test/NetTopologySuite.IO.ShapeFile.Test/NtsIssueNumberAttribute.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using NUnit.Framework;
3 |
4 | namespace NetTopologySuite.IO.ShapeFile.Test
5 | {
6 | ///
7 | /// The issue number used in this test (or fixture) actually refers to an
8 | /// issue on https://github.com/NetTopologySuite/NetTopologySuite, back
9 | /// before this project was split out on its own.
10 | ///
11 | [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class)]
12 | public sealed class NtsIssueNumberAttribute : PropertyAttribute
13 | {
14 | public NtsIssueNumberAttribute(int issueNumber)
15 | : base("NetTopologySuite issue", issueNumber)
16 | {
17 | }
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/test/NetTopologySuite.IO.ShapeFile.Test/ShapeFile.Extended/HelperMethods.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using NetTopologySuite.Geometries;
3 | using NetTopologySuite.IO.Handlers;
4 | using Assert = NUnit.Framework.Assert;
5 |
6 | namespace NetTopologySuite.IO.Tests.ShapeFile.Extended
7 | {
8 | public static class HelperMethods
9 | {
10 | private static readonly double REQUIRED_PRECISION = Math.Pow(10, -9);
11 |
12 | public static void AssertEnvelopesEqual(Envelope env1, Envelope env2)
13 | {
14 | AssertEnvelopesEqual(env1, env2, REQUIRED_PRECISION);
15 | }
16 |
17 | public static void AssertEnvelopesEqual(Envelope env1, Envelope env2, double requiredPrecision, string errorMessage = "")
18 | {
19 | AssertDoubleValuesEqual(env1.MaxX, env2.MaxX, requiredPrecision, errorMessage);
20 | AssertDoubleValuesEqual(env1.MaxY, env2.MaxY, requiredPrecision, errorMessage);
21 | AssertDoubleValuesEqual(env1.MinX, env2.MinX, requiredPrecision, errorMessage);
22 | AssertDoubleValuesEqual(env1.MinY, env2.MinY, requiredPrecision, errorMessage);
23 | }
24 |
25 | public static void AssertPolygonsEqual(Polygon poly1, Polygon poly2)
26 | {
27 | Assert.IsNotNull(poly1);
28 | Assert.IsNotNull(poly2);
29 |
30 | LineString line1 = poly1.Shell;
31 | LineString line2 = poly2.Shell;
32 |
33 | Assert.AreEqual(line1.Coordinates.Length, line2.Coordinates.Length, "Number of coordinates between polygons doesn't match");
34 |
35 | for (int i = 0; i < line2.Coordinates.Length; i++)
36 | {
37 | AssertCoordinatesEqual(line2.Coordinates[i], line1.Coordinates[i]);
38 | }
39 | }
40 |
41 | public static void AssertCoordinatesEqual(Coordinate coord1, Coordinate coord2)
42 | {
43 | AssertDoubleValuesEqual(coord1.X, coord2.X);
44 | AssertDoubleValuesEqual(coord1.Y, coord2.Y);
45 | }
46 |
47 | public static void AssertDoubleValuesEqual(double num1, double num2)
48 | {
49 | AssertDoubleValuesEqual(num1, num2, REQUIRED_PRECISION);
50 | }
51 |
52 | public static void AssertDoubleValuesEqual(double num1, double num2, double requiredPrecision, string errorMessage = "")
53 | {
54 | if (string.IsNullOrWhiteSpace(errorMessage))
55 | {
56 | Assert.AreEqual(num1, num2, requiredPrecision);
57 | }
58 | else
59 | {
60 | Assert.AreEqual(num1, num2, requiredPrecision, errorMessage);
61 | }
62 | }
63 |
64 | public static void AssertMBRInfoEqual(MBRInfo info1, MBRInfo info2)
65 | {
66 | Assert.AreEqual(info1.ShapeFileDetails.OffsetFromStartOfFile, info2.ShapeFileDetails.OffsetFromStartOfFile);
67 | Assert.AreEqual(info1.ShapeFileDetails.ShapeIndex, info2.ShapeFileDetails.ShapeIndex);
68 | AssertEnvelopesEqual(info1.ShapeMBR, info2.ShapeMBR);
69 | }
70 | }
71 | }
72 |
--------------------------------------------------------------------------------
/test/NetTopologySuite.IO.ShapeFile.Test/ShapeFile.Extended/ShapefileDataWriterTests.cs:
--------------------------------------------------------------------------------
1 | using NetTopologySuite.Features;
2 | using NetTopologySuite.Geometries;
3 | using NUnit.Framework;
4 | using System;
5 | using System.Linq;
6 |
7 | namespace NetTopologySuite.IO.Tests.ShapeFile.Extended
8 | {
9 | ///
10 | /// Contains tests for the shapefile data writer.
11 | ///
12 | [TestFixture]
13 | public class ShapefileDataWriterTests
14 | {
15 | ///
16 | /// Tests creating a header from a feature.
17 | ///
18 | [Test]
19 | public void TestGetHeaderFromFeature()
20 | {
21 | var feature = new Feature(new Point(0, 0),
22 | new AttributesTable());
23 | feature.Attributes.Add("c_long", (long)12345678900000000);
24 | feature.Attributes.Add("c_ulong", (ulong)12345678900000000);
25 | feature.Attributes.Add("c_int", int.MinValue);
26 | feature.Attributes.Add("c_uint", uint.MinValue);
27 | feature.Attributes.Add("c_short", short.MaxValue);
28 | feature.Attributes.Add("c_ushort", ushort.MaxValue);
29 | feature.Attributes.Add("c_string", string.Empty);
30 | feature.Attributes.Add("c_double", double.MinValue);
31 | feature.Attributes.Add("c_bool", false);
32 | feature.Attributes.Add("c_datetime", new DateTime(1999, 01, 01));
33 |
34 | var header = ShapefileDataWriter.GetHeader(feature, 1);
35 |
36 | Assert.IsNotNull(header);
37 | Assert.AreEqual(10, header.Fields.Length);
38 | var field = header.Fields.FirstOrDefault(x => x.Name == "c_long");
39 | Assert.IsNotNull(field);
40 | Assert.AreEqual(78, field.DbaseType);
41 | Assert.AreEqual(0, field.DecimalCount);
42 | Assert.AreEqual(18, field.Length);
43 | field = header.Fields.FirstOrDefault(x => x.Name == "c_ulong");
44 | Assert.IsNotNull(field);
45 | Assert.AreEqual(78, field.DbaseType);
46 | Assert.AreEqual(0, field.DecimalCount);
47 | Assert.AreEqual(18, field.Length);
48 | field = header.Fields.FirstOrDefault(x => x.Name == "c_int");
49 | Assert.IsNotNull(field);
50 | Assert.AreEqual(78, field.DbaseType);
51 | Assert.AreEqual(0, field.DecimalCount);
52 | Assert.AreEqual(10, field.Length);
53 | field = header.Fields.FirstOrDefault(x => x.Name == "c_uint");
54 | Assert.IsNotNull(field);
55 | Assert.AreEqual(78, field.DbaseType);
56 | Assert.AreEqual(0, field.DecimalCount);
57 | Assert.AreEqual(10, field.Length);
58 | field = header.Fields.FirstOrDefault(x => x.Name == "c_short");
59 | Assert.IsNotNull(field);
60 | Assert.AreEqual(78, field.DbaseType);
61 | Assert.AreEqual(0, field.DecimalCount);
62 | Assert.AreEqual(10, field.Length);
63 | field = header.Fields.FirstOrDefault(x => x.Name == "c_ushort");
64 | Assert.IsNotNull(field);
65 | Assert.AreEqual(78, field.DbaseType);
66 | Assert.AreEqual(0, field.DecimalCount);
67 | Assert.AreEqual(10, field.Length);
68 | field = header.Fields.FirstOrDefault(x => x.Name == "c_string");
69 | Assert.IsNotNull(field);
70 | Assert.AreEqual(67, field.DbaseType);
71 | Assert.AreEqual(0, field.DecimalCount);
72 | Assert.AreEqual(254, field.Length);
73 | field = header.Fields.FirstOrDefault(x => x.Name == "c_double");
74 | Assert.IsNotNull(field);
75 | Assert.AreEqual(78, field.DbaseType);
76 | Assert.AreEqual(8, field.DecimalCount);
77 | Assert.AreEqual(18, field.Length);
78 | field = header.Fields.FirstOrDefault(x => x.Name == "c_bool");
79 | Assert.IsNotNull(field);
80 | Assert.AreEqual(76, field.DbaseType);
81 | Assert.AreEqual(0, field.DecimalCount);
82 | Assert.AreEqual(1, field.Length);
83 | field = header.Fields.FirstOrDefault(x => x.Name == "c_datetime");
84 | Assert.IsNotNull(field);
85 | Assert.AreEqual(68, field.DbaseType);
86 | Assert.AreEqual(0, field.DecimalCount);
87 | Assert.AreEqual(8, field.Length);
88 | }
89 | }
90 | }
--------------------------------------------------------------------------------
/test/NetTopologySuite.IO.ShapeFile.Test/ShapeFile.Extended/TempFileWriter.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.IO;
3 |
4 | using NUnit.Framework;
5 |
6 | namespace NetTopologySuite.IO.Tests.ShapeFile.Extended
7 | {
8 | internal sealed class TempFileWriter : IDisposable
9 | {
10 | public TempFileWriter(string ext, byte[] data)
11 | {
12 | this.Path = System.IO.Path.GetFullPath(System.IO.Path.ChangeExtension(TestContext.CurrentContext.Test.ID, ext));
13 | File.WriteAllBytes(this.Path, data);
14 | }
15 |
16 | ~TempFileWriter() => this.InternalDispose();
17 |
18 | public string Path { get; }
19 |
20 | public void Dispose()
21 | {
22 | this.InternalDispose();
23 | GC.SuppressFinalize(this);
24 | }
25 |
26 | private void InternalDispose()
27 | {
28 | try
29 | {
30 | File.Delete(this.Path);
31 | }
32 | catch
33 | {
34 | }
35 | }
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/test/NetTopologySuite.IO.ShapeFile.Test/ShapeFileEncodingTest.cs:
--------------------------------------------------------------------------------
1 | using NetTopologySuite.Features;
2 | using NetTopologySuite.Geometries;
3 | using NUnit.Framework;
4 | using System.Collections.Generic;
5 | using System.Text;
6 |
7 | namespace NetTopologySuite.IO.ShapeFile.Test
8 | {
9 | [TestFixture]
10 | public class ShapeFileEncodingTest
11 | {
12 | [SetUp]
13 | public void Setup()
14 | {
15 | var sfdr = new ShapefileDataWriter("encoding_sample");
16 | var h = new DbaseFileHeader();
17 | h.AddColumn("id", 'n', 8, 0);
18 | h.AddColumn("Test", 'C', 15, 0);
19 | h.AddColumn("Ålder", 'N', 8, 0);
20 | h.AddColumn("Ödestext", 'C', 254, 0);
21 | h.NumRecords = 1;
22 | sfdr.Header = h;
23 |
24 | var feats = new List();
25 | var at = new AttributesTable();
26 | at.Add("id", "0");
27 | at.Add("Test", "Testar");
28 | at.Add("Ålder", 10);
29 | at.Add("Ödestext", "Lång text med åäö etc");
30 | feats.Add(new Feature(new Point(0, 0), at));
31 | sfdr.Write(feats);
32 | }
33 |
34 | [Test]
35 | public void TestLoadShapeFileWithEncoding()
36 | {
37 | var reader = new ShapefileDataReader("encoding_sample.shp", GeometryFactory.Default);
38 | var header = reader.DbaseHeader;
39 | Assert.AreEqual(header.Encoding, CodePagesEncodingProvider.Instance.GetEncoding(1252), "Invalid encoding!");
40 |
41 | Assert.AreEqual(header.Fields[1].Name, "Test");
42 | Assert.AreEqual(header.Fields[2].Name, "Ålder");
43 | Assert.AreEqual(header.Fields[3].Name, "Ödestext");
44 |
45 | Assert.IsTrue(reader.Read(), "Error reading file");
46 | Assert.AreEqual(reader["Test"], "Testar");
47 | Assert.AreEqual(reader["Ödestext"], "Lång text med åäö etc");
48 | }
49 | }
50 | }
51 |
--------------------------------------------------------------------------------
/test/NetTopologySuite.IO.ShapeFile.Test/ShapeFileInvalidHeaderTest.cs:
--------------------------------------------------------------------------------
1 | using NUnit.Framework;
2 | using System.IO;
3 |
4 | namespace NetTopologySuite.IO.ShapeFile.Test
5 | {
6 | [TestFixture]
7 | [Ignore("Sample file(s) not published")]
8 | public class ShapeFileInvalidHeaderTest
9 | {
10 | private readonly string _invalidPath = Path.Combine(CommonHelpers.TestShapefilesDirectory, "invalidheader.shp");
11 |
12 | [Test]
13 | public void TestInvalidShapeFile()
14 | {
15 | /*
16 | var s = new NetTopologySuite.IO.ShapefileReader(_invalidPath);
17 | var sh = s.Header;
18 | var g = s.ReadAll();
19 | */
20 | string dbf = Path.ChangeExtension(_invalidPath, ".dbf");
21 | var d = new NetTopologySuite.IO.DbaseFileReader(dbf);
22 |
23 | var de = d.GetEnumerator();
24 | Assert.IsNull(de.Current);
25 | de.MoveNext();
26 | Assert.IsNotNull(de.Current);
27 | }
28 | }
29 | }
--------------------------------------------------------------------------------
/test/NetTopologySuite.IO.ShapeFile.Test/ShapeFileIssueNumberAttribute.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using NUnit.Framework;
3 |
4 | namespace NetTopologySuite.IO.ShapeFile.Test
5 | {
6 | ///
7 | /// The issue number used in this test (or fixture) refers to an issue on
8 | /// https://github.com/NetTopologySuite/NetTopologySuite.IO.ShapeFile, created
9 | /// after this project was split out on its own (and thus, it got its own
10 | /// set of issue numbers).
11 | ///
12 | [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class)]
13 | public sealed class ShapeFileIssueNumberAttribute : PropertyAttribute
14 | {
15 | public ShapeFileIssueNumberAttribute(int issueNumber)
16 | : base("NetTopologySuite.IO.ShapeFile issue", issueNumber)
17 | {
18 | }
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/test/NetTopologySuite.IO.ShapeFile.Test/ShapeRead.cs:
--------------------------------------------------------------------------------
1 | using NetTopologySuite.Geometries;
2 | using System;
3 | using System.IO;
4 |
5 | namespace NetTopologySuite.IO.ShapeFile.Test
6 | {
7 | ///
8 | ///
9 | ///
10 | public class ShapeRead
11 | {
12 | protected GeometryFactory Factory { get; private set; }
13 |
14 | protected WKTReader Reader { get; private set; }
15 |
16 | ///
17 | ///
18 | ///
19 | public ShapeRead()
20 | {
21 | // Set current dir to shapefiles dir
22 | Environment.CurrentDirectory = CommonHelpers.TestShapefilesDirectory;
23 |
24 | this.Factory = new GeometryFactory();
25 | this.Reader = new WKTReader();
26 | }
27 |
28 | ///
29 | ///
30 | ///
31 | public void Start()
32 | {
33 | //TestBugMultipolygonHShuntao();
34 | //TestBugCimino();
35 |
36 | //// Bug with a.shp and b.shp and intersection
37 | //GeometryCollection aColl = ReadShape("a.shp");
38 | //GeometryCollection bColl = ReadShape("b.shp");
39 | //Geometry result = aColl.Intersection(bColl);
40 |
41 | //// Point shapefile
42 | //TestShapeReadWrite("tnp_pts.shp", "Test_tnp_pts.shp");
43 |
44 | //// Arc shapefile
45 | TestShapeReadWrite("tnp_arc.shp", "arc.shp");
46 | TestShapeReadWrite("Stato_Fatto.shp", "Test_Stato_Fatto.shp");
47 | TestShapeReadWrite("Stato_Progetto.shp", "Test_Stato_Progetto.shp");
48 | TestShapeReadWrite("Zone_ISTAT.shp", "Test_Zone_ISTAT.shp");
49 | TestShapeReadWrite("Strade.shp", "Test_Strade.shp");
50 |
51 | //// Polygon shapefile
52 | //TestShapeReadWrite("tnp_pol.shp", "Test_tnp_pol.shp");
53 |
54 | //// MultiPoint shapefile
55 | //TestShapeReadWrite("tnp_multiPoint.shp", "Test_tnp_multiPoint.shp");
56 |
57 | // TestShapeReadWrite("a.shp", "Test_a.shp");
58 | // TestShapeReadWrite("b.shp", "Test_b.shp");
59 | }
60 |
61 | //private void TestBugMultipolygonHShuntao()
62 | //{
63 | // GeometryCollection gc1 = null;
64 | // GeometryCollection gc2 = null;
65 | // string file = "BJmultipolygon.shp";
66 | // if (!File.Exists(file))
67 | // throw new FileNotFoundException();
68 |
69 | // // Test with Default ShapefileReader
70 | // try
71 | // {
72 | // var sfr = new ShapefileReader(file);
73 | // gc1 = sfr.ReadAll();
74 | // }
75 | // catch (Exception ex)
76 | // {
77 | // throw ex;
78 | // }
79 |
80 | // //// Test with MyShapefileReader (only for debug purpose!)
81 | // //try
82 | // //{
83 | // // MyShapeFileReader reader = new MyShapeFileReader();
84 | // // gc2 = reader.Read(file);
85 | // //}
86 | // //catch (Exception ex)
87 | // //{
88 | // // throw ex;
89 | // //}
90 |
91 | // //// Check for equality
92 | // //if (!gc1.EqualsExact(gc2))
93 | // // throw new TopologyException("Both geometries must be equals!");
94 | //}
95 |
96 | //private void TestBugCimino()
97 | //{
98 | // try
99 | // {
100 | // string file = "countryCopy.shp";
101 | // if (!File.Exists(file))
102 | // throw new FileNotFoundException();
103 |
104 | // var sfr = new ShapefileReader(file);
105 |
106 | // var gc = sfr.ReadAll();
107 | // for (int i = 0; i < gc.NumGeometries; i++)
108 | // Console.WriteLine(i + " " + gc.Geometries[i].Envelope);
109 |
110 | // // IsValidOp.CheckShellsNotNested molto lento nell'analisi di J == 7 (Poligono con 11600 punti)
111 | // string write = Path.Combine(Path.GetTempPath(), "copy_countryCopy");
112 | // var sfw = new ShapefileWriter(gc.Factory);
113 | // sfw.Write(write, gc);
114 | // Console.WriteLine("Write Complete!");
115 | // }
116 | // catch (Exception ex)
117 | // {
118 | // throw ex;
119 | // }
120 | //}
121 |
122 | private static GeometryCollection ReadShape(string shapepath)
123 | {
124 | if (!File.Exists(shapepath))
125 | throw new ArgumentException("File " + shapepath + " not found!");
126 |
127 | var reader = new ShapefileReader(shapepath);
128 | var geometries = reader.ReadAll();
129 | return geometries;
130 | }
131 |
132 | private static void WriteShape(GeometryCollection geometries, string shapepath)
133 | {
134 | if (File.Exists(shapepath))
135 | File.Delete(shapepath);
136 | var sfw = new ShapefileWriter(geometries.Factory);
137 | ShapefileWriter.WriteGeometryCollection(Path.GetFileNameWithoutExtension(shapepath), geometries);
138 | }
139 |
140 | private static void TestShapeReadWrite(string shapepath, string outputpath)
141 | {
142 | var collection = ReadShape(shapepath);
143 | WriteShape(collection, outputpath);
144 | var testcollection = ReadShape(outputpath);
145 |
146 | if (!collection.EqualsExact(testcollection))
147 | throw new ArgumentException("Geometries are not equals");
148 | Console.WriteLine("TEST OK!");
149 | }
150 | }
151 | }
152 |
--------------------------------------------------------------------------------
/test/NetTopologySuite.IO.ShapeFile.Test/Streams/ByteStreamProviderFixture.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.IO;
3 | using System.Text;
4 | using NetTopologySuite.IO.Streams;
5 | using NUnit.Framework;
6 |
7 | namespace NetTopologySuite.IO.ShapeFile.Test.Streams
8 | {
9 | [TestFixture]
10 | public class ByteStreamProviderFixture
11 | {
12 | [TestCase("This is sample text", 1252)]
13 | [TestCase("Dies sind deutsche Umlaute: Ää. Öö, Üü, ß", 1252)]
14 | [TestCase("Dies sind deutsche Umlaute: Ää. Öö, Üü, ß", 850)]
15 | [TestCase("Dies sind deutsche Umlaute: Ää. Öö, Üü, ß", 437)]
16 | public void TestConstructorText(string constructorText, int codepage)
17 | {
18 | var encoding = CodePagesEncodingProvider.Instance.GetEncoding(codepage);
19 |
20 | var bsp = new ByteStreamProvider("Test", constructorText, encoding);
21 | Assert.That(bsp.UnderlyingStreamIsReadonly, Is.True);
22 | Assert.That(bsp.Length, Is.EqualTo(constructorText.Length));
23 | Assert.That(bsp.Length == bsp.MaxLength, Is.True);
24 |
25 | using (var streamreader = new StreamReader(bsp.OpenRead(), encoding))
26 | {
27 | string streamText = streamreader.ReadToEnd();
28 | Assert.That(streamText, Is.EqualTo(constructorText));
29 | }
30 | }
31 |
32 | [TestCase(50, 50, true)]
33 | [TestCase(50, 100, true)]
34 | [TestCase(50, 50, false)]
35 | [TestCase(50, 100, false)]
36 | public void TestConstructor(int length, int maxLength, bool @readonly)
37 | {
38 | var bsp = new ByteStreamProvider("Test", CreateData(length), maxLength, @readonly);
39 | Assert.That(bsp.UnderlyingStreamIsReadonly, Is.EqualTo(@readonly));
40 | Assert.That(bsp.Length, Is.EqualTo(length));
41 | Assert.That(bsp.MaxLength, Is.EqualTo(maxLength));
42 |
43 | using (var ms = (MemoryStream)bsp.OpenRead())
44 | {
45 | byte[] data = ms.ToArray();
46 | Assert.That(data, Is.Not.Null);
47 | Assert.That(data.Length, Is.EqualTo(length));
48 | for (int i = 0; i < length; i++)
49 | Assert.That(data[i], Is.EqualTo(bsp.Buffer[i]));
50 | }
51 |
52 | try
53 | {
54 | using (var ms = (MemoryStream)bsp.OpenWrite(false))
55 | {
56 | var sw = new BinaryWriter(ms);
57 | sw.BaseStream.Position = 50;
58 | for (int i = 0; i < 10; i++)
59 | sw.Write((byte)i);
60 | sw.Flush();
61 | Assert.That(ms.Length, Is.EqualTo(length+10));
62 | Assert.That(bsp.Length, Is.EqualTo(length+10));
63 | Assert.That(bsp.Buffer[59], Is.EqualTo(9));
64 | }
65 | }
66 | catch (Exception ex)
67 | {
68 | if (ex is AssertionException)
69 | throw;
70 |
71 | if (!@readonly)
72 | {
73 | Assert.That(ex, Is.TypeOf(typeof(NotSupportedException)));
74 | Assert.That(length, Is.EqualTo(maxLength));
75 | }
76 | }
77 | }
78 |
79 | private static byte[] CreateData(int length)
80 | {
81 | var rnd = new Random();
82 |
83 | byte[] res = new byte[length];
84 | for (int i = 0; i < length; i++)
85 | res[i] = (byte) rnd.Next(0, 255);
86 | return res;
87 | }
88 | }
89 | }
90 |
--------------------------------------------------------------------------------
/test/NetTopologySuite.IO.ShapeFile.Test/Streams/ManagedStreamProviderFixture.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.IO;
3 | using System.Text;
4 | using NetTopologySuite.IO.Streams;
5 | using NUnit.Framework;
6 |
7 | namespace NetTopologySuite.IO.ShapeFile.Test.Streams
8 | {
9 | [TestFixture]
10 | public class ManagedStreamProviderFixture
11 | {
12 | [TestCase("This is sample text", 1252)]
13 | [TestCase("Dies sind deutsche Umlaute: Ää. Öö, Üü, ß", 1252)]
14 | [TestCase("Dies sind deutsche Umlaute: Ää. Öö, Üü, ß", 850)]
15 | [TestCase("Dies sind deutsche Umlaute: Ää. Öö, Üü, ß", 437)]
16 | public void TestConstructorText(string constructorText, int codepage)
17 | {
18 | var encoding = CodePagesEncodingProvider.Instance.GetEncoding(codepage);
19 |
20 | using (var memoryStream = new MemoryStream())
21 | {
22 | memoryStream.Write(encoding.GetBytes(constructorText));
23 | memoryStream.Position = 0;
24 | var bsp = new ExternallyManagedStreamProvider("Test", memoryStream);
25 |
26 | Assert.That(bsp.UnderlyingStreamIsReadonly, Is.False);
27 |
28 | using (var streamreader = new StreamReader(bsp.OpenRead(), encoding))
29 | {
30 | string streamText = streamreader.ReadToEnd();
31 | Assert.That(streamText, Is.EqualTo(constructorText));
32 | }
33 | }
34 | }
35 |
36 | [Test]
37 | public void TestWithReadonlyStream()
38 | {
39 | byte[] sourceData = CreateData(50);
40 | using var sourceStream = new MemoryStream(sourceData, 0, sourceData.Length, false);
41 | var provider = new ExternallyManagedStreamProvider("Test", sourceStream);
42 | Assert.That(provider.UnderlyingStreamIsReadonly);
43 |
44 | TestReading(provider, sourceData);
45 |
46 | Assert.That(() => provider.OpenWrite(false), Throws.InstanceOf());
47 | Assert.That(() => provider.OpenWrite(true), Throws.InstanceOf());
48 | }
49 |
50 | [Test]
51 | public void TestWithWritableStream()
52 | {
53 | byte[] sourceData = CreateData(50);
54 | using var sourceStream = new MemoryStream();
55 | sourceStream.Write(sourceData);
56 | sourceStream.Position = 0;
57 | var provider = new ExternallyManagedStreamProvider("Test", sourceStream);
58 | Assert.That(!provider.UnderlyingStreamIsReadonly);
59 |
60 | TestReading(provider, sourceData);
61 |
62 | // source stream position is now at the end.
63 | byte[] extraSourceData = CreateData(10);
64 | using var targetStream = provider.OpenWrite(false);
65 | targetStream.Write(extraSourceData);
66 | Assert.That(sourceStream, Has.Length.EqualTo(sourceData.Length + extraSourceData.Length));
67 | targetStream.Position = sourceData.Length;
68 | byte[] extraTargetData = new byte[extraSourceData.Length];
69 | int off = 0;
70 | while (off < extraTargetData.Length)
71 | {
72 | off += sourceStream.Read(extraTargetData.AsSpan(off));
73 | }
74 |
75 | Assert.That(extraTargetData, Is.EqualTo(extraSourceData));
76 |
77 | // original data shouldn't have been clobbered by that.
78 | sourceStream.Position = 0;
79 | sourceStream.SetLength(sourceData.Length);
80 | TestReading(provider, sourceData);
81 | }
82 |
83 | [Test]
84 | public void TestTruncate() {
85 | string test = "truncate string";
86 |
87 | using (var memoryStream = new MemoryStream())
88 | {
89 | memoryStream.Write(Encoding.ASCII.GetBytes(test));
90 | memoryStream.Position = 0;
91 | var bsp = new ExternallyManagedStreamProvider("Test", memoryStream);
92 | var stream = bsp.OpenWrite(true);
93 |
94 | Assert.That(stream.Length, Is.EqualTo(0));
95 | }
96 | }
97 |
98 | [Test]
99 | public void TestTruncateNonSeekableStream()
100 | {
101 | string test = "truncate string";
102 |
103 | using (var memoryStream = new NonSeekableStream())
104 | {
105 | try
106 | {
107 | memoryStream.Write(Encoding.ASCII.GetBytes(test));
108 | memoryStream.Position = 0;
109 | var bsp = new ExternallyManagedStreamProvider("Test", memoryStream);
110 | var stream = bsp.OpenWrite(true);
111 | }
112 | catch (InvalidOperationException ex)
113 | {
114 | Assert.AreEqual(ex.Message, "The underlying stream doesn't support seeking! You are unable to truncate the data.");
115 | }
116 |
117 | }
118 | }
119 |
120 | private static void TestReading(ExternallyManagedStreamProvider provider, byte[] sourceData)
121 | {
122 | using var copyTargetStream = new MemoryStream();
123 | using var copySourceStream = provider.OpenRead();
124 | copySourceStream.CopyTo(copyTargetStream);
125 | Assert.That(copyTargetStream.ToArray(), Is.EqualTo(sourceData));
126 | }
127 |
128 | private static byte[] CreateData(int length)
129 | {
130 | byte[] res = new byte[length];
131 | new Random().NextBytes(res);
132 | return res;
133 | }
134 |
135 | private class NonSeekableStream : MemoryStream
136 | {
137 | public override bool CanSeek => false;
138 | }
139 | }
140 | }
141 |
--------------------------------------------------------------------------------
/test/NetTopologySuite.IO.ShapeFile.Test/TestShapefiles/AllNulls.dbf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/NetTopologySuite/NetTopologySuite.IO.ShapeFile/d11dc5c304a20122dbc9152b5a7484c7649ecbcc/test/NetTopologySuite.IO.ShapeFile.Test/TestShapefiles/AllNulls.dbf
--------------------------------------------------------------------------------
/test/NetTopologySuite.IO.ShapeFile.Test/TestShapefiles/AllNulls.shp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/NetTopologySuite/NetTopologySuite.IO.ShapeFile/d11dc5c304a20122dbc9152b5a7484c7649ecbcc/test/NetTopologySuite.IO.ShapeFile.Test/TestShapefiles/AllNulls.shp
--------------------------------------------------------------------------------
/test/NetTopologySuite.IO.ShapeFile.Test/TestShapefiles/CA_Cable_region.shp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/NetTopologySuite/NetTopologySuite.IO.ShapeFile/d11dc5c304a20122dbc9152b5a7484c7649ecbcc/test/NetTopologySuite.IO.ShapeFile.Test/TestShapefiles/CA_Cable_region.shp
--------------------------------------------------------------------------------
/test/NetTopologySuite.IO.ShapeFile.Test/TestShapefiles/EmptyShapeFile.shp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/NetTopologySuite/NetTopologySuite.IO.ShapeFile/d11dc5c304a20122dbc9152b5a7484c7649ecbcc/test/NetTopologySuite.IO.ShapeFile.Test/TestShapefiles/EmptyShapeFile.shp
--------------------------------------------------------------------------------
/test/NetTopologySuite.IO.ShapeFile.Test/TestShapefiles/Issue167.shp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/NetTopologySuite/NetTopologySuite.IO.ShapeFile/d11dc5c304a20122dbc9152b5a7484c7649ecbcc/test/NetTopologySuite.IO.ShapeFile.Test/TestShapefiles/Issue167.shp
--------------------------------------------------------------------------------
/test/NetTopologySuite.IO.ShapeFile.Test/TestShapefiles/Sept_polygones.dbf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/NetTopologySuite/NetTopologySuite.IO.ShapeFile/d11dc5c304a20122dbc9152b5a7484c7649ecbcc/test/NetTopologySuite.IO.ShapeFile.Test/TestShapefiles/Sept_polygones.dbf
--------------------------------------------------------------------------------
/test/NetTopologySuite.IO.ShapeFile.Test/TestShapefiles/Sept_polygones.shp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/NetTopologySuite/NetTopologySuite.IO.ShapeFile/d11dc5c304a20122dbc9152b5a7484c7649ecbcc/test/NetTopologySuite.IO.ShapeFile.Test/TestShapefiles/Sept_polygones.shp
--------------------------------------------------------------------------------
/test/NetTopologySuite.IO.ShapeFile.Test/TestShapefiles/US_DMA_region.dbf:
--------------------------------------------------------------------------------
1 | k a a NAME C @ KEYINFO C
San Francisco-Oakland-San Jose, CA 807
--------------------------------------------------------------------------------
/test/NetTopologySuite.IO.ShapeFile.Test/TestShapefiles/US_DMA_region.shp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/NetTopologySuite/NetTopologySuite.IO.ShapeFile/d11dc5c304a20122dbc9152b5a7484c7649ecbcc/test/NetTopologySuite.IO.ShapeFile.Test/TestShapefiles/US_DMA_region.shp
--------------------------------------------------------------------------------
/test/NetTopologySuite.IO.ShapeFile.Test/TestShapefiles/UnifiedChecksMaterial.dbf:
--------------------------------------------------------------------------------
1 | _ A Q ShapeName C P
Rectangle Triangle
--------------------------------------------------------------------------------
/test/NetTopologySuite.IO.ShapeFile.Test/TestShapefiles/UnifiedChecksMaterial.shp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/NetTopologySuite/NetTopologySuite.IO.ShapeFile/d11dc5c304a20122dbc9152b5a7484c7649ecbcc/test/NetTopologySuite.IO.ShapeFile.Test/TestShapefiles/UnifiedChecksMaterial.shp
--------------------------------------------------------------------------------
/test/NetTopologySuite.IO.ShapeFile.Test/TestShapefiles/UnifiedChecksMaterialNullAtEnd.shp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/NetTopologySuite/NetTopologySuite.IO.ShapeFile/d11dc5c304a20122dbc9152b5a7484c7649ecbcc/test/NetTopologySuite.IO.ShapeFile.Test/TestShapefiles/UnifiedChecksMaterialNullAtEnd.shp
--------------------------------------------------------------------------------
/test/NetTopologySuite.IO.ShapeFile.Test/TestShapefiles/UnifiedChecksMaterialNullAtStart.shp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/NetTopologySuite/NetTopologySuite.IO.ShapeFile/d11dc5c304a20122dbc9152b5a7484c7649ecbcc/test/NetTopologySuite.IO.ShapeFile.Test/TestShapefiles/UnifiedChecksMaterialNullAtStart.shp
--------------------------------------------------------------------------------
/test/NetTopologySuite.IO.ShapeFile.Test/TestShapefiles/UnifiedChecksMaterialNullInMiddle.shp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/NetTopologySuite/NetTopologySuite.IO.ShapeFile/d11dc5c304a20122dbc9152b5a7484c7649ecbcc/test/NetTopologySuite.IO.ShapeFile.Test/TestShapefiles/UnifiedChecksMaterialNullInMiddle.shp
--------------------------------------------------------------------------------
/test/NetTopologySuite.IO.ShapeFile.Test/TestShapefiles/Victoria North.dbf:
--------------------------------------------------------------------------------
1 | x aL W cropId C P fieldName C P totalAcres C P plantedAcr C P fillColor C P fillOpacit N strokeColo C P strokeOpac N strokeWidt N farmName C P
9788 Matt George Victoria North 24.00 24.00 #C0C000 40#C0C000 100 2 9788 Matt George Victoria North 24.00 24.00 #C0C000 40#C0C000 100 2
--------------------------------------------------------------------------------
/test/NetTopologySuite.IO.ShapeFile.Test/TestShapefiles/Victoria North.shp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/NetTopologySuite/NetTopologySuite.IO.ShapeFile/d11dc5c304a20122dbc9152b5a7484c7649ecbcc/test/NetTopologySuite.IO.ShapeFile.Test/TestShapefiles/Victoria North.shp
--------------------------------------------------------------------------------
/test/NetTopologySuite.IO.ShapeFile.Test/TestShapefiles/Victoria North.shx:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/NetTopologySuite/NetTopologySuite.IO.ShapeFile/d11dc5c304a20122dbc9152b5a7484c7649ecbcc/test/NetTopologySuite.IO.ShapeFile.Test/TestShapefiles/Victoria North.shx
--------------------------------------------------------------------------------
/test/NetTopologySuite.IO.ShapeFile.Test/TestShapefiles/Volume2.shp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/NetTopologySuite/NetTopologySuite.IO.ShapeFile/d11dc5c304a20122dbc9152b5a7484c7649ecbcc/test/NetTopologySuite.IO.ShapeFile.Test/TestShapefiles/Volume2.shp
--------------------------------------------------------------------------------
/test/NetTopologySuite.IO.ShapeFile.Test/TestShapefiles/__emptyShapefile.dbf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/NetTopologySuite/NetTopologySuite.IO.ShapeFile/d11dc5c304a20122dbc9152b5a7484c7649ecbcc/test/NetTopologySuite.IO.ShapeFile.Test/TestShapefiles/__emptyShapefile.dbf
--------------------------------------------------------------------------------
/test/NetTopologySuite.IO.ShapeFile.Test/TestShapefiles/__emptyShapefile.shp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/NetTopologySuite/NetTopologySuite.IO.ShapeFile/d11dc5c304a20122dbc9152b5a7484c7649ecbcc/test/NetTopologySuite.IO.ShapeFile.Test/TestShapefiles/__emptyShapefile.shp
--------------------------------------------------------------------------------
/test/NetTopologySuite.IO.ShapeFile.Test/TestShapefiles/__emptyShapefile.shx:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/NetTopologySuite/NetTopologySuite.IO.ShapeFile/d11dc5c304a20122dbc9152b5a7484c7649ecbcc/test/NetTopologySuite.IO.ShapeFile.Test/TestShapefiles/__emptyShapefile.shx
--------------------------------------------------------------------------------
/test/NetTopologySuite.IO.ShapeFile.Test/TestShapefiles/afvalbakken.dbf:
--------------------------------------------------------------------------------
1 | l a 8 W type C 2 CODE C
papier glas papier glas papier glas papier glas glas glas glas glas glas papier glas papier papier papier papier glas papier glas papier glas papier papier
--------------------------------------------------------------------------------
/test/NetTopologySuite.IO.ShapeFile.Test/TestShapefiles/afvalbakken.shp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/NetTopologySuite/NetTopologySuite.IO.ShapeFile/d11dc5c304a20122dbc9152b5a7484c7649ecbcc/test/NetTopologySuite.IO.ShapeFile.Test/TestShapefiles/afvalbakken.shp
--------------------------------------------------------------------------------
/test/NetTopologySuite.IO.ShapeFile.Test/TestShapefiles/chinese_encoding.dbf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/NetTopologySuite/NetTopologySuite.IO.ShapeFile/d11dc5c304a20122dbc9152b5a7484c7649ecbcc/test/NetTopologySuite.IO.ShapeFile.Test/TestShapefiles/chinese_encoding.dbf
--------------------------------------------------------------------------------
/test/NetTopologySuite.IO.ShapeFile.Test/TestShapefiles/chinese_encoding.shp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/NetTopologySuite/NetTopologySuite.IO.ShapeFile/d11dc5c304a20122dbc9152b5a7484c7649ecbcc/test/NetTopologySuite.IO.ShapeFile.Test/TestShapefiles/chinese_encoding.shp
--------------------------------------------------------------------------------
/test/NetTopologySuite.IO.ShapeFile.Test/TestShapefiles/chinese_encoding.shx:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/NetTopologySuite/NetTopologySuite.IO.ShapeFile/d11dc5c304a20122dbc9152b5a7484c7649ecbcc/test/NetTopologySuite.IO.ShapeFile.Test/TestShapefiles/chinese_encoding.shx
--------------------------------------------------------------------------------
/test/NetTopologySuite.IO.ShapeFile.Test/TestShapefiles/christchurch-canterbury-h.shp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/NetTopologySuite/NetTopologySuite.IO.ShapeFile/d11dc5c304a20122dbc9152b5a7484c7649ecbcc/test/NetTopologySuite.IO.ShapeFile.Test/TestShapefiles/christchurch-canterbury-h.shp
--------------------------------------------------------------------------------
/test/NetTopologySuite.IO.ShapeFile.Test/TestShapefiles/crustal_test.dbf:
--------------------------------------------------------------------------------
1 | j a3 DGC_CODICE N
2 | ID_GTR C NAME_ZONE C d ID_ZONE C LAMBDA0 N BETA N M0 N MMAX_EXP N ZMIN N ZMAX N
1PRZ01 PRZ01 1.675700000000000 1.640800000000000 4.000000000000000 8.600000000000000 15.000000000000000 15.000000000000000 2PRZ02 PRZ02 3.245800000000000 1.387800000000000 3.000000000000000 8.699999999999999 10.000000000000000 10.000000000000000 3PRZ03 PRZ03 1.560300000000000 1.639200000000000 4.000000000000000 8.400000000000000 6.000000000000000 6.000000000000000 4PRZ04 PRZ04 2.993500000000000 1.389900000000000 3.000000000000000 7.800000000000000 6.000000000000000 6.000000000000000 5PRZ05 PRZ05 1.510000000000000 2.120400000000000 4.000000000000000 7.500000000000000 5.000000000000000 5.000000000000000 6PRZ06 PRZ06 2.337700000000000 1.597100000000000 3.000000000000000 7.400000000000000 10.000000000000000 10.000000000000000 7CHZ01 CHZ01 4.116000000000000 1.605300000000000 4.000000000000000 7.600000000000000 6.000000000000000 6.000000000000000 8CHZ02 CHZ02 0.653000000000000 1.572900000000000 4.500000000000000 8.900000000000000 5.000000000000000 5.000000000000000 9CHZ04 CHZ04 11.620100000000001 1.373300000000000 3.000000000000000 8.000000000000000 6.000000000000000 6.000000000000000 10CHZ05 CHZ05 0.130600000000000 1.640100000000000 4.000000000000000 8.000000000000000 5.000000000000000 5.000000000000000 11CHZ07 CHZ07 0.726700000000000 1.807100000000000 4.000000000000000 7.000000000000000 15.000000000000000 15.000000000000000 12CHZ08 CHZ08 1.042600000000000 1.682700000000000 4.000000000000000 7.500000000000000 6.000000000000000 6.000000000000000 13CHZ09 CHZ09 4.697300000000000 1.630000000000000 4.000000000000000 8.000000000000000 5.000000000000000 5.000000000000000 14CHZ10 CHZ10 0.163100000000000 1.506100000000000 4.000000000000000 6.500000000000000 10.000000000000000 10.000000000000000 15CHZ11 CHZ11 0.912300000000000 1.341800000000000 4.000000000000000 8.300000000000001 6.000000000000000 6.000000000000000 16CHZ12 CHZ12 4.195000000000000 1.524000000000000 4.000000000000000 6.800000000000000 6.000000000000000 6.000000000000000 17CHZ03 CHZ03 0.399500000000000 2.165400000000000 4.000000000000000 6.000000000000000 6.000000000000000 6.000000000000000 18BOZ01 BOZ01 3.378300000000000 1.225000000000000 3.000000000000000 7.400000000000000 10.000000000000000 10.000000000000000 19CHZ06 CHZ06 0.805200000000000 1.404000000000000 4.000000000000000 7.600000000000000 6.000000000000000 6.000000000000000
--------------------------------------------------------------------------------
/test/NetTopologySuite.IO.ShapeFile.Test/TestShapefiles/crustal_test.shp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/NetTopologySuite/NetTopologySuite.IO.ShapeFile/d11dc5c304a20122dbc9152b5a7484c7649ecbcc/test/NetTopologySuite.IO.ShapeFile.Test/TestShapefiles/crustal_test.shp
--------------------------------------------------------------------------------
/test/NetTopologySuite.IO.ShapeFile.Test/TestShapefiles/crustal_test_bugged.dbf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/NetTopologySuite/NetTopologySuite.IO.ShapeFile/d11dc5c304a20122dbc9152b5a7484c7649ecbcc/test/NetTopologySuite.IO.ShapeFile.Test/TestShapefiles/crustal_test_bugged.dbf
--------------------------------------------------------------------------------
/test/NetTopologySuite.IO.ShapeFile.Test/TestShapefiles/crustal_test_bugged.shp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/NetTopologySuite/NetTopologySuite.IO.ShapeFile/d11dc5c304a20122dbc9152b5a7484c7649ecbcc/test/NetTopologySuite.IO.ShapeFile.Test/TestShapefiles/crustal_test_bugged.shp
--------------------------------------------------------------------------------
/test/NetTopologySuite.IO.ShapeFile.Test/TestShapefiles/date.dbf:
--------------------------------------------------------------------------------
1 | j a W ID N THEDATE D
020060310
--------------------------------------------------------------------------------
/test/NetTopologySuite.IO.ShapeFile.Test/TestShapefiles/error_union.shp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/NetTopologySuite/NetTopologySuite.IO.ShapeFile/d11dc5c304a20122dbc9152b5a7484c7649ecbcc/test/NetTopologySuite.IO.ShapeFile.Test/TestShapefiles/error_union.shp
--------------------------------------------------------------------------------
/test/NetTopologySuite.IO.ShapeFile.Test/TestShapefiles/line_ed50_geo.dbf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/NetTopologySuite/NetTopologySuite.IO.ShapeFile/d11dc5c304a20122dbc9152b5a7484c7649ecbcc/test/NetTopologySuite.IO.ShapeFile.Test/TestShapefiles/line_ed50_geo.dbf
--------------------------------------------------------------------------------
/test/NetTopologySuite.IO.ShapeFile.Test/TestShapefiles/line_ed50_geo.shp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/NetTopologySuite/NetTopologySuite.IO.ShapeFile/d11dc5c304a20122dbc9152b5a7484c7649ecbcc/test/NetTopologySuite.IO.ShapeFile.Test/TestShapefiles/line_ed50_geo.shp
--------------------------------------------------------------------------------
/test/NetTopologySuite.IO.ShapeFile.Test/TestShapefiles/line_ed50_utm36.shp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/NetTopologySuite/NetTopologySuite.IO.ShapeFile/d11dc5c304a20122dbc9152b5a7484c7649ecbcc/test/NetTopologySuite.IO.ShapeFile.Test/TestShapefiles/line_ed50_utm36.shp
--------------------------------------------------------------------------------
/test/NetTopologySuite.IO.ShapeFile.Test/TestShapefiles/line_wgs84_geo.shp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/NetTopologySuite/NetTopologySuite.IO.ShapeFile/d11dc5c304a20122dbc9152b5a7484c7649ecbcc/test/NetTopologySuite.IO.ShapeFile.Test/TestShapefiles/line_wgs84_geo.shp
--------------------------------------------------------------------------------
/test/NetTopologySuite.IO.ShapeFile.Test/TestShapefiles/point_ed50_geo.dbf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/NetTopologySuite/NetTopologySuite.IO.ShapeFile/d11dc5c304a20122dbc9152b5a7484c7649ecbcc/test/NetTopologySuite.IO.ShapeFile.Test/TestShapefiles/point_ed50_geo.dbf
--------------------------------------------------------------------------------
/test/NetTopologySuite.IO.ShapeFile.Test/TestShapefiles/point_ed50_geo.shp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/NetTopologySuite/NetTopologySuite.IO.ShapeFile/d11dc5c304a20122dbc9152b5a7484c7649ecbcc/test/NetTopologySuite.IO.ShapeFile.Test/TestShapefiles/point_ed50_geo.shp
--------------------------------------------------------------------------------
/test/NetTopologySuite.IO.ShapeFile.Test/TestShapefiles/polygon intersecting line.shp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/NetTopologySuite/NetTopologySuite.IO.ShapeFile/d11dc5c304a20122dbc9152b5a7484c7649ecbcc/test/NetTopologySuite.IO.ShapeFile.Test/TestShapefiles/polygon intersecting line.shp
--------------------------------------------------------------------------------
/test/NetTopologySuite.IO.ShapeFile.Test/TestShapefiles/polygon_ed50_geo.shp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/NetTopologySuite/NetTopologySuite.IO.ShapeFile/d11dc5c304a20122dbc9152b5a7484c7649ecbcc/test/NetTopologySuite.IO.ShapeFile.Test/TestShapefiles/polygon_ed50_geo.shp
--------------------------------------------------------------------------------
/test/NetTopologySuite.IO.ShapeFile.Test/TestShapefiles/polygon_wgs84_geo.shp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/NetTopologySuite/NetTopologySuite.IO.ShapeFile/d11dc5c304a20122dbc9152b5a7484c7649ecbcc/test/NetTopologySuite.IO.ShapeFile.Test/TestShapefiles/polygon_wgs84_geo.shp
--------------------------------------------------------------------------------
/test/NetTopologySuite.IO.ShapeFile.Test/TestShapefiles/shape_PointZM.shp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/NetTopologySuite/NetTopologySuite.IO.ShapeFile/d11dc5c304a20122dbc9152b5a7484c7649ecbcc/test/NetTopologySuite.IO.ShapeFile.Test/TestShapefiles/shape_PointZM.shp
--------------------------------------------------------------------------------
/test/NetTopologySuite.IO.ShapeFile.Test/TestShapefiles/shape_pointM.shp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/NetTopologySuite/NetTopologySuite.IO.ShapeFile/d11dc5c304a20122dbc9152b5a7484c7649ecbcc/test/NetTopologySuite.IO.ShapeFile.Test/TestShapefiles/shape_pointM.shp
--------------------------------------------------------------------------------
/test/NetTopologySuite.IO.ShapeFile.Test/TestShapefiles/shape_pointZM_MissingM values.shp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/NetTopologySuite/NetTopologySuite.IO.ShapeFile/d11dc5c304a20122dbc9152b5a7484c7649ecbcc/test/NetTopologySuite.IO.ShapeFile.Test/TestShapefiles/shape_pointZM_MissingM values.shp
--------------------------------------------------------------------------------
/test/NetTopologySuite.IO.ShapeFile.Test/TestShapefiles/tnp_pol.shp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/NetTopologySuite/NetTopologySuite.IO.ShapeFile/d11dc5c304a20122dbc9152b5a7484c7649ecbcc/test/NetTopologySuite.IO.ShapeFile.Test/TestShapefiles/tnp_pol.shp
--------------------------------------------------------------------------------
/test/NetTopologySuite.IO.ShapeFile.Test/TestShapefiles/with_M.dbf:
--------------------------------------------------------------------------------
1 | o7 a - W LINE_NAME C ( Year N
1000-103 0 1008-103 0 1016-103 0 1024-103 0 1032-103 0 1034-105 0 1040-103 0 1042-105 0 1046-105 0 1048-103 0 1050-105 0 1058-105 0 1062-105 0 1066-105 0 1070-105 0 1078-105 0 1082-105 0 1090-105 0 1205B-105 0 1243B-105 0 1267B-105 0 1281B-105 0 1295B-105 0 1309B-105 0 1323B-105 0 1337B-105 0 1351B-105 0 1365B-105 0 213A-103 0 736-103 0 742-103 0 750-103 0 758-103 0 768-103 0 776-103 0 786-103 0 792-103 0 800-103 0 808-103 0 816-103 0 824-103 0 832-103 0 840-103 0 848-103 0 858-103 0 862-103 0 872-103 0 880-103 0 886-103 0 896-103 0 906-103 0 912-103 0 968-103 0 984-103 0 992-103 0
--------------------------------------------------------------------------------
/test/NetTopologySuite.IO.ShapeFile.Test/TestShapefiles/with_M.shp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/NetTopologySuite/NetTopologySuite.IO.ShapeFile/d11dc5c304a20122dbc9152b5a7484c7649ecbcc/test/NetTopologySuite.IO.ShapeFile.Test/TestShapefiles/with_M.shp
--------------------------------------------------------------------------------
/test/NetTopologySuite.IO.ShapeFile.Test/Various/CascadedPolygonUnionFixture.cs:
--------------------------------------------------------------------------------
1 | using NetTopologySuite.Geometries;
2 | using NetTopologySuite.Operation.Overlay;
3 | using NetTopologySuite.Operation.Overlay.Snap;
4 | using NetTopologySuite.Operation.Union;
5 | using NUnit.Framework;
6 | using System;
7 | using System.Linq;
8 |
9 | namespace NetTopologySuite.IO.ShapeFile.Test.Various
10 | {
11 | [TestFixture]
12 | public class CascadedPolygonUnionFixture
13 | {
14 | protected GeometryFactory Factory { get; private set; }
15 |
16 | protected WKTReader Reader { get; private set; }
17 |
18 | public CascadedPolygonUnionFixture()
19 | {
20 | // Set current dir to shapefiles dir
21 | Environment.CurrentDirectory = CommonHelpers.TestShapefilesDirectory;
22 |
23 | this.Factory = new GeometryFactory();
24 | this.Reader = new WKTReader();
25 | }
26 |
27 | [Test]
28 | public void PerformCascadedPolygonUnion()
29 | {
30 | var reader = new ShapefileReader("tnp_pol.shp");
31 | var collection = reader.ReadAll().Where(e => e is Polygon).ToList();
32 | var u1 = collection[0];
33 | for (int i = 1; i < collection.Count; i++)
34 | u1 = SnapIfNeededOverlayOp.Overlay(u1, collection[i], SpatialFunction.Union);
35 | var u2 = CascadedPolygonUnion.Union(collection);
36 | if (!u1.EqualsTopologically(u2))
37 | Assert.Fail("failure");
38 | }
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/test/NetTopologySuite.IO.ShapeFile.Test/Various/NormalizeTest.cs:
--------------------------------------------------------------------------------
1 | using NetTopologySuite.Geometries;
2 | using NUnit.Framework;
3 |
4 | namespace NetTopologySuite.IO.ShapeFile.Test.Various
5 | {
6 | ///
7 | ///
8 | ///
9 | [TestFixture]
10 | public class NormalizeTest
11 | {
12 | protected GeometryFactory Factory { get; private set; }
13 |
14 | protected WKTReader Reader { get; private set; }
15 |
16 | private Polygon _polygon = null;
17 | private LinearRing _shell = null;
18 | private LinearRing _hole = null;
19 |
20 | ///
21 | /// Initializes a new instance of the class.
22 | ///
23 | public NormalizeTest() : base() { }
24 |
25 | ///
26 | /// Method called prior to every test in this fixture
27 | ///
28 | [SetUp]
29 | public void Init()
30 | {
31 | this.Factory = new GeometryFactory();
32 | this.Reader = new WKTReader();
33 |
34 | _shell = Factory.CreateLinearRing(new Coordinate[] { new Coordinate(100,100),
35 | new Coordinate(200,100),
36 | new Coordinate(200,200),
37 | new Coordinate(100,200),
38 | new Coordinate(100,100), });
39 | // NOTE: Hole is created with not correct order for holes
40 | _hole = Factory.CreateLinearRing(new Coordinate[] { new Coordinate(120,120),
41 | new Coordinate(180,120),
42 | new Coordinate(180,180),
43 | new Coordinate(120,180),
44 | new Coordinate(120,120), });
45 | _polygon = Factory.CreatePolygon(_shell, new LinearRing[] { _hole, });
46 | }
47 |
48 | ///
49 | ///
50 | ///
51 | [Test]
52 | public void NotNormalizedGDBOperation()
53 | {
54 | byte[] bytes = new GDBWriter().Write(_polygon);
55 | var test = new GDBReader().Read(bytes);
56 |
57 | //This is no longer true
58 | //Assert.IsNull(test);
59 | Assert.IsTrue(test.IsEmpty);
60 | Assert.IsTrue(test is IPolygonal);
61 | }
62 |
63 | ///
64 | ///
65 | ///
66 | [Test]
67 | public void NormalizedGDBOperation()
68 | {
69 | _polygon.Normalize();
70 |
71 | byte[] bytes = new GDBWriter().Write(_polygon);
72 | var test = new GDBReader().Read(bytes);
73 |
74 | Assert.IsNotNull(test);
75 | Assert.IsTrue(_polygon.EqualsExact(test));
76 | }
77 | }
78 | }
79 |
--------------------------------------------------------------------------------
/test/NetTopologySuite.IO.ShapeFile.Test/WKTReaderTests.cs:
--------------------------------------------------------------------------------
1 | using NetTopologySuite.Geometries;
2 | using NUnit.Framework;
3 |
4 | namespace NetTopologySuite.IO.ShapeFile.Test
5 | {
6 | public class WKTReaderTests
7 | {
8 | private readonly WKTReader _wktReader;
9 |
10 | public WKTReaderTests()
11 | {
12 | _wktReader = new WKTReader(new GeometryFactory(new PrecisionModel(), 4326)) { IsOldNtsCoordinateSyntaxAllowed = false };
13 | }
14 |
15 | [Test]
16 | public void TestShapeType()
17 | {
18 | string wkt = "POLYGON ((-86.7605020509258 41.5101338613656, -86.7604972038273 41.5100611525915, -86.7604971708084 41.5100606308085, -86.7604611720717 41.5094596307695, -86.7604611426546 41.5094591103497, -86.7604291439208 41.5088571103154, -86.760429130715 41.508856853856, -86.7603991319814 41.5082548538241, -86.7603991259966 41.5082547317887, -86.7603701303631 41.5076537960468, -86.7603401446338 41.5070530565908, -86.7603071566895 41.5064532528163, -86.7603071500912 41.506453131098, -86.7602814240795 41.5059715533315, -86.7605549835241 41.5059607024218, -86.7605808466407 41.5064448078787, -86.760613844555 41.5070447469854, -86.7606138651484 41.5070451395365, -86.7606438664126 41.5076461395046, -86.7606438727239 41.5076462680791, -86.7606728710439 41.5082472070294, -86.7607028628788 41.5088490177453, -86.7607348434949 41.5094506292495, -86.7607708135428 41.5100511081057, -86.760776407335 41.5101350123382, -86.7605020509258 41.5101338613656))";
19 | var geometry = (Polygon)_wktReader.Read(wkt);
20 |
21 | Assert.IsTrue(geometry.Shell.CoordinateSequence.Ordinates == Ordinates.XY);
22 | Assert.IsTrue(Shapefile.GetShapeType(geometry) == ShapeGeometryType.Polygon);
23 | }
24 | }
25 | }
26 |
--------------------------------------------------------------------------------