public LocalNativeSqlReader(MgSqlDataReader reader)
 {
     _reader   = reader;
     _mgReader = new FixedWKTReader();
     _agfRw    = new MgAgfReaderWriter();
     _wktRw    = new MgWktReaderWriter();
 }
Esempio n. 2
0
 protected override void Dispose(bool disposing)
 {
     if (disposing)
     {
         Close();
         if (_agfRw != null)
         {
             try
             {
                 _agfRw.Dispose();
             }
             catch (MgException ex)
             {
                 ex.Dispose();
             }
             _agfRw = null;
         }
         if (_wktRw != null)
         {
             try
             {
                 _wktRw.Dispose();
             }
             catch (MgException ex)
             {
                 ex.Dispose();
             }
             _wktRw = null;
         }
     }
     base.Dispose(disposing);
 }
Esempio n. 3
0
        public SpatialContextResultDialog(MgSpatialContextReader reader)
            : this()
        {
            _reader = reader;
            _wktRW  = new MgWktReaderWriter();
            _agfRW  = new MgAgfReaderWriter();

            StringBuilder sb = new StringBuilder();

            while (_reader.ReadNext())
            {
                MgGeometry geom = null;
                if (_reader.ExtentType == MgSpatialContextExtentType.scStatic)
                {
                    geom = _agfRW.Read(_reader.Extent);
                }

                sb.AppendFormat("Spatial Context{0}\tName: {1}{0}\tDescription: {2}{0}\tCoordinate System: {3}{0}\tCoordinate System Wkt: {4}{0}\tExtent Type {5}{0}\tExtents (if applicable): {6}{0}\tXY Tolerance: {7}{0}\tZ Tolerance: {8}{0}\tIs Active: {9}{0}{0}",
                                Environment.NewLine,
                                _reader.Name,
                                _reader.Description,
                                _reader.CoordinateSystem,
                                _reader.CoordinateSystemWkt,
                                _reader.ExtentType == MgSpatialContextExtentType.scDynamic ? "Dynamic" : "Static",
                                geom != null ? _wktRW.Write(geom) : "N/A",
                                _reader.XYTolerance,
                                _reader.ZTolerance,
                                _reader.IsActive());
            }
            textBox1.Text = sb.ToString();
            _reader.Close();
        }
Esempio n. 4
0
        public void Execute(IPlatformFactory factory, ITestLogger logger)
        {
            var     wkt   = new MgWktReaderWriter();
            MgPoint geom1 = wkt.Read("POINT XY (1.0 1.0)") as MgPoint;
            MgPoint geom2 = wkt.Read("POINT XY (2.0 2.0)") as MgPoint;
            MgPoint geom3 = wkt.Read("POINT XY (1.0 1.0)") as MgPoint;

            MgPointCollection coll = new MgPointCollection();

            coll.Add(geom1);
            coll.Add(geom2);
            coll.Add(geom3);

            Assert.AreEqual(3, coll.Count);
            Assert.IsTrue(geom1.Equals(coll[0]));
            Assert.IsTrue(coll[0].Equals(coll[2]));
            Assert.IsFalse(coll[0].Equals(coll[1]));
            coll[0] = coll[1];
            Assert.IsTrue(coll[0].Equals(coll[1]));

            double x = 0.0;

            foreach (MgPoint geom in coll)
            {
                x += geom.GetCoordinate().GetX();
            }
            Assert.AreEqual(5.0, x);
        }
Esempio n. 5
0
 public LocalNativeDataReader(MgDataReader reader)
 {
     _reader = reader;
     _mgReader = new FixedWKTReader();
     _agfRw = new MgAgfReaderWriter();
     _wktRw = new MgWktReaderWriter();
 }
Esempio n. 6
0
        public SpatialContextResultDialog(MgSpatialContextReader reader)
            : this()
        {
            _reader = reader;
            _wktRW = new MgWktReaderWriter();
            _agfRW=  new MgAgfReaderWriter();

            StringBuilder sb = new StringBuilder();
            while (_reader.ReadNext())
            {
                MgGeometry geom = null;
                if (_reader.ExtentType == MgSpatialContextExtentType.scStatic)
                {
                    geom = _agfRW.Read(_reader.Extent);
                }

                sb.AppendFormat("Spatial Context{0}\tName: {1}{0}\tDescription: {2}{0}\tCoordinate System: {3}{0}\tCoordinate System Wkt: {4}{0}\tExtent Type {5}{0}\tExtents (if applicable): {6}{0}\tXY Tolerance: {7}{0}\tZ Tolerance: {8}{0}\tIs Active: {9}{0}{0}",
                    Environment.NewLine,
                    _reader.Name,
                    _reader.Description,
                    _reader.CoordinateSystem,
                    _reader.CoordinateSystemWkt,
                    _reader.ExtentType == MgSpatialContextExtentType.scDynamic ? "Dynamic" : "Static",
                    geom != null ? _wktRW.Write(geom) : "N/A",
                    _reader.XYTolerance,
                    _reader.ZTolerance,
                    _reader.IsActive());
            }
            textBox1.Text = sb.ToString();
            _reader.Close();
        }
Esempio n. 7
0
 void OnDisposed(object sender, EventArgs e)
 {
     if (_wktRw != null)
     {
         _wktRw.Dispose();
         _wktRw = null;
     }
 }
Esempio n. 8
0
 public LocalNativeFeatureReader(MgFeatureReader reader)
 {
     _reader = reader;
     _mgReader = new FixedWKTReader();
     _agfRw = new MgAgfReaderWriter();
     _wktRw = new MgWktReaderWriter();
     base.ClassDefinition = Utility.ConvertClassDefinition(reader.GetClassDefinition());
     base.FieldCount = reader.GetPropertyCount();
 }
Esempio n. 9
0
 public LocalNativeFeatureReader(MgFeatureReader reader)
 {
     _reader              = reader;
     _mgReader            = new FixedWKTReader();
     _agfRw               = new MgAgfReaderWriter();
     _wktRw               = new MgWktReaderWriter();
     base.ClassDefinition = Utility.ConvertClassDefinition(reader.GetClassDefinition());
     base.FieldCount      = reader.GetPropertyCount();
 }
Esempio n. 10
0
 void OnDisposed(object sender, EventArgs e)
 {
     _properties.Clear();
     _layers.Clear();
     _wktRw.Dispose();
     _wktRw = null;
     _geomFact.Dispose();
     _geomFact = null;
 }
Esempio n. 11
0
 public RedlineEditor(IMapViewer viewer, RedlineLayer layer)
 {
     _viewer = viewer;
     _layer = layer;
     var provider = viewer.GetProvider();
     _featSvc = (MgFeatureService)provider.CreateService(MgServiceType.FeatureService);
     _wktRW = new MgWktReaderWriter();
     _agfRW = new MgAgfReaderWriter();
     _geomFact = new MgGeometryFactory();
 }
Esempio n. 12
0
    string pointTransformAndWriteZ(string geom, MgMap map)
    {
        double[] x = new double[1];
        double[] y = new double[1];
        double[] z = new double[1];

        MgWktReaderWriter wktrwdmr = new MgWktReaderWriter();
        MgPoint           cntr     = wktrwdmr.Read(geom).Centroid;

        x[0] = cntr.Coordinate.X;
        y[0] = cntr.Coordinate.Y;
        z[0] = 0;

        StringBuilder output = new StringBuilder();

        output.Append("<table width=\"100%\" class=\"results\">");

        //WGS preko MG API
        MgCoordinateSystemFactory fact = new MgCoordinateSystemFactory();
        string wktFrom = map.GetMapSRS();

        string wktTo = "GEOGCS[\"LL84\",DATUM[\"WGS84\",SPHEROID[\"WGS84\",6378137.000,298.25722293]],PRIMEM[\"Greenwich\",0],UNIT[\"Degree\",0.01745329251994]]";

        MgCoordinateSystem          CSSource       = fact.Create(wktFrom);
        MgCoordinateSystem          CSTarget       = fact.Create(wktTo);
        MgCoordinateSystemTransform coordTransform = fact.GetTransform(CSSource, CSTarget);

        MgGeometryFactory geomFact = new MgGeometryFactory();

        // GK
        //samo prvo višino zaenkrat, dokler ni enačbe za Z
        output.Append(String.Format("<tr><td class='header'><b>Map koordinates:</b></td><td class=\"results\"><table><tr><td><b>Y:</b></td><td>{0}</td></tr><tr><td><b>X:</b></td><td>{1}</td></tr></table></td></tr>", string.Format("{0:0.0}", x[0]), string.Format("{0:0.0}", y[0])));

        int i = 0;

        //transformacija preko MG koordinatnega sistema
        foreach (double pointX in x)
        {
            MgCoordinate coord = geomFact.CreateCoordinateXY(x[i], y[i]);
            coord = coordTransform.Transform(coord);

            x[i] = coord.X;
            y[i] = coord.Y;

            i++;
        }

        double[] xwgs = x;
        double[] ywgs = y;
        output.Append(String.Format("<tr><td class='header'><b>WGS84:</b></td><td class=\"results\"><table><tr><td><b>Lon:</b></td><td>{0}</td></tr><tr><td><b>Lat:</b></td><td>{1}</td></tr></table></td></tr>", string.Format("{0:0.000000}", xwgs[0]), string.Format("{0:0.000000}", ywgs[0])));

        output.Append("</table>");

        return(output.ToString());
    }
Esempio n. 13
0
        public RedlineEditor(IMapViewer viewer, RedlineLayer layer)
        {
            _viewer = viewer;
            _layer  = layer;
            var provider = viewer.GetProvider();

            _featSvc  = (MgFeatureService)provider.CreateService(MgServiceType.FeatureService);
            _wktRW    = new MgWktReaderWriter();
            _agfRW    = new MgAgfReaderWriter();
            _geomFact = new MgGeometryFactory();
        }
Esempio n. 14
0
        public void Execute(IPlatformFactory factory, ITestLogger logger)
        {
            var resSvc    = (MgResourceService)factory.CreateService(MgServiceType.ResourceService);
            var renderSvc = (MgRenderingService)factory.CreateService(MgServiceType.RenderingService);
            var root      = "../../TestData/TileService/";

            Utils.LoadResource(resSvc, "Library://UnitTests/Data/RoadCenterLines.FeatureSource", root + "UT_RoadCenterLines.fs");
            Utils.LoadResourceData(resSvc, "Library://UnitTests/Data/RoadCenterLines.FeatureSource", "UT_RoadCenterLines.sdf", MgResourceDataType.File, root + "UT_RoadCenterLines.sdf");
            Utils.LoadResource(resSvc, "Library://UnitTests/Layers/RoadCenterLines.LayerDefinition", root + "UT_RoadCenterLines.ldf");

            Utils.LoadResource(resSvc, "Library://UnitTests/Data/VotingDistricts.FeatureSource", root + "UT_VotingDistricts.fs");
            Utils.LoadResourceData(resSvc, "Library://UnitTests/Data/VotingDistricts.FeatureSource", "UT_VotingDistricts.sdf", MgResourceDataType.File, root + "UT_VotingDistricts.sdf");
            Utils.LoadResource(resSvc, "Library://UnitTests/Layers/VotingDistricts.LayerDefinition", root + "UT_VotingDistricts.ldf");

            Utils.LoadResource(resSvc, "Library://UnitTests/Data/Parcels.FeatureSource", root + "UT_Parcels.fs");
            Utils.LoadResourceData(resSvc, "Library://UnitTests/Data/Parcels.FeatureSource", "UT_Parcels.sdf", MgResourceDataType.File, root + "UT_Parcels.sdf");
            Utils.LoadResource(resSvc, "Library://UnitTests/Layers/Parcels.LayerDefinition", root + "UT_Parcels.ldf");

            Utils.LoadResource(resSvc, "Library://UnitTests/Maps/BaseMap.MapDefinition", root + "UT_BaseMap.mdf");

            var mdfId = new MgResourceIdentifier("Library://UnitTests/Maps/BaseMap.MapDefinition");

            //This is a sample request from the AJAX viewer. It selected 7 features. It should do the same here.
            var dpi    = 96;
            var width  = 773;
            var height = 696;
            var scale  = 4345.697945713148;
            var x      = -87.72117757411266;
            var y      = 43.7527161153258;
            var wkt    = "POLYGON((-87.72250482778884 43.75497812742761, -87.72134799968197 43.75497812742761, -87.72134799968197 43.75358373640595, -87.72250482778884 43.75358373640595, -87.72250482778884 43.75497812742761))";
            var map    = (MgMap)factory.CreateMap(mdfId, mdfId.Name, width, height, x, y, scale, dpi);

            var wktRw      = new MgWktReaderWriter();
            var geom       = wktRw.Read(wkt);
            var layerNames = new MgStringCollection();

            layerNames.Add("Parcels");

            var result = renderSvc.QueryFeatures(map, layerNames, geom, MgFeatureSpatialOperations.Intersects, -1);
            var sel    = result.GetSelection();

            sel.SetMap(map);

            var total     = 0;
            var selLayers = sel.GetLayers();

            foreach (var sl in selLayers)
            {
                total += sel.GetSelectedFeaturesCount(sl, sl.FeatureClassName);
            }

            Assert.AreEqual(7, total);
        }
Esempio n. 15
0
        // GET: Search/Results
        public ActionResult Results(SearchInputModel input)
        {
            MgSiteConnection conn = CreateConnection(input);
            MgMap            map  = new MgMap(conn);

            map.Open(input.MapName);

            MgLayerCollection layers = map.GetLayers();
            int lidx = layers.IndexOf("Parcels");

            if (lidx < 0)
            {
                throw new Exception("Layer not found on map: Parcels");
            }
            MgLayerBase           layer = layers[lidx];
            MgFeatureQueryOptions query = new MgFeatureQueryOptions();

            //Don't fret about the input here. This is not a SQL injection attack vector. This filter string is
            //not SQL, it's a FDO filter. A 'DROP TABLE' or any other destructive SQL will fail on
            //query execution when this filter is parsed to a FDO filter.
            switch (input.By)
            {
            case "OWNER":
                query.SetFilter("RNAME LIKE '%" + input.Query.Replace("'", "\'") + "%'");
                break;

            case "ADDRESS":
                query.SetFilter("RPROPAD LIKE '%" + input.Query.Replace("'", "\'") + "%'");
                break;

            case "BBOX":
                double[] parts = input.Query.Split(',').Select(s => double.Parse(s, CultureInfo.InvariantCulture)).ToArray();
                if (parts.Length != 4)
                {
                    throw new Exception("Invalid BBOX parameter");
                }
                MgWktReaderWriter wktRw      = new MgWktReaderWriter();
                MgGeometry        filterGeom = wktRw.Read(MakeWktPolygon(parts[0], parts[1], parts[2], parts[3]));
                query.SetSpatialFilter(layer.FeatureGeometryName, filterGeom, MgFeatureSpatialOperations.Intersects);
                break;

            default:
                throw new Exception("Unknown query type: " + input.By);
            }

            SearchResultViewModel vm = new SearchResultViewModel();

            vm.Session = input.Session;
            vm.MapName = input.MapName;
            vm.LoadResults(layer, query);
            return(View(vm));
        }
Esempio n. 16
0
        void OnDisposed(object sender, EventArgs e)
        {
            if (_wktRw != null)
            {
                _wktRw.Dispose();
                _wktRw = null;
            }

            if (_geomFact != null)
            {
                _geomFact.Dispose();
                _geomFact = null;
            }
        }
Esempio n. 17
0
        MgPropertyCollection MakePoint(String name, double x, double y, MgWktReaderWriter wktReaderWriter, MgAgfReaderWriter agfReaderWriter)
        {
            MgPropertyCollection propertyCollection = new MgPropertyCollection();
            MgStringProperty     nameProperty       = new MgStringProperty("NAME", name);

            propertyCollection.Add(nameProperty);

            MgGeometry         geometry           = wktReaderWriter.Read("POINT XY (" + x + " " + y + ")");
            MgByteReader       geometryByteReader = agfReaderWriter.Write(geometry);
            MgGeometryProperty geometryProperty   = new MgGeometryProperty("GEOM", geometryByteReader);

            propertyCollection.Add(geometryProperty);

            return(propertyCollection);
        }
Esempio n. 18
0
        public override void Invoke()
        {
            var viewer = this.Viewer;

            viewer.DigitizeCircle((x, y, r) =>
            {
                if (_wktRw == null)
                {
                    _wktRw = new MgWktReaderWriter();
                }

                MgGeometry geom = _wktRw.Read(Util.MakeWktCircle(x, y, r, true));
                viewer.SelectByGeometry(geom);
            });
        }
Esempio n. 19
0
        private void InitBase(IMapViewer viewer)
        {
            this.Title = Strings.TitleQuery;
            this.Disposed += new EventHandler(OnDisposed);
            _viewer = viewer;
            _properties = new BindingList<MgDataPropertyDefinition>();
            _layers = new BindingList<MgLayerBase>();
            _wktRw = new MgWktReaderWriter();
            _geomFact = new MgGeometryFactory();

            cmbOperator.DataSource = Enum.GetValues(typeof(QueryOperator));
            cmbLayer.DataSource = _layers;
            cmbProperty.DataSource = _properties;

            cmbOperator.SelectedIndex = 0;
        }
Esempio n. 20
0
        private void InitBase(IMapViewer viewer)
        {
            this.Title     = Strings.TitleQuery;
            this.Disposed += new EventHandler(OnDisposed);
            _viewer        = viewer;
            _properties    = new BindingList <MgDataPropertyDefinition>();
            _layers        = new BindingList <MgLayerBase>();
            _wktRw         = new MgWktReaderWriter();
            _geomFact      = new MgGeometryFactory();

            cmbOperator.DataSource = Enum.GetValues(typeof(QueryOperator));
            cmbLayer.DataSource    = _layers;
            cmbProperty.DataSource = _properties;

            cmbOperator.SelectedIndex = 0;
        }
Esempio n. 21
0
 public DigitizingAndRedlining(IMapViewer viewer)
 {
     InitializeComponent();
     _viewer = viewer;
     _geomFact = new MgGeometryFactory();
     _wktRW = new MgWktReaderWriter();
     _agfRW = new MgAgfReaderWriter();
     this.Title = "Digitizing and Redlining";
     _viewer.PropertyChanged += OnViewerPropertyChanged;
     MgMapBase map = _viewer.GetMap();
     MgLayerCollection layers = map.GetLayers();
     if (layers.IndexOf("Redline") >= 0)
     {
         _redlineLayer = (MgdLayer)layers.GetItem("Redline");
     }
     CheckDigitizingState();
 }
        // GET: Search/Results
        public ActionResult Results(SearchInputModel input)
        {
            MgSiteConnection conn = CreateConnection(input);
            MgMap map = new MgMap(conn);
            map.Open(input.MapName);

            MgLayerCollection layers = map.GetLayers();
            int lidx = layers.IndexOf("Parcels");
            if (lidx < 0)
            {
                throw new Exception("Layer not found on map: Parcels");
            }
            MgLayerBase layer = layers.GetItem(lidx);
            MgFeatureQueryOptions query = new MgFeatureQueryOptions();
            //Don't fret about the input here. This is not a SQL injection attack vector. This filter string is
            //not SQL, it's a FDO filter. A 'DROP TABLE' or any other destructive SQL will fail on
            //query execution when this filter is parsed to a FDO filter.
            switch (input.By)
            {
                case "OWNER":
                    query.SetFilter("RNAME LIKE '%" + input.Query.Replace("'", "\'") + "%'");
                    break;
                case "ADDRESS":
                    query.SetFilter("RPROPAD LIKE '%" + input.Query.Replace("'", "\'") + "%'");
                    break;
                case "BBOX":
                    double[] parts = input.Query.Split(',').Select(s => double.Parse(s, CultureInfo.InvariantCulture)).ToArray();
                    if (parts.Length != 4)
                    {
                        throw new Exception("Invalid BBOX parameter");
                    }
                    MgWktReaderWriter wktRw = new MgWktReaderWriter();
                    MgGeometry filterGeom = wktRw.Read(MakeWktPolygon(parts[0], parts[1], parts[2], parts[3]));
                    query.SetSpatialFilter(layer.FeatureGeometryName, filterGeom, MgFeatureSpatialOperations.Intersects);
                    break;
                default:
                    throw new Exception("Unknown query type: " + input.By);
            }

            SearchResultViewModel vm = new SearchResultViewModel();
            vm.Session = input.Session;
            vm.MapName = input.MapName;
            vm.LoadResults(layer, query);
            return View(vm);
        }
Esempio n. 23
0
        public DigitizingAndRedlining(IMapViewer viewer)
        {
            InitializeComponent();
            _viewer    = viewer;
            _geomFact  = new MgGeometryFactory();
            _wktRW     = new MgWktReaderWriter();
            _agfRW     = new MgAgfReaderWriter();
            this.Title = "Digitizing and Redlining";
            _viewer.PropertyChanged += OnViewerPropertyChanged;
            MgMapBase         map    = _viewer.GetMap();
            MgLayerCollection layers = map.GetLayers();

            if (layers.IndexOf("Redline") >= 0)
            {
                _redlineLayer = (MgdLayer)layers.GetItem("Redline");
            }
            CheckDigitizingState();
        }
Esempio n. 24
0
        protected override void OnLoad(EventArgs e)
        {
            _wktRw    = new MgWktReaderWriter();
            _geomFact = new MgGeometryFactory();
            new MapViewerController(mgMapViewer1,          //The MgMapViewer
                                    mgLegend1,             //The MgLegend
                                    this,                  //The IMapStatusBar
                                    mgPropertyPane1);      //The MgPropertyPane

            MgdServiceFactory    factory  = new MgdServiceFactory();
            MgdResourceService   resSvc   = (MgdResourceService)factory.CreateService(MgServiceType.ResourceService);
            MgResourceIdentifier mapDefId = new MgResourceIdentifier("Library://Samples/Sheboygan/Maps/Sheboygan.MapDefinition");

            //If this map definition doesn't exist, we ask the user to
            //load the Sheboygan package
            if (!resSvc.ResourceExists(mapDefId))
            {
                using (OpenFileDialog diag = new OpenFileDialog())
                {
                    diag.Filter = "MapGuide Packages (*.mgp)|*.mgp";
                    if (diag.ShowDialog() == DialogResult.OK)
                    {
                        MgByteSource source = new MgByteSource(diag.FileName);
                        MgByteReader reader = source.GetReader();
                        resSvc.ApplyResourcePackage(reader);
                    }
                    else
                    {
                        //No map, nothing to do here
                        Application.Exit();
                    }
                }
            }

            //Create our runtime map
            MgdMap map = new MgdMap(mapDefId);
            //Create our viewer provider
            MgMapViewerProvider provider = new MgDesktopMapViewerProvider(map);

            //Initialize our viewer with this provider
            mgMapViewer1.Init(provider);
            UpdateButtonCheckedState();
        }
Esempio n. 25
0
        private void OnPointDrawn(double x, double y)
        {
            if (_pointLayer == null) //Our point layer doesn't exist
            {
                CreateRedlineLayer();
            }

            //Now insert our point. This code should look familiar
            //to you, setting up the MgPropertyCollection for insertion
            MgPropertyCollection props = new MgPropertyCollection();
            MgWktReaderWriter    wktRw = new MgWktReaderWriter();
            MgAgfReaderWriter    agfRw = new MgAgfReaderWriter();

            MgGeometry   geom = wktRw.Read("POINT (" + x + " " + y + ")");
            MgByteReader agf  = agfRw.Write(geom);

            MgGeometryProperty geomProp = new MgGeometryProperty("Geometry", agf);

            props.Add(geomProp);

            //Here's where we differ from the official MapGuide API
            //instead of a monolithic UpdateFeatures() that tries to
            //do everything, we have individual InsertFeatures/DeleteFeatures/UpdateFeatures
            //methods. So here's the mg-desktop way

            MgFeatureReader result = _pointLayer.InsertFeatures(props);

            result.Close();

            //Or if you have have access to the MgdLayer instance

            /*
             * MgResourceIdentifier fsId = new MgResourceIdentifier(_pointLayer.GetFeatureSourceId());
             * MgServiceFactory factory = new MgServiceFactory();
             * MgdFeatureService featSvc = (MgdFeatureService)factory.CreateService(MgServiceType.FeatureService);
             * MgFeatureReader fr = featSvc.InsertFeatures(fsId, "Default:Redline", props);
             * fr.Close();
             */

            //Now refresh to see your newly drawn point
            mgMapViewer1.RefreshMap();
        }
Esempio n. 26
0
        protected override void OnLoad(EventArgs e)
        {
            _wktRw = new MgWktReaderWriter();
            _geomFact = new MgGeometryFactory();
            new MapViewerController(mgMapViewer1,          //The MgMapViewer
                                    mgLegend1,             //The MgLegend
                                    this,                  //The IMapStatusBar
                                    mgPropertyPane1);      //The MgPropertyPane

            MgdServiceFactory factory = new MgdServiceFactory();
            MgdResourceService resSvc = (MgdResourceService)factory.CreateService(MgServiceType.ResourceService);
            MgResourceIdentifier mapDefId = new MgResourceIdentifier("Library://Samples/Sheboygan/Maps/Sheboygan.MapDefinition");
            //If this map definition doesn't exist, we ask the user to
            //load the Sheboygan package
            if (!resSvc.ResourceExists(mapDefId))
            {
                using (OpenFileDialog diag = new OpenFileDialog())
                {
                    diag.Filter = "MapGuide Packages (*.mgp)|*.mgp";
                    if (diag.ShowDialog() == DialogResult.OK)
                    {
                        MgByteSource source = new MgByteSource(diag.FileName);
                        MgByteReader reader = source.GetReader();
                        resSvc.ApplyResourcePackage(reader);
                    }
                    else
                    {
                        //No map, nothing to do here
                        Application.Exit();
                    }
                }
            }

            //Create our runtime map
            MgdMap map = new MgdMap(mapDefId);
            //Create our viewer provider
            MgMapViewerProvider provider = new MgDesktopMapViewerProvider(map);
            //Initialize our viewer with this provider
            mgMapViewer1.Init(provider);
            UpdateButtonCheckedState();
        }
Esempio n. 27
0
        public static void WellKnownText()
        {
            MgAgfReaderWriter agfReaderWriter;
            MgWktReaderWriter wktReaderWriter;
            MgPoint           pt11FromText;
            MgPoint           pt11;
            var          pt11TextSpec = "POINT XY ( 1 1 )";
            MgByteReader byteReader;
            string       geometryAgfText;


            agfReaderWriter = new MgAgfReaderWriter();
            wktReaderWriter = new MgWktReaderWriter();
            // In the string to geometry direction:
            pt11FromText = wktReaderWriter.Read(pt11TextSpec) as MgPoint;
            byteReader   = agfReaderWriter.Write(pt11FromText);
            // In the geometry to string direction:
            pt11            = (MgPoint)agfReaderWriter.Read(byteReader);
            geometryAgfText = wktReaderWriter.Write(pt11);
            // geometryAgfText now contains the text representation of the geometry
        }
Esempio n. 28
0
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            string sessionId = GetRequestParameters(Request)["SESSION"];
            string mapName   = GetRequestParameters(Request)["MAPNAME"];
            string locale    = GetRequestParameters(Request)["LOCALE"];

            if (string.IsNullOrEmpty(sessionId))
            {
                Response.Clear();
                Response.End();
                return;
            }

            if (string.IsNullOrEmpty(mapName))
            {
                Response.Clear();
                Response.End();
                return;
            }

            MgResourceService resourceSrvc = GetMgResurceService(sessionId);
            MgFeatureService  featureSrvc  = GetMgFeatureService(sessionId);

            MgMap map = new MgMap();
            map.Open(resourceSrvc, mapName);

            string layernames = GetRequestParameters(Request)["LAYERNAMES"];
            string GEOMETRY   = GetRequestParameters(Request)["GEOMETRY"];
            string selVar     = GetRequestParameters(Request)["SELECTIONVARIANT"];
            string type       = GetRequestParameters(Request)["tp"];
            string inputSel   = GetRequestParameters(Request)["SELECTION"];

            bool hasInputGeom = false;
            if (!string.IsNullOrEmpty(GEOMETRY))
            {
                hasInputGeom = true;
            }

            //selection ima prednost pred podano geometrijo ...
            MgWktReaderWriter wktrw = new MgWktReaderWriter();
            if (!string.IsNullOrEmpty(inputSel))
            {
                MgGeometry inputGeom = MultiGeometryFromSelection(featureSrvc, map, inputSel);
                GEOMETRY = wktrw.Write(inputGeom);
            }

            MgAgfReaderWriter agfRW = new MgAgfReaderWriter();

            int nLayer = 0;
            // pobrišem in zgradim na novo samo tiste, ki imajo zadetke ...
            int           nSloj  = 0;
            string        filter = "";
            StringBuilder sbOut  = new StringBuilder();
            sbOut.Append("<table width=\"100%\" class=\"results\">");
            sbOut.Append("<tr><td class='header'></td><td class='header'>" + "Layer" + "</td><td class='header' align=\"center\">" + "Select" + "</td><td class='header' align=\"center\">" + "Report" + "</td></tr>");

            MgSelection selAll = new MgSelection(map);

            foreach (MgLayer layer in map.GetLayers())
            {
                if (type != "2")
                {
                    if (!layer.IsVisible())
                    {
                        goto nextlay;
                    }
                }

                if (layer.LegendLabel == "")
                {
                    goto nextlay;
                }

                try
                {
                    nLayer++;

                    filter = String.Format("{0} {1} GeomFromText('{2}')", layer.GetFeatureGeometryName(), selVar, GEOMETRY);

                    //preveriti še filter na Layerju. Ker ne gre drugače, je potrebno pogledati v XML
                    MgResourceIdentifier layerDefResId = layer.GetLayerDefinition();
                    MgByteReader         byteReader    = resourceSrvc.GetResourceContent(layerDefResId);

                    System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
                    String xmlLayerDef         = byteReader.ToString();
                    doc.LoadXml(xmlLayerDef);

                    KALI.MGE.Objects.KALILayerDefinition.LayerDefinition ld = KALI.MGE.Objects.KALILayerDefinition.LayerDefinition.Parse(xmlLayerDef);

                    if (!string.IsNullOrEmpty(ld.VectorLayerDefinition.Filter))
                    {
                        filter += " AND (" + ld.VectorLayerDefinition.Filter + ")";
                    }

                    //query the features
                    MgFeatureQueryOptions opts = new MgFeatureQueryOptions();
                    opts.SetFilter(filter);
                    String featureClassName    = layer.GetFeatureClassName();
                    MgResourceIdentifier srcId = new MgResourceIdentifier(layer.GetFeatureSourceId());

                    MgFeatureReader features = featureSrvc.SelectFeatures(srcId, featureClassName, opts);

                    bool hasResult = features.ReadNext();

                    if (hasResult)
                    {
                        nSloj++;

                        int n = 0;

                        MgClassDefinition classDef = features.GetClassDefinition();

                        MgPropertyDefinitionCollection classDefProps = classDef.GetIdentityProperties();
                        ArrayList idPropNames = new ArrayList(classDefProps.GetCount());
                        for (int j = 0; j < classDefProps.GetCount(); j++)
                        {
                            MgPropertyDefinition idProp = classDefProps.GetItem(j);
                            idPropNames.Add(idProp.GetName());
                        }

                        MgSelection sel = new MgSelection(map);
                        do
                        {
                            // Generate XML to selection this feature
                            MgPropertyCollection idProps = new MgPropertyCollection();
                            foreach (string id in idPropNames)
                            {
                                int idPropType = features.GetPropertyType(id);
                                switch (idPropType)
                                {
                                case MgPropertyType.Int32:
                                    idProps.Add(new MgInt32Property(id, features.GetInt32(id)));
                                    break;

                                case MgPropertyType.String:
                                    idProps.Add(new MgStringProperty(id, features.GetString(id)));
                                    break;

                                case MgPropertyType.Int64:
                                    idProps.Add(new MgInt64Property(id, features.GetInt64(id)));
                                    break;

                                case MgPropertyType.Double:
                                    idProps.Add(new MgDoubleProperty(id, features.GetDouble(id)));
                                    break;

                                case MgPropertyType.Single:
                                    idProps.Add(new MgSingleProperty(id, features.GetSingle(id)));
                                    break;

                                case MgPropertyType.DateTime:
                                    idProps.Add(new MgDateTimeProperty(id, features.GetDateTime(id)));
                                    break;

                                default:
                                    //throw new SearchError(String.Format(MgLocalizer.GetString("SEARCHTYYPENOTSUP", locale), new Object[] { idPropType.ToString() }), searchError);
                                    break;
                                }
                            }

                            sel.AddFeatureIds(layer, featureClassName, idProps);
                            selAll.AddFeatureIds(layer, featureClassName, idProps);

                            n++;

                            //if (n > 1000) break;
                        } while (features.ReadNext());

                        features.Close();
                        features.Dispose();

                        string selText = EscapeForHtml(sel.ToXml());
                        string seljs   = "<div class=\"allLay\" onclick=\"parent.SetSelectionXML('" + selText + "');\"><img width=\"16\" height=\"16\" style=\"border:0\" src=\"images/mActionZoomToSelected.png\"/></div>";
                        string seljs3  = "<div class=\"allLay\" onclick=\"parent.MultiGridShow('" + selText + "');\"><img width=\"16\" height=\"16\" style=\"border:0\" src=\"images/mActionOpenTable.png\"/></div>";

                        string linfo = "<b>" + layer.LegendLabel + "</b><br />" + n.ToString() + " " + "Hits";
                        sbOut.Append("<tr><td class=\"results\">" + nSloj.ToString() + "</td><td class=\"results\">" + linfo + "</td><td align=\"center\" class=\"results\">" + seljs + "</td><td align=\"center\" class=\"results\">" + seljs3 + "</td></tr>");
                    }
                }
                catch (Exception)
                {
                    continue;
                }

nextlay:
                continue;
            }

            sbOut.Append("</table>");

            string selAllText = EscapeForHtml(selAll.ToXml());
            string seljsAll   = "<div class=\"allLay\" onclick=\"parent.SetSelectionXML('" + selAllText + "');\"><img width=\"16\" height=\"16\" style=\"border:0\" src=\"images/mActionZoomToSelected.png\"/>" + "Select All" + "</div>";
            string seljsAll3  = "<div class=\"allLay\" onclick=\"parent.MultiGridShow('" + selAllText + "');\"><img width=\"16\" height=\"16\" style=\"border:0\" src=\"images/mActionOpenTable.png\"/>" + "Report All" + "</div>";

            sbOut.Append(string.Format("<br /><table width=\"100%\" class=\"results\"><tr><td class=\"results\">{0}</td><td class=\"results\">{1}</td></tr></table>", seljsAll, seljsAll3));


            featureSrvc.Dispose();
            resourceSrvc.Dispose();

            if (nSloj > 0)
            {
                litPrebodi.Text = sbOut.ToString();
            }
            else
            {
                litPrebodiTitle.Visible = false;
                litPrebodi.Text         = "<b>" + "None layer lies below the selected item/area!" + "</b>";
            }

            MgGeometry inGeom = wktrw.Read(GEOMETRY);

            double rw = map.ViewScale / Math.Sqrt(inGeom.Area);

            //koordinate
            if (hasInputGeom & rw > 400)
            {
                string output = "";

                output = pointTransformAndWriteZ(GEOMETRY, map);

                litKoordinate.Text      = output;
                litKoordinateTitle.Text = "Coordinates of selected points:";
            }
        }
    }
Esempio n. 29
0
        private void btnCreatePointsOfInterest_Click(object sender, EventArgs e)
        {
            string layerName = "Points";
            string legendLabel = "Points of Interest";
            string groupName = "Analysis";

            MgMapViewerProvider provider = _viewer.GetProvider();
            MgResourceService resourceService = (MgResourceService)provider.CreateService(MgServiceType.ResourceService);
            //We use MgdFeatureService instead of MgFeatureService as this sample demonstrates APIs unique to mg-desktop
            MgdFeatureService featureService = (MgdFeatureService)provider.CreateService(MgServiceType.FeatureService);

            MgMapBase map = _viewer.GetMap();
            MgLayerCollection layers = map.GetLayers();
            MgLayerGroupCollection groups = map.GetLayerGroups();

            //NOTE: mg-desktop has no formal concept of a session repository, but we still
            //support session-based resources as a form of temporary resource (for the duration
            //of the application). Session ids in mg-desktop can be any arbitrary string
            string sessionId = Guid.NewGuid().ToString();

            if (layers.IndexOf(layerName) >= 0)
            {
                MessageBox.Show("Layer (" + layerName + ") already created");
                return;
            }

            //---------------------------------------------------//
            // Create a feature source with point data.
            // (The Sheboygan sample data does not contain such data,
            // so we"ll create it.)

            // Create a feature class definition for the new feature source
            MgClassDefinition classDefinition = new MgClassDefinition();
            classDefinition.SetName("Points");
            classDefinition.SetDescription("Feature class with point data.");
            classDefinition.SetDefaultGeometryPropertyName("GEOM");

            MgPropertyDefinitionCollection idProps = classDefinition.GetIdentityProperties();
            MgPropertyDefinitionCollection clsProps = classDefinition.GetProperties();

            // Create an identify property
            MgDataPropertyDefinition identityProperty = new MgDataPropertyDefinition("KEY");
            identityProperty.SetDataType(MgPropertyType.Int32);
            identityProperty.SetAutoGeneration(true);
            identityProperty.SetReadOnly(true);
            // Add the identity property to the class definition
            clsProps.Add(identityProperty);
            idProps.Add(identityProperty);

            // Create a name property
            MgDataPropertyDefinition nameProperty = new MgDataPropertyDefinition("NAME");
            nameProperty.SetDataType(MgPropertyType.String);
            // Add the name property to the class definition
            clsProps.Add(nameProperty);

            // Create a geometry property
            MgGeometricPropertyDefinition geometryProperty = new MgGeometricPropertyDefinition("GEOM");
            geometryProperty.SetGeometryTypes(MgFeatureGeometricType.Point);
            // Add the geometry property to the class definition
            clsProps.Add(geometryProperty);

            // Create a feature schema
            MgFeatureSchema featureSchema = new MgFeatureSchema("PointSchema", "Point schema");
            MgClassDefinitionCollection classes = featureSchema.GetClasses();
            // Add the feature schema to the class definition
            classes.Add(classDefinition);

            // Create the feature source
            String featureSourceName = "Library://Samples/DevGuide/Data/points.FeatureSource";
            MgResourceIdentifier resourceIdentifier = new MgResourceIdentifier(featureSourceName);
            //wkt = "LOCALCS[\"*XY-MT*\",LOCAL_DATUM[\"*X-Y*\",10000],UNIT[\"Meter\", 1],AXIS[\"X\",EAST],AXIS[\"Y\",NORTH]]";
            String wkt = "GEOGCS[\"LL84\",DATUM[\"WGS84\",SPHEROID[\"WGS84\",6378137.000,298.25722293]],PRIMEM[\"Greenwich\",0],UNIT[\"Degree\",0.01745329251994]]";
            MgCreateSdfParams sdfParams = new MgCreateSdfParams("LatLong", wkt, featureSchema);
            featureService.CreateFeatureSource(resourceIdentifier, sdfParams);

            // We need to add some data to the sdf before using it.  The spatial context
            // reader must have an extent.
            MgBatchPropertyCollection batchPropertyCollection = new MgBatchPropertyCollection();
            MgWktReaderWriter wktReaderWriter = new MgWktReaderWriter();
            MgAgfReaderWriter agfReaderWriter = new MgAgfReaderWriter();
            MgGeometryFactory geometryFactory = new MgGeometryFactory();

            // Make four points
            batchPropertyCollection.Add(MakePoint("Point A", -87.727, 43.748, wktReaderWriter, agfReaderWriter));

            batchPropertyCollection.Add(MakePoint("Point B", -87.728, 43.730, wktReaderWriter, agfReaderWriter));

            batchPropertyCollection.Add(MakePoint("Point C", -87.726, 43.750, wktReaderWriter, agfReaderWriter));

            batchPropertyCollection.Add(MakePoint("Point D", -87.728, 43.750, wktReaderWriter, agfReaderWriter));

            // Old way commented out
            
            /*
            // Add the batch property collection to the feature source
            MgInsertFeatures cmd = new MgInsertFeatures("Points", batchPropertyCollection);
            MgFeatureCommandCollection featureCommandCollection = new MgFeatureCommandCollection();
            featureCommandCollection.Add(cmd);

            // Execute the "add" commands
            featureService.UpdateFeatures(resourceIdentifier, featureCommandCollection, false);
            */

            // Here's the mg-desktop way
            MgPropertyCollection insertResult = featureService.InsertFeatures(resourceIdentifier, "Points", batchPropertyCollection);
            for (int i = 0; i < insertResult.GetCount(); i++)
            {
                MgFeatureProperty fp = insertResult.GetItem(i) as MgFeatureProperty;
                if (fp != null)
                {
                    MgFeatureReader fr = fp.GetValue();
                    fr.Close();
                }
            }

            // ...
            //---------------------------------------------------//
            // Create a new layer

            LayerDefinitionFactory factory = new LayerDefinitionFactory();

            // Create a mark symbol
            String resourceId = "Library://Samples/Sheboygan/Symbols/BasicSymbols.SymbolLibrary";
            String symbolName = "PushPin";
            String width = "24";  // unit = points
            String height = "24"; // unit = points
            String color = "FFFF0000";
            String markSymbol = factory.CreateMarkSymbol(resourceId, symbolName, width, height, color);

            // Create a text symbol
            String text = "ID";
            String fontHeight = "12";
            String foregroundColor = "FF000000";
            String textSymbol = factory.CreateTextSymbol(text, fontHeight, foregroundColor);

            // Create a point rule.
            String ruleLegendLabel = "trees";
            String filter = "";
            String pointRule = factory.CreatePointRule(ruleLegendLabel, filter, textSymbol, markSymbol);

            // Create a point type style.
            String pointTypeStyle = factory.CreatePointTypeStyle(pointRule);

            // Create a scale range.
            String minScale = "0";
            String maxScale = "1000000000000";
            String pointScaleRange = factory.CreateScaleRange(minScale, maxScale, pointTypeStyle);

            // Create the layer definiton.
            String featureName = "PointSchema:Points";
            String geometry = "GEOM";
            String layerDefinition = factory.CreateLayerDefinition(featureSourceName, featureName, geometry, pointScaleRange);
            //---------------------------------------------------//
            // ...

            XmlDocument domDocument = new XmlDocument();
            domDocument.LoadXml(layerDefinition);

            //Add the layer to the map
            // TODO: Should probably validate this XML content
            using (MemoryStream ms = new MemoryStream())
            {
                domDocument.Save(ms);
                ms.Position = 0L;
                //Note we do this to ensure our XML content is free of any BOM characters
                byte[] ldfBytes = ms.ToArray();
                Encoding utf8 = Encoding.UTF8;
                String layerDefStr = new String(utf8.GetChars(ldfBytes));
                ldfBytes = new byte[layerDefStr.Length - 1];
                int byteCount = utf8.GetBytes(layerDefStr, 1, layerDefStr.Length - 1, ldfBytes, 0);
                // Save the new layer definition to the session repository  
                MgByteSource byteSource = new MgByteSource(ldfBytes, ldfBytes.Length);
                MgResourceIdentifier resourceID = new MgResourceIdentifier("Session:" + sessionId + "//" + layerName + ".LayerDefinition");
                resourceService.SetResource(resourceID, byteSource.GetReader(), null);

                //Insert this layer to our map
                MgdLayer newLayer = new MgdLayer(resourceID, resourceService);
                newLayer.Name = layerName;
                newLayer.LegendLabel = legendLabel;
                newLayer.DisplayInLegend = true;
                newLayer.SetVisible(true);
                layers.Insert(0, newLayer);

                //Create analysis group if not already created
                if (groups.IndexOf(groupName) < 0)
                {
                    MgLayerGroup group = new MgLayerGroup(groupName);
                    group.LegendLabel = groupName;
                    group.DisplayInLegend = true;
                    groups.Add(group);
                    newLayer.Group = group;
                }

                MessageBox.Show("Layer (" + layerName + ") created");
                _viewer.RefreshMap();
                IMapLegend legend = Shell.Instance.Legend;
                if (legend != null)
                    legend.RefreshLegend();
            }
        }
Esempio n. 30
0
        public override string QueryMapFeatures(RuntimeMap rtMap, int maxFeatures, string wkt, bool persist, string selectionVariant, QueryMapOptions extraOptions)
        {
            string runtimeMapName = rtMap.Name;
            MgRenderingService rs = this.Connection.CreateService(MgServiceType.RenderingService) as MgRenderingService;
            MgResourceService res = this.Connection.CreateService(MgServiceType.ResourceService) as MgResourceService;
            MgMap map = new MgMap();
            string mapname = runtimeMapName.IndexOf(":") > 0 ? new ResourceIdentifier(runtimeMapName).Path : runtimeMapName;
            map.Open(res, mapname);

            MgWktReaderWriter r = new MgWktReaderWriter();
            MgStringCollection layerNames = null;
            string featureFilter = "";
            int layerAttributeFilter = 0;
            int op = MgFeatureSpatialOperations.Intersects;
            if (selectionVariant == "TOUCHES")
                op = MgFeatureSpatialOperations.Touches;
            else if (selectionVariant == "INTERSECTS")
                op = MgFeatureSpatialOperations.Intersects;
            else if (selectionVariant == "WITHIN")
                op = MgFeatureSpatialOperations.Within;
            else if (selectionVariant == "ENVELOPEINTERSECTS")
                op = MgFeatureSpatialOperations.EnvelopeIntersects;
            else
                throw new ArgumentException("Unknown or unsupported selection variant: " + selectionVariant);

            if (extraOptions != null)
            {
                if (!string.IsNullOrEmpty(extraOptions.FeatureFilter))
                    featureFilter = extraOptions.FeatureFilter;
                if (extraOptions.LayerNames != null && extraOptions.LayerNames.Length > 0)
                {
                    layerNames = new MgStringCollection();
                    foreach (var name in extraOptions.LayerNames)
                        layerNames.Add(name);
                }
                layerAttributeFilter = (int)extraOptions.LayerAttributeFilter;
            }

            MgFeatureInformation info = rs.QueryFeatures(map, layerNames, r.Read(wkt), op, featureFilter, maxFeatures, layerAttributeFilter);

            string xml = "";
            GetByteReaderMethod fetch = () => { return info.ToXml(); };
            using (var sr = new StreamReader(new MgReadOnlyStream(fetch)))
            {
                xml = sr.ReadToEnd();
            }

            //We only want the FeatureSet element
            var doc = new System.Xml.XmlDocument();
            doc.LoadXml(xml);
            xml = doc.DocumentElement["FeatureSet"].OuterXml;

            MgSelection sel = new MgSelection(map, xml);
            sel.Save(res, mapname);

            LogMethodCall("QueryMapFeatures", true, runtimeMapName, wkt, persist, selectionVariant, extraOptions == null ? "null" : "QueryMapOptions");

            return xml;
        }
Esempio n. 31
0
        private void btnFindFeaturesInBuffer_Click(object sender, EventArgs e)
        {
            MgSelectionBase selection = _viewer.GetSelection();
            MgReadOnlyLayerCollection selectedLayers = selection.GetLayers();
            if (selectedLayers == null)
            {
                MessageBox.Show("Select a parcel");
                return;
            }
            MgLayerBase parcels = null;
            for (int i = 0; i < selectedLayers.GetCount(); i++)
            {
                MgLayerBase layer = selectedLayers.GetItem(i);
                if (layer.Name == "Parcels")
                {
                    parcels = layer;
                    break;
                }
            }
            if (parcels == null)
            {
                MessageBox.Show("Select a parcel");
                return;
            }

            int bufferRingSize = 500; // measured in metres

            // Set up some objects for coordinate conversion

            MgMapBase map = _viewer.GetMap();
            MgLayerCollection mapLayers = map.GetLayers();
            MgMapViewerProvider provider = _viewer.GetProvider();
            MgResourceService resourceService = (MgResourceService)provider.CreateService(MgServiceType.ResourceService);
            //Casting to MgdFeatureService because we want to use convenience APIs
            MgFeatureService featureService = (MgdFeatureService)provider.CreateService(MgServiceType.FeatureService);
            string sessionId = Guid.NewGuid().ToString();

            String mapWktSrs = map.GetMapSRS();
            MgAgfReaderWriter agfReaderWriter = new MgAgfReaderWriter();
            MgWktReaderWriter wktReaderWriter = new MgWktReaderWriter();
            MgCoordinateSystemFactory coordinateSystemFactory = new MgCoordinateSystemFactory();
            MgCoordinateSystem srs = coordinateSystemFactory.Create(mapWktSrs);
            MgMeasure srsMeasure = srs.GetMeasure();

            // Check for a buffer layer. If it exists, delete
            // the current features.
            // If it does not exist, create a feature source and
            // a layer to hold the buffer.

            BufferHelper helper = new BufferHelper();
            MgdLayer bufferLayer = null;
            int layerIndex = map.GetLayers().IndexOf("Buffer");
            if (layerIndex < 0)
            {
                // The layer does not exist and must be created.

                MgResourceIdentifier bufferFeatureResId = new MgResourceIdentifier("Session:" + sessionId + "//Buffer.FeatureSource");
                helper.CreateBufferFeatureSource(featureService, mapWktSrs, bufferFeatureResId);
                bufferLayer = helper.CreateBufferLayer(resourceService, bufferFeatureResId, sessionId);
                map.GetLayers().Insert(0, bufferLayer);
            }
            else
            {
                bufferLayer = (MgdLayer)map.GetLayers().GetItem(layerIndex);
                bufferLayer.DeleteFeatures("ID like '%'");
            }

            // Check for a parcel marker layer. If it exists, delete
            // the current features.
            // If it does not exist, create a feature source and
            // a layer to hold the parcel markers.

            MgdLayer parcelMarkerLayer = null;
            layerIndex = map.GetLayers().IndexOf("ParcelMarker");
            if (layerIndex < 0)
            {
                MgResourceIdentifier parcelFeatureResId = new MgResourceIdentifier("Session:" + sessionId + "//ParcelMarker.FeatureSource");
                helper.CreateParcelMarkerFeatureSource(featureService, mapWktSrs, parcelFeatureResId);
                parcelMarkerLayer = helper.CreateParcelMarkerLayer(resourceService, parcelFeatureResId, sessionId);
                map.GetLayers().Insert(0, parcelMarkerLayer);
            }
            else
            {
                parcelMarkerLayer = (MgdLayer)map.GetLayers().GetItem(layerIndex);
                parcelMarkerLayer.DeleteFeatures("ID like '%'");
            }

            // Check each layer in the selection.

            for (int i = 0; i < selectedLayers.GetCount(); i++)
            {
                // Only check selected features in the Parcels layer.

                MgdLayer layer = (MgdLayer)selectedLayers.GetItem(i);

                if (layer.GetName() == "Parcels")
                {
                    string geomName = layer.GetFeatureGeometryName();
                    System.Diagnostics.Trace.TraceInformation("Marking all parcels inside the buffer that are of type 'MFG'");

                    MgFeatureReader featureReader = selection.GetSelectedFeatures(layer, layer.GetFeatureClassName(), false);


                    // Process each item in the MgFeatureReader. Get the
                    // geometries from all the selected features and
                    // merge them into a single geometry.

                    MgGeometryCollection inputGeometries = new MgGeometryCollection();
                    while (featureReader.ReadNext())
                    {
                        MgByteReader featureGeometryData = featureReader.GetGeometry(geomName);
                        MgGeometry featureGeometry = agfReaderWriter.Read(featureGeometryData);

                        inputGeometries.Add(featureGeometry);
                    }

                    MgGeometryFactory geometryFactory = new MgGeometryFactory();
                    MgGeometry mergedGeometries = geometryFactory.CreateMultiGeometry(inputGeometries);

                    // Create a buffer from the merged geometries

                    double bufferDist = srs.ConvertMetersToCoordinateSystemUnits(bufferRingSize);
                    MgGeometry bufferGeometry = mergedGeometries.Buffer(bufferDist, srsMeasure);

                    // Create a filter to select parcels within the buffer. Combine
                    // a basic filter and a spatial filter to select all parcels
                    // within the buffer that are of type "MFG".

                    MgFeatureQueryOptions queryOptions = new MgFeatureQueryOptions();
                    queryOptions.SetFilter("RTYPE = 'MFG'");
                    queryOptions.SetSpatialFilter(geomName, bufferGeometry, MgFeatureSpatialOperations.Inside);

                    featureReader = layer.SelectFeatures(queryOptions);

                    // Get the features from the feature source,
                    // determine the centroid of each selected feature, and
                    // add a point to the ParcelMarker layer to mark the
                    // centroid.
                    // Collect all the points into an MgFeatureCommandCollection,
                    // so they can all be added in one operation.

                    MgFeatureCommandCollection parcelMarkerCommands = new MgFeatureCommandCollection();
                    int inserted = 0;
                    while (featureReader.ReadNext())
                    {
                        MgByteReader byteReader = featureReader.GetGeometry(geomName);
                        MgGeometry geometry = agfReaderWriter.Read(byteReader);
                        MgPoint point = geometry.GetCentroid();

                        // Create an insert command for this parcel.
                        MgPropertyCollection properties = new MgPropertyCollection();
                        properties.Add(new MgGeometryProperty("ParcelLocation", agfReaderWriter.Write(point)));
                        //parcelMarkerCommands.Add(new MgInsertFeatures("ParcelMarkerClass", properties));
                        MgFeatureReader fr = parcelMarkerLayer.InsertFeatures(properties);
                        fr.Close();
                        inserted++;
                    }
                    featureReader.Close();

                    if (inserted == 0)
                    {
                        MessageBox.Show("No parcels within the buffer area match.");
                        return;
                    }

                    // Create a feature in the buffer feature source to show the area covered by the buffer.

                    MgPropertyCollection props = new MgPropertyCollection();
                    props.Add(new MgGeometryProperty("BufferGeometry", agfReaderWriter.Write(bufferGeometry)));
                    bufferLayer.InsertFeatures(props);

                    // Ensure that the buffer layer is visible and in the legend.

                    bufferLayer.SetVisible(true);
                    bufferLayer.ForceRefresh();
                    bufferLayer.SetDisplayInLegend(true);
                    parcelMarkerLayer.SetVisible(true);
                    parcelMarkerLayer.ForceRefresh();

                    MessageBox.Show("Done");
                    _viewer.RefreshMap();
                    IMapLegend legend = Shell.Instance.Legend;
                    if (legend != null)
                        legend.RefreshLegend();
                }
            }
        }
Esempio n. 32
0
 static GeomConverter()
 {
     _agfRw  = new MgAgfReaderWriter();
     _wktRw  = new MgWktReaderWriter();
     _reader = new FixedWKTReader();
 }
Esempio n. 33
0
        private void bgGridLoader_DoWork(object sender, DoWorkEventArgs e)
        {
            var reader = (MgReader)e.Argument;
            var wktRw = new MgWktReaderWriter();
            var agfRw = new MgAgfReaderWriter();

            var cls = _layer.GetClassDefinition();
            var idProps = cls.GetIdentityProperties();
            var idNames = new List<string>();
            for (int i = 0; i < idProps.Count; i++)
            {
                var prop = idProps.GetItem(i);
                idNames.Add(prop.Name);
            }
            _identityProps = idNames.ToArray();

            var propNames = new List<string>();
            int propCount = reader.GetPropertyCount();
            //.net 2.0 compatibility hack for set-like behaviour
            var skipProps = new Dictionary<int, int>();
            for (int i = 0; i < propCount; i++)
            {
                var pt = reader.GetPropertyType(i);
                if (pt == MgPropertyType.Blob ||
                    pt == MgPropertyType.Clob ||
                    pt == MgPropertyType.Feature ||
                    pt == MgPropertyType.Null ||
                    pt == MgPropertyType.Raster)
                {
                    skipProps[i] = i;
                }
                else
                {
                    var name = reader.GetPropertyName(i);
                    _propMap.Add(name, pt);
                    propNames.Add(name);
                }
            }
            try
            {
                bgGridLoader.ReportProgress(-1, new InitGridAction() { ColumnNames = propNames.ToArray() });
                int read = 0;
                while (reader.ReadNext())
                {
                    object[] values = new object[propCount];
                    for (int i = 0; i < propCount; i++)
                    {
                        if (skipProps.ContainsKey(i))
                            continue;

                        if (reader.IsNull(i))
                        {
                            values[i] = null;
                        }
                        else
                        {
                            switch (reader.GetPropertyType(i))
                            {
                                case MgPropertyType.Boolean:
                                    values[i] = reader.GetBoolean(i);
                                    break;
                                case MgPropertyType.Byte:
                                    values[i] = reader.GetByte(i);
                                    break;
                                case MgPropertyType.DateTime:
                                    values[i] = ToClrDateTime(reader.GetDateTime(i));
                                    break;
                                case MgPropertyType.Decimal:
                                case MgPropertyType.Double:
                                    values[i] = reader.GetDouble(i);
                                    break;
                                case MgPropertyType.Geometry:
                                    {
                                        try
                                        {
                                            var agf = reader.GetGeometry(i);
                                            var geom = agfRw.Read(agf);
                                            var env = geom.Envelope();
                                            var envLL = env.LowerLeftCoordinate;
                                            var envUR = env.UpperRightCoordinate;
                                            var wkt = wktRw.Write(geom);

                                            values[i] = new BoxedGeometry()
                                            {
                                                Text = wkt,
                                                GeomBounds = new Bounds()
                                                {
                                                    LowerX = envLL.X,
                                                    LowerY = envLL.Y,
                                                    UpperX = envUR.X,
                                                    UpperY = envUR.Y
                                                }
                                            };
                                        }
                                        catch
                                        {
                                            values[i] = null;
                                        }
                                    }
                                    break;
                                case MgPropertyType.Int16:
                                    values[i] = reader.GetInt16(i);
                                    break;
                                case MgPropertyType.Int32:
                                    values[i] = reader.GetInt32(i);
                                    break;
                                case MgPropertyType.Int64:
                                    values[i] = reader.GetInt64(i);
                                    break;
                                case MgPropertyType.Single:
                                    values[i] = reader.GetSingle(i);
                                    break;
                                case MgPropertyType.String :
                                    values[i] = reader.GetString(i);
                                    break;
                            }
                        }
                    }
                    bgGridLoader.ReportProgress(-1, new AddRow() { Values = values });
                    read++;
                    if ((_limit > 0 && read >= _limit))
                        break;
                }
            }
            finally
            {
                reader.Close();
                wktRw.Dispose();
                agfRw.Dispose();
                wktRw = null;
                agfRw = null;
            }
        }
Esempio n. 34
0
        private void btnFindFeaturesInBuffer_Click(object sender, EventArgs e)
        {
            MgSelectionBase           selection      = _viewer.GetSelection();
            MgReadOnlyLayerCollection selectedLayers = selection.GetLayers();

            if (selectedLayers == null)
            {
                MessageBox.Show("Select a parcel");
                return;
            }
            MgLayerBase parcels = null;

            for (int i = 0; i < selectedLayers.GetCount(); i++)
            {
                MgLayerBase layer = selectedLayers.GetItem(i);
                if (layer.Name == "Parcels")
                {
                    parcels = layer;
                    break;
                }
            }
            if (parcels == null)
            {
                MessageBox.Show("Select a parcel");
                return;
            }

            int bufferRingSize = 500; // measured in metres

            // Set up some objects for coordinate conversion

            MgMapBase           map             = _viewer.GetMap();
            MgLayerCollection   mapLayers       = map.GetLayers();
            MgMapViewerProvider provider        = _viewer.GetProvider();
            MgResourceService   resourceService = (MgResourceService)provider.CreateService(MgServiceType.ResourceService);
            //Casting to MgdFeatureService because we want to use convenience APIs
            MgFeatureService featureService = (MgdFeatureService)provider.CreateService(MgServiceType.FeatureService);
            string           sessionId      = Guid.NewGuid().ToString();

            String                    mapWktSrs               = map.GetMapSRS();
            MgAgfReaderWriter         agfReaderWriter         = new MgAgfReaderWriter();
            MgWktReaderWriter         wktReaderWriter         = new MgWktReaderWriter();
            MgCoordinateSystemFactory coordinateSystemFactory = new MgCoordinateSystemFactory();
            MgCoordinateSystem        srs        = coordinateSystemFactory.Create(mapWktSrs);
            MgMeasure                 srsMeasure = srs.GetMeasure();

            // Check for a buffer layer. If it exists, delete
            // the current features.
            // If it does not exist, create a feature source and
            // a layer to hold the buffer.

            BufferHelper helper      = new BufferHelper();
            MgdLayer     bufferLayer = null;
            int          layerIndex  = map.GetLayers().IndexOf("Buffer");

            if (layerIndex < 0)
            {
                // The layer does not exist and must be created.

                MgResourceIdentifier bufferFeatureResId = new MgResourceIdentifier("Session:" + sessionId + "//Buffer.FeatureSource");
                helper.CreateBufferFeatureSource(featureService, mapWktSrs, bufferFeatureResId);
                bufferLayer = helper.CreateBufferLayer(resourceService, bufferFeatureResId, sessionId);
                map.GetLayers().Insert(0, bufferLayer);
            }
            else
            {
                bufferLayer = (MgdLayer)map.GetLayers().GetItem(layerIndex);
                bufferLayer.DeleteFeatures("ID like '%'");
            }

            // Check for a parcel marker layer. If it exists, delete
            // the current features.
            // If it does not exist, create a feature source and
            // a layer to hold the parcel markers.

            MgdLayer parcelMarkerLayer = null;

            layerIndex = map.GetLayers().IndexOf("ParcelMarker");
            if (layerIndex < 0)
            {
                MgResourceIdentifier parcelFeatureResId = new MgResourceIdentifier("Session:" + sessionId + "//ParcelMarker.FeatureSource");
                helper.CreateParcelMarkerFeatureSource(featureService, mapWktSrs, parcelFeatureResId);
                parcelMarkerLayer = helper.CreateParcelMarkerLayer(resourceService, parcelFeatureResId, sessionId);
                map.GetLayers().Insert(0, parcelMarkerLayer);
            }
            else
            {
                parcelMarkerLayer = (MgdLayer)map.GetLayers().GetItem(layerIndex);
                parcelMarkerLayer.DeleteFeatures("ID like '%'");
            }

            // Check each layer in the selection.

            for (int i = 0; i < selectedLayers.GetCount(); i++)
            {
                // Only check selected features in the Parcels layer.

                MgdLayer layer = (MgdLayer)selectedLayers.GetItem(i);

                if (layer.GetName() == "Parcels")
                {
                    string geomName = layer.GetFeatureGeometryName();
                    System.Diagnostics.Trace.TraceInformation("Marking all parcels inside the buffer that are of type 'MFG'");

                    MgFeatureReader featureReader = selection.GetSelectedFeatures(layer, layer.GetFeatureClassName(), false);


                    // Process each item in the MgFeatureReader. Get the
                    // geometries from all the selected features and
                    // merge them into a single geometry.

                    MgGeometryCollection inputGeometries = new MgGeometryCollection();
                    while (featureReader.ReadNext())
                    {
                        MgByteReader featureGeometryData = featureReader.GetGeometry(geomName);
                        MgGeometry   featureGeometry     = agfReaderWriter.Read(featureGeometryData);

                        inputGeometries.Add(featureGeometry);
                    }

                    MgGeometryFactory geometryFactory  = new MgGeometryFactory();
                    MgGeometry        mergedGeometries = geometryFactory.CreateMultiGeometry(inputGeometries);

                    // Create a buffer from the merged geometries

                    double     bufferDist     = srs.ConvertMetersToCoordinateSystemUnits(bufferRingSize);
                    MgGeometry bufferGeometry = mergedGeometries.Buffer(bufferDist, srsMeasure);

                    // Create a filter to select parcels within the buffer. Combine
                    // a basic filter and a spatial filter to select all parcels
                    // within the buffer that are of type "MFG".

                    MgFeatureQueryOptions queryOptions = new MgFeatureQueryOptions();
                    queryOptions.SetFilter("RTYPE = 'MFG'");
                    queryOptions.SetSpatialFilter(geomName, bufferGeometry, MgFeatureSpatialOperations.Inside);

                    featureReader = layer.SelectFeatures(queryOptions);

                    // Get the features from the feature source,
                    // determine the centroid of each selected feature, and
                    // add a point to the ParcelMarker layer to mark the
                    // centroid.
                    // Collect all the points into an MgFeatureCommandCollection,
                    // so they can all be added in one operation.

                    MgFeatureCommandCollection parcelMarkerCommands = new MgFeatureCommandCollection();
                    int inserted = 0;
                    while (featureReader.ReadNext())
                    {
                        MgByteReader byteReader = featureReader.GetGeometry(geomName);
                        MgGeometry   geometry   = agfReaderWriter.Read(byteReader);
                        MgPoint      point      = geometry.GetCentroid();

                        // Create an insert command for this parcel.
                        MgPropertyCollection properties = new MgPropertyCollection();
                        properties.Add(new MgGeometryProperty("ParcelLocation", agfReaderWriter.Write(point)));
                        //parcelMarkerCommands.Add(new MgInsertFeatures("ParcelMarkerClass", properties));
                        MgFeatureReader fr = parcelMarkerLayer.InsertFeatures(properties);
                        fr.Close();
                        inserted++;
                    }
                    featureReader.Close();

                    if (inserted == 0)
                    {
                        MessageBox.Show("No parcels within the buffer area match.");
                        return;
                    }

                    // Create a feature in the buffer feature source to show the area covered by the buffer.

                    MgPropertyCollection props = new MgPropertyCollection();
                    props.Add(new MgGeometryProperty("BufferGeometry", agfReaderWriter.Write(bufferGeometry)));
                    bufferLayer.InsertFeatures(props);

                    // Ensure that the buffer layer is visible and in the legend.

                    bufferLayer.SetVisible(true);
                    bufferLayer.ForceRefresh();
                    bufferLayer.SetDisplayInLegend(true);
                    parcelMarkerLayer.SetVisible(true);
                    parcelMarkerLayer.ForceRefresh();

                    MessageBox.Show("Done");
                    _viewer.RefreshMap();
                    IMapLegend legend = Shell.Instance.Legend;
                    if (legend != null)
                    {
                        legend.RefreshLegend();
                    }
                }
            }
        }
Esempio n. 35
0
 private ReaderResponseDialog()
 {
     InitializeComponent();
     _wktRW = new MgWktReaderWriter();
     _agfRW = new MgAgfReaderWriter();
 }
Esempio n. 36
0
    //----------------------------------------------------------------------------------------
    // �� �ܣ� ���ڴ�������ݣ�x��y�������ռ��Ҫ������
    //
    // �� �ߣ�
    //
    //
    // �� �ڣ�2007.05.#
    //
    //-----------------------------------------------------------------------------------------
    public MgPropertyCollection MakePoint(string name, double x, double y)
    {
        MgPropertyCollection propertyCollection = new MgPropertyCollection();
        MgStringProperty nameProperty = new MgStringProperty("NAME", name);
        propertyCollection.Add(nameProperty);

        MgWktReaderWriter wktReaderWriter = new MgWktReaderWriter();
        MgAgfReaderWriter agfReaderWriter = new MgAgfReaderWriter();

        MgGeometry geometry = wktReaderWriter.Read("POINT XY (" + x.ToString() + " " + y.ToString() + ")");
        MgByteReader geometryByteReader = agfReaderWriter.Write(geometry);
        MgGeometryProperty geometryProperty = new MgGeometryProperty("GEOM", geometryByteReader);
        propertyCollection.Add(geometryProperty);

        return propertyCollection;
    }
Esempio n. 37
0
        /// <summary>
        /// Initializes this viewer with the specified viewer provider, if the provider contains a map
        /// it will load that as well. Otherwise a call to <see cref="LoadMap"/> is required afterwards
        /// </summary>
        /// <param name="provider">The provider.</param>
        public void Init(MgMapViewerProvider provider)
        {
            if (_agfRW == null)
                _agfRW = new MgAgfReaderWriter();

            if (_wktRW == null)
                _wktRW = new MgWktReaderWriter();

            if (_geomFact == null)
                _geomFact = new MgGeometryFactory();

            _provider = provider;

            if (_resSvc != null) //Forward looking, dispose the existing one as it may be of a different implementation
            {
                _resSvc.Dispose();
                _resSvc = null;
            }
            _resSvc = (MgResourceService)_provider.CreateService(MgServiceType.ResourceService);

            _overlayRenderOpts = CreateMapRenderingOptions(0, 0, 255);
            _selectionRenderOpts = CreateSelectionRenderingOptions(0, 0, 255);

            if (_provider != null)
            {
                _provider.MapLoaded -= OnMapSetOnProvider;
                _provider = null;
            }

            _provider = provider;
            _provider.MapLoaded += OnMapSetOnProvider;
            var map = _provider.GetMap();
            if (map != null)
                OnMapSetOnProvider(this, EventArgs.Empty);
        }
Esempio n. 38
0
        /// <summary>
        /// Releases the unmanaged resources used by the <see cref="T:System.Windows.Forms.Control"/> and its child controls and optionally releases the managed resources.
        /// </summary>
        /// <param name="disposing">true to release both managed and unmanaged resources; false to release only unmanaged resources.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                base.MouseUp -= OnMapMouseUp;
                base.MouseMove -= OnMapMouseMove;
                base.MouseDown -= OnMapMouseDown;
                base.MouseClick -= OnMapMouseClick;
                base.MouseDoubleClick -= OnMapMouseDoubleClick;
                base.MouseHover -= OnMapMouseHover;
                base.MouseEnter -= OnMouseEnter;
                base.MouseLeave -= OnMapMouseLeave;

                if (renderWorker != null)
                {
                    renderWorker.DoWork -= renderWorker_DoWork;
                    renderWorker.RunWorkerCompleted -= renderWorker_RunWorkerCompleted;
                }

                if (_csFact != null)
                {
                    _csFact.Dispose();
                    _csFact = null;
                }

                if (_resSvc != null)
                {
                    _resSvc.Dispose();
                    _resSvc = null;
                }

                if (_selection != null)
                {
                    _selection.Dispose();
                    _selection = null;
                }

                if (_mapCs != null)
                {
                    _mapCs.Dispose();
                    _mapCs = null;
                }

                if (_agfRW != null)
                {
                    _agfRW.Dispose();
                    _agfRW = null;
                }

                if (_wktRW != null)
                {
                    _wktRW.Dispose();
                    _wktRW = null;
                }

                if (_geomFact != null)
                {
                    _geomFact.Dispose();
                    _geomFact = null;
                }

                if (_mapMeasure != null)
                {
                    _mapMeasure.Dispose();
                    _mapMeasure = null;
                }
            }
            base.Dispose(disposing);
        }
Esempio n. 39
0
 void OnDisposed(object sender, EventArgs e)
 {
     _properties.Clear();
     _layers.Clear();
     _wktRw.Dispose();
     _wktRw = null;
     _geomFact.Dispose();
     _geomFact = null;
 }
Esempio n. 40
0
        private void bgGridLoader_DoWork(object sender, DoWorkEventArgs e)
        {
            var reader = (MgReader)e.Argument;
            var wktRw  = new MgWktReaderWriter();
            var agfRw  = new MgAgfReaderWriter();

            var cls     = _layer.GetClassDefinition();
            var idProps = cls.GetIdentityProperties();
            var idNames = new List <string>();

            for (int i = 0; i < idProps.Count; i++)
            {
                var prop = idProps.GetItem(i);
                idNames.Add(prop.Name);
            }
            _identityProps = idNames.ToArray();

            var propNames = new List <string>();
            int propCount = reader.GetPropertyCount();
            //.net 2.0 compatibility hack for set-like behaviour
            var skipProps = new Dictionary <int, int>();

            for (int i = 0; i < propCount; i++)
            {
                var pt = reader.GetPropertyType(i);
                if (pt == MgPropertyType.Blob ||
                    pt == MgPropertyType.Clob ||
                    pt == MgPropertyType.Feature ||
                    pt == MgPropertyType.Null ||
                    pt == MgPropertyType.Raster)
                {
                    skipProps[i] = i;
                }
                else
                {
                    var name = reader.GetPropertyName(i);
                    _propMap.Add(name, pt);
                    propNames.Add(name);
                }
            }
            try
            {
                bgGridLoader.ReportProgress(-1, new InitGridAction()
                {
                    ColumnNames = propNames.ToArray()
                });
                int read = 0;
                while (reader.ReadNext())
                {
                    object[] values = new object[propCount];
                    for (int i = 0; i < propCount; i++)
                    {
                        if (skipProps.ContainsKey(i))
                        {
                            continue;
                        }

                        if (reader.IsNull(i))
                        {
                            values[i] = null;
                        }
                        else
                        {
                            switch (reader.GetPropertyType(i))
                            {
                            case MgPropertyType.Boolean:
                                values[i] = reader.GetBoolean(i);
                                break;

                            case MgPropertyType.Byte:
                                values[i] = reader.GetByte(i);
                                break;

                            case MgPropertyType.DateTime:
                                values[i] = ToClrDateTime(reader.GetDateTime(i));
                                break;

                            case MgPropertyType.Decimal:
                            case MgPropertyType.Double:
                                values[i] = reader.GetDouble(i);
                                break;

                            case MgPropertyType.Geometry:
                            {
                                try
                                {
                                    var agf   = reader.GetGeometry(i);
                                    var geom  = agfRw.Read(agf);
                                    var env   = geom.Envelope();
                                    var envLL = env.LowerLeftCoordinate;
                                    var envUR = env.UpperRightCoordinate;
                                    var wkt   = wktRw.Write(geom);

                                    values[i] = new BoxedGeometry()
                                    {
                                        Text       = wkt,
                                        GeomBounds = new Bounds()
                                        {
                                            LowerX = envLL.X,
                                            LowerY = envLL.Y,
                                            UpperX = envUR.X,
                                            UpperY = envUR.Y
                                        }
                                    };
                                }
                                catch
                                {
                                    values[i] = null;
                                }
                            }
                            break;

                            case MgPropertyType.Int16:
                                values[i] = reader.GetInt16(i);
                                break;

                            case MgPropertyType.Int32:
                                values[i] = reader.GetInt32(i);
                                break;

                            case MgPropertyType.Int64:
                                values[i] = reader.GetInt64(i);
                                break;

                            case MgPropertyType.Single:
                                values[i] = reader.GetSingle(i);
                                break;

                            case MgPropertyType.String:
                                values[i] = reader.GetString(i);
                                break;
                            }
                        }
                    }
                    bgGridLoader.ReportProgress(-1, new AddRow()
                    {
                        Values = values
                    });
                    read++;
                    if ((_limit > 0 && read >= _limit))
                    {
                        break;
                    }
                }
            }
            finally
            {
                reader.Close();
                wktRw.Dispose();
                agfRw.Dispose();
                wktRw = null;
                agfRw = null;
            }
        }
Esempio n. 41
0
        private void btnCreatePointsOfInterest_Click(object sender, EventArgs e)
        {
            string layerName   = "Points";
            string legendLabel = "Points of Interest";
            string groupName   = "Analysis";

            MgMapViewerProvider provider        = _viewer.GetProvider();
            MgResourceService   resourceService = (MgResourceService)provider.CreateService(MgServiceType.ResourceService);
            //We use MgdFeatureService instead of MgFeatureService as this sample demonstrates APIs unique to mg-desktop
            MgdFeatureService featureService = (MgdFeatureService)provider.CreateService(MgServiceType.FeatureService);

            MgMapBase              map    = _viewer.GetMap();
            MgLayerCollection      layers = map.GetLayers();
            MgLayerGroupCollection groups = map.GetLayerGroups();

            //NOTE: mg-desktop has no formal concept of a session repository, but we still
            //support session-based resources as a form of temporary resource (for the duration
            //of the application). Session ids in mg-desktop can be any arbitrary string
            string sessionId = Guid.NewGuid().ToString();

            if (layers.IndexOf(layerName) >= 0)
            {
                MessageBox.Show("Layer (" + layerName + ") already created");
                return;
            }

            //---------------------------------------------------//
            // Create a feature source with point data.
            // (The Sheboygan sample data does not contain such data,
            // so we"ll create it.)

            // Create a feature class definition for the new feature source
            MgClassDefinition classDefinition = new MgClassDefinition();

            classDefinition.SetName("Points");
            classDefinition.SetDescription("Feature class with point data.");
            classDefinition.SetDefaultGeometryPropertyName("GEOM");

            MgPropertyDefinitionCollection idProps  = classDefinition.GetIdentityProperties();
            MgPropertyDefinitionCollection clsProps = classDefinition.GetProperties();

            // Create an identify property
            MgDataPropertyDefinition identityProperty = new MgDataPropertyDefinition("KEY");

            identityProperty.SetDataType(MgPropertyType.Int32);
            identityProperty.SetAutoGeneration(true);
            identityProperty.SetReadOnly(true);
            // Add the identity property to the class definition
            clsProps.Add(identityProperty);
            idProps.Add(identityProperty);

            // Create a name property
            MgDataPropertyDefinition nameProperty = new MgDataPropertyDefinition("NAME");

            nameProperty.SetDataType(MgPropertyType.String);
            // Add the name property to the class definition
            clsProps.Add(nameProperty);

            // Create a geometry property
            MgGeometricPropertyDefinition geometryProperty = new MgGeometricPropertyDefinition("GEOM");

            geometryProperty.SetGeometryTypes(MgFeatureGeometricType.Point);
            // Add the geometry property to the class definition
            clsProps.Add(geometryProperty);

            // Create a feature schema
            MgFeatureSchema             featureSchema = new MgFeatureSchema("PointSchema", "Point schema");
            MgClassDefinitionCollection classes       = featureSchema.GetClasses();

            // Add the feature schema to the class definition
            classes.Add(classDefinition);

            // Create the feature source
            String featureSourceName = "Library://Samples/DevGuide/Data/points.FeatureSource";
            MgResourceIdentifier resourceIdentifier = new MgResourceIdentifier(featureSourceName);
            //wkt = "LOCALCS[\"*XY-MT*\",LOCAL_DATUM[\"*X-Y*\",10000],UNIT[\"Meter\", 1],AXIS[\"X\",EAST],AXIS[\"Y\",NORTH]]";
            String wkt = "GEOGCS[\"LL84\",DATUM[\"WGS84\",SPHEROID[\"WGS84\",6378137.000,298.25722293]],PRIMEM[\"Greenwich\",0],UNIT[\"Degree\",0.01745329251994]]";
            MgFileFeatureSourceParams sdfParams = new MgFileFeatureSourceParams("OSGeo.SDF", "LatLong", wkt, featureSchema);

            featureService.CreateFeatureSource(resourceIdentifier, sdfParams);

            // We need to add some data to the sdf before using it.  The spatial context
            // reader must have an extent.
            MgBatchPropertyCollection batchPropertyCollection = new MgBatchPropertyCollection();
            MgWktReaderWriter         wktReaderWriter         = new MgWktReaderWriter();
            MgAgfReaderWriter         agfReaderWriter         = new MgAgfReaderWriter();
            MgGeometryFactory         geometryFactory         = new MgGeometryFactory();

            // Make four points
            batchPropertyCollection.Add(MakePoint("Point A", -87.727, 43.748, wktReaderWriter, agfReaderWriter));

            batchPropertyCollection.Add(MakePoint("Point B", -87.728, 43.730, wktReaderWriter, agfReaderWriter));

            batchPropertyCollection.Add(MakePoint("Point C", -87.726, 43.750, wktReaderWriter, agfReaderWriter));

            batchPropertyCollection.Add(MakePoint("Point D", -87.728, 43.750, wktReaderWriter, agfReaderWriter));

            // Old way commented out

            /*
             * // Add the batch property collection to the feature source
             * MgInsertFeatures cmd = new MgInsertFeatures("Points", batchPropertyCollection);
             * MgFeatureCommandCollection featureCommandCollection = new MgFeatureCommandCollection();
             * featureCommandCollection.Add(cmd);
             *
             * // Execute the "add" commands
             * featureService.UpdateFeatures(resourceIdentifier, featureCommandCollection, false);
             */

            // Here's the mg-desktop way
            MgFeatureReader insertResult = featureService.InsertFeatures(resourceIdentifier, "Points", batchPropertyCollection);

            insertResult.Close();

            // ...
            //---------------------------------------------------//
            // Create a new layer

            LayerDefinitionFactory factory = new LayerDefinitionFactory();

            // Create a mark symbol
            String resourceId = "Library://Samples/Sheboygan/Symbols/BasicSymbols.SymbolLibrary";
            String symbolName = "PushPin";
            String width      = "24"; // unit = points
            String height     = "24"; // unit = points
            String color      = "FFFF0000";
            String markSymbol = factory.CreateMarkSymbol(resourceId, symbolName, width, height, color);

            // Create a text symbol
            String text            = "ID";
            String fontHeight      = "12";
            String foregroundColor = "FF000000";
            String textSymbol      = factory.CreateTextSymbol(text, fontHeight, foregroundColor);

            // Create a point rule.
            String ruleLegendLabel = "trees";
            String filter          = "";
            String pointRule       = factory.CreatePointRule(ruleLegendLabel, filter, textSymbol, markSymbol);

            // Create a point type style.
            String pointTypeStyle = factory.CreatePointTypeStyle(pointRule);

            // Create a scale range.
            String minScale        = "0";
            String maxScale        = "1000000000000";
            String pointScaleRange = factory.CreateScaleRange(minScale, maxScale, pointTypeStyle);

            // Create the layer definiton.
            String featureName     = "PointSchema:Points";
            String geometry        = "GEOM";
            String layerDefinition = factory.CreateLayerDefinition(featureSourceName, featureName, geometry, pointScaleRange);
            //---------------------------------------------------//
            // ...

            XmlDocument domDocument = new XmlDocument();

            domDocument.LoadXml(layerDefinition);

            //Add the layer to the map
            // TODO: Should probably validate this XML content
            using (MemoryStream ms = new MemoryStream())
            {
                domDocument.Save(ms);
                ms.Position = 0L;
                //Note we do this to ensure our XML content is free of any BOM characters
                byte[]   ldfBytes    = ms.ToArray();
                Encoding utf8        = Encoding.UTF8;
                String   layerDefStr = new String(utf8.GetChars(ldfBytes));
                ldfBytes = new byte[layerDefStr.Length - 1];
                int byteCount = utf8.GetBytes(layerDefStr, 1, layerDefStr.Length - 1, ldfBytes, 0);
                // Save the new layer definition to the session repository
                MgByteSource         byteSource = new MgByteSource(ldfBytes, ldfBytes.Length);
                MgResourceIdentifier resourceID = new MgResourceIdentifier("Session:" + sessionId + "//" + layerName + ".LayerDefinition");
                resourceService.SetResource(resourceID, byteSource.GetReader(), null);

                //Insert this layer to our map
                MgdLayer newLayer = new MgdLayer(resourceID, resourceService);
                newLayer.Name            = layerName;
                newLayer.LegendLabel     = legendLabel;
                newLayer.DisplayInLegend = true;
                newLayer.SetVisible(true);
                layers.Insert(0, newLayer);

                //Create analysis group if not already created
                if (groups.IndexOf(groupName) < 0)
                {
                    MgLayerGroup group = new MgLayerGroup(groupName);
                    group.LegendLabel     = groupName;
                    group.DisplayInLegend = true;
                    groups.Add(group);
                    newLayer.Group = group;
                }

                MessageBox.Show("Layer (" + layerName + ") created");
                _viewer.RefreshMap();
                IMapLegend legend = Shell.Instance.Legend;
                if (legend != null)
                {
                    legend.RefreshLegend();
                }
            }
        }
Esempio n. 42
0
 static GeomConverter()
 {
     _agfRw = new MgAgfReaderWriter();
     _wktRw = new MgWktReaderWriter();
 }
        public LocalNativeRecord(MgReader reader, FixedWKTReader mgReader, MgAgfReaderWriter agfRw, MgWktReaderWriter wktRw)
        {
            for (int i = 0; i < reader.GetPropertyCount(); i++)
            {
                string name = reader.GetPropertyName(i);

                _ordinalMap[i] = name;

                var pt = (PropertyValueType)reader.GetPropertyType(name);
                switch (pt)
                {
                    case PropertyValueType.Blob:
                        _values[name] = new BlobValue();
                        break;

                    case PropertyValueType.Boolean:
                        _values[name] = new BooleanValue();
                        break;

                    case PropertyValueType.Byte:
                        _values[name] = new ByteValue();
                        break;

                    case PropertyValueType.Clob:
                        _values[name] = new ClobValue();
                        break;

                    case PropertyValueType.DateTime:
                        _values[name] = new DateTimeValue();
                        break;

                    case PropertyValueType.Double:
                        _values[name] = new DoubleValue();
                        break;

                    case PropertyValueType.Feature:
                        _values[name] = new FeatureValue();
                        break;

                    case PropertyValueType.Geometry:
                        _values[name] = new GeometryValue();
                        break;

                    case PropertyValueType.Int16:
                        _values[name] = new Int16Value();
                        break;

                    case PropertyValueType.Int32:
                        _values[name] = new Int32Value();
                        break;

                    case PropertyValueType.Int64:
                        _values[name] = new Int64Value();
                        break;

                    case PropertyValueType.Raster:
                        _values[name] = new RasterValue();
                        break;

                    case PropertyValueType.Single:
                        _values[name] = new SingleValue();
                        break;

                    case PropertyValueType.String:
                        _values[name] = new StringValue();
                        break;
                }
            }

            for (int i = 0; i < reader.GetPropertyCount(); i++)
            {
                string name = _ordinalMap[i];
                GetByteReaderMethod getblob = () => { return reader.GetBLOB(name); };
                GetByteReaderMethod getclob = () => { return reader.GetCLOB(name); };
                GetByteReaderMethod getgeom = () => { return reader.GetGeometry(name); };
                if (!reader.IsNull(name))
                {
                    var pt = (PropertyValueType)reader.GetPropertyType(name);
                    switch (pt)
                    {
                        case PropertyValueType.Blob:
                            ((BlobValue)_values[name]).Value = Utility.StreamAsArray(new MgReadOnlyStream(getblob));
                            break;

                        case PropertyValueType.Boolean:
                            ((BooleanValue)_values[name]).Value = reader.GetBoolean(name);
                            break;

                        case PropertyValueType.Byte:
                            ((ByteValue)_values[name]).Value = reader.GetByte(name);
                            break;

                        case PropertyValueType.Clob:
                            byte[] b = Utility.StreamAsArray(new MgReadOnlyStream(getclob));
                            ((ClobValue)_values[name]).Value = Encoding.UTF8.GetChars(b);
                            break;

                        case PropertyValueType.DateTime:
                            ((DateTimeValue)_values[name]).Value = Utility.ConvertMgDateTime(reader.GetDateTime(name));
                            break;

                        case PropertyValueType.Double:
                            ((DoubleValue)_values[name]).Value = reader.GetDouble(name);
                            break;
                        //case PropertyValueType.Feature:
                        case PropertyValueType.Geometry:
                            try
                            {
                                //TODO: See if SWIG issues come into play here
                                var geom = agfRw.Read(reader.GetGeometry(name));
                                var wkt = wktRw.Write(geom);
                                ((GeometryValue)_values[name]).Value = mgReader.Read(wkt);
                            }
                            catch //Invalid geometry fail!
                            {
                                ((GeometryValue)_values[name]).SetNull();
                            }
                            break;

                        case PropertyValueType.Int16:
                            ((Int16Value)_values[name]).Value = reader.GetInt16(name);
                            break;

                        case PropertyValueType.Int32:
                            ((Int32Value)_values[name]).Value = reader.GetInt32(name);
                            break;

                        case PropertyValueType.Int64:
                            ((Int64Value)_values[name]).Value = reader.GetInt64(name);
                            break;

                        case PropertyValueType.Single:
                            ((SingleValue)_values[name]).Value = reader.GetSingle(name);
                            break;

                        case PropertyValueType.String:
                            ((StringValue)_values[name]).Value = reader.GetString(name);
                            break;
                    }
                }
            }
        }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            string sessionId = GetRequestParameters(Request)["SESSION"];
            string mapName = GetRequestParameters(Request)["MAPNAME"];
            string locale = GetRequestParameters(Request)["LOCALE"];

            if (string.IsNullOrEmpty(sessionId))
            {
                Response.Clear();
                Response.End();
                return;
            }

            if (string.IsNullOrEmpty(mapName))
            {
                Response.Clear();
                Response.End();
                return;
            }

            MgResourceService resourceSrvc = GetMgResurceService(sessionId);
            MgFeatureService featureSrvc = GetMgFeatureService(sessionId);

            MgMap map = new MgMap();
            map.Open(resourceSrvc, mapName);

            string layernames = GetRequestParameters(Request)["LAYERNAMES"];
            string GEOMETRY = GetRequestParameters(Request)["GEOMETRY"];
            string selVar = GetRequestParameters(Request)["SELECTIONVARIANT"];
            string type = GetRequestParameters(Request)["tp"];
            string inputSel = GetRequestParameters(Request)["SELECTION"];

            bool hasInputGeom = false;
            if (!string.IsNullOrEmpty(GEOMETRY))
            {
                hasInputGeom = true;
            }

            //selection ima prednost pred podano geometrijo ...
            MgWktReaderWriter wktrw = new MgWktReaderWriter();
            if (!string.IsNullOrEmpty(inputSel))
            {
                MgGeometry inputGeom = MultiGeometryFromSelection(featureSrvc, map, inputSel);
                GEOMETRY = wktrw.Write(inputGeom);
            }

            MgAgfReaderWriter agfRW = new MgAgfReaderWriter();

            int nLayer = 0;
            // pobrišem in zgradim na novo samo tiste, ki imajo zadetke ...
            int nSloj = 0;
            string filter = "";
            StringBuilder sbOut = new StringBuilder();
            sbOut.Append("<table width=\"100%\" class=\"results\">");
            sbOut.Append("<tr><td class='header'></td><td class='header'>" + "Layer" + "</td><td class='header' align=\"center\">" + "Select" + "</td><td class='header' align=\"center\">" + "Report" + "</td></tr>");

            MgSelection selAll = new MgSelection(map);

            foreach (MgLayer layer in map.GetLayers())
            {
                if (type != "2")
                {
                    if (!layer.IsVisible())
                    {
                        goto nextlay;
                    }
                }

                if (layer.LegendLabel == "")
                {
                    goto nextlay;
                }

                try
                {
                    nLayer++;

                    filter = String.Format("{0} {1} GeomFromText('{2}')", layer.GetFeatureGeometryName(), selVar, GEOMETRY);

                    //preveriti še filter na Layerju. Ker ne gre drugače, je potrebno pogledati v XML
                    MgResourceIdentifier layerDefResId = layer.GetLayerDefinition();
                    MgByteReader byteReader = resourceSrvc.GetResourceContent(layerDefResId);

                    System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
                    String xmlLayerDef = byteReader.ToString();
                    doc.LoadXml(xmlLayerDef);

                    KALI.MGE.Objects.KALILayerDefinition.LayerDefinition ld = KALI.MGE.Objects.KALILayerDefinition.LayerDefinition.Parse(xmlLayerDef);

                    if (!string.IsNullOrEmpty(ld.VectorLayerDefinition.Filter))
                    {
                        filter += " AND (" + ld.VectorLayerDefinition.Filter + ")";
                    }

                    //query the features
                    MgFeatureQueryOptions opts = new MgFeatureQueryOptions();
                    opts.SetFilter(filter);
                    String featureClassName = layer.GetFeatureClassName();
                    MgResourceIdentifier srcId = new MgResourceIdentifier(layer.GetFeatureSourceId());

                    MgFeatureReader features = featureSrvc.SelectFeatures(srcId, featureClassName, opts);

                    bool hasResult = features.ReadNext();

                    if (hasResult)
                    {
                        nSloj++;

                        int n = 0;

                        MgClassDefinition classDef = features.GetClassDefinition();

                        MgPropertyDefinitionCollection classDefProps = classDef.GetIdentityProperties();
                        ArrayList idPropNames = new ArrayList(classDefProps.GetCount());
                        for (int j = 0; j < classDefProps.GetCount(); j++)
                        {
                            MgPropertyDefinition idProp = classDefProps.GetItem(j);
                            idPropNames.Add(idProp.GetName());
                        }

                        MgSelection sel = new MgSelection(map);
                        do
                        {
                            // Generate XML to selection this feature
                            MgPropertyCollection idProps = new MgPropertyCollection();
                            foreach (string id in idPropNames)
                            {
                                int idPropType = features.GetPropertyType(id);
                                switch (idPropType)
                                {
                                    case MgPropertyType.Int32:
                                        idProps.Add(new MgInt32Property(id, features.GetInt32(id)));
                                        break;
                                    case MgPropertyType.String:
                                        idProps.Add(new MgStringProperty(id, features.GetString(id)));
                                        break;
                                    case MgPropertyType.Int64:
                                        idProps.Add(new MgInt64Property(id, features.GetInt64(id)));
                                        break;
                                    case MgPropertyType.Double:
                                        idProps.Add(new MgDoubleProperty(id, features.GetDouble(id)));
                                        break;
                                    case MgPropertyType.Single:
                                        idProps.Add(new MgSingleProperty(id, features.GetSingle(id)));
                                        break;
                                    case MgPropertyType.DateTime:
                                        idProps.Add(new MgDateTimeProperty(id, features.GetDateTime(id)));
                                        break;
                                    default:
                                        //throw new SearchError(String.Format(MgLocalizer.GetString("SEARCHTYYPENOTSUP", locale), new Object[] { idPropType.ToString() }), searchError);
                                        break;
                                }
                            }

                            sel.AddFeatureIds(layer, featureClassName, idProps);
                            selAll.AddFeatureIds(layer, featureClassName, idProps);

                            n++;

                            //if (n > 1000) break;
                        } while (features.ReadNext());

                        features.Close();
                        features.Dispose();

                        string selText = EscapeForHtml(sel.ToXml());
                        string seljs = "<div class=\"allLay\" onclick=\"parent.SetSelectionXML('" + selText + "');\"><img width=\"16\" height=\"16\" style=\"border:0\" src=\"images/mActionZoomToSelected.png\"/></div>";
                        string seljs3 = "<div class=\"allLay\" onclick=\"parent.MultiGridShow('" + selText + "');\"><img width=\"16\" height=\"16\" style=\"border:0\" src=\"images/mActionOpenTable.png\"/></div>";

                        string linfo = "<b>" + layer.LegendLabel + "</b><br />" + n.ToString() + " " + "Hits";
                        sbOut.Append("<tr><td class=\"results\">" + nSloj.ToString() + "</td><td class=\"results\">" + linfo + "</td><td align=\"center\" class=\"results\">" + seljs + "</td><td align=\"center\" class=\"results\">" + seljs3 + "</td></tr>");
                    }
                }
                catch (Exception)
                {
                    continue;
                }

            nextlay:
                continue;
            }

            sbOut.Append("</table>");

            string selAllText = EscapeForHtml(selAll.ToXml());
            string seljsAll = "<div class=\"allLay\" onclick=\"parent.SetSelectionXML('" + selAllText + "');\"><img width=\"16\" height=\"16\" style=\"border:0\" src=\"images/mActionZoomToSelected.png\"/>" + "Select All" + "</div>";
            string seljsAll3 = "<div class=\"allLay\" onclick=\"parent.MultiGridShow('" + selAllText + "');\"><img width=\"16\" height=\"16\" style=\"border:0\" src=\"images/mActionOpenTable.png\"/>" + "Report All" + "</div>";

            sbOut.Append(string.Format("<br /><table width=\"100%\" class=\"results\"><tr><td class=\"results\">{0}</td><td class=\"results\">{1}</td></tr></table>", seljsAll, seljsAll3));

            featureSrvc.Dispose();
            resourceSrvc.Dispose();

            if (nSloj > 0)
            {
                litPrebodi.Text = sbOut.ToString();
            }
            else
            {
                litPrebodiTitle.Visible = false;
                litPrebodi.Text = "<b>" + "None layer lies below the selected item/area!" + "</b>";
            }

            MgGeometry inGeom = wktrw.Read(GEOMETRY);

            double rw = map.ViewScale / Math.Sqrt(inGeom.Area);

            //koordinate
            if (hasInputGeom & rw > 400)
            {
                string output = "";

                output = pointTransformAndWriteZ(GEOMETRY, map);

                litKoordinate.Text = output;
                litKoordinateTitle.Text = "Coordinates of selected points:";
            }
        }
    }
Esempio n. 45
0
        public string QueryMapFeatures(RuntimeMap rtMap, int maxFeatures, string wkt, bool persist, string selectionVariant, QueryMapOptions extraOptions)
        {
            var impl = rtMap as LocalRuntimeMap;
            if (impl == null)
                throw new ArgumentException("Instance is not a LocalRuntimeMap", "map"); //LOCALIZEME

            var rs = GetRenderingService();
            var res = GetResourceService();
            var map = impl.GetWrappedInstance();

            MgWktReaderWriter r = new MgWktReaderWriter();
            MgStringCollection layerNames = null;
            string featureFilter = "";
            int layerAttributeFilter = 0;
            int op = MgFeatureSpatialOperations.Intersects;
            if (selectionVariant == "TOUCHES")
                op = MgFeatureSpatialOperations.Touches;
            else if (selectionVariant == "INTERSECTS")
                op = MgFeatureSpatialOperations.Intersects;
            else if (selectionVariant == "WITHIN")
                op = MgFeatureSpatialOperations.Within;
            else if (selectionVariant == "ENVELOPEINTERSECTS")
                op = MgFeatureSpatialOperations.EnvelopeIntersects;
            else
                throw new ArgumentException("Unknown or unsupported selection variant: " + selectionVariant);

            if (extraOptions != null)
            {
                if (!string.IsNullOrEmpty(extraOptions.FeatureFilter))
                    featureFilter = extraOptions.FeatureFilter;
                if (extraOptions.LayerNames != null && extraOptions.LayerNames.Length > 0)
                {
                    layerNames = new MgStringCollection();
                    foreach (var name in extraOptions.LayerNames)
                        layerNames.Add(name);
                }
                layerAttributeFilter = (int)extraOptions.LayerAttributeFilter;
            }

            MgdFeatureInformation info = rs.QueryFeatures(map, layerNames, r.Read(wkt), op, featureFilter, maxFeatures, layerAttributeFilter);

            string xml = "";
            GetByteReaderMethod fetch = () => { return info.ToXml(); };
            using (var sr = new StreamReader(new MgReadOnlyStream(fetch)))
            {
                xml = sr.ReadToEnd();
            }

            impl.Selection.LoadXml(xml);

            return xml;
        }
Esempio n. 46
0
    //----------------------------------------------------------------------------------------
    // �� �ܣ� ������ʱ��
    //
    // �� �ߣ�
    //
    //
    // �� �ڣ�2007.05.#
    //
    //-----------------------------------------------------------------------------------------
    public bool CreatePointsLayer(String rootPath, String sessionId)
    {
        // ��ȡҪ�ط������Դ����
        MgResourceService resourceService = (MgResourceService)siteConnection.CreateService(MgServiceType.ResourceService);
        MgFeatureService featureService = (MgFeatureService)siteConnection.CreateService(MgServiceType.FeatureService);

        //  �򿪵�ͼ
        MgMap map = new MgMap();
        map.Open(resourceService, "Sheboygan");
        // ---Ҫ�����Ҫ�ز������û��������������滹Ҫ���ܣ�--��ʼ
        // ���������ݵ�Ҫ��Դ
        CreateFeatureSource(sessionId);
        String featureSourceName = "Session:" + sessionId + "//Points.FeatureSource";
        MgResourceIdentifier resourceIdentifier = new MgResourceIdentifier(featureSourceName);

        MgBatchPropertyCollection batchPropertyCollection = new MgBatchPropertyCollection();
        MgWktReaderWriter wktReaderWriter = new MgWktReaderWriter();
        MgAgfReaderWriter agfReaderWriter = new MgAgfReaderWriter();
        MgGeometryFactory geometryFactory = new MgGeometryFactory();

        // �������¼
        MgPropertyCollection propertyCollection = MakePoint("Point A", -87.727, 43.748);
        batchPropertyCollection.Add(propertyCollection);

        propertyCollection = MakePoint("Point B", -87.728, 43.730);
        batchPropertyCollection.Add(propertyCollection);

        propertyCollection = MakePoint("Point C", -87.726, 43.750);
        batchPropertyCollection.Add(propertyCollection);

        propertyCollection = MakePoint("Point D", -87.728, 43.750);
        batchPropertyCollection.Add(propertyCollection);

        // ��������Ҫ��������ӵ�Ҫ��Դ
        MgInsertFeatures Insertcmd = new MgInsertFeatures("Points", batchPropertyCollection);
        MgFeatureCommandCollection featureCommandCollection = new MgFeatureCommandCollection();
        featureCommandCollection.Add(Insertcmd);
        featureService.UpdateFeatures(resourceIdentifier, featureCommandCollection, false);
        MgResourceIdentifier resourceID = null;
        //--------------Ҫ�����Ҫ�ز��� ����

        // �����㣬ͨ���㹤��LayerDefinitionFactory
        LayerDefinitionFactory factory = new LayerDefinitionFactory();
        factory.RootDirectoryPath = rootPath;

        //-------------------��������ʽ------------------------//
        // ������Ƿ���l
        string resourceSymbel = "Library://MgTutorial/Symbols/BasicSymbols.SymbolLibrary";
        string symbolName = "PushPin";
        string width = "24";  // unit = points
        string height = "24"; // unit = points
        string color = "FFFF0000";
        string markSymbol = factory.CreateMarkSymbol(resourceSymbel, symbolName, width, height, color);

        // �����ı�
        string text = "ID";
        string fontHeight = "12";
        string foregroundColor = "FF000000";
        string textSymbol = factory.CreateTextSymbol(text, fontHeight, foregroundColor);

        // ���������
        string legendLabel = "trees";
        string filter = "";
        string pointRule = factory.CreatePointRule(legendLabel, filter, textSymbol, markSymbol);

        // ��������ʽ
        string pointTypeStyle = factory.CreatePointTypeStyle(pointRule);

        // �������ŷ�Χ
        string minScale = "0";
        string maxScale = "1000000000000";
        string pointScaleRange = factory.CreateScaleRange(minScale, maxScale, pointTypeStyle);

        // �����㶨��
        string featureName = "PointSchema:Points";
        string geometry = "GEOM";
        string layerDefinition = factory.CreateLayerDefinition(featureSourceName, featureName, geometry, pointScaleRange);

        MgByteSource byteSource = new MgByteSource(Encoding.UTF8.GetBytes(layerDefinition), layerDefinition.Length);
        MgByteReader byteReader = byteSource.GetReader();

        resourceID = new MgResourceIdentifier("Session:" + sessionId + "//Points.LayerDefinition");
        resourceService.SetResource(resourceID, byteReader, null);
        //��������IJ㶨�����ݣ������ã�
        MgByteSink byteSink = new MgByteSink(resourceService.GetResourceContent(resourceID));
        string filePath = "C:\\Temp\\LayerDefinition.xml";
        byteSink.ToFile(filePath);

        // �����㲢��ӵ�����͵�ͼ��
        MgLayer newLayer = CreateLayerResource(resourceID, resourceService, "Points", "��ʱ��", map);

        AddLayerToGroup(newLayer, "Analysis", "����", map);

        MgLayerCollection layerCollection = map.GetLayers();
        if (layerCollection.Contains("Points"))
        {
            MgLayer pointsLayer = layerCollection.GetItem("Points");
            pointsLayer.SetVisible(true);
        }
        // �����ͼ
        map.Save(resourceService);

        return true;
    }
    string pointTransformAndWriteZ(string geom, MgMap map)
    {
        double[] x = new double[1];
        double[] y = new double[1];
        double[] z = new double[1];

        MgWktReaderWriter wktrwdmr = new MgWktReaderWriter();
        MgPoint cntr = wktrwdmr.Read(geom).Centroid;

        x[0] = cntr.Coordinate.X;
        y[0] = cntr.Coordinate.Y;
        z[0] = 0;

        StringBuilder output = new StringBuilder();
        output.Append("<table width=\"100%\" class=\"results\">");

        //WGS preko MG API
        MgCoordinateSystemFactory fact = new MgCoordinateSystemFactory();
        string wktFrom = map.GetMapSRS();

        string wktTo = "GEOGCS[\"LL84\",DATUM[\"WGS84\",SPHEROID[\"WGS84\",6378137.000,298.25722293]],PRIMEM[\"Greenwich\",0],UNIT[\"Degree\",0.01745329251994]]";

        MgCoordinateSystem CSSource = fact.Create(wktFrom);
        MgCoordinateSystem CSTarget = fact.Create(wktTo);
        MgCoordinateSystemTransform coordTransform = fact.GetTransform(CSSource, CSTarget);

        MgGeometryFactory geomFact = new MgGeometryFactory();

        // GK
        //samo prvo višino zaenkrat, dokler ni enačbe za Z
        output.Append(String.Format("<tr><td class='header'><b>Map koordinates:</b></td><td class=\"results\"><table><tr><td><b>Y:</b></td><td>{0}</td></tr><tr><td><b>X:</b></td><td>{1}</td></tr></table></td></tr>", string.Format("{0:0.0}", x[0]), string.Format("{0:0.0}", y[0])));

        int i = 0;

        //transformacija preko MG koordinatnega sistema
        foreach (double pointX in x)
        {
            MgCoordinate coord = geomFact.CreateCoordinateXY(x[i], y[i]);
            coord = coordTransform.Transform(coord);

            x[i] = coord.X;
            y[i] = coord.Y;

            i++;
        }

        double[] xwgs = x;
        double[] ywgs = y;
        output.Append(String.Format("<tr><td class='header'><b>WGS84:</b></td><td class=\"results\"><table><tr><td><b>Lon:</b></td><td>{0}</td></tr><tr><td><b>Lat:</b></td><td>{1}</td></tr></table></td></tr>", string.Format("{0:0.000000}", xwgs[0]), string.Format("{0:0.000000}", ywgs[0])));

        output.Append("</table>");

        return output.ToString();
    }
Esempio n. 48
0
        public override void Invoke()
        {
            var viewer = this.Viewer;
            viewer.DigitizeCircle((x, y, r) =>
            {
                if (_wktRw == null)
                    _wktRw = new MgWktReaderWriter();

                MgGeometry geom = _wktRw.Read(Util.MakeWktCircle(x, y, r, true));
                viewer.SelectByGeometry(geom);
            });
        }
Esempio n. 49
0
 void OnDisposed(object sender, EventArgs e)
 {
     if (_wktRw != null)
     {
         _wktRw.Dispose();
         _wktRw = null;
     }
 }
Esempio n. 50
0
 public void InitMapGuide()
 {
     MapGuideApi.MgInitializeWebTier("d:/mgdev/web/src/webconfig.ini");
     factory = new MgGeometryFactory();
     wkt = new MgWktReaderWriter();
     build = new GeomBuild();
 }
Esempio n. 51
0
        void OnDisposed(object sender, EventArgs e)
        {
            if (_wktRw != null)
            {
                _wktRw.Dispose();
                _wktRw = null;
            }

            if (_geomFact != null)
            {
                _geomFact.Dispose();
                _geomFact = null;
            }
        }
Esempio n. 52
0
        private void btnCreateBuffer_Click(object sender, EventArgs e)
        {
            MgSelectionBase           selection = _viewer.GetSelection();
            MgReadOnlyLayerCollection layers    = selection.GetLayers();

            if (layers == null)
            {
                MessageBox.Show("Select a parcel");
                return;
            }
            MgLayerBase parcels = null;

            for (int i = 0; i < layers.GetCount(); i++)
            {
                MgLayerBase layer = layers.GetItem(i);
                if (layer.Name == "Parcels")
                {
                    parcels = layer;
                    break;
                }
            }
            if (parcels == null)
            {
                MessageBox.Show("Select a parcel");
                return;
            }

            int bufferRingSize  = 100; // measured in metres
            int bufferRingCount = 5;

            // Set up some objects for coordinate conversion
            MgMapBase           map             = _viewer.GetMap();
            MgLayerCollection   mapLayers       = map.GetLayers();
            MgMapViewerProvider provider        = _viewer.GetProvider();
            MgResourceService   resourceService = (MgResourceService)provider.CreateService(MgServiceType.ResourceService);
            //Casting to MgdFeatureService because we want to use convenience APIs
            MgFeatureService featureService = (MgdFeatureService)provider.CreateService(MgServiceType.FeatureService);

            String                    mapWktSrs               = map.GetMapSRS();
            MgAgfReaderWriter         agfReaderWriter         = new MgAgfReaderWriter();
            MgWktReaderWriter         wktReaderWriter         = new MgWktReaderWriter();
            MgCoordinateSystemFactory coordinateSystemFactory = new MgCoordinateSystemFactory();
            MgCoordinateSystem        srs        = coordinateSystemFactory.Create(mapWktSrs);
            MgMeasure                 srsMeasure = srs.GetMeasure();
            string                    sessionId  = Guid.NewGuid().ToString();

            BufferHelper helper = new BufferHelper();

            // Check for a buffer layer. If it exists, delete
            // the current features.
            // If it does not exist, create a feature source and
            // a layer to hold the buffer.

            MgdLayer bufferLayer = null;
            int      layerIndex  = mapLayers.IndexOf("Buffer");

            if (layerIndex < 0)
            {
                // The layer does not exist and must be created.

                MgResourceIdentifier bufferFeatureResId = new MgResourceIdentifier("Session:" + sessionId + "//Buffer.FeatureSource");
                helper.CreateBufferFeatureSource(featureService, mapWktSrs, bufferFeatureResId);
                bufferLayer = helper.CreateBufferLayer(resourceService, bufferFeatureResId, sessionId);
                mapLayers.Insert(0, bufferLayer);
            }
            else
            {
                bufferLayer = (MgdLayer)map.GetLayers().GetItem(layerIndex);
                bufferLayer.DeleteFeatures("ID like '%'");
            }

            // Get the selected features from the MgSelection object
            MgFeatureReader featureReader = selection.GetSelectedFeatures(parcels, parcels.GetFeatureClassName(), false);

            // Process each item in the MgFeatureReader. Get the
            // geometries from all the selected features and
            // merge them into a single geometry.

            MgGeometryCollection inputGeometries = new MgGeometryCollection();

            while (featureReader.ReadNext())
            {
                MgByteReader featureGeometryData = featureReader.GetGeometry(parcels.GetFeatureGeometryName());
                MgGeometry   featureGeometry     = agfReaderWriter.Read(featureGeometryData);

                inputGeometries.Add(featureGeometry);
            }

            MgGeometryFactory geometryFactory  = new MgGeometryFactory();
            MgGeometry        mergedGeometries = geometryFactory.CreateMultiGeometry(inputGeometries);

            // Add buffer features to the temporary feature source.
            // Create multiple concentric buffers to show area.
            // If the stylization for the layer draws the features
            // partially transparent, the concentric rings will be
            // progressively darker towards the center.
            // The stylization is set in the layer template file, which
            // is used in function CreateBufferLayer().

            for (int bufferRing = 0; bufferRing < bufferRingCount; bufferRing++)
            {
                double     bufferDist     = srs.ConvertMetersToCoordinateSystemUnits(bufferRingSize * (bufferRing + 1));
                MgGeometry bufferGeometry = mergedGeometries.Buffer(bufferDist, srsMeasure);

                MgPropertyCollection properties = new MgPropertyCollection();
                properties.Add(new MgGeometryProperty("BufferGeometry", agfReaderWriter.Write(bufferGeometry)));

                MgFeatureReader fr = bufferLayer.InsertFeatures(properties);
                fr.Close();
            }

            bufferLayer.SetVisible(true);
            bufferLayer.ForceRefresh();
            bufferLayer.SetDisplayInLegend(true);

            MessageBox.Show("Buffer created");
            _viewer.RefreshMap();
            IMapLegend legend = Shell.Instance.Legend;

            if (legend != null)
            {
                legend.RefreshLegend();
            }
        }
Esempio n. 53
0
 public override void Dispose()
 {
     Close();
     if (_agfRw != null)
     {
         try
         {
             _agfRw.Dispose();
         }
         catch (MgException ex)
         {
             ex.Dispose();
         }
         _agfRw = null;
     }
     if (_wktRw != null)
     {
         try
         {
             _wktRw.Dispose();
         }
         catch (MgException ex)
         {
             ex.Dispose();
         }
         _wktRw = null;
     }
     base.Dispose();
 }
Esempio n. 54
0
        private void btnCreateBuffer_Click(object sender, EventArgs e)
        {
            MgSelectionBase selection = _viewer.GetSelection();
            MgReadOnlyLayerCollection layers = selection.GetLayers();
            if (layers == null)
            {
                MessageBox.Show("Select a parcel");
                return;
            }
            MgLayerBase parcels = null;
            for (int i = 0; i < layers.GetCount(); i++)
            {
                MgLayerBase layer = layers.GetItem(i);
                if (layer.Name == "Parcels")
                {
                    parcels = layer;
                    break;
                }
            }
            if (parcels == null)
            {
                MessageBox.Show("Select a parcel");
                return;
            }

            int bufferRingSize = 100; // measured in metres
            int bufferRingCount = 5;

            // Set up some objects for coordinate conversion
            MgMapBase map = _viewer.GetMap();
            MgLayerCollection mapLayers = map.GetLayers();
            MgMapViewerProvider provider = _viewer.GetProvider();
            MgResourceService resourceService = (MgResourceService)provider.CreateService(MgServiceType.ResourceService);
            //Casting to MgdFeatureService because we want to use convenience APIs
            MgFeatureService featureService = (MgdFeatureService)provider.CreateService(MgServiceType.FeatureService);

            String mapWktSrs = map.GetMapSRS();
            MgAgfReaderWriter agfReaderWriter = new MgAgfReaderWriter();
            MgWktReaderWriter wktReaderWriter = new MgWktReaderWriter();
            MgCoordinateSystemFactory coordinateSystemFactory = new MgCoordinateSystemFactory();
            MgCoordinateSystem srs = coordinateSystemFactory.Create(mapWktSrs);
            MgMeasure srsMeasure = srs.GetMeasure();
            string sessionId = Guid.NewGuid().ToString();

            BufferHelper helper = new BufferHelper();

            // Check for a buffer layer. If it exists, delete
            // the current features.
            // If it does not exist, create a feature source and
            // a layer to hold the buffer.

            MgdLayer bufferLayer = null;
            int layerIndex = mapLayers.IndexOf("Buffer");
            if (layerIndex < 0)
            {
                // The layer does not exist and must be created.

                MgResourceIdentifier bufferFeatureResId = new MgResourceIdentifier("Session:" + sessionId + "//Buffer.FeatureSource");
                helper.CreateBufferFeatureSource(featureService, mapWktSrs, bufferFeatureResId);
                bufferLayer = helper.CreateBufferLayer(resourceService, bufferFeatureResId, sessionId);
                mapLayers.Insert(0, bufferLayer);
            }
            else
            {
                bufferLayer = (MgdLayer)map.GetLayers().GetItem(layerIndex);
                bufferLayer.DeleteFeatures("ID like '%'");
            }

            // Get the selected features from the MgSelection object
            MgFeatureReader featureReader = selection.GetSelectedFeatures(parcels, parcels.GetFeatureClassName(), false);

            // Process each item in the MgFeatureReader. Get the
            // geometries from all the selected features and
            // merge them into a single geometry.

            MgGeometryCollection inputGeometries = new MgGeometryCollection();
            while (featureReader.ReadNext())
            {
                MgByteReader featureGeometryData = featureReader.GetGeometry(parcels.GetFeatureGeometryName());
                MgGeometry featureGeometry = agfReaderWriter.Read(featureGeometryData);

                inputGeometries.Add(featureGeometry);
            }

            MgGeometryFactory geometryFactory = new MgGeometryFactory();
            MgGeometry mergedGeometries = geometryFactory.CreateMultiGeometry(inputGeometries);

            // Add buffer features to the temporary feature source.
            // Create multiple concentric buffers to show area.
            // If the stylization for the layer draws the features
            // partially transparent, the concentric rings will be
            // progressively darker towards the center.
            // The stylization is set in the layer template file, which
            // is used in function CreateBufferLayer().

            for (int bufferRing = 0; bufferRing < bufferRingCount; bufferRing++)
            {
                double bufferDist = srs.ConvertMetersToCoordinateSystemUnits(bufferRingSize * (bufferRing + 1));
                MgGeometry bufferGeometry = mergedGeometries.Buffer(bufferDist, srsMeasure);

                MgPropertyCollection properties = new MgPropertyCollection();
                properties.Add(new MgGeometryProperty("BufferGeometry", agfReaderWriter.Write(bufferGeometry)));

                MgFeatureReader fr = bufferLayer.InsertFeatures(properties);
                fr.Close();
            }

            bufferLayer.SetVisible(true);
            bufferLayer.ForceRefresh();
            bufferLayer.SetDisplayInLegend(true);

            MessageBox.Show("Buffer created");
            _viewer.RefreshMap();
            IMapLegend legend = Shell.Instance.Legend;
            if (legend != null)
                legend.RefreshLegend();
        }
Esempio n. 55
0
        private void OnPointDrawn(double x, double y)
        {
            if (_pointLayer == null) //Our point layer doesn't exist
                CreateRedlineLayer();
            
            //Now insert our point. This code should look familiar
            //to you, setting up the MgPropertyCollection for insertion
            MgPropertyCollection props = new MgPropertyCollection();
            MgWktReaderWriter wktRw = new MgWktReaderWriter();
            MgAgfReaderWriter agfRw = new MgAgfReaderWriter();

            MgGeometry geom = wktRw.Read("POINT (" + x + " " + y + ")");
            MgByteReader agf = agfRw.Write(geom);

            MgGeometryProperty geomProp = new MgGeometryProperty("Geometry", agf);
            props.Add(geomProp);

            //Here's where we differ from the official MapGuide API
            //instead of a monolithic UpdateFeatures() that tries to 
            //do everything, we have individual InsertFeatures/DeleteFeatures/UpdateFeatures
            //methods. So here's the mg-desktop way

            MgFeatureReader result = _pointLayer.InsertFeatures(props);
            result.Close();

            //Or if you have have access to the MgdLayer instance
            /*
            MgResourceIdentifier fsId = new MgResourceIdentifier(_pointLayer.GetFeatureSourceId());
            MgServiceFactory factory = new MgServiceFactory();
            MgdFeatureService featSvc = (MgdFeatureService)factory.CreateService(MgServiceType.FeatureService);
            MgFeatureReader fr = featSvc.InsertFeatures(fsId, "Default:Redline", props);
            fr.Close();
             */
            
            //Now refresh to see your newly drawn point
            mgMapViewer1.RefreshMap();
        }
Esempio n. 56
0
 private ReaderResponseDialog()
 {
     InitializeComponent();
     _wktRW = new MgWktReaderWriter();
     _agfRW = new MgAgfReaderWriter();
 }
Esempio n. 57
0
        public LocalNativeRecord(MgReader reader, FixedWKTReader mgReader, MgAgfReaderWriter agfRw, MgWktReaderWriter wktRw)
        {
            for (int i = 0; i < reader.GetPropertyCount(); i++)
            {
                string name = reader.GetPropertyName(i);

                _ordinalMap[i] = name;

                var pt = (PropertyValueType)reader.GetPropertyType(name);
                switch (pt)
                {
                    case PropertyValueType.Blob:
                        _values[name] = new BlobValue();
                        break;
                    case PropertyValueType.Boolean:
                        _values[name] = new BooleanValue();
                        break;
                    case PropertyValueType.Byte:
                        _values[name] = new ByteValue();
                        break;
                    case PropertyValueType.Clob:
                        _values[name] = new ClobValue();
                        break;
                    case PropertyValueType.DateTime:
                        _values[name] = new DateTimeValue();
                        break;
                    case PropertyValueType.Double:
                        _values[name] = new DoubleValue();
                        break;
                    case PropertyValueType.Feature:
                        _values[name] = new FeatureValue();
                        break;
                    case PropertyValueType.Geometry:
                        _values[name] = new GeometryValue();
                        break;
                    case PropertyValueType.Int16:
                        _values[name] = new Int16Value();
                        break;
                    case PropertyValueType.Int32:
                        _values[name] = new Int32Value();
                        break;
                    case PropertyValueType.Int64:
                        _values[name] = new Int64Value();
                        break;
                    case PropertyValueType.Raster:
                        _values[name] = new RasterValue();
                        break;
                    case PropertyValueType.Single:
                        _values[name] = new SingleValue();
                        break;
                    case PropertyValueType.String:
                        _values[name] = new StringValue();
                        break;
                }
            }

            for (int i = 0; i < reader.GetPropertyCount(); i++)
            {
                string name = _ordinalMap[i];
                GetByteReaderMethod getblob = () => { return reader.GetBLOB(name); };
                GetByteReaderMethod getclob = () => { return reader.GetCLOB(name); };
                GetByteReaderMethod getgeom = () => { return reader.GetGeometry(name); };
                if (!reader.IsNull(name))
                {
                    var pt = (PropertyValueType)reader.GetPropertyType(name);
                    switch (pt)
                    {
                        case PropertyValueType.Blob:
                            ((BlobValue)_values[name]).Value = Utility.StreamAsArray(new MgReadOnlyStream(getblob));
                            break;
                        case PropertyValueType.Boolean:
                            ((BooleanValue)_values[name]).Value = reader.GetBoolean(name);
                            break;
                        case PropertyValueType.Byte:
                            ((ByteValue)_values[name]).Value = reader.GetByte(name);
                            break;
                        case PropertyValueType.Clob:
                            byte [] b = Utility.StreamAsArray(new MgReadOnlyStream(getclob));
                            ((ClobValue)_values[name]).Value = Encoding.UTF8.GetChars(b);
                            break;
                        case PropertyValueType.DateTime:
                            ((DateTimeValue)_values[name]).Value = Utility.ConvertMgDateTime(reader.GetDateTime(name));
                            break;
                        case PropertyValueType.Double:
                            ((DoubleValue)_values[name]).Value = reader.GetDouble(name);
                            break;
                        //case PropertyValueType.Feature:
                        case PropertyValueType.Geometry:
                            try
                            {
                                //TODO: See if SWIG issues come into play here
                                var geom = agfRw.Read(reader.GetGeometry(name));
                                var wkt = wktRw.Write(geom);
                                ((GeometryValue)_values[name]).Value = mgReader.Read(wkt);
                            }
                            catch //Invalid geometry fail!
                            {
                                ((GeometryValue)_values[name]).SetNull();
                            }
                            break;
                        case PropertyValueType.Int16:
                            ((Int16Value)_values[name]).Value = reader.GetInt16(name);
                            break;
                        case PropertyValueType.Int32:
                            ((Int32Value)_values[name]).Value = reader.GetInt32(name);
                            break;
                        case PropertyValueType.Int64:
                            ((Int64Value)_values[name]).Value = reader.GetInt64(name);
                            break;
                        case PropertyValueType.Single:
                            ((SingleValue)_values[name]).Value = reader.GetSingle(name);
                            break;
                        case PropertyValueType.String:
                            ((StringValue)_values[name]).Value = reader.GetString(name);
                            break;
                    }
                }
            }
        }