Пример #1
1
        /// <summary>
        /// Creates a new KmzFile using the data specified in the KmlFile.
        /// </summary>
        /// <param name="kml">The Kml data to add to the archive.</param>
        /// <returns>
        /// A new KmzFile populated with the data specified in the KmlFile.
        /// </returns>
        /// <remarks>
        /// This overloaded version does not resolve any links in the Kml data
        /// and, therefore, will not add any local references to the archive.
        /// </remarks>
        /// <exception cref="ArgumentNullException">kml is null.</exception>
        public static KmzFile Create(KmlFile kml)
        {
            if (kml == null)
            {
                throw new ArgumentNullException("kml");
            }

            var instance = new KmzFile(new MemoryStream());
            instance._zip = new ZipFile();

            // Add the Kml data
            using (var stream = new MemoryStream())
            {
                kml.Save(stream);
                instance.AddFile(DefaultKmlFilename, stream.ToArray());
            }
            return instance;
        }
Пример #2
0
        public void ShouldFindAllTheLinkTypesInTheKmlFile()
        {
            // Verify that GetLinks finds all kinds of hrefs in a KML file.
            string[] expected =
            {
                "http://example.com/icon.jpg",
                "itemicon.png",
                "../more.kml",
                "go.jpeg",
                "so.jpeg",
                "po.jpeg",
                "#myschema",
                "model.dae",
                "style.kml#style"
            };

            using (var stream = SampleData.CreateStream("Engine.Data.Links.kml"))
                using (var reader = new StreamReader(stream))
                {
                    var resolver = new LinkResolver(KmlFile.Load(reader));

                    IEnumerable <string> links = resolver.Links.Select(u => u.OriginalString);

                    Assert.That(links, Is.EquivalentTo(expected));
                }
        }
Пример #3
0
        /// <summary>
        /// Run one route script with an IFR model aircraft
        /// </summary>
        /// <param name="route">A complete route script to run</param>
        /// <returns>True if OK</returns>
        private bool RunSimFromScript(CmdList route)
        {
            string routeName = route.Descriptor.Start_IcaoID + "_" + route.Descriptor.End_IcaoID;

            var virtAcft = new IFRvAcft(route); // use the Jet model
            var kmlFile  = new KmlFile( );
            var kmlLine  = new line {
                Name      = routeName,
                LineColor = LineStyle.LT_Blue
            };

            do
            {
                virtAcft.StepModel(m_stepLen_sec); // step the model at 2 sec until finished

                kmlLine.Add(new point {
                    Position    = new LatLon(virtAcft.LatLon),
                    Altitude_ft = virtAcft.Alt_ft,
                    Heading     = (int)virtAcft.TRK
                });
            } while (!virtAcft.Out);
            // setup Comm
            kmlFile.Lines.Add(kmlLine);
            kmlFile.WriteKML(routeName + ".kml");
            return(Valid);
        }
        /// <summary>
        /// Parses the raw KML Data file returned by the inReach service and produces live
        /// waypoint data.
        /// </summary>
        /// <param name="stream">stream to read kml from</param>
        /// <param name="mapShareIdentifier">MapShare identifier used for request</param>
        /// <returns>live waypoint data</returns>
        internal LiveWaypointData ParseRawKmlDataFile(Stream stream, string mapShareIdentifier)
        {
            var file = KmlFile.Load(stream);

            var placemark = file.Root.Flatten().First(x => x is Placemark) as Placemark;

            if (placemark == null)
            {
                throw new FormatException("Garmin inReach Raw KML Data contains no Placemark");
            }

            var point = placemark.Geometry as Point;

            var when = (placemark.Time as Timestamp).When;

            if (when.HasValue)
            {
                this.lastRequestByMapShareIdentifier[mapShareIdentifier] = new DateTimeOffset(when.Value);
            }

            return(new LiveWaypointData
            {
                ID = FormatLiveWaypointId(mapShareIdentifier),
                Name = "Garmin inReach " + placemark.Name,
                Latitude = point.Coordinate.Latitude,
                Longitude = point.Coordinate.Longitude,
                Altitude = (int)(point.Coordinate.Altitude ?? 0.0),
                TimeStamp = when.HasValue ? new DateTimeOffset(when.Value) : DateTimeOffset.Now,
                Description = FormatDescriptionFromPlacemark(placemark),
                DetailsLink = string.Format(MapSharePublicUrl, mapShareIdentifier),
            });
        }
Пример #5
0
        static void LoadFile()
        {
            FileStream fs;
            KmlFile    file = null;

            Console.WriteLine("Enter KML filepath:");
            try
            {
                fs   = File.OpenRead(Console.ReadLine());
                file = KmlFile.Load(fs);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.Write("Retry/Exit (r/x)? ");
                if (Console.ReadKey().KeyChar == 'r')
                {
                    Console.WriteLine();
                    LoadFile();
                    return;
                }
                else
                {
                    Environment.Exit(0);
                }
            }

            kmlFile = file;
        }
Пример #6
0
        public static string ExploreKml(string filename, KmlFile file)
        {
            List <string> lines = new List <string>()
            {
                $"{filename}:"
            };

            if (!(file.Root is Kml kml))
            {
                return("File root isn't a KML");
            }

            if (!(kml.Feature is Document doc))
            {
                return("Main feature isn't a Document");
            }

            if (!doc.Features.Any())
            {
                return("No features in Document");
            }

            foreach (Feature element in doc.Features)
            {
                lines.AddRange(DisplayElement(element, 0));
            }

            lines.Add("");
            return(string.Join("\r\n", lines));
        }
Пример #7
0
        public void TestAltMarkupData()
        {
            using (var stream = SampleData.CreateStream("Engine.Data.Entity Data.kml"))
            {
                KmlFile   file      = KmlFile.Load(stream);
                Placemark placemark = file.Root as Placemark;
                Assert.That(placemark, Is.Not.Null);

                EntityMapper mapper = new EntityMapper(file);
                mapper.ParseEntityFields(placemark);

                Assert.That(mapper.Entities.Count, Is.EqualTo(6));
                for (int i = 0; i < 4; ++i)
                {
                    Assert.That(mapper.Markup[i], Is.EqualTo(AltMarkup[i]));
                }

                // Assert that a second parse produces the same result (this
                // is different to the C++ version, which clears the Entities
                // but adds to the Markup - we reset both.
                mapper.ParseEntityFields(placemark);
                Assert.That(mapper.Entities.Count, Is.EqualTo(6));
                Assert.That(mapper.Markup.Count, Is.EqualTo(4));
            }
        }
Пример #8
0
        public void TestSave()
        {
            // Create the Kml data
            const string Xml    = "<Placemark xmlns='http://www.opengis.net/kml/2.2'><name>tmp kml</name></Placemark>";
            var          parser = new Parser();

            parser.ParseString(Xml, true);
            var kml = KmlFile.Create(parser.Root, false);

            using (var stream = new MemoryStream())
            {
                // Create and save the archive
                using (var file = KmzFile.Create(kml))
                {
                    file.Save(stream);
                }

                // Try to open the saved archive, rewinding the stream
                stream.Position = 0;
                using (var file = KmzFile.Open(stream))
                {
                    // Make sure it's the same as what we saved
                    parser.ParseString(file.ReadKml(), true);
                    SampleData.CompareElements(kml.Root, parser.Root);
                }
            }
        }
Пример #9
0
        public void TestDispose()
        {
            // Make sure we can't call any methods after the object has been disposed
            var file = KmzFile.Create(KmlFile.Create(new Kml(), false));

            file.Dispose();

            // Make sure we can call Dispose more than once
            Assert.That(() => file.Dispose(), Throws.Nothing);

            // Check all methods and properties throw.
            var flags = BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public;

            foreach (var method in typeof(KmzFile).GetMethods(flags))
            {
                // Dispose should be able to be called mutliple times without
                // an exception being thrown.
                if (method.Name != "Dispose")
                {
                    // Actual exception thrown will be TargetInvocationException
                    // so check the InnerException.
                    object[] arguments = new object[method.GetParameters().Length];
                    Assert.That(() => method.Invoke(file, arguments),
                                Throws.InnerException.TypeOf <ObjectDisposedException>());
                }
            }
            foreach (var property in typeof(KmzFile).GetProperties(flags))
            {
                // Mono doesn't throw a TargetInvocationException so just check that the property
                // throws, as it doesn't throw any other type of exception.
                Assert.That(() => property.GetValue(file, null),
                            Throws.Exception);
            }
        }
Пример #10
0
        public static void Run()
        {
            var point = new sd.Point
            {
                Coordinate = new sb.Vector(37.42052549, -122.0816695)
            };

            var placemark = new sd.Placemark
            {
                Name     = "Да круто",
                Geometry = point
            };

            var point1 = new sd.Point
            {
                Coordinate = new sb.Vector(37.419837, -122.078902)
            };

            var placemark1 = new sd.Placemark
            {
                Name     = "Да круто",
                Geometry = point1
            };

            var document = new sd.Document
            {
                Description = new sd.Description {
                    Text = "Документ"
                }
            };

            var kml = new sd.Kml
            {
                Feature = document
            };

            var folder = new sd.Folder
            {
                Description = new sd.Description {
                    Text = "Светофоры"
                },
                Name = "СО"
            };

            folder.AddFeature(placemark);
            document.AddFeature(folder);
            document.AddFeature(placemark1);

            //var serializer = new sb.Serializer();

            //using FileStream fileStream = new FileStream("kmlTest.kml", FileMode.OpenOrCreate);
            //serializer.Serialize(kml, fileStream);
            var kmlFile = KmlFile.Create(kml, true);

            //using KmzFile kmz = SaveKmlAndLinkedContentIntoAKmzArchive(kmlFile, OutputPath);
            //using Stream output = File.Create(OutputPath);
            //kmz.Save(output);
            //Console.WriteLine("Saved to '{0}'.", OutputPath);
            //Console.ReadKey();
        }
Пример #11
0
        /// <summary>
        /// Basic output of the instances Kml to a Kmz as specified in configuration.
        /// </summary>
        public void Save(string band = "")
        {
            string FileName;

            if (String.IsNullOrWhiteSpace(settings.FileName))
            {
                if (band == "")
                {
                    FileName = $"{DateTime.Now.ToString("yyyy-MM-dd")} - Subscriber Map.kmz";
                }
                else
                {
                    FileName = $"{DateTime.Now.ToString("yyyy-MM-dd")} - Subscriber Map ({band}).kmz";
                }
            }
            else
            {
                FileName = settings.FileName;
            }

            KmlFile kmlFile = KmlFile.Create(OutputKml, true);

            using (FileStream fs = new FileStream(FileName, FileMode.Create))
            {
                using (KmzFile kmz = KmzFile.Create(kmlFile))
                {
                    kmz.Save(fs);
                }
            }
        }
Пример #12
0
 private static KmlFile LoadKml(string path)
 {
     using (Stream file = File.OpenRead(path))
     {
         return(KmlFile.Load(file));
     }
 }
Пример #13
0
        /// <summary>
        /// Method to parse the KmlFile
        /// </summary>
        /// <param name="kmlFile">The file to parse</param>
        private void ParseKml(KmlFile kmlFile)
        {
            var kml = kmlFile.Root as Kml;

            if (kml == null)
            {
                throw new Exception("Kml file is null! Please check that the file conforms to http://www.opengis.net/kml/2.2 standards");
            }

            var doc = kml.Feature as Document;

            if (doc == null)
            {
                throw new Exception("Kml file does not have a document node! please check that the file conforms to http://www.opengis.net/kml/2.2 standards");
            }

            _geometryFactory = GeoAPI.GeometryServiceProvider.Instance.CreateGeometryFactory(4326);
            ConnectionID     = doc.Name;
            if (doc.Description != null && !string.IsNullOrEmpty(doc.Description.Text))
            {
                ConnectionID += " (" + doc.Description.Text + ")";
            }

            ExtractStyles(kml);
            ExtractStyleMaps(kml);
            ExtractGeometries(kml);
        }
        public List <PostImport.ExcelPost> LesInn(byte[] content)
        {
            var poster = new List <PostImport.ExcelPost>();

            var kml = KmlFile.Load(new MemoryStream(content));

            var root     = (SharpKml.Dom.Kml)kml.Root;
            var document = (Document)root.Feature;

            foreach (var folder in document.Features.OfType <Folder>())
            {
                foreach (var placemark in folder.Features.OfType <Placemark>())
                {
                    var name        = placemark.Name;
                    var description = placemark.Description;
                    var point       = placemark.Geometry as Point;
                    var coordinates = point?.Coordinate ?? new Vector();
                    var image       = placemark.ExtendedData?.Data?.FirstOrDefault()?.Value;
                    var post        = KonverterTilExcelPost(name, description, coordinates, image, document.Name);
                    poster.Add(post);
                }
            }

            return(poster);
        }
Пример #15
0
        public static KmlFile JoinFoldersIntoKml(String inputPath)
        {
            DirectoryInfo dir = new DirectoryInfo(inputPath);

            if (!dir.Exists)
            {
                throw new DirectoryNotFoundException();
            }

            FileInfo kmlf = dir.EnumerateFiles().ToList().FirstOrDefault(f => ".kml".Equals(f.Extension, StringComparison.OrdinalIgnoreCase));

            if (kmlf == null)
            {
                throw new Exception();
            }

            KmlFile rootKmlFile = FileHelper.LoadKmlKmzFile(kmlf.FullName);

            if (!(rootKmlFile.Root is Document))
            {
                throw new Exception();
            }
            Document rootDoc = (Document)(rootKmlFile.Root.Clone());

            dir.EnumerateDirectories().ToList().ForEach(f => { processFolder(rootDoc, f); });
            KmlFile kmlOut = KmlFile.Create(rootDoc, false);

            return(kmlOut);
        }
Пример #16
0
        static void processFolder(Container parentContainer, DirectoryInfo directory)
        {
            FileInfo kmlf = directory.EnumerateFiles().ToList().FirstOrDefault(f => ".kml".Equals(f.Extension, StringComparison.OrdinalIgnoreCase));

            if (kmlf == null)
            {
                throw new Exception();
            }

            KmlFile rootKmlFile = FileHelper.LoadKmlKmzFile(kmlf.FullName);

            if (!(rootKmlFile.Root is Document))
            {
                throw new Exception();
            }
            Document doc    = (Document)rootKmlFile.Root;
            Folder   folder = (Folder)parentContainer.Features.FirstOrDefault(c => c is Folder && doc.Name.Equals(c.Name, StringComparison.OrdinalIgnoreCase));

            if (folder == null)
            {
                folder = new Folder();
                parentContainer.AddFeature(folder);
            }
            folder.Name = doc.Name;
            if (doc.Description != null)
            {
                folder.Description = doc.Description;
            }
            List <DirectoryInfo> directories = directory.EnumerateDirectories().ToList();

            doc.Features.ToList().ForEach(feature => folder.AddFeature(feature.Clone()));
            directory.EnumerateDirectories().ToList().ForEach(f => { processFolder(folder, f); });
        }
Пример #17
0
        static void Main(string[] args)
        {
            String  inFile  = @"C:\tmp\Test\Ferrocarril Belgrano.kml";
            String  outFile = @"C:\tmp\Test\out.kml";
            KmlFile kmlFile = null;

            using (Stream fileStream = File.OpenRead(inFile))
            {
                kmlFile = KmlFile.Load(fileStream);
            }
            Kml      kml = kmlFile.Root as Kml;
            Document d   = kml.Feature as Document;
            Folder   f   = (Folder)d.Features.FirstOrDefault();
            Folder   f2  = (Folder)f.Features.FirstOrDefault();

            Document doc = new Document();

            doc.Name = "MyTestKml";
            d.Schemas.ToList().ForEach(s => doc.AddSchema(s.Clone()));
            doc.AddFeature(f2.Clone());

            // This allows us to save and Element easily.
            KmlFile kmlOut = KmlFile.Create(doc, false);

            using (var stream = System.IO.File.OpenWrite(outFile))
            {
                kmlOut.Save(stream);
            }
        }
Пример #18
0
        public void TestSingleSimpleDelete()
        {
            const string DeleteXml =
                "<Update>" +
                "<targetHref/>" +
                "<Delete>" +
                "<Placemark targetId=\"p\"/>" +
                "</Delete>" +
                "</Update>";

            var parser = new Parser();

            parser.ParseString("<Folder><Placemark id=\"p\"/></Folder>", false);
            var file = KmlFile.Create(parser.Root, false);

            var target = parser.Root as Folder;

            Assert.That(target, Is.Not.Null);
            Assert.That(target.Features.Count(), Is.EqualTo(1));

            parser.ParseString(DeleteXml, false);
            var update = parser.Root as Update;

            Assert.That(update, Is.Not.Null);

            update.Process(file);
            Assert.That(target.Features.Count(), Is.EqualTo(0));
            Assert.That(file.FindObject("p"), Is.Null); // Make sure it was deleted from the KmlFile too.
        }
Пример #19
0
        public void TestSingleSimpleChange()
        {
            const string ChangeXml =
                "<Update>" +
                "<targetHref/>" +
                "<Change>" +
                "<Placemark targetId=\"p\">" +
                "<name>NEW NAME</name>" +
                "</Placemark>" +
                "</Change>" +
                "</Update>";

            var parser = new Parser();

            parser.ParseString("<Placemark id=\"p\"><name>hi</name></Placemark>", false);
            var file = KmlFile.Create(parser.Root, false);

            var target = file.FindObject("p") as Placemark;

            Assert.That(target, Is.Not.Null);
            Assert.That(target.Name, Is.EqualTo("hi"));

            parser.ParseString(ChangeXml, false);
            var update = parser.Root as Update;

            Assert.That(update, Is.Not.Null); // Verify the test XML

            update.Process(file);
            Assert.That(target.Name, Is.EqualTo("NEW NAME"));
            Assert.That(target.TargetId, Is.Null);
        }
Пример #20
0
        private static void ProcessDelete(DeleteCollection delete, KmlFile file)
        {
            foreach (var source in delete)
            {
                if (source.TargetId != null)
                {
                    Feature feature = file.FindObject(source.TargetId) as Feature;
                    if (feature != null)
                    {
                        // Remove the Feature from the parent, which is either
                        // a Container or Kml
                        Container container = feature.Parent as Container;
                        if (container != null)
                        {
                            container.RemoveFeature(source.TargetId);
                        }
                        else
                        {
                            Kml kml = feature.Parent as Kml;
                            if (kml != null)
                            {
                                kml.Feature = null;
                            }
                        }

                        // Also remove it from the file
                        file.RemoveFeature(feature);
                    }
                }
            }
        }
Пример #21
0
        public static void Run()
        {
            KmlFile file = Program.OpenFile("Enter a file to show the placemarks of:");

            if (file == null)
            {
                return;
            }

            // It's good practice for the root element of the file to be a Kml element
            if (file.Root is Kml kml)
            {
                var placemarks = new List <Placemark>();
                ExtractPlacemarks(kml.Feature, placemarks);

                // Sort using their names
                placemarks.Sort((a, b) => string.Compare(a.Name, b.Name));

                // Display the results
                foreach (Placemark placemark in placemarks)
                {
                    Console.WriteLine(placemark.Name);
                }
            }
        }
Пример #22
0
        /// <summary>
        /// Returns the KML file at the specified <paramref name="path"/>.
        ///
        /// If the KMZ file's <see cref="KmlDocument.NetworkLink"/> property indicates another KML or KMZ file, that file will be retrieved and returned instead.
        /// </summary>
        /// <param name="path">The path to the file on disk.</param>
        /// <returns>An instance of <see cref="KmlFile"/>.</returns>
        public static KmlFile LoadKml(string path)
        {
            KmlFile kml;

            // Get the KML file from the KMZ file at "path"
            using (KmzFile kmz = OpenRead(path)) {
                kml = kmz.Kml;
            }

            // If the KML file doesn't have a network link, we'll just return it right away
            if (kml.Document.HasNetworkLink == false)
            {
                return(kml);
            }

            // Get the KML or KMZ file specified by the network link
            HttpResponse response = (HttpResponse)HttpUtils.Requests.Get(kml.Document.NetworkLink.Link.Href);

            // Parse the response body
            switch (response.ContentType)
            {
            case KmlConstants.KmlMimeType:
                return(KmlFile.Parse(response.Body));

            case KmlConstants.KmzMimeType:
                using (KmzFile kmz = Parse(response.BinaryBody)) return(kmz.Kml);

            default:
                throw new KmzException("Unknown mime type " + response.ContentType);
            }
        }
Пример #23
0
        /// <summary>
        /// Creates a new KML data file from stream
        /// </summary>
        /// <param name="stream">stream to read from</param>
        /// <param name="isKml">indicates if stream contains a kml or a kmz file</param>
        public KmlDataFile(Stream stream, bool isKml)
        {
            if (isKml)
            {
                using (var reader = new StreamReader(stream))
                {
                    this.kml = KmlFile.Load(reader);

                    if (this.kml.Root == null &&
                        stream.CanSeek)
                    {
                        stream.Seek(0, SeekOrigin.Begin);

                        this.kml = this.ReadLegacyKmlStream(stream, isKml);
                    }
                }
            }
            else
            {
                var kmz = KmzFile.Open(stream);
                this.kml = kmz.GetDefaultKmlFile();
            }

            if (this.kml != null)
            {
                this.ScanKml();
            }
        }
Пример #24
0
        private void OpenMenu_Click(object sender, RoutedEventArgs e)
        {
            // Create an instance of the open file dialog box.
            OpenFileDialog openFileDialog = new OpenFileDialog();

            // Set filter options and filter index.
            openFileDialog.Filter      = "Google Earth (.kml .kmz)|*.kml;*.kmz";
            openFileDialog.FilterIndex = 1;

            openFileDialog.Multiselect = true;

            // Call the ShowDialog method to show the dialog box.
            bool?userClickedOK = openFileDialog.ShowDialog();

            // Process input if the user clicked OK.
            if (userClickedOK == true)
            {
                KmlFile kmlFile = KmlFileHelper.OpenFile(openFileDialog.FileName);
                FerromapasKmlHelper.AddFerromapasSchemaIfNotExists(kmlFile);
                String fileName = ((kmlFile.Root as Kml).Feature as Document).Name;
                this.Title          = fileName;
                this.kmlFile        = kmlFile;
                kmlTreeView.kmlFile = kmlFile;
                this.fileName       = openFileDialog.FileName;
            }
        }
Пример #25
0
        public static KmlFile OpenFile(string prompt)
        {
            string filename = GetInputFile(prompt, "Data/20191114.kml");

            KmlFile file;

            try
            {
                using (FileStream stream = File.Open(filename, FileMode.Open))
                {
                    file = KmlFile.Load(stream);
                }
            }
            catch (Exception ex)
            {
                DisplayError(ex.GetType() + "\n" + ex.Message);
                return(null);
            }

            if (file.Root == null)
            {
                DisplayError("Unable to find any recognized Kml in the specified file.");
                return(null);
            }
            return(file);
        }
Пример #26
0
        public void TestManyDeletes()
        {
            const int NumberOfFolders = 100;

            var folder = new Folder();

            for (int i = 0; i < NumberOfFolders; ++i)
            {
                folder.AddFeature(CreateFeature(i, true)); // Add the features with their Id set
            }
            Assert.That(folder.Features.Count(), Is.EqualTo(NumberOfFolders));

            var file   = KmlFile.Create(folder, false);
            var update = new Update();

            for (int i = 0; i < NumberOfFolders; ++i)
            {
                var delete = new DeleteCollection
                {
                    CreateFeature(i, false) // This time set the TargetId
                };
                update.AddUpdate(delete);
            }
            update.Process(file);
            Assert.That(folder.Features.Count(), Is.EqualTo(0));
        }
Пример #27
0
        /// Read file in KMZ and KML format
        private void ReadGISFile()
        {
            string pathToimage = null;

            using (FileStream reader = new FileStream(path, FileMode.Open))
                using (KmzFile kmzFile = KmzFile.Open(reader))
                {
                    KmlFile kmlFile = kmzFile.GetDefaultKmlFile();
                    var     image   = kmlFile.Root.Flatten().OfType <GroundOverlay>().FirstOrDefault();
                    if (image != null)
                    {
                        pathToimage = image.Icon.Href.ToString();
                    }
                    var latLonBox = kmlFile.Root.Flatten().OfType <LatLonBox>().FirstOrDefault();
                    if (latLonBox != null)
                    {
                        var coorners = GetMapCorners(latLonBox);
                        map = new Map()
                        {
                            MapCorners = coorners,
                            Rotation   = latLonBox.Rotation,
                            Name       = kmlFile.Root.Flatten().OfType <Folder>().FirstOrDefault().Name
                        };
                    }
                }

            ReadArchiveAndExport(pathToimage);
        }
Пример #28
0
        /// <summary>
        /// Provides in-place (destructive) processing of the <see cref="Update"/>.
        /// </summary>
        /// <param name="update">The update instance.</param>
        /// <param name="file">
        /// A KmlFile containing the <c>Update</c> and the update targets.
        /// </param>
        /// <exception cref="ArgumentNullException">file is null.</exception>
        public static void Process(this Update update, KmlFile file)
        {
            if (file == null)
            {
                throw new ArgumentNullException("file");
            }

            foreach (var child in update.Updates)
            {
                ChangeCollection change = child as ChangeCollection;
                if (change != null)
                {
                    ProcessChange(change, file);
                    continue;
                }

                CreateCollection create = child as CreateCollection;
                if (create != null)
                {
                    ProcessCreate(create, file);
                    continue;
                }

                DeleteCollection delete = child as DeleteCollection;
                if (delete != null)
                {
                    ProcessDelete(delete, file);
                }
            }
        }
Пример #29
0
        private static KmlFile CreateFile(string kml, bool duplicates)
        {
            var parser = new Parser();

            parser.ParseString(kml, false);
            return(KmlFile.Create(parser.Root, duplicates));
        }
Пример #30
0
        private static KmzFile SaveKmlAndLinkedContentIntoAKmzArchive(KmlFile kml, string path)
        {
            // All the links in the KML will be relative to the KML file, so
            // find it's directory so we can add them later
            string basePath = Path.GetDirectoryName(path);

            // Create the archive with the KML data
            KmzFile kmz = KmzFile.Create(kml);

            // Now find all the linked content in the KML so we can add the
            // files to the KMZ archive
            var links = new LinkResolver(kml);

            // Next gather the local references and add them.
            foreach (string relativePath in links.GetRelativePaths())
            {
                // Make sure it doesn't point to a directory below the base path
                if (relativePath.StartsWith("..", StringComparison.Ordinal))
                {
                    continue;
                }

                // Add it to the archive
                string fullPath = Path.Combine(basePath, relativePath);
                using (Stream file = File.OpenRead(fullPath))
                {
                    kmz.AddFile(relativePath, file);
                }
            }

            return(kmz);
        }
Пример #31
0
        public static void Run()
        {
            KmlFile file = Program.OpenFile("Enter a file to show the styles of:");

            if (file == null)
            {
                return;
            }

            Console.WriteLine("Style names:");
            // We're going to extend the first style later
            StyleSelector firstStyle = null;

            foreach (StyleSelector style in file.Styles.OrderBy(s => s.Id))
            {
                if (firstStyle == null)
                {
                    firstStyle = style;
                }
                Console.WriteLine(style.Id);
            }

            // If there was a style display it's Xml
            if (firstStyle != null)
            {
                Console.WriteLine("\nExpanding '{0}':", firstStyle.Id);
                var serializer = new Serializer();
                serializer.Serialize(firstStyle);
                Console.WriteLine(serializer.Xml);
            }
        }
Пример #32
0
        public void TestSave()
        {
            // Create the Kml data
            const string Xml    = "<Placemark xmlns='http://www.opengis.net/kml/2.2'><name>tmp kml</name></Placemark>";
            var          parser = new Parser();

            parser.ParseString(Xml, true);
            var kml = KmlFile.Create(parser.Root, false);

            // This will be where we temporary save the archive to
            string tempFile = Path.GetTempFileName();

            try
            {
                // Create and save the archive
                using (var file = KmzFile.Create(kml))
                {
                    file.Save(tempFile);
                }

                // Try to open the saved archive
                using (var file = KmzFile.Open(tempFile))
                {
                    // Make sure it's the same as what we saved
                    parser.ParseString(file.ReadKml(), true);
                    SampleData.CompareElements(kml.Root, parser.Root);
                }
            }
            finally
            {
                File.Delete(tempFile);
            }
        }
Пример #33
0
        public static void Run()
        {
            const string OutputPath = "output.kmz";
            string       input      = Program.GetInputFile("Enter a file to convert to Kmz:", "Data/doc.kml");

            try
            {
                KmlFile kml = LoadKml(input);

                using (KmzFile kmz = SaveKmlAndLinkedContentIntoAKmzArchive(kml, input))
                    using (Stream output = File.Create(OutputPath))
                    {
                        kmz.Save(output);
                        Console.WriteLine("Saved to '{0}'.", OutputPath);
                    }

                // Now open the file we saved and list the contents
                using (Stream file = File.OpenRead(OutputPath))
                    using (KmzFile kmz = KmzFile.Open(file))
                    {
                        Console.WriteLine("Contents:");
                        foreach (string name in kmz.Files)
                        {
                            Console.WriteLine(name);
                        }
                    }
            }
            catch (Exception ex)
            {
                Program.DisplayError(ex.GetType() + "\n" + ex.Message);
            }
        }
        /// <summary>
        /// Initializes a new instance of the EntityMapper class.
        /// </summary>
        /// <param name="file">The kml information to parse.</param>
        /// <exception cref="ArgumentNullException">file is null.</exception>
        public EntityMapper(KmlFile file)
        {
            if (file == null)
            {
                throw new ArgumentNullException("file");
            }

            _file = file;
        }
Пример #35
0
        public static string getBusDescription(KmlFile kml)
        {
            string name = "";

            foreach (var item in kml.Root.Flatten().OfType<Document>())
            {
                name = item.Name;
            }

            return name;
        }
Пример #36
0
 private static void ProcessChange(ChangeCollection change, KmlFile file)
 {
     foreach (var source in change)
     {
         if (source.TargetId != null)
         {
             KmlObject target = file.FindObject(source.TargetId);
             if (target != null)
             {
                 target.Merge(source);
                 target.TargetId = null; // Merge copied the TargetId from the source, but target shouldn't have it set
             }
         }
     }
 }
Пример #37
0
 private static void ProcessCreate(CreateCollection create, KmlFile file)
 {
     foreach (var source in create)
     {
         if (source.TargetId != null)
         {
             Container target = file.FindObject(source.TargetId) as Container;
             if (target != null) // Make sure it was found and that the target was a Container
             {
                 foreach (var feature in source.Features)
                 {
                     var clone = feature.Clone(); // We never give the original source.
                     target.AddFeature(clone);
                     file.AddFeature(clone);
                 }
             }
         }
     }
 }
Пример #38
0
        /* Código referente ao cadastro dos Ônibus juntamente com suas Rotas.
         É feito um join da rota do ônibus com as estações em que ele passa. Portanto, DEVE ser feito o
            cadastro das estações de ônibus ANTES de adicionar a rota.
         É realizado um insert nas tabelas BUSES, ROUTES e STATION_BUSES */
        private bool addBusRoutes(KmlFile kml)
        {
            BUS bus = new BUS();
            ROUTE route = new ROUTE();
            DBRoute dbRoute = new DBRoute(context);
            DBStation dbStation = new DBStation(context);

            route.BUS = bus;

            StringBuilder sb = new StringBuilder("LINESTRING (");
            bus.Bus_Description = Methods.getBusDescription(kml);
            bool hasStation = false;

            foreach (var folder in kml.Root.Flatten().OfType<Folder>())
            {
                if (folder.Flatten().OfType<SharpKml.Dom.LineString>().Any())
                {
                    DBStation_Bus dbStationBus = new DBStation_Bus(context);

                    foreach (var placemark in folder.Flatten().OfType<SharpKml.Dom.Placemark>())
                    {
                        parseLineString(placemark, sb); // grava a rota do onibus
                        hasStation = parsePoint(placemark, dbStationBus, dbStation, bus, route, hasStation); // grava as estacoes que o onibus passa
                    }
                }
            }

            if (!hasStation)
            {
                string message = "The stations this bus pass by are not in the database. Please insert the stations first, then the bus route";
                Methods.DisplayMessage(lblMessage, message, Color.Red);
                throw new Exception(message);
            }

            route.Route_Coordinates = DbGeography.LineFromText(sb.Replace(',', ')', sb.Length - 1, 1).ToString(), 4326);

            dbRoute.Add(route);
            return true;
        }
Пример #39
0
           private async void ConvertPolyLinesToKml(KmlFile passedInKmlFile)
        {
            KmlFile kmlF = passedInKmlFile;
            string bobby = "Bobby";
           
            
            byte[] byteArray = new byte[1000];

            using (MemoryStream sourceStream = File.Open(bobby, FileMode.OpenOrCreate))
            {
                kmlF.Save((Stream)sourceStream);
            }

            //var file = FileIO.
            //IRandomAccessStream stream = await newFile.OpenAsync(FileAccessMode.ReadWrite);

            //var buffer = new Windows.Storage.Streams.Buffer(1024 * 1024 * 10);
            //await FileIO.WriteBufferAsync(newFile, buffer);



            

        }
Пример #40
0
 /// <summary>
 /// Creates an instance of this class using the provided KmlFile
 /// </summary>
 /// <param name="kmlFile">The KmlFile</param>
 public KmlProvider(KmlFile kmlFile)
 {
     ParseKml(kmlFile);
 }
Пример #41
0
        // Código referente ao cadastro dos Pontos de Referência OU das Estações de Ônibus
        // É realizado um insert nas tabelas STATIONS OU LANDMARKs e LANDMARK_KNOWN_AS
        private bool parseFolder(KmlFile kml, bool done, StreamWriter writetext)
        {
            foreach (var folder in kml.Root.Flatten().OfType<Folder>())
            {
                IEnumerable<Placemark> enumerablePlacemark = null;

                if (folder.Flatten().OfType<Placemark>().Any())
                {
                    if (folder.Flatten().OfType<LineString>().Any())
                    {
                        enumerablePlacemark = folder.Flatten().OfType<Placemark>().Take(1);
                    }
                    else
                    {
                        enumerablePlacemark = folder.Flatten().OfType<Placemark>();
                    }
                }

                done = parsePlacemark(enumerablePlacemark, done, writetext, kml);
            }
            return done;
        }
 public void SetKML(KmlFile kmlFile)
 {
     _kmlFile = kmlFile;
 }
Пример #43
0
 private bool parsePlacemark(IEnumerable<Placemark> enumerablePlacemark, bool done, StreamWriter writetext, KmlFile kml = null)
 {
     foreach (var placemark in enumerablePlacemark)
     {
         done = parsePoint(placemark, done, writetext);
         if (placemark.Flatten().OfType<SharpKml.Dom.LineString>().Any())
         {
             BUS bus = new BUS();
             bus.Bus_Description = Methods.getBusDescription(kml);
         }
     }
     return done;
 }
Пример #44
0
        private static void RunTestCase(KmlFile file, string id, BoundingBox box)
        {
            Feature feature = file.FindObject(id) as Feature;
            Assert.That(feature, Is.Not.Null); // Verify the test data

            var bounds = feature.CalculateBounds();
            Assert.That(bounds, Is.Not.Null);
            Assert.That(bounds.East, Is.EqualTo(box.East));
            Assert.That(bounds.North, Is.EqualTo(box.North));
            Assert.That(bounds.South, Is.EqualTo(box.South));
            Assert.That(bounds.West, Is.EqualTo(box.West));
        }
Пример #45
0
        /// <summary>
        /// Method to parse the KmlFile
        /// </summary>
        /// <param name="kmlFile">The file to parse</param>
        private void ParseKml(KmlFile kmlFile)
        {
            var kml = kmlFile.Root as Kml;
            if (kml == null)
            {
                throw new Exception("Kml file is null! Please check that the file conforms to http://www.opengis.net/kml/2.2 standards");
            }

            var doc = kml.Feature as Document;
            if (doc == null)
            {
                throw new Exception("Kml file does not have a document node! please check that the file conforms to http://www.opengis.net/kml/2.2 standards");
            }

            _geometryFactory = GeoAPI.GeometryServiceProvider.Instance.CreateGeometryFactory(4326);
            ConnectionID = doc.Name;
            if (!string.IsNullOrEmpty(doc.Description.Text))
                ConnectionID += " (" + doc.Description.Text + ")";

            ExtractStyles(kml);
            ExtractStyleMaps(kml);
            ExtractGeometries(kml);

        }
Пример #46
0
        private static void RunTestCase(TestCase test, KmlFile file)
        {
            // Need to create a file from the element for Process to use,
            // making sure we pass a copy not the real thing!
            var target = KmlFile.Create(file.FindObject(test.Target).Clone(), false);

            // Update is stored as an orphan of the parent folder
            var update = (Update)(file.FindObject(test.Input).Orphans.ElementAt(0));
            var expected = file.FindObject(test.Output).Children.ElementAt(0);
            update.Process(target);
            SampleData.CompareElements(expected, target.Root.Children.ElementAt(0));
        }