public static char ToFeatureCode(this FeatureClass featureClass) { switch (featureClass) { case FeatureClass.Country: return('A'); case FeatureClass.City: return('P'); case FeatureClass.WaterBody: return('H'); case FeatureClass.LandArea: return('L'); case FeatureClass.TransportRoute: return('R'); case FeatureClass.Facility: return('S'); case FeatureClass.GeographicLandmark: return('T'); case FeatureClass.UnderseaLandmark: return('U'); case FeatureClass.Vegetation: return('V'); default: throw new ArgumentException("Invalid Feature Class"); } }
public override DateTime?GetDate() { DateTime? result = null; const string objectId = "RecordedAt"; IActiveView activeView = ArcUtils.ActiveView; IEnvelope envelope = activeView.Extent; ISpatialFilter spatialFilter = new SpatialFilterClass { Geometry = envelope, GeometryField = FeatureClass.ShapeFieldName, SpatialRel = esriSpatialRelEnum.esriSpatialRelContains, SubFields = objectId }; var existsResult = FeatureClass.Search(spatialFilter, false); IFeature feature = existsResult.NextFeature(); if (feature != null) { // ReSharper disable UseIndexedProperty int imId = existsResult.FindField(objectId); object value = feature.get_Value(imId); result = (DateTime)value; // ReSharper restore UseIndexedProperty } return(result); }
public static async Task KeyPointsIntegration() { await QueuedTask.Run(() => { using (Geodatabase gdb1 = new Geodatabase(new FileGeodatabaseConnectionPath(new Uri(GeoDataTool.DefaultProject.DefaultGeodatabasePath)))) { gdb1.ApplyEdits(() => { FeatureClass voyageRiskKeyPoint = gdb1.OpenDataset <FeatureClass>(ConstDefintion.ConstFeatureClass_VoyageRiskKeyPoint); FeatureClassDefinition voyageRiskKeyPointDefinition = gdb1.GetDefinition <FeatureClassDefinition>(ConstDefintion.ConstFeatureClass_VoyageRiskKeyPoint); voyageRiskKeyPoint.DeleteRows(new QueryFilter() { WhereClause = "OBJECTID >= 1" }); string shapeFieldName = voyageRiskKeyPointDefinition.GetShapeField(); RiskAssessment(gdb1, voyageRiskKeyPoint, ConstDefintion.ConstFeatureClass_VoyageMaskInternalPoint, 1); RiskAssessment(gdb1, voyageRiskKeyPoint, ConstDefintion.ConstFeatureClass_VoyageMaskOutlinePoint, 0); double midLocaRisk = Math.Pow(0.5, 3.03); RiskAssessment(gdb1, voyageRiskKeyPoint, ConstDefintion.ConstFeatureClass_VoyageMaskLocaMidPoint, midLocaRisk); RiskAssessment(gdb1, voyageRiskKeyPoint, ConstDefintion.ConstFeatureClass_VoyageMaskRiskMidPoint, 0.5); }); } }); }
public static bool CanChange([NotNull] Feature feature, [NotNull] HashSet <long> editableClassHandles, out string warnings) { warnings = null; FeatureClass featureClass = feature.GetTable(); if (featureClass == null) { return(false); } long handle = featureClass.Handle.ToInt64(); if (!editableClassHandles.Contains(handle)) { warnings = "Not updated because the layer is not editable"; _msg.DebugFormat("Updated feature {0} is not editable!", GdbObjectUtils.ToString(feature)); return(false); } return(true); }
/// <summary> /// GetUtilityNetworkFromFeatureClass - gets a utility network from a layer /// </summary> /// <param name="layer"></param> /// <returns>a UtilityNetwork object, or null if the layer does not reference a utility network</returns> public static UtilityNetwork GetUtilityNetworkFromLayer(Layer layer) { if (layer is UtilityNetworkLayer) { UtilityNetworkLayer utilityNetworkLayer = layer as UtilityNetworkLayer; return(utilityNetworkLayer.GetUtilityNetwork()); } else if (layer is SubtypeGroupLayer) { CompositeLayer compositeLayer = layer as CompositeLayer; return(GetUtilityNetworkFromLayer(compositeLayer.Layers.First())); } else if (layer is FeatureLayer) { FeatureLayer featureLayer = layer as FeatureLayer; using (FeatureClass featureClass = featureLayer.GetFeatureClass()) { if (featureClass.IsControllerDatasetSupported()) { IReadOnlyList <Dataset> controllerDatasets = featureClass.GetControllerDatasets(); foreach (Dataset controllerDataset in controllerDatasets) { if (controllerDataset is UtilityNetwork) { return(controllerDataset as UtilityNetwork); } } } } } return(null); }
public async void setDomainValuesLayer(string dataset, string fieldName, string sourceTarget, bool resetUI) { List <ComboData> domain = new List <ComboData>(); await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() => { try { var lyr = Helpers.CreateFeatureLayer(new Uri(dataset), MapView.Active.Map); FeatureLayer flayer = lyr as FeatureLayer; ArcGIS.Core.Data.TableDefinition def = null; ArcGIS.Core.CIM.CIMDataConnection cim = flayer.GetDataConnection(); FeatureClass fclass = flayer.GetFeatureClass(); def = fclass.GetDefinition(); domain = getDomainValuesforTable(def, fieldName); } catch { raiseDomainErrorMessage(dataset, fieldName); } return; }); if (resetUI == true) { resetDomainValuesUI(domain, sourceTarget); } else { resetDomainValuesUIFromConfig(domain, sourceTarget); } return; }
public void FromFeatureInstance_DoesNotAllow_AsyncVoid_Steps() { var featureInstance = new FeatureWithAsyncVoidStep(); //act / assert. Assert.Throws <InvalidOperationException>(() => FeatureClass.FromFeatureInstance(featureInstance)); }
public static void EqualClass(ClassDefinition classDef, ClassDefinition cd) { Assert.AreEqual(classDef.Name, cd.Name); Assert.AreEqual(classDef.Properties.Count, cd.Properties.Count); Assert.AreEqual(classDef.IdentityProperties.Count, cd.IdentityProperties.Count); Assert.AreEqual(classDef.ClassType, cd.ClassType); switch (classDef.ClassType) { case ClassType.ClassType_FeatureClass: { FeatureClass fc1 = classDef as FeatureClass; FeatureClass fc2 = cd as FeatureClass; Assert.AreEqual(fc1.GeometryProperty.Name, fc2.GeometryProperty.Name); } break; } foreach (PropertyDefinition propDef in classDef.Properties) { int pidx = cd.Properties.IndexOf(propDef.Name); Assert.IsTrue(pidx >= 0, "Could not find property named {0} in class {1}", propDef.Name, cd.Name); PropertyDefinition pd = cd.Properties[pidx]; EqualProperty(propDef, pd); } }
private ObservableCollection <string> GetAllCourse() { var task = QueuedTask.Run(() => { ObservableCollection <string> result = new ObservableCollection <string>(); using (Geodatabase geodatabase = new Geodatabase(new FileGeodatabaseConnectionPath(new Uri(GeoDataTool.DefaultProject.DefaultGeodatabasePath)))) { using (FeatureClass course = geodatabase.OpenDataset <FeatureClass>(ConstDefintion.ConstFeatureClass_Course)) { using (RowCursor rowCursor = course.Search(null, false)) { while (rowCursor.MoveNext()) { using (Row row = rowCursor.Current) { result.Add(row.GetObjectID().ToString()); } } } } } return(result); }); return(task.Result); }
public void TestCloneFeatureClassNoGeometry() { FeatureClass fc = new FeatureClass("Test", "Test Feature Class"); DataPropertyDefinition id = new DataPropertyDefinition("ID", ""); DataPropertyDefinition name = new DataPropertyDefinition("Name", ""); id.DataType = DataType.DataType_Int32; id.IsAutoGenerated = true; id.ReadOnly = true; id.Nullable = false; name.DataType = DataType.DataType_String; name.Length = 255; name.Nullable = true; fc.Properties.Add(id); fc.Properties.Add(name); fc.IdentityProperties.Add(id); ClassDefinition cd = FdoSchemaUtil.CloneClass(fc); Assert.IsNotNull(cd); Assert.AreEqual(cd.Name, fc.Name); Assert.AreEqual(cd.Description, fc.Description); Assert.AreEqual(cd.Properties.Count, fc.Properties.Count); Assert.AreEqual(cd.IdentityProperties.Count, fc.IdentityProperties.Count); }
internal void AddClass(ClassType type) { string schema = GetSelectedSchema(); if (!string.IsNullOrEmpty(schema)) { string prefix = "FeatureClass"; if (type == ClassType.ClassType_Class) { prefix = "Class"; } string name = _context.GenerateName(prefix); while (_context.ClassNameExists(schema, name)) { name = _context.GenerateName(prefix); } ClassDefinition cls = null; if (type == ClassType.ClassType_Class) { cls = new Class(name, ""); } else if (type == ClassType.ClassType_FeatureClass) { cls = new FeatureClass(name, ""); } if (cls != null) { _context.AddClass(schema, cls); } } }
public virtual IEnumerable <Cluster> Cluster(FeatureClass featureClass, int k = 1) { var samples = featureClass.Samples; var randomIndices = Enumerable.Range(0, samples.Count - 1) .TakeRandom(k) .ToList(); var clusters = new List <Cluster>(); for (int i = 0; i < k; i++) { var cluster = new Cluster(randomIndices[i], featureClass.Samples[randomIndices[i]]) { FeatureClassName = featureClass.Name, Centroid = featureClass.Samples[randomIndices[i]] }; clusters.Add(cluster); samples.RemoveAt(randomIndices[i]); } foreach (var sample in samples) { var chosenCluster = clusters .Select(x => new Tuple <double, Cluster>(sample.EuclidDistance(x.Centroid), x)) .OrderBy(x => x.Item1) .First() .Item2; chosenCluster.Add(featureClass.Samples.IndexOf(sample), sample); } return(clusters); }
/// <summary> /// 获取当前MapCtl里所有注册版本且归档的历史图层集合 /// </summary> /// <returns></returns> /// <remarks></remarks> private bool GetHisLayerColl() { string strName = null; FeatureClass pFeatCls = default(FeatureClass); IFeatureLayer pFeatLayer = default(IFeatureLayer); int i = 0; if (ClsHistory.Map.LayerCount == 0) { MessageBoxEx.Show("当前图层中没有可查看的图层!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); return(false); } for (i = 0; i <= ClsHistory.Map.LayerCount - 1; i++) { if (ClsHistory.Map.get_Layer(i) is IFeatureLayer) { pFeatLayer = ClsHistory.Map.get_Layer(i) as IFeatureLayer; pFeatCls = pFeatLayer.FeatureClass as FeatureClass; strName = pFeatCls.BrowseName; if (HasArch(ClsHistory.WorkSpace, strName) == true) { m_pHisLayerColl.Add(pFeatLayer); } else { MessageBoxEx.Show("不存在'" + strName + "'图层的历史数据!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); return(false); } } } return(true); }
private Task addFeatureLayer() { Debug.WriteLine("addFeatureLayer enter"); return(ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() => { ArcGIS.Core.Data.DatabaseConnectionProperties connectionProperties = new DatabaseConnectionProperties(EnterpriseDatabaseType.PostgreSQL) { AuthenticationMode = AuthenticationMode.DBMS, Instance = @"127.0.0.1", Database = "geomapmaker2", User = "******", Password = "******", //Version = "dbo.DEFAULT" }; using (Geodatabase geodatabase = new Geodatabase(connectionProperties)) { using (FeatureClass featureClass = geodatabase.OpenDataset <FeatureClass>("geomapmaker2.geomapmaker2.line_features")) { var layerParamsQueryDefn = new FeatureLayerCreationParams(featureClass) { IsVisible = true, DefinitionFilter = new CIMDefinitionFilter() { Name = "User", DefinitionExpression = "user_id = " + DataHelper.userID } }; featureLayer = LayerFactory.Instance.CreateLayer <FeatureLayer>(layerParamsQueryDefn, MapView.Active.Map); } } })); }
public AppProccessor(FeatureClass featureClass, FeatureLayer routesLayer, FeatureLayer routesNewLayer, FeatureLayer dotsNewLayer) { this.featureClass = featureClass; this.routesLayer = routesLayer; this.routesNewLayer = routesNewLayer; this.dotsNewLayer = dotsNewLayer; }
private string GetDisplayField(FeatureClass featureClass) { string displayField = ""; Map map = MapView.Active.Map; if (map == null) { return(displayField); } //Get flattened layers from Map. If the feature class exists in the map, get that feature Layer and its display field. If not, return null. var layer = map.GetLayersAsFlattenedList().OfType <FeatureLayer>().FirstOrDefault(lyr => lyr.GetFeatureClass().GetName() == featureClass.GetName()); if (layer == null) { return(""); } CIMFeatureLayer currentCIMFeatureLayer = layer.GetDefinition() as CIMFeatureLayer; CIMFeatureTable cimFeatureTable = currentCIMFeatureLayer.FeatureTable; displayField = cimFeatureTable.DisplayField; return(displayField); }
private async Task <string> GetSelectedItemDisplayValue(string featureClassName, long objectID) { string value = ""; FeatureClass featureClass = null; foreach (var kvp in CustomIdentify.LayersInMapFeatureClassMap) { if (kvp.Value.GetName() == featureClassName) { featureClass = kvp.Value; } } //FeatureClass featureClass = _geodatabase.OpenDataset<FeatureClass>(featureClassName); if (featureClass == null) { return(value); } string displayField = GetDisplayField(featureClass); //could be null if the feature class is not a layer in the map. if (!string.IsNullOrEmpty(displayField)) { value = await GetAttributeValue(featureClass, displayField, objectID); } else { value = objectID.ToString(); } return(value); }
private void GetFeaturesAndAddAttachment() { // TODO // open the file geodatabase c:\ProSDKWorkshop\data\generic.gdb using (Geodatabase geodatabase = new Geodatabase(@"c:\ProSDKWorkshop\data\generic.gdb")) { using (FeatureClass pointFeatureClass = geodatabase.OpenDataset <FeatureClass>("SamplePoints")) { using (RowCursor features = pointFeatureClass.Search()) { while (features.MoveNext()) { Feature currentFeature = features.Current as Feature; currentFeature.AddAttachment(new Attachment("SamplePicture", "image/png", CreateMemoryStreamFromContentsOf(@"C:\ProSDKWorkshop\data\redlands.png"))); } } } } // TODO // open the SamplePoints feature class // TODO // retrieve all features by searching the feature class // TODO // for each feature add the attachment // TODO // add the sample picture as an attachment // add the feature class as a layer to the active map LayerFactory.CreateFeatureLayer(new Uri(@"c:\ProSDKWorkshop\data\generic.gdb\SamplePoints"), MapView.Active.Map); }
private IList <FeatureClass> GetFeatureClasses(string[] fileContent) { var featureClasses = new List <FeatureClass>(); var splittedRows = fileContent.Select(x => x.Split(',')); var classNames = splittedRows.Select(x => x[0]).Distinct(); var sampleCount = splittedRows .Select(x => x.ExceptWithDuplicates(new string[] { x[0] }).Count()) .Min(); foreach (var className in classNames) { var features = splittedRows.Where(x => x[0].Equals(className)).ToList(); var featureClass = new FeatureClass { Name = className, Matrix = Matrix <double> .Build.Dense(features.Count(), sampleCount) }; for (int i = 0; i < features.Count(); i++) { var featureData = features[i].ExceptWithDuplicates(new string[] { className }).ToList(); for (int j = 0; j < sampleCount; j++) { var sample = featureData[j]; featureClass.Matrix[i, j] = double.Parse(sample.Replace('.', ',')); } } featureClasses.Add(featureClass); } return(featureClasses); }
public static FieldSetter ValidateTargetFields( this FieldSetter instance, FeatureClass featureClass, string parameterName) { if (instance == null) { return(null); } if (featureClass == null) { return(instance); } try { var fieldNames = featureClass.GetDefinition().GetFields().Select(f => f.Name); instance.ValidateTargetFields(fieldNames); } catch (Exception ex) { throw new InvalidConfigurationException( $"Parameter {parameterName} is invalid: {ex.Message}"); } return(instance); }
public void MainMethodCode() { Uri arcgisOnlineURL = new Uri("http://services1.arcgis.com/47GG2ga246DGaLwa/arcgis/rest/services/FeatureServiceName/FeatureServer"); ServiceConnectionProperties arcGISOnline = new ServiceConnectionProperties(arcgisOnlineURL); using (Geodatabase featureService = new Geodatabase(arcGISOnline)) { using (FeatureClass featureClass = featureService.OpenDataset <FeatureClass>("0")) { // Use the feature class opened from layer ID 0. } using (Table table = featureService.OpenDataset <Table>("4")) { // Use the table opened from layer ID 4. } using (AttributedRelationshipClass attributedRelationshipClass = featureService.OpenDataset <AttributedRelationshipClass>("5")) { // Use the attributed relationship class opened from layer ID 5. } try { string idOfLayerWhichIsNotTable = "3"; featureService.OpenDataset <Table>(idOfLayerWhichIsNotTable); } catch (InvalidOperationException) { // Handle Exception. } } }
public bool Init() { _messages = new List <string>(); if (System.IO.File.Exists(SaveFilePath)) { System.IO.File.Delete(SaveFilePath); } if (!ArcGISFileHelper.CreatePersonalDataBase(SaveFilePath))//创建数据库文件失败 { return(false); } if (FeatureClass != null) { var values = FeatureClass.GetUniqueValue(FieldName); var tool = new Select(); foreach (var item in values) { tool.in_features = FeatureClass; tool.out_feature_class = string.Format("{0}\\{1}_{2}", SaveFilePath, LayerName, item); tool.where_clause = string.Format("[{0}] = '{1}'", FieldName, item); if (!GPHelper.Excute(tool)) { _messages.Add(string.Format("执行{0}发生错误", tool.where_clause)); } } return(true); } return(false); }
public void ExtractScenario_Extracts_Scenario_With_Background() { //arrange. var scenarioName = "some scenario name 123"; var featureInstance = new FeatureWithMatchingScenarioStepsToExtract(); var sut = FeatureClass.FromFeatureInstance(featureInstance); var gherkinDocument = CreateGherkinDocument(scenarioName, new string[] { "Given " + FeatureWithMatchingScenarioStepsToExtract.ScenarioStep1Text.Replace(@"(\d+)", "12", StringComparison.InvariantCultureIgnoreCase), "And " + FeatureWithMatchingScenarioStepsToExtract.ScenarioStep2Text.Replace(@"(\d+)", "15", StringComparison.InvariantCultureIgnoreCase), "When " + FeatureWithMatchingScenarioStepsToExtract.ScenarioStep3Text, "Then " + FeatureWithMatchingScenarioStepsToExtract.ScenarioStep4Text.Replace(@"(\d+)", "27", StringComparison.InvariantCultureIgnoreCase) }, null, new string[] { "Given a background step" }); //act. var scenario = sut.ExtractScenario( gherkinDocument.Feature.Children.OfType <Gherkin.Ast.Scenario>().First(), gherkinDocument.Feature.Children.OfType <Gherkin.Ast.Background>().First()); //assert. Assert.NotNull(scenario); }
public async Task UpdateFeatureAsync(long uid, Geometry geometry) { await QueuedTask.Run(() => { using (FeatureClass featureClass = Layer.GetFeatureClass()) { FeatureClassDefinition definition = featureClass?.GetDefinition(); string objectIdField = definition?.GetObjectIDField(); QueryFilter filter = new QueryFilter { WhereClause = $"{objectIdField} = {uid}" }; using (RowCursor existsResult = featureClass?.Search(filter, false)) { while (existsResult?.MoveNext() ?? false) { using (Row row = existsResult.Current) { Feature feature = row as Feature; feature?.SetShape(geometry); feature?.Store(); } } } } }); }
public static Dictionary <string, FeatureClass> GetMapLayersFeatureClassMap(Geodatabase geodatabase) { Dictionary <string, FeatureClass> lyrFeatureClassMap = new Dictionary <string, FeatureClass>(); Map map = MapView.Active.Map; if (map == null) { return(null); } var layers = map.GetLayersAsFlattenedList().OfType <FeatureLayer>(); foreach (var lyr in layers) { string fc = lyr.GetFeatureClass().GetName(); FeatureClass featureClass = geodatabase.OpenDataset <FeatureClass>(fc); if (featureClass != null) { lyrFeatureClassMap.Add(lyr.Name, featureClass); } } return(lyrFeatureClassMap); }
public Task <UtilityNetwork> GetUNByLayer(Layer layer) { return(QueuedTask.Run(() => { if (layer is FeatureLayer) { FeatureLayer featureLayer = layer as FeatureLayer; using (FeatureClass featureClass = featureLayer.GetFeatureClass()) { if (featureClass.IsControllerDatasetSupported()) { IReadOnlyList <Dataset> datasets = featureClass.GetControllerDatasets(); foreach (var dataset in datasets) { if (dataset is UtilityNetwork) { return dataset as UtilityNetwork; } else { dataset.Dispose(); } } } } } else if (layer is UtilityNetworkLayer) { UtilityNetworkLayer utilityNetworkLayer = layer as UtilityNetworkLayer; return utilityNetworkLayer.GetUtilityNetwork(); } return null; })); }
/// <summary> /// Calculate viewpoints along a vector line, e.g. road, path. /// </summary> /// <param name="gdbPath">Path to GDB</param> /// <param name="featureClassName">Feature class</param> /// <returns>Viewpoints</returns> private HashSet <SpatialUtils.ViewpointProps> GetLine(String gdbPath, String featureClassName) { HashSet <SpatialUtils.ViewpointProps> result = new HashSet <SpatialUtils.ViewpointProps>(); //using hash set to prevent duplicates, possible speed up with array using (Geodatabase geodatabase = new Geodatabase(new FileGeodatabaseConnectionPath(new Uri(gdbPath)))) using (FeatureClass featureClass = geodatabase.OpenDataset <FeatureClass>(featureClassName)) { QueryFilter queryFilter = new QueryFilter { SubFields = "POINT_X, POINT_Y, ORIG_FID", PostfixClause = "ORDER BY ORIG_FID" }; using (RowCursor rowCursor = featureClass.Search(queryFilter, false)) { double previousX = Double.NaN; double previousY = Double.NaN; int previousFid = Int32.MinValue; while (rowCursor.MoveNext()) { using (Row row = rowCursor.Current) { double pointX = Convert.ToDouble(row["POINT_X"]); double pointY = Convert.ToDouble(row["POINT_Y"]); int fid = Convert.ToInt32(row["ORIG_FID"]); if (fid == previousFid) { double length = Math.Sqrt(Math.Pow(pointX - previousX, 2) + Math.Pow(pointY - previousY, 2)); int steps = (int)Math.Floor(length / stepLength); double xStep = (pointX - previousX) / steps; double yStep = (pointY - previousY) / steps; for (int i = 0; i <= steps; i++) { Tuple <int, int> point = inputRaster.MapToPixel(previousX + xStep * i, previousY + yStep * i); result.Add(new SpatialUtils.ViewpointProps() { X = point.Item1, Y = point.Item2 }); } } else if (previousFid != Int32.MinValue) //endpoint { Tuple <int, int> point = inputRaster.MapToPixel(previousX, previousY); result.Add(new SpatialUtils.ViewpointProps() { X = point.Item1, Y = point.Item2 }); } previousX = pointX; previousY = pointY; previousFid = fid; } } } } return(result); }
private async Task openDatabase(JObject props) { await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() => { //Get Layers that are NOT Group layers and are unchecked //var layers = MapView.Active.Map.Layers.ToList(); //MapView.Active.Map.RemoveLayers(layers); // Opening a Non-Versioned SQL Server instance. ArcGIS.Core.Data.DatabaseConnectionProperties connectionProperties = new DatabaseConnectionProperties(EnterpriseDatabaseType.PostgreSQL) { AuthenticationMode = AuthenticationMode.DBMS, // Where testMachine is the machine where the instance is running and testInstance is the name of the SqlServer instance. //Instance = @"127.0.0.1", Instance = props["instance"].ToString(), // Provided that a database called LocalGovernment has been created on the testInstance and geodatabase has been enabled on the database. //Database = "geomapmaker", Database = props["database"].ToString(), // Provided that a login called gdb has been created and corresponding schema has been created with the required permissions. //User = "******", User = props["user"].ToString(), //Password = "******", Password = props["password"].ToString(), //Version = "dbo.DEFAULT" }; using (Geodatabase geodatabase = new Geodatabase(connectionProperties)) { DataHelper.connectionString = geodatabase.GetConnectionString(); Debug.WriteLine("DataHelper.connectionString set to " + DataHelper.connectionString); // Use the geodatabase /* * CIMSqlQueryDataConnection sqldc = new CIMSqlQueryDataConnection() * { * WorkspaceConnectionString = geodatabase.GetConnectionString(), * GeometryType = esriGeometryType.esriGeometryPoint, * OIDFields = "OBJECTID", * Srid = "4326", * //SqlQuery = "select * from geomapmaker2.features where id = " + DataHelper.userID + " and ST_GeometryType(geom)='ST_Point'", * Dataset = "somepoints" * }; * FeatureLayer flyr = (FeatureLayer)LayerFactory.Instance.CreateLayer(sqldc, MapView.Active.Map, layerName: DataHelper.userName + "'s points"); */ //FeatureClass fC = geodatabase.OpenDataset<FeatureClass>("somepoints"); //FeatureLayer flyr = LayerFactory.Instance.CreateFeatureLayer(fC, MapView.Active.Map); var featureClasses = geodatabase.GetDefinitions <FeatureClassDefinition>(); foreach (FeatureClassDefinition fCD in featureClasses) { FeatureClass fC = geodatabase.OpenDataset <FeatureClass>(fCD.GetName()); FeatureLayer flyr = LayerFactory.Instance.CreateFeatureLayer(fC, MapView.Active.Map); } } }); }
private static void SetShape([NotNull] RowBuffer rowBuffer, [NotNull] Geometry geometry, FeatureClass featureClass) { string shapeFieldName = featureClass.GetDefinition().GetShapeField(); SetShape(rowBuffer, geometry, shapeFieldName); }
public PickableFeatureClassItem(FeatureClass featureClass, esriGeometryType geometryType, List <FeatureLayer> belongingFeatureLayers) { _itemText = featureClass.GetName(); _geometry = null; _itemImageUri = GetImagePath(geometryType); BelongingFeatureLayers = belongingFeatureLayers; }
/// <summary> /// Utility method to clone a class definition /// </summary> /// <param name="cd">The class to clone.</param> /// <param name="ignoreDeleted">if set to <c>true</c> [ignore deleted].</param> /// <returns></returns> public static ClassDefinition CloneClass(ClassDefinition cd, bool ignoreDeleted) { ClassDefinition classDef = null; switch (cd.ClassType) { case ClassType.ClassType_Class: { Class c = new Class(cd.Name, cd.Description); CopyProperties(cd.Properties, c.Properties, ignoreDeleted); CopyIdentityProperties(cd.IdentityProperties, c.IdentityProperties, ignoreDeleted); CopyElementAttributes(cd.Attributes, c.Attributes); CopyUniqueConstraints(cd.UniqueConstraints, c); classDef = c; } break; case ClassType.ClassType_FeatureClass: { FeatureClass sfc = (FeatureClass)cd; FeatureClass fc = new FeatureClass(cd.Name, cd.Description); CopyProperties(cd.Properties, fc.Properties, ignoreDeleted); CopyIdentityProperties(cd.IdentityProperties, fc.IdentityProperties, ignoreDeleted); if (sfc.GeometryProperty != null) { string geomName = sfc.GeometryProperty.Name; fc.GeometryProperty = fc.Properties[fc.Properties.IndexOf(geomName)] as GeometricPropertyDefinition; } CopyElementAttributes(cd.Attributes, fc.Attributes); CopyUniqueConstraints(cd.UniqueConstraints, fc); classDef = fc; } break; default: throw new UnsupportedException(Res.GetStringFormatted("ERR_UNSUPPORTED_CLONE_CLASS_TYPE", cd.ClassType)); } return classDef; }
private async Task<string> GetDomainValueAsync(string fieldName, string key) { try { IEnumerable<GDBProjectItem> gdbProjectItems = Project.Current.GetItems<GDBProjectItem>(); return await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() => { foreach (GDBProjectItem gdbProjectItem in gdbProjectItems) { using (Datastore datastore = gdbProjectItem.GetDatastore()) { //Unsupported datastores (non File GDB and non Enterprise GDB) will be of type UnknownDatastore if (datastore is UnknownDatastore) continue; Geodatabase geodatabase = datastore as Geodatabase; string geodatabasePath = geodatabase.GetPath(); if (geodatabasePath == ProSymbolEditorModule.Current.MilitaryOverlaySchema.DatabaseName) { //Correct GDB, open the current selected feature class _currentFeatureClass = geodatabase.OpenDataset<FeatureClass>(_currentFeatureClassName); using (_currentFeatureClass) { ArcGIS.Core.Data.FeatureClassDefinition facilitySiteDefinition = _currentFeatureClass.GetDefinition(); IReadOnlyList<ArcGIS.Core.Data.Field> fields = facilitySiteDefinition.GetFields(); ArcGIS.Core.Data.Field foundField = fields.FirstOrDefault(field => field.Name == fieldName); if (foundField != null) { CodedValueDomain domain = foundField.GetDomain() as CodedValueDomain; return domain.GetCodedValue(key).ToString(); } } break; } } } return ""; }); } catch (Exception exception) { System.Diagnostics.Debug.WriteLine(exception.ToString()); } return null; }
public void TestCloneClass() { ClassDefinition c1 = new FeatureClass("Test", "Test Feature Class"); DataPropertyDefinition id = new DataPropertyDefinition("ID", ""); DataPropertyDefinition name = new DataPropertyDefinition("Name", ""); id.DataType = DataType.DataType_Int32; id.IsAutoGenerated = true; id.ReadOnly = true; id.Nullable = false; name.DataType = DataType.DataType_String; name.Length = 255; name.Nullable = true; GeometricPropertyDefinition geom = new GeometricPropertyDefinition("Geometry", ""); geom.GeometryTypes = (int)GeometryType.GeometryType_Polygon; geom.ReadOnly = false; c1.Properties.Add(id); c1.Properties.Add(name); c1.Properties.Add(geom); c1.IdentityProperties.Add(id); ((FeatureClass)c1).GeometryProperty = geom; ClassDefinition cd = FdoSchemaUtil.CloneClass(c1); Assert.IsNotNull(cd); FeatureClass fc = cd as FeatureClass; Assert.IsNotNull(fc); Assert.AreEqual(cd.Name, c1.Name); Assert.AreEqual(cd.ClassType, c1.ClassType); Assert.IsNotNull(fc.GeometryProperty); Assert.IsNotNull(((FeatureClass)c1).GeometryProperty); Assert.AreEqual(fc.GeometryProperty.Name, ((FeatureClass)c1).GeometryProperty.Name); Assert.AreEqual(cd.Description, c1.Description); Assert.AreEqual(cd.Properties.Count, c1.Properties.Count); Assert.AreEqual(cd.IdentityProperties.Count, c1.IdentityProperties.Count); c1.Dispose(); c1 = new Class("TestClass", "Test Class"); id = new DataPropertyDefinition("ID", ""); name = new DataPropertyDefinition("Name", ""); id.DataType = DataType.DataType_Int32; id.IsAutoGenerated = true; id.ReadOnly = true; id.Nullable = false; name.DataType = DataType.DataType_String; name.Length = 255; name.Nullable = true; cd = FdoSchemaUtil.CloneClass(c1); Assert.IsNotNull(cd); Assert.AreEqual(cd.Name, c1.Name); Assert.AreEqual(cd.Description, c1.Description); Assert.AreEqual(cd.Properties.Count, c1.Properties.Count); Assert.AreEqual(cd.IdentityProperties.Count, c1.IdentityProperties.Count); }
/// <summary> /// Utility method to clone a feature schema /// </summary> /// <param name="fs"></param> /// <param name="ignoreDeleted"></param> /// <returns></returns> public static FeatureSchema CloneSchema(FeatureSchema fs, bool ignoreDeleted) { if (fs == null) throw new ArgumentNullException("fs"); /* * This method is BIG. So it needs some explanation. * * Because Association and Object Properties reference other classes, the classes * containing such properties are processed *last*. Everything else is assumed to * be cloned (without problems) and cached in a temp dictionary for processing these * classes w/ Association/Object properties. * * When processing these remaining classes, we iteratively attempt to clone each class. * Each successfully cloned class will be added to the temp dictionary. Eventually all * references will be satisfied, that's when we can finally return the cloned schema. */ Dictionary<string, ClassDefinition> cloned = new Dictionary<string,ClassDefinition>(); List<ClassDefinition> classesWithReferences = new List<ClassDefinition>(); FeatureSchema fsc = new FeatureSchema(fs.Name, fs.Description); CopyElementAttributes(fs.Attributes, fsc.Attributes); if (ignoreDeleted) { foreach (ClassDefinition cls in fs.Classes) { if (cls.ElementState != SchemaElementState.SchemaElementState_Deleted) { ICollection<string> refs = GetReferencedClasses(cls); if (refs.Count == 0) { var klass = CloneClass(cls, ignoreDeleted); fsc.Classes.Add(klass); cloned.Add(klass.QualifiedName, klass); } else { //Check for self-references classesWithReferences.Add(cls); } } } } else { foreach (ClassDefinition cls in fs.Classes) { ICollection<string> refs = GetReferencedClasses(cls); if (refs.Count == 0) { var klass = CloneClass(cls, ignoreDeleted); fsc.Classes.Add(klass); cloned.Add(klass.QualifiedName, klass); } else { //Check for self-references classesWithReferences.Add(cls); } } } //TODO: Does the FDO spec allow self-referenced Association/Object //properties? If not, it would simplify this code greatly. //Repeat until all references satisfied while (classesWithReferences.Count > 0) { List<ClassDefinition> successfullyCloned = new List<ClassDefinition>(); foreach (ClassDefinition cls in classesWithReferences) { bool bSuccess = false; ClassDefinition klass = null; switch (cls.ClassType) { case ClassType.ClassType_Class: klass = new Class(cls.Name, cls.Description); break; case ClassType.ClassType_FeatureClass: klass = new FeatureClass(cls.Name, cls.Description); break; } Dictionary<AssociationPropertyDefinition, AssociationPropertyDefinition> processAp = new Dictionary<AssociationPropertyDefinition, AssociationPropertyDefinition>(); Dictionary<ObjectPropertyDefinition, ObjectPropertyDefinition> processOp = new Dictionary<ObjectPropertyDefinition, ObjectPropertyDefinition>(); var props = cls.Properties; for (int i = 0; i < props.Count; i++) { var prop = props[i]; if (prop.PropertyType == PropertyType.PropertyType_AssociationProperty) { var ap = (AssociationPropertyDefinition)prop; var apClone = new AssociationPropertyDefinition(ap.Name, ap.Description); ClassDefinition associatedClass = null; associatedClass = cloned[ap.AssociatedClass.QualifiedName]; if (associatedClass == null) { //could be a self-reference if (klass.Name.Equals(ap.AssociatedClass.Name)) associatedClass = klass; } if (associatedClass != null) { apClone.AssociatedClass = associatedClass; apClone.DeleteRule = ap.DeleteRule; //Process identity properties. Shelve for later processing if //any property can't be found var idProps = ap.IdentityProperties; bool foundAll = true; foreach (DataPropertyDefinition dp in idProps) { if (!props.Contains(dp)) foundAll = false; } if (foundAll) { foreach (DataPropertyDefinition dp in idProps) { apClone.IdentityProperties.Add((DataPropertyDefinition)props[dp.Name]); } } else { processAp.Add(apClone, ap); } apClone.LockCascade = ap.LockCascade; apClone.Multiplicity = ap.Multiplicity; //Process reverse identity properties. Shelve for later processing if //any property can't be found var ridProps = ap.ReverseIdentityProperties; foundAll = true; foreach (DataPropertyDefinition dp in ridProps) { if (!props.Contains(dp)) foundAll = false; } if (foundAll) { foreach (DataPropertyDefinition dp in ridProps) { apClone.ReverseIdentityProperties.Add((DataPropertyDefinition)apClone.AssociatedClass.Properties[dp.Name]); } } else { processAp.Add(apClone, ap); } apClone.ReverseMultiplicity = ap.ReverseMultiplicity; apClone.ReverseName = ap.ReverseName; klass.Properties.Add(apClone); } else { break; } } else if (prop.PropertyType == PropertyType.PropertyType_ObjectProperty) { var op = (ObjectPropertyDefinition)prop; var opClone = new ObjectPropertyDefinition(op.Name, op.Description); if (cloned.ContainsKey(op.Class.QualifiedName)) { ClassDefinition associatedClass = cloned[op.Class.QualifiedName]; opClone.Class = associatedClass; //Process identity property. Shelve for later processing if none found if (props.Contains(op.IdentityProperty.Name)) { opClone.IdentityProperty = (DataPropertyDefinition)op.Class.Properties[op.IdentityProperty.Name]; } else { processOp.Add(opClone, op); } opClone.ObjectType = op.ObjectType; opClone.OrderType = op.OrderType; klass.Properties.Add(opClone); } else { break; } } else { bool identity = false; bool geometry = false; var dp = prop as DataPropertyDefinition; var gp = prop as GeometricPropertyDefinition; identity = (dp != null && cls.IdentityProperties.Contains(dp)); geometry = (gp != null && cls.ClassType == ClassType.ClassType_FeatureClass && ((FeatureClass)cls).GeometryProperty == gp); //Clone property and add to cloned class var cp = CloneProperty(prop); klass.Properties.Add(cp); if (identity) { Debug.Assert(cp.PropertyType == PropertyType.PropertyType_DataProperty); klass.IdentityProperties.Add((DataPropertyDefinition)cp); } if (geometry) { Debug.Assert(cp.PropertyType == PropertyType.PropertyType_GeometricProperty); Debug.Assert(klass.ClassType == ClassType.ClassType_FeatureClass); ((FeatureClass)klass).GeometryProperty = (GeometricPropertyDefinition)cp; } } } if (processAp.Count > 0) { foreach (AssociationPropertyDefinition apClone in processAp.Keys) { var ap = processAp[apClone]; //Retry identity properties apClone.IdentityProperties.Clear(); var idProps = ap.IdentityProperties; foreach (DataPropertyDefinition dp in idProps) { apClone.IdentityProperties.Add((DataPropertyDefinition)props[dp.Name]); } //Retry reverse identity properties apClone.ReverseIdentityProperties.Clear(); var ridProps = ap.ReverseIdentityProperties; foreach (DataPropertyDefinition dp in ridProps) { apClone.ReverseIdentityProperties.Add((DataPropertyDefinition)apClone.AssociatedClass.Properties[dp.Name]); } } } if (processOp.Count > 0) { foreach (ObjectPropertyDefinition opClone in processOp.Keys) { var op = processOp[opClone]; //Retry identity property opClone.IdentityProperty = (DataPropertyDefinition)op.Class.Properties[op.IdentityProperty.Name]; } } //All properties accounted for if (klass.Properties.Count == cls.Properties.Count && klass.IdentityProperties.Count == cls.IdentityProperties.Count) { bSuccess = true; } if (bSuccess) { fsc.Classes.Add(klass); successfullyCloned.Add(cls); } } //Purge successfully cloned entries foreach (ClassDefinition cls in successfullyCloned) { int ridx = classesWithReferences.IndexOf(cls); if (ridx >= 0) classesWithReferences.RemoveAt(ridx); } } return fsc; }
public void TestSchemaCanBeApplied() { FeatureSchema schema = new FeatureSchema("Default", ""); FeatureClass fc = new FeatureClass("Class1", ""); DataPropertyDefinition id = new DataPropertyDefinition("ID", ""); id.DataType = DataType.DataType_Int32; id.IsAutoGenerated = true; fc.Properties.Add(id); fc.IdentityProperties.Add(id); GeometricPropertyDefinition geom = new GeometricPropertyDefinition("Geometry", ""); geom.GeometryTypes = (int)GeometryType.GeometryType_Point; fc.Properties.Add(geom); schema.Classes.Add(fc); /* IConnection conn = FeatureAccessManager.GetConnectionManager().CreateConnection("OSGeo.SHP"); conn.ConnectionString = "DefaultFileLocation=" + AppGateway.RunningApplication.AppPath; using (conn) { conn.Open(); using (FeatureService service = new FeatureService(conn)) { IncompatibleSchema incSchema = null; bool result = service.CanApplySchema(schema, out incSchema); Assert.IsNull(incSchema); Assert.IsTrue(result); } conn.Close(); }*/ }
private string GetDisplayField(FeatureClass featureClass) { string displayField = ""; Map map = MapView.Active.Map; if (map == null) return displayField; //Get flattened layers from Map. If the feature class exists in the map, get that feature Layer and its display field. If not, return null. var layer = map.GetLayersAsFlattenedList().OfType<FeatureLayer>().FirstOrDefault(lyr => lyr.GetFeatureClass().GetName() == featureClass.GetName()); if (layer == null) return ""; CIMFeatureLayer currentCIMFeatureLayer = layer.GetDefinition() as CIMFeatureLayer; CIMFeatureTable cimFeatureTable = currentCIMFeatureLayer.FeatureTable; displayField = cimFeatureTable.DisplayField; return displayField; }
//private Dictionary<string, FeatureClass> GetMapLayersFeatureClassMap() //{ // Dictionary<string, FeatureClass> lyrFeatureClassMap = new Dictionary<string, FeatureClass>(); // Map map = MapView.Active.Map; // if (map == null) // return null; // var layers = map.GetLayersAsFlattenedList().OfType<FeatureLayer>(); // foreach (var lyr in layers) // { // string fc = lyr.GetFeatureClass().GetName(); // FeatureClass featureClass = _geodatabase.OpenDataset<FeatureClass>(fc); // if (featureClass != null) // lyrFeatureClassMap.Add(lyr.Name, featureClass); // } // return lyrFeatureClassMap; //} private Task<string> GetAttributeValue(FeatureClass featureClass, string fieldName, long objectId) { return QueuedTask.Run(() => { string value = ""; try { var oidField = featureClass.GetDefinition().GetObjectIDField(); QueryFilter queryFilter = new QueryFilter { WhereClause = string.Format("({0} in ({1}))", oidField, objectId) }; using (RowCursor rowCursor = featureClass.Search(queryFilter, false)) { while (rowCursor.MoveNext()) { using (Row row = rowCursor.Current) { value = Convert.ToString(row[fieldName]); } } } } catch (GeodatabaseFieldException ) { // One of the fields in the where clause might not exist. There are multiple ways this can be handled: // Handle error appropriately } catch (Exception exception) { System.Diagnostics.Debug.Write(exception.Message); } return value; }); }
private ClassDefinition CreateMergedClass(ClassDefinition leftCls, ClassDefinition rightCls) { ClassDefinition cls = null; if (!string.IsNullOrEmpty(_options.GeometryProperty)) cls = new FeatureClass(_options.Target.ClassName, ""); else cls = new Class(_options.Target.ClassName, ""); var props = cls.Properties; foreach (PropertyDefinition p in leftCls.Properties) { int idx = props.IndexOf(p.Name); if (idx < 0) { var prop = FdoSchemaUtil.CloneProperty(p); props.Add(prop); } } foreach (PropertyDefinition p in rightCls.Properties) { int idx = props.IndexOf(p.Name); if (idx < 0) { var prop = FdoSchemaUtil.CloneProperty(p); props.Add(prop); } } //Strip off autogeneration because we want to preserve original values foreach (PropertyDefinition p in props) { if (p.PropertyType == PropertyType.PropertyType_DataProperty) { DataPropertyDefinition dp = (DataPropertyDefinition)p; dp.IsAutoGenerated = false; } } DataPropertyDefinition fid = new DataPropertyDefinition("FID", "Autogenerated ID"); fid.DataType = DataType.DataType_Int32; fid.IsAutoGenerated = true; fid.Nullable = false; props.Add(fid); cls.IdentityProperties.Add(fid); if (!string.IsNullOrEmpty(_options.GeometryProperty)) { //If prefixed, we need to qualify it to match what's in the merged class string pn = _options.GeometryProperty; if (_options.Side == JoinSide.Left) { if (!string.IsNullOrEmpty(_options.LeftPrefix)) pn = _options.LeftPrefix + pn; } else { if (!string.IsNullOrEmpty(_options.RightPrefix)) pn = _options.RightPrefix + pn; } int idx = props.IndexOf(pn); if (idx < 0) { throw new FdoETLException("Property not found in merged class: " + _options.GeometryProperty); } else { var p = props[idx]; if (p.PropertyType != PropertyType.PropertyType_GeometricProperty) throw new FdoETLException("Designated property is not a geometry property: " + _options.GeometryProperty); ((FeatureClass)cls).GeometryProperty = (GeometricPropertyDefinition)p; } } return cls; }
public void TestSchemaCannotBeApplied() { FeatureSchema schema = new FeatureSchema("Default", ""); FeatureClass fc = new FeatureClass("Class1", ""); DataPropertyDefinition id = new DataPropertyDefinition("ID", ""); id.DataType = DataType.DataType_Int32; id.IsAutoGenerated = true; fc.Properties.Add(id); fc.IdentityProperties.Add(id); //Unsupported property in SHP DataPropertyDefinition d1 = new DataPropertyDefinition("Unsupported", ""); d1.DataType = DataType.DataType_Int64; d1.Nullable = true; fc.Properties.Add(d1); GeometricPropertyDefinition geom = new GeometricPropertyDefinition("Geometry", ""); geom.GeometryTypes = (int)GeometryType.GeometryType_Point; fc.Properties.Add(geom); schema.Classes.Add(fc); /* IConnection conn = FeatureAccessManager.GetConnectionManager().CreateConnection("OSGeo.SHP"); conn.ConnectionString = "DefaultFileLocation=" + AppGateway.RunningApplication.AppPath; using (conn) { conn.Open(); using (FeatureService service = new FeatureService(conn)) { IncompatibleSchema incSchema = null; bool result = service.CanApplySchema(schema, out incSchema); Assert.IsNotNull(incSchema); Assert.IsFalse(result); foreach (IncompatibleClass incClass in incSchema.Classes) { foreach (IncompatibleProperty incProp in incClass.Properties) { Assert.AreEqual(incProp.Reasons.Count, incProp.ReasonCodes.Count); } } } conn.Close(); }*/ }
internal void AddClass(ClassType type) { string schema = GetSelectedSchema(); if (!string.IsNullOrEmpty(schema)) { string prefix = "FeatureClass"; if (type == ClassType.ClassType_Class) prefix = "Class"; string name = _context.GenerateName(prefix); while(_context.ClassNameExists(schema, name)) { name = _context.GenerateName(prefix); } ClassDefinition cls = null; if (type == ClassType.ClassType_Class) cls = new Class(name, ""); else if (type == ClassType.ClassType_FeatureClass) cls = new FeatureClass(name, ""); if (cls != null) _context.AddClass(schema, cls); } }
/// <summary> /// Creates a <see cref="ClassDefinition"/> from this instance /// </summary> /// <param name="createAutoGeneratedId">If true, will add an auto-generated id property to this class definition</param> /// <returns>The class definition</returns> public ClassDefinition CreateClassDefinition(bool createAutoGeneratedId) { ClassDefinition cd = null; if (!string.IsNullOrEmpty(this.GeometryColumn)) { FeatureClass fc = new FeatureClass(this.TableName, string.Empty); GeometricPropertyDefinition gp = new GeometricPropertyDefinition(this.GeometryColumn, string.Empty); fc.Properties.Add(gp); fc.GeometryProperty = gp; cd = fc; } else { cd = new Class(this.TableName, string.Empty); } if (createAutoGeneratedId) { int num = 1; string name = "AutoID"; string genName = name + num; string theName = string.Empty; if (this.Columns[name] != null) { while (this.Columns[genName] != null) { genName = name + (num++); } theName = genName; } else { theName = name; } DataPropertyDefinition id = new DataPropertyDefinition(theName, string.Empty); id.IsAutoGenerated = true; id.DataType = DataType.DataType_Int32; cd.Properties.Add(id); cd.IdentityProperties.Add(id); } //Now process columns foreach (DataColumn dc in this.Columns) { if (dc.ColumnName != this.GeometryColumn) { DataPropertyDefinition dp = ExpressUtility.GetDataPropertyForColumn(dc); cd.Properties.Add(dp); } } return cd; }
private async void GetMilitaryDomainsAsync(SymbolAttributeSet loadSet = null) { try { IEnumerable<GDBProjectItem> gdbProjectItems = Project.Current.GetItems<GDBProjectItem>(); await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() => { foreach (GDBProjectItem gdbProjectItem in gdbProjectItems) { using (Datastore datastore = gdbProjectItem.GetDatastore()) { //Unsupported datastores (non File GDB and non Enterprise GDB) will be of type UnknownDatastore if (datastore is UnknownDatastore) continue; Geodatabase geodatabase = datastore as Geodatabase; string geodatabasePath = geodatabase.GetPath(); if (geodatabasePath == ProSymbolEditorModule.Current.MilitaryOverlaySchema.DatabaseName) { //Correct GDB, open the current selected feature class _currentFeatureClass = geodatabase.OpenDataset<FeatureClass>(_currentFeatureClassName); using (_currentFeatureClass) { ArcGIS.Core.Data.FeatureClassDefinition facilitySiteDefinition = _currentFeatureClass.GetDefinition(); IReadOnlyList<ArcGIS.Core.Data.Field> fields = facilitySiteDefinition.GetFields(); MilitaryFieldsInspectorModel.PopulateDomains(fields); MilitaryFieldsInspectorModel.CheckLabelFieldsExistence(fields); } break; } } } }); //Check for affiliation tag if (_selectedStyleItem != null) { string identityCode = ""; if (_selectedStyleItem.Tags.ToUpper().Contains("FRIEND")) { identityCode = await GetDomainValueAsync("identity", "Friend"); } else if (_selectedStyleItem.Tags.ToUpper().Contains("HOSTILE")) { identityCode = await GetDomainValueAsync("identity", "Hostile/Faker"); } else if (_selectedStyleItem.Tags.ToUpper().Contains("NEUTRAL")) { identityCode = await GetDomainValueAsync("identity", "Neutral"); } else if (_selectedStyleItem.Tags.ToUpper().Contains("UNKNOWN")) { identityCode = await GetDomainValueAsync("identity", "Unknown"); } //Check name of style last to see if it has an affiliation, but no associated tag //But only do this if no tag existed if (identityCode == "") { if (_selectedStyleItem.Name.ToUpper().Contains(": FRIEND")) { identityCode = await GetDomainValueAsync("identity", "Friend"); } else if (_selectedStyleItem.Name.ToUpper().Contains(": HOSTILE")) { identityCode = await GetDomainValueAsync("identity", "Hostile/Faker"); } else if (_selectedStyleItem.Name.ToUpper().Contains(": NEUTRAL")) { identityCode = await GetDomainValueAsync("identity", "Neutral"); } else if (_selectedStyleItem.Name.ToUpper().Contains(": UNKNOWN")) { identityCode = await GetDomainValueAsync("identity", "Unknown"); } } if (identityCode != "") { foreach (DomainCodedValuePair dcvp in MilitaryFieldsInspectorModel.IdentityDomainValues) { if (dcvp.Code.ToString() == identityCode) { SymbolAttributeSet.DisplayAttributes.SelectedIdentityDomainPair = dcvp; break; } } } } //Load any passed in values to selected values for the domain combo boxes if (loadSet != null) { SymbolAttributeSet.DisplayAttributes.SelectedIdentityDomainPair = MilitaryFieldsInspectorModel.IdentityDomainValues.FirstOrDefault(pair => pair.Code.ToString() == loadSet.DisplayAttributes.Identity); SymbolAttributeSet.DisplayAttributes.SelectedEchelonDomainPair = MilitaryFieldsInspectorModel.EcholonDomainValues.FirstOrDefault(pair => pair.Code.ToString() == loadSet.DisplayAttributes.Echelon); SymbolAttributeSet.DisplayAttributes.SelectedMobilityDomainPair = MilitaryFieldsInspectorModel.MobilityDomainValues.FirstOrDefault(pair => pair.Code.ToString() == loadSet.DisplayAttributes.Mobility); SymbolAttributeSet.DisplayAttributes.SelectedOperationalConditionDomainPair = MilitaryFieldsInspectorModel.OperationalConditionAmplifierDomainValues.FirstOrDefault(pair => pair.Code.ToString() == loadSet.DisplayAttributes.OperationalCondition); SymbolAttributeSet.DisplayAttributes.SelectedIndicatorDomainPair = MilitaryFieldsInspectorModel.TfFdHqDomainValues.FirstOrDefault(pair => pair.Code.ToString() == loadSet.DisplayAttributes.Indicator); SymbolAttributeSet.DisplayAttributes.SelectedStatusDomainPair = MilitaryFieldsInspectorModel.StatusDomainValues.FirstOrDefault(pair => pair.Code.ToString() == loadSet.DisplayAttributes.Status); SymbolAttributeSet.DisplayAttributes.SelectedContextDomainPair = MilitaryFieldsInspectorModel.ContextDomainValues.FirstOrDefault(pair => pair.Code.ToString() == loadSet.DisplayAttributes.Context); SymbolAttributeSet.DisplayAttributes.SelectedModifier1DomainPair = MilitaryFieldsInspectorModel.Modifier1DomainValues.FirstOrDefault(pair => pair.Code.ToString() == loadSet.DisplayAttributes.Modifier1); SymbolAttributeSet.DisplayAttributes.SelectedModifier2DomainPair = MilitaryFieldsInspectorModel.Modifier2DomainValues.FirstOrDefault(pair => pair.Code.ToString() == loadSet.DisplayAttributes.Modifier2); SymbolAttributeSet.LabelAttributes.SelectedCredibilityDomainPair = MilitaryFieldsInspectorModel.CredibilityDomainValues.FirstOrDefault(pair => pair.Code.ToString() == loadSet.LabelAttributes.Credibility); SymbolAttributeSet.LabelAttributes.SelectedReinforcedDomainPair = MilitaryFieldsInspectorModel.ReinforcedDomainValues.FirstOrDefault(pair => pair.Code.ToString() == loadSet.LabelAttributes.Reinforced); SymbolAttributeSet.LabelAttributes.SelectedReliabilityDomainPair = MilitaryFieldsInspectorModel.ReliabilityDomainValues.FirstOrDefault(pair => pair.Code.ToString() == loadSet.LabelAttributes.Reliability); SymbolAttributeSet.LabelAttributes.SelectedCountryCodeDomainPair = MilitaryFieldsInspectorModel.CountryCodeDomainValues.FirstOrDefault(pair => pair.Code.ToString() == loadSet.LabelAttributes.CountryCode); } } catch (Exception exception) { System.Diagnostics.Debug.WriteLine(exception.ToString()); } }
/// <summary> /// Takes an prepopulated IDataReader and creates an array of FeatureClasss /// </summary> public static List<FeatureClass> PopulateObjectWithJoin(IDataReader dr) { ColumnFieldList list = new ColumnFieldList(dr); List<FeatureClass> arr = new List<FeatureClass>(); FeatureClass obj; while (dr.Read()) { obj = new FeatureClass(); if (list.IsColumnPresent("FeatureClassID")) { obj._featureClassID = (int)dr["FeatureClassID"]; } if (list.IsColumnPresent("Name")) { obj._name = (string)dr["Name"]; } if (list.IsColumnPresent("Description")) { obj._description = (string)dr["Description"]; } arr.Add(obj); } dr.Close(); return arr; }
void RunExport(string fileName) { CadastralMapModel mapModel = CadastralMapModel.Current; using (ICreateDataStore cmd = m_Connection.CreateCommand(CommandType.CommandType_CreateDataStore) as ICreateDataStore) { try { cmd.DataStoreProperties.SetProperty("File", fileName); cmd.Execute(); } catch (OSGeo.FDO.Common.Exception ex) { Console.WriteLine(ex.Message); } } // The connection after the created is ConnectionState_Closed, so open it! m_Connection.ConnectionInfo.ConnectionProperties.SetProperty("File", fileName); m_Connection.Open(); // Define coordinate system using (ICreateSpatialContext cmd = m_Connection.CreateCommand(CommandType.CommandType_CreateSpatialContext) as ICreateSpatialContext) { ISpatialSystem ss = mapModel.SpatialSystem; cmd.CoordinateSystem = ss.Name; // CSMap key name cmd.ExtentType = SpatialContextExtentType.SpatialContextExtentType_Static; IWindow mapExtent = mapModel.Extent; IDirectPosition minxy = m_Factory.CreatePositionXY(mapExtent.Min.X, mapExtent.Min.Y); IDirectPosition maxxy = m_Factory.CreatePositionXY(mapExtent.Max.X, mapExtent.Max.Y); IEnvelope extent = m_Factory.CreateEnvelope(minxy, maxxy); IGeometry gx = m_Factory.CreateGeometry(extent); cmd.Extent = m_Factory.GetFgf(gx); cmd.XYTolerance = 0.000001; // resolution? cmd.CoordinateSystemWkt = EditingController.Current.GetCoordinateSystemText(); cmd.Execute(); } // Define feature schema FeatureSchema fs = new FeatureSchema("Steve", "This is a test"); FeatureClass fc = new FeatureClass("FC", "Test feature class"); fs.Classes.Add(fc); GeometricPropertyDefinition gp = new GeometricPropertyDefinition("Geometry", "Polygon property"); // When you stick more than one geometric type into the output, you can't // convert to SHP (not with FDO Toolbox anyway). //gp.GeometryTypes = (int)GeometricType.GeometricType_Surface; gp.GeometryTypes = (int)GeometricType.GeometricType_All; fc.Properties.Add(gp); fc.GeometryProperty = gp; // c.f. FdoToolbox ExpressUtility DataPropertyDefinition dp = new DataPropertyDefinition("ID", "Test ID"); dp.DataType = DataType.DataType_Int32; dp.Nullable = false; dp.ReadOnly = true; dp.IsAutoGenerated = true; fc.Properties.Add(dp); // Feature class requires an identity column for the insert fc.IdentityProperties.Add(dp); using (IApplySchema cmd = m_Connection.CreateCommand(CommandType.CommandType_ApplySchema) as IApplySchema) { cmd.FeatureSchema = fs; cmd.Execute(); } mapModel.Index.QueryWindow(null, SpatialType.Polygon | SpatialType.Point, ExportFeature); m_Connection.Flush(); m_Connection.Close(); }