Example #1
0
        static void Main(string[] args)
        {
            var geometryFactory = new GeometryFactory();
            var reader          = new ShapefileDataReader(Path.Combine("..", "data", "refpunt.shp"),
                                                          geometryFactory);

            var header = reader.DbaseHeader;

            var features = new List <IFeature>();

            while (reader.Read())
            {
                Console.WriteLine(reader.Geometry);

                for (var i = 0; i < header.NumFields; i++)
                {
                    Console.WriteLine("{0} - {1}", header.Fields[i].Name, reader.GetValue(i + 1));
                }

                var feature = reader.Feature;

                features.Add(feature);
            }

            var writer = new ShapefileDataWriter("temp.shp")
            {
                Header = header
            };

            writer.Write(features);
        }
        private void TestShapeCreation()
        {
            var points = new Coordinate[3];

            points[0] = new Coordinate(0, 0);
            points[1] = new Coordinate(1, 0);
            points[2] = new Coordinate(1, 1);

            var line_string = new LineString(points);

            var attributes = new AttributesTable();

            attributes.AddAttribute("FOO", "FOO");

            var feature  = new Feature(Factory.CreateMultiLineString(new ILineString[] { line_string }), attributes);
            var features = new Feature[1];

            features[0] = feature;

            var shp_writer = new ShapefileDataWriter("line_string")
            {
                Header = ShapefileDataWriter.GetHeader(features[0], features.Length)
            };

            shp_writer.Write(features);
        }
Example #3
0
        private static void ExportFeatures(List <IFeature> pFeatures, string pFileName, bool pIsMainFile)
        {
            if (pFeatures.Count == 0)
            {
                CDebug.Warning("You are trying to export 0 features");
                return;
            }

            string shapeFileFolder = pIsMainFile ? CProjectData.outputFolder : CProjectData.outputTileSubfolder;

            shapeFileFolder += "/shp_" + pFileName;
            Directory.CreateDirectory(shapeFileFolder);            //create subfolder

            // Construct the shapefile name. Don't add the .shp extension or the ShapefileDataWriter will
            // produce an unwanted shapefile
            string shapeFileName    = Path.Combine(shapeFileFolder, pFileName);
            string shapeFilePrjName = Path.Combine(shapeFileFolder, $"{pFileName}.prj");

            // Create the shapefile
            var outGeomFactory = GeometryFactory.Default;
            var writer         = new ShapefileDataWriter(shapeFileName, outGeomFactory);
            var outDbaseHeader = ShapefileDataWriter.GetHeader(pFeatures[0], pFeatures.Count);

            writer.Header = outDbaseHeader;
            writer.Write(pFeatures);

            //Create the projection file
            using (var streamWriter = new StreamWriter(shapeFilePrjName))
            {
                streamWriter.Write(GeographicCoordinateSystem.WGS84.WKT);
            }
        }
        public bool ConvertJsonToShapeFileNew(string json, string shapeFilePath, string namefile)
        {
            string geometryString  = ConvertGeometryToString(json);
            var    attributesTable = new NetTopologySuite.Features.AttributesTable();
            var    attributes      = AddAttribute(json);
            var    geomFactory     = new NetTopologySuite.Geometries.GeometryFactory(new NetTopologySuite.Geometries.PrecisionModel(), 4326);
            var    wktReader       = new WKTReader(geomFactory);
            var    geometry        = wktReader.Read(geometryString);
            string filesPathName   = shapeFilePath.Substring(0, shapeFilePath.Length - 4);

            removeShapeFileIfExists(filesPathName);
            if (attributes != null)
            {
                attributesTable = attributes;
                var features = new List <NetTopologySuite.Features.IFeature>
                {
                    new NetTopologySuite.Features.Feature(geometry, attributesTable)
                };
                var name = namefile.Substring(0, namefile.Length - 4);
                // Create the directory where we will save the shapefile
                //var shapeFilePath = Path.Combine(Server.MapPath("~/Document"), name);
                if (!Directory.Exists(filesPathName))
                {
                    Directory.CreateDirectory(filesPathName);
                }

                // Construct the shapefile name. Don't add the .shp extension or the ShapefileDataWriter will
                // produce an unwanted shapefile
                var shapeFileName    = Path.Combine(filesPathName, name);
                var shapeFilePrjName = Path.Combine(filesPathName, $"{name}.prj");

                // Create the shapefile
                var outGeomFactory = NetTopologySuite.Geometries.GeometryFactory.Default;
                var writer         = new ShapefileDataWriter(shapeFileName, outGeomFactory, Encoding.UTF8);
                var outDbaseHeader = ShapefileDataWriter.GetHeader(features[0], features.Count, Encoding.UTF8);
                writer.Header = outDbaseHeader;
                writer.Write(features);

                // Create the projection file
                using (var streamWriter = new StreamWriter(shapeFilePrjName))
                {
                    streamWriter.Write(GeographicCoordinateSystem.WGS84.WKT);
                }
                System.IO.File.WriteAllText(Path.Combine(filesPathName, $"{name}.cpg"), Encoding.UTF8.HeaderName);
                //var shapeFileReader = new ShapefileDataReader(shapeFileName, NetTopologySuite.Geometries.GeometryFactory.Default, Encoding.UTF8);
                //var read = shapeFileReader.Read();
                //var values = new object[shapeFileReader.FieldCount - 1];
                //var a = values[1];
                //var a1 = shapeFileReader.GetName(0);
                //var geom = shapeFileReader.Geometry;

                string zipName = filesPathName + ".zip";
                CompressToZipFile(new List <string>()
                {
                    shapeFileName + ".shp", shapeFileName + ".dbf", shapeFileName + ".prj", shapeFileName + ".shx", shapeFileName + ".cpg"
                }, zipName);
                return(true);
            }
            return(false);
        }
Example #5
0
        // see https://code.google.com/p/nettopologysuite/issues/detail?id=146
        public void Issue146_ShapeCreationWithInvalidAttributeName()
        {
            var points = new Coordinate[3];

            points[0] = new Coordinate(0, 0);
            points[1] = new Coordinate(1, 0);
            points[2] = new Coordinate(1, 1);
            var ls  = new LineString(points);
            var mls = GeometryFactory.Default.CreateMultiLineString(new ILineString[] { ls });

            var attrs = new AttributesTable();

            attrs.Add("Simulation name", "FOO");

            var features = new[] { new Feature(mls, attrs) };
            ShapefileDataWriter shp_writer = null;

            Assert.Throws <ArgumentException>(() => shp_writer =
                                                  new ShapefileDataWriter("invalid_line_string")
            {
                Header = ShapefileDataWriter.GetHeader(features[0], features.Length)
            });

            //Assert.Throws<ArgumentException>(() => shp_writer.Write(features));
        }
        static void Main(string[] args)
        {
            FeatureCollection features = new FeatureCollection();
            // Polygon 1
            List <Coordinate> coords = new List <Coordinate>();

            coords.Add(new Coordinate(0, 0));
            coords.Add(new Coordinate(0, 10));
            coords.Add(new Coordinate(10, 10));
            coords.Add(new Coordinate(10, 0));
            coords.Add(new Coordinate(0, 0));
            LinearRing ring = new LinearRing(coords.ToArray());
            Polygon    poly = new Polygon(ring);
            // Polygon1 attributes
            AttributesTable attr = new AttributesTable();

            attr.AddAttribute("Column1", "HELLO");
            attr.AddAttribute("Column2", "WORLD !");
            Feature featureForPolygon = new Feature(poly, attr);

            features.Add(featureForPolygon);
            ShapefileDataWriter writer = new ShapefileDataWriter(@"%userprofile%\documents\outFile");

            writer.Header = new DbaseFileHeader();
            writer.Header.AddColumn("Column1", 'C', 10, 0);
            writer.Header.AddColumn("Column2", 'C', 10, 0);
            writer.Write(features.Features);
        }
Example #7
0
        public void TestCreateEmptyShapefile()
        {
            const string filename = "__empty";
            const string emptyShp = filename + ".shp";
            const string emptyShx = filename + ".shx";
            const string emptyDbf = filename + ".dbf";

            if (File.Exists(emptyShp))
            {
                File.Delete(emptyShp);
            }
            if (File.Exists(emptyShx))
            {
                File.Delete(emptyShx);
            }
            if (File.Exists(emptyDbf))
            {
                File.Delete(emptyDbf);
            }

            var writer = new ShapefileDataWriter(filename, Factory);

            writer.Header = new DbaseFileHeader();
            writer.Write(new IFeature[0]);

            Assert.That(File.Exists(emptyShp), Is.True);
            Assert.That(File.Exists(emptyShx), Is.True);
            Assert.That(File.Exists(emptyDbf), Is.True);
        }
Example #8
0
    public static void WriteFeaturesToShapefile(string filename, List <Feature> features)
    {
        if (File.Exists(filename + ".shp"))
        {
            File.Delete(filename + ".shp");
        }

        if (File.Exists(filename + ".dbf"))
        {
            File.Delete(filename + ".dbf");
        }

        if (File.Exists(filename + ".shx"))
        {
            File.Delete(filename + ".shx");
        }

        if (features.Count == 0)
        {
            return;
        }

        var outGeomFactory = GeometryFactory.Default;
        var writer         = new ShapefileDataWriter(filename, outGeomFactory);
        var outDbaseHeader = ShapefileDataWriter.GetHeader(features[0], features.Count);

        writer.Header = outDbaseHeader;
        writer.Write(features);
    }
Example #9
0
        public void WriteShouldWorkWithoutIndexFileWhenRequested()
        {
            var pt         = GeometryFactory.Default.CreatePoint(new Coordinate(2, 3));
            var attributes = new AttributesTable {
                { "Foo", "Bar" }
            };

            Feature[] features = { new Feature(pt, attributes) };

            string baseFileName = TestContext.CurrentContext.Test.ID;
            string shpFilePath  = baseFileName + ".shp";
            string dbfFilePath  = baseFileName + ".dbf";
            string shxFilePath  = baseFileName + ".shx";

            var reg = new ShapefileStreamProviderRegistry(
                shapeStream: new FileStreamProvider(StreamTypes.Shape, shpFilePath),
                dataStream: new FileStreamProvider(StreamTypes.Data, dbfFilePath),
                indexStream: null,
                validateShapeProvider: true,
                validateDataProvider: true,
                validateIndexProvider: false);

            var wr = new ShapefileDataWriter(reg, GeometryFactory.Default, CodePagesEncodingProvider.Instance.GetEncoding(1252));

            wr.Header = ShapefileDataWriter.GetHeader(features[0], features.Length);
            wr.Write(features);

            Assert.True(File.Exists(shpFilePath));
            Assert.True(File.Exists(dbfFilePath));
            Assert.False(File.Exists(shxFilePath));
        }
Example #10
0
        static void WriteBuildingsToShapefile(string fileName, List <NetTopologySuite.Features.Feature> buildings)
        {
            if (File.Exists(fileName + ".shp"))
            {
                File.Delete(fileName + ".shp");
            }
            if (File.Exists(fileName + ".dbf"))
            {
                File.Delete(fileName + ".dbf");
            }
            if (File.Exists(fileName + ".dbf"))
            {
                File.Delete(fileName + ".dbf");
            }

            if (buildings.Count == 0)
            {
                return;
            }

            var outGeoFactory  = NetTopologySuite.Geometries.GeometryFactory.Default;
            var writer         = new ShapefileDataWriter(fileName, outGeoFactory);
            var outDBaseHeader = ShapefileDataWriter.GetHeader(buildings[0], buildings.Count);

            writer.Header = outDBaseHeader;
            writer.Write(buildings);
        }
Example #11
0
        static void Main(string[] args)
        {
            // let's show you what's going on.
            OsmSharp.Logging.Logger.LogAction = (origin, level, message, parameters) =>
            {
                Console.WriteLine(string.Format("[{0}] {1} - {2}", origin, level, message));
            };

            Download.ToFile("http://files.itinero.tech/data/OSM/planet/europe/luxembourg-latest.osm.pbf", "luxembourg-latest.osm.pbf").Wait();

            using (var fileStream = File.OpenRead("luxembourg-latest.osm.pbf"))
            {
                // create source stream.
                var source = new PBFOsmStreamSource(fileStream);

                // show progress.
                var progress = source.ShowProgress();

                // filter all powerlines and keep all nodes.
                var filtered = from osmGeo in progress
                               where osmGeo.Type == OsmSharp.OsmGeoType.Node ||
                               (osmGeo.Type == OsmSharp.OsmGeoType.Way && osmGeo.Tags != null && osmGeo.Tags.Contains("power", "line"))
                               select osmGeo;

                // convert to a feature stream.
                // WARNING: nodes that are partof powerlines will be kept in-memory.
                //          it's important to filter only the objects you need **before**
                //          you convert to a feature stream otherwise all objects will
                //          be kept in-memory.
                var features = filtered.ToFeatureSource();

                // filter out only linestrings.
                var lineStrings = from feature in features
                                  where feature.Geometry is LineString
                                  select feature;

                // build feature collection.
                var featureCollection = new FeatureCollection();
                var attributesTable   = new AttributesTable {
                    { "type", "powerline" }
                };
                foreach (var feature in lineStrings)
                { // make sure there is a constant # of attributes with the same names before writing the shapefile.
                    featureCollection.Add(new Feature(feature.Geometry, attributesTable));
                }

                // convert to shape.
                var header      = ShapefileDataWriter.GetHeader(featureCollection.Features.First(), featureCollection.Features.Count);
                var shapeWriter = new ShapefileDataWriter("luxembourg.shp", new GeometryFactory())
                {
                    Header = header
                };
                shapeWriter.Write(featureCollection.Features);
            }
        }
Example #12
0
        public void BuildStradeFixed()
        {
            var path = "strade" + shp;

            Assert.IsTrue(File.Exists(path));

            var reader   = new ShapefileDataReader(path, factory);
            var features = new List <IFeature>(reader.RecordCount);

            while (reader.Read())
            {
                var feature = new Feature(reader.Geometry, new AttributesTable());
                var values  = new object[reader.FieldCount - 1];
                reader.GetValues(values);
                for (var i = 0; i < values.Length; i++)
                {
                    var name  = reader.GetName(i + 1);
                    var value = values[i];
                    feature.Attributes.AddAttribute(name, value);
                }
                features.Add(feature);
            }
            Assert.AreEqual(703, features.Count);

            var shapepath = "strade_fixed";

            if (File.Exists(shapepath + shp))
            {
                File.Delete(shapepath + shp);
            }
            Assert.IsFalse(File.Exists(shapepath + shp));
            if (File.Exists(shapepath + shx))
            {
                File.Delete(shapepath + shx);
            }
            Assert.IsFalse(File.Exists(shapepath + shx));
            if (File.Exists(shapepath + dbf))
            {
                File.Delete(shapepath + dbf);
            }
            Assert.IsFalse(File.Exists(shapepath + dbf));

            var header = reader.DbaseHeader;

            var writer = new ShapefileDataWriter(shapepath, factory)
            {
                Header = header
            };

            writer.Write(features);

            Assert.IsTrue(File.Exists(shapepath + shp));
            Assert.IsTrue(File.Exists(shapepath + shx));
            Assert.IsTrue(File.Exists(shapepath + dbf));
        }
Example #13
0
        public static void CreateShpFile(Feature polygone, List <Feature> points)
        {
            GeometryFactory outGeomFactory = new GeometryFactory();
            string          folderPath     = Path.Combine("..\\..\\..\\data\\", polygone.Attributes["name"].ToString());

            System.IO.Directory.CreateDirectory(folderPath);
            ShapefileDataWriter writer = new ShapefileDataWriter($"{folderPath}/{polygone.Attributes["name"]}", outGeomFactory);

            DbaseFileHeader outDbaseHeader = ShapefileDataWriter.GetHeader((Feature)points[0], points.Count);

            writer.Header = outDbaseHeader;
            writer.Write(points);
        }
Example #14
0
        public static void Combine(string finalShape, string projection, params CombineShapefile[] combineShapes)
        {
            DbfHeader dbfHeader = new DbfHeader();

            dbfHeader.AddCharacter("Label", 80);

            ShapefileHeader shapeHeader = ShapefileHeader.CreateEmpty(ShapefileGeometryType.Polygon);
            GeometryFactory gf          = new GeometryFactory();

            using (ShapefileDataWriter writer = ShapefileDataWriter.Create(finalShape, dbfHeader, shapeHeader))
            {
                // Write the projection file.
                File.WriteAllText(Path.ChangeExtension(finalShape, ".prj"), projection);

                foreach (CombineShapefile workerShp in combineShapes)
                {
                    GeometryTransform transform = GeometryTransform.GetTransform(workerShp.FilePath, projection);

                    using (ShapefileIndexReader index = new ShapefileIndexReader(Path.ChangeExtension(workerShp.FilePath, ".shx")))
                    {
                        if (transform != null)
                        {
                            writer.Header.Bounds.ExpandToInclude(transform.Apply(index.Header.Bounds));
                        }
                        else
                        {
                            writer.Header.Bounds.ExpandToInclude(index.Header.Bounds);
                        }

                        Task[] tasks = new Task[Environment.ProcessorCount];
                        for (int i = 0; i < tasks.Length; i++)
                        {
                            tasks[i] = Task.Factory.StartNew(() =>
                            {
                                using (ShapefileBlockReader reader = new ShapefileBlockReader(workerShp.FilePath, index, gf, transform))
                                {
                                    while (reader.Read())
                                    {
                                        writer.Write(reader.Geometry, reader.Record.GetString(workerShp.Label));
                                    }
                                }
                            });
                        }

                        Task.WaitAll(tasks);

                        writer.Flush();
                    }
                }
            }
        }
        public void ok_when_writing_shapefile_with_no_features()
        {
            DbaseFileHeader header = new DbaseFileHeader();

            header.AddColumn("X", 'C', 10, 0);
            ShapefileDataWriter writer = new ShapefileDataWriter(@"issue36")
            {
                Header = header
            };

            IList <IFeature> features = new List <IFeature>();

            writer.Write(features);
        }
Example #16
0
        /// <summary>
        /// Executes the actual algorithm.
        /// </summary>
        protected override void DoRun()
        {
            // assumed here all arguments are as they should be.
            var features = new FeaturesList(_routerDb, _profiles);

            var header      = ShapefileDataWriter.GetHeader(features[0], features.Count);
            var shapeWriter = new ShapefileDataWriter(_fileName, new GeometryFactory())
            {
                Header = header
            };

            shapeWriter.Write(features);

            this.HasSucceeded = true;
        }
Example #17
0
        public void ok_when_writing_shapefile_with_no_features()
        {
            DbaseFileHeader header = new DbaseFileHeader();

            header.AddColumn("X", 'C', 10, 0);
            ShapefileDataWriter writer = new ShapefileDataWriter(@"issue36")
            {
                Header = header
            };

            IList <IFeature> features = new List <IFeature>();

            Assert.DoesNotThrow(() => writer.Write(features));

            _numPassed++;
        }
Example #18
0
        private void SaveGraphResult(IGeometry path)
        {
            if (path == null)
            {
                throw new ArgumentNullException("path");
            }

            const string shapepath = "graphresult";

            if (File.Exists(shapepath + shp))
            {
                File.Delete(shapepath + shp);
            }
            Assert.IsFalse(File.Exists(shapepath + shp));
            if (File.Exists(shapepath + shx))
            {
                File.Delete(shapepath + shx);
            }
            Assert.IsFalse(File.Exists(shapepath + shx));
            if (File.Exists(shapepath + dbf))
            {
                File.Delete(shapepath + dbf);
            }
            Assert.IsFalse(File.Exists(shapepath + dbf));

            const string field1  = "OBJECTID";
            var          feature = new Feature(path, new AttributesTable());

            feature.Attributes.AddAttribute(field1, 0);

            var header = new DbaseFileHeader {
                NumRecords = 1, NumFields = 1
            };

            header.AddColumn(field1, 'N', 5, 0);

            var writer = new ShapefileDataWriter(shapepath, factory)
            {
                Header = header
            };

            writer.Write(new List <IFeature>(new[] { feature, }));

            Assert.IsTrue(File.Exists(shapepath + shp));
            Assert.IsTrue(File.Exists(shapepath + shx));
            Assert.IsTrue(File.Exists(shapepath + dbf));
        }
        public void shapefile_with_empty_attributes_table_should_not_thrown_errors()
        {
            IFeature         feature  = new Feature(new Point(0, 0), new AttributesTable());
            IList <IFeature> features = new List <IFeature> {
                feature
            };

            string path   = CreateShapefilePath();
            var    header = ShapefileDataWriter.GetHeader(feature, features.Count);
            var    writer = new ShapefileDataWriter(path)
            {
                Header = header
            };

            writer.Write(features);
            Assert.That(File.Exists(Path.ChangeExtension(path, ".shp")), Is.True);
        }
Example #20
0
        /// <summary>
        /// Executes the actual algorithm.
        /// </summary>
        public void Run(CancellationToken cancellationToken)
        {
            // assumed here all arguments are as they should be.
            var features = new FeaturesList(_routerDb);

            if (features.Count == 0)
            {
                return;
            }

            var header      = ShapefileDataWriter.GetHeader(features[0], features.Count);
            var shapeWriter = new ShapefileDataWriter(_fileName, new GeometryFactory())
            {
                Header = header
            };

            shapeWriter.Write(features);
        }
        public Stream WriteShape(IList <Feature> featureCollection, string name, DbaseFileHeader header = null)
        {
            if (featureCollection.IsEmpty())
            {
                return(null);
            }
            ShapeMemoryStreamDataWriter shapeWriter = new ShapeMemoryStreamDataWriter(GISService.CreateGeometryFactory());

            shapeWriter.Header = header == null?ShapefileDataWriter.GetHeader(featureCollection.First(), featureCollection.Count) : header;

            shapeWriter.Write(featureCollection as IList);

            MemoryStream shpMemStream = shapeWriter.GetShpStream();
            MemoryStream shxMemStream = shapeWriter.GetShxStream();
            MemoryStream dbfMemStream = shapeWriter.GetDbfStream();
            MemoryStream prjMemStream = new MemoryStream(Encoding.UTF8.GetBytes(GisConstants.EsriWkt21781));
            MemoryStream cpgMemStream = new MemoryStream(Encoding.UTF8.GetBytes(GisConstants.EsriUTF8CodePage));

            ZipFile zipfile = new ZipFile();

            shpMemStream.Seek(0, 0);
            shxMemStream.Seek(0, 0);
            dbfMemStream.Seek(0, 0);
            prjMemStream.Seek(0, 0);

            zipfile.AddEntry(name + ".shp", shpMemStream);
            zipfile.AddEntry(name + ".shx", shxMemStream);
            zipfile.AddEntry(name + ".dbf", dbfMemStream);
            zipfile.AddEntry(name + ".prj", prjMemStream);
            zipfile.AddEntry(name + ".cpg", cpgMemStream);

            MemoryStream stream = new MemoryStream();

            zipfile.Save(stream);
            stream.Seek(0, 0);

            shpMemStream.Close();
            shxMemStream.Close();
            dbfMemStream.Close();
            prjMemStream.Close();
            return(stream);
        }
        public void ok_when_writing_shapefile_with_features()
        {
            DbaseFileHeader header = new DbaseFileHeader();

            header.AddColumn("X", 'C', 10, 0);
            ShapefileDataWriter writer = new ShapefileDataWriter(@"issue36")
            {
                Header = header
            };

            IAttributesTable attributesTable = new AttributesTable();

            attributesTable.AddAttribute("X", "y");
            IFeature feature = new Feature(new Point(1, 2), attributesTable);

            IList <IFeature> features = new List <IFeature>();

            features.Add(feature);
            writer.Write(features);
        }
        // see https://code.google.com/p/nettopologysuite/issues/detail?id=146
        public void Issue146_ShapeCreationWithInvalidAttributeName()
        {
            Coordinate[] points = new Coordinate[3];
            points[0] = new Coordinate(0, 0);
            points[1] = new Coordinate(1, 0);
            points[2] = new Coordinate(1, 1);
            LineString       ls  = new LineString(points);
            IMultiLineString mls = GeometryFactory.Default.CreateMultiLineString(new ILineString[] { ls });

            AttributesTable attrs = new AttributesTable();

            attrs.AddAttribute("Simulation name", "FOO");

            Feature[]           features   = new[] { new Feature(mls, attrs) };
            ShapefileDataWriter shp_writer = new ShapefileDataWriter("invalid_line_string")
            {
                Header = ShapefileDataWriter.GetHeader(features[0], features.Length)
            };

            shp_writer.Write(features);
        }
Example #24
0
        private void SaveCommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            Layer layerToSave = CollectionViewSource.GetDefaultView(Layers).CurrentItem as Layer;

            if (layerToSave.FileName != "")
            {
                saveFileDialog.FileName         = Path.GetFileNameWithoutExtension(layerToSave.FileName);
                saveFileDialog.InitialDirectory = layerToSave.FileName;
            }
            if (saveFileDialog.ShowDialog() == true)
            {
                string name = saveFileDialog.FileName;
                try
                {
                    mapCanvas.CommitAll();

                    List <Feature> features = new List <Feature>();

                    foreach (ShapefileShape item in layerToSave.Shapes)
                    {
                        Dictionary <string, object> dictionary = new Dictionary <string, object>();
                        foreach (ShapefileAttributeEntry items in item.Attributes)
                        {
                            dictionary.Add(items.FieldDescriptor.Name, items.Value);
                        }
                        features.Add(new Feature(item.Geometry, new AttributesTable(dictionary)));
                    }

                    ShapefileDataWriter writer = new ShapefileDataWriter(name, GeometryFactory.Default)
                    {
                        Header = layerToSave.Header
                    };
                    writer.Write(features);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                }
            }
        }
        public void Setup()
        {
            var sfdr = new ShapefileDataWriter("encoding_sample");
            var h    = new DbaseFileHeader();

            h.AddColumn("id", 'n', 8, 0);
            h.AddColumn("Test", 'C', 15, 0);
            h.AddColumn("Ålder", 'N', 8, 0);
            h.AddColumn("Ödestext", 'C', 254, 0);
            h.NumRecords = 1;
            sfdr.Header  = h;

            var feats = new List <IFeature>();
            var at    = new AttributesTable();

            at.Add("id", "0");
            at.Add("Test", "Testar");
            at.Add("Ålder", 10);
            at.Add("Ödestext", "Lång text med åäö etc");
            feats.Add(new Feature(new Point(0, 0), at));
            sfdr.Write(feats);
        }
        public void Create(List <RadioInfo> list, string outputName, string projection)
        {
            var features = new List <IFeature>();

            foreach (RadioInfo radio in list)
            {
                ///////
                var attributesTable = new AttributesTable();
                if (radio.Geometry != null)
                {
                    attributesTable.AddAttribute("Redcode", radio.Redcode);
                    attributesTable.AddAttribute("IsValid", radio.Geometry.IsValid);
                    attributesTable.AddAttribute("Points", radio.Geometry.Coordinates.Count());
                    attributesTable.AddAttribute("AreaKm2", radio.Geometry.Area * 1000 * 1000);
                    attributesTable.AddAttribute("Polygons", radio.Polygon.Count);
                    attributesTable.AddAttribute("PerimeterKm", radio.TotalPerimeter * 1000);
                    GeometryFactory fc  = new GeometryFactory();
                    var             geo = radio.Geometry;
                    features.Add(new Feature(geo, attributesTable));
                }
                else
                {
                    Console.WriteLine("Empty geometry: " + radio.Redcode);
                }
            }
            // Create the shapefile
            var outGeomFactory = GeometryFactory.Default;
            var writer         = new ShapefileDataWriter(Context.ResolveFilename(outputName), outGeomFactory);
            var outDbaseHeader = ShapefileDataWriter.GetHeader(features[0], features.Count);

            writer.Header = outDbaseHeader;
            writer.Write(features);

            // Create the projection file
            using (var streamWriter = new StreamWriter(Context.ResolveFilename(outputName + ".prj")))
            {
                streamWriter.Write(projection);
            }
        }
Example #27
0
        public static void Convert(ShapefileGeometryType type, SqlDataReader reader, string shapefile)
        {
            if (!reader.Read())
            {
                throw new Exception("No Results found");
            }

            int             geomOrdinal, colCount;
            ShapefileHeader shapeHeader = ShapefileHeader.CreateEmpty(type);
            DbfHeader       dbfHeader   = BuildHeader(reader, out geomOrdinal, out colCount);
            GeometryFactory factory     = new GeometryFactory();
            Envelope        env         = shapeHeader.Bounds;

            using (ShapefileDataWriter writer = ShapefileDataWriter.Create(shapefile, dbfHeader, shapeHeader))
            {
                do
                {
                    SqlGeometry geom = reader[geomOrdinal] as SqlGeometry;
                    if (!geom.STIsValid())
                    {
                        geom = geom.MakeValid();
                    }

                    for (int i = 0, offset = 0; i < colCount; i++)
                    {
                        if (i == geomOrdinal)
                        {
                            offset++;
                        }

                        writer.Record.SetRaw(i, reader[i + offset]);
                    }

                    ExpandEnv(env, geom.STBoundary());
                    writer.Write(ConvertToGeometry.SqlGeometryToGeometry(geom, factory));
                }while (reader.Read());
            }
        }
        public void ok_when_writing_shapefile_with_features()
        {
            var header = new DbaseFileHeader();

            header.AddColumn("X", 'C', 10, 0);
            var writer = new ShapefileDataWriter(@"issue36")
            {
                Header = header
            };

            IAttributesTable attributesTable = new AttributesTable();

            attributesTable.Add("X", "y");
            IFeature feature = new Feature(new Point(1, 2), attributesTable);

            IList <IFeature> features = new List <IFeature>();

            features.Add(feature);

            Assert.DoesNotThrow(() => writer.Write(features));

            _numPassed++;
        }
Example #29
0
        public void SaveNodesToShape(string shapeFileName, Dictionary <long, GeoNode> allNodesCache, List <GeoNode> nodesToSave)
        {
            string firstNameAttribute = "a";
            string lastNameAttribute  = "b";

            //create geometry factory
            IGeometryFactory geomFactory = NtsGeometryServices.Instance.CreateGeometryFactory();


            IList <Feature> features = new List <Feature>();

            for (int i = 0; i < nodesToSave.Count - 1; i++)
            {
                GeoNode node1 = nodesToSave[i];
                GeoNode node2 = nodesToSave[i + 1];
                //var ngbGeoNode = allNodesCache[ngb.NodeId];
                var             line = geomFactory.CreateLineString(new[] { new Coordinate(node1.Longitude, node1.Latitude), new Coordinate(node2.Longitude, node2.Latitude) });
                AttributesTable t1   = new AttributesTable();
                t1.AddAttribute(firstNameAttribute, node1.OSMId);
                t1.AddAttribute(lastNameAttribute, node2.OSMId);

                Feature feat = new Feature(line, t1);
                features.Add(feat);
            }
            var dirName = Path.GetDirectoryName(shapeFileName);

            if (!Directory.Exists(dirName))
            {
                Directory.CreateDirectory(dirName);
            }
            var writer = new ShapefileDataWriter(shapeFileName)
            {
                Header = ShapefileDataWriter.GetHeader(features[0], features.Count)
            };

            writer.Write(features);
        }
        public void Test()
        {
            var features = new List <IFeature>();
            var seq      = DotSpatialAffineCoordinateSequenceFactory.Instance.Create(1, Ordinates.XY);

            seq.SetOrdinate(0, Ordinate.X, -91.0454);
            seq.SetOrdinate(0, Ordinate.Y, 32.5907);
            var pt   = new GeometryFactory(DotSpatialAffineCoordinateSequenceFactory.Instance).CreatePoint(seq);
            var attr = new AttributesTable();

            attr.Add("FirstName", "John");
            attr.Add("LastName", "Doe");
            features.Add(new Feature(pt, attr));

            string fileName = Path.GetTempFileName();

            fileName = fileName.Substring(0, fileName.Length - 4);
            var shpWriter = new ShapefileDataWriter(fileName, features[0].Geometry.Factory)
            {
                Header = ShapefileDataWriter.GetHeader(features[0], features.Count)
            };

            shpWriter.Write(features);

            bool isTrue;

            using (var reader = new ShapefileDataReader(fileName, pt.Factory))
                @isTrue = reader.ShapeHeader.ShapeType.ToString() == "Point";

            foreach (string file in Directory.GetFiles(Path.GetTempPath(), Path.GetFileName(fileName) + ".*"))
            {
                File.Delete(file);
            }

            Assert.IsTrue(@isTrue);
        }