private void btnProcesar_Click_1(object sender, EventArgs e) { statusLblProcesando.Text = "Procesando datos..."; IProgressDialogFactory pProDiaFac = new ProgressDialogFactoryClass(); IStepProgressor pStepPro = pProDiaFac.Create(null, 0); pStepPro.MinRange = 1; pStepPro.MaxRange = 5; pStepPro.StepValue = 1; IProgressDialog2 pProDia = (IProgressDialog2)pStepPro; pProDia.Animation = esriProgressAnimationTypes.esriProgressGlobe; pProDia.Title = "Incorporando Lecturas"; pProDia.ShowDialog(); pStepPro.Step(); pStepPro.Message = "Procesando precipitacion..."; ProcesarLecturas procesarLecturas = new ProcesarLecturas(); try { procesarLecturas.CalcularResultadosPrecipitacion(_sigpiDao, "DEFI_PRECI", "LECTUS_PRECI", dtPickerFechaAProcesar.Value, 10); } catch (Exception ex) { MessageBox.Show("Error procesando las lecturas:\n" + ex.Message); } pStepPro.Step(); pStepPro.Message = "Procesando Temperatura..."; try { procesarLecturas.CalcularResultadosTemperatura(_sigpiDao, "DEFI_TEMPE", "LECTUS_TEMPE", dtPickerFechaAProcesar.Value, "T5", 10); } catch (Exception ex) { MessageBox.Show("Error procesando las lecturas:\n" + ex.Message); } string sSQL = "UPDATE FECHAS_PROCESO SET FEC_PROCE = #" + dtPickerFechaAProcesar.Value.ToString("MM/dd/yyyy") + "#"; try { _sigpiDao.EjecutarSentenciaSinQuery(sSQL); } catch (Exception ex) { MessageBox.Show("No se pudo actualizar la fecha de incorporacion.\n" + ex.Message); } _sigpi.FechaProcesamiento = dtPickerFechaAProcesar.Value; txtUltimaFechaProceso.Text = dtPickerFechaAProcesar.Value.ToLongDateString(); pProDia.HideDialog(); MessageBox.Show("Datos Procesados"); }
/// <summary> /// Increments the progress bar and updates the status bar with specified status message. /// </summary> /// <param name="statusMessage">The status message.</param> public virtual bool Step(string statusMessage) { _ProgressBar.Step(); _ProgressBar.Show(); _ProgressBar.Message = statusMessage; return(true); }
private void button4_Click(object sender, EventArgs e) { this.Cursor = Cursors.WaitCursor; DateTime fechaProcesamiento = sigpi.FechaProcesamiento; IWorkspaceFactory pWF = new RasterWorkspaceFactoryClass(); IWorkspace pWorkspace = pWF.OpenFromFile(sigpi.Parametros.RutaSIGPI + "\\" + sigpi.Parametros.Raster, 0); IEnumDataset pEnumDS = pWorkspace.get_Datasets(esriDatasetType.esriDTRasterDataset); IDataset pDS = pEnumDS.Next(); List <string> capas = new List <string>(); while (pDS != null) { if (!pDS.Name.ToUpper().Contains("RASTER")) { capas.Add(pDS.Name.ToUpper()); } pDS = pEnumDS.Next(); } FrmProbabilidadCalculada frmProbabilidad = new FrmProbabilidadCalculada(capas.ToArray()); this.Cursor = Cursors.Default; if (frmProbabilidad.ShowDialog() == System.Windows.Forms.DialogResult.Cancel) { return; } int iNumDias = frmProbabilidad.NumeroDeDias; IProgressDialogFactory pProDiaFac = new ProgressDialogFactoryClass(); IStepProgressor pStepPro = pProDiaFac.Create(null, 0); pStepPro.MinRange = 1; pStepPro.MaxRange = 2; pStepPro.StepValue = 1; IProgressDialog2 pProDia = (IProgressDialog2)pStepPro; pProDia.Animation = esriProgressAnimationTypes.esriProgressGlobe; pProDia.Title = "Calcular Probabilidad"; pProDia.ShowDialog(); pStepPro.Step(); pStepPro.Message = "Calculando Probabilidad..."; try { procesamiento.ProbabilidadCalculada(frmProbabilidad.ModeloBase, iNumDias, sigpi, frmProbabilidad.OpcionDeGuardar); } catch (Exception ex) { MessageBox.Show(ex.Message); } pProDia.HideDialog(); MessageBox.Show("Se ha calculado el modelo y la probabilidad para el dia:\n" + sigpi.FechaProcesamiento); txtFechaUltimoModelo.Text = sigpi.FechaProcesamiento.ToLongDateString(); }
private void CloneFileList() { bool itWorked = false; int cloneCount = 1; // labeling the processor bar ITrackCancel trackcancel = new CancelTracker(); IProgressDialogFactory progressdialogfactory = new ProgressDialogFactoryClass(); IStepProgressor stepprogressor = progressdialogfactory.Create(trackcancel, _application.hWnd); stepprogressor.MinRange = 0; stepprogressor.MaxRange = _fileList.Count; stepprogressor.StepValue = 1; stepprogressor.Message = "Copying..."; IProgressDialog2 progressdialog = (IProgressDialog2)stepprogressor; // Creates and displays progressdialog.CancelEnabled = false; progressdialog.Description = "Copying {_fileList.Count} files..."; progressdialog.Title = MB_TITLE; progressdialog.Animation = esriProgressAnimationTypes.esriProgressSpiral; foreach (KeyValuePair <String, Boolean> file in _fileList) { if (file.Value) { progressdialog.Description = string.Format("Copying File {0} of {1}...", cloneCount, _fileList.Count); if (!itWorked) { SaveFileTypeList(GetExtension()); } itWorked = true; try { var sourceFile = txb_FileWorkspaceSrc.Text + @"\" + Utilities_General.AddPrefixAndSuffixToFileName(file.Key, txb_Prefix.Text, txb_Suffix.Text) + GetExtension(); var destinationFile = txb_FileWorkspaceDst.Text + @"\" + Utilities_General.AddPrefixAndSuffixToFileName(file.Key, txb_Prefix.Text, txb_Suffix.Text) + GetExtension(); System.IO.File.Copy(sourceFile, destinationFile); } catch (Exception yourBest) // but you don't succeed { yourBest.ToString(); // Just So We Get No Crashes ;) } stepprogressor.Step(); cloneCount++; } } trackcancel = null; stepprogressor = null; progressdialog.HideDialog(); progressdialog = null; //_activeView.Refresh(); }
private void ValidateFileList() { int cloneCount = 1; // labeling the processor bar ITrackCancel trackcancel = new CancelTracker(); IProgressDialogFactory progressdialogfactory = new ProgressDialogFactoryClass(); IStepProgressor stepprogressor = progressdialogfactory.Create(trackcancel, _application.hWnd); stepprogressor.MinRange = 0; stepprogressor.MaxRange = _fileList.Count; stepprogressor.StepValue = 1; stepprogressor.Message = "Validating..."; IProgressDialog2 progressdialog = (IProgressDialog2)stepprogressor; // Creates and displays progressdialog.CancelEnabled = false; progressdialog.Description = "Validating {_fileList.Count} files..."; progressdialog.Title = MB_TITLE; progressdialog.Animation = esriProgressAnimationTypes.esriProgressSpiral; IDictionary <String, Boolean> newList = new Dictionary <String, Boolean>(); foreach (KeyValuePair <String, Boolean> file in _fileList) { progressdialog.Description = string.Format("Validating {0} of {1}...", cloneCount, _fileList.Count); string filePath = txb_FileWorkspaceSrc.Text + "\\" + Utilities_General.AddPrefixAndSuffixToFileName(file.Key, txb_Prefix.Text, txb_Suffix.Text) + GetExtension(); if (!File.Exists(filePath)) { newList.Add(file.Key, false); } else { newList.Add(file.Key, file.Value); } stepprogressor.Step(); cloneCount++; } _fileList = newList; trackcancel = null; stepprogressor = null; progressdialog.HideDialog(); progressdialog = null; //_activeView.Refresh(); }
private bool ExportTable(Excel.Workbook ExcelWbk, IMxDocument MxDoc, IStandaloneTable StandTable, ref IProgressDialog2 progressDialog, ref IStepProgressor stepProgressor, ref ITrackCancel trackCancel) { ITableProperties TableProperties = null; IEnumTableProperties EnumTableProperties = null; ITableProperty3 TableProperty = null; ITableCharacteristics TableCharacteristics = null; ITableSelection TabSel = null; IDisplayTable DisplayTable = null; ITable Table = null; IRow TabRow = null; IObjectClass ObjectClass = null; ISubtypes Subtypes = null; ITableFields TableFields = null; ICursor Cursor = null; IField CurField = null; IDomain Domain = null; ICodedValueDomain CodedValueDomain = null; object missing = null; object sheet = null; Microsoft.Office.Interop.Excel.Style style = null; try { bool UseDescriptions; int subtype; string SheetName; int Col = 0; int Row = 0; int i; int j; missing = System.Reflection.Missing.Value; sheet = ExcelWbk.Sheets[ExcelWbk.Sheets.Count]; Excel.Worksheet ExcelSheet; Excel.Range ExcelRange; //Add new Excel worksheet ExcelSheet = (Excel.Worksheet)ExcelWbk.Sheets.Add(missing, sheet, missing, missing); //style = ExcelWbk.Styles.Add("Style1"); //style.NumberFormat = "@"; //style.Font.Name = "Arial"; //style.Font.Bold = True //style.Font.Size = 12; //style.Interior.Pattern = Microsoft.Office.Interop.Excel.XlPattern.xlPattern Solid //style.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlighLe ft SheetName = StandTable.Name; if (SheetName.Length > 30) { SheetName = SheetName.Substring(0, 30); } ExcelSheet.Name = SheetName; //Determine whether to use descriptions or codes for domains UseDescriptions = true; TableProperties = MxDoc.TableProperties; EnumTableProperties = (IEnumTableProperties)TableProperties; EnumTableProperties.Reset(); TableProperty = (ITableProperty3)EnumTableProperties.Next(); while (TableProperty != null) { if (TableProperty.StandaloneTable != null) { if (TableProperty.StandaloneTable.Equals(StandTable)) { TableCharacteristics = (ITableCharacteristics)TableProperty; UseDescriptions = TableCharacteristics.ShowCodedValueDomainDescriptions; break; } } TableProperty = (ITableProperty3)EnumTableProperties.Next(); } TabSel = (ITableSelection)StandTable; DisplayTable = (IDisplayTable)StandTable; Table = (ITable)DisplayTable.DisplayTable; //Get subtype info ObjectClass = Table as IObjectClass; Subtypes = ObjectClass as ISubtypes; //Get TableFields so later we can determine whether that field is visible TableFields = (ITableFields)StandTable; //loop through each field and write column headings Row = 1; for (j = 0; j < TableFields.FieldCount; j++) { CurField = TableFields.get_Field(j); //skip blob and geometry fields if ((CurField.Type != esriFieldType.esriFieldTypeBlob) && (CurField.Type != esriFieldType.esriFieldTypeGeometry)) { Col += 1; //Write field alias name as Excel column header ExcelSheet.Cells[Row, Col] = TableFields.get_FieldInfo(j).Alias; if (CurField.Type == esriFieldType.esriFieldTypeString) { ExcelSheet.get_Range(ExcelSheet.Cells[1, Col], ExcelSheet.Cells[65535, Col]).EntireColumn.NumberFormat = "@"; } } } //Get all selected records for this table (use IDisplayTable to get any joined data) DisplayTable.DisplaySelectionSet.Search(null, true, out Cursor); //subtype = Subtypes.DefaultSubtypeCode; //For each selected record TabRow = Cursor.NextRow(); //stepProgressor.Step(); // progressDialog.Description = A4LGSharedFunctions.Localizer.GetString("ExportAsset") + stepProgressor.Position + A4LGSharedFunctions.Localizer.GetString("Of") + MxDoc.FocusMap.SelectionCount.ToString() + "."; while (TabRow != null) { Row += 1; if (Subtypes != null && Subtypes.HasSubtype == true && (TabRow.get_Value(Subtypes.SubtypeFieldIndex) != null)) { subtype = Convert.ToInt32(TabRow.get_Value(Subtypes.SubtypeFieldIndex)); } else { subtype = -99999; } //For each column Col = 0; for (j = 0; j < TableFields.FieldCount; j++) { CurField = TableFields.get_Field(j); //skip blob and geometry fields in data also if ((CurField.Type != esriFieldType.esriFieldTypeBlob) && (CurField.Type != esriFieldType.esriFieldTypeGeometry)) { Col += 1; ExcelSheet.Cells[Row, Col] = TabRow.get_Value(j); if (UseDescriptions == true && subtype == -99999) { Domain = CurField.Domain; if (Domain != null) { if (Domain.Type == esriDomainType.esriDTCodedValue) { CodedValueDomain = (ICodedValueDomain)CurField.Domain; for (i = 0; i < CodedValueDomain.CodeCount; i++) { if ((CodedValueDomain.get_Value(i)).ToString() == (TabRow.get_Value(j)).ToString()) { //System.Diagnostics.Debug.Print(CodedValueDomain.get_Name(0).ToString()); ExcelSheet.Cells[Row, Col] = CodedValueDomain.get_Name(i); i = CodedValueDomain.CodeCount; } } } } } else if (UseDescriptions == true && subtype != -99999) { if (Subtypes.SubtypeFieldIndex == j) { ExcelSheet.Cells[Row, Col] = Subtypes.get_SubtypeName(subtype); } else { Domain = Subtypes.get_Domain(subtype, CurField.Name); if ((Domain != null) && (Domain.Type == esriDomainType.esriDTCodedValue)) { CodedValueDomain = (ICodedValueDomain)Domain; for (i = 0; i < CodedValueDomain.CodeCount; i++) { if ((CodedValueDomain.get_Value(i)).ToString() == (TabRow.get_Value(j)).ToString()) { //System.Diagnostics.Debug.Print(CodedValueDomain.get_Name(0).ToString()); ExcelSheet.Cells[Row, Col] = CodedValueDomain.get_Name(i); i = CodedValueDomain.CodeCount; } } } } } } } stepProgressor.Step(); progressDialog.Description = A4LGSharedFunctions.Localizer.GetString("ExportAsset") + stepProgressor.Position + A4LGSharedFunctions.Localizer.GetString("Of") + MxDoc.FocusMap.SelectionCount.ToString() + "."; if (!trackCancel.Continue()) { return(false); } TabRow = Cursor.NextRow(); } //Hide Columns Col = 0; for (j = 0; j < TableFields.FieldCount; j++) { CurField = TableFields.get_Field(j); //skip blob and geometry fields in data also if ((CurField.Type != esriFieldType.esriFieldTypeBlob) && (CurField.Type != esriFieldType.esriFieldTypeGeometry)) { Col += 1; //Autofit ExcelRange = ExcelSheet.get_Range(ExcelSheet.Cells[1, Col], ExcelSheet.Cells[Row, Col]); ExcelRange.EntireColumn.AutoFit(); //Hide column if invisible in ArcMap if (TableFields.get_FieldInfo(j).Visible == false) { ExcelRange = ExcelSheet.get_Range(ExcelSheet.Cells[1, Col], ExcelSheet.Cells[Row, Col]); ExcelRange.EntireColumn.Hidden = true; } } } return(true); } catch { MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("ExportXLError")); return(true); } finally { TableProperties = null; EnumTableProperties = null; TableProperty = null; TableCharacteristics = null; TabSel = null; DisplayTable = null; Table = null; TabRow = null; ObjectClass = null; Subtypes = null; TableFields = null; if (Cursor != null) { Marshal.ReleaseComObject(Cursor); } Cursor = null; CurField = null; Domain = null; CodedValueDomain = null; missing = null; sheet = null; style = null; } }
// Execute: Execute the function given the array of the parameters public void Execute(IArray paramvalues, ITrackCancel trackcancel, IGPEnvironmentManager envMgr, IGPMessages message) { // Get the first Input Parameter IGPParameter parameter = (IGPParameter)paramvalues.get_Element(0); // UnPackGPValue. This ensures you get the value either form the dataelement or GpVariable (ModelBuilder) IGPValue parameterValue = m_GPUtilities.UnpackGPValue(parameter); // Open Input Dataset IFeatureClass inputFeatureClass; IQueryFilter qf; m_GPUtilities.DecodeFeatureLayer(parameterValue, out inputFeatureClass, out qf); if (inputFeatureClass == null) { message.AddError(2, "Could not open input dataset."); return; } // Add the field if it does not exist. int indexA; parameter = (IGPParameter)paramvalues.get_Element(1); string field = parameter.Value.GetAsText(); indexA = inputFeatureClass.FindField(field); if (indexA < 0) { IFieldEdit fieldEdit = new FieldClass(); fieldEdit.Type_2 = esriFieldType.esriFieldTypeDouble; fieldEdit.Name_2 = field; inputFeatureClass.AddField(fieldEdit); } int featcount = inputFeatureClass.FeatureCount(null); //Set the properties of the Step Progressor IStepProgressor pStepPro = (IStepProgressor)trackcancel; pStepPro.MinRange = 0; pStepPro.MaxRange = featcount; pStepPro.StepValue = (1); pStepPro.Message = "Calculating Area"; pStepPro.Position = 0; pStepPro.Show(); // Create an Update Cursor indexA = inputFeatureClass.FindField(field); IFeatureCursor updateCursor = inputFeatureClass.Update(qf, false); IFeature updateFeature = updateCursor.NextFeature(); IGeometry geometry; IArea area; double dArea; while (updateFeature != null) { geometry = updateFeature.Shape; area = (IArea)geometry; dArea = area.Area; updateFeature.set_Value(indexA, dArea); updateCursor.UpdateFeature(updateFeature); updateFeature.Store(); updateFeature = updateCursor.NextFeature(); pStepPro.Step(); } pStepPro.Hide(); // Release the update cursor to remove the lock on the input data. System.Runtime.InteropServices.Marshal.ReleaseComObject(updateCursor); }
public bool UpdateHistoryOnLines(ITable pLinesTable, ITable pPointsTable, int iParcelCount, ICadastralFabric pCadFabric, List<string> sOIDList, Dictionary<int, string> ParcelToHistory_DICT, IStepProgressor m_pStepProgressor, ITrackCancel m_pTrackCancel) { bool m_bShowProgressor = (iParcelCount > 10); sOIDList.Add(""); int tokenLimit = 995; bool bCont = true; int j = 0; int iCounter = 0; ICadastralFabricSchemaEdit2 pSchemaEd = null; try { #region update line table history //Get the line table history fields //SystemStart, SystemEnd, LegalStart, LegalEnd, Historic int iParcelID = pLinesTable.FindField("parcelid"); string sParcelID = pLinesTable.Fields.get_Field(iParcelID).Name; int iLineSysStartDate = pLinesTable.FindField("systemstartdate"); string sLineSysStartDate = pLinesTable.Fields.get_Field(iLineSysStartDate).Name; int iLineSysEndDate = pLinesTable.FindField("systemenddate"); string sLineSysEndDate = pLinesTable.Fields.get_Field(iLineSysEndDate).Name; int iLineLegalStartDate = pLinesTable.FindField("legalstartdate"); string sLineLegalStartDate = pLinesTable.Fields.get_Field(iLineLegalStartDate).Name; int iLineLegalEndDate = pLinesTable.FindField("legalenddate"); string sLineLegalEndDate = pLinesTable.Fields.get_Field(iLineLegalEndDate).Name; int iLineHistorical = pLinesTable.FindField("historical"); string sLineHistorical = pLinesTable.Fields.get_Field(iLineHistorical).Name; int iFromPoint = pLinesTable.FindField("frompointid"); string sFromPoint = pLinesTable.Fields.get_Field(iFromPoint).Name; int iToPoint = pLinesTable.FindField("topointid"); string sToPoint = pLinesTable.Fields.get_Field(iToPoint).Name; IQueryFilter pQueryFilter = new QueryFilterClass(); pQueryFilter.SubFields = pLinesTable.OIDFieldName + ", parcelid," + sLineSysStartDate + "," + sLineSysEndDate + "," + sLineLegalStartDate + "," + sLineLegalEndDate + "," + sLineHistorical + "," + sFromPoint + "," + sToPoint; pSchemaEd = (ICadastralFabricSchemaEdit2)pCadFabric; pSchemaEd.ReleaseReadOnlyFields(pLinesTable, esriCadastralFabricTable.esriCFTLines); //release safety-catch Dictionary<int, string> PointToHistory_DICT = new Dictionary<int, string>(iParcelCount); List<string> sPointOIDList = new List<string>(); List<int> iLinesOIDList = new List<int>(); sPointOIDList.Add(""); j = iCounter = 0; ICursor pCur = null; object obj = null; foreach (string sHistory in sOIDList) { if (sHistory.Trim() == "") continue; pQueryFilter.WhereClause = sParcelID + " IN (" + sHistory + ")"; pCur = pLinesTable.Update(pQueryFilter, false); IRow pLine = pCur.NextRow(); while (pLine != null) { //Check if the cancel button was pressed. If so, stop process if (m_bShowProgressor) { bCont = m_pTrackCancel.Continue(); if (!bCont) break; } iLinesOIDList.Add(pLine.OID); string sParcHistory = ""; if (ParcelToHistory_DICT.TryGetValue((int)pLine.get_Value(iParcelID), out sParcHistory)) { string[] sHistoryItems = sParcHistory.Split(','); if (sHistoryItems[0].Trim() == "") obj = DBNull.Value; else obj = sHistoryItems[0]; pLine.set_Value(iLineSysStartDate, obj); if (sHistoryItems[1].Trim() == "") obj = DBNull.Value; else obj = sHistoryItems[1]; pLine.set_Value(iLineSysEndDate, obj); if (sHistoryItems[2].Trim() == "") obj = DBNull.Value; else obj = sHistoryItems[2]; pLine.set_Value(iLineLegalStartDate, obj); if (sHistoryItems[3].Trim() == "") obj = DBNull.Value; else obj = sHistoryItems[3]; pLine.set_Value(iLineLegalEndDate, obj); if (sHistoryItems[4].Trim() == "") obj = DBNull.Value; else { bool x = (sHistoryItems[4].Trim().ToLower() == "true") ? true : false; if (x) obj = 1; else obj = 0; } pLine.set_Value(iLineHistorical, obj); pLine.Store(); int iVal = (int)pLine.get_Value(iToPoint); if (!PointToHistory_DICT.ContainsKey(iVal)) { PointToHistory_DICT.Add(iVal, sParcHistory); if (iCounter <= tokenLimit) { if (sPointOIDList[j].Trim() == "") sPointOIDList[j] = Convert.ToString(iVal); else sPointOIDList[j] = sPointOIDList[j] + "," + Convert.ToString(iVal); iCounter++; } else {//maximum tokens reached iCounter = 0; //set up the next OIDList j++; sPointOIDList.Add(""); sPointOIDList[j] = sPointOIDList[j] + Convert.ToString(iVal); } } else //if the point is here already { //Since the lines that have the shared points may have different //history these points need a different treatment. The approach in this code will make updates //in favour of non-historic data. UpdateHistoryOnPoints(pLine, iVal, PointToHistory_DICT, iLineSysEndDate, iLineLegalEndDate, iLineHistorical); } iVal = (int)pLine.get_Value(iFromPoint); if (!PointToHistory_DICT.ContainsKey(iVal)) { PointToHistory_DICT.Add(iVal, sParcHistory); if (iCounter <= tokenLimit) { if (sPointOIDList[j].Trim() == "") sPointOIDList[j] = Convert.ToString(iVal); else sPointOIDList[j] = sPointOIDList[j] + "," + Convert.ToString(iVal); iCounter++; } else {//maximum tokens reached iCounter = 0; //set up the next OIDList j++; sPointOIDList.Add(""); sPointOIDList[j] = sPointOIDList[j] + Convert.ToString(iVal); } } else //if the point is here already { //Since the lines that have the shared points may have different //history these points need a different treatment. The approach in this code will make updates //in favour of non-historic data. UpdateHistoryOnPoints(pLine, iVal, PointToHistory_DICT, iLineSysEndDate, iLineLegalEndDate, iLineHistorical); } } Marshal.ReleaseComObject(pLine); pLine = pCur.NextRow(); if (m_bShowProgressor) { if (m_pStepProgressor.Position < m_pStepProgressor.MaxRange) m_pStepProgressor.Step(); } } Marshal.FinalReleaseComObject(pCur); } if (!bCont) return false; #endregion #region Find other lines connected to these points and Update the dictionary values //search back on lines with points list iLinesOIDList.Sort(); foreach (string sPointsQuery in sPointOIDList) { if (sPointsQuery.Trim() == "") continue; pQueryFilter.WhereClause = sToPoint + " IN (" + sPointsQuery + ")"; pCur = pLinesTable.Search(pQueryFilter, false); IRow pLine = pCur.NextRow(); while (pLine != null) { int iPos = iLinesOIDList.BinarySearch(pLine.OID); if (iPos < 0) //not found < 0 {//if this line is not in the original line list, its points are shared outside of //the original selection. Since the lines that have the shared points may have different //history these points need a different treatment. The approach in this code will make updates //in favour of non-historic parcels. int iVal = (int)pLine.get_Value(iFromPoint); UpdateHistoryOnPoints(pLine, iVal, PointToHistory_DICT, iLineSysEndDate, iLineLegalEndDate, iLineHistorical); iVal = (int)pLine.get_Value(iToPoint); UpdateHistoryOnPoints(pLine, iVal, PointToHistory_DICT, iLineSysEndDate, iLineLegalEndDate, iLineHistorical); } Marshal.FinalReleaseComObject(pLine); pLine = pCur.NextRow(); } Marshal.FinalReleaseComObject(pCur); //Now redo the same search with the From point. These are separate searches because using OR with //2 separate in clauses is slow. pQueryFilter.WhereClause = sFromPoint + " IN (" + sPointsQuery + ")"; pCur = pLinesTable.Search(pQueryFilter, false); pLine = pCur.NextRow(); while (pLine != null) { int iPos = iLinesOIDList.BinarySearch(pLine.OID); if (iPos < 0) //not found < 0 {//if this line is not in the original list, its points are shared outside of //the original selection and should be removed from the point update list int iVal = (int)pLine.get_Value(iFromPoint); UpdateHistoryOnPoints(pLine, iVal, PointToHistory_DICT, iLineSysEndDate, iLineLegalEndDate, iLineHistorical); iVal = (int)pLine.get_Value(iToPoint); UpdateHistoryOnPoints(pLine, iVal, PointToHistory_DICT, iLineSysEndDate, iLineLegalEndDate, iLineHistorical); } Marshal.FinalReleaseComObject(pLine); pLine = pCur.NextRow(); } Marshal.FinalReleaseComObject(pCur); } #endregion #region Update the Points //update the points with the values in the dictionary. pSchemaEd.ReleaseReadOnlyFields(pPointsTable, esriCadastralFabricTable.esriCFTPoints); //declare the smaller points list List<string> sPointOIDSubsetList = new List<string>(); sPointOIDSubsetList.Add(""); iCounter = j = 0; foreach (KeyValuePair<int, String> entry in PointToHistory_DICT) { string s = entry.Key.ToString(); if (iCounter <= tokenLimit) { if (sPointOIDSubsetList[j].Trim() == "") sPointOIDSubsetList[j] = s; else sPointOIDSubsetList[j] = sPointOIDSubsetList[j] + "," + s; iCounter++; } else {//maximum tokens reached iCounter = 0; //set up the next OIDList j++; sPointOIDSubsetList.Add(""); sPointOIDSubsetList[j] = sPointOIDSubsetList[j] + s; } } //Get the point table history fields //SystemStart, SystemEnd, LegalStart, LegalEnd, Historic int iPointSysStartDate = pPointsTable.FindField("systemstartdate"); string sPointSysStartDate = pPointsTable.Fields.get_Field(iPointSysStartDate).Name; int iPointSysEndDate = pPointsTable.FindField("systemenddate"); string sPointSysEndDate = pPointsTable.Fields.get_Field(iPointSysEndDate).Name; int iPointLegalStartDate = pPointsTable.FindField("legalstartdate"); string sPointLegalStartDate = pPointsTable.Fields.get_Field(iPointLegalStartDate).Name; int iPointLegalEndDate = pPointsTable.FindField("legalenddate"); string sPointLegalEndDate = pPointsTable.Fields.get_Field(iPointLegalEndDate).Name; int iPointHistorical = pPointsTable.FindField("historical"); string sPointHistorical = pPointsTable.Fields.get_Field(iPointHistorical).Name; string sOIDFld = pPointsTable.OIDFieldName; pQueryFilter.SubFields = sOIDFld + "," + sPointSysStartDate + "," + sPointSysEndDate + "," + sPointLegalStartDate + "," + iPointLegalEndDate + "," + sPointHistorical; foreach (string sPointsQuery in sPointOIDSubsetList) { if (sPointsQuery.Trim() == "") continue; pQueryFilter.WhereClause = sOIDFld + " IN (" + sPointsQuery + ")"; pCur = pPointsTable.Update(pQueryFilter, false); IRow pPoint = pCur.NextRow(); while (pPoint != null) { //Check if the cancel button was pressed. If so, stop process if (m_bShowProgressor) { bCont = m_pTrackCancel.Continue(); if (!bCont) break; } string sPointHistory = ""; if (PointToHistory_DICT.TryGetValue((int)pPoint.OID, out sPointHistory)) { string[] sHistoryItems = sPointHistory.Split(','); if (sHistoryItems[0].Trim() == "") obj = DBNull.Value; else obj = sHistoryItems[0]; pPoint.set_Value(iPointSysStartDate, obj); if (sHistoryItems[1].Trim() == "") obj = DBNull.Value; else obj = sHistoryItems[1]; pPoint.set_Value(iPointSysEndDate, obj); if (sHistoryItems[2].Trim() == "") obj = DBNull.Value; else obj = sHistoryItems[2]; pPoint.set_Value(iPointLegalStartDate, obj); if (sHistoryItems[3].Trim() == "") obj = DBNull.Value; else obj = sHistoryItems[3]; pPoint.set_Value(iPointLegalEndDate, obj); if (sHistoryItems[4].Trim() == "") obj = DBNull.Value; else { bool x = (sHistoryItems[4].Trim().ToLower() == "true") ? true : false; if (x) obj = 1; else obj = 0; } pPoint.set_Value(iPointHistorical, obj); pPoint.Store(); } Marshal.ReleaseComObject(pPoint); pPoint = pCur.NextRow(); if (m_bShowProgressor) { if (m_pStepProgressor.Position < m_pStepProgressor.MaxRange) m_pStepProgressor.Step(); } } Marshal.FinalReleaseComObject(pCur); if (!bCont) return false; else return true; } #endregion if (!bCont) return false; else return true; } catch (Exception ex) { MessageBox.Show(ex.Message); return false; } finally { pSchemaEd.ResetReadOnlyFields(esriCadastralFabricTable.esriCFTPoints);//set safety back on pSchemaEd.ResetReadOnlyFields(esriCadastralFabricTable.esriCFTLines);//set safety back on } }
public bool ChangeDatesOnTableMulti(ICursor pCursor, List<bool> HistorySettings, List<string> sDate, bool Unversioned, Dictionary<int, string> ParcelToHistory_DICT,IStepProgressor m_pStepProgressor, ITrackCancel m_pTrackCancel) { bool bSystemEndDate_Clear = HistorySettings[0]; bool bLegalStDate_Clear = HistorySettings[1]; bool bLegalEndDate_Clear = HistorySettings[2]; bool bSystemEndDate_Set = HistorySettings[3]; bool bLegalStDate_Set = HistorySettings[4]; bool bLegalEndDate_Set = HistorySettings[5]; object dbNull = DBNull.Value; int FldIdxSystemEnd = pCursor.FindField("systemenddate"); int iHistorical = pCursor.FindField("historical"); int FldIdxLegalSt =pCursor.FindField("legalstartdate"); int FldIdxLegalEnd = pCursor.FindField("legalenddate"); bool bHasSysEndDateFld = (FldIdxSystemEnd > -1); bool bHasHistoricFld = (iHistorical > -1); bool bCont = true; bool m_bShowProgressor = (m_pStepProgressor!=null); IRow pRow = pCursor.NextRow(); while (pRow != null) { //Check if the cancel button was pressed. If so, stop process if (m_bShowProgressor) { bCont = m_pTrackCancel.Continue(); if (!bCont) break; } string sHistoryInfo = ""; string[] sUpdateDictionaryDates = null; bool bTryGetTrue = false; if (ParcelToHistory_DICT.TryGetValue(pRow.OID, out sHistoryInfo)) { //update the strings in the dictionary sUpdateDictionaryDates = sHistoryInfo.Split(','); bTryGetTrue = true; } if (bSystemEndDate_Set && bTryGetTrue) { pRow.set_Value(FldIdxSystemEnd, sDate[0]); if (bHasHistoricFld) // if writing date to SystemEndDate field pRow.set_Value(iHistorical, 1); //then set the Historical flag to true = 1 //update the dictionary //find the location of the System End Date string x= ParcelToHistory_DICT[pRow.OID]; int i1 = x.IndexOf(",", 0); int i2 = x.IndexOf(",", i1+1); string s1= x.Remove(i1 + 1, i2 - i1); string s2=s1.Insert(i1 + 1, sDate[0] + ","); ParcelToHistory_DICT[pRow.OID] = s2; } if (bSystemEndDate_Clear && bTryGetTrue) { pRow.set_Value(FldIdxSystemEnd, dbNull); if (bHasHistoricFld) // if writing date to SystemEndDate field pRow.set_Value(iHistorical, 0); //then set the Historical flag to true = 1 //update the dictionary //find the location of the System End Date string x = ParcelToHistory_DICT[pRow.OID]; int i1 = x.IndexOf(",", 0); int i2 = x.IndexOf(",", i1 + 1); string s1 = x.Remove(i1 + 1, i2 - i1); string s2 = s1.Insert(i1 + 1, ","); ParcelToHistory_DICT[pRow.OID] = s2; } if (bLegalStDate_Set && bTryGetTrue) { pRow.set_Value(FldIdxLegalSt, sDate[1]); //update the dictionary //find the location of the System End Date string x = ParcelToHistory_DICT[pRow.OID]; int i1 = x.IndexOf(",", 0); int i2 = x.IndexOf(",", i1 + 1); int i3 = x.IndexOf(",", i2 + 1); string s1 = x.Remove(i2 + 1, i3 - i2); string s2 = s1.Insert(i2 + 1,sDate[1] + ","); ParcelToHistory_DICT[pRow.OID] = s2; } if (bLegalStDate_Clear && bTryGetTrue) { pRow.set_Value(FldIdxLegalSt, dbNull); //update the dictionary //find the location of the System End Date string x = ParcelToHistory_DICT[pRow.OID]; int i1 = x.IndexOf(",", 0); int i2 = x.IndexOf(",", i1 + 1); int i3 = x.IndexOf(",", i2 + 1); string s1 = x.Remove(i2 + 1, i3 - i2); string s2 = s1.Insert(i2 + 1, ","); ParcelToHistory_DICT[pRow.OID] = s2; } if (bLegalEndDate_Set && bTryGetTrue) { pRow.set_Value(FldIdxLegalEnd, sDate[2]); //update the dictionary //find the location of the System End Date string x = ParcelToHistory_DICT[pRow.OID]; int i1 = x.IndexOf(",", 0); int i2 = x.IndexOf(",", i1 + 1); int i3 = x.IndexOf(",", i2 + 1); int i4 = x.IndexOf(",", i3 + 1); string s1 = x.Remove(i3 + 1, i4 - i3); string s2 = s1.Insert(i3 + 1, sDate[2] + ","); ParcelToHistory_DICT[pRow.OID] = s2; } if (bLegalEndDate_Clear && bTryGetTrue) { pRow.set_Value(FldIdxLegalEnd, dbNull); //update the dictionary //find the location of the System End Date string x = ParcelToHistory_DICT[pRow.OID]; int i1 = x.IndexOf(",", 0); int i2 = x.IndexOf(",", i1 + 1); int i3 = x.IndexOf(",", i2 + 1); int i4 = x.IndexOf(",", i3 + 1); string s1 = x.Remove(i3 + 1, i4 - i3); string s2 = s1.Insert(i3 + 1, ","); ParcelToHistory_DICT[pRow.OID] = s2; } if (Unversioned) pCursor.UpdateRow(pRow); else pRow.Store(); Marshal.ReleaseComObject(pRow); pRow = pCursor.NextRow(); if (m_bShowProgressor) { if (m_pStepProgressor.Position < m_pStepProgressor.MaxRange) m_pStepProgressor.Step(); } } Marshal.ReleaseComObject(pCursor); if (!bCont) return false; return true; }
public void Calculate(string sShorelineLayer, string sDepthPointsLayer, double dblInterval, string strShoreDepthField, string strDepthPointDepthField) { try { IMxDocument pmxdoc = ArcMap.Document as IMxDocument; IMap pmap = pmxdoc.FocusMap; IFeatureLayer pDepthSoundings = FindLayer(pmap, sDepthPointsLayer) as IFeatureLayer; IFeatureLayer pShorelineLayer = FindLayer(pmap, sShorelineLayer) as IFeatureLayer; //IFeatureLayer pOutpoints = FindLayer(pmap, sOutpoints) as IFeatureLayer; IFeatureLayer pOutpoints = new FeatureLayerClass(); pOutpoints.FeatureClass = MakePointFC(); pOutpoints.Name = "Output Points"; ArcMap.Document.ActiveView.FocusMap.AddLayer(pOutpoints); IFeatureLayer pConnectingLines = FindLayer(pmap, "ConnectingLines") as IFeatureLayer; IFeatureLayer pShorePoints = FindLayer(pmap, "ShorePoints") as IFeatureLayer; ////Add fields if necessary //AddField(pOutpoints, "Distance"); //AddField(pOutpoints, "Elevation"); //Set up the Outpoints cursor IFeatureCursor pFCurOutPoints = pOutpoints.Search(null, false); pFCurOutPoints = pOutpoints.FeatureClass.Insert(true); IFeatureBuffer pFOutPointsBuffer = pOutpoints.FeatureClass.CreateFeatureBuffer(); //Set up the LineLayer Cursor (now using selected lines) IFeatureSelection pShoreLineSelection = pShorelineLayer as IFeatureSelection; if (pShoreLineSelection.SelectionSet.Count == 0) { MessageBox.Show("You must have at least one shoreline feature selected"); return; } ICursor pShorelineCursor; IFeatureCursor pSelShoreFeatCur; pShoreLineSelection.SelectionSet.Search(null, false, out pShorelineCursor); pSelShoreFeatCur = pShorelineCursor as IFeatureCursor; IFeature pShoreLineFeature = pSelShoreFeatCur.NextFeature(); //IFeatureCursor pFCur = pShorelineLayer.Search(null, false); //IFeature pShoreLineFeature = pFCur.NextFeature(); //Set up the pConnectingLines cursor IFeatureCursor pFCurOutLines = pConnectingLines.Search(null, false); pFCurOutLines = pConnectingLines.FeatureClass.Insert(true); IFeatureBuffer pFBuffer = pConnectingLines.FeatureClass.CreateFeatureBuffer(); //Set up the pShorePoints cursor IFeatureCursor pShorePointsCursor = pShorePoints.Search(null, false); IFeature pShorePointFeature = pShorePointsCursor.NextFeature(); IFeature pNewLineFeature = null; IPointCollection pNewLinePointColl = null; double dblDistance = 0; double dblTotalDistanceCalculated = 0; int iNumIntervals = 0; double dblElevationDiff = 0; double dblElevationInterval = 0; double dblElevation = 0; double dlbStartElevation = 0; double dblEndElevation = 0; int iLineProgressCount = 0; IProgressDialog2 pProgressDialog = ShowProgressIndicator("Calculating points for shoreline vertex: ", 0, 1); pProgressDialog.ShowDialog(); IEnvelope pCombinedEnvelope = CombineExtents(pDepthSoundings.FeatureClass, pShorelineLayer.FeatureClass); while (pShoreLineFeature != null) { //IPointCollection4 pPointColl = pShoreLineFeature.Shape as IPointCollection4; IPoint ppoint = new PointClass(); //for (int i = 0; i <= pPointColl.PointCount - 1; i++) while (pShorePointFeature != null) { ppoint = pShorePointFeature.ShapeCopy as IPoint; System.Diagnostics.Debug.WriteLine("ppoint: " + ppoint.X.ToString()); System.Diagnostics.Debug.WriteLine("shorepoint: " + pShorePointFeature.OID.ToString()); ////try walking line at set intervals instead of just at vertices //IPoint pLineVertex = new PointClass(); //pLineVertex = pPointColl.get_Point(i); IFeatureCursor pDepthCursor = pDepthSoundings.Search(null, false); IFeatureIndex2 pFtrInd = new FeatureIndexClass(); pFtrInd.FeatureClass = pDepthSoundings.FeatureClass; pFtrInd.FeatureCursor = pDepthCursor; pFtrInd.Index(null, pCombinedEnvelope); IIndexQuery2 pIndQry = pFtrInd as IIndexQuery2; int FtdID = 0; double dDist2Ftr = 0; pIndQry.NearestFeature(ppoint, out FtdID, out dDist2Ftr); IFeature pCloseFeature = pDepthSoundings.FeatureClass.GetFeature(FtdID); IPoint pEndPoint = new PointClass(); pEndPoint = pCloseFeature.Shape as IPoint; //Make the line here pNewLineFeature = pConnectingLines.FeatureClass.CreateFeature(); pNewLinePointColl = new PolylineClass(); object missing = Type.Missing; pNewLinePointColl.AddPoint(pEndPoint, ref missing, ref missing); pNewLinePointColl.AddPoint(ppoint, ref missing, ref missing); pNewLineFeature.Shape = pNewLinePointColl as PolylineClass; //Check to see if new line crosses land, if not, process it. //bool bLineIntersectsShore = FeatureIntersects(pShorelineLayer, pConnectingLines, pNewLineFeature); bool bLineIntersectsShore = false; if (bLineIntersectsShore == false) { pNewLineFeature.Store(); ICurve pCurve = pNewLineFeature.Shape as ICurve; pCurve.Project(pmap.SpatialReference); //Get the Starting Elevation from the closest depth point dlbStartElevation = GetStartElevation(pDepthSoundings, pConnectingLines, pNewLineFeature, strDepthPointDepthField); //The Elevation for the first run IS the start elevation dblElevation = dlbStartElevation; //////Get the ending elevation from the shoreline dblEndElevation = GetEndElevation(pShorelineLayer, pConnectingLines, pNewLineFeature, strShoreDepthField); //number of line segments based on the user's interval iNumIntervals = Convert.ToInt32(pCurve.Length / dblInterval); dblElevationDiff = Math.Abs(dblEndElevation - dlbStartElevation); //The calculated elevation interval to step up each time dblElevationInterval = dblElevationDiff / iNumIntervals; ppoint = new PointClass(); while (dblTotalDistanceCalculated <= pCurve.Length) { pFOutPointsBuffer.set_Value(pFOutPointsBuffer.Fields.FindField("LineOID"), pNewLineFeature.OID); pFOutPointsBuffer.set_Value(pFOutPointsBuffer.Fields.FindField("Distance"), dblDistance); pFOutPointsBuffer.set_Value(pFOutPointsBuffer.Fields.FindField("Elevation"), dblElevation); //this code set the point on the line at a distance pCurve.QueryPoint(0, dblDistance, false, ppoint); pFOutPointsBuffer.set_Value(pFOutPointsBuffer.Fields.FindField("X"), ppoint.X); pFOutPointsBuffer.set_Value(pFOutPointsBuffer.Fields.FindField("Y"), ppoint.Y); //reCalc the new distance and elevation values for the next iteration dblDistance = dblDistance + dblInterval; //add or subtract elevation depending on whether dblElevationDiff is positve or negative if (dblElevationDiff > 0) { dblElevation = dblElevation - dblElevationInterval; } else { dblElevation = dblElevation + dblElevationInterval; } dblTotalDistanceCalculated = dblTotalDistanceCalculated + dblInterval; //Insert the feature into the featureclass pFOutPointsBuffer.Shape = ppoint; pFCurOutPoints.InsertFeature(pFOutPointsBuffer); } //Reset the distance values back to 0 for the next feature dblDistance = 0; dblTotalDistanceCalculated = 0; pFCurOutPoints.Flush(); pStepProgressor.Step(); pProgressDialog.Description = "Calculating points for shoreline vertex: " + pShorePointFeature.OID.ToString(); iLineProgressCount++; } pShorePointFeature = pShorePointsCursor.NextFeature(); } pShoreLineFeature = pSelShoreFeatCur.NextFeature(); } //cleanup pFCurOutLines.Flush(); pSelShoreFeatCur.Flush(); pProgressDialog.HideDialog(); pmxdoc.ActiveView.Refresh(); } catch (Exception ex) { MessageBox.Show(ex.Message); MessageBox.Show(ex.StackTrace); } }
private bool ResetPointAssociations(ITable PointTable, IQueryFilter QueryFilter, bool Unversioned, IStepProgressor StepProgressor, ITrackCancel TrackCancel) { try { ITableWrite pTableWr = (ITableWrite)PointTable;//used for unversioned table IRow pPointFeat = null; ICursor pPtCurs = null; if (Unversioned) pPtCurs = pTableWr.UpdateRows(QueryFilter, false); else pPtCurs = PointTable.Update(QueryFilter, false); pPointFeat = pPtCurs.NextRow(); if (StepProgressor != null) { if (StepProgressor.Position < StepProgressor.MaxRange) StepProgressor.Step(); } Int32 iPointIDX = pPtCurs.Fields.FindField("NAME"); bool bCont = true; while (pPointFeat != null) {//loop through all of the fabric points, and if any of the point id values are in the deleted set, //then remove the control name from the point's NAME field if (TrackCancel != null) bCont = TrackCancel.Continue(); if (!bCont) break; pPointFeat.set_Value(iPointIDX, DBNull.Value); if (Unversioned) pPtCurs.UpdateRow(pPointFeat); else pPointFeat.Store(); Marshal.ReleaseComObject(pPointFeat); //garbage collection pPointFeat = pPtCurs.NextRow(); if (StepProgressor != null) { if (StepProgressor.Position < StepProgressor.MaxRange) StepProgressor.Step(); } } Marshal.ReleaseComObject(pPtCurs); //garbage collection if (!bCont) return false; return true; } catch (COMException ex) { MessageBox.Show("Problem resetting point table's control association: " + Convert.ToString(ex.ErrorCode)); return false; } }
private void GenerarModelo(string sTablaPrecipPromedio, string sConsultaTablaPrecipPromedio, string sPrefijo, string sTablaTempPromedio, string sConsultaTablaTempPromedio) { ProcesarLecturas procesarLecturas = new ProcesarLecturas(); try { procesarLecturas.CalcularResultadosPrecipitacion(sigpiDao, "DEFI_PRECI", "LECTUS_PRECI", sigpi.FechaProcesamiento, 5); } catch (Exception ex) { MessageBox.Show("Error procesando las lecturas:\n" + ex.Message); } //pStepPro.Step(); //pStepPro.Message = "Procesando Temperatura..."; try { procesarLecturas.CalcularResultadosTemperatura(sigpiDao, "DEFI_TEMPE", "LECTUS_TEMPE", sigpi.FechaProcesamiento, "T5", 5); } catch (Exception ex) { MessageBox.Show("Error procesando las lecturas:\n" + ex.Message); } string sSQL = "UPDATE FECHAS_PROCESO SET FEC_PROCE = #" + sigpi.FechaProcesamiento.ToString("MM/dd/yyyy") + "#"; try { sigpiDao.EjecutarSentenciaSinQuery(sSQL); } catch (Exception ex) { MessageBox.Show("No se pudo actualizar la fecha de incorporacion.\n" + ex.Message); } IProgressDialogFactory pProDiaFac = new ProgressDialogFactoryClass(); IStepProgressor pStepPro = pProDiaFac.Create(null, 0); pStepPro.MinRange = 1; pStepPro.MaxRange = 5; pStepPro.StepValue = 1; IProgressDialog2 pProDia = (IProgressDialog2)pStepPro; pProDia.Animation = esriProgressAnimationTypes.esriProgressGlobe; pProDia.Title = "Generar Grids"; pProDia.ShowDialog(); pStepPro.Step(); pStepPro.Message = "Generando Grids Meteorologicos..."; IFeatureClass pFeatureClass; IWorkspaceFactory pShpWorkspaceFactory = new ShapefileWorkspaceFactoryClass(); IWorkspace pWorkspaceTemp = pShpWorkspaceFactory.OpenFromFile(parametros.RutaSIGPI + parametros.Temporal, 0); // Crear FeatureClass a partir de los datos de la tabla de los promedios de la precipitacion try { //pFeatureClass = procesamiento.ConstruirFeatureClass(pWorkspaceTemp, "DEFI_PRECI", "estaciones", "CODIGO", "DEFI_PRECI.P5 >= 0", "JP"); pFeatureClass = procesamiento.ConstruirFeatureClass(pWorkspaceTemp, sTablaPrecipPromedio, "estaciones", "CODIGO", sConsultaTablaPrecipPromedio, "JP"); } catch (Exception ex) { MessageBox.Show("Error generando el FeatureClass de Estaciones. Descripcion: \n" + ex.Message); return; } IWorkspaceFactory pWF = new AccessWorkspaceFactoryClass(); IFeatureWorkspace pWSMask = (IFeatureWorkspace)pWF.OpenFromFile(parametros.RutaGBD, 0); IGeoDataset pFCMask = (IGeoDataset)pWSMask.OpenFeatureClass(parametros.Mascara); DateTime date = sigpi.FechaProcesamiento; string sMonth = date.ToString("MM"); //P5 pStepPro.Step(); pStepPro.Message = "Generando Grids Meteorologicos: Precipitacion Total"; IRaster pRaster1 = procesamiento.ConstruirGrid(pFeatureClass, "P5", parametros, pFCMask, "RP5", "", true); //DSLL5 pStepPro.Step(); pStepPro.Message = "Generando Grids Meteorologicos: Promedio ultimos 5 dias sin lluvia"; IRaster pRaster2 = procesamiento.ConstruirGrid(pFeatureClass, "DSLL5", parametros, pFCMask, "DSLL5", "", true); //Crear FeatureClass a partir de la tabla de promedios de temperatura //pFeatureClass = procesamiento.ConstruirFeatureClass(pWorkspaceTemp, "DEFI_TEMPE", "estaciones", "CODIGO", "DEFI_TEMPE.T5 >= 0", "JT"); pFeatureClass = procesamiento.ConstruirFeatureClass(pWorkspaceTemp, sTablaTempPromedio, "estaciones", "CODIGO", sConsultaTablaTempPromedio, "JT"); //T5 pStepPro.Step(); pStepPro.Message = "Generando Grids Meteorologicos: Temperatura promedio"; IRaster pRaster3 = procesamiento.ConstruirGrid(pFeatureClass, "T5", parametros, pFCMask, "RT5", "", true); //TMMMM IRaster pRaster4 = SIGPIUtils.AbrirRasterDesdeArchivo(parametros.RutaSIGPI + "\\" + parametros.TMMMM, "tmmx" + sMonth); //Susceptibilidad //IRaster pRaster5 = SIGPIUtils.AbrirRaster(parametros.RutaSIGPI + "\\" + parametros.Grids, parametros.Susceptibilidad); IRaster pRaster5 = SIGPIUtils.AbrirRasterDesdeGDB(parametros.RutaGBD, parametros.Susceptibilidad); //Asentamientos //IRaster pRaster6 = SIGPIUtils.AbrirRaster(parametros.RutaSIGPI + "\\" + parametros.Grids, parametros.Asentamientos); IRaster pRaster6 = SIGPIUtils.AbrirRasterDesdeGDB(parametros.RutaGBD, parametros.Asentamientos); IRaster[] pRasters = { pRaster1, pRaster2, pRaster3, pRaster4, pRaster5, pRaster6 }; try { procesamiento.AlgoritmoCompleto(pRasters, sigpi); } catch (Exception ex) { MessageBox.Show(ex.Message); } pProDia.HideDialog(); MessageBox.Show("Algoritmo completo ejecutado"); }
protected override void OnClick() { bool bShowProgressor = false; IStepProgressor pStepProgressor = null; //Create a CancelTracker. ITrackCancel pTrackCancel = null; IProgressDialogFactory pProgressorDialogFact; IMouseCursor pMouseCursor = new MouseCursorClass(); pMouseCursor.SetCursor(2); //first get the selected parcel features UID pUID = new UIDClass(); pUID.Value = "{114D685F-99B7-4B63-B09F-6D1A41A4DDC1}"; ICadastralExtensionManager2 pCadExtMan = (ICadastralExtensionManager2)ArcMap.Application.FindExtensionByCLSID(pUID); ICadastralEditor pCadEd = (ICadastralEditor)ArcMap.Application.FindExtensionByCLSID(pUID); //check if there is a Manual Mode "modify" job active =========== ICadastralPacketManager pCadPacMan = (ICadastralPacketManager)pCadExtMan; if (pCadPacMan.PacketOpen) { MessageBox.Show("The Delete Control command cannot be used when there is an open job.\r\nPlease finish or discard the open job, and try again.", "Delete Selected Control"); return; } IEditor pEd = (IEditor)ArcMap.Application.FindExtensionByName("esri object editor"); IActiveView pActiveView = ArcMap.Document.ActiveView; IMap pMap = pActiveView.FocusMap; ICadastralFabric pCadFabric = null; clsFabricUtils FabricUTILS = new clsFabricUtils(); IProgressDialog2 pProgressorDialog = null; //if we're in an edit session then grab the target fabric if (pEd.EditState == esriEditState.esriStateEditing) { pCadFabric = pCadEd.CadastralFabric; } if (pCadFabric == null) {//find the first fabric in the map if (!FabricUTILS.GetFabricFromMap(pMap, out pCadFabric)) { MessageBox.Show ("No Parcel Fabric found in the map.\r\nPlease add a single fabric to the map, and try again."); return; } } IArray CFControlLayers = new ArrayClass(); if (!(FabricUTILS.GetControlLayersFromFabric(pMap, pCadFabric, out CFControlLayers))) { return; //no fabric sublayers available for the targeted fabric } bool bIsFileBasedGDB = false; bool bIsUnVersioned = false; bool bUseNonVersionedDelete = false; IWorkspace pWS = null; ITable pPointsTable = null; ITable pControlTable = null; try { if (pEd.EditState == esriEditState.esriStateEditing) { try { pEd.StartOperation(); } catch { pEd.AbortOperation();//abort any open edit operations and try again pEd.StartOperation(); } } IFeatureLayer pFL = (IFeatureLayer)CFControlLayers.get_Element(0); IDataset pDS = (IDataset)pFL.FeatureClass; pWS = pDS.Workspace; if (!FabricUTILS.SetupEditEnvironment(pWS, pCadFabric, pEd, out bIsFileBasedGDB, out bIsUnVersioned, out bUseNonVersionedDelete)) { return; } //loop through each control layer and //Get the selection of control int iCnt = 0; int iTotalSelectionCount = 0; for (; iCnt < CFControlLayers.Count; iCnt++) { pFL = (IFeatureLayer)CFControlLayers.get_Element(iCnt); IFeatureSelection pFeatSel = (IFeatureSelection)pFL; ISelectionSet2 pSelSet = (ISelectionSet2)pFeatSel.SelectionSet; iTotalSelectionCount += pSelSet.Count; } if (iTotalSelectionCount == 0) { MessageBox.Show("Please select some fabric control points and try again.", "No Selection", MessageBoxButtons.OK, MessageBoxIcon.Information); if (bUseNonVersionedDelete) { pCadEd.CadastralFabricLayer = null; CFControlLayers = null; } return; } bShowProgressor = (iTotalSelectionCount > 10); if (bShowProgressor) { pProgressorDialogFact = new ProgressDialogFactoryClass(); pTrackCancel = new CancelTrackerClass(); pStepProgressor = pProgressorDialogFact.Create(pTrackCancel, ArcMap.Application.hWnd); pProgressorDialog = (IProgressDialog2)pStepProgressor; pStepProgressor.MinRange = 1; pStepProgressor.MaxRange = iTotalSelectionCount * 2; //(runs through selection twice) pStepProgressor.StepValue = 1; pProgressorDialog.Animation = ESRI.ArcGIS.Framework.esriProgressAnimationTypes.esriProgressSpiral; } //loop through each control layer and //delete from its selection m_pQF = new QueryFilterClass(); iCnt = 0; for (; iCnt < CFControlLayers.Count; iCnt++) { pFL = (IFeatureLayer)CFControlLayers.get_Element(iCnt); IFeatureSelection pFeatSel = (IFeatureSelection)pFL; ISelectionSet2 pSelSet = (ISelectionSet2)pFeatSel.SelectionSet; ISQLSyntax pSQLSyntax = (ISQLSyntax)pWS; string sPref = pSQLSyntax.GetSpecialCharacter(esriSQLSpecialCharacters.esriSQL_DelimitedIdentifierPrefix); string sSuff = pSQLSyntax.GetSpecialCharacter(esriSQLSpecialCharacters.esriSQL_DelimitedIdentifierSuffix); if (bShowProgressor) { pProgressorDialog.ShowDialog(); pStepProgressor.Message = "Collecting Control point data..."; } //Add the OIDs of all the selected control points into a new feature IDSet string[] sOIDListPoints = { "(" }; int tokenLimit = 995; //int tokenLimit = 5; //temp for testing bool bCont = true; int j = 0; int iCounter = 0; m_pFIDSetControl = new FIDSetClass(); ICursor pCursor = null; pSelSet.Search(null, false, out pCursor);//code deletes all selected control points IFeatureCursor pControlFeatCurs = (IFeatureCursor)pCursor; IFeature pControlFeat = pControlFeatCurs.NextFeature(); int iPointID = pControlFeatCurs.FindField("POINTID"); while (pControlFeat != null) { //Check if the cancel button was pressed. If so, stop process if (bShowProgressor) { bCont = pTrackCancel.Continue(); if (!bCont) { break; } } bool bExists = false; m_pFIDSetControl.Find(pControlFeat.OID, out bExists); if (!bExists) { m_pFIDSetControl.Add(pControlFeat.OID); object obj = pControlFeat.get_Value(iPointID); if (iCounter <= tokenLimit) { //if the PointID is not null add it to a query string as well if (obj != DBNull.Value) { sOIDListPoints[j] += Convert.ToString(obj) + ","; } iCounter++; } else {//maximum tokens reached //set up the next OIDList sOIDListPoints[j] = sOIDListPoints[j].Trim(); iCounter = 0; j++; FabricUTILS.RedimPreserveString(ref sOIDListPoints, 1); sOIDListPoints[j] = "("; if (obj != DBNull.Value) { sOIDListPoints[j] += Convert.ToString(obj) + ","; } } } Marshal.ReleaseComObject(pControlFeat); //garbage collection pControlFeat = pControlFeatCurs.NextFeature(); if (bShowProgressor) { if (pStepProgressor.Position < pStepProgressor.MaxRange) { pStepProgressor.Step(); } } } Marshal.ReleaseComObject(pCursor); //garbage collection if (!bCont) { AbortEdits(bUseNonVersionedDelete, pEd, pWS); return; } if (bUseNonVersionedDelete) { if (!FabricUTILS.StartEditing(pWS, bIsUnVersioned)) { if (bUseNonVersionedDelete) { pCadEd.CadastralFabricLayer = null; } return; } } //first delete all the control point records if (bShowProgressor) { pStepProgressor.Message = "Deleting control points..."; } bool bSuccess = true; pPointsTable = (ITable)pCadFabric.get_CadastralTable(esriCadastralFabricTable.esriCFTPoints); pControlTable = (ITable)pCadFabric.get_CadastralTable(esriCadastralFabricTable.esriCFTControl); if (!bUseNonVersionedDelete) { bSuccess = FabricUTILS.DeleteRowsByFIDSet(pControlTable, m_pFIDSetControl, pStepProgressor, pTrackCancel); } if (bUseNonVersionedDelete) { bSuccess = FabricUTILS.DeleteRowsUnversioned(pWS, pControlTable, m_pFIDSetControl, pStepProgressor, pTrackCancel); } if (!bSuccess) { AbortEdits(bUseNonVersionedDelete, pEd, pWS); return; } //next need to use an in clause to update the points, ... ICadastralFabricSchemaEdit2 pSchemaEd = (ICadastralFabricSchemaEdit2)pCadFabric; //...for each item in the sOIDListPoints array foreach (string inClause in sOIDListPoints) { string sClause = inClause.Trim().TrimEnd(','); if (sClause.EndsWith("(")) { continue; } if (sClause.Length < 3) { continue; } pSchemaEd.ReleaseReadOnlyFields(pPointsTable, esriCadastralFabricTable.esriCFTPoints); m_pQF.WhereClause = (sPref + pPointsTable.OIDFieldName + sSuff).Trim() + " IN " + sClause + ")"; if (!FabricUTILS.ResetPointAssociations(pPointsTable, m_pQF, bIsUnVersioned)) { pSchemaEd.ResetReadOnlyFields(esriCadastralFabricTable.esriCFTPoints); return; } pSchemaEd.ResetReadOnlyFields(esriCadastralFabricTable.esriCFTPoints); } } if (bUseNonVersionedDelete) { FabricUTILS.StopEditing(pWS); } if (pEd.EditState == esriEditState.esriStateEditing) { pEd.StopOperation("Delete Control Points"); } } catch (Exception ex) { MessageBox.Show(ex.Message); return; } finally { RefreshMap(pActiveView, CFControlLayers); //update the TOC IMxDocument mxDocument = (ESRI.ArcGIS.ArcMapUI.IMxDocument)(ArcMap.Application.Document); for (int i = 0; i < mxDocument.ContentsViewCount; i++) { IContentsView pCV = (IContentsView)mxDocument.get_ContentsView(i); pCV.Refresh(null); } if (pProgressorDialog != null) { pProgressorDialog.HideDialog(); } if (bUseNonVersionedDelete) { pCadEd.CadastralFabricLayer = null; CFControlLayers = null; } if (pMouseCursor != null) { pMouseCursor.SetCursor(0); } } }
protected override void OnClick() { IMouseCursor pMouseCursor = new MouseCursorClass(); pMouseCursor.SetCursor(2); //first get the selected parcel features UID pUID = new UIDClass(); pUID.Value = "{114D685F-99B7-4B63-B09F-6D1A41A4DDC1}"; ICadastralExtensionManager2 pCadExtMan = (ICadastralExtensionManager2)ArcMap.Application.FindExtensionByCLSID(pUID); ICadastralEditor pCadEd = (ICadastralEditor)ArcMap.Application.FindExtensionByCLSID(pUID); Marshal.ReleaseComObject(pUID); IEditor pEd = (IEditor)ArcMap.Application.FindExtensionByName("esri object editor"); IFeatureLayer CFPointLayer = null; IFeatureLayer CFLineLayer = null; IFeatureLayer CFControlLayer = null; IFeatureLayer CFLinePointLayer = null; IActiveView pActiveView = ArcMap.Document.ActiveView; IMap pMap = pActiveView.FocusMap; ICadastralFabric pCadFabric = null; IProgressDialog2 pProgressorDialog = null; clsFabricUtils UTILS = new clsFabricUtils(); //if we're in an edit session then grab the target fabric if (pEd.EditState == esriEditState.esriStateEditing) { pCadFabric = pCadEd.CadastralFabric; } if (pCadFabric == null) {//find the first fabric in the map if (!UTILS.GetFabricFromMap(pMap, out pCadFabric)) { MessageBox.Show ("No Parcel Fabric found in the map.\r\nPlease add a single fabric to the map, and try again."); return; } } IArray CFParcelLayers = new ArrayClass(); if (!(UTILS.GetFabricSubLayersFromFabric(pMap, pCadFabric, out CFPointLayer, out CFLineLayer, out CFParcelLayers, out CFControlLayer, out CFLinePointLayer))) { return; //no fabric sublayers available for the targeted fabric } bool bIsFileBasedGDB = false; bool bIsUnVersioned = false; bool bUseNonVersioned = false; IWorkspace pWS = null; try { //Get the selection of parcels IFeatureLayer pFL = (IFeatureLayer)CFParcelLayers.get_Element(0); IDataset pDS = (IDataset)pFL.FeatureClass; pWS = pDS.Workspace; if (!UTILS.SetupEditEnvironment(pWS, pCadFabric, pEd, out bIsFileBasedGDB, out bIsUnVersioned, out bUseNonVersioned)) { return; } if (bUseNonVersioned) { ICadastralFabricLayer pCFLayer = new CadastralFabricLayerClass(); pCFLayer.CadastralFabric = pCadFabric; pCadEd.CadastralFabricLayer = pCFLayer;//NOTE: Need to set this back to NULL when done. } Hashtable FabLyrToFieldMap = new Hashtable(); DateChanger pDateChangerDialog = new DateChanger(); pDateChangerDialog.cboBoxFabricClasses.Items.Clear(); string[] FieldStrArr = new string[CFParcelLayers.Count]; for (int i = 0; i < CFParcelLayers.Count; i++) { FieldStrArr[i] = ""; IFeatureLayer lyr = (IFeatureLayer)CFParcelLayers.get_Element(i); // ICadastralFabricLayer cflyr = CFParcelLayers.get_Element(i); pDateChangerDialog.cboBoxFabricClasses.Items.Add(lyr.Name); IFields pFlds = lyr.FeatureClass.Fields; for (int j = 0; j < lyr.FeatureClass.Fields.FieldCount; j++) { IField pFld = lyr.FeatureClass.Fields.get_Field(j); if (pFld.Type == esriFieldType.esriFieldTypeDate) { if (FieldStrArr[i].Trim() == "") { FieldStrArr[i] = pFld.Name; } else { FieldStrArr[i] += "," + pFld.Name; } } } FabLyrToFieldMap.Add(i, FieldStrArr[i]); } pDateChangerDialog.FieldMap = FabLyrToFieldMap; pDateChangerDialog.cboBoxFabricClasses.SelectedIndex = 0; // ******** Display the dialog ********* DialogResult pDialogResult = pDateChangerDialog.ShowDialog(); if (pDialogResult != DialogResult.OK) { return; } //************************ //*** get the choices from the dialog IFeatureLayer flyr = (IFeatureLayer)CFParcelLayers.get_Element(pDateChangerDialog.cboBoxFabricClasses.SelectedIndex); int iDateFld = flyr.FeatureClass.Fields.FindField(pDateChangerDialog.cboBoxFields.Text); if (pDateChangerDialog.radioButton2.Checked) { IField pFld = flyr.FeatureClass.Fields.get_Field(iDateFld); if (!pFld.IsNullable) { MessageBox.Show("The field you selected does not allow NULL values, and must have a date." + Environment.NewLine + "Please try again using the date option, or using a different date field.", "Field does not Allow Null", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } } ICadastralFabricSubLayer pSubLyr = (ICadastralFabricSubLayer)flyr; bool bLines = false; bool bParcels = false; if (pSubLyr.CadastralTableType == esriCadastralFabricTable.esriCFTLines) { bLines = true; } if (pSubLyr.CadastralTableType == esriCadastralFabricTable.esriCFTParcels) { bParcels = true; } //find out if there is a selection for the chosen layer bool ChosenLayerHasSelection = false; IFeatureSelection pFeatSel = null; ISelectionSet2 pSelSet = null; ICadastralSelection pCadaSel = null; IEnumGSParcels pEnumGSParcels = null; int iFeatureCnt = 0; pFeatSel = (IFeatureSelection)flyr; if (pFeatSel != null) { pSelSet = (ISelectionSet2)pFeatSel.SelectionSet; ChosenLayerHasSelection = (pSelSet.Count > 0); iFeatureCnt = pSelSet.Count; } //**** if (iFeatureCnt == 0) { if (MessageBox.Show("There are no features selected in the " + flyr.Name + " layer." + Environment.NewLine + "Click OK to Change dates for ALL features in the layer.", "No Selection", MessageBoxButtons.OKCancel) != DialogResult.OK) { return; } } else { pCadaSel = (ICadastralSelection)pCadEd; //** TODO: this enum should be based on the selected points, lines, or line-points pEnumGSParcels = pCadaSel.SelectedParcels;// need to get the parcels before trying to get the parcel count: BUG workaround //*** } if (iFeatureCnt == 0) { m_pCursor = (ICursor)flyr.FeatureClass.Search(null, false); ITable pTable = (ITable)flyr.FeatureClass; iFeatureCnt = pTable.RowCount(null); } m_bShowProgressor = (iFeatureCnt > 10); if (m_bShowProgressor) { m_pProgressorDialogFact = new ProgressDialogFactoryClass(); m_pTrackCancel = new CancelTrackerClass(); m_pStepProgressor = m_pProgressorDialogFact.Create(m_pTrackCancel, ArcMap.Application.hWnd); pProgressorDialog = (IProgressDialog2)m_pStepProgressor; m_pStepProgressor.MinRange = 1; m_pStepProgressor.MaxRange = iFeatureCnt; m_pStepProgressor.StepValue = 1; pProgressorDialog.Animation = ESRI.ArcGIS.Framework.esriProgressAnimationTypes.esriProgressSpiral; } m_pQF = new QueryFilterClass(); string sPref; string sSuff; ISQLSyntax pSQLSyntax = (ISQLSyntax)pWS; sPref = pSQLSyntax.GetSpecialCharacter(esriSQLSpecialCharacters.esriSQL_DelimitedIdentifierPrefix); sSuff = pSQLSyntax.GetSpecialCharacter(esriSQLSpecialCharacters.esriSQL_DelimitedIdentifierSuffix); //====== need to do this for all the parcel sublayers in the map that are part of the target fabric if (m_bShowProgressor) { pProgressorDialog.ShowDialog(); m_pStepProgressor.Message = "Collecting data..."; } bool bCont = true; m_pFIDSetParcels = new FIDSetClass(); if (ChosenLayerHasSelection && bParcels && !bIsUnVersioned) { //if there is a selection add the OIDs of all the selected parcels into a new feature IDSet pEnumGSParcels.Reset(); IGSParcel pGSParcel = pEnumGSParcels.Next(); while (pGSParcel != null) { //Check if the cancel button was pressed. If so, stop process if (m_bShowProgressor) { bCont = m_pTrackCancel.Continue(); if (!bCont) { break; } } m_pFIDSetParcels.Add(pGSParcel.DatabaseId); Marshal.ReleaseComObject(pGSParcel); //garbage collection pGSParcel = pEnumGSParcels.Next(); //} if (m_bShowProgressor) { if (m_pStepProgressor.Position < m_pStepProgressor.MaxRange) { m_pStepProgressor.Step(); } } } } if ((!ChosenLayerHasSelection && bParcels && !bIsUnVersioned) || (!ChosenLayerHasSelection && bLines && !bIsUnVersioned)) { IRow pRow = m_pCursor.NextRow(); while (pRow != null) { m_pFIDSetParcels.Add(pRow.OID); Marshal.ReleaseComObject(pRow); pRow = m_pCursor.NextRow(); } Marshal.ReleaseComObject(m_pCursor); } if (bLines && ChosenLayerHasSelection && !bIsUnVersioned) { pSelSet.Search(null, false, out m_pCursor); IRow pRow = m_pCursor.NextRow(); int iFld = m_pCursor.FindField("PARCELID"); while (pRow != null) { m_pFIDSetParcels.Add((int)pRow.get_Value(iFld)); Marshal.ReleaseComObject(pRow); pRow = m_pCursor.NextRow(); } Marshal.ReleaseComObject(m_pCursor); } //========================================================= if (!bCont) { //Since I'm using update cursor need to clear the cadastral selection pCadaSel.SelectedParcels = null; //clear selection, to make sure the parcel explorer is updated and refreshed properly return; } string sTime = ""; if (!bIsUnVersioned) { //see if parcel locks can be obtained on the selected parcels. First create a job. DateTime localNow = DateTime.Now; sTime = Convert.ToString(localNow); ICadastralJob pJob = new CadastralJobClass(); pJob.Name = sTime; pJob.Owner = System.Windows.Forms.SystemInformation.UserName; pJob.Description = "Change Date on selected parcels"; try { Int32 jobId = pCadFabric.CreateJob(pJob); } catch (COMException ex) { if (ex.ErrorCode == (int)fdoError.FDO_E_CADASTRAL_FABRIC_JOB_ALREADY_EXISTS) { MessageBox.Show("Job named: '" + pJob.Name + "', already exists"); } else { MessageBox.Show(ex.Message); } m_pStepProgressor = null; if (!(pProgressorDialog == null)) { pProgressorDialog.HideDialog(); } pProgressorDialog = null; if (bUseNonVersioned) { pCadEd.CadastralFabricLayer = null; } return; } } //if we're in an enterprise then test for edit locks ICadastralFabricLocks pFabLocks = (ICadastralFabricLocks)pCadFabric; if (!bIsUnVersioned) { pFabLocks.LockingJob = sTime; ILongArray pLocksInConflict = null; ILongArray pSoftLcksInConflict = null; ILongArray pParcelsToLock = new LongArrayClass(); UTILS.FIDsetToLongArray(m_pFIDSetParcels, ref pParcelsToLock, m_pStepProgressor); if (m_pStepProgressor != null && !bIsFileBasedGDB) { m_pStepProgressor.Message = "Testing for edit locks on parcels..."; } try { pFabLocks.AcquireLocks(pParcelsToLock, true, ref pLocksInConflict, ref pSoftLcksInConflict); } catch (COMException pCOMEx) { if (pCOMEx.ErrorCode == (int)fdoError.FDO_E_CADASTRAL_FABRIC_JOB_LOCK_ALREADY_EXISTS) { MessageBox.Show("Edit Locks could not be acquired on all selected parcels."); // since the operation is being aborted, release any locks that were acquired pFabLocks.UndoLastAcquiredLocks(); //clear selection, to make sure the parcel explorer is updated and refreshed properly RefreshMap(pActiveView, CFParcelLayers, CFPointLayer, CFLineLayer, CFControlLayer, CFLinePointLayer); } else { MessageBox.Show(Convert.ToString(pCOMEx.ErrorCode)); } if (bUseNonVersioned) { pCadEd.CadastralFabricLayer = null; } return; } } //Now... start the edit. Start an edit operation. if (pEd.EditState == esriEditState.esriStateEditing) { pEd.StartOperation(); } if (bUseNonVersioned) { if (!UTILS.StartEditing(pWS, bUseNonVersioned)) { if (bUseNonVersioned) { pCadEd.CadastralFabricLayer = null; } return; } } //Change all the date records if (m_pStepProgressor != null) { m_pStepProgressor.Message = "Changing dates..."; } bool bSuccess = true; ITable Table2Edit = (ITable)flyr.FeatureClass; ITableWrite pTableWr = (ITableWrite)Table2Edit; if (ChosenLayerHasSelection) { //TODO: Selection based update does not work on unversioned tables //need to change this code to create an update cursor from the selection, //including code for tokens > 995 pSelSet.Update(null, false, out m_pCursor); } else { if (bUseNonVersioned) { m_pCursor = pTableWr.UpdateRows(null, false); } else { m_pCursor = Table2Edit.Update(null, false); } } ICadastralFabricSchemaEdit2 pSchemaEd = (ICadastralFabricSchemaEdit2)pCadFabric; if (bLines) { pSchemaEd.ReleaseReadOnlyFields(Table2Edit, esriCadastralFabricTable.esriCFTLines); //release safety-catch } else if (bParcels) { pSchemaEd.ReleaseReadOnlyFields(Table2Edit, esriCadastralFabricTable.esriCFTParcels); //release safety-catch } else { pSchemaEd.ReleaseReadOnlyFields(Table2Edit, esriCadastralFabricTable.esriCFTPoints); //release safety-catch pSchemaEd.ReleaseReadOnlyFields(Table2Edit, esriCadastralFabricTable.esriCFTControl); //release safety-catch pSchemaEd.ReleaseReadOnlyFields(Table2Edit, esriCadastralFabricTable.esriCFTLinePoints); //release safety-catch } if (pDateChangerDialog.radioButton2.Checked) { bSuccess = UTILS.ChangeDatesOnTable(m_pCursor, pDateChangerDialog.cboBoxFields.Text, "", bUseNonVersioned, m_pStepProgressor, m_pTrackCancel); } else { bSuccess = UTILS.ChangeDatesOnTable(m_pCursor, pDateChangerDialog.cboBoxFields.Text, pDateChangerDialog.dateTimePicker1.Text, bUseNonVersioned, m_pStepProgressor, m_pTrackCancel); } if (!bSuccess) { if (!bIsUnVersioned) { pFabLocks.UndoLastAcquiredLocks(); } if (bUseNonVersioned) { UTILS.AbortEditing(pWS); } else { pEd.AbortOperation(); } //clear selection, to make sure the parcel explorer is updated and refreshed properly return; } if (pEd.EditState == esriEditState.esriStateEditing) { pEd.StopOperation("Change Date"); } if (bUseNonVersioned) { UTILS.StopEditing(pWS); } if (bParcels) { pSchemaEd.ResetReadOnlyFields(esriCadastralFabricTable.esriCFTParcels); } else if (bLines) { pSchemaEd.ResetReadOnlyFields(esriCadastralFabricTable.esriCFTLines); } else { pSchemaEd.ResetReadOnlyFields(esriCadastralFabricTable.esriCFTPoints); //release safety-catch pSchemaEd.ResetReadOnlyFields(esriCadastralFabricTable.esriCFTControl); //release safety-catch pSchemaEd.ResetReadOnlyFields(esriCadastralFabricTable.esriCFTLinePoints); //release safety-catch } } catch (Exception ex) { MessageBox.Show("Error:" + ex.Message); if (bUseNonVersioned) { UTILS.AbortEditing(pWS); } else { pEd.AbortOperation(); } } finally { RefreshMap(pActiveView, CFParcelLayers, CFPointLayer, CFLineLayer, CFControlLayer, CFLinePointLayer); if (bUseNonVersioned) { pCadEd.CadastralFabricLayer = null; CFParcelLayers = null; CFPointLayer = null; CFLineLayer = null; CFControlLayer = null; CFLinePointLayer = null; } m_pStepProgressor = null; if (!(pProgressorDialog == null)) { pProgressorDialog.HideDialog(); } pProgressorDialog = null; } }
public bool DeleteRowsUnversioned(IWorkspace TheWorkSpace, ITable inTable, IFIDSet pFIDSet, IStepProgressor StepProgressor, ITrackCancel TrackCancel) { IMouseCursor pMouseCursor = new MouseCursorClass(); pMouseCursor.SetCursor(2); Debug.WriteLine(StepProgressor.Position); Debug.WriteLine(StepProgressor.MaxRange); IQueryFilter pQF = new QueryFilterClass(); ISQLSyntax pSQLSyntax = (ISQLSyntax)TheWorkSpace; string sPref = pSQLSyntax.GetSpecialCharacter(esriSQLSpecialCharacters.esriSQL_DelimitedIdentifierPrefix); string sSuff = pSQLSyntax.GetSpecialCharacter(esriSQLSpecialCharacters.esriSQL_DelimitedIdentifierSuffix); ICursor ipCursor = null; IRow pRow = null; //make sure that there are no more then 999 tokens for the in clause(ORA- query will otherwise error on an Oracle database) int iTokenLimit = 995; int iTokenSet = 0; //the index of the set of 995 tokens string sWhereClauseLHS = sPref + inTable.OIDFieldName + sSuff + " in ("; string[] ids = { sWhereClauseLHS }; try { ITableWrite pTableWr = (ITableWrite)inTable; pFIDSet.Reset(); bool bCont = true; Int32 iID; Int32 count = pFIDSet.Count(); int j = 0; //inner count for each set of IDs for (int k = 0; k < count; k++) { if (j > iTokenLimit) {//over the limit for this Token set, time to create a new set ids[iTokenSet] += ")";//close the previous set RedimPreserveString(ref ids, 1);//make space in the string array for the next token set iTokenSet++;//increment the index ids[iTokenSet] = sWhereClauseLHS; //left-hand side of the where clause j = 0;//reset the inner count back to zero } pFIDSet.Next(out iID); if (j > 0) //write a comma if this is not the first ID ids[iTokenSet] += ","; ids[iTokenSet] += iID.ToString(); j++; //increment the inner count } ids[iTokenSet] += ")"; if (count > 0) { for (int k = 0; k <= iTokenSet; k++) { pQF.WhereClause = ids[k]; ipCursor = pTableWr.UpdateRows(pQF, false); pRow = ipCursor.NextRow(); while (pRow != null) { ipCursor.DeleteRow(); Marshal.ReleaseComObject(pRow); if (StepProgressor != null) { //Check if the cancel button was pressed. If so, stop process if (TrackCancel != null) bCont = TrackCancel.Continue(); if (!bCont) break; if (StepProgressor.Position < StepProgressor.MaxRange) StepProgressor.Step(); } pRow = ipCursor.NextRow(); } if (!bCont) { AbortEditing(TheWorkSpace); if (ipCursor != null) Marshal.ReleaseComObject(ipCursor); if (pRow != null) Marshal.ReleaseComObject(pRow); //if (pQF != null) // Marshal.ReleaseComObject(pQF); return false; } Marshal.ReleaseComObject(ipCursor); } //Marshal.ReleaseComObject(pQF); } Debug.WriteLine(StepProgressor.Position); return true; } catch (Exception ex) { if (ipCursor != null) Marshal.ReleaseComObject(ipCursor); if (pRow != null) Marshal.ReleaseComObject(pRow); //if (pQF != null) // Marshal.ReleaseComObject(pQF); MessageBox.Show(Convert.ToString(ex.Message)); return false; } }
public bool DeleteRowsByFIDSetReturnGeomCollection(ITable inTable, IFIDSet pFIDSet, IStepProgressor StepProgressor, ITrackCancel TrackCancel, ref IGeometryCollection GeomCollection) { //this routine uses the GetRows method, avoids the need to break up the InClause. if (pFIDSet == null) return false; IMouseCursor pMouseCursor = new MouseCursorClass(); pMouseCursor.SetCursor(2); try { pFIDSet.Reset(); int[] iID = { }; bool bCont = true; iID = RedimPreserveInt(ref iID, pFIDSet.Count()); for (int iCount = 0; iCount <= pFIDSet.Count() - 1; iCount++) pFIDSet.Next(out iID[iCount]); ICursor pCursor = inTable.GetRows(iID, false); IRow row = pCursor.NextRow(); if (StepProgressor != null) { if (StepProgressor.Position < StepProgressor.MaxRange) StepProgressor.Step(); } while (row != null) { IFeature pFeat = row as IFeature; IGeometry pGeom = pFeat.ShapeCopy; if (pGeom != null) { if (!pGeom.IsEmpty) { object obj = Type.Missing; IEnvelope2 pEnv = (IEnvelope2)pGeom.Envelope; pEnv.Expand(0.1, 0.1, false); GeomCollection.AddGeometry(pEnv, ref obj, ref obj); } } //Check if the cancel button was pressed. If so, stop process if (StepProgressor != null) { if (TrackCancel != null) bCont = TrackCancel.Continue(); if (!bCont) break; } row.Delete(); Marshal.ReleaseComObject(row); row = pCursor.NextRow(); if (StepProgressor != null) { if (StepProgressor.Position < StepProgressor.MaxRange) StepProgressor.Step(); } } Marshal.ReleaseComObject(pCursor); inTable = null; iID = null; if (!bCont) return false; return true; } catch (COMException ex) { StepProgressor = null; if (ex.ErrorCode == -2147217400) //MessageBox.Show(ex.ErrorCode + Environment.NewLine + ex.Message + // Environment.NewLine + "This error indicates that the fabric may not have been correctly upgraded."); //TODO: need to confirm this. m_LastErrorCode = ex.ErrorCode; else MessageBox.Show(ex.Message + Environment.NewLine + ex.ErrorCode); m_LastErrorCode = ex.ErrorCode; return false; } }
private void CreateBatchFile() { string path = ""; FolderBrowserDialog fbd = new FolderBrowserDialog(); if (fbd.ShowDialog() == DialogResult.OK) { path = fbd.SelectedPath; } if (!Directory.Exists(path)) { Utilities_MessageBox.ErrorBox("Path Does Not Exist", MB_TITLE); return; } int versionCount = 1; // This is used to make mutiple files so the batch file don't overwrite on another. string filePath = path + string.Format(@"\{0}_{1}_{2}.bat", cbo_TileIndex.Text, "CopyFiles", versionCount); while (File.Exists(filePath)) { versionCount++; filePath = path + string.Format(@"\{0}_{1}_{2}.bat", cbo_TileIndex.Text, "CopyFiles", versionCount); } bool itWorked = false; int cloneCount = 1; // labeling the processor bar ITrackCancel trackcancel = new CancelTracker(); IProgressDialogFactory progressdialogfactory = new ProgressDialogFactoryClass(); IStepProgressor stepprogressor = progressdialogfactory.Create(trackcancel, _application.hWnd); stepprogressor.MinRange = 0; stepprogressor.MaxRange = _fileList.Count; stepprogressor.StepValue = 1; stepprogressor.Message = "Generating..."; IProgressDialog2 progressdialog = (IProgressDialog2)stepprogressor; // Creates and displays progressdialog.CancelEnabled = false; progressdialog.Description = "Prepping {_fileList.Count} files..."; progressdialog.Title = MB_TITLE; progressdialog.Animation = esriProgressAnimationTypes.esriProgressSpiral; foreach (KeyValuePair <String, Boolean> file in _fileList) { if (file.Value) { progressdialog.Description = string.Format("Adding File {0} of {1}...", cloneCount, _fileList.Count); if (!itWorked) { SaveFileTypeList(GetExtension()); } itWorked = true; try { var sourceFile = txb_FileWorkspaceSrc.Text + @"\" + Utilities_General.AddPrefixAndSuffixToFileName(file.Key, txb_Prefix.Text, txb_Suffix.Text) + GetExtension(); var destinationFile = txb_FileWorkspaceDst.Text + @"\" + Utilities_General.AddPrefixAndSuffixToFileName(file.Key, txb_Prefix.Text, txb_Suffix.Text) + GetExtension(); using (System.IO.StreamWriter sw = File.AppendText(filePath)) { sw.WriteLine(String.Format("copy {0} {1}", sourceFile, destinationFile)); } } catch (Exception yourBest) // but you don't succeed { yourBest.ToString(); // Just So We Get No Crashes ;) } stepprogressor.Step(); cloneCount++; } } trackcancel = null; stepprogressor = null; progressdialog.HideDialog(); progressdialog = null; //_activeView.Refresh(); }
/// <summary> /// Incorpora lecturas desde los archivos descargados desde la intranet /// </summary> private void IncorporarLecturas2() { statusLblProcesando.Text = "Incorporando Lecturas..."; IProgressDialogFactory pProDiaFac = new ProgressDialogFactoryClass(); IStepProgressor pStepPro = pProDiaFac.Create(null, 0); pStepPro.MinRange = 1; pStepPro.MaxRange = 5; pStepPro.StepValue = 1; IProgressDialog2 pProDia = (IProgressDialog2)pStepPro; pProDia.Animation = esriProgressAnimationTypes.esriProgressGlobe; pProDia.Title = "Incorporando Lecturas"; pProDia.ShowDialog(); pStepPro.Step(); pStepPro.Message = "Incorporando temperatura..."; SIGPIParametros parametros = _parametros; PrepararInformacion preparar = new PrepararInformacion(); string mesTemperatura, mesPrecipitacion; string sRuta = parametros.RutaSIGPI + "\\" + parametros.Lecturas + "\\" + LECTURAS_TEMPERATURA; if (!System.IO.File.Exists(sRuta)) { MessageBox.Show("No existe el Archivo '" + sRuta + "' Verifique la ruta"); return; } Microsoft.Office.Interop.Excel.Application _excelApp = new Microsoft.Office.Interop.Excel.Application(); Workbook workBook = _excelApp.Workbooks.Open(sRuta, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing); Worksheet sheet; try { sheet = (Worksheet)workBook.Sheets[1]; } catch (Exception ex) { MessageBox.Show(ex.Message); _excelApp.Workbooks.Close(); pProDia.HideDialog(); return; } mesTemperatura = ""; try { mesTemperatura = preparar.VerificarFechasLecturas(sheet, SIGPI_CELDA_MES_TEMPERATURA); } catch (Exception ex) { _excelApp.Workbooks.Close(); pProDia.HideDialog(); MessageBox.Show(ex.Message); return; } DateTime dFechaAIncorporar = dtPickerFechaAIncorporar.Value; int iDay = dFechaAIncorporar.Day; if (dFechaAIncorporar.Month != ConversionMes.MesNumero(mesTemperatura.ToUpper())) { if (dFechaAIncorporar.Month != ConversionMes.MesNumero(mesTemperatura.ToUpper()) + 1) { MessageBox.Show("La fecha seleccionada no se encuentra en el archivo de lecturas. Periodo correspondiente al mes de: " + mesTemperatura); _excelApp.Workbooks.Close(); pProDia.HideDialog(); return; } } int iTotalEstaciones = preparar.TotalEstaciones(sheet, SIGPI_COLUMNA_ESTACIONES); string sColumnaDia = preparar.ColumnaLecturaDia(sheet, 8, iDay.ToString(), "3"); if (sColumnaDia == "-99") { MessageBox.Show("No se encontro el dia de lectura en el archivo de Excel de temperaturas. Dia: " + iDay.ToString()); _excelApp.Workbooks.Close(); pProDia.HideDialog(); return; } List <Lectura> listaTemperatura = preparar.ObtenerLecturas(sheet, _sigpiDao, SIGPI_COLUMNA_CODIGO_TEMPERATURA, sColumnaDia, SIGPI_TEMPERATURA_MIN_VAL, SIGPI_TEMPERATURA_MAX_VAL); //pStepPro.Step(); DateTime dFechaIncorporacionActual = dtPickerFechaAIncorporar.Value; //_sigpi.FechaIncorporacion.AddDays(1); //string sFechaIncorporacionActual = dFechaIncorporacionActual.ToString("dd/MM/yyyy"); bool bIncorporarTemperatura = preparar.IncorporarLecturas(_sigpiDao, SIGPI_TABLA_LECTURAS_TEMPERATURA, dFechaIncorporacionActual, listaTemperatura); pStepPro.Message = "Incorporando Precipitacion..."; pStepPro.Step(); pStepPro.StepValue = 3; sRuta = parametros.RutaSIGPI + "\\" + parametros.Lecturas + "\\" + LECTURAS_PRECIPITACION; _excelApp.Workbooks.Close(); _excelApp = new Microsoft.Office.Interop.Excel.Application(); workBook = _excelApp.Workbooks.Open(sRuta, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing); sheet = (Worksheet)workBook.Sheets[1]; try { mesPrecipitacion = preparar.VerificarFechasLecturas(sheet, SIGPI_CELDA_MES_PRECIPITACION); } catch (Exception ex) { MessageBox.Show(ex.Message); _excelApp.Workbooks.Close(); pProDia.HideDialog(); return; } sColumnaDia = preparar.ColumnaLecturaDia(sheet, 8, iDay.ToString(), "2"); if (sColumnaDia == "-99") { MessageBox.Show("No se encontro el dia de lectura en el archivo de Excel de precipitacion. Dia: " + iDay.ToString()); _excelApp.Workbooks.Close(); pProDia.HideDialog(); return; } List <Lectura> listaPrecipitacion = preparar.ObtenerLecturas(sheet, _sigpiDao, SIGPI_COLUMNA_CODIGO_PRECIPITACION, sColumnaDia, SIGPI_PRECIPITACION_MIN_VAL, SIGPI_PRECIPITACION_MAX_VAL); bool bIncorporarPrecip = preparar.IncorporarLecturas(_sigpiDao, SIGPI_TABLA_LECTURAS_PRECIPITACION, dFechaIncorporacionActual, listaPrecipitacion); pStepPro.StepValue = 4; pProDia.HideDialog(); if (bIncorporarTemperatura && bIncorporarPrecip) { txtUltimoDiaIncorporacion.Text = dtPickerFechaAIncorporar.Value.ToLongDateString(); preparar.ActualizarFechaIncorporacion(dtPickerFechaAIncorporar.Value, _sigpiDao); _sigpi.FechaIncorporacion = dtPickerFechaAIncorporar.Value; dtPickerFechaAProcesar.Value = dtPickerFechaAIncorporar.Value; dtPickerFechaAIncorporar.Value = dtPickerFechaAIncorporar.Value.AddDays(1); MessageBox.Show("Incorporacion de lecturas terminada!"); } _excelApp.Workbooks.Close(); }
public bool DeleteByInClause(IWorkspace TheWorkSpace, ITable inTable, IField QueryIntegerField, List <string> InClauseIDs, bool IsVersioned, IStepProgressor StepProgressor, ITrackCancel TrackCancel) { IMouseCursor pMouseCursor = new MouseCursorClass(); pMouseCursor.SetCursor(2); IQueryFilter pQF = new QueryFilterClass(); ISQLSyntax pSQLSyntax = (ISQLSyntax)TheWorkSpace; string sPref = pSQLSyntax.GetSpecialCharacter(esriSQLSpecialCharacters.esriSQL_DelimitedIdentifierPrefix); string sSuff = pSQLSyntax.GetSpecialCharacter(esriSQLSpecialCharacters.esriSQL_DelimitedIdentifierSuffix); ICursor ipCursor = null; IRow pRow = null; //make sure that there are no more then 999 tokens for the in clause(ORA- query will otherwise error on an Oracle database) //this code assumes that InClauseIDs holds an arraylist of comma separated OIDs with no more than 995 id's per list item string sWhereClauseLHS = sPref + QueryIntegerField.Name + sSuff + " in ("; try { ITableWrite pTableWr = (ITableWrite)inTable; bool bCont = true; Int32 count = InClauseIDs.Count - 1; for (int k = 0; k <= count; k++) { pQF.WhereClause = sWhereClauseLHS + InClauseIDs[k] + ")"; //left-hand side of the where clause if (pQF.WhereClause.Contains("()")) { continue; } if (!IsVersioned) { ipCursor = pTableWr.UpdateRows(pQF, false); } else { ipCursor = inTable.Update(pQF, false); } pRow = ipCursor.NextRow(); while (pRow != null) { ipCursor.DeleteRow(); Marshal.ReleaseComObject(pRow); if (StepProgressor != null) { //Check if the cancel button was pressed. If so, stop process if (TrackCancel != null) { bCont = TrackCancel.Continue(); } if (!bCont) { break; } if (StepProgressor.Position < StepProgressor.MaxRange) { StepProgressor.Step(); } } pRow = ipCursor.NextRow(); } if (!bCont) { AbortEditing(TheWorkSpace); if (ipCursor != null) { Marshal.ReleaseComObject(ipCursor); } if (pRow != null) { Marshal.ReleaseComObject(pRow); } return(false); } Marshal.ReleaseComObject(ipCursor); } return(true); } catch (Exception ex) { if (ipCursor != null) { Marshal.ReleaseComObject(ipCursor); } if (pRow != null) { Marshal.ReleaseComObject(pRow); } MessageBox.Show(Convert.ToString(ex.Message)); return(false); } }
private void ExportTable(Excel.Workbook ExcelWbk, IMxDocument MxDoc, IStandaloneTable StandTable, ref IProgressDialog2 progressDialog, ref IStepProgressor stepProgressor) { ITableProperties TableProperties = null; IEnumTableProperties EnumTableProperties = null; ITableProperty3 TableProperty = null; ITableCharacteristics TableCharacteristics = null; ITableSelection TabSel = null; IDisplayTable DisplayTable = null; ITable Table = null; IRow TabRow = null; IObjectClass ObjectClass = null; ISubtypes Subtypes = null; ITableFields TableFields = null; ICursor Cursor = null; IField CurField = null; IDomain Domain = null; ICodedValueDomain CodedValueDomain = null; object missing = null; object sheet = null; Microsoft.Office.Interop.Excel.Style style = null; try { bool UseDescriptions; int subtype; string SheetName; int Col = 0; int Row = 0; int i; int j; missing = System.Reflection.Missing.Value; sheet = ExcelWbk.Sheets[ExcelWbk.Sheets.Count]; Excel.Worksheet ExcelSheet; Excel.Range ExcelRange; //Add new Excel worksheet ExcelSheet = (Excel.Worksheet)ExcelWbk.Sheets.Add(missing, sheet, missing, missing); //style = ExcelWbk.Styles.Add("Style1"); //style.NumberFormat = "@"; //style.Font.Name = "Arial"; //style.Font.Bold = True //style.Font.Size = 12; //style.Interior.Pattern = Microsoft.Office.Interop.Excel.XlPattern.xlPattern Solid //style.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlighLe ft SheetName = StandTable.Name; if (SheetName.Length > 30) { SheetName = SheetName.Substring(0, 30); } ExcelSheet.Name = SheetName; //Determine whether to use descriptions or codes for domains UseDescriptions = true; TableProperties = MxDoc.TableProperties; EnumTableProperties = (IEnumTableProperties)TableProperties; EnumTableProperties.Reset(); TableProperty = (ITableProperty3)EnumTableProperties.Next(); while (TableProperty != null) { if (TableProperty.StandaloneTable != null) { if (TableProperty.StandaloneTable.Equals(StandTable)) { TableCharacteristics = (ITableCharacteristics)TableProperty; UseDescriptions = TableCharacteristics.ShowCodedValueDomainDescriptions; break; } } TableProperty = (ITableProperty3)EnumTableProperties.Next(); } TabSel = (ITableSelection)StandTable; DisplayTable = (IDisplayTable)StandTable; Table = (ITable)DisplayTable.DisplayTable; //Get subtype info ObjectClass = Table as IObjectClass; Subtypes = ObjectClass as ISubtypes; //Get TableFields so later we can determine whether that field is visible TableFields = (ITableFields)StandTable; //loop through each field and write column headings Row = 1; for (j = 0; j < TableFields.FieldCount; j++) { CurField = TableFields.get_Field(j); //skip blob and geometry fields if ((CurField.Type != esriFieldType.esriFieldTypeBlob) && (CurField.Type != esriFieldType.esriFieldTypeGeometry)) { Col += 1; //Write field alias name as Excel column header ExcelSheet.Cells[Row, Col] = TableFields.get_FieldInfo(j).Alias; if (CurField.Type == esriFieldType.esriFieldTypeString) ExcelSheet.get_Range(ExcelSheet.Cells[1, Col], ExcelSheet.Cells[65535, Col]).EntireColumn.NumberFormat = "@"; } } //Get all selected records for this table (use IDisplayTable to get any joined data) DisplayTable.DisplaySelectionSet.Search(null, true, out Cursor); //subtype = Subtypes.DefaultSubtypeCode; //For each selected record TabRow = Cursor.NextRow(); //stepProgressor.Step(); // progressDialog.Description = A4LGSharedFunctions.Localizer.GetString("ExportAsset") + stepProgressor.Position + A4LGSharedFunctions.Localizer.GetString("Of") + MxDoc.FocusMap.SelectionCount.ToString() + "."; while (TabRow != null) { Row += 1; if (Subtypes != null && Subtypes.HasSubtype == true && (TabRow.get_Value(Subtypes.SubtypeFieldIndex) != null)) { subtype = Convert.ToInt32(TabRow.get_Value(Subtypes.SubtypeFieldIndex)); } else { subtype = -99999; } //For each column Col = 0; for (j = 0; j < TableFields.FieldCount; j++) { CurField = TableFields.get_Field(j); //skip blob and geometry fields in data also if ((CurField.Type != esriFieldType.esriFieldTypeBlob) && (CurField.Type != esriFieldType.esriFieldTypeGeometry)) { Col += 1; ExcelSheet.Cells[Row, Col] = TabRow.get_Value(j); if (UseDescriptions == true && subtype == -99999) { Domain = CurField.Domain; if (Domain != null) { if (Domain.Type == esriDomainType.esriDTCodedValue) { CodedValueDomain = (ICodedValueDomain)CurField.Domain; for (i = 0; i < CodedValueDomain.CodeCount; i++) { if ((CodedValueDomain.get_Value(i)).ToString() == (TabRow.get_Value(j)).ToString()) { //System.Diagnostics.Debug.Print(CodedValueDomain.get_Name(0).ToString()); ExcelSheet.Cells[Row, Col] = CodedValueDomain.get_Name(i); i = CodedValueDomain.CodeCount; } } } } } else if (UseDescriptions == true && subtype != -99999) { if (Subtypes.SubtypeFieldIndex == j) { ExcelSheet.Cells[Row, Col] = Subtypes.get_SubtypeName(subtype); } else { Domain = Subtypes.get_Domain(subtype, CurField.Name); if ((Domain != null) && (Domain.Type == esriDomainType.esriDTCodedValue)) { CodedValueDomain = (ICodedValueDomain)Domain; for (i = 0; i < CodedValueDomain.CodeCount; i++) { if ((CodedValueDomain.get_Value(i)).ToString() == (TabRow.get_Value(j)).ToString()) { //System.Diagnostics.Debug.Print(CodedValueDomain.get_Name(0).ToString()); ExcelSheet.Cells[Row, Col] = CodedValueDomain.get_Name(i); i = CodedValueDomain.CodeCount; } } } } } } } stepProgressor.Step(); progressDialog.Description = A4LGSharedFunctions.Localizer.GetString("ExportAsset") + stepProgressor.Position + A4LGSharedFunctions.Localizer.GetString("Of") + MxDoc.FocusMap.SelectionCount.ToString() + "."; TabRow = Cursor.NextRow(); } //Hide Columns Col = 0; for (j = 0; j < TableFields.FieldCount; j++) { CurField = TableFields.get_Field(j); //skip blob and geometry fields in data also if ((CurField.Type != esriFieldType.esriFieldTypeBlob) && (CurField.Type != esriFieldType.esriFieldTypeGeometry)) { Col += 1; //Autofit ExcelRange = ExcelSheet.get_Range(ExcelSheet.Cells[1, Col], ExcelSheet.Cells[Row, Col]); ExcelRange.EntireColumn.AutoFit(); //Hide column if invisible in ArcMap if (TableFields.get_FieldInfo(j).Visible == false) { ExcelRange = ExcelSheet.get_Range(ExcelSheet.Cells[1, Col], ExcelSheet.Cells[Row, Col]); ExcelRange.EntireColumn.Hidden = true; } } } } catch { MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("ExportXLError")); } finally { TableProperties = null; EnumTableProperties = null; TableProperty = null; TableCharacteristics = null; TabSel = null; DisplayTable = null; Table = null; TabRow = null; ObjectClass = null; Subtypes = null; TableFields = null; if (Cursor != null) Marshal.ReleaseComObject(Cursor); Cursor = null; CurField = null; Domain = null; CodedValueDomain = null; missing = null; sheet = null; style = null; } }
private void button1_Click(object sender, EventArgs e) { IProgressDialogFactory pProDiaFac = new ProgressDialogFactoryClass(); IStepProgressor pStepPro = pProDiaFac.Create(null, 0); pStepPro.MinRange = 1; pStepPro.MaxRange = 5; pStepPro.StepValue = 1; IProgressDialog2 pProDia = (IProgressDialog2)pStepPro; pProDia.Animation = esriProgressAnimationTypes.esriProgressGlobe; pProDia.Title = "Generar Grids"; pProDia.ShowDialog(); pStepPro.Step(); pStepPro.Message = "Generando Grids Meteorologicos..."; IFeatureClass pFeatureClass; IWorkspaceFactory pShpWorkspaceFactory = new ShapefileWorkspaceFactoryClass(); IWorkspace pWorkspaceTemp = pShpWorkspaceFactory.OpenFromFile(parametros.RutaSIGPI + parametros.Temporal, 0); try { pFeatureClass = procesamiento.ConstruirFeatureClass(pWorkspaceTemp, "DEFI_PRECI", "estaciones", "CODIGO", "DEFI_PRECI.P5 >= 0", "JP"); } catch (Exception ex) { MessageBox.Show("Error generando el FeatureClass de Estaciones. Descripcion: \n" + ex.Message); return; } IWorkspaceFactory pWF = new AccessWorkspaceFactoryClass(); IFeatureWorkspace pWSMask = (IFeatureWorkspace)pWF.OpenFromFile(parametros.RutaGBD, 0); IGeoDataset pFCMask = (IGeoDataset)pWSMask.OpenFeatureClass(parametros.Mascara); DateTime date = sigpi.FechaProcesamiento; string sMonth = date.ToString("MM"); //P5 pStepPro.Step(); pStepPro.Message = "Generando Grids Meteorologicos: Precipitacion Total"; IRaster pRaster1 = procesamiento.ConstruirGrid(pFeatureClass, "P5", parametros, pFCMask, "RP5", "", true); //DSLL5 pStepPro.Step(); pStepPro.Message = "Generando Grids Meteorologicos: Promedio ultimos 5 dias sin lluvia"; IRaster pRaster2 = procesamiento.ConstruirGrid(pFeatureClass, "DSLL5", parametros, pFCMask, "DSLL5", "", true); pFeatureClass = procesamiento.ConstruirFeatureClass(pWorkspaceTemp, "DEFI_TEMPE", "estaciones", "CODIGO", "DEFI_TEMPE.T5 >= 0", "JT"); //T5 pStepPro.Step(); pStepPro.Message = "Generando Grids Meteorologicos: Temperatura promedio"; IRaster pRaster3 = procesamiento.ConstruirGrid(pFeatureClass, "T5", parametros, pFCMask, "RT5", "", true); //TMMMM IRaster pRaster4 = SIGPIUtils.AbrirRasterDesdeArchivo(parametros.RutaSIGPI + "\\" + parametros.TMMMM, "tmmx" + sMonth); //Susceptibilidad //IRaster pRaster5 = SIGPIUtils.AbrirRaster(parametros.RutaSIGPI + "\\" + parametros.Grids, parametros.Susceptibilidad); IRaster pRaster5 = SIGPIUtils.AbrirRasterDesdeGDB(parametros.RutaGBD, parametros.Susceptibilidad); //Asentamientos //IRaster pRaster6 = SIGPIUtils.AbrirRaster(parametros.RutaSIGPI + "\\" + parametros.Grids, parametros.Asentamientos); IRaster pRaster6 = SIGPIUtils.AbrirRasterDesdeGDB(parametros.RutaGBD, parametros.Asentamientos); IRaster[] pRasters = { pRaster1, pRaster2, pRaster3, pRaster4, pRaster5, pRaster6 }; try { procesamiento.AlgoritmoCompleto(pRasters, sigpi); } catch (Exception ex) { MessageBox.Show(ex.Message); } pProDia.HideDialog(); MessageBox.Show("Algoritmo completo ejecutado"); }
private void MakeAreaVolumeTable(double dStartingElev, double dEndingElev, double dGraduationValue) { SaveFileDialog dlgSaveFile = new SaveFileDialog(); dlgSaveFile.Filter = "csv files (*.csv)|*.csv|All files (*.*)|*.*"; if (dlgSaveFile.ShowDialog() == DialogResult.OK) { Toggle3DExtension("ON"); StreamWriter sw = new StreamWriter(dlgSaveFile.FileName); sw.WriteLine("Elevation,Area_acres,Volume"); IMxDocument pmxdoc = ArcMap.Document as IMxDocument; IMap pmap = pmxdoc.FocusMap; ILayer player = FindLayer(pmap, cboRasterLayers.Text); //bool bFeetCorrect = chkFeetCorrect.Checked; esriPlaneReferenceType eRef; double dlbRange = Math.Abs(dStartingElev - dEndingElev); IProgressDialog2 pProgressDialog = ShowProgressIndicator("Calculating...", Convert.ToInt32(dlbRange / dGraduationValue), 1); pProgressDialog.ShowDialog(); eRef = esriPlaneReferenceType.esriPlaneReferenceBelow; ////if (radAbove.Checked) ////{ //// eRef = esriPlaneReferenceType.esriPlaneReferenceAbove; ////} ////else ////{ //// eRef = esriPlaneReferenceType.esriPlaneReferenceBelow; ////} ISurface pSurface = GetSurfaceFromLayer(player); while (dEndingElev > dStartingElev) { pStepProgressor.Step(); //Check difference between these two calculations double dArea = pSurface.GetProjectedArea(dStartingElev, eRef); //double dArea = pSurface.GetSurfaceArea(dStartingElev, eRef); //Convert square meters to acres dArea = dArea * 0.000247; double dVolume = pSurface.GetVolume(dStartingElev, eRef); //Convert cubic meter to acre-foot dVolume = dVolume * 0.000811; //Meters to feet. Probably not needed if (chkVertUnitCorrect.Checked) { dVolume = dVolume / 3.28084; } sw.WriteLine(dStartingElev + "," + dArea + "," + dVolume); dStartingElev = dStartingElev + dGraduationValue; } sw.Close(); pProgressDialog.HideDialog(); } AddTable(Path.GetDirectoryName(dlgSaveFile.FileName), Path.GetFileName(dlgSaveFile.FileName)); Toggle3DExtension("OFF"); }
public void ExtractPointData(string sLineLayer, string sRasterLayer, double dblInterval, string strFileName) { try { strSaveFile = strFileName; IMxDocument pmxdoc = ArcMap.Document as IMxDocument; IMap pmap = pmxdoc.FocusMap; IFeatureLayer pLineLayer = FindLayer(sLineLayer) as IFeatureLayer; IRasterLayer pRasterLayer = FindLayer(sRasterLayer) as IRasterLayer; //IFeatureLayer pPointLayer = FindLayer(sPointLayer) as IFeatureLayer; IFeatureLayer pPointLayer = new FeatureLayerClass(); pPointLayer.FeatureClass = MakePointFC(); //pPointLayer.Name = "Points"; // ArcMap.Document.ActiveView.FocusMap.AddLayer(pPointLayer); //get the Workspace from the IDataset interface on the feature class IDataset dataset = (IDataset)pLineLayer.FeatureClass; IWorkspace workspace = dataset.Workspace; //Cast for an IWorkspaceEdit IWorkspaceEdit workspaceEdit = (IWorkspaceEdit)workspace; //Start an edit session and operation workspaceEdit.StartEditing(true); workspaceEdit.StartEditOperation(); IProgressDialog2 pProgressDialog = ShowProgressIndicator("Calculating...", pLineLayer.FeatureClass.FeatureCount(null), 1); pProgressDialog.ShowDialog(); //Set up the Outpoints cursor IFeatureCursor pFCurOutPoints = pPointLayer.Search(null, false); pFCurOutPoints = pPointLayer.FeatureClass.Insert(true); //Set up the LineLayer Cursor IFeatureCursor pFCur = pLineLayer.Search(null, false); IFeature pLineFeature = pFCur.NextFeature(); IFeatureBuffer pFBuffer = pPointLayer.FeatureClass.CreateFeatureBuffer(); ICurve pCurve; double dlbProcessedLength = 0; double dblFCTotalLength = 0; int p = 0; while (pLineFeature != null) { pProgressDialog.Description = "Calculating line segment " + p.ToString() + " of: " + pLineLayer.FeatureClass.FeatureCount(null).ToString(); //create startpoint pCurve = pLineFeature.Shape as ICurve; pFBuffer.Shape = pCurve.FromPoint; pFBuffer.set_Value(pFBuffer.Fields.FindField("Distance"), 0); pFBuffer.set_Value(pFBuffer.Fields.FindField("LineOID"), pLineFeature.OID); pFBuffer.set_Value(pFBuffer.Fields.FindField("X"), pCurve.FromPoint.X); pFBuffer.set_Value(pFBuffer.Fields.FindField("Y"), pCurve.FromPoint.Y); pFCurOutPoints.InsertFeature(pFBuffer); double dblTotalDistance = pCurve.Length; dlbProcessedLength = dblInterval; IConstructPoint contructionPoint; IPoint ppoint; while (dlbProcessedLength <= dblTotalDistance) { contructionPoint = new PointClass(); contructionPoint.ConstructAlong(pCurve, esriSegmentExtension.esriNoExtension, dlbProcessedLength, false); ppoint = new PointClass(); ppoint = contructionPoint as IPoint; pFBuffer.Shape = ppoint; //dblFCTotalLength += dblInterval; pFBuffer.set_Value(pFBuffer.Fields.FindField("Distance"), Math.Round(dlbProcessedLength, 4)); pFBuffer.set_Value(pFBuffer.Fields.FindField("LineOID"), pLineFeature.OID); pFBuffer.set_Value(pFBuffer.Fields.FindField("X"), ppoint.X); pFBuffer.set_Value(pFBuffer.Fields.FindField("Y"), ppoint.Y); pFCurOutPoints.InsertFeature(pFBuffer); dlbProcessedLength += dblInterval; pStepProgressor.Step(); } dblFCTotalLength += dblInterval; p++; pLineFeature = pFCur.NextFeature(); } //cleanup pFCurOutPoints.Flush(); pFCur.Flush(); //Stop editing workspaceEdit.StopEditOperation(); workspaceEdit.StopEditing(true); Extract(pRasterLayer, pPointLayer); pProgressDialog.HideDialog(); pmxdoc.ActiveView.Refresh(); } catch (Exception ex) { MessageBox.Show(ex.Message); MessageBox.Show(ex.StackTrace); } }
public bool DeleteByInClause(IWorkspace TheWorkSpace, ITable inTable, IField QueryIntegerField, List<string> InClauseIDs, bool IsVersioned, IStepProgressor StepProgressor, ITrackCancel TrackCancel) { IMouseCursor pMouseCursor = new MouseCursorClass(); pMouseCursor.SetCursor(2); IQueryFilter pQF = new QueryFilterClass(); ISQLSyntax pSQLSyntax = (ISQLSyntax)TheWorkSpace; string sPref = pSQLSyntax.GetSpecialCharacter(esriSQLSpecialCharacters.esriSQL_DelimitedIdentifierPrefix); string sSuff = pSQLSyntax.GetSpecialCharacter(esriSQLSpecialCharacters.esriSQL_DelimitedIdentifierSuffix); ICursor ipCursor = null; IRow pRow = null; //make sure that there are no more then 999 tokens for the in clause(ORA- query will otherwise error on an Oracle database) //this code assumes that InClauseIDs holds an arraylist of comma separated OIDs with no more than 995 id's per list item string sWhereClauseLHS = sPref + QueryIntegerField.Name + sSuff + " in ("; try { ITableWrite pTableWr = (ITableWrite)inTable; bool bCont = true; Int32 count = InClauseIDs.Count - 1; for (int k = 0; k <= count; k++) { pQF.WhereClause = sWhereClauseLHS + InClauseIDs[k] + ")"; //left-hand side of the where clause if (pQF.WhereClause.Contains("()")) continue; if (!IsVersioned) ipCursor = pTableWr.UpdateRows(pQF, false); else ipCursor = inTable.Update(pQF, false); pRow = ipCursor.NextRow(); while (pRow != null) { ipCursor.DeleteRow(); Marshal.ReleaseComObject(pRow); if (StepProgressor != null) { //Check if the cancel button was pressed. If so, stop process if (TrackCancel != null) bCont = TrackCancel.Continue(); if (!bCont) break; if (StepProgressor.Position < StepProgressor.MaxRange) StepProgressor.Step(); } pRow = ipCursor.NextRow(); } if (!bCont) { AbortEditing(TheWorkSpace); if (ipCursor != null) Marshal.ReleaseComObject(ipCursor); if (pRow != null) Marshal.ReleaseComObject(pRow); return false; } Marshal.ReleaseComObject(ipCursor); } return true; } catch (Exception ex) { if (ipCursor != null) Marshal.ReleaseComObject(ipCursor); if (pRow != null) Marshal.ReleaseComObject(pRow); MessageBox.Show(Convert.ToString(ex.Message)); return false; } }
public void Draw(IStepProgressor stepProgressor, IActiveView activeView, FileCache fileCache, ITrackCancel trackCancel, ISpatialReference layerSpatialReference, ref string currentLevel, ITileSource tileSource, IDisplay display) { _tileSource = tileSource; _trackCancel = trackCancel; _layerSpatialReference = layerSpatialReference; _currentLevel = currentLevel; _fileCache = fileCache; _tileProvider = (WebTileProvider)tileSource.Provider; var spatialReferences = new SpatialReferences(); _dataSpatialReference = spatialReferences.GetSpatialReference(tileSource.Schema.Srs); //var fetcher = new FileFetcher<Image>(osmTileSource, fileCache); _display = display; if (!activeView.Extent.IsEmpty) { _tiles = GetTiles(activeView); currentLevel = _currentLevel; Logger.Debug("Number of tiles to draw: " + _tiles.Count); if (_tiles.ToList().Count > 0) { stepProgressor.MinRange = 0; stepProgressor.MaxRange = _tiles.ToList().Count; stepProgressor.Show(); var downloadFinished = new ManualResetEvent(false); // this is a hack, otherwise we get error message... // "WaitAll for multiple handles on a STA thread is not supported. (mscorlib)" // so lets start a thread first... var t = new Thread(DownloadTiles); t.Start(downloadFinished); // wait till finished downloadFinished.WaitOne(); // 3. Now draw all tiles... if (layerSpatialReference != null && _dataSpatialReference != null) { _needReproject = (layerSpatialReference.FactoryCode != _dataSpatialReference.FactoryCode); } Logger.Debug("Need reproject tile: " + _needReproject.ToString()); foreach (var tile in _tiles) { stepProgressor.Step(); if (tile != null) { var name = _fileCache.GetFileName(tile.Index); if (!File.Exists(name)) { continue; } DrawRaster(name); } } stepProgressor.Hide(); } else { Logger.Debug("No tiles to retrieve or draw"); } Logger.Debug("End drawing tiles: " + _tiles.ToList().Count); } }
public void Execute(ESRI.ArcGIS.esriSystem.IArray paramvalues, ESRI.ArcGIS.esriSystem.ITrackCancel TrackCancel, ESRI.ArcGIS.Geoprocessing.IGPEnvironmentManager envMgr, ESRI.ArcGIS.Geodatabase.IGPMessages message) { try { IGPUtilities3 gpUtilities3 = new GPUtilitiesClass() as IGPUtilities3; if (TrackCancel == null) { TrackCancel = new CancelTrackerClass(); } // decode in the input layers IGPParameter in_SourceFeatureClassParameter = paramvalues.get_Element(in_sourceFeatureClassNumber) as IGPParameter; IGPValue in_SourceFeatureGPValue = gpUtilities3.UnpackGPValue(in_SourceFeatureClassParameter) as IGPValue; IFeatureClass sourceFeatureClass = null; IQueryFilter queryFilter = null; gpUtilities3.DecodeFeatureLayer((IGPValue)in_SourceFeatureGPValue, out sourceFeatureClass, out queryFilter); if (sourceFeatureClass == null) { message.AddError(120027, resourceManager.GetString("GPTools_OSMGPFeatureComparison_source_nullpointer")); return; } IGPParameter in_NumberOfIntersectionsFieldParameter = paramvalues.get_Element(in_sourceIntersectionFieldNumber) as IGPParameter; IGPValue in_NumberOfIntersectionsFieldGPValue = gpUtilities3.UnpackGPValue(in_NumberOfIntersectionsFieldParameter) as IGPValue; IGPParameter in_SourceRefIDFieldParameter = paramvalues.get_Element(in_sourceRefIDsFieldNumber) as IGPParameter; IGPValue in_SourceRefIDFieldGPValue = gpUtilities3.UnpackGPValue(in_SourceRefIDFieldParameter) as IGPValue; IGPParameter in_MatchFeatureClassParameter = paramvalues.get_Element(in_MatchFeatureClassNumber) as IGPParameter; IGPValue in_MatchFeatureGPValue = gpUtilities3.UnpackGPValue(in_MatchFeatureClassParameter) as IGPValue; IFeatureClass matchFeatureClass = null; IQueryFilter matchQueryFilter = null; gpUtilities3.DecodeFeatureLayer((IGPValue)in_MatchFeatureGPValue, out matchFeatureClass, out matchQueryFilter); if (matchFeatureClass == null) { message.AddError(120028, resourceManager.GetString("GPTools_OSMGPFeatureComparison_match_nullpointer")); return; } if (queryFilter != null) { if (((IGeoDataset)matchFeatureClass).SpatialReference != null) { queryFilter.set_OutputSpatialReference(sourceFeatureClass.ShapeFieldName, ((IGeoDataset)matchFeatureClass).SpatialReference); } } IWorkspace sourceWorkspace = ((IDataset)sourceFeatureClass).Workspace; IWorkspaceEdit sourceWorkspaceEdit = sourceWorkspace as IWorkspaceEdit; if (sourceWorkspace.Type == esriWorkspaceType.esriRemoteDatabaseWorkspace) { sourceWorkspaceEdit = sourceWorkspace as IWorkspaceEdit; sourceWorkspaceEdit.StartEditing(false); sourceWorkspaceEdit.StartEditOperation(); } // get an overall feature count as that determines the progress indicator int featureCount = ((ITable)sourceFeatureClass).RowCount(queryFilter); // set up the progress indicator IStepProgressor stepProgressor = TrackCancel as IStepProgressor; if (stepProgressor != null) { stepProgressor.MinRange = 0; stepProgressor.MaxRange = featureCount; stepProgressor.Position = 0; stepProgressor.Message = resourceManager.GetString("GPTools_OSMGPFeatureComparison_progressMessage"); stepProgressor.StepValue = 1; stepProgressor.Show(); } int numberOfIntersectionsFieldIndex = sourceFeatureClass.FindField(in_NumberOfIntersectionsFieldGPValue.GetAsText()); int sourceRefIDFieldIndex = sourceFeatureClass.FindField(in_SourceRefIDFieldGPValue.GetAsText()); ISpatialFilter matchFCSpatialFilter = new SpatialFilter(); matchFCSpatialFilter.GeometryField = matchFeatureClass.ShapeFieldName; matchFCSpatialFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects; matchFCSpatialFilter.WhereClause = matchQueryFilter.WhereClause; using (ComReleaser comReleaser = new ComReleaser()) { IFeatureCursor sourceFeatureCursor = sourceFeatureClass.Search(queryFilter, false); comReleaser.ManageLifetime(sourceFeatureCursor); IFeature sourceFeature = null; while ((sourceFeature = sourceFeatureCursor.NextFeature()) != null) { int numberOfIntersections = 0; string intersectedFeatures = String.Empty; IPolyline sourceLine = sourceFeature.Shape as IPolyline; matchFCSpatialFilter.Geometry = sourceLine; using (ComReleaser innerReleaser = new ComReleaser()) { IFeatureCursor matchFeatureCursor = matchFeatureClass.Search(matchFCSpatialFilter, false); innerReleaser.ManageLifetime(matchFeatureCursor); IFeature matchFeature = null; while ((matchFeature = matchFeatureCursor.NextFeature()) != null) { IPointCollection intersectionPointCollection = null; try { ITopologicalOperator topoOperator = sourceLine as ITopologicalOperator; if (topoOperator.IsSimple == false) { ((ITopologicalOperator2)topoOperator).IsKnownSimple_2 = false; topoOperator.Simplify(); } IPolyline matchPolyline = matchFeature.Shape as IPolyline; if (queryFilter != null) { matchPolyline.Project(sourceLine.SpatialReference); } if (((ITopologicalOperator)matchPolyline).IsSimple == false) { ((ITopologicalOperator2)matchPolyline).IsKnownSimple_2 = false; ((ITopologicalOperator)matchPolyline).Simplify(); } intersectionPointCollection = topoOperator.Intersect(matchPolyline, esriGeometryDimension.esriGeometry0Dimension) as IPointCollection; } catch (Exception ex) { message.AddWarning(ex.Message); continue; } if (intersectionPointCollection != null && intersectionPointCollection.PointCount > 0) { numberOfIntersections = numberOfIntersections + intersectionPointCollection.PointCount; if (String.IsNullOrEmpty(intersectedFeatures)) { intersectedFeatures = matchFeature.OID.ToString(); } else { intersectedFeatures = intersectedFeatures + "," + matchFeature.OID.ToString(); } } } if (numberOfIntersectionsFieldIndex > -1) { sourceFeature.set_Value(numberOfIntersectionsFieldIndex, numberOfIntersections); } if (sourceRefIDFieldIndex > -1) { if (intersectedFeatures.Length > sourceFeatureClass.Fields.get_Field(sourceRefIDFieldIndex).Length) { sourceFeature.set_Value(sourceRefIDFieldIndex, intersectedFeatures.Substring(0, sourceFeatureClass.Fields.get_Field(sourceRefIDFieldIndex).Length)); } else { sourceFeature.set_Value(sourceRefIDFieldIndex, intersectedFeatures); } } } try { sourceFeature.Store(); } catch (Exception ex) { message.AddWarning(ex.Message); } if (stepProgressor != null) { // update the progress UI stepProgressor.Step(); } // check for user cancellation if (TrackCancel.Continue() == false) { return; } } } if (sourceWorkspaceEdit != null) { sourceWorkspaceEdit.StopEditOperation(); sourceWorkspaceEdit.StopEditing(true); } if (stepProgressor != null) { stepProgressor.Hide(); } } catch (Exception ex) { message.AddAbort(ex.Message); } }
public bool UpdateInconsistentHistoryOnParcels(ITable pParcelsTable, int iParcelCount, ICadastralFabric pCadFabric, List<string> sOIDUpdateList, Dictionary<int, string> ParcelToHistory_DICT, IStepProgressor m_pStepProgressor, ITrackCancel m_pTrackCancel) { bool m_bShowProgressor = (iParcelCount > 10); bool bCont = true; ICadastralFabricSchemaEdit2 pSchemaEd=null; try { #region update line table history //Get the line table history fields //SystemStart, SystemEnd, LegalStart, LegalEnd, Historic int iParcelSysEndDate = pParcelsTable.FindField("systemenddate"); string sParcelSysEndDate = pParcelsTable.Fields.get_Field(iParcelSysEndDate).Name; int iParcelHistorical = pParcelsTable.FindField("historical"); string sParcelHistorical = pParcelsTable.Fields.get_Field(iParcelHistorical).Name; IQueryFilter pQueryFilter = new QueryFilterClass(); pQueryFilter.SubFields = pParcelsTable.OIDFieldName + "," + sParcelSysEndDate + "," + sParcelHistorical; pSchemaEd = (ICadastralFabricSchemaEdit2)pCadFabric; pSchemaEd.ReleaseReadOnlyFields(pParcelsTable, esriCadastralFabricTable.esriCFTParcels); //release safety-catch ICursor pCur = null; object obj = null; foreach (string sOIDSet in sOIDUpdateList) { if (sOIDSet.Trim() == "") continue; pQueryFilter.WhereClause = pParcelsTable.OIDFieldName + " IN (" + sOIDSet + ")"; pCur = pParcelsTable.Update(pQueryFilter, false); IRow pParcel = pCur.NextRow(); while (pParcel != null) { //Check if the cancel button was pressed. If so, stop process if (m_bShowProgressor) { bCont = m_pTrackCancel.Continue(); if (!bCont) break; } string sParcHistory = ""; if (ParcelToHistory_DICT.TryGetValue((int)pParcel.OID, out sParcHistory)) { string[] sHistoryItems = sParcHistory.Split(','); if (sHistoryItems[1].Trim() == "") obj = DBNull.Value; else obj = sHistoryItems[1]; pParcel.set_Value(iParcelSysEndDate, obj); if (sHistoryItems[4].Trim() == "") obj = DBNull.Value; else { bool x = (sHistoryItems[4].Trim().ToLower() == "true") ? true : false; if (x) obj = 1; else obj = 0; } pParcel.set_Value(iParcelHistorical, obj); pParcel.Store(); } Marshal.ReleaseComObject(pParcel); pParcel = pCur.NextRow(); if (m_bShowProgressor) { if (m_pStepProgressor.Position < m_pStepProgressor.MaxRange) m_pStepProgressor.Step(); } } Marshal.FinalReleaseComObject(pCur); } if (!bCont) return false; else return true; #endregion } catch (Exception ex) { MessageBox.Show(ex.Message); return false; } finally { pSchemaEd.ResetReadOnlyFields(esriCadastralFabricTable.esriCFTParcels);//set safety back on } }
public bool MergePlans(ITable ParcelTable, Dictionary <int, int> Lookup, string[] sInClause, bool Unversioned, IStepProgressor StepProgressor, ITrackCancel TrackCancel) { IDataset pDS = (IDataset)ParcelTable; IWorkspace pWS = pDS.Workspace; Int32 iPlanIDX = ParcelTable.Fields.FindField("PLANID"); ISQLSyntax pSQLSyntax = (ISQLSyntax)pWS; string sPref = pSQLSyntax.GetSpecialCharacter(esriSQLSpecialCharacters.esriSQL_DelimitedIdentifierPrefix); string sSuff = pSQLSyntax.GetSpecialCharacter(esriSQLSpecialCharacters.esriSQL_DelimitedIdentifierSuffix); ITableWrite pTableWr = (ITableWrite)ParcelTable; bool bCont = true; int zz = 0; int iCnt = sInClause.GetLength(0); try { foreach (string ss in sInClause) { if (ss == null) { continue; } IQueryFilter pQF = new QueryFilterClass(); string InClause = ss.Replace(",", " ").Trim(); InClause = InClause.Replace(" ", ","); string FieldName = "PLANID"; pQF.WhereClause = sPref + FieldName + sSuff + " IN (" + InClause + ")"; if (!ParcelTable.HasOID) { MessageBox.Show("Has no OID"); } int iRowCnt = ParcelTable.RowCount(pQF); ICursor pCur = null; if (Unversioned) { pCur = pTableWr.UpdateRows(pQF, false); } else { pCur = ParcelTable.Update(pQF, false); } //Check if the cancel button was pressed. If so, stop process if (TrackCancel != null) { bCont = TrackCancel.Continue(); } if (!bCont) { break; } //now for each of these parcels, use the dictionary to re-assign the plan id value IRow pParcel = pCur.NextRow(); if (StepProgressor != null) { StepProgressor.MinRange = StepProgressor.Position; //reset the progress bar position StepProgressor.MaxRange = StepProgressor.Position + iRowCnt; if (StepProgressor.Position < StepProgressor.MaxRange) { StepProgressor.Step(); } StepProgressor.Message = "Moving parcels to target plans...step " + Convert.ToString(++zz) + " of " + Convert.ToString(iCnt); } if (pQF != null) { Marshal.ReleaseComObject(pQF); } while (pParcel != null) { //Check if the cancel button was pressed. If so, stop process if (TrackCancel != null) { bCont = TrackCancel.Continue(); } if (!bCont) { break; } int MergePlanID = (int)pParcel.get_Value(iPlanIDX); int TargetPlanID = -1; if (Lookup.TryGetValue(MergePlanID, out TargetPlanID)) { pParcel.set_Value(iPlanIDX, TargetPlanID); pCur.UpdateRow(pParcel); } Marshal.ReleaseComObject(pParcel); pParcel = pCur.NextRow(); if (StepProgressor != null) { if (StepProgressor.Position < StepProgressor.MaxRange) { StepProgressor.Step(); } } } if (pCur != null) { Marshal.ReleaseComObject(pCur); } if (!bCont) { break; } } if (pTableWr != null) { Marshal.ReleaseComObject(pTableWr); } Marshal.ReleaseComObject(pWS); if (!bCont) { return(false); } return(true); } catch (COMException ex) { MessageBox.Show(ex.Message + ": " + Convert.ToString(ex.ErrorCode)); return(false); } }
public void FIDsetToLongArray(IFIDSet InFIDSet, ref ILongArray OutLongArray, IStepProgressor StepProgressor) { Int32 pfID = -1; InFIDSet.Reset(); double dMax = InFIDSet.Count(); int iMax = (int)(dMax); for (Int32 pCnt = 0; pCnt <= (InFIDSet.Count() - 1); pCnt++) { InFIDSet.Next(out pfID); OutLongArray.Add(pfID); if (StepProgressor != null) { if (StepProgressor.Position < StepProgressor.MaxRange) StepProgressor.Step(); } } return; }
public bool DeleteRowsByFIDSet(ITable inTable, IFIDSet pFIDSet, IStepProgressor StepProgressor, ITrackCancel TrackCancel) {//this routine uses the GetRows method, avoids the need to break up the InClause. IMouseCursor pMouseCursor = new MouseCursorClass(); pMouseCursor.SetCursor(2); try { pFIDSet.Reset(); int[] iID = { }; bool bCont = true; iID = RedimPreserveInt(ref iID, pFIDSet.Count()); for (int iCount = 0; iCount <= pFIDSet.Count() - 1; iCount++) { pFIDSet.Next(out iID[iCount]); } ICursor pCursor = inTable.GetRows(iID, false); IRow row = pCursor.NextRow(); if (StepProgressor != null) { StepProgressor.MinRange = StepProgressor.Position; //reset the progress bar position StepProgressor.MaxRange = StepProgressor.Position + pFIDSet.Count(); if (StepProgressor.Position < StepProgressor.MaxRange) { StepProgressor.Step(); } } while (row != null) { //Check if the cancel button was pressed. If so, stop process if (StepProgressor != null) { if (TrackCancel != null) { bCont = TrackCancel.Continue(); } if (!bCont) { break; } } row.Delete(); Marshal.ReleaseComObject(row); row = pCursor.NextRow(); if (StepProgressor != null) { if (StepProgressor.Position < StepProgressor.MaxRange) { StepProgressor.Step(); } } } Marshal.ReleaseComObject(pCursor); inTable = null; iID = null; if (!bCont) { return(false); } return(true); } catch (COMException ex) { StepProgressor = null; MessageBox.Show(ex.Message); return(false); } }
public bool ChangeDatesOnTable(ICursor pCursor, string FieldName, string sDate, bool Unversioned, IStepProgressor m_pStepProgressor, ITrackCancel m_pTrackCancel) { bool bWriteNull = (sDate.Trim() == ""); object dbNull = DBNull.Value; int FldIdx = pCursor.FindField(FieldName); int iSysEndDate = pCursor.FindField("systemenddate"); int iHistorical = pCursor.FindField("historical"); bool bIsSysEndDate = (FieldName.ToLower() == "systemenddate"); bool bIsHistorical = (FieldName.ToLower() == "historical"); bool bHasSysEndDateFld = (iSysEndDate > -1); bool bHasHistoricFld = (iHistorical > -1); bool bCont = true; bool m_bShowProgressor = (m_pStepProgressor != null); if (bWriteNull) { IField pfld = pCursor.Fields.get_Field(FldIdx); if (!pfld.IsNullable) return false; } DateTime localNow = DateTime.Now; IRow pRow = pCursor.NextRow(); while (pRow != null) { //Check if the cancel button was pressed. If so, stop process if (m_bShowProgressor) { bCont = m_pTrackCancel.Continue(); if (!bCont) break; } if (bWriteNull) { if (bIsHistorical) //if writing null to Historical field, use 0 instead pRow.set_Value(FldIdx, 0); else pRow.set_Value(FldIdx, dbNull); if (bIsHistorical && bHasSysEndDateFld) // if writing null to Historical field pRow.set_Value(iSysEndDate, dbNull); // then also Null system end date if (bIsSysEndDate && bHasHistoricFld) // if writing null to SystemEndDate field pRow.set_Value(iHistorical, 0); //then set the Historical flag to false = 0 } else { pRow.set_Value(FldIdx, sDate); if (bIsSysEndDate && bHasHistoricFld) // if writing date to SystemEndDate field pRow.set_Value(iHistorical, 1); //then set the Historical flag to true = 1 } if (Unversioned) pCursor.UpdateRow(pRow); else pRow.Store(); Marshal.ReleaseComObject(pRow); pRow = pCursor.NextRow(); if (m_bShowProgressor) { if (m_pStepProgressor.Position < m_pStepProgressor.MaxRange) m_pStepProgressor.Step(); } } Marshal.ReleaseComObject(pCursor); if (!bCont) return false; return true; }
public bool DeleteRowsUnversioned(IWorkspace TheWorkSpace, ITable inTable, IFIDSet pFIDSet, IStepProgressor StepProgressor, ITrackCancel TrackCancel) { IMouseCursor pMouseCursor = new MouseCursorClass(); pMouseCursor.SetCursor(2); if (StepProgressor != null) { StepProgressor.MinRange = StepProgressor.Position; //reset the progress bar position StepProgressor.MaxRange = StepProgressor.Position + pFIDSet.Count(); if (StepProgressor.Position < StepProgressor.MaxRange) { StepProgressor.Step(); } } IQueryFilter pQF = new QueryFilterClass(); ISQLSyntax pSQLSyntax = (ISQLSyntax)TheWorkSpace; string sPref = pSQLSyntax.GetSpecialCharacter(esriSQLSpecialCharacters.esriSQL_DelimitedIdentifierPrefix); string sSuff = pSQLSyntax.GetSpecialCharacter(esriSQLSpecialCharacters.esriSQL_DelimitedIdentifierSuffix); ICursor ipCursor = null; IRow pRow = null; //make sure that there are no more then 999 tokens for the in clause(ORA- query will otherwise error on an Oracle database) int iTokenLimit = 995; int iTokenSet = 0; //the index of the set of 995 tokens string sWhereClauseLHS = sPref + inTable.OIDFieldName + sSuff + " in ("; string[] ids = { sWhereClauseLHS }; try { ITableWrite pTableWr = (ITableWrite)inTable; pFIDSet.Reset(); bool bCont = true; Int32 iID; Int32 count = pFIDSet.Count(); int j = 0; //inner count for each set of IDs for (int k = 0; k < count; k++) { if (j > iTokenLimit) { //over the limit for this Token set, time to create a new set ids[iTokenSet] += ")"; //close the previous set RedimPreserveString(ref ids, 1); //make space in the string array for the next token set iTokenSet++; //increment the index ids[iTokenSet] = sWhereClauseLHS; //left-hand side of the where clause j = 0; //reset the inner count back to zero } pFIDSet.Next(out iID); if (j > 0) //write a comma if this is not the first ID { ids[iTokenSet] += ","; } ids[iTokenSet] += iID.ToString(); j++; //increment the inner count } ids[iTokenSet] += ")"; if (count > 0) { for (int k = 0; k <= iTokenSet; k++) { pQF.WhereClause = ids[k]; ipCursor = pTableWr.UpdateRows(pQF, false); pRow = ipCursor.NextRow(); while (pRow != null) { ipCursor.DeleteRow(); Marshal.ReleaseComObject(pRow); if (StepProgressor != null) { //Check if the cancel button was pressed. If so, stop process if (TrackCancel != null) { bCont = TrackCancel.Continue(); } if (!bCont) { break; } if (StepProgressor.Position < StepProgressor.MaxRange) { StepProgressor.Step(); } } pRow = ipCursor.NextRow(); } if (!bCont) { AbortEditing(TheWorkSpace); if (ipCursor != null) { Marshal.ReleaseComObject(ipCursor); } if (pRow != null) { Marshal.ReleaseComObject(pRow); } if (pQF != null) { Marshal.ReleaseComObject(pQF); } if (pMouseCursor != null) { Marshal.ReleaseComObject(pMouseCursor); } return(false); } Marshal.ReleaseComObject(ipCursor); } Marshal.ReleaseComObject(pQF); } Marshal.ReleaseComObject(pMouseCursor); return(true); } catch (COMException ex) { if (ipCursor != null) { Marshal.ReleaseComObject(ipCursor); } if (pRow != null) { Marshal.ReleaseComObject(pRow); } if (pQF != null) { Marshal.ReleaseComObject(pQF); } if (pMouseCursor != null) { Marshal.ReleaseComObject(pMouseCursor); } MessageBox.Show(Convert.ToString(ex.ErrorCode)); return(false); } }
private bool ExportLayer(Excel.Workbook ExcelWbk, IMxDocument MxDoc, IFeatureLayer FLayer, ref IProgressDialog2 progressDialog, ref IStepProgressor stepProgressor, ref ITrackCancel trackCancel) { IFeatureClass FC = null; ISubtypes Subtypes = null; ITableProperties TableProperties = null; IEnumTableProperties EnumTableProperties = null; ITableProperty3 TableProperty = null; ITableCharacteristics TableCharacteristics = null; IFeatureSelection FeatSel = null; IDisplayTable DisplayTable = null; ITable Table = null; ILayerFields LayerFields = null; ITableFields TableFields = null; ILayer LayerTest = null; ICursor Cursor = null; IFeatureCursor FCursor = null; IField CurField = null; IDomain Domain = null; ICodedValueDomain CodedValueDomain = null; IFeature Feat = null; List <IPoint> pGeo = null; object missing = null; object sheet = null; Excel.Worksheet ExcelSheet = null; Excel.Range ExcelRange = null; Microsoft.Office.Interop.Excel.Style style = null; try { int Col = 0; int Row = 0; int i; int j; bool UseDescriptions; int subtype; string SheetName; missing = System.Reflection.Missing.Value; sheet = ExcelWbk.Sheets[ExcelWbk.Sheets.Count]; //Add new Excel worksheet ExcelSheet = (Excel.Worksheet)ExcelWbk.Sheets.Add(missing, sheet, missing, missing); SheetName = FLayer.Name; if (SheetName.Length > 30) { SheetName = SheetName.Substring(0, 30); } ExcelSheet.Name = SheetName; //style = ExcelWbk.Styles.Add("Style1"); //style.NumberFormat = "@"; LayerTest = (ILayer)FLayer; //Get Subtype info FC = FLayer.FeatureClass; Subtypes = FC as ISubtypes; //Determine whether to use descriptions or codes for domains and subtypes UseDescriptions = true; TableProperties = MxDoc.TableProperties; EnumTableProperties = (IEnumTableProperties)TableProperties; EnumTableProperties.Reset(); TableProperty = (ITableProperty3)EnumTableProperties.Next(); while (TableProperty != null && TableProperty.Layer != null) //Fixed { if (TableProperty.Layer.Equals(LayerTest)) { TableCharacteristics = (ITableCharacteristics)TableProperty; UseDescriptions = TableCharacteristics.ShowCodedValueDomainDescriptions; } TableProperty = (ITableProperty3)EnumTableProperties.Next(); } FeatSel = (IFeatureSelection)FLayer; DisplayTable = (IDisplayTable)FLayer; Table = (ITable)DisplayTable.DisplayTable; //Get TableFields so later we can determine whether that field is visible LayerFields = (ILayerFields)FLayer; TableFields = (ITableFields)FLayer; //loop through each field and write column headings Row = 1; for (j = 0; j < TableFields.FieldCount; j++) { CurField = TableFields.get_Field(j); //skip blob and geometry fields if ((CurField.Type != esriFieldType.esriFieldTypeBlob) && (CurField.Type != esriFieldType.esriFieldTypeGeometry)) { Col += 1; //Write field alias name as Excel column header ExcelSheet.Cells[Row, Col] = TableFields.get_FieldInfo(j).Alias; if (CurField.Type == esriFieldType.esriFieldTypeString) { ExcelSheet.get_Range(ExcelSheet.Cells[1, Col], ExcelSheet.Cells[65535, Col]).EntireColumn.NumberFormat = "@"; } } } Col += 1; ExcelSheet.Cells[Row, Col] = "X_COORD"; Col += 1; ExcelSheet.Cells[Row, Col] = "Y_COORD"; Col += 1; ExcelSheet.Cells[Row, Col] = "Lat"; Col += 1; ExcelSheet.Cells[Row, Col] = "Long"; IField pFieldTest = FLayer.FeatureClass.Fields.get_Field(FLayer.FeatureClass.Fields.FindField(FLayer.FeatureClass.ShapeFieldName)); IGeometryDef pGeometryDefTest = null; pGeometryDefTest = pFieldTest.GeometryDef; bool bZAware = false; bool bMAware = false; //Determine if M or Z aware if (pGeometryDefTest.GeometryType == esriGeometryType.esriGeometryPoint) { bZAware = pGeometryDefTest.HasZ; bMAware = pGeometryDefTest.HasM; } if (bZAware) { Col += 1; ExcelSheet.Cells[Row, Col] = "Z_COORD"; } pFieldTest = null; pGeometryDefTest = null; //Get all selected records for this table (use IDisplayTable to get any joined data) DisplayTable.DisplaySelectionSet.Search(null, true, out Cursor); FCursor = (IFeatureCursor)Cursor; //subtype = Subtypes.DefaultSubtypeCode; //For each selected record Feat = FCursor.NextFeature(); // stepProgressor.Step(); // progressDialog.Description = A4LGSharedFunctions.Localizer.GetString("ExportAsset") + stepProgressor.Position + A4LGSharedFunctions.Localizer.GetString("Of") + MxDoc.FocusMap.SelectionCount.ToString() + "."; while (Feat != null) { Row += 1; if (Subtypes != null && Subtypes.HasSubtype == true && (Feat.get_Value(Subtypes.SubtypeFieldIndex) != null)) { subtype = Convert.ToInt32(Feat.get_Value(Subtypes.SubtypeFieldIndex)); } else { subtype = -99999; } //For each column Col = 0; for (j = 0; j < TableFields.FieldCount; j++) { CurField = TableFields.get_Field(j); //skip blob and geometry fields in data also if ((CurField.Type != esriFieldType.esriFieldTypeBlob) && (CurField.Type != esriFieldType.esriFieldTypeGeometry)) { Col += 1; ExcelSheet.Cells[Row, Col] = Feat.get_Value(j); if (UseDescriptions == true && subtype == -99999) { Domain = CurField.Domain; if (Domain != null) { if (Domain.Type == esriDomainType.esriDTCodedValue) { CodedValueDomain = (ICodedValueDomain)CurField.Domain; for (i = 0; i < CodedValueDomain.CodeCount; i++) { if ((CodedValueDomain.get_Value(i)).ToString() == (Feat.get_Value(j)).ToString()) { //System.Diagnostics.Debug.Print(CodedValueDomain.get_Name(0).ToString()); ExcelSheet.Cells[Row, Col] = CodedValueDomain.get_Name(i); i = CodedValueDomain.CodeCount; } } } } } else if (UseDescriptions == true && subtype != -99999) { if (Subtypes.SubtypeFieldIndex == j) { ExcelSheet.Cells[Row, Col] = Subtypes.get_SubtypeName(subtype); } else { Domain = Subtypes.get_Domain(subtype, CurField.Name); if ((Domain != null) && (Domain.Type == esriDomainType.esriDTCodedValue)) { CodedValueDomain = (ICodedValueDomain)Domain; for (i = 0; i < CodedValueDomain.CodeCount; i++) { if ((CodedValueDomain.get_Value(i)).ToString() == (Feat.get_Value(j)).ToString()) { //System.Diagnostics.Debug.Print(CodedValueDomain.get_Name(0).ToString()); ExcelSheet.Cells[Row, Col] = CodedValueDomain.get_Name(i); i = CodedValueDomain.CodeCount; } } } } } } } if (Feat.Shape != null) { if (Feat.Shape.IsEmpty == false) { pGeo = Globals.GetGeomCenter(Feat.Shape); if (pGeo != null) { if (pGeo.Count > 0) { if (pGeo[0].X != null) { ExcelSheet.Cells[Row, Col + 1] = pGeo[0].X; } if (pGeo[0].Y != null) { ExcelSheet.Cells[Row, Col + 2] = pGeo[0].Y; } if (pGeo[0] != null) { pGeo[0].Project(srWGS84); ExcelSheet.Cells[Row, Col + 3] = pGeo[0].Y; ExcelSheet.Cells[Row, Col + 4] = pGeo[0].X; } if (bZAware) { ExcelSheet.Cells[Row, Col + 5] = pGeo[0].Z; } } } } } stepProgressor.Step(); progressDialog.Description = A4LGSharedFunctions.Localizer.GetString("ExportAsset") + stepProgressor.Position + A4LGSharedFunctions.Localizer.GetString("Of") + MxDoc.FocusMap.SelectionCount.ToString() + "."; if (!trackCancel.Continue()) { return(false); } Feat = FCursor.NextFeature(); } //Hide Columns Col = 0; for (j = 0; j < TableFields.FieldCount; j++) { CurField = TableFields.get_Field(j); //skip blob and geometry fields in data also if ((CurField.Type != esriFieldType.esriFieldTypeBlob) && (CurField.Type != esriFieldType.esriFieldTypeGeometry)) { Col += 1; //Autofit ExcelRange = ExcelSheet.get_Range(ExcelSheet.Cells[1, Col], ExcelSheet.Cells[Row, Col]); ExcelRange.EntireColumn.AutoFit(); //Hide column if invisible in ArcMap if (TableFields.get_FieldInfo(j).Visible == false) { ExcelRange = ExcelSheet.get_Range(ExcelSheet.Cells[1, Col], ExcelSheet.Cells[Row, Col]); ExcelRange.EntireColumn.Hidden = true; } } } return(true); } catch { MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("ExportXLError")); return(true); } finally { FC = null; Subtypes = null; TableProperties = null; if (EnumTableProperties != null) { Marshal.ReleaseComObject(EnumTableProperties); } EnumTableProperties = null; TableProperty = null; TableCharacteristics = null; FeatSel = null; DisplayTable = null; Table = null; LayerFields = null; TableFields = null; LayerTest = null; if (Cursor != null) { Marshal.ReleaseComObject(Cursor); } Cursor = null; if (FCursor != null) { Marshal.ReleaseComObject(FCursor); } FCursor = null; CurField = null; Domain = null; CodedValueDomain = null; Feat = null; pGeo = null; missing = null; sheet = null; ExcelSheet = null; ExcelRange = null; style = null; } }
public bool InsertPlanRecords(ITable pPlansTable, ArrayList sPlanInserts, ArrayList UnitsAndFormat, ArrayList ExistingPlans, bool bUseNonVersionedEdit, IStepProgressor m_pStepProgressor, ITrackCancel TrackCancel, ref Dictionary <string, int> LookUp) { IRowBuffer pPlanRowBuff = null; ICursor pPlanCur = null; try { Dictionary <string, int> ExistingPlanLookup = new Dictionary <string, int>(); ArrayList ExistingPlans2 = new ArrayList(); foreach (string s in ExistingPlans) { string[] sItems = Regex.Split(s, "oid:"); string sPart1 = sItems[0].Substring(0, s.IndexOf("(")).Trim(); ExistingPlans2.Add(sPart1); string sPart2 = sItems[1].Substring(0, sItems[1].LastIndexOf(")")).Trim(); int jj = Convert.ToInt32(sPart2); if (!ExistingPlanLookup.ContainsKey(sPart1)) { ExistingPlanLookup.Add((string)sPart1, jj); } } ITableWrite pPlansTableWr = (ITableWrite)pPlansTable; bool bShowProgressor = (m_pStepProgressor != null && TrackCancel != null); if (bShowProgressor) { m_pStepProgressor.Message = "Inserting new Plans..."; } if (bUseNonVersionedEdit) { pPlanCur = pPlansTableWr.InsertRows(true); } else { pPlanCur = pPlansTable.Insert(true); } pPlanRowBuff = pPlansTable.CreateRowBuffer(); bool bCont = true; foreach (string s in sPlanInserts) { //Check if the cancel button was pressed. If so, stop process if (bShowProgressor) { bCont = TrackCancel.Continue(); if (!bCont) { break; } } if (ExistingPlanLookup.ContainsKey(s)) { int iVal = -1; if (ExistingPlanLookup.TryGetValue(s, out iVal)) { LookUp.Add(s, iVal); } } else { pPlanRowBuff.set_Value(pPlanRowBuff.Fields.FindField("Name"), s); pPlanRowBuff.set_Value(pPlanRowBuff.Fields.FindField("Description"), "Recovered missing plan."); DateTime mDate = DateTime.Now; var SystemDate = mDate.Date; pPlanRowBuff.set_Value(pPlanRowBuff.Fields.FindField("SystemStartDate"), SystemDate); int DistanceUnits = (int)UnitsAndFormat[2];//9001;//units should be set based on fabric projection pPlanRowBuff.set_Value(pPlanRowBuff.Fields.FindField("DistanceUnits"), DistanceUnits); int DirectionFormat = (int)UnitsAndFormat[3];//4; pPlanRowBuff.set_Value(pPlanRowBuff.Fields.FindField("DirectionFormat"), DirectionFormat); int AreaUnits = (int)UnitsAndFormat[1]; //2; pPlanRowBuff.set_Value(pPlanRowBuff.Fields.FindField("AreaUnits"), AreaUnits); int AngleUnits = (int)UnitsAndFormat[0]; //3; pPlanRowBuff.set_Value(pPlanRowBuff.Fields.FindField("AngleUnits"), AngleUnits); int LineParameters = (int)UnitsAndFormat[4];//4; pPlanRowBuff.set_Value(pPlanRowBuff.Fields.FindField("LineParameters"), LineParameters); int Accuracy = 4; pPlanRowBuff.set_Value(pPlanRowBuff.Fields.FindField("Accuracy"), Accuracy); object P_Oid = pPlanCur.InsertRow(pPlanRowBuff); LookUp.Add(s, (int)P_Oid); } if (bShowProgressor) { if (m_pStepProgressor.Position < m_pStepProgressor.MaxRange) { m_pStepProgressor.Step(); } } } if (pPlanRowBuff != null) { do { }while (Marshal.ReleaseComObject(pPlanRowBuff) > 0); } if (pPlanCur != null) { do { }while (Marshal.ReleaseComObject(pPlanCur) > 0); } return(bCont); //return the result from the Cancel tracker...true unless cancel was clicked. } catch (COMException ex) { MessageBox.Show(ex.Message); if (pPlanRowBuff != null) { do { }while (Marshal.ReleaseComObject(pPlanRowBuff) > 0); } if (pPlanCur != null) { do { }while (Marshal.ReleaseComObject(pPlanCur) > 0); } return(false); } }
// Execute: Execute the function given the array of the parameters public void Execute(IArray paramvalues, ITrackCancel trackcancel, IGPEnvironmentManager envMgr, IGPMessages message) { IFeatureClass outputFeatureClass = null; try { // get the input feature class IGPMultiValue inputFeatureClasses_Parameter = (IGPMultiValue)m_GPUtilities.UnpackGPValue(paramvalues.get_Element(0)); layer[] input_featureClasses = new layer[inputFeatureClasses_Parameter.Count]; for (int i = 0; i < inputFeatureClasses_Parameter.Count; i++) { IGPValue inputFeatureClass_Parameter = inputFeatureClasses_Parameter.get_Value(i); IFeatureClass inputFeatureClass; IQueryFilter inputQF; m_GPUtilities.DecodeFeatureLayer(inputFeatureClass_Parameter, out inputFeatureClass, out inputQF); input_featureClasses[i] = new layer() { featureclass = inputFeatureClass, qFilter = inputQF }; } if (input_featureClasses.Length == 0 || input_featureClasses.Any(w => w.featureclass == null)) { message.AddError(2, "Could not open one or more input dataset."); return; } //IFields additionalFields = new FieldsClass(); //additionalFields.AddField(FEATURE_SOURCE_FIELD_NAME, esriFieldType.esriFieldTypeString); //additionalFields.AddField(FEATURE_ID_FIELD_NAME, esriFieldType.esriFieldTypeInteger); //additionalFields.AddField( // input_featureClasses[0].featureclass.Fields.get_Field( // input_featureClasses[0].featureclass.Fields.FindField( // input_featureClasses[0].featureclass.ShapeFieldName))); // create the output feature class IGPValue outputFeatureClass_Parameter = m_GPUtilities.UnpackGPValue(paramvalues.get_Element(1)); outputFeatureClass = GPHelperFunctions.CreateFeatureClass(outputFeatureClass_Parameter, envMgr); if (outputFeatureClass == null) { message.AddError(2, "Could not create output dataset."); return; } IGPString curveTypeParameter = (IGPString)m_GPUtilities.UnpackGPValue(paramvalues.get_Element(2)); ArcConstructionMethods method; if (!Enum.TryParse <ArcConstructionMethods>(curveTypeParameter.Value, true, out method)) { message.AddError(2, string.Format("The value {0} is not expected. Expected values are: {1}.", curveTypeParameter.Value, string.Join(",", Enum.GetNames(typeof(ArcConstructionMethods))))); return; } IStepProgressor stepPro = (IStepProgressor)trackcancel; GPHelperFunctions.dropSpatialIndex(outputFeatureClass); BoostVoronoi bv = new BoostVoronoi(100); double minX = int.MaxValue, minY = int.MaxValue, maxX = int.MinValue, maxY = int.MinValue; List <site_key> point_sites = new List <site_key>(); List <site_key> segment_sites = new List <site_key>(); for (short i = 0; i < input_featureClasses.Length; i++) { layer l = input_featureClasses[i]; int featcount = l.featureclass.FeatureCount(l.qFilter); stepPro.MinRange = 0; stepPro.MaxRange = featcount; stepPro.StepValue = (1); stepPro.Message = "Reading features"; stepPro.Position = 0; stepPro.Show(); IFeatureCursor cursor = null; IFeature row = null; try { cursor = l.featureclass.Search(l.qFilter, false); while ((row = cursor.NextFeature()) != null) { stepPro.Step(); IPoint point = row.Shape as IPoint; if (point != null) { double X = point.X; double Y = point.Y; minX = Math.Min(minX, X); maxX = Math.Max(maxX, X); minY = Math.Min(minY, Y); maxY = Math.Max(maxY, Y); bv.AddPoint(point.X, point.Y); point_sites.Add(new site_key(i, row.OID)); } IMultipoint multipoint = row.Shape as IMultipoint; if (multipoint != null) { IPointCollection pointCollection = (IPointCollection)multipoint; IEnumVertex vertices = pointCollection.EnumVertices; IPoint vertex = null; int part, index; vertices.Next(out vertex, out part, out index); minX = Math.Min(minX, multipoint.Envelope.XMin); maxX = Math.Max(maxX, multipoint.Envelope.XMax); minY = Math.Min(minY, multipoint.Envelope.YMin); maxY = Math.Max(maxY, multipoint.Envelope.YMax); while (vertex != null) { bv.AddPoint(vertex.X, vertex.Y); point_sites.Add(new site_key(i, row.OID)); vertices.Next(out vertex, out part, out index); } } IPolyline polyline = row.Shape as IPolyline; if (polyline != null) { double fromX = polyline.FromPoint.X; double fromY = polyline.FromPoint.Y; double toX = polyline.ToPoint.X; double toY = polyline.ToPoint.Y; if (toX < fromX) { minX = Math.Min(minX, toX); maxX = Math.Max(maxX, fromX); } else { minX = Math.Min(minX, fromX); maxX = Math.Max(maxX, toX); } if (toY < fromY) { minY = Math.Min(minY, toY); maxY = Math.Max(maxY, fromY); } else { minY = Math.Min(minY, fromY); maxY = Math.Max(maxY, toY); } bv.AddSegment( polyline.FromPoint.X, polyline.FromPoint.Y, polyline.ToPoint.X, polyline.ToPoint.Y ); segment_sites.Add(new site_key(i, row.OID)); } Marshal.ReleaseComObject(row); } } finally { if (row != null) { Marshal.ReleaseComObject(row); } if (cursor != null) { Marshal.ReleaseComObject(cursor); } stepPro.Hide(); } } message.AddMessage(String.Format("{0}, {1} -> {2}, {3}", minX, minY, maxX, maxY)); int width = Math.Max((int)((maxX - minX) * 0.1), 1); int height = Math.Max((int)((maxY - minY) * 0.1), 1); maxX = maxX + width; minX = minX - width; maxY = maxY + height; minY = minY - height; message.AddMessage(String.Format("{0}, {1} -> {2}, {3}", minX, minY, maxX, maxY)); bv.AddSegment(minX, minY, maxX, minY); segment_sites.Add(new site_key(-1, -1)); bv.AddSegment(maxX, minY, maxX, maxY); segment_sites.Add(new site_key(-1, -1)); bv.AddSegment(maxX, maxY, minX, maxY); segment_sites.Add(new site_key(-1, -1)); bv.AddSegment(minX, maxY, minX, minY); segment_sites.Add(new site_key(-1, -1)); stepPro.Message = "Solve Voronoi"; stepPro.MaxRange = 0; stepPro.MaxRange = 0; stepPro.Show(); bv.Construct(); stepPro.Hide(); int featureSourceIndx = outputFeatureClass.Fields.FindField(FEATURE_SOURCE_FIELD_NAME); int featureIDIndx = outputFeatureClass.Fields.FindField(FEATURE_ID_FIELD_NAME); IFeatureCursor inserts = null; IFeatureBuffer buffer = null; try { object missing = Type.Missing; ISpatialReference spatialReference = ((IGeoDataset)outputFeatureClass).SpatialReference; inserts = outputFeatureClass.Insert(false); buffer = outputFeatureClass.CreateFeatureBuffer(); List <Cell> cells = bv.Cells; message.AddMessage(string.Format("{0} cells calculated", cells.Count)); List <Edge> edges = bv.Edges; message.AddMessage(string.Format("{0} edges calculated", edges.Count)); List <Vertex> vertices = bv.Vertices; message.AddMessage(string.Format("{0} vertexes calculated", vertices.Count)); stepPro.Message = "Write cells"; stepPro.MaxRange = 0; stepPro.MaxRange = cells.Count; stepPro.Show(); for (int cellIndex = 0; cellIndex < cells.Count; cellIndex++) { try { if (cellIndex % 5000 == 0) { message.AddMessage(String.Format("{0}. {1} cells processed.", DateTime.Now, cellIndex)); } Cell cell = cells[cellIndex]; int currentSite = cell.Site; IGeometryCollection geometryCollection = new GeometryBagClass() { SpatialReference = spatialReference }; //ignores any sliver cells if (cell.IsOpen || cell.EdgesIndex.Count < 3) { continue; } ISegmentCollection segmentCollection = createSegments(cell, bv, method, spatialReference); if (((IArea)segmentCollection).Area <= 0) { message.AddMessage("A invalid geometry has been detected, try reversing the orientation."); ISegmentCollection reversed_segmentCollection = new PolygonClass() { SpatialReference = spatialReference }; for (int i = segmentCollection.SegmentCount - 1; i >= 0; i--) { ISegment segment = (ISegment)segmentCollection.get_Segment(i); segment.ReverseOrientation(); reversed_segmentCollection.AddSegment(segment); } segmentCollection = reversed_segmentCollection; } ((IPolygon)segmentCollection).SpatialReference = spatialReference; if (((IArea)segmentCollection).Area <= 0) { message.AddWarning("An empty shell has been created"); for (int i = 0; i < segmentCollection.SegmentCount; i++) { ISegment segment = (ISegment)segmentCollection.get_Segment(i); message.AddMessage(String.Format("From {0}, {1} To {2},{3}", segment.FromPoint.X, segment.FromPoint.Y, segment.ToPoint.X, segment.ToPoint.Y)); } } //set attributes site_key sk = (currentSite >= point_sites.Count) ? segment_sites[currentSite - point_sites.Count] : point_sites[currentSite]; if (!sk.isEmpty) { buffer.set_Value(featureSourceIndx, input_featureClasses[sk.featureClassIndex].featureclass.AliasName); buffer.set_Value(featureIDIndx, sk.objectID); } else { buffer.set_Value(featureSourceIndx, DBNull.Value); buffer.set_Value(featureIDIndx, DBNull.Value); } IPolygon voronoiPolygon = (IPolygon)segmentCollection; buffer.Shape = (IPolygon)voronoiPolygon; inserts.InsertFeature(buffer); } catch (Exception e) { message.AddWarning("Failed to create a cell"); } } } finally { if (buffer != null) { Marshal.ReleaseComObject(buffer); } if (inserts != null) { Marshal.ReleaseComObject(inserts); } } GPHelperFunctions.createSpatialIndex(outputFeatureClass); } catch (Exception exx) { message.AddError(2, exx.Message); message.AddMessage(exx.ToString()); } finally { if (outputFeatureClass != null) { Marshal.ReleaseComObject(outputFeatureClass); } ((IProgressor)trackcancel).Hide(); } }
public bool UpdateParcelRecordsByPlanGroup(ITable pParcelsTable, ArrayList sParcelUpdates, Dictionary <string, int> TheNewPlanIDs, Dictionary <int, int> ParcelLookup, bool bUseNonVersionedEdit, IStepProgressor m_pStepProgressor, ITrackCancel TrackCancel) { bool bShowProgressor = (m_pStepProgressor != null && TrackCancel != null); if (bShowProgressor) { m_pStepProgressor.Message = "Updating Parcels..."; } Int32 iPlanID = pParcelsTable.Fields.FindField("PLANID"); IDataset pDS = (IDataset)pParcelsTable; ISQLSyntax pSQLSyntax = (ISQLSyntax)pDS.Workspace; string sPref = pSQLSyntax.GetSpecialCharacter(esriSQLSpecialCharacters.esriSQL_DelimitedIdentifierPrefix); string sSuff = pSQLSyntax.GetSpecialCharacter(esriSQLSpecialCharacters.esriSQL_DelimitedIdentifierSuffix); IQueryFilter pQF = new QueryFilterClass(); string FieldName = pParcelsTable.OIDFieldName; bool bCont = true; try { foreach (string InClause in sParcelUpdates) { if (InClause.Trim() == "") { continue; } pQF.WhereClause = sPref + FieldName + sSuff + " IN (" + InClause + ")"; ITableWrite2 pParcelsTableWr = (ITableWrite2)pParcelsTable; ICursor pUpdateCur = null; if (bUseNonVersionedEdit) { pUpdateCur = pParcelsTableWr.UpdateRows(pQF, false); } else { pUpdateCur = pParcelsTable.Update(pQF, false); } IRow pRow = pUpdateCur.NextRow(); //now update the parcel planid int iOldPlanID = -1; int iNewPlanID = -1; while (pRow != null) { int iParcelID = pRow.OID; if (!ParcelLookup.TryGetValue(iParcelID, out iOldPlanID)) { continue; } string sNewPlanName = "[" + Convert.ToString(iOldPlanID) + "]"; if (!TheNewPlanIDs.TryGetValue(sNewPlanName, out iNewPlanID)) { continue; } pRow.set_Value(iPlanID, iNewPlanID); pUpdateCur.UpdateRow(pRow); if (bShowProgressor) { if (m_pStepProgressor.Position < m_pStepProgressor.MaxRange) { m_pStepProgressor.Step(); } } Marshal.ReleaseComObject(pRow); //after garbage collection, and before gettng the next row, //check if the cancel button was pressed. If so, stop process if (bShowProgressor) { bCont = TrackCancel.Continue(); } if (!bCont) { break; } pRow = pUpdateCur.NextRow(); } if (pUpdateCur != null) { Marshal.ReleaseComObject(pUpdateCur); } if (!bCont) { break; } } } catch (COMException Ex) { MessageBox.Show("Problem encountered:" + Ex.ErrorCode.ToString() + ":" + Ex.Message, "Update Parcel Records"); if (pQF != null) { Marshal.ReleaseComObject(pQF); } return(false); } if (pQF != null) { Marshal.ReleaseComObject(pQF); } return(bCont); //return the result from the Cancel tracker...true unless cancel was clicked. }
private void btnIncorporar_Click_1(object sender, EventArgs e) { //IncorporarLecturas2(); //return; statusLblProcesando.Text = "Incorporando Lecturas..."; IProgressDialogFactory pProDiaFac = new ProgressDialogFactoryClass(); IStepProgressor pStepPro = pProDiaFac.Create(null, 0); pStepPro.MinRange = 1; pStepPro.MaxRange = 5; pStepPro.StepValue = 1; IProgressDialog2 pProDia = (IProgressDialog2)pStepPro; pProDia.Animation = esriProgressAnimationTypes.esriProgressGlobe; pProDia.Title = "Incorporando Lecturas"; pProDia.ShowDialog(); pStepPro.Step(); pStepPro.Message = "Incorporando temperatura..."; SIGPIParametros parametros = _parametros; PrepararInformacion preparar = new PrepararInformacion(); string mesTemperatura, mesPrecipitacion; string sRuta = parametros.RutaSIGPI + "\\" + parametros.Lecturas + "\\" + LECTURAS_TEMPERATURA; Microsoft.Office.Interop.Excel.Application _excelApp = null; Workbook workBook = null; Worksheet sheet = null; string sColumnaDia; DateTime dFechaIncorporacionActual; int iDay; bool bIncorporarTemperatura; try { _excelApp = new Microsoft.Office.Interop.Excel.Application(); workBook = _excelApp.Workbooks.Open(sRuta, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing); sheet = (Worksheet)workBook.Worksheets.get_Item(1); //.Sheets["max"]; mesTemperatura = ""; try { mesTemperatura = preparar.VerificarFechasLecturas(sheet, SIGPI_CELDA_MES_TEMPERATURA); } catch (Exception ex) { MessageBox.Show(ex.Message); pProDia.HideDialog(); _excelApp.Workbooks.Close(); return; } DateTime dFechaAIncorporar = dtPickerFechaAIncorporar.Value; iDay = dFechaAIncorporar.Day; if (dFechaAIncorporar.Month != ConversionMes.MesNumero(mesTemperatura.ToUpper())) { if (dFechaAIncorporar.Month != ConversionMes.MesNumero(mesTemperatura.ToUpper()) + 1) { MessageBox.Show("La fecha seleccionada no se encuentra en el archivo de lecturas. Periodo correspondiente al mes de: " + mesTemperatura); pProDia.HideDialog(); _excelApp.Workbooks.Close(); return; } } int iTotalEstaciones = preparar.TotalEstaciones(sheet, SIGPI_COLUMNA_CODIGO_TEMPERATURA); sColumnaDia = preparar.ColumnaLecturaDia(sheet, SIGPI_COLUMNA_INICIO_DIA_TEMPERATURA, iDay.ToString(), SIGPI_FILA_DIA_TEMPERATURA); if (sColumnaDia == "-99") { MessageBox.Show("No se encontro el dia de lectura en el archivo de Excel de temperaturas. Dia: " + iDay.ToString()); pProDia.HideDialog(); _excelApp.Workbooks.Close(); return; } List <Lectura> listaTemperatura = preparar.ObtenerLecturas(sheet, _sigpiDao, SIGPI_COLUMNA_CODIGO_TEMPERATURA, sColumnaDia, SIGPI_TEMPERATURA_MIN_VAL, SIGPI_TEMPERATURA_MAX_VAL); pStepPro.Step(); dFechaIncorporacionActual = dtPickerFechaAIncorporar.Value; //_sigpi.FechaIncorporacion.AddDays(1); //MessageBox.Show("lecturas a incorporar Temp. : " + listaTemperatura.Count.ToString()); bIncorporarTemperatura = preparar.IncorporarLecturas(_sigpiDao, SIGPI_TABLA_LECTURAS_TEMPERATURA, dFechaIncorporacionActual, listaTemperatura); pStepPro.Message = "Incorporando Precipitacion..."; pStepPro.Step(); pStepPro.StepValue = 3; } finally { _excelApp.Workbooks.Close(); GC.Collect(); GC.WaitForPendingFinalizers(); System.Runtime.InteropServices.Marshal.FinalReleaseComObject(workBook); System.Runtime.InteropServices.Marshal.FinalReleaseComObject(_excelApp); } sRuta = parametros.RutaSIGPI + "\\" + parametros.Lecturas + "\\" + LECTURAS_PRECIPITACION; try { _excelApp = new Microsoft.Office.Interop.Excel.Application(); workBook = _excelApp.Workbooks.Open(sRuta, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing); sheet = (Worksheet)workBook.Worksheets.get_Item(1); //Sheets["precipitacion"]; try { mesPrecipitacion = preparar.VerificarFechasLecturas(sheet, SIGPI_CELDA_MES_PRECIPITACION); } catch (Exception ex) { MessageBox.Show(ex.Message); pProDia.HideDialog(); _excelApp.Workbooks.Close(); return; } sColumnaDia = preparar.ColumnaLecturaDia(sheet, SIGPI_COLUMNA_INICIO_DIA_PRECIPITACION, iDay.ToString(), SIGPI_FILA_DIA_PRECIPITACION); if (sColumnaDia == "-99") { MessageBox.Show("No se encontro el dia de lectura en el archivo de Excel de precipitacion. Dia: " + iDay.ToString()); pProDia.HideDialog(); _excelApp.Workbooks.Close(); return; } List <Lectura> listaPrecipitacion = preparar.ObtenerLecturas(sheet, _sigpiDao, SIGPI_COLUMNA_CODIGO_PRECIPITACION, sColumnaDia, SIGPI_PRECIPITACION_MIN_VAL, SIGPI_PRECIPITACION_MAX_VAL); //MessageBox.Show("lecturas a incorporar Prec. : " + listaPrecipitacion.Count.ToString()); bool bIncorporarPrecip = preparar.IncorporarLecturas(_sigpiDao, SIGPI_TABLA_LECTURAS_PRECIPITACION, dFechaIncorporacionActual, listaPrecipitacion); pStepPro.StepValue = 4; pProDia.HideDialog(); if (bIncorporarTemperatura && bIncorporarPrecip) { txtUltimoDiaIncorporacion.Text = dtPickerFechaAIncorporar.Value.ToLongDateString(); preparar.ActualizarFechaIncorporacion(dtPickerFechaAIncorporar.Value, _sigpiDao); _sigpi.FechaIncorporacion = dtPickerFechaAIncorporar.Value; dtPickerFechaAProcesar.Value = dtPickerFechaAIncorporar.Value; dtPickerFechaAIncorporar.Value = dtPickerFechaAIncorporar.Value.AddDays(1); MessageBox.Show("Incorporacion de lecturas terminada!"); } } finally { _excelApp.Workbooks.Close(); } }
public void GeneratePoints2(string sLineLayer, string sDepthPointsLayer, double dblInterval, string strDepthField) { try { IMxDocument pmxdoc = ArcMap.Document as IMxDocument; IMap pmap = pmxdoc.FocusMap; IFeatureLayer pDepthSoundings = FindLayer(pmap, sDepthPointsLayer) as IFeatureLayer; IFeatureLayer pLineLayer = FindLayer(pmap, sLineLayer) as IFeatureLayer; IFeatureLayer pOutpoints = new FeatureLayerClass(); pOutpoints.FeatureClass = MakePointFC(); pOutpoints.Name = "Output Points"; ArcMap.Document.ActiveView.FocusMap.AddLayer(pOutpoints); IProgressDialog2 pProgressDialog = ShowProgressIndicator("Calculating...", pLineLayer.FeatureClass.FeatureCount(null), 1); pProgressDialog.ShowDialog(); //Set up the Outpoints cursor IFeatureCursor pFCurOutPoints = pOutpoints.Search(null, false); pFCurOutPoints = pOutpoints.FeatureClass.Insert(true); //Set up the LineLayer Cursor IFeatureCursor pFCur = pLineLayer.Search(null, false); IFeature pLineFeature = pFCur.NextFeature(); IFeatureBuffer pFBuffer = pOutpoints.FeatureClass.CreateFeatureBuffer(); ICurve pCurve; IPoint ppoint; int iLineProgressCount = 1; double dblDistance = 0; double dblTotalDistanceCalculated = 0; double iNumIntervals = 0; double dblElevationDiff = 0; double dblElevationInterval = 0; double dblElevation = 0; double dlbStartElevation = 0; double dblEndElevation = 0; pProgressDialog.Description = "Generating points for Line: " + iLineProgressCount + " of " + pLineLayer.FeatureClass.FeatureCount(null).ToString(); while (pLineFeature != null) { int iStartVertex = 0; int iEndVertex = 1; //Get the vertices of the line feature IPointCollection4 pPointColl = pLineFeature.Shape as IPointCollection4; //loop thru the vertices for (int i = 0; i <= pPointColl.PointCount - 1; i++) { IPoint pStartPoint = pPointColl.get_Point(iStartVertex); IPoint pEndPoint = pPointColl.get_Point(iEndVertex); //Make an intermediate line segment between each set of vertices IPath pPath = MakePath(pStartPoint, pEndPoint); //Get the starting elevation from the depth point layer dlbStartElevation = GetPointElevation(pDepthSoundings, pLineLayer, pStartPoint, strDepthField); dblElevation = dlbStartElevation; IPointCollection pPointForPath = null; //Get the ending elevation from the next vertex pEndPoint = pPointColl.get_Point(iEndVertex); dblEndElevation = GetPointElevation(pDepthSoundings, pLineLayer, pEndPoint, strDepthField); //If the returned elevation is 0, then there is no coincident depth point, move to the next vertex for your endpoint if (dblEndElevation == 0) { //IPointCollection reshapePath = new PathClass(); object missing = Type.Missing; pPointForPath = new PathClass(); pPointForPath.AddPoint(pStartPoint, ref missing, ref missing); while (dblEndElevation == 0) { pEndPoint = pPointColl.get_Point(iEndVertex); dblEndElevation = GetPointElevation(pDepthSoundings, pLineLayer, pEndPoint, strDepthField); pPointForPath.AddPoint(pEndPoint, ref missing, ref missing); //pLineSegment.Reshape(reshapePath as IPath); if (dblEndElevation != 0) { break; } iEndVertex++; } } if (pPointForPath != null) { pPath = pPointForPath as IPath; } //number of line segments based on the user's interval iNumIntervals = Convert.ToDouble(pPath.Length / dblInterval); dblElevationDiff = dblEndElevation - dlbStartElevation; //The calculated elevation interval to step up each time dblElevationInterval = dblElevationDiff / iNumIntervals; ppoint = new PointClass(); while (dblTotalDistanceCalculated <= pPath.Length) { pFBuffer.set_Value(pFBuffer.Fields.FindField("LineOID"), pLineFeature.OID); pFBuffer.set_Value(pFBuffer.Fields.FindField("Distance"), Math.Round(dblDistance, 4)); pFBuffer.set_Value(pFBuffer.Fields.FindField("Elevation"), Math.Round(dblElevation, 4)); //this code set the point on the line at a distance pPath.QueryPoint(0, dblDistance, false, ppoint); pFBuffer.set_Value(pFBuffer.Fields.FindField("X"), ppoint.X); pFBuffer.set_Value(pFBuffer.Fields.FindField("Y"), ppoint.Y); //reCalc the new distance and elevation values for the next iteration dblDistance = dblDistance + dblInterval; dblTotalDistanceCalculated = dblTotalDistanceCalculated + dblInterval; //Insert the feature into the featureclass pFBuffer.Shape = ppoint; if (!IsPointCoincident(ppoint, pOutpoints)) { pFCurOutPoints.InsertFeature(pFBuffer); } if (dblTotalDistanceCalculated >= pPath.Length) { break; } dblElevation = dblElevation + dblElevationInterval; } //start the next line segment at the end of last one iStartVertex = iEndVertex; //look to the next vertex for the new ending point iEndVertex++; if (iEndVertex == pPointColl.PointCount) { ////if its the last vertex of the last line, add a point //pFBuffer.Shape = pPath.ToPoint; //pFBuffer.set_Value(pFBuffer.Fields.FindField("LineOID"), pLineFeature.OID); //pFBuffer.set_Value(pFBuffer.Fields.FindField("Distance"), Math.Round(dblDistance, 4)); //pFBuffer.set_Value(pFBuffer.Fields.FindField("Elevation"), Math.Round(dblElevation, 4)); //pFBuffer.set_Value(pFBuffer.Fields.FindField("X"), pPath.ToPoint.X); //pFBuffer.set_Value(pFBuffer.Fields.FindField("Y"), pPath.ToPoint.Y); //pFCurOutPoints.InsertFeature(pFBuffer); //Reset the distance values back to 0 for the next feature dblDistance = 0; dblTotalDistanceCalculated = 0; pStepProgressor.Step(); iLineProgressCount++; pPath.SetEmpty(); break; } //Reset the distance values back to 0 for the next feature dblDistance = 0; dblTotalDistanceCalculated = 0; //pLineFeature = pFCur.NextFeature(); pStepProgressor.Step(); //pProgressDialog.Description = "Generating points for Line: " + iLineProgressCount + " of " + pLineLayer.FeatureClass.FeatureCount(null).ToString(); iLineProgressCount++; pPath.SetEmpty(); } pLineFeature = pFCur.NextFeature(); } //cleanup pFCurOutPoints.Flush(); pFCur.Flush(); pProgressDialog.HideDialog(); pmxdoc.ActiveView.Refresh(); } catch (Exception ex) { } }
protected override void OnClick() { #region Prepare for editing IMouseCursor pMouseCursor = new MouseCursorClass(); pMouseCursor.SetCursor(2); UID pUID = new UIDClass(); pUID.Value = "{114D685F-99B7-4B63-B09F-6D1A41A4DDC1}"; ICadastralExtensionManager2 pCadExtMan = (ICadastralExtensionManager2)ArcMap.Application.FindExtensionByCLSID(pUID); ICadastralEditor pCadEd = (ICadastralEditor)ArcMap.Application.FindExtensionByCLSID(pUID); //check if there is a Manual Mode "modify" job active =========== ICadastralPacketManager pCadPacMan = (ICadastralPacketManager)pCadExtMan; if (pCadPacMan.PacketOpen) { MessageBox.Show("This command cannot be used when there is an open job.\r\nPlease finish or discard the open job, and try again.", "Delete Selected Parcels"); return; } IEditor pEd = (IEditor)ArcMap.Application.FindExtensionByName("esri object editor"); IActiveView pActiveView = ArcMap.Document.ActiveView; IMap pMap = pActiveView.FocusMap; ICadastralFabric pCadFabric = null; clsFabricUtils FabricUTILS = new clsFabricUtils(); IProgressDialog2 pProgressorDialog = null; //if we're in an edit session then grab the target fabric if (pEd.EditState == esriEditState.esriStateEditing) { pCadFabric = pCadEd.CadastralFabric; } else { MessageBox.Show("Please start editing and try again."); return; } if (pCadFabric == null) {//find the first fabric in the map if (!FabricUTILS.GetFabricFromMap(pMap, out pCadFabric)) { MessageBox.Show ("No Parcel Fabric found in the map.\r\nPlease add a single fabric to the map, and try again."); return; } } IArray CFParcelLayers = new ArrayClass(); if (!(FabricUTILS.GetFabricSubLayersFromFabric(pMap, pCadFabric, out CFPointLayer, out CFLineLayer, out CFParcelLayers, out CFControlLayer, out CFLinePointLayer))) { return; //no fabric sublayers available for the targeted fabric } //bool bIsFileBasedGDB = false; bool bIsUnVersioned = false; bool bUseNonVersionedDelete = false; //ICadastralFabricLayer pCFLayer = null; IWorkspace pWS = null; ITable pParcelsTable = null; ITable pLinesTable = null; ITable pLinePtsTable = null; ITable pPointsTable = null; pParcelsTable = (ITable)pCadFabric.get_CadastralTable(esriCadastralFabricTable.esriCFTParcels); pLinesTable = (ITable)pCadFabric.get_CadastralTable(esriCadastralFabricTable.esriCFTLines); pLinePtsTable = (ITable)pCadFabric.get_CadastralTable(esriCadastralFabricTable.esriCFTLinePoints); pPointsTable = (ITable)pCadFabric.get_CadastralTable(esriCadastralFabricTable.esriCFTPoints); #endregion dlgChangeParcelHistory pChangeHistoryDialog = new dlgChangeParcelHistory(); // ******** Display the dialog ********* DialogResult pDialogResult = pChangeHistoryDialog.ShowDialog(); if (pDialogResult != DialogResult.OK) { return; } //************************ #region Get Selection //Get the selection of parcels IFeatureLayer pFL = (IFeatureLayer)CFParcelLayers.get_Element(0); IDataset pDS = (IDataset)pFL.FeatureClass; pWS = pDS.Workspace; ICadastralSelection pCadaSel = (ICadastralSelection)pCadEd; IEnumGSParcels pEnumGSParcels = pCadaSel.SelectedParcels;// need to get the parcels before trying to get the parcel count: BUG workaround IFeatureSelection pFeatSel = (IFeatureSelection)pFL; ISelectionSet2 pSelSet = (ISelectionSet2)pFeatSel.SelectionSet; ICadastralFabricSchemaEdit2 pSchemaEd = null; try { int iParcelCount = pCadaSel.SelectedParcelCount; bool m_bShowProgressor = (iParcelCount > 10); if (m_bShowProgressor) { m_pProgressorDialogFact = new ProgressDialogFactoryClass(); m_pTrackCancel = new CancelTrackerClass(); m_pStepProgressor = m_pProgressorDialogFact.Create(m_pTrackCancel, ArcMap.Application.hWnd); pProgressorDialog = (IProgressDialog2)m_pStepProgressor; m_pStepProgressor.MinRange = 1; m_pStepProgressor.MaxRange = iParcelCount * 14; //(estimate 7 lines per parcel, 4 pts per parcel) m_pStepProgressor.StepValue = 1; pProgressorDialog.Animation = ESRI.ArcGIS.Framework.esriProgressAnimationTypes.esriProgressSpiral; } if (m_bShowProgressor) { pProgressorDialog.ShowDialog(); m_pStepProgressor.Message = "Initializing..."; } #endregion #region Get Parcel History Fields //Get the parcel table history fields //SystemStart, SystemEnd, LegalStart, LegalEnd, Historic int iParcSysStartDate = pParcelsTable.FindField("systemstartdate"); int iParcSysEndDate = pParcelsTable.FindField("systemenddate"); int iParcLegalStartDate = pParcelsTable.FindField("legalstartdate"); int iParcLegalEndDate = pParcelsTable.FindField("legalenddate"); int iParcHistorical = pParcelsTable.FindField("historical"); //Add the OIDs of all the selected parcels into a new feature IDSet //Need a Lookup for the History information Dictionary <int, string> ParcelToHistory_DICT = new Dictionary <int, string>(); List <string> sOIDList = new List <string>(); sOIDList.Add(""); int tokenLimit = 995; bool bCont = true; int j = 0; int iCounter = 0; m_pFIDSetParcels = new FIDSetClass(); pEnumGSParcels.Reset(); IGSParcel pGSParcel = pEnumGSParcels.Next(); while (pGSParcel != null) { //Check if the cancel button was pressed. If so, stop process if (m_bShowProgressor) { bCont = m_pTrackCancel.Continue(); if (!bCont) { break; } } m_pFIDSetParcels.Add(pGSParcel.DatabaseId); if (iCounter <= tokenLimit) { if (sOIDList[j].Trim() == "") { sOIDList[j] = Convert.ToString(pGSParcel.DatabaseId); } else { sOIDList[j] = sOIDList[j] + "," + Convert.ToString(pGSParcel.DatabaseId); } iCounter++; } else {//maximum tokens reached iCounter = 0; //set up the next OIDList j++; sOIDList.Add(""); sOIDList[j] = Convert.ToString(pGSParcel.DatabaseId); } //add to the lookup IGSAttributes pGSParcelAttributes = (IGSAttributes)pGSParcel; object pObj = pGSParcelAttributes.GetProperty("systemstartdate"); string sSystemStartParcel = ""; if (pObj != null) { sSystemStartParcel = pObj.ToString(); } pObj = pGSParcelAttributes.GetProperty("systemenddate"); string sSystemEndParcel = ""; if (pObj != null) { sSystemEndParcel = pObj.ToString(); } string sLegalStartParcel = pGSParcel.LegalStartDate.ToString(); string sLegalEndParcel = pGSParcel.LegalEndDate.ToString(); string sHistorical = pGSParcel.Historical.ToString(); ParcelToHistory_DICT.Add(pGSParcel.DatabaseId, sSystemStartParcel + "," + sSystemEndParcel + "," + sLegalStartParcel + "," + sLegalEndParcel + "," + sHistorical); Marshal.ReleaseComObject(pGSParcel); //garbage collection pGSParcel = pEnumGSParcels.Next(); if (m_bShowProgressor) { if (m_pStepProgressor.Position < m_pStepProgressor.MaxRange) { m_pStepProgressor.Step(); } } } Marshal.ReleaseComObject(pEnumGSParcels); //garbage collection #endregion #region Confirm Edit Locks bool bIsFileBasedGDB = false; bool bIsUnVersioned = false; bool bUseNonVersioned = false; if (!FabricUTILS.SetupEditEnvironment(pWS, pCadFabric, pEd, out bIsFileBasedGDB, out bIsUnVersioned, out bUseNonVersioned)) { return; } //if we're in an enterprise then test for edit locks string sTime = ""; if (!bIsUnVersioned && !bIsFileBasedGDB) { //see if parcel locks can be obtained on the selected parcels. First create a job. DateTime localNow = DateTime.Now; sTime = Convert.ToString(localNow); ICadastralJob pJob = new CadastralJobClass(); pJob.Name = sTime; pJob.Owner = System.Windows.Forms.SystemInformation.UserName; pJob.Description = "Delete selected parcels"; try { Int32 jobId = pCadFabric.CreateJob(pJob); } catch (COMException ex) { if (ex.ErrorCode == (int)fdoError.FDO_E_CADASTRAL_FABRIC_JOB_ALREADY_EXISTS) { MessageBox.Show("Job named: '" + pJob.Name + "', already exists"); } else { MessageBox.Show(ex.Message); } m_pStepProgressor = null; if (!(pProgressorDialog == null)) { pProgressorDialog.HideDialog(); } pProgressorDialog = null; Marshal.ReleaseComObject(pJob); if (bUseNonVersioned) { pCadEd.CadastralFabricLayer = null; } return; } Marshal.ReleaseComObject(pJob); } ICadastralFabricLocks pFabLocks = (ICadastralFabricLocks)pCadFabric; if (!bIsUnVersioned && !bIsFileBasedGDB) { pFabLocks.LockingJob = sTime; ILongArray pLocksInConflict = null; ILongArray pSoftLcksInConflict = null; ILongArray pParcelsToLock = new LongArrayClass(); FabricUTILS.FIDsetToLongArray(m_pFIDSetParcels, ref pParcelsToLock, m_pStepProgressor); if (m_bShowProgressor && !bIsFileBasedGDB) { m_pStepProgressor.Message = "Testing for edit locks on parcels..."; } try { pFabLocks.AcquireLocks(pParcelsToLock, true, ref pLocksInConflict, ref pSoftLcksInConflict); } catch (COMException pCOMEx) { if (pCOMEx.ErrorCode == (int)fdoError.FDO_E_CADASTRAL_FABRIC_JOB_LOCK_ALREADY_EXISTS || pCOMEx.ErrorCode == (int)fdoError.FDO_E_CADASTRAL_FABRIC_JOB_CURRENTLY_EDITED) { MessageBox.Show("Edit Locks could not be acquired on all selected parcels."); // since the operation is being aborted, release any locks that were acquired pFabLocks.UndoLastAcquiredLocks(); } else { MessageBox.Show(pCOMEx.Message + Environment.NewLine + Convert.ToString(pCOMEx.ErrorCode)); } if (bUseNonVersioned) { pCadEd.CadastralFabricLayer = null; } return; } Marshal.ReleaseComObject(pSoftLcksInConflict); Marshal.ReleaseComObject(pParcelsToLock); Marshal.ReleaseComObject(pLocksInConflict); } #endregion string sParcelSysEndDate = pParcelsTable.Fields.get_Field(iParcSysEndDate).Name; string sParcelLegalStartDate = pParcelsTable.Fields.get_Field(iParcLegalStartDate).Name; string sParcelLegalEndDate = pParcelsTable.Fields.get_Field(iParcLegalEndDate).Name; string sParcelHistoric = pParcelsTable.Fields.get_Field(iParcHistorical).Name; if (m_bShowProgressor) { pProgressorDialog.ShowDialog(); m_pStepProgressor.Message = "Updating parcel history..."; } pEd.StartOperation(); #region The Edit //make change to parcels bool bSuccess = false; ICursor pCurs = null; IQueryFilter pQuFilter = new QueryFilterClass(); pQuFilter.SubFields = pParcelsTable.OIDFieldName + "," + sParcelLegalEndDate + "," + sParcelLegalStartDate + "," + sParcelSysEndDate + "," + sParcelHistoric; bool bSystemEndDate_Clear = pChangeHistoryDialog.chkSystemEndDate.Checked && pChangeHistoryDialog.optClearSEDate.Checked; bool bLegalStDate_Clear = pChangeHistoryDialog.chkLegalStartDate.Checked && pChangeHistoryDialog.optClearLSDate.Checked; bool bLegalEndDate_Clear = pChangeHistoryDialog.chkLegalEndDate.Checked && pChangeHistoryDialog.optClearLEDate.Checked; bool bSystemEndDate_Set = pChangeHistoryDialog.chkSystemEndDate.Checked && pChangeHistoryDialog.optChooseSEDate.Checked; bool bLegalStDate_Set = pChangeHistoryDialog.chkLegalStartDate.Checked && pChangeHistoryDialog.optChooseLSDate.Checked; bool bLegalEndDate_Set = pChangeHistoryDialog.chkLegalEndDate.Checked && pChangeHistoryDialog.optChooseLEDate.Checked; List <bool> bHistory = new List <bool>(); bHistory.Add(bSystemEndDate_Clear); bHistory.Add(bLegalStDate_Clear); bHistory.Add(bLegalEndDate_Clear); bHistory.Add(bSystemEndDate_Set); bHistory.Add(bLegalStDate_Set); bHistory.Add(bLegalEndDate_Set); List <string> sDates = new List <string>(); sDates.Add(pChangeHistoryDialog.dtSEDatePicker.Text); sDates.Add(pChangeHistoryDialog.dtLSDatePicker.Text); sDates.Add(pChangeHistoryDialog.dtLEDatePicker.Text); pSchemaEd = (ICadastralFabricSchemaEdit2)pCadFabric; pSchemaEd.ReleaseReadOnlyFields(pLinesTable, esriCadastralFabricTable.esriCFTLines); //release safety-catch pSchemaEd.ReleaseReadOnlyFields(pParcelsTable, esriCadastralFabricTable.esriCFTParcels); //release safety-catch pSchemaEd.ReleaseReadOnlyFields(pPointsTable, esriCadastralFabricTable.esriCFTPoints); //release safety-catch foreach (string sInClause in sOIDList) { if (sInClause.Trim() == "") { continue; } pQuFilter.WhereClause = pParcelsTable.OIDFieldName + " IN (" + sInClause + ")"; pCurs = pParcelsTable.Update(pQuFilter, false); bSuccess = FabricUTILS.ChangeDatesOnTableMulti(pCurs, bHistory, sDates, bUseNonVersioned, ParcelToHistory_DICT, m_pStepProgressor, m_pTrackCancel); if (!bSuccess) { if (!bIsUnVersioned) { pFabLocks.UndoLastAcquiredLocks(); } if (bUseNonVersioned) { FabricUTILS.AbortEditing(pWS); } else { pEd.AbortOperation(); } //clear selection, to make sure the parcel explorer is updated and refreshed properly return; } } //make change to points and lines if (!FabricUTILS.UpdateHistoryOnLines(pLinesTable, pPointsTable, iParcelCount, pCadFabric, sOIDList, ParcelToHistory_DICT, m_pStepProgressor, m_pTrackCancel)) { if (!bIsUnVersioned) { pFabLocks.UndoLastAcquiredLocks(); } if (bUseNonVersioned) { FabricUTILS.AbortEditing(pWS); } else { pEd.AbortOperation(); } } else { pEd.StopOperation("Change Parcel History"); } #endregion //now refresh the map layers RefreshMap(pActiveView, CFParcelLayers, CFPointLayer, CFLineLayer, CFControlLayer, CFLinePointLayer); } catch (Exception ex) { pEd.AbortOperation(); MessageBox.Show("Error:" + ex.Message); } finally { if (!(pProgressorDialog == null)) { pProgressorDialog.HideDialog(); } pSchemaEd.ResetReadOnlyFields(esriCadastralFabricTable.esriCFTPoints); //set safety back on pSchemaEd.ResetReadOnlyFields(esriCadastralFabricTable.esriCFTLines); //set safety back on pSchemaEd.ResetReadOnlyFields(esriCadastralFabricTable.esriCFTParcels); //set safety back on } }
private void ExportLayer(Excel.Workbook ExcelWbk, IMxDocument MxDoc, IFeatureLayer FLayer, ref IProgressDialog2 progressDialog, ref IStepProgressor stepProgressor) { IFeatureClass FC = null; ISubtypes Subtypes = null; ITableProperties TableProperties = null; IEnumTableProperties EnumTableProperties = null; ITableProperty3 TableProperty = null; ITableCharacteristics TableCharacteristics = null; IFeatureSelection FeatSel = null; IDisplayTable DisplayTable = null; ITable Table = null; ILayerFields LayerFields = null; ITableFields TableFields = null; ILayer LayerTest = null; ICursor Cursor = null; IFeatureCursor FCursor = null; IField CurField = null; IDomain Domain = null; ICodedValueDomain CodedValueDomain = null; IFeature Feat = null; List<IPoint> pGeo = null; object missing = null; object sheet = null; Excel.Worksheet ExcelSheet = null; Excel.Range ExcelRange = null; Microsoft.Office.Interop.Excel.Style style = null; try { int Col = 0; int Row = 0; int i; int j; bool UseDescriptions; int subtype; string SheetName; missing = System.Reflection.Missing.Value; sheet = ExcelWbk.Sheets[ExcelWbk.Sheets.Count]; //Add new Excel worksheet ExcelSheet = (Excel.Worksheet)ExcelWbk.Sheets.Add(missing, sheet, missing, missing); SheetName = FLayer.Name; if (SheetName.Length > 30) { SheetName = SheetName.Substring(0, 30); } ExcelSheet.Name = SheetName; //style = ExcelWbk.Styles.Add("Style1"); //style.NumberFormat = "@"; LayerTest = (ILayer)FLayer; //Get Subtype info FC = FLayer.FeatureClass; Subtypes = FC as ISubtypes; //Determine whether to use descriptions or codes for domains and subtypes UseDescriptions = true; TableProperties = MxDoc.TableProperties; EnumTableProperties = (IEnumTableProperties)TableProperties; EnumTableProperties.Reset(); TableProperty = (ITableProperty3)EnumTableProperties.Next(); while (TableProperty != null && TableProperty.Layer != null) //Fixed { if (TableProperty.Layer.Equals(LayerTest)) { TableCharacteristics = (ITableCharacteristics)TableProperty; UseDescriptions = TableCharacteristics.ShowCodedValueDomainDescriptions; } TableProperty = (ITableProperty3)EnumTableProperties.Next(); } FeatSel = (IFeatureSelection)FLayer; DisplayTable = (IDisplayTable)FLayer; Table = (ITable)DisplayTable.DisplayTable; //Get TableFields so later we can determine whether that field is visible LayerFields = (ILayerFields)FLayer; TableFields = (ITableFields)FLayer; //loop through each field and write column headings Row = 1; for (j = 0; j < TableFields.FieldCount; j++) { CurField = TableFields.get_Field(j); //skip blob and geometry fields if ((CurField.Type != esriFieldType.esriFieldTypeBlob) && (CurField.Type != esriFieldType.esriFieldTypeGeometry)) { Col += 1; //Write field alias name as Excel column header ExcelSheet.Cells[Row, Col] = TableFields.get_FieldInfo(j).Alias; if (CurField.Type == esriFieldType.esriFieldTypeString) ExcelSheet.get_Range(ExcelSheet.Cells[1, Col], ExcelSheet.Cells[65535, Col]).EntireColumn.NumberFormat = "@"; } } Col += 1; ExcelSheet.Cells[Row, Col] = "X_COORD"; Col += 1; ExcelSheet.Cells[Row, Col] = "Y_COORD"; Col += 1; ExcelSheet.Cells[Row, Col] = "Lat"; Col += 1; ExcelSheet.Cells[Row, Col] = "Long"; IField pFieldTest = FLayer.FeatureClass.Fields.get_Field(FLayer.FeatureClass.Fields.FindField(FLayer.FeatureClass.ShapeFieldName)); IGeometryDef pGeometryDefTest = null; pGeometryDefTest = pFieldTest.GeometryDef; bool bZAware = false; bool bMAware = false; //Determine if M or Z aware if (pGeometryDefTest.GeometryType == esriGeometryType.esriGeometryPoint) { bZAware = pGeometryDefTest.HasZ; bMAware = pGeometryDefTest.HasM; } if (bZAware) { Col += 1; ExcelSheet.Cells[Row, Col] = "Z_COORD"; } pFieldTest = null; pGeometryDefTest = null; //Get all selected records for this table (use IDisplayTable to get any joined data) DisplayTable.DisplaySelectionSet.Search(null, true, out Cursor); FCursor = (IFeatureCursor)Cursor; //subtype = Subtypes.DefaultSubtypeCode; //For each selected record Feat = FCursor.NextFeature(); // stepProgressor.Step(); // progressDialog.Description = A4LGSharedFunctions.Localizer.GetString("ExportAsset") + stepProgressor.Position + A4LGSharedFunctions.Localizer.GetString("Of") + MxDoc.FocusMap.SelectionCount.ToString() + "."; while (Feat != null) { Row += 1; if (Subtypes != null && Subtypes.HasSubtype == true && (Feat.get_Value(Subtypes.SubtypeFieldIndex) != null)) { subtype = Convert.ToInt32(Feat.get_Value(Subtypes.SubtypeFieldIndex)); } else { subtype = -99999; } //For each column Col = 0; for (j = 0; j < TableFields.FieldCount; j++) { CurField = TableFields.get_Field(j); //skip blob and geometry fields in data also if ((CurField.Type != esriFieldType.esriFieldTypeBlob) && (CurField.Type != esriFieldType.esriFieldTypeGeometry)) { Col += 1; ExcelSheet.Cells[Row, Col] = Feat.get_Value(j); if (UseDescriptions == true && subtype == -99999) { Domain = CurField.Domain; if (Domain != null) { if (Domain.Type == esriDomainType.esriDTCodedValue) { CodedValueDomain = (ICodedValueDomain)CurField.Domain; for (i = 0; i < CodedValueDomain.CodeCount; i++) { if ((CodedValueDomain.get_Value(i)).ToString() == (Feat.get_Value(j)).ToString()) { //System.Diagnostics.Debug.Print(CodedValueDomain.get_Name(0).ToString()); ExcelSheet.Cells[Row, Col] = CodedValueDomain.get_Name(i); i = CodedValueDomain.CodeCount; } } } } } else if (UseDescriptions == true && subtype != -99999) { if (Subtypes.SubtypeFieldIndex == j) { ExcelSheet.Cells[Row, Col] = Subtypes.get_SubtypeName(subtype); } else { Domain = Subtypes.get_Domain(subtype, CurField.Name); if ((Domain != null) && (Domain.Type == esriDomainType.esriDTCodedValue)) { CodedValueDomain = (ICodedValueDomain)Domain; for (i = 0; i < CodedValueDomain.CodeCount; i++) { if ((CodedValueDomain.get_Value(i)).ToString() == (Feat.get_Value(j)).ToString()) { //System.Diagnostics.Debug.Print(CodedValueDomain.get_Name(0).ToString()); ExcelSheet.Cells[Row, Col] = CodedValueDomain.get_Name(i); i = CodedValueDomain.CodeCount; } } } } } } } if (Feat.Shape != null) { if (Feat.Shape.IsEmpty == false) { pGeo = Globals.GetGeomCenter(Feat.Shape); if (pGeo != null) { if (pGeo.Count > 0) { if (pGeo[0].X != null) ExcelSheet.Cells[Row, Col + 1] = pGeo[0].X; if (pGeo[0].Y != null) ExcelSheet.Cells[Row, Col + 2] = pGeo[0].Y; if (pGeo[0] != null) { pGeo[0].Project(srWGS84); ExcelSheet.Cells[Row, Col + 3] = pGeo[0].Y; ExcelSheet.Cells[Row, Col + 4] = pGeo[0].X; } if (bZAware) { ExcelSheet.Cells[Row, Col + 5] = pGeo[0].Z; } } } } } stepProgressor.Step(); progressDialog.Description = A4LGSharedFunctions.Localizer.GetString("ExportAsset") + stepProgressor.Position + A4LGSharedFunctions.Localizer.GetString("Of") + MxDoc.FocusMap.SelectionCount.ToString() + "."; Feat = FCursor.NextFeature(); } //Hide Columns Col = 0; for (j = 0; j < TableFields.FieldCount; j++) { CurField = TableFields.get_Field(j); //skip blob and geometry fields in data also if ((CurField.Type != esriFieldType.esriFieldTypeBlob) && (CurField.Type != esriFieldType.esriFieldTypeGeometry)) { Col += 1; //Autofit ExcelRange = ExcelSheet.get_Range(ExcelSheet.Cells[1, Col], ExcelSheet.Cells[Row, Col]); ExcelRange.EntireColumn.AutoFit(); //Hide column if invisible in ArcMap if (TableFields.get_FieldInfo(j).Visible == false) { ExcelRange = ExcelSheet.get_Range(ExcelSheet.Cells[1, Col], ExcelSheet.Cells[Row, Col]); ExcelRange.EntireColumn.Hidden = true; } } } } catch { MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("ExportXLError")); } finally { FC = null; Subtypes = null; TableProperties = null; if (EnumTableProperties != null) Marshal.ReleaseComObject(EnumTableProperties); EnumTableProperties = null; TableProperty = null; TableCharacteristics = null; FeatSel = null; DisplayTable = null; Table = null; LayerFields = null; TableFields = null; LayerTest = null; if (Cursor != null) Marshal.ReleaseComObject(Cursor); Cursor = null; if (FCursor != null) Marshal.ReleaseComObject(FCursor); FCursor = null; CurField = null; Domain = null; CodedValueDomain = null; Feat = null; pGeo = null; missing = null; sheet = null; ExcelSheet = null; ExcelRange = null; style = null; } }
private bool ResetPointAssociations(ITable PointTable, IQueryFilter QueryFilter, bool Unversioned, IStepProgressor StepProgressor, ITrackCancel TrackCancel) { try { ITableWrite pTableWr = (ITableWrite)PointTable;//used for unversioned table IRow pPointFeat = null; ICursor pPtCurs = null; if (Unversioned) { pPtCurs = pTableWr.UpdateRows(QueryFilter, false); } else { pPtCurs = PointTable.Update(QueryFilter, false); } pPointFeat = pPtCurs.NextRow(); if (StepProgressor != null) { if (StepProgressor.Position < StepProgressor.MaxRange) { StepProgressor.Step(); } } Int32 iPointIDX = pPtCurs.Fields.FindField("NAME"); bool bCont = true; while (pPointFeat != null) {//loop through all of the fabric points, and if any of the point id values are in the deleted set, //then remove the control name from the point's NAME field if (TrackCancel != null) { bCont = TrackCancel.Continue(); } if (!bCont) { break; } pPointFeat.set_Value(iPointIDX, DBNull.Value); if (Unversioned) { pPtCurs.UpdateRow(pPointFeat); } else { pPointFeat.Store(); } Marshal.ReleaseComObject(pPointFeat); //garbage collection pPointFeat = pPtCurs.NextRow(); if (StepProgressor != null) { if (StepProgressor.Position < StepProgressor.MaxRange) { StepProgressor.Step(); } } } Marshal.ReleaseComObject(pPtCurs); //garbage collection if (!bCont) { return(false); } return(true); } catch (COMException ex) { MessageBox.Show("Problem resetting point table's control association: " + Convert.ToString(ex.ErrorCode)); return(false); } }
public void Draw(IStepProgressor stepProgressor, IActiveView activeView, FileCache fileCache, ITrackCancel trackCancel, ISpatialReference layerSpatialReference, ref string currentLevel, ITileSource tileSource, IDisplay display) { _tileSource = tileSource; _trackCancel = trackCancel; _layerSpatialReference = layerSpatialReference; _currentLevel = currentLevel; _fileCache = fileCache; _tileProvider = (WebTileProvider)tileSource.Provider; var spatialReferences = new SpatialReferences(); _dataSpatialReference = spatialReferences.GetSpatialReference(tileSource.Schema.Srs); //var fetcher = new FileFetcher<Image>(osmTileSource, fileCache); _display = display; if (!activeView.Extent.IsEmpty) { _tiles = GetTiles(activeView); currentLevel = _currentLevel; Logger.Debug("Number of tiles to draw: " + _tiles.Count); if (_tiles.ToList().Count > 0) { stepProgressor.MinRange = 0; stepProgressor.MaxRange = _tiles.ToList().Count; stepProgressor.Show(); var downloadFinished = new ManualResetEvent(false); // this is a hack, otherwise we get error message... // "WaitAll for multiple handles on a STA thread is not supported. (mscorlib)" // so lets start a thread first... var t = new Thread(DownloadTiles); t.Start(downloadFinished); // wait till finished downloadFinished.WaitOne(); // 3. Now draw all tiles... if (layerSpatialReference != null && _dataSpatialReference!=null) { _needReproject = (layerSpatialReference.FactoryCode != _dataSpatialReference.FactoryCode); } Logger.Debug("Need reproject tile: " + _needReproject.ToString()); foreach (var tile in _tiles) { stepProgressor.Step(); if (tile != null) { var name = _fileCache.GetFileName(tile.Index); if (!File.Exists(name)) continue; DrawRaster(name); } } stepProgressor.Hide(); } else { Logger.Debug("No tiles to retrieve or draw"); } Logger.Debug("End drawing tiles: " + _tiles.ToList().Count); } }