Пример #1
0
        internal void AddRedlineLayer(RedlineLayer layer, string fdoProvider)
        {
            var fsId = GetRegistryFeatureSource();
            MgFeatureCommandCollection commands   = new MgFeatureCommandCollection();
            MgPropertyCollection       insertVals = new MgPropertyCollection();

            MgStringProperty regId     = new MgStringProperty("ResourceId", layer.FeatureSource);
            MgStringProperty ldfId     = new MgStringProperty("LayerDefinition", layer.LayerDefinition);
            MgStringProperty name      = new MgStringProperty("Name", layer.Name);
            MgStringProperty provider  = new MgStringProperty("FdoProvider", fdoProvider);
            MgInt32Property  geomTypes = new MgInt32Property("GeometryTypes", layer.GeometryTypes);
            MgInt32Property  styleType = new MgInt32Property("StyleType", (int)layer.StyleType);

            insertVals.Add(regId);
            insertVals.Add(ldfId);
            insertVals.Add(name);
            insertVals.Add(provider);
            insertVals.Add(geomTypes);
            insertVals.Add(styleType);

            MgInsertFeatures insert = new MgInsertFeatures("Default:MarkupRegistry", insertVals);

            commands.Add(insert);

            MgPropertyCollection result       = _featSvc.UpdateFeatures(fsId, commands, false);
            MgFeatureProperty    insertResult = result.GetItem(0) as MgFeatureProperty;

            if (insertResult != null)
            {
                MgFeatureReader fr = insertResult.GetValue();
                fr.Close();
            }
        }
Пример #2
0
        private void InsertRedlineGeometry(MgGeometry geom)
        {
            MgPropertyCollection feature  = new MgPropertyCollection();
            MgByteReader         agf      = _agfRW.Write(geom);
            MgGeometryProperty   geomProp = new MgGeometryProperty("Geometry", agf);

            feature.Add(geomProp);

            _redlineLayer.ForceRefresh();
            var reader   = _redlineLayer.InsertFeatures(feature);
            int inserted = 0;

            while (reader.ReadNext())
            {
                inserted++;
            }
            reader.Close();
            if (inserted > 0)
            {
                _viewer.RefreshMap();
                IMapLegend legend = Shell.Instance.Legend;
                if (legend != null)
                {
                    legend.RefreshLegend();
                }
            }
        }
Пример #3
0
        public void Execute(IPlatformFactory factory, ITestLogger logger)
        {
            MgPropertyCollection coll     = new MgPropertyCollection();
            MgDoubleProperty     dblProp  = new MgDoubleProperty("DoubleProp", 1.1111);
            MgInt32Property      intProp  = new MgInt32Property("IntProp", 1);
            MgDateTime           dateTime = new MgDateTime(2006, 9, 21);
            MgDateTimeProperty   dateProp = new MgDateTimeProperty("DateProp", dateTime);
            MgSingleProperty     single   = new MgSingleProperty("SingleProp", (float)2.2222);

            coll.Add(dblProp);
            coll.Add(intProp);
            coll.Add(dateProp);
            coll[2] = single;

            Assert.AreEqual(1.1111, (coll[0] as MgDoubleProperty).GetValue());
            Assert.AreEqual(MgPropertyType.Double, coll[0].GetPropertyType());
            Assert.AreEqual(MgPropertyType.Int32, coll[1].GetPropertyType());
            Assert.AreEqual(MgPropertyType.Single, coll[2].GetPropertyType());
            Assert.AreEqual((float)2.2222, (coll[2] as MgSingleProperty).GetValue());
            Assert.AreEqual(3, coll.Count);

            Assert.AreEqual(MgPropertyType.Double, coll[0].GetPropertyType());

            string str = "";

            foreach (MgProperty prop in coll)
            {
                str = str + "[" + prop.GetName() + "]";
            }
            Assert.AreEqual("[DoubleProp][IntProp][SingleProp]", str);
        }
Пример #4
0
        protected override void ExecuteInternal()
        {
            MgPropertyCollection props = new MgPropertyCollection();

            MgFeatureCommandUtility.Populate(props, this.RecordToInsert);
            this.ConnImpl.InsertFeatures(new MgResourceIdentifier(this.FeatureSourceId), this.ClassName, props);
        }
Пример #5
0
        public void BatchPropertyCollection()
        {
            MgPropertyCollection coll1 = new MgPropertyCollection();
            MgDoubleProperty dblProp = new MgDoubleProperty("DoubleProp", 1.1111);
            coll1.Add(dblProp);

            MgPropertyCollection coll2 = new MgPropertyCollection();
            MgInt32Property intProp = new MgInt32Property("IntProp", 1);
            coll2.Add(intProp);

            MgPropertyCollection coll3 = new MgPropertyCollection();
            MgSingleProperty single = new MgSingleProperty("SingleProp", (float)2.2222);
            coll3.Add(single);

            MgBatchPropertyCollection coll = new MgBatchPropertyCollection();
            coll.Add(coll1);
            coll.Add(coll2);

            Assert.AreEqual(2, coll.Count);
            Assert.AreEqual(MgPropertyType.Double, coll[0][0].GetPropertyType());
            Assert.AreEqual(MgPropertyType.Int32, coll[1][0].GetPropertyType());

            coll[1] = coll3;

            string str = "";
            foreach (MgPropertyCollection c in coll)
            {
                str = str + "[" + c[0].GetName() + "]";
            }
            Assert.AreEqual("[DoubleProp][SingleProp]", str);
        }
Пример #6
0
        public override int ExecuteInternal()
        {
            MgPropertyCollection props = new MgPropertyCollection();

            MgFeatureCommandUtility.Populate(props, this.ValuesToUpdate);
            return(this.ConnImpl.UpdateFeatures(new MgResourceIdentifier(this.FeatureSourceId), this.ClassName, props, this.Filter));
        }
Пример #7
0
        public static void ReleaseReader(MgPropertyCollection res, MgFeatureCommandCollection commands)
        {
            if (res == null)
            {
                return;
            }

            for (int i = 0; i < res.GetCount(); i++)
            {
                MgFeatureCommand cmd = commands.GetItem(i);
                if (cmd is MgInsertFeatures)
                {
                    MgFeatureProperty resProp = res.GetItem(i) as MgFeatureProperty;
                    if (resProp != null)
                    {
                        MgFeatureReader reader = resProp.GetValue() as MgFeatureReader;
                        if (reader == null)
                        {
                            return;
                        }
                        reader.Close();
                    }
                }
            }
        }
Пример #8
0
        internal void DeleteLayer(RedlineLayer layer)
        {
            var regId = GetRegistryFeatureSource();
            MgFeatureCommandCollection commands = new MgFeatureCommandCollection();
            MgDeleteFeatures           delete   = new MgDeleteFeatures("Default:MarkupRegistry", "ResourceId = '" + layer.FeatureSource + "'");

            commands.Add(delete);

            MgPropertyCollection results      = _featSvc.UpdateFeatures(regId, commands, false);
            MgInt32Property      deleteResult = results.GetItem(0) as MgInt32Property;

            if (deleteResult != null && deleteResult.GetValue() > 0)
            {
                var ldfId = new MgResourceIdentifier(layer.LayerDefinition);
                var fsId  = new MgResourceIdentifier(layer.FeatureSource);

                if (_resSvc.ResourceExists(ldfId))
                {
                    _resSvc.DeleteResource(ldfId);
                }

                if (_resSvc.ResourceExists(fsId))
                {
                    _resSvc.DeleteResource(fsId);
                }
            }
        }
Пример #9
0
        public void Execute(IPlatformFactory factory, ITestLogger logger)
        {
            MgPropertyCollection propVals = new MgPropertyCollection();
            MgInt32Property      prop     = new MgInt32Property("prop", 1);

            propVals.Add(prop);
            MgUpdateFeatures update = new MgUpdateFeatures("class2", propVals, "where cat < dog");
            MgInsertFeatures insert = new MgInsertFeatures("class3", propVals);
            MgDeleteFeatures del    = new MgDeleteFeatures("class1", "where cat > dog");

            MgFeatureCommandCollection coll = new MgFeatureCommandCollection();

            coll.Add(update);
            coll.Add(insert);
            coll.Add(del);

            Assert.AreEqual(3, coll.Count);
            Assert.AreEqual(MgFeatureCommandType.DeleteFeatures, coll[2].GetCommandType());
            coll[0] = coll[1];

            string txt = "";

            foreach (MgFeatureCommand cmd in coll)
            {
                txt += "[" + cmd.GetCommandType() + "]";
            }
            Assert.AreEqual("[0][0][2]", txt);
        }
Пример #10
0
        public void Execute(IPlatformFactory factory, ITestLogger logger)
        {
            MgPropertyCollection propColl = new MgPropertyCollection();

            propColl.Add(new MgInt32Property("intProp", 10));
            MgInsertFeatures inf = new MgInsertFeatures("ClassName", propColl);

            Assert.AreEqual("ClassName", inf.FeatureClassName);
        }
Пример #11
0
 public static void AddPointFeature(string FeatureName, MgPropertyCollection featureProps, MgPoint geom, MgFeatureService featureSrvc, MgResourceIdentifier dataSourceId)
 {
     MgByteReader geomReader = new MgAgfReaderWriter().Write(geom);
     MgGeometryProperty geometryProp = new MgGeometryProperty("GEOM", geomReader);
     featureProps.Add(geometryProp);
     MgInsertFeatures cmd = new MgInsertFeatures(FeatureName, featureProps);
     MgFeatureCommandCollection commands = new MgFeatureCommandCollection();
     commands.Add(cmd);
     ReleaseReader(featureSrvc.UpdateFeatures(dataSourceId, commands, false));
 }
Пример #12
0
        public static void AddFeatureToCollection(MgBatchPropertyCollection propCollection, MgAgfReaderWriter agfRW, int featureId, MgGeometry featureGeom)
        {
            MgPropertyCollection bufferProps = new MgPropertyCollection();
            MgInt32Property      idProp      = new MgInt32Property("ID", featureId); //NOXLATE

            bufferProps.Add(idProp);
            MgByteReader       geomReader = agfRW.Write(featureGeom);
            MgGeometryProperty geomProp   = new MgGeometryProperty("GEOM", geomReader); //NOXLATE

            bufferProps.Add(geomProp);
            propCollection.Add(bufferProps);
        }
Пример #13
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);
        }
Пример #14
0
        internal void UpdateRedlineText(string text, int[] ids)
        {
            MgMapBase         map          = _viewer.GetMap();
            MgLayerCollection layers       = map.GetLayers();
            MgLayerBase       redlineLayer = layers.GetItem(_layer.SystemName);

            //HACK: Workaround FeatId leaky abstraction in SHP provider
            MgClassDefinition cls = redlineLayer.GetClassDefinition();
            MgPropertyDefinitionCollection idProps = cls.GetIdentityProperties();
            MgPropertyDefinition           idProp  = idProps.GetItem(0);

            redlineLayer.ForceRefresh();

            //This lib doesn't reference mg-desktop so the convenience APIs aren't available to us
            //Gotta go the old verbose route
            List <string> filters = new List <string>();

            foreach (int id in ids)
            {
                filters.Add(idProp.Name + " = " + id);
            }
            string updateFilter = string.Join(" OR ", filters.ToArray());
            MgFeatureCommandCollection commands     = new MgFeatureCommandCollection();
            MgPropertyCollection       updateValues = new MgPropertyCollection();
            MgStringProperty           updateProp   = new MgStringProperty(RedlineSchemaFactory.TEXT_NAME, text);

            updateValues.Add(updateProp);

            MgUpdateFeatures update = new MgUpdateFeatures(redlineLayer.FeatureClassName, updateValues, updateFilter);

            commands.Add(update);

            MgPropertyCollection result       = redlineLayer.UpdateFeatures(commands);
            MgInt32Property      updateResult = result.GetItem(0) as MgInt32Property;
            MgStringProperty     errorResult  = result.GetItem(0) as MgStringProperty;

            if (errorResult != null)
            {
                throw new Exception(errorResult.GetValue());
            }
            _viewer.RefreshMap();
        }
Пример #15
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();
        }
Пример #16
0
        private void InsertRedlineGeometry(MgGeometry geom)
        {
            MgPropertyCollection feature = new MgPropertyCollection();
            MgByteReader agf = _agfRW.Write(geom);
            MgGeometryProperty geomProp = new MgGeometryProperty("Geometry", agf);
            feature.Add(geomProp);

            _redlineLayer.ForceRefresh();
            var reader = _redlineLayer.InsertFeatures(feature);
            int inserted = 0;
            while (reader.ReadNext())
            {
                inserted++;
            }
            reader.Close();
            if (inserted > 0)
            {
                _viewer.RefreshMap();
                IMapLegend legend = Shell.Instance.Legend;
                if (legend != null)
                    legend.RefreshLegend();
            }
        }
Пример #17
0
        public void Execute(IPlatformFactory factory, ITestLogger logger)
        {
            MgPropertyCollection coll1   = new MgPropertyCollection();
            MgDoubleProperty     dblProp = new MgDoubleProperty("DoubleProp", 1.1111);

            coll1.Add(dblProp);

            MgPropertyCollection coll2   = new MgPropertyCollection();
            MgInt32Property      intProp = new MgInt32Property("IntProp", 1);

            coll2.Add(intProp);

            MgPropertyCollection coll3  = new MgPropertyCollection();
            MgSingleProperty     single = new MgSingleProperty("SingleProp", (float)2.2222);

            coll3.Add(single);


            MgBatchPropertyCollection coll = new MgBatchPropertyCollection();

            coll.Add(coll1);
            coll.Add(coll2);

            Assert.AreEqual(2, coll.Count);
            Assert.AreEqual(MgPropertyType.Double, coll[0][0].GetPropertyType());
            Assert.AreEqual(MgPropertyType.Int32, coll[1][0].GetPropertyType());

            coll[1] = coll3;

            string str = "";

            foreach (MgPropertyCollection c in coll)
            {
                str = str + "[" + c[0].GetName() + "]";
            }
            Assert.AreEqual("[DoubleProp][SingleProp]", str);
        }
Пример #18
0
 internal LocalNativeCoordinateSystemDefinition(CoordinateSystemCategory parent, MgPropertyCollection props)
     : base(parent)
 {
     int pcount = props.GetCount();
     for (int i = 0; i < pcount; i++)
     {
         var prop = props.GetItem(i);
         switch (prop.Name.ToLower())
         {
             case "code":
                 m_code = (prop as MgStringProperty).Value;
                 break;
             case "description":
                 m_description = (prop as MgStringProperty).Value;
                 break;
             case "projection":
                 m_projection = (prop as MgStringProperty).Value;
                 break;
             case "projection description":
                 m_projectionDescription = (prop as MgStringProperty).Value;
                 break;
             case "Datum":
                 m_datum = (prop as MgStringProperty).Value;
                 break;
             case "datum description":
                 m_datumDescription = (prop as MgStringProperty).Value;
                 break;
             case "ellipsoid":
                 m_ellipsoid = (prop as MgStringProperty).Value;
                 break;
             case "ellipsoid description":
                 m_ellipsoidDescription = (prop as MgStringProperty).Value;
                 break;
         }
     }
 }
Пример #19
0
        internal void DeleteRedlines(int[] ids)
        {
            MgMapBase         map          = _viewer.GetMap();
            MgLayerCollection layers       = map.GetLayers();
            MgLayerBase       redlineLayer = layers.GetItem(_layer.SystemName);

            //HACK: Workaround FeatId leaky abstraction in SHP provider
            MgClassDefinition cls = redlineLayer.GetClassDefinition();
            MgPropertyDefinitionCollection idProps = cls.GetIdentityProperties();
            MgPropertyDefinition           idProp  = idProps.GetItem(0);

            redlineLayer.ForceRefresh();

            //This lib doesn't reference mg-desktop so the convenience APIs aren't available to us
            //Gotta go the old verbose route
            List <string> filters = new List <string>();

            foreach (int id in ids)
            {
                filters.Add(idProp.Name + " = " + id);
            }
            string deleteFilter = string.Join(" OR ", filters.ToArray());
            MgFeatureCommandCollection commands = new MgFeatureCommandCollection();

            MgDeleteFeatures delete = new MgDeleteFeatures(redlineLayer.FeatureClassName, deleteFilter);

            commands.Add(delete);

            MgPropertyCollection result       = redlineLayer.UpdateFeatures(commands);
            MgInt32Property      deleteResult = result.GetItem(0) as MgInt32Property;

            if (deleteResult != null && deleteResult.GetValue() > 0)
            {
                _viewer.RefreshMap();
            }
        }
Пример #20
0
        internal static void Update(MgPropertyCollection props, IRecord record)
        {
            if (props.Count != record.FieldCount)
            {
                throw new InvalidOperationException("Number of values to update does not match. Ensure the MgPropertyCollection was initialized first with PropertyUtil.Populate() first and that the input IRecord comes from the same source used to initialize this MgPropertyCollection"); //LOCALIZEME
            }
            //Flip the null bit first
            for (int i = 0; i < props.Count; i++)
            {
                var p  = props.GetItem(i);
                var np = p as MgNullableProperty;
                if (np != null)
                {
                    np.SetNull(true);
                }

                string name = p.Name;
                if (!record.IsNull(name))
                {
                    switch (p.PropertyType)
                    {
                    case MgPropertyType.Blob:
                    {
                        var bytes = record.GetBlob(name);
                        var bs    = new MgByteSource(bytes, bytes.Length);
                        ((MgBlobProperty)p).SetValue(bs.GetReader());
                    }
                    break;

                    case MgPropertyType.Boolean:
                    {
                        ((MgBooleanProperty)p).SetValue(record.GetBoolean(name));
                    }
                    break;

                    case MgPropertyType.Byte:
                    {
                        ((MgByteProperty)p).SetValue(record.GetByte(name));
                    }
                    break;

                    case MgPropertyType.Clob:
                    {
                        var bytes = record.GetBlob(name);
                        var bs    = new MgByteSource(bytes, bytes.Length);
                        ((MgClobProperty)p).SetValue(bs.GetReader());
                    }
                    break;

                    case MgPropertyType.DateTime:
                    {
                        var dt  = record.GetDateTime(i);
                        var mdt = new MgDateTime((short)dt.Year, (short)dt.Month, (short)dt.Day, (short)dt.Hour, (short)dt.Minute, (short)dt.Second, dt.Millisecond * 1000);
                        ((MgDateTimeProperty)p).SetValue(mdt);
                    }
                    break;

                    case MgPropertyType.Decimal:
                    case MgPropertyType.Double:
                    {
                        ((MgDoubleProperty)p).SetValue(record.GetDouble(name));
                    }
                    break;

                    case MgPropertyType.Geometry:
                    {
                        var agf = GeomConverter.GetAgf(record.GetGeometry(name));
                        ((MgGeometryProperty)p).SetValue(agf);
                    }
                    break;

                    case MgPropertyType.Int16:
                    {
                        ((MgInt16Property)p).SetValue(record.GetInt16(name));
                    }
                    break;

                    case MgPropertyType.Int32:
                    {
                        ((MgInt32Property)p).SetValue(record.GetInt32(name));
                    }
                    break;

                    case MgPropertyType.Int64:
                    {
                        ((MgInt64Property)p).SetValue(record.GetInt64(name));
                    }
                    break;

                    case MgPropertyType.Single:
                    {
                        ((MgSingleProperty)p).SetValue(record.GetSingle(name));
                    }
                    break;

                    case MgPropertyType.String:
                    {
                        ((MgStringProperty)p).SetValue(record.GetString(name));
                    }
                    break;

                    default:
                        throw new NotSupportedException();
                    }
                }
            }
        }
Пример #21
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();
        }
Пример #22
0
 public void UpdateFeatures()
 {
     MgPropertyCollection propColl = new MgPropertyCollection();
     propColl.Add(new MgInt32Property("intProp", 10));
     MgUpdateFeatures uf = new MgUpdateFeatures("ClassName", propColl, "filter");
     Assert.AreEqual("ClassName", uf.FeatureClassName);
     Assert.AreEqual("ClassName", uf.FeatureClassName);
 }
Пример #23
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();
                    }
                }
            }
        }
Пример #24
0
        private void btnSelect_Click(object sender, EventArgs e)
        {
            _viewer.ClearSelection();
            var sel = _viewer.GetSelection();

            foreach (DataGridViewRow row in grdResults.SelectedRows)
            {
                MgPropertyCollection idProps = new MgPropertyCollection();
                foreach (string name in _identityProps)
                {
                    int idx = Array.IndexOf(_columns, name);
                    if (idx >= 0)
                    {
                        int type = _propMap[name];
                        switch (type)
                        {
                        case MgPropertyType.Boolean:
                            idProps.Add(new MgBooleanProperty(name, Convert.ToBoolean(row.Cells[idx].Value)));
                            break;

                        case MgPropertyType.Byte:
                            idProps.Add(new MgByteProperty(name, Convert.ToByte(row.Cells[idx].Value)));
                            break;

                        case MgPropertyType.DateTime:
                            idProps.Add(new MgDateTimeProperty(name, FromClrDateTime((DateTime)row.Cells[idx].Value)));
                            break;

                        case MgPropertyType.Decimal:
                        case MgPropertyType.Double:
                            idProps.Add(new MgDoubleProperty(name, Convert.ToDouble(row.Cells[idx].Value)));
                            break;

                        case MgPropertyType.Int16:
                            idProps.Add(new MgInt16Property(name, Convert.ToInt16(row.Cells[idx].Value)));
                            break;

                        case MgPropertyType.Int32:
                            idProps.Add(new MgInt32Property(name, Convert.ToInt32(row.Cells[idx].Value)));
                            break;

                        case MgPropertyType.Int64:
                            idProps.Add(new MgInt64Property(name, Convert.ToInt64(row.Cells[idx].Value)));
                            break;

                        case MgPropertyType.Single:
                            idProps.Add(new MgSingleProperty(name, Convert.ToSingle(row.Cells[idx].Value)));
                            break;

                        case MgPropertyType.String:
                            idProps.Add(new MgStringProperty(name, Convert.ToString(row.Cells[idx].Value)));
                            break;
                        }
                    }
                }
                if (idProps.Count == _identityProps.Length)
                {
                    sel.AddFeatureIds(_layer, _layer.FeatureClassName, idProps);
                }
                else
                {
                    idProps.Dispose();
                    idProps = null;
                }
            }
            _viewer.UpdateSelection(true);
        }
        internal LocalNativeCoordinateSystemDefinition(CoordinateSystemCategory parent, MgPropertyCollection props)
            : base(parent)
        {
            int pcount = props.GetCount();

            for (int i = 0; i < pcount; i++)
            {
                var prop = props.GetItem(i);
                switch (prop.Name.ToLower())
                {
                case "code":
                    m_code = (prop as MgStringProperty).Value;
                    break;

                case "description":
                    m_description = (prop as MgStringProperty).Value;
                    break;

                case "projection":
                    m_projection = (prop as MgStringProperty).Value;
                    break;

                case "projection description":
                    m_projectionDescription = (prop as MgStringProperty).Value;
                    break;

                case "Datum":
                    m_datum = (prop as MgStringProperty).Value;
                    break;

                case "datum description":
                    m_datumDescription = (prop as MgStringProperty).Value;
                    break;

                case "ellipsoid":
                    m_ellipsoid = (prop as MgStringProperty).Value;
                    break;

                case "ellipsoid description":
                    m_ellipsoidDescription = (prop as MgStringProperty).Value;
                    break;
                }
            }
        }
Пример #26
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:";
            }
        }
    }
Пример #27
0
        public void UpdateMarkup()
        {
            MgResourceIdentifier featureSourceId = new MgResourceIdentifier(libraryPath + this.GetMarkupName() + ".FeatureSource");

            MgPropertyCollection propertyValues = new MgPropertyCollection();
            propertyValues.Add(new MgStringProperty("Text", GetParameter(this.args, "UPDATETEXT")));
            propertyValues.Add(new MgStringProperty("ReverseText", ReverseString(GetParameter(this.args, "UPDATETEXT"))));

            MgFeatureCommandCollection commands = new MgFeatureCommandCollection();
            commands.Add(new MgUpdateFeatures("Markup", propertyValues, "ID = " + GetParameter(this.args, "MARKUPFEATURE")));
            _featureService.UpdateFeatures(featureSourceId, commands, false);

            /*int projectId = GetProjectId();
            if (projectId > 0)
            {
                using (System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(ConfigurationManager.ConnectionStrings["ProjectManagerConnectionString"].ConnectionString))
                {
                    var cmd = conn.CreateCommand();
                    cmd.CommandText = String.Format("UPDATE Projects SET Name = @Name WHERE ProjectId={0} AND UID={1}", projectId, GetParameter(this.args, "MARKUPFEATURE"));
                    var nameParam = new System.Data.SqlClient.SqlParameter
                                    {
                                        ParameterName="@Name",
                                        SqlDbType = System.Data.SqlDbType.NVarChar,
                                        Size=50,
                                        Value = GetParameter(this.args, "UPDATETEXT")
                                    };
                    cmd.Parameters.Add(nameParam);
                    conn.Open();
                    cmd.ExecuteNonQuery();
                }
            }*/
        }
Пример #28
0
        public void InsertMarkupFeature(MgPropertyCollection propertyValues)
        {
            MgResourceIdentifier featureSourceId = new MgResourceIdentifier(libraryPath + this.GetMarkupName() + ".FeatureSource");

            MgFeatureCommandCollection commands = new MgFeatureCommandCollection();
            commands.Add(new MgInsertFeatures("Markup", propertyValues));

            _featureService.UpdateFeatures(featureSourceId, commands, false);
               /* int projectId = GetProjectId();
            if (projectId > 0)
            {
                using (System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(ConfigurationManager.ConnectionStrings["ProjectManagerConnectionString"].ConnectionString))
                {
                    var cmd = conn.CreateCommand();
                    cmd.CommandText = String.Format("INSERT INTO Projects(UID, Name, ProjectId, StatusId, ManagerId) VALUES({0}, @Name, {1}, 9, 14)", GetLastUID(featureSourceId), projectId);
                    var nameParam = new System.Data.SqlClient.SqlParameter
                    {
                        ParameterName = "@Name",
                        SqlDbType = System.Data.SqlDbType.NVarChar,
                        Size = 50,
                        Value = GetParameter(this.args, "TEXT")
                    };
                    cmd.Parameters.Add(nameParam);
                    conn.Open();
                    cmd.ExecuteNonQuery();
                }
            }*/
        }
Пример #29
0
 internal void InsertFeatures(MgResourceIdentifier fsId, string className, MgPropertyCollection props)
 {
     try
     {
         MgdFeatureService fs = GetFeatureService();
         MgFeatureReader fr = null;
         try
         {
             fr = fs.InsertFeatures(fsId, className, props);
         }
         finally
         {
             if (fr != null)
                 fr.Close();
         }
     }
     catch (MgException ex)
     {
         var exMgd = new FeatureServiceException(ex.Message);
         exMgd.MgErrorDetails = ex.GetDetails();
         exMgd.MgStackTrace = ex.GetStackTrace();
         ex.Dispose();
         throw exMgd;
     }
 }
Пример #30
0
 internal int UpdateFeatures(MgResourceIdentifier fsId, string className, MgPropertyCollection props, string filter)
 {
     try
     {
         MgdFeatureService fs = GetFeatureService();
         return fs.UpdateFeatures(fsId, className, props, filter);
     }
     catch (MgException ex)
     {
         var exMgd = new FeatureServiceException(ex.Message);
         exMgd.MgErrorDetails = ex.GetDetails();
         exMgd.MgStackTrace = ex.GetStackTrace();
         ex.Dispose();
         throw exMgd;
     }
 }
Пример #31
0
    //---------------------------------------------------------------------------------------
    //
    //        ���ܣ�����Ҫ�����ݣ������ڹ�����¼
    //
    //         ���ߣ�
    //
    //         ���ڣ� 2007.5.23
    //        
    //         �޸���ʷ����
    //        
    //---------------------------------------------------------------------------------------
    private MgPropertyCollection populateParcelFeatureAttributes(MgPolygon geom, ParcelProperty newParcel)
    {
        MgPropertyCollection props = new MgPropertyCollection();
        MgAgfReaderWriter agfWriter = new MgAgfReaderWriter();
        props.Add(new MgGeometryProperty("GEOM", agfWriter.Write(geom)));
        props.Add(new MgStringProperty("ACRE", newParcel.Acreage));
        props.Add(new MgStringProperty("BILLADDR", newParcel.BillingAddr));
        props.Add(new MgStringProperty("DESC1", newParcel.Description1));
        props.Add(new MgStringProperty("DESC2", newParcel.Description2));
        props.Add(new MgStringProperty("DESC3", newParcel.Description3));
        props.Add(new MgStringProperty("DESC4", newParcel.Description4));
        props.Add(new MgStringProperty("LOTDIM", newParcel.LotDimension));
        props.Add(new MgInt32Property("SQFT", newParcel.LotSize));
        props.Add(new MgStringProperty("OWNER", newParcel.Owner));
        props.Add(new MgStringProperty("ZONE", newParcel.Zoning));

        return props;
    }
Пример #32
0
    private MgPropertyCollection buildPropertyCol(ParcelProperty newFeatureValue)
    {
        MgPropertyCollection props = new MgPropertyCollection();

        props.Add(new MgStringProperty("RACRE", newFeatureValue.Acreage));
        props.Add(new MgStringProperty("RBILAD", newFeatureValue.BillingAddr));
        props.Add(new MgStringProperty("RLDESCR1", newFeatureValue.Description1));
        props.Add(new MgStringProperty("RLDESCR2", newFeatureValue.Description2));
        props.Add(new MgStringProperty("RLDESCR3", newFeatureValue.Description3));
        props.Add(new MgStringProperty("RLDESCR4", newFeatureValue.Description4));
        props.Add(new MgStringProperty("RLOT", newFeatureValue.LotDimension));
        props.Add(new MgInt32Property("RSQFT", newFeatureValue.LotSize));
        props.Add(new MgStringProperty("RNAME", newFeatureValue.Owner));
        props.Add(new MgStringProperty("RTYPE", newFeatureValue.Zoning));

        return props;
    }
Пример #33
0
        internal void AddRedlineLayer(RedlineLayer layer, string fdoProvider)
        {
            var fsId = GetRegistryFeatureSource();
            MgFeatureCommandCollection commands = new MgFeatureCommandCollection();
            MgPropertyCollection insertVals = new MgPropertyCollection();

            MgStringProperty regId = new MgStringProperty("ResourceId", layer.FeatureSource);
            MgStringProperty ldfId = new MgStringProperty("LayerDefinition", layer.LayerDefinition);
            MgStringProperty name = new MgStringProperty("Name", layer.Name);
            MgStringProperty provider = new MgStringProperty("FdoProvider", fdoProvider);
            MgInt32Property geomTypes = new MgInt32Property("GeometryTypes", layer.GeometryTypes);
            MgInt32Property styleType = new MgInt32Property("StyleType", (int)layer.StyleType);

            insertVals.Add(regId);
            insertVals.Add(ldfId);
            insertVals.Add(name);
            insertVals.Add(provider);
            insertVals.Add(geomTypes);
            insertVals.Add(styleType);

            MgInsertFeatures insert = new MgInsertFeatures("Default:MarkupRegistry", insertVals);
            commands.Add(insert);

            MgPropertyCollection result = _featSvc.UpdateFeatures(fsId, commands, false);
            MgFeatureProperty insertResult = result.GetItem(0) as MgFeatureProperty;
            if (insertResult != null)
            {
                MgFeatureReader fr = insertResult.GetValue();
                fr.Close();
            }
        }
Пример #34
0
 public void InsertFeatures()
 {
     MgPropertyCollection propColl = new MgPropertyCollection();
     propColl.Add(new MgInt32Property("intProp", 10));
     MgInsertFeatures inf = new MgInsertFeatures("ClassName", propColl);
     Assert.AreEqual("ClassName", inf.FeatureClassName);
 }
Пример #35
0
 public void CreateNew(int uid, string infrastructureType)
 {
     if (!string.IsNullOrEmpty(infrastructureType) && (infrastructureType != "בחר מרשימה"))
     {
         SetInfrastructureType(this._parentLayer.FeatureSourceId, infrastructureType);
         MgGeometryProperty geometry = null;
         MgResourceIdentifier resId = new MgResourceIdentifier(this._parentLayer.FeatureSourceId);
         MgFeatureQueryOptions opt = new MgFeatureQueryOptions();
         opt.SetFilter(string.Format("{0}={1}", this._uidKey, uid));
         MgFeatureReader reader = this._helper.FeatureService.SelectFeatures(resId, this._parentLayer.FeatureClassName, opt);
         MgClassDefinition classDefinition = this._helper.FeatureService.GetClassDefinition(resId, this._parentLayer.FeatureClassName.Split(new char[] { ':' })[0], this._parentLayer.FeatureClassName.Split(new char[] { ':' })[1]);
         if (classDefinition != null)
         {
             string geomName = classDefinition.DefaultGeometryPropertyName;
             if (reader.ReadNext())
             {
                 MgByteReader value = reader.GetGeometry(geomName);
                 if (value != null)
                 {
                     geometry = new MgGeometryProperty(geomName, value);
                 }
             }
         }
         reader.Close();
         reader.Dispose();
         if (geometry != null)
         {
             MgDateTime today = new MgDateTime();
             MgPropertyCollection properties = new MgPropertyCollection {
             geometry,
             new MgInt32Property("UID", uid),
             new MgStringProperty("InfrastructureType", infrastructureType),
             new MgStringProperty("OperationType", "לא מוגדר"),
             new MgStringProperty("Status", "פתוח"),
             new MgStringProperty("FeatureSource", this._parentLayer.FeatureSourceId),
             new MgDateTimeProperty("dtStart", today),
             new MgDateTimeProperty("dtDue", today),
             new MgDateTimeProperty("dtUpdate", today)
         };
             MgInsertFeatures insert = new MgInsertFeatures("Maintenance", properties);
             MgFeatureCommandCollection commands = new MgFeatureCommandCollection {
             insert
         };
             this._helper.FeatureService.UpdateFeatures(this._sdfResId, commands, false);
         }
     }
 }
Пример #36
0
        private MgPropertyCollection CreatePropertyCollection(MgByteReader byteReader)
        {
            MgPropertyCollection propertyValues = new MgPropertyCollection();

            propertyValues.Add(new MgStringProperty("Text", GetParameter(this.args, "TEXT")));
            propertyValues.Add(new MgStringProperty("ReverseText", ReverseString(GetParameter(this.args, "TEXT"))));
            if (_hasProjectIdField)
            {
                propertyValues.Add(new MgInt32Property("ProjectId", GetProjectId()));
            }
            propertyValues.Add(new MgGeometryProperty("Geometry", byteReader));

            return propertyValues;
        }
    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:";
            }
        }
    }
Пример #38
0
        /* OldUpdateFeature
        public void oldUpdateFeature(string filter)
        {
            string featureclassname = string.empty;

            mgresourceidentifier featureresid = new mgresourceidentifier(mlayer.getfeaturesourceid());

            mgbytereader reader1 = msiteutilities.resourceservice.getresourceheader(featureresid);
            string s = reader1.tostring();
            //join update
            mgstringcollection r = msiteutilities.featureservice.getclasses(featureresid, mlayer.featureclassname.split(':')[0]);
            if (r.getcount() > 1)
            {
                mgclassdefinition classdefinition = msiteutilities.featureservice.getclassdefinition(featureresid, mlayer.featureclassname.split(':')[0], mlayer.featureclassname.split(':')[1]);
                dictionary<string, list<mgpropertydefinition>> propcollection = new dictionary<string, list<mgpropertydefinition>>();
                foreach(var item in classdefinition.getproperties())
                {
                    string[] strs = item.qualifiedname.split('.');
                    if(!propcollection.containskey(strs[0]))
                    {
                        propcollection.add(strs[0], new list<mgpropertydefinition>());
                    }
                    propcollection[strs[0]].add(item);
                }
                string joinedschema = r.getitem(1);
                string[] arr = joinedschema.split(']');
                string schemaname = arr[2];
                string prefix = arr[1].remove(0, 1);
                string joinname = arr[0].remove(0, 1);
                featureclassname = r.getitem(0);
                dictionary<string, featproperty> parentproperties = new dictionary<string, featproperty>();
                dictionary<string, featproperty> childproperties = new dictionary<string, featproperty>();
                foreach (var item in propertiescollection)
                {
                    if (item.key.indexof(prefix) >= 0)
                    {
                        item.value.name = item.value.name.substring(prefix.length);
                        childproperties.add(item.value.name, item.value);
                    }
                    else
                    {
                        parentproperties.add(item.key, item.value);
                    }
                }

                updatingfeature(featureresid, featureclassname, filter, parentproperties);

                if (propertiescollection.containskey("uid"))
                {
                    mgresourceidentifier childresid = new mgresourceidentifier(featureresid.tostring());
                    string childfeatureclassname = schemaname.split(':')[1];
                    string childupdatingfilter = string.format("uid={0}", propertiescollection["uid"].value);
                    childresid.setname(childfeatureclassname);
                    updatingfeature(childresid, schemaname, childupdatingfilter, childproperties);
                }
                return;
            }
            else
            {
                updatingfeature(featureresid, featureclassname, filter, propertiescollection);
            }
        }
        */
        private void UpdatingFeature(MgResourceIdentifier featureResId, string FeatureClassName, string Filter, Dictionary<string, FeatProperty> propCollection)
        {
            string _filter = "FeatId LIKE '%%'";

            MgFeatureQueryOptions queryOptions = new MgFeatureQueryOptions();
            queryOptions.SetFilter(_filter);

            MgFeatureReader featureReader = mSiteUtilities.FeatureService.SelectFeatures(featureResId, FeatureClassName.Split(':')[1], null);

            featureReader = mSiteUtilities.FeatureService.SelectFeatures(featureResId, FeatureClassName.Split(':')[1], queryOptions);

            featureReader.ReadNext();
            //---------------------------------
            //-----lets start update
            //---------------------------------
            MgFeatureCommandCollection updCommands = new MgFeatureCommandCollection();

            MgPropertyCollection properties = new MgPropertyCollection();
            foreach (var item in propCollection)
            {
                try
                {
                    MgProperty prop = item.Value.GenerateProperty();
                    if (prop != null)
                    {
                        prop.Name = item.Key;
                        properties.Add(prop);
                    }
                }
                catch (InvalidOperationException)
                { }
            }

            if (FeatureClassName == string.Empty)
                FeatureClassName = mLayer.FeatureClassName;
            if (properties.Count > 0)
            {
                MgUpdateFeatures updateCommand = new MgUpdateFeatures(FeatureClassName, properties, Filter);
                updCommands.Add(updateCommand);

                MgPropertyCollection res = mSiteUtilities.FeatureService.UpdateFeatures(featureResId, updCommands, false);

                mSiteUtilities.Map.Save(mSiteUtilities.ResourceService);
                //---------------------------------
                //-----end of update
                //---------------------------------
                //====================================================================
            }
            featureReader.Close();
        }
Пример #39
0
        public void FeatureCommandCollection()
        {
            MgPropertyCollection propVals = new MgPropertyCollection();
            MgInt32Property prop = new MgInt32Property("prop", 1);
            propVals.Add(prop);
            MgUpdateFeatures update = new MgUpdateFeatures("class2", propVals, "where cat < dog");
            MgInsertFeatures insert = new MgInsertFeatures("class3", propVals);
            MgDeleteFeatures del = new MgDeleteFeatures("class1", "where cat > dog");

            MgFeatureCommandCollection coll = new MgFeatureCommandCollection();
            coll.Add(update);
            coll.Add(insert);
            coll.Add(del);

            Assert.AreEqual(3, coll.Count);
            Assert.AreEqual(MgFeatureCommandType.DeleteFeatures, coll[2].GetCommandType());
            coll[0] = coll[1];

            string txt = "";
            foreach (MgFeatureCommand cmd in coll)
            {
                txt += "[" + cmd.GetCommandType() + "]";
            }
            Assert.AreEqual("[0][0][2]", txt);
        }
Пример #40
0
        internal void InsertFeatures(MgResourceIdentifier fsId, string className, MgPropertyCollection props)
        {
            try
            {
                MgFeatureCommandCollection cmds = new MgFeatureCommandCollection();
                MgInsertFeatures insert = new MgInsertFeatures(className, props);
                cmds.Add(insert);

                MgFeatureService fs = (MgFeatureService)this.Connection.CreateService(MgServiceType.FeatureService);
                MgPropertyCollection result = fs.UpdateFeatures(fsId, cmds, false);

                ((MgFeatureProperty)result.GetItem(0)).GetValue().Close();
            }
            catch (MgException ex)
            {
                var exMgd = new FeatureServiceException(ex.Message);
                exMgd.MgErrorDetails = ex.GetDetails();
                exMgd.MgStackTrace = ex.GetStackTrace();
                ex.Dispose();
                throw exMgd;
            }
        }
Пример #41
0
        public void PropertyCollection()
        {
            MgPropertyCollection coll = new MgPropertyCollection();
            MgDoubleProperty dblProp = new MgDoubleProperty("DoubleProp", 1.1111);
            MgInt32Property intProp = new MgInt32Property("IntProp", 1);
            MgDateTime dateTime = new MgDateTime(2006, 9, 21);
            MgDateTimeProperty dateProp = new MgDateTimeProperty("DateProp", dateTime);
            MgSingleProperty single = new MgSingleProperty("SingleProp", (float) 2.2222);
            coll.Add(dblProp);
            coll.Add(intProp);
            coll.Add(dateProp);
            coll[2] = single;

            Assert.AreEqual(1.1111, (coll[0] as MgDoubleProperty).GetValue());
            Assert.AreEqual(MgPropertyType.Double, coll[0].GetPropertyType());
            Assert.AreEqual(MgPropertyType.Int32, coll[1].GetPropertyType());
            Assert.AreEqual(MgPropertyType.Single, coll[2].GetPropertyType());
            Assert.AreEqual((float) 2.2222, (coll[2] as MgSingleProperty).GetValue());
            Assert.AreEqual(3, coll.Count);

            Assert.AreEqual(MgPropertyType.Double, coll[0].GetPropertyType());

            string str = "";
            foreach (MgProperty prop in coll)
            {
                str = str+"["+prop.GetName()+"]";
            }
            Assert.AreEqual("[DoubleProp][IntProp][SingleProp]", str);
        }
Пример #42
0
        internal int UpdateFeatures(MgResourceIdentifier fsId, string className, MgPropertyCollection props, string filter)
        {
            try
            {
                MgFeatureCommandCollection cmds = new MgFeatureCommandCollection();
                MgUpdateFeatures update = new MgUpdateFeatures(className, props, filter);
                cmds.Add(update);

                MgFeatureService fs = (MgFeatureService)this.Connection.CreateService(MgServiceType.FeatureService);
                MgPropertyCollection result = fs.UpdateFeatures(fsId, cmds, false);

                var ip = result.GetItem(0) as MgInt32Property;
                if (ip != null)
                    return ip.GetValue();
                return -1;
            }
            catch (MgException ex)
            {
                var exMgd = new FeatureServiceException(ex.Message);
                exMgd.MgErrorDetails = ex.GetDetails();
                exMgd.MgStackTrace = ex.GetStackTrace();
                ex.Dispose();
                throw exMgd;
            }
        }
Пример #43
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();
            }
        }
Пример #44
0
        internal void UpdateRedlineText(string text, int[] ids)
        {
            MgMapBase map = _viewer.GetMap();
            MgLayerCollection layers = map.GetLayers();
            MgLayerBase redlineLayer = layers.GetItem(_layer.SystemName);

            //HACK: Workaround FeatId leaky abstraction in SHP provider
            MgClassDefinition cls = redlineLayer.GetClassDefinition();
            MgPropertyDefinitionCollection idProps = cls.GetIdentityProperties();
            MgPropertyDefinition idProp = idProps.GetItem(0);

            redlineLayer.ForceRefresh();

            //This lib doesn't reference mg-desktop so the convenience APIs aren't available to us
            //Gotta go the old verbose route
            List<string> filters = new List<string>();
            foreach (int id in ids)
            {
                filters.Add(idProp.Name + " = " + id);
            }
            string updateFilter = string.Join(" OR ", filters.ToArray());
            MgFeatureCommandCollection commands = new MgFeatureCommandCollection();
            MgPropertyCollection updateValues = new MgPropertyCollection();
            MgStringProperty updateProp = new MgStringProperty(RedlineSchemaFactory.TEXT_NAME, text);
            updateValues.Add(updateProp);
            
            MgUpdateFeatures update = new MgUpdateFeatures(redlineLayer.FeatureClassName, updateValues, updateFilter);
            commands.Add(update);

            MgPropertyCollection result = redlineLayer.UpdateFeatures(commands);
            MgInt32Property updateResult = result.GetItem(0) as MgInt32Property;
            MgStringProperty errorResult = result.GetItem(0) as MgStringProperty;
            if (errorResult != null)
            {
                throw new Exception(errorResult.GetValue());
            }
            _viewer.RefreshMap();
        }
Пример #45
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();
                }
            }
        }
Пример #46
0
        private void InsertRedlineGeometry(string text, MgGeometry geom, RedlineAction onRedlineAdded)
        {
            MgPropertyCollection feature = new MgPropertyCollection();
            MgByteReader agf = _agfRW.Write(geom);
            MgGeometryProperty geomProp = new MgGeometryProperty(RedlineSchemaFactory.GEOM_NAME, agf);
            feature.Add(geomProp);
            MgStringProperty strProp = new MgStringProperty(RedlineSchemaFactory.TEXT_NAME, text);
            feature.Add(strProp);

            MgMapBase map = _viewer.GetMap();
            MgLayerCollection layers = map.GetLayers();
            MgLayerBase redlineLayer = layers.GetItem(_layer.SystemName);
            MgClassDefinition cls = redlineLayer.GetClassDefinition();
            MgPropertyDefinitionCollection idProps = cls.GetIdentityProperties();
            MgPropertyDefinition idProp = idProps.GetItem(0);

            redlineLayer.ForceRefresh();

            //This lib doesn't reference mg-desktop so the convenience APIs aren't available to us
            //Gotta go the old verbose route
            MgFeatureCommandCollection commands = new MgFeatureCommandCollection();
            
            MgInsertFeatures insert = new MgInsertFeatures(redlineLayer.FeatureClassName, feature);
            commands.Add(insert);

            MgPropertyCollection result = redlineLayer.UpdateFeatures(commands);
            //Insert result is a MgFeatureProperty containing an MgFeatureReader
            MgFeatureProperty insertResult = result.GetItem(0) as MgFeatureProperty;
            MgStringProperty errorResult = result.GetItem(0) as MgStringProperty;
            if (insertResult != null)
            {
                var reader = insertResult.GetValue();
                int inserted = 0;
                int? id = null;
                try
                {
                    if (reader.ReadNext())
                    {
                        inserted++;
                        id = reader.GetInt32(idProp.Name);
                    }
                }
                catch (MgException ex)
                {
                    ex.Dispose();
                }
                finally
                {
                    reader.Close();
                }
                if (inserted > 0)
                {
                    _viewer.RefreshMap();
                    onRedlineAdded(id, text);
                }
            }
            else if (errorResult != null)
            {
                throw new Exception(errorResult.GetValue());
            }
        }
Пример #47
0
    public bool ShowSpatialFilter()
    {
        bool result = true;
        MgUserInformation userInfo = new MgUserInformation(Request["SESSION"]);
        MgSiteConnection siteConnection = new MgSiteConnection();
        siteConnection.Open(userInfo);

        MgResourceIdentifier sdfResId = new MgResourceIdentifier("Session:" + Request["SESSION"] + "//Filter.FeatureSource");

        MgResourceService resourceService = siteConnection.CreateService(MgServiceType.ResourceService) as MgResourceService;
        MgFeatureService featureService = siteConnection.CreateService(MgServiceType.FeatureService) as MgFeatureService;

        MgFeatureCommandCollection updateCommands = new MgFeatureCommandCollection();

        MgMap map = new MgMap();
        map.Open(resourceService, Request["MAPNAME"]);

        MgLayer layer = null;
        MgLayerCollection layers = map.GetLayers();
        if (layers.Contains("_QuerySpatialFilter"))
        {
            layer = (MgLayer)layers.GetItem("_QuerySpatialFilter");
            //updateCommands.Add(new MgDeleteFeatures("Filter", "ID > 0"));
        }
        else
        {
            // Create the Feature Source (SDF)

            MgFeatureSchema sdfSchema = this.CreateFilterSchema();
            MgCreateSdfParams sdfParams = new MgCreateSdfParams("MAPCS", map.GetMapSRS(), sdfSchema);
            featureService.CreateFeatureSource(sdfResId, sdfParams);

            // Create the Layer

            MgResourceIdentifier layerResId = new MgResourceIdentifier("Session:" + Request["SESSION"] + "//Filter.LayerDefinition");
            String layerDefinition = File.ReadAllText(GetQueryXmlTemplatePath());
            layerDefinition = layerDefinition.Replace("%s", sdfResId.ToString());

            MgByteReader reader = new MgByteReader(layerDefinition, "text/xml");
            resourceService.SetResource(layerResId, reader, null);

            layer = new MgLayer(layerResId, resourceService);

            layer.SetName("_QuerySpatialFilter");
            layer.SetLegendLabel("תחום זמני");
            layer.SetDisplayInLegend(true);
            layer.SetSelectable(true);
            layer.ForceRefresh();
            layer.NeedsRefresh();

            layers.Insert(0, layer);
        }

        // Make the layer visible

        layer.SetVisible(true);
        map.Save(resourceService);

        // Add the geometry to the filter feature source
        MgPolygon polygon = this.CreatePolygonFromGeomText(Request["GEOMTEXT"].ToString());
        MgAgfReaderWriter agfWriter = new MgAgfReaderWriter();
        MgByteReader byteReader = agfWriter.Write(polygon);

        MgPropertyCollection propertyValues = new MgPropertyCollection();
        propertyValues.Add(new MgGeometryProperty("Geometry", byteReader));
        try
        {
            updateCommands.Add(new MgInsertFeatures("Filter", propertyValues));

            featureService.UpdateFeatures(sdfResId, updateCommands, false);
        }
        catch { }

        return result;
    }
Пример #48
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;
    }
Пример #49
0
        internal static void Populate(MgPropertyCollection props, IMutableRecord record)
        {
            for (int i = 0; i < record.FieldCount; i++)
            {
                var    pt   = record.GetPropertyType(i);
                string name = record.GetName(i);
                if (record.IsNull(i))
                {
                    switch (pt)
                    {
                    case PropertyValueType.Blob:
                    {
                        var propVal = new MgBlobProperty(name, null);
                        propVal.SetNull(true);
                        props.Add(propVal);
                    }
                    break;

                    case PropertyValueType.Boolean:
                    {
                        var propVal = new MgBooleanProperty(name, false);
                        propVal.SetNull(true);
                        props.Add(propVal);
                    }
                    break;

                    case PropertyValueType.Byte:
                    {
                        var propVal = new MgByteProperty(name, 0);
                        propVal.SetNull(true);
                        props.Add(propVal);
                    }
                    break;

                    case PropertyValueType.Clob:
                    {
                        var propVal = new MgClobProperty(name, null);
                        propVal.SetNull(true);
                        props.Add(propVal);
                    }
                    break;

                    case PropertyValueType.DateTime:
                    {
                        var propVal = new MgDateTimeProperty(name, null);
                        propVal.SetNull(true);
                        props.Add(propVal);
                    }
                    break;

                    case PropertyValueType.Double:
                    {
                        var propVal = new MgDoubleProperty(name, 0.0);
                        propVal.SetNull(true);
                        props.Add(propVal);
                    }
                    break;

                    case PropertyValueType.Geometry:
                    {
                        var propVal = new MgGeometryProperty(name, null);
                        propVal.SetNull(true);
                        props.Add(propVal);
                    }
                    break;

                    case PropertyValueType.Int16:
                    {
                        var propVal = new MgInt16Property(name, 0);
                        propVal.SetNull(true);
                        props.Add(propVal);
                    }
                    break;

                    case PropertyValueType.Int32:
                    {
                        var propVal = new MgInt32Property(name, 0);
                        propVal.SetNull(true);
                        props.Add(propVal);
                    }
                    break;

                    case PropertyValueType.Int64:
                    {
                        var propVal = new MgInt64Property(name, 0L);
                        propVal.SetNull(true);
                        props.Add(propVal);
                    }
                    break;

                    case PropertyValueType.Single:
                    {
                        var propVal = new MgSingleProperty(name, 0.0f);
                        propVal.SetNull(true);
                        props.Add(propVal);
                    }
                    break;

                    case PropertyValueType.String:
                    {
                        var propVal = new MgStringProperty(name, "");
                        propVal.SetNull(true);
                        props.Add(propVal);
                    }
                    break;

                    default:
                        throw new NotSupportedException();
                    }
                }
                else
                {
                    switch (pt)
                    {
                    case PropertyValueType.Blob:
                    {
                        var bytes = record.GetBlob(i);
                        var br    = new MgByteSource(bytes, bytes.Length);
                        var bv    = new MgBlobProperty(name, br.GetReader());
                        props.Add(bv);
                    }
                    break;

                    case PropertyValueType.Boolean:
                    {
                        props.Add(new MgBooleanProperty(name, record.GetBoolean(i)));
                    }
                    break;

                    case PropertyValueType.Byte:
                    {
                        props.Add(new MgByteProperty(name, record.GetByte(i)));
                    }
                    break;

                    case PropertyValueType.Clob:
                    {
                        var bytes = record.GetBlob(i);
                        var br    = new MgByteSource(bytes, bytes.Length);
                        var bv    = new MgClobProperty(name, br.GetReader());
                        props.Add(bv);
                    }
                    break;

                    case PropertyValueType.DateTime:
                    {
                        var dt  = record.GetDateTime(i);
                        var mdt = new MgDateTime((short)dt.Year, (short)dt.Month, (short)dt.Day, (short)dt.Hour, (short)dt.Minute, (short)dt.Second, dt.Millisecond * 1000);
                        props.Add(new MgDateTimeProperty(name, mdt));
                    }
                    break;

                    case PropertyValueType.Double:
                    {
                        props.Add(new MgDoubleProperty(name, record.GetDouble(i)));
                    }
                    break;

                    case PropertyValueType.Geometry:
                    {
                        MgByteReader agf = GeomConverter.GetAgf(record.GetGeometry(i));
                        props.Add(new MgGeometryProperty(name, agf));
                    }
                    break;

                    case PropertyValueType.Int16:
                    {
                        props.Add(new MgInt16Property(name, record.GetInt16(i)));
                    }
                    break;

                    case PropertyValueType.Int32:
                    {
                        props.Add(new MgInt32Property(name, record.GetInt32(i)));
                    }
                    break;

                    case PropertyValueType.Int64:
                    {
                        props.Add(new MgInt64Property(name, record.GetInt64(i)));
                    }
                    break;

                    case PropertyValueType.Single:
                    {
                        props.Add(new MgSingleProperty(name, record.GetSingle(i)));
                    }
                    break;

                    case PropertyValueType.String:
                    {
                        props.Add(new MgStringProperty(name, record.GetString(i)));
                    }
                    break;

                    default:
                        throw new NotSupportedException();
                    }
                }
            }
        }
Пример #50
0
    //----------------------------------------------------------------------------------------
    // �� �ܣ� �ͷ�����
    //
    // �� �ߣ�
    //
    //
    // �� �ڣ�2007.05.#
    //
    //-----------------------------------------------------------------------------------------
    void ReleaseReader(MgPropertyCollection res, MgFeatureCommandCollection commands)
    {
        if (res == null)
            return;

        for (int i = 0; i < res.GetCount(); i++)
        {
            MgFeatureCommand cmd = commands.GetItem(i);
            if (cmd is MgInsertFeatures)
            {
                MgFeatureProperty resProp = res.GetItem(i) as MgFeatureProperty;
                if (resProp != null)
                {
                    MgFeatureReader reader = resProp.GetValue() as MgFeatureReader;
                    if (reader == null)
                        return;
                    reader.Close();
                }
            }
        }
    }
Пример #51
0
        public string AddNaaz(double X, double Y, string MapSession, string mapName)
        {
            try
            {
                string dataSource = "Session:" + MapSession + "//RedlineSymbol.FeatureSource";
                string layerDef = "Session:" + MapSession + "//RedlineSymbol.LayerDefinition";
                //  MgSiteConnection site = MGMapObject.GetMgSite(MapSession);

                MgUserInformation userInfo = new MgUserInformation(MapSession);
                MgSiteConnection siteConnection = new MgSiteConnection();
                siteConnection.Open(userInfo);

                // Create a ReserviceService object and use it to open the Map
                // object from the sessions repository. Use the Map object to
                // determine if the "AddressMarker" layer is visible.

                MgResourceService resourceService = siteConnection.CreateService(MgServiceType.ResourceService) as MgResourceService;
                MgMap map = new MgMap();
                map.Open(resourceService, mapName);
              //  MgLayer locationLayer = GetLayerByName(map, "LocationMarker");

                if (siteConnection == null)
                {
                    return "יש לרענן את האתר , לחיצה על כפתור הבית בפינה השמאלית עליונה";
                }
                MgFeatureService featureSrvc = siteConnection.CreateService(2) as MgFeatureService;
                MgResourceService resourceSrvc = siteConnection.CreateService(0) as MgResourceService;
                MgResourceIdentifier dataSourceId = new MgResourceIdentifier(dataSource);
                MgResourceIdentifier layerDefId = new MgResourceIdentifier(layerDef);
                //MgMap map = MGMapObject.GetMgMap(resourceSrvc, mapName);
                MgGeometryFactory geomFactory = new MgGeometryFactory();
                MgPoint geom = geomFactory.CreatePoint(geomFactory.CreateCoordinateXY(X, Y));
                if (DataSourceExists(resourceSrvc, dataSourceId))
                {
                    resourceSrvc.DeleteResource(dataSourceId);
                }
                MgClassDefinition classDef = CreateFeatureClass("RedlineSymbol", "RedlineSymbol");
                AddFeatureClassProperty(classDef, "KEY", 7, true);
                SetGeometryProp(classDef);
                MgFeatureSchema schema = CreateSchema(classDef, "RedlineSymbolShema", "RedlineSymbolShema");
                MgCreateSdfParams parameters = new MgCreateSdfParams("ArbitraryXY", GetMapSrs(map), schema);
                featureSrvc.CreateFeatureSource(dataSourceId, parameters);
                MgLayerCollection layers = map.GetLayers();
                MgLayer layer = FindLayer(layers, layerDef);
                LayerDefinitionFactory LayerDeffactory = new LayerDefinitionFactory();
                if ((layer == null) && LayerDeffactory.CreateLayerDef("SymbolLayerDef_Cell", dataSource, "RedlineSymbol", ""))
                {
                    resourceSrvc.SetResource(layerDefId, LayerDeffactory.layerDefContent, null);
                    layer = new MgLayer(layerDefId, resourceSrvc);
                    layer.SetDisplayInLegend(false);
                    layer.SetSelectable(false);
                    layer.SetVisible(true);
                    layer.SetLegendLabel("ZoomSymbol");
                    layers.Insert(0, layer);
                }
                MgPropertyCollection featureProps = new MgPropertyCollection();
                AddPointFeature("RedlineSymbol", featureProps, geom, featureSrvc, dataSourceId);
                if (layer != null)
                {
                    layer.ForceRefresh();
                }
                map.Save(resourceSrvc);
                siteConnection = null;
                map = null;
                dataSourceId = null;
                layerDefId = null;
                featureSrvc = null;
                resourceSrvc = null;
                geomFactory = null;
                geom = null;
                classDef = null;
                schema = null;
                featureProps = null;
                parameters = null;
                layers = null;
                layer = null;
                LayerDeffactory = null;
                GC.Collect();
                GC.WaitForPendingFinalizers();
                return "Ok";
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
Пример #52
0
 public SelectedFeatureInfo(MgLayerBase _layer, MgPropertyCollection _properties)
 {
     layer      = _layer;
     properties = _properties;
 }
Пример #53
0
        /// <summary>Получает набор свойств MgPropertyCollection из текущей записи _reader в соответствии со списком _listed_prop_defs</summary>
        /// <param name="_reader"></param>
        /// <param name="_listed_prop_defs"></param>
        /// <returns></returns>
        internal static MgPropertyCollection GetPropertiesFromReader(MgFeatureReader _reader, MgPropertyDefinitionCollection _listed_prop_defs)
        {
            MgPropertyCollection result_props = new MgPropertyCollection();

            MgPropertyDefinitionCollection reader_prop_defs = _reader.GetClassDefinition().GetProperties();

            foreach (MgPropertyDefinition curr_prop_def in _listed_prop_defs)
            {
                if (!reader_prop_defs.Contains(curr_prop_def.Name) || _reader.IsNull(curr_prop_def.Name))
                {
                    continue;
                }

                int property_type = _reader.GetPropertyType(curr_prop_def.Name);
                if (property_type == MgPropertyType.Blob)
                {
                    result_props.Add(
                        new MgBlobProperty(curr_prop_def.Name, _reader.GetBLOB(curr_prop_def.Name))
                        );
                }
                else if (property_type == MgPropertyType.Boolean)
                {
                    result_props.Add(
                        new MgBooleanProperty(curr_prop_def.Name, _reader.GetBoolean(curr_prop_def.Name))
                        );
                }
                else if (property_type == MgPropertyType.Byte)
                {
                    result_props.Add(
                        new MgByteProperty(curr_prop_def.Name, _reader.GetByte(curr_prop_def.Name))
                        );
                }
                else if (property_type == MgPropertyType.Clob)
                {
                    result_props.Add(
                        new MgClobProperty(curr_prop_def.Name, _reader.GetCLOB(curr_prop_def.Name))
                        );
                }
                else if (property_type == MgPropertyType.DateTime)
                {
                    result_props.Add(
                        new MgDateTimeProperty(curr_prop_def.Name, _reader.GetDateTime(curr_prop_def.Name))
                        );
                }
                else if (property_type == MgPropertyType.Double)
                {
                    result_props.Add(
                        new MgDoubleProperty(curr_prop_def.Name, _reader.GetDouble(curr_prop_def.Name))
                        );
                }
                else if (property_type == MgPropertyType.Feature)
                {
                    result_props.Add(
                        new MgFeatureProperty(curr_prop_def.Name, _reader.GetFeatureObject(curr_prop_def.Name))
                        );
                }
                else if (property_type == MgPropertyType.Geometry)
                {
                    result_props.Add(
                        new MgGeometryProperty(curr_prop_def.Name, _reader.GetGeometry(curr_prop_def.Name))
                        );
                }
                else if (property_type == MgPropertyType.Int16)
                {
                    result_props.Add(
                        new MgInt16Property(curr_prop_def.Name, _reader.GetInt16(curr_prop_def.Name))
                        );
                }
                else if (property_type == MgPropertyType.Int32)
                {
                    result_props.Add(
                        new MgInt32Property(curr_prop_def.Name, _reader.GetInt32(curr_prop_def.Name))
                        );
                }
                else if (property_type == MgPropertyType.Int64)
                {
                    result_props.Add(
                        new MgInt64Property(curr_prop_def.Name, _reader.GetInt64(curr_prop_def.Name))
                        );
                }
                else if (property_type == MgPropertyType.Raster)
                {
                    result_props.Add(
                        new MgRasterProperty(curr_prop_def.Name, _reader.GetRaster(curr_prop_def.Name))
                        );
                }
                else if (property_type == MgPropertyType.Single)
                {
                    result_props.Add(
                        new MgSingleProperty(curr_prop_def.Name, _reader.GetSingle(curr_prop_def.Name))
                        );
                }
                else if (property_type == MgPropertyType.String)
                {
                    result_props.Add(
                        new MgStringProperty(curr_prop_def.Name, _reader.GetString(curr_prop_def.Name))
                        );
                }
            }              //foreach

            return(result_props);
        }
Пример #54
0
        }        //method

        internal static void SelectionToDataGridView(MgSelectionBase _selection_base)
        {
            palette_window.links_control.is_suspended = true;         // информируем о заморозке
            palette_window.links_control.SuspendLayout();             // замораживаем логику
            palette_window.links_control.data_grid.Enabled = false;
            palette_window.links_control.data_grid.SuspendLayout();   // замораживаем логику DataGridView
            palette_window.links_control.layers_list.Enabled = false;

            palette_window.links_control.progressbar_in_status.Visible = true;             // включение ProgressBar
            palette_window.links_control.status_strip.Refresh();



            MgReadOnlyLayerCollection layers = _selection_base.GetLayers();

            int curr_features_count = 0, features_count = 0;

            // подсчет количества выбранных объектов
            foreach (MgLayerBase layer in layers)
            {
                features_count += _selection_base.GetSelectedFeaturesCount(layer, layer.FeatureClassName);
            }

            if (features_count == 0)
            {
                return;
            }

            // заполнение списка слоев
            palette_window.links_control.layers_list.Items.Clear();             // очищаем список

            if (layers.Count > 1)
            {
                palette_window.links_control.layers_list.Items.Add("(Все выбранные)");
            }

            foreach (MgLayerBase layer in layers)
            {
                palette_window.links_control.layers_list.Items.Add(layer.Name);
            }
            palette_window.links_control.layers_list.SelectedIndex = 0;

            // заполнение DataGridView
            palette_window.links_control.data_grid.Rows.Clear();              // очищаем строки

            foreach (MgLayerBase layer in layers)
            {
                int curr_ftr_class_idx = config.IndexOf(layer.FeatureClassName);
                if (curr_ftr_class_idx == -1)
                {
                    curr_features_count += _selection_base.GetSelectedFeaturesCount(layer, layer.FeatureClassName);;
                    palette_window.links_control.UpdateStatusRowCounterLabelAndProgressBar(curr_features_count, features_count);
                    continue;
                }
                FeatureClassLinkInfo curr_link_info = config.link_info_array[curr_ftr_class_idx];

                MgFeatureReader ftr_rdr = _selection_base.GetSelectedFeatures(layer, layer.FeatureClassName, false);

                MgPropertyDefinitionCollection identity_prop_defs = ftr_rdr.GetClassDefinition().GetIdentityProperties();                 // получаем набор идентификационных полей

                while (ftr_rdr.ReadNext())
                {
                    curr_features_count++;

                    DataGridViewRow link_row = new DataGridViewRow();   // новая строка

                    DataGridViewLinkCell link_cell;                     // ячейка

                    // формирование URL
                    link_cell = new DataGridViewLinkCell();

                    string title_str = ResolveLinkStringByValueFromReader(ftr_rdr, curr_link_info.LinkTitle);
                    link_cell.Value       = String.IsNullOrEmpty(title_str)? "<Null>": title_str;
                    link_cell.ToolTipText =
                        curr_link_info.LinkCommandPath
                        + command_splitter
                        + ResolveLinkStringByValueFromReader(ftr_rdr, curr_link_info.LinkURL);
                    link_row.Cells.Add(link_cell);                     // вставка ячейки

                    // формирование ID
                    MgPropertyCollection curr_identity_props = GetPropertiesFromReader(ftr_rdr, identity_prop_defs);

                    SelectedFeatureInfo sel_info = new SelectedFeatureInfo(layer, curr_identity_props);
                    link_cell       = new DataGridViewLinkCell();
                    link_cell.Value = sel_info;
                    link_row.Cells.Add(link_cell);                     // вставка ячейки

                    // добавлени строки в DataGridView
                    palette_window.links_control.data_grid.Rows.Add(link_row);

                    // обновление ProgressBar'а и счетчика строк
                    palette_window.links_control.UpdateStatusRowCounterLabelAndProgressBar(curr_features_count, features_count);
                }                                                                               /// while (ftr_rdr.ReadNext())
            }                                                                                   /// foreach (MgLayerBase layer in layers)

            palette_window.links_control.URL.SortMode = DataGridViewColumnSortMode.NotSortable; // сброс сортировки
            palette_window.links_control.URL.SortMode = DataGridViewColumnSortMode.Automatic;   // на исходную автоматическую

            palette_window.links_control.data_grid.SelectAll();                                 // выбираем все строки

            palette_window.links_control.progressbar_in_status.Visible = false;

            palette_window.links_control.layers_list.Enabled = true;
            palette_window.links_control.data_grid.Enabled   = true;
            palette_window.links_control.data_grid.ResumeLayout();   // размораживаем логику DataGridView
            palette_window.links_control.ResumeLayout();             // размораживаем логику
            palette_window.links_control.is_suspended = false;

            palette_window.links_control.UpdateStatusRowCounterLabel();             // обновляем строку статуса
        }
Пример #55
0
        private void InsertRedlineGeometry(string text, MgGeometry geom, RedlineAction onRedlineAdded)
        {
            MgPropertyCollection feature  = new MgPropertyCollection();
            MgByteReader         agf      = _agfRW.Write(geom);
            MgGeometryProperty   geomProp = new MgGeometryProperty(RedlineSchemaFactory.GEOM_NAME, agf);

            feature.Add(geomProp);
            MgStringProperty strProp = new MgStringProperty(RedlineSchemaFactory.TEXT_NAME, text);

            feature.Add(strProp);

            MgMapBase         map                  = _viewer.GetMap();
            MgLayerCollection layers               = map.GetLayers();
            MgLayerBase       redlineLayer         = layers.GetItem(_layer.SystemName);
            MgClassDefinition cls                  = redlineLayer.GetClassDefinition();
            MgPropertyDefinitionCollection idProps = cls.GetIdentityProperties();
            MgPropertyDefinition           idProp  = idProps.GetItem(0);

            redlineLayer.ForceRefresh();

            //This lib doesn't reference mg-desktop so the convenience APIs aren't available to us
            //Gotta go the old verbose route
            MgFeatureCommandCollection commands = new MgFeatureCommandCollection();

            MgInsertFeatures insert = new MgInsertFeatures(redlineLayer.FeatureClassName, feature);

            commands.Add(insert);

            MgPropertyCollection result = redlineLayer.UpdateFeatures(commands);
            //Insert result is a MgFeatureProperty containing an MgFeatureReader
            MgFeatureProperty insertResult = result.GetItem(0) as MgFeatureProperty;
            MgStringProperty  errorResult  = result.GetItem(0) as MgStringProperty;

            if (insertResult != null)
            {
                var reader   = insertResult.GetValue();
                int inserted = 0;
                int?id       = null;
                try
                {
                    if (reader.ReadNext())
                    {
                        inserted++;
                        id = reader.GetInt32(idProp.Name);
                    }
                }
                catch (MgException ex)
                {
                    ex.Dispose();
                }
                finally
                {
                    reader.Close();
                }
                if (inserted > 0)
                {
                    _viewer.RefreshMap();
                    onRedlineAdded(id, text);
                }
            }
            else if (errorResult != null)
            {
                throw new Exception(errorResult.GetValue());
            }
        }
Пример #56
0
        private void UpdateCenterDebugPoint()
        {
            if (_debugCenter == null)
                _debugCenter = new MgPropertyCollection();

            var center = _wktRW.Read("POINT (" + _map.ViewCenter.Coordinate.X.ToString(CultureInfo.InvariantCulture) + " " + _map.ViewCenter.Coordinate.Y.ToString(CultureInfo.InvariantCulture) + ")"); //NOXLATE
            var agf = _agfRW.Write(center);
            if (!_debugCenter.Contains("Geometry")) //NOXLATE
            {
                MgGeometryProperty geom = new MgGeometryProperty("Geometry", agf); //NOXLATE
                _debugCenter.Add(geom);
            }
            else
            {
                MgGeometryProperty geom = (MgGeometryProperty)_debugCenter.GetItem("Geometry"); //NOXLATE
                geom.SetValue(agf);
            }

            int deleted = _debugLayer.DeleteFeatures(string.Empty);
            Trace.TraceInformation("Deleted {0} debug points", deleted); //NOXLATE
            var reader = _debugLayer.InsertFeatures(_debugCenter);
            int inserted = 0;
            while (reader.ReadNext())
            {
                inserted++;
            }
            reader.Close();
            Trace.TraceInformation("Added {0} debug points", inserted); //NOXLATE
            _debugLayer.ForceRefresh();
        }