//private void AddField(IFeatureLayer pFeaturelayer, string strFieldName) //{ // IMxDocument pmxdoc = ArcMap.Document as IMxDocument; // IMap pmap = pmxdoc.FocusMap; // IFeatureClass pFeatureClass = pFeaturelayer.FeatureClass; // IFieldEdit pNewField = new FieldClass(); // pNewField.Name_2 = strFieldName; // if (pFeatureClass.FindField(strFieldName) != -1) // { // //MessageBox.Show("Field: " + strFieldName + " already exists."); // return; // } // pNewField.Type_2 = esriFieldType.esriFieldTypeDouble; // pNewField.Length_2 = 50; // pNewField.Editable_2 = true; // pNewField.IsNullable_2 = true; // pNewField.DefaultValue_2 = null; // pFeatureClass.AddField(pNewField); // pNewField = null; // GC.Collect(); //} private IProgressDialog2 ShowProgressIndicator(string strTitle, int iMax, int iStepValue) { IProgressDialogFactory pProgressDlgFact; IProgressDialog2 pProgressDialog; ITrackCancel pTrackCancel; //'Show a progress dialog while we cycle through the features pTrackCancel = new CancelTrackerClass(); pProgressDlgFact = new ProgressDialogFactoryClass(); pProgressDialog = (IProgressDialog2)pProgressDlgFact.Create(pTrackCancel, 0); pProgressDialog.CancelEnabled = false; pProgressDialog.Title = strTitle; pProgressDialog.Animation = esriProgressAnimationTypes.esriProgressGlobe; //'Set the properties of the Step Progressor pStepProgressor = (IStepProgressor)pProgressDialog; pStepProgressor.MinRange = 0; pStepProgressor.MaxRange = iMax; pStepProgressor.StepValue = iStepValue; return(pProgressDialog); }
public ProgressDialog(bool a_EnableCancel, int a_MinValue, int a_MaxValue, string a_Title, string a_Description) { var a_ProgressDialogFactory = new ProgressDialogFactoryClass(); m_TrackCancel = new CancelTracker(); m_StepProgressor = a_ProgressDialogFactory.Create(m_TrackCancel, 0); m_ProgressDialog = (IProgressDialog2)m_StepProgressor; m_TrackCancel.CancelOnClick = a_EnableCancel; m_TrackCancel.CancelOnKeyPress = a_EnableCancel; m_StepProgressor.MinRange = a_MinValue; m_StepProgressor.MaxRange = a_MaxValue; m_StepProgressor.StepValue = 1; m_StepProgressor.Position = m_StepProgressor.MinRange; if (a_MinValue == a_MaxValue) { m_StepProgressor.Hide(); } m_ProgressDialog.CancelEnabled = a_EnableCancel; m_ProgressDialog.Title = a_Title; m_ProgressDialog.Description = a_Description; m_ProgressDialog.Animation = esriProgressAnimationTypes.esriProgressSpiral; }
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"); }
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 Cleanup(IProgressDialog2 ProgressorDialog, IMouseCursor MouseCursor) { MouseCursor.SetCursor(0); if (!(ProgressorDialog == null)) { ProgressorDialog.HideDialog(); } ProgressorDialog = null; m_pStepProgressor = null; }
/// <summary>Exports all bookmarks to PDF files.</summary> /// <param name="directory">The directory that the exported files will be written to.</param> /// <param name="dpi">The resolution of the output files.</param> /// <param name="exportFormat">The format of the exported files.</param> public void ExportBookmarksToFiles(string directory, long dpi, ExportFormat exportFormat) { if (!Directory.Exists(directory)) { throw new DirectoryNotFoundException("Directory not found: " + directory); } IMouseCursor mc = new MouseCursorClass(); const int hourglass = 2; mc.SetCursor(hourglass); IMxDocument mxDoc = _app.Document as IMxDocument; IMapBookmarks bookmarks = (IMapBookmarks)mxDoc.FocusMap; IEnumSpatialBookmark enumBM = bookmarks.Bookmarks; enumBM.Reset(); ISpatialBookmark sbm = enumBM.Next(); ProgressDialogFactoryClass dialogFactory = new ProgressDialogFactoryClass(); var cancelTracker = new CancelTrackerClass(); IStepProgressor stepProgressor = dialogFactory.Create(cancelTracker, _app.hWnd); IProgressDialog2 progDialog = stepProgressor as IProgressDialog2; progDialog.CancelEnabled = true; progDialog.ShowDialog(); stepProgressor.Hide(); stepProgressor.Message = "Exporting..."; // Create a formatting string with the proper extension. (E.g., "{0}.pdf" for PDF files".) string fnFmt = string.Format("{{0}}.{0}", Enum.GetName(typeof(ExportFormat), exportFormat)); try { while (sbm != null) { sbm.ZoomTo(mxDoc.FocusMap); string filename = System.IO.Path.Combine(directory, string.Format(fnFmt, sbm.Name)); ExportPageLayoutToFile(mxDoc.PageLayout, filename, dpi, exportFormat); sbm = enumBM.Next(); } } finally { if (progDialog != null) { progDialog.HideDialog(); ComReleaser.ReleaseCOMObject(progDialog); } } }
private void AutoSave_Save() { if (!CheckRequirements()) { return; } if (!IsSaveable()) { return; } ITrackCancel trackcancel = new CancelTrackerClass(); IProgressDialogFactory progressdialogfactory = new ProgressDialogFactoryClass(); IStepProgressor stepprogressor = progressdialogfactory.Create(trackcancel, _application.hWnd); stepprogressor.MinRange = 0; stepprogressor.MaxRange = 1; stepprogressor.StepValue = 1; stepprogressor.Message = "Saving..."; IProgressDialog2 progressdialog = (IProgressDialog2)stepprogressor; // Creates and displays progressdialog.CancelEnabled = true; progressdialog.Description = "Saving..."; progressdialog.Title = "Saving..."; progressdialog.Animation = esriProgressAnimationTypes.esriDownloadFile; try { ILayer layer = _utilitiesArcmap.Layer(this.cboTargetLayer.Text); IFeatureLayer featurelayer = layer as IFeatureLayer; if (!(featurelayer == null)) { IFeatureClass featureclass = featurelayer.FeatureClass; IWorkspace2 workspace = ((IDataset)featureclass).Workspace as IWorkspace2; IWorkspaceEdit2 workspaceedit = (IWorkspaceEdit2)workspace; workspaceedit.StopEditing(true); workspaceedit.StartEditing(true); } } catch (Exception ex) { MessageBox.Show(ex.Message, "ABE Calculators", MessageBoxButtons.OK, MessageBoxIcon.Stop); } finally { trackcancel = null; stepprogressor = null; progressdialog.HideDialog(); progressdialog = null; this.btnClose.Enabled = true; } }
/// <summary> /// Occurs when this command is clicked /// </summary> public override void OnClick() { MgSettings MS = new MgSettings(); if (!Directory.Exists(MS.RootDir)) { MS.RootDir = Environment.GetFolderPath(Environment.SpecialFolder.Personal); } if (!Directory.Exists(MS.OutDir)) { MS.OutDir = MS.RootDir; } MS.Save(); MainForm M = new MainForm(); if (M.ShowDialog() == DialogResult.OK) { MergeFunc MF = new MergeFunc(M.RootDir, M.Filename, M.OutDir); TM = new System.Windows.Forms.Timer(); SW.Reset(); Geoprocessor GP = new Geoprocessor() { AddOutputsToMap = M.AddOutputsToMap, OverwriteOutput = M.OverwriteOutput }; GP.ToolExecuting += GP_ToolExecuting; GP.ToolExecuted += GP_ToolExecuted; TM.Tick += TM_Tick; ITrackCancel pTrackCancel = new CancelTrackerClass(); IProgressDialogFactory pProgDlgFactory = new ProgressDialogFactoryClass(); pProDlg = pProgDlgFactory.Create(pTrackCancel, m_application.hWnd) as IProgressDialog2; pProDlg.CancelEnabled = true; pProDlg.Title = "Merge in progress..."; pProDlg.Description = "Please wait patiently..."; pProDlg.Animation = esriProgressAnimationTypes.esriProgressSpiral; pStepPro = pProDlg as IStepProgressor; pStepPro.MinRange = 0; pStepPro.MaxRange = 100; pStepPro.StepValue = 1; pStepPro.Message = "Initiating..."; GP.Execute(MF.GetMerge(), pTrackCancel); } M.Dispose(); }
public virtual bool Work() { TrackCancel = new CancelTrackerClass(); ProgressDialogFactory = new ProgressDialogFactoryClass(); ProgressDialog = ProgressDialogFactory.Create(TrackCancel, hWd) as IProgressDialog2; ProgressDialog.CancelEnabled = false; ProgressDialog.Description = Description; ProgressDialog.Title = Description; ProgressDialog.Animation = esriProgressAnimationTypes.esriProgressGlobe; StepProgressor = ProgressDialog as IStepProgressor; StepProgressor.MinRange = 0; StepProgressor.StepValue = 1; StepProgressor.Message = "正在初始化工具......"; ProgressDialog.ShowDialog(); return(true); }
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(); }
public override void setStepProgressorProperties(int MaxRange, String Message, int MinRange = 0, int Position = 0, int StepValue = 1) { if (stepProgress != null) { stepProgress.Hide(); Marshal.ReleaseComObject(stepProgress); } stepProgress = progressDialogFactory.Create(cancelTracker, 0); IProgressDialog2 progressDialog = (IProgressDialog2)stepProgress; progressDialog.Animation = esriProgressAnimationTypes.esriProgressSpiral; progressDialog.Title = "Inferring Curved Segments"; stepProgress.Message = Message; if (MaxRange != MinRange) //for some reason, if you set the values the same, the progressor doesn't go away { stepProgress.MinRange = MinRange; stepProgress.MaxRange = MaxRange; stepProgress.StepValue = StepValue; } stepProgress.Show(); }
protected override void OnClick() { //first check that we are currently editing if (ArcMap.Editor.EditState != esriEditState.esriStateEditing) { MessageBox.Show("Please start editing and try again.", "Sample Code"); return; } //get the cadastral editor ICadastralEditor pCadEd = (ICadastralEditor)ArcMap.Application.FindExtensionByName("esriCadastralUI.CadastralEditorExtension"); //get the fabric line layers that belong to the target fabric. // **SAMPLE CODE NOTE** //This next function allows for more than 1 fabric lines sublayer in the map document, and uses a line layer array //However, this sample code assumes just one line fabric sub layer, and works with the first found //The function is provided for other expanded uses if needed elsewhere. IArray LineLayerArray; if (!GetFabricSubLayers(ArcMap.Document.ActiveView.FocusMap, esriCadastralFabricTable.esriCFTLines, true, pCadEd.CadastralFabric, out LineLayerArray)) { return; } // get the line selection; this code sample uses first line layer for the target fabric (first element) ISelectionSet2 LineSelection = GetSelectionFromLayer(LineLayerArray.get_Element(0) as ICadastralFabricSubLayer); // check to see if there is only one parcel line selected // **SAMPLE CODE NOTE** //This sample code ensures one line feature, although it can be easily adapted for use on //multiple line selection. if (LineSelection.Count != 1) { MessageBox.Show("Please select only one parcel line from the Target fabric.", "Sample Code"); return; } //Get a search cursor from the line selection to get the parcel id //We need to get an edit lock on the parcel using the parcel id //An edit lock will guarantee the edit will persist in a multi-user environment after a reconcile ILongArray pParcelsToLock = new LongArrayClass(); IFIDSet pFIDSetForParcelRegen = new FIDSet(); ICursor pCur; LineSelection.Search(null, false, out pCur); //this cursor returns the selected lines // **SAMPLE CODE NOTE** //setup for potential use for multiple line selection, even though this sample uses a single line selection //get the field indices for line attributes needed. int idxParcelID = pCur.FindField("parcelid"); int idxToPointID = pCur.FindField("topointid"); int idxFromPointID = pCur.FindField("frompointid"); int idxCenterPtId = pCur.FindField("centerpointid"); int idxDistance = pCur.FindField("distance"); int idxRadius = pCur.FindField("radius"); int idxCategory = pCur.FindField("category"); //also need the fabric point table and fields IFeatureClass pFabricPointsFC = (IFeatureClass)pCadEd.CadastralFabric.get_CadastralTable(esriCadastralFabricTable.esriCFTPoints); int idxPointX = pFabricPointsFC.FindField("x"); int idxPointY = pFabricPointsFC.FindField("y"); int idxPointCtrPt = pFabricPointsFC.FindField("centerpoint"); var ListFromToPairsForRadialLines = new List <int[]>(); // **SAMPLE CODE NOTE** //setup for potential use for multiple line selection, even though this sample uses a single line selection //the list declared above is here for potential use in Add-ins that make use of multiple circular arc lines int[] ParcelIdCtrPtIdFromId1FromId2; IRow pRow = pCur.NextRow(); while (pRow != null) { int iParcelID = (int)pRow.get_Value(idxParcelID); pParcelsToLock.Add(iParcelID); //LongArray for the parcel locks pFIDSetForParcelRegen.Add(iParcelID); //FIDSet for the parcel regenerate //now check for a center point id on the line; this is for the case of changing the radius of an existing curve object value = pRow.get_Value(idxCenterPtId); if (value != DBNull.Value) { //collecting information to remove radial lines ParcelIdCtrPtIdFromId1FromId2 = new int[4]; // 4-element array ParcelIdCtrPtIdFromId1FromId2[0] = iParcelID; ParcelIdCtrPtIdFromId1FromId2[1] = (int)value; //center point is always the to point of the radial line ParcelIdCtrPtIdFromId1FromId2[2] = (int)pRow.get_Value(idxFromPointID); ParcelIdCtrPtIdFromId1FromId2[3] = (int)pRow.get_Value(idxToPointID); // **SAMPLE CODE NOTE** //now add the array, to the list to accomodate other add-ins that may use //more than one selected circular arc line ListFromToPairsForRadialLines.Add(ParcelIdCtrPtIdFromId1FromId2); } Marshal.ReleaseComObject(pRow); pRow = pCur.NextRow(); } Marshal.ReleaseComObject(pCur); bool IsFileBasedGDB = (ArcMap.Editor.EditWorkspace.WorkspaceFactory.WorkspaceType != esriWorkspaceType.esriRemoteDatabaseWorkspace); if (!IsFileBasedGDB) { //for file geodatabase creating a job is optional //see if parcel locks can be obtained on the selected parcels. First create a job. string NewJobName = ""; if (!CreateJob(pCadEd.CadastralFabric, "Sample Code change line to curve", out NewJobName)) { return; } if (!TestForEditLocks(pCadEd.CadastralFabric, NewJobName, pParcelsToLock)) { return; } } //if we get this far, an edit lock has been acquired, or this is file geodatabase (no lock required) //prompt the user for a new radius value string sRadius = Interaction.InputBox("Enter a new Radius:", "Radius"); //**SAMPLE CODE NOTE** : // using the Interaction class from the Microsfot Visual Basic library // is a quick and easy way to provide an input dialog in a single line of code for sample purposes, // without neeing to add a windows form, dockable window, or other UI elements into this project. double dRadius = 0; if (!Double.TryParse(sRadius, out dRadius)) { return; } //we have a valid double value, so we can get ready to edit IProgressDialogFactory pProgressorDialogFact = new ProgressDialogFactoryClass(); ITrackCancel pTrackCancel = new CancelTracker(); IStepProgressor pStepProgressor = pProgressorDialogFact.Create(pTrackCancel, ArcMap.Application.hWnd); IProgressDialog2 pProgressorDialog = (IProgressDialog2)pStepProgressor; ICadastralFabricSchemaEdit2 pSchemaEd = (ICadastralFabricSchemaEdit2)pCadEd.CadastralFabric; try { //turn off the read-only flag on the lines table and points table pSchemaEd.ReleaseReadOnlyFields(LineSelection.Target, esriCadastralFabricTable.esriCFTLines); //release read-only pSchemaEd.ReleaseReadOnlyFields((ITable)pFabricPointsFC, esriCadastralFabricTable.esriCFTPoints); //release read-only //start an edit operation ArcMap.Editor.StartOperation(); //get an update cursor to make the edit on the line(s) LineSelection.Update(null, false, out pCur); pRow = pCur.NextRow(); int iChangeCount = 0; while (pRow != null) { double dChord = (double)pRow.get_Value(idxDistance); if (Math.Abs(dRadius) <= dChord / 2 && dRadius != 0) //minimum allowable radius is half the chord { Marshal.ReleaseComObject(pRow); pRow = pCur.NextRow(); continue; } //compute a center point location from new radius, unless it's 0 int iNewCtrPtId = 0; if (dRadius != 0) { IFeature pFeat = pRow as IFeature; IPoint pCtrPt = ComputeCenterPointFromRadius(pFeat.Shape as IPolyline, dRadius, true); IFeature pNewPointFeat = pFabricPointsFC.CreateFeature(); //**SAMPLE CODE NOTE** : //if adding a large number of points (more than 20) then createfeature is not the fastest approach, //Instead you would pre-allocate points using an insert cursor... //At this point in the code, the normal geodatabase performance considerations apply iNewCtrPtId = pNewPointFeat.OID; pNewPointFeat.set_Value(idxPointX, pCtrPt.X); pNewPointFeat.set_Value(idxPointY, pCtrPt.Y); pNewPointFeat.set_Value(idxPointCtrPt, 1); //1 = true boolean pNewPointFeat.Shape = pCtrPt; pNewPointFeat.Store(); } //get the initial radius if the line is a curve (radius is being updated) object obj = pRow.get_Value(idxRadius); bool bIsChangingFromCurve = (obj != DBNull.Value); //there is a radius value obj = pRow.get_Value(idxCenterPtId); bIsChangingFromCurve = bIsChangingFromCurve && (obj != DBNull.Value); //radius value and Ctr Pt ID exist int iExistingCtrPtId = 0; if (bIsChangingFromCurve) { iExistingCtrPtId = (int)obj; } if (dRadius == 0) //user entered value is zero meaning convert to straight line { //changing to a straight line so set the center point an radius to null pRow.set_Value(idxRadius, DBNull.Value); pRow.set_Value(idxCenterPtId, DBNull.Value); } else if (!bIsChangingFromCurve) //user entered a new radius, and the existing line is not a curve { //changing to a circular arc so set the radius, and set the center point id to the new point's OID pRow.set_Value(idxRadius, dRadius); pRow.set_Value(idxCenterPtId, iNewCtrPtId); } else if (bIsChangingFromCurve) //user entered a radius, and the existing line is a curve { pCur.UpdateRow(pRow); } iChangeCount++; Marshal.ReleaseComObject(pRow); pRow = pCur.NextRow(); } Marshal.ReleaseComObject(pCur); if (iChangeCount == 0) {//if there are no changes then don't add to the edit operation stack ArcMap.Editor.AbortOperation(); return; } if (ListFromToPairsForRadialLines.Count > 0) { IQueryFilter pQuFilter = new QueryFilter(); string sCat = LineSelection.Target.Fields.get_Field(idxCategory).Name; string sToPt = LineSelection.Target.Fields.get_Field(idxToPointID).Name; string sFromPt = LineSelection.Target.Fields.get_Field(idxFromPointID).Name; string sParcelID = LineSelection.Target.Fields.get_Field(idxParcelID).Name; string sInClauseToPts = "("; string sInClauseFromPts = "("; string sInClauseParcelIds = "("; //**SAMPLE CODE NOTE** : //The following In Clause, when contructed for production environments //should take into account the token limit on Oracle database platforms. (<1000) // the processing of the in clause should be broekn into blocks with the in cluase has no more than 1000 elements foreach (int[] iParcelIdCtrPtIdFromId1FromId2 in ListFromToPairsForRadialLines) { if (sInClauseParcelIds.Length == 1) { sInClauseParcelIds += iParcelIdCtrPtIdFromId1FromId2[0].ToString(); } else { sInClauseParcelIds += "," + iParcelIdCtrPtIdFromId1FromId2[0].ToString(); } if (sInClauseToPts.Length == 1) { sInClauseToPts += iParcelIdCtrPtIdFromId1FromId2[1].ToString(); } else { sInClauseToPts += "," + iParcelIdCtrPtIdFromId1FromId2[1].ToString(); } if (sInClauseFromPts.Length == 1) { sInClauseFromPts += iParcelIdCtrPtIdFromId1FromId2[2].ToString(); sInClauseFromPts += "," + iParcelIdCtrPtIdFromId1FromId2[3].ToString(); } else { sInClauseFromPts += "," + iParcelIdCtrPtIdFromId1FromId2[2].ToString(); sInClauseFromPts += "," + iParcelIdCtrPtIdFromId1FromId2[2].ToString(); } } pQuFilter.WhereClause = sCat + " = 4 AND " + sParcelID + " IN " + sInClauseParcelIds + ") AND " + sFromPt + " IN " + sInClauseFromPts + ") AND " + sToPt + " IN " + sInClauseToPts + ")"; LineSelection.Target.DeleteSearchedRows(pQuFilter); } //with the new information added to the line, the rest of the parcel needs to be updated //regenerate the parcel using the parcel fidset ICadastralFabricRegeneration pRegenFabric = new CadastralFabricRegenerator(); #region regenerator enum // enum esriCadastralRegeneratorSetting // esriCadastralRegenRegenerateGeometries = 1 // esriCadastralRegenRegenerateMissingRadials = 2, // esriCadastralRegenRegenerateMissingPoints = 4, // esriCadastralRegenRemoveOrphanPoints = 8, // esriCadastralRegenRemoveInvalidLinePoints = 16, // esriCadastralRegenSnapLinePoints = 32, // esriCadastralRegenRepairLineSequencing = 64, // esriCadastralRegenRepairPartConnectors = 128 // By default, the bitmask member is 0 which will only regenerate geometries. // (equivalent to passing in regeneratorBitmask = 1) #endregion pRegenFabric.CadastralFabric = pCadEd.CadastralFabric; pRegenFabric.RegeneratorBitmask = 7; pRegenFabric.RegenerateParcels(pFIDSetForParcelRegen, false, pTrackCancel); //15 (enum values of 8 means remove orphan points; this only works when doing entire fabric) //TODO: remove orphaned center points programmatically pStepProgressor.MinRange = 0; pStepProgressor.MaxRange = iChangeCount; pStepProgressor.StepValue = 1; pProgressorDialog.Animation = ESRI.ArcGIS.Framework.esriProgressAnimationTypes.esriProgressSpiral; pRegenFabric.RegenerateParcels(pFIDSetForParcelRegen, false, pTrackCancel); ArcMap.Editor.StopOperation("Change line radius"); } catch (Exception ex) { ArcMap.Editor.AbortOperation(); MessageBox.Show(ex.Message); } finally { if (pSchemaEd != null) { pSchemaEd.ResetReadOnlyFields(esriCadastralFabricTable.esriCFTPoints); pSchemaEd.ResetReadOnlyFields(esriCadastralFabricTable.esriCFTLines); } pStepProgressor = null; if (!(pProgressorDialog == null)) { pProgressorDialog.HideDialog(); } pProgressorDialog = null; RefreshMap(LineLayerArray); ICadastralExtensionManager pCExMan = (ICadastralExtensionManager)pCadEd; IParcelPropertiesWindow2 pPropW = (IParcelPropertiesWindow2)pCExMan.ParcelPropertiesWindow; pPropW.RefreshAll(); //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); } } }
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 void Execute(IArray paramvalues, ITrackCancel trackcancel, IGPEnvironmentManager envMgr, IGPMessages messages) { // Re-validate. IGPMessages ms = m_util.InternalValidate(ParameterInfo, paramvalues, false, false, envMgr); messages.AddMessage("MWSW Boundary Generator, v. 0.0"); if (((IGPMessage)(ms)).IsError()) { messages.AddMessages(ms); return; } if (!AoGPParameter.ValidateAll(m_parms, paramvalues, messages)) { return; } try { IGPValue inlyr = m_util.UnpackGPValue((paramvalues.get_Element(0) as IGPParameter).Value); IGPDouble ang_tol = m_util.UnpackGPValue((paramvalues.get_Element(1) as IGPParameter).Value) as IGPDouble; IGPDouble dist_tol = m_util.UnpackGPValue((paramvalues.get_Element(2) as IGPParameter).Value) as IGPDouble; IGPValue outlyr = m_util.UnpackGPValue((paramvalues.get_Element(3) as IGPParameter).Value); // DumpIt("In layer",inlyr,messages); // DumpIt("Out layer",outlyr,typeof(IGPValue),messages); IFeatureClass inputfc; IQueryFilter inputqf; m_util.DecodeFeatureLayer(inlyr, out inputfc, out inputqf); // DumpIt("In Featureclass",inputfc,typeof(IFeatureClass),messages); // DumpIt("In QF",inputqf,typeof(IQueryFilter),messages); messages.AddMessage("In angle tolerance: " + ang_tol.Value); messages.AddMessage("In distance tolerance: " + dist_tol.Value); messages.AddMessage("Input featureclass: " + inputfc.AliasName); messages.AddMessage("Output path: " + outlyr.GetAsText()); trackcancel.Progressor.Show(); trackcancel.Progressor.Message = "Processing..."; string outp_txt = outlyr.GetAsText(); AoFeatureClassName fcname = new AoFeatureClassName(outp_txt); ISpatialReference spref = AoTable.From(inputfc)[inputfc.ShapeFieldName].Field.GeometryDef.SpatialReference; string shapename = fcname.ShapeFieldName != "" ? fcname.ShapeFieldName : "Shape"; m_outp_schema[shapename] = AoField.Shape(shapename, esriGeometryType.esriGeometryPolyline, spref); // TODO: shapefiles seem to get an FID automatically, // while geodb needs an 'OBJECTID', // who knows about other workspace types? // Is there a way to figure this out w/o looking at the type? IFeatureClass outputfc = fcname.Workspace.CreateFeatureClass(fcname.Basename, m_outp_schema.Fields, null, null, esriFeatureType.esriFTSimple, shapename, ""); IStepProgressor progressor = trackcancel.Progressor as IStepProgressor; progressor.MaxRange = 200; BGenImp implementation = new BGenImp(spref, ang_tol.Value, dist_tol.Value); implementation.Run(inputfc, outputfc, delegate(double howfar) { progressor.Position = (int)(200.0 * howfar); }); messages.AddMessage("Finished, worked through " + implementation.TotalSegments + " line segments total."); return; } catch (Exception e) { while (e != null) { messages.AddError(1, "Exception: " + e.Message); e = e.InnerException; } } }
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; }
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; } }
protected override void OnClick() { m_pApp = (IApplication)ArcMap.Application; if (m_pApp == null) //if the app is null then could be running from ArcCatalog m_pApp = (IApplication)ArcCatalog.Application; if (m_pApp == null) { MessageBox.Show("Could not access the application.", "No Application found"); return; } IGxApplication pGXApp = (IGxApplication)m_pApp; stdole.IUnknown pUnk = null; try { pUnk = (stdole.IUnknown)pGXApp.SelectedObject.InternalObjectName.Open(); } catch (COMException ex) { if (ex.ErrorCode == (int)fdoError.FDO_E_DATASET_TYPE_NOT_SUPPORTED_IN_RELEASE || ex.ErrorCode == -2147220944) MessageBox.Show("The dataset is not supported in this release.", "Could not open the dataset"); else MessageBox.Show(ex.ErrorCode.ToString(), "Could not open the dataset"); return; } if (pUnk is ICadastralFabric) m_pCadaFab = (ICadastralFabric)pUnk; else { MessageBox.Show("Please select a parcel fabric and try again.", "Not a parcel fabric"); return; } IMouseCursor pMouseCursor = new MouseCursorClass(); pMouseCursor.SetCursor(2); Utils FabricUTILS = new Utils(); ITable pTable = m_pCadaFab.get_CadastralTable(esriCadastralFabricTable.esriCFTParcels); IDataset pDS = (IDataset)pTable; IWorkspace pWS = pDS.Workspace; bool bIsFileBasedGDB = true; bool bIsUnVersioned = true; FabricUTILS.GetFabricPlatform(pWS, m_pCadaFab, out bIsFileBasedGDB, out bIsUnVersioned); //Do a Start and Stop editing to make sure we're not running in an edit session if (!FabricUTILS.StartEditing(pWS, true)) {//if start editing fails then bail if (pUnk != null) Marshal.ReleaseComObject(pUnk); Cleanup(pMouseCursor, null, pTable, null, pWS, null, true); FabricUTILS = null; return; } FabricUTILS.StopEditing(pWS); ITable pPlansTable = m_pCadaFab.get_CadastralTable(esriCadastralFabricTable.esriCFTPlans); ITable pParcelsTable = m_pCadaFab.get_CadastralTable(esriCadastralFabricTable.esriCFTParcels); m_pProgressorDialogFact = new ProgressDialogFactoryClass(); m_pTrackCancel = new CancelTrackerClass(); m_pStepProgressor = m_pProgressorDialogFact.Create(m_pTrackCancel, m_pApp.hWnd); IProgressDialog2 pProgressorDialog = (IProgressDialog2)m_pStepProgressor; int iRowCount = pPlansTable.RowCount(null); int iRowCount2 = pParcelsTable.RowCount(null); m_pStepProgressor.MinRange = 1; m_pStepProgressor.MaxRange =iRowCount + iRowCount2; m_pStepProgressor.StepValue = 1; pProgressorDialog.Animation = ESRI.ArcGIS.Framework.esriProgressAnimationTypes.esriProgressSpiral; pProgressorDialog.ShowDialog(); m_pStepProgressor.Message = "Searching " + iRowCount2.ToString() + " parcel records..."; int iFixCnt = 0; //load all the plan names into a string array ArrayList NoPlanParcels = new ArrayList(); ArrayList NoPlanParcelsGrouped = new ArrayList(); ArrayList PlansList = new ArrayList(); Dictionary<int, int> ParcelLookup = new Dictionary<int, int>(); if (!FindNoPlanParcels(pPlansTable, pParcelsTable, ref PlansList, ref NoPlanParcels, ref NoPlanParcelsGrouped, ref ParcelLookup, out iFixCnt)) { pProgressorDialog.HideDialog(); if (iFixCnt > 0) MessageBox.Show("Canceled searching for parcels with no plan.", "Fix Parcels With No Name"); NoPlanParcels = null; Cleanup(pMouseCursor, null, pTable, pPlansTable, pWS, pProgressorDialog, true); return; } m_pStepProgressor.Message = "Search complete."; NoPlanParcels.Sort(); dlgFixParcelsWithNoPlan MissingPlansDialog = new dlgFixParcelsWithNoPlan(); FillTheList(MissingPlansDialog.listView1, NoPlanParcels); FillTheList(MissingPlansDialog.listViewByGroup, NoPlanParcelsGrouped); FillTheListBox(MissingPlansDialog.listPlans, PlansList); MissingPlansDialog.ThePlansList = PlansList; MissingPlansDialog.label1.Text = "Found " + iFixCnt.ToString() + " parcels that have a missing plan record."; MissingPlansDialog.lblSelectionCount.Text = "(" + iFixCnt.ToString() + " of " + iFixCnt.ToString() + " selected to fix)"; //cleanup Cleanup(null, null, null, null, null, pProgressorDialog, false); DialogResult dResult = MissingPlansDialog.ShowDialog(); if (dResult == DialogResult.Cancel) { Cleanup(null, null, pTable, pPlansTable, pWS, pProgressorDialog, true); return; } //re-initilize the progressor m_pProgressorDialogFact = new ProgressDialogFactoryClass(); m_pTrackCancel = new CancelTrackerClass(); m_pStepProgressor = m_pProgressorDialogFact.Create(m_pTrackCancel, m_pApp.hWnd); pProgressorDialog = (IProgressDialog2)m_pStepProgressor; m_pStepProgressor.MinRange = 1; m_pStepProgressor.MaxRange = MissingPlansDialog.listView1.CheckedItems.Count; m_pStepProgressor.StepValue = 1; pProgressorDialog.Animation = ESRI.ArcGIS.Framework.esriProgressAnimationTypes.esriProgressSpiral; pProgressorDialog.ShowDialog(); m_pStepProgressor.Message = "Fixing parcels without a plan..."; if (!FabricUTILS.StartEditing(pWS, bIsUnVersioned)) { pProgressorDialog.HideDialog(); Cleanup(null, null, pTable, pPlansTable, pWS, pProgressorDialog, true); FabricUTILS = null; return; } int iNewPlanID = 0; //Need to collect the choices from the UI and write the results to the DB ICadastralFabricSchemaEdit2 pSchemaEd = (ICadastralFabricSchemaEdit2)m_pCadaFab; if (MissingPlansDialog.radioBtnExistingPlan.Checked) {//Get the id of the EXISTING Plan string sPlanString = MissingPlansDialog.listPlans.SelectedItem.ToString(); string[] sPlanOID = Regex.Split(sPlanString, "oid:"); sPlanOID[1].Trim(); iNewPlanID = Convert.ToInt32(sPlanOID[1].Remove(sPlanOID[1].LastIndexOf(")"))); } Dictionary<string, int> PlanLookUp= new Dictionary<string,int>(); ArrayList iUnitsAndFormat = new ArrayList(); iUnitsAndFormat.Add(m_AngleUnits); iUnitsAndFormat.Add(m_AreaUnits); iUnitsAndFormat.Add(m_DistanceUnits); iUnitsAndFormat.Add(m_DirectionFormat); iUnitsAndFormat.Add(m_LineParams); if (MissingPlansDialog.radioBtnUserDef.Checked) { //create a NEW plan named with user's entered text ArrayList sPlanInserts = new ArrayList(); pSchemaEd.ReleaseReadOnlyFields(pPlansTable, esriCadastralFabricTable.esriCFTPlans); //release safety-catch sPlanInserts.Add(MissingPlansDialog.txtPlanName.Text); FabricUTILS.InsertPlanRecords(pPlansTable, sPlanInserts,iUnitsAndFormat,PlansList, bIsUnVersioned, null, null, ref PlanLookUp); if (!PlanLookUp.TryGetValue(MissingPlansDialog.txtPlanName.Text, out iNewPlanID)) { Cleanup(null, null, pTable, pPlansTable, pWS, pProgressorDialog, true); FabricUTILS = null; return; } } if (MissingPlansDialog.radioBtnPlanID.Checked) {//create multiple new plans for each PlanID ArrayList sPlanInserts = new ArrayList(); foreach (ListViewItem listItem in MissingPlansDialog.listViewByGroup.CheckedItems) sPlanInserts.Add("[" + listItem.SubItems[0].Text + "]"); pSchemaEd.ReleaseReadOnlyFields(pPlansTable, esriCadastralFabricTable.esriCFTPlans); //release safety-catch FabricUTILS.InsertPlanRecords(pPlansTable, sPlanInserts, iUnitsAndFormat, PlansList, bIsUnVersioned, null, null, ref PlanLookUp); } ArrayList sParcelUpdates = new ArrayList(); sParcelUpdates.Add(""); int i = 0; int iCnt = 0; int iTokenLimit = 995; foreach (ListViewItem listItem in MissingPlansDialog.listView1.CheckedItems) { string s = listItem.SubItems[1].Text; string[] sItems = Regex.Split(s, "id:"); if (iCnt >= iTokenLimit)//time to start a new row { sParcelUpdates.Add("");//add a new item to the arraylist iCnt = 0;//reset token counter i++;//increment array index } sItems[1] = sItems[1].Remove(sItems[1].LastIndexOf(")")); if (iCnt == 0) sParcelUpdates[i] += sItems[1]; else sParcelUpdates[i] += "," + sItems[1]; iCnt++; } //============edit block========== try { pSchemaEd.ReleaseReadOnlyFields(pTable, esriCadastralFabricTable.esriCFTParcels); //release safety-catch if (MissingPlansDialog.radioBtnUserDef.Checked || MissingPlansDialog.radioBtnExistingPlan.Checked) { if (!FabricUTILS.UpdateParcelRecords(pTable, sParcelUpdates, iNewPlanID, bIsUnVersioned, m_pStepProgressor, m_pTrackCancel)) { pSchemaEd.ResetReadOnlyFields(esriCadastralFabricTable.esriCFTParcels); pSchemaEd.ResetReadOnlyFields(esriCadastralFabricTable.esriCFTPlans); FabricUTILS.AbortEditing(pWS); Cleanup(null, null, pTable, pPlansTable, pWS, pProgressorDialog, true); FabricUTILS = null; return; } } if (MissingPlansDialog.radioBtnPlanID.Checked) { if (!FabricUTILS.UpdateParcelRecordsByPlanGroup(pTable, sParcelUpdates, PlanLookUp, ParcelLookup, bIsUnVersioned, m_pStepProgressor, m_pTrackCancel)) { pSchemaEd.ResetReadOnlyFields(esriCadastralFabricTable.esriCFTParcels); pSchemaEd.ResetReadOnlyFields(esriCadastralFabricTable.esriCFTPlans); FabricUTILS.AbortEditing(pWS); Cleanup(null, null, pTable, pPlansTable, pWS, pProgressorDialog, true); FabricUTILS = null; return; } } pSchemaEd.ResetReadOnlyFields(esriCadastralFabricTable.esriCFTParcels); pSchemaEd.ResetReadOnlyFields(esriCadastralFabricTable.esriCFTPlans); FabricUTILS.StopEditing(pWS); //Cleanup(null, null, pTable, pPlansTable, pWS, pProgressorDialog, true); //FabricUTILS = null; } catch (COMException Ex) { MessageBox.Show(Ex.ErrorCode.ToString() +":" + Ex.Message,"Fix Missing Plans"); } finally { Cleanup(null, null, pTable, pPlansTable, pWS, pProgressorDialog, true); FabricUTILS = null; } }
private void Cleanup(IMouseCursor MouseCursor, IFIDSet PlansFIDSet, ITable pTable, ITable PlansTable, IWorkspace Workspace, IProgressDialog2 pProgressorDialog, bool CleanFabricVar) { if (pProgressorDialog != null) pProgressorDialog.HideDialog(); if (MouseCursor != null) MouseCursor.SetCursor(0); if (m_pStepProgressor != null) m_pStepProgressor.Hide(); m_pStepProgressor = null; if (PlansFIDSet != null) { do { } while (Marshal.ReleaseComObject(PlansFIDSet) > 0); } if (m_pProgressorDialogFact != null) { do { } while (Marshal.ReleaseComObject(m_pProgressorDialogFact) > 0); } if (m_pTrackCancel != null) { do { } while (Marshal.ReleaseComObject(m_pTrackCancel) > 0); } if (PlansTable != null) { do { } while (Marshal.ReleaseComObject(PlansTable) > 0); } if (m_pCadaFab != null && CleanFabricVar) { do { } while (Marshal.ReleaseComObject(m_pCadaFab) > 0); } if (pTable != null) { do { } while (Marshal.ReleaseComObject(pTable) > 0); } if (Workspace != null) { do { } while (Marshal.ReleaseComObject(Workspace) > 0); } }
protected override void OnClick() { m_pApp = (IApplication)ArcMap.Application; if (m_pApp == null) //if the app is null then could be running from ArcCatalog m_pApp = (IApplication)ArcCatalog.Application; if (m_pApp == null) { MessageBox.Show("Could not access the application.", "No Application found"); return; } IGxApplication pGXApp = (IGxApplication)m_pApp; stdole.IUnknown pUnk = null; try { pUnk = (stdole.IUnknown)pGXApp.SelectedObject.InternalObjectName.Open(); } catch (COMException ex) { if (ex.ErrorCode == (int)fdoError.FDO_E_DATASET_TYPE_NOT_SUPPORTED_IN_RELEASE || ex.ErrorCode == -2147220944) MessageBox.Show("The dataset is not supported in this release.", "Could not open the dataset"); else MessageBox.Show(ex.ErrorCode.ToString(), "Could not open the dataset"); return; } if (pUnk is ICadastralFabric) m_pCadaFab = (ICadastralFabric)pUnk; else { MessageBox.Show("Please select a parcel fabric and try again.", "Not a parcel fabric"); return; } IMouseCursor pMouseCursor = new MouseCursorClass(); pMouseCursor.SetCursor(2); Utils FabricUTILS = new Utils(); ITable pTable = m_pCadaFab.get_CadastralTable(esriCadastralFabricTable.esriCFTParcels); IDataset pDS = (IDataset)pTable; IWorkspace pWS = pDS.Workspace; bool bIsFileBasedGDB = true; bool bIsUnVersioned = true; FabricUTILS.GetFabricPlatform(pWS, m_pCadaFab, out bIsFileBasedGDB, out bIsUnVersioned); //Do a Start and Stop editing to make sure we're not running in an edit session if (!FabricUTILS.StartEditing(pWS, true)) {//if start editing fails then bail if (pUnk != null) Marshal.ReleaseComObject(pUnk); Cleanup(pMouseCursor, null, pTable, null, pWS, null); FabricUTILS = null; return; } FabricUTILS.StopEditing(pWS); IFIDSet pPlansToDelete = null; try { string[] SummaryNames = new string[0]; //define as dynamic array string[] RepeatPlans = new string[0]; //define as dynamic array ITable pPlansTable = m_pCadaFab.get_CadastralTable(esriCadastralFabricTable.esriCFTPlans); //load all the plan names into a string array m_pProgressorDialogFact = new ProgressDialogFactoryClass(); m_pTrackCancel = new CancelTrackerClass(); m_pStepProgressor = m_pProgressorDialogFact.Create(m_pTrackCancel, m_pApp.hWnd); IProgressDialog2 pProgressorDialog = (IProgressDialog2)m_pStepProgressor; int iRowCount = pPlansTable.RowCount(null); m_pStepProgressor.MinRange = 1; m_pStepProgressor.MaxRange = iRowCount * 2; m_pStepProgressor.StepValue = 1; pProgressorDialog.Animation = ESRI.ArcGIS.Framework.esriProgressAnimationTypes.esriProgressSpiral; pProgressorDialog.ShowDialog(); m_pStepProgressor.Message = "Finding same-name plans to merge..."; int iRepeatCnt = 0; if (!FindRepeatPlans(pPlansTable, out RepeatPlans, out SummaryNames, out iRepeatCnt)) { pProgressorDialog.HideDialog(); if (iRepeatCnt == 0) { MessageBox.Show("All plans in the fabric have unique names." + Environment.NewLine + "There are no plans to merge.", "Merge plans by name"); } else { MessageBox.Show("There was a problem searching for repeat plans.", "Merge plans by name"); } SummaryNames = null; RepeatPlans = null; Cleanup(pMouseCursor, null, pTable, pPlansTable, pWS, pProgressorDialog); return; } dlgMergeSameNamePlans TheSummaryDialog = new dlgMergeSameNamePlans(); FillTheSummaryList(TheSummaryDialog, SummaryNames); DialogResult dResult = TheSummaryDialog.ShowDialog(); if (dResult == DialogResult.Cancel) { pProgressorDialog.HideDialog(); SummaryNames = null; RepeatPlans = null; Cleanup(pMouseCursor, null,pTable, pPlansTable, pWS, pProgressorDialog); pPlansTable = null; return; } //get the time now m_pStartTime = new TimeClass(); m_pStartTime.SetFromCurrentLocalTime(); Dictionary<int, int> Lookup = new Dictionary<int, int>(); string[] InClause = new string[0]; //define as dynamic array m_pStepProgressor.Message = "Creating the merge query..."; FabricUTILS.BuildSearchMapAndQuery(RepeatPlans, out Lookup, out InClause, out pPlansToDelete); ICadastralFabricSchemaEdit2 pSchemaEd = (ICadastralFabricSchemaEdit2)m_pCadaFab; ITable ParcelTable = m_pCadaFab.get_CadastralTable(esriCadastralFabricTable.esriCFTParcels); pSchemaEd.ReleaseReadOnlyFields(ParcelTable, esriCadastralFabricTable.esriCFTParcels); //release safety-catch if (!FabricUTILS.StartEditing(pWS, bIsUnVersioned)) { Cleanup(pMouseCursor, pPlansToDelete,pTable, pPlansTable, pWS, pProgressorDialog); InClause = null; Lookup.Clear(); Lookup = null; return; } //setup progressor dialog for merge m_pStepProgressor.Message = "Moving parcels from source to target plans..."; if (!FabricUTILS.MergePlans(ParcelTable, Lookup, InClause, bIsUnVersioned,m_pStepProgressor,m_pTrackCancel)) { FabricUTILS.AbortEditing(pWS); pSchemaEd.ResetReadOnlyFields(esriCadastralFabricTable.esriCFTParcels); Cleanup(pMouseCursor, pPlansToDelete,pTable,pPlansTable, pWS,pProgressorDialog); InClause = null; Lookup.Clear(); Lookup = null; return; } if (TheSummaryDialog.checkBox1.Checked) { //setup progressor dialog for Delete m_pStepProgressor.MaxRange = pPlansToDelete.Count(); m_pStepProgressor.Message = "Deleting source plans..."; if (bIsUnVersioned) { if (!FabricUTILS.DeleteRowsUnversioned(pWS, pPlansTable, pPlansToDelete, m_pStepProgressor, m_pTrackCancel)) Cleanup(pMouseCursor, pPlansToDelete,pTable,pPlansTable,pWS,pProgressorDialog); } else { if (!FabricUTILS.DeleteRowsByFIDSet(pPlansTable, pPlansToDelete, m_pStepProgressor, m_pTrackCancel)) Cleanup(pMouseCursor, pPlansToDelete,pTable,pPlansTable, pWS,pProgressorDialog); } } pSchemaEd.ResetReadOnlyFields(esriCadastralFabricTable.esriCFTParcels); m_pEndTime = new TimeClass(); m_pEndTime.SetFromCurrentLocalTime(); ITimeDuration HowLong = m_pEndTime.SubtractTime(m_pStartTime); m_pStepProgressor.Message = "[" + HowLong.Hours.ToString("00") + "h " + HowLong.Minutes.ToString("00") + "m " + HowLong.Seconds.ToString("00") + "s]" + " Saving changes...please wait."; FabricUTILS.StopEditing(pWS); Cleanup(pMouseCursor, pPlansToDelete,pTable,pPlansTable, pWS,pProgressorDialog); } catch (COMException ex) { MessageBox.Show(Convert.ToString(ex.ErrorCode)); Cleanup(pMouseCursor, pPlansToDelete,pTable,null,pWS,null); } }
private void Cleanup(IMouseCursor MouseCursor, IFIDSet PlansFIDSet, ITable pTable, ITable PlansTable, IWorkspace Workspace,IProgressDialog2 pProgressorDialog) { if (pProgressorDialog!=null) pProgressorDialog.HideDialog(); if (MouseCursor!=null) MouseCursor.SetCursor(0); if (m_pStepProgressor!=null) m_pStepProgressor.Hide(); m_pStepProgressor = null; try { Marshal.ReleaseComObject(PlansFIDSet); //garbage collection } catch { } try { Marshal.ReleaseComObject(m_pProgressorDialogFact); //garbage collection } catch { } try { Marshal.ReleaseComObject(m_pTrackCancel); //garbage collection } catch { } if (PlansTable!= null) Marshal.ReleaseComObject(PlansTable); if (m_pCadaFab != null) Marshal.ReleaseComObject(m_pCadaFab); if (pTable != null) Marshal.ReleaseComObject(pTable); if (Workspace!= null) Marshal.ReleaseComObject(Workspace); if (m_pStartTime != null) Marshal.ReleaseComObject(m_pStartTime); if (m_pEndTime != null) Marshal.ReleaseComObject(m_pEndTime); }
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 execute_Utilities = new GPUtilitiesClass(); if (TrackCancel == null) { TrackCancel = new CancelTrackerClass(); } IGPParameter inputOSMParameter = paramvalues.get_Element(in_osmFeatureClass) as IGPParameter; IGPValue inputOSMGPValue = execute_Utilities.UnpackGPValue(inputOSMParameter); IGPParameter tagCollectionParameter = paramvalues.get_Element(in_attributeSelector) as IGPParameter; IGPMultiValue tagCollectionGPValue = execute_Utilities.UnpackGPValue(tagCollectionParameter) as IGPMultiValue; if (tagCollectionGPValue == null) { message.AddError(120048, string.Format(resourceManager.GetString("GPTools_NullPointerParameterType"), tagCollectionParameter.Name)); return; } bool useUpdateCursor = false; IFeatureClass osmFeatureClass = null; ITable osmInputTable = null; IQueryFilter osmQueryFilter = null; try { execute_Utilities.DecodeFeatureLayer(inputOSMGPValue, out osmFeatureClass, out osmQueryFilter); if (osmFeatureClass != null) { if (osmFeatureClass.Extension is IOSMClassExtension) { useUpdateCursor = false; } else { useUpdateCursor = true; } } osmInputTable = osmFeatureClass as ITable; } catch { } try { if (osmInputTable == null) { execute_Utilities.DecodeTableView(inputOSMGPValue, out osmInputTable, out osmQueryFilter); } } catch { } if (osmInputTable == null) { string errorMessage = String.Format(resourceManager.GetString("GPTools_OSMGPAttributeSelecto_unableopentable"), inputOSMGPValue.GetAsText()); message.AddError(120053, errorMessage); return; } // find the field that holds tag binary/xml field int osmTagCollectionFieldIndex = osmInputTable.FindField("osmTags"); // if the Field doesn't exist - wasn't found (index = -1) get out if (osmTagCollectionFieldIndex == -1) { message.AddError(120005, resourceManager.GetString("GPTools_OSMGPAttributeSelector_notagfieldfound")); return; } // check if the tag collection includes the keyword "ALL", if does then we'll need to extract all tags bool extractAll = false; for (int valueIndex = 0; valueIndex < tagCollectionGPValue.Count; valueIndex++) { if (tagCollectionGPValue.get_Value(valueIndex).GetAsText().Equals("ALL")) { extractAll = true; break; } } //if (extractAll) //{ // if (osmTagKeyCodedValues == null) // extractAllTags(ref osmTagKeyCodedValues, osmInputTable, osmQueryFilter, osmTagCollectionFieldIndex, false); // if (osmTagKeyCodedValues == null) // { // message.AddAbort(resourceManager.GetString("GPTools_OSMGPAttributeSelector_Unable2RetrieveTags")); // return; // } // // empty the existing gp multivalue object // tagCollectionGPValue = new GPMultiValueClass(); // // fill the coded domain in gp multivalue object // for (int valueIndex = 0; valueIndex < osmTagKeyCodedValues.CodeCount; valueIndex++) // { // tagCollectionGPValue.AddValue(osmTagKeyCodedValues.get_Value(valueIndex)); // } //} // get an overall feature count as that determines the progress indicator int featureCount = osmInputTable.RowCount(osmQueryFilter); // 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_OSMGPAttributeSelector_progressMessage"); stepProgressor.StepValue = 1; stepProgressor.Show(); } // let's get all the indices of the desired fields // if the field already exists get the index and if it doesn't exist create it Dictionary <string, int> tagsAttributesIndices = new Dictionary <string, int>(); Dictionary <int, int> attributeFieldLength = new Dictionary <int, int>(); IFeatureWorkspaceManage featureWorkspaceManage = ((IDataset)osmInputTable).Workspace as IFeatureWorkspaceManage; String illegalCharacters = String.Empty; ISQLSyntax sqlSyntax = ((IDataset)osmInputTable).Workspace as ISQLSyntax; if (sqlSyntax != null) { illegalCharacters = sqlSyntax.GetInvalidCharacters(); } IFieldsEdit fieldsEdit = osmInputTable.Fields as IFieldsEdit; using (SchemaLockManager lockMgr = new SchemaLockManager(osmInputTable)) { try { string tagKey = String.Empty; ESRI.ArcGIS.Geoprocessing.IGeoProcessor2 gp = new ESRI.ArcGIS.Geoprocessing.GeoProcessorClass(); // if we have explicitly defined tags to extract then go through the list of values now if (extractAll == false) { for (int valueIndex = 0; valueIndex < tagCollectionGPValue.Count; valueIndex++) { if (TrackCancel.Continue() == false) { return; } try { // Check if the input field already exists. string nameofTag = tagCollectionGPValue.get_Value(valueIndex).GetAsText(); tagKey = convert2AttributeFieldName(nameofTag, illegalCharacters); int fieldIndex = osmInputTable.FindField(tagKey); if (fieldIndex < 0) { // generate a new attribute field IFieldEdit fieldEdit = new FieldClass(); fieldEdit.Name_2 = tagKey; fieldEdit.AliasName_2 = nameofTag + resourceManager.GetString("GPTools_OSMGPAttributeSelector_aliasaddition"); fieldEdit.Type_2 = esriFieldType.esriFieldTypeString; fieldEdit.Length_2 = 100; osmInputTable.AddField(fieldEdit); message.AddMessage(string.Format(resourceManager.GetString("GPTools_OSMGPAttributeSelector_addField"), tagKey, nameofTag)); // re-generate the attribute index fieldIndex = osmInputTable.FindField(tagKey); } if (fieldIndex > 0) { tagsAttributesIndices.Add(nameofTag, fieldIndex); attributeFieldLength.Add(fieldIndex, osmInputTable.Fields.get_Field(fieldIndex).Length); } } catch (Exception ex) { // the key is already there, this might result because from multiple upper and lower-case combinations of the same key message.AddWarning(ex.Message + " (" + convert2OSMKey(tagKey, illegalCharacters) + ")"); } } } else { List <string> listofAllTags = extractAllTags(osmInputTable, osmQueryFilter, osmTagCollectionFieldIndex); foreach (string nameOfTag in listofAllTags) { if (TrackCancel.Continue() == false) { return; } try { // Check if the input field already exists. tagKey = convert2AttributeFieldName(nameOfTag, illegalCharacters); int fieldIndex = osmInputTable.FindField(tagKey); if (fieldIndex < 0) { // generate a new attribute field IFieldEdit fieldEdit = new FieldClass(); fieldEdit.Name_2 = tagKey; fieldEdit.AliasName_2 = nameOfTag + resourceManager.GetString("GPTools_OSMGPAttributeSelector_aliasaddition"); fieldEdit.Type_2 = esriFieldType.esriFieldTypeString; fieldEdit.Length_2 = 100; osmInputTable.AddField(fieldEdit); message.AddMessage(string.Format(resourceManager.GetString("GPTools_OSMGPAttributeSelector_addField"), tagKey, nameOfTag)); // re-generate the attribute index fieldIndex = osmInputTable.FindField(tagKey); } if (fieldIndex > 0) { tagsAttributesIndices.Add(nameOfTag, fieldIndex); attributeFieldLength.Add(fieldIndex, osmInputTable.Fields.get_Field(fieldIndex).Length); } } catch (Exception ex) { // the key is already there, this might result because from multiple upper and lower-case combinations of the same key message.AddWarning(ex.Message + " (" + convert2OSMKey(tagKey, illegalCharacters) + ")"); } } } } catch (Exception ex) { message.AddWarning(ex.Message); } } try { execute_Utilities.DecodeFeatureLayer(inputOSMGPValue, out osmFeatureClass, out osmQueryFilter); if (osmFeatureClass != null) { if (osmFeatureClass.Extension is IOSMClassExtension) { useUpdateCursor = false; } else { useUpdateCursor = true; } } osmInputTable = osmFeatureClass as ITable; } catch { } try { if (osmInputTable == null) { execute_Utilities.DecodeTableView(inputOSMGPValue, out osmInputTable, out osmQueryFilter); } } catch { } if (osmInputTable == null) { string errorMessage = String.Format(resourceManager.GetString("GPTools_OSMGPAttributeSelecto_unableopentable"), inputOSMGPValue.GetAsText()); message.AddError(120053, errorMessage); return; } using (ComReleaser comReleaser = new ComReleaser()) { using (SchemaLockManager lockMgr = new SchemaLockManager(osmInputTable)) { // get an update cursor for all the features to process ICursor rowCursor = null; if (useUpdateCursor) { rowCursor = osmInputTable.Update(osmQueryFilter, false); } else { rowCursor = osmInputTable.Search(osmQueryFilter, false); } comReleaser.ManageLifetime(rowCursor); IRow osmRow = null; Dictionary <string, string> tagKeys = new Dictionary <string, string>(); int progessIndex = 0; #if DEBUG message.AddMessage("useUpdateCursor: " + useUpdateCursor.ToString()); #endif // as long as there are features.... while ((osmRow = rowCursor.NextRow()) != null) { // retrieve the tags of the current feature tag[] storedTags = _osmUtility.retrieveOSMTags(osmRow, osmTagCollectionFieldIndex, ((IDataset)osmInputTable).Workspace); bool rowChanged = false; if (storedTags != null) { foreach (tag tagItem in storedTags) { // Check for matching values so we only change a minimum number of rows if (tagsAttributesIndices.ContainsKey(tagItem.k)) { int fieldIndex = tagsAttributesIndices[tagItem.k]; //...then stored the value in the attribute field // ensure that the content of the tag actually does fit into the field length...otherwise do truncate it string tagValue = tagItem.v; int fieldLength = attributeFieldLength[fieldIndex]; if (tagValue.Length > fieldLength) { tagValue = tagValue.Substring(0, fieldLength); } osmRow.set_Value(fieldIndex, tagValue); rowChanged = true; } else { #if DEBUG //message.AddWarning(tagItem.k); #endif } } } storedTags = null; try { if (rowChanged) { if (useUpdateCursor) { rowCursor.UpdateRow(osmRow); } else { // update the feature through the cursor osmRow.Store(); } } progessIndex++; } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.Message); message.AddWarning(ex.Message); } if (osmRow != null) { Marshal.ReleaseComObject(osmRow); } if (stepProgressor != null) { // update the progress UI stepProgressor.Position = progessIndex; } // check for user cancellation (every 100 rows) if ((progessIndex % 100 == 0) && (TrackCancel.Continue() == false)) { return; } } if (stepProgressor != null) { stepProgressor.Hide(); } } } execute_Utilities.ReleaseInternals(); Marshal.ReleaseComObject(execute_Utilities); } catch (Exception ex) { message.AddError(120054, ex.Message); } }
/// <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 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; } }
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); } } }
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 bool GetJobAndLocks(ICadastralFabric Fabric, IFIDSet FIDSetParcels, IStepProgressor StepProgressor) { string sTime = ""; bool bIsUnVersioned = false; 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 selected parcels"; try { Int32 jobId = Fabric.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); } Marshal.ReleaseComObject(pJob); return false; } Marshal.ReleaseComObject(pJob); } //if we're in an enterprise then test for edit locks ICadastralFabricLocks pFabLocks = (ICadastralFabricLocks)Fabric; if (!bIsUnVersioned) { pFabLocks.LockingJob = sTime; ILongArray pLocksInConflict = null; ILongArray pSoftLcksInConflict = null; ILongArray pParcelsToLock = new LongArrayClass(); FIDsetToLongArray(FIDSetParcels, ref pParcelsToLock, StepProgressor); if (StepProgressor != null) StepProgressor.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(); } else { MessageBox.Show(Convert.ToString(pCOMEx.ErrorCode)); } return false; } Marshal.ReleaseComObject(pSoftLcksInConflict); Marshal.ReleaseComObject(pParcelsToLock); Marshal.ReleaseComObject(pLocksInConflict); return true; } return false; }
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; } }
bool FindEmptyPlans(ICadastralFabric Fabric, IStepProgressor StepProgressor, ITrackCancel TrackCancel, out IFIDSet EmptyPlans) { ICursor pPlansCur = null; ICursor pParcelCur = null; IFIDSet pEmptyPlansFIDSet = new FIDSetClass(); List<int> pNonEmptyPlansList = new List<int>(); IDataset pDS=(IDataset)Fabric; IWorkspace pWS = pDS.Workspace; ISQLSyntax pSQLSyntax = (ISQLSyntax)pWS; string sPref = pSQLSyntax.GetSpecialCharacter(esriSQLSpecialCharacters.esriSQL_DelimitedIdentifierPrefix); string sSuff = pSQLSyntax.GetSpecialCharacter(esriSQLSpecialCharacters.esriSQL_DelimitedIdentifierSuffix); try { ITable pPlansTable = Fabric.get_CadastralTable(esriCadastralFabricTable.esriCFTPlans); ITable pParcelsTable = Fabric.get_CadastralTable(esriCadastralFabricTable.esriCFTParcels); ////build a list of ids for all the plans found via parcels //if a Personal GDB then don't try to use DISTINCT if (pWS.Type == esriWorkspaceType.esriLocalDatabaseWorkspace && pWS.PathName.ToLower().EndsWith(".mdb")) { pParcelCur = pParcelsTable.Search(null, false); } else { IQueryFilter pQuF = new QueryFilterClass(); pQuF.SubFields = "PLANID"; IQueryFilterDefinition2 queryFilterDef = (IQueryFilterDefinition2)pQuF; queryFilterDef.PrefixClause = "DISTINCT PLANID"; pParcelCur = pParcelsTable.Search(pQuF, true); //Recycling set to true } Int32 iPlanIDX = pParcelCur.Fields.FindField("PLANID"); IRow pParcRow = pParcelCur.NextRow(); while (pParcRow != null) { //Create a collection of planIDs from Parcels table that we know are not empty Int32 iPlanID = -1; object Attr_val = pParcRow.get_Value(iPlanIDX); if (Attr_val != DBNull.Value) { iPlanID = (Int32)Attr_val; if (iPlanID > -1) { if (!pNonEmptyPlansList.Contains(iPlanID)) pNonEmptyPlansList.Add(iPlanID); } } Marshal.ReleaseComObject(pParcRow); pParcRow = pParcelCur.NextRow(); } if (pParcelCur != null) Marshal.FinalReleaseComObject(pParcelCur); pPlansCur = pPlansTable.Search(null, false); IRow pPlanRow = pPlansCur.NextRow(); while (pPlanRow != null) { bool bFound = false; bFound = pNonEmptyPlansList.Contains(pPlanRow.OID); if (!bFound) //This plan was not found in our parcel-referenced plans { //check if this is the default map plan, so it can be excluded from deletion Int32 iPlanNameIDX = pPlanRow.Fields.FindField("NAME"); string sPlanName = (string)pPlanRow.get_Value(iPlanNameIDX); if (sPlanName.ToUpper() != "<MAP>") pEmptyPlansFIDSet.Add(pPlanRow.OID); } Marshal.ReleaseComObject(pPlanRow); pPlanRow = pPlansCur.NextRow(); } EmptyPlans = pEmptyPlansFIDSet; return true; } catch (Exception ex) { MessageBox.Show(Convert.ToString(ex.Message), "Find Empty Plans"); EmptyPlans = null; return false; } finally { if (pParcelCur != null) { do { } while (Marshal.ReleaseComObject(pParcelCur) > 0); } if (pNonEmptyPlansList != null) { pNonEmptyPlansList.Clear(); pNonEmptyPlansList = null; } if (pParcelCur != null) { do { } while (Marshal.ReleaseComObject(pParcelCur) > 0); } } }
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 (IsBeAdded(tile)) // continue; // _showTiles.Add(tile);*/ // /* 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 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 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 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 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); } }
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 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. }
// 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); }
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; } }
public void Apply(ISchematicInMemoryDiagram inMemoryDiagram, ESRI.ArcGIS.esriSystem.ITrackCancel cancelTracker) { if (m_reducedNodeClassName == "" || inMemoryDiagram == null) { return; } // initialize the schematic rules helper ISchematicRulesHelper rulesHelper = new SchematicRulesHelperClass(); rulesHelper.InitHelper(inMemoryDiagram); rulesHelper.KeepVertices = m_keepVertices; //////////////////////// // get the feature classes processed by the rule ISchematicDiagramClass diagramClass = null; try { diagramClass = inMemoryDiagram.SchematicDiagramClass; } catch { } if (diagramClass == null) { return; } ISchematicDataset schematicDataset = null; try { schematicDataset = diagramClass.SchematicDataset; } catch { } ISchematicElementClassContainer elementclassContainer = (ISchematicElementClassContainer)schematicDataset; if (elementclassContainer == null) { return; } ISchematicElementClass elementClassReducedNode = null; elementClassReducedNode = elementclassContainer.GetSchematicElementClass(m_reducedNodeClassName); ISchematicElementClass elementClassSuperspan = null; elementClassSuperspan = elementclassContainer.GetSchematicElementClass(m_superspanLinkClassName); if (elementClassSuperspan == null || elementClassReducedNode == null) { return; } ISchematicInMemoryFeatureClassContainer featureClassContainer = (ISchematicInMemoryFeatureClassContainer)inMemoryDiagram; if (featureClassContainer == null) { return; } ISchematicInMemoryFeatureClass superspanLinkClass = featureClassContainer.GetSchematicInMemoryFeatureClass(elementClassSuperspan); // ///////////////////////// // fetch the superspan spatial reference IGeoDataset geoDataset = (IGeoDataset)superspanLinkClass; ISpatialReference spatialRef = null; if (geoDataset != null) { spatialRef = geoDataset.SpatialReference; } if (spatialRef == null) { return; } // Retrieve the schematic in memory feature nodes to reduce System.Collections.Generic.Dictionary <string, ISchematicInMemoryFeature> colSchfeatureNode = new Dictionary <string, ISchematicInMemoryFeature>(); // get all feature of parent node class IEnumSchematicInMemoryFeature enumSchematicInMemoryFeature = inMemoryDiagram.GetSchematicInMemoryFeaturesByClass(elementClassReducedNode); // retain only the nodes of degree two RetainNodesDegreeTwo(enumSchematicInMemoryFeature, colSchfeatureNode, rulesHelper); // there would be inserted a SQL query to also filter by attributes IProgressor msgProgressor = null; if (cancelTracker != null) { msgProgressor = cancelTracker.Progressor; IStepProgressor stepProgressor = (IStepProgressor)msgProgressor; if (stepProgressor != null) { stepProgressor.MinRange = 0; stepProgressor.MaxRange = colSchfeatureNode.Count; stepProgressor.StepValue = 1; stepProgressor.Position = 0; stepProgressor.Message = m_description; cancelTracker.Reset(); cancelTracker.Progressor = msgProgressor; stepProgressor.Show(); } } ISchematicInMemoryFeature schFeatureToReduce; foreach (KeyValuePair <string, ISchematicInMemoryFeature> kvp in colSchfeatureNode) { if (cancelTracker != null) { if (cancelTracker.Continue() == false) { break; } } schFeatureToReduce = colSchfeatureNode[kvp.Key]; if (schFeatureToReduce != null) { ReduceNode(rulesHelper, superspanLinkClass, spatialRef, schFeatureToReduce); } } // release memory colSchfeatureNode.Clear(); colSchfeatureNode = null; rulesHelper = null; }
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 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; } }
private void Cleanup(IProgressDialog2 ProgressorDialog, IMouseCursor MouseCursor) { MouseCursor.SetCursor(0); if (!(ProgressorDialog == null)) { ProgressorDialog.HideDialog(); } ProgressorDialog = null; m_pStepProgressor = null; }
// 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(); } }
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 (IsBeAdded(tile)) // continue; // _showTiles.Add(tile);*/ // /* 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); } }
protected override void OnClick() { m_pApp = (IApplication)ArcMap.Application; if (m_pApp == null) //if the app is null then could be running from ArcCatalog m_pApp = (IApplication)ArcCatalog.Application; if (m_pApp == null) { MessageBox.Show("Could not access the application.", "No Application found"); return; } IGxApplication pGXApp = (IGxApplication)m_pApp; stdole.IUnknown pUnk = null; try { pUnk = (stdole.IUnknown)pGXApp.SelectedObject.InternalObjectName.Open(); } catch (COMException ex) { if (ex.ErrorCode == (int)fdoError.FDO_E_DATASET_TYPE_NOT_SUPPORTED_IN_RELEASE || ex.ErrorCode == -2147220944) MessageBox.Show("The dataset is not supported in this release.", "Could not open the dataset"); else MessageBox.Show(ex.ErrorCode.ToString(), "Could not open the dataset"); return; } if (pUnk is ICadastralFabric) m_pCadaFab = (ICadastralFabric)pUnk; else { MessageBox.Show("Please select a parcel fabric and try again.", "Not a parcel fabric"); return; } IMouseCursor pMouseCursor = new MouseCursorClass(); pMouseCursor.SetCursor(2); clsFabricUtils FabricUTILS = new clsFabricUtils(); IProgressDialog2 pProgressorDialog = null; ITable pTable = m_pCadaFab.get_CadastralTable(esriCadastralFabricTable.esriCFTParcels); IDataset pDS = (IDataset)pTable; IWorkspace pWS = pDS.Workspace; bool bIsFileBasedGDB = true; bool bIsUnVersioned = true; FabricUTILS.GetFabricPlatform(pWS, m_pCadaFab, out bIsFileBasedGDB, out bIsUnVersioned); if (!bIsFileBasedGDB && !bIsUnVersioned) { MessageBox.Show("Truncate operates on non-versioned fabrics." + Environment.NewLine + "Please unversion the fabric and try again.", "Tables are versioned"); return; } //Do a Start and Stop editing to make sure truncate it not running within an edit session if (!FabricUTILS.StartEditing(pWS, bIsUnVersioned)) {//if start editing fails then bail Cleanup(pProgressorDialog, pMouseCursor); return; } FabricUTILS.StopEditing(pWS); dlgTruncate pTruncateDialog = new dlgTruncate(); IArray TableArray = new ESRI.ArcGIS.esriSystem.ArrayClass(); pTruncateDialog.TheFabric = m_pCadaFab; pTruncateDialog.TheTableArray = TableArray; //Display the dialog DialogResult pDialogResult = pTruncateDialog.ShowDialog(); if (pDialogResult != DialogResult.OK) { pTruncateDialog = null; if (TableArray != null) { TableArray.RemoveAll(); } return; } m_pProgressorDialogFact = new ProgressDialogFactoryClass(); m_pTrackCancel = new CancelTrackerClass(); m_pStepProgressor = m_pProgressorDialogFact.Create(m_pTrackCancel, m_pApp.hWnd); pProgressorDialog = (IProgressDialog2)m_pStepProgressor; m_pStepProgressor.MinRange = 0; m_pStepProgressor.MaxRange = pTruncateDialog.DropRowCount; m_pStepProgressor.StepValue = 1; pProgressorDialog.Animation = ESRI.ArcGIS.Framework.esriProgressAnimationTypes.esriProgressSpiral; bool bSuccess = false; int iControlRowCount=0; //look in registry to get flag on whether to run truncate on standard tables, or to delete by row. string sDesktopVers = FabricUTILS.GetDesktopVersionFromRegistry(); if (sDesktopVers.Trim() == "") sDesktopVers = "Desktop10.0"; else sDesktopVers = "Desktop" + sDesktopVers; bool bDeleteTablesByRowInsteadOfTruncate = false; string sValues = FabricUTILS.ReadFromRegistry(RegistryHive.CurrentUser, "Software\\ESRI\\" + sDesktopVers + "\\ArcMap\\Cadastral", "AddIn.DeleteFabricRecords_Truncate"); if (sValues.Trim().ToLower() == "deletebytruncateonstandardtables" || bIsFileBasedGDB) bDeleteTablesByRowInsteadOfTruncate = false; if (sValues.Trim().ToLower() == "deletebyrowonstandardtables") bDeleteTablesByRowInsteadOfTruncate = true; if (pTruncateDialog.TruncateControl && !pTruncateDialog.TruncateParcelsLinesPoints) { // get the control point count ITable pControlTable = m_pCadaFab.get_CadastralTable(esriCadastralFabricTable.esriCFTControl); iControlRowCount = pControlTable.RowCount(null); } try { //Work on the table array pTable = null; m_pFIDSet = new FIDSetClass(); for (int i = 0; i <= TableArray.Count - 1; i++) { //if (TableArray.get_Element(i) is ITable) ...redundant { pTable = (ITable)TableArray.get_Element(i); IDataset pDataSet = (IDataset)pTable; //Following code uses the truncate method //*** if (pTable is IFeatureClass || !bDeleteTablesByRowInsteadOfTruncate) { ITableWrite2 pTableWr = (ITableWrite2)pTable; m_pStepProgressor.Message = "Deleting all rows in " + pDataSet.Name; int RowCnt=pTable.RowCount(null); pTableWr.Truncate(); m_pStepProgressor.MaxRange -= RowCnt; //now re-insert the default plan string sName = pDataSet.Name.ToUpper().Trim(); if (sName.EndsWith("_PLANS")) { int idxPlanName = pTable.FindField("Name"); int idxPlanDescription = pTable.FindField("Description"); int idxPlanAngleUnits = pTable.FindField("AngleUnits"); int idxPlanAreaUnits = pTable.FindField("AreaUnits"); int idxPlanDistanceUnits = pTable.FindField("DistanceUnits"); int idxPlanDirectionFormat = pTable.FindField("DirectionFormat"); int idxPlanLineParameters = pTable.FindField("LineParameters"); int idxPlanCombinedGridFactor = pTable.FindField("CombinedGridFactor"); int idxPlanTrueMidBrg = pTable.FindField("TrueMidBrg"); int idxPlanAccuracy = pTable.FindField("Accuracy"); int idxPlanInternalAngles = pTable.FindField("InternalAngles"); ICursor pCur = pTableWr.InsertRows(false); IRowBuffer pRowBuff = pTable.CreateRowBuffer(); double dOneMeterEquals = FabricUTILS.ConvertMetersToFabricUnits(1, m_pCadaFab); bool bIsMetric = (dOneMeterEquals==1); //write category 1 pRowBuff.set_Value(idxPlanName, "<map>"); pRowBuff.set_Value(idxPlanDescription, "System default plan"); pRowBuff.set_Value(idxPlanAngleUnits, 3); // if (bIsMetric) { pRowBuff.set_Value(idxPlanAreaUnits, 5); pRowBuff.set_Value(idxPlanDistanceUnits, 9001); pRowBuff.set_Value(idxPlanDirectionFormat, 1); } else { pRowBuff.set_Value(idxPlanAreaUnits, 4); pRowBuff.set_Value(idxPlanDistanceUnits, 9003); pRowBuff.set_Value(idxPlanDirectionFormat, 4); } pRowBuff.set_Value(idxPlanLineParameters, 4); pRowBuff.set_Value(idxPlanCombinedGridFactor, 1); //pRowBuff.set_Value(idxPlanTrueMidBrg, 1); pRowBuff.set_Value(idxPlanAccuracy, 4); pRowBuff.set_Value(idxPlanInternalAngles, 0); pCur.InsertRow(pRowBuff); pCur.Flush(); if (pRowBuff != null) Marshal.ReleaseComObject(pRowBuff); if (pCur != null) Marshal.ReleaseComObject(pCur); } } } } } catch(COMException ex) { MessageBox.Show(ex.Message + ": " + Convert.ToString(ex.ErrorCode)); Cleanup(pProgressorDialog, pMouseCursor); return; } //do the loop again, this time within the edit transaction and using the delete function for the chosen tables try { //Start an Edit Transaction if (!FabricUTILS.StartEditing(pWS, bIsUnVersioned)) {//if start editing fails then bail Cleanup(pProgressorDialog, pMouseCursor); return; } for (int i = 0; i <= TableArray.Count - 1; i++) { //if (TableArray.get_Element(i) is ITable) { pTable = (ITable)TableArray.get_Element(i); IDataset pDataSet = (IDataset)pTable; if (pTable is IFeatureClass || !bDeleteTablesByRowInsteadOfTruncate) { } else { //The following code is in place to workaround a limitation of truncate for fabric classes //without a shapefield. It uses an alternative method for removing all the rows //with the Delete function. //General note: This method could be used exclusively, without needing the truncate method. //One advantage is that it allows the option to cancel the whole //operation using the cancel tracker. Truncate is faster, but is problematic if //the truncate fails, and leaves a partially deleted fabric. For example, if the //lines table is deleted but the points table truncate fails, the fabric would be in a //corrupt state. //**** m_pFIDSet.SetEmpty(); string sName = pDataSet.Name.ToUpper().Trim(); m_pStepProgressor.Message = "Loading rows from " + pDataSet.Name; if (sName.EndsWith("_PLANS")) {//for Plans table make sure the default plan is not deleted IQueryFilter pQF = new QueryFilterClass(); string sPref; string sSuff; ISQLSyntax pSQLSyntax = (ISQLSyntax)pWS; sPref = pSQLSyntax.GetSpecialCharacter(esriSQLSpecialCharacters.esriSQL_DelimitedIdentifierPrefix); sSuff = pSQLSyntax.GetSpecialCharacter(esriSQLSpecialCharacters.esriSQL_DelimitedIdentifierSuffix); string sFieldName = "NAME"; //pQF.WhereClause = sPref + sFieldName + sSuff + " <> '<map>'"; pQF.WhereClause = sFieldName + " <> '<map>'"; if (!BuildFIDSetFromTable(pTable, pQF, ref m_pFIDSet)) { FabricUTILS.AbortEditing(pWS); Cleanup(pProgressorDialog, pMouseCursor); return; } } else { if (!BuildFIDSetFromTable(pTable, null, ref m_pFIDSet)) { FabricUTILS.AbortEditing(pWS); Cleanup(pProgressorDialog, pMouseCursor); return; } } if (m_pFIDSet.Count() == 0) continue; m_pStepProgressor.Message = "Deleting all rows in " + pDataSet.Name; bSuccess = FabricUTILS.DeleteRowsUnversioned(pWS, pTable, m_pFIDSet, m_pStepProgressor, m_pTrackCancel); if (!bSuccess) { FabricUTILS.AbortEditing(pWS); Cleanup(pProgressorDialog, pMouseCursor); return; } } } } //now need to Fix control-to-point associations if one table was truncated //and the other was not if (pTruncateDialog.TruncateControl && !pTruncateDialog.TruncateParcelsLinesPoints) { IQueryFilter pQF = new QueryFilterClass(); string sPref; string sSuff; ISQLSyntax pSQLSyntax = (ISQLSyntax)pWS; sPref = pSQLSyntax.GetSpecialCharacter(esriSQLSpecialCharacters.esriSQL_DelimitedIdentifierPrefix); sSuff = pSQLSyntax.GetSpecialCharacter(esriSQLSpecialCharacters.esriSQL_DelimitedIdentifierSuffix); ITable PointTable = m_pCadaFab.get_CadastralTable(esriCadastralFabricTable.esriCFTPoints); m_pStepProgressor.Message = "Resetting control associations on points...please wait."; int idxFld = PointTable.FindField("NAME"); string sFieldName = PointTable.Fields.get_Field(idxFld).Name; //NAME IS NOT NULL AND (NAME <>'' OR NAME <>' ') //pQF.WhereClause = sPref + sFieldName + sSuff + " IS NOT NULL AND (" + // sPref + sFieldName + sSuff + "<>'' OR " + sPref + sFieldName + sSuff + " <>' ')"; //pQF.WhereClause = sFieldName + " IS NOT NULL AND (" + sFieldName + "<>'' OR " + sFieldName + " <>' ')"; pQF.WhereClause = sFieldName + " IS NOT NULL AND " + sFieldName + " > ''"; //changed 1/14/2016 ICadastralFabricSchemaEdit2 pSchemaEd = (ICadastralFabricSchemaEdit2)m_pCadaFab; pSchemaEd.ReleaseReadOnlyFields(PointTable, esriCadastralFabricTable.esriCFTPoints); m_pStepProgressor.MinRange = 0; m_pStepProgressor.MaxRange = iControlRowCount; if (!ResetPointAssociations(PointTable, pQF, true, m_pStepProgressor, m_pTrackCancel)) { pSchemaEd.ResetReadOnlyFields(esriCadastralFabricTable.esriCFTPoints); FabricUTILS.AbortEditing(pWS); Cleanup(pProgressorDialog, pMouseCursor); return; } pSchemaEd.ResetReadOnlyFields(esriCadastralFabricTable.esriCFTPoints); } else if (pTruncateDialog.TruncateParcelsLinesPoints && !pTruncateDialog.TruncateControl) { IQueryFilter pQF = new QueryFilterClass(); string sPref; string sSuff; ISQLSyntax pSQLSyntax = (ISQLSyntax)pWS; sPref = pSQLSyntax.GetSpecialCharacter(esriSQLSpecialCharacters.esriSQL_DelimitedIdentifierPrefix); sSuff = pSQLSyntax.GetSpecialCharacter(esriSQLSpecialCharacters.esriSQL_DelimitedIdentifierSuffix); //POINTID >=0 AND POINTID IS NOT NULL m_pStepProgressor.Message = "Resetting associations on control points...please wait."; ITable ControlTable = m_pCadaFab.get_CadastralTable(esriCadastralFabricTable.esriCFTControl); int idxFld = ControlTable.FindField("POINTID"); string sFieldName = ControlTable.Fields.get_Field(idxFld).Name; //pQF.WhereClause = sPref + sFieldName + sSuff + " IS NOT NULL AND " + // sPref + sFieldName + sSuff + " >=0"; pQF.WhereClause = sFieldName + " IS NOT NULL AND " + sFieldName + " >=0"; ICadastralFabricSchemaEdit2 pSchemaEd = (ICadastralFabricSchemaEdit2)m_pCadaFab; pSchemaEd.ReleaseReadOnlyFields(ControlTable, esriCadastralFabricTable.esriCFTControl); if (!FabricUTILS.ResetControlAssociations(ControlTable, null, true)) { pSchemaEd.ResetReadOnlyFields(esriCadastralFabricTable.esriCFTControl); FabricUTILS.AbortEditing(pWS); Cleanup(pProgressorDialog, pMouseCursor); return; } pSchemaEd.ResetReadOnlyFields(esriCadastralFabricTable.esriCFTControl); } //now need to re-assign default accuracy table values, if the option was checked if (pTruncateDialog.ResetAccuracyTableDefaults) { double dCat1 = FabricUTILS.ConvertMetersToFabricUnits(0.001, m_pCadaFab); double dCat2 = FabricUTILS.ConvertMetersToFabricUnits(0.01, m_pCadaFab); double dCat3 = FabricUTILS.ConvertMetersToFabricUnits(0.02, m_pCadaFab); double dCat4 = FabricUTILS.ConvertMetersToFabricUnits(0.05, m_pCadaFab); double dCat5 = FabricUTILS.ConvertMetersToFabricUnits(0.2, m_pCadaFab); double dCat6 = FabricUTILS.ConvertMetersToFabricUnits(1, m_pCadaFab); double dCat7 = FabricUTILS.ConvertMetersToFabricUnits(10, m_pCadaFab); ITable pAccTable = m_pCadaFab.get_CadastralTable(esriCadastralFabricTable.esriCFTAccuracy); int idxBrgSD = pAccTable.FindField("BrgSD"); int idxDistSD = pAccTable.FindField("DistSD"); int idxPPM = pAccTable.FindField("PPM"); int idxCategory = pAccTable.FindField("Category"); int idxDescription = pAccTable.FindField("Description"); ITableWrite2 pTableWr = (ITableWrite2)pAccTable; ICursor pCur = pTableWr.InsertRows(false); IRowBuffer pRowBuff = pAccTable.CreateRowBuffer(); //write category 1 pRowBuff.set_Value(idxCategory, 1); pRowBuff.set_Value(idxBrgSD, 5); pRowBuff.set_Value(idxDistSD, dCat1); pRowBuff.set_Value(idxPPM, 5); pRowBuff.set_Value(idxDescription, "1 - Highest"); pCur.InsertRow(pRowBuff); //write category 2 pRowBuff.set_Value(idxCategory, 2); pRowBuff.set_Value(idxBrgSD, 30); pRowBuff.set_Value(idxDistSD, dCat2); pRowBuff.set_Value(idxPPM, 25); pRowBuff.set_Value(idxDescription, "2 - After 1980"); pCur.InsertRow(pRowBuff); //write category 3 pRowBuff.set_Value(idxCategory, 3); pRowBuff.set_Value(idxBrgSD, 60); pRowBuff.set_Value(idxDistSD, dCat3); pRowBuff.set_Value(idxPPM, 50); pRowBuff.set_Value(idxDescription, "3 - 1908 to 1980"); pCur.InsertRow(pRowBuff); //write category 4 pRowBuff.set_Value(idxCategory, 4); pRowBuff.set_Value(idxBrgSD, 120); pRowBuff.set_Value(idxDistSD, dCat4); pRowBuff.set_Value(idxPPM, 125); pRowBuff.set_Value(idxDescription, "4 - 1881 to 1907"); pCur.InsertRow(pRowBuff); //write category 5 pRowBuff.set_Value(idxCategory, 5); pRowBuff.set_Value(idxBrgSD, 300); pRowBuff.set_Value(idxDistSD, dCat5); pRowBuff.set_Value(idxPPM, 125); pRowBuff.set_Value(idxDescription, "5 - Before 1881"); pCur.InsertRow(pRowBuff); //write category 6 pRowBuff.set_Value(idxCategory, 6); pRowBuff.set_Value(idxBrgSD, 3600); pRowBuff.set_Value(idxDistSD, dCat6); pRowBuff.set_Value(idxPPM, 1000); pRowBuff.set_Value(idxDescription, "6 - 1800"); pCur.InsertRow(pRowBuff); //write category 7 pRowBuff.set_Value(idxCategory, 7); pRowBuff.set_Value(idxBrgSD, 6000); pRowBuff.set_Value(idxDistSD, dCat7); pRowBuff.set_Value(idxPPM, 5000); pRowBuff.set_Value(idxDescription, "7 - Lowest"); pCur.InsertRow(pRowBuff); pCur.Flush(); if (pRowBuff != null) Marshal.ReleaseComObject(pRowBuff); if (pCur != null) Marshal.ReleaseComObject(pCur); } //now need to cleanup the IDSequence table if ALL the tables were truncated if(pTruncateDialog.TruncateControl&& pTruncateDialog.TruncateParcelsLinesPoints && pTruncateDialog.TruncateJobs && pTruncateDialog.TruncateAdjustments) { IWorkspace2 pWS2=(IWorkspace2)pWS; IDataset TheFabricDS=(IDataset)m_pCadaFab; string sFabricName=TheFabricDS.Name; string sName = sFabricName + "_IDSequencer"; bool bExists=pWS2.get_NameExists(esriDatasetType.esriDTTable, sName); IFeatureWorkspace pFWS=(IFeatureWorkspace)pWS; ITable pSequencerTable; if (bExists) { pSequencerTable = pFWS.OpenTable(sName); IFIDSet pFIDSet= new FIDSetClass(); if (BuildFIDSetFromTable(pSequencerTable, null, ref pFIDSet)) FabricUTILS.DeleteRowsUnversioned(pWS, pSequencerTable, pFIDSet, null, null); } } Cleanup(pProgressorDialog, pMouseCursor); if (TableArray != null) { TableArray.RemoveAll(); } FabricUTILS.StopEditing(pWS); } catch (Exception ex) { FabricUTILS.AbortEditing(pWS); Cleanup(pProgressorDialog, pMouseCursor); MessageBox.Show(Convert.ToString(ex.Message)); } }
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(); } }
private IProgressDialog2 ShowProgressIndicator(string strTitle, int iMax, int iStepValue) { IProgressDialogFactory pProgressDlgFact; IProgressDialog2 pProgressDialog; ITrackCancel pTrackCancel; //'Show a progress dialog while we cycle through the features pTrackCancel = new CancelTrackerClass(); pProgressDlgFact = new ProgressDialogFactoryClass(); pProgressDialog = (IProgressDialog2)pProgressDlgFact.Create(pTrackCancel, 0); pProgressDialog.CancelEnabled = false; pProgressDialog.Title = strTitle; pProgressDialog.Animation = esriProgressAnimationTypes.esriProgressGlobe; //'Set the properties of the Step Progressor pStepProgressor = (IStepProgressor)pProgressDialog; pStepProgressor.MinRange = 0; pStepProgressor.MaxRange = iMax; pStepProgressor.StepValue = iStepValue; return pProgressDialog; }
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 } }
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 execute_Utilities = new GPUtilitiesClass(); OSMUtility osmUtility = new OSMUtility(); if (TrackCancel == null) { TrackCancel = new CancelTrackerClass(); } IGPParameter inputOSMParameter = paramvalues.get_Element(in_osmFeatureClassNumber) as IGPParameter; IGPValue inputOSMGPValue = execute_Utilities.UnpackGPValue(inputOSMParameter); IGPParameter tagFieldsParameter = paramvalues.get_Element(in_attributeSelectorNumber) as IGPParameter; IGPMultiValue tagCollectionGPValue = execute_Utilities.UnpackGPValue(tagFieldsParameter) as IGPMultiValue; if (tagCollectionGPValue == null) { message.AddError(120048, string.Format(resourceManager.GetString("GPTools_NullPointerParameterType"), tagFieldsParameter.Name)); return; } IFeatureClass osmFeatureClass = null; ITable osmInputTable = null; IQueryFilter osmQueryFilter = null; try { execute_Utilities.DecodeFeatureLayer(inputOSMGPValue, out osmFeatureClass, out osmQueryFilter); osmInputTable = osmFeatureClass as ITable; } catch { } try { if (osmInputTable == null) { execute_Utilities.DecodeTableView(inputOSMGPValue, out osmInputTable, out osmQueryFilter); } } catch { } if (osmInputTable == null) { return; } // find the field that holds tag binary/xml field int osmTagCollectionFieldIndex = osmInputTable.FindField("osmTags"); // if the Field doesn't exist - wasn't found (index = -1) get out if (osmTagCollectionFieldIndex == -1) { message.AddError(120005, resourceManager.GetString("GPTools_OSMGPAttributeSelector_notagfieldfound")); return; } // set up the progress indicator IStepProgressor stepProgressor = TrackCancel as IStepProgressor; if (stepProgressor != null) { int featureCount = osmInputTable.RowCount(osmQueryFilter); stepProgressor.MinRange = 0; stepProgressor.MaxRange = featureCount; stepProgressor.Position = 0; stepProgressor.Message = resourceManager.GetString("GPTools_OSMGPCombineAttributes_progressMessage"); stepProgressor.StepValue = 1; stepProgressor.Show(); } String illegalCharacters = String.Empty; ISQLSyntax sqlSyntax = ((IDataset)osmInputTable).Workspace as ISQLSyntax; if (sqlSyntax != null) { illegalCharacters = sqlSyntax.GetInvalidCharacters(); } // establish the list of field indexes only once Dictionary <string, int> fieldIndexes = new Dictionary <string, int>(); for (int selectedGPValueIndex = 0; selectedGPValueIndex < tagCollectionGPValue.Count; selectedGPValueIndex++) { // find the field index int fieldIndex = osmInputTable.FindField(tagCollectionGPValue.get_Value(selectedGPValueIndex).GetAsText()); if (fieldIndex != -1) { string tagKeyName = osmInputTable.Fields.get_Field(fieldIndex).Name; tagKeyName = OSMToolHelper.convert2OSMKey(tagKeyName, illegalCharacters); fieldIndexes.Add(tagKeyName, fieldIndex); } } ICursor updateCursor = null; IRow osmRow = null; using (ComReleaser comReleaser = new ComReleaser()) { updateCursor = osmInputTable.Update(osmQueryFilter, false); comReleaser.ManageLifetime(updateCursor); osmRow = updateCursor.NextRow(); int progressIndex = 0; while (osmRow != null) { // get the current tag collection from the row ESRI.ArcGIS.OSM.OSMClassExtension.tag[] osmTags = osmUtility.retrieveOSMTags(osmRow, osmTagCollectionFieldIndex, ((IDataset)osmInputTable).Workspace); Dictionary <string, string> tagsDictionary = new Dictionary <string, string>(); for (int tagIndex = 0; tagIndex < osmTags.Length; tagIndex++) { tagsDictionary.Add(osmTags[tagIndex].k, osmTags[tagIndex].v); } // look if the tag needs to be updated or added bool tagsUpdated = false; foreach (var fieldItem in fieldIndexes) { object fldValue = osmRow.get_Value(fieldItem.Value); if (fldValue != System.DBNull.Value) { if (tagsDictionary.ContainsKey(fieldItem.Key)) { if (!tagsDictionary[fieldItem.Key].Equals(fldValue)) { tagsDictionary[fieldItem.Key] = Convert.ToString(fldValue); tagsUpdated = true; } } else { tagsDictionary.Add(fieldItem.Key, Convert.ToString(fldValue)); tagsUpdated = true; } } else { if (tagsDictionary.ContainsKey(fieldItem.Key)) { tagsDictionary.Remove(fieldItem.Key); tagsUpdated = true; } } } if (tagsUpdated) { List <ESRI.ArcGIS.OSM.OSMClassExtension.tag> updatedTags = new List <ESRI.ArcGIS.OSM.OSMClassExtension.tag>(); foreach (var tagItem in tagsDictionary) { ESRI.ArcGIS.OSM.OSMClassExtension.tag newTag = new ESRI.ArcGIS.OSM.OSMClassExtension.tag(); newTag.k = tagItem.Key; newTag.v = tagItem.Value; updatedTags.Add(newTag); } // insert the tags back into the collection field if (updatedTags.Count != 0) { osmUtility.insertOSMTags(osmTagCollectionFieldIndex, osmRow, updatedTags.ToArray(), ((IDataset)osmInputTable).Workspace); updateCursor.UpdateRow(osmRow); } } progressIndex++; if (stepProgressor != null) { stepProgressor.Position = progressIndex; } if (osmRow != null) { Marshal.ReleaseComObject(osmRow); } osmRow = updateCursor.NextRow(); } if (stepProgressor != null) { stepProgressor.Hide(); } } } catch (Exception ex) { message.AddError(120007, ex.Message); } }
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); } }
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 } }
protected override void OnClick() { m_pApp = (IApplication)ArcMap.Application; if (m_pApp == null) { //if the app is null then could be running from ArcCatalog m_pApp = (IApplication)ArcCatalog.Application; } if (m_pApp == null) { MessageBox.Show("Could not access the application.", "No Application found"); return; } IGxApplication pGXApp = (IGxApplication)m_pApp; stdole.IUnknown pUnk = null; try { pUnk = (stdole.IUnknown)pGXApp.SelectedObject.InternalObjectName.Open(); } catch (COMException ex) { if (ex.ErrorCode == (int)fdoError.FDO_E_DATASET_TYPE_NOT_SUPPORTED_IN_RELEASE || ex.ErrorCode == -2147220944) { MessageBox.Show("The dataset is not supported in this release.", "Could not open the dataset"); } else { MessageBox.Show(ex.ErrorCode.ToString(), "Could not open the dataset"); } return; } if (pUnk is ICadastralFabric) { m_pCadaFab = (ICadastralFabric)pUnk; } else { MessageBox.Show("Please select a parcel fabric and try again.", "Not a parcel fabric"); return; } IMouseCursor pMouseCursor = new MouseCursorClass(); pMouseCursor.SetCursor(2); clsFabricUtils FabricUTILS = new clsFabricUtils(); IProgressDialog2 pProgressorDialog = null; ITable pTable = m_pCadaFab.get_CadastralTable(esriCadastralFabricTable.esriCFTParcels); IDataset pDS = (IDataset)pTable; IWorkspace pWS = pDS.Workspace; bool bIsFileBasedGDB = true; bool bIsUnVersioned = true; FabricUTILS.GetFabricPlatform(pWS, m_pCadaFab, out bIsFileBasedGDB, out bIsUnVersioned); if (!bIsFileBasedGDB && !bIsUnVersioned) { MessageBox.Show("Truncate operates on non-versioned fabrics." + Environment.NewLine + "Please unversion the fabric and try again.", "Tables are versioned"); return; } //Do a Start and Stop editing to make sure truncate it not running within an edit session if (!FabricUTILS.StartEditing(pWS, bIsUnVersioned)) {//if start editing fails then bail Cleanup(pProgressorDialog, pMouseCursor); return; } FabricUTILS.StopEditing(pWS); dlgTruncate pTruncateDialog = new dlgTruncate(); IArray TableArray = new ESRI.ArcGIS.esriSystem.ArrayClass(); pTruncateDialog.TheFabric = m_pCadaFab; pTruncateDialog.TheTableArray = TableArray; //Display the dialog DialogResult pDialogResult = pTruncateDialog.ShowDialog(); if (pDialogResult != DialogResult.OK) { pTruncateDialog = null; if (TableArray != null) { TableArray.RemoveAll(); } return; } m_pProgressorDialogFact = new ProgressDialogFactoryClass(); m_pTrackCancel = new CancelTrackerClass(); m_pStepProgressor = m_pProgressorDialogFact.Create(m_pTrackCancel, m_pApp.hWnd); pProgressorDialog = (IProgressDialog2)m_pStepProgressor; m_pStepProgressor.MinRange = 0; m_pStepProgressor.MaxRange = pTruncateDialog.DropRowCount; m_pStepProgressor.StepValue = 1; pProgressorDialog.Animation = ESRI.ArcGIS.Framework.esriProgressAnimationTypes.esriProgressSpiral; bool bSuccess = false; int iControlRowCount = 0; //look in registry to get flag on whether to run truncate on standard tables, or to delete by row. string sDesktopVers = FabricUTILS.GetDesktopVersionFromRegistry(); if (sDesktopVers.Trim() == "") { sDesktopVers = "Desktop10.0"; } else { sDesktopVers = "Desktop" + sDesktopVers; } bool bDeleteTablesByRowInsteadOfTruncate = false; string sValues = FabricUTILS.ReadFromRegistry(RegistryHive.CurrentUser, "Software\\ESRI\\" + sDesktopVers + "\\ArcMap\\Cadastral", "AddIn.DeleteFabricRecords_Truncate"); if (sValues.Trim().ToLower() == "deletebytruncateonstandardtables" || bIsFileBasedGDB) { bDeleteTablesByRowInsteadOfTruncate = false; } if (sValues.Trim().ToLower() == "deletebyrowonstandardtables") { bDeleteTablesByRowInsteadOfTruncate = true; } if (pTruncateDialog.TruncateControl && !pTruncateDialog.TruncateParcelsLinesPoints) { // get the control point count ITable pControlTable = m_pCadaFab.get_CadastralTable(esriCadastralFabricTable.esriCFTControl); iControlRowCount = pControlTable.RowCount(null); } try { //Work on the table array pTable = null; m_pFIDSet = new FIDSetClass(); for (int i = 0; i <= TableArray.Count - 1; i++) { //if (TableArray.get_Element(i) is ITable) ...redundant { pTable = (ITable)TableArray.get_Element(i); IDataset pDataSet = (IDataset)pTable; //Following code uses the truncate method //*** if (pTable is IFeatureClass || !bDeleteTablesByRowInsteadOfTruncate) { ITableWrite2 pTableWr = (ITableWrite2)pTable; m_pStepProgressor.Message = "Deleting all rows in " + pDataSet.Name; int RowCnt = pTable.RowCount(null); pTableWr.Truncate(); m_pStepProgressor.MaxRange -= RowCnt; //now re-insert the default plan string sName = pDataSet.Name.ToUpper().Trim(); if (sName.EndsWith("_PLANS")) { int idxPlanName = pTable.FindField("Name"); int idxPlanDescription = pTable.FindField("Description"); int idxPlanAngleUnits = pTable.FindField("AngleUnits"); int idxPlanAreaUnits = pTable.FindField("AreaUnits"); int idxPlanDistanceUnits = pTable.FindField("DistanceUnits"); int idxPlanDirectionFormat = pTable.FindField("DirectionFormat"); int idxPlanLineParameters = pTable.FindField("LineParameters"); int idxPlanCombinedGridFactor = pTable.FindField("CombinedGridFactor"); int idxPlanTrueMidBrg = pTable.FindField("TrueMidBrg"); int idxPlanAccuracy = pTable.FindField("Accuracy"); int idxPlanInternalAngles = pTable.FindField("InternalAngles"); ICursor pCur = pTableWr.InsertRows(false); IRowBuffer pRowBuff = pTable.CreateRowBuffer(); double dOneMeterEquals = FabricUTILS.ConvertMetersToFabricUnits(1, m_pCadaFab); bool bIsMetric = (dOneMeterEquals == 1); //write category 1 pRowBuff.set_Value(idxPlanName, "<map>"); pRowBuff.set_Value(idxPlanDescription, "System default plan"); pRowBuff.set_Value(idxPlanAngleUnits, 3); // if (bIsMetric) { pRowBuff.set_Value(idxPlanAreaUnits, 5); pRowBuff.set_Value(idxPlanDistanceUnits, 9001); pRowBuff.set_Value(idxPlanDirectionFormat, 1); } else { pRowBuff.set_Value(idxPlanAreaUnits, 4); pRowBuff.set_Value(idxPlanDistanceUnits, 9003); pRowBuff.set_Value(idxPlanDirectionFormat, 4); } pRowBuff.set_Value(idxPlanLineParameters, 4); pRowBuff.set_Value(idxPlanCombinedGridFactor, 1); //pRowBuff.set_Value(idxPlanTrueMidBrg, 1); pRowBuff.set_Value(idxPlanAccuracy, 4); pRowBuff.set_Value(idxPlanInternalAngles, 0); pCur.InsertRow(pRowBuff); pCur.Flush(); if (pRowBuff != null) { Marshal.ReleaseComObject(pRowBuff); } if (pCur != null) { Marshal.ReleaseComObject(pCur); } } } } } } catch (COMException ex) { MessageBox.Show(ex.Message + ": " + Convert.ToString(ex.ErrorCode)); Cleanup(pProgressorDialog, pMouseCursor); return; } //do the loop again, this time within the edit transaction and using the delete function for the chosen tables try { //Start an Edit Transaction if (!FabricUTILS.StartEditing(pWS, bIsUnVersioned)) {//if start editing fails then bail Cleanup(pProgressorDialog, pMouseCursor); return; } for (int i = 0; i <= TableArray.Count - 1; i++) { //if (TableArray.get_Element(i) is ITable) { pTable = (ITable)TableArray.get_Element(i); IDataset pDataSet = (IDataset)pTable; if (pTable is IFeatureClass || !bDeleteTablesByRowInsteadOfTruncate) { } else { //The following code is in place to workaround a limitation of truncate for fabric classes //without a shapefield. It uses an alternative method for removing all the rows //with the Delete function. //General note: This method could be used exclusively, without needing the truncate method. //One advantage is that it allows the option to cancel the whole //operation using the cancel tracker. Truncate is faster, but is problematic if //the truncate fails, and leaves a partially deleted fabric. For example, if the //lines table is deleted but the points table truncate fails, the fabric would be in a //corrupt state. //**** m_pFIDSet.SetEmpty(); string sName = pDataSet.Name.ToUpper().Trim(); m_pStepProgressor.Message = "Loading rows from " + pDataSet.Name; if (sName.EndsWith("_PLANS")) {//for Plans table make sure the default plan is not deleted IQueryFilter pQF = new QueryFilterClass(); string sPref; string sSuff; ISQLSyntax pSQLSyntax = (ISQLSyntax)pWS; sPref = pSQLSyntax.GetSpecialCharacter(esriSQLSpecialCharacters.esriSQL_DelimitedIdentifierPrefix); sSuff = pSQLSyntax.GetSpecialCharacter(esriSQLSpecialCharacters.esriSQL_DelimitedIdentifierSuffix); string sFieldName = "NAME"; //pQF.WhereClause = sPref + sFieldName + sSuff + " <> '<map>'"; pQF.WhereClause = sFieldName + " <> '<map>'"; if (!BuildFIDSetFromTable(pTable, pQF, ref m_pFIDSet)) { FabricUTILS.AbortEditing(pWS); Cleanup(pProgressorDialog, pMouseCursor); return; } } else { if (!BuildFIDSetFromTable(pTable, null, ref m_pFIDSet)) { FabricUTILS.AbortEditing(pWS); Cleanup(pProgressorDialog, pMouseCursor); return; } } if (m_pFIDSet.Count() == 0) { continue; } m_pStepProgressor.Message = "Deleting all rows in " + pDataSet.Name; bSuccess = FabricUTILS.DeleteRowsUnversioned(pWS, pTable, m_pFIDSet, m_pStepProgressor, m_pTrackCancel); if (!bSuccess) { FabricUTILS.AbortEditing(pWS); Cleanup(pProgressorDialog, pMouseCursor); return; } } } } //now need to Fix control-to-point associations if one table was truncated //and the other was not if (pTruncateDialog.TruncateControl && !pTruncateDialog.TruncateParcelsLinesPoints) { IQueryFilter pQF = new QueryFilterClass(); string sPref; string sSuff; ISQLSyntax pSQLSyntax = (ISQLSyntax)pWS; sPref = pSQLSyntax.GetSpecialCharacter(esriSQLSpecialCharacters.esriSQL_DelimitedIdentifierPrefix); sSuff = pSQLSyntax.GetSpecialCharacter(esriSQLSpecialCharacters.esriSQL_DelimitedIdentifierSuffix); ITable PointTable = m_pCadaFab.get_CadastralTable(esriCadastralFabricTable.esriCFTPoints); m_pStepProgressor.Message = "Resetting control associations on points...please wait."; int idxFld = PointTable.FindField("NAME"); string sFieldName = PointTable.Fields.get_Field(idxFld).Name; //NAME IS NOT NULL AND (NAME <>'' OR NAME <>' ') //pQF.WhereClause = sPref + sFieldName + sSuff + " IS NOT NULL AND (" + // sPref + sFieldName + sSuff + "<>'' OR " + sPref + sFieldName + sSuff + " <>' ')"; //pQF.WhereClause = sFieldName + " IS NOT NULL AND (" + sFieldName + "<>'' OR " + sFieldName + " <>' ')"; pQF.WhereClause = sFieldName + " IS NOT NULL AND " + sFieldName + " > ''"; //changed 1/14/2016 ICadastralFabricSchemaEdit2 pSchemaEd = (ICadastralFabricSchemaEdit2)m_pCadaFab; pSchemaEd.ReleaseReadOnlyFields(PointTable, esriCadastralFabricTable.esriCFTPoints); m_pStepProgressor.MinRange = 0; m_pStepProgressor.MaxRange = iControlRowCount; if (!ResetPointAssociations(PointTable, pQF, true, m_pStepProgressor, m_pTrackCancel)) { pSchemaEd.ResetReadOnlyFields(esriCadastralFabricTable.esriCFTPoints); FabricUTILS.AbortEditing(pWS); Cleanup(pProgressorDialog, pMouseCursor); return; } pSchemaEd.ResetReadOnlyFields(esriCadastralFabricTable.esriCFTPoints); } else if (pTruncateDialog.TruncateParcelsLinesPoints && !pTruncateDialog.TruncateControl) { IQueryFilter pQF = new QueryFilterClass(); string sPref; string sSuff; ISQLSyntax pSQLSyntax = (ISQLSyntax)pWS; sPref = pSQLSyntax.GetSpecialCharacter(esriSQLSpecialCharacters.esriSQL_DelimitedIdentifierPrefix); sSuff = pSQLSyntax.GetSpecialCharacter(esriSQLSpecialCharacters.esriSQL_DelimitedIdentifierSuffix); //POINTID >=0 AND POINTID IS NOT NULL m_pStepProgressor.Message = "Resetting associations on control points...please wait."; ITable ControlTable = m_pCadaFab.get_CadastralTable(esriCadastralFabricTable.esriCFTControl); int idxFld = ControlTable.FindField("POINTID"); string sFieldName = ControlTable.Fields.get_Field(idxFld).Name; //pQF.WhereClause = sPref + sFieldName + sSuff + " IS NOT NULL AND " + // sPref + sFieldName + sSuff + " >=0"; pQF.WhereClause = sFieldName + " IS NOT NULL AND " + sFieldName + " >=0"; ICadastralFabricSchemaEdit2 pSchemaEd = (ICadastralFabricSchemaEdit2)m_pCadaFab; pSchemaEd.ReleaseReadOnlyFields(ControlTable, esriCadastralFabricTable.esriCFTControl); if (!FabricUTILS.ResetControlAssociations(ControlTable, null, true)) { pSchemaEd.ResetReadOnlyFields(esriCadastralFabricTable.esriCFTControl); FabricUTILS.AbortEditing(pWS); Cleanup(pProgressorDialog, pMouseCursor); return; } pSchemaEd.ResetReadOnlyFields(esriCadastralFabricTable.esriCFTControl); } //now need to re-assign default accuracy table values, if the option was checked if (pTruncateDialog.ResetAccuracyTableDefaults) { double dCat1 = FabricUTILS.ConvertMetersToFabricUnits(0.001, m_pCadaFab); double dCat2 = FabricUTILS.ConvertMetersToFabricUnits(0.01, m_pCadaFab); double dCat3 = FabricUTILS.ConvertMetersToFabricUnits(0.02, m_pCadaFab); double dCat4 = FabricUTILS.ConvertMetersToFabricUnits(0.05, m_pCadaFab); double dCat5 = FabricUTILS.ConvertMetersToFabricUnits(0.2, m_pCadaFab); double dCat6 = FabricUTILS.ConvertMetersToFabricUnits(1, m_pCadaFab); double dCat7 = FabricUTILS.ConvertMetersToFabricUnits(10, m_pCadaFab); ITable pAccTable = m_pCadaFab.get_CadastralTable(esriCadastralFabricTable.esriCFTAccuracy); int idxBrgSD = pAccTable.FindField("BrgSD"); int idxDistSD = pAccTable.FindField("DistSD"); int idxPPM = pAccTable.FindField("PPM"); int idxCategory = pAccTable.FindField("Category"); int idxDescription = pAccTable.FindField("Description"); ITableWrite2 pTableWr = (ITableWrite2)pAccTable; ICursor pCur = pTableWr.InsertRows(false); IRowBuffer pRowBuff = pAccTable.CreateRowBuffer(); //write category 1 pRowBuff.set_Value(idxCategory, 1); pRowBuff.set_Value(idxBrgSD, 5); pRowBuff.set_Value(idxDistSD, dCat1); pRowBuff.set_Value(idxPPM, 5); pRowBuff.set_Value(idxDescription, "1 - Highest"); pCur.InsertRow(pRowBuff); //write category 2 pRowBuff.set_Value(idxCategory, 2); pRowBuff.set_Value(idxBrgSD, 30); pRowBuff.set_Value(idxDistSD, dCat2); pRowBuff.set_Value(idxPPM, 25); pRowBuff.set_Value(idxDescription, "2 - After 1980"); pCur.InsertRow(pRowBuff); //write category 3 pRowBuff.set_Value(idxCategory, 3); pRowBuff.set_Value(idxBrgSD, 60); pRowBuff.set_Value(idxDistSD, dCat3); pRowBuff.set_Value(idxPPM, 50); pRowBuff.set_Value(idxDescription, "3 - 1908 to 1980"); pCur.InsertRow(pRowBuff); //write category 4 pRowBuff.set_Value(idxCategory, 4); pRowBuff.set_Value(idxBrgSD, 120); pRowBuff.set_Value(idxDistSD, dCat4); pRowBuff.set_Value(idxPPM, 125); pRowBuff.set_Value(idxDescription, "4 - 1881 to 1907"); pCur.InsertRow(pRowBuff); //write category 5 pRowBuff.set_Value(idxCategory, 5); pRowBuff.set_Value(idxBrgSD, 300); pRowBuff.set_Value(idxDistSD, dCat5); pRowBuff.set_Value(idxPPM, 125); pRowBuff.set_Value(idxDescription, "5 - Before 1881"); pCur.InsertRow(pRowBuff); //write category 6 pRowBuff.set_Value(idxCategory, 6); pRowBuff.set_Value(idxBrgSD, 3600); pRowBuff.set_Value(idxDistSD, dCat6); pRowBuff.set_Value(idxPPM, 1000); pRowBuff.set_Value(idxDescription, "6 - 1800"); pCur.InsertRow(pRowBuff); //write category 7 pRowBuff.set_Value(idxCategory, 7); pRowBuff.set_Value(idxBrgSD, 6000); pRowBuff.set_Value(idxDistSD, dCat7); pRowBuff.set_Value(idxPPM, 5000); pRowBuff.set_Value(idxDescription, "7 - Lowest"); pCur.InsertRow(pRowBuff); pCur.Flush(); if (pRowBuff != null) { Marshal.ReleaseComObject(pRowBuff); } if (pCur != null) { Marshal.ReleaseComObject(pCur); } } //now need to cleanup the IDSequence table if ALL the tables were truncated if (pTruncateDialog.TruncateControl && pTruncateDialog.TruncateParcelsLinesPoints && pTruncateDialog.TruncateJobs && pTruncateDialog.TruncateAdjustments) { IWorkspace2 pWS2 = (IWorkspace2)pWS; IDataset TheFabricDS = (IDataset)m_pCadaFab; string sFabricName = TheFabricDS.Name; string sName = sFabricName + "_IDSequencer"; bool bExists = pWS2.get_NameExists(esriDatasetType.esriDTTable, sName); IFeatureWorkspace pFWS = (IFeatureWorkspace)pWS; ITable pSequencerTable; if (bExists) { pSequencerTable = pFWS.OpenTable(sName); IFIDSet pFIDSet = new FIDSetClass(); if (BuildFIDSetFromTable(pSequencerTable, null, ref pFIDSet)) { FabricUTILS.DeleteRowsUnversioned(pWS, pSequencerTable, pFIDSet, null, null); } } } Cleanup(pProgressorDialog, pMouseCursor); if (TableArray != null) { TableArray.RemoveAll(); } FabricUTILS.StopEditing(pWS); } catch (Exception ex) { FabricUTILS.AbortEditing(pWS); Cleanup(pProgressorDialog, pMouseCursor); MessageBox.Show(Convert.ToString(ex.Message)); } }
/// <summary> /// Occurs when this command is clicked /// </summary> public override void OnClick() { try { if (m_application == null) { return; } IDocument document = m_application.Document; ISxDocument sxDocument = (ISxDocument)(document); if (sxDocument != null) { m_scene = sxDocument.Scene; } if (m_scene == null) { return; } activeView = m_scene as IActiveView; //有图层选图层 if (m_scene.LayerCount == 0) { return; } //选择基准面 if (Common.SelectLayer(m_scene.Layers, out SelectedLyrIndex, true, "选择自定义表面") == false) { return; } //QI IRasterLayer baseRasterLayer = m_scene.Layer[SelectedLyrIndex[0]] as IRasterLayer; //不管选多少个只选第一个 if (baseRasterLayer == null) { throw new ArgumentNullException("自定义表面RasterLayer转换失败,为空。"); } IRaster raster = baseRasterLayer.Raster; if (raster == null) { throw new ArgumentNullException("自定义表面Raster转换失败,为空。"); } IRasterSurface rasterSurface = new RasterSurfaceClass(); rasterSurface.PutRaster(raster, 0); ISurface surface = rasterSurface as ISurface; //选择图层 if (Common.SelectLayer(m_scene.Layers, out SelectedLyrIndex, false, "选择要进行偏移的图层") == false) { return; } //选择倍数 NumSelect MultiNS = new NumSelect("输入夸大倍数", true); if (MultiNS.ShowDialog() != DialogResult.OK) { return; } double Multiplier = MultiNS.Result; //选择偏移量 NumSelect NS = new NumSelect(); if (NS.ShowDialog() != DialogResult.OK) { return; } double Offset = NS.Result; bool DisableCache = NS.DisableCache; //Create a CancelTracker. ITrackCancel pTrackCancel = new CancelTrackerClass(); //Create the ProgressDialog. This automatically displays the dialog IProgressDialogFactory pProgDlgFactory = new ProgressDialogFactoryClass(); IProgressDialog2 pProDlg = pProgDlgFactory.Create(pTrackCancel, m_application.hWnd) as IProgressDialog2; pProDlg.CancelEnabled = true; pProDlg.Title = "正在进行自定义表面设置及偏移调整"; pProDlg.Description = "设置中,请稍候..."; pProDlg.Animation = esriProgressAnimationTypes.esriProgressSpiral; IStepProgressor pStepPro = pProDlg as IStepProgressor; pStepPro.MinRange = 0; pStepPro.MaxRange = SelectedLyrIndex.Count; pStepPro.StepValue = 1; pStepPro.Message = "初始化中..."; bool bCont = true; //对每一个选中的图层进行操作 for (int i = 0; i < SelectedLyrIndex.Count; i++) { //m_application.StatusBar.set_Message(0, i.ToString()); pStepPro.Message = "已完成(" + i.ToString() + "/" + SelectedLyrIndex.Count.ToString() + ")"; bCont = pTrackCancel.Continue(); if (!bCont) { break; } //选中一个栅格图层 IRasterLayer rasterLayer = m_scene.Layer[SelectedLyrIndex[i]] as IRasterLayer; if (rasterLayer == null) { pStepPro.Message = "选中的图层非栅格图层..."; continue; } I3DProperties p3DProperties = null; ILayerExtensions layerExtensions = rasterLayer as ILayerExtensions; //遍历LayerExtensions找到I3DProperties for (int j = 0; j < layerExtensions.ExtensionCount; j++) { if (layerExtensions.get_Extension(j) is I3DProperties) { p3DProperties = layerExtensions.get_Extension(j) as I3DProperties; } } //设置I3DProperties p3DProperties.ZFactor = Multiplier; //系数 p3DProperties.BaseOption = esriBaseOption.esriBaseSurface; //基准面浮动 p3DProperties.BaseSurface = surface; //基准面 p3DProperties.OffsetExpressionString = Offset.ToString(); //偏移常量 if (DisableCache) { p3DProperties.RenderMode = esriRenderMode.esriRenderImmediate; //直接从文件渲染 p3DProperties.RenderVisibility = esriRenderVisibility.esriRenderWhenStopped; //停止导航时渲染 } p3DProperties.Apply3DProperties(rasterLayer); } pProDlg.HideDialog(); //========================================== //刷新,不起作用 if (activeView == null) { throw new Exception("活动视图为空! "); } if (m_sceneHookHelper.ActiveViewer == null) { throw new Exception("无活动视图!"); } activeView.Refresh(); m_sceneHookHelper.ActiveViewer.Redraw(true); //========================================== } catch (Exception err) { MessageBox.Show(err.ToString()); } }