public static void RelateTableLayer(ILayer pSrcLayer, string pSrcFieldName, ITable pToTable, string pToFieldName) { try { IAttributeTable table = pSrcLayer as IAttributeTable; if (table != null) { ITable attributeTable = table.AttributeTable; if (pToTable is IStandaloneTable) { pToTable = (pToTable as IStandaloneTable).Table; } IMemoryRelationshipClassFactory factory = new MemoryRelationshipClassFactoryClass(); IRelationshipClass relationshipClass = factory.Open("TabletoLayer", (IObjectClass)pToTable, pToFieldName, (IObjectClass)attributeTable, pSrcFieldName, "forward", "backward", esriRelCardinality.esriRelCardinalityOneToMany); ((IRelationshipClassCollectionEdit)pSrcLayer).AddRelationshipClass(relationshipClass); } } catch (COMException exception) { MessageBox.Show(exception.Message, "COM Error: " + exception.ErrorCode.ToString(), MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } catch (Exception exception2) { MessageBox.Show(exception2.Message, ".NET Error: ", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } }
public static void RelateTableLayer(ILayer ilayer_0, string string_0, ITable itable_0, string string_1) { try { IAttributeTable table = ilayer_0 as IAttributeTable; if (table != null) { ITable attributeTable = table.AttributeTable; if (itable_0 is IStandaloneTable) { itable_0 = (itable_0 as IStandaloneTable).Table; } IMemoryRelationshipClassFactory factory = new MemoryRelationshipClassFactoryClass(); IRelationshipClass relationshipClass = factory.Open("TabletoLayer", (IObjectClass)itable_0, string_1, (IObjectClass)attributeTable, string_0, "forward", "backward", esriRelCardinality.esriRelCardinalityOneToMany); ((IRelationshipClassCollectionEdit)ilayer_0).AddRelationshipClass(relationshipClass); } } catch (COMException exception) { MessageBox.Show(exception.Message, "COM Error: " + exception.ErrorCode.ToString(), MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } catch (Exception exception2) { MessageBox.Show(exception2.Message, ".NET Error: ", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } }
public static void JoinTableLayer(ITable itable_0, string string_0, ITable itable_1, string string_1) { try { ITable attributeTable = null; ITable displayTable = null; IDisplayTable table3 = itable_0 as IDisplayTable; if (table3 != null) { displayTable = table3.DisplayTable; } if (displayTable is IRelQueryTable) { attributeTable = displayTable; } else { IAttributeTable table4 = itable_0 as IAttributeTable; if (table4 == null) { return; } attributeTable = table4.AttributeTable; } if (itable_1 is IStandaloneTable) { itable_1 = (itable_1 as IStandaloneTable).Table; } IMemoryRelationshipClassFactory factory = new MemoryRelationshipClassFactoryClass(); IRelationshipClass relClass = factory.Open("TabletoLayer", (IObjectClass)itable_1, string_1, (IObjectClass)attributeTable, string_0, "forward", "backward", esriRelCardinality.esriRelCardinalityOneToMany); ((IDisplayRelationshipClass)itable_0).DisplayRelationshipClass(relClass, esriJoinType.esriLeftOuterJoin); } catch (COMException exception) { MessageBox.Show(exception.Message, "COM Error: " + exception.ErrorCode.ToString(), MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } catch (Exception exception2) { MessageBox.Show(exception2.Message, ".NET Error: ", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } }
public void FindCurves(string whereClause = null) { IMap pMap = ArcMap.Document.ActiveView.FocusMap; if (hasOpenJob()) return; IRelationshipClass relationshipClass = null; ISelectionSet relatedSelectionSet = null; myAOProgressor progressor = new myAOProgressor(); try { Finished = false; progressor.setStepProgressorProperties(1, "Initializing"); ICadastralFabricLayer CFLayer = GetFabricLayer(pMap); IFeatureLayer CFLineLayer = CFLayer.get_CadastralSubLayer(esriCadastralFabricRenderer.esriCFRLines); IFeatureLayer CFParcelLayer = CFLayer.get_CadastralSubLayer(esriCadastralFabricRenderer.esriCFRParcels); //for each CF line feature class IFeatureSelection CFLineFeatureSelection = (IFeatureSelection)CFLineLayer; IFeatureSelection CFParcelFeatureSelection = (IFeatureSelection)CFParcelLayer; ISelectionSet selectionSet = null; if (CFParcelFeatureSelection.SelectionSet.Count > 0) { //parcels selected //Create memory relationship class to help with the mapping IMemoryRelationshipClassFactory MemoryRCF = new MemoryRelationshipClassFactoryClass(); relationshipClass = MemoryRCF.Open("Parcel_Layer_Rel", CFParcelLayer.FeatureClass, "ObjectID", CFLineLayer.FeatureClass, "ParcelID", "forward", "backward", esriRelCardinality.esriRelCardinalityOneToMany); //convert selection set to ISet of rows ISet polySet = new Set(); ICursor cursor; CFParcelFeatureSelection.SelectionSet.Search(null, false, out cursor); IRow row = null; while((row = cursor.NextRow()) != null) polySet.Add(row); polySet.Reset(); //use the relationship class to find related rows ISet lineSet = relationshipClass.GetObjectsRelatedToObjectSet(polySet); //convert set back to selection set lineSet.Reset(); //create an empty selection set (there should be a better way to do this.... //will only evaluate the lines related to the parcels that are selected //selectionSet = CFLineLayer.FeatureClass.Select(new QueryFilter() { WhereClause = "1=0" }, esriSelectionType.esriSelectionTypeIDSet, esriSelectionOption.esriSelectionOptionNormal, null); //will union the current line selection and the parcel selection relatedSelectionSet = CFLineFeatureSelection.SelectionSet.Select(null, esriSelectionType.esriSelectionTypeIDSet, esriSelectionOption.esriSelectionOptionNormal, null); while ((row = (IRow)lineSet.Next()) != null) { relatedSelectionSet.Add(row.OID); Marshal.ReleaseComObject(row); } Marshal.ReleaseComObject(lineSet); polySet.Reset(); while ((row = (IRow)polySet.Next()) != null) Marshal.ReleaseComObject(row); Marshal.ReleaseComObject(polySet); selectionSet = relatedSelectionSet; } else if (CFLineFeatureSelection.SelectionSet.Count > 0) { //lines selected selectionSet = CFLineFeatureSelection.SelectionSet; } else { if (DialogResult.OK != messageBox.Show("You are about to run the add-in on the entire feature class, this could take a long time. Proceeed?", "Long Operation", MessageBoxButtons.OKCancel)) return; } FindCurves(CFLineLayer.Name, CFLineLayer.FeatureClass, selectionSet, whereClause, progressor); if (Curves.Count == 0) { messageBox.Show("No inferred curved lines found."); return; } } catch (Exception Exx) { messageBox.Show(Exx.Message); if (relationshipClass != null) Marshal.ReleaseComObject(relationshipClass); if (relatedSelectionSet != null) Marshal.ReleaseComObject(relatedSelectionSet); } finally { progressor.Dispose(); Finished = true; } }
private void SelectByJoin(string scratchMdbPath, string selectionDatasetName) { bool restoreEditSession = InEditingSession && HluLayerBeingEdited; if (restoreEditSession) CloseEditSession(true); IRelationshipClass relClass = null; IDataset joinDataset; ITable joinTable; IWorkspaceFactory joinWorkspaceFactory = new OLEDBWorkspaceFactoryClass(); try { SetCursor(true); OpenOleDbWorkspace(scratchMdbPath, selectionDatasetName, ref joinWorkspaceFactory, out joinDataset, out joinTable); if ((joinTable.Fields.FieldCount == 1) && (joinTable.Fields.get_Field(0).Name == _hluLayerStructure.incidColumn.ColumnName)) // single column incid: use a join { IDisplayTable hluDisplayTable = (IDisplayTable)_hluLayer; IFeatureClass hluDisplayTableFeatureClass = (IFeatureClass)hluDisplayTable.DisplayTable; ITable hluLayerTable = (ITable)hluDisplayTableFeatureClass; string originPKJoinField = _hluLayerStructure.incidColumn.ColumnName; string originFKJoinField = _hluFeatureClass.Fields.get_Field(_hluFieldMap[_hluLayerStructure.incidColumn.Ordinal]).Name; // create virtual relate IMemoryRelationshipClassFactory memoryRelFactory = new MemoryRelationshipClassFactoryClass(); relClass = memoryRelFactory.Open("SelRelClass", (IObjectClass)joinTable, originPKJoinField, (IObjectClass)hluLayerTable, originFKJoinField, "forward", "backward", esriRelCardinality.esriRelCardinalityOneToMany); // use Relate to perform a join IDisplayRelationshipClass displayRelClass = (IDisplayRelationshipClass)_hluLayer; displayRelClass.DisplayRelationshipClass(relClass, esriJoinType.esriLeftOuterJoin); _joinedTable = true; Regex fldNameRegex = new Regex(@"((""|\[)*" + selectionDatasetName + @"(""|\[)*\.)*(""|\])*" + originPKJoinField + @"(""|\])*", RegexOptions.IgnoreCase); string joinExpr = originPKJoinField; string s = null; for (int i = hluDisplayTable.DisplayTable.Fields.FieldCount - 1; i > 0; i--) { s = hluDisplayTable.DisplayTable.Fields.get_Field(i).Name; if (fldNameRegex.IsMatch(s)) { joinExpr = s; break; } } IQueryFilter queryFilter = new QueryFilterClass(); queryFilter.WhereClause = String.Format("{0} IS NOT NULL", joinExpr); // invalidate only the selection cache. Flag the original selection _hluView.PartialRefresh(esriViewDrawPhase.esriViewGeoSelection, null, null); // perform selection ISelectionSet selSet = hluDisplayTable.SelectDisplayTable(queryFilter, esriSelectionType.esriSelectionTypeHybrid, esriSelectionOption.esriSelectionOptionNormal, null); _hluFeatureSelection = (IFeatureSelection)_hluLayer; _hluFeatureSelection.SelectionSet = selSet; } else // multi-column join: use cumulative selection sets { SelectByJoinMultiColumn(joinTable); } } catch { } finally { // Remove the virtual relationship. if (relClass != null) { //IRelationshipClassCollectionEdit relClassEdit = (IRelationshipClassCollectionEdit)joinLayer; //relClassEdit.RemoveAllRelationshipClasses(); ((IDisplayRelationshipClass)_hluLayer).DisplayRelationshipClass( null, esriJoinType.esriLeftInnerJoin); } // Destroy workspace factory so the attribute dataset can // be deleted later. joinDataset = null; joinTable = null; joinWorkspaceFactory = null; if (restoreEditSession) OpenEditSession(); SetCursor(false); } }
private void Export(string tempMdbPathName, string attributeDatasetName, bool selectedOnly) { IRelationshipClass relClass = null; IFeatureClass outFeatureClass = null; IFeatureClass joinFeatureClass = null; IFeatureLayer joinLayer = null; IDataset attributeDataset; ITable exportAttributes; IWorkspaceFactory joinWorkspaceFactory = new OLEDBWorkspaceFactoryClass(); object outWS = null; try { SetCursor(true); OpenOleDbWorkspace(tempMdbPathName, attributeDatasetName, ref joinWorkspaceFactory, out attributeDataset, out exportAttributes); IDisplayTable hluDisplayTable = (IDisplayTable)_hluLayer; IFeatureClass hluDisplayTableFeatureClass = (IFeatureClass)hluDisplayTable.DisplayTable; // Set the selected and total feature counts. int selectedFeatureCount = _hluFeatureSelection.SelectionSet.Count; int totalFeatureCount = _hluLayer.FeatureClass.FeatureCount(null); int exportFeatureCount = 0; // Prompt the user for where to save the export layer. IExportOperation exportOp = new ExportOperation(); bool saveProjection; esriExportTableOptions exportOptions; IDatasetName exportDatasetName = exportOp.GetOptions(hluDisplayTableFeatureClass, _hluLayer.Name, _hluFeatureSelection != null && _hluFeatureSelection.SelectionSet.Count > 0, true, _application.hWnd, out saveProjection, out exportOptions); // If no export dataset name was chosen by the user then cancel the export. if (exportDatasetName == null) { _pipeData.Add("cancelled"); return; } // Open the export dataset workspace. outWS = ((IName)exportDatasetName.WorkspaceName).Open(); // Determine if the export layer is a shapefile. bool isShp = IsShp(outWS as IWorkspace); //--------------------------------------------------------------------- // FIX: 050 Warn ArcGIS users if field names may be truncated or // renamed exporting to shapefiles. // // If the export layer is a shapefile check if any of // the attribute field names will be truncated. if (isShp) { bool fieldNamesTruncated = false; for (int i = 0; i < exportAttributes.Fields.FieldCount; i++) { IField attributeField = exportAttributes.Fields.get_Field(i); if (attributeField.Name.Length > 10) { fieldNamesTruncated = true; break; } } // Warn the user that some field names may get truncated. if (fieldNamesTruncated) { MessageBoxResult userResponse = MessageBoxResult.No; userResponse = MessageBox.Show("Some field names may get truncated or renamed exporting to a shapefile.\n\nDo you wish to proceed?", "HLU: Export", MessageBoxButton.YesNo, MessageBoxImage.Question); if (userResponse != MessageBoxResult.Yes) { _pipeData.Add("cancelled"); return; } } } //--------------------------------------------------------------------- // Get the geometry definition for the feature layer. IGeometryDef geomDef = _hluFeatureClass.Fields.get_Field(_hluFeatureClass.FindField( _hluFeatureClass.ShapeFieldName)).GeometryDef; ITable joinLayerTable; IDisplayTable joinDisplayTable; //--------------------------------------------------------------------- // CHANGED: CR13 (Export features performance) // // If only a sub-set of features are being exported then // export the sub-set to a temporary feature class before // joining the temporary layer to the attribute dataset. if (selectedOnly) { // Set the export options for which records to export. exportOptions = esriExportTableOptions.esriExportSelectedRecords; // Set the input DataSet name IDataset inDataset; inDataset = (IDataset)hluDisplayTable.DisplayTable; IDatasetName inDatasetName; inDatasetName = (IDatasetName)inDataset.FullName; // set the output temporary DataSet name IFeatureClassName outFCName = new FeatureClassNameClass(); IDatasetName outDatasetName = (IDatasetName)outFCName; outDatasetName.Name = String.Format("{0}_temp", exportDatasetName.Name); outDatasetName.WorkspaceName = exportDatasetName.WorkspaceName; // Get the selected features for export ISelectionSet selectionSet = _hluFeatureSelection.SelectionSet; // If there is no selection cancel the export. if (_hluFeatureSelection.SelectionSet.Count == 0) { _pipeData.Add("noselection"); return; } // Export the selected features to the temporary dataset. exportOp.ExportFeatureClass(inDatasetName, null, selectionSet, geomDef, (IFeatureClassName)outDatasetName, _application.hWnd); // Cast the workspace to IFeatureWorkspace and open the feature class. IFeatureWorkspace featureWorkspace = (IFeatureWorkspace)outWS; joinFeatureClass = featureWorkspace.OpenFeatureClass(outDatasetName.Name); // Add an attribute index to the incid field. AddFieldIndex(joinFeatureClass, String.Format("IX_{0}", _hluLayerStructure.incidColumn.ColumnName), _hluLayerStructure.incidColumn.ColumnName); // Set the join layer to the temporary feature class. joinLayer = new FeatureLayerClass(); joinLayer.FeatureClass = joinFeatureClass; joinLayer.Name = joinFeatureClass.AliasName; // Set the join layer table to the temporary feature class. joinDisplayTable = (IDisplayTable)joinLayer; //IFeatureClass joinDisplayTableFC = (IFeatureClass)joinDisplayTable.DisplayTable; IFeatureClass joinDisplayTableFC = joinFeatureClass; joinLayerTable = (ITable)joinDisplayTableFC; // Set the count for the number of features to be exported. exportFeatureCount = selectedFeatureCount; } // Otherwise, join the whole feature layer to the // attribute dataset. else { // Clear any current selection. _hluFeatureSelection.SelectionSet = null; // Set the export options for which records to export. exportOptions = esriExportTableOptions.esriExportAllRecords; // Set the join feature class to the current HLU feature class. joinFeatureClass = _hluFeatureClass; // Set the join layer to the current HLU feature layer. joinLayer = _hluLayer; joinLayerTable = (ITable)hluDisplayTableFeatureClass; joinDisplayTable = hluDisplayTable; // Set the count for the number of features to be exported. exportFeatureCount = totalFeatureCount; } //--------------------------------------------------------------------- // Get the field names to be used when joining the attribute data and the feature layer string originPKJoinField = _hluLayerStructure.incidColumn.ColumnName; string originFKJoinField = _hluFeatureClass.Fields.get_Field(_hluFieldMap[_hluLayerStructure.incidColumn.Ordinal]).Name; // Get a list of all the fields to be used in the export layer (plus separate lists of all // those fields that will come from the attribute table and those that will come from the // feature layer). List<IField> attributeFields; List<IField> featClassFields; List<IField> exportFields = ExportFieldLists(isShp, originPKJoinField, originFKJoinField, joinFeatureClass, exportAttributes, out attributeFields, out featClassFields); // Add x/y, length, or area and length fields to the list of fields in the export layer // if the export layer is a shapefile. ExportAddGeometryPropertyFields(isShp, exportFields); // Create a virtual relationship between the feature class // and the attribute dataset. IMemoryRelationshipClassFactory memoryRelFactory = new MemoryRelationshipClassFactoryClass(); relClass = memoryRelFactory.Open("ExportRelClass", (IObjectClass)exportAttributes, originPKJoinField, (IObjectClass)joinLayerTable, originFKJoinField, "forward", "backward", esriRelCardinality.esriRelCardinalityOneToMany); // Use the relationship to perform a join. IDisplayRelationshipClass displayRelClass = (IDisplayRelationshipClass)joinLayer; displayRelClass.DisplayRelationshipClass(relClass, esriJoinType.esriLeftInnerJoin); // Create query filter for the export cursor so that // only the required fields are retrieved. bool featClassFieldsQualified; bool attributeFieldsQualified; IQueryFilter exportQueryFilter = ExportQueryFilter(originPKJoinField, joinLayer, joinFeatureClass, joinDisplayTable, attributeDataset, featClassFields, attributeFields, out featClassFieldsQualified, out attributeFieldsQualified); // Create a collection of fields for the output feature class. // Adds OID and SHAPE at beginning. IFields outFields = CreateFieldsCollection(true, geomDef.HasZ, geomDef.HasM, outWS, joinFeatureClass.ShapeType, exportFields.Select(f => f.Length).ToArray(), exportFields.Select(f => f.Name).ToArray(), exportFields.Select(f => f.Name).ToArray(), exportFields.Select(f => f.Type).ToArray(), exportFields.Select(f => f.Type != esriFieldType.esriFieldTypeOID).ToArray(), geomDef.SpatialReference); // Create the output feature class. outFeatureClass = CreateFeatureClass(exportDatasetName.Name, null, outWS, outFields, esriFeatureType.esriFTSimple, joinFeatureClass.ShapeType, null, null); // Map the fields between the display and table and the output feature // class as the display table always includes all fields. // The first two fields are always OID and SHAPE. int[] exportFieldMap = new int[] { 0, 1 }.Concat(featClassFields .Select(f => joinDisplayTable.DisplayTable.Fields.FindField(featClassFieldsQualified ? joinLayer.Name + "." + f.Name : f.Name))).Concat(attributeFields .Select(f => joinDisplayTable.DisplayTable.Fields.FindField(attributeFieldsQualified ? attributeDataset.Name + "." + f.Name : f.Name))).ToArray(); //--------------------------------------------------------------------- // FIX: 038 Display the export progress bar correctly when exporting // from ArcGIS. // Pass the number of features to be exported, not the number of incids, // so that the export progress is displayed corectly // // Insert the features and attributes into the new feature class. ExportInsertFeatures(joinDisplayTable, exportQueryFilter, exportFeatureCount, exportFieldMap, isShp, outWS, outFeatureClass); //--------------------------------------------------------------------- //--------------------------------------------------------------------- // CHANGED: CR16 (Adding exported features) // Ask the user if they want to add the new export layer // to the active map. MessageBoxResult addResponse = MessageBoxResult.No; addResponse = MessageBox.Show("The export operation succeeded.\n\nAdd the exported layer to the current map?", "HLU: Export", MessageBoxButton.YesNo, MessageBoxImage.Question); if (addResponse == MessageBoxResult.Yes) { // Add the exported feature layer to the active map. IFeatureLayer hluExportLayer; hluExportLayer = new FeatureLayer(); hluExportLayer.FeatureClass = outFeatureClass; hluExportLayer.Name = outFeatureClass.AliasName; _focusMap.AddLayer(hluExportLayer); } //--------------------------------------------------------------------- } catch (Exception ex) { _pipeData.Add(ex.Message); } finally { // Remove the virtual relationship. if (relClass != null) { //IRelationshipClassCollectionEdit relClassEdit = (IRelationshipClassCollectionEdit)joinLayer; //relClassEdit.RemoveAllRelationshipClasses(); ((IDisplayRelationshipClass)joinLayer).DisplayRelationshipClass( null, esriJoinType.esriLeftInnerJoin); } // Destroy workspace factory so the attribute dataset can // be deleted later. attributeDataset = null; exportAttributes = null; joinWorkspaceFactory = null; // Delete the temporary feature class. try { if (joinFeatureClass != _hluFeatureClass) { IDataset tempDataset = (IDataset)joinFeatureClass; if (tempDataset != null) tempDataset.Delete(); } } catch { } SetCursor(false); } }
private ISet GetSelectedPrimaryParcels(IFeatureLayer surveyParcelLayer, IWorkspace tantalisWorkspace) { // Mar 12, 2008 m_pISDUTExt = RestTransactionManager.Instance.BaseTransactionManager.extension(); //(ISDUTExtension)_App.FindExtensionByName("SUITT Extension"); this.TANTschema = m_pISDUTExt.get_SystemValue("db.tant.schema") + "."; ISet theReturn = null; if (surveyParcelLayer == null) return null; IQueryFilter theQF = new QueryFilterClass(); util.Logger.Write("Fetching all selected parcels"); //theQF.WhereClause = PARCEL_TYPE_FIELD_NAME + " = " + PRIMARY_PARCEL_CODE; //util.Logger.Write("Fetching parcels where: " + PARCEL_TYPE_FIELD_NAME + " = " + PRIMARY_PARCEL_CODE); if (tantalisWorkspace != null) { // Create in-memory join IRelationshipClass2 theRC = null; try { // Open the related table ITable theOsdbTable = ((IFeatureWorkspace)tantalisWorkspace).OpenTable(TANTschema + SURVEY_PARCEL_TAB_NAME); IMemoryRelationshipClassFactory theFactory = new MemoryRelationshipClassFactoryClass(); theRC = (IRelationshipClass2)theFactory.Open( SURVEY_PARCEL_FC_NAME + "_to_" + SURVEY_PARCEL_TAB_NAME, (IObjectClass)surveyParcelLayer.FeatureClass, SURVEY_PARCEL_FK_NAME, (IObjectClass)theOsdbTable, SURVEY_PARCEL_FK_NAME, "forward", "backward", esriRelCardinality.esriRelCardinalityOneToOne); } catch (Exception ex) { util.Logger.Write("Error creating memory relationship class between " + SURVEY_PARCEL_FC_NAME + " and " + SURVEY_PARCEL_TAB_NAME + ":" + Environment.NewLine + ex.Message + Environment.NewLine + ex.StackTrace); return null; } // Loop through the selected features ISet theSelectedSPs = new SetClass(); ICursor theCursor = null; ((IFeatureSelection)surveyParcelLayer).SelectionSet.Search(null, false, out theCursor); IRow theSPRow = theCursor.NextRow(); while (theSPRow != null) { theSelectedSPs.Add(theSPRow); theSPRow = theCursor.NextRow(); } Marshal.ReleaseComObject(theCursor); IRelClassEnumRowPairs thePairs = theRC.GetObjectsMatchingObjectSetEx(theSelectedSPs, theQF, true); theReturn = new SetClass(); IRow theOsdbRow; thePairs.Next(out theSPRow, out theOsdbRow); while (theSPRow != null) { theReturn.Add(theSPRow); thePairs.Next(out theSPRow, out theOsdbRow); } } else { // Loop through the selected features theReturn = new SetClass(); ICursor theCursor = null; ((IFeatureSelection)surveyParcelLayer).SelectionSet.Search(theQF, false, out theCursor); IRow theSPRow = theCursor.NextRow(); while (theSPRow != null) { theReturn.Add(theSPRow); theSPRow = theCursor.NextRow(); } Marshal.ReleaseComObject(theCursor); } return theReturn; }
private void Export(string tempMdbPathName, string attributeDatasetName, int exportRowCount) { IRelationshipClass relClass = null; IFeatureClass outFeatureClass = null; try { SetCursor(true); IDataset attributeDataset; ITable exportAttributes; OpenOleDbWorkspace(tempMdbPathName, attributeDatasetName, out attributeDataset, out exportAttributes); IDisplayTable hluDisplayTable = (IDisplayTable)_hluLayer; IFeatureClass hluDisplayTableFeatureClass = (IFeatureClass)hluDisplayTable.DisplayTable; ITable hluLayerTable = (ITable)hluDisplayTableFeatureClass; IExportOperation exportOp = new ExportOperation(); bool saveProjection; esriExportTableOptions exportOptions; IDatasetName exportDatasetName = exportOp.GetOptions(hluDisplayTableFeatureClass, _hluLayer.Name, _hluFeatureSelection != null && _hluFeatureSelection.SelectionSet.Count > 0, true, _application.hWnd, out saveProjection, out exportOptions); if (exportDatasetName == null) { _pipeData.Add("cancelled"); return; } object outWS = ((IName)exportDatasetName.WorkspaceName).Open(); string originPKJoinField = _hluLayerStructure.incidColumn.ColumnName; string originFKJoinField = _hluFeatureClass.Fields.get_Field(_hluFieldMap[_hluLayerStructure.incidColumn.Ordinal]).Name; List<IField> attributeFields; List<IField> featClassFields; List<IField> exportFields = ExportFieldLists(originPKJoinField, originFKJoinField, exportAttributes, out attributeFields, out featClassFields); bool isShp = IsShp(outWS as IWorkspace); ExportAddGeometryPropertyFields(isShp, exportFields); // create virtual relate IMemoryRelationshipClassFactory memoryRelFactory = new MemoryRelationshipClassFactoryClass(); relClass = memoryRelFactory.Open("ExportRelClass", (IObjectClass)exportAttributes, originPKJoinField, (IObjectClass)hluLayerTable, originFKJoinField, "forward", "backward", esriRelCardinality.esriRelCardinalityOneToMany); // use Relate to perform a join IDisplayRelationshipClass displayRelClass = (IDisplayRelationshipClass)_hluLayer; displayRelClass.DisplayRelationshipClass(relClass, esriJoinType.esriLeftOuterJoin); // create query filter for export cursor bool featClassFieldsQualified; bool attributeFieldsQualified; IQueryFilter exportQueryFilter = ExportQueryFilter(originPKJoinField, hluDisplayTable, attributeDataset, featClassFields, attributeFields, out featClassFieldsQualified, out attributeFieldsQualified); IGeometryDef geomDef = _hluFeatureClass.Fields.get_Field(_hluFeatureClass.FindField( _hluFeatureClass.ShapeFieldName)).GeometryDef; // adds OID and SHAPE at beginning, possibly Shape_Length and Shape_Area at end // when populating new rows we loop over exportFieldOrdinals // if we export shp we calculate geometry props into the last two fields, which are // not in exportFields IFields outFields = CreateFieldsCollection(true, geomDef.HasZ, geomDef.HasM, outWS, _hluFeatureClass.ShapeType, exportFields.Select(f => f.Length).ToArray(), exportFields.Select(f => f.Name).ToArray(), exportFields.Select(f => f.Name).ToArray(), exportFields.Select(f => f.Type).ToArray(), exportFields.Select(f => f.Type != esriFieldType.esriFieldTypeOID).ToArray(), geomDef.SpatialReference); // create output feature class outFeatureClass = CreateFeatureClass(exportDatasetName.Name, null, outWS, outFields, esriFeatureType.esriFTSimple, _hluFeatureClass.ShapeType, null, null); // field map between display and output feature class, as display // table always includes all fields, regardless of SubFields // the first two fields are always OID and SHAPE // the last two Shape_Length and Shape_Area, either added automatically or here int[] exportFieldMap = new int[] { 0, 1 }.Concat(featClassFields .Select(f => hluDisplayTable.DisplayTable.Fields.FindField(featClassFieldsQualified ? _hluLayer.Name + "." + f.Name : f.Name))).Concat(attributeFields .Select(f => hluDisplayTable.DisplayTable.Fields.FindField(attributeFieldsQualified ? attributeDataset.Name + "." + f.Name : f.Name))).ToArray(); // insert features into new feature class ExportInsertFeatures(hluDisplayTable, exportQueryFilter, exportRowCount, exportFieldMap, isShp, outWS, outFeatureClass); } catch (Exception ex) { _pipeData.Add(ex.Message); } finally { if (relClass != null) ((IDisplayRelationshipClass)_hluLayer).DisplayRelationshipClass( null, esriJoinType.esriLeftInnerJoin); outFeatureClass = null; try { if (File.Exists(tempMdbPathName)) File.Delete(tempMdbPathName); } catch { } SetCursor(false); } }
private void CompareAreas(IFeatureClass workingFeatureClass, IFeatureCursor checkCursor, ITable relatedTable, string relateFieldName, string areaFieldName, double conversionFactor, double tolerance, bool canDefer, bool canExcept) { IDataset theDS1 = (IDataset)relatedTable; IDataset theDS2 = (IDataset)workingFeatureClass; IRelationshipClass theRC = null; if (relatedTable != null && relateFieldName != null && relateFieldName.Length > 0) { try { // Create relationshipclass backwards to normal, b/c we're checking // that the SIDs that exist in the FC exist in the biz table IMemoryRelationshipClassFactory theFactory = new MemoryRelationshipClassFactoryClass(); IObjectClass bob = (IObjectClass)workingFeatureClass; IObjectClass sam = (IObjectClass)relatedTable; theRC = theFactory.Open( theDS2.Name + "_to_" + theDS1.Name, bob, relateFieldName, sam, relateFieldName, "forward", "backward", esriRelCardinality.esriRelCardinalityOneToOne); } catch (Exception ex) { this.LogMessage("Error creating memory relationship class between " + theDS2.Name + " and " + theDS1.Name + ":" +Environment.NewLine + ex.Message + Environment.NewLine + ex.StackTrace); return; } } try { int areaFieldIndex = -1; int fkIndex = -1; if (theRC == null) { // Area field is on the feature areaFieldIndex = workingFeatureClass.FindField(areaFieldName); } else { // Area field is on the related table areaFieldIndex = relatedTable.FindField(areaFieldName); fkIndex = workingFeatureClass.FindField(relateFieldName); } IFeature theFeature = checkCursor.NextFeature(); while (theFeature != null) { double areaDbValue = double.NaN; double areaGeoValue = double.NaN; // Get the geographic area in sq. metres if (theFeature.Shape != null && theFeature.Shape.IsEmpty == false) { IGeometry theGeometry = theFeature.ShapeCopy; theGeometry.Project(SpatialReferenceHelper.BCAlbersSpatialReference); areaGeoValue = ((IArea)theGeometry).Area; } if (theRC == null) { // Db Area is on the feature areaDbValue = Convert.ToDouble(theFeature.get_Value(areaFieldIndex)); areaDbValue *= conversionFactor; } else { // Db Area is on related feature // Only valid if there is exactly one related record // and it has a real area (not zero or null) ISet theSet = theRC.GetObjectsRelatedToObject((IObject)theFeature); if (theSet.Count == 1) { IObject theRelatedObject = (IObject)theSet.Next(); if (theRelatedObject != null) { object theValue = theRelatedObject.get_Value(areaFieldIndex); if (Convert.IsDBNull(theValue) == false) { double theDValue = Convert.ToDouble(theValue); if (theDValue > 0) { areaDbValue = theDValue; areaDbValue *= conversionFactor; } } } } } if (double.IsNaN(areaDbValue)) { /* IPoint theErrorPoint = this.get_ErrorPoint(theFeature.Shape); DataQualityError theError = new DataQualityError(this.Name, canDefer, canExcept); theError.Location = theErrorPoint; theError.Severity = 1; theError.Description = "Null database area"; ExtendedInfo theInfo = new ExtendedInfo(); theInfo.AddProperty("Feature class", theDS2.Name); theInfo.AddProperty("Feature ID", theFeature.OID.ToString()); if (theRC != null) { theInfo.AddProperty("Related table", theDS1.Name); object fkValue = theFeature.get_Value(fkIndex); theInfo.AddProperty("FK value", fkValue == null ? "NULL" : fkValue.ToString()); } theError.ExtendedData = theInfo.WriteXML(); this._errors.Add(theError); */ } else if (double.IsNaN(areaGeoValue)) { IPoint theErrorPoint = this.get_ErrorPoint(null); DataQualityError theError = new DataQualityError(this.Name, canDefer, canExcept); theError.Location = theErrorPoint; theError.Severity = 1; theError.Description = "Null geographic area"; ExtendedInfo theInfo = new ExtendedInfo(); theInfo.AddProperty("Feature class", theDS2.Name); theInfo.AddProperty("Feature ID", theFeature.OID.ToString()); if (theRC != null) { theInfo.AddProperty("Related table", theDS1.Name); object fkValue = theFeature.get_Value(fkIndex); theInfo.AddProperty("SID", fkValue == null ? "NULL" : fkValue.ToString()); } theError.ExtendedData = theInfo.WriteXML(); this._errors.Add(theError); } else { double difference = Math.Abs(areaDbValue - areaGeoValue); if (difference > tolerance) { // Error IPoint theErrorPoint = this.get_ErrorPoint(theFeature.Shape); DataQualityError theError = new DataQualityError(this.Name, canDefer, canExcept); theError.Location = theErrorPoint; if (difference < tolerance * 2) theError.Severity = 3; else if (difference < tolerance * 10) theError.Severity = 2; else theError.Severity = 1; theError.Description = "Stored area different from geographic area"; ExtendedInfo theInfo = new ExtendedInfo(); theInfo.AddProperty("Feature class", theDS2.Name); theInfo.AddProperty("Feature ID", theFeature.OID.ToString()); theInfo.AddProperty("Geographic area (sq. metres)", areaGeoValue.ToString()); theInfo.AddProperty("Database area (sq. metres)", areaDbValue.ToString()); if (theRC != null) { theInfo.AddProperty("Related table", theDS1.Name); object fkValue = theFeature.get_Value(fkIndex); theInfo.AddProperty("SID", fkValue == null ? "NULL" : fkValue.ToString()); } theError.ExtendedData = theInfo.WriteXML(); //this.LogMessage(theError.ExtendedData); this._errors.Add(theError); } } theFeature = checkCursor.NextFeature(); } } catch (Exception ex) { this.LogMessage("Error comparing areas:" + Environment.NewLine + ex.Message + Environment.NewLine + ex.StackTrace); } }
private void CompareSIDs(IFeatureClass workingFeatureClass, IFeatureCursor checkCursor, ITable osdbBizTable, string sidFieldName, bool canDefer, bool canExcept) { IDataset theDS1 = (IDataset)osdbBizTable; IDataset theDS2 = (IDataset)workingFeatureClass; IRelationshipClass theRC = null; try { // Create relationshipclass backwards to normal, b/c we're checking // that the SIDs that exist in the FC exist in the biz table IMemoryRelationshipClassFactory theFactory = new MemoryRelationshipClassFactoryClass(); theRC = theFactory.Open( theDS2.Name + "_to_" + theDS1.Name, (IObjectClass)workingFeatureClass, sidFieldName, (IObjectClass)osdbBizTable, sidFieldName, "forward", "backward", esriRelCardinality.esriRelCardinalityOneToOne); } catch (Exception ex) { this.LogMessage("Error creating memory relationship class between " + theDS2.Name + " and " + theDS1.Name + ":" +Environment.NewLine + ex.Message + Environment.NewLine + ex.StackTrace); return; } try { int sidIndex = workingFeatureClass.FindField(sidFieldName); IFeature theFeature = checkCursor.NextFeature(); while (theFeature != null) { ISet theSet = theRC.GetObjectsRelatedToObject((IObject)theFeature); if (theSet.Count == 0) { // Error IPoint theErrorPoint = this.get_ErrorPoint(theFeature.Shape); DataQualityError theError = new DataQualityError(this.Name, canDefer, canExcept); theError.Location = theErrorPoint; theError.Severity = 1; theError.Description = "No corresponding OSDB record"; ExtendedInfo theInfo = new ExtendedInfo(); theInfo.AddProperty("Feature class", theDS2.Name); theInfo.AddProperty("OSDB table", theDS1.Name); theInfo.AddProperty("Feature ID", theFeature.OID.ToString()); object sidValue = theFeature.get_Value(sidIndex); theInfo.AddProperty("SID value", sidValue == null ? "NULL" : sidValue.ToString()); theError.ExtendedData = theInfo.WriteXML(); //this.LogMessage(theError.ExtendedData); this._errors.Add(theError); } theFeature = checkCursor.NextFeature(); } } catch (Exception ex) { this.LogMessage("Error looking for OSDB records:" + Environment.NewLine + ex.Message + Environment.NewLine + ex.StackTrace); } }
public IRelationshipClass get_OsdbRelationship( IFeatureClass workingFeatureClass, ITable osdbBizTable, string sidFieldName) { IRelationshipClass theReturn = null; if (osdbBizTable == null || workingFeatureClass == null) return theReturn; IDataset theDS1 = (IDataset)osdbBizTable; IDataset theDS2 = (IDataset)workingFeatureClass; try { IMemoryRelationshipClassFactory theFactory = new MemoryRelationshipClassFactoryClass(); theReturn = theFactory.Open( theDS1.Name + "_to_" + theDS2.Name, (IObjectClass)osdbBizTable, sidFieldName, (IObjectClass)workingFeatureClass, sidFieldName, "forward", "backward", esriRelCardinality.esriRelCardinalityOneToOne); } catch (Exception ex) { util.Logger.Write("Error creating memory relationship class between " + theDS1.Name + " and " + theDS2.Name + ":" +Environment.NewLine + ex.Message + Environment.NewLine + ex.StackTrace); } return theReturn; }
private int count(string prefix, TransactionConfig.LayerConfig layer, IWorkspace sdeConn, SEE see) { if(prefix !=null && !prefix.Equals("") && !prefix.EndsWith(".")) { prefix = prefix+"."; } Logger.Write("Opening "+prefix+layer.OsdbLayerName); IFeatureClass osdb_fc = null; try { osdb_fc = ((IFeatureWorkspace)sdeConn).OpenFeatureClass(prefix+layer.OsdbLayerName); } catch(Exception e) { throw new HandledException(e); } ITable osdb_tbl = (ITable)osdb_fc; string[] keys = layer.Keys; IRelationshipClass osdb_rltn = null; if(layer.JoinName != null) { Logger.Write("Creating Join"); IMemoryRelationshipClassFactory memoryRelClassFactory = new MemoryRelationshipClassFactoryClass(); ITable osdb_jtbl = null; try { osdb_jtbl = ((IFeatureWorkspace)sdeConn).OpenTable(prefix+layer.JoinTable); } catch(Exception e) { MessageBox.Show("Table "+prefix+layer.JoinTable+" Not Found in OSDB", "EXCEPTION", MessageBoxButtons.OK, MessageBoxIcon.Error); throw new HandledException(e); } string kprint = null; for(int i=0;i<keys.Length;i++) { if(kprint == null) { kprint = keys[i]; } else { kprint = kprint+","+keys[i]; } } osdb_rltn = memoryRelClassFactory.Open(layer.JoinName,osdb_fc,kprint,(IObjectClass)osdb_jtbl,kprint, "forward","backward",esriRelCardinality.esriRelCardinalityOneToOne); } ISpatialFilter osdb_filter = new SpatialFilterClass(); osdb_filter.Geometry = see.Shape; osdb_filter.GeometryField = osdb_fc.ShapeFieldName; osdb_filter.SubFields = osdb_fc.OIDFieldName; osdb_filter.SpatialRel = esriSpatialRelEnum.esriSpatialRelRelation; if (layer.isPoint) { osdb_filter.SpatialRelDescription = Transaction.ExtractPointMask; } else { if (layer.isLine) { osdb_filter.SpatialRelDescription = Transaction.ExtractLineMask; } else { if (layer.isPoly) { osdb_filter.SpatialRelDescription = Transaction.ExtractPolyMask; } else { // default osdb_filter.SpatialRelDescription = Transaction.ExtractPolyMask; } } } Logger.Write("Create extract cursor"); ICursor osdb_cursor = null; int r = 0; try { osdb_cursor = osdb_tbl.Search(osdb_filter, false); for (IRow row = osdb_cursor.NextRow(); row != null; row = osdb_cursor.NextRow()) { if (row != null) r++; } } finally { if (osdb_filter != null) { Utils.Release(osdb_filter); } if (osdb_cursor != null) { Utils.Release(osdb_cursor); } } return r; }