/// <summary> /// 数据排序 /// </summary> /// <param name="pFeatureClass"></param> //排序函数 private void SortFeatures(IFeatureClass pFeatureClass, IFeatureLayer _pLayer) { ITableSort pTableSort = new TableSortClass(); IFields pFields = pFeatureClass.Fields; IField pField = pFields.get_Field(col_index); col_index = 0; pTableSort.Fields = pField.Name; if (up) { pTableSort.set_Ascending(pField.Name, true); } else { pTableSort.set_Ascending(pField.Name, false); } pTableSort.set_CaseSensitive(pField.Name, true); pTableSort.Table = pFeatureClass as ITable; pTableSort.Sort(null); ICursor pCursor = pTableSort.Rows; pTs = pTableSort; RefreshTable(_pLayer, pFeatureClass, dataGridView1, pField.Name, pCursor); }
/// <summary> /// 要素排序 /// </summary> /// <param name="pFeatureClass">要排序的要素类</param> /// <param name="columName">Name of the colum.</param> private void SortFeatures(IFeatureClass pFeatureClass, string columName) { ITableSort pTableSort = new TableSortClass(); IFields pFields = pFeatureClass.Fields; int index = pFields.FindFieldByAliasName(columName); IField pField = pFields.get_Field(index); pTableSort.Fields = pField.Name; switch (_up) { case true: pTableSort.set_Ascending(pField.Name, true); _up = false; break; case false: pTableSort.set_Ascending(pField.Name, false); _up = true; break; } pTableSort.set_CaseSensitive(pField.Name, true); pTableSort.Table = pFeatureClass as ITable; pTableSort.Sort(null); ICursor pCursor = pTableSort.Rows; _pTs = pTableSort; RefreshTable(); }
/// <summary> /// This function sorts an input table, /// then it loops through each feature of the table to see if the x values are the same /// if they are the same, the x and y values are incremented by the offset sum amount /// if they are not the same the offset is reset to the original offset /// </summary> /// <param name="pTable">the table to sort and create offset xy values for the xy events</param> /// <param name="dblOffset">the amount in map units to offset the x and y</param> /// <changelog> /// /// comments created. /// /// added test to see if med_X has a length greater than 0 /// </changelog> public void createOffset(ITable pTable, Double dblXOffset, Double dblYOffset, string xValue, string yValue) { ITableSort pTableSort = new TableSortClass(); pTableSort.Fields = xValue + "," + yValue; pTableSort.set_Ascending(xValue, false); pTableSort.set_Ascending(yValue, false); pTableSort.Table = pTable; pTableSort.Sort(null); ICursor pCursor = pTableSort.Rows; //pTable.Update(null, true); IRow pRow = pCursor.NextRow(); string x1 = ""; string y = ""; string x2 = ""; double dblXTemp = 0; double dblYTemp = 0; double dblXFactor = dblXOffset; double dblYFactor = dblYOffset; do { x1 = pRow.get_Value(pRow.Fields.FindField(xValue)).ToString(); if (x1.Length > 0) { if (x1 == x2) { y = pRow.get_Value(pRow.Fields.FindField(yValue)).ToString(); dblXTemp = (Double.Parse(x1)) + dblXFactor; dblYTemp = (Double.Parse(y)) + dblYFactor; pRow.set_Value(pRow.Fields.FindField(xValue), dblXTemp.ToString()); pRow.set_Value(pRow.Fields.FindField(yValue), dblYTemp.ToString()); pRow.Store(); dblXFactor += dblXOffset; dblYFactor += dblYOffset; } else { dblXFactor = dblXOffset; dblYFactor = dblYOffset; } } x2 = x1; pRow = pCursor.NextRow(); }while (pRow != null); pCursor.Flush(); }
public void PopulateComboboxContents() { // Clear the combobox first Clear(); // Get a reference to the Data Sources Table ITable dataSourcesTable = commonFunctions.OpenTable(m_EditWorkspace, "DataSources"); // Get all the Data Sources into a cursor, sorted alphabetically ITableSort dsSorter = new TableSortClass(); dsSorter.Table = dataSourcesTable; dsSorter.QueryFilter = null; dsSorter.Fields = "Source"; dsSorter.set_Ascending("Source", true); // Seem to have trouble sorting. I suspect it has to do with this being a >255 char m_identifier? Should Source be > 255?? dsSorter.Sort(null); ICursor sortedSources = dsSorter.Rows; //ICursor sortedSources = dataSourcesTable.Search(null, false); // Iterate through the returned, sorted rows. Add each one to the DataTable IRow aSource = sortedSources.NextRow(); while (aSource != null) { Add(aSource.get_Value(dataSourcesTable.FindField("Source")).ToString(), aSource.get_Value(dataSourcesTable.FindField("DataSources_ID")).ToString()); aSource = sortedSources.NextRow(); } System.Runtime.InteropServices.Marshal.ReleaseComObject(sortedSources); }
public void PopulateComboboxContents() { // Clear the combobox first Clear(); // Get a reference to the Data Sources Table ITable dataSourcesTable = commonFunctions.OpenTable(m_EditWorkspace, "DataSources"); // Get all the Data Sources into a cursor, sorted alphabetically ITableSort dsSorter = new TableSortClass(); dsSorter.Table = dataSourcesTable; dsSorter.QueryFilter = null; dsSorter.Fields = "Source"; dsSorter.set_Ascending("Source", true); // Seem to have trouble sorting. I suspect it has to do with this being a >255 char m_identifier? Should Source be > 255?? dsSorter.Sort(null); ICursor sortedSources = dsSorter.Rows; //ICursor sortedSources = dataSourcesTable.Search(null, false); // Iterate through the returned, sorted rows. Add each one to the DataTable IRow aSource = sortedSources.NextRow(); while (aSource != null) { Add(aSource.get_Value(dataSourcesTable.FindField("Source")).ToString(), aSource.get_Value(dataSourcesTable.FindField("DataSources_ID")).ToString()); aSource = sortedSources.NextRow(); } System.Runtime.InteropServices.Marshal.ReleaseComObject(sortedSources); }
/// <summary> /// 查找要素 /// </summary> /// <param name="layer">图层</param> /// <param name="fieldName">字段</param> /// <param name="attributeValue">查询条件</param> /// <returns>查询结果(图层名称,几何图形,属性信息)</returns> public List <Tuple <IFeature, IGeometry, Dictionary <string, string> > > SearchFeaturesByGeoAndText(ILayer layer, Dictionary <string, string> fldvals) { IFeatureLayer featureLayer = (IFeatureLayer)layer; IFeatureClass feaclass = featureLayer.FeatureClass; if (feaclass == null) { Log.Error("[GIS]....The FeatureClass of the Feature layer " + featureLayer.Name + " is null, please check the geodatabase if the feature layer exists."); return(null); } var featureList = new List <Tuple <IFeature, IGeometry, Dictionary <string, string> > >(); var filter0 = new QueryFilterClass(); IFields flds = feaclass.Fields; string sql = CreateSqlexpression(flds, fldvals); filter0.WhereClause = sql; IFeatureCursor featureCursor = feaclass.Search(filter0, false); if (feaclass.Fields.FindField(GIS.GIS_Const.FIELD_XH) != -1) { ITableSort tableSort = new TableSortClass(); tableSort.Table = featureLayer.FeatureClass as ITable; tableSort.QueryFilter = filter0; //tableSort.Fields = GIS.GIS_Const.FIELD_XH; //tableSort.set_Ascending(GIS.GIS_Const.FIELD_XH, false); tableSort.Fields = GIS.GIS_Const.FIELD_OBJECTID; tableSort.set_Ascending(GIS.GIS_Const.FIELD_OBJECTID, false); tableSort.Sort(null); featureCursor = tableSort.Rows as IFeatureCursor; } if (featureCursor != null) { var feature = featureCursor.NextFeature(); IGeometry featureGeometry = null; while (feature != null) { var fieldDict = new Dictionary <string, string>(); for (int i = 0; i < feature.Fields.FieldCount; i++) { var field = feature.Fields.Field[i]; if (field.Type != esriFieldType.esriFieldTypeGeometry) { fieldDict.Add(field.Name, feature.Value[i].ToString()); } else { featureGeometry = feature.Shape; } } var featureTuple = new Tuple <IFeature, IGeometry, Dictionary <string, string> >(feature, featureGeometry, fieldDict); featureList.Add(featureTuple); feature = featureCursor.NextFeature(); } } return(featureList); }
private static void UpdateCodedValueDomain(IWorkspace theWorkspace, string DomainName, string SourceClassName, string CodeFieldName, string ValueFieldName) { // Get reference to the table to read codes and values from ITable theTable = commonFunctions.OpenTable(theWorkspace, SourceClassName); // Get reference to the domain itself IWorkspaceDomains wsDomains = (IWorkspaceDomains)theWorkspace; ICodedValueDomain theDomain = (ICodedValueDomain)wsDomains.get_DomainByName(DomainName); // Requires exclusive schema lock ISchemaLock schemaLock = (ISchemaLock)theDomain; try { // Get an exclusive lock schemaLock.ChangeSchemaLock(esriSchemaLock.esriExclusiveSchemaLock); // Clear everything out of the domain first int codedValues = theDomain.CodeCount; for (int i = 0; i <= codedValues - 1; i++) { theDomain.DeleteCode(theDomain.Value[0]); } // Sort the table ITableSort tableSorter = new TableSortClass(); tableSorter.Fields = ValueFieldName; tableSorter.set_Ascending(ValueFieldName, true); tableSorter.Table = theTable; tableSorter.Sort(null); // Loop through the sorted rows, add to the domain int codeFld = theTable.FindField(CodeFieldName); int valueFld = theTable.FindField(ValueFieldName); ICursor theCursor = tableSorter.Rows; IRow theRow = theCursor.NextRow(); while (theRow != null) { theDomain.AddCode(theRow.get_Value(codeFld), theRow.get_Value(valueFld).ToString()); theRow = theCursor.NextRow(); } } catch (Exception e) { MessageBox.Show(DomainName + " was not updated. This is likely because an exclusive schema lock could not be obtained.", "NCGMP Tools"); } finally { // Release the exclusive lock, if it was acquired. // This block of code (finally) is called whether or not there is a problem schemaLock.ChangeSchemaLock(esriSchemaLock.esriSharedSchemaLock); } }
private static void UpdateCodedValueDomain(IWorkspace theWorkspace, string DomainName, string SourceClassName, string CodeFieldName, string ValueFieldName) { // Get reference to the table to read codes and values from ITable theTable = commonFunctions.OpenTable(theWorkspace, SourceClassName); // Get reference to the domain itself IWorkspaceDomains wsDomains = (IWorkspaceDomains)theWorkspace; ICodedValueDomain theDomain = (ICodedValueDomain)wsDomains.get_DomainByName(DomainName); // Requires exclusive schema lock ISchemaLock schemaLock = (ISchemaLock)theDomain; try { // Get an exclusive lock schemaLock.ChangeSchemaLock(esriSchemaLock.esriExclusiveSchemaLock); // Clear everything out of the domain first int codedValues = theDomain.CodeCount; for (int i = 0; i <= codedValues - 1; i++) { theDomain.DeleteCode(theDomain.Value[0]); } // Sort the table ITableSort tableSorter = new TableSortClass(); tableSorter.Fields = ValueFieldName; tableSorter.set_Ascending(ValueFieldName, true); tableSorter.Table = theTable; tableSorter.Sort(null); // Loop through the sorted rows, add to the domain int codeFld = theTable.FindField(CodeFieldName); int valueFld = theTable.FindField(ValueFieldName); ICursor theCursor = tableSorter.Rows; IRow theRow = theCursor.NextRow(); while (theRow != null) { theDomain.AddCode(theRow.get_Value(codeFld), theRow.get_Value(valueFld).ToString()); theRow = theCursor.NextRow(); } } catch (Exception e) { MessageBox.Show(DomainName + " was not updated. This is likely because an exclusive schema lock could not be obtained.", "NCGMP Tools"); } finally { // Release the exclusive lock, if it was acquired. // This block of code (finally) is called whether or not there is a problem schemaLock.ChangeSchemaLock(esriSchemaLock.esriSharedSchemaLock); } }
/// <summary> /// 数据排序 /// </summary> /// <param name="pFeatureClass"></param> private void SortFeatures(IFeatureClass pFeatureClass) { ITableSort pTableSort = new TableSortClass(); IFields pFields = pFeatureClass.Fields; IField pField = pFields.get_Field(col_index); pTableSort.Fields = pField.Name; pTableSort.set_Ascending(pField.Name, up); pTableSort.set_CaseSensitive(pField.Name, true); pTableSort.Table = pFeatureClass as ITable; pTableSort.Sort(null); pFCuror = (IFeatureCursor)pTableSort.Rows; pTs = pTableSort; RefreshDataGridViewDataSource(gdvAttribute, GetAttributeTable(pFClass, pFCuror)); }
/// <summary> /// 获得当前字段的唯一值 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void buttonGetValue_Click(object sender, EventArgs e) { try { if (this.listBoxFields.SelectedIndex == -1) return; string currentFieldName = this.listBoxFields.Text;//当前字段名 string currentLayerName=this.comboBoxLayers.Text; this.pEnumLayer.Reset(); for (this.pLayer = this.pEnumLayer.Next(); this.pLayer != null; this.pLayer = this.pEnumLayer.Next()) { if (this.pLayer.Name == currentLayerName) break; } this.pLayerFields = this.pLayer as ILayerFields; IField pField = this.pLayerFields.get_Field(this.pLayerFields.FindField(currentFieldName)); esriFieldType pFieldType = pField.Type; //对Table中当前字段进行排序,把结果赋给Cursor ITable pTable = this.pLayer as ITable; ITableSort pTableSort = new TableSortClass(); pTableSort.Table = pTable; pTableSort.Fields = currentFieldName; pTableSort.set_Ascending(currentFieldName, true); pTableSort.set_CaseSensitive(currentFieldName, true); pTableSort.Sort(null);//排序 ICursor pCursor = pTableSort.Rows; //字段统计 IDataStatistics pDataStatistics = new DataStatisticsClass(); pDataStatistics.Cursor = pCursor; pDataStatistics.Field = currentFieldName; System.Collections.IEnumerator pEnumeratorUniqueValues = pDataStatistics.UniqueValues;//唯一值枚举 int uniqueValueCount = pDataStatistics.UniqueValueCount;//唯一值的个数 this.listBoxValues.Items.Clear(); string currentValue = null; pEnumeratorUniqueValues.Reset(); if (pFieldType == esriFieldType.esriFieldTypeString) { while (pEnumeratorUniqueValues.MoveNext()) { currentValue = pEnumeratorUniqueValues.Current.ToString(); this.listBoxValues.Items.Add("'" + currentValue + "'"); } } else { while (pEnumeratorUniqueValues.MoveNext()) { currentValue = pEnumeratorUniqueValues.Current.ToString(); this.listBoxValues.Items.Add(currentValue); } } } catch (Exception ex) { MessageBox.Show(ex.Message); } }
/// <summary> /// 数据排序 /// </summary> /// <param name="pFeatureClass"></param> private void SortFeatures(IFeatureClass pFeatureClass) { ITableSort pTableSort = new TableSortClass(); IFields pFields = pFeatureClass.Fields; IField pField = pFields.get_Field(col_index); pTableSort.Fields = pField.Name; pTableSort.set_Ascending(pField.Name, up); pTableSort.set_CaseSensitive(pField.Name, true); pTableSort.Table = pFeatureClass as ITable; pTableSort.Sort(null); pFCuror = (IFeatureCursor)pTableSort.Rows; pTs = pTableSort; RefreshDataGridViewDataSource(gdvAttribute, GetAttributeTable(pFClass, pFCuror)); }
private void FeatureSort() { IFeatureSelection featureSel = featurelayer as IFeatureSelection; featureSel.SelectFeatures(null, esriSelectionResultEnum.esriSelectionResultNew, false); ISelectionSet selectionSet = featureSel.SelectionSet; //新建TableSort对象 ITableSort pTableSort = new TableSortClass(); //进行排序的字段,排序方法, //只选一个字段排序 if (cbxSecField.Text == "" && cbxThirdField.Text == "") { pTableSort.Fields = cbxFirstField.Text; if (checkBox1.Checked == true) { pTableSort.set_Ascending(cbxFirstField.Text, true); } } //根据三个字段排序 if (cbxFirstField.Text != "" && cbxThirdField.Text != "") { pTableSort.Fields = cbxThirdField.Text + "," + cbxSecField.Text + "," + cbxThirdField.Text; if (checkBox1.Checked == true) { pTableSort.set_Ascending(cbxFirstField.Text, true); } else { pTableSort.set_Ascending(cbxFirstField.Text, false); } if (checkBox2.Checked == true) { pTableSort.set_Ascending(cbxSecField.Text, true); } else { pTableSort.set_Ascending(cbxSecField.Text, false); } if (checkBox3.Checked == true) { pTableSort.set_Ascending(cbxSecField.Text, true); } else { pTableSort.set_Ascending(cbxThirdField.Text, false); } } //根据两个字段排序 if (cbxSecField.Text != "" && cbxThirdField.Text == "") { pTableSort.Fields = cbxFirstField.Text + "," + cbxSecField.Text; if (checkBox1.Checked == true) { pTableSort.set_Ascending(cbxFirstField.Text, true); } else { pTableSort.set_Ascending(cbxFirstField.Text, false); } if (checkBox2.Checked == true) { pTableSort.set_Ascending(cbxSecField.Text, true); } else { pTableSort.set_Ascending(cbxSecField.Text, false); } } //设置排序的数据源 pTableSort.SelectionSet = selectionSet; pTableSort.Sort(null); IFeatureCursor featureCursor; featureCursor = pTableSort.Rows as IFeatureCursor; IFeature feature; feature = featureCursor.NextFeature(); //选取要素 m_map.ClearSelection(); int i = Convert.ToInt32(comboBox1.Text); int j = 0; while (feature != null) { j++; if (j <= i) { m_map.SelectFeature(featurelayer as ILayer, feature); feature = featureCursor.NextFeature(); } else { break; } } m_mapcontrol.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGeoSelection, null, null); }
private void btnShowAllValue_Click(object sender, EventArgs e) { if (cmbFields.Text=="") { MessageBox.Show("��ѡ���ֶ���", "��ʾ", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } listBoxValue.Items.Clear(); IFeatureLayer pFeatureLayer; pFeatureLayer = (IFeatureLayer)pMap.get_Layer(iLayerIndex); IFeatureCursor pFeatureCursor; pFeatureCursor = pFeatureLayer.FeatureClass.Search(null, false); IFeature pFeature; pFeature = pFeatureCursor.NextFeature(); //��Table�е�ǰ�ֶν�������,�ѽ������Cursor ITable pTable = pFeatureLayer as ITable; ITableSort pTableSort = new TableSortClass(); pTableSort.Table = pTable; pTableSort.Fields = cmbFields.Text; pTableSort.set_Ascending(cmbFields.Text, true); pTableSort.set_CaseSensitive(cmbFields.Text, true); pTableSort.Sort(null); ICursor pCursor = pTableSort.Rows; //��ֵͳ�� IDataStatistics pData = new DataStatisticsClass(); pData.Cursor = pCursor; pData.Field = cmbFields.Text; System.Collections.IEnumerator pEnumeratorUniqueValues = pData.UniqueValues;//Ψһֵö�� int uniqueValueCount = pData.UniqueValueCount;//Ψһֵ�ĸ��� this.listBoxValue.Items.Clear(); string fldValue = null; pEnumeratorUniqueValues.Reset(); ILayerFields pFields = pFeatureLayer as ILayerFields; if (pFields.get_Field(pFields.FindField(cmbFields.Text)).Type == esriFieldType.esriFieldTypeString) { while (pEnumeratorUniqueValues.MoveNext()) { fldValue = pEnumeratorUniqueValues.Current.ToString(); this.listBoxValue.Items.Add("'" + fldValue + "'"); } } else if(cmbFields .Text =="shape" ) { fldValue = Convert.ToString(pFeature.Shape.GeometryType); this.listBoxValue.Items.Add(fldValue); } else { while (pEnumeratorUniqueValues.MoveNext()) { fldValue = pEnumeratorUniqueValues.Current.ToString(); this.listBoxValue.Items.Add(fldValue); } } /* while(pFeature!=null) { string fldValue; if (cmbFields.Text == "Shape") { fldValue = Convert.ToString(pFeature.Shape.GeometryType); } else fldValue = Convert.ToString(pFeature.get_Value(iFieldIndex)); listBoxValue.Items.Add(fldValue); pFeature = pFeatureCursor.NextFeature(); } */ }
private void CreateDailyProfilesTable(ITable inputHSPRTable, string outputFileGdbPath, double fgdbVersion) { // Find the needed fields on the input HSPR table int profileIDField = inputHSPRTable.FindField("PROFILE_ID"); int relSpField = inputHSPRTable.FindField("REL_SP"); // Create the Profiles table in the output file geodatabase and open an InsertCursor on it Type factoryType = Type.GetTypeFromProgID("esriDataSourcesGDB.FileGDBWorkspaceFactory"); var gdbWSF = Activator.CreateInstance(factoryType) as IWorkspaceFactory; var gdbFWS = gdbWSF.OpenFromFile(outputFileGdbPath, 0) as IFeatureWorkspace; var ocd = new ObjectClassDescriptionClass() as IObjectClassDescription; var tableFields = ocd.RequiredFields as IFieldsEdit; var newField = new FieldClass() as IFieldEdit; newField.Name_2 = "ProfileID"; newField.Type_2 = esriFieldType.esriFieldTypeSmallInteger; tableFields.AddField(newField as IField); for (int i = 0; i < 288; i++) { newField = new FieldClass(); newField.Type_2 = esriFieldType.esriFieldTypeSingle; newField.Name_2 = ((fgdbVersion == 10.0) ? "TimeFactor_" : "SpeedFactor_") + String.Format("{0:00}", i / 12) + String.Format("{0:00}", (i % 12) * 5); tableFields.AddField(newField as IField); } ITable newTable = gdbFWS.CreateTable(ProfilesTableName, tableFields as IFields, ocd.InstanceCLSID, ocd.ClassExtensionCLSID, ""); int newTableProfileIDField = newTable.FindField("ProfileID"); IRowBuffer buff = newTable.CreateRowBuffer(); ICursor insertCursor = newTable.Insert(true); // Loop through the HSPR table and populate the newly-created Profiles table ITableSort ts = new TableSortClass(); ts.Table = inputHSPRTable; ts.Fields = "PROFILE_ID, TIME_SLOT"; ts.set_Ascending("PROFILE_ID", true); ts.set_Ascending("TIME_SLOT", true); ts.Sort(null); ICursor cur = ts.Rows; IRow r = cur.NextRow(); while (r != null) { buff.set_Value(newTableProfileIDField, r.get_Value(profileIDField)); for (int i = 1; i <= 288; i++) { buff.set_Value(newTableProfileIDField + i, (fgdbVersion == 10.0) ? (100 / (float)(r.get_Value(relSpField))) : ((float)(r.get_Value(relSpField)) / 100)); r = cur.NextRow(); } insertCursor.InsertRow(buff); } // Flush any outstanding writes to the table insertCursor.Flush(); }
/// <summary> /// Creates voyage tracks based on chunks of time. The time interval is provided by the user. /// </summary> /// <param name="pFL"></param> /// <param name="pVoyageTable"></param> /// <param name="pNewFC"></param> /// <param name="iUserTime"></param> /// <param name="iUserUnits"></param> private void CreateUserTimeChunkTracks(IFeatureLayer pFL, ITable pVoyageTable, IFeatureClass pNewFC, int iUserTime, int iUserUnits) { ITable pTable = (ITable)pFL; ICursor pCursor = pTable.Search(null, false); IDataStatistics pDS = new DataStatisticsClass(); pDS.Field = "MMSI"; pDS.Cursor = pCursor; IEnumerator pEnum = pDS.UniqueValues; IFeatureCursor pInsertCursor = pNewFC.Insert(false); IFeatureBuffer myFeatureBuffer = pNewFC.CreateFeatureBuffer(); ISpatialReference pSR = CreateGeographicSR(); int iNewVoyageID = pNewFC.Fields.FindField("VoyageID"); int iVoyageID = pVoyageTable.Fields.FindField("VoyageID"); int iNewDestinationID = pNewFC.Fields.FindField("Destination"); int iDestinationID = pVoyageTable.Fields.FindField("Destination"); int iNewCargoID = pNewFC.Fields.FindField("Cargo"); int iCargoID = pVoyageTable.Fields.FindField("Cargo"); int iNewDraughtID = pNewFC.Fields.FindField("Draught"); int iDraughtID = pVoyageTable.Fields.FindField("Draught"); int iNewETAID = pNewFC.Fields.FindField("ETA"); int iETAID = pVoyageTable.Fields.FindField("ETA"); int iNewStartTimeID = pNewFC.Fields.FindField("StartTime"); int iStartTimeID = pVoyageTable.Fields.FindField("StartTime"); int iNewEndTimeID = pNewFC.Fields.FindField("EndTime"); int iEndTimeID = pVoyageTable.Fields.FindField("EndTime"); int iNewMMSIID = pNewFC.Fields.FindField("MMSI"); int iMMSIID = pVoyageTable.Fields.FindField("MMSI"); object missing = Type.Missing; while (pEnum.MoveNext()) { IQueryFilter pQF = new QueryFilterClass(); pQF.WhereClause = "MMSI = " + pEnum.Current.ToString(); IFeatureCursor pFeatureCursor = pFL.FeatureClass.Search(pQF, false); ITableSort pTableSort = new TableSortClass(); pTableSort.Table = (ITable)pFL; pTableSort.Cursor = (ICursor)pFeatureCursor; pTableSort.Fields = "BaseDateTime"; pTableSort.set_Ascending("BaseDateTime", true); pTableSort.Sort(null); ICursor pSortedCursor = pTableSort.Rows; IRow pRow = pSortedCursor.NextRow(); bool bCreateNewFeature = true; DateTime currDate = new DateTime(1900, 1, 1); DateTime endDate = currDate; IPointCollection myCollection = null; IPolyline5 myPolyline = null; while (pRow != null) { if (pRow is IFeature) { currDate = (DateTime)pRow.get_Value(pRow.Fields.FindField("BaseDateTime")); if (bCreateNewFeature) { myCollection = new PolylineClass(); switch (iUserUnits) { case 0: //seconds endDate = currDate.AddSeconds(m_iUserTime); break; case 1: //minutes endDate = currDate.AddMinutes(m_iUserTime); break; case 2: //hours endDate = currDate.AddHours(m_iUserTime); break; case 3: //days endDate = currDate.AddDays(m_iUserTime); break; case 4: //months endDate = currDate.AddMonths(m_iUserTime); break; case 5: //years endDate = currDate.AddYears(m_iUserTime); break; } bCreateNewFeature = false; } if (currDate < endDate) { IFeature pFeature = (IFeature)pRow; IPoint myPoint = (IPoint)pFeature.Shape; myCollection.AddPoint(myPoint, ref missing, ref missing); pRow = pSortedCursor.NextRow(); } else { myPolyline = (IPolyline5)myCollection; myPolyline.SpatialReference = pSR; myFeatureBuffer.Shape = (IGeometry)myPolyline; IQueryFilter pVoyageQF = new QueryFilterClass(); pQF.WhereClause = "VoyageID = " + pRow.get_Value(pRow.Fields.FindField("VoyageID")); ICursor pVoyageCursor = pVoyageTable.Search(pQF, true); IRow pVoyageRow = pVoyageCursor.NextRow(); if (pVoyageRow != null) { myFeatureBuffer.set_Value(iNewVoyageID, pVoyageRow.get_Value(iVoyageID)); myFeatureBuffer.set_Value(iNewDestinationID, pVoyageRow.get_Value(iDestinationID)); myFeatureBuffer.set_Value(iNewCargoID, pVoyageRow.get_Value(iCargoID)); myFeatureBuffer.set_Value(iNewDraughtID, pVoyageRow.get_Value(iDraughtID)); myFeatureBuffer.set_Value(iNewETAID, pVoyageRow.get_Value(iETAID)); myFeatureBuffer.set_Value(iNewStartTimeID, pVoyageRow.get_Value(iStartTimeID)); myFeatureBuffer.set_Value(iNewEndTimeID, pVoyageRow.get_Value(iEndTimeID)); myFeatureBuffer.set_Value(iNewMMSIID, pVoyageRow.get_Value(iMMSIID)); } else { myFeatureBuffer.set_Value(iNewVoyageID, 0); myFeatureBuffer.set_Value(iNewDestinationID, ""); myFeatureBuffer.set_Value(iNewCargoID, 0); myFeatureBuffer.set_Value(iNewDraughtID, 0); myFeatureBuffer.set_Value(iNewETAID, 0); myFeatureBuffer.set_Value(iNewStartTimeID, 0); myFeatureBuffer.set_Value(iNewEndTimeID, 0); myFeatureBuffer.set_Value(iNewMMSIID, 0); } pInsertCursor.InsertFeature(myFeatureBuffer); bCreateNewFeature = true; } } } myPolyline = (IPolyline5)myCollection; myPolyline.SpatialReference = pSR; myFeatureBuffer.Shape = (IGeometry)myPolyline; pInsertCursor.InsertFeature(myFeatureBuffer); } pInsertCursor.Flush(); }
public List<GisDataAdapter> GetRowsPorQuery(string tableName, string whereClause, string orderingFields) { IFeatureWorkspace featureWorkspace = (IFeatureWorkspace)ws; ITable table = featureWorkspace.OpenTable(tableName); ITableSort tableSort = new TableSortClass(); tableSort.Table = table; tableSort.Fields = orderingFields; tableSort.set_Ascending(orderingFields, true); ICursor cursor; IRow row; List<GisDataAdapter> adapters = new List<GisDataAdapter>(); if (string.IsNullOrEmpty(whereClause)) { tableSort.Sort(null); cursor = tableSort.Rows; } else { IQueryFilter queryFilter = new QueryFilterClass(); queryFilter.WhereClause = whereClause; tableSort.QueryFilter = queryFilter; tableSort.Sort(null); cursor = tableSort.Rows; } while ((row = cursor.NextRow()) != null) { adapters.Add(new GisDataAdapter((IObject)row)); } return adapters; }
private void btnShowAllValue_Click(object sender, EventArgs e) { if (cmbFields.Text == "") { MessageBox.Show("请选择字段名", "提示", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } listBoxValue.Items.Clear(); IFeatureLayer pFeatureLayer; pFeatureLayer = (IFeatureLayer)pMap.get_Layer(iLayerIndex); IFeatureCursor pFeatureCursor; pFeatureCursor = pFeatureLayer.FeatureClass.Search(null, false); IFeature pFeature; pFeature = pFeatureCursor.NextFeature(); //对Table中当前字段进行排序,把结果赋给Cursor ITable pTable = pFeatureLayer as ITable; ITableSort pTableSort = new TableSortClass(); pTableSort.Table = pTable; pTableSort.Fields = cmbFields.Text; pTableSort.set_Ascending(cmbFields.Text, true); pTableSort.set_CaseSensitive(cmbFields.Text, true); pTableSort.Sort(null); ICursor pCursor = pTableSort.Rows; //数值统计 IDataStatistics pData = new DataStatisticsClass(); pData.Cursor = pCursor; pData.Field = cmbFields.Text; System.Collections.IEnumerator pEnumeratorUniqueValues = pData.UniqueValues; //唯一值枚举 int uniqueValueCount = pData.UniqueValueCount; //唯一值的个数 this.listBoxValue.Items.Clear(); string fldValue = null; pEnumeratorUniqueValues.Reset(); ILayerFields pFields = pFeatureLayer as ILayerFields; if (pFields.get_Field(pFields.FindField(cmbFields.Text)).Type == esriFieldType.esriFieldTypeString) { while (pEnumeratorUniqueValues.MoveNext()) { fldValue = pEnumeratorUniqueValues.Current.ToString(); this.listBoxValue.Items.Add("'" + fldValue + "'"); } } else if (cmbFields.Text == "shape") { fldValue = Convert.ToString(pFeature.Shape.GeometryType); this.listBoxValue.Items.Add(fldValue); } else { while (pEnumeratorUniqueValues.MoveNext()) { fldValue = pEnumeratorUniqueValues.Current.ToString(); this.listBoxValue.Items.Add(fldValue); } } /* while(pFeature!=null) * { * string fldValue; * if (cmbFields.Text == "Shape") * { * fldValue = Convert.ToString(pFeature.Shape.GeometryType); * } * else * fldValue = Convert.ToString(pFeature.get_Value(iFieldIndex)); * * listBoxValue.Items.Add(fldValue); * pFeature = pFeatureCursor.NextFeature(); * } */ }
private void CreateAndPopulateTurnFeatureClass(string outputFileGdbPath, string fdsName, string ProhibMPTableName, string tempStatsTableName, IGPMessages messages, ITrackCancel trackcancel) { // Determine the number of AltID fields we need (the same as the MAX_SEQNR value). Type factoryType = Type.GetTypeFromProgID("esriDataSourcesGDB.FileGDBWorkspaceFactory"); var wsf = Activator.CreateInstance(factoryType) as IWorkspaceFactory; var fws = wsf.OpenFromFile(outputFileGdbPath, 0) as IFeatureWorkspace; ITable tempStatsTable = fws.OpenTable(tempStatsTableName); short numAltIDFields = 2; if (tempStatsTable.RowCount(null) == 1) numAltIDFields = (short)((double)(tempStatsTable.GetRow(1).get_Value(tempStatsTable.FindField("MAX_SEQNR")))); // Open the MP table and find the fields we need ITable mpTable = fws.OpenTable(ProhibMPTableName); int seqNrField = mpTable.FindField("SEQNR"); int trpElIDField = mpTable.FindField("TRPELID"); int idFieldOnMP = mpTable.FindField("ID"); int mpJnctIDField = mpTable.FindField("JNCTID"); // Create a temporary template feature class var fcd = new FeatureClassDescriptionClass() as IFeatureClassDescription; var ocd = fcd as IObjectClassDescription; var fieldsEdit = ocd.RequiredFields as IFieldsEdit; IField fieldOnMPTable = mpTable.Fields.get_Field(idFieldOnMP); // use the ID field as a template for the AltID fields for (short i = 1; i <= numAltIDFields; i++) { IFieldEdit newField = new FieldClass(); newField.Name_2 = "AltID" + i; newField.Precision_2 = fieldOnMPTable.Precision; newField.Scale_2 = fieldOnMPTable.Scale; newField.Type_2 = fieldOnMPTable.Type; fieldsEdit.AddField(newField as IField); } fieldsEdit.AddField(fieldOnMPTable); fieldOnMPTable = mpTable.Fields.get_Field(mpJnctIDField); fieldsEdit.AddField(fieldOnMPTable); var fieldChk = new FieldCheckerClass() as IFieldChecker; IEnumFieldError enumFieldErr = null; IFields validatedFields = null; fieldChk.ValidateWorkspace = fws as IWorkspace; fieldChk.Validate(fieldsEdit as IFields, out enumFieldErr, out validatedFields); var tempFC = fws.CreateFeatureClass("TheTemplate", validatedFields, ocd.InstanceCLSID, ocd.ClassExtensionCLSID, esriFeatureType.esriFTSimple, fcd.ShapeFieldName, "") as IDataset; // Create the turn feature class from the template, then delete the template Geoprocessor gp = new Geoprocessor(); CreateTurnFeatureClass createTurnFCTool = new CreateTurnFeatureClass(); string pathToFds = outputFileGdbPath + "\\" + fdsName; createTurnFCTool.out_location = pathToFds; createTurnFCTool.out_feature_class_name = TurnFCName; createTurnFCTool.maximum_edges = numAltIDFields; createTurnFCTool.in_template_feature_class = outputFileGdbPath + "\\TheTemplate"; gp.Execute(createTurnFCTool, trackcancel); tempFC.Delete(); // Open the new turn feature class and find all the fields on it IFeatureClass turnFC = fws.OpenFeatureClass(TurnFCName); int[] altIDFields = new int[numAltIDFields]; int[] edgeFCIDFields = new int[numAltIDFields]; int[] edgeFIDFields = new int[numAltIDFields]; int[] edgePosFields = new int[numAltIDFields]; for (short i = 0; i < numAltIDFields; i++) { altIDFields[i] = turnFC.FindField("AltID" + (i + 1)); edgeFCIDFields[i] = turnFC.FindField("Edge" + (i + 1) + "FCID"); edgeFIDFields[i] = turnFC.FindField("Edge" + (i + 1) + "FID"); edgePosFields[i] = turnFC.FindField("Edge" + (i + 1) + "Pos"); } int edge1endField = turnFC.FindField("Edge1End"); int idFieldOnTurnFC = turnFC.FindField("ID"); int turnFCJnctIDField = turnFC.FindField("JNCTID"); // Look up the FCID of the Streets feature class IFeatureClass streetsFC = fws.OpenFeatureClass(StreetsFCName); int streetsFCID = streetsFC.FeatureClassID; // Set up queries var ts = new TableSortClass() as ITableSort; ts.Fields = "ID, SEQNR"; ts.set_Ascending("ID", true); ts.set_Ascending("SEQNR", true); ts.QueryFilter = new QueryFilterClass(); ts.Table = mpTable; ts.Sort(null); ICursor mpCursor = ts.Rows; IFeatureCursor turnFCCursor = turnFC.Insert(true); IFeatureBuffer turnBuffer = turnFC.CreateFeatureBuffer(); // Write the field values to the turn feature class accordingly turnBuffer.set_Value(edge1endField, "?"); // dummy value; will be updated in a later calculation int numFeatures = 0; IRow mpRow = mpCursor.NextRow(); while (mpRow != null) { // Transfer the non-edge identifying field values to the buffer turnBuffer.set_Value(idFieldOnTurnFC, mpRow.get_Value(idFieldOnMP)); turnBuffer.set_Value(turnFCJnctIDField, mpRow.get_Value(mpJnctIDField)); // Write the AltID values to the buffer int seq = (int)(mpRow.get_Value(seqNrField)); int lastEntry; do { lastEntry = seq; turnBuffer.set_Value(altIDFields[lastEntry - 1], mpRow.get_Value(trpElIDField)); mpRow = mpCursor.NextRow(); if (mpRow == null) break; seq = (int)(mpRow.get_Value(seqNrField)); } while (seq != 1); // Zero-out the unused fields for (int i = lastEntry; i < numAltIDFields; i++) turnBuffer.set_Value(altIDFields[i], 0); // Write the FCID and Pos field values to the buffer for (short i = 0; i < numAltIDFields; i++) { double altID = (double)(turnBuffer.get_Value(altIDFields[i])); if (altID != 0) { turnBuffer.set_Value(edgeFCIDFields[i], streetsFCID); turnBuffer.set_Value(edgeFIDFields[i], 1); turnBuffer.set_Value(edgePosFields[i], 0.5); } else { turnBuffer.set_Value(edgeFCIDFields[i], 0); turnBuffer.set_Value(edgeFIDFields[i], 0); turnBuffer.set_Value(edgePosFields[i], 0); } } // Create the turn feature turnFCCursor.InsertFeature(turnBuffer); numFeatures++; if ((numFeatures % 100) == 0) { // check for user cancel if (trackcancel != null && !trackcancel.Continue()) throw (new COMException("Function cancelled.")); } } // Flush any outstanding writes to the turn feature class turnFCCursor.Flush(); // Update the Edge1End values AddMessage("Updating the Edge1End values...", messages, trackcancel); MakeFeatureLayer makeFeatureLayerTool = new MakeFeatureLayer(); makeFeatureLayerTool.in_features = pathToFds + "\\" + TurnFCName; makeFeatureLayerTool.out_layer = "Turn_Layer"; gp.Execute(makeFeatureLayerTool, trackcancel); AddJoin addJoinTool = new AddJoin(); addJoinTool.in_layer_or_view = "Turn_Layer"; addJoinTool.in_field = "AltID1"; addJoinTool.join_table = pathToFds + "\\" + StreetsFCName; addJoinTool.join_field = "ID"; gp.Execute(addJoinTool, trackcancel); CalculateField calcFieldTool = new CalculateField(); calcFieldTool.in_table = "Turn_Layer"; calcFieldTool.field = TurnFCName + ".Edge1End"; calcFieldTool.expression = "x"; calcFieldTool.code_block = "Select Case [" + TurnFCName + ".JNCTID]\n Case [" + StreetsFCName + ".F_JNCTID]: x = \"N\"\n Case [" + StreetsFCName + ".T_JNCTID]: x = \"Y\"\n Case Else: x = \"?\"\nEnd Select"; calcFieldTool.expression_type = "VB"; gp.Execute(calcFieldTool, trackcancel); RemoveJoin removeJoinTool = new RemoveJoin(); removeJoinTool.in_layer_or_view = "Turn_Layer"; removeJoinTool.join_name = StreetsFCName; gp.Execute(removeJoinTool, trackcancel); Delete deleteTool = new Delete(); deleteTool.in_data = "Turn_Layer"; gp.Execute(deleteTool, trackcancel); AddMessage("Updating the EdgeFID values...", messages, trackcancel); // Create a temporary network dataset for updating the EdgeFID values IDENetworkDataset dends = new DENetworkDatasetClass(); dends.SupportsTurns = true; dends.Buildable = true; (dends as IDataElement).Name = StreetsFCName; (dends as IDEGeoDataset).SpatialReference = (streetsFC as IGeoDataset).SpatialReference; IArray sourceArray = new ArrayClass(); var efs = new EdgeFeatureSourceClass() as IEdgeFeatureSource; (efs as INetworkSource).Name = StreetsFCName; efs.UsesSubtypes = false; efs.ClassConnectivityGroup = 1; efs.ClassConnectivityPolicy = esriNetworkEdgeConnectivityPolicy.esriNECPEndVertex; sourceArray.Add(efs); var tfs = new TurnFeatureSourceClass() as INetworkSource; tfs.Name = TurnFCName; sourceArray.Add(tfs); dends.Sources = sourceArray; var fdxc = fws.OpenFeatureDataset(fdsName) as IFeatureDatasetExtensionContainer; var dsCont = fdxc.FindExtension(esriDatasetType.esriDTNetworkDataset) as IDatasetContainer2; var tempNDS = dsCont.CreateDataset(dends as IDEDataset) as IDataset; // Set the EdgeFID field values by running UpdateByAlternateIDFields UpdateByAlternateIDFields updateByAltIDTool = new UpdateByAlternateIDFields(); updateByAltIDTool.in_network_dataset = pathToFds + "\\" + StreetsFCName; updateByAltIDTool.alternate_ID_field_name = "ID"; gp.Execute(updateByAltIDTool, trackcancel); // Delete the temporary network dataset tempNDS.Delete(); // Write the turn geometries TurnGeometryUtilities.WriteTurnGeometry(outputFileGdbPath, StreetsFCName, TurnFCName, numAltIDFields, 0.3, messages, trackcancel); // Index the turn geometries AddMessage("Creating spatial index on the turn feature class...", messages, trackcancel); AddSpatialIndex addSpatialIndexTool = new AddSpatialIndex(); addSpatialIndexTool.in_features = pathToFds + "\\" + TurnFCName; gp.Execute(addSpatialIndexTool, trackcancel); return; }
private void CreateAndPopulateRoadSplitsTable(string outputFileGdbPath, string BifurcationMPTableName, IGPMessages messages, ITrackCancel trackcancel) { // Open the Rdms table and find all the fields we need Type factoryType = Type.GetTypeFromProgID("esriDataSourcesGDB.FileGDBWorkspaceFactory"); var wsf = Activator.CreateInstance(factoryType) as IWorkspaceFactory; var fws = wsf.OpenFromFile(outputFileGdbPath, 0) as IFeatureWorkspace; // Open the MP table and find the fields we need ITable mpTable = fws.OpenTable(BifurcationMPTableName); int seqNrField = mpTable.FindField("SEQNR"); int trpElIDField = mpTable.FindField("TRPELID"); int idFieldOnMP = mpTable.FindField("ID"); int mpJnctIDField = mpTable.FindField("JNCTID"); int FJnctIDField = mpTable.FindField("F_JNCTID"); int TJnctIDField = mpTable.FindField("T_JNCTID"); int StreetsOIDField = mpTable.FindField("StreetsOID"); // Open the Streets feature class and get its feature class ID IFeatureClass inputLineFeatures = fws.OpenFeatureClass(StreetsFCName); int streetsFCID = inputLineFeatures.FeatureClassID; // Define the fields for the RoadSplits table var ocd = new ObjectClassDescriptionClass() as IObjectClassDescription; var fieldsEdit = ocd.RequiredFields as IFieldsEdit; IFieldEdit field; // Add the anchor edge fields to the table field = new FieldClass(); field.Name_2 = "EdgeFCID"; field.Type_2 = esriFieldType.esriFieldTypeInteger; fieldsEdit.AddField(field); field = new FieldClass(); field.Name_2 = "EdgeFID"; field.Type_2 = esriFieldType.esriFieldTypeInteger; fieldsEdit.AddField(field); field = new FieldClass(); field.Name_2 = "EdgeFrmPos"; field.Type_2 = esriFieldType.esriFieldTypeDouble; fieldsEdit.AddField(field); field = new FieldClass(); field.Name_2 = "EdgeToPos"; field.Type_2 = esriFieldType.esriFieldTypeDouble; fieldsEdit.AddField(field); // Add the branch edge fields to the table for (short i = 0; i < 3; i++) { field = new FieldClass(); field.Name_2 = "Branch" + i + "FCID"; field.Type_2 = esriFieldType.esriFieldTypeInteger; fieldsEdit.AddField(field); field = new FieldClass(); field.Name_2 = "Branch" + i + "FID"; field.Type_2 = esriFieldType.esriFieldTypeInteger; fieldsEdit.AddField(field); field = new FieldClass(); field.Name_2 = "Branch" + i + "FrmPos"; field.Type_2 = esriFieldType.esriFieldTypeDouble; fieldsEdit.AddField(field); field = new FieldClass(); field.Name_2 = "Branch" + i + "ToPos"; field.Type_2 = esriFieldType.esriFieldTypeDouble; fieldsEdit.AddField(field); } // Check the fields and create the RoadSplits table var fieldChk = new FieldCheckerClass() as IFieldChecker; IEnumFieldError enumFieldErr = null; IFields validatedFields = null; fieldChk.ValidateWorkspace = fws as IWorkspace; fieldChk.Validate(fieldsEdit as IFields, out enumFieldErr, out validatedFields); var roadSplitsTable = fws.CreateTable(RoadSplitsTableName, validatedFields, ocd.InstanceCLSID, ocd.ClassExtensionCLSID, "") as ITable; // Find all the fields int EdgeFCIDFI = roadSplitsTable.FindField("EdgeFCID"); int EdgeFIDFI = roadSplitsTable.FindField("EdgeFID"); int EdgeFrmPosFI = roadSplitsTable.FindField("EdgeFrmPos"); int EdgeToPosFI = roadSplitsTable.FindField("EdgeToPos"); int Branch0FCIDFI = roadSplitsTable.FindField("Branch0FCID"); int Branch0FIDFI = roadSplitsTable.FindField("Branch0FID"); int Branch0FrmPosFI = roadSplitsTable.FindField("Branch0FrmPos"); int Branch0ToPosFI = roadSplitsTable.FindField("Branch0ToPos"); int Branch1FCIDFI = roadSplitsTable.FindField("Branch1FCID"); int Branch1FIDFI = roadSplitsTable.FindField("Branch1FID"); int Branch1FrmPosFI = roadSplitsTable.FindField("Branch1FrmPos"); int Branch1ToPosFI = roadSplitsTable.FindField("Branch1ToPos"); int Branch2FCIDFI = roadSplitsTable.FindField("Branch2FCID"); int Branch2FIDFI = roadSplitsTable.FindField("Branch2FID"); int Branch2FrmPosFI = roadSplitsTable.FindField("Branch2FrmPos"); int Branch2ToPosFI = roadSplitsTable.FindField("Branch2ToPos"); // Create insert cursor and row buffer for output ICursor tableInsertCursor = roadSplitsTable.Insert(true); IRowBuffer tableBuffer = roadSplitsTable.CreateRowBuffer(); IRow row = tableBuffer as IRow; tableBuffer.set_Value(EdgeFCIDFI, null); tableBuffer.set_Value(EdgeFIDFI, null); tableBuffer.set_Value(EdgeFrmPosFI, null); tableBuffer.set_Value(EdgeToPosFI, null); tableBuffer.set_Value(Branch0FCIDFI, null); tableBuffer.set_Value(Branch0FIDFI, null); tableBuffer.set_Value(Branch0FrmPosFI, null); tableBuffer.set_Value(Branch0ToPosFI, null); tableBuffer.set_Value(Branch1FCIDFI, null); tableBuffer.set_Value(Branch1FIDFI, null); tableBuffer.set_Value(Branch1FrmPosFI, null); tableBuffer.set_Value(Branch1ToPosFI, null); tableBuffer.set_Value(Branch2FCIDFI, null); tableBuffer.set_Value(Branch2FIDFI, null); tableBuffer.set_Value(Branch2FrmPosFI, null); tableBuffer.set_Value(Branch2ToPosFI, null); // Create input cursor for the MP table we are importing ITableSort tableSort = new TableSortClass(); tableSort.Fields = "ID, SEQNR"; tableSort.set_Ascending("ID", true); tableSort.set_Ascending("SEQNR", true); tableSort.QueryFilter = null; tableSort.Table = mpTable; tableSort.Sort(null); ICursor inputCursor = tableSort.Rows; IRow inputTableRow = inputCursor.NextRow(); if (inputTableRow == null) return; // if MP table is empty, there's nothing to do long currentID = Convert.ToInt64(inputTableRow.get_Value(idFieldOnMP)); int streetsOID = Convert.ToInt32(inputTableRow.get_Value(StreetsOIDField)); int seqNr = Convert.ToInt32(inputTableRow.get_Value(seqNrField)); double frmPos = 0.0; double toPos = 1.0; if (seqNr == 1) { if (Convert.ToInt64(inputTableRow.get_Value(mpJnctIDField)) == Convert.ToInt64(inputTableRow.get_Value(FJnctIDField))) { frmPos = 1.0; toPos = 0.0; } } else { if (Convert.ToInt64(inputTableRow.get_Value(mpJnctIDField)) == Convert.ToInt64(inputTableRow.get_Value(TJnctIDField))) { frmPos = 1.0; toPos = 0.0; } } switch (seqNr) { case 1: tableBuffer.set_Value(EdgeFCIDFI, streetsFCID); tableBuffer.set_Value(EdgeFIDFI, streetsOID); tableBuffer.set_Value(EdgeFrmPosFI, frmPos); tableBuffer.set_Value(EdgeToPosFI, toPos); break; case 2: tableBuffer.set_Value(Branch0FCIDFI, streetsFCID); tableBuffer.set_Value(Branch0FIDFI, streetsOID); tableBuffer.set_Value(Branch0FrmPosFI, frmPos); tableBuffer.set_Value(Branch0ToPosFI, toPos); break; case 3: tableBuffer.set_Value(Branch1FCIDFI, streetsFCID); tableBuffer.set_Value(Branch1FIDFI, streetsOID); tableBuffer.set_Value(Branch1FrmPosFI, frmPos); tableBuffer.set_Value(Branch1ToPosFI, toPos); break; case 4: tableBuffer.set_Value(Branch2FCIDFI, streetsFCID); tableBuffer.set_Value(Branch2FIDFI, streetsOID); tableBuffer.set_Value(Branch2FrmPosFI, frmPos); tableBuffer.set_Value(Branch2ToPosFI, toPos); break; } double previousID = currentID; while ((inputTableRow = inputCursor.NextRow()) != null) { currentID = Convert.ToInt64(inputTableRow.get_Value(idFieldOnMP)); if (currentID != previousID) { // write out the previous buffered row and reinitialize the buffer tableInsertCursor.InsertRow(tableBuffer); tableBuffer.set_Value(EdgeFCIDFI, null); tableBuffer.set_Value(EdgeFIDFI, null); tableBuffer.set_Value(EdgeFrmPosFI, null); tableBuffer.set_Value(EdgeToPosFI, null); tableBuffer.set_Value(Branch0FCIDFI, null); tableBuffer.set_Value(Branch0FIDFI, null); tableBuffer.set_Value(Branch0FrmPosFI, null); tableBuffer.set_Value(Branch0ToPosFI, null); tableBuffer.set_Value(Branch1FCIDFI, null); tableBuffer.set_Value(Branch1FIDFI, null); tableBuffer.set_Value(Branch1FrmPosFI, null); tableBuffer.set_Value(Branch1ToPosFI, null); tableBuffer.set_Value(Branch2FCIDFI, null); tableBuffer.set_Value(Branch2FIDFI, null); tableBuffer.set_Value(Branch2FrmPosFI, null); tableBuffer.set_Value(Branch2ToPosFI, null); } streetsOID = Convert.ToInt32(inputTableRow.get_Value(StreetsOIDField)); seqNr = Convert.ToInt32(inputTableRow.get_Value(seqNrField)); frmPos = 0.0; toPos = 1.0; if (seqNr == 1) { if (Convert.ToInt64(inputTableRow.get_Value(mpJnctIDField)) == Convert.ToInt64(inputTableRow.get_Value(FJnctIDField))) { frmPos = 1.0; toPos = 0.0; } } else { if (Convert.ToInt64(inputTableRow.get_Value(mpJnctIDField)) == Convert.ToInt64(inputTableRow.get_Value(TJnctIDField))) { frmPos = 1.0; toPos = 0.0; } } switch (seqNr) { case 1: tableBuffer.set_Value(EdgeFCIDFI, streetsFCID); tableBuffer.set_Value(EdgeFIDFI, streetsOID); tableBuffer.set_Value(EdgeFrmPosFI, frmPos); tableBuffer.set_Value(EdgeToPosFI, toPos); break; case 2: tableBuffer.set_Value(Branch0FCIDFI, streetsFCID); tableBuffer.set_Value(Branch0FIDFI, streetsOID); tableBuffer.set_Value(Branch0FrmPosFI, frmPos); tableBuffer.set_Value(Branch0ToPosFI, toPos); break; case 3: tableBuffer.set_Value(Branch1FCIDFI, streetsFCID); tableBuffer.set_Value(Branch1FIDFI, streetsOID); tableBuffer.set_Value(Branch1FrmPosFI, frmPos); tableBuffer.set_Value(Branch1ToPosFI, toPos); break; case 4: tableBuffer.set_Value(Branch2FCIDFI, streetsFCID); tableBuffer.set_Value(Branch2FIDFI, streetsOID); tableBuffer.set_Value(Branch2FrmPosFI, frmPos); tableBuffer.set_Value(Branch2ToPosFI, toPos); break; } previousID = currentID; } // Write out the final row and flush tableInsertCursor.InsertRow(tableBuffer); tableInsertCursor.Flush(); }
/// <summary> /// 按下"添加所有值"按钮后,让table按当前字段的值进行排序,并把信息添加到listView里面 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnUniValueAddAllValues_Click(object sender, EventArgs e) { try { string currentFieldName = this.cbbUniValueField.Text;//当前字段名 string currentFieldType = this.lsvFields.FindItemWithText(currentFieldName).SubItems[2].Text;//当前字段类型 bool currentTypeIsNumeric = false;//判断当前字段类型是否为数字类型 if (currentFieldType == "Short Integer" || currentFieldType == "Long Integer" || currentFieldType == "Float" || currentFieldType == "Double") { currentTypeIsNumeric = true; } this.lsvUniqueValue.Items.Clear(); //对Table中当前字段进行排序,把结果赋给Cursor ITable pTable = this.pLayer as ITable; ITableSort pTableSort = new TableSortClass(); pTableSort.Table = pTable; pTableSort.Fields = currentFieldName; pTableSort.set_Ascending(currentFieldName, true); pTableSort.set_CaseSensitive(currentFieldName, true); pTableSort.Sort(null);//排序 ICursor pCursor = pTableSort.Rows; //字段统计 IDataStatistics pDataStatistics = new DataStatisticsClass(); pDataStatistics.Cursor = pCursor; pDataStatistics.Field = currentFieldName; System.Collections.IEnumerator pEnumeratorUniqueValues = pDataStatistics.UniqueValues;//唯一值枚举 int uniqueValueCount = pDataStatistics.UniqueValueCount;//唯一值的个数 //table中当前字段有值(不为null)的row的个数,并把信息添加到listView的第一行 IQueryFilter pQueryFilter = new QueryFilterClass(); pQueryFilter.AddField(currentFieldName); int valueSum = pTable.RowCount(pQueryFilter); this.lsvUniqueValue.Items.Add(currentFieldName); this.lsvUniqueValue.Items[0].SubItems.Add(currentFieldName); this.lsvUniqueValue.Items[0].SubItems.Add(valueSum.ToString()); //循环把信息添加到listView里 int i = 1;//注意!是从1开始,因为第一行已经被占用 string currentValue = null;//指示当前的值 //IDataStatistics pUniValueStatistics = new DataStatisticsClass(); int currentValueCount; for (pEnumeratorUniqueValues.Reset(); pEnumeratorUniqueValues.MoveNext(); i++) { currentValue = pEnumeratorUniqueValues.Current.ToString();//当前值 this.lsvUniqueValue.Items.Add(currentValue); this.lsvUniqueValue.Items[i].SubItems.Add(currentValue); //需要这个if的原因是SQL语句中数字和非数字的写法不一样 if (currentTypeIsNumeric) { pQueryFilter.WhereClause = "\"" + currentFieldName + "\"" + " = " + currentValue; } else { pQueryFilter.WhereClause = "\"" + currentFieldName + "\"" + " = " + "'" + currentValue + "'"; } currentValueCount = pTable.RowCount(pQueryFilter);//table中该字段是当前值的row的个数 this.lsvUniqueValue.Items[i].SubItems.Add(currentValueCount.ToString()); } } catch (Exception ex) { MessageBox.Show(ex.Message); } }
/// <summary> /// 查找要素 /// </summary> /// <params name="layer">图层</params> /// <params name="fieldName">字段</params> /// <params name="attributeValue">查询条件</params> /// <returns>查询结果(图层名称,几何图形,属性信息)</returns> public List<Tuple<IFeature, IGeometry, Dictionary<string, string>>> SearchFeaturesByGeoAndText(ILayer layer, Dictionary<string, string> fldvals) { IFeatureLayer featureLayer = (IFeatureLayer)layer; IFeatureClass feaclass = featureLayer.FeatureClass; if (feaclass == null) { Log.Error("[GIS]....The FeatureClass of the Feature layer " + featureLayer.Name + " is null, please check the geodatabase if the feature layer exists."); return null; } var featureList = new List<Tuple<IFeature, IGeometry, Dictionary<string, string>>>(); var filter0 = new QueryFilterClass(); IFields flds = feaclass.Fields; string sql = CreateSqlexpression(flds, fldvals); filter0.WhereClause = sql; IFeatureCursor featureCursor = feaclass.Search(filter0, false); if (feaclass.Fields.FindField(GIS.GIS_Const.FIELD_XH) != -1) { ITableSort tableSort = new TableSortClass(); tableSort.Table = featureLayer.FeatureClass as ITable; tableSort.QueryFilter = filter0; //tableSort.Fields = GIS.GIS_Const.FIELD_XH; //tableSort.set_Ascending(GIS.GIS_Const.FIELD_XH, false); tableSort.Fields = GIS.GIS_Const.FIELD_OBJECTID; tableSort.set_Ascending(GIS.GIS_Const.FIELD_OBJECTID, false); tableSort.Sort(null); featureCursor = tableSort.Rows as IFeatureCursor; } if (featureCursor != null) { var feature = featureCursor.NextFeature(); IGeometry featureGeometry = null; while (feature != null) { var fieldDict = new Dictionary<string, string>(); for (int i = 0; i < feature.Fields.FieldCount; i++) { var field = feature.Fields.Field[i]; if (field.Type != esriFieldType.esriFieldTypeGeometry) { fieldDict.Add(field.Name, feature.Value[i].ToString()); } else { featureGeometry = feature.Shape; } } var featureTuple = new Tuple<IFeature, IGeometry, Dictionary<string, string>>(feature, featureGeometry, fieldDict); featureList.Add(featureTuple); feature = featureCursor.NextFeature(); } } return featureList; }
public azgsSqlDatabaseChooser() { InitializeComponent(); // Populate the listbox // Build a DataTable to bind to the listbox control DataTable projectTable = new DataTable(); DataColumn projName = new DataColumn(); projName.ColumnName = "ProjectName"; projName.DataType = typeof(string); DataColumn dbName = new DataColumn(); dbName.ColumnName = "DatabaseName"; dbName.DataType = typeof(string); projectTable.Columns.Add(projName); projectTable.Columns.Add(dbName); // Populate the DataTable - Right now this is pinging a DB on malachite IPropertySet connectionProperties = new PropertySetClass(); connectionProperties.SetProperty("SERVER", "malachite\\azgsgeodatabases"); connectionProperties.SetProperty("INSTANCE", "sde:sqlserver:malachite\\azgsgeodatabases"); connectionProperties.SetProperty("DATABASE", "AzgsIndex"); connectionProperties.SetProperty("AUTHENTICATION_MODE", "OSA"); connectionProperties.SetProperty("VERSION", "dbo.Default"); try { IWorkspaceFactory wsFact = new SdeWorkspaceFactoryClass(); IWorkspace theWs = wsFact.Open(connectionProperties, 0); // Open the table in the repository database ITable ProjectListingsTable = commonFunctions.OpenTable(theWs, "ProjectDatabases"); // Get all the records into a sorted cursor ITableSort projSorter = new TableSortClass(); projSorter.Table = ProjectListingsTable; projSorter.QueryFilter = null; projSorter.Fields = "ProjectName"; projSorter.set_Ascending("ProjectName", true); projSorter.Sort(null); ICursor projCur = projSorter.Rows; //ProjectListingsTable.Search(null, false); // Loop through the cursor and add records to the DataTable IRow projRow = projCur.NextRow(); while (projRow != null) { projectTable.Rows.Add((String)projRow.get_Value(ProjectListingsTable.FindField("ProjectName")), (String)projRow.get_Value(ProjectListingsTable.FindField("DatabaseName"))); projRow = projCur.NextRow(); } System.Runtime.InteropServices.Marshal.ReleaseComObject(projCur); // Bind the DataTable to the control this.listProjects.DataSource = projectTable; this.listProjects.DisplayMember = "ProjectName"; this.listProjects.ValueMember = "DatabaseName"; this.listProjects.SelectedItem = null; this.listVersions.DataSource = null; } catch (Exception ex) { MessageBox.Show(ex.Message + "\n\n" + ex.StackTrace); return; } }
private void GetAttributeVale() { try { if (this.listBoxField.SelectedIndex == -1) { return; } string currentFieldName = this.listBoxField.Text;//当前字段名 string currentLayerName = this.cboLayer.Text; this.pEnumLayer.Reset(); for (this.pLayer = this.pEnumLayer.Next(); this.pLayer != null; this.pLayer = this.pEnumLayer.Next()) { if (this.pLayer.Name == currentLayerName) { break; } } this.pLayerFields = this.pLayer as ILayerFields; IField pField = this.pLayerFields.get_Field(this.pLayerFields.FindField(currentFieldName)); esriFieldType pFieldType = pField.Type; //对Table中当前字段进行排序,把结果赋给Cursor ITable pTable = this.pLayer as ITable; ITableSort pTableSort = new TableSortClass(); pTableSort.Table = pTable; pTableSort.Fields = currentFieldName; pTableSort.set_Ascending(currentFieldName, true); pTableSort.set_CaseSensitive(currentFieldName, true); pTableSort.Sort(null);//排序 ICursor pCursor = pTableSort.Rows; //IRow pRow = pCursor.NextRow(); //int nSize = 0; //while (pRow != null) //{ // nSize++; // pRow = pCursor.NextRow(); //} //DevComponents.DotNetBar.MessageBox.Show(nSize.ToString()); //return; //字段统计 IDataStatistics pDataStatistics = new DataStatisticsClass(); pDataStatistics.Cursor = pCursor; pDataStatistics.Field = currentFieldName; System.Collections.IEnumerator pEnumeratorUniqueValues = pDataStatistics.UniqueValues; //唯一值枚举 int uniqueValueCount = pDataStatistics.UniqueValueCount; //唯一值的个数 this.listBoxValue.Items.Clear(); string currentValue = null; pEnumeratorUniqueValues.Reset(); if (pFieldType == esriFieldType.esriFieldTypeString) { while (pEnumeratorUniqueValues.MoveNext()) { currentValue = pEnumeratorUniqueValues.Current.ToString(); this.listBoxValue.Items.Add("'" + currentValue + "'"); } } else { while (pEnumeratorUniqueValues.MoveNext()) { currentValue = pEnumeratorUniqueValues.Current.ToString(); this.listBoxValue.Items.Add(currentValue); } } } catch (Exception ex) { MessageBox.Show(ex.Message); } }
private void CreateSignposts(string inputSignsTablePath, string outputFileGdbPath, IGPMessages messages, ITrackCancel trackcancel) { // Open the input Signs table ITable inputSignsTable = m_gpUtils.OpenTableFromString(inputSignsTablePath); // Open the Streets feature class Type gdbFactoryType = Type.GetTypeFromProgID("esriDataSourcesGDB.FileGDBWorkspaceFactory"); var gdbWSF = Activator.CreateInstance(gdbFactoryType) as IWorkspaceFactory; var gdbFWS = gdbWSF.OpenFromFile(outputFileGdbPath, 0) as IFeatureWorkspace; IFeatureClass inputLineFeatures = gdbFWS.OpenFeatureClass(StreetsFCName); // Create the signpost feature class and table IFeatureClass outputSignFeatures = SignpostUtilities.CreateSignsFeatureClass(inputLineFeatures, SignpostFCName); ITable outputSignDetailTable = SignpostUtilities.CreateSignsDetailTable(inputLineFeatures, SignpostJoinTableName); #region Find fields //(Validate checked that these exist) IFields inputTableFields = inputSignsTable.Fields; int inSequenceFI = inputTableFields.FindField("SEQ_NUM"); int inExitNumFI = inputTableFields.FindField("EXIT_NUM"); int inFromIDFI = inputTableFields.FindField("SRC_LINKID"); int inToIDFI = inputTableFields.FindField("DST_LINKID"); int inLangFI = inputTableFields.FindField("LANG_CODE"); int inBranchRteIDFI = inputTableFields.FindField("BR_RTEID"); int inDirectionFI = inputTableFields.FindField("BR_RTEDIR"); int inToNameFI = inputTableFields.FindField("SIGN_TEXT"); int inAccessFI = inputTableFields.FindField("SIGN_TXTTP"); int inToLocaleFI = inputTableFields.FindField("TOW_RTEID"); // Find output fields (we just made these) IFields outputSignFeatureFields = outputSignFeatures.Fields; int outExitNameFI = outputSignFeatureFields.FindField("ExitName"); int[] outBranchXFI = new int[SignpostUtilities.MaxBranchCount]; int[] outBranchXDirFI = new int[SignpostUtilities.MaxBranchCount]; int[] outBranchXLngFI = new int[SignpostUtilities.MaxBranchCount]; int[] outTowardXFI = new int[SignpostUtilities.MaxBranchCount]; int[] outTowardXLngFI = new int[SignpostUtilities.MaxBranchCount]; string indexString; for (int i = 0; i < SignpostUtilities.MaxBranchCount; i++) { indexString = Convert.ToString(i, System.Globalization.CultureInfo.InvariantCulture); outBranchXFI[i] = outputSignFeatureFields.FindField("Branch" + indexString); outBranchXDirFI[i] = outputSignFeatureFields.FindField("Branch" + indexString + "Dir"); outBranchXLngFI[i] = outputSignFeatureFields.FindField("Branch" + indexString + "Lng"); outTowardXFI[i] = outputSignFeatureFields.FindField("Toward" + indexString); outTowardXLngFI[i] = outputSignFeatureFields.FindField("Toward" + indexString + "Lng"); } IFields outputTableFields = outputSignDetailTable.Fields; int outTblSignpostIDFI = outputTableFields.FindField("SignpostID"); int outTblSequenceFI = outputTableFields.FindField("Sequence"); int outTblEdgeFCIDFI = outputTableFields.FindField("EdgeFCID"); int outTblEdgeFIDFI = outputTableFields.FindField("EdgeFID"); int outTblEdgeFrmPosFI = outputTableFields.FindField("EdgeFrmPos"); int outTblEdgeToPosFI = outputTableFields.FindField("EdgeToPos"); // Find ID fields on referenced lines int inLinesOIDFI = inputLineFeatures.FindField(inputLineFeatures.OIDFieldName); int inLinesUserIDFI = inputLineFeatures.FindField("LINK_ID"); int inLinesShapeFI = inputLineFeatures.FindField(inputLineFeatures.ShapeFieldName); #endregion // Get the language lookup hash System.Collections.Hashtable langLookup = CreateLanguageLookup(); // Fetch all line features referenced by the input signs table. We do the // "join" this hard way to support all data sources in the sample. // Also, for large numbers of sign records, this strategy of fetching all // related features and holding them in RAM could be a problem. To fix // this, one could process the input sign records in batches. System.Collections.Hashtable lineFeaturesList = SignpostUtilities.FillFeatureCache(inputSignsTable, inFromIDFI, inToIDFI, inputLineFeatures, "LINK_ID", trackcancel); // Create output feature/row buffers IFeatureBuffer featureBuffer = outputSignFeatures.CreateFeatureBuffer(); IFeature feature = featureBuffer as IFeature; IRowBuffer featureRowBuffer = featureBuffer as IRowBuffer; IRowBuffer tableBuffer = outputSignDetailTable.CreateRowBuffer(); IRow row = tableBuffer as IRow; IRowBuffer tableRowBuffer = tableBuffer as IRowBuffer; // Create insert cursors. IFeatureCursor featureInsertCursor = outputSignFeatures.Insert(true); ICursor tableInsertCursor = outputSignDetailTable.Insert(true); // Create input cursor for the signs table we are importing ITableSort tableSort = new TableSortClass(); tableSort.Fields = "SRC_LINKID, DST_LINKID, SEQ_NUM"; tableSort.set_Ascending("SRC_LINKID", true); tableSort.set_Ascending("DST_LINKID", true); tableSort.set_Ascending("SEQ_NUM", true); tableSort.QueryFilter = null; tableSort.Table = inputSignsTable; tableSort.Sort(null); ICursor inputCursor = tableSort.Rows; IRow inputTableRow; int numOutput = 0; int numInput = 0; short inSequenceValue; long fromIDVal, toIDVal; int nextBranchNum = -1, nextTowardNum = -1; // these are initialized to prevent uninitialized variable compiler error SignpostUtilities.FeatureData fromFeatureData = new SignpostUtilities.FeatureData(-1, null); SignpostUtilities.FeatureData toFeatureData = new SignpostUtilities.FeatureData(-1, null); object newOID; string branchText, towardText, signText, accessText; string langText, langValue; ICurve fromEdgeCurve, toEdgeCurve; IPoint fromEdgeStart, fromEdgeEnd, toEdgeStart, toEdgeEnd; int refLinesFCID = inputLineFeatures.ObjectClassID; IGeometry outputSignGeometry; double lastSrcLinkID = -1.0, currentSrcLinkID = -1.0; double lastDstLinkID = -1.0, currentDstLinkID = -1.0; double fromEdgeFromPos = 0.0; double fromEdgeToPos = 1.0; double toEdgeFromPos = 0.0; double toEdgeToPos = 1.0; while ((inputTableRow = inputCursor.NextRow()) != null) { currentSrcLinkID = Convert.ToInt32(inputTableRow.get_Value(inFromIDFI)); currentDstLinkID = Convert.ToInt32(inputTableRow.get_Value(inToIDFI)); // If we have a new source/destination link ID, we need to // insert the signpost feature in progress and write the detail records. // (identical code is also after the while loop for the last sign record) if (((currentSrcLinkID != lastSrcLinkID) || (currentDstLinkID != lastDstLinkID)) && ((lastSrcLinkID != -1) && (lastDstLinkID != -1))) { // clean up unused parts of the row and pack toward/branch items SignpostUtilities.CleanUpSignpostFeatureValues(featureBuffer, nextBranchNum - 1, nextTowardNum - 1, outBranchXFI, outBranchXDirFI, outBranchXLngFI, outTowardXFI, outTowardXLngFI); // save sign feature record newOID = featureInsertCursor.InsertFeature(featureBuffer); // set streets table values tableRowBuffer.set_Value(outTblSignpostIDFI, newOID); tableRowBuffer.set_Value(outTblSequenceFI, 1); tableRowBuffer.set_Value(outTblEdgeFCIDFI, refLinesFCID); tableRowBuffer.set_Value(outTblEdgeFIDFI, fromFeatureData.OID); tableRowBuffer.set_Value(outTblEdgeFrmPosFI, fromEdgeFromPos); tableRowBuffer.set_Value(outTblEdgeToPosFI, fromEdgeToPos); // insert first detail record tableInsertCursor.InsertRow(tableRowBuffer); tableRowBuffer.set_Value(outTblSequenceFI, 0); tableRowBuffer.set_Value(outTblEdgeFIDFI, toFeatureData.OID); tableRowBuffer.set_Value(outTblEdgeFrmPosFI, toEdgeFromPos); tableRowBuffer.set_Value(outTblEdgeToPosFI, toEdgeToPos); // insert second detail record tableInsertCursor.InsertRow(tableRowBuffer); numOutput++; if ((numOutput % 100) == 0) { // check for user cancel if (trackcancel != null && !trackcancel.Continue()) throw (new COMException("Function cancelled.")); } } lastSrcLinkID = currentSrcLinkID; lastDstLinkID = currentDstLinkID; inSequenceValue = Convert.ToInt16(inputTableRow.get_Value(inSequenceFI)); if (inSequenceValue == 1) { // We are starting a sequence of records for a new sign. // nextBranchNum and nextTowardNum keep track of which branch and // toward item numbers we have used and are not necessarily the same // as inSequenceValue. nextBranchNum = 0; nextTowardNum = 0; fromIDVal = Convert.ToInt64(inputTableRow.get_Value(inFromIDFI)); toIDVal = Convert.ToInt64(inputTableRow.get_Value(inToIDFI)); // If the signpost references a line feature that is not in the lines // feature class, add a warning message and keep going. // Only warn for the first 100 not found. numInput++; try { fromFeatureData = (SignpostUtilities.FeatureData)lineFeaturesList[fromIDVal]; toFeatureData = (SignpostUtilities.FeatureData)lineFeaturesList[toIDVal]; } catch { if (numInput - numOutput < 100) { messages.AddWarning("Line feature not found for sign with FromID: " + Convert.ToString(fromIDVal, System.Globalization.CultureInfo.InvariantCulture) + ", ToID: " + Convert.ToString(toIDVal, System.Globalization.CultureInfo.InvariantCulture)); } continue; } // To set from and to position in the detail table and to construct geometry // for the output signs feature class, we need see where and // if the two edge features connect to figure out their digitized direction. fromEdgeCurve = fromFeatureData.feature as ICurve; toEdgeCurve = toFeatureData.feature as ICurve; fromEdgeStart = fromEdgeCurve.FromPoint; fromEdgeEnd = fromEdgeCurve.ToPoint; toEdgeStart = toEdgeCurve.FromPoint; toEdgeEnd = toEdgeCurve.ToPoint; fromEdgeFromPos = 0.0; fromEdgeToPos = 1.0; toEdgeFromPos = 0.0; toEdgeToPos = 1.0; // flip the from edge? if (TurnGeometryUtilities.EqualPoints(fromEdgeStart, toEdgeStart) || TurnGeometryUtilities.EqualPoints(fromEdgeStart, toEdgeEnd)) { fromEdgeFromPos = 1.0; fromEdgeToPos = 0.0; } // flip the to edge? if (TurnGeometryUtilities.EqualPoints(toEdgeEnd, fromEdgeStart) || TurnGeometryUtilities.EqualPoints(toEdgeEnd, fromEdgeEnd)) { toEdgeFromPos = 1.0; toEdgeToPos = 0.0; } // set sign feature values // construct shape - the only purpose of the shape is visualization and it can be null outputSignGeometry = MakeSignGeometry(fromEdgeCurve, toEdgeCurve, fromEdgeFromPos == 1.0, toEdgeFromPos == 1.0); featureBuffer.Shape = outputSignGeometry; featureBuffer.set_Value(outExitNameFI, inputTableRow.get_Value(inExitNumFI)); } // Look up the language code langText = (inputTableRow.get_Value(inLangFI) as string).Trim(); langValue = SignpostUtilities.GetLanguageValue(langText, langLookup); // Populate Branch items from BR_RTEID and BR_RTEDIR branchText = (inputTableRow.get_Value(inBranchRteIDFI) as string).Trim(); if (branchText.Length > 0) { // check for schema overflow if (nextBranchNum > SignpostUtilities.MaxBranchCount - 1) continue; // set values featureBuffer.set_Value(outBranchXFI[nextBranchNum], branchText); featureBuffer.set_Value(outBranchXDirFI[nextBranchNum], inputTableRow.get_Value(inDirectionFI)); featureBuffer.set_Value(outBranchXLngFI[nextBranchNum], langValue); // get ready for next branch nextBranchNum++; } // Populate Branch or Toward items from SIGN_TEXT depending upon the value in the SIGN_TXTTP field: // - if SIGN_TXTTP == "B" (direct), populate a branch // - if SIGN_TXTTP == "T" (direct), populate a toward signText = (inputTableRow.get_Value(inToNameFI) as string).Trim(); if (signText.Length > 0) { accessText = (inputTableRow.get_Value(inAccessFI) as string); if (accessText == "B") { // check for schema overflow if (nextBranchNum > SignpostUtilities.MaxBranchCount - 1) continue; // set values featureBuffer.set_Value(outBranchXFI[nextBranchNum], signText); featureBuffer.set_Value(outBranchXDirFI[nextBranchNum], inputTableRow.get_Value(inDirectionFI)); featureBuffer.set_Value(outBranchXLngFI[nextBranchNum], langValue); // get ready for next branch nextBranchNum++; } else if (accessText == "T") { // check for schema overflow if (nextTowardNum > SignpostUtilities.MaxBranchCount - 1) continue; // set values featureBuffer.set_Value(outTowardXFI[nextTowardNum], signText); featureBuffer.set_Value(outTowardXLngFI[nextTowardNum], langValue); // get ready for next toward nextTowardNum++; } else continue; // not expected } // Populate Toward items from TOW_RTEID towardText = (inputTableRow.get_Value(inToLocaleFI) as string).Trim(); if (towardText.Length > 0) { // check for schema overflow if (nextTowardNum > SignpostUtilities.MaxBranchCount - 1) continue; // set values featureBuffer.set_Value(outTowardXFI[nextTowardNum], towardText); featureBuffer.set_Value(outTowardXLngFI[nextTowardNum], langValue); // get ready for next toward nextTowardNum++; } } // each input table record // Assuming the table wasn't empty to begin with (detected by the Currents no longer being -1.0), // add the last signpost feature and detail records (same code as above) if (currentSrcLinkID != -1.0 && currentDstLinkID != -1.0) { // clean up unused parts of the row and pack toward/branch items SignpostUtilities.CleanUpSignpostFeatureValues(featureBuffer, nextBranchNum - 1, nextTowardNum - 1, outBranchXFI, outBranchXDirFI, outBranchXLngFI, outTowardXFI, outTowardXLngFI); // save sign feature record newOID = featureInsertCursor.InsertFeature(featureBuffer); // set streets table values tableRowBuffer.set_Value(outTblSignpostIDFI, newOID); tableRowBuffer.set_Value(outTblSequenceFI, 1); tableRowBuffer.set_Value(outTblEdgeFCIDFI, refLinesFCID); tableRowBuffer.set_Value(outTblEdgeFIDFI, fromFeatureData.OID); tableRowBuffer.set_Value(outTblEdgeFrmPosFI, fromEdgeFromPos); tableRowBuffer.set_Value(outTblEdgeToPosFI, fromEdgeToPos); // insert first detail record tableInsertCursor.InsertRow(tableRowBuffer); tableRowBuffer.set_Value(outTblSequenceFI, 0); tableRowBuffer.set_Value(outTblEdgeFIDFI, toFeatureData.OID); tableRowBuffer.set_Value(outTblEdgeFrmPosFI, toEdgeFromPos); tableRowBuffer.set_Value(outTblEdgeToPosFI, toEdgeToPos); // insert second detail record tableInsertCursor.InsertRow(tableRowBuffer); numOutput++; // Flush any outstanding writes to the feature class and table featureInsertCursor.Flush(); tableInsertCursor.Flush(); } // add a summary message messages.AddMessage(Convert.ToString(numOutput) + " of " + Convert.ToString(numInput) + " signposts added."); return; }
private void SplitFeature(IQueryFilter selectionQueryFilter, string lastToidFragmentID, string[] historyColumns) { // make sure selection changed event handler won't intervene _selectFieldOrdinals = null; if (_pipeData == null) _pipeData = new List<string>(); try { lock (_pipeData) { // clear the pipe _pipeData.Clear(); // check if HLU layer is being edited if (!HluLayerBeingEdited) return; // make sure at least two features are selected if (_hluFeatureSelection == null) _hluFeatureSelection = (IFeatureSelection)_hluLayer; if (_hluFeatureSelection.SelectionSet.Count < 2) return; // write history field names and types to pipe int[] historyFieldOrdinals = HistorySchema(historyColumns); // get the lowest OID in selection set (using query filter for safety) ICursor cursor; _hluFeatureSelection.SelectionSet.Search(selectionQueryFilter, true, out cursor); ITableSort tableSort = new TableSortClass(); tableSort.Table = (ITable)_hluFeatureClass; tableSort.Cursor = cursor; tableSort.Fields = _hluFeatureClass.OIDFieldName; tableSort.set_Ascending(_hluFeatureClass.OIDFieldName, true); tableSort.Sort(null); ICursor sortCursor = tableSort.Rows; IRow row = sortCursor.NextRow(); int minOID = row.OID; FlushCursor(false, ref cursor); // start workspace edit session and operation StartEditing(); try { // get features to be updated IFeatureCursor updateCursor = _hluFeatureClass.Update(selectionQueryFilter, false); string numFormat = String.Format("D{0}", lastToidFragmentID.Length); int newToidFragmentIDnum = Int32.Parse(lastToidFragmentID); int toidFragOrdinal = _hluFieldMap[_hluLayerStructure.toid_fragment_idColumn.Ordinal]; // temporary history list, sorted before adding to _pipeData List<string> historyList = new List<string>(); int originalFeatureIx = -1; int i = 0; IFeature updateFeature; //--------------------------------------------------------------------- // FIXED: KI106 (Shape area and length values) // Includes updates for the geom1 and geom2 columns as the features // have changed in size // Check if the current layer is a shapefile bool isShp = IsShp(_hluWS as IWorkspace); //--------------------------------------------------------------------- while ((updateFeature = updateCursor.NextFeature()) != null) { if (updateFeature.OID != minOID) { // Set the toid_fragment_id to the next available number updateFeature.set_Value(toidFragOrdinal, (++newToidFragmentIDnum).ToString(numFormat)); } else { // Store the original feature number originalFeatureIx = i; } //--------------------------------------------------------------------- // FIXED: KI106 (Shape area and length values) // Includes updates for the geom1 and geom2 columns as the features // have changed in size // If it is a shapefile then update the geometry fields if (isShp) { double geom1; double geom2; GetGeometryProperties(updateFeature, out geom1, out geom2); int ixGeom1 = updateFeature.Fields.FindField("shape_leng"); int ixGeom2 = updateFeature.Fields.FindField("shape_area"); updateFeature.set_Value(ixGeom1, geom1); updateFeature.set_Value(ixGeom2, geom2); } // Update the feature updateCursor.UpdateFeature(updateFeature); //updateFeature.Store(); //--------------------------------------------------------------------- historyList.Add(History(updateFeature, historyFieldOrdinals, null)); i++; } // make sure original feature is on top of the list _pipeData.Add(historyList[originalFeatureIx]); _pipeData.AddRange(historyList.Where((h, index) => index != originalFeatureIx)); FlushCursor(false, ref updateCursor); // stop edit operation and session CommitEdits(); // redraw selected HLU features _hluView.PartialRefresh(esriViewDrawPhase.esriViewGeoSelection, _hluLayer, _hluView.Extent); } catch { DiscardEdits(); throw; } } } catch { _pipeData.Clear(); } }
/// <summary> /// Creates voyage tracks using all the points in the given AOI. Based on time and VoyageID. /// </summary> /// <param name="pBroadcast"></param> /// <param name="pVoyageTable"></param> /// <param name="pVoyageTracks"></param> /// <param name="pPolygon"></param> /// <param name="iMaxTime"></param> private void CreatePolylineFeatures(IFeatureLayer pBroadcast, ITable pVoyageTable, IFeatureClass pVoyageTracks, IGeometry pPolygon, int iMaxTime) { IFeatureClassLoad pFCLoad = (IFeatureClassLoad)pVoyageTracks; pFCLoad.LoadOnlyMode = true; try { IFeatureCursor pOutFeatCurs = pVoyageTracks.Insert(true); IFeatureBuffer myFeatureBuffer = pVoyageTracks.CreateFeatureBuffer(); ISpatialReference pSR = CreateGeographicSR(); ISpatialFilter pSpatialFilter = null; IFeatureCursor pCursor = null; if (pPolygon != null) { pSpatialFilter = new SpatialFilterClass(); pSpatialFilter.Geometry = pPolygon; pSpatialFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects; pCursor = pBroadcast.Search((IQueryFilter)pSpatialFilter, false); } else { //Get Unique Voyage IDs from Broadcast table pCursor = pBroadcast.Search(null, false); } IDataStatistics pDS = new DataStatisticsClass(); pDS.Field = "VoyageID"; pDS.Cursor = (ICursor)pCursor; IEnumerator pEnum = pDS.UniqueValues; /*List<string> aVoyageIDs = new List<string>(); * while (pEnum.MoveNext()) * { * aVoyageIDs.Add(pEnum.Current.ToString()); * }*/ object missing = Type.Missing; //foreach (string myID in aVoyageIDs) int i = 0; DateTime startDate = new DateTime(1900, 1, 1); while (pEnum.MoveNext()) { DateTime lastTime = startDate; string myID = pEnum.Current.ToString(); IPointCollection myCollection = new PolylineClass(); IQueryFilter pQF = new QueryFilterClass(); pQF.WhereClause = "VoyageID = " + myID; ICursor pVoyageCursor = pVoyageTable.Search(pQF, true); IRow pVoyageRow = pVoyageCursor.NextRow(); if (pSpatialFilter != null) { pQF = (IQueryFilter)pSpatialFilter; pQF.WhereClause = "VoyageID = " + myID; } IFeatureCursor pFeatureCursor = pBroadcast.Search(pQF, false); ITableSort pTableSort = new TableSortClass(); pTableSort.Table = (ITable)pBroadcast; pTableSort.Cursor = (ICursor)pFeatureCursor; pTableSort.Fields = "BaseDateTime"; pTableSort.set_Ascending("BaseDateTime", true); pTableSort.Sort(null); ICursor pSortedCursor = pTableSort.Rows; IRow pRow = pSortedCursor.NextRow(); while (pRow != null) { if (pRow is IFeature) { IFeature pFeature = (IFeature)pRow; IPoint myPoint = (IPoint)pFeature.Shape; DateTime thisTime = Convert.ToDateTime(pFeature.get_Value(pFeature.Fields.FindField("BaseDateTime"))); if (m_iMaxTime == 0) //add them all, no matter what { myCollection.AddPoint(myPoint, ref missing, ref missing); } else { if (lastTime.CompareTo(startDate) != 0) //first point in track, definitely add point { TimeSpan mySpan = thisTime.Subtract(lastTime); if (mySpan.TotalMinutes > m_iMaxTime) //this one is too far away. Create the feature, then start over { if (myCollection.PointCount > 0) { AddLineFeature(myFeatureBuffer, myCollection, pSR, pVoyageRow, myID); } pOutFeatCurs.InsertFeature(myFeatureBuffer); myCollection = new PolylineClass(); } } myCollection.AddPoint(myPoint, ref missing, ref missing); lastTime = thisTime; } } pRow = pSortedCursor.NextRow(); } if (myCollection.PointCount > 0) { AddLineFeature(myFeatureBuffer, myCollection, pSR, pVoyageRow, myID); } pOutFeatCurs.InsertFeature(myFeatureBuffer); i++; if (i == 1000) { pOutFeatCurs.Flush(); i = 0; } } pOutFeatCurs.Flush(); } catch (Exception ex) { clsStatic.ShowErrorMessage(ex.ToString()); } finally { pFCLoad.LoadOnlyMode = false; } }
private void CreateAndPopulateTurnFeatureClass(string outputFileGdbPath, string fdsName, string ProhibRdmsTableName, string tempStatsTableName, IGPMessages messages, ITrackCancel trackcancel) { // Determine the number of AltID fields we need (one more than the MAX_SEQ_NUMBER value). Type factoryType = Type.GetTypeFromProgID("esriDataSourcesGDB.FileGDBWorkspaceFactory"); var wsf = Activator.CreateInstance(factoryType) as IWorkspaceFactory; var fws = wsf.OpenFromFile(outputFileGdbPath, 0) as IFeatureWorkspace; ITable tempStatsTable = fws.OpenTable(tempStatsTableName); short numAltIDFields = 2; if (tempStatsTable.RowCount(null) == 1) numAltIDFields = (short)(1 + (double)(tempStatsTable.GetRow(1).get_Value(tempStatsTable.FindField("MAX_SEQ_NUMBER")))); // Open the Rdms table and find the fields we need ITable rdmsTable = fws.OpenTable(ProhibRdmsTableName); int seqNumberField = rdmsTable.FindField("SEQ_NUMBER"); int linkIDFieldOnRdms = rdmsTable.FindField("LINK_ID"); int manLinkIDField = rdmsTable.FindField("MAN_LINKID"); int condIDFieldOnRdms = rdmsTable.FindField("COND_ID"); int endOfLkFieldOnRdms = rdmsTable.FindField("END_OF_LK"); // Create a temporary template feature class var fcd = new FeatureClassDescriptionClass() as IFeatureClassDescription; var ocd = fcd as IObjectClassDescription; var fieldsEdit = ocd.RequiredFields as IFieldsEdit; IField fieldOnRdmsTable = rdmsTable.Fields.get_Field(linkIDFieldOnRdms); // use the LINK_ID field as a template for the AltID fields for (short i = 1; i <= numAltIDFields; i++) { IFieldEdit newField = new FieldClass(); newField.Name_2 = "AltID" + i; newField.Precision_2 = fieldOnRdmsTable.Precision; newField.Scale_2 = fieldOnRdmsTable.Scale; newField.Type_2 = fieldOnRdmsTable.Type; fieldsEdit.AddField(newField as IField); } fieldOnRdmsTable = rdmsTable.Fields.get_Field(condIDFieldOnRdms); fieldsEdit.AddField(fieldOnRdmsTable); var fieldChk = new FieldCheckerClass() as IFieldChecker; IEnumFieldError enumFieldErr = null; IFields validatedFields = null; fieldChk.ValidateWorkspace = fws as IWorkspace; fieldChk.Validate(fieldsEdit as IFields, out enumFieldErr, out validatedFields); var tempFC = fws.CreateFeatureClass("TheTemplate", validatedFields, ocd.InstanceCLSID, ocd.ClassExtensionCLSID, esriFeatureType.esriFTSimple, fcd.ShapeFieldName, "") as IDataset; // Create the turn feature class from the template, then delete the template Geoprocessor gp = new Geoprocessor(); CreateTurnFeatureClass createTurnFCTool = new CreateTurnFeatureClass(); string pathToFds = outputFileGdbPath + "\\" + fdsName; createTurnFCTool.out_location = pathToFds; createTurnFCTool.out_feature_class_name = TurnFCName; createTurnFCTool.maximum_edges = numAltIDFields; createTurnFCTool.in_template_feature_class = outputFileGdbPath + "\\TheTemplate"; gp.Execute(createTurnFCTool, trackcancel); tempFC.Delete(); // Open the new turn feature class and find all the fields on it IFeatureClass turnFC = fws.OpenFeatureClass(TurnFCName); int[] altIDFields = new int[numAltIDFields]; int[] edgeFCIDFields = new int[numAltIDFields]; int[] edgeFIDFields = new int[numAltIDFields]; int[] edgePosFields = new int[numAltIDFields]; for (short i = 0; i < numAltIDFields; i++) { altIDFields[i] = turnFC.FindField("AltID" + (i + 1)); edgeFCIDFields[i] = turnFC.FindField("Edge" + (i + 1) + "FCID"); edgeFIDFields[i] = turnFC.FindField("Edge" + (i + 1) + "FID"); edgePosFields[i] = turnFC.FindField("Edge" + (i + 1) + "Pos"); } int edge1endField = turnFC.FindField("Edge1End"); int condIDFieldOnTurnFC = turnFC.FindField("COND_ID"); // Look up the FCID of the Streets feature class IFeatureClass streetsFC = fws.OpenFeatureClass(StreetsFCName); int streetsFCID = streetsFC.FeatureClassID; // Set up queries var ts = new TableSortClass() as ITableSort; ts.Fields = "COND_ID, SEQ_NUMBER"; ts.set_Ascending("COND_ID", true); ts.set_Ascending("SEQ_NUMBER", true); ts.QueryFilter = new QueryFilterClass(); ts.Table = rdmsTable; ts.Sort(null); ICursor rdmsCursor = ts.Rows; IFeatureCursor turnFCCursor = turnFC.Insert(true); IFeatureBuffer turnBuffer = turnFC.CreateFeatureBuffer(); // Write the field values to the turn feature class accordingly int numFeatures = 0; IRow rdmsRow = rdmsCursor.NextRow(); while (rdmsRow != null) { // Transfer the non-edge identifying field values to the buffer turnBuffer.set_Value(condIDFieldOnTurnFC, rdmsRow.get_Value(condIDFieldOnRdms)); // Write the Edge1End field value to the buffer switch ((string)(rdmsRow.get_Value(endOfLkFieldOnRdms))) { case "N": turnBuffer.set_Value(edge1endField, "Y"); break; case "R": turnBuffer.set_Value(edge1endField, "N"); break; default: break; // not expected } // Write the AltID values to the buffer turnBuffer.set_Value(altIDFields[0], rdmsRow.get_Value(linkIDFieldOnRdms)); short seq = (short)(rdmsRow.get_Value(seqNumberField)); short lastEntry; do { lastEntry = seq; turnBuffer.set_Value(altIDFields[lastEntry], rdmsRow.get_Value(manLinkIDField)); rdmsRow = rdmsCursor.NextRow(); if (rdmsRow == null) break; seq = (short)(rdmsRow.get_Value(seqNumberField)); } while (seq != 1); // Zero-out the unused fields for (int i = lastEntry + 1; i < numAltIDFields; i++) turnBuffer.set_Value(altIDFields[i], 0); // Write the FCID and Pos field values to the buffer for (short i = 0; i < numAltIDFields; i++) { int altID = (int)(turnBuffer.get_Value(altIDFields[i])); if (altID != 0) { turnBuffer.set_Value(edgeFCIDFields[i], streetsFCID); turnBuffer.set_Value(edgeFIDFields[i], 1); turnBuffer.set_Value(edgePosFields[i], 0.5); } else { turnBuffer.set_Value(edgeFCIDFields[i], 0); turnBuffer.set_Value(edgeFIDFields[i], 0); turnBuffer.set_Value(edgePosFields[i], 0); } } // Create the turn feature turnFCCursor.InsertFeature(turnBuffer); numFeatures++; if ((numFeatures % 100) == 0) { // check for user cancel if (trackcancel != null && !trackcancel.Continue()) throw (new COMException("Function cancelled.")); } } // Flush any outstanding writes to the turn feature class turnFCCursor.Flush(); messages.AddMessage("Updating the EdgeFID values..."); // Create a temporary network dataset for updating the EdgeFID values IDENetworkDataset dends = new DENetworkDatasetClass(); dends.SupportsTurns = true; dends.Buildable = true; (dends as IDataElement).Name = StreetsFCName; (dends as IDEGeoDataset).SpatialReference = (streetsFC as IGeoDataset).SpatialReference; IArray sourceArray = new ArrayClass(); var efs = new EdgeFeatureSourceClass() as IEdgeFeatureSource; (efs as INetworkSource).Name = StreetsFCName; efs.UsesSubtypes = false; efs.ClassConnectivityGroup = 1; efs.ClassConnectivityPolicy = esriNetworkEdgeConnectivityPolicy.esriNECPEndVertex; sourceArray.Add(efs); var tfs = new TurnFeatureSourceClass() as INetworkSource; tfs.Name = TurnFCName; sourceArray.Add(tfs); dends.Sources = sourceArray; var fdxc = fws.OpenFeatureDataset(fdsName) as IFeatureDatasetExtensionContainer; var dsCont = fdxc.FindExtension(esriDatasetType.esriDTNetworkDataset) as IDatasetContainer2; var tempNDS = dsCont.CreateDataset(dends as IDEDataset) as IDataset; // Set the EdgeFID field values by running UpdateByAlternateIDFields UpdateByAlternateIDFields updateByAltIDTool = new UpdateByAlternateIDFields(); updateByAltIDTool.in_network_dataset = pathToFds + "\\" + StreetsFCName; updateByAltIDTool.alternate_ID_field_name = "LINK_ID"; gp.Execute(updateByAltIDTool, trackcancel); // Delete the temporary network dataset tempNDS.Delete(); // Write the turn geometries TurnGeometryUtilities.WriteTurnGeometry(outputFileGdbPath, StreetsFCName, TurnFCName, numAltIDFields, 0.3, messages, trackcancel); // Index the turn geometries messages.AddMessage("Creating spatial index on the turn feature class..."); AddSpatialIndex addSpatialIndexTool = new AddSpatialIndex(); addSpatialIndexTool.in_features = pathToFds + "\\" + TurnFCName; gp.Execute(addSpatialIndexTool, trackcancel); return; }
private void CreateSignposts(string inputSITablePath, string inputSPTablePath, string outputFileGdbPath, IGPMessages messages, ITrackCancel trackcancel) { // Open the input SI and SP tables ITable inputSignInformationTable = m_gpUtils.OpenTableFromString(inputSITablePath); ITable inputSignPathTable = m_gpUtils.OpenTableFromString(inputSPTablePath); // Open the Streets feature class Type gdbFactoryType = Type.GetTypeFromProgID("esriDataSourcesGDB.FileGDBWorkspaceFactory"); var gdbWSF = Activator.CreateInstance(gdbFactoryType) as IWorkspaceFactory; var gdbFWS = gdbWSF.OpenFromFile(outputFileGdbPath, 0) as IFeatureWorkspace; IFeatureClass inputLineFeatures = gdbFWS.OpenFeatureClass(StreetsFCName); // Create the signpost feature class and table IFeatureClass outputSignFeatures = SignpostUtilities.CreateSignsFeatureClass(inputLineFeatures, SignpostFCName); ITable outputSignDetailTable = SignpostUtilities.CreateSignsDetailTable(inputLineFeatures, SignpostJoinTableName); #region Find fields //(Validate checked that these exist) IFields inputSITableFields = inputSignInformationTable.Fields; int inSiIdFI = inputSITableFields.FindField("ID"); int inSiInfoTypFI = inputSITableFields.FindField("INFOTYP"); int inSiTxtContFI = inputSITableFields.FindField("TXTCONT"); int inSiTxtContLCFI = inputSITableFields.FindField("TXTCONTLC"); int inSiConTypFI = inputSITableFields.FindField("CONTYP"); IFields inputSPTableFields = inputSignPathTable.Fields; int inSpIdFI = inputSPTableFields.FindField("ID"); int inSpSeqNrFI = inputSPTableFields.FindField("SEQNR"); int inSpTrpElIdFI = inputSPTableFields.FindField("TRPELID"); int inSpTrpElTypFI = inputSPTableFields.FindField("TRPELTYP"); // Find output fields (we just made these) IFields outputSignFeatureFields = outputSignFeatures.Fields; int outExitNameFI = outputSignFeatureFields.FindField("ExitName"); int[] outBranchXFI = new int[SignpostUtilities.MaxBranchCount]; int[] outBranchXDirFI = new int[SignpostUtilities.MaxBranchCount]; int[] outBranchXLngFI = new int[SignpostUtilities.MaxBranchCount]; int[] outTowardXFI = new int[SignpostUtilities.MaxBranchCount]; int[] outTowardXLngFI = new int[SignpostUtilities.MaxBranchCount]; string indexString; for (int i = 0; i < SignpostUtilities.MaxBranchCount; i++) { indexString = Convert.ToString(i, System.Globalization.CultureInfo.InvariantCulture); outBranchXFI[i] = outputSignFeatureFields.FindField("Branch" + indexString); outBranchXDirFI[i] = outputSignFeatureFields.FindField("Branch" + indexString + "Dir"); outBranchXLngFI[i] = outputSignFeatureFields.FindField("Branch" + indexString + "Lng"); outTowardXFI[i] = outputSignFeatureFields.FindField("Toward" + indexString); outTowardXLngFI[i] = outputSignFeatureFields.FindField("Toward" + indexString + "Lng"); } IFields outputTableFields = outputSignDetailTable.Fields; int outTblSignpostIDFI = outputTableFields.FindField("SignpostID"); int outTblSequenceFI = outputTableFields.FindField("Sequence"); int outTblEdgeFCIDFI = outputTableFields.FindField("EdgeFCID"); int outTblEdgeFIDFI = outputTableFields.FindField("EdgeFID"); int outTblEdgeFrmPosFI = outputTableFields.FindField("EdgeFrmPos"); int outTblEdgeToPosFI = outputTableFields.FindField("EdgeToPos"); // Find ID fields on referenced lines int inLinesOIDFI = inputLineFeatures.FindField(inputLineFeatures.OIDFieldName); int inLinesUserIDFI = inputLineFeatures.FindField("ID"); int inLinesShapeFI = inputLineFeatures.FindField(inputLineFeatures.ShapeFieldName); #endregion // Get the language lookup hash System.Collections.Hashtable langLookup = CreateLanguageLookup(); // Fetch all line features referenced by the input signs table. We do the // "join" this hard way to support all data sources in the sample. // Also, for large numbers of sign records, this strategy of fetching all // related features and holding them in RAM could be a problem. To fix // this, one could process the input sign records in batches. System.Collections.Hashtable lineFeaturesList = SignpostUtilities.FillFeatureCache(inputSignPathTable, inSpTrpElIdFI, -1, inputLineFeatures, "ID", trackcancel); // Create output feature/row buffers IFeatureBuffer featureBuffer = outputSignFeatures.CreateFeatureBuffer(); IFeature feature = featureBuffer as IFeature; IRowBuffer featureRowBuffer = featureBuffer as IRowBuffer; IRowBuffer tableBuffer = outputSignDetailTable.CreateRowBuffer(); IRow row = tableBuffer as IRow; IRowBuffer tableRowBuffer = tableBuffer as IRowBuffer; // Create insert cursors. IFeatureCursor featureInsertCursor = outputSignFeatures.Insert(true); ICursor tableInsertCursor = outputSignDetailTable.Insert(true); // Create input cursors for the sign tables we are importing ITableSort spTableSort = new TableSortClass(); spTableSort.Fields = "ID, SEQNR"; spTableSort.set_Ascending("ID", true); spTableSort.set_Ascending("SEQNR", true); spTableSort.QueryFilter = null; spTableSort.Table = inputSignPathTable; spTableSort.Sort(null); ICursor spInputCursor = spTableSort.Rows; ITableSort siTableSort = new TableSortClass(); siTableSort.Fields = "ID, SEQNR, DESTSEQ, RNPART"; siTableSort.set_Ascending("ID", true); siTableSort.set_Ascending("SEQNR", true); siTableSort.set_Ascending("DESTSEQ", true); siTableSort.set_Ascending("RNPART", true); siTableSort.QueryFilter = null; siTableSort.Table = inputSignInformationTable; siTableSort.Sort(null); ICursor siInputCursor = siTableSort.Rows; IRow inputSpTableRow; IRow inputSiTableRow; long currentID = -1, loopSpID, loopSiID; int numOutput = 0; int numInput = 0; bool fetchFeatureDataSucceeded; ArrayList idVals = new System.Collections.ArrayList(2); ArrayList edgesData = new System.Collections.ArrayList(2); ArrayList reverseEdge = new System.Collections.ArrayList(2); SignpostUtilities.FeatureData currentFeatureData = new SignpostUtilities.FeatureData(-1, null); ICurve earlierEdgeCurve, laterEdgeCurve; IPoint earlierEdgeStart, earlierEdgeEnd; IPoint laterEdgeStart, laterEdgeEnd; int nextBranchNum = -1, nextTowardNum = -1; string infoTypText, txtContText; string txtContTextLC, langVal; int conTypVal; int refLinesFCID = inputLineFeatures.ObjectClassID; IGeometry outputSignGeometry; object newOID; inputSpTableRow = spInputCursor.NextRow(); inputSiTableRow = siInputCursor.NextRow(); while (inputSpTableRow != null && inputSiTableRow != null) { currentID = Convert.ToInt64(inputSpTableRow.get_Value(inSpIdFI)); // fetch the edge ID values from the SP table for the current sign ID idVals.Clear(); while (true) { idVals.Add(Convert.ToInt64(inputSpTableRow.get_Value(inSpTrpElIdFI))); inputSpTableRow = spInputCursor.NextRow(); if (inputSpTableRow == null) break; // we've reached the end of the SP table loopSpID = Convert.ToInt64(inputSpTableRow.get_Value(inSpIdFI)); if (loopSpID != currentID) break; // we're now on a new ID value } numInput++; // fetch the FeatureData for each of these edges edgesData.Clear(); fetchFeatureDataSucceeded = true; foreach (long currentIDVal in idVals) { try { currentFeatureData = (SignpostUtilities.FeatureData)lineFeaturesList[currentIDVal]; edgesData.Add(currentFeatureData); } catch { fetchFeatureDataSucceeded = false; if (numInput - numOutput < 100) { messages.AddWarning("Line feature not found for signpost with ID: " + Convert.ToString(currentIDVal, System.Globalization.CultureInfo.InvariantCulture)); } break; } } if (!fetchFeatureDataSucceeded) continue; if (edgesData.Count == 1) { messages.AddWarning("Signpost with ID " + Convert.ToString(currentID, System.Globalization.CultureInfo.InvariantCulture) + " only has one transportation element."); continue; } // determine the orientation for each of these edges reverseEdge.Clear(); for (int i = 1; i < edgesData.Count; i++) { // get the endpoints of the earlier curve currentFeatureData = (SignpostUtilities.FeatureData)edgesData[i - 1]; earlierEdgeCurve = currentFeatureData.feature as ICurve; earlierEdgeStart = earlierEdgeCurve.FromPoint; earlierEdgeEnd = earlierEdgeCurve.ToPoint; // get the endpoints of the later curve currentFeatureData = (SignpostUtilities.FeatureData)edgesData[i]; laterEdgeCurve = currentFeatureData.feature as ICurve; laterEdgeStart = laterEdgeCurve.FromPoint; laterEdgeEnd = laterEdgeCurve.ToPoint; // determine the orientation of the first edge // (first edge is reversed if its Start point is coincident with either point of the second edge) if (i == 1) reverseEdge.Add(TurnGeometryUtilities.EqualPoints(earlierEdgeStart, laterEdgeStart) || TurnGeometryUtilities.EqualPoints(earlierEdgeStart, laterEdgeEnd)); // determine the orientation of the i'th edge // (i'th edge is reversed if its End point is coincident with either point of the previous edge) reverseEdge.Add(TurnGeometryUtilities.EqualPoints(laterEdgeEnd, earlierEdgeStart) || TurnGeometryUtilities.EqualPoints(laterEdgeEnd, earlierEdgeEnd)); } // write out the sign geometry to the featureBuffer outputSignGeometry = MakeSignGeometry(edgesData, reverseEdge); featureBuffer.Shape = outputSignGeometry; // fetch the signpost information from the SI table for the current sign ID nextBranchNum = 0; nextTowardNum = 0; featureBuffer.set_Value(outExitNameFI, ""); while (inputSiTableRow != null) { loopSiID = Convert.ToInt64(inputSiTableRow.get_Value(inSiIdFI)); if (loopSiID < currentID) { inputSiTableRow = siInputCursor.NextRow(); continue; } else if (loopSiID > currentID) { break; // we're now on a new ID value } infoTypText = inputSiTableRow.get_Value(inSiInfoTypFI) as string; txtContText = inputSiTableRow.get_Value(inSiTxtContFI) as string; txtContTextLC = inputSiTableRow.get_Value(inSiTxtContLCFI) as string; langVal = SignpostUtilities.GetLanguageValue(txtContTextLC, langLookup); conTypVal = Convert.ToInt32(inputSiTableRow.get_Value(inSiConTypFI)); switch (infoTypText) { case "4E": // exit number featureBuffer.set_Value(outExitNameFI, txtContText); break; case "9D": // place name case "4I": // other destination // check for schema overflow if (nextTowardNum > SignpostUtilities.MaxBranchCount - 1) { inputSiTableRow = siInputCursor.NextRow(); continue; } // set values featureBuffer.set_Value(outTowardXFI[nextTowardNum], txtContText); featureBuffer.set_Value(outTowardXLngFI[nextTowardNum], langVal); // get ready for next toward nextTowardNum++; break; case "6T": // street name case "RN": // route number if (conTypVal == 2) // toward { // check for schema overflow if (nextTowardNum > SignpostUtilities.MaxBranchCount - 1) { inputSiTableRow = siInputCursor.NextRow(); continue; } // set values featureBuffer.set_Value(outTowardXFI[nextTowardNum], txtContText); featureBuffer.set_Value(outTowardXLngFI[nextTowardNum], langVal); // get ready for next toward nextTowardNum++; } else // branch { // check for schema overflow if (nextBranchNum > SignpostUtilities.MaxBranchCount - 1) { inputSiTableRow = siInputCursor.NextRow(); continue; } // set values featureBuffer.set_Value(outBranchXFI[nextBranchNum], txtContText); featureBuffer.set_Value(outBranchXDirFI[nextBranchNum], ""); featureBuffer.set_Value(outBranchXLngFI[nextBranchNum], "en"); // get ready for next branch nextBranchNum++; } break; } // switch inputSiTableRow = siInputCursor.NextRow(); } // each SI table record // clean up unused parts of the row and pack toward/branch items SignpostUtilities.CleanUpSignpostFeatureValues(featureBuffer, nextBranchNum - 1, nextTowardNum - 1, outBranchXFI, outBranchXDirFI, outBranchXLngFI, outTowardXFI, outTowardXLngFI); // insert sign feature record newOID = featureInsertCursor.InsertFeature(featureBuffer); // set streets table values tableRowBuffer.set_Value(outTblSignpostIDFI, newOID); tableRowBuffer.set_Value(outTblEdgeFCIDFI, refLinesFCID); for (int i = 0; i < edgesData.Count; i++) { currentFeatureData = (SignpostUtilities.FeatureData)edgesData[i]; tableRowBuffer.set_Value(outTblSequenceFI, i + 1); tableRowBuffer.set_Value(outTblEdgeFIDFI, currentFeatureData.OID); if ((bool)reverseEdge[i]) { tableRowBuffer.set_Value(outTblEdgeFrmPosFI, 1.0); tableRowBuffer.set_Value(outTblEdgeToPosFI, 0.0); } else { tableRowBuffer.set_Value(outTblEdgeFrmPosFI, 0.0); tableRowBuffer.set_Value(outTblEdgeToPosFI, 1.0); } // insert detail record tableInsertCursor.InsertRow(tableRowBuffer); } numOutput++; if ((numOutput % 100) == 0) { // check for user cancel if (trackcancel != null && !trackcancel.Continue()) throw (new COMException("Function cancelled.")); } } // outer while // Flush any outstanding writes to the feature class and table featureInsertCursor.Flush(); tableInsertCursor.Flush(); // add a summary message messages.AddMessage(Convert.ToString(numOutput) + " of " + Convert.ToString(numInput) + " signposts added."); return; }
/// <summary> /// 获得当前字段的唯一值 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void buttonGetValue_Click(object sender, EventArgs e) { try { if (this.listBoxFields.SelectedIndex == -1) { return; } string currentFieldName = this.listBoxFields.Text;//当前字段名 string currentLayerName = this.comboBoxLayers.Text; this.pEnumLayer.Reset(); for (this.pLayer = this.pEnumLayer.Next(); this.pLayer != null; this.pLayer = this.pEnumLayer.Next()) { if (this.pLayer.Name == currentLayerName) { break; } } this.pLayerFields = this.pLayer as ILayerFields; IField pField = this.pLayerFields.get_Field(this.pLayerFields.FindField(currentFieldName)); esriFieldType pFieldType = pField.Type; //对Table中当前字段进行排序,把结果赋给Cursor ITable pTable = this.pLayer as ITable; ITableSort pTableSort = new TableSortClass(); pTableSort.Table = pTable; pTableSort.Fields = currentFieldName; pTableSort.set_Ascending(currentFieldName, true); pTableSort.set_CaseSensitive(currentFieldName, true); pTableSort.Sort(null);//排序 ICursor pCursor = pTableSort.Rows; //字段统计 IDataStatistics pDataStatistics = new DataStatisticsClass(); pDataStatistics.Cursor = pCursor; pDataStatistics.Field = currentFieldName; System.Collections.IEnumerator pEnumeratorUniqueValues = pDataStatistics.UniqueValues; //唯一值枚举 int uniqueValueCount = pDataStatistics.UniqueValueCount; //唯一值的个数 this.listBoxValues.Items.Clear(); string currentValue = null; pEnumeratorUniqueValues.Reset(); if (pFieldType == esriFieldType.esriFieldTypeString) { while (pEnumeratorUniqueValues.MoveNext()) { currentValue = pEnumeratorUniqueValues.Current.ToString(); this.listBoxValues.Items.Add("'" + currentValue + "'"); } } else { while (pEnumeratorUniqueValues.MoveNext()) { currentValue = pEnumeratorUniqueValues.Current.ToString(); this.listBoxValues.Items.Add(currentValue); } } } catch (Exception ex) { MessageBox.Show(ex.Message); } }
private void CreateRoadSplitsTable(string inputRdmsTable, string outputFileGdbPath, IGPMessages messages, ITrackCancel trackcancel) { // Open the Rdms table and find all the fields we need Type factoryType = Type.GetTypeFromProgID("esriDataSourcesGDB.FileGDBWorkspaceFactory"); var wsf = Activator.CreateInstance(factoryType) as IWorkspaceFactory; var fws = wsf.OpenFromFile(outputFileGdbPath, 0) as IFeatureWorkspace; ITable rdmsTable = fws.OpenTable(inputRdmsTable); int seqNumberField = rdmsTable.FindField("SEQ_NUMBER"); int linkIDFieldOnRdms = rdmsTable.FindField("LINK_ID"); int manLinkIDField = rdmsTable.FindField("MAN_LINKID"); int condIDFieldOnRdms = rdmsTable.FindField("COND_ID"); int endOfLkFieldOnRdms = rdmsTable.FindField("END_OF_LK"); // Open the Streets feature class and get its feature class ID IFeatureClass inputLineFeatures = fws.OpenFeatureClass(StreetsFCName); int streetsFCID = inputLineFeatures.FeatureClassID; // Define the fields for the RoadSplits table var ocd = new ObjectClassDescriptionClass() as IObjectClassDescription; var fieldsEdit = ocd.RequiredFields as IFieldsEdit; IFieldEdit field; // Add the anchor edge fields to the table field = new FieldClass(); field.Name_2 = "EdgeFCID"; field.Type_2 = esriFieldType.esriFieldTypeInteger; fieldsEdit.AddField(field); field = new FieldClass(); field.Name_2 = "EdgeFID"; field.Type_2 = esriFieldType.esriFieldTypeInteger; fieldsEdit.AddField(field); field = new FieldClass(); field.Name_2 = "EdgeFrmPos"; field.Type_2 = esriFieldType.esriFieldTypeDouble; fieldsEdit.AddField(field); field = new FieldClass(); field.Name_2 = "EdgeToPos"; field.Type_2 = esriFieldType.esriFieldTypeDouble; fieldsEdit.AddField(field); // Add the branch edge fields to the table for (int i = 0; i < 3; i++) { field = new FieldClass(); field.Name_2 = "Branch" + i + "FCID"; field.Type_2 = esriFieldType.esriFieldTypeInteger; fieldsEdit.AddField(field); field = new FieldClass(); field.Name_2 = "Branch" + i + "FID"; field.Type_2 = esriFieldType.esriFieldTypeInteger; fieldsEdit.AddField(field); field = new FieldClass(); field.Name_2 = "Branch" + i + "FrmPos"; field.Type_2 = esriFieldType.esriFieldTypeDouble; fieldsEdit.AddField(field); field = new FieldClass(); field.Name_2 = "Branch" + i + "ToPos"; field.Type_2 = esriFieldType.esriFieldTypeDouble; fieldsEdit.AddField(field); } // Check the fields and create the RoadSplits table var fieldChk = new FieldCheckerClass() as IFieldChecker; IEnumFieldError enumFieldErr = null; IFields validatedFields = null; fieldChk.ValidateWorkspace = fws as IWorkspace; fieldChk.Validate(fieldsEdit as IFields, out enumFieldErr, out validatedFields); var roadSplitsTable = fws.CreateTable(RoadSplitsTableName, validatedFields, ocd.InstanceCLSID, ocd.ClassExtensionCLSID, "") as ITable; // Find all the fields int EdgeFCIDFI = roadSplitsTable.FindField("EdgeFCID"); int EdgeFIDFI = roadSplitsTable.FindField("EdgeFID"); int EdgeFrmPosFI = roadSplitsTable.FindField("EdgeFrmPos"); int EdgeToPosFI = roadSplitsTable.FindField("EdgeToPos"); int Branch0FCIDFI = roadSplitsTable.FindField("Branch0FCID"); int Branch0FIDFI = roadSplitsTable.FindField("Branch0FID"); int Branch0FrmPosFI = roadSplitsTable.FindField("Branch0FrmPos"); int Branch0ToPosFI = roadSplitsTable.FindField("Branch0ToPos"); int Branch1FCIDFI = roadSplitsTable.FindField("Branch1FCID"); int Branch1FIDFI = roadSplitsTable.FindField("Branch1FID"); int Branch1FrmPosFI = roadSplitsTable.FindField("Branch1FrmPos"); int Branch1ToPosFI = roadSplitsTable.FindField("Branch1ToPos"); int Branch2FCIDFI = roadSplitsTable.FindField("Branch2FCID"); int Branch2FIDFI = roadSplitsTable.FindField("Branch2FID"); int Branch2FrmPosFI = roadSplitsTable.FindField("Branch2FrmPos"); int Branch2ToPosFI = roadSplitsTable.FindField("Branch2ToPos"); // Fetch all line features referenced by the input Rdms table. We do the // "join" this hard way to support all data sources in the sample. // Also, for large numbers of special explications, this strategy of fetching all // related features and holding them in RAM could be a problem. To fix // this, one could process the input records from the Rdms table in batches. System.Collections.Hashtable lineFeaturesList = SignpostUtilities.FillFeatureCache(rdmsTable, linkIDFieldOnRdms, manLinkIDField, inputLineFeatures, "LINK_ID", trackcancel); // Create insert cursor and row buffer for output ICursor tableInsertCursor = roadSplitsTable.Insert(true); IRowBuffer tableBuffer = roadSplitsTable.CreateRowBuffer(); IRow row = tableBuffer as IRow; // Create input cursor for the Rdms table we are importing ITableSort tableSort = new TableSortClass(); tableSort.Fields = "LINK_ID, COND_ID, SEQ_NUMBER"; tableSort.set_Ascending("LINK_ID", true); tableSort.set_Ascending("COND_ID", true); tableSort.set_Ascending("SEQ_NUMBER", true); tableSort.QueryFilter = null; tableSort.Table = rdmsTable; tableSort.Sort(null); ICursor inputCursor = tableSort.Rows; IRow inputTableRow = inputCursor.NextRow(); if (inputTableRow == null) return; // if Rdms table is empty, there's nothing to do // these are initialized to prevent uninitialized variable compiler error SignpostUtilities.FeatureData linkFeatureData = new SignpostUtilities.FeatureData(-1, null); SignpostUtilities.FeatureData manLinkFeatureData = new SignpostUtilities.FeatureData(-1, null); ICurve fromEdgeCurve, toEdgeCurve; IPoint fromEdgeStart, fromEdgeEnd, toEdgeStart, toEdgeEnd; double fromEdgeFromPos = 0.0; double fromEdgeToPos = 1.0; double toEdgeFromPos = 0.0; double toEdgeToPos = 1.0; long currentLinkID = Convert.ToInt64(inputTableRow.get_Value(linkIDFieldOnRdms)); long manLinkID = Convert.ToInt64(inputTableRow.get_Value(manLinkIDField)); try { linkFeatureData = (SignpostUtilities.FeatureData)lineFeaturesList[currentLinkID]; manLinkFeatureData = (SignpostUtilities.FeatureData)lineFeaturesList[manLinkID]; // To set from and to position in the output table, we need see where and // if the two edge features connect to figure out their digitized direction. fromEdgeCurve = linkFeatureData.feature as ICurve; toEdgeCurve = manLinkFeatureData.feature as ICurve; fromEdgeStart = fromEdgeCurve.FromPoint; fromEdgeEnd = fromEdgeCurve.ToPoint; toEdgeStart = toEdgeCurve.FromPoint; toEdgeEnd = toEdgeCurve.ToPoint; // flip the from edge? if (TurnGeometryUtilities.EqualPoints(fromEdgeStart, toEdgeStart) || TurnGeometryUtilities.EqualPoints(fromEdgeStart, toEdgeEnd)) { fromEdgeFromPos = 1.0; fromEdgeToPos = 0.0; } // flip the to edge? if (TurnGeometryUtilities.EqualPoints(toEdgeEnd, fromEdgeStart) || TurnGeometryUtilities.EqualPoints(toEdgeEnd, fromEdgeEnd)) { toEdgeFromPos = 1.0; toEdgeToPos = 0.0; } // set the field values in the buffer tableBuffer.set_Value(EdgeFCIDFI, streetsFCID); tableBuffer.set_Value(EdgeFIDFI, linkFeatureData.OID); tableBuffer.set_Value(EdgeFrmPosFI, fromEdgeFromPos); tableBuffer.set_Value(EdgeToPosFI, fromEdgeToPos); tableBuffer.set_Value(Branch0FCIDFI, streetsFCID); tableBuffer.set_Value(Branch0FIDFI, manLinkFeatureData.OID); tableBuffer.set_Value(Branch0FrmPosFI, toEdgeFromPos); tableBuffer.set_Value(Branch0ToPosFI, toEdgeToPos); tableBuffer.set_Value(Branch1FCIDFI, null); tableBuffer.set_Value(Branch1FIDFI, null); tableBuffer.set_Value(Branch1FrmPosFI, null); tableBuffer.set_Value(Branch1ToPosFI, null); tableBuffer.set_Value(Branch2FCIDFI, null); tableBuffer.set_Value(Branch2FIDFI, null); tableBuffer.set_Value(Branch2FrmPosFI, null); tableBuffer.set_Value(Branch2ToPosFI, null); } catch { messages.AddWarning("Line feature not found for explication with from ID: " + Convert.ToString(currentLinkID, System.Globalization.CultureInfo.InvariantCulture) + ", To ID: " + Convert.ToString(manLinkID, System.Globalization.CultureInfo.InvariantCulture)); } long previousLinkID = currentLinkID; int nextBranch = 1; while ((inputTableRow = inputCursor.NextRow()) != null) { currentLinkID = Convert.ToInt64(inputTableRow.get_Value(linkIDFieldOnRdms)); manLinkID = Convert.ToInt64(inputTableRow.get_Value(manLinkIDField)); try { linkFeatureData = (SignpostUtilities.FeatureData)lineFeaturesList[currentLinkID]; manLinkFeatureData = (SignpostUtilities.FeatureData)lineFeaturesList[manLinkID]; } catch { messages.AddWarning("Line feature not found for explication with from ID: " + Convert.ToString(currentLinkID, System.Globalization.CultureInfo.InvariantCulture) + ", To ID: " + Convert.ToString(manLinkID, System.Globalization.CultureInfo.InvariantCulture)); continue; } // To set from and to position in the output table, we need see where and // if the two edge features connect to figure out their digitized direction. fromEdgeCurve = linkFeatureData.feature as ICurve; toEdgeCurve = manLinkFeatureData.feature as ICurve; fromEdgeStart = fromEdgeCurve.FromPoint; fromEdgeEnd = fromEdgeCurve.ToPoint; toEdgeStart = toEdgeCurve.FromPoint; toEdgeEnd = toEdgeCurve.ToPoint; fromEdgeFromPos = 0.0; fromEdgeToPos = 1.0; toEdgeFromPos = 0.0; toEdgeToPos = 1.0; // flip the from edge? if (TurnGeometryUtilities.EqualPoints(fromEdgeStart, toEdgeStart) || TurnGeometryUtilities.EqualPoints(fromEdgeStart, toEdgeEnd)) { fromEdgeFromPos = 1.0; fromEdgeToPos = 0.0; } // flip the to edge? if (TurnGeometryUtilities.EqualPoints(toEdgeEnd, fromEdgeStart) || TurnGeometryUtilities.EqualPoints(toEdgeEnd, fromEdgeEnd)) { toEdgeFromPos = 1.0; toEdgeToPos = 0.0; } // set the field values in the buffer if (previousLinkID == currentLinkID) { switch (nextBranch) { case 1: tableBuffer.set_Value(Branch1FCIDFI, streetsFCID); tableBuffer.set_Value(Branch1FIDFI, manLinkFeatureData.OID); tableBuffer.set_Value(Branch1FrmPosFI, toEdgeFromPos); tableBuffer.set_Value(Branch1ToPosFI, toEdgeToPos); nextBranch = 2; break; case 2: tableBuffer.set_Value(Branch2FCIDFI, streetsFCID); tableBuffer.set_Value(Branch2FIDFI, manLinkFeatureData.OID); tableBuffer.set_Value(Branch2FrmPosFI, toEdgeFromPos); tableBuffer.set_Value(Branch2ToPosFI, toEdgeToPos); nextBranch = 3; break; case 3: messages.AddWarning("There are more than three road splits for From ID: " + Convert.ToString(currentLinkID, System.Globalization.CultureInfo.InvariantCulture)); nextBranch = 4; break; case 4: // do nothing here, as there's no need to repeat the warning message. break; } } else { // write out the previous buffered row... tableInsertCursor.InsertRow(tableBuffer); // ...and then set field values in the fresh buffer tableBuffer.set_Value(EdgeFCIDFI, streetsFCID); tableBuffer.set_Value(EdgeFIDFI, linkFeatureData.OID); tableBuffer.set_Value(EdgeFrmPosFI, fromEdgeFromPos); tableBuffer.set_Value(EdgeToPosFI, fromEdgeToPos); tableBuffer.set_Value(Branch0FCIDFI, streetsFCID); tableBuffer.set_Value(Branch0FIDFI, manLinkFeatureData.OID); tableBuffer.set_Value(Branch0FrmPosFI, toEdgeFromPos); tableBuffer.set_Value(Branch0ToPosFI, toEdgeToPos); tableBuffer.set_Value(Branch1FCIDFI, null); tableBuffer.set_Value(Branch1FIDFI, null); tableBuffer.set_Value(Branch1FrmPosFI, null); tableBuffer.set_Value(Branch1ToPosFI, null); tableBuffer.set_Value(Branch2FCIDFI, null); tableBuffer.set_Value(Branch2FIDFI, null); tableBuffer.set_Value(Branch2FrmPosFI, null); tableBuffer.set_Value(Branch2ToPosFI, null); nextBranch = 1; } previousLinkID = currentLinkID; } // Write out the final row and flush tableInsertCursor.InsertRow(tableBuffer); tableInsertCursor.Flush(); }
public azgsSqlDatabaseChooser() { InitializeComponent(); // Populate the listbox // Build a DataTable to bind to the listbox control DataTable projectTable = new DataTable(); DataColumn projName = new DataColumn(); projName.ColumnName = "ProjectName"; projName.DataType = typeof(string); DataColumn dbName = new DataColumn(); dbName.ColumnName = "DatabaseName"; dbName.DataType = typeof(string); projectTable.Columns.Add(projName); projectTable.Columns.Add(dbName); // Populate the DataTable - Right now this is pinging a DB on malachite IPropertySet connectionProperties = new PropertySetClass(); connectionProperties.SetProperty("SERVER", "malachite\\azgsgeodatabases"); connectionProperties.SetProperty("INSTANCE", "sde:sqlserver:malachite\\azgsgeodatabases"); connectionProperties.SetProperty("DATABASE", "AzgsIndex"); connectionProperties.SetProperty("AUTHENTICATION_MODE", "OSA"); connectionProperties.SetProperty("VERSION", "dbo.Default"); try { IWorkspaceFactory wsFact = new SdeWorkspaceFactoryClass(); IWorkspace theWs = wsFact.Open(connectionProperties, 0); // Open the table in the repository database ITable ProjectListingsTable = commonFunctions.OpenTable(theWs, "ProjectDatabases"); // Get all the records into a sorted cursor ITableSort projSorter = new TableSortClass(); projSorter.Table = ProjectListingsTable; projSorter.QueryFilter = null; projSorter.Fields = "ProjectName"; projSorter.set_Ascending("ProjectName", true); projSorter.Sort(null); ICursor projCur = projSorter.Rows; //ProjectListingsTable.Search(null, false); // Loop through the cursor and add records to the DataTable IRow projRow = projCur.NextRow(); while (projRow != null) { projectTable.Rows.Add((String)projRow.get_Value(ProjectListingsTable.FindField("ProjectName")), (String)projRow.get_Value(ProjectListingsTable.FindField("DatabaseName"))); projRow = projCur.NextRow(); } System.Runtime.InteropServices.Marshal.ReleaseComObject(projCur); // Bind the DataTable to the control this.listProjects.DataSource = projectTable; this.listProjects.DisplayMember = "ProjectName"; this.listProjects.ValueMember = "DatabaseName"; this.listProjects.SelectedItem = null; this.listVersions.DataSource = null; } catch (Exception ex) { MessageBox.Show(ex.Message + "\n\n" + ex.StackTrace); return; } }
/// <summary> /// 按下"添加所有值"按钮后,让table按当前字段的值进行排序,并把信息添加到listView里面 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnUniValueAddAllValues_Click(object sender, EventArgs e) { try { string currentFieldName = this.cbbUniValueField.Text; //当前字段名 string currentFieldType = this.lsvFields.FindItemWithText(currentFieldName).SubItems[2].Text; //当前字段类型 bool currentTypeIsNumeric = false; //判断当前字段类型是否为数字类型 if (currentFieldType == "Short Integer" || currentFieldType == "Long Integer" || currentFieldType == "Float" || currentFieldType == "Double") { currentTypeIsNumeric = true; } this.lsvUniqueValue.Items.Clear(); //对Table中当前字段进行排序,把结果赋给Cursor ITable pTable = this.pLayer as ITable; ITableSort pTableSort = new TableSortClass(); pTableSort.Table = pTable; pTableSort.Fields = currentFieldName; pTableSort.set_Ascending(currentFieldName, true); pTableSort.set_CaseSensitive(currentFieldName, true); pTableSort.Sort(null);//排序 ICursor pCursor = pTableSort.Rows; //字段统计 IDataStatistics pDataStatistics = new DataStatisticsClass(); pDataStatistics.Cursor = pCursor; pDataStatistics.Field = currentFieldName; System.Collections.IEnumerator pEnumeratorUniqueValues = pDataStatistics.UniqueValues; //唯一值枚举 int uniqueValueCount = pDataStatistics.UniqueValueCount; //唯一值的个数 //table中当前字段有值(不为null)的row的个数,并把信息添加到listView的第一行 IQueryFilter pQueryFilter = new QueryFilterClass(); pQueryFilter.AddField(currentFieldName); int valueSum = pTable.RowCount(pQueryFilter); this.lsvUniqueValue.Items.Add(currentFieldName); this.lsvUniqueValue.Items[0].SubItems.Add(currentFieldName); this.lsvUniqueValue.Items[0].SubItems.Add(valueSum.ToString()); //循环把信息添加到listView里 int i = 1; //注意!是从1开始,因为第一行已经被占用 string currentValue = null; //指示当前的值 //IDataStatistics pUniValueStatistics = new DataStatisticsClass(); int currentValueCount; for (pEnumeratorUniqueValues.Reset(); pEnumeratorUniqueValues.MoveNext(); i++) { currentValue = pEnumeratorUniqueValues.Current.ToString();//当前值 this.lsvUniqueValue.Items.Add(currentValue); this.lsvUniqueValue.Items[i].SubItems.Add(currentValue); //需要这个if的原因是SQL语句中数字和非数字的写法不一样 if (currentTypeIsNumeric) { pQueryFilter.WhereClause = "\"" + currentFieldName + "\"" + " = " + currentValue; } else { pQueryFilter.WhereClause = "\"" + currentFieldName + "\"" + " = " + "'" + currentValue + "'"; } currentValueCount = pTable.RowCount(pQueryFilter);//table中该字段是当前值的row的个数 this.lsvUniqueValue.Items[i].SubItems.Add(currentValueCount.ToString()); } } catch (Exception ex) { MessageBox.Show(ex.Message); } }