//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(); }
/// <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 static string TraceIsolation(double[] x, double[] y, IApplication app, string sourceFLName, string valveFLName, string operableFieldNameValves, string operableFieldNameSources, double snapTol, bool processEvent, string[] opValues, string addSQL, bool traceIndeterminate, bool ZeroSourceCont, bool selectEdges, string MeterName, string MeterCritField, string MeterCritVal) { IMap map = null; List<int> valveFCClassIDs = new List<int>(); IProgressDialogFactory pProDFact = null; IStepProgressor pStepPro = null; IProgressDialog2 pProDlg = null; ITrackCancel pTrkCan = null; int pointAlong = 0; List<IGeometricNetwork> gnList = null; int gnIdx; IGeometricNetwork gn = null; IPoint snappedPoint = null; int EID = -1; double distanceAlong; List<INetFlag> startNetFlag = null; List<IFlagDisplay> pFlagsDisplay = null; //Find feature classes string[] sourceFLs; IFeatureClass[] sourceFC = null; IFeatureLayer[] sourceFL = null; List<int> sourceFCClassIDs = new List<int>(); string[] strValveFLs; IFeatureLayer pTempLay = null; List<IFeatureLayer> valveFLs = null; List<IFeatureClass> valveFCs = null; //IFeatureLayer meterFL = null; // string meterDSName; IJunctionFlag[] junctionFlag = null; IEdgeFlag[] edgeFlag = null; ITraceFlowSolverGEN traceFlowSolver = null; INetSolver netSolver = null; INetElementBarriersGEN netElementBarriers = null; INetElementBarriers nb = null; IEnumNetEID juncEIDs = null; IEnumNetEID edgeEIDs = null; IEIDInfo eidInfo = null; IEIDInfo valveEIDInfo = null; IEIDInfo sourceEIDInfo = null; IEIDInfo vEIDInfo = null; List<int[]> userIds = null; IEIDHelper eidHelper = null; List<Hashtable> valveEIDInfoHT = null; Hashtable sourceEIDInfoHT = null; System.Object[] segCosts = null; ISelectionSetBarriers netElementBarrier = null; List<IEdgeFlag> pEdgeFlags = null; List<IJunctionFlag> pJunctionFlags = null; //List<IEdgeFlag> pEdgeFlagsBar = null; //List<IJunctionFlag> pJunctionFlagsBar = null; INetElementBarriers pEdgeElementBarriers = null; INetElementBarriers pJunctionElementBarriers = null; ISelectionSetBarriers pSelectionSetBarriers = null; List<INetFlag> pNetFlags; //ITraceResult traceRes = null; IFlagDisplay pFlagDisplay = null; INetworkAnalysisExt pNetAnalysisExt = null; UID pID = null; IJunctionFlag[] junctionFlags = null; IEdgeFlag[] edgeFlags = null; Hashtable noSourceValveHT = null; Hashtable hasSourceValveHT = null; List<BarClassIDS> barrierIds = null; Hashtable sourceDirectEIDInfoHT = null; INetFlag netFlag1 = null; INetFlag netFlag2 = null; try { map = ((app.Document as IMxDocument).FocusMap); bool boolCont = true; if (processEvent) { // Create a CancelTracker pTrkCan = new CancelTrackerClass(); // Create the ProgressDialog. This automatically displays the dialog pProDFact = new ProgressDialogFactoryClass(); pProDlg = (IProgressDialog2)pProDFact.Create(pTrkCan, 0); // Set the properties of the ProgressDialog pProDlg.CancelEnabled = true; pProDlg.Description = A4LGSharedFunctions.Localizer.GetString("GeoNetToolsDesc_16a"); pProDlg.Title = A4LGSharedFunctions.Localizer.GetString("GeoNetToolsTitle_16a"); pProDlg.Animation = esriProgressAnimationTypes.esriProgressGlobe; // Set the properties of the Step Progressor pStepPro = (IStepProgressor)pProDlg; pStepPro.MinRange = 0; pStepPro.MaxRange = 18; pStepPro.StepValue = 1; pStepPro.Position = 0; pStepPro.Message = A4LGSharedFunctions.Localizer.GetString("GeoNetToolsProc_4"); pStepPro.Message = A4LGSharedFunctions.Localizer.GetString("GeoNetToolsMess_14a"); pStepPro.Step(); boolCont = pTrkCan.Continue(); if (!boolCont) { pStepPro.Hide(); pProDlg.HideDialog(); pStepPro = null; pProDlg = null; pProDFact = null; return A4LGSharedFunctions.Localizer.GetString("CanceledReturnStatement"); } } if (processEvent) { pStepPro.Message = A4LGSharedFunctions.Localizer.GetString("GeoNetToolsProc_4"); pStepPro.Step(); boolCont = pTrkCan.Continue(); } if (!boolCont) { pStepPro.Hide(); pProDlg.HideDialog(); pStepPro = null; pProDlg = null; pProDFact = null; return A4LGSharedFunctions.Localizer.GetString("CanceledReturnStatement"); } pointAlong++; gnList = Globals.GetGeometricNetworksCurrentlyVisible(ref map); gnIdx = -1; if (processEvent) { pStepPro.Message = A4LGSharedFunctions.Localizer.GetString("GeoNetToolsMess_14a"); pStepPro.Step(); boolCont = pTrkCan.Continue(); } if (!boolCont) { pStepPro.Hide(); pProDlg.HideDialog(); pStepPro = null; pProDlg = null; pProDFact = null; return A4LGSharedFunctions.Localizer.GetString("CanceledReturnStatement"); } pointAlong++; // Create junction or edge flag at start of trace - also returns geometric network, snapped point, and EID of junction if (processEvent) { pStepPro.Message = A4LGSharedFunctions.Localizer.GetString("GeoNetToolsMess_15a"); pStepPro.Step(); boolCont = pTrkCan.Continue(); } if (!boolCont) { pStepPro.Hide(); pProDlg.HideDialog(); pStepPro = null; pProDlg = null; pProDFact = null; return A4LGSharedFunctions.Localizer.GetString("CanceledReturnStatement"); } startNetFlag = new List<INetFlag>();// null;// Globals.GetJunctionFlag(x, y, map, ref gnList, snapTol, ref gnIdx, out snappedPoint, out EID) as INetFlag; //if (startNetFlag == null) pFlagsDisplay = new List<IFlagDisplay>(); if (x != null) { for (int l = 0; l < x.Length; l++) { startNetFlag.Add(Globals.GetEdgeFlag(x[l], y[l], ref map, ref gnList, snapTol, ref gnIdx, out snappedPoint, out EID, out distanceAlong, out pFlagDisplay, true) as INetFlag); pFlagsDisplay.Add(pFlagDisplay); } } pointAlong++; //Set network to trace if (gnIdx > -1) gn = gnList[gnIdx] as IGeometricNetwork; if (app != null) { pID = new UID(); pID.Value = "esriEditorExt.UtilityNetworkAnalysisExt"; pNetAnalysisExt = (INetworkAnalysisExt)app.FindExtensionByCLSID(pID); if (gn != null) { Globals.SetCurrentNetwork(ref pNetAnalysisExt, ref gn); } traceFlowSolver = Globals.CreateTraceFlowSolverFromToolbar(ref pNetAnalysisExt, out pEdgeFlags, out pJunctionFlags, out pEdgeElementBarriers, out pJunctionElementBarriers, out pSelectionSetBarriers) as ITraceFlowSolverGEN; gn = pNetAnalysisExt.CurrentNetwork; netSolver = traceFlowSolver as INetSolver; } else { if (gn == null || startNetFlag.Count == 0) { return A4LGSharedFunctions.Localizer.GetString("NoFlagReturnStatement"); } traceFlowSolver = new TraceFlowSolverClass() as ITraceFlowSolverGEN; netSolver = traceFlowSolver as INetSolver; netSolver.SourceNetwork = gn.Network; } traceFlowSolver.TraceIndeterminateFlow = traceIndeterminate; pNetFlags = new List<INetFlag>(); if (pEdgeFlags != null) { foreach (IEdgeFlag pEdFl in pEdgeFlags) { pNetFlags.Add((INetFlag)pEdFl); } } if (pJunctionFlags != null) { foreach (IJunctionFlag pJcFl in pJunctionFlags) { pNetFlags.Add((INetFlag)pJcFl); } } if (startNetFlag != null) { if (startNetFlag.Count > 0) { foreach (INetFlag pNF in startNetFlag) { if (pNF != null) { pNetFlags.Add((INetFlag)pNF); } } } // pNetFlags.Add((INetFlag)startNetFlag); } if (pNetFlags.Count == 0) { return A4LGSharedFunctions.Localizer.GetString("AddFlagOrClickReturnStatement"); } // Stop if user point was not on a visible network feature, old trace results and selection are cleared if (gn == null || pNetFlags.Count == 0) { return A4LGSharedFunctions.Localizer.GetString("NotIntersectReturnStatement"); } pointAlong++; if (processEvent) { pStepPro.Message = A4LGSharedFunctions.Localizer.GetString("GeoNetToolsProc_16a"); pStepPro.Step(); boolCont = pTrkCan.Continue(); } if (!boolCont) { pStepPro.Hide(); pProDlg.HideDialog(); pStepPro = null; pProDlg = null; pProDFact = null; return A4LGSharedFunctions.Localizer.GetString("CanceledReturnStatement"); } //Find feature classes sourceFLs = sourceFLName.Split('|'); sourceFC = new IFeatureClass[sourceFLs.Length]; sourceFL = new IFeatureLayer[sourceFLs.Length]; for (int i = 0; i < sourceFLs.Length; i++) { bool FCorLayerTemp = true; sourceFL[i] = (IFeatureLayer)Globals.FindLayer(map, sourceFLs[i], ref FCorLayerTemp); if (sourceFL[i] != null) { sourceFC[i] = sourceFL[i].FeatureClass; sourceFCClassIDs.Add(sourceFL[i].FeatureClass.FeatureClassID); } } pointAlong++; // IFeatureClass sourceFC = (IFeatureClass)Globals.GetFeatureClassFromGeometricNetwork(sourceFCName, gn, esriFeatureType.esriFTSimpleJunction); // IFeatureClass valveFC = (IFeatureClass)Globals.GetFeatureClassFromGeometricNetwork(valveFCName, gn, esriFeatureType.esriFTSimpleJunction); strValveFLs = valveFLName.Split('|'); valveFLs = new List<IFeatureLayer>();//(IFeatureLayer)Globals.FindLayer(map, valveFLName); valveFCs = new List<IFeatureClass>();//[strValveFLs.Length]; for (int i = 0; i < strValveFLs.Length; i++) { bool FCorLayerTemp = true; pTempLay = (IFeatureLayer)Globals.FindLayer(map, strValveFLs[i], ref FCorLayerTemp); if (pTempLay != null) { if (pTempLay.FeatureClass != null) { valveFLs.Add(pTempLay); valveFCs.Add(pTempLay.FeatureClass); valveFCClassIDs.Add(pTempLay.FeatureClass.FeatureClassID); } } } // string strMeterFL = meterFLName; //meterFL = (IFeatureLayer)Globals.FindLayer(map, meterFLName); //meterDSName = ""; //if (meterFL != null) //{ // if (meterFL is IDataset) // { // IDataset pTempDataset = (IDataset)meterFL; // meterDSName = pTempDataset.BrowseName; // if (meterDSName.Contains(".")) // { // meterDSName = meterDSName.Substring(meterDSName.LastIndexOf(".") + 1); // } // Marshal.ReleaseComObject(pTempDataset); // pTempDataset = null; // } //} //meterFL = null; if (processEvent) { pStepPro.Message = A4LGSharedFunctions.Localizer.GetString("GeoNetToolsProc_16a"); pStepPro.Step(); boolCont = pTrkCan.Continue(); } if (!boolCont) { pStepPro.Hide(); pProDlg.HideDialog(); pStepPro = null; pProDlg = null; pProDFact = null; return A4LGSharedFunctions.Localizer.GetString("CanceledReturnStatement"); } pointAlong++; if (valveFCs == null) { if (processEvent) { pStepPro.Message = A4LGSharedFunctions.Localizer.GetString("GeoNetToolsMess_15d") + valveFLName + A4LGSharedFunctions.Localizer.GetString("GeoNetToolsMess_15e") + Environment.NewLine + A4LGSharedFunctions.Localizer.GetString("GeoNetToolsMess_15f"); pStepPro.Step(); boolCont = pTrkCan.Continue(); } if (!boolCont) { pStepPro.Hide(); pProDlg.HideDialog(); pStepPro = null; pProDlg = null; pProDFact = null; return A4LGSharedFunctions.Localizer.GetString("CanceledReturnStatement"); ; } return A4LGSharedFunctions.Localizer.GetString("LambdaReturnStatement") + valveFLName + A4LGSharedFunctions.Localizer.GetString("GeoNetToolsMess_15e") + Environment.NewLine + A4LGSharedFunctions.Localizer.GetString("GeoNetToolsMess_15f"); } pointAlong++; if (valveFCs.Count == 0) { if (processEvent) { pStepPro.Message = A4LGSharedFunctions.Localizer.GetString("GeoNetToolsMess_15d") + valveFLName + A4LGSharedFunctions.Localizer.GetString("GeoNetToolsMess_15e") + Environment.NewLine + A4LGSharedFunctions.Localizer.GetString("GeoNetToolsMess_15f"); pStepPro.Step(); boolCont = pTrkCan.Continue(); } if (!boolCont) { pStepPro.Hide(); pProDlg.HideDialog(); pStepPro = null; pProDlg = null; pProDFact = null; return A4LGSharedFunctions.Localizer.GetString("CanceledReturnStatement"); } return A4LGSharedFunctions.Localizer.GetString("LambdaReturnStatement") + valveFLName + A4LGSharedFunctions.Localizer.GetString("GeoNetToolsMess_15e") + Environment.NewLine + A4LGSharedFunctions.Localizer.GetString("GeoNetToolsMess_15f"); } if (sourceFC == null) { if (processEvent) { pStepPro.Message = A4LGSharedFunctions.Localizer.GetString("GeoNetToolsMess_15d") + sourceFLs + A4LGSharedFunctions.Localizer.GetString("GeoNetToolsMess_15e") + Environment.NewLine + A4LGSharedFunctions.Localizer.GetString("GeoNetToolsMess_15f"); pStepPro.Step(); boolCont = pTrkCan.Continue(); } if (!boolCont) { pStepPro.Hide(); pProDlg.HideDialog(); pStepPro = null; pProDlg = null; pProDFact = null; return A4LGSharedFunctions.Localizer.GetString("CanceledReturnStatement"); } return A4LGSharedFunctions.Localizer.GetString("LambdaReturnStatement") + sourceFLs + A4LGSharedFunctions.Localizer.GetString("GeoNetToolsMess_15e") + Environment.NewLine + A4LGSharedFunctions.Localizer.GetString("GeoNetToolsMess_15f"); } pointAlong++; if (sourceFC.Length == 0) { if (processEvent) { pStepPro.Message = A4LGSharedFunctions.Localizer.GetString("GeoNetToolsMess_15d") + sourceFLs + A4LGSharedFunctions.Localizer.GetString("GeoNetToolsMess_15e") + Environment.NewLine + A4LGSharedFunctions.Localizer.GetString("GeoNetToolsMess_15f"); pStepPro.Step(); boolCont = pTrkCan.Continue(); } if (!boolCont) { pStepPro.Hide(); pProDlg.HideDialog(); pStepPro = null; pProDlg = null; pProDFact = null; return A4LGSharedFunctions.Localizer.GetString("CanceledReturnStatement"); } return A4LGSharedFunctions.Localizer.GetString("LambdaReturnStatement") + sourceFLs + A4LGSharedFunctions.Localizer.GetString("GeoNetToolsMess_15e") + Environment.NewLine + A4LGSharedFunctions.Localizer.GetString("GeoNetToolsMess_15f"); } pointAlong++; if (processEvent) { pStepPro.Message = A4LGSharedFunctions.Localizer.GetString("GeoNetToolsProc_16b"); pStepPro.Step(); boolCont = pTrkCan.Continue(); } if (!boolCont) { pStepPro.Hide(); pProDlg.HideDialog(); pStepPro = null; pProDlg = null; pProDFact = null; return A4LGSharedFunctions.Localizer.GetString("CanceledReturnStatement"); } Globals.AddFlagsToTraceSolver(pNetFlags.ToArray(), ref traceFlowSolver, out junctionFlags, out edgeFlags); if (processEvent) { pStepPro.Message = A4LGSharedFunctions.Localizer.GetString("GeoNetToolsProc_16c"); pStepPro.Step(); boolCont = pTrkCan.Continue(); } if (!boolCont) { pStepPro.Hide(); pProDlg.HideDialog(); pStepPro = null; pProDlg = null; pProDFact = null; return A4LGSharedFunctions.Localizer.GetString("CanceledReturnStatement"); } //Create barriers based on all operable valves pointAlong++; netElementBarriers = new NetElementBarriersClass() as INetElementBarriersGEN; netElementBarriers.ElementType = esriElementType.esriETJunction; netElementBarriers.Network = gn.Network; userIds = Globals.GetOperableValveOIDs(valveFCs.ToArray(), operableFieldNameValves, opValues, addSQL); if (userIds == null) { if (processEvent) { pStepPro.Message = A4LGSharedFunctions.Localizer.GetString("GeoNetToolsProc_16d"); pStepPro.Step(); boolCont = pTrkCan.Continue(); } if (!boolCont) { pStepPro.Hide(); pProDlg.HideDialog(); pStepPro = null; pProDlg = null; pProDFact = null; return A4LGSharedFunctions.Localizer.GetString("CanceledReturnStatement"); } } else { if (userIds.Count == 0) { if (processEvent) { pStepPro.Message = A4LGSharedFunctions.Localizer.GetString("GeoNetToolsProc_16d"); pStepPro.Step(); boolCont = pTrkCan.Continue(); } if (!boolCont) { pStepPro.Hide(); pProDlg.HideDialog(); pStepPro = null; pProDlg = null; pProDFact = null; return A4LGSharedFunctions.Localizer.GetString("CanceledReturnStatement"); } } else { try { int idxUser = 0; if (processEvent) { pStepPro.Message = A4LGSharedFunctions.Localizer.GetString("GeoNetToolsProc_16e"); pStepPro.Step(); boolCont = pTrkCan.Continue(); } if (!boolCont) { pStepPro.Hide(); pProDlg.HideDialog(); pStepPro = null; pProDlg = null; pProDFact = null; return A4LGSharedFunctions.Localizer.GetString("CanceledReturnStatement"); } foreach (IFeatureClass valveFC in valveFCs) { int[] usrid = userIds[idxUser]; if (usrid.Length > 0) { netElementBarriers.SetBarriers(valveFC.FeatureClassID, ref usrid); //error here after sum nb = netElementBarriers as INetElementBarriers; netSolver.set_ElementBarriers(esriElementType.esriETJunction, nb); } idxUser++; } } catch (Exception Ex) { if (processEvent) { pStepPro.Message = A4LGSharedFunctions.Localizer.GetString("GeoNetToolsError_16a") + Ex.Message; pStepPro.Step(); boolCont = pTrkCan.Continue(); return A4LGSharedFunctions.Localizer.GetString("CanceledReturnStatement"); } if (!boolCont) { pStepPro.Hide(); pProDlg.HideDialog(); pStepPro = null; pProDlg = null; pProDFact = null; return A4LGSharedFunctions.Localizer.GetString("CanceledReturnStatement"); } } } } pointAlong++; if (processEvent) { pStepPro.Message = A4LGSharedFunctions.Localizer.GetString("GeoNetToolsProc_16f"); pStepPro.Step(); boolCont = pTrkCan.Continue(); } if (!boolCont) { pStepPro.Hide(); pProDlg.HideDialog(); pStepPro = null; pProDlg = null; pProDFact = null; return A4LGSharedFunctions.Localizer.GetString("CanceledReturnStatement"); } try { traceFlowSolver.FindFlowEndElements(esriFlowMethod.esriFMConnected, esriFlowElements.esriFEJunctionsAndEdges, out juncEIDs, out edgeEIDs); } catch { juncEIDs = null; edgeEIDs = null; if (processEvent) { pStepPro.Message = A4LGSharedFunctions.Localizer.GetString("ErrorInThe") + "FindFlowEndElements"; pStepPro.Step(); boolCont = pTrkCan.Continue(); } if (!boolCont) { pStepPro.Hide(); pProDlg.HideDialog(); pStepPro = null; pProDlg = null; pProDFact = null; return A4LGSharedFunctions.Localizer.GetString("CanceledReturnStatement"); } return A4LGSharedFunctions.Localizer.GetString("DontFindFlowEltReturnStatement"); //MessageBox.Show("Error in the FindFlowEndElements"); } pointAlong++; eidHelper = new EIDHelperClass(); eidHelper.GeometricNetwork = gn; eidHelper.ReturnFeatures = true; //Save valves which stopped the trace if (processEvent) { pStepPro.Message = A4LGSharedFunctions.Localizer.GetString("GeoNetToolsProc_16g"); pStepPro.Step(); boolCont = pTrkCan.Continue(); } if (!boolCont) { pStepPro.Hide(); pProDlg.HideDialog(); pStepPro = null; pProDlg = null; pProDFact = null; return A4LGSharedFunctions.Localizer.GetString("CanceledReturnStatement"); } pointAlong++; valveEIDInfoHT = new List<Hashtable>(); int totalreachcount = 0; foreach (IFeatureClass valveFC in valveFCs) { if (valveFC != null) { Hashtable valveEIDInfoHTtemp = Globals.GetEIDInfoListByFC(valveFC.FeatureClassID, juncEIDs, eidHelper); totalreachcount = totalreachcount + valveEIDInfoHTtemp.Count; valveEIDInfoHT.Add(valveEIDInfoHTtemp); } } if (totalreachcount == 0) { if (processEvent) { pStepPro.Message = (A4LGSharedFunctions.Localizer.GetString("GeoNetToolsMess_16a") + valveFLName + A4LGSharedFunctions.Localizer.GetString("GeoNetToolsMess_15c") + Environment.NewLine + Environment.NewLine + A4LGSharedFunctions.Localizer.GetString("GeoNetToolsMess_16b") + valveFLName + A4LGSharedFunctions.Localizer.GetString("GeoNetToolsMess_16c") + Environment.NewLine + A4LGSharedFunctions.Localizer.GetString("GeoNetToolsMess_16d") + Environment.NewLine + A4LGSharedFunctions.Localizer.GetString("GeoNetToolsMess_16e")); pStepPro.Step(); boolCont = pTrkCan.Continue(); } if (!boolCont) { pStepPro.Hide(); pProDlg.HideDialog(); pStepPro = null; pProDlg = null; pProDFact = null; return A4LGSharedFunctions.Localizer.GetString("CanceledReturnStatement"); } return A4LGSharedFunctions.Localizer.GetString("Error") + A4LGSharedFunctions.Localizer.GetString("GeoNetToolsMess_16a") + valveFLName + A4LGSharedFunctions.Localizer.GetString("GeoNetToolsMess_15c") + Environment.NewLine + Environment.NewLine + A4LGSharedFunctions.Localizer.GetString("GeoNetToolsMess_16b") + valveFLName + A4LGSharedFunctions.Localizer.GetString("GeoNetToolsMess_16c") + Environment.NewLine + A4LGSharedFunctions.Localizer.GetString("GeoNetToolsMess_16d") + Environment.NewLine + A4LGSharedFunctions.Localizer.GetString("GeoNetToolsMess_16e"); } pointAlong++; if (processEvent) { pStepPro.Message = A4LGSharedFunctions.Localizer.GetString("GeoNetToolsProc_16h"); pStepPro.Step(); boolCont = pTrkCan.Continue(); } if (!boolCont) { pStepPro.Hide(); pProDlg.HideDialog(); pStepPro = null; pProDlg = null; pProDFact = null; return A4LGSharedFunctions.Localizer.GetString("CanceledReturnStatement"); } traceFlowSolver = new TraceFlowSolverClass() as ITraceFlowSolverGEN; traceFlowSolver.TraceIndeterminateFlow = traceIndeterminate; netSolver = traceFlowSolver as INetSolver; netSolver.SourceNetwork = gn.Network; //Globals.AddFlagsToTraceSolver(startNetFlag.ToArray(), ref traceFlowSolver, out junctionFlag, out edgeFlag); Globals.AddFlagsToTraceSolver(pNetFlags.ToArray(), ref traceFlowSolver, out junctionFlag, out edgeFlag); Globals.AddBarriersToSolver(ref traceFlowSolver, ref pEdgeElementBarriers, ref pJunctionElementBarriers, ref pSelectionSetBarriers); pointAlong++; foreach (int sFC in sourceFCClassIDs) { netSolver.DisableElementClass(sFC); } traceFlowSolver.FindFlowEndElements(esriFlowMethod.esriFMConnected, esriFlowElements.esriFEJunctions, out juncEIDs, out edgeEIDs); pointAlong++; //Save sources which are reachable if (processEvent) { pStepPro.Message = A4LGSharedFunctions.Localizer.GetString("GeoNetToolsProc_16i"); pStepPro.Step(); boolCont = pTrkCan.Continue(); } if (!boolCont) { pStepPro.Hide(); pProDlg.HideDialog(); pStepPro = null; pProDlg = null; pProDFact = null; return A4LGSharedFunctions.Localizer.GetString("CanceledReturnStatement"); } sourceEIDInfoHT = new Hashtable(); //foreach (IFeatureClass sFC in sourceFC) //{ Globals.GetEIDInfoListByFCWithHT(ref sourceEIDInfoHT, sourceFCClassIDs, operableFieldNameSources, opValues, juncEIDs, eidHelper); //} pointAlong++; if (sourceEIDInfoHT.Count == 0) { if (processEvent) { pStepPro.Message = A4LGSharedFunctions.Localizer.GetString("No") + sourceFLName + A4LGSharedFunctions.Localizer.GetString("GeoNetToolsMess_15c") + Environment.NewLine + Environment.NewLine + A4LGSharedFunctions.Localizer.GetString("GeoNetToolsMess_16b") + sourceFLName + A4LGSharedFunctions.Localizer.GetString("GeoNetToolsMess_16c") + Environment.NewLine + A4LGSharedFunctions.Localizer.GetString("GeoNetToolsProc_16j"); pStepPro.Step(); boolCont = pTrkCan.Continue(); } if (!boolCont) { pStepPro.Hide(); pProDlg.HideDialog(); pStepPro = null; pProDlg = null; pProDFact = null; return null; } return A4LGSharedFunctions.Localizer.GetString("Error") + A4LGSharedFunctions.Localizer.GetString("No") + sourceFLName + A4LGSharedFunctions.Localizer.GetString("GeoNetToolsMess_15c") + Environment.NewLine + Environment.NewLine + A4LGSharedFunctions.Localizer.GetString("GeoNetToolsMess_16b") + sourceFLName + A4LGSharedFunctions.Localizer.GetString("GeoNetToolsMess_16c") + Environment.NewLine + A4LGSharedFunctions.Localizer.GetString("GeoNetToolsProc_16j"); } if (processEvent) { pStepPro.Message = A4LGSharedFunctions.Localizer.GetString("GeoNetToolsProc_16k"); pStepPro.Step(); boolCont = pTrkCan.Continue(); } if (!boolCont) { pStepPro.Hide(); pProDlg.HideDialog(); pStepPro = null; pProDlg = null; pProDFact = null; return null; } traceFlowSolver = new TraceFlowSolverClass() as ITraceFlowSolverGEN; traceFlowSolver.TraceIndeterminateFlow = traceIndeterminate; netSolver = traceFlowSolver as INetSolver; netSolver.SourceNetwork = gn.Network; //Globals.AddFlagsToTraceSolver(startNetFlag.ToArray(), ref traceFlowSolver, out junctionFlag, out edgeFlag); Globals.AddFlagsToTraceSolver(pNetFlags.ToArray(), ref traceFlowSolver, out junctionFlag, out edgeFlag); Globals.AddBarriersToSolver(ref traceFlowSolver, ref pEdgeElementBarriers, ref pJunctionElementBarriers, ref pSelectionSetBarriers); pointAlong++; //Set the barriers in the network based on the saved valves if (processEvent) { pStepPro.Message = A4LGSharedFunctions.Localizer.GetString("GeoNetToolsProc_16l"); pStepPro.Step(); boolCont = pTrkCan.Continue(); } if (!boolCont) { pStepPro.Hide(); pProDlg.HideDialog(); pStepPro = null; pProDlg = null; pProDFact = null; return A4LGSharedFunctions.Localizer.GetString("CanceledReturnStatement"); } //Run the trace to find directly reachable sources (without passing valve) if (processEvent) { pStepPro.Message = A4LGSharedFunctions.Localizer.GetString("GeoNetToolsProc_16m"); pStepPro.Step(); boolCont = pTrkCan.Continue(); } if (!boolCont) { pStepPro.Hide(); pProDlg.HideDialog(); pStepPro = null; pProDlg = null; pProDFact = null; return A4LGSharedFunctions.Localizer.GetString("CanceledReturnStatement"); } netElementBarrier = new SelectionSetBarriersClass(); totalreachcount = 0; foreach (Hashtable HTentry in valveEIDInfoHT) { foreach (DictionaryEntry entry in HTentry) { eidInfo = entry.Value as IEIDInfo; netElementBarrier.Add(eidInfo.Feature.Class.ObjectClassID, eidInfo.Feature.OID); } totalreachcount++; } pointAlong++; netSolver.SelectionSetBarriers = netElementBarrier; pointAlong++; Globals.AddBarriersToSolver(ref traceFlowSolver, ref pEdgeElementBarriers, ref pJunctionElementBarriers, ref pSelectionSetBarriers); traceFlowSolver.FindFlowElements(esriFlowMethod.esriFMConnected, esriFlowElements.esriFEJunctionsAndEdges, out juncEIDs, out edgeEIDs); // Hashtable sourceDirectEIDInfoHT = Globals.GetEIDInfoListByFC(sourceFC.FeatureClassID, juncEIDs, eidHelper); sourceDirectEIDInfoHT = new Hashtable(); Globals.GetEIDInfoListByFCWithHT(ref sourceDirectEIDInfoHT, sourceFCClassIDs, operableFieldNameSources, opValues, juncEIDs, eidHelper); //Remove directly reachable sources from source array if (processEvent) { pStepPro.Message = A4LGSharedFunctions.Localizer.GetString("GeoNetToolsProc_16n"); pStepPro.Step(); boolCont = pTrkCan.Continue(); } if (!boolCont) { pStepPro.Hide(); pProDlg.HideDialog(); pStepPro = null; pProDlg = null; pProDFact = null; return A4LGSharedFunctions.Localizer.GetString("CanceledReturnStatement"); } pointAlong++; foreach (DictionaryEntry entry in sourceDirectEIDInfoHT) { eidInfo = entry.Value as IEIDInfo; sourceEIDInfoHT.Remove(eidInfo.Feature.OID); } pointAlong++;//21 if (sourceEIDInfoHT.Count == 0) { if (processEvent) { pStepPro.Message = A4LGSharedFunctions.Localizer.GetString("No") + sourceFLName + A4LGSharedFunctions.Localizer.GetString("GeoNetToolsProc_16o") + Environment.NewLine + Environment.NewLine + A4LGSharedFunctions.Localizer.GetString("GeoNetToolsMess_16b") + sourceFLName + A4LGSharedFunctions.Localizer.GetString("GeoNetToolsMess_16c") + Environment.NewLine + A4LGSharedFunctions.Localizer.GetString("GeoNetToolsProc_16j"); pStepPro.Step(); boolCont = pTrkCan.Continue(); } if (!boolCont) { pStepPro.Hide(); pProDlg.HideDialog(); pStepPro = null; pProDlg = null; pProDFact = null; return A4LGSharedFunctions.Localizer.GetString("CanceledReturnStatement"); } return A4LGSharedFunctions.Localizer.GetString("Error") + A4LGSharedFunctions.Localizer.GetString("No") + sourceFLName + A4LGSharedFunctions.Localizer.GetString("GeoNetToolsProc_16o") + Environment.NewLine + Environment.NewLine + A4LGSharedFunctions.Localizer.GetString("GeoNetToolsMess_16b") + sourceFLName + A4LGSharedFunctions.Localizer.GetString("GeoNetToolsMess_16c") + Environment.NewLine + A4LGSharedFunctions.Localizer.GetString("GeoNetToolsProc_16j"); } pointAlong++;//22 if (processEvent) { pStepPro.Message = A4LGSharedFunctions.Localizer.GetString("GeoNetToolsProc_16p"); pStepPro.Step(); boolCont = pTrkCan.Continue(); } if (!boolCont) { pStepPro.Hide(); pProDlg.HideDialog(); pStepPro = null; pProDlg = null; pProDFact = null; return A4LGSharedFunctions.Localizer.GetString("CanceledReturnStatement"); } noSourceValveHT = new Hashtable(); hasSourceValveHT = new Hashtable(); // IEIDInfo vEIDInfo; barrierIds = null; bool foundSource; // ArrayList barrierArrayList; pointAlong++; totalreachcount = 0; foreach (Hashtable valveHT in valveEIDInfoHT) { foreach (DictionaryEntry valveEntry in valveHT) { foundSource = false; valveEIDInfo = valveEntry.Value as IEIDInfo; //Create array of all isolation valves excluding the current one // barrierArrayList = new ArrayList(); barrierIds = new List<BarClassIDS>(); foreach (Hashtable valveHTBar in valveEIDInfoHT) { BarClassIDS barClID = new BarClassIDS(); List<int> tempIntArr = new List<int>(); foreach (DictionaryEntry valveEntryBar in valveHTBar) { vEIDInfo = valveEntryBar.Value as IEIDInfo; barClID.ClassID = vEIDInfo.Feature.Class.ObjectClassID; vEIDInfo = valveEntryBar.Value as IEIDInfo; if (vEIDInfo.Feature.OID == valveEIDInfo.Feature.OID && vEIDInfo.Feature.Class.ObjectClassID == valveEIDInfo.Feature.Class.ObjectClassID) { } else { // barrierArrayList.Add(vEIDInfo.Feature.OID); tempIntArr.Add(vEIDInfo.Feature.OID); //barrierIds.Add(vEIDInfo.Feature.OID); } } barClID.IDs = tempIntArr.ToArray(); barrierIds.Add(barClID); } //if (valveHT.Count > 1) //{ // barrierArrayList = new ArrayList(); // barrierIds = new int[valveHT.Count - 1]; // foreach (DictionaryEntry v in valveHT) // { // vEIDInfo = v.Value as IEIDInfo; // if (vEIDInfo.Feature.OID != valveEIDInfo.Feature.OID) // { // barrierArrayList.Add(vEIDInfo.Feature.OID); // } // } // barrierArrayList.CopyTo(barrierIds); //} //else // barrierArrayList = null; pointAlong++; //For each source, attempt to trace foreach (DictionaryEntry sourceEntry in sourceEIDInfoHT) { sourceEIDInfo = sourceEntry.Value as IEIDInfo; //Setup trace to test each valve traceFlowSolver = new TraceFlowSolverClass() as ITraceFlowSolverGEN; traceFlowSolver.TraceIndeterminateFlow = traceIndeterminate; netSolver = traceFlowSolver as INetSolver; netSolver.SourceNetwork = gn.Network; Globals.AddBarriersToSolver(ref traceFlowSolver, ref pEdgeElementBarriers, ref pJunctionElementBarriers, ref pSelectionSetBarriers); //Set the first junction flag for path finding based this current valve netFlag1 = new JunctionFlagClass(); netFlag1.UserClassID = valveEIDInfo.Feature.Class.ObjectClassID; netFlag1.UserID = valveEIDInfo.Feature.OID; netFlag1.UserSubID = 0; netFlag1.Label = A4LGSharedFunctions.Localizer.GetString("GeoNetToolsLbl_16a"); //AddFlagToTraceSolver(netFlag1, ref traceFlowSolver, out junctionFlag, out edgeFlag); //Set the second (and last) trace flag at this source netFlag2 = new JunctionFlagClass(); netFlag2.UserClassID = sourceEIDInfo.Feature.Class.ObjectClassID; netFlag2.UserID = sourceEIDInfo.Feature.OID; netFlag2.UserSubID = 0; netFlag2.Label = A4LGSharedFunctions.Localizer.GetString("GeoNetToolsLbl_16b"); Globals.AddTwoJunctionFlagsToTraceSolver(ref traceFlowSolver, netFlag1, netFlag2); //Set as isolation valves (except the current one) as barriers if (barrierIds != null && barrierIds.Count > 0) { netElementBarriers = new NetElementBarriersClass() as INetElementBarriersGEN; netElementBarriers.ElementType = esriElementType.esriETJunction; netElementBarriers.Network = gn.Network; bool setBar = false; foreach (BarClassIDS tempBarIDS in barrierIds) { if (tempBarIDS.IDs.Length > 0) { int[] barIDs = tempBarIDS.IDs; netElementBarriers.SetBarriers(tempBarIDS.ClassID, ref barIDs); setBar = true; } } if (setBar)//required, it would produce an error if there where no other barriers { nb = netElementBarriers as INetElementBarriers; netSolver.set_ElementBarriers(esriElementType.esriETJunction, nb); } } //Run trace segCosts = new System.Object[1]; segCosts[0] = new System.Object(); edgeEIDs = null; traceFlowSolver.FindPath(esriFlowMethod.esriFMConnected, esriShortestPathObjFn.esriSPObjFnMinSum, out juncEIDs, out edgeEIDs, 1, ref segCosts); if (edgeEIDs != null && edgeEIDs.Count > 0) { foundSource = true; break; } } // End of source loop pointAlong++;//25 -30ish if (foundSource) { hasSourceValveHT.Add(valveEIDInfo.Feature.OID, valveEIDInfo);//valveEIDInfo.Feature.Class.ObjectClassID +":" + } else { noSourceValveHT.Add(valveEIDInfo.Feature.OID, valveEIDInfo); } } // End of valve loop totalreachcount++; } //Setup last trace with correct valve barriers if (hasSourceValveHT.Count == 0) { if (ZeroSourceCont) hasSourceValveHT = noSourceValveHT; else return A4LGSharedFunctions.Localizer.GetString("NoWaterSourceIdentifiedReturnStatement"); } if (processEvent) { pStepPro.Message = A4LGSharedFunctions.Localizer.GetString("GeoNetToolsProc_16q"); pStepPro.Step(); boolCont = pTrkCan.Continue(); } if (!boolCont) { pStepPro.Hide(); pProDlg.HideDialog(); pStepPro = null; pProDlg = null; pProDFact = null; return A4LGSharedFunctions.Localizer.GetString("CanceledReturnStatement"); } pointAlong++; traceFlowSolver = new TraceFlowSolverClass() as ITraceFlowSolverGEN; traceFlowSolver.TraceIndeterminateFlow = traceIndeterminate; netSolver = traceFlowSolver as INetSolver; netSolver.SourceNetwork = gn.Network; //Globals.AddFlagsToTraceSolver(startNetFlag.ToArray(), ref traceFlowSolver, out junctionFlag, out edgeFlag); Globals.AddFlagsToTraceSolver(pNetFlags.ToArray(), ref traceFlowSolver, out junctionFlag, out edgeFlag); Globals.AddBarriersToSolver(ref traceFlowSolver, ref pEdgeElementBarriers, ref pJunctionElementBarriers, ref pSelectionSetBarriers); //Set the barriers in the network based on the saved valves netElementBarrier = new SelectionSetBarriersClass(); foreach (DictionaryEntry entry in hasSourceValveHT) { eidInfo = entry.Value as IEIDInfo; //netElementBarrier.Add(valveFC.FeatureClassID, eidInfo.Feature.OID); netElementBarrier.Add(((IFeatureClass)eidInfo.Feature.Class).FeatureClassID, eidInfo.Feature.OID); } netSolver.SelectionSetBarriers = netElementBarrier; pointAlong++; //Run last trace traceFlowSolver.FindFlowElements(esriFlowMethod.esriFMConnected, esriFlowElements.esriFEJunctionsAndEdges, out juncEIDs, out edgeEIDs); //skipped valves => //Hashtable skippedValvesEIDInfoHT = GetEIDInfoListByFC(valveFC.FeatureClassID, juncEIDs, eidHelper); //Select junction features pointAlong++; //51,44 //Open identify dialog with selected features //IdentifySelected(map); if (processEvent) { pStepPro.Message = A4LGSharedFunctions.Localizer.GetString("Complete"); pStepPro.Step(); boolCont = pTrkCan.Continue(); } if (!boolCont) { pStepPro.Hide(); pProDlg.HideDialog(); pStepPro = null; pProDlg = null; pProDFact = null; return A4LGSharedFunctions.Localizer.GetString("CanceledReturnStatement"); } if (snappedPoint != null) { snappedPoint.Project(map.SpatialReference); // traceRes.TracePoint = snappedPoint; } // return "Post1"; //Globals.LoadJunctions(ref traceRes, ref gn, ref map, ref juncEIDs, ref meterDSName); // Globals.LoadValves(ref traceRes, ref gn, ref map, ref hasSourceValveHT); //Globals.LoadEdges(ref traceRes, ref gn, ref map, ref edgeEIDs); //((IMxDocument)app.Document).FocusMap.ClearSelection(); //Globals.RemoveGraphics(((IMxDocument)app.Document).FocusMap, false); string returnVal = ""; returnVal = Globals.SelectJunctions(ref map, ref gn, ref juncEIDs, ref junctionFlag, MeterName, MeterCritField, MeterCritVal, processEvent); if (processEvent) { if (selectEdges) Globals.SelectEdges(ref map, ref gn, ref edgeEIDs); else Globals.DrawEdges(ref map, ref gn, ref edgeEIDs); } returnVal = Globals.SelectValveJunctions(ref map, ref hasSourceValveHT, ref valveFLs, processEvent) + "_" + returnVal; if (processEvent) { if (pNetAnalysisExt != null) { foreach (IFlagDisplay pFgDi in pFlagsDisplay) { Globals.AddFlagToGN(ref pNetAnalysisExt, ref gn, pFgDi); // Globals.AddPointGraphic(map, pFgDi.Geometry as IPoint, false); } } else { foreach (IFlagDisplay pFgDi in pFlagsDisplay) { // Globals.AddFlagToGN(ref pNetAnalysisExt, ref gn, pFgDi); Globals.AddPointGraphic(map, pFgDi.Geometry as IPoint, false); } } Globals.GetCommand("esriArcMapUI.ZoomToSelectedCommand", app).Execute(); } return returnVal; } catch (Exception ex) { // MessageBox.Show(ex.ToString()); return ex.Message.ToString() + "\n" + pointAlong; } finally { barrierIds = null; sourceDirectEIDInfoHT = null; netFlag1 = null; netFlag2 = null; junctionFlags = null; edgeFlags = null; pID = null; noSourceValveHT = null; hasSourceValveHT = null; if (pProDlg != null) { pProDlg.HideDialog(); } pStepPro = null; pProDlg = null; pProDFact = null; if (gnList != null) { // Marshal.ReleaseComObject(gnList); } if (gn != null) { Marshal.ReleaseComObject(gn); } if (snappedPoint != null) { Marshal.ReleaseComObject(snappedPoint); } if (startNetFlag != null) { // Marshal.ReleaseComObject(startNetFlag); } if (sourceFC != null) { // Marshal.ReleaseComObject(sourceFC); } if (sourceFL != null) { // Marshal.ReleaseComObject(sourceFL); } if (pTempLay != null) { Marshal.ReleaseComObject(pTempLay); } if (valveFLs != null) { // Marshal.ReleaseComObject(valveFLs); } if (valveFCs != null) { // Marshal.ReleaseComObject(valveFCs); } //if (meterFL != null) //{ // Marshal.ReleaseComObject(meterFL); //} if (junctionFlag != null) { // Marshal.ReleaseComObject(junctionFlag); } if (edgeFlag != null) { // Marshal.ReleaseComObject(edgeFlag); } if (traceFlowSolver != null) { Marshal.ReleaseComObject(traceFlowSolver); } if (netSolver != null) { Marshal.ReleaseComObject(netSolver); } if (netElementBarriers != null) { Marshal.ReleaseComObject(netElementBarriers); } if (nb != null) { Marshal.ReleaseComObject(nb); } if (juncEIDs != null) { Marshal.ReleaseComObject(juncEIDs); } if (edgeEIDs != null) { Marshal.ReleaseComObject(edgeEIDs); } if (eidInfo != null) { Marshal.ReleaseComObject(eidInfo); } if (valveEIDInfo != null) { Marshal.ReleaseComObject(valveEIDInfo); } if (sourceEIDInfo != null) { Marshal.ReleaseComObject(sourceEIDInfo); } if (vEIDInfo != null) { Marshal.ReleaseComObject(vEIDInfo); } if (userIds != null) { // Marshal.ReleaseComObject(userIds); } if (eidHelper != null) { Marshal.ReleaseComObject(eidHelper); } if (valveEIDInfoHT != null) { // Marshal.ReleaseComObject(valveEIDInfoHT); } if (sourceEIDInfoHT != null) { // Marshal.ReleaseComObject(sourceEIDInfoHT); } if (segCosts != null) { // Marshal.ReleaseComObject(segCosts); } if (netElementBarrier != null) { Marshal.ReleaseComObject(netElementBarrier); } //if (traceRes != null) //{ // traceRes.Dispose(); // // Marshal.ReleaseComObject(traceRes); //} pNetAnalysisExt = null; pFlagsDisplay = null; pEdgeFlags = null; pJunctionFlags = null; pNetFlags = null; pFlagDisplay = null; //pEdgeFlagsBar = null; //pJunctionFlagsBar = null; gnList = null; gn = null; snappedPoint = null; startNetFlag = null; sourceFC = null; sourceFL = null; pTempLay = null; valveFLs = null; valveFCs = null; //meterFL = null; junctionFlag = null; edgeFlag = null; traceFlowSolver = null; netSolver = null; netElementBarriers = null; nb = null; juncEIDs = null; edgeEIDs = null; eidInfo = null; valveEIDInfo = null; sourceEIDInfo = null; vEIDInfo = null; userIds = null; eidHelper = null; valveEIDInfoHT = null; sourceEIDInfoHT = null; segCosts = null; netElementBarrier = null; //traceRes = null; } GC.Collect(); GC.WaitForFullGCComplete(300); }
public static string TraceFindClosest(double[] x, double[] y, IApplication app, string targetFLName, string sWeightName, double snapTol, bool processEvent, bool traceIndeterminate) { IMap map = null; IProgressDialogFactory pProDFact = null; IStepProgressor pStepPro = null; IProgressDialog2 pProDlg = null; ITrackCancel pTrkCan = null; List<IGeometricNetwork> gnList = null; int gnIdx; IGeometricNetwork gn = null; IPoint snappedPoint = null; int EID = -1; double distanceAlong; List<INetFlag> startNetFlag = null; List<IFlagDisplay> pFlagsDisplay = null; //Find feature classes IJunctionFlag[] junctionFlag = null; IEdgeFlag[] edgeFlag = null; ITraceFlowSolverGEN traceFlowSolver = null; INetSolver netSolver = null; INetElementBarriersGEN netElementBarriers = null; INetElementBarriers nb = null; IEnumNetEID juncEIDs = null; IEnumNetEID edgeEIDs = null; IEIDInfo eidInfo = null; IEIDInfo valveEIDInfo = null; IEIDInfo sourceEIDInfo = null; IEIDInfo vEIDInfo = null; List<int[]> userIds = null; IEIDHelper eidHelper = null; List<Hashtable> valveEIDInfoHT = null; Hashtable sourceEIDInfoHT = null; System.Object[] segCosts = null; ISelectionSetBarriers netElementBarrier = null; List<IEdgeFlag> pEdgeFlags = null; List<IJunctionFlag> pJunctionFlags = null; //List<IEdgeFlag> pEdgeFlagsBar = null; //List<IJunctionFlag> pJunctionFlagsBar = null; INetElementBarriers pEdgeElementBarriers = null; INetElementBarriers pJunctionElementBarriers = null; ISelectionSetBarriers pSelectionSetBarriers = null; List<INetFlag> pNetFlags; //ITraceResult traceRes = null; IFlagDisplay pFlagDisplay = null; INetworkAnalysisExt pNetAnalysisExt = null; UID pID = null; IJunctionFlag[] junctionFlags = null; IEdgeFlag[] edgeFlags = null; List<BarClassIDS> barrierIds = null; Hashtable sourceDirectEIDInfoHT = null; INetFlag netFlag1 = null; INetFlag netFlag2 = null; Hashtable htClosestAsset = null; IFeatureLayer pClosestLayer = null; INetwork pNetwork = null; INetSchema pNetSchema = null; INetWeight pNetWeight = null; INetSolverWeights pNetSolverW = null; try { map = ((app.Document as IMxDocument).FocusMap); bool boolCont = true; if (processEvent) { // Create a CancelTracker pTrkCan = new CancelTrackerClass(); // Create the ProgressDialog. This automatically displays the dialog pProDFact = new ProgressDialogFactoryClass(); pProDlg = (IProgressDialog2)pProDFact.Create(pTrkCan, 0); // Set the properties of the ProgressDialog pProDlg.CancelEnabled = true; pProDlg.Description = A4LGSharedFunctions.Localizer.GetString("GeoNetToolsDesc_15a"); pProDlg.Title = A4LGSharedFunctions.Localizer.GetString("GeoNetToolsTitle_15a"); pProDlg.Animation = esriProgressAnimationTypes.esriProgressGlobe; // Set the properties of the Step Progressor pStepPro = (IStepProgressor)pProDlg; pStepPro.MinRange = 0; pStepPro.MaxRange = 18; pStepPro.StepValue = 1; pStepPro.Position = 0; pStepPro.Message = A4LGSharedFunctions.Localizer.GetString("GeoNetToolsProc_4"); pStepPro.Message = A4LGSharedFunctions.Localizer.GetString("GeoNetToolsMess_14a"); pStepPro.Step(); boolCont = pTrkCan.Continue(); if (!boolCont) { pStepPro.Hide(); pProDlg.HideDialog(); pStepPro = null; pProDlg = null; pProDFact = null; return A4LGSharedFunctions.Localizer.GetString("CanceledReturnStatement"); } } if (processEvent) { pStepPro.Message = A4LGSharedFunctions.Localizer.GetString("GeoNetToolsProc_4"); pStepPro.Step(); boolCont = pTrkCan.Continue(); } if (!boolCont) { pStepPro.Hide(); pProDlg.HideDialog(); pStepPro = null; pProDlg = null; pProDFact = null; return A4LGSharedFunctions.Localizer.GetString("CanceledReturnStatement"); } gnList = Globals.GetGeometricNetworksCurrentlyVisible(ref map); gnIdx = -1; if (processEvent) { pStepPro.Message = A4LGSharedFunctions.Localizer.GetString("GeoNetToolsMess_14a"); pStepPro.Step(); boolCont = pTrkCan.Continue(); } if (!boolCont) { pStepPro.Hide(); pProDlg.HideDialog(); pStepPro = null; pProDlg = null; pProDFact = null; return A4LGSharedFunctions.Localizer.GetString("CanceledReturnStatement"); } // Create junction or edge flag at start of trace - also returns geometric network, snapped point, and EID of junction if (processEvent) { pStepPro.Message = A4LGSharedFunctions.Localizer.GetString("GeoNetToolsMess_15a"); pStepPro.Step(); boolCont = pTrkCan.Continue(); } if (!boolCont) { pStepPro.Hide(); pProDlg.HideDialog(); pStepPro = null; pProDlg = null; pProDFact = null; return A4LGSharedFunctions.Localizer.GetString("CanceledReturnStatement"); } startNetFlag = new List<INetFlag>();// null;// Globals.GetJunctionFlag(x, y, map, ref gnList, snapTol, ref gnIdx, out snappedPoint, out EID) as INetFlag; //if (startNetFlag == null) pFlagsDisplay = new List<IFlagDisplay>(); if (x != null) { for (int l = 0; l < x.Length; l++) { startNetFlag.Add(Globals.GetEdgeFlag(x[l], y[l], ref map, ref gnList, snapTol, ref gnIdx, out snappedPoint, out EID, out distanceAlong, out pFlagDisplay, true) as INetFlag); pFlagsDisplay.Add(pFlagDisplay); } } //Set network to trace if (gnIdx > -1) gn = gnList[gnIdx] as IGeometricNetwork; if (app != null) { pID = new UID(); pID.Value = "esriEditorExt.UtilityNetworkAnalysisExt"; pNetAnalysisExt = (INetworkAnalysisExt)app.FindExtensionByCLSID(pID); if (gn != null) { Globals.SetCurrentNetwork(ref pNetAnalysisExt, ref gn); } traceFlowSolver = Globals.CreateTraceFlowSolverFromToolbar(ref pNetAnalysisExt, out pEdgeFlags, out pJunctionFlags, out pEdgeElementBarriers, out pJunctionElementBarriers, out pSelectionSetBarriers) as ITraceFlowSolverGEN; gn = pNetAnalysisExt.CurrentNetwork; netSolver = traceFlowSolver as INetSolver; } else { if (gn == null || startNetFlag.Count == 0) { return A4LGSharedFunctions.Localizer.GetString("NoFlagReturnStatement"); } traceFlowSolver = new TraceFlowSolverClass() as ITraceFlowSolverGEN; netSolver = traceFlowSolver as INetSolver; netSolver.SourceNetwork = gn.Network; } traceFlowSolver.TraceIndeterminateFlow = traceIndeterminate; pNetFlags = new List<INetFlag>(); if (pEdgeFlags != null) { foreach (IEdgeFlag pEdFl in pEdgeFlags) { pNetFlags.Add((INetFlag)pEdFl); } } if (pJunctionFlags != null) { foreach (IJunctionFlag pJcFl in pJunctionFlags) { pNetFlags.Add((INetFlag)pJcFl); } } if (startNetFlag != null) { if (startNetFlag.Count > 0) { foreach (INetFlag pNF in startNetFlag) { if (pNF != null) { pNetFlags.Add((INetFlag)pNF); } } } // pNetFlags.Add((INetFlag)startNetFlag); } if (pNetFlags.Count == 0) { return A4LGSharedFunctions.Localizer.GetString("AddFlagOrClickReturnStatement"); } // Stop if user point was not on a visible network feature, old trace results and selection are cleared if (gn == null || pNetFlags.Count == 0) { return A4LGSharedFunctions.Localizer.GetString("NotIntersectReturnStatement"); } bool fndAsLayer = false; pClosestLayer = Globals.FindLayer(app, targetFLName, ref fndAsLayer) as IFeatureLayer; if (pClosestLayer == null) { return A4LGSharedFunctions.Localizer.GetString("LayerNotFoundReturnStatement"); } if (processEvent) { pStepPro.Message = A4LGSharedFunctions.Localizer.GetString("GeoNetToolsProc_15a"); pStepPro.Step(); boolCont = pTrkCan.Continue(); } try { Globals.AddFlagsToTraceSolver(pNetFlags.ToArray(), ref traceFlowSolver, out junctionFlag, out edgeFlag); traceFlowSolver.FindFlowElements(esriFlowMethod.esriFMConnected, esriFlowElements.esriFEJunctions, out juncEIDs, out edgeEIDs); } catch { juncEIDs = null; edgeEIDs = null; if (processEvent) { pStepPro.Message = A4LGSharedFunctions.Localizer.GetString("ErrorInThe") + "FindFlowEndElements"; pStepPro.Step(); boolCont = pTrkCan.Continue(); } if (!boolCont) { pStepPro.Hide(); pProDlg.HideDialog(); pStepPro = null; pProDlg = null; pProDFact = null; return A4LGSharedFunctions.Localizer.GetString("CanceledReturnStatement"); } return A4LGSharedFunctions.Localizer.GetString("DontFindFlowEltReturnStatement"); //MessageBox.Show("Error in the FindFlowEndElements"); } eidHelper = new EIDHelperClass(); eidHelper.GeometricNetwork = gn; eidHelper.ReturnFeatures = true; //Save valves which stopped the trace if (processEvent) { pStepPro.Message = A4LGSharedFunctions.Localizer.GetString("GeoNetToolsProc_15b"); pStepPro.Step(); boolCont = pTrkCan.Continue(); } if (!boolCont) { pStepPro.Hide(); pProDlg.HideDialog(); pStepPro = null; pProDlg = null; pProDFact = null; return A4LGSharedFunctions.Localizer.GetString("CanceledReturnStatement"); } if (pClosestLayer.FeatureClass != null) { htClosestAsset = Globals.GetEIDInfoListByFC(pClosestLayer.FeatureClass.FeatureClassID, juncEIDs, eidHelper); } if (htClosestAsset.Count == 0) { if (processEvent) { pStepPro.Message = (A4LGSharedFunctions.Localizer.GetString("GeoNetToolsMess_15b") + targetFLName + A4LGSharedFunctions.Localizer.GetString("GeoNetToolsMess_15c")); pStepPro.Step(); boolCont = pTrkCan.Continue(); return A4LGSharedFunctions.Localizer.GetString("NoFeaturesReturnStatement"); } } if (!boolCont) { pStepPro.Hide(); pProDlg.HideDialog(); pStepPro = null; pProDlg = null; pProDFact = null; return A4LGSharedFunctions.Localizer.GetString("CanceledReturnStatement"); } traceFlowSolver = new TraceFlowSolverClass() as ITraceFlowSolverGEN; traceFlowSolver.TraceIndeterminateFlow = traceIndeterminate; netSolver = traceFlowSolver as INetSolver; netSolver.SourceNetwork = gn.Network; ////Globals.AddFlagsToTraceSolver(startNetFlag.ToArray(), ref traceFlowSolver, out junctionFlag, out edgeFlag); //Globals.AddFlagsToTraceSolver(pNetFlags.ToArray(), ref traceFlowSolver, out junctionFlag, out edgeFlag); Globals.AddBarriersToSolver(ref traceFlowSolver, ref pEdgeElementBarriers, ref pJunctionElementBarriers, ref pSelectionSetBarriers); pNetwork = gn.Network; pNetSchema = pNetwork as INetSchema; for (int i = 0; i < pNetSchema.WeightCount; i++) { pNetWeight = pNetSchema.get_Weight(i); if (pNetWeight.WeightName == sWeightName) break; } if (pNetWeight != null) { if (pNetWeight.WeightType == esriWeightType.esriWTBitGate || pNetWeight.WeightType == esriWeightType.esriWTNull) { pNetWeight = null; } } //Get trace weights if (pNetWeight != null) { pNetSolverW = traceFlowSolver as INetSolverWeights; pNetSolverW.JunctionWeight = pNetWeight; pNetSolverW.FromToEdgeWeight = pNetWeight; pNetSolverW.ToFromEdgeWeight = pNetWeight; } double shortest = 9999999.9; int pntAlong = 0; foreach (DictionaryEntry entry in htClosestAsset) { pntAlong++; ////Set the first junction flag for path finding based this current valve //netFlag1 = new JunctionFlagClass(); //netFlag1.UserClassID = valveEIDInfo.Feature.Class.ObjectClassID; //netFlag1.UserID = valveEIDInfo.Feature.OID; //netFlag1.UserSubID = 0; //netFlag1.Label = A4LGSharedFunctions.Localizer.GetString("GeoNetToolsLbl_16a"); //AddFlagToTraceSolver(netFlag1, ref traceFlowSolver, out junctionFlag, out edgeFlag); // startNetFlag[0].Label = A4LGSharedFunctions.Localizer.GetString("GeoNetToolsLbl_16a"); // startNetFlag[0].UserSubID = 0; //Set the second (and last) trace flag at this source //netFlag2 = new JunctionFlagClass(); //eidInfo = entry.Value as IEIDInfo; //netFlag2.UserClassID = eidInfo.Feature.Class.ObjectClassID; //netFlag2.UserID = eidInfo.Feature.OID; //netFlag2.UserSubID = 0; //netFlag2.Label = A4LGSharedFunctions.Localizer.GetString("GeoNetToolsLbl_16b"); eidInfo = entry.Value as IEIDInfo; IPoint pTmpPnt = eidInfo.Feature.Shape as IPoint; //ref point, ref map, ref gn, snapTol, out snappedPoint, // out EID, out distanceAlong, out pFlagDisplay, Flag); bool Flag = true; netFlag2 = Globals.GetEdgeFlagWithGN(ref pTmpPnt, ref map, ref gn, snapTol, out snappedPoint, out EID, out distanceAlong, out pFlagDisplay, Flag) as INetFlag; // Globals.AddTwoJunctionFlagsToTraceSolver(ref traceFlowSolver, netFlag1, netFlag2); Globals.AddTwoJunctionFlagsToTraceSolver(ref traceFlowSolver, startNetFlag[0], netFlag2); //Run trace segCosts = new System.Object[1]; segCosts[0] = new System.Object(); edgeEIDs = null; object pTotalCost = null; IEnumNetEID pJuncSel = null; IEnumNetEID pEdgeSel = null; //traceFlowSolver.FindAccumulation(esriFlowMethod.esriFMConnected, esriFlowElements.esriFEJunctionsAndEdges, out pJuncSel, out pEdgeSel,out pTotalCost); traceFlowSolver.FindPath(esriFlowMethod.esriFMConnected, esriShortestPathObjFn.esriSPObjFnMinSum, out juncEIDs, out edgeEIDs, 1, ref segCosts); if (Convert.ToDouble(segCosts[0]) < shortest) { shortest = Convert.ToDouble(segCosts[0]); } string test = ""; // if (edgeEIDs != null && edgeEIDs.Count > 0) // { // // foundSource = true; // // break; // } } MessageBox.Show(shortest.ToString()); //if (!boolCont) //{ // pStepPro.Hide(); // pProDlg.HideDialog(); // pStepPro = null; // pProDlg = null; // pProDFact = null; // return A4LGSharedFunctions.Localizer.GetString("CanceledReturnStatement"); //} //pointAlong++; //traceFlowSolver = new TraceFlowSolverClass() as ITraceFlowSolverGEN; //traceFlowSolver.TraceIndeterminateFlow = traceIndeterminate; //netSolver = traceFlowSolver as INetSolver; //netSolver.SourceNetwork = gn.Network; ////Globals.AddFlagsToTraceSolver(startNetFlag.ToArray(), ref traceFlowSolver, out junctionFlag, out edgeFlag); //Globals.AddFlagsToTraceSolver(pNetFlags.ToArray(), ref traceFlowSolver, out junctionFlag, out edgeFlag); //Globals.AddBarriersToSolver(ref traceFlowSolver, ref pEdgeElementBarriers, ref pJunctionElementBarriers, ref pSelectionSetBarriers); ////Set the barriers in the network based on the saved valves //netElementBarrier = new SelectionSetBarriersClass(); //foreach (DictionaryEntry entry in hasSourceValveHT) //{ // eidInfo = entry.Value as IEIDInfo; // //netElementBarrier.Add(valveFC.FeatureClassID, eidInfo.Feature.OID); // netElementBarrier.Add(((IFeatureClass)eidInfo.Feature.Class).FeatureClassID, eidInfo.Feature.OID); //} //netSolver.SelectionSetBarriers = netElementBarrier; //pointAlong++; ////Run last trace //traceFlowSolver.FindFlowElements(esriFlowMethod.esriFMConnected, esriFlowElements.esriFEJunctionsAndEdges, out juncEIDs, out edgeEIDs); ////skipped valves => //Hashtable skippedValvesEIDInfoHT = GetEIDInfoListByFC(valveFC.FeatureClassID, juncEIDs, eidHelper); ////Select junction features //pointAlong++; //51,44 ////Open identify dialog with selected features ////IdentifySelected(map); //if (processEvent) //{ // pStepPro.Message = A4LGSharedFunctions.Localizer.GetString("Complete"); // pStepPro.Step(); // boolCont = pTrkCan.Continue(); //} //if (!boolCont) //{ // pStepPro.Hide(); // pProDlg.HideDialog(); // pStepPro = null; // pProDlg = null; // pProDFact = null; // return A4LGSharedFunctions.Localizer.GetString("CanceledReturnStatement"); //} //if (snappedPoint != null) //{ // snappedPoint.Project(map.SpatialReference); // // traceRes.TracePoint = snappedPoint; //} //// return "Post1"; ////Globals.LoadJunctions(ref traceRes, ref gn, ref map, ref juncEIDs, ref meterDSName); //// Globals.LoadValves(ref traceRes, ref gn, ref map, ref hasSourceValveHT); ////Globals.LoadEdges(ref traceRes, ref gn, ref map, ref edgeEIDs); ////((IMxDocument)app.Document).FocusMap.ClearSelection(); ////Globals.RemoveGraphics(((IMxDocument)app.Document).FocusMap, false); //string returnVal = ""; //returnVal = Globals.SelectJunctions(ref map, ref gn, ref juncEIDs, ref junctionFlag, MeterName, MeterCritField, MeterCritVal, processEvent); //if (processEvent) //{ // if (selectEdges) // Globals.SelectEdges(ref map, ref gn, ref edgeEIDs); // else // Globals.DrawEdges(ref map, ref gn, ref edgeEIDs); //} //returnVal = Globals.SelectValveJunctions(ref map, ref hasSourceValveHT, ref valveFLs, processEvent) + "_" + returnVal; //if (processEvent) //{ // if (pNetAnalysisExt != null) // { // foreach (IFlagDisplay pFgDi in pFlagsDisplay) // { // Globals.AddFlagToGN(ref pNetAnalysisExt, ref gn, pFgDi); // // Globals.AddPointGraphic(map, pFgDi.Geometry as IPoint, false); // } // } // else // { // foreach (IFlagDisplay pFgDi in pFlagsDisplay) // { // // Globals.AddFlagToGN(ref pNetAnalysisExt, ref gn, pFgDi); // Globals.AddPointGraphic(map, pFgDi.Geometry as IPoint, false); // } // } // Globals.GetCommand("esriArcMapUI.ZoomToSelectedCommand", app).Execute(); //} string returnVal = ""; return returnVal; } catch (Exception ex) { // MessageBox.Show(ex.ToString()); return ex.Message.ToString(); } finally { barrierIds = null; sourceDirectEIDInfoHT = null; netFlag1 = null; netFlag2 = null; junctionFlags = null; edgeFlags = null; pID = null; if (pProDlg != null) { pProDlg.HideDialog(); } pStepPro = null; pProDlg = null; pProDFact = null; if (gnList != null) { // Marshal.ReleaseComObject(gnList); } if (gn != null) { Marshal.ReleaseComObject(gn); } if (snappedPoint != null) { Marshal.ReleaseComObject(snappedPoint); } if (startNetFlag != null) { // Marshal.ReleaseComObject(startNetFlag); } if (junctionFlag != null) { Marshal.ReleaseComObject(junctionFlag); } if (edgeFlag != null) { // Marshal.ReleaseComObject(edgeFlag); } if (traceFlowSolver != null) { Marshal.ReleaseComObject(traceFlowSolver); } if (netSolver != null) { Marshal.ReleaseComObject(netSolver); } if (netElementBarriers != null) { Marshal.ReleaseComObject(netElementBarriers); } if (nb != null) { Marshal.ReleaseComObject(nb); } if (juncEIDs != null) { Marshal.ReleaseComObject(juncEIDs); } if (edgeEIDs != null) { Marshal.ReleaseComObject(edgeEIDs); } if (eidInfo != null) { Marshal.ReleaseComObject(eidInfo); } if (valveEIDInfo != null) { Marshal.ReleaseComObject(valveEIDInfo); } if (sourceEIDInfo != null) { Marshal.ReleaseComObject(sourceEIDInfo); } if (vEIDInfo != null) { Marshal.ReleaseComObject(vEIDInfo); } if (userIds != null) { // Marshal.ReleaseComObject(userIds); } if (eidHelper != null) { Marshal.ReleaseComObject(eidHelper); } if (valveEIDInfoHT != null) { // Marshal.ReleaseComObject(valveEIDInfoHT); } if (sourceEIDInfoHT != null) { // Marshal.ReleaseComObject(sourceEIDInfoHT); } if (segCosts != null) { // Marshal.ReleaseComObject(segCosts); } if (netElementBarrier != null) { Marshal.ReleaseComObject(netElementBarrier); } //if (traceRes != null) //{ // traceRes.Dispose(); // // Marshal.ReleaseComObject(traceRes); //} pNetAnalysisExt = null; pFlagsDisplay = null; pEdgeFlags = null; pJunctionFlags = null; pNetFlags = null; pFlagDisplay = null; //pEdgeFlagsBar = null; //pJunctionFlagsBar = null; gnList = null; gn = null; snappedPoint = null; startNetFlag = null; junctionFlag = null; edgeFlag = null; traceFlowSolver = null; netSolver = null; netElementBarriers = null; nb = null; juncEIDs = null; edgeEIDs = null; eidInfo = null; valveEIDInfo = null; sourceEIDInfo = null; vEIDInfo = null; userIds = null; eidHelper = null; valveEIDInfoHT = null; sourceEIDInfoHT = null; segCosts = null; netElementBarrier = null; //traceRes = null; } GC.Collect(); GC.WaitForFullGCComplete(300); }
public static void EstablishFlow(Globals.GNFlowDirection flowDirection, IApplication app) { IProgressDialog2 progressDialog = default(IProgressDialog2); IProgressDialogFactory progressDialogFactory = null; IEditor editor = null; IEditLayers eLayers = null; IMouseCursor appCursor = null; INetworkAnalysisExt netExt = null; UID pUID = null; IMap pMap = null; List<IGeometricNetwork> gnList = null; ITrackCancel trackCancel = null; Int32 int32_hWnd; IStepProgressor stepProgressor = null; IMxDocument mxdoc = null; try { int calcCount = 0; //Get editor editor = Globals.getEditor(ref app); if (editor.EditState != esriEditState.esriStateEditing) { MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("MustBEditg"), A4LGSharedFunctions.Localizer.GetString("GeoNetToolsLbl_2")); return; } eLayers = editor as IEditLayers; //Change mouse cursor to wait - automatically changes back (ArcGIS Desktop only) appCursor = new MouseCursorClass(); appCursor.SetCursor(2); ESRI.ArcGIS.esriSystem.IStatusBar statusBar = app.StatusBar; statusBar.set_Message(0, A4LGSharedFunctions.Localizer.GetString("GeoNetToolsWait_1")); //Get NA Extension in order to update the current network with the first visible network pUID = new UIDClass(); pUID.Value = "esriEditorExt.UtilityNetworkAnalysisExt"; netExt = app.FindExtensionByCLSID(pUID) as INetworkAnalysisExt; //Get Visible geometric networks pMap = editor.Map; gnList = Globals.GetGeometricNetworksCurrentlyVisible(ref pMap); if (gnList.Count > 0) { //ProgressBar progressDialogFactory = new ProgressDialogFactoryClass(); // Create a CancelTracker trackCancel = new CancelTrackerClass(); // Set the properties of the Step Progressor int32_hWnd = app.hWnd; stepProgressor = progressDialogFactory.Create(trackCancel, int32_hWnd); stepProgressor.MinRange = 0; stepProgressor.MaxRange = gnList.Count; stepProgressor.StepValue = 1; stepProgressor.Message = ""; stepProgressor.Hide(); // Create the ProgressDialog. This automatically displays the dialog progressDialog = (ESRI.ArcGIS.Framework.IProgressDialog2)stepProgressor; // Explict Cast // Set the properties of the ProgressDialog progressDialog.CancelEnabled = false; progressDialog.Description = A4LGSharedFunctions.Localizer.GetString("GeoNetToolsDesc_1"); progressDialog.Title = A4LGSharedFunctions.Localizer.GetString("GeoNetToolsTitle_1"); progressDialog.Animation = ESRI.ArcGIS.Framework.esriProgressAnimationTypes.esriProgressSpiral; bool editStarted = false; try {// Create an edit operation enabling undo/redo editor.StartOperation(); editStarted = true; } catch { editStarted = false; } IGeometricNetwork gn = null; IEnumFeatureClass enumFC = null; INetwork net = null; IUtilityNetworkGEN unet = null; IEnumNetEID edgeEIDs = null; //IFeatureLayer fLayer = null; try { for (int i = 0; i < gnList.Count; i++) { gn = gnList[i] as IGeometricNetwork; // fLayer = Globals.FindLayerByFeatureClass(pMap, gn.OrphanJunctionFeatureClass, false); //if (fLayer == null) //{ // MessageBox.Show("Unable to set flow direction for " + gn.FeatureDataset.Name + ". Add the " + gn.OrphanJunctionFeatureClass.AliasName + " to your map and try again, if needed", "Establish Flow Direction"); // stepProgressor.Step(); // continue; //} //if (!eLayers.IsEditable(fLayer)) //{ // MessageBox.Show("Unable to set flow direction for " + gn.FeatureDataset.Name + ". It is visible but not editable.", "Establish Flow Direction"); // stepProgressor.Step(); // continue; //} stepProgressor.Message = A4LGSharedFunctions.Localizer.GetString("GeoNetToolsProc_1");// +fLayer.Name; //Establish flow using AncillaryRole values if (flowDirection == Globals.GNFlowDirection.AncillaryRole) { enumFC = gn.get_ClassesByNetworkAncillaryRole(esriNetworkClassAncillaryRole.esriNCARSourceSink); if (enumFC.Next() == null) MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("GeoNetToolsError_1a") + gn.FeatureDataset.Name + A4LGSharedFunctions.Localizer.GetString("GeoNetToolsError_1b") + Environment.NewLine + A4LGSharedFunctions.Localizer.GetString("GeoNetToolsError_1c"), A4LGSharedFunctions.Localizer.GetString("GeoNetToolsProc_2")); else { gn.EstablishFlowDirection(); calcCount += 1; } } //Establish flow direction based on digitized direction. else { net = gn.Network; unet = net as IUtilityNetworkGEN; edgeEIDs = net.CreateNetBrowser(esriElementType.esriETEdge); edgeEIDs.Reset(); int edgeEID; for (long j = 0; j < edgeEIDs.Count; j++) { edgeEID = edgeEIDs.Next(); unet.SetFlowDirection(edgeEID, esriFlowDirection.esriFDWithFlow); } calcCount += 1; } stepProgressor.Step(); } } catch (Exception ex) { editor.AbortOperation(); MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("GeoNetToolsProc_2") + "\n" + ex.Message, ex.Source); } finally { if (enumFC != null) Marshal.ReleaseComObject(enumFC); gn = null; enumFC = null; net = null; unet = null; edgeEIDs = null; //fLayer = null; } if (editStarted) { // Stop the edit operation if (flowDirection == Globals.GNFlowDirection.AncillaryRole) editor.StopOperation(A4LGSharedFunctions.Localizer.GetString("GeoNetToolsProc_2")); else editor.StopOperation(A4LGSharedFunctions.Localizer.GetString("GeoNetToolsProc_3")); } object Missing = Type.Missing; mxdoc = app.Document as IMxDocument; mxdoc.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGraphics, Missing, mxdoc.ActiveView.Extent); if (app != null) app.StatusBar.set_Message(2, A4LGSharedFunctions.Localizer.GetString("GeoNetToolsMess_1a") + calcCount + A4LGSharedFunctions.Localizer.GetString("GeoNetToolsMess_1b")); } } catch (Exception ex) { MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("GeoNetToolsProc_2") + "\n" + ex.Message, ex.Source); return; } finally { // Cleanup if (progressDialog != null) progressDialog.HideDialog(); progressDialog = null; progressDialogFactory = null; editor = null; eLayers = null; appCursor = null; netExt = null; pUID = null; pMap = null; gnList = null; trackCancel = null; stepProgressor = null; mxdoc = null; } }
internal void Solve(IFeatureLayer tilelayoutfeaturelayer, IFeatureClass tilelayoutfeatureclass, string lasfolder, string lastoolsfolder, bool useselected, int tilenamefieldindex, decimal numberofprocesses) { _batches = new List <string>(); ITrackCancel trackcancel = new CancelTrackerClass(); IProgressDialogFactory progressdialogfactory = new ProgressDialogFactoryClass(); IStepProgressor stepprogressor = progressdialogfactory.Create(trackcancel, _application.hWnd); stepprogressor.MinRange = 0; stepprogressor.MaxRange = tilelayoutfeatureclass.FeatureCount(null); stepprogressor.StepValue = 1; stepprogressor.Message = "Tiles"; _progressdialog = (IProgressDialog2)stepprogressor; // Explict Cast _progressdialog.CancelEnabled = true; _progressdialog.Description = "Processing " + tilelayoutfeatureclass.FeatureCount(null).ToString() + " tile(s)."; _progressdialog.Title = "Processing..."; _progressdialog.Animation = esriProgressAnimationTypes.esriProgressSpiral; IGeoDataset geodataset = null; if (tilelayoutfeatureclass is ESRI.ArcGIS.Geodatabase.IGeoDataset) { geodataset = (IGeoDataset)tilelayoutfeatureclass; } else { MessageBox.Show("No projection found", "Boundary Problem", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } string mergedfolder = System.IO.Path.Combine(lasfolder, "merged"); if (System.IO.Directory.Exists(mergedfolder)) { try { System.IO.Directory.Delete(mergedfolder, true); } catch (Exception) { throw; } Thread.Sleep(1000); } try { System.IO.Directory.CreateDirectory(mergedfolder); } catch (Exception) { throw; } string shpfolder = System.IO.Path.Combine(lasfolder, "shp"); if (System.IO.Directory.Exists(shpfolder)) { try { System.IO.Directory.Delete(shpfolder, true); } catch (Exception) { throw; } Thread.Sleep(1000); } try { System.IO.Directory.CreateDirectory(shpfolder); } catch (Exception) { throw; } string clipfolder = System.IO.Path.Combine(lasfolder, "clipped"); if (System.IO.Directory.Exists(clipfolder)) { try { System.IO.Directory.Delete(clipfolder, true); } catch (Exception) { throw; } Thread.Sleep(1000); } try { System.IO.Directory.CreateDirectory(clipfolder); } catch (Exception) { throw; } try { int count = 1; StringBuilder indexbatchscript = new StringBuilder(); indexbatchscript.AppendLine("set PATH=\"" + lastoolsfolder + "\""); StringBuilder mergebatchscript = new StringBuilder(); bool writescripts = false; if (useselected) { IFeatureSelection featureselection = tilelayoutfeaturelayer as IFeatureSelection; int featurecount = featureselection.SelectionSet.Count; stepprogressor.MaxRange = featureselection.SelectionSet.Count; _progressdialog.Description = "Processing " + featureselection.SelectionSet.Count.ToString() + " tile(s)."; IEnumIDs enumIDs = featureselection.SelectionSet.IDs; enumIDs.Reset(); int intOID = enumIDs.Next(); while (intOID != -1) { IFeature feature = tilelayoutfeatureclass.GetFeature(intOID); if (feature != null) { IPolygon polygon = null; string tilename = feature.get_Value(tilenamefieldindex).ToString(); string command = BuildMergedCommand(feature, tilename, lasfolder, tilelayoutfeatureclass, tilenamefieldindex, out polygon); if (command.Length > 0) { string entry = "lasindex -i " + tilename + ".las"; indexbatchscript.AppendLine(entry); entry = "lasmerge " + command + " -o merged\\" + tilename + ".las"; mergebatchscript.AppendLine(entry); CreateShapefile(tilename, polygon, shpfolder, geodataset.SpatialReference); writescripts = true; } } intOID = enumIDs.Next(); bool cont = trackcancel.Continue(); if (!cont) { break; } stepprogressor.Message = "Processing segment " + count.ToString() + " of " + featurecount.ToString(); stepprogressor.Step(); count++; } } else { int featurecount = tilelayoutfeatureclass.FeatureCount(null); IFeatureCursor featurecursor = tilelayoutfeatureclass.Search(null, false); IFeature feature = null; while ((feature = featurecursor.NextFeature()) != null) { IPolygon polygon = null; string tilename = feature.get_Value(tilenamefieldindex).ToString(); string command = BuildMergedCommand(feature, tilename, lasfolder, tilelayoutfeatureclass, tilenamefieldindex, out polygon); if (command.Length > 0) { string entry = "lasindex -i " + tilename + ".las"; indexbatchscript.AppendLine(entry); entry = "lasmerge " + command + " -o merged\\" + tilename + ".las"; mergebatchscript.AppendLine(entry); CreateShapefile(tilename, polygon, shpfolder, geodataset.SpatialReference); writescripts = true; } bool cont = trackcancel.Continue(); if (!cont) { break; } stepprogressor.Message = "Processing segment " + count.ToString() + " of " + featurecount.ToString(); stepprogressor.Step(); count++; } } if (writescripts) { string mergefilepath = System.IO.Path.Combine(lasfolder, "_merge.bat"); if (System.IO.File.Exists(mergefilepath)) { try { System.IO.File.Delete(mergefilepath); } catch (Exception) { throw; } } string indexfilepath = System.IO.Path.Combine(lasfolder, "_index.bat"); if (System.IO.File.Exists(indexfilepath)) { try { System.IO.File.Delete(indexfilepath); } catch (Exception) { throw; } } //===================== try { System.IO.File.WriteAllText(indexfilepath, indexbatchscript.ToString()); _batches.Add(indexfilepath); } catch (Exception) { throw; } //===================== //***** if ((int)numberofprocesses == 1) { try { using (StreamWriter sr = new StreamWriter(mergefilepath)) { sr.WriteLine("set PATH=\"" + lastoolsfolder + "\""); sr.Write(mergebatchscript.ToString()); } System.IO.File.WriteAllText(mergefilepath, mergebatchscript.ToString()); _batches.Add(mergefilepath); } catch (Exception) { throw; } } else { try { int linecount = 0, filecount = 0, batchlinecount = 0; String[] lines = mergebatchscript.ToString().Split(System.Environment.NewLine.ToCharArray()); var newlines = new List <string>(); foreach (string line in lines) { string newline = line.Trim(); if (newline.Length > 0) { newlines.Add(newline); } } batchlinecount = (int)(newlines.Count / numberofprocesses) + 1; do { if (batchlinecount >= (newlines.Count / numberofprocesses)) { batchlinecount = 0; filecount++; mergefilepath = System.IO.Path.Combine(lasfolder, "_merge_" + filecount + ".bat"); if (System.IO.File.Exists(mergefilepath)) { try { System.IO.File.Delete(mergefilepath); } catch (Exception) { throw; } } using (StreamWriter sw = new StreamWriter(mergefilepath, true)) { sw.WriteLine("set PATH=\"" + lastoolsfolder + "\""); } _batches.Add(mergefilepath); } using (StreamWriter sw = new StreamWriter(mergefilepath, true)) { sw.WriteLine(newlines[linecount]); sw.WriteLine(BuildIndexCommand(newlines[linecount])); sw.WriteLine(BuildClipCommand(newlines[linecount])); } linecount++; batchlinecount++; } while (linecount < newlines.Count); } catch (Exception) { throw; } } } } catch (Exception ex) { MessageBox.Show(ex.Message, "Boundary Problem", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } finally { trackcancel = null; stepprogressor = null; _progressdialog.HideDialog(); _progressdialog = null; } }
/// <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(); }
static void Main(string[] args) { //arg 0 = source layer string file gdb string with feature class name //arg 1 = target layer path for fabric layer //arg 2 = control point tolerance (in projection units) to match with existing fabric points, -1 means don't do it //arg 3 = merge tolerance. Merge with existing control points if within tolerance, -1 means turn off merging //arg 4 = control merging choices for attributes [KeepExistingAttributes | UpdateExistingAttributes] //arg 5 = must have same name to merge if within the tolerance? [NamesMustMatchToMerge | IgnoreNames] //arg 6 = if control is merged keep existing names or update with incoming names? [KeepExistingNames | UpdateExistingNames] //.....(arg 6 is ignored if arg 5 = NamesMustMatchToMerge) //arg 7 = control merging choices for coordinates [UpdateXY | UpdateXYZ | UpdateZ | KeepExistingXYZ] //arg 8 = create a log file at the same location as the executable? [LoggingOn | LoggingOff] //.....(a log file is always generated unless LoggingOff is explcitly used) //ESRI License Initializer generated code. m_AOLicenseInitializer.InitializeApplication(new esriLicenseProductCode[] { esriLicenseProductCode.esriLicenseProductCodeStandard, esriLicenseProductCode.esriLicenseProductCodeAdvanced }, new esriLicenseExtensionCode[] { }); //ESRI License Initializer generated code. //Do not make any call to ArcObjects after ShutDownApplication() int iLen = args.Length; if (iLen < 2) { UsageMessage(); m_AOLicenseInitializer.ShutdownApplication(); return; } ITrackCancel pTrkCan = new CancelTrackerClass(); // Create and display the Progress Dialog IProgressDialogFactory pProDlgFact = new ProgressDialogFactoryClass(); IProgressDialog2 pProDlg = pProDlgFact.Create(pTrkCan, 0) as IProgressDialog2; try { ICadastralControlImporter pControlPointCadastralImp = new CadastralControlImporterClass(); // args[0] ============================================ string PathToFileGDBandFeatureClass = args[0]; if (args[0].Contains(":") && args[0].Contains("\\")) { PathToFileGDBandFeatureClass = args[0]; } else { string[] sExecPathArr = System.Reflection.Assembly.GetEntryAssembly().Location.Split('\\'); string x = ""; for (int i = 0; i < (sExecPathArr.Length - 1); i++) { x += sExecPathArr[i] + "\\"; } PathToFileGDBandFeatureClass = x + PathToFileGDBandFeatureClass; } string[] PathToFileGDBArray = PathToFileGDBandFeatureClass.Split('\\'); string NameOfSourceFeatureClass = PathToFileGDBArray[PathToFileGDBArray.Length - 1]; string PathToFileGDB = ""; for (int i = 0; i < (PathToFileGDBArray.Length - 1); i++) { PathToFileGDB += PathToFileGDBArray[i] + "\\"; } PathToFileGDB = PathToFileGDB.TrimEnd('\\'); if (!System.IO.Directory.Exists(PathToFileGDB)) { throw new Exception("File does not exist. [" + PathToFileGDB + "]"); } // args[1] ============================================ string layerFilePathToFabric = args[1]; if (!(layerFilePathToFabric.Contains(":") && layerFilePathToFabric.Contains("\\"))) { string[] sExecPathArr = System.Reflection.Assembly.GetEntryAssembly().Location.Split('\\'); string x = ""; for (int i = 0; i < (sExecPathArr.Length - 1); i++) { x += sExecPathArr[i] + "\\"; } layerFilePathToFabric = x + layerFilePathToFabric; } if (!System.IO.File.Exists(layerFilePathToFabric)) { throw new Exception("File does not exist. [" + layerFilePathToFabric + "]"); } ILayerFile layerFileToTargetFabric = new LayerFileClass(); layerFileToTargetFabric.Open(layerFilePathToFabric); ILayer pLayer = layerFileToTargetFabric.Layer; ICadastralFabricLayer pParcelFabLyr = pLayer as ICadastralFabricLayer; ICadastralFabric pParcelFabric = pParcelFabLyr.CadastralFabric; IDataset pDS = pParcelFabric as IDataset; IName pDSName = pDS.FullName; ICadastralFabricName pCadastralFabricName = pDSName as ICadastralFabricName; IWorkspaceFactory workspaceFactory = new FileGDBWorkspaceFactory(); IFeatureWorkspace pFWS = (IFeatureWorkspace)workspaceFactory.OpenFromFile(PathToFileGDB, 0); pDS = (IDataset)pFWS.OpenFeatureClass(NameOfSourceFeatureClass); IName pSourceFeatClassName = pDS.FullName; // args[2] ============================================ bool bHasControlTolerance = iLen > 2; double dControlToFabricPointMatchTolerance = -1; if (bHasControlTolerance) { if (!Double.TryParse(args[2], out dControlToFabricPointMatchTolerance)) { throw new Exception("The third parameter should be a numeric value. [" + args[2] + "]"); } } pControlPointCadastralImp.ControlPointTolerance = dControlToFabricPointMatchTolerance; //'***** performance, -1 means that matching to existing fabric points is turned off pControlPointCadastralImp.UseShapeField = true; //============= Arguments for merging control points =============== // args[3] [4] [5] [6] [7] ============================================ bool bIsMergingControlPoints = (iLen == 7); if (bIsMergingControlPoints) { //arg 3 = merge tolerance. Merge with existing control points if within tolerance, -1 means turn off merging //arg 4 = control merging choices for attributes [KeepExistingAttributes | UpdateExistingAttributes] //arg 5 = must have same name to merge if within the tolerance? [NamesMustMatchToMerge | IgnoreNames] //arg 6 = if control is merged keep existing names or update with incoming names? [KeepExistingNames | UpdateExistingNames] //.....(arg 6 is ignored if arg 5 = NamesMustMatchToMerge) //arg 7 = control merging choices for coordinates [UpdateXY | UpdateXYZ | UpdateZ | KeepExistingXYZ] double dControlPointMergingTolerance = -1; if (!Double.TryParse(args[3], out dControlPointMergingTolerance)) { { throw new Exception("The fourth parameter should be a numeric value. [" + args[3] + "]"); } } ICadastralControlImporterMerging pImpMerge = pControlPointCadastralImp as ICadastralControlImporterMerging; pImpMerge.MergeCloseControl = dControlPointMergingTolerance > 0; pImpMerge.CloseControlTolerance = dControlPointMergingTolerance; if (args[4].ToLower().Contains("updateexistingattributes")) { pImpMerge.MergeAttributesOption = esriCFControlMergingAttributes.esriCFControlMergingUpdateAttributes; } else { pImpMerge.MergeAttributesOption = esriCFControlMergingAttributes.esriCFControlMergingKeepAttributes; } pImpMerge.MergeControlNameCaseSensitive = false; pImpMerge.MergeControlSameName = args[5].ToLower().Contains("namesmustmatchtomerge"); if (args[6].ToLower().Contains("updateexistingnames") && !args[5].ToLower().Contains("namesmustmatchtomerge")) { pImpMerge.MergeNameOption = esriCFControlMergingName.esriCFControlMergingUpdateExistingNames; } else { pImpMerge.MergeNameOption = esriCFControlMergingName.esriCFControlMergingKeepExistingNames; } if (args[7].ToLower() == "updatexy") { pImpMerge.MergeCoordinateOption = esriCFControlMergingCoordinate.esriCFControlMergingUpdateXY; } else if (args[7].ToLower() == "updatexyz") { pImpMerge.MergeCoordinateOption = esriCFControlMergingCoordinate.esriCFControlMergingUpdateXYZ; } else if (args[7].ToLower() == "updatez") { pImpMerge.MergeCoordinateOption = esriCFControlMergingCoordinate.esriCFControlMergingUpdateZ; } else if (args[7].ToLower() == "keepexistingxyz") { pImpMerge.MergeCoordinateOption = esriCFControlMergingCoordinate.esriCFControlMergingKeepExistingCoordinates; } } ICadastralImporter pControlImporter = (ICadastralImporter)pControlPointCadastralImp; bool bHasExplicitLogFileParameter = (iLen > 8); bool bExplicitTurnLoggingOff = false; /// Argument for logging importer results //arg 8 = create a log file at the same location as the executable? [LoggingOn | LoggingOff | <path to logfile>] //.....(a log file is always generated unless LoggingOff is explcitly used) string sLogFilePath = "LogControlImport"; if (bHasExplicitLogFileParameter) { if (args[8].ToLower() == "loggingoff") { bExplicitTurnLoggingOff = true; } if (args[8].ToLower() != "loggingon" && !bExplicitTurnLoggingOff) { if (args[8].Contains(":") && args[8].Contains("\\")) //if (args[8].ToLower() != "loggingon") { sLogFilePath = args[8]; } else { string[] sExecPathArr = System.Reflection.Assembly.GetEntryAssembly().Location.Split('\\'); string x = ""; for (int i = 0; i < (sExecPathArr.Length - 1); i++) { x += sExecPathArr[i] + "\\"; } sLogFilePath = x + args[8]; } } } else { string[] sExecPathArr = System.Reflection.Assembly.GetEntryAssembly().Location.Split('\\'); string x = ""; for (int i = 0; i < (sExecPathArr.Length - 1); i++) { x += sExecPathArr[i] + "\\"; } sLogFilePath = x + sLogFilePath; } sLogFilePath += ".log"; if (!bExplicitTurnLoggingOff) { pControlImporter.OutputLogfile = sLogFilePath; //default location is same as executable } //Set the properties of the Progress Dialog pProDlg.CancelEnabled = false; pProDlg.Description = "Importing Control Point data ..."; pProDlg.Title = "Importing Control Points"; pProDlg.Animation = esriProgressAnimationTypes.esriProgressGlobe; Console.WriteLine("Starting data load..."); pControlImporter.Import(pSourceFeatClassName, pCadastralFabricName, pTrkCan); //BUG fails if the TrackCancel is null Console.WriteLine("Finished data load..."); } catch (Exception ex) { Console.WriteLine(ex.Message); //UsageMessage(); } finally { if (pProDlg != null) { pProDlg.HideDialog(); } m_AOLicenseInitializer.ShutdownApplication(); } }
public static void batchLoadBarriers(IApplication app) { bool fndAsLayer = false; List<string> strFiles = new List<string>(); IEnumLayer pLays = null; IProgressDialogFactory pProDFact = null; IStepProgressor pStepPro = null; IProgressDialog2 pProDlg = null; ITrackCancel pTrkCan = null; IFeatureLayer pFl = null; IFeatureCursor featureCursor = null; IFeature feature = null; IFeatureLayerDefinition2 pFLD = null; IQueryFilter pQF = null; ILayer pLay = null; bool boolCont = true; int featCount = 0; try { double seTol = ConfigUtil.GetConfigValue("Trace_Click_Point_Tolerence", 5.0); pLays = Globals.GetLayers(app, "VECTOR"); if (pLays != null) { pLay = pLays.Next(); while (pLay != null) { if (pLay is IFeatureLayer) { if (((IFeatureLayer)pLay).FeatureClass != null) { if (((IFeatureLayer)pLay).FeatureClass.ShapeType == esriGeometryType.esriGeometryPoint) { strFiles.Add(pLay.Name); } } } pLay = pLays.Next(); } //MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("GeoNetToolsLbl_1") + "\n" + ex.Message, ex.Source); string strRetVal = Globals.showOptionsForm(strFiles, A4LGSharedFunctions.Localizer.GetString("GeoNetToolsBatchBarrier"), ComboBoxStyle.DropDownList); if (strRetVal != null && strRetVal != "||Cancelled||") { pFl = (IFeatureLayer)Globals.FindLayer(app, strRetVal, ref fndAsLayer); if (pFl == null) { MessageBox.Show(strRetVal + A4LGSharedFunctions.Localizer.GetString("AttributeAssistantEditorMess_14bb")); return; } if (pFl.FeatureClass == null) { MessageBox.Show(strRetVal + A4LGSharedFunctions.Localizer.GetString("GeoNetToolsError_18d")); return; } pFLD = (IFeatureLayerDefinition2)pFl; // Create a CancelTracker pTrkCan = new CancelTrackerClass(); // Create the ProgressDialog. This automatically displays the dialog pProDFact = new ProgressDialogFactoryClass(); pProDlg = (IProgressDialog2)pProDFact.Create(pTrkCan, 0); // Set the properties of the ProgressDialog pProDlg.CancelEnabled = true; pProDlg.Animation = esriProgressAnimationTypes.esriProgressGlobe; // Set the properties of the Step Progressor pStepPro = (IStepProgressor)pProDlg; pStepPro.MinRange = 0; pQF = new QueryFilterClass(); if (pFLD.DefinitionExpression.Trim() == "") { featCount = pFl.FeatureClass.FeatureCount(null); } else { pQF.WhereClause = pFLD.DefinitionExpression; featCount = pFl.FeatureClass.FeatureCount(pQF); } if (featCount == 0) { return; } pStepPro.MaxRange = featCount; pStepPro.StepValue = 1; pStepPro.Position = 0; pStepPro.Message = A4LGSharedFunctions.Localizer.GetString("GeoNetToolsProc_6"); featureCursor = pFl.Search(null, false); feature = featureCursor.NextFeature(); while (feature != null) { if (!boolCont) { pStepPro.Hide(); pProDlg.HideDialog(); pStepPro = null; pProDlg = null; pProDFact = null; return; } if (A4WaterUtilities.GeoNetTools.AddBarrier(feature.Shape as IPoint, app, seTol, false) == false) { return; } feature = featureCursor.NextFeature(); pStepPro.Step(); boolCont = pTrkCan.Continue(); } if (featureCursor != null) { Marshal.ReleaseComObject(featureCursor); } } } } catch (Exception ex) { System.Diagnostics.Debug.Write(ex.Message); } finally { if (pProDlg != null) { pProDlg.HideDialog(); } pStepPro = null; pProDlg = null; pProDFact = null; pTrkCan = null; pLays = null; pFl = null; featureCursor = null; feature = null; pFLD = null; pQF = null; pLay = null; } }
/// <summary> /// Occurs when this command is clicked /// </summary> public override void OnClick() { try { if (m_application == null) { return; } IDocument document = m_application.Document; //根据应用类型初始化 switch (applicationType) { case ApplicationType.ArcMap: { IMxDocument mxDocument = (IMxDocument)(document); if (mxDocument != null) { m_map = mxDocument.FocusMap; } if (m_map == null) { return; } activeView = m_map as IActiveView; //有图层则选颜色 if (m_map.LayerCount == 0) { return; } if (Common.SelectColor(out FromIC, out ToIC) == false) { return; } //选图层 if (Common.SelectLayer(m_map.Layers, out SelectedLyrIndex) == false) { return; } break; } case ApplicationType.ArcScene: { 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.SelectColor(out FromIC, out ToIC) == false) { return; } //选图层 if (Common.SelectLayer(m_scene.Layers, out SelectedLyrIndex) == false) { return; } break; } default: { throw new ArgumentException("未指定应用类型。"); } } //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 = null; switch (applicationType) { case ApplicationType.ArcMap: { rasterLayer = m_map.Layer[SelectedLyrIndex[i]] as IRasterLayer; break; } case ApplicationType.ArcScene: { rasterLayer = m_scene.Layer[SelectedLyrIndex[i]] as IRasterLayer; break; } default: { throw new ArgumentException("未指定应用类型。"); } } if (rasterLayer == null) { pStepPro.Message = "选中的图层非栅格图层..."; continue; } //设置图层渲染器并更新 IRasterRenderer pRasterRenderer = UniqueValueRender(rasterLayer); //渲染唯一值 rasterLayer.Renderer = pRasterRenderer; rasterLayer.Renderer.Update(); //========================================== //刷新看起来不起作用 if (applicationType == ApplicationType.ArcScene) { m_scene.SceneGraph.Invalidate(rasterLayer, true, false); m_sceneHookHelper.ActiveViewer.Redraw(true); m_scene.SceneGraph.RefreshViewers(); //pRasterRenderer.Draw(rasterLayer.Raster,esriDrawPhase.esriDPGeography,display,null); } //========================================== } pProDlg.HideDialog(); //刷新 if (activeView == null) { throw new Exception("活动视图为空! "); } switch (applicationType) { case ApplicationType.ArcMap: { activeView.Refresh(); break; } case ApplicationType.ArcScene: { //========================================== //刷新看起来不起作用 //if (m_sceneHookHelper.ActiveViewer == null) // throw new Exception("无活动视图。"); activeView.Refresh(); //m_sceneHookHelper.ActiveViewer.Redraw(true); //IDisplay display = m_scene.SceneGraph as IDisplay; //if (display == null) // throw new ArgumentNullException("显示对象为空。"); //for (int i = 0; i < SelectedLyrIndex.Count; i++) //{ // IRasterLayer rasterLayer = m_scene.Layer[SelectedLyrIndex[i]] as IRasterLayer; // rasterLayer.Draw(esriDrawPhase.esriDPGeography, display, null); //} //IViewers3D viewers3D = m_scene.SceneGraph as IViewers3D; //if (viewers3D == null) // throw new ArgumentNullException("3D显示对象为空。"); //viewers3D.RefreshViewers(); break; //========================================== } default: { throw new ArgumentException("未指定应用类型。"); } } } catch (Exception err) { MessageBox.Show(err.ToString()); } }
private void CreateBatchFile() { string path = ""; FolderBrowserDialog fbd = new FolderBrowserDialog(); if (fbd.ShowDialog() == DialogResult.OK) { path = fbd.SelectedPath; } if (!Directory.Exists(path)) { Utilities_MessageBox.ErrorBox("Path Does Not Exist", MB_TITLE); return; } int versionCount = 1; // This is used to make mutiple files so the batch file don't overwrite on another. string filePath = path + string.Format(@"\{0}_{1}_{2}.bat", cbo_TileIndex.Text, "CopyFiles", versionCount); while (File.Exists(filePath)) { versionCount++; filePath = path + string.Format(@"\{0}_{1}_{2}.bat", cbo_TileIndex.Text, "CopyFiles", versionCount); } bool itWorked = false; int cloneCount = 1; // labeling the processor bar ITrackCancel trackcancel = new CancelTracker(); IProgressDialogFactory progressdialogfactory = new ProgressDialogFactoryClass(); IStepProgressor stepprogressor = progressdialogfactory.Create(trackcancel, _application.hWnd); stepprogressor.MinRange = 0; stepprogressor.MaxRange = _fileList.Count; stepprogressor.StepValue = 1; stepprogressor.Message = "Generating..."; IProgressDialog2 progressdialog = (IProgressDialog2)stepprogressor; // Creates and displays progressdialog.CancelEnabled = false; progressdialog.Description = "Prepping {_fileList.Count} files..."; progressdialog.Title = MB_TITLE; progressdialog.Animation = esriProgressAnimationTypes.esriProgressSpiral; foreach (KeyValuePair <String, Boolean> file in _fileList) { if (file.Value) { progressdialog.Description = string.Format("Adding File {0} of {1}...", cloneCount, _fileList.Count); if (!itWorked) { SaveFileTypeList(GetExtension()); } itWorked = true; try { var sourceFile = txb_FileWorkspaceSrc.Text + @"\" + Utilities_General.AddPrefixAndSuffixToFileName(file.Key, txb_Prefix.Text, txb_Suffix.Text) + GetExtension(); var destinationFile = txb_FileWorkspaceDst.Text + @"\" + Utilities_General.AddPrefixAndSuffixToFileName(file.Key, txb_Prefix.Text, txb_Suffix.Text) + GetExtension(); using (System.IO.StreamWriter sw = File.AppendText(filePath)) { sw.WriteLine(String.Format("copy {0} {1}", sourceFile, destinationFile)); } } catch (Exception yourBest) // but you don't succeed { yourBest.ToString(); // Just So We Get No Crashes ;) } stepprogressor.Step(); cloneCount++; } } trackcancel = null; stepprogressor = null; progressdialog.HideDialog(); progressdialog = null; //_activeView.Refresh(); }
/// <summary> /// Ejecuta el modelo de amenazas de incendios /// </summary> /// <param name="sTablaPrecipPromedio">Tabla Precipitacion Promedio</param> /// <param name="sConsultaTablaPrecipPromedio">SQL para la table precipitacion promedio</param> /// <param name="sPrefijo">Prefijo para los nombres de las capas</param> /// <param name="sTablaTempPromedio">Nombre de la tabla temporal de promedios</param> /// <param name="sConsultaTablaTempPromedio">SQL para la tabla temporal de promedios</param> /// <param name="bUsarSatelite">Indica si se han de utilizar las imagenes de satelita</param> /// <param name="bMostrarIntermedios">Indica si se mostraran los resultados intermedios en el mapa activo</param> private void GenerarModelo(string sTablaPrecipPromedio, string sConsultaTablaPrecipPromedio, string sPrefijo, string sTablaTempPromedio, string sConsultaTablaTempPromedio, bool bUsarSatelite, bool bMostrarIntermedios, String[] sRastersPrecipitacion) { String sPath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase); String tempDir = ""; sPath = sPath.Replace("file:\\", ""); SIGPIParametros parametros = new SIGPIParametros(); try { XmlSerializer serializer = new XmlSerializer(typeof(SIGPIParametros)); System.IO.StreamReader r = new System.IO.StreamReader(sPath + "\\parameters\\parametros.xml"); parametros = (SIGPIParametros)serializer.Deserialize(r); r.Close(); serializer = null; r = null; } catch (Exception ex) { MessageBox.Show(ex.Message, "SIGPI 2013"); return; } SIGPIProcesamiento procesamiento = new SIGPIProcesamiento(parametros); SIGPICls sigpi = new SIGPICls(); SIGPIDao sigpiDao = new SIGPIDao(); sigpiDao.ConnectLocalDB(parametros.RutaBD); sigpiDao.UltimaFechaIncorporacion(sigpi); sigpi.Parametros = parametros; OleDbCommand command = sigpiDao.LocalDBConnection.CreateCommand(); OleDbParameter param = command.CreateParameter(); OleDbParameter param1 = command.CreateParameter(); param.ParameterName = "fecProce"; param.Value = sigpi.FechaProcesamiento; command.CommandText = "UPDATE FECHAS_PROCESO SET FEC_PROCE = @fecProce"; command.Parameters.Add(param); string sSQL = ""; // "UPDATE FECHAS_PROCESO SET FEC_PROCE = #" + sigpi.FechaProcesamiento.ToString("MM/dd/yyyy") + "#"; try { sigpiDao.EjecutarSentenciaSinQuery(command); } catch (Exception ex) { MessageBox.Show("No se pudo actualizar la fecha de incorporacion.\n" + ex.Message); } IProgressDialogFactory pProDiaFac = new ProgressDialogFactoryClass(); IStepProgressor pStepPro = pProDiaFac.Create(null, 0); pStepPro.MinRange = 1; pStepPro.MaxRange = 5; pStepPro.StepValue = 1; IProgressDialog2 pProDia = (IProgressDialog2)pStepPro; pProDia.Animation = esriProgressAnimationTypes.esriProgressGlobe; pProDia.Title = "Generar Modelo Amenazas"; pProDia.ShowDialog(); pStepPro.Step(); pStepPro.Message = "Generando Grids Meteorologicos..."; IFeatureClass pFeatureClass; IWorkspaceFactory pShpWorkspaceFactory = new ShapefileWorkspaceFactoryClass(); IWorkspaceFactory pFileGDBWorkspaceFactory = new FileGDBWorkspaceFactoryClass(); string sFormatTmp = "gdb_" + sigpi.FechaProcesamiento.ToString("yyyyMMdd") + "_" + DateTime.Now.ToString("HHmmss"); tempDir = sigpi.Parametros.TempDir; if (tempDir == null || tempDir.Trim().Equals("")) { tempDir = System.IO.Path.GetTempPath(); } string sRutaFileGDB = System.IO.Path.GetTempPath() + sFormatTmp + ".gdb"; if (System.IO.Directory.Exists(sRutaFileGDB)) { try { System.IO.Directory.Delete(sRutaFileGDB); } catch (Exception ex) { MessageBox.Show("No se pudo borrar la File Geodatabase Temporal: " + sRutaFileGDB + " Intente Borrarla Manualmente. " + ex.Message); return; } } Geoprocessor gp = new Geoprocessor(); IWorkspaceName pWSName; string sCapaResultado = "Amenaza_" + sigpi.FechaProcesamiento.ToString("yyyy_MM_dd"); string sRutaGdbResultados = parametros.RutaSIGPI + parametros.Resultado + "\\" + sigpi.FechaProcesamiento.Year.ToString() + "-" + sigpi.FechaProcesamiento.ToString("MM") + "-Modelos.gdb"; if (System.IO.Directory.Exists(sRutaGdbResultados)) { GPUtilitiesClass gpUtilClass = new GPUtilitiesClass(); try { Delete del = new Delete(); del.in_data = sRutaGdbResultados + "\\" + sCapaResultado; gp.Execute(del, null); } catch (Exception) { } } else { try { pWSName = pFileGDBWorkspaceFactory.Create(parametros.RutaSIGPI + parametros.Resultado + "\\", sigpi.FechaProcesamiento.Year.ToString() + "-" + sigpi.FechaProcesamiento.ToString("MM") + "-Modelos.gdb", null, 0); } catch (Exception ex) { MessageBox.Show("No se pudo crear la Geodatabase de resultados: \n" + sRutaGdbResultados); pStepPro.Hide(); } } pWSName = pFileGDBWorkspaceFactory.Create(System.IO.Path.GetTempPath(), sFormatTmp, null, 0); ESRI.ArcGIS.esriSystem.IName name = (ESRI.ArcGIS.esriSystem.IName)pWSName; IFeatureWorkspace pWorkspaceTemp; try { pWorkspaceTemp = (IFeatureWorkspace)name.Open(); } catch (Exception ex) { MessageBox.Show(ex.Message); return; } IWorkspaceFactory pWF = new AccessWorkspaceFactoryClass(); IFeatureWorkspace pWSMask = (IFeatureWorkspace)pWF.OpenFromFile(parametros.RutaGBD, 0); IGeoDataset pFCMask = (IGeoDataset)pWSMask.OpenFeatureClass(parametros.Mascara); ISpatialReference pSpaRef = pFCMask.SpatialReference; IEnvelope pEnv = pFCMask.Extent; string sNombreTabla = "TMPPR_"; DateTime fechaProcesamiento = sigpi.FechaProcesamiento; fechaProcesamiento = fechaProcesamiento.Date; for (int i = 0; i < 10; i++) { try { sigpiDao.EjecutarSentenciaSinQuery("DROP TABLE " + sNombreTabla + i.ToString()); } catch (Exception ex) { System.Console.WriteLine(ex.Message); } // "IIf([LECTUS_PRECI]![LECTURA]<=2,5,IIf([LECTUS_PRECI]![LECTURA]<=8 And [LECTUS_PRECI]![LECTURA]>2,4,IIf([LECTUS_PRECI]![LECTURA]<=14 And [LECTUS_PRECI]![LECTURA]>8,3,IIf([LECTUS_PRECI]![LECTURA]<=24 And [LECTUS_PRECI]![LECTURA]>14,2,IIf([LECTUS_PRECI]![LECTURA]>24,1,0))))) AS LECTURAS " + //sSQL = "SELECT CODIGO, FECHA, X, Y, LECTURA AS RASTERVALU " + // "INTO " + sNombreTabla + i.ToString() + " " + // "FROM LECTUS_PRECI " + // "WHERE (((FECHA)=#" + sigpi.FechaProcesamiento.AddDays(-i).ToString("MM/dd/yyyy") + "#))"; command = sigpiDao.LocalDBConnection.CreateCommand(); command.CommandText = "SELECT CODIGO, FECHA, X, Y, LECTURA AS RASTERVALU " + "INTO " + sNombreTabla + i.ToString() + " " + "FROM LECTUS_PRECI " + "WHERE (((FECHA) >=@fecha) and ((FECHA) <@fecha1))"; param = command.CreateParameter(); param.ParameterName = "fecha"; param.Value = sigpi.FechaProcesamiento.AddDays(-i); command.Parameters.Add(param); param1 = command.CreateParameter(); param1.ParameterName = "fecha1"; param1.Value = sigpi.FechaProcesamiento.AddDays(-i + 1); command.Parameters.Add(param1); try { sigpiDao.EjecutarSentenciaSinQuery(command); } catch (Exception ex) { MessageBox.Show("Error generando las tablas temporales de precipitaciones. Descripcion: \n" + ex.Message); //pProDia.HideDialog(); return; } } try { sigpiDao.EjecutarSentenciaSinQuery("DROP TABLE TEMPERATURA_PROMEDIO"); } catch (Exception ex) { } //"IIf(Avg(LECTUS_TEMPE.LECTURA)<=6,1,IIf(Avg(LECTUS_TEMPE.LECTURA) <=12 And Avg(LECTUS_TEMPE.LECTURA)>6,2," + //"IIf(Avg(LECTUS_TEMPE.LECTURA)<=18 And Avg(LECTUS_TEMPE.LECTURA)>12,3,IIf(Avg(LECTUS_TEMPE.LECTURA)<=24 And " + //"Avg(LECTUS_TEMPE.LECTURA)>12,4,IIf(Avg(LECTUS_TEMPE.LECTURA)>24,5,0))))) AS LECTURAS, " + //sSQL = "SELECT CODIGO, Max(LECTUS_TEMPE.FECHA) AS FECHA, 10 AS Num_Dias, X, Y, AVG(LECTURA) AS RASTERVALU " + // "INTO TEMPERATURA_PROMEDIO " + // "FROM LECTUS_TEMPE " + // "WHERE (((FECHA)>=#" + sigpi.FechaProcesamiento.AddDays(-10).ToString("MM/dd/yyyy") + "# " + // "And (FECHA)<=#" + sigpi.FechaProcesamiento.ToString("MM/dd/yyyy") + "#)) " + // "GROUP BY CODIGO, X, Y"; command = sigpiDao.LocalDBConnection.CreateCommand(); command.CommandText = "SELECT CODIGO, Max(LECTUS_TEMPE.FECHA) AS FECHA, 10 AS Num_Dias, X, Y, AVG(LECTURA) AS RASTERVALU " + "INTO TEMPERATURA_PROMEDIO " + "FROM LECTUS_TEMPE " + "WHERE (((FECHA)>= @fecha1 " + "And (FECHA)<= @fecha)) " + "GROUP BY CODIGO, X, Y"; param = command.CreateParameter(); param.ParameterName = "fecha"; param.Value = sigpi.FechaProcesamiento; param1 = command.CreateParameter(); param1.ParameterName = "fecha1"; param1.Value = sigpi.FechaProcesamiento.AddDays(-10); command.Parameters.Add(param1); command.Parameters.Add(param); try { sigpiDao.EjecutarSentenciaSinQuery(command); } catch (Exception ex) { MessageBox.Show("Error Generando Tabla: TEMPERATURA_PROMEDIO " + ex.Message); pProDia.HideDialog(); return; } string sExpression = ""; string sOutGrid; double dPeso = 0; string sAmenazaXPrecipitacion = sRutaFileGDB + "\\amenaza_x_precipitacion"; string sTablaTemperaturaPromedio = "TEMPERATURA_PROMEDIO"; string sFCTempPromedio = "TEMP_PROMEDIO"; string sPrefijoIDW = "idw"; string sAmenazaXTemperatura = sRutaFileGDB + "\\" + "amenaza_x_temperatura"; string sAmenazasParciales = parametros.RutaGBD + "\\" + "amenazas_parciales_2"; string sAmenazaBruta = sRutaFileGDB + "\\amenaza_incendio_bruta"; string sAmenazaFinal = sRutaFileGDB + "\\amenaza_incendio_final"; string sTablaReclassIncendios = parametros.TablaReclasificacionIncendios; //"tbl_reclass_amenaza_incendios"; string sTablaReclassTemp = parametros.TablaReclasificacionTemperatura; //"tbl_reclass_temperatura"; string sTablaReclassPrecip = parametros.TablaReclasificacionPrecipitacion; //"tbl_reclass_precipitacion"; string sAmenazaXTemperaturaCombinada = sRutaFileGDB + "\\" + "amenaza_x_temperatura_combinada"; string sEstVirtualesPrecipitacion = sRutaFileGDB + "\\" + "estaciones_virtuales_precipitacion"; string sAmenazaXPrecipitacionCombinada = sRutaFileGDB + "\\" + "amenaza_x_precipitacion_combinada"; string sAmenazaFinalBrutaNVI = sRutaFileGDB + "\\" + "amenaza_incend_raw_nvi"; string sNVITempReclass = sRutaFileGDB + "\\" + "nvi_reclass_temp"; string sFromField = "FROM_"; string sToField = "TO_"; string sOutField = "OUT"; string sNoData = "NODATA"; string sFieldLecturas = "RASTERVALU"; //LECTURAS"; string sTipoEstadistico = parametros.TipoEstadistico; //"MAXIMUM"; string sAmenazaXPrecipReclass = sAmenazaXPrecipitacion + "_reclass"; string sAmenazaXTempReclass = sAmenazaXTemperatura + "_reclass"; string nvi = parametros.RutaSIGPI + "NVI" + "\\" + "tmpMosaic.500m_16_days_NDVI_GEO.tif"; double dPesoPrecipitacion = parametros.PesoPrecipitacion; //0.29; double dPesoTemperatura = parametros.PesoTemperatura; //0.24; double dPesoAmenazasParciales = parametros.PesoAmenazasParciales; //0.47; IDataset pDS; IDatasetName pDSName; IDatasetName pDSName2 = new FeatureClassNameClass(); IExportOperation pExportOp = new ExportOperationClass(); string sEstacionesVirtuales = sRutaFileGDB + "\\" + "EstacionesVirtuales.shp"; ExtractValuesToPoints extractValPoint = new ExtractValuesToPoints(); extractValPoint.in_point_features = sEstacionesVirtuales; extractValPoint.interpolate_values = "NONE"; extractValPoint.add_attributes = "VALUE_ONLY"; //'0.037037037; // 1" = 1/3600 double dCellSize = parametros.TamanoCelda / (3600 * 30); double[] iPesos = parametros.Pesos; //{ 30, 20, 10, 9, 8, 7, 6, 5, 4, 3 }; double iTotalPesos = 0; //102; foreach (double dP in iPesos) { iTotalPesos += dP; } gp.AddOutputsToMap = bMostrarIntermedios; gp.SetEnvironmentValue("Mask", parametros.RutaGBD + "\\" + parametros.Mascara); gp.SetEnvironmentValue("Extent", pEnv.XMin.ToString() + " " + pEnv.YMin.ToString() + " " + pEnv.XMax.ToString() + " " + pEnv.YMax.ToString()); ESRI.ArcGIS.SpatialAnalystTools.Idw idw = new Idw(); idw.z_field = sFieldLecturas; idw.cell_size = dCellSize; for (int i = 0; i < 10; i++) { pFeatureClass = procesamiento.FCPrecipitacion(sNombreTabla + i.ToString(), pSpaRef); pDS = (IDataset)pFeatureClass; pDSName = (IDatasetName)pDS.FullName; pDSName2.Name = sNombreTabla + i.ToString(); pDSName2.WorkspaceName = pWSName; try { pExportOp.ExportFeatureClass(pDSName, null, null, null, (IFeatureClassName)pDSName2, 0); } catch (Exception ex) { MessageBox.Show(ex.Message); pProDia.HideDialog(); return; } if (bUsarSatelite) { //Geoprocessor gp1 = new Geoprocessor(); //extractValPoint.in_raster = sRastersPrecipitacion[i]; // txtRutaPrecipitacion.Text; //extractValPoint.out_point_features = sEstVirtualesPrecipitacion + i.ToString(); //try //{ // gp1.Execute(extractValPoint, null); //} //catch (Exception ex) //{ // MessageBox.Show(ex.Message); //} //Merge merge = new Merge(); //string sInputMerge = sRutaFileGDB + "\\" + sNombreTabla + i.ToString() + ";" + sEstVirtualesPrecipitacion + i.ToString(); //merge.inputs = sInputMerge; ////"[" + sRutaFileGDB + "\\" + sNombreTabla + i.ToString() + ";" + sEstVirtualesPrecipitacion + i.ToString() + "]" ; //merge.output = sRutaFileGDB + "\\" + "est_precip_temporal" + i.ToString(); //try //{ // gp.Execute(merge, null); //} //catch (Exception ex) //{ // MessageBox.Show(ex.Message); //} //idw.in_point_features = sRutaFileGDB + "\\" + "est_precip_temporal" + i.ToString(); idw.in_point_features = sRutaFileGDB + "\\" + sNombreTabla + i.ToString(); } else { idw.in_point_features = sRutaFileGDB + "\\" + sNombreTabla + i.ToString(); } sOutGrid = sRutaFileGDB + "\\" + sPrefijoIDW + "_" + sNombreTabla + i.ToString(); idw.out_raster = sOutGrid; try { gp.Execute(idw, null); } catch (Exception ex) { MessageBox.Show(ex.Message); } dPeso = iPesos[i] / iTotalPesos; sExpression += "( Raster(r'" + sOutGrid + "') * " + dPeso.ToString().Replace(",", ".") + ")"; if (i < 9) { sExpression += " + "; } } pStepPro.Step(); ////for (int i = 0; i < 10; i++) ////{ //// //pStepPro.Message = "Generando Modelo Precipitacion: " + i.ToString(); //// sOutGrid = sRutaFileGDB + "\\" + sPrefijoIDW + "_" + sNombreTabla + i.ToString(); //// idw.in_point_features = sRutaFileGDB + "\\" + sNombreTabla + i.ToString(); //// idw.out_raster = sOutGrid; //// gp.Execute(idw, null); //// dPeso = iPesos[i] / iTotalPesos; //// sExpression += "(" + sOutGrid + " * " + dPeso.ToString() + ")"; //// if (i < 9) //// sExpression += " + "; ////} //gp.AddMessage("Expresion: " + sExpression); //SingleOutputMapAlgebra mapAlgebra = new SingleOutputMapAlgebra(); ESRI.ArcGIS.SpatialAnalystTools.RasterCalculator mapAlgebra = new RasterCalculator(); //mapAlgebra.expression_string = sExpression; // mapAlgebra.out_raster = sAmenazaXPrecipitacion; mapAlgebra.expression = sExpression; mapAlgebra.output_raster = sAmenazaXPrecipitacion; pStepPro.Message = "Generando Amenaza Precipitacion..."; try { gp.Execute(mapAlgebra, null); } catch (Exception ex) { MessageBox.Show("Error Generando Amenaza x Precipitacion. " + ex.Message); pProDia.HideDialog(); return; } //if (bUsarSatelite) // Para la combinacion de la precipitacion x estaciones y satelite //{ // //CellStatistics cellStatisticsP = new CellStatistics(); // //cellStatisticsP.in_rasters_or_constants = sAmenazaXPrecipitacion + ";" + txtRutaPrecipitacion.Text; // //cellStatisticsP.out_raster = sAmenazaXPrecipitacionCombinada; // //cellStatisticsP.statistics_type = sTipoEstadistico; // try // { // gp.Execute(extractValPoint, null); // //sAmenazaXPrecipitacion = sAmenazaXPrecipitacionCombinada; // } // catch (Exception ex) // { // MessageBox.Show("Error generando estaciones virtuales con precipitacion." + ex.Message); // return; // } // Merge merge = new Merge(); // merge.inputs = //} DateTime date = sigpi.FechaProcesamiento; string sMonth = date.ToString("MM"); pStepPro.Step(); pStepPro.Message = "Generando Amenaza x Temperatura"; pFeatureClass = procesamiento.FCPrecipitacion(sTablaTemperaturaPromedio, pSpaRef); pDS = (IDataset)pFeatureClass; pDSName = (IDatasetName)pDS.FullName; pDSName2.Name = sFCTempPromedio; pDSName2.WorkspaceName = pWSName; try { pExportOp.ExportFeatureClass(pDSName, null, null, null, (IFeatureClassName)pDSName2, 0); } catch (Exception ex) { throw new Exception(ex.Message); } idw.in_point_features = sRutaFileGDB + "\\" + sFCTempPromedio; idw.out_raster = sAmenazaXTemperatura; try { gp.Execute(idw, null); } catch (Exception ex) { Console.WriteLine(ex.Message); } //if (bUsarSatelite) //{ // Geoprocessor gp1 = new Geoprocessor(); // Con pContmp = new Con(); // pContmp.in_conditional_raster = txtRutaTemperatura.Text; // pContmp.in_true_raster_or_constant = txtRutaTemperatura.Text; // pContmp.in_false_raster_or_constant = -99; // string sRasterTTemp = sAmenazaXTemperaturaCombinada + "_ajs"; // pContmp.out_raster = sRasterTTemp; // pContmp.where_clause = "VALUE < 55"; // try // { // gp1.Execute(pContmp, null); // } // catch (Exception) // { // sRasterTTemp = txtRutaTemperatura.Text; ; // } // gp1 = null; // CellStatistics cellStatistics = new CellStatistics(); // cellStatistics.in_rasters_or_constants = sAmenazaXTemperatura + ";" + sRasterTTemp; // cellStatistics.out_raster = sAmenazaXTemperaturaCombinada; // cellStatistics.statistics_type = sTipoEstadistico; // try // { // gp.Execute(cellStatistics, null); // sAmenazaXTemperatura = sAmenazaXTemperaturaCombinada; // } // catch (Exception) // { // } //} ReclassByTable rbt = new ReclassByTable(); rbt.in_raster = sAmenazaXPrecipitacion; rbt.in_remap_table = sTablaReclassPrecip; // parametros.RutaGBD + "\\" + sTablaReclassPrecip; rbt.from_value_field = sFromField; rbt.to_value_field = sToField; rbt.output_value_field = sOutField; rbt.missing_values = sNoData; rbt.out_raster = sAmenazaXPrecipReclass; //pStepPro.Message = "Generando Amenaza X Precipitacion Reclasificada"; try { gp.Execute(rbt, null); } catch (Exception ex) { MessageBox.Show(ex.Message); pProDia.HideDialog(); return; } rbt.in_raster = sAmenazaXTemperatura; rbt.in_remap_table = sTablaReclassTemp; // parametros.RutaGBD + "\\" + sTablaReclassTemp; rbt.out_raster = sAmenazaXTempReclass; //pStepPro.Message = "Generando Amenaza X Temperatura Reclasificada"; try { gp.Execute(rbt, null); } catch (Exception ex) { MessageBox.Show(ex.Message); pProDia.HideDialog(); return; } sExpression = "( Raster(r'" + sAmenazaXPrecipReclass + "') * " + dPesoPrecipitacion.ToString().Replace(",", ".") + ") + " + "( Raster(r'" + sAmenazaXTempReclass + "') * " + dPesoTemperatura.ToString().Replace(",", ".") + ") + " + "( Raster(r'" + sAmenazasParciales + "') * " + dPesoAmenazasParciales.ToString().Replace(",", ".") + ")"; //mapAlgebra.expression_string = sExpression; //mapAlgebra.out_raster = sAmenazaBruta; sExpression = sExpression.Replace("\\\\", "/").Replace("\\", "/"); mapAlgebra.expression = sExpression; mapAlgebra.output_raster = sAmenazaBruta; pStepPro.Message = "Generando Amenaza Final Bruta"; try { gp.Execute(mapAlgebra, null); } catch (Exception ex) { MessageBox.Show(ex.Message); } //if (txtRutaNVI.Text.Trim() != "") //{ Geoprocessor gp2 = new Geoprocessor(); mapAlgebra = new RasterCalculator(); sExpression = "Con (Raster(r'" + nvi + "') < 0.75, Raster(r'" + sAmenazaBruta + "'), Raster(r'" + sAmenazaBruta + "') -1)"; sExpression = sExpression.Replace("\\\\", "/").Replace("\\", "/"); mapAlgebra.expression = sExpression; mapAlgebra.output_raster = sAmenazaFinalBrutaNVI; try { gp2.Execute(mapAlgebra, null); } catch (Exception ex) { MessageBox.Show(ex.Message); } //} rbt.in_raster = sAmenazaFinalBrutaNVI; // sAmenazaBruta; rbt.in_remap_table = sTablaReclassIncendios; // parametros.RutaGBD + "\\" + sTablaReclassIncendios; rbt.from_value_field = sFromField; rbt.to_value_field = sToField; rbt.output_value_field = sOutField; rbt.missing_values = sNoData; rbt.out_raster = sAmenazaFinal; pStepPro.Message = "Generando Amenaza Final Reclasificada"; gp.AddOutputsToMap = true; try { gp.Execute(rbt, null); } catch (Exception ex) { MessageBox.Show(ex.Message); } Copy copy = new Copy(); copy.in_data = sAmenazaFinal; copy.out_data = sRutaGdbResultados + "\\" + sCapaResultado; try { gp.Execute(copy, null); } catch (Exception ex) { MessageBox.Show("Error Copiando el resultado. \n " + ex.Message); } MessageBox.Show("Algoritmo completo ejecutado: " + sRutaGdbResultados + "\\" + sCapaResultado); if (m_pApp != null) { IRasterLayer pRLayer = new RasterLayerClass(); try { IWorkspaceFactory pWF2 = new FileGDBWorkspaceFactoryClass(); IRasterWorkspaceEx pRW = (IRasterWorkspaceEx)pWF2.OpenFromFile(sRutaGdbResultados, 0); IRasterDataset pRDataset = pRW.OpenRasterDataset(sCapaResultado); pRLayer.CreateFromDataset(pRDataset); pRLayer.Name = sCapaResultado; IMxDocument pMxDoc = m_pApp.Document as IMxDocument; IMap pMap = pMxDoc.FocusMap; AsignarSimbologiaProbabilidad(pRLayer); pMap.AddLayer(pRLayer); if (pMap.LayerCount > 0) { pMap.MoveLayer(pRLayer, pMap.LayerCount - 1); } pMxDoc.UpdateContents(); pMxDoc.ActiveView.Refresh(); } catch (Exception ex) { MessageBox.Show(ex.Message, "Error cargando Capa!!!"); } } pProDia.HideDialog(); }
private void GenerarModelo(string sTablaPrecipPromedio, string sConsultaTablaPrecipPromedio, string sPrefijo, string sTablaTempPromedio, string sConsultaTablaTempPromedio) { ProcesarLecturas procesarLecturas = new ProcesarLecturas(); try { procesarLecturas.CalcularResultadosPrecipitacion(sigpiDao, "DEFI_PRECI", "LECTUS_PRECI", sigpi.FechaProcesamiento, 5); } catch (Exception ex) { MessageBox.Show("Error procesando las lecturas:\n" + ex.Message); } //pStepPro.Step(); //pStepPro.Message = "Procesando Temperatura..."; try { procesarLecturas.CalcularResultadosTemperatura(sigpiDao, "DEFI_TEMPE", "LECTUS_TEMPE", sigpi.FechaProcesamiento, "T5", 5); } catch (Exception ex) { MessageBox.Show("Error procesando las lecturas:\n" + ex.Message); } string sSQL = "UPDATE FECHAS_PROCESO SET FEC_PROCE = #" + sigpi.FechaProcesamiento.ToString("MM/dd/yyyy") + "#"; try { sigpiDao.EjecutarSentenciaSinQuery(sSQL); } catch (Exception ex) { MessageBox.Show("No se pudo actualizar la fecha de incorporacion.\n" + ex.Message); } IProgressDialogFactory pProDiaFac = new ProgressDialogFactoryClass(); IStepProgressor pStepPro = pProDiaFac.Create(null, 0); pStepPro.MinRange = 1; pStepPro.MaxRange = 5; pStepPro.StepValue = 1; IProgressDialog2 pProDia = (IProgressDialog2)pStepPro; pProDia.Animation = esriProgressAnimationTypes.esriProgressGlobe; pProDia.Title = "Generar Grids"; pProDia.ShowDialog(); pStepPro.Step(); pStepPro.Message = "Generando Grids Meteorologicos..."; IFeatureClass pFeatureClass; IWorkspaceFactory pShpWorkspaceFactory = new ShapefileWorkspaceFactoryClass(); IWorkspace pWorkspaceTemp = pShpWorkspaceFactory.OpenFromFile(parametros.RutaSIGPI + parametros.Temporal, 0); // Crear FeatureClass a partir de los datos de la tabla de los promedios de la precipitacion try { //pFeatureClass = procesamiento.ConstruirFeatureClass(pWorkspaceTemp, "DEFI_PRECI", "estaciones", "CODIGO", "DEFI_PRECI.P5 >= 0", "JP"); pFeatureClass = procesamiento.ConstruirFeatureClass(pWorkspaceTemp, sTablaPrecipPromedio, "estaciones", "CODIGO", sConsultaTablaPrecipPromedio, "JP"); } catch (Exception ex) { MessageBox.Show("Error generando el FeatureClass de Estaciones. Descripcion: \n" + ex.Message); return; } IWorkspaceFactory pWF = new AccessWorkspaceFactoryClass(); IFeatureWorkspace pWSMask = (IFeatureWorkspace)pWF.OpenFromFile(parametros.RutaGBD, 0); IGeoDataset pFCMask = (IGeoDataset)pWSMask.OpenFeatureClass(parametros.Mascara); DateTime date = sigpi.FechaProcesamiento; string sMonth = date.ToString("MM"); //P5 pStepPro.Step(); pStepPro.Message = "Generando Grids Meteorologicos: Precipitacion Total"; IRaster pRaster1 = procesamiento.ConstruirGrid(pFeatureClass, "P5", parametros, pFCMask, "RP5", "", true); //DSLL5 pStepPro.Step(); pStepPro.Message = "Generando Grids Meteorologicos: Promedio ultimos 5 dias sin lluvia"; IRaster pRaster2 = procesamiento.ConstruirGrid(pFeatureClass, "DSLL5", parametros, pFCMask, "DSLL5", "", true); //Crear FeatureClass a partir de la tabla de promedios de temperatura //pFeatureClass = procesamiento.ConstruirFeatureClass(pWorkspaceTemp, "DEFI_TEMPE", "estaciones", "CODIGO", "DEFI_TEMPE.T5 >= 0", "JT"); pFeatureClass = procesamiento.ConstruirFeatureClass(pWorkspaceTemp, sTablaTempPromedio, "estaciones", "CODIGO", sConsultaTablaTempPromedio, "JT"); //T5 pStepPro.Step(); pStepPro.Message = "Generando Grids Meteorologicos: Temperatura promedio"; IRaster pRaster3 = procesamiento.ConstruirGrid(pFeatureClass, "T5", parametros, pFCMask, "RT5", "", true); //TMMMM IRaster pRaster4 = SIGPIUtils.AbrirRasterDesdeArchivo(parametros.RutaSIGPI + "\\" + parametros.TMMMM, "tmmx" + sMonth); //Susceptibilidad //IRaster pRaster5 = SIGPIUtils.AbrirRaster(parametros.RutaSIGPI + "\\" + parametros.Grids, parametros.Susceptibilidad); IRaster pRaster5 = SIGPIUtils.AbrirRasterDesdeGDB(parametros.RutaGBD, parametros.Susceptibilidad); //Asentamientos //IRaster pRaster6 = SIGPIUtils.AbrirRaster(parametros.RutaSIGPI + "\\" + parametros.Grids, parametros.Asentamientos); IRaster pRaster6 = SIGPIUtils.AbrirRasterDesdeGDB(parametros.RutaGBD, parametros.Asentamientos); IRaster[] pRasters = { pRaster1, pRaster2, pRaster3, pRaster4, pRaster5, pRaster6 }; try { procesamiento.AlgoritmoCompleto(pRasters, sigpi); } catch (Exception ex) { MessageBox.Show(ex.Message); } pProDia.HideDialog(); MessageBox.Show("Algoritmo completo ejecutado"); }
public static void CalculateFlowAccum(List<FlowLayerDetails> sumFlowAcc, IApplication app) { IMap pMap = null; IFeatureLayer pFLayer = null; IFeatureSelection pFSel = null; IFeatureCursor pFCursor = null; ICursor pCursor = null; IFeature pFeature = null; IEditor pEditor = null; string retAcc = ""; int lSumFieldLoc; IProgressDialogFactory pProDFact; IStepProgressor pStepPro; IProgressDialog2 pProDlg = null; ITrackCancel pTrkCan; try { if (app == null) return; pMap = ((app.Document as IMxDocument).FocusMap); if (pMap == null) return; pEditor = Globals.getEditor(app); if (pEditor.EditState != esriEditState.esriStateEditing) { MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("MustBEditg")); return; } bool boolCont = true; // Create a CancelTracker pTrkCan = new CancelTrackerClass(); // Create the ProgressDialog. This automatically displays the dialog pProDFact = new ProgressDialogFactoryClass(); pProDlg = (IProgressDialog2)pProDFact.Create(pTrkCan, 0); pProDlg.CancelEnabled = true; pProDlg.Animation = esriProgressAnimationTypes.esriProgressGlobe; // Set the properties of the Step Progressor pStepPro = (IStepProgressor)pProDlg; foreach (FlowLayerDetails sumAcc in sumFlowAcc) { bool boolFoundAsLayer = true; pFLayer = Globals.FindLayer(app, sumAcc.LayerName, ref boolFoundAsLayer) as IFeatureLayer; if (pFLayer == null) { //MessageBox.Show(sumAcc.LayerName + " feature layer not found.\nAny selected features in this layer will be analyzed for acculmuation."); continue; } if (pFLayer.FeatureClass == null) { MessageBox.Show(sumAcc.LayerName + A4LGSharedFunctions.Localizer.GetString("GeoNetToolsError_20a")); continue; } if (Globals.IsEditable(ref pFLayer, ref pEditor) == false) { MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("GeoNetToolsError_20b") + sumAcc.LayerName + "."); } pFSel = pFLayer as IFeatureSelection; // Verify that the layer has some features selected if (pFSel.SelectionSet.Count < 1) { //MessageBox.Show(sumAcc.LayerName + " layer must have some features selected."); continue; } lSumFieldLoc = pFLayer.FeatureClass.Fields.FindField(sumAcc.SumFlowField); if (lSumFieldLoc == -1) { MessageBox.Show(sumAcc.LayerName + A4LGSharedFunctions.Localizer.GetString("GeoNetToolsError_20d") + sumAcc.SumFlowField + A4LGSharedFunctions.Localizer.GetString("GeoNetToolsError_20e")); return; } // Step through each selected feature in the selection set pFSel.SelectionSet.Search(null, false, out pCursor); pFCursor = pCursor as IFeatureCursor; // Set the properties of the ProgressDialog pProDlg.Description = A4LGSharedFunctions.Localizer.GetString("GeoNetToolsMess_20a") + sumAcc.LayerName; pProDlg.Title = A4LGSharedFunctions.Localizer.GetString("GeoNetToolsMess_20a") + sumAcc.LayerName; pStepPro.MinRange = 0; pStepPro.MaxRange = pFSel.SelectionSet.Count; pStepPro.StepValue = 1; pStepPro.Position = 0; pStepPro.Message = A4LGSharedFunctions.Localizer.GetString("GeoNetToolsMess_20a") + sumAcc.LayerName + " 0" + A4LGSharedFunctions.Localizer.GetString("OutOf") + pFSel.SelectionSet.Count; try { pEditor.StartOperation(); } catch { pEditor.AbortOperation(); pEditor.StartOperation(); } int cnt = 1; while ((pFeature = pFCursor.NextFeature()) != null) { pStepPro.Message = A4LGSharedFunctions.Localizer.GetString("GeoNetToolsMess_20a") + sumAcc.LayerName + cnt + A4LGSharedFunctions.Localizer.GetString("OutOf") + pFSel.SelectionSet.Count; pStepPro.Step(); boolCont = pTrkCan.Continue(); if (!boolCont) { pStepPro.Hide(); pProDlg.HideDialog(); pStepPro = null; pProDlg = null; pProDFact = null; return; } retAcc = Globals.ReturnAccumulation(ref app, ref pFeature, sumAcc.WeightName, sumAcc.FlowDirection); if (Globals.IsNumeric(retAcc)) { pFeature.set_Value(lSumFieldLoc, retAcc); pFeature.Store(); } else { } cnt++; } pEditor.StopOperation(A4LGSharedFunctions.Localizer.GetString("GeoNetToolsDone_20a") + sumAcc.LayerName); } MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("GeoNetToolsDone_20b")); } catch (Exception ex) { MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("ErrorInThe") + A4LGSharedFunctions.Localizer.GetString("GeoNetToolsLbl_20a") + "\n" + ex.Message); } finally { //pStepPro.Hide(); if (pProDlg != null) pProDlg.HideDialog(); pProDFact = null; pStepPro = null; pProDlg = null; pTrkCan = null; pMap = null; pFLayer = null; pFSel = null; if (pFCursor != null) Marshal.ReleaseComObject(pFCursor); pFCursor = null; if (pCursor != null) Marshal.ReleaseComObject(pCursor); pCursor = null; pFeature = null; pEditor = null; } }
private void PrepareMapForOutput(object sender, MapOutput_EventArgs e) { ITrackCancel pTrackCancel = new CancelTrackerClass(); IProgressDialogFactory pPDFact = new ProgressDialogFactoryClass(); IProgressDialog2 pProgressDialog = null; //IMxDocument pMxDoc = null; try { //pMxDoc = (IMxDocument)m_app.Document; // check the spatial reference of the first map in the draw order ISpatialReference pSpatialRef = m_pISDUTExt.MxDocument.Maps.get_Item(0).SpatialReference; // get the template file and store the pagelayout and map IGxFile pGxFile = new GxMapClass(); pGxFile.Path = e.mapTemplatePath; //@"D:\Project\64235_SUT\development\current\src\templates\exA.mxt"; IGxMapPageLayout pGxMapPageLayout = (IGxMapPageLayout)pGxFile; IPageLayout pPageLayoutTemplate = pGxMapPageLayout.PageLayout; IMap pMapTemplate = FindMap(pPageLayoutTemplate); // make sure the user understands that we're only supporting one map frame in the template if (m_pISDUTExt.MxDocument.Maps.Count > 1) { System.Windows.Forms.DialogResult diagRes2 = MessageBox.Show("You have more maps than the target template can accomodate.\n" + "The top most map in your Table of Contents will be used in \n" + "the template and the others will be discarded. \n\n" + "Do you want to continue?", "SUITT Question", MessageBoxButtons.YesNo); if(diagRes2 == DialogResult.No) return; } // setup the progress dialog and show it pProgressDialog = (IProgressDialog2)pPDFact.Create(pTrackCancel,m_app.hWnd); pProgressDialog.Animation = esriProgressAnimationTypes.esriProgressGlobe; pProgressDialog.Title = "Loading and applying template..."; pProgressDialog.CancelEnabled = true; pProgressDialog.ShowDialog(); // save the layers in the template target frame to a List System.Collections.Generic.List<ILayer> templateMapLayers = new System.Collections.Generic.List<ILayer>(); for(int i = 0; i < pMapTemplate.LayerCount; i++) { templateMapLayers.Add(pMapTemplate.get_Layer(i)); } // remove other map frames from the current document (the 'destination') while (m_pISDUTExt.MxDocument.Maps.Count > 1) { m_pISDUTExt.MxDocument.Maps.RemoveAt(m_pISDUTExt.MxDocument.Maps.Count - 1); } IMap pMapToBeReplaced = m_pISDUTExt.MxDocument.FocusMap; // set the active view to the pagelayout mode m_pISDUTExt.MxDocument.ActiveView = (IActiveView)m_pISDUTExt.MxDocument.PageLayout; // Get active views and extents for both the template and current map frames. // Will be used to set the extents later IActiveView pAVdest = (IActiveView)m_pISDUTExt.MxDocument.FocusMap; IActiveView pAVtemplate = (IActiveView)pMapTemplate; IEnvelope pEnvDest = pAVdest.Extent; pEnvDest.SpatialReference = m_pISDUTExt.MxDocument.FocusMap.SpatialReference; IEnvelope pEnvTemplate = pAVtemplate.Extent; pEnvTemplate.SpatialReference = pMapTemplate.SpatialReference; // deal with reprojecting data frames as necessary DialogResult diagResMatchSR = DialogResult.No; try { if (pMapTemplate.SpatialReference.FactoryCode != pSpatialRef.FactoryCode) { diagResMatchSR = MessageBox.Show("The spatial reference of the map is not the\n" + "same as the target map of the template.\n\n" + "Do you want to change the current map spatial reference to\n" + "match the template spatial reference?", "SUITT Question", MessageBoxButtons.YesNo); if (diagResMatchSR == DialogResult.No) { //m_pISDUTExt.Document.Maps.get_Item(0).SpatialReference = pMapTemplate.SpatialReference; pMapTemplate.SpatialReference = pMapToBeReplaced.SpatialReference; } } } catch { } // save the layers in the current map frame to a List System.Collections.Generic.List<ILayer> destMapLayers = new System.Collections.Generic.List<ILayer>(); for(int i = 0; i < m_pISDUTExt.MxDocument.FocusMap.LayerCount; i++) { destMapLayers.Add(m_pISDUTExt.MxDocument.FocusMap.get_Layer(i)); } // if the spatial reference systems don't match, project the current map envelope // to match the SR of the template --> will use this to set the extents later if (pMapTemplate.SpatialReference.FactoryCode != pMapToBeReplaced.SpatialReference.FactoryCode) { pEnvDest.Project(pEnvTemplate.SpatialReference); } IGroupLayer pGroupLayer = new GroupLayerClass(); pGroupLayer.Name = "Layers From Template"; // group the layers in the new map frame (from the template) //for(int i = 0; i < templateMapLayers.Count; i++) foreach(ILayer pLayer in templateMapLayers) { pGroupLayer.Add(pLayer); pMapTemplate.DeleteLayer(pLayer); } // copy all elements from the template to the current document pagelayout CopyPasteLayoutElements(m_pISDUTExt.MxDocument.PageLayout, pPageLayoutTemplate); // add the layers from the current (destination) document to the new map frame // that got copied over from the template for (int i = destMapLayers.Count - 1; i >= 0; i--) { pMapTemplate.AddLayer(destMapLayers[i]); } // add and move group layer to top of TOC pMapTemplate.AddLayer((ILayer)pGroupLayer); pMapTemplate.MoveLayer((ILayer)pGroupLayer, 0); //m_pISDUTExt.Document.Maps.get_Item(0).AddLayer((ILayer)pGroupLayer); //m_pISDUTExt.Document.Maps.get_Item(0).MoveLayer((ILayer)pGroupLayer, 0); // set the extent of the map pAVtemplate.Extent = pEnvDest; // refresh the TOC m_pISDUTExt.MxDocument.CurrentContentsView.Refresh(null); // Do the search and replaces for the text elements Hashtable htSearchAndRep = new Hashtable(); // add the date string strDate = DateTime.Today.ToLongDateString(); htSearchAndRep.Add("<Enter Date Here>",strDate); pSpatialRef = m_pISDUTExt.MxDocument.Maps.get_Item(0).SpatialReference; // add the spatial ref info IProjectedCoordinateSystem pPCS = pSpatialRef as IProjectedCoordinateSystem; try { // try to set the datum if (pPCS != null) { IDatum pDatum = pPCS.GeographicCoordinateSystem.Datum; /* * esriSRDatum_NAD1927 6267 North American Datum 1927. * esriSRDatum_NAD1983 6269 North American Datum 1983. */ if (pDatum.FactoryCode == 6267) htSearchAndRep.Add("<Enter NAD Here>","27"); else if (pDatum.FactoryCode == 6269) htSearchAndRep.Add("<Enter NAD Here>","83"); } } catch{} try { // try to set the utm zone if (pPCS.FactoryCode >= 26903 && pPCS.FactoryCode <= 26923) // NAD83 UTM Zones 3-23 { string strZone = Convert.ToString(pPCS.FactoryCode - 26900); htSearchAndRep.Add("<Enter Zone Here>",strZone); } else if(pPCS.FactoryCode >= 26703 && pPCS.FactoryCode <= 26722) // NAD27 UTM Zones 3-22 { string strZone = Convert.ToString(pPCS.FactoryCode - 26700); htSearchAndRep.Add("<Enter Zone Here>",strZone); } } catch{} // do all replacements ReplaceText(htSearchAndRep,m_pISDUTExt.MxDocument.PageLayout); //m_pISDUTExt.Document = (IMxDocument)m_app.Document; //m_pISDUTExt.Document.FocusMap.MapScale = Convert.ToInt32(e.mapScale); pMapTemplate.MapScale = Convert.ToInt32(e.mapScale); //IActiveView pAV = (IActiveView)m_pISDUTExt.Document.PageLayout; //util.Utils.Release(m_pISDUTExt.Document); //pAV.Refresh(); pAVtemplate.Refresh(); } catch(Exception ex) { Debug.WriteLine(ex.Message + "\n" + ex.StackTrace); util.Logger.Write(" Descrip : Preparing map for output " + "\n Message : " + ex.Message + "\n StackTrc : " + ex.StackTrace,util.Logger.LogLevel.Debug); } finally { try { pProgressDialog.HideDialog(); //util.Utils.Release(m_pISDUTExt.Document); } catch{} } }
private bool UpdatePointXYFromGeometry(ITable PointTable, IQueryFilter QueryFilter, bool Unversioned, double UpdateIfMoreThanTolerance, out int ChangedPointCount) { IApplication pApp = (IApplication)ArcMap.Application; if (pApp == null) { //if the app is null then must be running from ArcCatalog...based on equivalent test in calling function. pApp = (IApplication)ArcCatalog.Application; } IProgressDialogFactory pProgressorDialogFact = new ProgressDialogFactoryClass(); ITrackCancel pTrackCancel = new CancelTrackerClass(); IStepProgressor pStepProgressor = pProgressorDialogFact.Create(pTrackCancel, pApp.hWnd); IProgressDialog2 pProgressorDialog = (IProgressDialog2)pStepProgressor; try { pStepProgressor.MinRange = 0; pStepProgressor.MaxRange = PointTable.RowCount(null); pStepProgressor.StepValue = 1; pProgressorDialog.Animation = ESRI.ArcGIS.Framework.esriProgressAnimationTypes.esriProgressSpiral; bool bCont = true; IRow pPointFeat = null; ICursor pPtCurs = null; ChangedPointCount = 0; if (Unversioned) { ITableWrite pTableWr = (ITableWrite)PointTable;//used for unversioned table pPtCurs = pTableWr.UpdateRows(QueryFilter, false); } else { pPtCurs = PointTable.Update(QueryFilter, false); } pPointFeat = pPtCurs.NextRow(); int iPointIdx_X = pPtCurs.Fields.FindField("X"); int iPointIdx_Y = pPtCurs.Fields.FindField("Y"); pProgressorDialog.ShowDialog(); pStepProgressor.Message = "Updating point data..."; 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 bCont = pTrackCancel.Continue(); if (!bCont) { break; } IFeature pFeat = (IFeature)pPointFeat; IPoint pPtSource = (IPoint)pFeat.ShapeCopy; if (pPtSource == null) { Marshal.ReleaseComObject(pPointFeat); //garbage collection pPointFeat = pPtCurs.NextRow(); continue; } if (pPtSource.IsEmpty) { Marshal.ReleaseComObject(pPointFeat); //garbage collection pPointFeat = pPtCurs.NextRow(); continue; } IPoint pPtTarget = new ESRI.ArcGIS.Geometry.PointClass(); pPtTarget.X = Convert.ToDouble(pPointFeat.get_Value(iPointIdx_X)); pPtTarget.Y = Convert.ToDouble(pPointFeat.get_Value(iPointIdx_Y)); ILine pLine = new ESRI.ArcGIS.Geometry.LineClass(); pLine.PutCoords(pPtSource, pPtTarget); if (pLine.Length > UpdateIfMoreThanTolerance) { pPointFeat.set_Value(iPointIdx_X, pPtSource.X); pPointFeat.set_Value(iPointIdx_Y, pPtSource.Y); //if (Unversioned) pPtCurs.UpdateRow(pPointFeat); //else // pPointFeat.Store(); ChangedPointCount++; string sCnt = ChangedPointCount.ToString() + " of " + pStepProgressor.MaxRange.ToString(); pStepProgressor.Message = "Updating point data..." + sCnt; } Marshal.ReleaseComObject(pPointFeat); //garbage collection pPointFeat = pPtCurs.NextRow(); if (pStepProgressor.Position < pStepProgressor.MaxRange) { pStepProgressor.Step(); } } Marshal.ReleaseComObject(pPtCurs); //garbage collection return(bCont); } catch (COMException ex) { MessageBox.Show("Problem updating point XY from shape: " + Convert.ToString(ex.ErrorCode)); ChangedPointCount = 0; return(false); } finally { pStepProgressor = null; if (!(pProgressorDialog == null)) { pProgressorDialog.HideDialog(); } pProgressorDialog = null; } }
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); } }
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() { //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 UpdatePointXYFromGeometry(ITable PointTable, IQueryFilter QueryFilter, bool Unversioned, double UpdateIfMoreThanTolerance, out int ChangedPointCount) { IProgressDialogFactory pProgressorDialogFact = new ProgressDialogFactoryClass(); ITrackCancel pTrackCancel = new CancelTrackerClass(); IStepProgressor pStepProgressor = pProgressorDialogFact.Create(pTrackCancel, ArcMap.Application.hWnd); IProgressDialog2 pProgressorDialog = (IProgressDialog2)pStepProgressor; try { pStepProgressor.MinRange = 0; pStepProgressor.MaxRange = PointTable.RowCount(null); pStepProgressor.StepValue = 1; pProgressorDialog.Animation = ESRI.ArcGIS.Framework.esriProgressAnimationTypes.esriProgressSpiral; bool bCont = true; IRow pPointFeat = null; ICursor pPtCurs = null; ChangedPointCount = 0; if (Unversioned) { ITableWrite pTableWr = (ITableWrite)PointTable;//used for unversioned table pPtCurs = pTableWr.UpdateRows(QueryFilter, false); } else pPtCurs = PointTable.Update(QueryFilter, false); pPointFeat = pPtCurs.NextRow(); int iPointIdx_X = pPtCurs.Fields.FindField("X"); int iPointIdx_Y = pPtCurs.Fields.FindField("Y"); pProgressorDialog.ShowDialog(); pStepProgressor.Message = "Updating point data..."; 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 bCont = pTrackCancel.Continue(); if (!bCont) break; IFeature pFeat = (IFeature)pPointFeat; IPoint pPtSource = (IPoint)pFeat.ShapeCopy; if (pPtSource == null) { Marshal.ReleaseComObject(pPointFeat); //garbage collection pPointFeat = pPtCurs.NextRow(); continue; } if (pPtSource.IsEmpty) { Marshal.ReleaseComObject(pPointFeat); //garbage collection pPointFeat = pPtCurs.NextRow(); continue; } IPoint pPtTarget = new ESRI.ArcGIS.Geometry.PointClass(); pPtTarget.X = Convert.ToDouble(pPointFeat.get_Value(iPointIdx_X)); pPtTarget.Y = Convert.ToDouble(pPointFeat.get_Value(iPointIdx_Y)); ILine pLine = new ESRI.ArcGIS.Geometry.LineClass(); pLine.PutCoords(pPtSource, pPtTarget); if (pLine.Length > UpdateIfMoreThanTolerance) { pPointFeat.set_Value(iPointIdx_X, pPtSource.X); pPointFeat.set_Value(iPointIdx_Y, pPtSource.Y); //if (Unversioned) pPtCurs.UpdateRow(pPointFeat); //else // pPointFeat.Store(); ChangedPointCount++; string sCnt = ChangedPointCount.ToString() + " of " + pStepProgressor.MaxRange.ToString(); pStepProgressor.Message = "Updating point data..." + sCnt; } Marshal.ReleaseComObject(pPointFeat); //garbage collection pPointFeat = pPtCurs.NextRow(); if (pStepProgressor.Position < pStepProgressor.MaxRange) pStepProgressor.Step(); } Marshal.ReleaseComObject(pPtCurs); //garbage collection return bCont; } catch (COMException ex) { MessageBox.Show("Problem updating point XY from shape: " + Convert.ToString(ex.ErrorCode)); ChangedPointCount = 0; return false; } finally { pStepProgressor = null; if (!(pProgressorDialog == null)) pProgressorDialog.HideDialog(); pProgressorDialog = null; } }
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(); } }
/// <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()); } }
private void ExportInsertFeatures(IDisplayTable hluDisplayTable, IQueryFilter exportQueryFilter, int exportRowCount, int[] exportFieldMap, bool isShp, object outWS, IFeatureClass outFeatureClass) { // Create a Cancel Tracker. ITrackCancel trackCancel = new CancelTrackerClass(); // Create the Progress Dialog. This automatically displays the dialog. IProgressDialogFactory progressDlgFactory = new ProgressDialogFactoryClass(); IProgressDialog2 progressDlg = progressDlgFactory.Create(trackCancel, _application.hWnd) as IProgressDialog2; // Set the properties of the Progress Dialog. progressDlg.CancelEnabled = true; progressDlg.Title = "Export Progress"; progressDlg.Description = string.Format("Exporting HLU Features and Attributes\n({0} features)", exportRowCount.ToString()); progressDlg.Animation = esriProgressAnimationTypes.esriNoAnimation; // Set the properties of the Step Progressor. IStepProgressor stepProgressor = progressDlg as IStepProgressor; stepProgressor.MinRange = 0; stepProgressor.MaxRange = exportRowCount; stepProgressor.StepValue = 1; stepProgressor.Message = ""; // Set the continue progress to true. bool contProgress = true; IWorkspaceEdit workspaceEdit = null; IWorkspace wsOut = outWS as IWorkspace; bool restoreEditSession = InEditingSession; if (restoreEditSession) CloseEditSession(true); // If the workspace is remote then the data is being accessed // via ArcSDE. if (wsOut.WorkspaceFactory.WorkspaceType == esriWorkspaceType.esriRemoteDatabaseWorkspace) { Editor.StartEditing(wsOut); Editor.StartOperation(); } // Otherwise, it must be a FileSystem (for shapefiles) // or LocalDatabase (for geodatabases) workspace. else { workspaceEdit = (IWorkspaceEdit)outWS; workspaceEdit.StartEditing(true); workspaceEdit.StartEditOperation(); } IFeatureCursor exportFeatureCursor = (IFeatureCursor)hluDisplayTable.SearchDisplayTable(exportQueryFilter, true); IFeature exportFeature; IFeatureCursor insertCursor = outFeatureClass.Insert(true); IFeatureBuffer featureBuffer = outFeatureClass.CreateFeatureBuffer(); bool calcGeometry = _hluFeatureClass.ShapeType == esriGeometryType.esriGeometryPoint || isShp; double geom1; double geom2; // The last two fields are always the geometry fields. int ixGeom1 = featureBuffer.Fields.FieldCount - 2; int ixGeom2 = featureBuffer.Fields.FieldCount - 1; try { object item; while ((exportFeature = exportFeatureCursor.NextFeature()) != null) { featureBuffer.Shape = exportFeature.ShapeCopy; for (int i = 2; i < exportFieldMap.Length; i++) { item = exportFeature.get_Value(exportFieldMap[i]); if (item != DBNull.Value) featureBuffer.set_Value(i, item); //--------------------------------------------------------------------- // FIX: 036 Clear all missing fields when exporting features from ArcGIS. else featureBuffer.set_Value(i, null); //--------------------------------------------------------------------- } if (calcGeometry) { GetGeometryProperties(exportFeature, out geom1, out geom2); if (geom1 != -1) featureBuffer.set_Value(ixGeom1, geom1); if (geom2 != -1) featureBuffer.set_Value(ixGeom2, geom2); } try { insertCursor.InsertFeature(featureBuffer); } catch { } // Check if the cancel button was pressed. If so, stop the process. contProgress = trackCancel.Continue(); if (!contProgress) throw new Exception("Export cancelled by user."); } FlushCursor(false, ref insertCursor); if (workspaceEdit == null) { Editor.StopOperation(String.Empty); Editor.StopEditing(true); } else { workspaceEdit.StopEditOperation(); workspaceEdit.StopEditing(true); } } catch { if (workspaceEdit == null) { Editor.AbortOperation(); Editor.StopEditing(false); } else { workspaceEdit.AbortEditOperation(); workspaceEdit.StopEditOperation(); workspaceEdit.StopEditing(false); } throw; } finally { FlushCursor(true, ref exportFeatureCursor); if (restoreEditSession) OpenEditSession(); // Hide the progress dialog. trackCancel = null; stepProgressor = null; progressDlg.HideDialog(); progressDlg = null; progressDlgFactory = null; } }
public static void CheckConnections(IApplication app, bool CheckVisibleOnly) { IProgressDialog2 progressDialog = default(IProgressDialog2); IGeometricNetwork geometricNetwork = null; ISelectionEvents selEvents = null; IMxDocument mxDoc = null; IActiveView activeView = null; IMap map = null; List<IGeometricNetwork> gnList = null; IMouseCursor appCursor = null; IEnumFeatureClass enumClass = null; IFeatureClass featureClass = null; IFeatureLayer featureLayer = null; IProgressDialogFactory progressDialogFactory = null; ITrackCancel trackCancel = null; IStepProgressor stepProgressor = null; IFeatureSelection fSel = null; IEnumFeature enumFeatures = null; IEditor editor = null; try { editor = Globals.getEditor(ref app); if (editor == null) return; if (editor.EditState == esriEditState.esriStateNotEditing) { MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("MustBEditg"), A4LGSharedFunctions.Localizer.GetString("GeoNetToolsLbl_2")); return; } mxDoc = (IMxDocument)app.Document; activeView = (IActiveView)mxDoc.FocusMap; map = activeView.FocusMap; int countDeleted = 0; if (activeView == null) return; if (map.LayerCount == 0) return; long total = Globals.GetTotalVisibleNetworkFeatures(map); if (total > 1000) { if (MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("GeoNetToolsAsk_11a") + total + A4LGSharedFunctions.Localizer.GetString("GeoNetToolsAsk_11b"), A4LGSharedFunctions.Localizer.GetString("Proceed"), System.Windows.Forms.MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.No) { return; } } string resultMessage = ""; string resultMessage2 = ""; //Get visible networks gnList = Globals.GetGeometricNetworksCheckedVisible(ref map); if (gnList.Count == 0) { MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("GeoNetToolsError_11a"), A4LGSharedFunctions.Localizer.GetString("GeoNetToolsLbl_2")); return; } //Change mouse cursor to wait - automatically changes back (ArcGIS Desktop only) appCursor = new MouseCursorClass(); appCursor.SetCursor(2); //This step is required to avoid accidently deleting features if (map.SelectionCount > 0) { activeView.PartialRefresh(esriViewDrawPhase.esriViewGeoSelection, null, null); map.ClearSelection(); } int itotal = Convert.ToInt32(total); //ProgressBar progressDialogFactory = new ProgressDialogFactoryClass(); // Create a CancelTracker trackCancel = new CancelTrackerClass(); // Set the properties of the Step Progressor Int32 int32_hWnd = editor.Parent.hWnd; stepProgressor = progressDialogFactory.Create(trackCancel, int32_hWnd); stepProgressor.MinRange = 0; // stepProgressor.MaxRange = itotal stepProgressor.StepValue = 1; stepProgressor.Message = ""; stepProgressor.Hide(); // Create the ProgressDialog. This automatically displays the dialog progressDialog = (ESRI.ArcGIS.Framework.IProgressDialog2)stepProgressor; // Explict Cast // Set the properties of the ProgressDialog progressDialog.CancelEnabled = false; progressDialog.Description = A4LGSharedFunctions.Localizer.GetString("GeoNetToolsDesc_11"); progressDialog.Title = A4LGSharedFunctions.Localizer.GetString("GeoNetToolsTitle_11"); progressDialog.Animation = ESRI.ArcGIS.Framework.esriProgressAnimationTypes.esriProgressGlobe; for (int i = 0; i < gnList.Count; i++) { geometricNetwork = gnList[i] as IGeometricNetwork; enumClass = null; featureClass = null; featureLayer = null; int count = 0; enumClass = geometricNetwork.get_ClassesByType(esriFeatureType.esriFTSimpleJunction); //Find all 'disconnected junctions' in orphan junction layer (edges=0) //and also junctions in orphan junction that are unneed because they connect only 2 edges of the same feature // Do this first so we can safely delete them(if editing) string junFCName = ""; featureClass = geometricNetwork.OrphanJunctionFeatureClass; junFCName = featureClass.AliasName; bool FCorLayer = true; featureLayer = Globals.FindLayer((IMap)mxDoc.FocusMap, ((IDataset)featureClass).Name, ref FCorLayer) as IFeatureLayer; if (featureLayer != null && ( (Globals.isVisible((ILayer)featureLayer, (IMap)mxDoc.FocusMap) && CheckVisibleOnly) || (CheckVisibleOnly == false) ) ) { count = Globals.SelectJunctions(featureLayer, (IGeometry)activeView.Extent, 0, "ORPHAN", ref progressDialog, ref stepProgressor, ref trackCancel); if ((count > 0) && (editor != null) && (editor.EditState == esriEditState.esriStateEditing)) { try { editor.StartOperation(); fSel = (IFeatureSelection)featureLayer; enumFeatures = editor.EditSelection as IEnumFeature; Globals.DeleteFeatures(enumFeatures); editor.StopOperation(A4LGSharedFunctions.Localizer.GetString("GeoNetToolsDone_11a") + featureLayer.Name); } catch (Exception ex) { editor.AbortOperation(); MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("GeoNetToolsLbl_11") + "\n" + ex.Message, ex.Source); } countDeleted = +count; if (count == 1) { resultMessage2 += +count + A4LGSharedFunctions.Localizer.GetString("GeoNetToolsMess_11a") + featureLayer.Name + A4LGSharedFunctions.Localizer.GetString("GeoNetToolsMess_11b") + Environment.NewLine; } else if (count > 1) { resultMessage2 += count + A4LGSharedFunctions.Localizer.GetString("GeoNetToolsMess_11c") + featureLayer.Name + A4LGSharedFunctions.Localizer.GetString("GeoNetToolsMess_11d") + Environment.NewLine; } } else { if (count == 1) { resultMessage2 += +count + A4LGSharedFunctions.Localizer.GetString("GeoNetToolsMess_11a") + featureLayer.Name + A4LGSharedFunctions.Localizer.GetString("GeoNetToolsMess_11e") + Environment.NewLine; } else if (count > 1) { resultMessage2 += count + A4LGSharedFunctions.Localizer.GetString("GeoNetToolsMess_11c") + featureLayer.Name + A4LGSharedFunctions.Localizer.GetString("GeoNetToolsMess_11f") + Environment.NewLine; } } } //Step through each feature layer enumClass.Reset(); while ((featureClass = (IFeatureClass)enumClass.Next()) != null) { int numberJunctions; count = 0; // FCorLayer = true; featureLayer = Globals.FindLayer((IMap)mxDoc.FocusMap, ((IDataset)featureClass).Name, ref FCorLayer) as IFeatureLayer; if (featureLayer != null) { //Handle all non-orphan junction feature layers if (junFCName != featureClass.AliasName && featureLayer != null && ( (Globals.isVisible((ILayer)featureLayer, (IMap)mxDoc.FocusMap) && CheckVisibleOnly) || (CheckVisibleOnly == false) )) { numberJunctions = 1; count = Globals.SelectJunctions(featureLayer, (IGeometry)activeView.Extent, numberJunctions, "LT", ref progressDialog, ref stepProgressor, ref trackCancel); if (count == 1) { //Add lookup to config to see how many junctions a FC should connect to resultMessage += count + A4LGSharedFunctions.Localizer.GetString("AssetFromThe") + featureLayer.Name + A4LGSharedFunctions.Localizer.GetString("GeoNetToolsMess_11g") + Environment.NewLine;// "\r\n"; } if (count > 1) { //Add lookup to config to see how many junctions a FC should connect to resultMessage += count + A4LGSharedFunctions.Localizer.GetString("AssetsFromThe") + featureLayer.Name + A4LGSharedFunctions.Localizer.GetString("GeoNetToolsMess_11h") + Environment.NewLine;// "\r\n"; } } //Handle orphan junction feature layers else if (featureLayer != null && ( (Globals.isVisible((ILayer)featureLayer, (IMap)mxDoc.FocusMap) && CheckVisibleOnly) || (CheckVisibleOnly == false) )) { numberJunctions = 0; count = Globals.SelectJunctions(featureLayer, (IGeometry)activeView.Extent, numberJunctions, "EQ", ref progressDialog, ref stepProgressor, ref trackCancel); if (count == 1) { resultMessage += count + A4LGSharedFunctions.Localizer.GetString("JunctionInThe") + featureLayer.Name + A4LGSharedFunctions.Localizer.GetString("GeoNetToolsMess_11i") + Environment.NewLine;// "\r\n"; } if (count > 1) { resultMessage += count + A4LGSharedFunctions.Localizer.GetString("JunctionsInThe") + featureLayer.Name + A4LGSharedFunctions.Localizer.GetString("GeoNetToolsMess_11j") + Environment.NewLine;// "\r\n"; } numberJunctions = 1; count = Globals.SelectJunctions(featureLayer, (IGeometry)activeView.Extent, numberJunctions, "EQ", ref progressDialog, ref stepProgressor, ref trackCancel); if (count == 1) { resultMessage += count + A4LGSharedFunctions.Localizer.GetString("JunctionInThe") + featureLayer.Name + A4LGSharedFunctions.Localizer.GetString("GeoNetToolsMess_11k") + featureLayer.Name + A4LGSharedFunctions.Localizer.GetString("GeoNetToolsAsk_11b") + Environment.NewLine;// "\r\n"; } if (count > 1) { resultMessage += count + A4LGSharedFunctions.Localizer.GetString("JunctionsInThe") + featureLayer.Name + A4LGSharedFunctions.Localizer.GetString("GeoNetToolsMess_11l") + featureLayer.Name + A4LGSharedFunctions.Localizer.GetString("GeoNetToolsAsk_11b") + Environment.NewLine;// "\r\n"; } } } } //**** enumClass = geometricNetwork.get_ClassesByType(esriFeatureType.esriFTComplexEdge); //Step through each feature layer enumClass.Reset(); while ((featureClass = (IFeatureClass)enumClass.Next()) != null) { count = 0; FCorLayer = true; featureLayer = Globals.FindLayer((IMap)mxDoc.FocusMap, ((IDataset)featureClass).Name, ref FCorLayer) as IFeatureLayer; if (featureLayer != null) { //Handle all non-orphan junction feature layers if ((Globals.isVisible((ILayer)featureLayer, (IMap)mxDoc.FocusMap) && CheckVisibleOnly) || (CheckVisibleOnly == false)) { count = Globals.SelectEdges(featureLayer, (IGeometry)activeView.Extent, ref progressDialog, ref stepProgressor, ref trackCancel, geometricNetwork.OrphanJunctionFeatureClass.ObjectClassID); if (count == 1) { //Add lookup to config to see how many junctions a FC should connect to resultMessage += count + A4LGSharedFunctions.Localizer.GetString("AssetFromThe") + featureLayer.Name + A4LGSharedFunctions.Localizer.GetString("GeoNetToolsMess_11g") + Environment.NewLine;// "\r\n"; } if (count > 1) { //Add lookup to config to see how many junctions a FC should connect to resultMessage += count + A4LGSharedFunctions.Localizer.GetString("AssetsFromThe") + featureLayer.Name + A4LGSharedFunctions.Localizer.GetString("GeoNetToolsMess_11h") + Environment.NewLine;// "\r\n"; } } } } enumClass = geometricNetwork.get_ClassesByType(esriFeatureType.esriFTSimpleEdge); //Step through each feature layer enumClass.Reset(); while ((featureClass = (IFeatureClass)enumClass.Next()) != null) { count = 0; bool FCorLayerFeat = true; featureLayer = Globals.FindLayer((IMap)mxDoc.FocusMap, ((IDataset)featureClass).Name, ref FCorLayerFeat) as IFeatureLayer; if (featureLayer != null) { //Handle all non-orphan junction feature layers if ((Globals.isVisible((ILayer)featureLayer, (IMap)mxDoc.FocusMap) && CheckVisibleOnly) || (CheckVisibleOnly == false)) { count = Globals.SelectEdges(featureLayer, (IGeometry)activeView.Extent, ref progressDialog, ref stepProgressor, ref trackCancel, geometricNetwork.OrphanJunctionFeatureClass.ObjectClassID); if (count == 1) { //Add lookup to config to see how many junctions a FC should connect to resultMessage += count + A4LGSharedFunctions.Localizer.GetString("AssetFromThe") + featureLayer.Name + A4LGSharedFunctions.Localizer.GetString("GeoNetToolsMess_11g") + Environment.NewLine;// "\r\n"; } if (count > 1) { //Add lookup to config to see how many junctions a FC should connect to resultMessage += count + A4LGSharedFunctions.Localizer.GetString("AssetsFromThe") + featureLayer.Name + A4LGSharedFunctions.Localizer.GetString("GeoNetToolsMess_11h") + Environment.NewLine;// "\r\n"; } } } } } //** selEvents = (ISelectionEvents)mxDoc.FocusMap; if (selEvents != null) { selEvents.SelectionChanged(); } if (countDeleted == 0) activeView.PartialRefresh(esriViewDrawPhase.esriViewGeoSelection, null, null); else activeView.Refresh(); resultMessage += resultMessage2; if (resultMessage == "") resultMessage = A4LGSharedFunctions.Localizer.GetString("NoError"); if (progressDialog != null) progressDialog.HideDialog(); //Report results System.Windows.Forms.MessageBox.Show(resultMessage, A4LGSharedFunctions.Localizer.GetString("GeoNetToolsTitle_11"), System.Windows.Forms.MessageBoxButtons.OK); } catch (Exception ex) { System.Windows.Forms.MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("GeoNetToolsTitle_11") + "\n" + ex.Message); } finally { // Cleanup if (progressDialog != null) { progressDialog.HideDialog(); //progressDialog = null; Marshal.ReleaseComObject(progressDialog); //progressDialogFactory = null; Marshal.ReleaseComObject(progressDialogFactory); //trackCancel = null; Marshal.ReleaseComObject(trackCancel); //stepProgressor = null; Marshal.ReleaseComObject(stepProgressor); //appCursor = null; } if (appCursor != null) Marshal.ReleaseComObject(appCursor); gnList = null; // Marshal.ReleaseComObject(gnList); //enumClass = null; if (enumClass != null) Marshal.ReleaseComObject(enumClass); fSel = null; //Marshal.ReleaseComObject(fSel); enumFeatures = null; //Marshal.ReleaseComObject(enumFeatures); geometricNetwork = null; selEvents = null; mxDoc = null; activeView = null; map = null; featureClass = null; featureLayer = null; editor = null; } }
public static void RemoveFlagBarrier(IPoint pPnt, IApplication app, double snapTol) { IProgressDialogFactory pProDFact = null; IStepProgressor pStepPro = null; IProgressDialog2 pProDlg = null; ITrackCancel pTrkCan = null; List<IGeometricNetwork> gnList = null; IMap pMap = null; INetworkAnalysisExt pNetAnalysisExt = null; UID pID = null; try { pMap = (app.Document as IMxDocument).FocusMap; bool boolCont = true; // Create a CancelTracker pTrkCan = new CancelTrackerClass(); // Create the ProgressDialog. This automatically displays the dialog pProDFact = new ProgressDialogFactoryClass(); pProDlg = (IProgressDialog2)pProDFact.Create(pTrkCan, 0); // Set the properties of the ProgressDialog pProDlg.CancelEnabled = true; pProDlg.Animation = esriProgressAnimationTypes.esriProgressGlobe; // Set the properties of the Step Progressor pStepPro = (IStepProgressor)pProDlg; pStepPro.MinRange = 0; pStepPro.MaxRange = 6; pStepPro.StepValue = 1; pStepPro.Position = 0; pStepPro.Message = A4LGSharedFunctions.Localizer.GetString("GeoNetToolsProc_4"); gnList = Globals.GetGeometricNetworksCurrentlyVisible(ref pMap); if (gnList == null || gnList.Count == 0) { MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("GeoNetToolsError_2"), A4LGSharedFunctions.Localizer.GetString("GeoNetToolsErrorLbl_2")); return; } // Create junction or edge flag at start of trace - also returns geometric network, snapped point, and EID of junction pStepPro.Message = A4LGSharedFunctions.Localizer.GetString("GeoNetToolsProc_5") + "/" + A4LGSharedFunctions.Localizer.GetString("GeoNetToolsProc_6"); pStepPro.Step(); boolCont = pTrkCan.Continue(); if (!boolCont) { pStepPro.Hide(); pProDlg.HideDialog(); pStepPro = null; pProDlg = null; pProDFact = null; return; } if (app != null) { pID = new UID(); pID.Value = "esriEditorExt.UtilityNetworkAnalysisExt"; pNetAnalysisExt = (INetworkAnalysisExt)app.FindExtensionByCLSID(pID); Globals.RemoveFlagBarrierAtLocation(pPnt.X, pPnt.Y, ref pNetAnalysisExt, snapTol); } } catch (Exception ex) { MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("ErrorInThe") + A4LGSharedFunctions.Localizer.GetString("GeoNetToolsLbl_3") + ": " + ex.ToString()); } finally { if (pProDlg != null) { pProDlg.HideDialog(); } pStepPro = null; pProDlg = null; pProDFact = null; pTrkCan = null; gnList = null; pNetAnalysisExt = null; pMap = null; pID = null; } }
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 linepoint command cannot be used when there is an open job.\r\nPlease finish or discard the open job, and try again.", "Delete Selected LinePoints"); 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 CFLinePointLayers = new ArrayClass(); if (!(FabricUTILS.GetLinePointLayersFromFabric(pMap, pCadFabric, out CFLinePointLayers))) return; //no fabric sublayers available for the targeted fabric bool bIsFileBasedGDB = false; bool bIsUnVersioned = false; bool bUseNonVersionedDelete = false; IWorkspace pWS = null; ITable pLinePointTable = 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)CFLinePointLayers.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 linepoint layer and //Get the selection of linepoints int iCnt = 0; int iTotalSelectionCount = 0; for (; iCnt < CFLinePointLayers.Count; iCnt++) { pFL = (IFeatureLayer)CFLinePointLayers.get_Element(iCnt); IFeatureSelection pFeatSel = (IFeatureSelection)pFL; ISelectionSet2 pSelSet = (ISelectionSet2)pFeatSel.SelectionSet; iTotalSelectionCount += pSelSet.Count; } if (iTotalSelectionCount == 0) { MessageBox.Show("Please select some line points and try again.", "No Selection", MessageBoxButtons.OK, MessageBoxIcon.Information); if (bUseNonVersionedDelete) { pCadEd.CadastralFabricLayer = null; CFLinePointLayers = 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; pStepProgressor.StepValue = 1; pProgressorDialog.Animation = ESRI.ArcGIS.Framework.esriProgressAnimationTypes.esriProgressSpiral; } //loop through each linepoint layer and //delete from its selection m_pQF = new QueryFilterClass(); iCnt = 0; for (; iCnt < CFLinePointLayers.Count; iCnt++) { pFL = (IFeatureLayer)CFLinePointLayers.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 line point data..."; } //Add the OIDs of all the selected linepoints into a new feature IDSet bool bCont = true; m_pFIDSetLinePoints = new FIDSetClass(); ICursor pCursor = null; pSelSet.Search(null, false, out pCursor);//code deletes all selected line points IFeatureCursor pLinePointFeatCurs = (IFeatureCursor)pCursor; IFeature pLinePointFeat = pLinePointFeatCurs.NextFeature(); while (pLinePointFeat != null) { //Check if the cancel button was pressed. If so, stop process if (bShowProgressor) { bCont = pTrackCancel.Continue(); if (!bCont) break; } bool bExists = false; m_pFIDSetLinePoints.Find(pLinePointFeat.OID, out bExists); if (!bExists) m_pFIDSetLinePoints.Add(pLinePointFeat.OID); Marshal.ReleaseComObject(pLinePointFeat); //garbage collection pLinePointFeat = pLinePointFeatCurs.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; } } //delete all the line point records if (bShowProgressor) pStepProgressor.Message = "Deleting selected line points..."; bool bSuccess = true; pLinePointTable = (ITable)pCadFabric.get_CadastralTable(esriCadastralFabricTable.esriCFTLinePoints); if (!bUseNonVersionedDelete) bSuccess = FabricUTILS.DeleteRowsByFIDSet(pLinePointTable, m_pFIDSetLinePoints, pStepProgressor, pTrackCancel); if (bUseNonVersionedDelete) bSuccess = FabricUTILS.DeleteRowsUnversioned(pWS, pLinePointTable, m_pFIDSetLinePoints, pStepProgressor, pTrackCancel); if (!bSuccess) { AbortEdits(bUseNonVersionedDelete, pEd, pWS); return; } } if (bUseNonVersionedDelete) FabricUTILS.StopEditing(pWS); if (pEd.EditState == esriEditState.esriStateEditing) pEd.StopOperation("Delete Line Points"); } catch (Exception ex) { MessageBox.Show(ex.Message); return; } finally { RefreshMap(pActiveView, CFLinePointLayers); //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; CFLinePointLayers = null; } if (pMouseCursor != null) pMouseCursor.SetCursor(0); } }
public static void TraceFlow(ref IPoint point, IApplication app, esriFlowMethod flow, double snapTol, bool traceIndeterminate, bool selectEdges) { IMap map = null; IProgressDialogFactory pProDFact; IStepProgressor pStepPro; IProgressDialog2 pProDlg = null; ITrackCancel pTrkCan; List<IGeometricNetwork> gnList; IGeometricNetwork gn = null; IPoint snappedPoint = null; IFlagDisplay pFlagDisplay; INetFlag startNetFlag; ITraceFlowSolverGEN traceFlowSolver; List<IEdgeFlag> pEdgeFlags = null; List<IJunctionFlag> pJunctionFlags = null; //List<IEdgeFlag> pEdgeFlagsBar = null; //List<IJunctionFlag> pJunctionFlagsBar = null; INetElementBarriers pEdgeElementBarriers; INetElementBarriers pJunctionElementBarriers; ISelectionSetBarriers pSelectionSetBarriers; INetworkAnalysisExt pNetAnalysisExt = null; List<INetFlag> pNetFlags = new List<INetFlag>(); IJunctionFlag[] junctionFlag; IEdgeFlag[] edgeFlag; IEnumNetEID juncEIDs; IEnumNetEID edgeEIDs; IEnvelope env; int EID = -1; double distanceAlong; UID pID = null; INetSolver netSolver = null; try { map = ((IMxDocument)app.Document).FocusMap; bool boolCont = true; // Create a CancelTracker pTrkCan = new CancelTrackerClass(); // Create the ProgressDialog. This automatically displays the dialog pProDFact = new ProgressDialogFactoryClass(); pProDlg = (IProgressDialog2)pProDFact.Create(pTrkCan, 0); // Set the properties of the ProgressDialog pProDlg.CancelEnabled = true; if (flow == esriFlowMethod.esriFMConnected) { pProDlg.Description = A4LGSharedFunctions.Localizer.GetString("GeoNetToolsDesc_14a"); pProDlg.Title = A4LGSharedFunctions.Localizer.GetString("GeoNetToolsTitle_14a"); } else if (flow == esriFlowMethod.esriFMDownstream) { pProDlg.Description = A4LGSharedFunctions.Localizer.GetString("GeoNetToolsDesc_14b"); pProDlg.Title = A4LGSharedFunctions.Localizer.GetString("GeoNetToolsTitle_14b"); } else if (flow == esriFlowMethod.esriFMUpstream) { pProDlg.Description = A4LGSharedFunctions.Localizer.GetString("GeoNetToolsDesc_14c"); pProDlg.Title = A4LGSharedFunctions.Localizer.GetString("GeoNetToolsTitle_14c"); } pProDlg.Animation = esriProgressAnimationTypes.esriProgressGlobe; // Set the properties of the Step Progressor pStepPro = (IStepProgressor)pProDlg; pStepPro.MinRange = 0; pStepPro.MaxRange = 8; pStepPro.StepValue = 1; pStepPro.Position = 0; pStepPro.Message = A4LGSharedFunctions.Localizer.GetString("GeoNetToolsProc_4"); gnList = Globals.GetGeometricNetworksCurrentlyVisible(ref map); int gnIdx = -1; if (gnList == null || gnList.Count == 0) { MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("GeoNetToolsError_2"), A4LGSharedFunctions.Localizer.GetString("GeoNetToolsErrorLbl_2")); return; } pStepPro.Message = A4LGSharedFunctions.Localizer.GetString("GeoNetToolsMess_14a"); pStepPro.Step(); boolCont = pTrkCan.Continue(); if (!boolCont) { pStepPro.Hide(); pProDlg.HideDialog(); pStepPro = null; pProDlg = null; pProDFact = null; return; } //Remove old trace graphics (flags and results) Globals.RemoveTraceGraphics(map, true); Globals.ClearSelected(map, true); // Create junction or edge flag at start of trace - also returns geometric network, snapped point, and EID of junction pStepPro.Message = A4LGSharedFunctions.Localizer.GetString("GeoNetToolsProc_5"); pStepPro.Step(); boolCont = pTrkCan.Continue(); if (!boolCont) { pStepPro.Hide(); pProDlg.HideDialog(); pStepPro = null; pProDlg = null; pProDFact = null; return; } startNetFlag = Globals.GetJunctionFlag(ref point, ref map, ref gnList, snapTol, ref gnIdx, out snappedPoint, out EID, out pFlagDisplay, true) as INetFlag; if (startNetFlag == null) { startNetFlag = Globals.GetEdgeFlag(ref point, ref map, ref gnList, snapTol, ref gnIdx, out snappedPoint, out EID, out distanceAlong, out pFlagDisplay, true) as INetFlag; } //Set network to trace if (gnIdx > -1) gn = gnList[gnIdx] as IGeometricNetwork; // Stop if user point was not on a visible network feature, old trace results and selection are cleared if (gn == null || startNetFlag == null) { return; } pStepPro.Message = A4LGSharedFunctions.Localizer.GetString("GeoNetToolsMess_14b"); pStepPro.Step(); boolCont = pTrkCan.Continue(); if (!boolCont) { pStepPro.Hide(); pProDlg.HideDialog(); pStepPro = null; pProDlg = null; pProDFact = null; return; } //Setup trace solver // ITraceFlowSolverGEN traceFlowSolver = new TraceFlowSolverClass() as ITraceFlowSolverGEN; // ITraceFlowSolver traceFlowSolver = Globals.CreateTraceFlowSolverFromToolbar(gn); if (app != null) { pID = new UID(); pID.Value = "esriEditorExt.UtilityNetworkAnalysisExt"; pNetAnalysisExt = (INetworkAnalysisExt)app.FindExtensionByCLSID(pID); Globals.SetCurrentNetwork(ref pNetAnalysisExt, ref gn); traceFlowSolver = Globals.CreateTraceFlowSolverFromToolbar(ref pNetAnalysisExt, out pEdgeFlags, out pJunctionFlags, out pEdgeElementBarriers, out pJunctionElementBarriers, out pSelectionSetBarriers) as ITraceFlowSolverGEN; pID = null; } else { traceFlowSolver = new TraceFlowSolverClass() as ITraceFlowSolverGEN; netSolver = traceFlowSolver as INetSolver; netSolver.SourceNetwork = gn.Network; netSolver = null; } traceFlowSolver.TraceIndeterminateFlow = traceIndeterminate; pStepPro.Message = A4LGSharedFunctions.Localizer.GetString("GeoNetToolsMess_14c"); pStepPro.Step(); boolCont = pTrkCan.Continue(); if (!boolCont) { pStepPro.Hide(); pProDlg.HideDialog(); pStepPro = null; pProDlg = null; pProDFact = null; return; } //Add the flag to the trace solver if (pEdgeFlags != null) { foreach (IEdgeFlag pEdFl in pEdgeFlags) { pNetFlags.Add((INetFlag)pEdFl); } } if (pJunctionFlags != null) { foreach (IJunctionFlag pJcFl in pJunctionFlags) { pNetFlags.Add((INetFlag)pJcFl); } } if (startNetFlag != null) { pNetFlags.Add((INetFlag)startNetFlag); } Globals.AddFlagsToTraceSolver(pNetFlags.ToArray(), ref traceFlowSolver, out junctionFlag, out edgeFlag); pStepPro.Message = A4LGSharedFunctions.Localizer.GetString("GeoNetToolsMess_14d"); pStepPro.Step(); boolCont = pTrkCan.Continue(); if (!boolCont) { pStepPro.Hide(); pProDlg.HideDialog(); pStepPro = null; pProDlg = null; pProDFact = null; return; } //Run the trace traceFlowSolver.FindFlowElements(flow, esriFlowElements.esriFEJunctionsAndEdges, out juncEIDs, out edgeEIDs); if (juncEIDs.Count == 0) { if (flow == esriFlowMethod.esriFMDownstream) MessageBox.Show( A4LGSharedFunctions.Localizer.GetString("GeoNetToolsMess_14e") + Environment.NewLine + Environment.NewLine + A4LGSharedFunctions.Localizer.GetString("GeoNetToolsMess_14f") , A4LGSharedFunctions.Localizer.GetString("GeoNetToolsTitle_14b")); else MessageBox.Show( A4LGSharedFunctions.Localizer.GetString("GeoNetToolsMess_14g") + Environment.NewLine + Environment.NewLine + A4LGSharedFunctions.Localizer.GetString("GeoNetToolsMess_14f") , A4LGSharedFunctions.Localizer.GetString("GeoNetToolsTitle_14c")); return; } pStepPro.Message = A4LGSharedFunctions.Localizer.GetString("GeoNetToolsMess_14h"); pStepPro.Step(); boolCont = pTrkCan.Continue(); if (!boolCont) { pStepPro.Hide(); pProDlg.HideDialog(); pStepPro = null; pProDlg = null; pProDFact = null; return; } //Select junction features Globals.SelectJunctions(ref map, ref gn, ref juncEIDs, ref junctionFlag, "", "", "", true); if (selectEdges) Globals.SelectEdges(ref map, ref gn, ref edgeEIDs); else Globals.DrawEdges(ref map, ref gn, ref edgeEIDs); //edgeEIDs.Reset(); //Draw edge graphics //Draw graphic point at start location of trace if (pNetAnalysisExt != null) { Globals.AddFlagToGN(ref pNetAnalysisExt, ref gn, ref pFlagDisplay); } else { Globals.AddPointGraphic(map, snappedPoint, false); } Globals.GetCommand("esriArcMapUI.ZoomToSelectedCommand", app).Execute(); //Open identify dialog with selected features //IdentifySelected(map); // add set flow direction buttons pStepPro.Message = A4LGSharedFunctions.Localizer.GetString("Complete"); pStepPro.Step(); boolCont = pTrkCan.Continue(); if (!boolCont) { pStepPro.Hide(); pProDlg.HideDialog(); pStepPro = null; pProDlg = null; pProDFact = null; return; } ((IMxDocument)app.Document).ActiveView.Refresh(); return; } catch (Exception ex) { MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("ErrorInThe") + A4LGSharedFunctions.Localizer.GetString("GeoNetToolsProc_14a") + ": " + ex.ToString()); if (pProDlg != null) { pProDlg.HideDialog(); //pStepPro = null; pProDlg = null; pProDFact = null; return; } } finally { if (pProDlg != null) { pProDlg.HideDialog(); } pStepPro = null; pProDlg = null; pProDFact = null; gnList = null; gn = null; snappedPoint = null; pFlagDisplay = null; startNetFlag = null; traceFlowSolver = null; pEdgeFlags = null; pJunctionFlags = null; pNetAnalysisExt = null; pNetFlags = null; junctionFlag = null; edgeFlag = null; juncEIDs = null; edgeEIDs = null; env = null; map = null; pID = null; netSolver = null; } }
protected override void OnClick() { try { IGxSelection gxSelection = this.pGxApp.Selection; if (gxSelection.Count < 1) { return; } // Inizializzo le variabili per la progress bar... ITrackCancel trkCancel = null; IProgressDialogFactory prgFact = new ProgressDialogFactoryClass(); IStepProgressor stepProgressor = null; IProgressDialog2 progressDialog = null; int intNumberFcConverted = 0; int cont = gxSelection.Count; IEnumGxObject enumGxObject = gxSelection.SelectedObjects; stepProgressor = prgFact.Create(trkCancel, 0); progressDialog = stepProgressor as IProgressDialog2; progressDialog.Description = "Removing extensions..."; progressDialog.Title = "Removing extensions..."; progressDialog.Animation = esriProgressAnimationTypes.esriProgressSpiral; progressDialog.ShowDialog(); stepProgressor.MinRange = 0; stepProgressor.MaxRange = cont; stepProgressor.StepValue = 1; stepProgressor.Show(); IGxObject pGxObject = enumGxObject.Next(); while (pGxObject != null) { if (!(pGxObject is IGxDataset)) { return; } IGxDataset pGxDataset = pGxObject as IGxDataset; if (pGxDataset == null) { return; } //if (((pGxObject as IGxDataset).Type) != esriDatasetType.esriDTFeatureClass) //{ // return; //} this.engine(pGxDataset, pGxObject, ref intNumberFcConverted); pGxObject = enumGxObject.Next(); stepProgressor.Step(); } stepProgressor.Message = "End"; stepProgressor.Hide(); progressDialog.HideDialog(); MessageBox.Show($@"Extension removed for {intNumberFcConverted} objects!", "Attention", MessageBoxButtons.OK, MessageBoxIcon.Information); } catch (Exception ex) { MessageBox.Show("Error: " + ex.Message.ToString()); } }
public static void TraceIsolationSummary(IApplication app, string sourceFLName, string valveFLName, string operableFieldNameValve, string operableFieldNameSource, double snapTol, bool processEvent, string[] opValues, string addSQL, bool traceIndeterminate, bool ZeroSourceCont, string mainsFLName, string meterFLName, string metersCritFieldName, string metersCritValue, string traceSum_LayerName, string traceSum_FacilityIDField, string traceSum_DateFieldName, string traceSum_ValveCountFieldName, string traceSum_MeterCountFieldName, string traceSum_CritMeterCountFieldName, string traceSum_CommentsFieldName) { IFeatureLayer mainsFL = null; IFeatureLayer resultsLayer = null; IFeatureClass mainFC = null; INetworkClass mainsNetwork = null; IFeatureClass resultsFC = null; IFeatureSelection mainsFS = null; IFeature pMainsFeat = null; IProgressDialogFactory pProDFact = null; IStepProgressor pStepPro = null; IProgressDialog2 pProDlg = null; ITrackCancel pTrkCan = null; IWorkspaceEdit pWSEdit = null; IFeatureCursor pFC = null; IFeatureCursor pInsCur = null; // IFeatureClassLoad featureClassLoad = null; // ISchemaLock schemaLock = null; IFeatureBuffer pSumFeatBuf = null; IEnumIDs pSelectIDs = null; ICurve pCurve = null; IPoint pPnt = null; IDataset pDS = null; int facilityIDFieldPosition; int resultsFacilityIDFieldPosition; //int resultsSourceIDFieldPosition; int resultsDateFieldPosition; int resultsValveCountFieldPosition; int resultsMeterCountFieldPosition; int resultsCritMeterCountFieldPosition; int resultsCommentsFieldPosition; try { bool FCorLayerMains = true; mainsFL = (IFeatureLayer)Globals.FindLayer(((IMxDocument)app.Document).FocusMap, mainsFLName, ref FCorLayerMains); if (mainsFL == null) { MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("GeoNetToolsMess_15d") + mainsFLName + " feature class was not found.\r\n Check the TraceIsolationSummary_Main_FeatureLayer tag in the config"); return; } mainFC = mainsFL.FeatureClass; //Determine field position for facility id facilityIDFieldPosition = mainFC.Fields.FindField("FACILITYID"); if (facilityIDFieldPosition == -1) facilityIDFieldPosition = mainFC.Fields.FindField("FACID"); if (facilityIDFieldPosition == -1) facilityIDFieldPosition = mainFC.Fields.FindField("ASSETID"); if (facilityIDFieldPosition == -1) facilityIDFieldPosition = mainFC.Fields.FindField(mainFC.OIDFieldName); if (facilityIDFieldPosition == -1) return; mainsNetwork = mainFC as INetworkClass; if ((mainsNetwork == null) || (mainsNetwork.GeometricNetwork == null)) { MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("GeoNetToolsMess_15d") + mainsFLName + A4LGSharedFunctions.Localizer.GetString("GeoNetToolsError_18a")); return; } mainsFS = (IFeatureSelection)mainsFL; int FeatureCount = 0; if (mainsFS.SelectionSet.Count == 0) { MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("No") + mainsFL.Name + A4LGSharedFunctions.Localizer.GetString("GeoNetToolsError_18b"), A4LGSharedFunctions.Localizer.GetString("GeoNetToolsLbl_18a"), MessageBoxButtons.OK); return; } FeatureCount = mainsFS.SelectionSet.Count; bool boolCont = true; // Create a CancelTracker pTrkCan = new CancelTrackerClass(); // Create the ProgressDialog. This automatically displays the dialog pProDFact = new ProgressDialogFactoryClass(); pProDlg = (IProgressDialog2)pProDFact.Create(pTrkCan, 0); // Set the properties of the ProgressDialog pProDlg.CancelEnabled = true; pProDlg.Description = A4LGSharedFunctions.Localizer.GetString("GeoNetToolsDesc_18a"); pProDlg.Title = A4LGSharedFunctions.Localizer.GetString("GeoNetToolsTitle_18a"); pProDlg.Animation = esriProgressAnimationTypes.esriProgressGlobe; // Set the properties of the Step Progressor pStepPro = (IStepProgressor)pProDlg; pStepPro.MinRange = 1; pStepPro.MaxRange = FeatureCount - 1; pStepPro.StepValue = 1; pStepPro.Message = A4LGSharedFunctions.Localizer.GetString("GeoNetToolsMess_18a"); // Get Results feature class and test its schema bool FCorLayerResults = true; resultsLayer = (IFeatureLayer)Globals.FindLayer(((IMxDocument)app.Document).FocusMap, traceSum_LayerName, ref FCorLayerResults); if (resultsLayer == null) { MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("GeoNetToolsMess_15d") + traceSum_LayerName + A4LGSharedFunctions.Localizer.GetString("GeoNetToolsError_18c")); return; } if (resultsLayer.FeatureClass == null) { MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("GeoNetToolsMess_15d") + traceSum_LayerName + A4LGSharedFunctions.Localizer.GetString("GeoNetToolsError_18d")); return; } resultsFC = resultsLayer.FeatureClass; pDS = (IDataset)resultsFC; pWSEdit = (IWorkspaceEdit)pDS.Workspace; pDS = null; bool alreadyEditing = pWSEdit.IsBeingEdited(); // if (alreadyEditing != true) // pWSEdit.StartEditing(true); // pWSEdit.StartEditOperation( if (alreadyEditing == false) { MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("GeoNetToolsMess_15d") + traceSum_LayerName + " layer must be editable."); return; } // resultsFC = resultsLayer.FeatureClass; resultsFacilityIDFieldPosition = resultsFC.Fields.FindField(traceSum_FacilityIDField); resultsDateFieldPosition = resultsFC.Fields.FindField(traceSum_DateFieldName); resultsValveCountFieldPosition = resultsFC.Fields.FindField(traceSum_ValveCountFieldName); resultsMeterCountFieldPosition = resultsFC.Fields.FindField(traceSum_MeterCountFieldName); resultsCritMeterCountFieldPosition = resultsFC.Fields.FindField(traceSum_CritMeterCountFieldName); resultsCommentsFieldPosition = resultsFC.Fields.FindField(traceSum_CommentsFieldName); if (resultsFacilityIDFieldPosition == -1) { MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("Field") + traceSum_FacilityIDField + A4LGSharedFunctions.Localizer.GetString("GeoNetToolsError_18f"), A4LGSharedFunctions.Localizer.GetString("GeoNetToolsLbl_18a")); return; } //if (resultsDateFieldPosition == -1) //{ // MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("Field") + traceSum_DateFieldName + A4LGSharedFunctions.Localizer.GetString("GeoNetToolsError_18f"), A4LGSharedFunctions.Localizer.GetString("GeoNetToolsLbl_18a")); // return; //} if (resultsValveCountFieldPosition == -1) { MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("Field") + traceSum_ValveCountFieldName + A4LGSharedFunctions.Localizer.GetString("GeoNetToolsError_18f"), A4LGSharedFunctions.Localizer.GetString("GeoNetToolsLbl_18a")); return; } if (resultsMeterCountFieldPosition == -1) { MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("Field") + traceSum_MeterCountFieldName + A4LGSharedFunctions.Localizer.GetString("GeoNetToolsError_18f"), A4LGSharedFunctions.Localizer.GetString("GeoNetToolsLbl_18a")); return; } if (resultsCritMeterCountFieldPosition == -1) { MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("Field") + traceSum_CritMeterCountFieldName + A4LGSharedFunctions.Localizer.GetString("GeoNetToolsError_18f"), A4LGSharedFunctions.Localizer.GetString("GeoNetToolsLbl_18a")); return; } pWSEdit.StartEditOperation(); pInsCur = resultsFC.Insert(true); pSumFeatBuf = resultsFC.CreateFeatureBuffer(); int intValveCount = 0; int intMeterCount = 0; int intCritMeterCount = 0; string comments = ""; pSelectIDs = mainsFS.SelectionSet.IDs; int intCurID = pSelectIDs.Next(); while (intCurID != -1) { intValveCount = 0; intMeterCount = 0; intCritMeterCount = 0; comments = ""; try { // Globals.RemoveTraceGraphics(((IMxDocument)ArcMap.Application.Document).FocusMap, false); // Globals.ClearSelected(ArcMap.Application, false); Globals.ClearGNFlags(app, Globals.GNTypes.Flags); pMainsFeat = mainsFL.FeatureClass.GetFeature(intCurID); pStepPro.Message = A4LGSharedFunctions.Localizer.GetString("GeoNetToolsProc_18b") + pStepPro.Position + A4LGSharedFunctions.Localizer.GetString("Of") + FeatureCount + A4LGSharedFunctions.Localizer.GetString("GeoNetToolsProc_18a"); pCurve = (ICurve)pMainsFeat.Shape; pPnt = new PointClass(); pCurve.QueryPoint(esriSegmentExtension.esriNoExtension, 0.5, true, pPnt); string result = GeoNetTools.TraceIsolation(new double[] { pPnt.X }, new double[] { pPnt.Y }, app, sourceFLName, valveFLName, operableFieldNameValve, operableFieldNameSource, snapTol, false, opValues, addSQL, traceIndeterminate, ZeroSourceCont, false, meterFLName, metersCritFieldName, metersCritValue); string[] resVals = result.Split('_'); if (resVals.Length == 3) { intValveCount = Convert.ToInt32(resVals[0]); intMeterCount = Convert.ToInt32(resVals[1]); intCritMeterCount = Convert.ToInt32(resVals[2]); comments = A4LGSharedFunctions.Localizer.GetString("GeoNetToolsDone_18a"); } else { comments = result; } // pStepPro.Message = "Saving Result: " + pStepPro.Position + A4LGSharedFunctions.Localizer.GetString("Of") + FeatureCount + A4LGSharedFunctions.Localizer.GetString("GeoNetToolsProc_18a"); pSumFeatBuf.Shape = pMainsFeat.ShapeCopy; if (resultsDateFieldPosition > -1) { pSumFeatBuf.set_Value(resultsDateFieldPosition, DateTime.Now); } pSumFeatBuf.set_Value(resultsFacilityIDFieldPosition, pMainsFeat.get_Value(facilityIDFieldPosition)); pSumFeatBuf.set_Value(resultsValveCountFieldPosition, intValveCount); pSumFeatBuf.set_Value(resultsMeterCountFieldPosition, intMeterCount); pSumFeatBuf.set_Value(resultsCritMeterCountFieldPosition, intCritMeterCount); if (resultsCommentsFieldPosition > 0) { pSumFeatBuf.set_Value(resultsCommentsFieldPosition, comments); } pStepPro.Step(); pInsCur.InsertFeature(pSumFeatBuf); //curIdx = curIdx + 1; // pInsCur.InsertFeature (pFeatBuf); boolCont = pTrkCan.Continue(); if (!boolCont) { pInsCur.Flush(); pWSEdit.AbortEditOperation(); return; } } catch (Exception Ex) { System.Diagnostics.Debug.WriteLine(Ex.Message + A4LGSharedFunctions.Localizer.GetString("Step") + pStepPro.Position); System.Diagnostics.Trace.WriteLine(Ex.Message + A4LGSharedFunctions.Localizer.GetString("Step") + pStepPro.Position); // MessageBox.Show(Ex.Message); } intCurID = pSelectIDs.Next(); Marshal.ReleaseComObject(pMainsFeat); } try { pInsCur.Flush(); } catch { } pWSEdit.StopEditOperation(); } catch (Exception ex) { MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("GeoNetToolsLbl_18a") + "\n" + ex.Message); if (pWSEdit != null) { if (pWSEdit.IsBeingEdited() == true) { pWSEdit.AbortEditOperation(); // pWSEdit.StopEditing(false); } } } finally { //if (schemaLock != null) // schemaLock.ChangeSchemaLock(esriSchemaLock.esriSharedSchemaLock); //if (featureClassLoad != null) // featureClassLoad.LoadOnlyMode = false; //if (pWSEdit != null) //{ // if (pWSEdit.IsBeingEdited() == true) // { // pWSEdit.AbortEditOperation(); // pWSEdit.StopEditing(false); // } //} //if (pInsCur != null) // pInsCur.Flush(); if (pProDlg != null) pProDlg.HideDialog(); if (pFC != null) Marshal.ReleaseComObject(pFC); if (pInsCur != null) Marshal.ReleaseComObject(pInsCur); mainsFL = null; resultsLayer = null; mainFC = null; mainsNetwork = null; resultsFC = null; mainsFS = null; pMainsFeat = null; pProDFact = null; pStepPro = null; pProDlg = null; pTrkCan = null; pWSEdit = null; pFC = null; pInsCur = null; pSumFeatBuf = null; pSelectIDs = null; pCurve = null; pPnt = null; pDS = null; } }
/** * Executes each of the DataQualityTests in order and collects their results */ public int Execute() { // Establish the place to store the errors try { tm.TransactionManager theTM = this.Extension.TransactionManager; string theFCName = this.Extension.get_SystemValue("tm.template.dataerrors.table"); if (theTM.Current() == null) { // This isn't tied to any transaction, so prompt the user to save a pgdb SaveFileDialog theSaveDialog = new SaveFileDialog(); theSaveDialog.Filter = "Personal Geodatabase files (*.mdb)|*.mdb"; theSaveDialog.FilterIndex = 1; theSaveDialog.RestoreDirectory = true; theSaveDialog.Title = "Save Test Results"; if(theSaveDialog.ShowDialog() == DialogResult.OK) { string theTemplate = this.Extension.get_SystemValue("tm.template.tant.pgdb"); this._errors = new QAErrorStorage(theTemplate, theSaveDialog.FileName, theFCName); } else return -2; } else { if (this._errors == null || this._errors.StorageWorkspace != theTM.Current().PGDBConnection) { this._errors = new QAErrorStorage(theTM.Current().PGDBConnection, theFCName); } } } catch (Exception ex) { MessageBox.Show("Error raised when establishing place to save errors:" + Environment.NewLine + ex.Message, "Error Storage Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); util.Logger.Write("Error raised when establishing place to save errors:" + Environment.NewLine + ex.Message + Environment.NewLine + ex.StackTrace); return -1; } bool bShowErrorManager = false; ArrayList theNewErrors = new ArrayList(); // Initialize log file string logDirectory = this.Extension.get_SystemValue(util.Logger.LOG_DIRECTORY_KEY) + Path.DirectorySeparatorChar; String logFileName = logDirectory + "isdut_qa_" + DateTime.Now.ToString("s").Replace(":", "-") + ".log"; // Will put up a progress dialog, with a proper CancelTracker IProgressDialog2 thePDialog = null; try { ITrackCancel theCancelTracker = new CancelTrackerClass(); IProgressDialogFactory theFactory = new ProgressDialogFactoryClass(); thePDialog = (IProgressDialog2)theFactory.Create(theCancelTracker, this._app.hWnd); thePDialog.CancelEnabled = true; thePDialog.Description = ""; thePDialog.Title = "Running QA Tests"; thePDialog.Animation = esriProgressAnimationTypes.esriProgressGlobe; IStepProgressor theStepProgressor = (IStepProgressor)thePDialog; theStepProgressor.MinRange = 0; theStepProgressor.MaxRange = this.TestCount + 2; theStepProgressor.StepValue = 1; bool bContinue = true; bool bProblemWithTest = false; for (int i = 0; i < this.TestCount; i++) { QATest theQATest = this._tests.get_Test(i); theStepProgressor.Message = theQATest.Name; if (theQATest != null && theQATest.IsActive) { IDataQualityTest theTest = theQATest.Test; if (theTest != null) { int errCount = theTest.Execute(logFileName); bContinue = theCancelTracker.Continue(); if (bContinue == false) break; if (errCount < 0) { bProblemWithTest = true; } if (theTest.ErrorCount > 0) { DataQualityError theDQError; for (int j = 0; j < theTest.ErrorCount; j++) { theDQError = theTest.get_Error(j); theDQError.Status = DataQualityError.STATUS_NEW; theNewErrors.Add(theDQError); } } theTest.ClearErrors(); } } theStepProgressor.Step(); } theStepProgressor.Message = "Filtering exceptions..."; string path = RestTransactionManager.Instance.BaseTransactionManager.extension().get_SystemValue(DAOUtils.ISDUT_SEE_TEMP); IWorkspaceFactory workspaceFactory = new ESRI.ArcGIS.DataSourcesGDB.FileGDBWorkspaceFactoryClass(); IWorkspace theIsdutWorkspace = workspaceFactory.OpenFromFile(path, 0); this._exceptions = new QAExceptionStorage( theIsdutWorkspace, this.Extension.get_SystemValue("db.isdut.schema"), this._operationalAreaForLoadedTests); // Check each error to see if it is an exception foreach (object obj in theNewErrors) { DataQualityError theError = (DataQualityError)obj; if (_exceptions != null) { QAException theException = this._exceptions.FindException(theError); if (theException != null) theError.Status = theException.Status; } } theStepProgressor.Message = "Storing results..."; // Pass the new errors to the QAErrorStorage this._errors.ClearErrors(); this._errors.SetNewErrors(theNewErrors, this._operationalAreaForLoadedTests); // IsValid is true at this point theStepProgressor.Step(); bShowErrorManager = true; // If any of the tests returned an error value, invalidate if (bProblemWithTest) { this._errors.Invalidate(); MessageBox.Show("At least one test returned an error code, The test results have been written, but are not valid.", "Problem Testing", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } } catch (ErrorStorageException ese) { MessageBox.Show("There was an error storing the errors:" +Environment.NewLine + ese.Message + Environment.NewLine + ese.StackTrace, "Error Storage Problem", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } catch (Exception e) { if (theNewErrors.Count > 0) { util.Logger.Write("Error raised while testing data: " + Environment.NewLine + e.Message + Environment.NewLine + e.StackTrace, util.Logger.LogLevel.Debug); DialogResult theResult = MessageBox.Show("An error occurred when testing data. Would you like to store the partial results?", "Partial QA Results", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation); if (theResult == DialogResult.Yes) { this._errors.SetNewErrors(theNewErrors, this._operationalAreaForLoadedTests); bShowErrorManager = true; } } this._errors.Invalidate(); } finally { if (thePDialog != null) thePDialog.HideDialog(); thePDialog = null; } if (bShowErrorManager) { UID theUID = new UIDClass(); theUID.Value = "{73519A57-E89E-4773-87DA-E93661E23F6D}"; //ErrorManagerCmd // TODO: ICommandItem theCItem = this._app.Document.CommandBars.Find(theUID, false, false); if (theCItem != null) { ((ui.ErrorManagerCmd)theCItem.Command).Open(); } else MessageBox.Show("Could not locate the Error Manager command button", "COM Registration", MessageBoxButtons.OK, MessageBoxIcon.Information); } return this.ErrorCount; }
public static void AddBarrier(IPoint pPnt, IApplication app, double snapTol) { IProgressDialogFactory pProDFact = null; IStepProgressor pStepPro = null; IProgressDialog2 pProDlg = null; ITrackCancel pTrkCan = null; List<IGeometricNetwork> gnList = null; IGeometricNetwork gn = null; IPoint snappedPoint = null; IFlagDisplay pFlagDisplay = null; INetFlag startNetFlag = null; INetworkAnalysisExt pNetAnalysisExt = null; UID pID = null; IMap pMap = null; int EID = -1; double distanceAlong; try { pMap = (app.Document as IMxDocument).FocusMap; bool boolCont = true; // Create a CancelTracker pTrkCan = new CancelTrackerClass(); // Create the ProgressDialog. This automatically displays the dialog pProDFact = new ProgressDialogFactoryClass(); pProDlg = (IProgressDialog2)pProDFact.Create(pTrkCan, 0); // Set the properties of the ProgressDialog pProDlg.CancelEnabled = true; pProDlg.Animation = esriProgressAnimationTypes.esriProgressGlobe; // Set the properties of the Step Progressor pStepPro = (IStepProgressor)pProDlg; pStepPro.MinRange = 0; pStepPro.MaxRange = 6; pStepPro.StepValue = 1; pStepPro.Position = 0; pStepPro.Message = A4LGSharedFunctions.Localizer.GetString("GeoNetToolsProc_4"); gnList = Globals.GetGeometricNetworksCurrentlyVisible(ref pMap); int gnIdx = -1; if (gnList == null || gnList.Count == 0) { MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("GeoNetToolsError_2"), A4LGSharedFunctions.Localizer.GetString("GeoNetToolsErrorLbl_2")); return; } // Create junction or edge flag at start of trace - also returns geometric network, snapped point, and EID of junction pStepPro.Message = A4LGSharedFunctions.Localizer.GetString("GeoNetToolsProc_6"); pStepPro.Step(); boolCont = pTrkCan.Continue(); if (!boolCont) { pStepPro.Hide(); pProDlg.HideDialog(); pStepPro = null; pProDlg = null; pProDFact = null; return; } startNetFlag = Globals.GetJunctionFlag(ref pPnt, ref pMap, ref gnList, snapTol, ref gnIdx, out snappedPoint, out EID, out pFlagDisplay, false) as INetFlag; if (startNetFlag == null) { startNetFlag = Globals.GetEdgeFlag(ref pPnt, ref pMap, ref gnList, snapTol, ref gnIdx, out snappedPoint, out EID, out distanceAlong, out pFlagDisplay, false) as INetFlag; } //Set network to trace if (gnIdx > -1) gn = gnList[gnIdx] as IGeometricNetwork; // Stop if user point was not on a visible network feature, old trace results and selection are cleared if (gn == null || startNetFlag == null) { return; } if (app != null) { pID = new UID(); pID.Value = "esriEditorExt.UtilityNetworkAnalysisExt"; pNetAnalysisExt = (INetworkAnalysisExt)app.FindExtensionByCLSID(pID); Globals.SetCurrentNetwork(ref pNetAnalysisExt, ref gn); Globals.AddBarrierToGN(pNetAnalysisExt, gn, pFlagDisplay); // pFlagDisplay pNetAnalysisExt = null; pID = null; } } catch (Exception ex) { MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("ErrorInThe") + A4LGSharedFunctions.Localizer.GetString("GeoNetToolsLbl_3") + ": " + ex.ToString()); } finally { if (pProDlg != null) { pProDlg.HideDialog(); } pStepPro = null; pProDlg = null; pProDFact = null; pTrkCan = null; pMap = null; gnList = null; gn = null; snappedPoint = null; pFlagDisplay = null; startNetFlag = null; pNetAnalysisExt = null; pID = null; pMap = null; } }
private void button1_Click(object sender, EventArgs e) { IProgressDialogFactory pProDiaFac = new ProgressDialogFactoryClass(); IStepProgressor pStepPro = pProDiaFac.Create(null, 0); pStepPro.MinRange = 1; pStepPro.MaxRange = 5; pStepPro.StepValue = 1; IProgressDialog2 pProDia = (IProgressDialog2)pStepPro; pProDia.Animation = esriProgressAnimationTypes.esriProgressGlobe; pProDia.Title = "Generar Grids"; pProDia.ShowDialog(); pStepPro.Step(); pStepPro.Message = "Generando Grids Meteorologicos..."; IFeatureClass pFeatureClass; IWorkspaceFactory pShpWorkspaceFactory = new ShapefileWorkspaceFactoryClass(); IWorkspace pWorkspaceTemp = pShpWorkspaceFactory.OpenFromFile(parametros.RutaSIGPI + parametros.Temporal, 0); try { pFeatureClass = procesamiento.ConstruirFeatureClass(pWorkspaceTemp, "DEFI_PRECI", "estaciones", "CODIGO", "DEFI_PRECI.P5 >= 0", "JP"); } catch (Exception ex) { MessageBox.Show("Error generando el FeatureClass de Estaciones. Descripcion: \n" + ex.Message); return; } IWorkspaceFactory pWF = new AccessWorkspaceFactoryClass(); IFeatureWorkspace pWSMask = (IFeatureWorkspace)pWF.OpenFromFile(parametros.RutaGBD, 0); IGeoDataset pFCMask = (IGeoDataset)pWSMask.OpenFeatureClass(parametros.Mascara); DateTime date = sigpi.FechaProcesamiento; string sMonth = date.ToString("MM"); //P5 pStepPro.Step(); pStepPro.Message = "Generando Grids Meteorologicos: Precipitacion Total"; IRaster pRaster1 = procesamiento.ConstruirGrid(pFeatureClass, "P5", parametros, pFCMask, "RP5", "", true); //DSLL5 pStepPro.Step(); pStepPro.Message = "Generando Grids Meteorologicos: Promedio ultimos 5 dias sin lluvia"; IRaster pRaster2 = procesamiento.ConstruirGrid(pFeatureClass, "DSLL5", parametros, pFCMask, "DSLL5", "", true); pFeatureClass = procesamiento.ConstruirFeatureClass(pWorkspaceTemp, "DEFI_TEMPE", "estaciones", "CODIGO", "DEFI_TEMPE.T5 >= 0", "JT"); //T5 pStepPro.Step(); pStepPro.Message = "Generando Grids Meteorologicos: Temperatura promedio"; IRaster pRaster3 = procesamiento.ConstruirGrid(pFeatureClass, "T5", parametros, pFCMask, "RT5", "", true); //TMMMM IRaster pRaster4 = SIGPIUtils.AbrirRasterDesdeArchivo(parametros.RutaSIGPI + "\\" + parametros.TMMMM, "tmmx" + sMonth); //Susceptibilidad //IRaster pRaster5 = SIGPIUtils.AbrirRaster(parametros.RutaSIGPI + "\\" + parametros.Grids, parametros.Susceptibilidad); IRaster pRaster5 = SIGPIUtils.AbrirRasterDesdeGDB(parametros.RutaGBD, parametros.Susceptibilidad); //Asentamientos //IRaster pRaster6 = SIGPIUtils.AbrirRaster(parametros.RutaSIGPI + "\\" + parametros.Grids, parametros.Asentamientos); IRaster pRaster6 = SIGPIUtils.AbrirRasterDesdeGDB(parametros.RutaGBD, parametros.Asentamientos); IRaster[] pRasters = { pRaster1, pRaster2, pRaster3, pRaster4, pRaster5, pRaster6 }; try { procesamiento.AlgoritmoCompleto(pRasters, sigpi); } catch (Exception ex) { MessageBox.Show(ex.Message); } pProDia.HideDialog(); MessageBox.Show("Algoritmo completo ejecutado"); }
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 static ISpatialReference ProjectWorkspaceContents( IWorkspace w, FileInfo pgdb, Dictionary<string,ISpatialReference> outputSRDict, int hWnd) { bool bHaveStartedProjecting = false; string theBackup = ""; IStepProgressor theStepProgressor = null; ISpatialReference theReturn = null; try { // Get the default SR (if set) ISpatialReference theDefaultSR = null; if (outputSRDict.ContainsKey("*")) theDefaultSR = outputSRDict["*"]; // Check for schema locks IEnumDataset theEnumDataset = w.get_Datasets(esriDatasetType.esriDTFeatureDataset); ISchemaLock theSLock = theEnumDataset.Next() as ISchemaLock; int datasetCount = 0; while (theSLock != null) { datasetCount++; try { theSLock.ChangeSchemaLock(esriSchemaLock.esriExclusiveSchemaLock); theSLock.ChangeSchemaLock(esriSchemaLock.esriSharedSchemaLock); } catch (Exception ex) { string msg = "There is an exclusive lock. Please ensure you do not have ArcCatalog running."; MessageBox.Show(msg); throw new ExclusiveLockException(msg, ex); } theSLock = theEnumDataset.Next() as ISchemaLock; } if (hWnd != 0) { IProgressDialogFactory theFactory = new ProgressDialogFactoryClass(); IProgressDialog2 thePDialog = (IProgressDialog2)theFactory.Create(null, hWnd); theStepProgressor = (IStepProgressor)thePDialog; thePDialog.Description = ""; thePDialog.Title = "Projecting Transaction"; thePDialog.Animation = esriProgressAnimationTypes.esriProgressGlobe; theStepProgressor = (IStepProgressor)thePDialog; theStepProgressor.MinRange = 0; theStepProgressor.MaxRange = datasetCount + 2; theStepProgressor.StepValue = 1; } // Make a backup copy of the database //if (theStepProgressor != null) theStepProgressor.Message = "Creating backup file"; //theBackup = CreateBackup(pgdb); if (theStepProgressor != null) theStepProgressor.Step(); if (theStepProgressor != null) theStepProgressor.Message = "Initializing Geoprocessor"; Geoprocessor theGP = SetupGPEnvironment(pgdb.FullName); if (theStepProgressor != null) theStepProgressor.Step(); IGPProcess theGPProc = null; // Do feature datasets theEnumDataset = w.get_Datasets(esriDatasetType.esriDTFeatureDataset); IFeatureDataset theInFDataset = theEnumDataset.Next() as IFeatureDataset; // Mark that we're starting to edit the transaction tm.dao.MetadataDAO mdao = new tm.dao.MetadataDAO((IFeatureWorkspace)w); mdao.markStartReprojecting(); bHaveStartedProjecting = true; while (theInFDataset != null) { // Choose the output SR ISpatialReference theOutputSR = null; if (outputSRDict.ContainsKey(theInFDataset.Name)) theOutputSR = outputSRDict[theInFDataset.Name]; else theOutputSR = theDefaultSR; if (theOutputSR != null) { // Write the output SR to a prj file string prjFile = CreatePrjFile(theOutputSR); theReturn = theOutputSR; string inFDName = pgdb.FullName + System.IO.Path.DirectorySeparatorChar + theInFDataset.Name; string outFDName = inFDName + "_isdut"; if (theStepProgressor != null) theStepProgressor.Message = "Projecting " + theInFDataset.Name; theGPProc = new ESRI.ArcGIS.DataManagementTools.Project(inFDName, outFDName, prjFile); if (RunTool(theGP, theGPProc, null)) { //Debug.Print("Successful project of " + inFDName + " to " + outFDName); IFeatureDataset theOutFDataset = ((IFeatureWorkspace)w).OpenFeatureDataset(theInFDataset.Name + "_isdut"); WriteOutputBack(theInFDataset, theOutFDataset); } else { Debug.Print("Project of " + inFDName + " unsuccessful"); throw new GPFailedException("Projection failed for " + inFDName, null); } } else { util.Logger.Write("No SR was defined for feature dataset '" + theInFDataset.Name + "'", util.Logger.LogLevel.Warn); } if (theStepProgressor != null) theStepProgressor.Step(); theInFDataset = theEnumDataset.Next() as IFeatureDataset; } // Editing of the transaction is finished, clear the flag mdao.markEndReprojecting(); try { // If we got here, it's safe to delete the backup System.IO.File.Delete(theBackup); } catch (Exception) { } } catch (Exception ex) { if (bHaveStartedProjecting) { MessageBox.Show("ProjectWorkspaceContents experienced an error and has left the transaction in a halfway state." + Environment.NewLine + "A backup file was created prior to the operation. Please delete the original file and replace it with the backup." + Environment.NewLine + "The original file: " + pgdb.FullName + Environment.NewLine + "The backup file: " + theBackup, "Projection Error", MessageBoxButtons.OK, MessageBoxIcon.Error); throw new ProjectFailedToFinishException("ProjectWorkspaceContents left Personal Geodatabase in a halfway state. Backup PGDB is '" + theBackup + "'.", ex); } else { MessageBox.Show("ProjectWorkspaceContents experienced an error and has left the transaction untouched."); throw new ProjectFailedToStartException("ProjectWorkspaceContents did not begin processing", ex); } } finally { if (theStepProgressor != null) ((IProgressDialog2)theStepProgressor).HideDialog(); theStepProgressor = null; } return theReturn; }
public static void CreateJumps(IApplication app, JumpTypes jumpType, double jumpDistance) { IProgressDialog2 progressDialog = default(IProgressDialog2); IProgressDialogFactory progressDialogFactory = null; ITrackCancel trackCancel = null; IStepProgressor stepProgressor = null; ICursor lineCursor = null; IEditor editor = null; IFeature lineFeature = null; IMxDocument mxdoc = null; IMap map = null; UID geoFeatureLayerID = null; IEnumLayer enumLayer = null; IEditLayers eLayers = null; List<IFeatureLayer> lineLayers = null; ILayer layer = null; IFeatureLayer fLayer = null; IFeatureSelection fSel = null; try { //Get editor editor = Globals.getEditor(app); if (editor.EditState != esriEditState.esriStateEditing) { MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("MustBEditg"), A4LGSharedFunctions.Localizer.GetString("GeometryToolsLbl_6")); return; } //ProgressBar progressDialogFactory = new ProgressDialogFactoryClass(); // Create a CancelTracker trackCancel = new CancelTrackerClass(); // Set the properties of the Step Progressor Int32 int32_hWnd = editor.Parent.hWnd; stepProgressor = progressDialogFactory.Create(trackCancel, int32_hWnd); stepProgressor.MinRange = 0; // stepProgressor.MaxRange = itotal stepProgressor.StepValue = 1; stepProgressor.Message = ""; stepProgressor.Hide(); // Create the ProgressDialog. This automatically displays the dialog progressDialog = (ESRI.ArcGIS.Framework.IProgressDialog2)stepProgressor; // Explict Cast // Set the properties of the ProgressDialog progressDialog.CancelEnabled = false; progressDialog.Description = A4LGSharedFunctions.Localizer.GetString("GeometryToolsProc_12") +"..."; progressDialog.Title = A4LGSharedFunctions.Localizer.GetString("GeometryToolsProc_12"); progressDialog.Animation = ESRI.ArcGIS.Framework.esriProgressAnimationTypes.esriProgressGlobe; mxdoc = (IMxDocument)app.Document; map = editor.Map; //Get enumeration of feature layers geoFeatureLayerID = new UIDClass(); geoFeatureLayerID.Value = "{E156D7E5-22AF-11D3-9F99-00C04F6BC78E}"; enumLayer = map.get_Layers(((ESRI.ArcGIS.esriSystem.UID)geoFeatureLayerID), true); //Get enumeration of editable layers eLayers = (IEditLayers)editor; // Create list of visible line layers with selected feature(s) lineLayers = new List<IFeatureLayer>(); enumLayer.Reset(); layer = enumLayer.Next(); while (layer != null) { fLayer = (IFeatureLayer)layer; stepProgressor.Message = A4LGSharedFunctions.Localizer.GetString("GeometryToolsMess_2") + fLayer.Name; if (fLayer.Valid && (fLayer.FeatureClass.ShapeType == ESRI.ArcGIS.Geometry.esriGeometryType.esriGeometryPolyline) && (fLayer.Visible)) { if (eLayers.IsEditable(fLayer)) { fSel = fLayer as IFeatureSelection; if (fSel.SelectionSet.Count > 0) { stepProgressor.Message = A4LGSharedFunctions.Localizer.GetString("GeometryToolsMess_3") + fLayer.Name; lineLayers.Add(fLayer); } } } layer = enumLayer.Next(); } if (lineLayers.Count == 0) { MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("GeometryToolsError_7")); return; } // Create an edit operation enabling undo/redo editor.StartOperation(); IPointCollection linePointCollection = null; ISpatialFilter spatialFilter = null; IFeatureCursor featureCursor = null; IFeature crossFeature = null; ITopologicalOperator topologicalOP = null; ITopologicalOperator topologicalOP2 = null; IPointCollection intersectPointCollection = null; IPoint intersectPoint = null; IPoint outPoint = null; IPoint beginPoint = null; IPoint endPoint = null; IActiveView activeView = null; IInvalidArea invalid = null; IEnvelope ext = null; ISegmentCollection testSegmentColl = null; ISegment testSegment = null; ISegmentCollection segmentColl = null; ISegmentCollection segmentCollNew = null; IConstructCircularArc constructCircArc = null; ISegment curveSegment = null; //IProximityOperator proximityOP = null; IPolycurve3 selCurve = null; IPolycurve3 selCurveB = null; IPolycurve3 crossCurve = null; IPolycurve3 crossCurveB = null; IPolycurve3 testSelCurve = null; IPolycurve3 testSelCurveB = null; object _missing = null; IFeatureSelection lineSel = null; ISelectionSet2 sel = null; IZAware pZAware = null; ISegmentCollection testSegmentColl2 = null; ISegment testSegment2 = null; IGeometryDef pGeometryDefTest = null; IFields pFieldsTest = null; IField pFieldTest = null; IGeoDataset pDS = null; try { activeView = map as IActiveView; invalid = new InvalidAreaClass(); invalid.Display = editor.Display; linePointCollection = (IPointCollection)new PolylineClass(); spatialFilter = new SpatialFilterClass(); intersectPoint = new PointClass(); outPoint = new PointClass(); //used for curve test on cross feature bool testProjectOnto; bool testCreatePart; bool testSplitHappened; int testNewPartIndex; int testNewSegmentIndex; //used for curve test on selected feature bool testProjectOnto2; bool testCreatePart2; bool testSplitHappened2; int testNewPartIndex2; int testNewSegmentIndex2; //ICurve lineCurve; double totalDistance; double distAlongCurve = 0; double distFromCurve = 0; bool boolRightSide = false; //test the amount of needed space for the inserted curve double remainderDistance = 0; double pointDistance = 0; bool projectOnto; bool createPart; bool splitHappenedBefore; bool splitHappenedAfter; int newPartIndexBegin; int newSegmentIndexBegin; int newPartIndexEnd; int newSegmentIndexEnd; _missing = Type.Missing; // Step through all line layers with selection sets foreach (IFeatureLayer lineLayer in lineLayers) { stepProgressor.Message = A4LGSharedFunctions.Localizer.GetString("GeometryToolsMess_4a") + lineLayer.Name; // Get cursor of selected lines lineSel = (IFeatureSelection)lineLayer; sel = lineSel.SelectionSet as ISelectionSet2; sel.Search(null, false, out lineCursor); // Process each selected line int idx = 0; while ((lineFeature = (IFeature)lineCursor.NextRow()) != null) { idx++; stepProgressor.Message = A4LGSharedFunctions.Localizer.GetString("GeometryToolsMess_4b") + idx + A4LGSharedFunctions.Localizer.GetString("GeometryToolsMess_4c") + lineLayer.Name; if (lineFeature.Shape.GeometryType == esriGeometryType.esriGeometryPolyline) { selCurve = (IPolycurve3)lineFeature.ShapeCopy; pZAware = selCurve as IZAware; if (pZAware.ZAware) { pZAware.ZAware = false; } // Get cursor of crossing features spatialFilter.Geometry = selCurve; spatialFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelCrosses; featureCursor = lineLayer.Search(spatialFilter, false); // Process each crossing feature while ((crossFeature = (IFeature)featureCursor.NextFeature()) != null) { topologicalOP = (ITopologicalOperator)crossFeature.Shape; //topologicalOP2 = (ITopologicalOperator)polylinePointCollection; topologicalOP2 = (ITopologicalOperator)selCurve; topologicalOP2.Simplify(); topologicalOP.Simplify(); intersectPointCollection = (IPointCollection)topologicalOP.Intersect((IGeometry)selCurve, esriGeometryDimension.esriGeometry0Dimension); for (int i = 0; i < intersectPointCollection.PointCount; i++) { intersectPoint = intersectPointCollection.get_Point(i); //Determine if the crossing segement is an arc. //Continue if it is not. testProjectOnto = true; testCreatePart = false; crossCurve = (IPolycurve3)crossFeature.ShapeCopy; crossCurve.SplitAtPoint(intersectPoint, testProjectOnto, testCreatePart, out testSplitHappened, out testNewPartIndex, out testNewSegmentIndex); crossCurveB = (IPolycurve3)crossFeature.ShapeCopy; testSegmentColl = crossCurveB as ISegmentCollection; testSegment = testSegmentColl.get_Segment(testNewSegmentIndex - 1); if (testSegment.GeometryType != esriGeometryType.esriGeometryCircularArc) { //Determine if the current location of the selected line is an arc. //Continue if it is not. testProjectOnto2 = true; testCreatePart2 = false; testSelCurve = (IPolycurve3)lineFeature.ShapeCopy; testSelCurve.SplitAtPoint(intersectPoint, testProjectOnto2, testCreatePart2, out testSplitHappened2, out testNewPartIndex2, out testNewSegmentIndex2); testSelCurveB = (IPolycurve3)lineFeature.ShapeCopy; testSegmentColl2 = testSelCurveB as ISegmentCollection; testSegment2 = testSegmentColl2.get_Segment(testNewSegmentIndex2 - 1); if (testSegment2.GeometryType != esriGeometryType.esriGeometryCircularArc) { //Find distance along the original selected line //focusPolyline = (IPolyline)lineFeature.ShapeCopy; selCurveB = (IPolycurve3)lineFeature.ShapeCopy; selCurveB.QueryPointAndDistance(esriSegmentExtension.esriNoExtension, intersectPoint, false, outPoint, ref distAlongCurve, ref distFromCurve, ref boolRightSide); remainderDistance = selCurveB.Length - distAlongCurve; totalDistance = distAlongCurve + jumpDistance; //Continue if there is enough room if ((selCurveB.Length >= (jumpDistance / 2)) && (remainderDistance >= (jumpDistance / 2))) { //find the points where the curve will begin and end beginPoint = new PointClass(); endPoint = new PointClass(); selCurveB.QueryPoint(esriSegmentExtension.esriNoExtension, (distAlongCurve - (jumpDistance / 2)), false, beginPoint); selCurveB.QueryPoint(esriSegmentExtension.esriNoExtension, (distAlongCurve + (jumpDistance / 2)), false, endPoint); //split the original line at the two points (vertices for begin and end of new curve) projectOnto = true; createPart = false; selCurveB.SplitAtPoint(beginPoint, projectOnto, createPart, out splitHappenedBefore, out newPartIndexBegin, out newSegmentIndexBegin); selCurveB.SplitAtPoint(endPoint, projectOnto, createPart, out splitHappenedAfter, out newPartIndexEnd, out newSegmentIndexEnd); if ((splitHappenedBefore = true) && (splitHappenedAfter = true)) { //Create the curve segment and add it to the polyline constructCircArc = new CircularArcClass(); // proximityOP = (IProximityOperator)intersectPoint; //pointDistance = proximityOP.ReturnDistance(beginPoint); pointDistance = jumpDistance; //check for direction of line to always make the jump on top if (jumpType == JumpTypes.Over) if (endPoint.X > beginPoint.X) { try { constructCircArc.ConstructChordDistance(intersectPoint, beginPoint, false, (pointDistance)); } catch { MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("GeometryToolsError_8")); continue; } } else { try { constructCircArc.ConstructChordDistance(intersectPoint, beginPoint, true, (pointDistance)); } catch { MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("GeometryToolsError_8")); continue; } } else { if (endPoint.X <= beginPoint.X) { try { constructCircArc.ConstructChordDistance(intersectPoint, beginPoint, false, (pointDistance)); } catch { MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("GeometryToolsError_8")); continue; } } else { try { constructCircArc.ConstructChordDistance(intersectPoint, beginPoint, true, (pointDistance)); } catch { MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("GeometryToolsError_8")); continue; } } } curveSegment = constructCircArc as ISegment; if (curveSegment != null & curveSegment.Length > 0) { segmentCollNew = (ISegmentCollection)new PolylineClass(); segmentCollNew.AddSegment(curveSegment, ref _missing, ref _missing); segmentColl = (ISegmentCollection)selCurveB; segmentColl.ReplaceSegmentCollection(newSegmentIndexBegin, 1, segmentCollNew); string sShpName = lineLayer.FeatureClass.ShapeFieldName; pFieldsTest = lineLayer.FeatureClass.Fields; int lGeomIndex = pFieldsTest.FindField(sShpName); pFieldTest = pFieldsTest.get_Field(lGeomIndex); pGeometryDefTest = pFieldTest.GeometryDef; bool bZAware; bool bMAware; //Determine if M or Z aware bZAware = pGeometryDefTest.HasZ; bMAware = pGeometryDefTest.HasM; if (bZAware) { // IGeometry pGeo = new PolylineClass(); pZAware = selCurveB as IZAware; if (pZAware.ZAware) { } else { pZAware.ZAware = true; //pZAware.DropZs(); } // pZAware.DropZs(); IZ pZ = selCurveB as IZ; pZ.SetConstantZ(0); } if (bMAware) { } pDS = lineLayer.FeatureClass as IGeoDataset; selCurveB.SpatialReference = pDS.SpatialReference; lineFeature.Shape = (IGeometry)selCurveB; lineFeature.Store(); //Prepare to redraw area around feature ext = curveSegment.Envelope; ext.Expand(2, 2, true); invalid.Add(ext); } } } else { MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("GeometryToolsError_9")); } } } } } } } } } catch (Exception ex) { editor.AbortOperation(); MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("GeometryToolsLbl_6") + "\n" + ex.Message, ex.Source); } finally { // Refresh if (invalid!= null) invalid.Invalidate((short)esriScreenCache.esriAllScreenCaches); linePointCollection = null; spatialFilter = null; if (featureCursor != null) Marshal.ReleaseComObject(featureCursor); featureCursor = null; crossFeature = null; topologicalOP = null; topologicalOP2 = null; intersectPointCollection = null; intersectPoint = null; outPoint = null; beginPoint = null; endPoint = null; activeView = null; invalid = null; ext = null; testSegmentColl = null; testSegment = null; segmentColl = null; segmentCollNew = null; constructCircArc = null; curveSegment = null; //proximityOP = null; selCurve = null; selCurveB = null; crossCurve = null; crossCurveB = null; testSelCurve = null; testSelCurveB = null; _missing = null; lineSel = null; sel = null; pZAware = null; testSegmentColl2 = null; testSegment2 = null; pGeometryDefTest = null; pFieldsTest = null; pFieldTest = null; pDS = null; } // Stop the edit operation editor.StopOperation(A4LGSharedFunctions.Localizer.GetString("GeometryToolsLbl_6")); } catch (Exception ex) { MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("GeometryToolsLbl_6") + "\n" + ex.Message, ex.Source); return; } finally { if (lineCursor != null) { Marshal.ReleaseComObject(lineCursor); } // Cleanup if (progressDialog != null) { progressDialog.HideDialog(); //progressDialog = null; Marshal.ReleaseComObject(progressDialog); //progressDialogFactory = null; //Marshal.ReleaseComObject(progressDialogFactory); //trackCancel = null; //Marshal.ReleaseComObject(trackCancel); //stepProgressor = null; //Marshal.ReleaseComObject(stepProgressor); //appCursor = null; } progressDialog = null; progressDialogFactory = null; trackCancel = null; stepProgressor = null; lineCursor = null; editor = null; lineFeature = null; mxdoc = null; map = null; geoFeatureLayerID = null; enumLayer = null; eLayers = null; lineLayers = null; layer = null; fLayer = null; fSel = null; } }
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 linepoint command cannot be used when there is an open job.\r\nPlease finish or discard the open job, and try again.", "Delete Selected LinePoints"); 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 CFLinePointLayers = new ArrayClass(); if (!(FabricUTILS.GetLinePointLayersFromFabric(pMap, pCadFabric, out CFLinePointLayers))) { return; //no fabric sublayers available for the targeted fabric } bool bIsFileBasedGDB = false; bool bIsUnVersioned = false; bool bUseNonVersionedDelete = false; IWorkspace pWS = null; ITable pLinePointTable = 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)CFLinePointLayers.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 linepoint layer and //Get the selection of linepoints int iCnt = 0; int iTotalSelectionCount = 0; for (; iCnt < CFLinePointLayers.Count; iCnt++) { pFL = (IFeatureLayer)CFLinePointLayers.get_Element(iCnt); IFeatureSelection pFeatSel = (IFeatureSelection)pFL; ISelectionSet2 pSelSet = (ISelectionSet2)pFeatSel.SelectionSet; iTotalSelectionCount += pSelSet.Count; } if (iTotalSelectionCount == 0) { MessageBox.Show("Please select some line points and try again.", "No Selection", MessageBoxButtons.OK, MessageBoxIcon.Information); if (bUseNonVersionedDelete) { pCadEd.CadastralFabricLayer = null; CFLinePointLayers = 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; pStepProgressor.StepValue = 1; pProgressorDialog.Animation = ESRI.ArcGIS.Framework.esriProgressAnimationTypes.esriProgressSpiral; } //loop through each linepoint layer and //delete from its selection m_pQF = new QueryFilterClass(); iCnt = 0; for (; iCnt < CFLinePointLayers.Count; iCnt++) { pFL = (IFeatureLayer)CFLinePointLayers.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 line point data..."; } //Add the OIDs of all the selected linepoints into a new feature IDSet bool bCont = true; m_pFIDSetLinePoints = new FIDSetClass(); ICursor pCursor = null; pSelSet.Search(null, false, out pCursor);//code deletes all selected line points IFeatureCursor pLinePointFeatCurs = (IFeatureCursor)pCursor; IFeature pLinePointFeat = pLinePointFeatCurs.NextFeature(); while (pLinePointFeat != null) { //Check if the cancel button was pressed. If so, stop process if (bShowProgressor) { bCont = pTrackCancel.Continue(); if (!bCont) { break; } } bool bExists = false; m_pFIDSetLinePoints.Find(pLinePointFeat.OID, out bExists); if (!bExists) { m_pFIDSetLinePoints.Add(pLinePointFeat.OID); } Marshal.ReleaseComObject(pLinePointFeat); //garbage collection pLinePointFeat = pLinePointFeatCurs.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; } } //delete all the line point records if (bShowProgressor) { pStepProgressor.Message = "Deleting selected line points..."; } bool bSuccess = true; pLinePointTable = (ITable)pCadFabric.get_CadastralTable(esriCadastralFabricTable.esriCFTLinePoints); if (!bUseNonVersionedDelete) { bSuccess = FabricUTILS.DeleteRowsByFIDSet(pLinePointTable, m_pFIDSetLinePoints, pStepProgressor, pTrackCancel); } if (bUseNonVersionedDelete) { bSuccess = FabricUTILS.DeleteRowsUnversioned(pWS, pLinePointTable, m_pFIDSetLinePoints, pStepProgressor, pTrackCancel); } if (!bSuccess) { AbortEdits(bUseNonVersionedDelete, pEd, pWS); return; } } if (bUseNonVersionedDelete) { FabricUTILS.StopEditing(pWS); } if (pEd.EditState == esriEditState.esriStateEditing) { pEd.StopOperation("Delete Line Points"); } } catch (Exception ex) { MessageBox.Show(ex.Message); return; } finally { RefreshMap(pActiveView, CFLinePointLayers); //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; CFLinePointLayers = null; } if (pMouseCursor != null) { pMouseCursor.SetCursor(0); } } }