コード例 #1
0
        public void Read_ReturnsNullIfNoMoreGeometriesAreAvailable()
        {
            WkbReader target = new WkbReader(TestDataReader.Open("point-3DM.wkb"));

            target.Read();
            Geometry parsed = target.Read();

            Assert.Null(parsed);
        }
コード例 #2
0
        public void ReadT_ReturnsNullIfNoMoreGeometriesAreAvailable()
        {
            WkbReader target = new WkbReader(new MemoryStream(Data.IOTestData.point_3DM));

            target.Read <Point>();
            Geometry parsed = target.Read <Point>();

            Assert.Null(parsed);
        }
コード例 #3
0
        public void Read_ReadsMultipleGeometries()
        {
            Point expected1 = (Point)this.ParseWKT("point zm (-10.1 15.5 100.5 1000.5)");
            Point expected2 = (Point)this.ParseWKT("point zm (-10.2 15.6 100.6 1000.6)");

            WkbReader target = new WkbReader(TestDataReader.Open("two-points-3DM.wkb"));

            Point parsed1 = (Point)target.Read();

            this.ComparePoints(parsed1, expected1);

            Point parsed2 = (Point)target.Read();

            this.ComparePoints(parsed2, expected2);
        }
コード例 #4
0
        public void Read_ReadsMultipleGeometries()
        {
            Point expected1 = (Point)this.ParseWKT("point zm (-10.1 15.5 100.5 1000.5)");
            Point expected2 = (Point)this.ParseWKT("point zm (-10.2 15.6 100.6 1000.6)");

            WkbReader target = new WkbReader(new MemoryStream(Data.IOTestData.two_points_3DM));

            Point parsed1 = (Point)target.Read();

            this.ComparePoints(parsed1, expected1);

            Point parsed2 = (Point)target.Read();

            this.ComparePoints(parsed2, expected2);
        }
コード例 #5
0
        public void Buffer()
        {
            Coordinate[] c   = new Coordinate[36];
            Random       rnd = new Random();

            for (int i = 0; i < 36; i++)
            {
                c[i] = new Coordinate((rnd.NextDouble() + 360) - 180, (rnd.NextDouble() * 180) - 90);
            }
            MultiPoint mps = new MultiPoint(c);

            byte[]     vals     = mps.ToBinary();
            WkbReader  wkb      = new WkbReader();
            IGeometry  g        = wkb.Read(vals);
            MultiPoint mpsCheck = g as MultiPoint;

            if (mpsCheck != null)
            {
                Assert.AreEqual(mps.Buffer(200).Area, mpsCheck.Buffer(200).Area);
            }
            else
            {
                Assert.Fail("The test failed because the MpsCheck  was null.");
            }
        }
コード例 #6
0
        public void If_input_a_null_string_then_should_throw_exception()
        {
            string wkbHex = null;

            Should.Throw <ArgumentException>(() => WkbReader.Read(wkbHex))
            .Message.ShouldBe("Invalid hex wkb string");
        }
コード例 #7
0
        public void If_input_valid_multipolygon_with_lower_endian_then_should_return_correct_multipolygon()
        {
            const string hex       = "010600000002000000010300000001000000040000000000000000003e40000000000000344000000000008046400000000000004440000000000000244000000000000044400000000000003e400000000000003440010300000001000000050000000000000000002e4000000000000014400000000000004440000000000000244000000000000024400000000000003440000000000000144000000000000024400000000000002e400000000000001440";
            var          expectGeo = new MultiPolygon(new List <Polygon>
            {
                new Polygon(new List <Point>
                {
                    new Point(30, 20),
                    new Point(45, 40),
                    new Point(10, 40),
                    new Point(30, 20)
                }),
                new Polygon(new List <Point>
                {
                    new Point(15, 5),
                    new Point(40, 10),
                    new Point(10, 20),
                    new Point(5, 10),
                    new Point(15, 5)
                })
            });

            var geoResult = WkbReader.Read(hex);

            geoResult.Equals(expectGeo).ShouldBeTrue();
        }
コード例 #8
0
        public void MultiLsToByteArray()
        {
            var rnd = new Random();
            var ls  = new LineString[40];

            for (var ii = 0; ii < 40; ii++)
            {
                var coord = new Coordinate[36];
                for (var i = 0; i < 36; i++)
                {
                    coord[i] = new Coordinate((rnd.NextDouble() * 360) - 180, (rnd.NextDouble() * 180) - 90);
                }
                ls[ii] = new LineString(coord);
            }
            var mls      = new MultiLineString(ls);
            var vals     = mls.ToBinary();
            var wkr      = new WkbReader();
            var g        = wkr.Read(vals);
            var mlscheck = g as MultiLineString;

            if (mlscheck != null)
            {
                for (var ii = 0; ii < mls.Coordinates.Count; ii++)
                {
                    Assert.AreEqual(mls.Coordinates[ii].X, mlscheck.Coordinates[ii].X);
                    Assert.AreEqual(mls.Coordinates[ii].Y, mlscheck.Coordinates[ii].Y);
                }
            }
            else
            {
                Assert.Fail("The test failed bc the check multilinestring was null.");
            }
        }
コード例 #9
0
        public void MultipolygonToByteArray()
        {
            var rnd = new Random();
            var pg  = new Polygon[50];

            for (var i = 0; i < 50; i++)
            {
                var center = new Coordinate((rnd.NextDouble() * 360) - 180, (rnd.NextDouble() * 180) - 90);
                var coord  = new Coordinate[36];
                for (var ii = 0; ii < 36; ii++)
                {
                    coord[ii] = new Coordinate(center.X + Math.Cos((ii * 10) * Math.PI / 10), center.Y + (ii * 10) * Math.PI / 10);
                }
                coord[35] = new Coordinate(coord[0].X, coord[0].Y);
                pg[i]     = new Polygon(coord);
            }
            var mpg      = new MultiPolygon(pg);
            var vals     = mpg.ToBinary();
            var wkr      = new WkbReader();
            var g        = wkr.Read(vals);
            var mpgcheck = g as MultiPolygon;

            if (mpgcheck != null)
            {
                for (var ii = 0; ii < mpg.Coordinates.Count; ii++)
                {
                    Assert.AreEqual(mpg.Coordinates[ii].X, mpgcheck.Coordinates[ii].X);
                    Assert.AreEqual(mpg.Coordinates[ii].Y, mpgcheck.Coordinates[ii].Y);
                }
            }
            else
            {
                Assert.Fail("The test failed bc the check mpgcheck was null.");
            }
        }
コード例 #10
0
        public void LsToByteArray()
        {
            var coords = new Coordinate[36];
            var rnd    = new Random();

            for (var i = 0; i < 36; i++)
            {
                coords[i] = new Coordinate((rnd.NextDouble() * 360) - 180, (rnd.NextDouble() * 180) - 90);
            }
            var ls      = new LineString(coords);
            var vals    = ls.ToBinary();
            var wkr     = new WkbReader();
            var g       = wkr.Read(vals);
            var lscheck = g as LineString;

            if (lscheck != null)
            {
                for (var i = 0; i < ls.Count; i++)
                {
                    Assert.AreEqual(ls.Coordinates[i].X, lscheck.Coordinates[i].X);
                    Assert.AreEqual(ls.Coordinates[i].Y, lscheck.Coordinates[i].Y);
                }
                Assert.AreEqual(ls.Length, lscheck.Length);
                Assert.AreEqual(ls.Envelope.Height, lscheck.Envelope.Height);
                Assert.AreEqual(ls.Envelope.Width, lscheck.Envelope.Width);
            }
            else
            {
                Assert.Fail("The test failed bc the check lscheck was null.");
            }
        }
コード例 #11
0
        public void MultiPointToByteArray()
        {
            var c   = new Coordinate[36];
            var rnd = new Random();

            for (var i = 0; i < 36; i++)
            {
                c[i] = new Coordinate((rnd.NextDouble() + 360) - 180, (rnd.NextDouble() * 180) - 90);
            }
            var mps      = new MultiPoint(c);
            var vals     = mps.ToBinary();
            var wkb      = new WkbReader();
            var g        = wkb.Read(vals);
            var mpsCheck = g as MultiPoint;

            if (mpsCheck != null)
            {
                for (var ii = 0; ii < mps.Coordinates.Count; ii++)
                {
                    Assert.AreEqual(mps.Coordinates[ii].X, mpsCheck.Coordinates[ii].X);
                    Assert.AreEqual(mps.Coordinates[ii].Y, mpsCheck.Coordinates[ii].Y);
                }
            }
            else
            {
                Assert.Fail("The test failed because the MpsCheck  was null.");
            }
        }
コード例 #12
0
        public static void PopulateFeatureSet(IEnumerable <JoobGeometry> geometries, IFeatureSet featureSet)
        {
            if (geometries != null && geometries.Count() > 0)
            {
                var reader = new WkbReader();

                var minX = double.PositiveInfinity;
                var minY = double.PositiveInfinity;
                var maxX = double.NegativeInfinity;
                var maxY = double.NegativeInfinity;

                foreach (var geom in geometries.Where(g => g != null))
                {
                    var feature  = reader.Read(geom.GeoData);
                    var envelope = feature.Envelope;
                    if (envelope != null)
                    {
                        if (envelope.Minimum.X < minX)
                        {
                            minX = envelope.Minimum.X;
                        }

                        if (envelope.Minimum.Y < minY)
                        {
                            minY = envelope.Minimum.Y;
                        }

                        if (envelope.Maximum.X > maxX)
                        {
                            maxX = envelope.Maximum.X;
                        }

                        if (envelope.Maximum.Y > maxY)
                        {
                            maxY = envelope.Maximum.Y;
                        }
                    }

                    featureSet.AddFeature(feature);
                }

                if (!double.IsInfinity(minX))
                {
                    featureSet.Extent.MinX = minX;
                }
                if (!double.IsInfinity(minY))
                {
                    featureSet.Extent.MinY = minY;
                }
                if (!double.IsInfinity(maxX))
                {
                    featureSet.Extent.MaxX = maxX;
                }
                if (!double.IsInfinity(maxY))
                {
                    featureSet.Extent.MaxY = maxY;
                }
            }
        }
コード例 #13
0
        public void If_input_valid_point_with_lower_endian_then_should_return_correct_point()
        {
            const string hex       = "0101000020E61000005DA450163E1A5D40C44FD2B2A4F64340";
            var          expectGeo = new Point(116.4100395, 39.9269012);

            var geoResult = WkbReader.Read(hex);

            geoResult.Equals(expectGeo).ShouldBeTrue();
        }
コード例 #14
0
        public void Read_ReadsGeometry()
        {
            Point expected = (Point)this.ParseWKT("point zm (-10.1 15.5 100.5 1000.5)");

            WkbReader target = new WkbReader(new MemoryStream(Data.IOTestData.point_3DM));
            Point     parsed = (Point)target.Read();

            this.ComparePoints(parsed, expected);
        }
コード例 #15
0
        public void Read_ReturnsNullIfStreamIsEmpty()
        {
            MemoryStream stream = new MemoryStream();

            WkbReader target = new WkbReader(stream);
            Geometry  read   = target.Read();

            Assert.Null(read);
        }
コード例 #16
0
        public void ReadT_ThrowsExceptionIfWKBDoesNotRepresentGeometry()
        {
            byte[] wkb = new byte[] { 12, 0, 0, 45, 78, 124, 36, 0 };
            using (MemoryStream ms = new MemoryStream(wkb)) {
                WkbReader target = new WkbReader(ms);

                Assert.Throws <WkbFormatException>(() => target.Read <Point>());
            }
        }
コード例 #17
0
        public void Read_ReadsGeometry()
        {
            Point expected = (Point)this.ParseWKT("point zm (-10.1 15.5 100.5 1000.5)");

            WkbReader target = new WkbReader(TestDataReader.Open("point-3DM.wkb"));
            Point     parsed = (Point)target.Read();

            this.ComparePoints(parsed, expected);
        }
コード例 #18
0
        /// <summary>
        /// Opens the specified file
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public IFeatureSet Open(string fileName)
        {
            IFeatureSet fs = new FeatureSet();

            fs.Name     = Path.GetFileNameWithoutExtension(fileName);
            fs.Filename = fileName;
            using (var reader = new OgrDataReader(fileName))
            {
                // skip the geometry column which is always column 0
                for (int i = 1; i < reader.FieldCount; i++)
                {
                    string sFieldName = reader.GetName(i);
                    Type   type       = reader.GetFieldType(i);

                    int    uniqueNumber = 1;
                    string uniqueName   = sFieldName;
                    while (fs.DataTable.Columns.Contains(uniqueName))
                    {
                        uniqueName = sFieldName + uniqueNumber;
                        uniqueNumber++;
                    }
                    fs.DataTable.Columns.Add(new DataColumn(uniqueName, type));
                }

                var wkbReader = new WkbReader();
                while (reader.Read())
                {
                    var wkbGeometry = (byte[])reader["Geometry"];

                    var geometry = wkbReader.Read(wkbGeometry);

                    IFeature feature = new Feature(geometry);
                    feature.DataRow = fs.DataTable.NewRow();
                    for (int i = 1; i < reader.FieldCount; i++)
                    {
                        object value = reader[i];
                        if (value == null)
                        {
                            value = DBNull.Value;
                        }
                        feature.DataRow[i - 1] = value;
                    }
                    fs.Features.Add(feature);
                }

                try
                {
                    fs.Projection = reader.GetProj4ProjectionInfo();
                }
                catch (Exception ex)
                {
                    Trace.WriteLine(ex);
                }
            }

            return(fs);
        }
コード例 #19
0
        public void If_input_valid_point_with_big_endian_then_should_return_correct_point()
        {
            const string hex       = "000000000140000000000000004010000000000000";
            var          expectGeo = new Point(2, 4);

            var geoResult = WkbReader.Read(hex);

            geoResult.Equals(expectGeo).ShouldBeTrue();
        }
コード例 #20
0
ファイル: Geometry.cs プロジェクト: DomCR/WKInterpreter
        public static Geometry Deserialize(byte[] blop)
        {
            Geometry value = null;

            using (WkbReader reader = new WkbReader(blop))
            {
                value = reader.Read();
            }

            return(value);
        }
コード例 #21
0
        /// <summary>
        /// Перепроецирует геометрию в WGS84 и возвращает набор точек
        /// </summary>
        /// <param name="input">Простые полигоны и полилинии из БД в системе координать UtmZone31N</param>
        /// <returns>Набор точек в системе координат WGS84 (SRID 4326)</returns>
        /// <remarks>Внимание! Многоконтурная геометрия не поддерживается</remarks>
        public LocationCollection UtmZone31nToWgs84Transform(DbGeometry input)
        {
            if (input == null)
            {
                return(null);
            }

            //Перевод геометрии в формат понятный для библиотеки DotSpatial
            byte[]    wkbBynary = input.AsBinary();
            WkbReader wkbReader = new WkbReader();

            DotSpatial.Topology.IGeometry geom = wkbReader.Read(wkbBynary);

            //Определение используемых проекций
            ProjectionInfo beninPrj = KnownCoordinateSystems.Projected.UtmWgs1984.WGS1984UTMZone31N;
            ProjectionInfo worldPrj = KnownCoordinateSystems.Geographic.World.WGS1984;

            //Создание массива точек Х1,У1,Х2,У2...Хn,Уn
            double[] pointArray = new double[geom.Coordinates.Count() * 2];
            double[] zArray     = new double[1];
            zArray[0] = 0;

            int counterX = 0; int counterY = 1;

            foreach (var coordinate in geom.Coordinates)
            {
                pointArray[counterX] = coordinate.X;
                pointArray[counterY] = coordinate.Y;

                counterX += 2;
                counterY += 2;
            }

            //Операция перепроецирования над массивом точек
            Reproject.ReprojectPoints(pointArray, zArray, beninPrj, worldPrj, 0, (pointArray.Length / 2));


            LocationCollection loc = new LocationCollection();

            counterX = 0; counterY = 1;

            foreach (var coordinate in geom.Coordinates)
            {
                loc.Add(new Location(pointArray[counterY], pointArray[counterX]));

                counterX += 2;
                counterY += 2;
            }

            return(loc);
        }
コード例 #22
0
        public void If_input_valid_linestring_with_lower_endian_then_should_return_correct_linestring()
        {
            const string hex       = "0102000020E61000000400000095D74AE82EED28408A271653442E49402E7F74A03DED284001A02F62442E49409F6BA9CD49ED28403657CD73442E49407D1A417452ED2840A2F9522E432E4940";
            var          expectGeo = new LineString(new List <Point>
            {
                new Point(12.4632485, 50.3614601),
                new Point(12.4633608, 50.3614619),
                new Point(12.4634537, 50.361464),
                new Point(12.4635197, 50.3614252)
            });

            var geoResult = WkbReader.Read(hex);

            geoResult.Equals(expectGeo).ShouldBeTrue();
        }
コード例 #23
0
        public void If_input_valid_multipoint_with_lower_endian_then_should_return_correct_multipoint()
        {
            const string hex       = "010400000004000000010100000000000000000024400000000000004440010100000000000000000044400000000000003e4001010000000000000000003440000000000000344001010000000000000000003e400000000000002440";
            var          expectGeo = new MultiPoint(new List <Point>
            {
                new Point(10, 40),
                new Point(40, 30),
                new Point(20, 20),
                new Point(30, 10)
            });

            var geoResult = WkbReader.Read(hex);

            geoResult.Equals(expectGeo).ShouldBeTrue();
        }
コード例 #24
0
        public void PointToByteArray()
        {
            var rnd  = new Random();
            var c    = new Coordinate((rnd.NextDouble() + 360) - 180, (rnd.NextDouble() * 180) - 90);
            var p    = new Point(c);
            var vals = p.ToBinary();
            var wkr  = new WkbReader();
            var g    = wkr.Read(vals);
            var pt   = g as Point;

            if (pt != null)
            {
                Assert.AreEqual(p.X, pt.X);
                Assert.AreEqual(p.Y, pt.Y);
            }
            else
            {
                Assert.Fail("The test failed bc the check pt was null.");
            }
        }
コード例 #25
0
        private void LoadGeoData(string dbFile)
        {
            WkbReader geoReader = new WkbReader();

            Geo.GeoContext.Current.LongitudeWrapping = true;

            using (var vectorConn = new SQLiteConnection(dbFile, SQLiteOpen.READONLY))
            {
                using (var cmd = vectorConn.Prepare(
                           "SELECT geometry_hi, geometry_low, name_long, continent, long_wrap, z_index, tolerance_low, tolerance_hi FROM countries_v"))
                {
                    while (cmd.Step() == SQLiteResult.ROW)
                    {
                        var name = cmd.GetText(2).Trim();

                        IGeometry geometry = null;
                        using (var geo = new MemoryStream(cmd.GetBlob(_settings.IsLowMemory ? 1 : 0)))
                            geometry = geoReader.Read(geo);

                        var continent = Continent.Unspecified;
                        Enum.TryParse <Continent>(cmd.GetText(3).Replace(" ", string.Empty), out continent);

                        var longWrap = cmd.GetInteger(4) != 0;
                        var zIndex   = (int)cmd.GetInteger(5);

                        var toleranceLow = cmd.GetFloat(6);
                        var toleranceHi  = cmd.GetFloat(7);

                        var fileName = NormalizeName(name);

                        var country = new CountryInfo(continent, name, geometry,
                                                      new Uri(string.Format(_settings.SmallFlagFileNameFormat, fileName), UriKind.Relative),
                                                      new Uri(string.Format(_settings.LargeFlagFileNameFormat, fileName), UriKind.Relative),
                                                      longWrap, zIndex, toleranceLow, toleranceHi);

                        _countries[name.ToLower()] = country;
                    }
                }
            }
        }
コード例 #26
0
 private void Test(string wkt)
 {
     var wktReader = new WktReader();
     var geometry  = wktReader.Read(wkt);
     {
         var wkbWriter = new WkbWriter(new WkbWriterSettings {
             Triangle = true
         });
         var wkb       = wkbWriter.Write(geometry);
         var wkbReader = new WkbReader();
         var geometry2 = wkbReader.Read(wkb);
         Assert.AreEqual(geometry, geometry2);
     }
     {
         var wkbWriter = new WkbWriter(new WkbWriterSettings {
             Encoding = WkbEncoding.BigEndian, Triangle = true
         });
         var wkb       = wkbWriter.Write(geometry);
         var wkbReader = new WkbReader();
         var geometry2 = wkbReader.Read(wkb);
         Assert.AreEqual(geometry, geometry2);
     }
 }
コード例 #27
0
        public void PolygonToByteArray()
        {
            Coordinate[] coords = new Coordinate[20];
            Random       rnd    = new Random();
            Coordinate   center = new Coordinate((rnd.NextDouble() * 360) - 180, (rnd.NextDouble() * 180) - 90);

            for (int i = 0; i < 19; i++)
            {
                coords[i] = new Coordinate(center.X + Math.Cos((i * 10) * Math.PI / 10), center.Y + (i * 10) * Math.PI / 10);
            }
            coords[19] = new Coordinate(coords[0].X, coords[0].Y);
            Polygon pg = new Polygon(coords);

            byte[]    vals    = pg.ToBinary();
            WkbReader wkr     = new WkbReader();
            IGeometry g       = wkr.Read(vals);
            Polygon   pgcheck = g as Polygon;

            if (pgcheck != null)
            {
                for (int i = 0; i < pg.NumGeometries; i++)
                {
                    Assert.AreEqual(pg.Coordinates[i].X, pgcheck.Coordinates[i].X);
                    Assert.AreEqual(pg.Coordinates[i].Y, pgcheck.Coordinates[i].Y);
                }
                Assert.AreEqual(pg.Area, pgcheck.Area);
                Assert.AreEqual(pg.Centroid.X, pgcheck.Centroid.X);
                Assert.AreEqual(pg.Centroid.Y, pgcheck.Centroid.Y);
                Assert.AreEqual(pg.Length, pgcheck.Length);
                Assert.AreEqual(pg.Envelope.Width, pgcheck.Envelope.Width);
                Assert.AreEqual(pg.Envelope.Height, pgcheck.Envelope.Height);
            }
            else
            {
                Assert.Fail("The test failed bc the check pgcheck was null.");
            }
        }
コード例 #28
0
        /// <summary>
        /// Exports the selected database to fieldAttributes filegeodatabase
        /// </summary>
        /// <param name="progressBar">A progress bar object</param>
        /// <param name="logFunction">A log function</param>
        /// <param name="mdbFile">The outputShapefileName of an addressing database</param>
        /// <param name="approvedOnly">1 to include only approved, 0 to include all</param>
        /// <returns>Feature set</returns>
        public static FeatureSet GetRoadFeatureSetFromAdmAdrMdb(ref ToolStripProgressBar progressBar, Action <string, bool> logFunction, string mdbFile, int approvedOnly = 0)
        {
            // Setup SQL string to select all or only some streets
            string sqlStatement;

            if (approvedOnly == 1)
            {
                sqlStatement = "SELECT ADRROADID, NAMEENGLISH, NAMEARABIC, NAMEPOPULARENGLISH, NAMEPOPULARARABIC, ROADTYPE, ADRDISTRICTID, APPROVED FROM ADM_ADRROAD WHERE APPROVED = 1";
            }
            else
            {
                sqlStatement = "SELECT ADRROADID, NAMEENGLISH, NAMEARABIC, NAMEPOPULARENGLISH, NAMEPOPULARARABIC, ROADTYPE, ADRDISTRICTID, APPROVED FROM ADM_ADRROAD";
            }

            logFunction(sqlStatement, true);

            // Setup fieldAttributes dictionary to hold road names
            var roadNames = new Dictionary <int, DataRow>();

            // Connect to database and load names
            using (var database = new Database(mdbFile))
            {
                var dataTable = database.Query(sqlStatement);
                progressBar.Value = 0;
                foreach (DataRow mRow in dataTable.Rows)
                {
                    int mRoadId;
                    if (int.TryParse(mRow["ADRROADID"].ToString(), out mRoadId))
                    {
                        roadNames.Add(mRoadId, mRow);
                    }
                }

                // Connect to database using OGR to load geometries
                var ogrDriver = Ogr.GetDriverByName("PGeo");

                if (ogrDriver == null)
                {
                    return(null);
                }
                logFunction("Loaded driver", true);

                var ogrDataSource = ogrDriver.Open(mdbFile, 0);
                if (ogrDataSource == null)
                {
                    return(null);
                }
                logFunction("Loaded datasource", true);

                var roadSegmentLayer = ogrDataSource.GetLayerByName("ADRROADSEGMENT");
                if (roadSegmentLayer == null)
                {
                    logFunction("Could not load layer", true);
                    return(null);
                }
                logFunction("Loaded layer", true);

                // Create simplified roads
                var simplifiedRoadsFeatureSet = new SimplifiedRoads();

                int numberOfRoads = roadNames.Count();
                progressBar.Value = 0;
                var roadCounter    = 0;
                var segmentCounter = 0;

                foreach (var roadName in roadNames)
                {
                    roadCounter++;

                    int     roadIdentifier = roadName.Key;
                    DataRow roadData       = roadName.Value;

                    roadSegmentLayer.ResetReading();
                    roadSegmentLayer.SetAttributeFilter("ADRROADID=" + roadIdentifier);

                    OSGeo.OGR.Feature roadSegment;
                    var mWkbReader = new WkbReader();

                    while (null != (roadSegment = roadSegmentLayer.GetNextFeature()))
                    {
                        segmentCounter++;

                        OSGeo.OGR.Geometry mGeometry = roadSegment.GetGeometryRef();

                        if (mGeometry != null)
                        {
                            mGeometry.FlattenTo2D();

                            byte[] mWkb = new Byte[mGeometry.WkbSize()];

                            mGeometry.ExportToWkb(mWkb);

                            IMultiLineString multiLine;

                            IGeometry roadGeometry = mWkbReader.Read(mWkb);

                            if (roadGeometry.GetType() == typeof(DotSpatial.Topology.LineString))
                            {
                                var mLineStrings = new List <LineString>();
                                mLineStrings.Add(roadGeometry as LineString);
                                multiLine = new DotSpatial.Topology.MultiLineString(mLineStrings);
                            }
                            else
                            {
                                multiLine = roadGeometry as IMultiLineString;
                            }

                            int districtIdentifier, roadClass, roadApproved;
                            int.TryParse(roadData["ADRDISTRICTID"].ToString(), out districtIdentifier);
                            var nameArabic        = roadData["NAMEARABIC"].ToString();
                            var nameLatin         = roadData["NAMEENGLISH"].ToString();
                            var namePopularArabic = roadData["NAMEPOPULARARABIC"].ToString();
                            var namePopularLatin  = roadData["NAMEPOPULARENGLISH"].ToString();
                            int.TryParse(roadData["ROADTYPE"].ToString(), out roadClass);
                            int.TryParse(roadData["APPROVED"].ToString(), out roadApproved);

                            simplifiedRoadsFeatureSet.AddNewRow(
                                roadGeometry,
                                districtIdentifier,
                                roadIdentifier,
                                nameArabic,
                                nameLatin,
                                namePopularArabic,
                                namePopularLatin,
                                roadClass,
                                roadApproved);
                        }
                        else
                        {
                            logFunction("No geometry", true);
                        }

                        if (roadCounter % 100 == 0 || roadCounter == numberOfRoads)
                        {
                            progressBar.ProgressBar.Value = (int)Math.Round((double)(roadCounter * 100 / numberOfRoads));
                            Application.DoEvents();
                        }
                    }
                }

                simplifiedRoadsFeatureSet.UpdateExtent();
                logFunction("Done creating featureset", true);
                return(simplifiedRoadsFeatureSet);
            }
        }
コード例 #29
0
 public void ReadT_ThrowsExceptionIfWKBDoesNotRepresentSpecifiecGeometryType()
 {
     WkbReader target = new WkbReader(new MemoryStream(Data.IOTestData.point_3DM));
     Assert.Throws<WkbFormatException>(() => target.Read<LineString>());
 }
コード例 #30
0
        public void Read_ReadsGeometry()
        {
            Point expected = (Point)this.ParseWKT("point zm (-10.1 15.5 100.5 1000.5)");

            WkbReader target = new WkbReader(new MemoryStream(Data.IOTestData.point_3DM));
            Point parsed = (Point)target.Read();

            this.ComparePoints(parsed, expected);
        }
コード例 #31
0
        public void ReadT_ThrowsExceptionIfWKBDoesNotRepresentSpecifiecGeometryType()
        {
            WkbReader target = new WkbReader(TestDataReader.Open("point-3DM.wkb"));

            Assert.Throws <WkbFormatException>(() => target.Read <LineString>());
        }
コード例 #32
0
        public void Read_ReadsMultipleGeometries()
        {
            Point expected1 = (Point)this.ParseWKT("point zm (-10.1 15.5 100.5 1000.5)");
            Point expected2 = (Point)this.ParseWKT("point zm (-10.2 15.6 100.6 1000.6)");

            WkbReader target = new WkbReader(new MemoryStream(Data.IOTestData.two_points_3DM));

            Point parsed1 = (Point)target.Read();
            this.ComparePoints(parsed1, expected1);

            Point parsed2 = (Point)target.Read();
            this.ComparePoints(parsed2, expected2);
        }
コード例 #33
0
        public void Read_ReturnsNullIfNoMoreGeometriesAreAvailable()
        {
            WkbReader target = new WkbReader(new MemoryStream(Data.IOTestData.point_3DM));

            target.Read();
            Geometry parsed = target.Read();

            Assert.Null(parsed);
        }
コード例 #34
0
        public void Read_ReturnsNullIfStreamIsEmpty()
        {
            MemoryStream stream = new MemoryStream();

            WkbReader target = new WkbReader(stream);
            Geometry read = target.Read();

            Assert.Null(read);
        }
コード例 #35
0
        public void Read_ThrowsExceptionIfWKBDoesNotRepresentGeometry()
        {
            byte[] wkb = new byte[] { 12, 0, 0, 45, 78, 124, 36, 0 };
            using (MemoryStream ms = new MemoryStream(wkb)) {
                WkbReader target = new WkbReader(ms);

                Assert.Throws<WkbFormatException>(() => target.Read());
            }
        }
コード例 #36
0
        /// <summary>
        /// This open method is only called if this plugin has been given priority for one
        /// of the file extensions supported in the DialogReadFilter property supplied by
        /// this control.  Failing to provide a DialogReadFilter will result in this plugin
        /// being added to the list of DataProviders being supplied under the Add Other Data
        /// option in the file menu.
        /// </summary>
        /// <param name="connectionString">A string specifying the connection parameters.</param>
        /// <param name="tablespace">The name of the tablespace where the table is stored</param>
        /// <param name="schema">The name of the schema where the table is located</param>
        /// <param name="table">The name of the database table to get the data from</param>
        /// <param name="fidColumn">The name of the column that holds the unique primary key</param>
        /// <param name="geometryColumn">The name  of the column that holds the geometry</param>
        /// <returns>A List of IDataSets to be added to the Map.  These can also be groups of datasets.</returns>
        public IDataSet Open(string connectionString, string tablespace, string schema, string table, string fidColumn, string geometryColumn)
        {
            ConnectionString = connectionString;

            TableSpace     = tablespace;
            Schema         = schema;
            Table          = table;
            FidColumn      = fidColumn;
            GeometryColumn = geometryColumn;

            SetQualifyFormatStrings();

            IFeatureSet featureSet = new DbFeatureSet <DbVectorProvider <T>, T>(
                GetFeatureType(connectionString, tablespace, schema, table, geometryColumn, InitialCommands));

            //featureSet.AddFid();

            using (T c1 = OpenConnection(connectionString))
                using (T connection = OpenConnection(connectionString))
                {
                    string[] otherColumns  = GetOtherColumns(c1);
                    string   commandString =
                        string.Format("SELECT {0}, {1}, {2} FROM {3};",
                                      string.Format(AsBinaryClause, QualifiedColumn(geometryColumn)),
                                      QualifiedColumn(FidColumn), QualifiedColumn(otherColumns), QualifiedTable);

                    // Get schema information
                    DataAdapter         da = GetDataAdapter(commandString.Substring(0, commandString.Length - 1) + LimitClause + ";", connection);
                    System.Data.DataSet ds = new System.Data.DataSet();
                    da.FillSchema(ds, SchemaType.Source);
                    DataTable dt = ds.Tables[0];
                    if (dt == null)
                    {
                        throw new DbDataProviderException("Unable to get schema table");
                    }

                    // Add columns to the feature sets datatable
                    for (int i = 1; i < dt.Columns.Count; i++)
                    {
                        DataColumn dc            = dt.Columns[i];
                        DataColumn newDataColumn = featureSet.DataTable.Columns.Add(dc.ColumnName, dc.DataType);
                        newDataColumn.AllowDBNull       = dc.AllowDBNull;
                        newDataColumn.AutoIncrement     = dc.AutoIncrement;
                        newDataColumn.AutoIncrementSeed = dc.AutoIncrementSeed;
                        newDataColumn.AutoIncrementStep = dc.AutoIncrementStep;
                        newDataColumn.Caption           = dc.Caption;
                        newDataColumn.DateTimeMode      = dc.DateTimeMode;
                        newDataColumn.DefaultValue      = dc.DefaultValue;
                        newDataColumn.Expression        = dc.Expression;
                        newDataColumn.MaxLength         = dc.MaxLength;
                        newDataColumn.ReadOnly          = dc.ReadOnly;
                        newDataColumn.Prefix            = dc.Prefix;
                        newDataColumn.Unique            = dc.Unique;
                    }

                    // Read whole dataset
                    DbCommand cmd = connection.CreateCommand();
                    cmd.CommandText = commandString;
                    DbDataReader dr = cmd.ExecuteReader(CommandBehavior.Default);
                    if (dr.HasRows)
                    {
                        WkbReader wkbReader = new WkbReader();
                        dt = featureSet.DataTable;
                        //int fid = 0;
                        while (dr.Read())
                        {
                            if (!dr.IsDBNull(0))
                            {
                                IGeometry geom = wkbReader.Read((byte[])dr[0]);
                                IFeature  f    = featureSet.AddFeature(geom);
                                DataRow   row  = f.DataRow = dt.NewRow();
                                //row[0] = fid++;
                                for (int i = 1; i < dt.Columns.Count; i++)
                                {
                                    //row[i] = dr[i];
                                    row[i - 1] = dr[i];
                                }
                            }
                        }
                    }
                }
            featureSet.UpdateExtent();
            featureSet.Name = string.Format(QualifiedColumn(GeometryColumn));
            // Assign projection information to feature set
            featureSet.Projection = GetProjection();
            return(featureSet);
        }