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.Add("FOO", "FOO");

            var feature  = new Feature(Factory.CreateMultiLineString(new LineString[] { 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);
        }
Exemple #2
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);
            }

            ShapefileDataWriter 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);
        }
Exemple #3
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);
    }
Exemple #4
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);
            }
        }
Exemple #5
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));
        }
Exemple #6
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);
        }
Exemple #7
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);
        }
Exemple #9
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;
        }
Exemple #10
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++;
        }
Exemple #11
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);
        }
Exemple #13
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 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);
        }
Exemple #16
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 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);
            }
        }
        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 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++;
        }
        private void TestShapeCreation()
        {
            ICoordinate[] points = new ICoordinate[3];
            points[0] = new Coordinate(0, 0);
            points[1] = new Coordinate(1, 0);
            points[2] = new Coordinate(1, 1);

            LineString line_string = new LineString(points);

            AttributesTable attributes = new AttributesTable();

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

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

            Feature[] features = new Feature[1];
            features[0] = feature;

            ShapefileDataWriter shp_writer = new ShapefileDataWriter("C:\\line_string");

            shp_writer.Header = ShapefileDataWriter.GetHeader(features[0], features.Length);
            shp_writer.Write(features);
        }
Exemple #22
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);
        }
Exemple #24
0
 /// <summary>
 /// xy列表直接输出到shape文件
 /// </summary>
 /// <param name="polygonXYList">x1 y1,x2 y2,x3 y3,x4 y4</param>
 /// <param name="bw"></param>
 public static void ExportShapeFile(string path, List <string> polygonXYList)
 {
     try
     {
         ShapefileDataWriter shapeWrite  = new ShapefileDataWriter(path);
         IGeometryFactory    pGFactory   = new GeometryFactory();
         IList <Feature>     featureList = new List <Feature>();
         foreach (string str in polygonXYList)
         {
             List <Coordinate> coordList = new List <Coordinate>();
             string[]          xys       = str.Split(',');
             string            name      = xys[0];
             AttributesTable   at        = new AttributesTable();
             at.AddAttribute("TFH", name);
             for (int i = 1; i < xys.Length; i++)
             {
                 string[] xandy = xys[i].Split(' ');
                 double   x = 0, y = 0;
                 double.TryParse(xandy[0], out x);
                 double.TryParse(xandy[1], out y);
                 Coordinate coord = new Coordinate(x, y);
                 coordList.Add(coord);
             }
             IPolygon pPolygon = pGFactory.CreatePolygon(coordList.ToArray());
             Feature  f        = new Feature(pPolygon, at);
             featureList.Add(f);
         }
         System.Collections.IList features = (System.Collections.IList)featureList;
         shapeWrite.Header = ShapefileDataWriter.GetHeader(featureList[0], featureList.Count);
         shapeWrite.Write(features);
     }
     catch (Exception ex)
     {
         throw ex;
     }
 }
Exemple #25
0
        public void BuildShapefilesFromGraphBinary()
        {
            int       index = 0;
            IGeometry edges;
            WKBReader reader = new WKBReader(factory);

            using (FileStream stream = new FileStream("graph", FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                edges = reader.Read(stream);
                index++;
            }
            Assert.AreEqual(1, index);
            Assert.IsNotNull(edges);
            Assert.IsInstanceOfType(typeof(MultiLineString), edges);
            Assert.AreEqual(1179, edges.NumGeometries);

            string field1   = "OBJECTID";
            string field2   = "DESCRIPTION";
            IList  features = new List <Feature>(edges.NumGeometries);

            for (int i = 0; i < edges.NumGeometries; i++)
            {
                IGeometry ls = edges.GetGeometryN(i);
                Assert.IsInstanceOfType(typeof(LineString), ls);

                Feature f = new Feature(ls, new AttributesTable());
                f.Attributes.AddAttribute(field1, i);
                f.Attributes.AddAttribute(field2, String.Format("length: {0}", Convert.ToInt64(ls.Length)));
                features.Add(f);
            }
            Assert.IsNotEmpty(features);
            Assert.AreEqual(edges.NumGeometries, features.Count);

            DbaseFileHeader header = new DbaseFileHeader();

            header.NumRecords = edges.NumGeometries;
            header.NumFields  = 1;
            header.AddColumn(field1, 'N', 5, 0);
            header.AddColumn(field2, 'C', 254, 0);

            string path = "graph";

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

            ShapefileDataWriter writer = new ShapefileDataWriter(path, factory);

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

            Assert.IsTrue(File.Exists(path + shp));
            Assert.IsTrue(File.Exists(path + shx));
            Assert.IsTrue(File.Exists(path + dbf));

            IList subset = new List <Feature>(15);

            for (int i = 0; i < 15; i++)
            {
                subset.Add(features[i]);
            }
            Assert.IsNotEmpty(subset);
            Assert.AreEqual(15, subset.Count);

            path = "minimalgraph";
            if (File.Exists(path + shp))
            {
                File.Delete(path + shp);
            }
            Assert.IsFalse(File.Exists(path + shp));
            if (File.Exists(path + shx))
            {
                File.Delete(path + shx);
            }
            Assert.IsFalse(File.Exists(path + shx));
            if (File.Exists(path + dbf))
            {
                File.Delete(path + dbf);
            }
            Assert.IsFalse(File.Exists(path + dbf));

            writer        = new ShapefileDataWriter(path, factory);
            writer.Header = header;
            writer.Write(subset);

            Assert.IsTrue(File.Exists(path + shp));
            Assert.IsTrue(File.Exists(path + shx));
            Assert.IsTrue(File.Exists(path + dbf));
        }
        private void ReadFromShapeFile()
        {
            var          featureCollection = new List <IFeature>();
            const string filename          = @"country";

            if (!File.Exists(filename + ".dbf"))
            {
                throw new FileNotFoundException(filename + " not found at " + Environment.CurrentDirectory);
            }
            var dataReader = new ShapefileDataReader(filename, new GeometryFactory());

            while (dataReader.Read())
            {
                var feature = new Feature {
                    Geometry = dataReader.Geometry
                };

                var length = dataReader.DbaseHeader.NumFields;
                var keys   = new string[length];
                for (var i = 0; i < length; i++)
                {
                    keys[i] = dataReader.DbaseHeader.Fields[i].Name;
                }

                feature.Attributes = new AttributesTable();
                for (var i = 0; i < length; i++)
                {
                    var val = dataReader.GetValue(i);
                    feature.Attributes.AddAttribute(keys[i], val);
                }

                featureCollection.Add(feature);
            }

            var index = 0;

            Console.WriteLine("Elements = " + featureCollection.Count);
            foreach (IFeature feature in featureCollection)
            {
                Console.WriteLine("Feature " + index++);
                var table = feature.Attributes as AttributesTable;
                foreach (var name in table.GetNames())
                {
                    Console.WriteLine(name + ": " + table[name]);
                }
            }

            //Directory
            var dir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory,
                                   string.Format(@"..{0}..{0}..{0}NetTopologySuite.Samples.Shapefiles{0}",
                                                 Path.DirectorySeparatorChar));
            // Test write with stub header
            var file = dir + "testWriteStubHeader";

            if (File.Exists(file + ".shp"))
            {
                File.Delete(file + ".shp");
            }
            if (File.Exists(file + ".shx"))
            {
                File.Delete(file + ".shx");
            }
            if (File.Exists(file + ".dbf"))
            {
                File.Delete(file + ".dbf");
            }

            var dataWriter = new ShapefileDataWriter(file);

            dataWriter.Header = ShapefileDataWriter.GetHeader(featureCollection[0] as IFeature, featureCollection.Count);
            dataWriter.Write(featureCollection);

            // Test write with header from a existing shapefile
            file = dir + "testWriteShapefileHeader";
            if (File.Exists(file + ".shp"))
            {
                File.Delete(file + ".shp");
            }
            if (File.Exists(file + ".shx"))
            {
                File.Delete(file + ".shx");
            }
            if (File.Exists(file + ".dbf"))
            {
                File.Delete(file + ".dbf");
            }

            dataWriter = new ShapefileDataWriter(file)
            {
                Header =
                    ShapefileDataWriter.GetHeader(dir + "country.dbf")
            };
            dataWriter.Write(featureCollection);
        }
Exemple #27
0
        private void TestWriteZMValuesShapeFile(bool testM)
        {
            var points = new Coordinate[3];

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

            var csFactory = DotSpatialAffineCoordinateSequenceFactory.Instance;
            var sequence  = csFactory.Create(3, Ordinates.XYZM);

            for (int i = 0; i < 3; i++)
            {
                sequence.SetOrdinate(i, Ordinate.X, points[i].X);
                sequence.SetOrdinate(i, Ordinate.Y, points[i].Y);
                sequence.SetOrdinate(i, Ordinate.Z, 1 + i);
                if (testM)
                {
                    sequence.SetOrdinate(i, Ordinate.M, 11 + i);
                }
            }
            var lineString = Factory.CreateLineString(sequence);

            var attributes = new AttributesTable();

            attributes.Add("FOO", "Trond");

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

            features[0] = feature;

            var shpWriter = new ShapefileDataWriter("ZMtest", Factory)
            {
                Header = ShapefileDataWriter.GetHeader(features[0], features.Length)
            };

            shpWriter.Write(features);

            // Now let's read the file and verify that we got Z and M back
            var factory = new GeometryFactory(DotSpatialAffineCoordinateSequenceFactory.Instance);

            using (var reader = new ShapefileDataReader("ZMtest", factory))
            {
                reader.Read();
                var geom = reader.Geometry;

                for (int i = 0; i < 3; i++)
                {
                    var c = geom.Coordinates[i];
                    Assert.AreEqual(i + 1, c.Z);
                }

                if (testM)
                {
                    sequence = ((ILineString)geom).CoordinateSequence;
                    for (int i = 0; i < 3; i++)
                    {
                        Assert.AreEqual(sequence.GetOrdinate(i, Ordinate.M), 11 + i);
                    }
                }

                // Run a simple attribute test too
                string v = reader.GetString(1);
                Assert.AreEqual(v, "Trond");
            }
        }
        public async Task <IActionResult> GenerateFile()
        {
            var data = await _context.Profiles.Select(p => new
            {
                p.FirstName,
                p.LastName,
                p.Latitude,
                p.Longitude,
                p.CompanyName,
                p.IsDropOffPoint,
                p.Phone,
                p.IsRequestor,
                p.IsSupplier,
            }).ToListAsync();

            var geomFactory = NtsGeometryServices.Instance.CreateGeometryFactory();
            var features    = new List <Feature>();

            var faker = new Bogus.Faker("en");

            foreach (var d in data)
            {
                //note that attribute names can be at most 11 characters
                var t1 = new AttributesTable
                {
                    { "firstName", d.FirstName ?? "" },
                    { "lastName", d.LastName ?? "" },
                    { "companyName", d.CompanyName ?? "" },
                    { "dropOff", d.IsDropOffPoint.GetValueOrDefault().ToString() },
                    { "type", DetermineType(d.IsRequestor, d.IsSupplier) },
                    { "phoneNumber", d.Phone ?? "" },
                    { "amount1", faker.Random.Number(100, 10000) },
                    { "product1", faker.Commerce.ProductName() }
                };

                Geometry g1 = geomFactory.CreatePoint(new Coordinate(d.Longitude, d.Latitude));

                var feat1 = new Feature(g1, t1);
                features.Add(feat1);
            }

            var shapeFileFolder = GetShapeFilePath();
            var zipPath         = GetZipFilePath();
            var shapefileName   = Path.Combine(shapeFileFolder, "maker");

            var writer = new ShapefileDataWriter(shapefileName)
            {
                Header = ShapefileDataWriter.GetHeader(features[0], features.Count)
            };

            writer.Write(features);

            if (System.IO.File.Exists(zipPath))
            {
                System.IO.File.Delete(zipPath);
            }

            ZipFile.CreateFromDirectory(shapeFileFolder, zipPath, CompressionLevel.Fastest, false);

            await using (var csvWriter = new StreamWriter(GetCSVFilePath()))
                await using (var csv = new CsvWriter(csvWriter, CultureInfo.InvariantCulture))
                {
                    csv.WriteRecords(data);
                }


            return(Ok($"Files created and zipped to {zipPath}"));
        }
Exemple #29
0
        public static void Compress(string shapeFilePath, int gridFieldIndex, string encoding = null, string outputShapeFileName = "")
        {
            var factory = new GeometryFactory();

            if (!File.Exists(shapeFilePath))
            {
                Console.WriteLine("文件不存在。");
                return;
            }
            string filePath            = Path.GetDirectoryName(shapeFilePath);
            string outputShapeFilePath = "";
            var    outputFilePath      = Path.ChangeExtension(shapeFilePath, ".text");

            if (!string.IsNullOrEmpty(outputShapeFileName))
            {
                outputShapeFilePath = Path.Combine(filePath, outputShapeFileName);
                outputFilePath      = Path.ChangeExtension(outputShapeFileName, ".txt");
            }

            var      nFile        = new FileStream(outputFilePath, FileMode.Create);
            Encoding fileEncoding = Encoding.UTF8;

            nFile.Position = nFile.Length;

            var fts = new List <IFeature>();
            ShapefileDataReader reader;

            if (string.IsNullOrEmpty(encoding))
            {
                reader = new ShapefileDataReader(shapeFilePath, factory);
            }
            else
            {
                Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
                reader = new ShapefileDataReader(shapeFilePath, factory, Encoding.GetEncoding(encoding));
            }

            using (reader)
            {
                var  dict        = new Dictionary <string, IGeometry>();
                int  count       = 0;
                long recordCount = 0;
                try {
                    while (reader.Read())
                    {
                        recordCount++;
                        var gridId = reader.GetString(gridFieldIndex);
                        if (dict.ContainsKey(gridId))
                        {
                            continue;
                        }

                        count++;
                        if (count % 1000 == 0)
                        {
                            Console.WriteLine($"{count}");
                            nFile.Flush();
                        }


                        dict.Add(gridId, reader.Geometry);
                        string text  = $"{gridId},{reader.Geometry.ToString()}\n";
                        var    bytes = fileEncoding.GetBytes(text);

                        nFile.Write(bytes, 0, bytes.Length);

                        var attrs = new AttributesTable();
                        attrs.Add("GRIDID", gridId);
                        var feature = new Feature(reader.Geometry, attrs);
                        fts.Add(feature);
                    }
                }
                catch (Exception)
                {
                    Console.WriteLine($"第{recordCount}条记录读取错误!");
                    throw;
                }
                Console.WriteLine($"共处理{reader.RecordCount}条数据,压缩生成{count}条数据");


                nFile.Close();
            };


            if (!string.IsNullOrEmpty(outputShapeFilePath))
            {
                var writer = new ShapefileDataWriter(outputShapeFilePath, factory);
                writer.Header = ShapefileDataWriter.GetHeader(fts[0], fts.Count);
                writer.Write(fts);
            }

            Console.WriteLine("成功结束!");
        }
        public static void Reproject(string destinationFolder, string projection, params ReprojectShapefile[] shapes)
        {
            ProjectionInfo targetProjection = ProjectionInfo.FromEsriString(projection);

            foreach (ReprojectShapefile shape in shapes)
            {
                string shapePath = Path.Combine(destinationFolder, shape.DestinationName);

                ShapefileHeader shapeHeader = ShapefileHeader.CreateEmpty(ShapefileGeometryType.Polygon);
                DbfHeader       dbfHeader   = new DbfHeader();
                dbfHeader.AddCharacter("Label", 80);
                GeometryFactory gf = new GeometryFactory();

                using (ShapefileDataWriter writer = ShapefileDataWriter.Create(shapePath + ".shp", dbfHeader, shapeHeader))
                {
                    GeometryTransform transform = null;
                    if (File.Exists(Path.ChangeExtension(shape.Source, ".prj")))
                    {
                        transform = GeometryTransform.GetTransform(shape.Source, projection);

                        if (transform != null)
                        {
                            File.WriteAllText(shapePath + ".prj", projection);
                        }
                        else
                        {
                            File.Copy(Path.ChangeExtension(shape.Source, ".prj"), shapePath + ".prj");
                        }
                    }

                    using (ShapefileIndexReader index = new ShapefileIndexReader(Path.ChangeExtension(shape.Source, ".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(shape.Source, index, gf, transform))
                                {
                                    while (reader.Read())
                                    {
                                        writer.Write(reader.Geometry, reader.Record.GetString(shape.Label));
                                    }
                                }
                            });
                        }

                        Task.WaitAll(tasks);

                        writer.Flush();
                    }
                }
            }
        }