public IEnumInvalidObject ConvertTable(IDatasetName idatasetName_0, IQueryFilter iqueryFilter_0, IDatasetName idatasetName_1, IFields ifields_0, string string_0, int int_0, int int_1) { IEnumFieldError enumFieldError; IFields field; string str; IEnumInvalidObject enumInvalidObject = null; IFieldChecker fieldCheckerClass = new FieldChecker(); IWorkspace workspace = (idatasetName_1.WorkspaceName as IName).Open() as IWorkspace; fieldCheckerClass.ValidateWorkspace = workspace; fieldCheckerClass.Validate(ifields_0, out enumFieldError, out field); fieldCheckerClass.ValidateTableName(idatasetName_1.Name, out str); string str1 = str; ITable table = null; table = (workspace as IFeatureWorkspace).CreateTable(str1, field, null, null, string_0); ITable table1 = (idatasetName_0 as IName).Open() as ITable; ICursor cursor = table1.Search(iqueryFilter_0, false); int num = 0; ICursor cursor1 = table.Insert(true); IRow row = cursor.NextRow(); while (row != null) { IRowBuffer rowBuffer = table.CreateRowBuffer(); try { this.method_1(cursor1, rowBuffer, field, row); } catch (Exception exception) { Logger.Current.Error("", exception, ""); } num++; if (num == int_0) { num = 0; cursor1.Flush(); } row = cursor.NextRow(); if (this.ifeatureProgress_StepEventHandler_0 == null) { continue; } this.ifeatureProgress_StepEventHandler_0(); } if (num > 0) { cursor1.Flush(); } ComReleaser.ReleaseCOMObject(cursor); ComReleaser.ReleaseCOMObject(cursor1); return(enumInvalidObject); }
/// <summary> /// Copies the rows from the <paramref name="data" /> table to the source table. /// </summary> /// <param name="source">The source.</param> /// <param name="data">The data that will be copied.</param> /// <param name="filter">The filter that will be used prior to copying the data.</param> /// <param name="progress">The progress callback.</param> /// <returns> /// Returns a <see cref="List{T}" /> representing the object ids of the records loaded. /// </returns> /// <remarks> /// Assumes that the source and data table have the same schema. /// </remarks> public static List <int> Load(this ITable source, ITable data, IQueryFilter filter = null, IFeatureProgress progress = null) { if (progress != null) { progress.FeatureClassName = ((IDataset)source).Name; progress.MinFeatures = 0; progress.MaxFeatures = data.RowCount(filter); progress.Position = 0; progress.StepValue = 1; } var oids = new List <int>(); var fields = source.Fields.ToDictionary(f => f.Editable); using (ComReleaser cr = new ComReleaser()) { ICursor cursor = data.Search(filter, false); cr.ManageLifetime(cursor); ICursor insert = source.Insert(true); cr.ManageLifetime(insert); var buffer = source.CreateRowBuffer(); foreach (var rows in cursor.AsEnumerable().Batch(1000)) { foreach (var row in rows) { foreach (var field in fields) { buffer.Update(field.Value, row.Value[field.Value], false); } var oid = (int)insert.InsertRow(buffer); oids.Add(oid); if (progress != null) { progress.Step(); } } insert.Flush(); } insert.Flush(); } return(oids); }
public void LogRecord(ITable table, int ID, int index, double X_From, double Y_From, double M_From, double X_To, double Y_To, double M_To) { ICursor InsertCursor = table.Insert(false); try { IRowBuffer rowBuffer = table.CreateRowBuffer(); rowBuffer.set_Value(rowBuffer.Fields.FindField("ID"), ID); rowBuffer.set_Value(rowBuffer.Fields.FindField("index"), index); rowBuffer.set_Value(rowBuffer.Fields.FindField("X_From"), X_From); rowBuffer.set_Value(rowBuffer.Fields.FindField("Y_From"), Y_From); rowBuffer.set_Value(rowBuffer.Fields.FindField("M_From"), M_From); rowBuffer.set_Value(rowBuffer.Fields.FindField("X_To"), X_To); rowBuffer.set_Value(rowBuffer.Fields.FindField("Y_To"), Y_To); rowBuffer.set_Value(rowBuffer.Fields.FindField("M_To"), M_To); InsertCursor.InsertRow(rowBuffer); InsertCursor.Flush(); } catch (Exception ex) { throw; } finally { ESRI.ArcGIS.ADF.ComReleaser.ReleaseCOMObject(InsertCursor); } }
public static ITable SaveToWorkspace(this ICursor icursor, IFeatureWorkspace workspace, string layername) { UID uid = new UID(); uid.Value = "esriGeoDatabase.Object"; IFields newFields = new FieldsClass(); newFields = icursor.Fields; ITable newtable = workspace.CreateTable(layername, newFields, uid, null, ""); ICursor cursor = newtable.Insert(true); IRowBuffer prowbuffer = newtable.CreateRowBuffer(); IRow irow = null; while (null != (irow = icursor.NextRow())) { for (int i = 0; i < newtable.Fields.FieldCount; i++) { string name = irow.Value[i].ToString(); bool editfield = newtable.Fields.get_Field(i).Editable; if (editfield) { prowbuffer.Value[i] = irow.Value[i]; } } cursor.InsertRow(prowbuffer); } cursor.Flush(); return(newtable); }
private void Flush() { _insertCursor?.Flush(); _pendingInserts = 0; _pendingPointCount = 0; }
public int GetNextIdValue(string ClassName) { // ---------------------------------------------------------------------------------------------------------------------------- // ---------------------------------------------------------------------------------------------------------------------------- // By the way, it's important to remember that if the SysInfo table gets versioned, table identifiers are going to get botched. // Do not version the SysInfo table. // ArcObjects is happy to manipulate it outside an edit session // ---------------------------------------------------------------------------------------------------------------------------- // ---------------------------------------------------------------------------------------------------------------------------- // Create a query to find the existing Max ID IQueryFilter QF = new QueryFilterClass(); QF.WhereClause = "Sub = '" + ClassName + "' AND Pred = 'MaxID'"; // Perform the query ICursor readCursor = m_SysInfo.Search(QF, false); IRow readRow = readCursor.NextRow(); // If a record exists, update it to the new value and return that new value, otherwise, new row if (readRow == null) { // No record exists - create a new row and assign #1 IRowBuffer newRow = m_SysInfo.CreateRowBuffer(); newRow.set_Value(m_SysInfo.FindField("Sub"), ClassName); newRow.set_Value(m_SysInfo.FindField("Pred"), "MaxID"); newRow.set_Value(m_SysInfo.FindField("Obj"), 1); // Write the row ICursor writeCursor = m_SysInfo.Insert(true); writeCursor.InsertRow(newRow); writeCursor.Flush(); System.Runtime.InteropServices.Marshal.ReleaseComObject(writeCursor); // Return the ID return(1); } else { // A record exists - return the next value and increment the record string currentMax = (string)readRow.get_Value(m_SysInfo.FindField("Obj")); int newMax = int.Parse(currentMax) + 1; // Update the record ICursor updateCursor = m_SysInfo.Update(QF, false); IRow updateRow = updateCursor.NextRow(); updateRow.set_Value(m_SysInfo.FindField("Obj"), newMax); updateCursor.UpdateRow(updateRow); System.Runtime.InteropServices.Marshal.ReleaseComObject(updateCursor); //Flush failed when editing an SDE workspace where the SysInfo table was not versioned. //It didn't die without the flush in a File Geodatabase, but there was some kind of a hang that slowed ArcMap way down while debugging // may have been unrelated //updateCursor.Flush(); // Return the ID return(newMax); } }
/// <summary> /// Inserts a new record to the controller table /// </summary> /// <remarks> /// This uses a insert cursor WITHOUT buffer. Do not use for large inserts. /// </remarks> /// <exception cref="RepositoryException"></exception> /// <param name="toBeInserted">IObjectWrapper</param> public void Insert(T toBeInserted) { // this is not finished ITable table = this.GetTable; if (table == null) { throw new RepositoryException( "It's not possible to get the controller underlying table.", GetWorkspaceDefinition, GetTableDefinition, IsBeingEdited); } ICursor cursor = null; try { cursor = table.Insert(false); cursor.InsertRow(toBeInserted.UnderlyingObject); cursor.Flush(); } finally { if (cursor != null) { Marshal.ReleaseComObject(cursor); } } }
/// <summary> /// Join Urban-rural Devide Table /// </summary> /// <param name="layer"></param> /// <param name="year"></param> /// <author>Shen Yongyuan</author> /// <date>20091111</date> public static void JoinDevideTable(ILayer layer, int year, string city) { //Add Fields IFieldsEdit allFields = new FieldsClass(); IFieldEdit field1 = new FieldClass(); field1.Name_2 = "ID"; field1.Type_2 = esriFieldType.esriFieldTypeString; allFields.AddField(field1); IFieldEdit field2 = new FieldClass(); field2.Name_2 = Town.Constant.Constant.TmpFieldName; field2.Type_2 = esriFieldType.esriFieldTypeString; allFields.AddField(field2); //Create Table IWorkspaceFactory workspaceFactory = new InMemoryWorkspaceFactoryClass(); IWorkspaceName workspaceName = workspaceFactory.Create("", "Temporary WorkSpace In Memory", null, 0); IFeatureWorkspace workspace = ((IName)workspaceName).Open() as IFeatureWorkspace; ITable table = workspace.CreateTable(Town.Constant.Constant.TmpTableDevide, allFields, null, null, ""); //Import Data IWorkspaceEdit workspaceEdit = workspace as IWorkspaceEdit; workspaceEdit.StartEditing(false); workspaceEdit.StartEditOperation(); ICursor cursor = table.Insert(true); int fldField1 = cursor.Fields.FindField("ID"); int fldField2 = cursor.Fields.FindField(Town.Constant.Constant.TmpFieldName); //Query and Import Dictionary <int, string> devideResult = DataLib.DA_Devide.GetDevideResult(year, city); foreach (KeyValuePair <int, string> d in devideResult) { IRowBuffer buffer = table.CreateRowBuffer(); buffer.set_Value(fldField1, d.Key.ToString()); buffer.set_Value(fldField2, d.Value); cursor.InsertRow(buffer); } cursor.Flush(); workspaceEdit.StartEditOperation(); workspaceEdit.StopEditing(true); System.Runtime.InteropServices.Marshal.ReleaseComObject(cursor); //Join IMemoryRelationshipClassFactory pMemRelFact = new MemoryRelationshipClassFactory(); IFeatureLayer feaLayer = layer as IFeatureLayer; ITable originTable = feaLayer.FeatureClass as ITable; IRelationshipClass pRelClass = pMemRelFact.Open("Join", originTable as IObjectClass, "ID", table as IObjectClass, "ID", "forward", "backward", esriRelCardinality.esriRelCardinalityOneToOne); IDisplayRelationshipClass pDispRC = feaLayer as IDisplayRelationshipClass; pDispRC.DisplayRelationshipClass(null, esriJoinType.esriLeftOuterJoin); pDispRC.DisplayRelationshipClass(pRelClass, esriJoinType.esriLeftOuterJoin); }
private void CopyTableData(ITable sourceTable, ITable targetTable, IDictionary <int, int> filedIndexDictionary) { errorRowCount = 0; using (var comReleaser = new ComReleaser()) { ICursor sourceFeatureCursor = sourceTable.Search(null, false); ICursor targetFeatureCursor = targetTable.Insert(true); comReleaser.ManageLifetime(sourceFeatureCursor); comReleaser.ManageLifetime(targetFeatureCursor); List <int> targeFieldIndexs = filedIndexDictionary.Keys.ToList(); int fieldsLen = targeFieldIndexs.Count; IRow sourceFeature = sourceFeatureCursor.NextRow(); var count = 0; while (sourceFeature != null) { try { IRowBuffer targetFatureBuffer = targetTable.CreateRowBuffer(); for (int i = 0; i < fieldsLen; i++) { var targetIndex = targeFieldIndexs[i]; int sourceIndex = filedIndexDictionary[targeFieldIndexs[i]]; var value = sourceFeature.get_Value(sourceIndex); targetFatureBuffer.set_Value(targetIndex, value); } targetFeatureCursor.InsertRow(targetFatureBuffer); count++; if (count == 1000) { targetFeatureCursor.Flush(); count = 0; } } catch (Exception ex) { errorRowCount++; var message = "字段赋值错误"; // LoggingManager.GetLogger(GetType()).Error(message, ex); } sourceFeature = sourceFeatureCursor.NextRow(); } targetFeatureCursor.Flush(); } }
protected override void OnClick() { string tablePath = Path.Combine(DataPath, @"Geodatabase\ManhattanKS.gdb\ParcelIDs"); string tableName = Path.GetFileName(tablePath); const string searchField = "PID"; Type factoryType = Type.GetTypeFromProgID("esriDataSourcesGDB.FileGDBWorkspaceFactory"); IWorkspaceFactory workspaceFactory = Activator.CreateInstance(factoryType) as IWorkspaceFactory; IWorkspace workspace = workspaceFactory.OpenFromFile(Path.GetDirectoryName(tablePath), 0); IObjectClassDescription objClassDesc = new ObjectClassDescriptionClass(); IFields fields = objClassDesc.RequiredFields; IFieldsEdit fieldsEdit = (IFieldsEdit)fields; IField field = new FieldClass(); IFieldEdit fieldEdit = (IFieldEdit)field; fieldEdit.Name_2 = searchField; fieldEdit.Type_2 = esriFieldType.esriFieldTypeString; fieldEdit.IsNullable_2 = true; fieldEdit.AliasName_2 = searchField; fieldEdit.Editable_2 = true; fieldEdit.Length_2 = 250; fieldsEdit.AddField(field); fields = fieldsEdit; ITable table = CreateTable((IWorkspace2)workspace, tableName, fields); using (ComReleaser releaser = new ComReleaser()) { ICursor cursor = table.Insert(true); releaser.ManageLifetime(cursor); string txtPath = Path.Combine(DataPath, "UniqueValues.txt"); int searchFieldIndex = table.FindField(searchField); IRowBuffer buffer = table.CreateRowBuffer(); using (StreamReader reader = new StreamReader(txtPath)) { string line; while ((line = reader.ReadLine()) != null) { string id = line.Split(new[] { '.', ' ' }, StringSplitOptions.RemoveEmptyEntries)[1]; buffer.Value[searchFieldIndex] = id; cursor.InsertRow(buffer); } cursor.Flush(); } } ((ITableCollection)ArcMap.Document.FocusMap).AddTable(table); ArcMap.Document.UpdateContents(); Marshal.FinalReleaseComObject(table); }
/// <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(); }
/// <summary> /// 将DataTable的数据写入ITable中 /// </summary> /// <param name="dataTable">System.Data.DataTable对象,其字段名与ITable对象的字段名或字段别名一致的数据将写入ITable对象</param> /// <param name="table">ESRI.ArcGIS.Geodatabase.ITable对象</param> public static void DataTable2ITable(DataTable dataTable, ITable table) { //获取在ITable和System.Data.DataTable共有的字段 List <string> exsitFields = new List <string>(); //共有字段的名称 List <int> exsitFieldsIndex = new List <int>(); //共有字段的索引 for (int i = 0; i < table.Fields.FieldCount; i++) { var field = table.Fields.get_Field(i); if (dataTable.Columns.Contains(field.Name)) { exsitFields.Add(field.Name); exsitFieldsIndex.Add(i); } else if (dataTable.Columns.Contains(field.AliasName)) { exsitFields.Add(field.AliasName); exsitFieldsIndex.Add(i); } } //将System.Data.DataTable的数据写入ESRI的ITable中 ICursor cursor = table.Insert(true); IRowBuffer rowBuffer; int rowIndex = 0; try { for (int i = 0; i < dataTable.Rows.Count; i++) { rowBuffer = table.CreateRowBuffer(); rowIndex = i + 1; var dataRow = dataTable.Rows[i]; for (int j = 0; j < exsitFields.Count; j++) { var name = exsitFields[j]; var value = dataRow[name]; if (value == null || value.ToString() == "") { continue; } rowBuffer.set_Value(exsitFieldsIndex[j], value); } cursor.InsertRow(rowBuffer); } cursor.Flush(); } catch (Exception ex) { throw new Exception($"将DataTable的第{rowIndex}行写入“{(table as IDataset)?.Name}”表中时出现错误:{ex.Message}"); } System.Runtime.InteropServices.Marshal.ReleaseComObject(cursor); }
/// <summary> /// 结束编辑时保存当前编辑值 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void dataGrid_CellEndEdit(object sender, DataGridViewCellEventArgs e) { string strFeatureClassName = dataGrid.Tag.ToString(); try { IFeatureWorkspace pFeatureWorkspace = m_Workspace as IFeatureWorkspace; ITable pTable = pFeatureWorkspace.OpenTable("METADATA_LIB"); IQueryFilter pQueryFilter = new QueryFilterClass(); int pIndex = pTable.FindField("数据库名称"); IField pField = pTable.Fields.get_Field(pIndex); switch (pField.Type) { case esriFieldType.esriFieldTypeString: pQueryFilter.WhereClause = pField.Name + " = '" + strFeatureClassName + "'"; break; default: pQueryFilter.WhereClause = pField.Name + " = " + strFeatureClassName; break; } ///获取更新的行 ICursor pCursor = pTable.Update(pQueryFilter, false); IRow pRow = pCursor.NextRow(); while (pRow != null) { if (dataGrid.Rows[e.RowIndex].Cells[0].Value != null) { string strFiledName = dataGrid.Rows[e.RowIndex].Cells[0].Value.ToString(); if (strFiledName != "") { string strFiledValue = ""; if (dataGrid.Rows[e.RowIndex].Cells[e.ColumnIndex].Value != null) { strFiledValue = dataGrid.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString(); } ///更新该行strFiledName 字段值 pRow.set_Value(pRow.Fields.FindField(strFiledName), strFiledValue); pRow.Store(); } } pRow = pCursor.NextRow(); } pCursor.Flush(); System.Runtime.InteropServices.Marshal.ReleaseComObject(pCursor); pCursor = null; } catch { } }
/*************************************************************************** * 函数名:AddTableRecord * 参 数:string:数据库名称,List<string>:数据名称集,List<dynamic>:数据集 * 返回值:int:1:添加成功 * 功 能:向数据库中添加数据记录 ***************************************************************************/ public int AddTableRecord(string tableName, List <dynamic> values) { ITable table = dict[tableName] as ITable; ICursor cursor = table.Insert(true); IRowBuffer pRowBuffer = table.CreateRowBuffer(); for (int i = 1; i <= values.Count; i++) { pRowBuffer.Value[i] = values[i - 1]; } cursor.InsertRow(pRowBuffer); cursor.Flush(); return(1); }
private static void WriteRows([NotNull] ITable table, [NotNull] IssueStatistics issueStatistics, [NotNull] IIssueStatisticsTableFieldNames fieldNames) { const bool useBuffering = true; ICursor insertCursor = table.Insert(useBuffering); IRowBuffer rowBuffer = table.CreateRowBuffer(); var attributeWriter = new AttributeWriter(table, fieldNames); foreach (IssueGroup issueGroup in issueStatistics.GetIssueGroups()) { attributeWriter.Write(issueGroup, rowBuffer); insertCursor.InsertRow(rowBuffer); } insertCursor.Flush(); }
public static ITable CreateTimeZoneTable(string outputFileGdbPath, string timeZone) { // start with the initial set of required fields for a table IObjectClassDescription ocDescription = new ObjectClassDescriptionClass(); IFieldsEdit outFields = ocDescription.RequiredFields as IFieldsEdit; // add the MSTIMEZONE field to the table IFieldEdit field = new FieldClass(); field.Name_2 = "MSTIMEZONE"; field.Type_2 = esriFieldType.esriFieldTypeString; field.Length_2 = 50; outFields.AddField(field); // open the file geodatabase Type gdbFactoryType = Type.GetTypeFromProgID("esriDataSourcesGDB.FileGDBWorkspaceFactory"); var gdbWSF = Activator.CreateInstance(gdbFactoryType) as IWorkspaceFactory; var gdbFWS = gdbWSF.OpenFromFile(outputFileGdbPath, 0) as IFeatureWorkspace; // create the table ITable t = gdbFWS.CreateTable("TimeZones", outFields, ocDescription.InstanceCLSID, ocDescription.ClassExtensionCLSID, ""); // create a record in the table with the specified time zone ICursor cur = t.Insert(true); IRowBuffer buff = t.CreateRowBuffer(); buff.set_Value(t.FindField("MSTIMEZONE"), timeZone); cur.InsertRow(buff); // Flush any outstanding writes to the table cur.Flush(); return(t); }
public void Flush(bool releaseInsertCursor) { if (_insertCursor == null) { return; } _insertCursor.Flush(); InsertedRowCount = 0; _bufferedPointCount = 0; if (releaseInsertCursor) { if (_rowBuffer != null) { Marshal.ReleaseComObject(_rowBuffer); } Marshal.ReleaseComObject(_insertCursor); _insertCursor = null; _rowBuffer = null; } }
private void FlushCursor(bool noFlush, ref ICursor cursor) { try { if (!noFlush && !IsHluWorkspaceSDE && (cursor != null)) { cursor.Flush(); } } finally { Marshal.ReleaseComObject(cursor); cursor = null; } }
private void btnApply_Click(object sender, EventArgs e) { try { //Declare variables clsSnippet pSnippet = new clsSnippet(); string strLayerName = cboSourceLayer.Text; int intLIndex = pSnippet.GetIndexNumberFromLayerName(pActiveView, strLayerName); ILayer pLayer = mForm.axMapControl1.get_Layer(intLIndex); IFeatureLayer pFLayer = pLayer as IFeatureLayer; IFeatureClass pFClass = pFLayer.FeatureClass; string strOriRenderField = cboValueField.Text; string strUncernRenderField = CboUField.Text; string strConLevelField = nudConfidenceLevel.Value.ToString(); if (strOriRenderField == "" || strUncernRenderField == "") { MessageBox.Show("Plese choose field names"); return; } //Find Fields ITable pTable = (ITable)pFClass; int intOriIdx = pTable.FindField(strOriRenderField); int intUncernIdx = pTable.FindField(strUncernRenderField); //Create Geofeature Layer IGeoFeatureLayer pGeofeatureLayer = null; if (chkNewLayer.Checked == true) { IFeatureLayer pflOutput = new FeatureLayerClass(); pflOutput.FeatureClass = pFClass; pflOutput.Name = txtNewLayer.Text; pflOutput.Visible = true; pGeofeatureLayer = (IGeoFeatureLayer)pflOutput; } else { pGeofeatureLayer = (IGeoFeatureLayer)pFLayer; } //Calculate confidence levels Chart pChart = new Chart(); double dblConInstance = pChart.DataManipulator.Statistics.InverseNormalDistribution(Convert.ToDouble(nudConfidenceLevel.Value) / 100); if (tcUncer.SelectedIndex == 0) //Proportional symbol composite layers { double dblMinPtSize = Convert.ToDouble(nudSymbolSize.Value); //Find max value at attribute to set to initial value for finding Min value at composite symbols IField pOriField = pTable.Fields.get_Field(intOriIdx); ICursor pCursor = pTable.Search(null, false); IDataStatistics pDataStat = new DataStatisticsClass(); pDataStat.Field = pOriField.Name; pDataStat.Cursor = pCursor; IStatisticsResults pStatResults = pDataStat.Statistics; double dblMinValue = pStatResults.Maximum; pCursor.Flush(); pCursor = pTable.Search(null, false); IRow pRow = pCursor.NextRow(); double dblValue = 0; //Cacluate Min and Max value based on the confidence intervals //Min while (pRow != null) { dblValue = Convert.ToDouble(pRow.get_Value(intOriIdx)) - (Convert.ToDouble(pRow.get_Value(intUncernIdx)) * dblConInstance); if (dblValue < dblMinValue) { dblMinValue = dblValue; } pRow = pCursor.NextRow(); } //Max pCursor.Flush(); double dblMaxValue = 0; pCursor = pTable.Search(null, false); pRow = pCursor.NextRow(); dblValue = 0; //Cacluate Min and Max value based on the confidence intervals while (pRow != null) { dblValue = Convert.ToDouble(pRow.get_Value(intOriIdx)) + (Convert.ToDouble(pRow.get_Value(intUncernIdx)) * dblConInstance); if (dblValue > dblMaxValue) { dblMaxValue = dblValue; } pRow = pCursor.NextRow(); } //To adjust min value to 1, if the min value is zero double dbladjuctMinvalue = 0; if (dblMinValue <= 0) { dbladjuctMinvalue = (0 - dblMinValue) + 1; dblMinValue = dblMinValue + dbladjuctMinvalue; } //Loading uncertainty proportional symbol renderer IDisplay pDisplay = pActiveView.ScreenDisplay; UncernVis.BivariateRenderer.IPropCompositeRenderer pUnProprotional = new UncernVis.BivariateRenderer.PropCompositeRenderer(); pUnProprotional.m_dblMinPtSize = dblMinPtSize; pUnProprotional.m_dblMinValue = dblMinValue; pUnProprotional.m_dblMaxValue = dblMaxValue; pUnProprotional.m_dblOutlineSize = Convert.ToDouble(nudLinewidth.Value); pUnProprotional.m_dblAdjustedMinValue = dbladjuctMinvalue; IRgbColor pSymbolRgb = new RgbColorClass(); pSymbolRgb.Red = picSymbolColor.BackColor.R; pSymbolRgb.Green = picSymbolColor.BackColor.G; pSymbolRgb.Blue = picSymbolColor.BackColor.B; IRgbColor pLineRgb = new RgbColorClass(); pLineRgb.Red = picLineColor.BackColor.R; pLineRgb.Green = picLineColor.BackColor.G; pLineRgb.Blue = picLineColor.BackColor.B; pUnProprotional.m_pLineRgb = pLineRgb; pUnProprotional.m_pSymbolRgb = pSymbolRgb; pUnProprotional.m_strUncernRenderField = strUncernRenderField; pUnProprotional.m_strOriRenderField = strOriRenderField; pUnProprotional.m_dblConInstance = dblConInstance; pUnProprotional.m_pGeometryTypes = pFClass.ShapeType; //Create Legend pUnProprotional.CreateLegend(); pGeofeatureLayer.Renderer = (IFeatureRenderer)pUnProprotional; if (chkNewLayer.Checked == true) { mForm.axMapControl1.ActiveView.FocusMap.AddLayer(pGeofeatureLayer); } else { pFLayer = (IFeatureLayer)pGeofeatureLayer; } } else if (tcUncer.SelectedIndex == 1) // Chart composite symbols { double dblChartWidth = Convert.ToDouble(nudChartWidth.Value); double dblChartSize = Convert.ToDouble(nudChartSize.Value); double dblThickness = Convert.ToDouble(nudThickness.Value); //Cacluate Max value based on the confidence intervals ICursor pCursor = (ICursor)pFClass.Search(null, false); IRow pRow = pCursor.NextRow(); double dblMaxValue = 0; double dblTempValue = 0; double dblMaxEstimate = 0; double dblMaxUncern = 0; double dblTempEstimate = 0; double dblTempUncern = 0; while (pRow != null) { dblTempEstimate = Convert.ToDouble(pRow.get_Value(intOriIdx)); dblTempUncern = Convert.ToDouble(pRow.get_Value(intUncernIdx)) * dblConInstance; dblTempValue = dblTempEstimate + dblTempUncern; if (dblTempValue > dblMaxValue) { dblMaxValue = dblTempValue; dblMaxEstimate = dblTempEstimate; dblMaxUncern = dblTempUncern; } pRow = pCursor.NextRow(); } pCursor.Flush(); //IFeatureCursor pFCursor = pGeofeatureLayer.Search(null, true); IChartCompositeRenderer pChartCompositeRenderer = new ChartCompositeRenderer(); pChartCompositeRenderer.m_dblConInstance = dblConInstance; pChartCompositeRenderer.m_dblMaxValue = dblMaxValue; pChartCompositeRenderer.m_bln3Dfeature = chk3D.Checked; pChartCompositeRenderer.m_strOriRenderField = strOriRenderField; pChartCompositeRenderer.m_strUncernRenderField = strUncernRenderField; pChartCompositeRenderer.m_dblMaxEstimate = dblMaxEstimate; pChartCompositeRenderer.m_dblMaxUncern = dblMaxUncern; pChartCompositeRenderer.m_dblBarWidth = dblChartWidth; pChartCompositeRenderer.m_dblBarSize = dblChartSize; pChartCompositeRenderer.m_dblThickness = dblThickness; pChartCompositeRenderer.CreateLegend(); pGeofeatureLayer.Renderer = pChartCompositeRenderer as IFeatureRenderer; if (chkNewLayer.Checked == true) { mForm.axMapControl1.ActiveView.FocusMap.AddLayer(pGeofeatureLayer); } else { pFLayer = (IFeatureLayer)pGeofeatureLayer; } } else if (tcUncer.SelectedIndex == 2) //For Line Symbol { double dblMinPtSize = Convert.ToDouble(nudMinWidth.Value); //Find max value at attribute to set to initial value for finding Min value at composite symbols IField pOriField = pTable.Fields.get_Field(intOriIdx); ICursor pCursor = pTable.Search(null, false); IDataStatistics pDataStat = new DataStatisticsClass(); pDataStat.Field = pOriField.Name; pDataStat.Cursor = pCursor; IStatisticsResults pStatResults = pDataStat.Statistics; double dblMinValue = pStatResults.Maximum; pCursor.Flush(); pCursor = pTable.Search(null, false); IRow pRow = pCursor.NextRow(); double dblValue = 0; //Cacluate Min and Max value based on the confidence intervals //Min while (pRow != null) { dblValue = Convert.ToDouble(pRow.get_Value(intOriIdx)) - (Convert.ToDouble(pRow.get_Value(intUncernIdx)) * dblConInstance); if (dblValue < dblMinValue) { dblMinValue = dblValue; } pRow = pCursor.NextRow(); } //Max pCursor.Flush(); double dblMaxValue = 0; pCursor = pTable.Search(null, false); pRow = pCursor.NextRow(); dblValue = 0; //Cacluate Min and Max value based on the confidence intervals while (pRow != null) { dblValue = Convert.ToDouble(pRow.get_Value(intOriIdx)) + (Convert.ToDouble(pRow.get_Value(intUncernIdx)) * dblConInstance); if (dblValue > dblMaxValue) { dblMaxValue = dblValue; } pRow = pCursor.NextRow(); } //To adjust min value to 1, if the min value is zero double dbladjuctMinvalue = 0; if (dblMinValue <= 0) { dbladjuctMinvalue = (0 - dblMinValue) + 1; dblMinValue = dblMinValue + dbladjuctMinvalue; } //Loading uncertainty proportional symbol renderer IDisplay pDisplay = pActiveView.ScreenDisplay; UncernVis.BivariateRenderer.IPropCompositeRenderer pUnProprotional = new UncernVis.BivariateRenderer.PropCompositeRenderer(); pUnProprotional.m_dblMinPtSize = dblMinPtSize; pUnProprotional.m_dblMinValue = dblMinValue; pUnProprotional.m_dblMaxValue = dblMaxValue; pUnProprotional.m_dblOutlineSize = 0; pUnProprotional.m_dblAdjustedMinValue = dbladjuctMinvalue; IRgbColor pSymbolRgb = pSnippet.getRGB(picLineConColor.BackColor.R, picLineConColor.BackColor.G, picLineConColor.BackColor.B); //pSymbolRgb.Red = picSymbolColor.BackColor.R; //pSymbolRgb.Green = picSymbolColor.BackColor.G; //pSymbolRgb.Blue = picSymbolColor.BackColor.B; IRgbColor pLineRgb = pSnippet.getRGB(picLineCntColor.BackColor.R, picLineCntColor.BackColor.G, picLineCntColor.BackColor.B); //pLineRgb.Red = picLineColor.BackColor.R; //pLineRgb.Green = picLineColor.BackColor.G; //pLineRgb.Blue = picLineColor.BackColor.B; pUnProprotional.m_pLineRgb = pLineRgb; pUnProprotional.m_pSymbolRgb = pSymbolRgb; pUnProprotional.m_strUncernRenderField = strUncernRenderField; pUnProprotional.m_strOriRenderField = strOriRenderField; pUnProprotional.m_dblConInstance = dblConInstance; pUnProprotional.m_pGeometryTypes = pFClass.ShapeType; //Create Legend pUnProprotional.CreateLegend(); pGeofeatureLayer.Renderer = (IFeatureRenderer)pUnProprotional; if (chkNewLayer.Checked == true) { mForm.axMapControl1.ActiveView.FocusMap.AddLayer(pGeofeatureLayer); } else { pFLayer = (IFeatureLayer)pGeofeatureLayer; } } mForm.axMapControl1.ActiveView.Refresh(); mForm.axTOCControl1.Update(); } catch (Exception ex) { frmErrorLog pfrmErrorLog = new frmErrorLog(); pfrmErrorLog.ex = ex; pfrmErrorLog.ShowDialog(); return; } }
/// <summary> /// Reads NMEA data and creates features and records for each line of data. /// </summary> /// <param name="csvFullPath"></param> public static void NMEAToFeatureClass(string sNMEAFile) { try { XmlDocument oDoc = new XmlDocument(); XmlElement oNode = null; AISWrapper.Wrapper myWrapper = new AISWrapper.Wrapper(); ICursor pVoyageCursor = null; ICursor pVesselCursor = null; ICursor pBaseCursor = null; string[] myFiles = Directory.GetFiles(sNMEAFile, "*.txt"); foreach (string myFile in myFiles) { IWorkspace GDBWorkspace = CreateFileGdbWorkspace(sNMEAFile, System.IO.Path.GetFileNameWithoutExtension(myFile) + ".gdb"); ITable pVoyageTable = CreateTable(GDBWorkspace, createVoyageFields(GDBWorkspace), m_cVoyageTableName); ITable pVesselTable = CreateTable(GDBWorkspace, createVesselFields(GDBWorkspace), m_cVesselTabelName); ITable pBaseTable = CreateTable(GDBWorkspace, createBaseStationFields(GDBWorkspace), m_cBaseStationName); RegisterWithGeodatabase(pVoyageTable, "OID"); RegisterWithGeodatabase(pVesselTable, "OID"); RegisterWithGeodatabase(pBaseTable, "OID"); IFeatureClass pFeatureClass = CreateStandaloneFeatureClass(GDBWorkspace, "Broadcast", createFeatureFields(GDBWorkspace, CreateGeographicSR()), "Shape"); clsSupportTables pSupportTable = new clsSupportTables(GDBWorkspace); ITable pUnitsTable = pSupportTable.AddSupportTables(); RegisterWithGeodatabase(pUnitsTable, "OID"); IFeatureCursor featureCursor = pFeatureClass.Insert(true); IFeatureBuffer featureBuffer = pFeatureClass.CreateFeatureBuffer(); int featureCount = 0; int recordCount = 0; int iCurrentVoyageID = 1; List <Vessel> VesselList = new List <Vessel>(); //Hashtable VoyageList = new Hashtable(); DateTime currTime = new DateTime(1900, 1, 1); Hashtable VoyageTable = new Hashtable(); Hashtable VesselTable = new Hashtable(); //Hashtable VoyageTrack = new Hashtable(); int TimeID = pFeatureClass.FindField("BaseDateTime"); int ReceiverType = pFeatureClass.FindField("ReceiverType"); int ReceiverID = pFeatureClass.FindField("ReceiverID"); int MMSIID = pFeatureClass.FindField("MMSI"); int SOGID = pFeatureClass.FindField("SOG"); int COGID = pFeatureClass.FindField("COG"); int ROTID = pFeatureClass.FindField("ROT"); int HeadingID = pFeatureClass.FindField("Heading"); int StatusID = pFeatureClass.FindField("Status"); int VoyageID = pFeatureClass.FindField("VoyageID"); using (StreamReader readFile = new StreamReader(myFile)) { long FileSize = readFile.BaseStream.Length; m_pApplication.StatusBar.ShowProgressBar("Converting " + System.IO.Path.GetFileNameWithoutExtension(myFile) + " to feature class", 0, 100, 1, true); m_pApplication.StatusBar.ProgressBar.Position = 0; //int currentPercent = 0; while (!(readFile.EndOfStream)) //for (int i = 0; i < 500000; i++) { //if (readFile.BaseStream.Position >= 44945408) // MessageBox.Show("here"); //m_pApplication.StatusBar.StepProgressBar(); string myLine1 = readFile.ReadLine(); string myLine2 = ""; int msgType = 0; try { msgType = myWrapper.GetMessageType(myLine1); if (msgType == 5) { string[] sSplit = myLine1.Split(new string[] { "!AIVDM" }, StringSplitOptions.RemoveEmptyEntries); myLine1 = "!AIVDM" + sSplit[0]; myLine2 = "!AIVDM" + sSplit[1]; } else if (msgType == -1) { MessageBox.Show("ere"); } } catch { } switch (msgType) { case 1: case 2: case 3: case 18: case 19: { string myMessage = myWrapper.ParseMessage(myLine1, myLine2); if (myMessage != "") { oDoc.LoadXml(myMessage); PositionMessage pMessage = new PositionMessage(); oNode = (XmlElement)oDoc.SelectSingleNode("//Message/Longitude"); if (oNode != null) { pMessage.Longitude = double.Parse(oNode.InnerText); } oNode = (XmlElement)oDoc.SelectSingleNode("//Message/Latitude"); if (oNode != null) { pMessage.Latitude = double.Parse(oNode.InnerText); } oNode = (XmlElement)oDoc.SelectSingleNode("//Message/MMSI"); if (oNode != null) { pMessage.MMSI = int.Parse(oNode.InnerText); } oNode = (XmlElement)oDoc.SelectSingleNode("//Message/SOG"); if (oNode != null) { pMessage.SOG = double.Parse(oNode.InnerText); } oNode = (XmlElement)oDoc.SelectSingleNode("//Message/COG"); if (oNode != null) { pMessage.COG = double.Parse(oNode.InnerText); } oNode = (XmlElement)oDoc.SelectSingleNode("//Message/ROT"); if (oNode != null) { pMessage.ROT = double.Parse(oNode.InnerText); } oNode = (XmlElement)oDoc.SelectSingleNode("//Message/Heading"); if (oNode != null) { pMessage.Heading = int.Parse(oNode.InnerText); } oNode = (XmlElement)oDoc.SelectSingleNode("//Message/Status"); if (oNode != null) { pMessage.Status = int.Parse(oNode.InnerText); } oNode = (XmlElement)oDoc.SelectSingleNode("//Message/Time"); pMessage.MessageTime = DateTime.ParseExact(oNode.InnerText, "yyyy-MM-dd HH:mm:ss", new CultureInfo("en-US")); oNode = (XmlElement)oDoc.SelectSingleNode("//Message/ReceiverID"); if (oNode != null) { pMessage.ReceiverType = oNode.InnerText.Substring(0, 1); pMessage.ReceiverID = oNode.InnerText.Substring(1); } featureCount++; IPoint point = new PointClass(); point.PutCoords(pMessage.Longitude, pMessage.Latitude); point.SpatialReference = CreateGeographicSR(); featureBuffer.Shape = (IGeometry)point; featureBuffer.set_Value(TimeID, pMessage.MessageTime.ToString("yyyy-MM-dd HH:mm")); featureBuffer.set_Value(MMSIID, pMessage.MMSI); featureBuffer.set_Value(SOGID, pMessage.SOG); featureBuffer.set_Value(COGID, pMessage.COG); featureBuffer.set_Value(ROTID, pMessage.ROT); featureBuffer.set_Value(HeadingID, pMessage.Heading); featureBuffer.set_Value(StatusID, pMessage.Status); featureBuffer.set_Value(ReceiverType, pMessage.ReceiverType); featureBuffer.set_Value(ReceiverID, pMessage.ReceiverID); if (!(VoyageTable.ContainsKey(pMessage.MMSI.ToString()))) { Voyage myVoyage = new Voyage(); myVoyage.VoyageID = iCurrentVoyageID++; myVoyage.Destination = ""; VoyageTable.Add(pMessage.MMSI.ToString(), myVoyage); } Voyage thisVoyage = (Voyage)VoyageTable[pMessage.MMSI.ToString()]; featureBuffer.set_Value(VoyageID, thisVoyage.VoyageID); featureCursor.InsertFeature(featureBuffer); /*if (!(VoyageTrack.ContainsKey((int)VoyageTable[pMessage.MMSI.ToString()]))) * VoyageTrack.Add((int)VoyageTable[pMessage.MMSI.ToString()], new List<PointD>()); * * List<PointD> myList = (List<PointD>)VoyageTrack[(int)VoyageTable[pMessage.MMSI.ToString()]]; * myList.Add(new PointD(pMessage.Longitude, pMessage.Latitude)); */ if (featureCount % 1000 == 0) { featureCursor.Flush(); } } } break; case 4: { double dTemp = 0; string myMessage = myWrapper.ParseMessage(myLine1, myLine2); if (myMessage != "") { oDoc.LoadXml(myMessage); oNode = (XmlElement)oDoc.SelectSingleNode("//Message/MMSI"); pBaseCursor = pBaseTable.Insert(false); IRowBuffer pRowBuffer = pBaseTable.CreateRowBuffer(); pRowBuffer.set_Value(pRowBuffer.Fields.FindField("MMSI"), int.Parse(oNode.InnerText)); oNode = (XmlElement)oDoc.SelectSingleNode("//Message/Longitude"); if (double.TryParse(oNode.InnerText, out dTemp)) { pRowBuffer.set_Value(pRowBuffer.Fields.FindField("Longitude"), dTemp); } oNode = (XmlElement)oDoc.SelectSingleNode("//Message/Latitude"); if (double.TryParse(oNode.InnerText, out dTemp)) { pRowBuffer.set_Value(pRowBuffer.Fields.FindField("Latitude"), dTemp); } pBaseCursor.InsertRow(pRowBuffer); } } break; case 5: { string myMessage = myWrapper.ParseMessage(myLine1, myLine2); if (myMessage != "") { oDoc.LoadXml(myMessage); IRowBuffer pRowBuffer = null; int iTemp = 0; oNode = (XmlElement)oDoc.SelectSingleNode("//Message/MMSI"); string sMMSI = oNode.InnerText; oNode = (XmlElement)oDoc.SelectSingleNode("//Message/Time"); if (oNode != null) { currTime = DateTime.ParseExact(oNode.InnerText, "yyyy-MM-dd HH:mm:ss", new CultureInfo("en-US")); } oNode = (XmlElement)oDoc.SelectSingleNode("//Message/Destination"); bool bAddRow = false; if (VoyageTable.ContainsKey(sMMSI)) { Voyage myVoyage = (Voyage)VoyageTable[sMMSI]; if (myVoyage.Destination != oNode.InnerText.Replace("@", "")) { if (myVoyage.Destination != "") { myVoyage.VoyageID = iCurrentVoyageID++; } myVoyage.Destination = oNode.InnerText.Replace("@", ""); VoyageTable[sMMSI] = myVoyage; bAddRow = true; } } if (bAddRow) { IQueryFilter pQueryFilter = new QueryFilterClass(); pQueryFilter.WhereClause = "MMSI = " + sMMSI; ICursor pCursor = pVoyageTable.Search(pQueryFilter, false); IRow pRow = pCursor.NextRow(); if (pRow != null) { pRow.set_Value(pRow.Fields.FindField("EndTime"), currTime); pRow.Store(); } recordCount++; pVoyageCursor = pVoyageTable.Insert(false); pRowBuffer = pVoyageTable.CreateRowBuffer(); if (!(VesselTable.ContainsKey(sMMSI))) { VesselTable.Add(sMMSI, VesselTable.Count + 1); //store the Vessel IDs, according to MMSI } Voyage thisVoyage = (Voyage)VoyageTable[sMMSI]; pRowBuffer.set_Value(pRowBuffer.Fields.FindField("VoyageID"), thisVoyage.VoyageID); oNode = (XmlElement)oDoc.SelectSingleNode("//Message/MMSI"); if (int.TryParse(oNode.InnerText, out iTemp)) { pRowBuffer.set_Value(pRowBuffer.Fields.FindField("MMSI"), iTemp); } oNode = (XmlElement)oDoc.SelectSingleNode("//Message/Destination"); pRowBuffer.set_Value(pRowBuffer.Fields.FindField("Destination"), oNode.InnerText.Replace("@", "").Trim()); oNode = (XmlElement)oDoc.SelectSingleNode("//Message/ETA"); if (int.TryParse(oNode.InnerText, out iTemp)) { string myBinary = ToBinary(iTemp); if (myBinary.Length < 20) { myBinary = myBinary.PadLeft(20, '0'); } int iMinute = Convert.ToInt32(myBinary.Substring(14, 6), 2); int iHour = Convert.ToInt32(myBinary.Substring(9, 5), 2); int iDay = Convert.ToInt32(myBinary.Substring(4, 5), 2); int iMonth = Convert.ToInt32(myBinary.Substring(0, 4), 2); DateTime myDate; if (DateTime.TryParseExact(currTime.Year.ToString("0000-") + iMonth.ToString("00-") + iDay.ToString("00 ") + iHour.ToString("00:") + iMinute.ToString("00:") + "00", "yyyy-MM-dd HH:mm:ss", new CultureInfo("en-US"), DateTimeStyles.None, out myDate)) { pRowBuffer.set_Value(pRowBuffer.Fields.FindField("ETA"), myDate); } } pRowBuffer.set_Value(pRowBuffer.Fields.FindField("StartTime"), currTime); oNode = (XmlElement)oDoc.SelectSingleNode("//Message/Draught"); if (int.TryParse(oNode.InnerText, out iTemp)) { pRowBuffer.set_Value(pRowBuffer.Fields.FindField("Draught"), iTemp); } oNode = (XmlElement)oDoc.SelectSingleNode("//Message/Cargo"); if (int.TryParse(oNode.InnerText, out iTemp)) { pRowBuffer.set_Value(pRowBuffer.Fields.FindField("Cargo"), iTemp); } pVoyageCursor.InsertRow(pRowBuffer); } oNode = (XmlElement)oDoc.SelectSingleNode("//Message/Name"); Vessel myVessel = new Vessel(); myVessel.MMSI = sMMSI; myVessel.VesselName = oNode.InnerText.Replace("@", "").Trim(); if (!(VesselList.Contains(myVessel))) { VesselList.Add(myVessel); //store the unique MMSIs in a list /*if (!(VesselTable.ContainsKey(sMMSI))) //store the Vessel IDs, according to MMSI * VesselTable.Add(sMMSI, VesselTable.Count + 1);*/ pVesselCursor = pVesselTable.Insert(false); pRowBuffer = pVesselTable.CreateRowBuffer(); iTemp = 0; //pRowBuffer.set_Value(pRowBuffer.Fields.FindField("VesselID"), VesselTable.Count); oNode = (XmlElement)oDoc.SelectSingleNode("//Message/MMSI"); if (int.TryParse(oNode.InnerText, out iTemp)) { pRowBuffer.set_Value(pRowBuffer.Fields.FindField("MMSI"), iTemp); } oNode = (XmlElement)oDoc.SelectSingleNode("//Message/IMO"); if (int.TryParse(oNode.InnerText, out iTemp)) { pRowBuffer.set_Value(pRowBuffer.Fields.FindField("IMO"), iTemp); } oNode = (XmlElement)oDoc.SelectSingleNode("//Message/Call_Sign"); pRowBuffer.set_Value(pRowBuffer.Fields.FindField("CallSign"), oNode.InnerText.Replace("@", "").Trim()); oNode = (XmlElement)oDoc.SelectSingleNode("//Message/Name"); pRowBuffer.set_Value(pRowBuffer.Fields.FindField("Name"), oNode.InnerText.Replace("@", "").Trim()); oNode = (XmlElement)oDoc.SelectSingleNode("//Message/Type"); if (int.TryParse(oNode.InnerText, out iTemp)) { pRowBuffer.set_Value(pRowBuffer.Fields.FindField("VesselType"), iTemp); } oNode = (XmlElement)oDoc.SelectSingleNode("//Message/Length"); if (int.TryParse(oNode.InnerText, out iTemp)) { pRowBuffer.set_Value(pRowBuffer.Fields.FindField("Length"), iTemp); } oNode = (XmlElement)oDoc.SelectSingleNode("//Message/Width"); if (int.TryParse(oNode.InnerText, out iTemp)) { pRowBuffer.set_Value(pRowBuffer.Fields.FindField("Width"), iTemp); } oNode = (XmlElement)oDoc.SelectSingleNode("//Message/Dimensions"); pRowBuffer.set_Value(pRowBuffer.Fields.FindField("DimensionComponents"), oNode.InnerText); pVesselCursor.InsertRow(pRowBuffer); } if (recordCount % 1000 == 0) { pVesselCursor.Flush(); } } } break; } double iPercent = ((double)readFile.BaseStream.Position / (double)FileSize) * 100; if (iPercent > m_pApplication.StatusBar.ProgressBar.Position + 1) { m_pApplication.StatusBar.StepProgressBar(); } } //end while if (featureCursor != null) { featureCursor.Flush(); } if (pVoyageCursor != null) { pVoyageCursor.Flush(); } if (pVesselCursor != null) { pVesselCursor.Flush(); } if (pBaseCursor != null) { pBaseCursor.Flush(); } } //end using pSupportTable.CreateRelationshipClass(GDBWorkspace); m_pApplication.StatusBar.HideProgressBar(); } //end for each m_pApplication.StatusBar.HideProgressBar(); } catch (Exception ex) { MessageBox.Show(ex.ToString(), "AIS_Menu:Utilities:ReadCSV2FeatureClass"); } }
public bool CheckIn(IWorkspace store, string versionName, string dbpath, string gridFeatureClass, string gridCodeFieldName) { //创建子版本 IVersion ver_store = store as IVersion; IVersion new_version = ver_store.CreateVersion(versionName); new_version.Access = esriVersionAccess.esriVersionAccessPublic; IFeatureWorkspace target_ws = new_version as IFeatureWorkspace; IWorkspaceEdit2 wse = target_ws as IWorkspaceEdit2; //删除TaskGridLog ITable grid_tbl = target_ws.OpenTable("TaskGridLog"); IQueryFilter grid_filter = new QueryFilterClass(); grid_filter.WhereClause = "TaskName = '" + versionName + "'"; wse.StartEditing(false); grid_tbl.DeleteSearchedRows(grid_filter); wse.StopEditing(true); //删除CheckItem IQueryFilter checkItems_filter = new QueryFilterClass(); checkItems_filter.WhereClause = "versionName = '" + versionName + "'"; ITable checkItems = target_ws.OpenTable("CheckItemPtn"); checkItems.DeleteSearchedRows(checkItems_filter); checkItems = target_ws.OpenTable("CheckItemLn"); checkItems.DeleteSearchedRows(checkItems_filter); checkItems = target_ws.OpenTable("CheckItemPoly"); checkItems.DeleteSearchedRows(checkItems_filter); IFeatureClass grid_fc = target_ws.OpenFeatureClass(gridFeatureClass); int gridCodeFld_idx = grid_fc.FindField(gridCodeFieldName); Dictionary <string, int[]> updateGridCodes = new Dictionary <string, int[]>(); ISpatialFilter gridFilter = new SpatialFilter(); gridFilter.GeometryField = grid_fc.ShapeFieldName; gridFilter.AddField(gridCodeFieldName); gridFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects; //总更新网格面积 double totalUpdateGridsArea = 0; double totalUpdateGrids = 0; double totalUpdateItems = 0; double totalAddItems = 0; double totalDeleteItems = 0; wse.StartEditing(true); try { Type factoryType = Type.GetTypeFromProgID("esriDataSourcesGDB.AccessWorkspaceFactory"); IWorkspaceFactory workspaceFactory = (IWorkspaceFactory)Activator.CreateInstance (factoryType); IWorkspace source = workspaceFactory.OpenFromFile(dbpath, 0); IDataset ds = source as IDataset; List <String> fcNames = new List <string>(); Util.GetAllFeatureClassNames(ds, ref fcNames); IFeatureWorkspace source_ws = source as IFeatureWorkspace; foreach (string fcname in fcNames) { IWorkspace2 target_ws2 = target_ws as IWorkspace2; if (!target_ws2.get_NameExists(esriDatasetType.esriDTFeatureClass, fcname)) { continue; } IFeatureClass source_fc = source_ws.OpenFeatureClass(fcname); IFeatureClass target_fc = target_ws.OpenFeatureClass(fcname); int syncid_idx = source_fc.FindField("SyncID"); Dictionary <int, int> field_idxs = new Dictionary <int, int>(); for (int i = 0; i < source_fc.Fields.FieldCount; i++) { IField source_field = source_fc.Fields.get_Field(i); if (source_field.Name == "SyncID") { continue; } if (source_field.Name == "SyncTimeStamp") { continue; } if (source_field.Name == "SyncStatus") { continue; } if (source_field.Name == "SyncEditable") { continue; } if (source_field.Name == source_fc.OIDFieldName) { continue; } int j = target_fc.FindField(source_field.Name); if (j != -1) { field_idxs.Add(i, j); } } string checkItemName; switch (target_fc.ShapeType) { case esriGeometryType.esriGeometryPoint: checkItemName = "CheckItemPtn"; break; case esriGeometryType.esriGeometryPolyline: checkItemName = "CheckItemLn"; break; case esriGeometryType.esriGeometryPolygon: checkItemName = "CheckItemPoly"; break; default: checkItemName = "CheckItemPoly"; break; } IFeatureClass checkItem_fc = target_ws.OpenFeatureClass(checkItemName); int checkItem_f1 = checkItem_fc.FindField("FeatureClassName"); int checkItem_f2 = checkItem_fc.FindField("FeatureID"); int checkItem_f3 = checkItem_fc.FindField("VersionName"); int checkItem_f4 = checkItem_fc.FindField(checkItem_fc.ShapeFieldName); IGeoDataset checkItem_gds = checkItem_fc as IGeoDataset; //同步更新 wse.StartEditOperation(); IQueryFilter filter = new QueryFilterClass(); filter.WhereClause = "[SyncStatus]='U'"; IFeatureCursor source_cur = source_fc.Search(filter, false); IFeature source_fea = source_cur.NextFeature(); while (source_fea != null) { int id = Convert.ToInt32(source_fea.get_Value(syncid_idx)); IFeature target_fea = target_fc.GetFeature(id); foreach (KeyValuePair <int, int> field_idx in field_idxs) { target_fea.set_Value(field_idx.Value, source_fea.get_Value(field_idx.Key)); } target_fea.Store(); //添加check item IFeature checkItem_fea = checkItem_fc.CreateFeature(); checkItem_fea.set_Value(checkItem_f1, fcname); checkItem_fea.set_Value(checkItem_f2, id); checkItem_fea.set_Value(checkItem_f3, versionName); IGeometry shape = target_fea.ShapeCopy; shape.Project(checkItem_gds.SpatialReference); checkItem_fea.set_Value(checkItem_f4, shape); checkItem_fea.Store(); //添加TaskGridLog gridFilter.Geometry = target_fea.Shape; IFeatureCursor grid_cur = grid_fc.Search(gridFilter, true); IFeature grid_fea = grid_cur.NextFeature(); while (grid_fea != null) { string gridid = grid_fea.get_Value(gridCodeFld_idx).ToString(); if (updateGridCodes.ContainsKey(gridid)) { updateGridCodes[gridid][0] += 1; } else { int[] c = new int[2] { 1, 0 }; updateGridCodes.Add(gridid, c); } IArea area = grid_fea.Shape as IArea; totalUpdateGridsArea += area.Area; grid_fea = grid_cur.NextFeature(); } totalUpdateItems += 1; source_fea = source_cur.NextFeature(); } wse.StopEditOperation(); //同步删除 wse.StartEditOperation(); List <int> lst_del = new List <int>(); TaskManager tm = TaskManager.GetInstance(); ISpatialFilter target_filter = new SpatialFilterClass(); target_filter.Geometry = tm.GetTaskLocation(versionName); target_filter.SpatialRel = esriSpatialRelEnum.esriSpatialRelContains; target_filter.SubFields = ""; using (ComReleaser comReleaser = new ComReleaser()) { IFeatureCursor target_fea_cur = target_fc.Search(target_filter, false); comReleaser.ManageLifetime(target_fea_cur); IFeature target_fea_del = target_fea_cur.NextFeature(); while (target_fea_del != null) { filter = new QueryFilterClass(); filter.WhereClause = "[SyncID]=" + target_fea_del.OID.ToString(); using (ComReleaser comReleaser2 = new ComReleaser()) { IFeatureCursor source_cur_del = source_fc.Search(filter, true); comReleaser2.ManageLifetime(source_cur_del); source_fea = source_cur_del.NextFeature(); if (source_fea == null) { lst_del.Add(target_fea_del.OID); totalDeleteItems += 1; } } target_fea_del = target_fea_cur.NextFeature(); } } foreach (int id in lst_del) { IFeature target_fea_del = target_fc.GetFeature(id); target_fea_del.Delete(); } wse.StopEditOperation(); //同步新建 wse.StartEditOperation(); filter = new QueryFilterClass(); filter.WhereClause = "[SyncID] is null"; source_cur = source_fc.Search(filter, false); source_fea = source_cur.NextFeature(); while (source_fea != null) { IFeature target_fea = target_fc.CreateFeature(); foreach (KeyValuePair <int, int> field_idx in field_idxs) { target_fea.set_Value(field_idx.Value, source_fea.get_Value(field_idx.Key)); } target_fea.Store(); //添加check item IFeature checkItem_fea = checkItem_fc.CreateFeature(); checkItem_fea.set_Value(checkItem_f1, fcname); checkItem_fea.set_Value(checkItem_f2, target_fea.OID); checkItem_fea.set_Value(checkItem_f3, versionName); IGeometry shape = target_fea.ShapeCopy; shape.Project(checkItem_gds.SpatialReference); checkItem_fea.set_Value(checkItem_f4, shape); checkItem_fea.Store(); //添加TaskGridLog gridFilter.Geometry = target_fea.Shape; IFeatureCursor grid_cur = grid_fc.Search(gridFilter, true); IFeature grid_fea = grid_cur.NextFeature(); while (grid_fea != null) { string gridid = grid_fea.get_Value(gridCodeFld_idx).ToString(); if (updateGridCodes.ContainsKey(gridid)) { updateGridCodes[gridid][1] += 1; } else { int[] c = new int[2] { 0, 1 }; updateGridCodes.Add(gridid, c); } IArea area = grid_fea.Shape as IArea; totalUpdateGridsArea += area.Area; grid_fea = grid_cur.NextFeature(); } totalAddItems += 1; source_fea = source_cur.NextFeature(); } wse.StopEditOperation(); } //添加TaskGridLog wse.StartEditOperation(); using (ComReleaser comR = new ComReleaser()) { ICursor tgl_cur = grid_tbl.Insert(true); IRowBuffer tgl_rowBF = grid_tbl.CreateRowBuffer(); comR.ManageLifetime(tgl_rowBF); comR.ManageLifetime(tgl_cur); foreach (string gridcode in updateGridCodes.Keys) { tgl_rowBF.set_Value(1, versionName); tgl_rowBF.set_Value(2, gridcode); tgl_rowBF.set_Value(4, updateGridCodes[gridcode][1]); tgl_rowBF.set_Value(5, updateGridCodes[gridcode][0]); tgl_cur.InsertRow(tgl_rowBF); } tgl_cur.Flush(); } wse.StopEditOperation(); //设置Task的内容更新信息 totalUpdateGrids = updateGridCodes.Keys.Count; wse.StartEditOperation(); IFeatureClass task_fc = target_ws.OpenFeatureClass("TaskLog"); IQueryFilter task_filter = new QueryFilterClass(); task_filter.WhereClause = "TaskName = '" + versionName + "'"; IFeatureCursor cur = task_fc.Update(task_filter, true); IFeature task_fea = cur.NextFeature(); if (task_fea != null) { task_fea.set_Value(task_fc.FindField("totalAddItems"), totalAddItems); task_fea.set_Value(task_fc.FindField("totalUpdateItems"), totalUpdateItems); task_fea.set_Value(task_fc.FindField("totalDeleteItems"), totalDeleteItems); task_fea.set_Value(task_fc.FindField("totalGrids"), totalUpdateGrids); task_fea.set_Value(task_fc.FindField("totalGridsArea"), totalUpdateGridsArea); task_fea.Store(); } wse.StopEditOperation(); } catch (Exception ex) { return(false); } finally { wse.StopEditing(true); } return(true); }
private void btnApply_Click(object sender, EventArgs e) { try { //Declare variables clsSnippet pSnippet = new clsSnippet(); string strLayerName = cboSourceLayer.Text; int intLIndex = pSnippet.GetIndexNumberFromLayerName(pActiveView, strLayerName); ILayer pLayer = mForm.axMapControl1.get_Layer(intLIndex); IFeatureLayer pFLayer = pLayer as IFeatureLayer; ESRI.ArcGIS.Geodatabase.IFeatureClass pFClass = pFLayer.FeatureClass; string strOriRenderField = cboValueField.Text; string strUncernRenderField = cboUField.Text; double dblMinPtSize = Convert.ToDouble(nudSymbolSize.Value); //Create New Layer? IGeoFeatureLayer pGeofeatureLayer = null; if (chkNewLayer.Checked == true) { IFeatureLayer pflOutput = new FeatureLayerClass(); pflOutput.FeatureClass = pFClass; pflOutput.Name = txtNewLayer.Text; pflOutput.Visible = true; pGeofeatureLayer = (IGeoFeatureLayer)pflOutput; } else { pGeofeatureLayer = (IGeoFeatureLayer)pFLayer; } //Find Fields ITable pTable = (ITable)pFClass; int intOriIdx = pTable.FindField(strOriRenderField); int intUncernIdx = pTable.FindField(strUncernRenderField); //Find Min and Max Ori Value IField pOriField = pTable.Fields.get_Field(intOriIdx); ICursor pCursor = pTable.Search(null, true); IDataStatistics pDataStat = new DataStatisticsClass(); pDataStat.Field = pOriField.Name; pDataStat.Cursor = pCursor; IStatisticsResults pStatResults = pDataStat.Statistics; double dblMinOriValue = pStatResults.Minimum; double dblMaxOriValue = pStatResults.Maximum; pCursor.Flush(); //Find Min and Max Uncern Vale IField pUncernField = pTable.Fields.get_Field(intUncernIdx); pCursor = pTable.Search(null, true); pDataStat = new DataStatisticsClass(); pDataStat.Field = pUncernField.Name; pDataStat.Cursor = pCursor; pStatResults = pDataStat.Statistics; double dblMinUncernValue = pStatResults.Minimum; double dblMaxUncernValue = pStatResults.Maximum; pCursor.Flush(); //To adjust minn value to 1, if the min value is zero double dbladjuctMinvalue = 0; if (dblMinOriValue <= 0) { dbladjuctMinvalue = (0 - dblMinOriValue) + 1; dblMinOriValue = dblMinOriValue + dbladjuctMinvalue; } IDisplay pDisplay = pActiveView.ScreenDisplay; IRgbColor pSymbolRgb = new RgbColorClass(); pSymbolRgb.Red = picSymbolColor.BackColor.R; pSymbolRgb.Green = picSymbolColor.BackColor.G; pSymbolRgb.Blue = picSymbolColor.BackColor.B; IRgbColor pLineRgb = new RgbColorClass(); pLineRgb.Red = picLineColor.BackColor.R; pLineRgb.Green = picLineColor.BackColor.G; pLineRgb.Blue = picLineColor.BackColor.B; int intMethods = 0; if (cboMethods.Text == "Saturation") { intMethods = 1; } else if (cboMethods.Text == "Value") { intMethods = 2; } else if (cboMethods.Text == "Whiteness") { intMethods = 3; } IColoringProperties pPreUncern = new ColoringPropClass2(); //IColoringProperties pPreUncern = new ColoringProp(); pPreUncern.m_intMethods = intMethods; pPreUncern.m_intOriLegendCount = 3; //Needs to be changed pPreUncern.m_intUncernLegendCount = 3; //Needs to be changed pPreUncern.m_strOriRenderField = strOriRenderField; pPreUncern.m_strUncernRenderField = strUncernRenderField; pPreUncern.m_pSymbolRgb = pSymbolRgb; pPreUncern.m_pLineRgb = pLineRgb; pPreUncern.m_dblOutlineSize = Convert.ToDouble(nudLinewidth.Value); pPreUncern.m_dblAdjustedMinValue = dbladjuctMinvalue; pPreUncern.m_dblMinOriValue = dblMinOriValue; pPreUncern.m_dblMaxOriValue = dblMaxOriValue; pPreUncern.m_dblMinUncernValue = dblMinUncernValue; pPreUncern.m_dblMaxUncernValue = dblMaxUncernValue; pPreUncern.m_dblMinPtSize = dblMinPtSize; pPreUncern.CreateLegend(); pGeofeatureLayer.Renderer = (IFeatureRenderer)pPreUncern; if (chkNewLayer.Checked == true) { mForm.axMapControl1.ActiveView.FocusMap.AddLayer(pGeofeatureLayer); } else { pFLayer = (IFeatureLayer)pGeofeatureLayer; } mForm.axTOCControl1.Update(); mForm.axMapControl1.ActiveView.Refresh(); } catch (Exception ex) { frmErrorLog pfrmErrorLog = new frmErrorLog(); pfrmErrorLog.ex = ex; pfrmErrorLog.ShowDialog(); return; } }
private void btnBoxplot_Click(object sender, EventArgs e) { try { string strTargetLayerName = cboTargetLayer.Text; string strFieldName = cboFieldName.Text; string strGroupFieldName = cboGroupField.Text; int intTargetIndex = m_pSnippet.GetIndexNumberFromLayerName(m_pActiveView, strTargetLayerName); int intNFeatureCount = 0; ILayer pTargetLayer = m_pForm.axMapControl1.get_Layer(intTargetIndex); IFeatureLayer pTargetFLayer = (IFeatureLayer)pTargetLayer; //Extract geometry from selected feature IFeatureCursor pFCursor = null; pFCursor = pTargetFLayer.Search(null, true); intNFeatureCount = pTargetFLayer.FeatureClass.FeatureCount(null); int intFieldIdx = pTargetFLayer.FeatureClass.Fields.FindField(strFieldName); int intGroupIdx = pTargetFLayer.FeatureClass.Fields.FindField(strGroupFieldName); System.Collections.Generic.List <object> uvList = new System.Collections.Generic.List <object>(); ICursor ipCursor = pFCursor as ICursor; IRow ipRow = ipCursor.NextRow(); while (ipRow != null) { object curValue = ipRow.get_Value(intGroupIdx); if (!uvList.Contains(curValue)) { uvList.Add(curValue); } ipRow = ipCursor.NextRow(); } uvList.Sort(); //Add exeption for sorting //0421 HK //1. H L M if (uvList.Count == 3) { if (uvList[0].ToString() == "H" && uvList[1].ToString() == "L" && uvList[2].ToString() == "M") { uvList.Clear(); uvList.Add("L"); uvList.Add("M"); uvList.Add("H"); } if (uvList[0].ToString() == "High" && uvList[1].ToString() == "Low" && uvList[2].ToString() == "Medium") { uvList.Clear(); uvList.Add("Low"); uvList.Add("Medium"); uvList.Add("High"); } } ipCursor.Flush(); int intNGroups = uvList.Count; double[,] adbBPStats = new double[5, uvList.Count]; double[,] adbQuantiles = new double[5, uvList.Count]; IQueryFilter pQfilter = new QueryFilterClass(); double[][] adblTarget = new double[intNGroups][]; int[] aintNCounts = new int[intNGroups]; int i = 0; foreach (string uvValue in uvList) { pQfilter.WhereClause = strGroupFieldName + " = '" + uvValue + "'"; pFCursor = pTargetFLayer.Search(pQfilter, true); IFeature pFeature = pFCursor.NextFeature(); intNFeatureCount = pTargetFLayer.FeatureClass.FeatureCount(pQfilter); aintNCounts[i] = intNFeatureCount; adblTarget[i] = new double[intNFeatureCount]; int j = 0; while (pFeature != null) { adblTarget[i][j] = Convert.ToDouble(pFeature.get_Value(intFieldIdx)); j++; pFeature = pFCursor.NextFeature(); } pFCursor.Flush(); i++; } frmBoxPlotResults pfrmBoxplotResults = new frmBoxPlotResults(); pfrmBoxplotResults.Text = "Violin plot of " + pTargetFLayer.Name; pfrmBoxplotResults.pChart.Series.Clear(); ChartArea area = pfrmBoxplotResults.pChart.ChartAreas[0]; int intMaxFeatureNCount = aintNCounts.Max(); //Draw Lines for (int k = 0; k < intNGroups; k++) { string strNumbering = k.ToString(); double[] adblStats = new double[5]; adblStats = BoxPlotStats(adblTarget[k]); for (int l = 0; l < 5; l++) { adbQuantiles[l, k] = adblStats[l]; } int intXvalue = k * 2 + 1; double dblXmin = Convert.ToDouble(intXvalue) - 0.2; double dblXmax = Convert.ToDouble(intXvalue) + 0.2; double dblXBoxMin = Convert.ToDouble(intXvalue) - 0.1; double dblXBoxMax = Convert.ToDouble(intXvalue) + 0.1; //AddLineSeries(pfrmBoxplotResults, "min_" + strNumbering, Color.Black, 1, ChartDashStyle.Solid, dblXmin, dblXmax, adbQuantiles[0, k], adbQuantiles[0, k]); AddLineSeries(pfrmBoxplotResults, "BoxBottom_" + strNumbering, Color.Black, 1, ChartDashStyle.Solid, dblXBoxMin, dblXBoxMax, adbQuantiles[1, k], adbQuantiles[1, k]); AddLineSeries(pfrmBoxplotResults, "BoxLeft_" + strNumbering, Color.Black, 1, ChartDashStyle.Solid, dblXBoxMin, dblXBoxMin, adbQuantiles[1, k], adbQuantiles[3, k]); AddLineSeries(pfrmBoxplotResults, "BoxRight_" + strNumbering, Color.Black, 1, ChartDashStyle.Solid, dblXBoxMax, dblXBoxMax, adbQuantiles[1, k], adbQuantiles[3, k]); AddLineSeries(pfrmBoxplotResults, "Boxup_" + strNumbering, Color.Black, 1, ChartDashStyle.Solid, dblXBoxMin, dblXBoxMax, adbQuantiles[3, k], adbQuantiles[3, k]); AddLineSeries(pfrmBoxplotResults, "median_" + strNumbering, Color.Red, 2, ChartDashStyle.Solid, dblXmin, dblXmax, adbQuantiles[2, k], adbQuantiles[2, k]); //AddLineSeries(pfrmBoxplotResults, "max_" + strNumbering, Color.Black, 1, ChartDashStyle.Solid, dblXmin, dblXmax, adbQuantiles[4, k], adbQuantiles[4, k]); //AddLineSeries(pfrmBoxplotResults, "verDown_" + strNumbering, Color.Black, 1, ChartDashStyle.Dash, intXvalue, intXvalue, adbQuantiles[0, k], adbQuantiles[1, k]); //AddLineSeries(pfrmBoxplotResults, "verUp_" + strNumbering, Color.Black, 1, ChartDashStyle.Dash, intXvalue, intXvalue, adbQuantiles[3, k], adbQuantiles[4, k]); AddLineSeries(pfrmBoxplotResults, "ver_" + strNumbering, Color.Black, 1, ChartDashStyle.Dash, intXvalue, intXvalue, adbQuantiles[0, k], adbQuantiles[4, k]); //Draw Violin Plot var pviolin = new System.Windows.Forms.DataVisualization.Charting.Series { Name = "vio1_" + strNumbering, Color = Color.Black, BorderColor = Color.Black, IsVisibleInLegend = false, ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Line }; pfrmBoxplotResults.pChart.Series.Add(pviolin); double dblBandwidth = RuleofThumb(adblTarget[k]); double[,] adblViolinStats = ViolinPlot(adblTarget[k], dblBandwidth); int intChartLenth = (adblViolinStats.Length) / 2; pviolin.Points.AddXY(intXvalue, adblViolinStats[0, 0]); for (int l = 0; l < intChartLenth; l++) { pviolin.Points.AddXY(intXvalue - adblViolinStats[l, 1], adblViolinStats[l, 0]); } pviolin.Points.AddXY(intXvalue, adblViolinStats[intChartLenth - 1, 0]); for (int l = intChartLenth - 1; l >= 0; l--) { pviolin.Points.AddXY(intXvalue + adblViolinStats[l, 1], adblViolinStats[l, 0]); } pviolin.Points.AddXY(intXvalue, adblViolinStats[0, 0]); //for (int l = 0; l < intChartLenth; l++) //{ // if (adblViolinStats[l, 0] > adblStats[0] && adblViolinStats[l, 0] < adblStats[4]) // pviolin.Points.AddXY(intXvalue - adblViolinStats[l, 1], adblViolinStats[l, 0]); //} //if (adblViolinStats[intChartLenth - 1, 0] < adblStats[4]) // pviolin.Points.AddXY(intXvalue, adblStats[4]); //else // pviolin.Points.AddXY(intXvalue, adblStats[4]); //for (int l = intChartLenth - 1; l >= 0; l--) // if (adblViolinStats[l, 0] > adblStats[0] && adblViolinStats[l, 0] < adblStats[4]) // pviolin.Points.AddXY(intXvalue + adblViolinStats[l, 1], adblViolinStats[l, 0]); //if (adblViolinStats[0, 0] > adblStats[0]) // pviolin.Points.AddXY(intXvalue, adblViolinStats[0, 0]); //else // pviolin.Points.AddXY(intXvalue, adblStats[0]); } //Add Points System.Drawing.Color pMarkerColor = System.Drawing.Color.Blue; var seriesOutPts = new System.Windows.Forms.DataVisualization.Charting.Series { Name = "Points", Color = pMarkerColor, BorderColor = pMarkerColor, IsVisibleInLegend = false, IsXValueIndexed = false, ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Point, MarkerStyle = System.Windows.Forms.DataVisualization.Charting.MarkerStyle.Circle }; pfrmBoxplotResults.pChart.Series.Add(seriesOutPts); for (int k = 0; k < intNGroups; k++) { int intXvalue = k * 2 + 1; foreach (double dblValue in adblTarget[k]) { //if (dblValue < adbQuantiles[1, k] || dblValue > adbQuantiles[3, k]) seriesOutPts.Points.AddXY(intXvalue, dblValue); } } pMarkerColor = System.Drawing.Color.Black; var seriesInPts = new System.Windows.Forms.DataVisualization.Charting.Series { Name = "InPoints", Color = pMarkerColor, BorderColor = pMarkerColor, IsVisibleInLegend = false, IsXValueIndexed = false, ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Point, MarkerStyle = System.Windows.Forms.DataVisualization.Charting.MarkerStyle.Circle }; pfrmBoxplotResults.pChart.Series.Add(seriesInPts); for (int k = 0; k < intNGroups; k++) { int intXvalue = k * 2 + 1; foreach (double dblValue in adblTarget[k]) { if (dblValue >= adbQuantiles[0, k] && dblValue <= adbQuantiles[4, k]) { seriesInPts.Points.AddXY(intXvalue, dblValue); } } } //Store variables in frmBoxPlotResults pfrmBoxplotResults.mForm = m_pForm; pfrmBoxplotResults.pActiveView = m_pActiveView; pfrmBoxplotResults.pFLayer = pTargetFLayer; pfrmBoxplotResults.strFieldName = strFieldName; pfrmBoxplotResults.strGroupFieldName = strGroupFieldName; pfrmBoxplotResults.uvList = uvList; //pfrmBoxplotResults.pFillColor = pFillColor; pfrmBoxplotResults.adbQuantiles = adbQuantiles; pfrmBoxplotResults.pChart.ChartAreas[0].AxisX.Title = strGroupFieldName; pfrmBoxplotResults.pChart.ChartAreas[0].AxisY.Title = strFieldName; pfrmBoxplotResults.pChart.ChartAreas[0].AxisY.IsStartedFromZero = false; pfrmBoxplotResults.pChart.ChartAreas[0].AxisX.Maximum = intNGroups * 2; pfrmBoxplotResults.pChart.ChartAreas[0].AxisX.Interval = 2; pfrmBoxplotResults.pChart.ChartAreas[0].AxisX.Minimum = 0; pfrmBoxplotResults.pChart.ChartAreas[0].AxisX.IntervalOffset = -1; pfrmBoxplotResults.pChart.ChartAreas[0].AxisX.IsLabelAutoFit = false; for (int n = 0; n < uvList.Count; n++) { int intXvalue = n * 2 + 1; double dblXmin = Convert.ToDouble(intXvalue) - 0.6; double dblXmax = Convert.ToDouble(intXvalue) + 0.6; CustomLabel pcutsomLabel = new CustomLabel(); pcutsomLabel.FromPosition = dblXmin; pcutsomLabel.ToPosition = dblXmax; pcutsomLabel.Text = uvList[n].ToString(); pfrmBoxplotResults.pChart.ChartAreas[0].AxisX.CustomLabels.Add(pcutsomLabel); } pfrmBoxplotResults.Show(); } catch (Exception ex) { frmErrorLog pfrmErrorLog = new frmErrorLog(); pfrmErrorLog.ex = ex; pfrmErrorLog.ShowDialog(); return; } }
private void btnApply_Click(object sender, EventArgs e) { try { string strLayerName = cboSourceLayer.Text; if (cboSourceLayer.Text == "" || cboValueField.Text == "" || cboUField.Text == "") { MessageBox.Show("Assign proper layer and field"); return; } int intLIndex = pSnippet.GetIndexNumberFromLayerName(pActiveView, strLayerName); ILayer pLayer = mForm.axMapControl1.get_Layer(intLIndex); IFeatureLayer pFLayer = pLayer as IFeatureLayer; IFeatureClass pFClass = pFLayer.FeatureClass; //Create Rendering of Mean Value at Target Layer int intGCBreakeCount = Convert.ToInt32(nudGCNClasses.Value); string strGCRenderField = cboValueField.Text; IGeoFeatureLayer pGeofeatureLayer; if (chkNewLayer.Checked == true) { IFeatureLayer pflOutput = new FeatureLayerClass(); pflOutput.FeatureClass = pFClass; pflOutput.Name = txtNewLayer.Text; pflOutput.Visible = true; pGeofeatureLayer = (IGeoFeatureLayer)pflOutput; } else { pGeofeatureLayer = (IGeoFeatureLayer)pFLayer; } ITable pTable = (ITable)pFClass; IClassifyGEN pClassifyGEN; switch (cboGCClassify.Text) { case "Equal Interval": pClassifyGEN = new EqualIntervalClass(); break; case "Geometrical Interval": pClassifyGEN = new GeometricalInterval(); break; case "Natural Breaks": pClassifyGEN = new NaturalBreaksClass(); break; case "Quantile": pClassifyGEN = new QuantileClass(); break; case "StandardDeviation": pClassifyGEN = new StandardDeviationClass(); break; default: pClassifyGEN = new NaturalBreaksClass(); break; } //Need to be changed 1/29/15 ITableHistogram pTableHistogram = new BasicTableHistogramClass(); pTableHistogram.Field = strGCRenderField; pTableHistogram.Table = pTable; IBasicHistogram pHistogram = (IBasicHistogram)pTableHistogram; object xVals, frqs; pHistogram.GetHistogram(out xVals, out frqs); pClassifyGEN.Classify(xVals, frqs, intGCBreakeCount); ClassBreaksRenderer pRender = new ClassBreaksRenderer(); double[] cb = (double[])pClassifyGEN.ClassBreaks; pRender.Field = strGCRenderField; pRender.BreakCount = intGCBreakeCount; pRender.MinimumBreak = cb[0]; //' create our color ramp IAlgorithmicColorRamp pColorRamp = new AlgorithmicColorRampClass(); pColorRamp.Algorithm = esriColorRampAlgorithm.esriCIELabAlgorithm; IRgbColor pColor1 = new RgbColor(); IRgbColor pColor2 = new RgbColor(); //Can Change the color in here! pColor1.Red = picSymolfrom.BackColor.R; pColor1.Green = picSymolfrom.BackColor.G; pColor1.Blue = picSymolfrom.BackColor.B; Boolean blnOK = true; pColor2.Red = picSymbolTo.BackColor.R; pColor2.Green = picSymbolTo.BackColor.G; pColor2.Blue = picSymbolTo.BackColor.B; pColorRamp.FromColor = pColor1; pColorRamp.ToColor = pColor2; pColorRamp.Size = intGCBreakeCount; pColorRamp.CreateRamp(out blnOK); IEnumColors pEnumColors = pColorRamp.Colors; pEnumColors.Reset(); IRgbColor pColorOutline = new RgbColor(); //Can Change the color in here! pColorOutline.Red = picGCLineColor.BackColor.R; pColorOutline.Green = picGCLineColor.BackColor.G; pColorOutline.Blue = picGCLineColor.BackColor.B; double dblGCOutlineSize = Convert.ToDouble(nudGCLinewidth.Value); ICartographicLineSymbol pOutLines = new CartographicLineSymbol(); pOutLines.Width = dblGCOutlineSize; pOutLines.Color = (IColor)pColorOutline; //' use this interface to set dialog properties IClassBreaksUIProperties pUIProperties = (IClassBreaksUIProperties)pRender; pUIProperties.ColorRamp = "Custom"; ISimpleFillSymbol pSimpleFillSym; //' be careful, indices are different for the diff lists for (int j = 0; j < intGCBreakeCount; j++) { pRender.Break[j] = cb[j + 1]; pRender.Label[j] = Math.Round(cb[j], 2).ToString() + " - " + Math.Round(cb[j + 1], 2).ToString(); pUIProperties.LowBreak[j] = cb[j]; pSimpleFillSym = new SimpleFillSymbolClass(); pSimpleFillSym.Color = pEnumColors.Next(); pSimpleFillSym.Outline = pOutLines; pRender.Symbol[j] = (ISymbol)pSimpleFillSym; } pGeofeatureLayer.Renderer = (IFeatureRenderer)pRender; if (chkNewLayer.Checked == true) { mForm.axMapControl1.ActiveView.FocusMap.AddLayer(pGeofeatureLayer); } ////* Uncertainty Part *//// //Declare variables in if parts if (tcUncern.SelectedIndex == 0) //Graduated Color { int intUncernBreakCount = Convert.ToInt32(nudCoNClasses.Value); string strUncerFieldName = cboUField.Text; IFeatureLayer pflUncern = new FeatureLayerClass(); pflUncern.FeatureClass = pFClass; pflUncern.Name = cboSourceLayer.Text + " Uncertainty"; pflUncern.Visible = true; IGeoFeatureLayer pGFLUncern = (IGeoFeatureLayer)pflUncern; switch (cboTeClassify.Text) { case "Equal Interval": pClassifyGEN = new EqualIntervalClass(); break; case "Geometrical Interval": pClassifyGEN = new GeometricalInterval(); break; case "Natural Breaks": pClassifyGEN = new NaturalBreaksClass(); break; case "Quantile": pClassifyGEN = new QuantileClass(); break; case "StandardDeviation": pClassifyGEN = new StandardDeviationClass(); break; default: pClassifyGEN = new NaturalBreaksClass(); break; } //Need to be changed 1/29/15 pTableHistogram = new BasicTableHistogramClass(); pTableHistogram.Field = strUncerFieldName; pTableHistogram.Table = pTable; pHistogram = (IBasicHistogram)pTableHistogram; pHistogram.GetHistogram(out xVals, out frqs); pClassifyGEN.Classify(xVals, frqs, intUncernBreakCount); pRender = new ClassBreaksRenderer(); cb = (double[])pClassifyGEN.ClassBreaks; pRender.Field = strUncerFieldName; pRender.BreakCount = intUncernBreakCount; pRender.MinimumBreak = cb[0]; IClassBreaksUIProperties pUIColProperties = (IClassBreaksUIProperties)pRender; pUIColProperties.ColorRamp = "Custom"; pColorRamp = new AlgorithmicColorRampClass(); pColorRamp.Algorithm = esriColorRampAlgorithm.esriCIELabAlgorithm; pColor1 = new RgbColor(); pColor2 = new RgbColor(); //Can Change the color in here! pColor1 = pSnippet.getRGB(picCoColorFrom.BackColor.R, picCoColorFrom.BackColor.G, picCoColorFrom.BackColor.B); pColor2 = pSnippet.getRGB(picCoColorTo.BackColor.R, picCoColorTo.BackColor.G, picCoColorTo.BackColor.B); if (pColor1 == null || pColor2 == null) { return; } blnOK = true; pColorRamp.FromColor = pColor1; pColorRamp.ToColor = pColor2; pColorRamp.Size = intUncernBreakCount; pColorRamp.CreateRamp(out blnOK); pEnumColors = pColorRamp.Colors; pEnumColors.Reset(); pColorOutline = pSnippet.getRGB(picCoLineColor.BackColor.R, picCoLineColor.BackColor.G, picCoLineColor.BackColor.B); if (pColorOutline == null) { return; } double dblCoOutlineSize = Convert.ToDouble(nudCoLinewidth.Value); pOutLines = new CartographicLineSymbol(); pOutLines.Width = dblCoOutlineSize; pOutLines.Color = (IColor)pColorOutline; //' use this interface to set dialog properties pUIColProperties = (IClassBreaksUIProperties)pRender; pUIColProperties.ColorRamp = "Custom"; ISimpleMarkerSymbol pSimpleMarkerSym; double dblCoSymSize = Convert.ToDouble(nudCoSymbolSize.Value); //' be careful, indices are different for the diff lists for (int j = 0; j < intUncernBreakCount; j++) { pRender.Break[j] = cb[j + 1]; pRender.Label[j] = Math.Round(cb[j], 2).ToString() + " - " + Math.Round(cb[j + 1], 2).ToString(); pUIColProperties.LowBreak[j] = cb[j]; pSimpleMarkerSym = new SimpleMarkerSymbolClass(); pSimpleMarkerSym.Size = dblCoSymSize; pSimpleMarkerSym.Color = pEnumColors.Next(); pSimpleMarkerSym.Outline = true; pSimpleMarkerSym.OutlineColor = pColorOutline; pSimpleMarkerSym.OutlineSize = dblCoOutlineSize; pRender.Symbol[j] = (ISymbol)pSimpleMarkerSym; } pGFLUncern.Renderer = (IFeatureRenderer)pRender; mForm.axMapControl1.ActiveView.FocusMap.AddLayer(pGFLUncern); } else if (tcUncern.SelectedIndex == 1) //Texture { //Create Rendering of Uncertainty at Target Layer int intUncernBreakCount = Convert.ToInt32(nudTeNClasses.Value); string strUncerFieldName = cboUField.Text; IFeatureLayer pflUncern = new FeatureLayerClass(); pflUncern.FeatureClass = pFClass; pflUncern.Name = cboSourceLayer.Text + " Uncertainty"; pflUncern.Visible = true; IGeoFeatureLayer pGFLUncern = (IGeoFeatureLayer)pflUncern; switch (cboTeClassify.Text) { case "Equal Interval": pClassifyGEN = new EqualIntervalClass(); break; case "Geometrical Interval": pClassifyGEN = new GeometricalInterval(); break; case "Natural Breaks": pClassifyGEN = new NaturalBreaksClass(); break; case "Quantile": pClassifyGEN = new QuantileClass(); break; case "StandardDeviation": pClassifyGEN = new StandardDeviationClass(); break; default: pClassifyGEN = new NaturalBreaksClass(); break; } //Need to be changed 1/29/15 pTableHistogram = new BasicTableHistogramClass(); pTableHistogram.Field = strUncerFieldName; pTableHistogram.Table = pTable; pHistogram = (IBasicHistogram)pTableHistogram; pHistogram.GetHistogram(out xVals, out frqs); pClassifyGEN.Classify(xVals, frqs, intUncernBreakCount); pRender = new ClassBreaksRenderer(); cb = (double[])pClassifyGEN.ClassBreaks; pRender.Field = strUncerFieldName; pRender.BreakCount = intUncernBreakCount; pRender.MinimumBreak = cb[0]; IClassBreaksUIProperties pUITexProperties = (IClassBreaksUIProperties)pRender; pUITexProperties.ColorRamp = "Custom"; ILineFillSymbol pLineFillSym = new LineFillSymbolClass(); double dblFromSep = Convert.ToDouble(nudSeperationFrom.Value); double dblToSep = Convert.ToDouble(nudSeperationTo.Value); double dblInstantSep = (dblFromSep - dblToSep) / Convert.ToDouble(intUncernBreakCount - 1); double dblFromAngle = Convert.ToDouble(nudAngleFrom.Value); double dblToAngle = Convert.ToDouble(nudAngleFrom.Value); // Remove the angle part (04/16) double dblInstantAngle = (dblToAngle - dblFromAngle) / Convert.ToDouble(intUncernBreakCount - 1); double dblLinewidth = Convert.ToDouble(nudTeLinewidth.Value); IRgbColor pLineColor = new RgbColor(); pLineColor.Red = picTeLineColor.BackColor.R; pLineColor.Green = picTeLineColor.BackColor.G; pLineColor.Blue = picTeLineColor.BackColor.B; //' be careful, indices are different for the diff lists for (int j = 0; j < intUncernBreakCount; j++) { pRender.Break[j] = cb[j + 1]; pRender.Label[j] = Math.Round(cb[j], 5).ToString() + " - " + Math.Round(cb[j + 1], 5).ToString(); pUITexProperties.LowBreak[j] = cb[j]; pLineFillSym = new LineFillSymbolClass(); pLineFillSym.Angle = dblFromAngle + (dblInstantAngle * Convert.ToDouble(j)); pLineFillSym.Color = pLineColor; pLineFillSym.Separation = dblFromSep - (dblInstantSep * Convert.ToDouble(j)); pLineFillSym.LineSymbol.Width = dblLinewidth; pRender.Symbol[j] = (ISymbol)pLineFillSym; } pGFLUncern.Renderer = (IFeatureRenderer)pRender; mForm.axMapControl1.ActiveView.FocusMap.AddLayer(pGFLUncern); } else if (tcUncern.SelectedIndex == 2) //For Proportional Symbols { string strUncerFieldName = cboUField.Text; double dblMinPtSize = Convert.ToDouble(nudProSymbolSize.Value); double dblLineWidth = Convert.ToDouble(nudProLinewidth.Value); IFeatureLayer pflUncern = new FeatureLayerClass(); pflUncern.FeatureClass = pFClass; pflUncern.Name = cboSourceLayer.Text + " Uncertainty"; pflUncern.Visible = true; //Find Fields int intUncernIdx = pTable.FindField(strUncerFieldName); //Find Min value //Set to initial value for min IField pUncernField = pTable.Fields.get_Field(intUncernIdx); ICursor pCursor = pTable.Search(null, false); IDataStatistics pDataStat = new DataStatisticsClass(); pDataStat.Field = pUncernField.Name; pDataStat.Cursor = pCursor; IStatisticsResults pStatResults = pDataStat.Statistics; double dblMinValue = pStatResults.Minimum; double dblMaxValue = pStatResults.Maximum; pCursor.Flush(); IRgbColor pSymbolRgb = pSnippet.getRGB(picProSymbolColor.BackColor.R, picProSymbolColor.BackColor.G, picProSymbolColor.BackColor.B); if (pSymbolRgb == null) { return; } IRgbColor pLineRgb = pSnippet.getRGB(picProiLineColor.BackColor.R, picProiLineColor.BackColor.G, picProiLineColor.BackColor.B); if (pLineRgb == null) { return; } ISimpleMarkerSymbol pSMarkerSym = new SimpleMarkerSymbolClass(); pSMarkerSym.Style = esriSimpleMarkerStyle.esriSMSCircle; pSMarkerSym.Size = dblMinPtSize; pSMarkerSym.OutlineSize = dblLineWidth; pSMarkerSym.Outline = true; pSMarkerSym.OutlineColor = (IColor)pLineRgb; pSMarkerSym.Color = (IColor)pSymbolRgb; IGeoFeatureLayer pGFLUncern = (IGeoFeatureLayer)pflUncern; IProportionalSymbolRenderer pUncernRender = new ProportionalSymbolRendererClass(); pUncernRender.LegendSymbolCount = 2; //Need to be changed 0219 pUncernRender.Field = strUncerFieldName; pUncernRender.MaxDataValue = dblMaxValue; pUncernRender.MinDataValue = dblMinValue; pUncernRender.MinSymbol = (ISymbol)pSMarkerSym; pUncernRender.ValueUnit = esriUnits.esriUnknownUnits; pUncernRender.BackgroundSymbol = null; pUncernRender.CreateLegendSymbols(); pGFLUncern.Renderer = (IFeatureRenderer)pUncernRender; mForm.axMapControl1.ActiveView.FocusMap.AddLayer(pGFLUncern); } else if (tcUncern.SelectedIndex == 3) // Bar { string strUncerFieldName = cboUField.Text; double dblMaxLength = Convert.ToDouble(nudMaxBarHeight.Value); double dblBarWidth = Convert.ToDouble(nudBarWidth.Value); IFeatureLayer pflUncern = new FeatureLayerClass(); pflUncern.FeatureClass = pFClass; pflUncern.Name = cboSourceLayer.Text + " Uncertainty"; pflUncern.Visible = true; int intUncernIdx = pTable.FindField(strUncerFieldName); IField pUncernField = pTable.Fields.get_Field(intUncernIdx); ICursor pCursor = pTable.Search(null, false); IDataStatistics pDataStat = new DataStatisticsClass(); pDataStat.Field = pUncernField.Name; pDataStat.Cursor = pCursor; IStatisticsResults pStatResults = pDataStat.Statistics; double dblMaxValue = pStatResults.Maximum; pCursor.Flush(); IChartRenderer chartRenderer = new ChartRendererClass(); IRendererFields rendererFields = chartRenderer as IRendererFields; rendererFields.AddField(strUncerFieldName); IBarChartSymbol barChartSymbol = new BarChartSymbolClass(); barChartSymbol.Width = dblBarWidth; IMarkerSymbol markerSymbol = barChartSymbol as IMarkerSymbol; markerSymbol.Size = dblMaxLength; IChartSymbol chartSymbol = barChartSymbol as IChartSymbol; chartSymbol.MaxValue = dblMaxValue; ISymbolArray symbolArray = barChartSymbol as ISymbolArray; IFillSymbol fillSymbol = new SimpleFillSymbolClass(); fillSymbol.Color = pSnippet.getRGB(picBarSymCol.BackColor.R, picBarSymCol.BackColor.G, picBarSymCol.BackColor.B); if (fillSymbol.Color == null) { return; } symbolArray.AddSymbol(fillSymbol as ISymbol); if (chk3D.Checked) { I3DChartSymbol p3DChartSymbol = barChartSymbol as I3DChartSymbol; p3DChartSymbol.Display3D = true; p3DChartSymbol.Thickness = 3; } chartRenderer.ChartSymbol = barChartSymbol as IChartSymbol; SimpleFillSymbol pBaseFillSym = new SimpleFillSymbolClass(); //pBaseFillSym.Color = pSnippet.getRGB(picBarSymCol.BackColor.R, picBarSymCol.BackColor.G, picBarSymCol.BackColor.B); //chartRenderer.BaseSymbol = pBaseFillSym as ISymbol; chartRenderer.UseOverposter = false; chartRenderer.CreateLegend(); IGeoFeatureLayer pGFLUncern = (IGeoFeatureLayer)pflUncern; pGFLUncern.Renderer = (IFeatureRenderer)chartRenderer; mForm.axMapControl1.ActiveView.FocusMap.AddLayer(pGFLUncern); } #region illumination //This function is not applied in this version. 032317 HK //} // else if (tcUncern.SelectedIndex == 4) //illumination // { // frmProgress pfrmProgress = new frmProgress(); // pfrmProgress.lblStatus.Text = "Processing:"; // pfrmProgress.pgbProgress.Style = ProgressBarStyle.Marquee; // pfrmProgress.Show(); // string strUncerFieldName = cboUField.Text; // IGeoDataset geoDataset_output = createRasterfromPolygon(pFClass, strUncerFieldName, pFLayer, 100); // double altitude = Convert.ToDouble(nudAltitude.Value); // double azimuth = Convert.ToDouble(nudAzimuth.Value); // object zFactor = Convert.ToDouble(nudZFactor.Value); // ISurfaceOp2 pSurfOP = new RasterSurfaceOpClass(); // IRaster pOutputDS = (IRaster)pSurfOP.HillShade(geoDataset_output, azimuth, altitude, true, ref zFactor); // ((IDataset)geoDataset_output).Delete(); // // Create a raster for viewing // ESRI.ArcGIS.Carto.IRasterLayer rasterLayer = new ESRI.ArcGIS.Carto.RasterLayerClass(); // rasterLayer.CreateFromRaster(pOutputDS); // //Calculate hillshade value at slope 0 to set as background value // double dblRadian = (Math.PI / 180) * (90 - altitude); // double dblBackValue = Math.Truncate(255 * Math.Cos(dblRadian)); // IRasterStretch pRasterStretch = new RasterStretchColorRampRendererClass(); // IColor pColor = new RgbColorClass(); // pColor.NullColor = true; // pColor.Transparency = 0; // pRasterStretch.Background = true; // pRasterStretch.BackgroundColor = pColor; // pRasterStretch.set_BackgroundValues(ref dblBackValue); // rasterLayer.Name = "Uncertainty of " + strGCRenderField; // rasterLayer.Renderer = pRasterStretch as IRasterRenderer; // rasterLayer.Renderer.Update(); // //Apply Transparency // ILayerEffects pLayerEffect = (ILayerEffects)rasterLayer; // pLayerEffect.Transparency = Convert.ToInt16(nudTransparent.Value); // pfrmProgress.Close(); // // Add the raster to the map // pActiveView.FocusMap.AddLayer(rasterLayer); // } // mForm.axMapControl1.ActiveView.Refresh(); // mForm.axTOCControl1.Update(); #endregion } catch (Exception ex) { frmErrorLog pfrmErrorLog = new frmErrorLog(); pfrmErrorLog.ex = ex; pfrmErrorLog.ShowDialog(); return; } }
/// <summary> /// Append source SqlDataReader to Destination Table. /// Using IFeatureClassLoad.LoadOnlyMode = true. /// Support destination data format, SDE (FeatureClass), FileGDB (FeatureClass, Table). /// /// <para> /// <see href="http://resources.esri.com/help/9.3/ArcGISDesktop/ArcObjects/esriGeoDatabase/IFeatureClassLoad.htm"> /// More info IFeatureClassLoad</see> /// </para> /// </summary> /// <param name="readerSrc"></param> /// <param name="tableDest"></param> /// <param name="totalSrcRecord">Total record to append. Use for update progress callback.</param> /// <param name="flushDataEveryNRecord">Flush data every specified record.</param> /// <returns>Number of row appended.</returns> public int FastAppendUsingLoadOnlyMode(SqlDataReader readerSrc, ITable tableDest, int totalSrcRecord, int flushDataEveryNRecord = 10000) { // Check and throw Exception if (readerSrc == null || !readerSrc.HasRows) { // No data to append. return(0); } if (tableDest == null) { throw new ArgumentNullException("fclassDest", "Destination FeatureClass must not be null."); } IFeatureClassLoad fclassLoadDest = tableDest as IFeatureClassLoad; ISchemaLock schemaLockDest = tableDest as ISchemaLock; ICursor cursorDest = null; IRowBuffer rowBufferDest = null; //IFeature ftSrc = null; IRow rowDest = null; //IFields fieldsSrc = ftCursorSrc.Fields; IFields fieldsDest = tableDest.Fields; //IField fieldSrc; IField fieldDest; int inxFieldSrc = -1; string tableNameDest = ((IDataset)tableDest).Name; // Skip fields SkipFields.Add(tableDest.OIDFieldName.ToUpper()); // Check if LoadOnlyMode support if (fclassLoadDest == null) { throw new InvalidOperationException($"FastAppend (LoadOnlyMode) is not support for table \"{tableNameDest}\""); } int updateInterval = PercentCallbackInterval; int nextUpdatePercent = updateInterval; int currentRow = 0; int percent = 0; int totalRecord = totalSrcRecord; try { // Create an insert cursor cursorDest = tableDest.Insert(true); // Set schema lock and switch to Load Only Mode schemaLockDest.ChangeSchemaLock(esriSchemaLock.esriExclusiveSchemaLock); fclassLoadDest.LoadOnlyMode = true; // Make key Upper (for case-insensitive field name check) MakeAllDictConvertFieldValueKeyUpper(); Func <SqlDataReader, int, object> funcConvertValue = null; // Loop Src Record while (readerSrc.Read()) { rowBufferDest = tableDest.CreateRowBuffer(); rowDest = rowBufferDest as IRow; // Attribute CopyFieldsValue(readerSrc, rowDest); cursorDest.InsertRow(rowBufferDest); rowBufferDest = null; // Flush every 10000 row if (currentRow % flushDataEveryNRecord == 0) { cursorDest.Flush(); } // Update progess currentRow++; percent = CalPercent(currentRow, totalRecord); if (percent >= nextUpdatePercent) { ProgressCallback?.Invoke(percent); nextUpdatePercent += updateInterval; } } cursorDest.Flush(); } finally { // Clean up schemaLockDest?.ChangeSchemaLock(esriSchemaLock.esriSharedSchemaLock); if (fclassLoadDest != null) { fclassLoadDest.LoadOnlyMode = false; } readerSrc.Close(); if (cursorDest != null) { ComReleaser.ReleaseCOMObject(cursorDest); cursorDest = null; } } return(currentRow); }
private void DrawLegend() { try { if (blnBoxplot == true && cboSourceLayer.Text != "" && cboUField.Text != "" && cboValueField.Text != "") { mForm = System.Windows.Forms.Application.OpenForms["MainForm"] as MainForm; IActiveView pActiveView = mForm.axMapControl1.ActiveView; string strTargetLayerName = cboSourceLayer.Text; string strValueField = cboValueField.Text; string strUncerField = cboUField.Text; clsSnippet pSnippet = new clsSnippet(); int intTLayerIdx = pSnippet.GetIndexNumberFromLayerName(pActiveView, strTargetLayerName); ILayer pLayer = mForm.axMapControl1.get_Layer(intTLayerIdx); IFeatureLayer pFLayer = (IFeatureLayer)pLayer; IFeatureClass pFeatureClass = pFLayer.FeatureClass; int intValueFldIdx = pFeatureClass.FindField(strValueField); int intUncerFldIdx = pFeatureClass.FindField(strUncerField); REngine pEngine = mForm.pEngine; pEngine.Evaluate("confLevel <- " + nudConfiLevel.Value.ToString()); pEngine.Evaluate("bothlevel <- 1-((100-confLevel)/200)"); dblError = pEngine.Evaluate("error <- qnorm(bothlevel)").AsNumeric().First(); //Cacluate Max value based on the confidence intervals ICursor pCursor = (ICursor)pFeatureClass.Search(null, false); IRow pRow = pCursor.NextRow(); dblMaxValue = 0; double dblTempValue = 0; dblMaxEstimate = 0; dblMaxUncern = 0; double dblTempEstimate = 0; double dblTempUncern = 0; while (pRow != null) { dblTempEstimate = Convert.ToDouble(pRow.get_Value(intValueFldIdx)); dblTempUncern = Convert.ToDouble(pRow.get_Value(intUncerFldIdx)) * dblError; dblTempValue = dblTempEstimate + dblTempUncern; if (dblTempValue > dblMaxValue) { dblMaxValue = dblTempValue; dblMaxEstimate = dblTempEstimate; dblMaxUncern = dblTempUncern; } pRow = pCursor.NextRow(); } pCursor.Flush(); if (pGeofeatureLayer == null) { pGeofeatureLayer = null; IFeatureLayer pflOutput = new FeatureLayerClass(); pflOutput.FeatureClass = pFeatureClass; strOutputGFLName = pFeatureClass.AliasName + "_Uncern"; pflOutput.Name = strOutputGFLName; pflOutput.Visible = true; pGeofeatureLayer = (IGeoFeatureLayer)pflOutput; StackedLegned pStackedLegend = new StackedLegned(); pStackedLegend.m_strOriRenderField = strValueField; pStackedLegend.m_strUncernRenderField = strUncerField; pStackedLegend.dblMaxValue = dblMaxValue; pStackedLegend.dblMaxEstimate = dblMaxEstimate; pStackedLegend.dblMaxUncern = dblMaxUncern; pStackedLegend.bln3Dfeature = bln3Dfeature; pStackedLegend.CreateLegend(); pStackedLegend.PrepareFilter(pFeatureClass, null); pGeofeatureLayer.Renderer = pStackedLegend; pActiveView.FocusMap.AddLayer(pGeofeatureLayer); } else { int intLIndex = pSnippet.GetIndexNumberFromLayerName(pActiveView, strOutputGFLName); ILayer pNewLayer = mForm.axMapControl1.get_Layer(intLIndex); IFeatureLayer pNewFLayer = pNewLayer as IFeatureLayer; pGeofeatureLayer = pNewFLayer as IGeoFeatureLayer; StackedLegned pStackedLegend = new StackedLegned(); pStackedLegend.m_strOriRenderField = strValueField; pStackedLegend.m_strUncernRenderField = strUncerField; pStackedLegend.dblMaxValue = dblMaxValue; pStackedLegend.dblMaxEstimate = dblMaxEstimate; pStackedLegend.dblMaxUncern = dblMaxUncern; pStackedLegend.bln3Dfeature = bln3Dfeature; pStackedLegend.CreateLegend(); //pStackedLegend.PrepareFilter(pFeatureClass, null); pGeofeatureLayer.Renderer = pStackedLegend; //int intLIndex = pSnippet.GetIndexNumberFromLayerName(pActiveView, strOutputGFLName); //ILayer pNewLayer = mForm.axMapControl1.get_Layer(intLIndex); //IFeatureLayer pNewFLayer = pNewLayer as IFeatureLayer; pNewFLayer = (IFeatureLayer)pGeofeatureLayer; } pActiveView.Refresh(); } else { return; } } catch (Exception ex) { frmErrorLog pfrmErrorLog = new frmErrorLog(); pfrmErrorLog.ex = ex; pfrmErrorLog.ShowDialog(); return; } }
private void fillFields() { if (rd != null) { rd.addMessage("Output table name = " + wks.PathName + "\\" + tblName); } //bool weCreate = true; //if (!geoUtil.ftrExists(wks, tblName)) //{ IFields nflds = new FieldsClass(); IFieldsEdit nfldsE = (IFieldsEdit)nflds; IField nfld = new FieldClass(); IFieldEdit nfldE = (IFieldEdit)nfld; nfldE.Name_2 = "Band"; nfldE.Type_2 = esriFieldType.esriFieldTypeDouble; nfldsE.AddField(nfldE); IField nfld2 = new FieldClass(); IFieldEdit nfld2E = (IFieldEdit)nfld2; nfld2E.Name_2 = "Zone"; nfld2E.Type_2 = esriFieldType.esriFieldTypeDouble; nfldsE.AddField(nfld2E); IField nfld3 = new FieldClass(); IFieldEdit nfld3E = (IFieldEdit)nfld3; nfld3E.Name_2 = "Count"; nfld3E.Type_2 = esriFieldType.esriFieldTypeDouble; nfldsE.AddField(nfld3E); oTbl = geoUtil.createTable(wks, tblName, nflds); int[] fldIndex = new int[ZoneTypes.Length]; for (int zIndex = 0; zIndex < ZoneTypes.Length; zIndex++) { string fldNm = ZoneTypes[zIndex].ToString(); fldNm = geoUtil.createField(oTbl, fldNm, esriFieldType.esriFieldTypeDouble); fldIndex[zIndex] = oTbl.FindField(fldNm); } IWorkspaceEdit wksE = (IWorkspaceEdit)wks; if (wksE.IsBeingEdited()) { wksE.StopEditing(true); } try { int bdIndex = oTbl.FindField("Band"); int vlIndex = oTbl.FindField("Zone"); int cntIndex = oTbl.FindField("Count"); int bndCnt = 1; ICursor cur = oTbl.Insert(true); IRowBuffer rw = oTbl.CreateRowBuffer(); foreach (Dictionary <double, object[]> zoneValueDicOut in zoneValueDicArr) { foreach (KeyValuePair <double, object[]> kVp in zoneValueDicOut) { double key = kVp.Key; object[] vl = kVp.Value; Dictionary <rasterUtil.zoneType, double> vDic = getValueDic(vl); //IRow rw = null; //if (!weCreate) //{ // string qry = "Band = " + bndCnt.ToString() + " and Zone = " + key; // IQueryFilter qf = new QueryFilterClass(); // qf.WhereClause = qry; // ISelectionSet tblSelectionSet = oTbl.Select(qf, esriSelectionType.esriSelectionTypeIDSet, esriSelectionOption.esriSelectionOptionOnlyOne, wks); // if (tblSelectionSet.Count > 0) // { // int id = tblSelectionSet.IDs.Next(); // rw = oTbl.GetRow(id); // } // else // { // rw = oTbl.CreateRow(); // } //} //else //{ //rw = oTbl.CreateRow(); //} //Console.WriteLine(key.ToString()); rw.set_Value(bdIndex, bndCnt); rw.set_Value(vlIndex, key); rw.set_Value(cntIndex, vl[0]); for (int zIndex = 0; zIndex < ZoneTypes.Length; zIndex++)// (rasterUtil.zoneType zT in ZoneTypes) { rasterUtil.zoneType zT = ZoneTypes[zIndex]; double zVl = vDic[zT]; //Console.WriteLine("\t"+fldNm+ ": " + zVl.ToString()); rw.set_Value(fldIndex[zIndex], zVl); } //rw.Store(); cur.InsertRow(rw); } bndCnt += 1; } //trs.CommitTransaction(); cur.Flush(); System.Runtime.InteropServices.Marshal.ReleaseComObject(cur); System.Runtime.InteropServices.Marshal.ReleaseComObject(rw); } catch (Exception e) { Console.WriteLine(e.ToString()); //trs.AbortTransaction(); } finally { } }
protected override void OnClick() { m_pApp = (IApplication)ArcMap.Application; if (m_pApp == null) { //if the app is null then could be running from ArcCatalog m_pApp = (IApplication)ArcCatalog.Application; } if (m_pApp == null) { MessageBox.Show("Could not access the application.", "No Application found"); return; } IGxApplication pGXApp = (IGxApplication)m_pApp; stdole.IUnknown pUnk = null; try { pUnk = (stdole.IUnknown)pGXApp.SelectedObject.InternalObjectName.Open(); } catch (COMException ex) { if (ex.ErrorCode == (int)fdoError.FDO_E_DATASET_TYPE_NOT_SUPPORTED_IN_RELEASE || ex.ErrorCode == -2147220944) { MessageBox.Show("The dataset is not supported in this release.", "Could not open the dataset"); } else { MessageBox.Show(ex.ErrorCode.ToString(), "Could not open the dataset"); } return; } if (pUnk is ICadastralFabric) { m_pCadaFab = (ICadastralFabric)pUnk; } else { MessageBox.Show("Please select a parcel fabric and try again.", "Not a parcel fabric"); return; } IMouseCursor pMouseCursor = new MouseCursorClass(); pMouseCursor.SetCursor(2); clsFabricUtils FabricUTILS = new clsFabricUtils(); IProgressDialog2 pProgressorDialog = null; ITable pTable = m_pCadaFab.get_CadastralTable(esriCadastralFabricTable.esriCFTParcels); IDataset pDS = (IDataset)pTable; IWorkspace pWS = pDS.Workspace; bool bIsFileBasedGDB = true; bool bIsUnVersioned = true; FabricUTILS.GetFabricPlatform(pWS, m_pCadaFab, out bIsFileBasedGDB, out bIsUnVersioned); if (!bIsFileBasedGDB && !bIsUnVersioned) { MessageBox.Show("Truncate operates on non-versioned fabrics." + Environment.NewLine + "Please unversion the fabric and try again.", "Tables are versioned"); return; } //Do a Start and Stop editing to make sure truncate it not running within an edit session if (!FabricUTILS.StartEditing(pWS, bIsUnVersioned)) {//if start editing fails then bail Cleanup(pProgressorDialog, pMouseCursor); return; } FabricUTILS.StopEditing(pWS); dlgTruncate pTruncateDialog = new dlgTruncate(); IArray TableArray = new ESRI.ArcGIS.esriSystem.ArrayClass(); pTruncateDialog.TheFabric = m_pCadaFab; pTruncateDialog.TheTableArray = TableArray; //Display the dialog DialogResult pDialogResult = pTruncateDialog.ShowDialog(); if (pDialogResult != DialogResult.OK) { pTruncateDialog = null; if (TableArray != null) { TableArray.RemoveAll(); } return; } m_pProgressorDialogFact = new ProgressDialogFactoryClass(); m_pTrackCancel = new CancelTrackerClass(); m_pStepProgressor = m_pProgressorDialogFact.Create(m_pTrackCancel, m_pApp.hWnd); pProgressorDialog = (IProgressDialog2)m_pStepProgressor; m_pStepProgressor.MinRange = 0; m_pStepProgressor.MaxRange = pTruncateDialog.DropRowCount; m_pStepProgressor.StepValue = 1; pProgressorDialog.Animation = ESRI.ArcGIS.Framework.esriProgressAnimationTypes.esriProgressSpiral; bool bSuccess = false; int iControlRowCount = 0; //look in registry to get flag on whether to run truncate on standard tables, or to delete by row. string sDesktopVers = FabricUTILS.GetDesktopVersionFromRegistry(); if (sDesktopVers.Trim() == "") { sDesktopVers = "Desktop10.0"; } else { sDesktopVers = "Desktop" + sDesktopVers; } bool bDeleteTablesByRowInsteadOfTruncate = false; string sValues = FabricUTILS.ReadFromRegistry(RegistryHive.CurrentUser, "Software\\ESRI\\" + sDesktopVers + "\\ArcMap\\Cadastral", "AddIn.DeleteFabricRecords_Truncate"); if (sValues.Trim().ToLower() == "deletebytruncateonstandardtables" || bIsFileBasedGDB) { bDeleteTablesByRowInsteadOfTruncate = false; } if (sValues.Trim().ToLower() == "deletebyrowonstandardtables") { bDeleteTablesByRowInsteadOfTruncate = true; } if (pTruncateDialog.TruncateControl && !pTruncateDialog.TruncateParcelsLinesPoints) { // get the control point count ITable pControlTable = m_pCadaFab.get_CadastralTable(esriCadastralFabricTable.esriCFTControl); iControlRowCount = pControlTable.RowCount(null); } try { //Work on the table array pTable = null; m_pFIDSet = new FIDSetClass(); for (int i = 0; i <= TableArray.Count - 1; i++) { //if (TableArray.get_Element(i) is ITable) ...redundant { pTable = (ITable)TableArray.get_Element(i); IDataset pDataSet = (IDataset)pTable; //Following code uses the truncate method //*** if (pTable is IFeatureClass || !bDeleteTablesByRowInsteadOfTruncate) { ITableWrite2 pTableWr = (ITableWrite2)pTable; m_pStepProgressor.Message = "Deleting all rows in " + pDataSet.Name; int RowCnt = pTable.RowCount(null); pTableWr.Truncate(); m_pStepProgressor.MaxRange -= RowCnt; //now re-insert the default plan string sName = pDataSet.Name.ToUpper().Trim(); if (sName.EndsWith("_PLANS")) { int idxPlanName = pTable.FindField("Name"); int idxPlanDescription = pTable.FindField("Description"); int idxPlanAngleUnits = pTable.FindField("AngleUnits"); int idxPlanAreaUnits = pTable.FindField("AreaUnits"); int idxPlanDistanceUnits = pTable.FindField("DistanceUnits"); int idxPlanDirectionFormat = pTable.FindField("DirectionFormat"); int idxPlanLineParameters = pTable.FindField("LineParameters"); int idxPlanCombinedGridFactor = pTable.FindField("CombinedGridFactor"); int idxPlanTrueMidBrg = pTable.FindField("TrueMidBrg"); int idxPlanAccuracy = pTable.FindField("Accuracy"); int idxPlanInternalAngles = pTable.FindField("InternalAngles"); ICursor pCur = pTableWr.InsertRows(false); IRowBuffer pRowBuff = pTable.CreateRowBuffer(); double dOneMeterEquals = FabricUTILS.ConvertMetersToFabricUnits(1, m_pCadaFab); bool bIsMetric = (dOneMeterEquals == 1); //write category 1 pRowBuff.set_Value(idxPlanName, "<map>"); pRowBuff.set_Value(idxPlanDescription, "System default plan"); pRowBuff.set_Value(idxPlanAngleUnits, 3); // if (bIsMetric) { pRowBuff.set_Value(idxPlanAreaUnits, 5); pRowBuff.set_Value(idxPlanDistanceUnits, 9001); pRowBuff.set_Value(idxPlanDirectionFormat, 1); } else { pRowBuff.set_Value(idxPlanAreaUnits, 4); pRowBuff.set_Value(idxPlanDistanceUnits, 9003); pRowBuff.set_Value(idxPlanDirectionFormat, 4); } pRowBuff.set_Value(idxPlanLineParameters, 4); pRowBuff.set_Value(idxPlanCombinedGridFactor, 1); //pRowBuff.set_Value(idxPlanTrueMidBrg, 1); pRowBuff.set_Value(idxPlanAccuracy, 4); pRowBuff.set_Value(idxPlanInternalAngles, 0); pCur.InsertRow(pRowBuff); pCur.Flush(); if (pRowBuff != null) { Marshal.ReleaseComObject(pRowBuff); } if (pCur != null) { Marshal.ReleaseComObject(pCur); } } } } } } catch (COMException ex) { MessageBox.Show(ex.Message + ": " + Convert.ToString(ex.ErrorCode)); Cleanup(pProgressorDialog, pMouseCursor); return; } //do the loop again, this time within the edit transaction and using the delete function for the chosen tables try { //Start an Edit Transaction if (!FabricUTILS.StartEditing(pWS, bIsUnVersioned)) {//if start editing fails then bail Cleanup(pProgressorDialog, pMouseCursor); return; } for (int i = 0; i <= TableArray.Count - 1; i++) { //if (TableArray.get_Element(i) is ITable) { pTable = (ITable)TableArray.get_Element(i); IDataset pDataSet = (IDataset)pTable; if (pTable is IFeatureClass || !bDeleteTablesByRowInsteadOfTruncate) { } else { //The following code is in place to workaround a limitation of truncate for fabric classes //without a shapefield. It uses an alternative method for removing all the rows //with the Delete function. //General note: This method could be used exclusively, without needing the truncate method. //One advantage is that it allows the option to cancel the whole //operation using the cancel tracker. Truncate is faster, but is problematic if //the truncate fails, and leaves a partially deleted fabric. For example, if the //lines table is deleted but the points table truncate fails, the fabric would be in a //corrupt state. //**** m_pFIDSet.SetEmpty(); string sName = pDataSet.Name.ToUpper().Trim(); m_pStepProgressor.Message = "Loading rows from " + pDataSet.Name; if (sName.EndsWith("_PLANS")) {//for Plans table make sure the default plan is not deleted IQueryFilter pQF = new QueryFilterClass(); string sPref; string sSuff; ISQLSyntax pSQLSyntax = (ISQLSyntax)pWS; sPref = pSQLSyntax.GetSpecialCharacter(esriSQLSpecialCharacters.esriSQL_DelimitedIdentifierPrefix); sSuff = pSQLSyntax.GetSpecialCharacter(esriSQLSpecialCharacters.esriSQL_DelimitedIdentifierSuffix); string sFieldName = "NAME"; //pQF.WhereClause = sPref + sFieldName + sSuff + " <> '<map>'"; pQF.WhereClause = sFieldName + " <> '<map>'"; if (!BuildFIDSetFromTable(pTable, pQF, ref m_pFIDSet)) { FabricUTILS.AbortEditing(pWS); Cleanup(pProgressorDialog, pMouseCursor); return; } } else { if (!BuildFIDSetFromTable(pTable, null, ref m_pFIDSet)) { FabricUTILS.AbortEditing(pWS); Cleanup(pProgressorDialog, pMouseCursor); return; } } if (m_pFIDSet.Count() == 0) { continue; } m_pStepProgressor.Message = "Deleting all rows in " + pDataSet.Name; bSuccess = FabricUTILS.DeleteRowsUnversioned(pWS, pTable, m_pFIDSet, m_pStepProgressor, m_pTrackCancel); if (!bSuccess) { FabricUTILS.AbortEditing(pWS); Cleanup(pProgressorDialog, pMouseCursor); return; } } } } //now need to Fix control-to-point associations if one table was truncated //and the other was not if (pTruncateDialog.TruncateControl && !pTruncateDialog.TruncateParcelsLinesPoints) { IQueryFilter pQF = new QueryFilterClass(); string sPref; string sSuff; ISQLSyntax pSQLSyntax = (ISQLSyntax)pWS; sPref = pSQLSyntax.GetSpecialCharacter(esriSQLSpecialCharacters.esriSQL_DelimitedIdentifierPrefix); sSuff = pSQLSyntax.GetSpecialCharacter(esriSQLSpecialCharacters.esriSQL_DelimitedIdentifierSuffix); ITable PointTable = m_pCadaFab.get_CadastralTable(esriCadastralFabricTable.esriCFTPoints); m_pStepProgressor.Message = "Resetting control associations on points...please wait."; int idxFld = PointTable.FindField("NAME"); string sFieldName = PointTable.Fields.get_Field(idxFld).Name; //NAME IS NOT NULL AND (NAME <>'' OR NAME <>' ') //pQF.WhereClause = sPref + sFieldName + sSuff + " IS NOT NULL AND (" + // sPref + sFieldName + sSuff + "<>'' OR " + sPref + sFieldName + sSuff + " <>' ')"; //pQF.WhereClause = sFieldName + " IS NOT NULL AND (" + sFieldName + "<>'' OR " + sFieldName + " <>' ')"; pQF.WhereClause = sFieldName + " IS NOT NULL AND " + sFieldName + " > ''"; //changed 1/14/2016 ICadastralFabricSchemaEdit2 pSchemaEd = (ICadastralFabricSchemaEdit2)m_pCadaFab; pSchemaEd.ReleaseReadOnlyFields(PointTable, esriCadastralFabricTable.esriCFTPoints); m_pStepProgressor.MinRange = 0; m_pStepProgressor.MaxRange = iControlRowCount; if (!ResetPointAssociations(PointTable, pQF, true, m_pStepProgressor, m_pTrackCancel)) { pSchemaEd.ResetReadOnlyFields(esriCadastralFabricTable.esriCFTPoints); FabricUTILS.AbortEditing(pWS); Cleanup(pProgressorDialog, pMouseCursor); return; } pSchemaEd.ResetReadOnlyFields(esriCadastralFabricTable.esriCFTPoints); } else if (pTruncateDialog.TruncateParcelsLinesPoints && !pTruncateDialog.TruncateControl) { IQueryFilter pQF = new QueryFilterClass(); string sPref; string sSuff; ISQLSyntax pSQLSyntax = (ISQLSyntax)pWS; sPref = pSQLSyntax.GetSpecialCharacter(esriSQLSpecialCharacters.esriSQL_DelimitedIdentifierPrefix); sSuff = pSQLSyntax.GetSpecialCharacter(esriSQLSpecialCharacters.esriSQL_DelimitedIdentifierSuffix); //POINTID >=0 AND POINTID IS NOT NULL m_pStepProgressor.Message = "Resetting associations on control points...please wait."; ITable ControlTable = m_pCadaFab.get_CadastralTable(esriCadastralFabricTable.esriCFTControl); int idxFld = ControlTable.FindField("POINTID"); string sFieldName = ControlTable.Fields.get_Field(idxFld).Name; //pQF.WhereClause = sPref + sFieldName + sSuff + " IS NOT NULL AND " + // sPref + sFieldName + sSuff + " >=0"; pQF.WhereClause = sFieldName + " IS NOT NULL AND " + sFieldName + " >=0"; ICadastralFabricSchemaEdit2 pSchemaEd = (ICadastralFabricSchemaEdit2)m_pCadaFab; pSchemaEd.ReleaseReadOnlyFields(ControlTable, esriCadastralFabricTable.esriCFTControl); if (!FabricUTILS.ResetControlAssociations(ControlTable, null, true)) { pSchemaEd.ResetReadOnlyFields(esriCadastralFabricTable.esriCFTControl); FabricUTILS.AbortEditing(pWS); Cleanup(pProgressorDialog, pMouseCursor); return; } pSchemaEd.ResetReadOnlyFields(esriCadastralFabricTable.esriCFTControl); } //now need to re-assign default accuracy table values, if the option was checked if (pTruncateDialog.ResetAccuracyTableDefaults) { double dCat1 = FabricUTILS.ConvertMetersToFabricUnits(0.001, m_pCadaFab); double dCat2 = FabricUTILS.ConvertMetersToFabricUnits(0.01, m_pCadaFab); double dCat3 = FabricUTILS.ConvertMetersToFabricUnits(0.02, m_pCadaFab); double dCat4 = FabricUTILS.ConvertMetersToFabricUnits(0.05, m_pCadaFab); double dCat5 = FabricUTILS.ConvertMetersToFabricUnits(0.2, m_pCadaFab); double dCat6 = FabricUTILS.ConvertMetersToFabricUnits(1, m_pCadaFab); double dCat7 = FabricUTILS.ConvertMetersToFabricUnits(10, m_pCadaFab); ITable pAccTable = m_pCadaFab.get_CadastralTable(esriCadastralFabricTable.esriCFTAccuracy); int idxBrgSD = pAccTable.FindField("BrgSD"); int idxDistSD = pAccTable.FindField("DistSD"); int idxPPM = pAccTable.FindField("PPM"); int idxCategory = pAccTable.FindField("Category"); int idxDescription = pAccTable.FindField("Description"); ITableWrite2 pTableWr = (ITableWrite2)pAccTable; ICursor pCur = pTableWr.InsertRows(false); IRowBuffer pRowBuff = pAccTable.CreateRowBuffer(); //write category 1 pRowBuff.set_Value(idxCategory, 1); pRowBuff.set_Value(idxBrgSD, 5); pRowBuff.set_Value(idxDistSD, dCat1); pRowBuff.set_Value(idxPPM, 5); pRowBuff.set_Value(idxDescription, "1 - Highest"); pCur.InsertRow(pRowBuff); //write category 2 pRowBuff.set_Value(idxCategory, 2); pRowBuff.set_Value(idxBrgSD, 30); pRowBuff.set_Value(idxDistSD, dCat2); pRowBuff.set_Value(idxPPM, 25); pRowBuff.set_Value(idxDescription, "2 - After 1980"); pCur.InsertRow(pRowBuff); //write category 3 pRowBuff.set_Value(idxCategory, 3); pRowBuff.set_Value(idxBrgSD, 60); pRowBuff.set_Value(idxDistSD, dCat3); pRowBuff.set_Value(idxPPM, 50); pRowBuff.set_Value(idxDescription, "3 - 1908 to 1980"); pCur.InsertRow(pRowBuff); //write category 4 pRowBuff.set_Value(idxCategory, 4); pRowBuff.set_Value(idxBrgSD, 120); pRowBuff.set_Value(idxDistSD, dCat4); pRowBuff.set_Value(idxPPM, 125); pRowBuff.set_Value(idxDescription, "4 - 1881 to 1907"); pCur.InsertRow(pRowBuff); //write category 5 pRowBuff.set_Value(idxCategory, 5); pRowBuff.set_Value(idxBrgSD, 300); pRowBuff.set_Value(idxDistSD, dCat5); pRowBuff.set_Value(idxPPM, 125); pRowBuff.set_Value(idxDescription, "5 - Before 1881"); pCur.InsertRow(pRowBuff); //write category 6 pRowBuff.set_Value(idxCategory, 6); pRowBuff.set_Value(idxBrgSD, 3600); pRowBuff.set_Value(idxDistSD, dCat6); pRowBuff.set_Value(idxPPM, 1000); pRowBuff.set_Value(idxDescription, "6 - 1800"); pCur.InsertRow(pRowBuff); //write category 7 pRowBuff.set_Value(idxCategory, 7); pRowBuff.set_Value(idxBrgSD, 6000); pRowBuff.set_Value(idxDistSD, dCat7); pRowBuff.set_Value(idxPPM, 5000); pRowBuff.set_Value(idxDescription, "7 - Lowest"); pCur.InsertRow(pRowBuff); pCur.Flush(); if (pRowBuff != null) { Marshal.ReleaseComObject(pRowBuff); } if (pCur != null) { Marshal.ReleaseComObject(pCur); } } //now need to cleanup the IDSequence table if ALL the tables were truncated if (pTruncateDialog.TruncateControl && pTruncateDialog.TruncateParcelsLinesPoints && pTruncateDialog.TruncateJobs && pTruncateDialog.TruncateAdjustments) { IWorkspace2 pWS2 = (IWorkspace2)pWS; IDataset TheFabricDS = (IDataset)m_pCadaFab; string sFabricName = TheFabricDS.Name; string sName = sFabricName + "_IDSequencer"; bool bExists = pWS2.get_NameExists(esriDatasetType.esriDTTable, sName); IFeatureWorkspace pFWS = (IFeatureWorkspace)pWS; ITable pSequencerTable; if (bExists) { pSequencerTable = pFWS.OpenTable(sName); IFIDSet pFIDSet = new FIDSetClass(); if (BuildFIDSetFromTable(pSequencerTable, null, ref pFIDSet)) { FabricUTILS.DeleteRowsUnversioned(pWS, pSequencerTable, pFIDSet, null, null); } } } Cleanup(pProgressorDialog, pMouseCursor); if (TableArray != null) { TableArray.RemoveAll(); } FabricUTILS.StopEditing(pWS); } catch (Exception ex) { FabricUTILS.AbortEditing(pWS); Cleanup(pProgressorDialog, pMouseCursor); MessageBox.Show(Convert.ToString(ex.Message)); } }
//added by chulili 20110715 //导入excel文件,内容写入数据字典所选表格中 //excel文件第一行对应表格的字段名称(别名),第二行开始是记录内容 public static void ImportExcelToTableEx(string strFilename, string strTablename, bool isCovered) { SysCommon.CProgress vProgress = new SysCommon.CProgress("进度条"); vProgress.EnableCancel = false; vProgress.ShowDescription = true; vProgress.FakeProgress = false; vProgress.TopMost = true; vProgress.MaxValue = 5; vProgress.ShowProgress(); vProgress.SetProgress("导入Excel表格"); IFeatureWorkspace pFeatureWks = null; ITable pTable = null; try { pFeatureWks = Plugin.ModuleCommon.TmpWorkSpace as IFeatureWorkspace; pTable = pFeatureWks.OpenTable(strTablename); } catch { vProgress.Close(); return; } if (pTable == null) { vProgress.Close(); return; } string strConn; vProgress.SetProgress(1, "打开Excel文件"); strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + strFilename + ";Extended Properties='Excel 8.0;HDR=Yes;IMEX=1'"; OleDbConnection conn = new OleDbConnection(strConn); conn.Open(); //获取EXCEL文件内工作表名称 added by chulili 20110924 DataTable dt = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null); string SheetName = "Sheet1$"; if (dt != null) { if (dt.Rows.Count > 0) { SheetName = dt.Rows[0][2].ToString();//默认取第一张工作表 } } dt = null; OleDbCommand pCommand = null; OleDbDataReader pReader = null; try { vProgress.SetProgress("读取Excel文件表格内容"); pCommand = new OleDbCommand("SELECT * FROM [" + SheetName + "]", conn); pReader = pCommand.ExecuteReader(); } catch { conn.Close(); vProgress.Close(); return; } if (pReader == null) { conn.Close(); vProgress.Close(); return; } Dictionary <int, int> pDicFieldname = new Dictionary <int, int>(); for (int i = 0; i < pReader.FieldCount; i++) { string strFieldname = pReader.GetName(i); int j = pTable.Fields.FindFieldByAliasName(strFieldname); pDicFieldname.Add(i, j); } ICursor pCursor = null; try { if (isCovered) { vProgress.SetProgress("清除'" + strTablename + "'中记录"); pTable.DeleteSearchedRows(null); } vProgress.SetProgress("将Excel中表格内容写入'" + strTablename + "'"); pCursor = pTable.Insert(true); int Rowcnt = 0; while (pReader.Read()) { IRowBuffer pRowbuffer = pTable.CreateRowBuffer(); for (int i = 0; i < pReader.FieldCount; i++) { try { int index = pDicFieldname[i]; if (index < 0) { continue; } //OID列不允许赋值 if (pRowbuffer.Fields.get_Field(index).Type == esriFieldType.esriFieldTypeOID) { continue; } object objText = null; if (pReader[i].ToString() != "") { objText = pReader[i].ToString(); } if (index >= 0) { if (objText != null) { pRowbuffer.set_Value(index, objText); } else { pRowbuffer.set_Value(index, DBNull.Value as object); } } } catch (System.Exception ex) { } } pCursor.InsertRow(pRowbuffer); Rowcnt = Rowcnt + 1; if (Rowcnt % 1000 == 0) { pCursor.Flush(); } } pCursor.Flush(); System.Runtime.InteropServices.Marshal.ReleaseComObject(pCursor); pCursor = null; pReader.Close(); conn.Close(); vProgress.Close(); } catch { if (pCursor != null) { System.Runtime.InteropServices.Marshal.ReleaseComObject(pCursor); pCursor = null; } pReader.Close(); conn.Close(); vProgress.Close(); } }
private void buildZoneClassCount() { string cTblName = geoUtil.getSafeOutputNameNonRaster(wks, tblName.Replace("_VAT", "_CLASS")); if (rd != null) { rd.addMessage("Output table name = " + wks.PathName + "\\" + cTblName); } IFields nflds = new FieldsClass(); IFieldsEdit nfldsE = (IFieldsEdit)nflds; IField nfld = new FieldClass(); IFieldEdit nfldE = (IFieldEdit)nfld; nfldE.Name_2 = "Band"; nfldE.Type_2 = esriFieldType.esriFieldTypeDouble; nfldsE.AddField(nfldE); IField nfld2 = new FieldClass(); IFieldEdit nfld2E = (IFieldEdit)nfld2; nfld2E.Name_2 = "Zone"; nfld2E.Type_2 = esriFieldType.esriFieldTypeDouble; nfldsE.AddField(nfld2E); IField nfld4 = new FieldClass(); IFieldEdit nfld4E = (IFieldEdit)nfld4; nfld4E.Name_2 = "Class"; nfld4E.Type_2 = esriFieldType.esriFieldTypeDouble; nfldsE.AddField(nfld4E); IField nfld3 = new FieldClass(); IFieldEdit nfld3E = (IFieldEdit)nfld3; nfld3E.Name_2 = "Count"; nfld3E.Type_2 = esriFieldType.esriFieldTypeDouble; nfldsE.AddField(nfld3E); oTbl2 = geoUtil.createTable(wks, cTblName, nflds); IWorkspaceEdit wksE = (IWorkspaceEdit)wks; if (wksE.IsBeingEdited()) { wksE.StopEditing(true); } //ITransactions trs = (ITransactions)wks; //trs.StartTransaction(); try { int bdIndex = oTbl2.FindField("Band"); int vlIndex = oTbl2.FindField("Zone"); int cntIndex = oTbl2.FindField("Count"); int clsIndex = oTbl2.FindField("Class"); int bndCnt = 1; ICursor cur = oTbl2.Insert(true); IRowBuffer rw = oTbl2.CreateRowBuffer(); foreach (Dictionary <double, object[]> zoneValueDicOut in zoneValueDicArr) { foreach (KeyValuePair <double, object[]> kVp in zoneValueDicOut) { double key = kVp.Key; object[] vl = kVp.Value; Dictionary <double, int> uDic = (Dictionary <double, int>)vl[5]; foreach (KeyValuePair <double, int> uKvp in uDic) { double uDicKey = uKvp.Key; int uDicVl = uKvp.Value; rw.set_Value(bdIndex, bndCnt); rw.set_Value(vlIndex, key); rw.set_Value(cntIndex, uDicVl); rw.set_Value(clsIndex, uDicKey); cur.InsertRow(rw); } } bndCnt += 1; } cur.Flush(); System.Runtime.InteropServices.Marshal.ReleaseComObject(cur); System.Runtime.InteropServices.Marshal.ReleaseComObject(rw); //trs.CommitTransaction(); } catch (Exception e) { Console.WriteLine(e.ToString()); //trs.AbortTransaction(); } finally { } }
private void btnBoxplot_Click(object sender, EventArgs e) { try { #region Combined Chart string strTargetLayerName = cboTargetLayer.Text; string strFieldName = cboFieldName.Text; string strGroupFieldName = cboGroupField.Text; int intTargetIndex = m_pSnippet.GetIndexNumberFromLayerName(m_pActiveView, strTargetLayerName); int intNFeatureCount = 0; ILayer pTargetLayer = m_pForm.axMapControl1.get_Layer(intTargetIndex); IFeatureLayer pTargetFLayer = (IFeatureLayer)pTargetLayer; //Extract geometry from selected feature IFeatureCursor pFCursor = null; pFCursor = pTargetFLayer.Search(null, true); intNFeatureCount = pTargetFLayer.FeatureClass.FeatureCount(null); int intFieldIdx = pTargetFLayer.FeatureClass.Fields.FindField(strFieldName); int intGroupIdx = pTargetFLayer.FeatureClass.Fields.FindField(strGroupFieldName); System.Collections.Generic.List <object> uvList = new System.Collections.Generic.List <object>(); ICursor ipCursor = pFCursor as ICursor; IRow ipRow = ipCursor.NextRow(); while (ipRow != null) { object curValue = ipRow.get_Value(intGroupIdx); if (!uvList.Contains(curValue)) { uvList.Add(curValue); } ipRow = ipCursor.NextRow(); } uvList.Sort(); //Add exeption for sorting //0421 HK //1. H L M if (uvList.Count == 3) { if (uvList[0].ToString() == "H" && uvList[1].ToString() == "L" && uvList[2].ToString() == "M") { uvList.Clear(); uvList.Add("L"); uvList.Add("M"); uvList.Add("H"); } if (uvList[0].ToString() == "High" && uvList[1].ToString() == "Low" && uvList[2].ToString() == "Medium") { uvList.Clear(); uvList.Add("Low"); uvList.Add("Medium"); uvList.Add("High"); } } ipCursor.Flush(); int intNGroups = uvList.Count; double[,] adbBPStats = new double[5, uvList.Count]; double[,] adbQuantiles = new double[5, uvList.Count]; IQueryFilter pQfilter = new QueryFilterClass(); double[][] adblTarget = new double[intNGroups][]; double[][] adblDiff = new double[intNGroups][]; int[] aintNCounts = new int[intNGroups]; int i = 0; foreach (string uvValue in uvList) { pQfilter.WhereClause = strGroupFieldName + " = '" + uvValue + "'"; pFCursor = pTargetFLayer.Search(pQfilter, true); IFeature pFeature = pFCursor.NextFeature(); intNFeatureCount = pTargetFLayer.FeatureClass.FeatureCount(pQfilter); aintNCounts[i] = intNFeatureCount; adblTarget[i] = new double[intNFeatureCount]; adblDiff[i] = new double[intNFeatureCount]; int j = 0; while (pFeature != null) { adblTarget[i][j] = Convert.ToDouble(pFeature.get_Value(intFieldIdx)); j++; pFeature = pFCursor.NextFeature(); } pFCursor.Flush(); double[] dblQuantiles = new double[5]; dblQuantiles = BoxPlotStats(adblTarget[i]); adblDiff[i] = GetStatsForStackedBarChart(adblTarget[i]); for (int k = 0; k < 5; k++) // Needs to be modified 010716 HK { adbQuantiles[k, i] = dblQuantiles[k]; } i++; } frmBoxPlotResults pfrmBoxplotResults = new frmBoxPlotResults(); pfrmBoxplotResults.Text = "BoxPlot of " + pTargetFLayer.Name; pfrmBoxplotResults.pChart.Series.Clear(); ChartArea area = pfrmBoxplotResults.pChart.ChartAreas[0]; int intMaxFeatureNCount = aintNCounts.Max(); //Draw Lines for (int k = 0; k < intNGroups; k++) { int intXvalue = k * 2 + 1; double dblXmin = Convert.ToDouble(intXvalue) - 0.6; double dblXmax = Convert.ToDouble(intXvalue) + 0.6; double dblXBoxMin = Convert.ToDouble(intXvalue) - 0.8; double dblXBoxMax = Convert.ToDouble(intXvalue) + 0.8; AddLineSeries(pfrmBoxplotResults, "min_" + k.ToString(), Color.Black, 1, ChartDashStyle.Solid, dblXmin, dblXmax, adbQuantiles[0, k], adbQuantiles[0, k]); AddLineSeries(pfrmBoxplotResults, "BoxBottom_" + k.ToString(), Color.Black, 1, ChartDashStyle.Solid, dblXBoxMin, dblXBoxMax, adbQuantiles[1, k], adbQuantiles[1, k]); AddLineSeries(pfrmBoxplotResults, "BoxLeft_" + k.ToString(), Color.Black, 1, ChartDashStyle.Solid, dblXBoxMin, dblXBoxMin, adbQuantiles[1, k], adbQuantiles[3, k]); AddLineSeries(pfrmBoxplotResults, "BoxRight_" + k.ToString(), Color.Black, 1, ChartDashStyle.Solid, dblXBoxMax, dblXBoxMax, adbQuantiles[1, k], adbQuantiles[3, k]); AddLineSeries(pfrmBoxplotResults, "Boxup_" + k.ToString(), Color.Black, 1, ChartDashStyle.Solid, dblXBoxMin, dblXBoxMax, adbQuantiles[3, k], adbQuantiles[3, k]); AddLineSeries(pfrmBoxplotResults, "median_" + k.ToString(), Color.Black, 2, ChartDashStyle.Solid, dblXBoxMin, dblXBoxMax, adbQuantiles[2, k], adbQuantiles[2, k]); AddLineSeries(pfrmBoxplotResults, "max_" + k.ToString(), Color.Black, 1, ChartDashStyle.Solid, dblXmin, dblXmax, adbQuantiles[4, k], adbQuantiles[4, k]); AddLineSeries(pfrmBoxplotResults, "verDown_" + k.ToString(), Color.Black, 1, ChartDashStyle.Dash, intXvalue, intXvalue, adbQuantiles[0, k], adbQuantiles[1, k]); AddLineSeries(pfrmBoxplotResults, "verUp_" + k.ToString(), Color.Black, 1, ChartDashStyle.Dash, intXvalue, intXvalue, adbQuantiles[3, k], adbQuantiles[4, k]); } //Add Points System.Drawing.Color pMarkerColor = System.Drawing.Color.Blue; var seriesOutPts = new System.Windows.Forms.DataVisualization.Charting.Series { Name = "Points", Color = pMarkerColor, BorderColor = pMarkerColor, IsVisibleInLegend = false, IsXValueIndexed = false, ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Point, MarkerStyle = System.Windows.Forms.DataVisualization.Charting.MarkerStyle.Circle }; pfrmBoxplotResults.pChart.Series.Add(seriesOutPts); for (int k = 0; k < intNGroups; k++) { int intXvalue = k * 2 + 1; foreach (double dblValue in adblTarget[k]) { //if (dblValue < adbQuantiles[1, k] || dblValue > adbQuantiles[3, k]) seriesOutPts.Points.AddXY(intXvalue, dblValue); } } pMarkerColor = System.Drawing.Color.Black; var seriesInPts = new System.Windows.Forms.DataVisualization.Charting.Series { Name = "InPoints", Color = pMarkerColor, BorderColor = pMarkerColor, IsVisibleInLegend = false, IsXValueIndexed = false, ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Point, MarkerStyle = System.Windows.Forms.DataVisualization.Charting.MarkerStyle.Circle }; pfrmBoxplotResults.pChart.Series.Add(seriesInPts); for (int k = 0; k < intNGroups; k++) { int intXvalue = k * 2 + 1; foreach (double dblValue in adblTarget[k]) { if (dblValue >= adbQuantiles[1, k] && dblValue <= adbQuantiles[3, k]) { seriesInPts.Points.AddXY(intXvalue, dblValue); } } } //Store variables in frmBoxPlotResults pfrmBoxplotResults.mForm = m_pForm; pfrmBoxplotResults.pActiveView = m_pActiveView; pfrmBoxplotResults.pFLayer = pTargetFLayer; pfrmBoxplotResults.Text = "Boxplot of " + pTargetFLayer.Name; pfrmBoxplotResults.strFieldName = strFieldName; pfrmBoxplotResults.strGroupFieldName = strGroupFieldName; pfrmBoxplotResults.uvList = uvList; //pfrmBoxplotResults.pFillColor = pFillColor; pfrmBoxplotResults.adbQuantiles = adbQuantiles; pfrmBoxplotResults.pChart.ChartAreas[0].AxisX.Title = strGroupFieldName; pfrmBoxplotResults.pChart.ChartAreas[0].AxisY.Title = strFieldName; pfrmBoxplotResults.pChart.ChartAreas[0].AxisY.IsStartedFromZero = false; pfrmBoxplotResults.pChart.ChartAreas[0].AxisX.Maximum = intNGroups * 2; pfrmBoxplotResults.pChart.ChartAreas[0].AxisX.Interval = 2; pfrmBoxplotResults.pChart.ChartAreas[0].AxisX.Minimum = 0; pfrmBoxplotResults.pChart.ChartAreas[0].AxisX.IntervalOffset = -1; pfrmBoxplotResults.pChart.ChartAreas[0].AxisX.IsLabelAutoFit = false; for (int n = 0; n < uvList.Count; n++) { int intXvalue = n * 2 + 1; double dblXmin = Convert.ToDouble(intXvalue) - 0.6; double dblXmax = Convert.ToDouble(intXvalue) + 0.6; CustomLabel pcutsomLabel = new CustomLabel(); pcutsomLabel.FromPosition = dblXmin; pcutsomLabel.ToPosition = dblXmax; pcutsomLabel.Text = uvList[n].ToString(); pfrmBoxplotResults.pChart.ChartAreas[0].AxisX.CustomLabels.Add(pcutsomLabel); } #endregion pfrmBoxplotResults.Show(); #region Previous Method (ChartType = SeriesChartType.BoxPlot) //Previous Method using Boxplot Chart Type (01/07/16) //string strTargetLayerName = cboTargetLayer.Text; //string strFieldName = cboFieldName.Text; //string strGroupFieldName = cboGroupField.Text; //int intTargetIndex = pSnippet.GetIndexNumberFromLayerName(pActiveView, strTargetLayerName); //int intNFeatureCount = 0; //ILayer pTargetLayer = mForm.axMapControl1.get_Layer(intTargetIndex); //IFeatureLayer pTargetFLayer = (IFeatureLayer)pTargetLayer; ////Extract geometry from selected feature //IFeatureCursor pFCursor = null; //pFCursor = pTargetFLayer.Search(null, true); //intNFeatureCount = pTargetFLayer.FeatureClass.FeatureCount(null); //int intFieldIdx = pTargetFLayer.FeatureClass.Fields.FindField(strFieldName); //int intGroupIdx = pTargetFLayer.FeatureClass.Fields.FindField(strGroupFieldName); //System.Collections.Generic.List<object> uvList = new System.Collections.Generic.List<object>(); //ICursor ipCursor = pFCursor as ICursor; //IRow ipRow = ipCursor.NextRow(); //while (ipRow != null) //{ // object curValue = ipRow.get_Value(intGroupIdx); // if (!uvList.Contains(curValue)) // { // uvList.Add(curValue); // } // ipRow = ipCursor.NextRow(); //} //uvList.Sort(); //double[] adblTarget = new double[intNFeatureCount]; //string[] astrGroup = new string[intNFeatureCount]; //IQueryFilter pQfilter = new QueryFilterClass(); //frmBoxPlotResults pfrmBoxplotResults = new frmBoxPlotResults(); //pfrmBoxplotResults.pChart.Series.Clear(); //ChartArea area = pfrmBoxplotResults.pChart.ChartAreas[0]; //Series DataSeries = new Series(); //foreach (string uvValue in uvList) //{ // pQfilter.WhereClause = strGroupFieldName + " = '" + uvValue + "'"; // pFCursor = pTargetFLayer.Search(pQfilter, true); // IFeature pFeature = pFCursor.NextFeature(); // intNFeatureCount = pTargetFLayer.FeatureClass.FeatureCount(pQfilter); // adblTarget = new double[intNFeatureCount]; // int j = 0; // while (pFeature != null) // { // adblTarget[j] = Convert.ToDouble(pFeature.get_Value(intFieldIdx)); // j++; // pFeature = pFCursor.NextFeature(); // } // DataSeries = new Series(uvValue); // DataSeries.ChartArea = area.Name; // DataSeries.Color = Color.Transparent; // DataSeries.Points.DataBindY(adblTarget); // DataSeries.XValueType = ChartValueType.String; // //DataSeries.IsXValueIndexed = true; // pfrmBoxplotResults.pChart.Series.Add(DataSeries); //} //Series BoxPlotSeries = new Series() //{ // Name = "BoxPlotSeries", // ChartArea = area.Name, // ChartType = SeriesChartType.BoxPlot, // Color = Color.White, // BorderColor = Color.Black, // // IsXValueIndexed = true, //XValueType = ChartValueType.String, //}; //pfrmBoxplotResults.pChart.Series.Add(BoxPlotSeries); //pfrmBoxplotResults.pChart.Series["BoxPlotSeries"]["BoxPlotSeries"] = string.Join(";", uvList); //pfrmBoxplotResults.pChart.ChartAreas[0].AxisX.IsMarksNextToAxis = false; ////Manually Change the labels for Boxplot -- Needs to be modified 011117 HK //for (int n = 0; n <= uvList.Count; n++) //{ // //pfrmBoxplotResults.pChart.Series["BoxPlotSeries"].Points[n].AxisLabel = uvList[n].ToString(); // if (n == uvList.Count) // pfrmBoxplotResults.pChart.Series[0].Points[n].AxisLabel = " "; // else // pfrmBoxplotResults.pChart.Series[0].Points[n].AxisLabel = uvList[n].ToString(); // //area.AxisX.CustomLabels[n].Text = uvList[n].ToString(); //} //area.AxisX.Maximum = uvList.Count + 1; //area.AxisX.Minimum = 0; //pfrmBoxplotResults.Show(); #endregion } catch (Exception ex) { frmErrorLog pfrmErrorLog = new frmErrorLog(); pfrmErrorLog.ex = ex; pfrmErrorLog.ShowDialog(); return; } }