Пример #1
0
        /// <summary>
        /// Writes a spatial data set object to a Stream as KML
        /// </summary>
        /// <param name="geometries">A spatial data set to write</param>
        /// <param name="stream">Stream to write KML to.</param>
        /// <param name="compress">A boolean indicating if the Kml feed should be compressed as a Kmz file.</param>
        public Task WriteAsync(SpatialDataSet data, Stream stream, bool compress)
        {
            return(Task.Run(() =>
            {
                if (compress)
                {
                    using (var zipFile = new System.IO.Compression.ZipArchive(stream, System.IO.Compression.ZipArchiveMode.Create, false, Encoding.UTF8))
                    {
                        var entry = zipFile.CreateEntry("root.kml");

                        using (var xWriter = XmlWriter.Create(entry.Open(), xmlWriterSettings))
                        {
                            Write(data, xWriter);
                        }
                    }
                }
                else
                {
                    using (var xWriter = XmlWriter.Create(stream, xmlWriterSettings))
                    {
                        Write(data, xWriter);
                    }
                }
            }));
        }
Пример #2
0
        private void Write(SpatialDataSet data, XmlWriter xmlWriter)
        {
            //Open document
            xmlWriter.WriteStartDocument(true);

            //Write root tag and namespaces.
            xmlWriter.WriteStartElement("gpx", GpxNamespace);
            xmlWriter.WriteAttributeString("version", "1.1");
            xmlWriter.WriteAttributeString("xmlns", "gpxx", "http://www.w3.org/2000/xmlns/", GpxxNamespace);
            xmlWriter.WriteAttributeString("xmlns", "xsi", "http://www.w3.org/2000/xmlns/", XsiNamespace);
            xmlWriter.WriteAttributeString("xsi", "schemaLocation", XsiNamespace, "http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd");

            //Write document metadata.
            WriteDocumentMetadata(data, xmlWriter);

            foreach (var item in data.Geometries)
            {
                WriteGeometry(item, xmlWriter);
            }

            //Close feed tag
            xmlWriter.WriteEndElement();

            //Close document
            xmlWriter.WriteEndDocument();
        }
Пример #3
0
        private async Task <SpatialDataSet> ParseFolder(XElement doc, int requestLevel, string baseUri)
        {
            var result = new SpatialDataSet();

            var documents = (from x in doc.Elements()
                             where string.Compare(x.Name.LocalName, "Document", StringComparison.OrdinalIgnoreCase) == 0 ||
                             string.Compare(x.Name.LocalName, "Folder", StringComparison.OrdinalIgnoreCase) == 0 ||
                             string.Compare(x.Name.LocalName, "Placemark", StringComparison.OrdinalIgnoreCase) == 0
                             select x).ToList();

            foreach (var d in documents)
            {
                var data = await ParseContainer(d, requestLevel, baseUri);

                if (data.Geometries.Count > 0)
                {
                    result.Append(data);
                }

                //Get embedded folders
                var data2 = await ParseFolder(d, requestLevel, baseUri);

                if (data2.Geometries.Count > 0)
                {
                    result.Append(data2);
                }
            }

            return(result);
        }
Пример #4
0
        /// <summary>
        /// Reads a geometry from a stream of Well Known Binary asynchronously.
        /// </summary>
        /// <param name="stream">Stream of Well Known Binary</param>
        /// <returns>A SpatialDataSet containing the geometry. Only the one geometry is return.</returns>
        public override Task <SpatialDataSet> ReadAsync(Stream stream)
        {
            return(Task.Run <SpatialDataSet>(async() =>
            {
                try
                {
                    // Create a new binary reader using the newly created memorystream.
                    using (BinaryReader reader = new BinaryReader(stream))
                    {
                        // Call the main read function.
                        var g = await Read(reader);

                        var data = new SpatialDataSet()
                        {
                            BoundingBox = g.Envelope()
                        };

                        data.Geometries.Add(g);

                        return data;
                    }
                }
                catch (Exception ex)
                {
                    return new SpatialDataSet()
                    {
                        Error = ex.Message
                    };
                }
            }));
        }
Пример #5
0
        public IHttpActionResult InspireDatasetMonitoring(string registerName, string itemowner, string item)
        {
            Models.InspireDataset inspireDataset           = _inspireDatasetService.GetInspireDatasetByName(registerName, item);
            SpatialDataSet        inspireDatasetMonitoring = _inspireMonitoringService.MappingSpatialDataSet(inspireDataset);

            return(Ok(inspireDatasetMonitoring));
        }
Пример #6
0
        /// <summary>
        /// Read shapes items from the given BinaryReader.
        /// </summary>
        /// <param name="reader">A Shapefile as a BinaryReader</param>
        /// <returns>A List of ShapefileItem objects</returns>
        public Task <SpatialDataSet> ReadAsync(BinaryReader reader)
        {
            return(Task.Run <SpatialDataSet>(async() =>
            {
                try
                {
                    using (reader)
                    {
                        var data = new SpatialDataSet();

                        ShapefileShapeType shapeType;
                        BoundingBox bounds;

                        // Read the File Header.
                        ReadFileHeader(reader, out shapeType, out bounds);

                        //Read in shape records
                        data.Geometries = await ReadShapeRecords(reader, shapeType);
                        data.BoundingBox = bounds;

                        return data;
                    }
                }
                catch { }

                return null;
            }));
        }
Пример #7
0
        private async Task <SpatialDataSet> ParseGeoRSS(XDocument doc, string baseUri)
        {
            var result = new SpatialDataSet();

            try
            {
                var geoms  = new List <Geometry>();
                var styles = new Dictionary <string, ShapeStyle>();

                var channel = XmlUtilities.GetChildNode(doc.Root, "channel");

                if (channel != null)
                {
                    var items = XmlUtilities.GetElementsByTagName(channel, "item");
                    if (items != null)
                    {
                        for (int i = 0; i < items.Count; i++)
                        {
                            var g = await ParseGeoRSSItem(items[i], baseUri, styles);

                            if (g != null)
                            {
                                geoms.Add(g);
                            }
                        }
                    }
                }

                var entries = XmlUtilities.GetElementsByTagName(doc.Root, "entry");
                if (entries != null)
                {
                    for (int i = 0; i < entries.Count; i++)
                    {
                        var g = await ParseGeoRSSItem(entries[i], baseUri, styles);

                        if (g != null)
                        {
                            geoms.Add(g);
                        }
                    }
                }

                if (geoms.Count > 0)
                {
                    if (styles.Count > 0)
                    {
                        result.Styles = styles;
                    }

                    result.Geometries  = geoms;
                    result.BoundingBox = geoms.Envelope();
                }
            }
            catch (Exception ex)
            {
                result.Error = ex.Message;
            }

            return(result);
        }
Пример #8
0
        public Task <string> WriteAsync(SpatialDataSet data)
        {
            return(Task.Run <string>(() =>
            {
                if (_dataSourceType == BingDataSourceType.XML)
                {
                    var sb = new StringBuilder();

                    using (var xWriter = XmlWriter.Create(sb, xmlWriterSettings))
                    {
                        Write(data, xWriter);
                    }

                    return sb.ToString();
                }
                else
                {
                    using (var writer = new MemoryStream())
                    {
                        Write(data, writer);

                        using (var reader = new StreamReader(writer))
                        {
                            return reader.ReadToEnd();
                        }
                    }
                }
            }));
        }
Пример #9
0
 private void ClearMap()
 {
     PinLayer.Children.Clear();
     PolyLayer.Children.Clear();
     MetadataTbx.Text          = string.Empty;
     MetadataPanel.DataContext = null;
     DescriptionBox.Navigate("about:blank");
     CurrentDataSet = null;
 }
Пример #10
0
        /// <summary>
        /// Writes a list of geometries to a string.
        /// </summary>
        /// <param name="data">Data set to write</param>
        /// <returns>A GeoJSON string of the geometries</returns>
        public override Task <string> WriteAsync(SpatialDataSet data)
        {
            return(Task.Run <string>(() =>
            {
                // return Write(data);

                return string.Empty;
            }));
        }
Пример #11
0
 /// <summary>
 /// Writes a spatial data set to a Stream as GeoRSS
 /// </summary>
 /// <param name="data">A spatial data set containing the spatial data.</param>
 /// <param name="stream">A stream to write GeoRSS to.</param>
 public override Task WriteAsync(SpatialDataSet data, Stream stream)
 {
     return(Task.Run(() =>
     {
         using (var writer = XmlWriter.Create(stream, xmlWriterSettings))
         {
             Write(data, writer);
         }
     }));
 }
Пример #12
0
        void CenterView(SpatialDataSet data)
        {
            if (data.BoundingBox != null)
            {
#if WINDOWS_APP
                MyMap.SetView(data.BoundingBox.Center.ToBMGeometry().ToGeopoint().Position, 10);
#elif WINDOWS_PHONE_APP
                MyMap.SetView(data.BoundingBox.Center.ToBMGeometry(), 10);
#endif
            }
        }
Пример #13
0
 /// <summary>
 /// Writes a spatial data set object as a string.
 /// </summary>
 /// <param name="data">Data set to write</param>
 /// <returns>A GeoJSON string</returns>
 public override Task WriteAsync(SpatialDataSet data, Stream stream)
 {
     return(Task.Run(() =>
     {
         using (var writer = new StreamWriter(stream))
         {
             //var sGeoms = Write(data);
             //writer.Write(sGeoms);
         }
     }));
 }
        public SpatialDataSet MappingSpatialDataSet(InspireDataset inspireDataset)
        {
            var spatialDataset = new SpatialDataSet();

            spatialDataset.name               = inspireDataset.Name;
            spatialDataset.respAuthority      = inspireDataset.Owner?.name;
            spatialDataset.uuid               = inspireDataset.Uuid;
            spatialDataset.Themes             = GetThemes(inspireDataset.InspireThemes);
            spatialDataset.Coverage           = GetCoverage(inspireDataset);
            spatialDataset.MdDataSetExistence = GetMdDatasetEcistence(inspireDataset);
            return(spatialDataset);
        }
Пример #15
0
        private void Write(SpatialDataSet data, XmlWriter xmlWriter)
        {
            //<?xml version="1.0" encoding="utf-8"?>
            //<feed xmlns="http://www.w3.org/2005/Atom"
            //      xmlns:georss="http://www.georss.org/georss"
            //      xmlns:gml="http://www.opengis.net/gml">
            //   <title>Earthquakes</title>
            //   <subtitle>International earthquake observation labs</subtitle>
            //   <link href="http://example.org/"/>
            //   <updated>2005-12-13T18:30:02Z</updated>
            //   <author>
            //      <name>Dr. Thaddeus Remor</name>
            //      <email>[email protected]</email>
            //   </author>
            //   <id>urn:uuid:60a76c80-d399-11d9-b93C-0003939e0af6</id>
            //   <entry>
            //      <title>M 3.2, Mona Passage</title>
            //      <link href="http://example.org/2005/09/09/atom01"/>
            //      <id>urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a</id>
            //      <updated>2005-08-17T07:02:32Z</updated>
            //      <summary>We just had a big one.</summary>

            //      <georss:where>
            //         <gml:Point>
            //            <gml:pos>45.256 -71.92</gml:pos>
            //         </gml:Point>
            //      </georss:where>
            //   </entry>
            //</feed>

            //Open document
            xmlWriter.WriteStartDocument(true);

            //Write root tag and namespaces.
            xmlWriter.WriteStartElement("feed", "http://www.w3.org/2005/Atom");
            xmlWriter.WriteAttributeString("xmlns", "georss", "http://www.w3.org/2000/xmlns/", GeoRssNamespace);
            xmlWriter.WriteAttributeString("xmlns", "gml", "http://www.w3.org/2000/xmlns/", Gml.GmlNamespace);
            xmlWriter.WriteAttributeString("xmlns", "mappoint", "http://www.w3.org/2000/xmlns/", MapPointNamespace);

            //Write document metadata.
            WriteMetadata(data.Metadata, xmlWriter);

            foreach (var item in data.Geometries)
            {
                WriteGeometry(item, xmlWriter, data.Styles);
            }

            //Close feed tag
            xmlWriter.WriteEndElement();

            //Close document
            xmlWriter.WriteEndDocument();
        }
Пример #16
0
        /// <summary>
        /// Writes a spatial data set object as a string.
        /// </summary>
        /// <param name="geometries">A spatial data set to write</param>
        /// <returns>A string of KML</returns>
        public override Task <string> WriteAsync(SpatialDataSet data)
        {
            return(Task.Run <string>(() =>
            {
                var sb = new StringBuilder();
                using (var xWriter = XmlWriter.Create(sb, xmlWriterSettings))
                {
                    Write(data, xWriter);
                }

                return sb.ToString();
            }));
        }
Пример #17
0
 /// <summary>
 /// Writes the first geometry in a spatial data set as a Well Known Binary to a stream.
 /// </summary>
 /// <param name="geometry">A spatial data set.</param>
 /// <param name="stream">Stream to write to.</param>
 public override Task WriteAsync(SpatialDataSet data, Stream stream)
 {
     return(Task.Run(() =>
     {
         if (data != null && data.Geometries != null && data.Geometries.Count > 0)
         {
             using (var writer = new BinaryWriter(stream))
             {
                 //Write the Geometry
                 WriteGeometry(data.Geometries[0], writer);
             }
         }
     }));
 }
Пример #18
0
        /// <summary>
        /// Takes a dbf file name and a Shapefile and adds the dbf row to each ShapefileItem's attributes.
        /// </summary>
        /// <param name="dbfReader">The binary reader of the dbf file to be read</param>
        /// <param name="shapeFile">A Shapefile object that contains a list of ShapefileItem objects to get the attributes for</param>
        /// <param name="colRules">List of column indices to skip. Settign to null causes all columns to be read</param>
        public static Task <bool> MergeDBFData(BinaryReader dbfReader, SpatialDataSet dataSet, bool[] colRules)
        {
            return(Task.Run <bool>(() =>
            {
                //Read the header
                var attributesHeader = DBaseFileReader.ReadHeader(dbfReader);

                int numItems = dataSet.Geometries.Count;

                //Verify that the DBF file has the same number of rows as there are ShapefileItem's
                if (numItems != attributesHeader.NumRows)
                {
                    throw new Exception("Inconsistant number of records between dbf and List of ShapefileItem's.");
                }
                else
                {
                    int numValidRulesCols = 0;

                    if (colRules != null)
                    {
                        foreach (bool rule in colRules)
                        {
                            if (rule)
                            {
                                numValidRulesCols++;
                            }
                        }
                    }
                    else
                    {
                        numValidRulesCols = attributesHeader.NumColumns;
                    }

                    //Loop through each item and read the attributes
                    for (int i = 0; i < numItems; i++)
                    {
                        var r = DBaseFileReader.ReadRow(attributesHeader, dbfReader, colRules, numValidRulesCols);
                        if (r != null)
                        {
                            foreach (KeyValuePair <string, object> row in r)
                            {
                                dataSet.Geometries[i].Metadata.Properties.Add(row.Key, row.Value);
                            }
                        }
                    }
                }
                return true;
            }));
        }
Пример #19
0
 async Task LoadMap(SpatialDataSet data)
 {
     if (data != null)
     {
         if (!string.IsNullOrEmpty(data.Error))
         {
             await new MessageDialog(data.Error).ShowAsync();
         }
         else
         {
             MyMap.ClearMap();
             MyMap.LoadSpatialData(data, GeometryTapped);
             CenterView(data);
         }
     }
 }
Пример #20
0
 public override Task WriteAsync(SpatialDataSet data, Stream stream)
 {
     return(Task.Run(() =>
     {
         using (var writer = new StreamWriter(stream))
         {
             if (data.Geometries != null)
             {
                 foreach (var g in data.Geometries)
                 {
                     writer.WriteLine(Write(g));
                 }
             }
         }
     }));
 }
Пример #21
0
 public override Task WriteAsync(SpatialDataSet data, Stream stream)
 {
     return(Task.Run(() =>
     {
         if (_dataSourceType == BingDataSourceType.XML)
         {
             using (var writer = XmlWriter.Create(stream, xmlWriterSettings))
             {
                 Write(data, writer);
             }
         }
         else
         {
             Write(data, stream);
         }
     }));
 }
Пример #22
0
        /// <summary>
        /// Takes a dbf file name and a Shapefile and adds the dbf row to each ShapefileItem's attributes.
        /// </summary>
        /// <param name="dbfFileStream">The file stream of the dbf file to be read</param>
        /// <param name="shapeFile">A Shapefile object that contains a list of ShapefileItem objects to get the attributes for</param>
        /// <param name="colRules">List of column indices to skip. Settign to null causes all columns to be read</param>
        public static Task <bool> MergeDBFData(Stream dbfFileStream, SpatialDataSet dataSet, bool[] colRules)
        {
            return(Task.Run <bool>(async() =>
            {
                try
                {
                    //Create binary reader out of file stream
                    using (BinaryReader reader = new BinaryReader(dbfFileStream))
                    {
                        await MergeDBFData(reader, dataSet, colRules);
                    }

                    return true;
                }
                catch { }

                return false;
            }));
        }
Пример #23
0
        public TileGeneratingDialog(SpatialDataSet dataSet, ShapeStyle defaultStyle)
        {
            InitializeComponent();

            _dataSet      = dataSet;
            _defaultStyle = defaultStyle;

            if (_dataSet == null)
            {
                this.Close();
            }

            this.Loaded += (s, e) => {
                var hwnd = new WindowInteropHelper(this).Handle;
                SetWindowLong(hwnd, GWL_STYLE, GetWindowLong(hwnd, GWL_STYLE) & ~WS_SYSMENU);

                Application curApp     = Application.Current;
                Window      mainWindow = curApp.MainWindow;
                this.Left = mainWindow.Left + (mainWindow.Width - this.ActualWidth) / 2;
                this.Top  = mainWindow.Top + (mainWindow.Height - this.ActualHeight) / 2;

                //Fill comboboxes.
                var zoomLevels = new int[20];
                for (int i = 0; i < 20; i++)
                {
                    zoomLevels[i] = i + 1;
                }

                MinZoomCbx.ItemsSource   = zoomLevels;
                MinZoomCbx.SelectedIndex = 0;

                MaxZoomCbx.ItemsSource   = zoomLevels;
                MaxZoomCbx.SelectedIndex = 4;

                TileMsgTbx.Text           = string.Format(CultureInfo.InvariantCulture, "Approximately {0:N0} tiles.", CalculateTileCount(_dataSet.BoundingBox.ToBMGeometry(), (int)MinZoomCbx.SelectedValue, (int)MaxZoomCbx.SelectedValue));
                ProgressTbx.Text          = "";
                TileProgressBar.Value     = 0;
                ProcessTilesBtn.IsEnabled = true;
                CancelBtn.IsEnabled       = true;
            };
        }
Пример #24
0
        public static void LoadGeometries(SpatialDataSet data, IList <DependencyObject> pinLayer, IList <MapElement> shapeLayer, ShapeStyle defaultStyle, TappedEventHandler tapEvent)
#endif
        {
            if (data != null && data.Geometries != null && data.Geometries.Count > 0)
            {
                ShapeStyle style;

                foreach (var g in data.Geometries)
                {
                    style = defaultStyle;

                    if (!string.IsNullOrEmpty(g.StyleKey) &&
                        data.Styles != null &&
                        data.Styles.ContainsKey(g.StyleKey))
                    {
                        style = data.Styles[g.StyleKey];
                    }

                    LoadGeometry(g, pinLayer, shapeLayer, style, tapEvent);
                }
            }
        }
Пример #25
0
        private void Write(SpatialDataSet data, XmlWriter xmlWriter)
        {
            //<?xml version="1.0" encoding="UTF-8"?>
            //<DataSourceNameData>
            //  <xs:schema id="DataSourceName" xmlns="" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
            //    <xs:element name="DataSourceName" msdata:IsDataSet="true" msdata:UseCurrentLocale="true">
            //      <xs:complexType>
            //        <xs:choice minOccurs="0" maxOccurs="unbounded">
            //          <xs:element name="EntityTypeName">
            //            <xs:complexType>
            //              <xs:sequence>
            //                <xs:element name="AddressLine" type="xs:string" minOccurs="0" />
            //                <xs:element name="Locality" type="xs:string" minOccurs="0" />
            //                <xs:element name="AdminDistrict" type="xs:string" minOccurs="0" />
            //                <xs:element name="CountryRegion" type="xs:string" minOccurs="0" />
            //                <xs:element name="PostalCode" type="xs:string" minOccurs="0" />
            //                <xs:element name="Name" type="xs:string" minOccurs="0" />
            //                <xs:element name="EntityID" type="xs:string" />
            //                <xs:element name="Longitude" type="xs:double" minOccurs="0" />
            //                <xs:element name="Latitude" type="xs:double" minOccurs="0" />
            //                <xs:element name="StoreLayout" type="xs:anyType" minOccurs="0" />
            //              </xs:sequence>
            //            </xs:complexType>
            //          </xs:element>
            //        </xs:choice>
            //      </xs:complexType>
            //      <xs:unique name="Constraint1" msdata:PrimaryKey="true">
            //        <xs:selector xpath=".//EntityTypeName" />
            //        <xs:field xpath="EntityID" />
            //      </xs:unique>
            //    </xs:element>
            //  </xs:schema>
            //  <EntityTypeName>
            //    <AddressLine>Løven</AddressLine>
            //    <Locality>Aalborg</Locality>
            //    <AdminDistrict>Nordjyllands Amt</AdminDistrict>
            //    <CountryRegion>Danmark</CountryRegion>
            //    <PostalCode>9200</PostalCode>
            //    <Name>Fourth Coffee Store #22067</Name>
            //    <EntityID>-22067</EntityID>
            //    <Longitude>9.87443416667</Longitude>
            //    <Latitude>57.00376611111</Latitude>
            //    <StoreLayout>POLYGON((9.86445 57.13876,9.89266 57.13876, 9.89266 56.94234,9.86445 56.94234,9.86445 57.13876))</StoreLayout>
            //  </EntityTypeName>
            //</DataSourceNameData>

            Dictionary <string, Type> columnInfo;
            bool   hasGeometry;
            string dataSourceName, entityTypeName, primaryKeyName, geometryColumnName;

            data = CleanDataSet(data, out columnInfo, out dataSourceName, out entityTypeName, out primaryKeyName, out geometryColumnName, out hasGeometry);

            //Open document
            xmlWriter.WriteStartDocument(true);

            //Write root tag -> Data Source Name.
            xmlWriter.WriteStartElement(dataSourceName + "Data");

            //Write schema info
            WriteXmlSchema(xmlWriter, columnInfo, dataSourceName, entityTypeName, primaryKeyName, geometryColumnName, hasGeometry);

            if (data != null)
            {
                foreach (var item in data.Geometries)
                {
                    WriteXmlGeometry(item, xmlWriter, columnInfo, dataSourceName, entityTypeName, primaryKeyName, geometryColumnName, hasGeometry);
                }
            }

            //Close document
            xmlWriter.WriteEndDocument();
        }
Пример #26
0
        private void Write(SpatialDataSet data, Stream outputStream)
        {
            char delimiter;

            switch (_dataSourceType)
            {
            case BingDataSourceType.PIPE:
                delimiter = '|';
                break;

            case BingDataSourceType.TAB:
                delimiter = '\t';
                break;

            case BingDataSourceType.CSV:
            default:
                delimiter = ',';
                break;
            }

            Dictionary <string, Type> columnInfo;
            bool   hasGeometry;
            string dataSourceName, entityTypeName, primaryKeyName, geometryColumnName;

            data = CleanDataSet(data, out columnInfo, out dataSourceName, out entityTypeName, out primaryKeyName, out geometryColumnName, out hasGeometry);

            var colNames = new List <string>(columnInfo.Keys);

            if (!columnInfo.ContainsKey(primaryKeyName))
            {
                columnInfo.Add(primaryKeyName, typeof(string));
                colNames.Insert(0, primaryKeyName);
            }

            if (!columnInfo.ContainsKey("Latitude"))
            {
                columnInfo.Add("Latitude", typeof(double));
                colNames.Add("Latitude");
            }

            if (!columnInfo.ContainsKey("Longitude"))
            {
                columnInfo.Add("Longitude", typeof(double));
                colNames.Add("Longitude");
            }

            if (hasGeometry && !columnInfo.ContainsKey(geometryColumnName))
            {
                columnInfo.Add(geometryColumnName, typeof(string));
                colNames.Add(geometryColumnName);
            }

            using (var writer = new DelimitedFileWriter(outputStream, columnInfo.Count, delimiter))
            {
                //Add Bing Schema Information
                writer.WriteLine(string.Format(_schemaText, entityTypeName));

                var headerCells = new List <string>();

                //Generate Header Information
                foreach (var colName in colNames)
                {
                    var name = colName + "(" + GetDelimitedPropertyType(columnInfo[colName]);

                    if (string.CompareOrdinal(colName, primaryKeyName) == 0)
                    {
                        name += ",primaryKey";
                    }

                    name += ")";

                    headerCells.Add(name);
                }

                //Write Header Information
                writer.WriteRow(headerCells, false);

                if (data != null)
                {
                    //Write the rows
                    foreach (var item in data.Geometries)
                    {
                        WriteGeometry(item, writer, colNames, primaryKeyName, geometryColumnName, hasGeometry);
                    }
                }
            }
        }
Пример #27
0
        private async Task <SpatialDataSet> ParseDataSource(XDocument doc)
        {
            var result = new SpatialDataSet();

            try
            {
                var    geoms          = new List <Geometry>();
                string primaryKeyName = string.Empty;
                var    columnInfo     = new Dictionary <string, Type>();

                var schema = doc.Root.FirstNode as XElement;

                if (schema != null)
                {
                    var idAttr = XmlUtilities.GetAttribute(schema, "id");
                    if (idAttr != null)
                    {
                        result.Metadata.Properties.Add(DataSourceNameKey, idAttr.Value);
                    }

                    var dsSchema = (schema.FirstNode as XElement);

                    var entitySchema   = ((dsSchema.FirstNode as XElement).FirstNode as XElement).FirstNode;
                    var entityNameAttr = XmlUtilities.GetAttribute(entitySchema as XElement, "name");

                    if (entityNameAttr != null)
                    {
                        result.Metadata.Properties.Add(EntityTypeNameKey, entityNameAttr.Value);
                    }

                    var sequenceSchema = ((entitySchema as XElement).FirstNode as XElement).FirstNode as XElement;
                    var sequenceElms   = sequenceSchema.Elements();

                    foreach (var e in sequenceElms)
                    {
                        var elm     = e as XElement;
                        var name    = XmlUtilities.GetAttribute(elm, "name");
                        var xmlType = XmlUtilities.GetAttribute(elm, "type");

                        if (name != null && xmlType != null)
                        {
                            columnInfo.Add(name.Value, GetXmlPropertyType(xmlType.Value));
                        }
                    }

                    var primaryKeySchema = (dsSchema.LastNode as XElement).LastNode;

                    var primaryKeyAttr = XmlUtilities.GetAttribute(primaryKeySchema as XElement, "xpath");
                    if (primaryKeyAttr != null)
                    {
                        primaryKeyName = primaryKeyAttr.Value;
                        result.Metadata.Properties.Add(PrimaryKeyNameKey, primaryKeyName);
                    }

                    if (columnInfo.ContainsValue(typeof(Geometry)))
                    {
                        foreach (var k in columnInfo.Keys)
                        {
                            if (columnInfo[k] == typeof(Geometry))
                            {
                                result.Metadata.Properties.Add(GeometryColumnNameKey, k);
                                break;
                            }
                        }
                    }

                    var n = schema.NextNode;
                    while (n != null)
                    {
                        var g = await ParseGeometry(n as XElement, columnInfo, primaryKeyName);

                        if (g != null)
                        {
                            geoms.Add(g);
                        }

                        n = n.NextNode;
                    }

                    if (geoms.Count > 0)
                    {
                        result.Geometries  = geoms;
                        result.BoundingBox = geoms.Envelope();
                    }
                }
            }
            catch (Exception ex)
            {
                result.Error = ex.Message;
            }

            return(result);
        }
Пример #28
0
        private async Task <SpatialDataSet> ParseDelimitedDataSource(TextReader textReader)
        {
            char delimiter;

            switch (_dataSourceType)
            {
            case BingDataSourceType.PIPE:
                delimiter = '|';
                break;

            case BingDataSourceType.TAB:
                delimiter = '\t';
                break;

            case BingDataSourceType.CSV:
            default:
                delimiter = ',';
                break;
            }

            var    result         = new SpatialDataSet();
            var    geoms          = new List <Geometry>();
            string primaryKeyName = string.Empty;
            var    columnInfo     = new Dictionary <string, Type>();
            var    colNames       = new List <string>();

            try
            {
                using (var reader = new DelimitedFileReader(textReader, delimiter))
                {
                    var row = reader.GetNextRow();

                    if (row != null && row.Count > 0)
                    {
                        //Parse Schema Version info.
                        if (row[0].StartsWith("Bing Spatial Data Services", StringComparison.OrdinalIgnoreCase))
                        {
                            string entityName = string.Empty;

                            if (row[0].Contains(","))
                            {
                                var r = row[0].Split(new char[] { ',' });
                                if (r.Length >= 3)
                                {
                                    entityName = r[2].Trim();
                                }
                            }

                            if (row.Count >= 3)
                            {
                                entityName = row[2].Trim();
                            }

                            if (IsValidName(entityName))
                            {
                                result.Metadata.Properties.Add(EntityTypeNameKey, entityName);
                            }

                            row = reader.GetNextRow();
                        }

                        //Parse header row
                        columnInfo = ParseColumnHeader(row, out colNames, out primaryKeyName);

                        if (!string.IsNullOrWhiteSpace(primaryKeyName))
                        {
                            result.Metadata.Properties.Add(PrimaryKeyNameKey, primaryKeyName);
                        }

                        if (columnInfo.ContainsValue(typeof(Geometry)))
                        {
                            foreach (var k in columnInfo.Keys)
                            {
                                if (columnInfo[k] == typeof(Geometry))
                                {
                                    result.Metadata.Properties.Add(GeometryColumnNameKey, k);
                                    break;
                                }
                            }
                        }

                        row = reader.GetNextRow();
                    }

                    while (row != null && row.Count > 0)
                    {
                        var g = await ParseGeometry(row, colNames, columnInfo, primaryKeyName);

                        if (g != null)
                        {
                            geoms.Add(g);
                        }

                        row = reader.GetNextRow();
                    }

                    if (geoms.Count > 0)
                    {
                        result.Geometries  = geoms;
                        result.BoundingBox = geoms.Envelope();
                    }
                }
            }
            catch (Exception ex)
            {
                result.Error = ex.Message;
            }

            return(result);
        }
Пример #29
0
        private SpatialDataSet CleanDataSet(SpatialDataSet data, out Dictionary <string, Type> columnInfo, out string dataSourceName, out string entityTypeName, out string primaryKeyName, out string geometryColumnName, out bool hasGeometry)
        {
            columnInfo         = new Dictionary <string, Type>();
            hasGeometry        = false;
            dataSourceName     = _dataSourceName;
            entityTypeName     = _entityTypeName;
            primaryKeyName     = _primaryKeyName;
            geometryColumnName = _geometryColumnName;

            if (data != null)
            {
                if (data.Metadata != null && data.Metadata.Properties != null)
                {
                    if (data.Metadata.Properties.ContainsKey(DataSourceNameKey))
                    {
                        var s = data.Metadata.Properties[DataSourceNameKey].ToString();

                        if (IsValidName(s))
                        {
                            dataSourceName = s;
                        }
                    }

                    if (data.Metadata.Properties.ContainsKey(EntityTypeNameKey))
                    {
                        var s = data.Metadata.Properties[EntityTypeNameKey].ToString();

                        if (IsValidName(s))
                        {
                            entityTypeName = s;
                        }
                    }

                    if (data.Metadata.Properties.ContainsKey(PrimaryKeyNameKey))
                    {
                        var s = data.Metadata.Properties[PrimaryKeyNameKey].ToString();

                        if (IsValidPropertyName(s))
                        {
                            primaryKeyName = s;
                        }
                    }

                    if (data.Metadata.Properties.ContainsKey(GeometryColumnNameKey))
                    {
                        var s = data.Metadata.Properties[GeometryColumnNameKey].ToString();

                        if (IsValidPropertyName(s))
                        {
                            geometryColumnName = s;
                        }
                    }
                }


                var      ids   = new List <string>();
                long     idIdx = 1000000;
                Geometry g;

                for (var i = 0; i < data.Geometries.Count; i++)
                {
                    g = data.Geometries[i];

                    if (!(g is Point))
                    {
                        hasGeometry = true;
                    }
                    else if (g.STNumPoints() > _maxGeomPoints)
                    {
                        //TODO: Reduce resolution of data so that it fits into limits
                    }

                    if (g.Metadata != null && g.Metadata.Properties != null)
                    {
                        //Check metadata
                        foreach (var key in g.Metadata.Properties.Keys)
                        {
                            if (!columnInfo.ContainsKey(key) && IsValidPropertyName(key) &&
                                string.Compare(key, "Latitude", StringComparison.OrdinalIgnoreCase) != 0 &&
                                string.Compare(key, "Longitude", StringComparison.OrdinalIgnoreCase) != 0)
                            {
                                columnInfo.Add(key, g.Metadata.Properties[key].GetType());
                            }
                        }

                        //Check ID
                        if (string.IsNullOrWhiteSpace(g.Metadata.ID) || ids.Contains(g.Metadata.ID))
                        {
                            if (g.Metadata.Properties.ContainsKey(primaryKeyName) &&
                                !string.IsNullOrWhiteSpace(g.Metadata.Properties[primaryKeyName].ToString()) &&
                                !ids.Contains(g.Metadata.Properties[primaryKeyName].ToString()))
                            {
                                g.Metadata.ID = g.Metadata.Properties[primaryKeyName].ToString();
                            }
                            else
                            {
                                data.Geometries[i].Metadata.ID = idIdx.ToString();
                                idIdx++;
                            }
                        }

                        ids.Add(data.Geometries[i].Metadata.ID);
                    }
                }
            }

            return(data);
        }
Пример #30
0
 /// <summary>
 /// DO NOT USE. This is not implemented.
 /// </summary>
 public override Task WriteAsync(SpatialDataSet data, Stream stream)
 {
     throw new NotImplementedException();
 }