Exemplo n.º 1
0
        /// <summary>
        /// Clones the input datasource, saves it to the disk and starts append mode.
        /// </summary>
        public bool SaveAppendModeFeatureSet(IFeatureSet fs, OutputLayerInfo output, IToolLogger log)
        {
            if (File.Exists(output.Filename))
            {
                if (output.Overwrite)
                {
                    if (!GeoSource.Remove(output.Filename))
                    {
                        log.Info("Failed to overwrite.");
                        return(false);
                    }
                }
                else
                {
                    log.Info("Overwrite options isn't selected.");
                    return(false);
                }
            }

            if (!fs.SaveAsEx(output.Filename, true))
            {
                log.Info("Failed to save resulting datasource: " + fs.LastError);
                return(false);
            }

            fs.StartAppendMode();

            return(true);
        }
Exemplo n.º 2
0
        private void RemoveFile()
        {
            var item = GetSelectedItem <IFileItem>();

            if (item == null)
            {
                MessageService.Current.Info("No filename is selected.");
                return;
            }

            if (_context.Layers.Select(l => l.Identity).Contains(item.Identity))
            {
                MessageService.Current.Info("Can't remove datasource currently opened by the program.");
                return;
            }

            if (
                MessageService.Current.Ask("Do you want to remove the datasource: " + Environment.NewLine +
                                           item.Filename + "?"))
            {
                try
                {
                    var folder = item.Folder;
                    GeoSource.Remove(item.Filename);
                    RefreshItem(folder);
                }
                catch (Exception ex)
                {
                    MessageService.Current.Warn("Failed to remove file: " + ex.Message);
                }
            }
        }
Exemplo n.º 3
0
        /// <summary>
        /// Runs the operation
        /// </summary>
        private void btnOk_Click(object sender, EventArgs e)
        {
            CoordinateSystem cs = ProjectionTreeView1.SelectedCoordinateSystem;

            if (cs == null)
            {
                MessageService.Current.Info("No projection is selected.");
                return;
            }

            if (!LayersControl1.Filenames.Any())
            {
                MessageService.Current.Info("No files are selected.");
                return;
            }

            var projection = new SpatialReference();

            if (!projection.ImportFromEpsg(cs.Code))
            {
                MessageService.Current.Info("Failed to initialize the selected projection.");
                return;
            }

            var report = new TesterReportForm();
            int count  = 0; // number of successfully processed files

            foreach (string name in LayersControl1.Filenames)
            {
                var layer = GeoSource.Open(name) as ILayerSource;
                if (layer == null)
                {
                    continue;
                }

                string projName = layer.Projection != null ? layer.Projection.Name : "";
                if (layer.LayerType != LayerType.Invalid && layer.Projection != null)
                {
                    layer.Projection.CopyFrom(projection);
                    count++;
                }
                else
                {
                    report.AddFile(name, projName, ProjectionOperation.Skipped, "");
                }
            }

            if (count > 0)
            {
                MessageService.Current.Info(string.Format("The projection was successfully assigned to the files: {0}",
                                                          count));
            }

            if (report.MismatchedCount > 0)
            {
                report.ShowReport(projection, "The following files were not processed:", ReportType.Assignment);
            }

            LayersControl1.UpdateProjections();
        }
Exemplo n.º 4
0
        private void AddLayerToMapAsync(IDatabaseLayerItem item)
        {
            item.ShowLoadingIndicator();

            Task <IDatasource> .Factory.StartNew(() =>
            {
                var timer = new Stopwatch();
                timer.Start();

                var ds = GeoSource.OpenFromIdentity(item.Identity) as IVectorLayer;

                if (ds != null)
                {
                    var data = ds.Data;
                }

                return(ds);
            }).ContinueWith(t =>
            {
                if (t.Result != null)
                {
                    if (_layerService.AddDatasource(t.Result))
                    {
                        int handle = _layerService.LastLayerHandle;
                        _context.Map.ZoomToLayer(handle);
                    }
                }

                item.HideLoadingIndicator();
            }, TaskScheduler.FromCurrentSynchronizationContext());
        }
Exemplo n.º 5
0
        public DatasourceInput(string filename)
        {
            // TODO: datasource must be closed in case of OGR layers
            var identity = new LayerIdentity(filename);
            var ds       = GeoSource.OpenFromIdentity(identity);

            Datasource = ds.GetLayers().FirstOrDefault();
        }
Exemplo n.º 6
0
        /// <summary>
        /// Runs the tool.
        /// </summary>
        public override bool Run(ITaskHandle task)
        {
            // ReSharper disable once InvertIf
            if (Output.Overwrite && !GeoSource.Remove(Output.Filename))
            {
                Log.Warn("Failed to remove file: " + Output.Filename, null);
                return(false);
            }

            return(GisUtils.Instance.Polygonize(GridFilename, Output.Filename, BandIndex, false, null, GdalFormats.Shapefile));
        }
Exemplo n.º 7
0
        private static string GetDescription(string filename)
        {
            using (var ds = GeoSource.Open(filename))
            {
                if (ds != null)
                {
                    return(ds.ToolTipText);
                }
            }

            return(string.Empty);
        }
Exemplo n.º 8
0
        private bool SaveDatasource(IDatasource ds, string filename)
        {
            if (!GeoSource.Remove(filename))
            {
                return(HandleOverwriteFailure());
            }

            if (LayerSourceHelper.Save(ds, filename))
            {
                Logger.Current.Info("Layer ({0}) is created.", filename);
                return(true);
            }

            Logger.Current.Error("Failed to save datasource: " + ds.LastError);
            return(false);
        }
Exemplo n.º 9
0
        public bool DeleteOutputs(IParametrizedTool tool)
        {
            foreach (var output in tool.GetOutputs())
            {
                if (File.Exists(output.Filename) && output.Overwrite)
                {
                    if (!GeoSource.Remove(output.Filename))
                    {
                        MessageService.Current.Info("Failed to remove datasource: " + output.Filename);
                        return(false);
                    }
                }
            }

            return(true);
        }
Exemplo n.º 10
0
        /// <summary>
        /// Gets the geographic co ordinates and radius for a location by querying a GeoSource endpoint
        /// </summary>
        /// <param name="geoString">Location name</param>
        /// <param name="geoSource">Geosource to query</param>
        /// <returns>the geo point</returns>
        public static GeocodePoint GetGeoData(string geoString, GeoSource geoSource)
        {
            GeocodePoint geocodePoint = null;

            switch (geoSource)
            {
            case GeoSource.VirtualEarth:
                geocodePoint = GetGeoDataFromVirtualEarth(geoString);
                break;

            case GeoSource.LoMoLobby:
                geocodePoint = GetGeoDataFromLobby(geoString);
                break;
            }

            return(geocodePoint);
        }
Exemplo n.º 11
0
        /// <summary>
        /// Runs the tool.
        /// </summary>
        public override bool Run(ITaskHandle task)
        {
            var poly = GetPolygon();

            if (poly == null)
            {
                Log.Warn("Failed to extract the clip polygon.", null);
                return(false);
            }

            // ReSharper disable once InvertIf
            if (Output.Overwrite && !GeoSource.Remove(Output.Filename))
            {
                Log.Warn("Failed to remove file: " + Output.Filename, null);
                return(false);
            }

            return(GisUtils.Instance.ClipGridWithPolygon(Input.Datasource.Filename, poly, Output.Filename, KeepExtents));
        }
Exemplo n.º 12
0
        /// <summary>
        /// Removes output layers generated by the execution of the tool. Layers are removed both from map and from the disk.
        /// </summary>
        public static bool RemoveOutputs(this IParametrizedTool tool, IAppContext context, ILayerService layerService)
        {
            foreach (var output in tool.GetOutputs())
            {
                var cache = output.DatasourcePointer;

                if (cache == null)
                {
                    // it's normal in case tool execution failed or was interrupted
                    continue;
                }

                if (cache.LayerHandle != -1)
                {
                    // it's only in-memory, so it's enough to remove it from map
                    if (!layerService.RemoveLayer(cache.LayerHandle))
                    {
                        MessageService.Current.Warn("Failed to remove output layer from the map.");
                        return(false);
                    }
                }
                else if (cache.LayerIdentity != null)
                {
                    if (context.Layers.Any(l => l.Identity == cache.LayerIdentity))
                    {
                        if (!layerService.RemoveLayer(cache.LayerIdentity))
                        {
                            MessageService.Current.Warn("Failed to remove output layer from the map.");
                            return(false);
                        }
                    }

                    if (!GeoSource.Remove(cache.LayerIdentity.Filename))
                    {
                        MessageService.Current.Warn("Failed to remove output layer from disk.");
                        return(false);
                    }
                }
            }

            return(true);
        }
Exemplo n.º 13
0
        private bool AddLayersFromFilenameCore(string filename)
        {
            try
            {
                var ds = GeoSource.Open(filename);

                if (ds == null)
                {
                    MessageService.Current.Warn(string.Format("Failed to open datasource: {0} \n {1}", filename,
                                                              GeoSource.LastError));
                    return(false);
                }

                return(AddDatasource(ds));
            }
            catch (Exception ex)
            {
                MessageService.Current.Warn(string.Format("There was a problem opening layer: {0}. \n Details: {1}",
                                                          filename, ex.Message));
                return(false);
            }
        }
Exemplo n.º 14
0
        /// <summary>
        /// Projection name is written as suffix to the filename in case of reprojection.
        /// Let's try to find file with the same name, but correct suffix for projection.
        /// It's assumed here that projection for the layer passed doesn't match the project one.
        /// </summary>
        public static bool SeekSubstituteFile(this ILayerSource layer, ISpatialReference targetProjection, out ILayerSource newLayer)
        {
            newLayer = null;

            if (layer.LayerType == LayerType.VectorLayer)
            {
                // no substibutes for OGR layers
                return(false);
            }

            string testName = FilenameWithProjectionSuffix(layer.Filename, layer.Projection, targetProjection);

            if (!File.Exists(testName))
            {
                return(false);
            }

            var layerTest = GeoSource.Open(testName) as ILayerSource;

            if (layerTest == null)
            {
                return(false);
            }

            var f1 = new FileInfo(layer.Filename);
            var f2 = new FileInfo(testName);

            // the size of .shp files must be exactly the same
            bool equalSize = !(layerTest.LayerType == LayerType.Shapefile && f1.Length != f2.Length);

            if (layerTest.Projection.IsSameExt(targetProjection, layerTest.Envelope, 10) && equalSize)
            {
                newLayer = layerTest;
                return(true);
            }

            return(false);
        }
Exemplo n.º 15
0
        private static bool AddTempDataSource(
            IAppContext context,
            ILayerService layerService,
            string filename,
            OutputLayerInfo outputInfo)
        {
            var fs = FeatureSet.OpenAsInMemoryDatasource(filename);

            if (fs != null)
            {
                // output info name
                if (layerService.AddDatasource(fs))
                {
                    var layer = context.Layers.ItemByHandle(layerService.LastLayerHandle);
                    layer.Name = outputInfo.Name;

                    GeoSource.Remove(filename);
                    return(true);
                }
            }

            return(false);
        }
Exemplo n.º 16
0
        /// <summary>
        /// Reopens datasource which served as input for GisTool. The datasource will be searched
        /// for among open layers, including in-memory layers and if not present, reoped from the disk.
        /// </summary>
        private static IDatasourceInput ReopenDatasource(
            this DatasourcePointer ds,
            IAppContext context,
            IDatasourceInput oldInput)
        {
            int layerHandle = ds.LayerHandle;

            if (layerHandle != -1)
            {
                var layer = context.Layers.ItemByHandle(layerHandle);

                return(ReopenLayerInput(layer, oldInput));
            }

            var identity = ds.LayerIdentity;

            if (identity != null)
            {
                // maybe it opened
                var layer = context.Layers.FirstOrDefault(l => l.Identity == identity);

                if (layer != null)
                {
                    return(ReopenLayerInput(layer, oldInput));
                }

                // if not, let's try to open
                var source = GeoSource.OpenFromIdentity(identity) as ILayerSource;
                if (source != null)
                {
                    return(new DatasourceInput(source));
                }
            }

            return(null);
        }
Exemplo n.º 17
0
        public void GetEPSGCode()
        {
            var       sr         = new SpatialReference();
            const int Amersfoort = 28992;

            if (!sr.ImportFromEpsg(Amersfoort))
            {
                Assert.Fail("Failed to import projection: " + Amersfoort);
            }

            var code = sr.GetEpsgCode();

            Assert.AreEqual(Amersfoort, code);

            // Load shapefile and get its projection:
            const string sfFilename = @"D:\dev\GIS-Data\MapWindow-Projects\TheNetherlands\Assen.shp";
            var          ds         = GeoSource.Open(sfFilename);
            var          layer      = ds as ILayerSource;

            Assert.IsNotNull(layer);
            var layerCode = layer.Projection.GetEpsgCode();

            Assert.AreEqual(Amersfoort, layerCode);
        }
Exemplo n.º 18
0
        /// <summary>
        /// Does the reprojection work
        /// </summary>
        private void DoReprojection(IEnumerable <string> filenames, ISpatialReference projection, bool inPlace)
        {
            var report = new TesterReportForm();

            report.InitProgress(projection);
            var files = new List <string>();

            int count = 0; // number of successfully reprojected shapefiles

            foreach (string filename in filenames)
            {
                var layer = GeoSource.Open(filename) as ILayerSource;
                if (layer == null)
                {
                    continue;
                }

                ILayerSource layerNew = null;

                if (projection.IsSame(layer.Projection))
                {
                    report.AddFile(layer.Filename, projection.Name, ProjectionOperaion.SameProjection, "");
                    files.Add(layer.Filename);
                }
                else
                {
                    TestingResult result = _reprojectingService.Reproject(layer, out layerNew, projection, report);
                    if (result == TestingResult.Ok || result == TestingResult.Substituted)
                    {
                        var oper = result == TestingResult.Ok
                                       ? ProjectionOperaion.Reprojected
                                       : ProjectionOperaion.Substituted;
                        string newName = layerNew == null ? "" : layerNew.Filename;
                        report.AddFile(layer.Filename, layer.Projection.Name, oper, newName);
                        files.Add(newName == "" ? layer.Filename : newName);
                        count++;
                    }
                    else
                    {
                        var operation = result == TestingResult.Error
                                            ? ProjectionOperaion.FailedToReproject
                                            : ProjectionOperaion.Skipped;
                        report.AddFile(layer.Filename, layer.Projection.Name, ProjectionOperaion.Skipped, "");
                    }
                }

                layer.Close();
                if (layerNew != null)
                {
                    layerNew.Close();
                }
            }
            report.ShowReport(projection, "Reprojection results:", ReportType.Loading);

            IEnumerable <string> names = _context.Layers.Select(l => l.Filename).ToList();

            names = files.Except(names);

            if (count == 0)
            {
                MessageService.Current.Info("No files to add to the map.");
                return;
            }

            if (!projection.IsSame(_context.Map.Projection))
            {
                MessageService.Current.Info(
                    "Chosen projection is different from the project one. The layers can't be added to map.");
                return;
            }

            if (!names.Any())
            {
                MessageService.Current.Info("No files to add to the map.");
                return;
            }

            if (MessageService.Current.Ask("Do you want to add layers to the project?"))
            {
                //_context.Layers.StartAddingSession();

                foreach (string filename in names)
                {
                    var ds    = GeoSource.Open(filename);
                    var layer = LayerSourceHelper.ConvertToLayer(ds);
                    _context.Layers.Add(layer);
                }

                //_context.Layers.StopAddingSession();
            }
        }