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); }
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); }
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); }
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); }
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); }
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(); } } }
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); }
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)); }
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(); } }
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(); }
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(); }
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(); } }
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); }
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(); } }*/ }
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; }
//--------------------------------------------------------------------------------------- // // ���ܣ�����Ҫ�����ݣ������ڹ�����¼ // // ���ߣ� // // ���ڣ� 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; }
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); }
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(); } }
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(); }
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); }
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); }
//---------------------------------------------------------------------------------------- // �� �ܣ� ���ڴ�������ݣ�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; }
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(); }
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); }
public void InsertFeatures() { MgPropertyCollection propColl = new MgPropertyCollection(); propColl.Add(new MgInt32Property("intProp", 10)); MgInsertFeatures inf = new MgInsertFeatures("ClassName", propColl); Assert.AreEqual("ClassName", inf.FeatureClassName); }
private void UpdatingFeature(MgResourceIdentifier featureResId, string featureClassName, string filter, Dictionary<string, FeatureProperty> propCollection) { MgFeatureCommandCollection updCommands = new MgFeatureCommandCollection(); MgPropertyCollection properties = new MgPropertyCollection(); MgPropertyCollection properties2Log = new MgPropertyCollection(); if (this.InsertToLog) { properties2Log.Add(new MgInt32Property("ItemId", this.FeatId)); } foreach (KeyValuePair<string, FeatureProperty> item in propCollection) { try { MgProperty prop = item.Value.GenerateProperty(); MgProperty prop4Log = item.Value.GenerateProperty(false); if (prop4Log != null) { prop4Log.Name = item.Key; if (this.InsertToLog) { properties2Log.Add(prop4Log); } } if (prop != null) { prop.Name = item.Key; properties.Add(prop); } } catch (InvalidOperationException) { } } if (featureClassName == string.Empty) { featureClassName = this.Layer.FeatureClassName; } if (properties.Count > 0) { MgUpdateFeatures updateCommand = new MgUpdateFeatures(featureClassName, properties, filter); updCommands.Add(updateCommand); if (this.InsertToLog) { MgInsertFeatures insert = new MgInsertFeatures(featureClassName + "Log", properties2Log); updCommands.Add(insert); } this._helper.FeatureService.UpdateFeatures(featureResId, updCommands, false); this._helper.Map.Save(this._helper.ResourceService); } }
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()); } }
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); }
/// <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); }
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(); } } }
protected void Button2_Click(object sender, EventArgs e) { if (string.IsNullOrEmpty(Xcoord.Value) || string.IsNullOrEmpty(Ycoord.Value) || string.IsNullOrEmpty(kanam.Value)) { // Response.Write("<script type='text/javascript'>try{ zoom();}catch(e){}</script>"); ClientScript.RegisterStartupScript(GetType(), "zoomme", "<script>try{ zoomzfd();}catch(e){}</script>"); return; } /* String mgSessionId = GetRequestParameters()["SESSION"]; String mgMap = GetRequestParameters()["map"]; //GeocodeAddress addr = null; bool success = false; decimal LatInput=0; decimal LonInput=0;*/ // Initialize the web-extensions and connect to the Site using // the session identifier passed in the query string. try { InitializeWebTier(); //MgUserInformation userInfo = new MgUserInformation(mgSessionId); // mgSessionId = site.CreateSession(); MgUserInformation userInfo = new MgUserInformation(mgSessionId); MgSiteConnection siteConnection = new MgSiteConnection(); siteConnection.Open(userInfo); decimal LatInput = System.Convert.ToDecimal(Xcoord.Value); decimal LonInput = System.Convert.ToDecimal(Ycoord.Value); /* LatInput = System.Convert.ToDecimal(GetRequestParameters()["LatInput"]); LonInput = System.Convert.ToDecimal(GetRequestParameters()["LonInput"]);*/ // Make the request to geocoder.us passing the address. //addr = requestGeocodeAddress(address); if (LatInput != 0 && LonInput != 0) { //Request the specified address to the geocode service using REST, the // GET interface // if (targetsnew.InnerHtml == "") { targetsnewTitle.InnerHtml = "מיקום נוכחי :"; targetsoldTitle.InnerHtml = ""; targetsnew.InnerHtml = "<table>"; targetsnew.InnerHtml += "<tr><td><img src=\"../images/pushpinblue.jpg\">"; targetsnew.InnerHtml += "<a href=\"gotopoint.aspx?X=" + LonInput + "&Y=" + LatInput + "&Scale=2000\" target=\"scriptFrame\"> מיקום נמצא </a></td></tr>"; targetsnew.InnerHtml += "<tr><td align=left>X: " + LonInput + "</td></tr>"; targetsnew.InnerHtml += "<tr><td align=left>Y: " + LatInput + "<hr></td></tr>"; targetsnew.InnerHtml += "</table>"; } else { targetsoldTitle.InnerHtml = "מיקום קודם :"; targetsold.InnerHtml += targetsnew.InnerHtml; targetsnew.InnerHtml = "<table>"; targetsnew.InnerHtml += "<tr><td><img src=\"../images/pushpinblue.jpg\">"; targetsnew.InnerHtml += "<a href=\"gotopoint.aspx?X=" + LonInput + "&Y=" + LatInput + "&Scale=2000\" target=\"scriptFrame\"> מיקום נמצא </a></td></tr>"; targetsnew.InnerHtml += "<tr><td align=left>X: " + LonInput + "</td></tr>"; targetsnew.InnerHtml += "<tr><td align=left>Y: " + LatInput + "<hr></td></tr>"; targetsnew.InnerHtml += "</table>"; } // The geocode successfully returned a location. //if (IsDebugAssembly(this.GetType().Assembly)) // System.Diagnostics.Debugger.Launch(); MgResourceService resourceService = (MgResourceService)siteConnection.CreateService(MgServiceType.ResourceService); MgFeatureService featureService = (MgFeatureService)siteConnection.CreateService(MgServiceType.FeatureService); MgMap map = new MgMap(); map.Open(resourceService, mgMap); // map.Open(mgMap); // Check the map for the AddressMarker layer. If it does not // exist then create a feature source to store address results // and a layer to display them. MgResourceIdentifier locationMarkerDataResId = new MgResourceIdentifier("Session:" + mgSessionId + "//LocationMarker.FeatureSource"); // Session:7f4231a2-0d7e-11e2-8000-000c294ca3a6_en_7F0000010AFC0AFB0AFA//a2f5e4fb-0c3c-4ee7-bb5d-c8f4a226a68b.FeatureSource // MgResourceIdentifier locationMarkerDataResId = new MgResourceIdentifier("Library://rany1/Data/findLocation/temp/LocationMarker.FeatureSource"); // string layerDef = "Session:" + mgSessionId + "//LocationMarker.FeatureSource"; //string dataSource = "Library://rany1/Data/LocationMarker.FeatureSource"; /*string layerDef = "Library://rany1/Layers/LocationMarker.LayerDefinition"; MgLayerCollection colLays = map.GetLayers(); MgLayer layer = FindLayer(colLays, layerDef);*/ //// MgLayer locationLayer = FindLayerByName(,"LocationMarker") ;//GetLayerByName(map, "LocationMarker"); //MgLayerCollection colLays = map.GetLayers(); MgLayerCollection colLays = map.GetLayers(); MgLayer locationLayer = FindLayerByName(colLays, "LocationMarker"); if (locationLayer == null) { // diverr.InnerHtml += " לא נמצאו שכבות LocationMarker "; lf.CreateLocationMarkerFeatureSource(featureService, locationMarkerDataResId, map); locationLayer = lf.CreateLocationMarkerLayer(resourceService, locationMarkerDataResId, mgSessionId); map.GetLayers().Insert(0, locationLayer); } else if (locationLayer.GetVisible()) { // If the layer exists and is visible, then display the // previous results. //EmitAddressResults(featureService, locationMarkerDataResId, mgSessionId, Response); EmitLocationResults(featureService, locationMarkerDataResId, mgSessionId, HttpContext.Current.Response); } // Insert the results of the Geo-Code into the temporary // feature source and ensure the address marker layer // is visible. MgAgfReaderWriter geometryReaderWriter = new MgAgfReaderWriter(); MgGeometryFactory geometryFactory = new MgGeometryFactory(); MgPoint locationPoint = geometryFactory.CreatePoint(geometryFactory.CreateCoordinateXY(Convert.ToDouble(LonInput), Convert.ToDouble(LatInput))); MgPropertyCollection properties = new MgPropertyCollection(); properties.Add(new MgStringProperty("Address", "")); properties.Add(new MgGeometryProperty("Location", geometryReaderWriter.Write(locationPoint))); MgFeatureCommandCollection commands = new MgFeatureCommandCollection(); commands.Add(new MgInsertFeatures("LocationMarker", properties)); featureService.UpdateFeatures(locationMarkerDataResId, commands, false); locationLayer.SetVisible(true); locationLayer.ForceRefresh(); map.Save(resourceService); Response.Write("<script type='text/javascript'>try{ parent.parent.ZoomToView(" + px1.Value + ", " + py1.Value + ", " + kanam.Value + ", true);parent.parent.mapFrame.Refresh();}catch(e){}</script>"); /* success = true;*/ } else { // Response.Write("<tr><td>נקודת הציון לא נמצאה: <hr></td></tr>"); } } catch (MgException eee) { // Response.Write("<script type='text/javascript'>try{alert('rany'); parent.parent.ZoomToView(" + px1.Value + ", " + py1.Value + ", " + kanam.Value + ", true);parent.parent.mapFrame.Refresh();}catch(e){}</script>"); // Response.Write("<tr><td>" + eee.GetExceptionMessage() + "</td></tr>"); // Response.Write("<tr><td>" + eee.InnerException.Message + "</td></tr>"); Response.Write("<tr><td>" + eee.ToString() + "</td></tr>"); Response.Write("<tr><td>" + eee.GetBaseException() + "</td></tr>"); Response.Write("<tr><td>" + eee.GetStackTrace()+ "</td></tr>"); Response.Write("<tr><td>" + eee.GetExceptionMessage() + "</td></tr>"); Response.Write("<tr><td class=\"Spacer\"></td></tr>"); // Response.Write("<tr><td>" + eee.GetDetails() + "</td></tr>"); } }
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; }
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(); } } } }
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); }
/* 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(); }
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:"; } } }
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(); }
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:"; } } }
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(); } } } }
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(); } }
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()); } }
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; }