public void Execute(ESRI.ArcGIS.esriSystem.IArray paramvalues, ESRI.ArcGIS.esriSystem.ITrackCancel TrackCancel, ESRI.ArcGIS.Geoprocessing.IGPEnvironmentManager envMgr, ESRI.ArcGIS.Geodatabase.IGPMessages message) { try { IGPUtilities3 gpUtilities3 = new GPUtilitiesClass(); if (TrackCancel == null) { TrackCancel = new CancelTrackerClass(); } IGPParameter inputFeatureClassParameter = paramvalues.get_Element(in_osmFeaturesNumber) as IGPParameter; IGPValue inputFeatureGPValue = gpUtilities3.UnpackGPValue(inputFeatureClassParameter) as IGPValue; IFeatureClass osmFeatureClass = null; IQueryFilter queryFilter = null; gpUtilities3.DecodeFeatureLayer(inputFeatureGPValue, out osmFeatureClass, out queryFilter); ((ITable)osmFeatureClass).RemoveOSMClassExtension(); } catch (Exception ex) { message.AddError(120057, ex.Message); } }
//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); }
private void miOutput_Click(object sender, EventArgs e) { SaveFileDialog pSaveDialog = new SaveFileDialog(); pSaveDialog.FileName = ""; pSaveDialog.Filter = "JPEG图片(*.JPG)|*.jpg|TIFF图片(*.TIF)|*.tif|PDF文档(*.PDF)|*.pdf)"; if (pSaveDialog.ShowDialog() == DialogResult.OK) { double iScreenDisplayResolution = axPageLayoutControl1.ActiveView.ScreenDisplay.DisplayTransformation.Resolution; IExporter pExporter = null; if (pSaveDialog.FilterIndex == 1) { pExporter = new JpegExporterClass(); } else if (pSaveDialog.FilterIndex == 2) { pExporter = new TiffExporterClass(); } else if (pSaveDialog.FilterIndex == 3) { pExporter = new PDFExporterClass(); } pExporter.ExportFileName = pSaveDialog.FileName; pExporter.Resolution = (short)iScreenDisplayResolution; tagRECT deviceRect = axPageLayoutControl1.ActiveView.ScreenDisplay.DisplayTransformation.get_DeviceFrame(); IEnvelope pDeviceEnvelope = new EnvelopeClass(); pDeviceEnvelope.PutCoords(deviceRect.left, deviceRect.bottom, deviceRect.right, deviceRect.top); pExporter.PixelBounds = pDeviceEnvelope; ITrackCancel pCancel = new CancelTrackerClass(); axPageLayoutControl1.ActiveView.Output(pExporter.StartExporting(), pExporter.Resolution, ref deviceRect, axPageLayoutControl1.ActiveView.Extent, pCancel); Application.DoEvents(); pExporter.FinishExporting(); } }
//制图输出函数 public void OutputPhoto(string fileName) { double iScreenDispalyResolution = axPageLayoutControl1.ActiveView.ScreenDisplay.DisplayTransformation.Resolution; ESRI.ArcGIS.Output.IExport pExport = new ESRI.ArcGIS.Output.ExportPNGClass(); //设置输出文件路径及名称 pExport.ExportFileName = fileName; // 设置输出分辨率 pExport.Resolution = (short)iScreenDispalyResolution; // 获取输出范围,获取视图框架对象,进而得到视图范围 tagRECT deviceRect = axPageLayoutControl1.ActiveView.ScreenDisplay.DisplayTransformation.get_DeviceFrame(); IEnvelope pDeviceEnvelop = new EnvelopeClass(); // 设置一个边框范围 pDeviceEnvelop.PutCoords(deviceRect.left, deviceRect.bottom, deviceRect.right, deviceRect.top); // 将打印像素范围设置给输出对象 pExport.PixelBounds = pDeviceEnvelop; // 设置跟踪取消对象 ITrackCancel pCancle = new CancelTrackerClass(); // 进行视图控件的视图输出操作,设置对应参数 axPageLayoutControl1.ActiveView.Output(pExport.StartExporting(), (int)pExport.Resolution, ref deviceRect, axPageLayoutControl1.ActiveView.Extent, pCancle); Application.DoEvents(); pExport.FinishExporting(); pExport.Cleanup(); }
/// <summary> /// 出图 /// </summary> /// <param name="pActiveView"></param> /// <param name="fileName"></param> public static void ExporterMap(IActiveView pActiveView, string fileName) { IExport pExporter = new ExportJPEGClass(); //IEnvelope是指地物的外接矩形,用来表示地物图形的大体位置和形状,一般可用于检索地物,判断地物间的拓扑关系, //可以使得检索、判断的速度加快,因为有了IEnvelope,可以首先判断该外接矩形是否在检索范围内,而判断一个外接矩形是比较简单的。 IEnvelope pEnvelope = new EnvelopeClass(); // 设置跟踪取消对象 可用于取消操作 ITrackCancel pTrackCancel = new CancelTrackerClass(); tagRECT ptagRECT; ptagRECT.left = 0; ptagRECT.top = 0; ptagRECT.right = (int)pActiveView.Extent.Width; ptagRECT.bottom = (int)pActiveView.Extent.Height; // 获取输出分辨率 96 ——高清 int pResolution = (int)(pActiveView.ScreenDisplay.DisplayTransformation.Resolution); // 设置一个边框范围 pEnvelope.PutCoords(ptagRECT.left, ptagRECT.bottom, ptagRECT.right, ptagRECT.top); //出图分辨率 pExporter.Resolution = pResolution; pExporter.ExportFileName = fileName; // 将打印像素范围 设置给输出对象 pExporter.PixelBounds = pEnvelope; // 进行视图控件的视图输出操作,设置对应参数 pActiveView.Output(pExporter.StartExporting(), pResolution, ref ptagRECT, pActiveView.Extent, pTrackCancel); pExporter.FinishExporting(); //释放资源 System.Runtime.InteropServices.Marshal.ReleaseComObject(pExporter); }
//////////////////////////输出当前视图 public static void ExportWindow(AxMapControl MapCtrl) { SaveFileDialog pSaveDialog = new SaveFileDialog(); pSaveDialog.FileName = ""; pSaveDialog.Filter = "JPG图片(*.JPG)|*.jpg|tif图片(*.tif)|*.tif"; if (pSaveDialog.ShowDialog() == DialogResult.OK) { double iScreenDispalyResolution = MapCtrl.ActiveView.ScreenDisplay.DisplayTransformation.Resolution; IExporter pExporter = null; if (pSaveDialog.FilterIndex == 1) { pExporter = new JpegExporterClass(); } else if (pSaveDialog.FilterIndex == 2) { pExporter = new TiffExporterClass(); } pExporter.ExportFileName = pSaveDialog.FileName; pExporter.Resolution = (short)iScreenDispalyResolution; tagRECT deviceRect = MapCtrl.ActiveView.ScreenDisplay.DisplayTransformation.get_DeviceFrame(); IEnvelope pDeviceEnvelope = new EnvelopeClass(); pDeviceEnvelope.PutCoords(deviceRect.left, deviceRect.bottom, deviceRect.right, deviceRect.top); pExporter.PixelBounds = pDeviceEnvelope; ITrackCancel pCancle = new CancelTrackerClass(); MapCtrl.ActiveView.Output(pExporter.StartExporting(), pExporter.Resolution, ref deviceRect, MapCtrl.ActiveView.Extent, pCancle); pExporter.FinishExporting(); } }
/// <summary> /// 将地图上指定图层的标注转注记,存储在地图中 /// (保存在地图上的注记是IGraphicsLayer->IGraphicsContainer->IElement) /// </summary> /// <param name="map">执行标注转注记的地图</param> /// <param name="geoFeatureLayer">需要将标注转注记的图层(注意这些图层必须是map中的图层)</param> /// <param name="whichFeatures">标示将哪些要素生成注记的枚举(所有要素/当前范围的要素/选择的要素)</param> public static void ConvertLabelsToMapAnnotation(this IMap map, IGeoFeatureLayer[] geoFeatureLayer, esriLabelWhichFeatures whichFeatures = esriLabelWhichFeatures.esriVisibleFeatures) { IConvertLabelsToAnnotation convertLabelsToAnnotation = new ConvertLabelsToAnnotationClass(); ITrackCancel trackCancel = new CancelTrackerClass(); //设置标注转注记的参数:①地图、②注记存储位置(数据库注记/地图注记)、③哪些要素生成注记(所有要素/当前范围的要素/选择的要素) //④是否生成地位注记、⑥取消操作、⑦异常事件处理 convertLabelsToAnnotation.Initialize(map, esriAnnotationStorageType.esriMapAnnotation, whichFeatures, true, trackCancel, null); //添加要进行转换的图层 for (int i = 0; i < geoFeatureLayer.Length; i++) { convertLabelsToAnnotation.AddFeatureLayer(geoFeatureLayer[i], geoFeatureLayer[i].Name + "_Anno", null, null, false, false, false, false, true, ""); } //执行转换,生成注记 convertLabelsToAnnotation.ConvertLabels(); //隐藏标注 for (int i = 0; i < geoFeatureLayer.Length; i++) { geoFeatureLayer[i].DisplayAnnotation = false; } //刷新地图 IActiveView activeView = map as IActiveView; activeView.Refresh(); }
//导出地图 public void ExportMapToImage(AxPageLayoutControl axPageLayoutControl1) { try { SaveFileDialog saveFileDialog = new SaveFileDialog(); saveFileDialog.FileName = ""; saveFileDialog.Filter = "JPG图片(*.JPG)|*.jpg|tif图片(*.tif)|*.tif|PDF文档(*.PDF)|*.pdf"; if (saveFileDialog.ShowDialog() == DialogResult.OK) { double iScreenDispalyResolution = axPageLayoutControl1.ActiveView.ScreenDisplay. DisplayTransformation.Resolution;// 获取屏幕分辨率的值 IExporter exporter = new JpegExporterClass(); exporter.ExportFileName = saveFileDialog.FileName; exporter.Resolution = (short)iScreenDispalyResolution; //分辨率 tagRECT deviceRect = axPageLayoutControl1.ActiveView.ScreenDisplay.DisplayTransformation.get_DeviceFrame(); IEnvelope deviceEnvelope = new EnvelopeClass(); deviceEnvelope.PutCoords(deviceRect.left, deviceRect.bottom, deviceRect.right, deviceRect.top); exporter.PixelBounds = deviceEnvelope; // 输出图片的范围 ITrackCancel pCancle = new CancelTrackerClass(); //可用ESC键取消操作 axPageLayoutControl1.ActiveView.Output(exporter.StartExporting(), exporter.Resolution, ref deviceRect, axPageLayoutControl1.ActiveView.Extent, pCancle); Application.DoEvents(); exporter.FinishExporting(); } } catch (Exception Err) { MessageBox.Show(Err.Message, "输出图片", MessageBoxButtons.OK, MessageBoxIcon.Information); } }
/// <summary> /// 地图导出 /// </summary> /// <param name="pLayoutControl">布局控件</param> /// <param name="resolution">图片分辨率</param> public static void ExportMapToImage(AxPageLayoutControl pLayoutControl, short resolution) { IExport pExport = GetExport(); if (pExport == null) { return; } IActiveView activeView = pLayoutControl.ActiveView; //获取屏幕分辨率的值 double screenDispalyResolution = activeView.ScreenDisplay.DisplayTransformation.Resolution; //获取布局页面宽度和高度 IEnvelope pEnvelope = GetPageSize(pLayoutControl); //布局坐标转为屏幕坐标 tagRECT deviceRect = new tagRECT(); activeView.ScreenDisplay.DisplayTransformation.TransformRect(pEnvelope, ref deviceRect, 9); //设置输出范围坐标 deviceRect = SetDeviceRectProperty(deviceRect, resolution, screenDispalyResolution); //设置输出图片的范围 SetExportPixelBounds(pExport, deviceRect); ITrackCancel pCancle = new CancelTrackerClass(); //可用ESC键取消操作 activeView.Output(pExport.StartExporting(), resolution, ref deviceRect, pEnvelope, pCancle); Application.DoEvents(); pExport.FinishExporting(); MessageBox.Show("导出完成"); }
public void Execute(ESRI.ArcGIS.esriSystem.IArray paramvalues, ESRI.ArcGIS.esriSystem.ITrackCancel TrackCancel, ESRI.ArcGIS.Geoprocessing.IGPEnvironmentManager envMgr, ESRI.ArcGIS.Geodatabase.IGPMessages message) { try { IGPUtilities3 gpUtilities3 = new GPUtilitiesClass(); if (TrackCancel == null) { TrackCancel = new CancelTrackerClass(); } IGPParameter inputFeatureClassParameter = paramvalues.get_Element(in_osmFeaturesNumber) as IGPParameter; IGPValue inputFeatureGPValue = gpUtilities3.UnpackGPValue(inputFeatureClassParameter) as IGPValue; IFeatureClass osmFeatureClass = null; IQueryFilter queryFilter = null; gpUtilities3.DecodeFeatureLayer((IGPValue)inputFeatureGPValue, out osmFeatureClass, out queryFilter); ((ITable)osmFeatureClass).ApplyOSMClassExtension(); } catch (Exception ex) { message.AddError(120050, ex.Message); } }
/// <summary> /// 将地图上的标注转注记,生成注记图层存储在数据库中 /// (保存在数据库的注记图层是IFeatureClass/IFeatureLayer/IAnnotationLayer->IFeature as IAnnotationFeature.Annotation->IElement) /// </summary> /// <param name="map">执行标注转注记的地图</param> /// <param name="featureLinked">是否关联要素(关联要素的注记必须与其所关联的要素类存储在同一地理数据库中)</param> /// <param name="whichFeatures">标示哪些要素生成注记的枚举(所有要素/当前范围的要素/选择的要素)</param> /// <param name="outWorkspace">保存注记的工作空间</param> /// <param name="suffix">注记图层名称后缀</param> public static void ConvertLabelsToGdbAnnotationLayers(this IMap map, bool featureLinked = false, esriLabelWhichFeatures whichFeatures = esriLabelWhichFeatures.esriVisibleFeatures, IWorkspace outWorkspace = null, string suffix = "_Anno") { IConvertLabelsToAnnotation convertLabelsToAnnotation = new ConvertLabelsToAnnotationClass(); ITrackCancel pTrackCancel = new CancelTrackerClass(); //设置标注转注记的参数:①地图、②注记存储位置(数据库注记/地图注记)、③哪些要素生成注记(所有要素/当前范围的要素/选择的要素) //④是否生成地位注记、⑥取消操作、⑦异常事件处理 convertLabelsToAnnotation.Initialize(map, esriAnnotationStorageType.esriDatabaseAnnotation, whichFeatures, true, pTrackCancel, null); //添加要进行转换的图层 IGeoFeatureLayer geoFeatureLayer; for (int i = 0; i < map.LayerCount; i++) { geoFeatureLayer = map.get_Layer(i) as IGeoFeatureLayer; if (geoFeatureLayer != null) { IFeatureClass featureClass = geoFeatureLayer.FeatureClass; IDataset dataset = featureClass as IDataset; IFeatureWorkspace outFeatureWorkspace; IFeatureDataset featureDataset; if (featureLinked)//关联要素时,生成的注记必须存储在原地理数据库数据集中 { outFeatureWorkspace = dataset.Workspace as IFeatureWorkspace; featureDataset = featureClass.FeatureDataset; } else { outFeatureWorkspace = outWorkspace as IFeatureWorkspace; featureDataset = null; } convertLabelsToAnnotation.AddFeatureLayer(geoFeatureLayer, geoFeatureLayer.Name + suffix, outFeatureWorkspace, featureDataset, featureLinked, false, false, true, true, ""); } } //执行转换,生成注记 convertLabelsToAnnotation.ConvertLabels(); IEnumLayer enumLayer = convertLabelsToAnnotation.AnnoLayers; //隐藏标注 for (int i = 0; i < map.LayerCount; i++) { geoFeatureLayer = map.get_Layer(i) as IGeoFeatureLayer; geoFeatureLayer.DisplayAnnotation = false; } //添加注记图层到地图中 map.AddLayers(enumLayer, true); //刷新地图 IActiveView pActiveView = map as IActiveView; pActiveView.Refresh(); }
/// <summary> /// 创建取消操作 /// </summary> /// <returns></returns> private static ITrackCancel CreateTrackCancel() { ITrackCancel trackCancel = new CancelTrackerClass(); trackCancel.Reset(); trackCancel.CancelOnKeyPress = true; //点击ESC键时,中止转出 trackCancel.CancelOnClick = false; trackCancel.ProcessMessages = true; return(trackCancel); }
/// <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> /// 按纸张打印地图 //by yl [email protected] 2008.6.18 /// </summary> /// <param name="pActiveView"></param> /// <param name="pscale"></param> private void PrintAuto(IActiveView pActiveView) { try { IPaper pPaper = new Paper(); IPrinter pPrinter = new EmfPrinterClass(); System.Drawing.Printing.PrintDocument sysPrintDocumentDocument = new System.Drawing.Printing.PrintDocument(); pPaper.PrinterName = sysPrintDocumentDocument.PrinterSettings.PrinterName; pPrinter.Paper = pPaper; int Resolution = pPrinter.Resolution; double w, h; IEnvelope PEnvelope = pActiveView.Extent; w = PEnvelope.Width; h = PEnvelope.Height; double pw, ph;//纸张 pPrinter.QueryPaperSize(out pw, out ph); tagRECT userRECT = pActiveView.ExportFrame; userRECT.left = (int)(pPrinter.PrintableBounds.XMin * Resolution); userRECT.top = (int)(pPrinter.PrintableBounds.YMin * Resolution); if ((w / h) > (pw / ph))//以宽度来调整高度 { userRECT.right = userRECT.left + (int)(pPrinter.PrintableBounds.Width * Resolution); userRECT.bottom = userRECT.top + (int)((pPrinter.PrintableBounds.Width * Resolution) * h / w); } else { userRECT.bottom = userRECT.top + (int)(pPrinter.PrintableBounds.Height * Resolution); userRECT.right = userRECT.left + (int)(pPrinter.PrintableBounds.Height * Resolution * w / h); } IEnvelope pDriverBounds = new EnvelopeClass(); pDriverBounds.PutCoords(userRECT.left, userRECT.top, userRECT.right, userRECT.bottom); ITrackCancel pCancel = new CancelTrackerClass(); int hdc = pPrinter.StartPrinting(pDriverBounds, 0); pActiveView.Output(hdc, pPrinter.Resolution, ref userRECT, pActiveView.Extent, pCancel); pPrinter.FinishPrinting(); } catch (Exception e) { } }
private void MapSelectPrint()//拉框打印框内地图 { try { IEnvelope pEnv = new EnvelopeClass(); pEnv = axMapControl1.TrackRectangle(); SaveFileDialog exportJPGDialog = new SaveFileDialog(); exportJPGDialog.Title = "导出JPEG图像"; exportJPGDialog.Filter = "Jpeg Files(*.jpg,*.jpeg)|*.jpg,*.jpeg"; exportJPGDialog.RestoreDirectory = true; exportJPGDialog.ValidateNames = true; exportJPGDialog.OverwritePrompt = true; exportJPGDialog.DefaultExt = "jpg"; if (exportJPGDialog.ShowDialog() == DialogResult.OK) { double lScreenResolution; lScreenResolution = axMapControl1.ActiveView.ScreenDisplay.DisplayTransformation.Resolution; // lScreenResolution = axPageLayoutControl1.ActiveView.ScreenDisplay.DisplayTransformation.Resolution; IExport pExporter = new ExportJPEGClass() as IExport; //IExport pExporter = new ExportPDFClass() as IExport;//直接可以用!! pExporter.ExportFileName = exportJPGDialog.FileName; pExporter.Resolution = lScreenResolution; tagRECT deviceRECT; //用这句的话执行到底下的output()时就会出现错误:Not enough memory to create requested bitmap //MainaxMapControl.ActiveView.ScreenDisplay.DisplayTransformation.set_DeviceFrame(ref deviceRECT); deviceRECT = axMapControl1.ActiveView.ExportFrame; //////////////////////////// //deviceRECT.left = 0; //deviceRECT.top = 0; // deviceRECT.right = (int)pActiveView.Extent.Width; //deviceRECT.bottom = (int)pActiveView.Extent.Height; /////////////////////////////////// IEnvelope pDriverBounds = new EnvelopeClass(); //pDriverBounds = MainaxMapControl.ActiveView.FullExtent; pDriverBounds.PutCoords(deviceRECT.left, deviceRECT.bottom, deviceRECT.right, deviceRECT.top); pExporter.PixelBounds = pDriverBounds; ITrackCancel pCancel = new CancelTrackerClass(); axMapControl1.ActiveView.Output(pExporter.StartExporting(), (int)lScreenResolution, ref deviceRECT, pEnv, pCancel); pExporter.FinishExporting(); pExporter.Cleanup(); } } catch (Exception ex) { MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Stop); return; } }
/// <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(); }
private void ConvertLabelsToAnnotationSingleLayerMapAnno(IMap pMap, int layerIndex) { //label features by OBJECTID FEILD IGeoFeatureLayer pGeoFeatLayer; pGeoFeatLayer = pMap.Layer[layerIndex] as IGeoFeatureLayer; IAnnotateLayerPropertiesCollection pAnnotationLayerProColl = pGeoFeatLayer.AnnotationProperties; pGeoFeatLayer.DisplayAnnotation = true; IAnnotateLayerProperties pAnnoLayPro; IElementCollection pElecol1; IElementCollection pElecol2; pAnnotationLayerProColl.QueryItem(0, out pAnnoLayPro, out pElecol1, out pElecol2); ILabelEngineLayerProperties pLabelEngineLayerPro; pLabelEngineLayerPro = pAnnoLayPro as ILabelEngineLayerProperties; pLabelEngineLayerPro.Expression = "[OBJECTID]"; pAnnoLayPro.DisplayAnnotation = true; //convert to annotation IConvertLabelsToAnnotation pConvertLabelsToAnnotation = new ConvertLabelsToAnnotationClass(); ITrackCancel pTrackCancel = new CancelTrackerClass(); //Change global level options for the conversion by sending in different parameters to the next line. pConvertLabelsToAnnotation.Initialize(pMap, esriAnnotationStorageType.esriMapAnnotation, esriLabelWhichFeatures.esriVisibleFeatures, true, pTrackCancel, null); ILayer pLayer = pMap.get_Layer(layerIndex); IGeoFeatureLayer pGeoFeatureLayer = pLayer as IGeoFeatureLayer; if (pGeoFeatureLayer != null) { IFeatureClass pFeatureClass = pGeoFeatureLayer.FeatureClass; //Add the layer information to the converter object. Specify the parameters of the output annotation feature class here as well. pConvertLabelsToAnnotation.AddFeatureLayer(pGeoFeatureLayer, pGeoFeatureLayer.Name + "_Anno", null, null, false, false, false, false, false, ""); //Do the conversion. pConvertLabelsToAnnotation.ConvertLabels(); //Turn off labeling for the layer converted. pGeoFeatureLayer.DisplayAnnotation = false; //Refresh the map to update the display. IActiveView pActiveView = pMap as IActiveView; pActiveView.Refresh(); } }
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); }
public void OnMouseDown(int button, int shift, int x, int y) { pActiveView = hk.MapControl.ActiveView; hk.MapControl.Pan(); ITrackCancel pTrackCancel = new CancelTrackerClass(); pActiveView.Draw(0, pTrackCancel); if (pTrackCancel.Continue()) { //hk.StatusBar.Panels[0].Text = "地图正在绘制"; } else { //hk.StatusBar.Panels[0].Text = "地图绘制已经停止"; } pActiveView.Refresh(); }
public bool PrepareSwipe(IActiveView iactiveView_0) { if (iactiveView_0 is IMap) { IMap map = iactiveView_0 as IMap; if (map.LayerCount <= 0) { return(false); } this.int_4 = iactiveView_0.ScreenDisplay.hWnd; tagRECT deviceFrame = iactiveView_0.ScreenDisplay.DisplayTransformation.get_DeviceFrame(); int right = deviceFrame.right; int bottom = deviceFrame.bottom; if (this.bitmap_0 != null) { this.bitmap_0.Dispose(); this.graphics_0.Dispose(); this.graphics_0 = null; } this.bitmap_0 = new Bitmap(deviceFrame.right - deviceFrame.left, deviceFrame.bottom - deviceFrame.top); this.graphics_0 = Graphics.FromImage(this.bitmap_0); ITrackCancel trackCancel = new CancelTrackerClass(); IEnvelope extent = iactiveView_0.Extent; tagRECT pixelBounds = new tagRECT { bottom = bottom, left = 0, right = right, top = 0 }; ILayer currentLayer = _context.CurrentLayer; currentLayer.Visible = false; IntPtr hdc = this.graphics_0.GetHdc(); iactiveView_0.Output(hdc.ToInt32(), (int)iactiveView_0.ScreenDisplay.DisplayTransformation.Resolution, ref pixelBounds, extent, trackCancel); this.graphics_0.ReleaseHdc(hdc); currentLayer.Visible = true; currentLayer = null; return(true); } return(false); }
/// <summary> /// 将指定图层的标注转注记,生成注记图层存储在数据库中 /// (保存在数据库的注记图层是IFeatureClass/IFeatureLayer/IAnnotationLayer->IFeature as IAnnotationFeature.Annotation->IElement) /// </summary> /// <param name="map">执行标注转注记的地图</param> /// <param name="layer">执行标注转注记的图层</param> /// <param name="featureLinked">是否关联要素(关联要素的注记必须与其所关联的要素类存储在同一地理数据库中)</param> /// <param name="whichFeatures"></param> /// <parparam name="whichFeatures">标示哪些要素生成注记的枚举(所有要素/当前范围的要素/选择的要素)</parparam> public static void ConvertLabelsToGdbAnnotationSingleLayer(this IMap map, ILayer layer, bool featureLinked = false, esriLabelWhichFeatures whichFeatures = esriLabelWhichFeatures.esriVisibleFeatures) { IConvertLabelsToAnnotation convertLabelsToAnnotation = new ConvertLabelsToAnnotationClass(); ITrackCancel pTrackCancel = new CancelTrackerClass(); //设置标注转注记的参数:①地图、②注记存储位置(数据库注记/地图注记)、③哪些要素生成注记(所有要素/当前范围的要素/选择的要素) //④是否生成地位注记、⑥取消操作、⑦异常事件处理 convertLabelsToAnnotation.Initialize(map, esriAnnotationStorageType.esriDatabaseAnnotation, whichFeatures, true, pTrackCancel, null); IGeoFeatureLayer geoFeatureLayer = layer as IGeoFeatureLayer; if (geoFeatureLayer != null) { IFeatureClass featureClass = geoFeatureLayer.FeatureClass; IDataset dataset = featureClass as IDataset; IFeatureWorkspace featureWorkspace = dataset.Workspace as IFeatureWorkspace; try { convertLabelsToAnnotation.AddFeatureLayer(geoFeatureLayer, geoFeatureLayer.Name + "_Anno", featureWorkspace, featureClass.FeatureDataset, featureLinked, false, false, true, true, ""); } catch (Exception ex) { throw new Exception("标注转注记操作出错:" + ex.ToString()); } //执行转换,生成注记 convertLabelsToAnnotation.ConvertLabels(); IEnumLayer enumLayer = convertLabelsToAnnotation.AnnoLayers; //隐藏标注 geoFeatureLayer.DisplayAnnotation = false; //添加注记图层到地图中 map.AddLayers(enumLayer, true); //刷新地图 IActiveView pActiveView = map as IActiveView; pActiveView.Refresh(); } }
//输出当前地图为图片 public static string ExportImage(IActiveView pActiveView) { if (pActiveView == null) { return null; } try { SaveFileDialog pSaveFileDialog = new SaveFileDialog(); pSaveFileDialog.Filter = "JPEG(*.jpg)|*.jpg|AI(*.ai)|*.ai|BMP(*.BMP)|*.bmp|EMF(*.emf)|*.emf|GIF(*.gif)|*.gif|PDF(*.pdf)|*.pdf|PNG(*.png)|*.png|EPS(*.eps)|*.eps|SVG(*.svg)|*.svg|TIFF(*.tif)|*.tif"; pSaveFileDialog.Title = "输出地图"; pSaveFileDialog.RestoreDirectory = true; pSaveFileDialog.FilterIndex = 1; if (pSaveFileDialog.ShowDialog() != System.Windows.Forms.DialogResult.OK) { return null; } string FileName = pSaveFileDialog.FileName; IExport pExporter = null; switch (pSaveFileDialog.FilterIndex) { case 1: pExporter = new ExportJPEGClass(); break; case 2: pExporter = new ExportBMPClass(); break; case 3: pExporter = new ExportEMFClass(); break; case 4: pExporter = new ExportGIFClass(); break; case 5: pExporter = new ExportAIClass(); break; case 6: pExporter = new ExportPDFClass(); break; case 7: pExporter = new ExportPNGClass(); break; case 8: pExporter = new ExportPSClass(); break; case 9: pExporter = new ExportSVGClass(); break; case 10: pExporter = new ExportTIFFClass(); break; default: MessageBox.Show("输出格式错误"); return null; } IEnvelope pEnvelope = new EnvelopeClass(); ITrackCancel pTrackCancel = new CancelTrackerClass(); tagRECT ptagRECT; ptagRECT = pActiveView.ScreenDisplay.DisplayTransformation.get_DeviceFrame(); int pResolution = (int)(pActiveView.ScreenDisplay.DisplayTransformation.Resolution); pEnvelope.PutCoords(ptagRECT.left, ptagRECT.bottom, ptagRECT.right, ptagRECT.top); pExporter.Resolution = pResolution; pExporter.ExportFileName = FileName; pExporter.PixelBounds = pEnvelope; pActiveView.Output(pExporter.StartExporting(), pResolution, ref ptagRECT, pActiveView.Extent, pTrackCancel); pExporter.FinishExporting(); //释放资源 pSaveFileDialog.Dispose(); System.Runtime.InteropServices.Marshal.ReleaseComObject(pExporter); return FileName; } catch { return null; } }
public void Execute(ESRI.ArcGIS.esriSystem.IArray paramvalues, ESRI.ArcGIS.esriSystem.ITrackCancel TrackCancel, ESRI.ArcGIS.Geoprocessing.IGPEnvironmentManager envMgr, ESRI.ArcGIS.Geodatabase.IGPMessages message) { IGPUtilities3 gpUtilities3 = new GPUtilitiesClass(); OSMToolHelper osmToolHelper = new OSMToolHelper(); if (TrackCancel == null) { TrackCancel = new CancelTrackerClass(); } IGPEnvironment configKeyword = OSMToolHelper.getEnvironment(envMgr, "configKeyword"); IGPString gpString = configKeyword.Value as IGPString; string storageKeyword = String.Empty; if (gpString != null) { storageKeyword = gpString.Value; } IGPParameter osmFileParameter = paramvalues.get_Element(0) as IGPParameter; IGPValue osmFileLocationString = gpUtilities3.UnpackGPValue(osmFileParameter) as IGPValue; IGPParameter loadSuperRelationParameter = paramvalues.get_Element(1) as IGPParameter; IGPBoolean loadSuperRelationGPValue = gpUtilities3.UnpackGPValue(loadSuperRelationParameter) as IGPBoolean; IGPParameter osmSourceLineFeatureClassParameter = paramvalues.get_Element(2) as IGPParameter; IGPValue osmSourceLineFeatureClassGPValue = gpUtilities3.UnpackGPValue(osmSourceLineFeatureClassParameter) as IGPValue; IGPParameter osmSourcePolygonFeatureClassParameter = paramvalues.get_Element(3) as IGPParameter; IGPValue osmSourcePolygonFeatureClassGPValue = gpUtilities3.UnpackGPValue(osmSourcePolygonFeatureClassParameter) as IGPValue; IGPParameter osmTargetLineFeatureClassParameter = paramvalues.get_Element(6) as IGPParameter; IGPValue osmTargetLineFeatureClassGPValue = gpUtilities3.UnpackGPValue(osmTargetLineFeatureClassParameter) as IGPValue; IName workspaceName = gpUtilities3.CreateParentFromCatalogPath(osmTargetLineFeatureClassGPValue.GetAsText()); IWorkspace2 lineFeatureWorkspace = workspaceName.Open() as IWorkspace2; string[] lineFCNameElements = osmTargetLineFeatureClassGPValue.GetAsText().Split(System.IO.Path.DirectorySeparatorChar); IFeatureClass osmLineFeatureClass = null; IGPParameter tagLineCollectionParameter = paramvalues.get_Element(4) as IGPParameter; IGPMultiValue tagLineCollectionGPValue = gpUtilities3.UnpackGPValue(tagLineCollectionParameter) as IGPMultiValue; List<String> lineTagstoExtract = null; if (tagLineCollectionGPValue.Count > 0) { lineTagstoExtract = new List<string>(); for (int valueIndex = 0; valueIndex < tagLineCollectionGPValue.Count; valueIndex++) { string nameOfTag = tagLineCollectionGPValue.get_Value(valueIndex).GetAsText(); lineTagstoExtract.Add(nameOfTag); } } else { lineTagstoExtract = OSMToolHelper.OSMSmallFeatureClassFields(); } // lines try { osmLineFeatureClass = osmToolHelper.CreateSmallLineFeatureClass(lineFeatureWorkspace, lineFCNameElements[lineFCNameElements.Length - 1], storageKeyword, "", "", lineTagstoExtract); } catch (Exception ex) { message.AddError(120035, String.Format(resourceManager.GetString("GPTools_OSMGPDownload_nullpointfeatureclass"), ex.Message)); return; } if (osmLineFeatureClass == null) { return; } IGPParameter osmTargetPolygonFeatureClassParameter = paramvalues.get_Element(7) as IGPParameter; IGPValue osmTargetPolygonFeatureClassGPValue = gpUtilities3.UnpackGPValue(osmTargetPolygonFeatureClassParameter) as IGPValue; workspaceName = gpUtilities3.CreateParentFromCatalogPath(osmTargetPolygonFeatureClassGPValue.GetAsText()); IWorkspace2 polygonFeatureWorkspace = workspaceName.Open() as IWorkspace2; string[] polygonFCNameElements = osmTargetPolygonFeatureClassGPValue.GetAsText().Split(System.IO.Path.DirectorySeparatorChar); IFeatureClass osmPolygonFeatureClass = null; IGPParameter tagPolygonCollectionParameter = paramvalues.get_Element(5) as IGPParameter; IGPMultiValue tagPolygonCollectionGPValue = gpUtilities3.UnpackGPValue(tagPolygonCollectionParameter) as IGPMultiValue; List<String> polygonTagstoExtract = null; if (tagPolygonCollectionGPValue.Count > 0) { polygonTagstoExtract = new List<string>(); for (int valueIndex = 0; valueIndex < tagPolygonCollectionGPValue.Count; valueIndex++) { string nameOfTag = tagPolygonCollectionGPValue.get_Value(valueIndex).GetAsText(); polygonTagstoExtract.Add(nameOfTag); } } else { polygonTagstoExtract = OSMToolHelper.OSMSmallFeatureClassFields(); } // polygons try { osmPolygonFeatureClass = osmToolHelper.CreateSmallPolygonFeatureClass(polygonFeatureWorkspace, polygonFCNameElements[polygonFCNameElements.Length - 1], storageKeyword, "", "", polygonTagstoExtract); } catch (Exception ex) { message.AddError(120035, String.Format(resourceManager.GetString("GPTools_OSMGPDownload_nullpointfeatureclass"), ex.Message)); return; } if (osmPolygonFeatureClass == null) { return; } ComReleaser.ReleaseCOMObject(osmPolygonFeatureClass); ComReleaser.ReleaseCOMObject(osmLineFeatureClass); string[] gdbComponents = new string[polygonFCNameElements.Length - 1]; System.Array.Copy(lineFCNameElements, gdbComponents, lineFCNameElements.Length - 1); string fileGDBLocation = String.Join(System.IO.Path.DirectorySeparatorChar.ToString(), gdbComponents); osmToolHelper.smallLoadOSMRelations(osmFileLocationString.GetAsText(), osmSourceLineFeatureClassGPValue.GetAsText(), osmSourcePolygonFeatureClassGPValue.GetAsText(), osmTargetLineFeatureClassGPValue.GetAsText(), osmTargetPolygonFeatureClassGPValue.GetAsText(), lineTagstoExtract, polygonTagstoExtract, loadSuperRelationGPValue.Value); }
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; } }
/// <summary> /// TIN数据转栅格数据并进行坡度分析 张琪 20110614 /// </summary> /// <param name="pTinAdvanced"></param> /// <param name="pRastConvType"></param> /// <param name="sDir"></param> /// <param name="sName"></param> /// <param name="ePixelType"></param> /// <param name="cellsize"></param> /// <param name="pExtent"></param> /// <param name="bPerm"></param> /// <param name="strType"></param> /// <returns></returns> public IRasterDataset TinToRaster(ITinAdvanced pTinAdvanced, esriRasterizationType pRastConvType, String sDir, String sName, rstPixelType ePixelType, Double cellsize, IEnvelope pExtent, bool bPerm, String strType) { try { ESRI.ArcGIS.Geometry.IPoint pOrigin = pExtent.LowerLeft; pOrigin.X = pOrigin.X - (cellsize * 0.5); pOrigin.Y = pOrigin.Y - (cellsize * 0.5); int nCol, nRow; nCol = Convert.ToInt32(Math.Round(pExtent.Width / cellsize)) + 1; nRow = Convert.ToInt32(Math.Round(pExtent.Height / cellsize)) + 1; IGeoDataset pGeoDataset = pTinAdvanced as IGeoDataset; ISpatialReference2 pSpatialReference2 = pGeoDataset.SpatialReference as ISpatialReference2; IRasterDataset pRasterDataset = CreateRasterSurf(sDir, sName, strType, pOrigin, nCol, nRow, cellsize, cellsize, ePixelType, pSpatialReference2, bPerm); IRawPixels pRawPixels = GetRawPixels(pRasterDataset, 0); object pCache = pRawPixels.AcquireCache(); ITinSurface pTinSurface = pTinAdvanced as ITinSurface; IGeoDatabaseBridge2 pbridge2 = (IGeoDatabaseBridge2) new GeoDatabaseHelperClass(); IRasterProps pRasterProps = pRawPixels as IRasterProps; //float nodataFloat; //int nodataInt; double dZMin = pTinAdvanced.Extent.ZMin; object vNoData; if (ePixelType.ToString() == "PT_FLOAT") { vNoData = (dZMin - 1).ToString(); } else { vNoData = Convert.ToInt32((dZMin - 1)); } pRasterProps.NoDataValue = vNoData; IPnt pOffset = new DblPntClass(); int lMaxBlockX = 2048; if (nCol < lMaxBlockX) { lMaxBlockX = nCol; } int lMaxBlockY = 2048; if (nRow < lMaxBlockY) { lMaxBlockY = nRow; } IPnt pBlockSize = new DblPntClass(); pBlockSize.X = lMaxBlockX; pBlockSize.Y = lMaxBlockY; IPixelBlock3 pPixelBlock = pRawPixels.CreatePixelBlock(pBlockSize) as IPixelBlock3; object blockArray = pPixelBlock.get_PixelDataByRef(0); ITrackCancel pCancel = new CancelTrackerClass(); pCancel.CancelOnClick = false; pCancel.CancelOnKeyPress = true; int lBlockCount = Convert.ToInt32(Math.Round((nCol / lMaxBlockX) + 0.49) * Math.Round((nRow / lMaxBlockY) + 0.49)); ESRI.ArcGIS.Geometry.IPoint pBlockOrigin = new ESRI.ArcGIS.Geometry.PointClass(); int lColOffset, lRowOffset; for (lRowOffset = 0; lRowOffset < (nRow - 1);) { for (lColOffset = 0; lColOffset < (nCol - 1);) { if ((nCol - lColOffset) < lMaxBlockX) { pBlockSize.X = (nCol - lColOffset); pPixelBlock = pRawPixels.CreatePixelBlock(pBlockSize) as IPixelBlock3; blockArray = pPixelBlock.get_PixelDataByRef(0); } pBlockOrigin.X = pOrigin.X + (lColOffset * cellsize) + (cellsize * 0.5); pBlockOrigin.Y = pOrigin.Y + ((nRow - lRowOffset) * cellsize) - (cellsize * 0.5); pbridge2.QueryPixelBlock(pTinSurface, pBlockOrigin.X, pBlockOrigin.Y, cellsize, cellsize, pRastConvType, vNoData, ref blockArray); //pTinSurface.QueryPixelBlock(pBlockOrigin.X, pBlockOrigin.Y, cellsize, cellsize, pRastConvType, vNoData, blockArray); pOffset.X = lColOffset; pOffset.Y = lRowOffset; pPixelBlock.set_PixelData(0, (System.Object)blockArray); pRawPixels.Write(pOffset, pPixelBlock as IPixelBlock); if (lBlockCount > 1) { if (!pCancel.Continue()) { break; } else if (pTinAdvanced.ProcessCancelled) { break; } } lColOffset = lColOffset + lMaxBlockX; } bool bReset = false; if (pBlockSize.X != lMaxBlockX) { pBlockSize.X = lMaxBlockX; bReset = true; } if ((nRow - lRowOffset) < lMaxBlockY) { pBlockSize.Y = (nRow - lRowOffset); bReset = true; } if (bReset) { pPixelBlock.set_PixelData(0, blockArray); pPixelBlock = pRawPixels.CreatePixelBlock(pBlockSize) as IPixelBlock3; blockArray = pPixelBlock.get_PixelDataByRef(0); } lRowOffset = lRowOffset + lMaxBlockY; } pRawPixels.ReturnCache(pCache); pCache = null; pRawPixels = null; pPixelBlock = null; pRasterProps = null; blockArray = 0; pRasterDataset = OpenRasterDataset(sDir, sName); if (lBlockCount == 1) { pTinAdvanced.TrackCancel = null; } return(pRasterDataset); } catch { return(null); } }
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 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; } }
public void Execute(ESRI.ArcGIS.esriSystem.IArray paramvalues, ESRI.ArcGIS.esriSystem.ITrackCancel TrackCancel, ESRI.ArcGIS.Geoprocessing.IGPEnvironmentManager envMgr, ESRI.ArcGIS.Geodatabase.IGPMessages message) { IGPUtilities3 gpUtilities3 = new GPUtilitiesClass(); OSMToolHelper osmToolHelper = new OSMToolHelper(); if (TrackCancel == null) { TrackCancel = new CancelTrackerClass(); } IGPEnvironment configKeyword = OSMToolHelper.getEnvironment(envMgr, "configKeyword"); IGPString gpString = configKeyword.Value as IGPString; string storageKeyword = String.Empty; if (gpString != null) { storageKeyword = gpString.Value; } IGPParameter osmFileParameter = paramvalues.get_Element(0) as IGPParameter; IGPValue osmFileLocationString = gpUtilities3.UnpackGPValue(osmFileParameter) as IGPValue; IGPParameter loadSuperRelationParameter = paramvalues.get_Element(1) as IGPParameter; IGPBoolean loadSuperRelationGPValue = gpUtilities3.UnpackGPValue(loadSuperRelationParameter) as IGPBoolean; IGPParameter osmSourceLineFeatureClassParameter = paramvalues.get_Element(2) as IGPParameter; IGPValue osmSourceLineFeatureClassGPValue = gpUtilities3.UnpackGPValue(osmSourceLineFeatureClassParameter) as IGPValue; IGPParameter osmSourcePolygonFeatureClassParameter = paramvalues.get_Element(3) as IGPParameter; IGPValue osmSourcePolygonFeatureClassGPValue = gpUtilities3.UnpackGPValue(osmSourcePolygonFeatureClassParameter) as IGPValue; IGPParameter osmTargetLineFeatureClassParameter = paramvalues.get_Element(6) as IGPParameter; IGPValue osmTargetLineFeatureClassGPValue = gpUtilities3.UnpackGPValue(osmTargetLineFeatureClassParameter) as IGPValue; IName workspaceName = gpUtilities3.CreateParentFromCatalogPath(osmTargetLineFeatureClassGPValue.GetAsText()); IWorkspace2 lineFeatureWorkspace = workspaceName.Open() as IWorkspace2; string[] lineFCNameElements = osmTargetLineFeatureClassGPValue.GetAsText().Split(System.IO.Path.DirectorySeparatorChar); IFeatureClass osmLineFeatureClass = null; IGPParameter tagLineCollectionParameter = paramvalues.get_Element(4) as IGPParameter; IGPMultiValue tagLineCollectionGPValue = gpUtilities3.UnpackGPValue(tagLineCollectionParameter) as IGPMultiValue; List <String> lineTagstoExtract = null; if (tagLineCollectionGPValue.Count > 0) { lineTagstoExtract = new List <string>(); for (int valueIndex = 0; valueIndex < tagLineCollectionGPValue.Count; valueIndex++) { string nameOfTag = tagLineCollectionGPValue.get_Value(valueIndex).GetAsText(); lineTagstoExtract.Add(nameOfTag); } } else { lineTagstoExtract = OSMToolHelper.OSMSmallFeatureClassFields(); } // lines try { osmLineFeatureClass = osmToolHelper.CreateSmallLineFeatureClass(lineFeatureWorkspace, lineFCNameElements[lineFCNameElements.Length - 1], storageKeyword, "", "", lineTagstoExtract); } catch (Exception ex) { message.AddError(120035, String.Format(resourceManager.GetString("GPTools_OSMGPDownload_nullpointfeatureclass"), ex.Message)); return; } if (osmLineFeatureClass == null) { return; } IGPParameter osmTargetPolygonFeatureClassParameter = paramvalues.get_Element(7) as IGPParameter; IGPValue osmTargetPolygonFeatureClassGPValue = gpUtilities3.UnpackGPValue(osmTargetPolygonFeatureClassParameter) as IGPValue; workspaceName = gpUtilities3.CreateParentFromCatalogPath(osmTargetPolygonFeatureClassGPValue.GetAsText()); IWorkspace2 polygonFeatureWorkspace = workspaceName.Open() as IWorkspace2; string[] polygonFCNameElements = osmTargetPolygonFeatureClassGPValue.GetAsText().Split(System.IO.Path.DirectorySeparatorChar); IFeatureClass osmPolygonFeatureClass = null; IGPParameter tagPolygonCollectionParameter = paramvalues.get_Element(5) as IGPParameter; IGPMultiValue tagPolygonCollectionGPValue = gpUtilities3.UnpackGPValue(tagPolygonCollectionParameter) as IGPMultiValue; List <String> polygonTagstoExtract = null; if (tagPolygonCollectionGPValue.Count > 0) { polygonTagstoExtract = new List <string>(); for (int valueIndex = 0; valueIndex < tagPolygonCollectionGPValue.Count; valueIndex++) { string nameOfTag = tagPolygonCollectionGPValue.get_Value(valueIndex).GetAsText(); polygonTagstoExtract.Add(nameOfTag); } } else { polygonTagstoExtract = OSMToolHelper.OSMSmallFeatureClassFields(); } // polygons try { osmPolygonFeatureClass = osmToolHelper.CreateSmallPolygonFeatureClass(polygonFeatureWorkspace, polygonFCNameElements[polygonFCNameElements.Length - 1], storageKeyword, "", "", polygonTagstoExtract); } catch (Exception ex) { message.AddError(120035, String.Format(resourceManager.GetString("GPTools_OSMGPDownload_nullpointfeatureclass"), ex.Message)); return; } if (osmPolygonFeatureClass == null) { return; } ComReleaser.ReleaseCOMObject(osmPolygonFeatureClass); ComReleaser.ReleaseCOMObject(osmLineFeatureClass); string[] gdbComponents = new string[polygonFCNameElements.Length - 1]; System.Array.Copy(lineFCNameElements, gdbComponents, lineFCNameElements.Length - 1); string fileGDBLocation = String.Join(System.IO.Path.DirectorySeparatorChar.ToString(), gdbComponents); osmToolHelper.smallLoadOSMRelations(osmFileLocationString.GetAsText(), osmSourceLineFeatureClassGPValue.GetAsText(), osmSourcePolygonFeatureClassGPValue.GetAsText(), osmTargetLineFeatureClassGPValue.GetAsText(), osmTargetPolygonFeatureClassGPValue.GetAsText(), lineTagstoExtract, polygonTagstoExtract, loadSuperRelationGPValue.Value); }
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); }
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 void Execute(ESRI.ArcGIS.esriSystem.IArray paramvalues, ESRI.ArcGIS.esriSystem.ITrackCancel TrackCancel, ESRI.ArcGIS.Geoprocessing.IGPEnvironmentManager envMgr, ESRI.ArcGIS.Geodatabase.IGPMessages message) { try { IGPUtilities3 execute_Utilities = new GPUtilitiesClass(); if (TrackCancel == null) { TrackCancel = new CancelTrackerClass(); } IGPParameter inputOSMParameter = paramvalues.get_Element(in_osmFeatureClass) as IGPParameter; IGPValue inputOSMGPValue = execute_Utilities.UnpackGPValue(inputOSMParameter); IGPParameter tagCollectionParameter = paramvalues.get_Element(in_attributeSelector) as IGPParameter; IGPMultiValue tagCollectionGPValue = execute_Utilities.UnpackGPValue(tagCollectionParameter) as IGPMultiValue; if (tagCollectionGPValue == null) { message.AddError(120048, string.Format(resourceManager.GetString("GPTools_NullPointerParameterType"), tagCollectionParameter.Name)); return; } bool useUpdateCursor = false; IFeatureClass osmFeatureClass = null; ITable osmInputTable = null; IQueryFilter osmQueryFilter = null; try { execute_Utilities.DecodeFeatureLayer(inputOSMGPValue, out osmFeatureClass, out osmQueryFilter); if (osmFeatureClass != null) { if (osmFeatureClass.Extension is IOSMClassExtension) { useUpdateCursor = false; } else { useUpdateCursor = true; } } osmInputTable = osmFeatureClass as ITable; } catch { } try { if (osmInputTable == null) { execute_Utilities.DecodeTableView(inputOSMGPValue, out osmInputTable, out osmQueryFilter); } } catch { } if (osmInputTable == null) { string errorMessage = String.Format(resourceManager.GetString("GPTools_OSMGPAttributeSelecto_unableopentable"), inputOSMGPValue.GetAsText()); message.AddError(120053, errorMessage); return; } // find the field that holds tag binary/xml field int osmTagCollectionFieldIndex = osmInputTable.FindField("osmTags"); // if the Field doesn't exist - wasn't found (index = -1) get out if (osmTagCollectionFieldIndex == -1) { message.AddError(120005, resourceManager.GetString("GPTools_OSMGPAttributeSelector_notagfieldfound")); return; } // check if the tag collection includes the keyword "ALL", if does then we'll need to extract all tags bool extractAll = false; for (int valueIndex = 0; valueIndex < tagCollectionGPValue.Count; valueIndex++) { if (tagCollectionGPValue.get_Value(valueIndex).GetAsText().Equals("ALL")) { extractAll = true; break; } } //if (extractAll) //{ // if (osmTagKeyCodedValues == null) // extractAllTags(ref osmTagKeyCodedValues, osmInputTable, osmQueryFilter, osmTagCollectionFieldIndex, false); // if (osmTagKeyCodedValues == null) // { // message.AddAbort(resourceManager.GetString("GPTools_OSMGPAttributeSelector_Unable2RetrieveTags")); // return; // } // // empty the existing gp multivalue object // tagCollectionGPValue = new GPMultiValueClass(); // // fill the coded domain in gp multivalue object // for (int valueIndex = 0; valueIndex < osmTagKeyCodedValues.CodeCount; valueIndex++) // { // tagCollectionGPValue.AddValue(osmTagKeyCodedValues.get_Value(valueIndex)); // } //} // get an overall feature count as that determines the progress indicator int featureCount = osmInputTable.RowCount(osmQueryFilter); // set up the progress indicator IStepProgressor stepProgressor = TrackCancel as IStepProgressor; if (stepProgressor != null) { stepProgressor.MinRange = 0; stepProgressor.MaxRange = featureCount; stepProgressor.Position = 0; stepProgressor.Message = resourceManager.GetString("GPTools_OSMGPAttributeSelector_progressMessage"); stepProgressor.StepValue = 1; stepProgressor.Show(); } // let's get all the indices of the desired fields // if the field already exists get the index and if it doesn't exist create it Dictionary<string, int> tagsAttributesIndices = new Dictionary<string, int>(); Dictionary<int, int> attributeFieldLength = new Dictionary<int, int>(); IFeatureWorkspaceManage featureWorkspaceManage = ((IDataset)osmInputTable).Workspace as IFeatureWorkspaceManage; String illegalCharacters = String.Empty; ISQLSyntax sqlSyntax = ((IDataset)osmInputTable).Workspace as ISQLSyntax; if (sqlSyntax != null) { illegalCharacters = sqlSyntax.GetInvalidCharacters(); } IFieldsEdit fieldsEdit = osmInputTable.Fields as IFieldsEdit; using (SchemaLockManager lockMgr = new SchemaLockManager(osmInputTable)) { try { string tagKey = String.Empty; ESRI.ArcGIS.Geoprocessing.IGeoProcessor2 gp = new ESRI.ArcGIS.Geoprocessing.GeoProcessorClass(); // if we have explicitly defined tags to extract then go through the list of values now if (extractAll == false) { for (int valueIndex = 0; valueIndex < tagCollectionGPValue.Count; valueIndex++) { if (TrackCancel.Continue() == false) return; try { // Check if the input field already exists. string nameofTag = tagCollectionGPValue.get_Value(valueIndex).GetAsText(); tagKey = convert2AttributeFieldName(nameofTag, illegalCharacters); int fieldIndex = osmInputTable.FindField(tagKey); if (fieldIndex < 0) { // generate a new attribute field IFieldEdit fieldEdit = new FieldClass(); fieldEdit.Name_2 = tagKey; fieldEdit.AliasName_2 = nameofTag + resourceManager.GetString("GPTools_OSMGPAttributeSelector_aliasaddition"); fieldEdit.Type_2 = esriFieldType.esriFieldTypeString; fieldEdit.Length_2 = 100; osmInputTable.AddField(fieldEdit); message.AddMessage(string.Format(resourceManager.GetString("GPTools_OSMGPAttributeSelector_addField"), tagKey, nameofTag)); // re-generate the attribute index fieldIndex = osmInputTable.FindField(tagKey); } if (fieldIndex > 0) { tagsAttributesIndices.Add(nameofTag, fieldIndex); attributeFieldLength.Add(fieldIndex, osmInputTable.Fields.get_Field(fieldIndex).Length); } } catch (Exception ex) { // the key is already there, this might result because from multiple upper and lower-case combinations of the same key message.AddWarning(ex.Message + " (" + convert2OSMKey(tagKey, illegalCharacters) + ")"); } } } else { List<string> listofAllTags = extractAllTags(osmInputTable, osmQueryFilter, osmTagCollectionFieldIndex); foreach (string nameOfTag in listofAllTags) { if (TrackCancel.Continue() == false) return; try { // Check if the input field already exists. tagKey = convert2AttributeFieldName(nameOfTag, illegalCharacters); int fieldIndex = osmInputTable.FindField(tagKey); if (fieldIndex < 0) { // generate a new attribute field IFieldEdit fieldEdit = new FieldClass(); fieldEdit.Name_2 = tagKey; fieldEdit.AliasName_2 = nameOfTag + resourceManager.GetString("GPTools_OSMGPAttributeSelector_aliasaddition"); fieldEdit.Type_2 = esriFieldType.esriFieldTypeString; fieldEdit.Length_2 = 100; osmInputTable.AddField(fieldEdit); message.AddMessage(string.Format(resourceManager.GetString("GPTools_OSMGPAttributeSelector_addField"), tagKey, nameOfTag)); // re-generate the attribute index fieldIndex = osmInputTable.FindField(tagKey); } if (fieldIndex > 0) { tagsAttributesIndices.Add(nameOfTag, fieldIndex); attributeFieldLength.Add(fieldIndex, osmInputTable.Fields.get_Field(fieldIndex).Length); } } catch (Exception ex) { // the key is already there, this might result because from multiple upper and lower-case combinations of the same key message.AddWarning(ex.Message + " (" + convert2OSMKey(tagKey, illegalCharacters) + ")"); } } } } catch (Exception ex) { message.AddWarning(ex.Message); } } try { execute_Utilities.DecodeFeatureLayer(inputOSMGPValue, out osmFeatureClass, out osmQueryFilter); if (osmFeatureClass != null) { if (osmFeatureClass.Extension is IOSMClassExtension) { useUpdateCursor = false; } else { useUpdateCursor = true; } } osmInputTable = osmFeatureClass as ITable; } catch { } try { if (osmInputTable == null) { execute_Utilities.DecodeTableView(inputOSMGPValue, out osmInputTable, out osmQueryFilter); } } catch { } if (osmInputTable == null) { string errorMessage = String.Format(resourceManager.GetString("GPTools_OSMGPAttributeSelecto_unableopentable"), inputOSMGPValue.GetAsText()); message.AddError(120053, errorMessage); return; } using (ComReleaser comReleaser = new ComReleaser()) { using (SchemaLockManager lockMgr = new SchemaLockManager(osmInputTable)) { // get an update cursor for all the features to process ICursor rowCursor = null; if (useUpdateCursor) { rowCursor = osmInputTable.Update(osmQueryFilter, false); } else { rowCursor = osmInputTable.Search(osmQueryFilter, false); } comReleaser.ManageLifetime(rowCursor); IRow osmRow = null; Dictionary<string, string> tagKeys = new Dictionary<string, string>(); int progessIndex = 0; #if DEBUG message.AddMessage("useUpdateCursor: " + useUpdateCursor.ToString()); #endif // as long as there are features.... while ((osmRow = rowCursor.NextRow()) != null) { // retrieve the tags of the current feature tag[] storedTags = _osmUtility.retrieveOSMTags(osmRow, osmTagCollectionFieldIndex, ((IDataset)osmInputTable).Workspace); bool rowChanged = false; if (storedTags != null) { foreach (tag tagItem in storedTags) { // Check for matching values so we only change a minimum number of rows if (tagsAttributesIndices.ContainsKey(tagItem.k)) { int fieldIndex = tagsAttributesIndices[tagItem.k]; //...then stored the value in the attribute field // ensure that the content of the tag actually does fit into the field length...otherwise do truncate it string tagValue = tagItem.v; int fieldLength = attributeFieldLength[fieldIndex]; if (tagValue.Length > fieldLength) tagValue = tagValue.Substring(0, fieldLength); osmRow.set_Value(fieldIndex, tagValue); rowChanged = true; } else { #if DEBUG //message.AddWarning(tagItem.k); #endif } } } storedTags = null; try { if (rowChanged) { if (useUpdateCursor) { rowCursor.UpdateRow(osmRow); } else { // update the feature through the cursor osmRow.Store(); } } progessIndex++; } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.Message); message.AddWarning(ex.Message); } if (osmRow != null) { Marshal.ReleaseComObject(osmRow); } if (stepProgressor != null) { // update the progress UI stepProgressor.Position = progessIndex; } // check for user cancellation (every 100 rows) if ((progessIndex % 100 == 0) && (TrackCancel.Continue() == false)) { return; } } if (stepProgressor != null) { stepProgressor.Hide(); } } } execute_Utilities.ReleaseInternals(); Marshal.ReleaseComObject(execute_Utilities); } catch (Exception ex) { message.AddError(120054, ex.Message); } }
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); } }
/// <summary> /// Exports the map extent. /// </summary> /// <param name="activeView">The active view.</param> /// <param name="outRect">The out rect.</param> /// <param name="sOutputPath">The output file path.</param> /// <param name="dResolution">The d resolution.</param> /// <returns><c>true</c> if succeed, <c>false</c> otherwise.</returns> public bool ExportMapExtent(IActiveView activeView, Size outRect, string sOutputPath, double dResolution) { bool result; try { if (activeView == null) { result = false; } else { IExport export = null; if (sOutputPath.EndsWith(".jpg")) { export = new ExportJPEGClass(); } else if (sOutputPath.EndsWith(".tif")) { export = new ExportTIFFClass(); } else if (sOutputPath.EndsWith(".bmp")) { export = new ExportBMPClass(); } else if (sOutputPath.EndsWith(".emf")) { export = new ExportEMFClass(); } else if (sOutputPath.EndsWith(".png")) { export = new ExportPNGClass(); } else if (sOutputPath.EndsWith(".gif")) { export = new ExportGIFClass(); } export.ExportFileName = sOutputPath; IEnvelope extent = activeView.Extent; export.Resolution = dResolution; tagRECT tagRECT = default(tagRECT); tagRECT.left = (tagRECT.top = 0); tagRECT.right = outRect.Width; tagRECT.bottom = (int)((double)tagRECT.right * extent.Height / extent.Width); IEnvelope envelope = new EnvelopeClass(); envelope.PutCoords((double)tagRECT.left, (double)tagRECT.top, (double)tagRECT.right, (double)tagRECT.bottom); export.PixelBounds = envelope; ITrackCancel trackCancel = new CancelTrackerClass(); export.TrackCancel = trackCancel; trackCancel.Reset(); trackCancel.CancelOnKeyPress = true; trackCancel.CancelOnClick = false; trackCancel.ProcessMessages = true; int hDC = export.StartExporting(); activeView.Output(hDC, (int)((short)export.Resolution), ref tagRECT, extent, trackCancel); bool flag = trackCancel.Continue(); if (flag) { export.FinishExporting(); export.Cleanup(); } else { export.Cleanup(); } flag = trackCancel.Continue(); result = true; } } catch (Exception ex) { string message = ex.Message; result = false; } return(result); }
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; } }
public void Execute(ESRI.ArcGIS.esriSystem.IArray paramvalues, ESRI.ArcGIS.esriSystem.ITrackCancel TrackCancel, ESRI.ArcGIS.Geoprocessing.IGPEnvironmentManager envMgr, ESRI.ArcGIS.Geodatabase.IGPMessages message) { try { IGPUtilities3 gpUtilities3 = new GPUtilitiesClass(); if (TrackCancel == null) { TrackCancel = new CancelTrackerClass(); } IGPValue inputLayersGPValue = gpUtilities3.UnpackGPValue(paramvalues.get_Element(in_LayersNumber)); IGPMultiValue inputLayersMultiValue = gpUtilities3.UnpackGPValue(inputLayersGPValue) as IGPMultiValue; IGPParameter outputGroupLayerParameter = paramvalues.get_Element(out_groupLayerNumber) as IGPParameter; IGPValue outputGPGroupLayer = gpUtilities3.UnpackGPValue(outputGroupLayerParameter); IGPCompositeLayer outputCompositeLayer = outputGPGroupLayer as IGPCompositeLayer; if (outputCompositeLayer == null) { message.AddError(120048, string.Format(resourceManager.GetString("GPTools_NullPointerParameterType"), outputGroupLayerParameter.Name)); return; } IGroupLayer groupLayer = null; // find the last position of the "\" string // in case we find such a thing, i.e. position is >= -1 then let's assume that we are dealing with a layer file on disk // otherwise let's create a new group layer instance string outputGPLayerNameAsString = outputGPGroupLayer.GetAsText(); int separatorPosition = outputGPLayerNameAsString.LastIndexOf(System.IO.Path.DirectorySeparatorChar); string layerName = String.Empty; if (separatorPosition > -1) { layerName = outputGPGroupLayer.GetAsText().Substring(separatorPosition + 1); } else { layerName = outputGPGroupLayer.GetAsText(); } ILayer foundLayer = null; IGPLayer existingGPLayer = gpUtilities3.FindMapLayer2(layerName, out foundLayer); if (foundLayer != null) { gpUtilities3.RemoveFromMapEx((IGPValue)existingGPLayer); gpUtilities3.RemoveInternalLayerEx(foundLayer); } groupLayer = new GroupLayer(); ((ILayer)groupLayer).Name = layerName; for (int layerIndex = 0; layerIndex < inputLayersMultiValue.Count; layerIndex++) { IGPValue gpLayerToAdd = inputLayersMultiValue.get_Value(layerIndex) as IGPValue; ILayer sourceLayer = gpUtilities3.DecodeLayer(gpLayerToAdd); groupLayer.Add(sourceLayer); } outputGPGroupLayer = gpUtilities3.MakeGPValueFromObject(groupLayer); if (separatorPosition > -1) { try { // in the case that we are dealing with a layer file on disk // let's persist the group layer information into the file ILayerFile pointLayerFile = new LayerFileClass(); if (System.IO.Path.GetExtension(outputGPLayerNameAsString).ToUpper().Equals(".LYR")) { if (pointLayerFile.get_IsPresent(outputGPLayerNameAsString)) { try { gpUtilities3.Delete(outputGPGroupLayer); } catch (Exception ex) { message.AddError(120001, ex.Message); return; } } pointLayerFile.New(outputGPLayerNameAsString); pointLayerFile.ReplaceContents(groupLayer); pointLayerFile.Save(); } outputGPGroupLayer = gpUtilities3.MakeGPValueFromObject(pointLayerFile.Layer); } catch (Exception ex) { message.AddError(120002, ex.Message); return; } } gpUtilities3.PackGPValue(outputGPGroupLayer, outputGroupLayerParameter); } catch (Exception ex) { message.AddError(120049, ex.Message); } }
//输出当前地图至指定的文件 public static void ExportActiveView(IActiveView pView, Size outRect, string outPath) { try { //参数检查 if (pView == null) { throw new Exception("输入参数错误,无法生成图片文件!"); } //根据给定的文件扩展名,来决定生成不同类型的对象 ESRI.ArcGIS.Output.IExport export = null; if (outPath.EndsWith(".jpg", StringComparison.OrdinalIgnoreCase)) { export = new ESRI.ArcGIS.Output.ExportJPEGClass(); } else if (outPath.EndsWith(".tiff", StringComparison.OrdinalIgnoreCase)) { export = new ESRI.ArcGIS.Output.ExportTIFFClass(); } else if (outPath.EndsWith(".bmp", StringComparison.OrdinalIgnoreCase)) { export = new ESRI.ArcGIS.Output.ExportBMPClass(); } else if (outPath.EndsWith(".emf", StringComparison.OrdinalIgnoreCase)) { export = new ESRI.ArcGIS.Output.ExportEMFClass(); } else if (outPath.EndsWith(".png", StringComparison.OrdinalIgnoreCase)) { export = new ESRI.ArcGIS.Output.ExportPNGClass(); } else if (outPath.EndsWith(".gif", StringComparison.OrdinalIgnoreCase)) { export = new ESRI.ArcGIS.Output.ExportGIFClass(); } SetOutputQuality(pView, 1); export.ExportFileName = outPath; IEnvelope pEnvelope = pView.Extent; //导出参数 export.Resolution = 300; tagRECT exportRect = new tagRECT(); exportRect.left = exportRect.top = 0; exportRect.right = outRect.Width; exportRect.bottom = (int)(exportRect.right * pEnvelope.Height / pEnvelope.Width); ESRI.ArcGIS.Geometry.IEnvelope envelope = new ESRI.ArcGIS.Geometry.EnvelopeClass(); //输出范围 envelope.PutCoords(exportRect.left, exportRect.top, exportRect.right, exportRect.bottom); export.PixelBounds = envelope; //可用于取消操作 ITrackCancel pCancel = new CancelTrackerClass(); export.TrackCancel = pCancel; pCancel.Reset(); //点击ESC键时,中止转出 pCancel.CancelOnKeyPress = true; pCancel.CancelOnClick = false; pCancel.ProcessMessages = true; //获取handle System.Int32 hDC = export.StartExporting(); //开始转出 pView.Output(hDC, (System.Int32)export.Resolution, ref exportRect, pEnvelope, pCancel); bool bContinue = pCancel.Continue(); //捕获是否继续 if (bContinue) { export.FinishExporting(); export.Cleanup(); } else { export.Cleanup(); } bContinue = pCancel.Continue(); } catch (Exception e) { //错误信息提示 } }
/** * 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 void Execute(ESRI.ArcGIS.esriSystem.IArray paramvalues, ESRI.ArcGIS.esriSystem.ITrackCancel TrackCancel, ESRI.ArcGIS.Geoprocessing.IGPEnvironmentManager envMgr, ESRI.ArcGIS.Geodatabase.IGPMessages message) { IFeatureClass osmPointFeatureClass = null; IFeatureClass osmLineFeatureClass = null; IFeatureClass osmPolygonFeatureClass = null; OSMToolHelper osmToolHelper = null; try { DateTime syncTime = DateTime.Now; IGPUtilities3 gpUtilities3 = new GPUtilitiesClass(); osmToolHelper = new OSMToolHelper(); if (TrackCancel == null) { TrackCancel = new CancelTrackerClass(); } IGPParameter osmFileParameter = paramvalues.get_Element(in_osmFileNumber) as IGPParameter; IGPValue osmFileLocationString = gpUtilities3.UnpackGPValue(osmFileParameter) as IGPValue; // ensure that the specified file does exist bool osmFileExists = false; try { osmFileExists = System.IO.File.Exists(osmFileLocationString.GetAsText()); } catch (Exception ex) { message.AddError(120029, String.Format(resourceManager.GetString("GPTools_OSMGPFileReader_problemaccessingfile"), ex.Message)); return; } if (osmFileExists == false) { message.AddError(120030, String.Format(resourceManager.GetString("GPTools_OSMGPFileReader_osmfiledoesnotexist"), osmFileLocationString.GetAsText())); return; } IGPParameter conserveMemoryParameter = paramvalues.get_Element(in_conserveMemoryNumber) as IGPParameter; IGPBoolean conserveMemoryGPValue = gpUtilities3.UnpackGPValue(conserveMemoryParameter) as IGPBoolean; if (conserveMemoryGPValue == null) { message.AddError(120031, string.Format(resourceManager.GetString("GPTools_NullPointerParameterType"), conserveMemoryParameter.Name)); return; } message.AddMessage(resourceManager.GetString("GPTools_OSMGPFileReader_countingNodes")); long nodeCapacity = 0; long wayCapacity = 0; long relationCapacity = 0; Dictionary<esriGeometryType, List<string>> attributeTags = new Dictionary<esriGeometryType, List<string>>(); IGPParameter tagCollectionParameter = paramvalues.get_Element(in_attributeSelector) as IGPParameter; IGPMultiValue tagCollectionGPValue = gpUtilities3.UnpackGPValue(tagCollectionParameter) as IGPMultiValue; List<String> tagstoExtract = null; if (tagCollectionGPValue.Count > 0) { tagstoExtract = new List<string>(); for (int valueIndex = 0; valueIndex < tagCollectionGPValue.Count; valueIndex++) { string nameOfTag = tagCollectionGPValue.get_Value(valueIndex).GetAsText(); if (nameOfTag.ToUpper().Equals("ALL")) { tagstoExtract = new List<string>(); break; } else { tagstoExtract.Add(nameOfTag); } } } // if there is an "ALL" keyword then we scan for all tags, otherwise we only add the desired tags to the feature classes and do a 'quick' // count scan if (tagstoExtract != null) { if (tagstoExtract.Count > 0) { // if the number of tags is > 0 then do a simple feature count and take name tags names from the gp value osmToolHelper.countOSMStuff(osmFileLocationString.GetAsText(), ref nodeCapacity, ref wayCapacity, ref relationCapacity, ref TrackCancel); attributeTags.Add(esriGeometryType.esriGeometryPoint, tagstoExtract); attributeTags.Add(esriGeometryType.esriGeometryPolyline, tagstoExtract); attributeTags.Add(esriGeometryType.esriGeometryPolygon, tagstoExtract); } else { // the count should be zero if we encountered the "ALL" keyword // in this case count the features and create a list of unique tags attributeTags = osmToolHelper.countOSMCapacityAndTags(osmFileLocationString.GetAsText(), ref nodeCapacity, ref wayCapacity, ref relationCapacity, ref TrackCancel); } } else { // no tags we defined, hence we do a simple count and create an empty list indicating that no additional fields // need to be created osmToolHelper.countOSMStuff(osmFileLocationString.GetAsText(), ref nodeCapacity, ref wayCapacity, ref relationCapacity, ref TrackCancel); attributeTags.Add(esriGeometryType.esriGeometryPoint, new List<string>()); attributeTags.Add(esriGeometryType.esriGeometryPolyline, new List<string>()); attributeTags.Add(esriGeometryType.esriGeometryPolygon, new List<string>()); } if (nodeCapacity == 0 && wayCapacity == 0 && relationCapacity == 0) { return; } if (conserveMemoryGPValue.Value == false) { osmNodeDictionary = new Dictionary<string, OSMToolHelper.simplePointRef>(Convert.ToInt32(nodeCapacity)); } message.AddMessage(String.Format(resourceManager.GetString("GPTools_OSMGPFileReader_countedElements"), nodeCapacity, wayCapacity, relationCapacity)); // prepare the feature dataset and classes IGPParameter targetDatasetParameter = paramvalues.get_Element(out_targetDatasetNumber) as IGPParameter; IGPValue targetDatasetGPValue = gpUtilities3.UnpackGPValue(targetDatasetParameter); IDEDataset2 targetDEDataset2 = targetDatasetGPValue as IDEDataset2; if (targetDEDataset2 == null) { message.AddError(120048, string.Format(resourceManager.GetString("GPTools_NullPointerParameterType"), targetDatasetParameter.Name)); return; } string targetDatasetName = ((IGPValue)targetDEDataset2).GetAsText(); IDataElement targetDataElement = targetDEDataset2 as IDataElement; IDataset targetDataset = gpUtilities3.OpenDatasetFromLocation(targetDataElement.CatalogPath); IName parentName = null; try { parentName = gpUtilities3.CreateParentFromCatalogPath(targetDataElement.CatalogPath); } catch { message.AddError(120033, resourceManager.GetString("GPTools_OSMGPFileReader_unable_to_create_fd")); return; } // test if the feature classes already exists, // if they do and the environments settings are such that an overwrite is not allowed we need to abort at this point IGeoProcessorSettings gpSettings = (IGeoProcessorSettings)envMgr; if (gpSettings.OverwriteOutput == true) { } else { if (gpUtilities3.Exists((IGPValue)targetDEDataset2) == true) { message.AddError(120032, String.Format(resourceManager.GetString("GPTools_OSMGPFileReader_basenamealreadyexists"), targetDataElement.Name)); return; } } // load the descriptions from which to derive the domain values OSMDomains availableDomains = null; // Reading the XML document requires a FileStream. System.Xml.XmlTextReader reader = null; string xmlDomainFile = ""; m_editorConfigurationSettings.TryGetValue("osmdomainsfilepath", out xmlDomainFile); if (System.IO.File.Exists(xmlDomainFile)) { reader = new System.Xml.XmlTextReader(xmlDomainFile); } if (reader == null) { message.AddError(120033, resourceManager.GetString("GPTools_OSMGPDownload_NoDomainConfigFile")); return; } System.Xml.Serialization.XmlSerializer domainSerializer = null; try { domainSerializer = new XmlSerializer(typeof(OSMDomains)); availableDomains = domainSerializer.Deserialize(reader) as OSMDomains; } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.Message); System.Diagnostics.Debug.WriteLine(ex.StackTrace); message.AddError(120034, ex.Message); return; } reader.Close(); message.AddMessage(resourceManager.GetString("GPTools_preparedb")); Dictionary<string, IDomain> codedValueDomains = new Dictionary<string, IDomain>(); foreach (var domain in availableDomains.domain) { ICodedValueDomain pointCodedValueDomain = new CodedValueDomainClass(); ((IDomain)pointCodedValueDomain).Name = domain.name + "_pt"; ((IDomain)pointCodedValueDomain).FieldType = esriFieldType.esriFieldTypeString; ICodedValueDomain lineCodedValueDomain = new CodedValueDomainClass(); ((IDomain)lineCodedValueDomain).Name = domain.name + "_ln"; ((IDomain)lineCodedValueDomain).FieldType = esriFieldType.esriFieldTypeString; ICodedValueDomain polygonCodedValueDomain = new CodedValueDomainClass(); ((IDomain)polygonCodedValueDomain).Name = domain.name + "_ply"; ((IDomain)polygonCodedValueDomain).FieldType = esriFieldType.esriFieldTypeString; for (int i = 0; i < domain.domainvalue.Length; i++) { for (int domainGeometryIndex = 0; domainGeometryIndex < domain.domainvalue[i].geometrytype.Length; domainGeometryIndex++) { switch (domain.domainvalue[i].geometrytype[domainGeometryIndex]) { case geometrytype.point: pointCodedValueDomain.AddCode(domain.domainvalue[i].value, domain.domainvalue[i].value); break; case geometrytype.line: lineCodedValueDomain.AddCode(domain.domainvalue[i].value, domain.domainvalue[i].value); break; case geometrytype.polygon: polygonCodedValueDomain.AddCode(domain.domainvalue[i].value, domain.domainvalue[i].value); break; default: break; } } } // add the domain tables to the domains collection codedValueDomains.Add(((IDomain)pointCodedValueDomain).Name, (IDomain)pointCodedValueDomain); codedValueDomains.Add(((IDomain)lineCodedValueDomain).Name, (IDomain)lineCodedValueDomain); codedValueDomains.Add(((IDomain)polygonCodedValueDomain).Name, (IDomain)polygonCodedValueDomain); } IWorkspaceDomains workspaceDomain = null; IFeatureWorkspace featureWorkspace = null; // if the target dataset already exists we can go ahead and QI to it directly if (targetDataset != null) { workspaceDomain = targetDataset.Workspace as IWorkspaceDomains; featureWorkspace = targetDataset.Workspace as IFeatureWorkspace; } else { // in case it doesn't exist yet we will open the parent (the workspace - geodatabase- itself) and // use it as a reference to create the feature dataset and the feature classes in it. IWorkspace newWorkspace = ((IName)parentName).Open() as IWorkspace; workspaceDomain = newWorkspace as IWorkspaceDomains; featureWorkspace = newWorkspace as IFeatureWorkspace; } foreach (var domain in codedValueDomains.Values) { IDomain testDomain = null; try { testDomain = workspaceDomain.get_DomainByName(domain.Name); } catch { } if (testDomain == null) { workspaceDomain.AddDomain(domain); } } // this determines the spatial reference as defined from the gp environment settings and the initial wgs84 SR ISpatialReferenceFactory spatialReferenceFactory = new SpatialReferenceEnvironmentClass() as ISpatialReferenceFactory; ISpatialReference wgs84 = spatialReferenceFactory.CreateGeographicCoordinateSystem((int)esriSRGeoCSType.esriSRGeoCS_WGS1984) as ISpatialReference; ISpatialReference downloadSpatialReference = gpUtilities3.GetGPSpRefEnv(envMgr, wgs84, null, 0, 0, 0, 0, null); Marshal.ReleaseComObject(wgs84); Marshal.ReleaseComObject(spatialReferenceFactory); IGPEnvironment configKeyword = OSMGPDownload.getEnvironment(envMgr, "configKeyword"); IGPString gpString = configKeyword.Value as IGPString; string storageKeyword = String.Empty; if (gpString != null) { storageKeyword = gpString.Value; } IFeatureDataset targetFeatureDataset = null; if (gpUtilities3.Exists((IGPValue)targetDEDataset2)) { targetFeatureDataset = gpUtilities3.OpenDataset((IGPValue)targetDEDataset2) as IFeatureDataset; } else { targetFeatureDataset = featureWorkspace.CreateFeatureDataset(targetDataElement.Name, downloadSpatialReference); } downloadSpatialReference = ((IGeoDataset)targetFeatureDataset).SpatialReference; string metadataAbstract = resourceManager.GetString("GPTools_OSMGPFileReader_metadata_abstract"); string metadataPurpose = resourceManager.GetString("GPTools_OSMGPFileReader_metadata_purpose"); // assign the custom class extension for use with the OSM feature inspector UID osmClassUID = new UIDClass(); osmClassUID.Value = "{65CA4847-8661-45eb-8E1E-B2985CA17C78}"; // points try { osmPointFeatureClass = osmToolHelper.CreatePointFeatureClass((IWorkspace2)featureWorkspace, targetFeatureDataset, targetDataElement.Name + "_osm_pt", null, null, null, storageKeyword, availableDomains, metadataAbstract, metadataPurpose, attributeTags[esriGeometryType.esriGeometryPoint]); } catch (Exception ex) { message.AddError(120035, String.Format(resourceManager.GetString("GPTools_OSMGPDownload_nullpointfeatureclass"), ex.Message)); return; } if (osmPointFeatureClass == null) { return; } // change the property set of the osm class extension to skip any change detection during the initial data load osmPointFeatureClass.RemoveOSMClassExtension(); int osmPointIDFieldIndex = osmPointFeatureClass.FindField("OSMID"); Dictionary<string, int> osmPointDomainAttributeFieldIndices = new Dictionary<string, int>(); foreach (var domains in availableDomains.domain) { int currentFieldIndex = osmPointFeatureClass.FindField(domains.name); if (currentFieldIndex != -1) { osmPointDomainAttributeFieldIndices.Add(domains.name, currentFieldIndex); } } int tagCollectionPointFieldIndex = osmPointFeatureClass.FindField("osmTags"); int osmUserPointFieldIndex = osmPointFeatureClass.FindField("osmuser"); int osmUIDPointFieldIndex = osmPointFeatureClass.FindField("osmuid"); int osmVisiblePointFieldIndex = osmPointFeatureClass.FindField("osmvisible"); int osmVersionPointFieldIndex = osmPointFeatureClass.FindField("osmversion"); int osmChangesetPointFieldIndex = osmPointFeatureClass.FindField("osmchangeset"); int osmTimeStampPointFieldIndex = osmPointFeatureClass.FindField("osmtimestamp"); int osmMemberOfPointFieldIndex = osmPointFeatureClass.FindField("osmMemberOf"); int osmSupportingElementPointFieldIndex = osmPointFeatureClass.FindField("osmSupportingElement"); int osmWayRefCountFieldIndex = osmPointFeatureClass.FindField("wayRefCount"); // lines try { osmLineFeatureClass = osmToolHelper.CreateLineFeatureClass((IWorkspace2)featureWorkspace, targetFeatureDataset, targetDataElement.Name + "_osm_ln", null, null, null, storageKeyword, availableDomains, metadataAbstract, metadataPurpose, attributeTags[esriGeometryType.esriGeometryPolyline]); } catch (Exception ex) { message.AddError(120036, String.Format(resourceManager.GetString("GPTools_OSMGPDownload_nulllinefeatureclass"), ex.Message)); return; } if (osmLineFeatureClass == null) { return; } // change the property set of the osm class extension to skip any change detection during the initial data load osmLineFeatureClass.RemoveOSMClassExtension(); int osmLineIDFieldIndex = osmLineFeatureClass.FindField("OSMID"); Dictionary<string, int> osmLineDomainAttributeFieldIndices = new Dictionary<string, int>(); foreach (var domains in availableDomains.domain) { int currentFieldIndex = osmLineFeatureClass.FindField(domains.name); if (currentFieldIndex != -1) { osmLineDomainAttributeFieldIndices.Add(domains.name, currentFieldIndex); } } int tagCollectionPolylineFieldIndex = osmLineFeatureClass.FindField("osmTags"); int osmUserPolylineFieldIndex = osmLineFeatureClass.FindField("osmuser"); int osmUIDPolylineFieldIndex = osmLineFeatureClass.FindField("osmuid"); int osmVisiblePolylineFieldIndex = osmLineFeatureClass.FindField("osmvisible"); int osmVersionPolylineFieldIndex = osmLineFeatureClass.FindField("osmversion"); int osmChangesetPolylineFieldIndex = osmLineFeatureClass.FindField("osmchangeset"); int osmTimeStampPolylineFieldIndex = osmLineFeatureClass.FindField("osmtimestamp"); int osmMemberOfPolylineFieldIndex = osmLineFeatureClass.FindField("osmMemberOf"); int osmMembersPolylineFieldIndex = osmLineFeatureClass.FindField("osmMembers"); int osmSupportingElementPolylineFieldIndex = osmLineFeatureClass.FindField("osmSupportingElement"); // polygons try { osmPolygonFeatureClass = osmToolHelper.CreatePolygonFeatureClass((IWorkspace2)featureWorkspace, targetFeatureDataset, targetDataElement.Name + "_osm_ply", null, null, null, storageKeyword, availableDomains, metadataAbstract, metadataPurpose, attributeTags[esriGeometryType.esriGeometryPolygon]); } catch (Exception ex) { message.AddError(120037, String.Format(resourceManager.GetString("GPTools_OSMGPDownload_nullpolygonfeatureclass"), ex.Message)); return; } if (osmPolygonFeatureClass == null) { return; } // change the property set of the osm class extension to skip any change detection during the initial data load osmPolygonFeatureClass.RemoveOSMClassExtension(); int osmPolygonIDFieldIndex = osmPolygonFeatureClass.FindField("OSMID"); Dictionary<string, int> osmPolygonDomainAttributeFieldIndices = new Dictionary<string, int>(); foreach (var domains in availableDomains.domain) { int currentFieldIndex = osmPolygonFeatureClass.FindField(domains.name); if (currentFieldIndex != -1) { osmPolygonDomainAttributeFieldIndices.Add(domains.name, currentFieldIndex); } } int tagCollectionPolygonFieldIndex = osmPolygonFeatureClass.FindField("osmTags"); int osmUserPolygonFieldIndex = osmPolygonFeatureClass.FindField("osmuser"); int osmUIDPolygonFieldIndex = osmPolygonFeatureClass.FindField("osmuid"); int osmVisiblePolygonFieldIndex = osmPolygonFeatureClass.FindField("osmvisible"); int osmVersionPolygonFieldIndex = osmPolygonFeatureClass.FindField("osmversion"); int osmChangesetPolygonFieldIndex = osmPolygonFeatureClass.FindField("osmchangeset"); int osmTimeStampPolygonFieldIndex = osmPolygonFeatureClass.FindField("osmtimestamp"); int osmMemberOfPolygonFieldIndex = osmPolygonFeatureClass.FindField("osmMemberOf"); int osmMembersPolygonFieldIndex = osmPolygonFeatureClass.FindField("osmMembers"); int osmSupportingElementPolygonFieldIndex = osmPolygonFeatureClass.FindField("osmSupportingElement"); // relation table ITable relationTable = null; try { relationTable = osmToolHelper.CreateRelationTable((IWorkspace2)featureWorkspace, targetDataElement.Name + "_osm_relation", null, storageKeyword, metadataAbstract, metadataPurpose); } catch (Exception ex) { message.AddError(120038, String.Format(resourceManager.GetString("GPTools_OSMGPDownload_nullrelationtable"), ex.Message)); return; } if (relationTable == null) { return; } int osmRelationIDFieldIndex = relationTable.FindField("OSMID"); int tagCollectionRelationFieldIndex = relationTable.FindField("osmTags"); int osmUserRelationFieldIndex = relationTable.FindField("osmuser"); int osmUIDRelationFieldIndex = relationTable.FindField("osmuid"); int osmVisibleRelationFieldIndex = relationTable.FindField("osmvisible"); int osmVersionRelationFieldIndex = relationTable.FindField("osmversion"); int osmChangesetRelationFieldIndex = relationTable.FindField("osmchangeset"); int osmTimeStampRelationFieldIndex = relationTable.FindField("osmtimestamp"); int osmMemberOfRelationFieldIndex = relationTable.FindField("osmMemberOf"); int osmMembersRelationFieldIndex = relationTable.FindField("osmMembers"); int osmSupportingElementRelationFieldIndex = relationTable.FindField("osmSupportingElement"); // revision table ITable revisionTable = null; try { revisionTable = osmToolHelper.CreateRevisionTable((IWorkspace2)featureWorkspace, targetDataElement.Name + "_osm_revision", null, storageKeyword); } catch (Exception ex) { message.AddError(120039, String.Format(resourceManager.GetString("GPTools_OSMGPDownload_nullrevisiontable"), ex.Message)); return; } if (revisionTable == null) { return; } #region clean any existing data from loading targets ESRI.ArcGIS.Geoprocessing.IGeoProcessor2 gp = new ESRI.ArcGIS.Geoprocessing.GeoProcessorClass(); IGeoProcessorResult gpResult = new GeoProcessorResultClass(); try { IVariantArray truncateParameters = new VarArrayClass(); truncateParameters.Add(((IWorkspace)featureWorkspace).PathName + "\\" + targetDataElement.Name + "\\" + targetDataElement.Name + "_osm_pt"); gpResult = gp.Execute("TruncateTable_management", truncateParameters, TrackCancel); truncateParameters = new VarArrayClass(); truncateParameters.Add(((IWorkspace)featureWorkspace).PathName + "\\" + targetDataElement.Name + "\\" + targetDataElement.Name + "_osm_ln"); gpResult = gp.Execute("TruncateTable_management", truncateParameters, TrackCancel); truncateParameters = new VarArrayClass(); truncateParameters.Add(((IWorkspace)featureWorkspace).PathName + "\\" + targetDataElement.Name + "\\" + targetDataElement.Name + "_osm_ply"); gpResult = gp.Execute("TruncateTable_management", truncateParameters, TrackCancel); truncateParameters = new VarArrayClass(); truncateParameters.Add(((IWorkspace)featureWorkspace).PathName + "\\" + targetDataElement.Name + "_osm_relation"); gpResult = gp.Execute("TruncateTable_management", truncateParameters, TrackCancel); truncateParameters = new VarArrayClass(); truncateParameters.Add(((IWorkspace)featureWorkspace).PathName + "\\" + targetDataElement.Name + "_osm_revision"); gpResult = gp.Execute("TruncateTable_management", truncateParameters, TrackCancel); } catch (Exception ex) { message.AddWarning(ex.Message); } #endregion bool fastLoad = false; //// check for user interruption //if (TrackCancel.Continue() == false) //{ // message.AddAbort(resourceManager.GetString("GPTools_toolabort")); // return; //} //IFeatureCursor deleteCursor = null; //using (ComReleaser comReleaser = new ComReleaser()) //{ // // let's make sure that we clean out any old data that might have existed in the feature classes // deleteCursor = osmPointFeatureClass.Update(null, false); // comReleaser.ManageLifetime(deleteCursor); // for (IFeature feature = deleteCursor.NextFeature(); feature != null; feature = deleteCursor.NextFeature()) // { // feature.Delete(); // // check for user interruption // if (TrackCancel.Continue() == false) // { // message.AddAbort(resourceManager.GetString("GPTools_toolabort")); // return; // } // } //} //using (ComReleaser comReleaser = new ComReleaser()) //{ // deleteCursor = osmLineFeatureClass.Update(null, false); // comReleaser.ManageLifetime(deleteCursor); // for (IFeature feature = deleteCursor.NextFeature(); feature != null; feature = deleteCursor.NextFeature()) // { // feature.Delete(); // // check for user interruption // if (TrackCancel.Continue() == false) // { // message.AddAbort(resourceManager.GetString("GPTools_toolabort")); // return; // } // } //} //using (ComReleaser comReleaser = new ComReleaser()) //{ // deleteCursor = osmPolygonFeatureClass.Update(null, false); // comReleaser.ManageLifetime(deleteCursor); // for (IFeature feature = deleteCursor.NextFeature(); feature != null; feature = deleteCursor.NextFeature()) // { // feature.Delete(); // // check for user interruption // if (TrackCancel.Continue() == false) // { // message.AddAbort(resourceManager.GetString("GPTools_toolabort")); // return; // } // } //} //ICursor tableCursor = null; //using (ComReleaser comReleaser = new ComReleaser()) //{ // tableCursor = relationTable.Update(null, false); // comReleaser.ManageLifetime(tableCursor); // for (IRow row = tableCursor.NextRow(); row != null; row = tableCursor.NextRow()) // { // row.Delete(); // // check for user interruption // if (TrackCancel.Continue() == false) // { // message.AddAbort(resourceManager.GetString("GPTools_toolabort")); // return; // } // } //} //using (ComReleaser comReleaser = new ComReleaser()) //{ // tableCursor = revisionTable.Update(null, false); // comReleaser.ManageLifetime(tableCursor); // for (IRow row = tableCursor.NextRow(); row != null; row = tableCursor.NextRow()) // { // row.Delete(); // // check for user interruption // if (TrackCancel.Continue() == false) // { // message.AddAbort(resourceManager.GetString("GPTools_toolabort")); // return; // } // } //} // define variables helping to invoke core tools for data management IGeoProcessorResult2 gpResults2 = null; IGeoProcessor2 geoProcessor = new GeoProcessorClass(); #region load points osmToolHelper.loadOSMNodes(osmFileLocationString.GetAsText(), ref TrackCancel, ref message, targetDatasetGPValue, osmPointFeatureClass, conserveMemoryGPValue.Value, fastLoad, Convert.ToInt32(nodeCapacity), ref osmNodeDictionary, featureWorkspace, downloadSpatialReference, availableDomains, false); #endregion if (TrackCancel.Continue() == false) { return; } #region load ways List<string> missingWays = osmToolHelper.loadOSMWays(osmFileLocationString.GetAsText(), ref TrackCancel, ref message, targetDatasetGPValue, osmPointFeatureClass, osmLineFeatureClass, osmPolygonFeatureClass, conserveMemoryGPValue.Value, fastLoad, Convert.ToInt32(wayCapacity), ref osmNodeDictionary, featureWorkspace, downloadSpatialReference, availableDomains, false); #endregion if (downloadSpatialReference != null) Marshal.ReleaseComObject(downloadSpatialReference); #region for local geodatabases enforce spatial integrity bool storedOriginalLocal = geoProcessor.AddOutputsToMap; geoProcessor.AddOutputsToMap = false; if (osmLineFeatureClass != null) { if (((IDataset)osmLineFeatureClass).Workspace.Type == esriWorkspaceType.esriLocalDatabaseWorkspace) { gpUtilities3 = new GPUtilitiesClass() as IGPUtilities3; IGPParameter outLinesParameter = paramvalues.get_Element(out_osmLinesNumber) as IGPParameter; IGPValue lineFeatureClass = gpUtilities3.UnpackGPValue(outLinesParameter); DataManagementTools.RepairGeometry repairlineGeometry = new DataManagementTools.RepairGeometry(osmLineFeatureClass); IVariantArray repairGeometryParameterArray = new VarArrayClass(); repairGeometryParameterArray.Add(lineFeatureClass.GetAsText()); repairGeometryParameterArray.Add("DELETE_NULL"); gpResults2 = geoProcessor.Execute(repairlineGeometry.ToolName, repairGeometryParameterArray, TrackCancel) as IGeoProcessorResult2; message.AddMessages(gpResults2.GetResultMessages()); ComReleaser.ReleaseCOMObject(gpUtilities3); } } if (osmPolygonFeatureClass != null) { if (((IDataset)osmPolygonFeatureClass).Workspace.Type == esriWorkspaceType.esriLocalDatabaseWorkspace) { gpUtilities3 = new GPUtilitiesClass() as IGPUtilities3; IGPParameter outPolygonParameter = paramvalues.get_Element(out_osmPolygonsNumber) as IGPParameter; IGPValue polygonFeatureClass = gpUtilities3.UnpackGPValue(outPolygonParameter); DataManagementTools.RepairGeometry repairpolygonGeometry = new DataManagementTools.RepairGeometry(osmPolygonFeatureClass); IVariantArray repairGeometryParameterArray = new VarArrayClass(); repairGeometryParameterArray.Add(polygonFeatureClass.GetAsText()); repairGeometryParameterArray.Add("DELETE_NULL"); gpResults2 = geoProcessor.Execute(repairpolygonGeometry.ToolName, repairGeometryParameterArray, TrackCancel) as IGeoProcessorResult2; message.AddMessages(gpResults2.GetResultMessages()); ComReleaser.ReleaseCOMObject(gpUtilities3); } } geoProcessor.AddOutputsToMap = storedOriginalLocal; #endregion if (TrackCancel.Continue() == false) { return; } #region load relations List<string> missingRelations = osmToolHelper.loadOSMRelations(osmFileLocationString.GetAsText(), ref TrackCancel, ref message, targetDatasetGPValue, osmPointFeatureClass, osmLineFeatureClass, osmPolygonFeatureClass, Convert.ToInt32(relationCapacity), relationTable, availableDomains, fastLoad, false); #endregion // check for user interruption if (TrackCancel.Continue() == false) { return; } //storedOriginalLocal = geoProcessor.AddOutputsToMap; //try //{ // geoProcessor.AddOutputsToMap = false; // // add indexes for revisions // //IGPValue revisionTableGPValue = gpUtilities3.MakeGPValueFromObject(revisionTable); // string revisionTableString = targetDatasetGPValue.GetAsText() + System.IO.Path.DirectorySeparatorChar + ((IDataset)revisionTable).BrowseName; // IVariantArray parameterArrary2 = osmToolHelper.CreateAddIndexParameterArray(revisionTableString, "osmoldid;osmnewid", "osmID_IDX", "", ""); // gpResults2 = geoProcessor.Execute("AddIndex_management", parameterArrary2, TrackCancel) as IGeoProcessorResult2; // message.AddMessages(gpResults2.GetResultMessages()); //} //catch (Exception ex) //{ // message.AddWarning(ex.Message); //} //finally //{ // geoProcessor.AddOutputsToMap = storedOriginalLocal; //} #region update the references counts and member lists for nodes message.AddMessage(resourceManager.GetString("GPTools_OSMGPFileReader_updatereferences")); IFeatureCursor pointUpdateCursor = null; IQueryFilter pointQueryFilter = new QueryFilterClass(); // adjust of number of all other reference counter from 0 to 1 if (conserveMemoryGPValue.Value == true) { pointQueryFilter.WhereClause = osmPointFeatureClass.SqlIdentifier("wayRefCount") + " = 0"; pointQueryFilter.SubFields = osmPointFeatureClass.OIDFieldName + ",wayRefCount"; } using (SchemaLockManager ptLockManager = new SchemaLockManager(osmPointFeatureClass as ITable)) { using (ComReleaser comReleaser = new ComReleaser()) { int updateCount = 0; if (conserveMemoryGPValue.Value == true) { pointUpdateCursor = osmPointFeatureClass.Update(pointQueryFilter, false); updateCount = ((ITable)osmPointFeatureClass).RowCount(pointQueryFilter); } else { pointUpdateCursor = osmPointFeatureClass.Update(null, false); updateCount = ((ITable)osmPointFeatureClass).RowCount(null); } IStepProgressor stepProgressor = TrackCancel as IStepProgressor; if (stepProgressor != null) { stepProgressor.MinRange = 0; stepProgressor.MaxRange = updateCount; stepProgressor.Position = 0; stepProgressor.Message = resourceManager.GetString("GPTools_OSMGPFileReader_updatepointrefcount"); stepProgressor.StepValue = 1; stepProgressor.Show(); } comReleaser.ManageLifetime(pointUpdateCursor); IFeature pointFeature = pointUpdateCursor.NextFeature(); int positionCounter = 0; while (pointFeature != null) { positionCounter++; string nodeID = Convert.ToString(pointFeature.get_Value(osmPointIDFieldIndex)); if (conserveMemoryGPValue.Value == false) { // let get the reference counter from the internal node dictionary if (osmNodeDictionary[nodeID].RefCounter == 0) { pointFeature.set_Value(osmWayRefCountFieldIndex, 1); } else { pointFeature.set_Value(osmWayRefCountFieldIndex, osmNodeDictionary[nodeID].RefCounter); } } else { // in the case of memory conservation let's go change the 0s to 1s pointFeature.set_Value(osmWayRefCountFieldIndex, 1); } pointUpdateCursor.UpdateFeature(pointFeature); if (pointFeature != null) Marshal.ReleaseComObject(pointFeature); pointFeature = pointUpdateCursor.NextFeature(); if (stepProgressor != null) { stepProgressor.Position = positionCounter; } } if (stepProgressor != null) { stepProgressor.Hide(); } Marshal.ReleaseComObject(pointQueryFilter); } } #endregion if (osmNodeDictionary != null) { // clear outstanding resources potentially holding points osmNodeDictionary = null; System.GC.Collect(2, GCCollectionMode.Forced); } if (missingRelations.Count > 0) { missingRelations.Clear(); missingRelations = null; } if (missingWays.Count > 0) { missingWays.Clear(); missingWays = null; } SyncState.StoreLastSyncTime(targetDatasetName, syncTime); gpUtilities3 = new GPUtilitiesClass() as IGPUtilities3; // repackage the feature class into their respective gp values IGPParameter pointFeatureClassParameter = paramvalues.get_Element(out_osmPointsNumber) as IGPParameter; IGPValue pointFeatureClassGPValue = gpUtilities3.UnpackGPValue(pointFeatureClassParameter); gpUtilities3.PackGPValue(pointFeatureClassGPValue, pointFeatureClassParameter); IGPParameter lineFeatureClassParameter = paramvalues.get_Element(out_osmLinesNumber) as IGPParameter; IGPValue line1FeatureClassGPValue = gpUtilities3.UnpackGPValue(lineFeatureClassParameter); gpUtilities3.PackGPValue(line1FeatureClassGPValue, lineFeatureClassParameter); IGPParameter polygonFeatureClassParameter = paramvalues.get_Element(out_osmPolygonsNumber) as IGPParameter; IGPValue polygon1FeatureClassGPValue = gpUtilities3.UnpackGPValue(polygonFeatureClassParameter); gpUtilities3.PackGPValue(polygon1FeatureClassGPValue, polygonFeatureClassParameter); ComReleaser.ReleaseCOMObject(relationTable); ComReleaser.ReleaseCOMObject(revisionTable); ComReleaser.ReleaseCOMObject(targetFeatureDataset); ComReleaser.ReleaseCOMObject(featureWorkspace); ComReleaser.ReleaseCOMObject(osmFileLocationString); ComReleaser.ReleaseCOMObject(conserveMemoryGPValue); ComReleaser.ReleaseCOMObject(targetDataset); gpUtilities3.ReleaseInternals(); ComReleaser.ReleaseCOMObject(gpUtilities3); } catch (Exception ex) { message.AddError(120055, ex.Message); message.AddError(120055, ex.StackTrace); } finally { try { // TE -- 1/7/2015 // this is a 'breaking' change as the default loader won't no longer enable the edit extension // the reasoning here is that most users would like the OSM in a 'read-only' fashion, and don't need to track // changes to be properly transmitted back to the OSM server //if (osmPointFeatureClass != null) //{ // osmPointFeatureClass.ApplyOSMClassExtension(); // ComReleaser.ReleaseCOMObject(osmPointFeatureClass); //} //if (osmLineFeatureClass != null) //{ // osmLineFeatureClass.ApplyOSMClassExtension(); // ComReleaser.ReleaseCOMObject(osmLineFeatureClass); //} //if (osmPolygonFeatureClass != null) //{ // osmPolygonFeatureClass.ApplyOSMClassExtension(); // ComReleaser.ReleaseCOMObject(osmPolygonFeatureClass); //} osmToolHelper = null; System.GC.Collect(); System.GC.WaitForPendingFinalizers(); } catch (Exception ex) { message.AddError(120056, ex.ToString()); } } }
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; } }
public void Execute(ESRI.ArcGIS.esriSystem.IArray paramvalues, ESRI.ArcGIS.esriSystem.ITrackCancel TrackCancel, ESRI.ArcGIS.Geoprocessing.IGPEnvironmentManager envMgr, ESRI.ArcGIS.Geodatabase.IGPMessages message) { try { IGPUtilities3 execute_Utilities = new GPUtilitiesClass(); if (TrackCancel == null) { TrackCancel = new CancelTrackerClass(); } IGPParameter inputOSMParameter = paramvalues.get_Element(in_osmFeatureClass) as IGPParameter; IGPValue inputOSMGPValue = execute_Utilities.UnpackGPValue(inputOSMParameter); IGPParameter tagCollectionParameter = paramvalues.get_Element(in_attributeSelector) as IGPParameter; IGPMultiValue tagCollectionGPValue = execute_Utilities.UnpackGPValue(tagCollectionParameter) as IGPMultiValue; if (tagCollectionGPValue == null) { message.AddError(120048, string.Format(resourceManager.GetString("GPTools_NullPointerParameterType"), tagCollectionParameter.Name)); return; } bool useUpdateCursor = false; IFeatureClass osmFeatureClass = null; ITable osmInputTable = null; IQueryFilter osmQueryFilter = null; try { execute_Utilities.DecodeFeatureLayer(inputOSMGPValue, out osmFeatureClass, out osmQueryFilter); if (osmFeatureClass != null) { if (osmFeatureClass.Extension is IOSMClassExtension) { useUpdateCursor = false; } else { useUpdateCursor = true; } } osmInputTable = osmFeatureClass as ITable; } catch { } try { if (osmInputTable == null) { execute_Utilities.DecodeTableView(inputOSMGPValue, out osmInputTable, out osmQueryFilter); } } catch { } if (osmInputTable == null) { string errorMessage = String.Format(resourceManager.GetString("GPTools_OSMGPAttributeSelecto_unableopentable"), inputOSMGPValue.GetAsText()); message.AddError(120053, errorMessage); return; } // find the field that holds tag binary/xml field int osmTagCollectionFieldIndex = osmInputTable.FindField("osmTags"); // if the Field doesn't exist - wasn't found (index = -1) get out if (osmTagCollectionFieldIndex == -1) { message.AddError(120005, resourceManager.GetString("GPTools_OSMGPAttributeSelector_notagfieldfound")); return; } // check if the tag collection includes the keyword "ALL", if does then we'll need to extract all tags bool extractAll = false; for (int valueIndex = 0; valueIndex < tagCollectionGPValue.Count; valueIndex++) { if (tagCollectionGPValue.get_Value(valueIndex).GetAsText().Equals("ALL")) { extractAll = true; break; } } //if (extractAll) //{ // if (osmTagKeyCodedValues == null) // extractAllTags(ref osmTagKeyCodedValues, osmInputTable, osmQueryFilter, osmTagCollectionFieldIndex, false); // if (osmTagKeyCodedValues == null) // { // message.AddAbort(resourceManager.GetString("GPTools_OSMGPAttributeSelector_Unable2RetrieveTags")); // return; // } // // empty the existing gp multivalue object // tagCollectionGPValue = new GPMultiValueClass(); // // fill the coded domain in gp multivalue object // for (int valueIndex = 0; valueIndex < osmTagKeyCodedValues.CodeCount; valueIndex++) // { // tagCollectionGPValue.AddValue(osmTagKeyCodedValues.get_Value(valueIndex)); // } //} // get an overall feature count as that determines the progress indicator int featureCount = osmInputTable.RowCount(osmQueryFilter); // set up the progress indicator IStepProgressor stepProgressor = TrackCancel as IStepProgressor; if (stepProgressor != null) { stepProgressor.MinRange = 0; stepProgressor.MaxRange = featureCount; stepProgressor.Position = 0; stepProgressor.Message = resourceManager.GetString("GPTools_OSMGPAttributeSelector_progressMessage"); stepProgressor.StepValue = 1; stepProgressor.Show(); } // let's get all the indices of the desired fields // if the field already exists get the index and if it doesn't exist create it Dictionary <string, int> tagsAttributesIndices = new Dictionary <string, int>(); Dictionary <int, int> attributeFieldLength = new Dictionary <int, int>(); IFeatureWorkspaceManage featureWorkspaceManage = ((IDataset)osmInputTable).Workspace as IFeatureWorkspaceManage; String illegalCharacters = String.Empty; ISQLSyntax sqlSyntax = ((IDataset)osmInputTable).Workspace as ISQLSyntax; if (sqlSyntax != null) { illegalCharacters = sqlSyntax.GetInvalidCharacters(); } IFieldsEdit fieldsEdit = osmInputTable.Fields as IFieldsEdit; using (SchemaLockManager lockMgr = new SchemaLockManager(osmInputTable)) { try { string tagKey = String.Empty; ESRI.ArcGIS.Geoprocessing.IGeoProcessor2 gp = new ESRI.ArcGIS.Geoprocessing.GeoProcessorClass(); // if we have explicitly defined tags to extract then go through the list of values now if (extractAll == false) { for (int valueIndex = 0; valueIndex < tagCollectionGPValue.Count; valueIndex++) { if (TrackCancel.Continue() == false) { return; } try { // Check if the input field already exists. string nameofTag = tagCollectionGPValue.get_Value(valueIndex).GetAsText(); tagKey = convert2AttributeFieldName(nameofTag, illegalCharacters); int fieldIndex = osmInputTable.FindField(tagKey); if (fieldIndex < 0) { // generate a new attribute field IFieldEdit fieldEdit = new FieldClass(); fieldEdit.Name_2 = tagKey; fieldEdit.AliasName_2 = nameofTag + resourceManager.GetString("GPTools_OSMGPAttributeSelector_aliasaddition"); fieldEdit.Type_2 = esriFieldType.esriFieldTypeString; fieldEdit.Length_2 = 100; osmInputTable.AddField(fieldEdit); message.AddMessage(string.Format(resourceManager.GetString("GPTools_OSMGPAttributeSelector_addField"), tagKey, nameofTag)); // re-generate the attribute index fieldIndex = osmInputTable.FindField(tagKey); } if (fieldIndex > 0) { tagsAttributesIndices.Add(nameofTag, fieldIndex); attributeFieldLength.Add(fieldIndex, osmInputTable.Fields.get_Field(fieldIndex).Length); } } catch (Exception ex) { // the key is already there, this might result because from multiple upper and lower-case combinations of the same key message.AddWarning(ex.Message + " (" + convert2OSMKey(tagKey, illegalCharacters) + ")"); } } } else { List <string> listofAllTags = extractAllTags(osmInputTable, osmQueryFilter, osmTagCollectionFieldIndex); foreach (string nameOfTag in listofAllTags) { if (TrackCancel.Continue() == false) { return; } try { // Check if the input field already exists. tagKey = convert2AttributeFieldName(nameOfTag, illegalCharacters); int fieldIndex = osmInputTable.FindField(tagKey); if (fieldIndex < 0) { // generate a new attribute field IFieldEdit fieldEdit = new FieldClass(); fieldEdit.Name_2 = tagKey; fieldEdit.AliasName_2 = nameOfTag + resourceManager.GetString("GPTools_OSMGPAttributeSelector_aliasaddition"); fieldEdit.Type_2 = esriFieldType.esriFieldTypeString; fieldEdit.Length_2 = 100; osmInputTable.AddField(fieldEdit); message.AddMessage(string.Format(resourceManager.GetString("GPTools_OSMGPAttributeSelector_addField"), tagKey, nameOfTag)); // re-generate the attribute index fieldIndex = osmInputTable.FindField(tagKey); } if (fieldIndex > 0) { tagsAttributesIndices.Add(nameOfTag, fieldIndex); attributeFieldLength.Add(fieldIndex, osmInputTable.Fields.get_Field(fieldIndex).Length); } } catch (Exception ex) { // the key is already there, this might result because from multiple upper and lower-case combinations of the same key message.AddWarning(ex.Message + " (" + convert2OSMKey(tagKey, illegalCharacters) + ")"); } } } } catch (Exception ex) { message.AddWarning(ex.Message); } } try { execute_Utilities.DecodeFeatureLayer(inputOSMGPValue, out osmFeatureClass, out osmQueryFilter); if (osmFeatureClass != null) { if (osmFeatureClass.Extension is IOSMClassExtension) { useUpdateCursor = false; } else { useUpdateCursor = true; } } osmInputTable = osmFeatureClass as ITable; } catch { } try { if (osmInputTable == null) { execute_Utilities.DecodeTableView(inputOSMGPValue, out osmInputTable, out osmQueryFilter); } } catch { } if (osmInputTable == null) { string errorMessage = String.Format(resourceManager.GetString("GPTools_OSMGPAttributeSelecto_unableopentable"), inputOSMGPValue.GetAsText()); message.AddError(120053, errorMessage); return; } using (ComReleaser comReleaser = new ComReleaser()) { using (SchemaLockManager lockMgr = new SchemaLockManager(osmInputTable)) { // get an update cursor for all the features to process ICursor rowCursor = null; if (useUpdateCursor) { rowCursor = osmInputTable.Update(osmQueryFilter, false); } else { rowCursor = osmInputTable.Search(osmQueryFilter, false); } comReleaser.ManageLifetime(rowCursor); IRow osmRow = null; Dictionary <string, string> tagKeys = new Dictionary <string, string>(); int progessIndex = 0; #if DEBUG message.AddMessage("useUpdateCursor: " + useUpdateCursor.ToString()); #endif // as long as there are features.... while ((osmRow = rowCursor.NextRow()) != null) { // retrieve the tags of the current feature tag[] storedTags = _osmUtility.retrieveOSMTags(osmRow, osmTagCollectionFieldIndex, ((IDataset)osmInputTable).Workspace); bool rowChanged = false; if (storedTags != null) { foreach (tag tagItem in storedTags) { // Check for matching values so we only change a minimum number of rows if (tagsAttributesIndices.ContainsKey(tagItem.k)) { int fieldIndex = tagsAttributesIndices[tagItem.k]; //...then stored the value in the attribute field // ensure that the content of the tag actually does fit into the field length...otherwise do truncate it string tagValue = tagItem.v; int fieldLength = attributeFieldLength[fieldIndex]; if (tagValue.Length > fieldLength) { tagValue = tagValue.Substring(0, fieldLength); } osmRow.set_Value(fieldIndex, tagValue); rowChanged = true; } else { #if DEBUG //message.AddWarning(tagItem.k); #endif } } } storedTags = null; try { if (rowChanged) { if (useUpdateCursor) { rowCursor.UpdateRow(osmRow); } else { // update the feature through the cursor osmRow.Store(); } } progessIndex++; } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.Message); message.AddWarning(ex.Message); } if (osmRow != null) { Marshal.ReleaseComObject(osmRow); } if (stepProgressor != null) { // update the progress UI stepProgressor.Position = progessIndex; } // check for user cancellation (every 100 rows) if ((progessIndex % 100 == 0) && (TrackCancel.Continue() == false)) { return; } } if (stepProgressor != null) { stepProgressor.Hide(); } } } execute_Utilities.ReleaseInternals(); Marshal.ReleaseComObject(execute_Utilities); } catch (Exception ex) { message.AddError(120054, ex.Message); } }
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; } }
public void Execute(ESRI.ArcGIS.esriSystem.IArray paramvalues, ESRI.ArcGIS.esriSystem.ITrackCancel TrackCancel, ESRI.ArcGIS.Geoprocessing.IGPEnvironmentManager envMgr, ESRI.ArcGIS.Geodatabase.IGPMessages message) { _message = message; // classes to carry out the basic client/server communication HttpWebResponse httpResponse = null; string changeSetID = "-1"; IGPString baseURLGPString = new GPStringClass(); ICursor searchCursor = null; IGPUtilities3 gpUtilities3 = new GPUtilitiesClass(); if (TrackCancel == null) { TrackCancel = new CancelTrackerClass(); } IGPParameter userNameParameter = paramvalues.get_Element(in_userNameNumber) as IGPParameter; IGPString userNameGPValue = gpUtilities3.UnpackGPValue(userNameParameter) as IGPString; IHttpBasicGPValue userCredentialGPValue = new HttpBasicGPValue(); if (userNameGPValue != null) { userCredentialGPValue.UserName = userNameGPValue.Value; } else { return; } IGPParameter passwordParameter = paramvalues.get_Element(in_passwordNumber) as IGPParameter; IGPStringHidden passwordGPValue = gpUtilities3.UnpackGPValue(passwordParameter) as IGPStringHidden; if (passwordGPValue != null) { userCredentialGPValue.PassWord = passwordGPValue.Value; } else { return; } ITable revisionTable = null; int secondsToTimeout = 10; try { UpdateMessages(paramvalues, envMgr, message); if ((message.MaxSeverity == esriGPMessageSeverity.esriGPMessageSeverityAbort) || (message.MaxSeverity == esriGPMessageSeverity.esriGPMessageSeverityError)) { message.AddMessages(message); return; } IGPParameter baseURLParameter = paramvalues.get_Element(in_uploadURLNumber) as IGPParameter; baseURLGPString = gpUtilities3.UnpackGPValue(baseURLParameter) as IGPString; IGPParameter commentParameter = paramvalues.get_Element(in_uploadCommentNumber) as IGPParameter; IGPString uploadCommentGPString = gpUtilities3.UnpackGPValue(commentParameter) as IGPString; ISpatialReferenceFactory spatialReferenceFactory = new SpatialReferenceEnvironmentClass() as ISpatialReferenceFactory; m_wgs84 = spatialReferenceFactory.CreateGeographicCoordinateSystem((int)esriSRGeoCSType.esriSRGeoCS_WGS1984) as ISpatialReference; System.Xml.Serialization.XmlSerializer serializer = null; serializer = new XmlSerializer(typeof(osm)); osm createChangeSetOSM = new osm(); string user_displayname = ""; int userID = -1; // set the "default" value of the OSM server int maxElementsinChangeSet = 50000; HttpWebRequest httpClient = HttpWebRequest.Create(baseURLGPString.Value + "/api/capabilities") as HttpWebRequest; httpClient = OSMGPDownload.AssignProxyandCredentials(httpClient); SetBasicAuthHeader(httpClient, userCredentialGPValue.EncodedUserNamePassWord); httpClient.Timeout = secondsToTimeout * 1000; createChangeSetOSM.generator = m_Generator; createChangeSetOSM.version = "0.6"; changeset createChangeSet = new changeset(); createChangeSet.id = "0"; createChangeSet.open = changesetOpen.@false; List<tag> changeSetTags = new List<tag>(); tag createdByTag = new tag(); createdByTag.k = "created_by"; createdByTag.v = "ArcGIS Editor for OpenStreetMap"; changeSetTags.Add(createdByTag); tag commentTag = new tag(); commentTag.k = "comment"; commentTag.v = uploadCommentGPString.Value; changeSetTags.Add(commentTag); createChangeSet.tag = changeSetTags.ToArray(); createChangeSetOSM.Items = new object[] { createChangeSet }; api apiCapabilities = null; // retrieve some server settings try { httpResponse = httpClient.GetResponse() as HttpWebResponse; osm osmCapabilities = null; Stream stream = httpResponse.GetResponseStream(); XmlTextReader xmlReader = new XmlTextReader(stream); osmCapabilities = serializer.Deserialize(xmlReader) as osm; xmlReader.Close(); apiCapabilities = osmCapabilities.Items[0] as api; httpResponse.Close(); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.Message); message.AddWarning(ex.Message); } if (apiCapabilities != null) { // read the timeout parameter secondsToTimeout = Convert.ToInt32(apiCapabilities.timeout.seconds); httpClient.Timeout = secondsToTimeout * 1000; // update the setting of allowed features per changeset from the actual capabilities response maxElementsinChangeSet = Convert.ToInt32(apiCapabilities.changesets.maximum_elements); } // retrieve some information about the user try { httpClient = null; httpClient = HttpWebRequest.Create(baseURLGPString.Value + "/api/0.6/user/details") as HttpWebRequest; httpClient = OSMGPDownload.AssignProxyandCredentials(httpClient); SetBasicAuthHeader(httpClient, userCredentialGPValue.EncodedUserNamePassWord); httpResponse = httpClient.GetResponse() as HttpWebResponse; osm osmCapabilities = null; Stream stream = httpResponse.GetResponseStream(); XmlTextReader xmlReader = new XmlTextReader(stream); osmCapabilities = serializer.Deserialize(xmlReader) as osm; xmlReader.Close(); user userInformation = osmCapabilities.Items[0] as user; if (userInformation != null) { user_displayname = userInformation.display_name; userID = Convert.ToInt32(userInformation.id); } } catch (ArgumentOutOfRangeException ex) { message.AddError(120044, ex.Message); return; } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.Message); message.AddWarning(ex.Message); } IGPParameter revisionTableParameter = paramvalues.get_Element(in_changesTablesNumber) as IGPParameter; int featureUpdateCounter = 0; IQueryFilter revisionTableQueryFilter = null; try { gpUtilities3.DecodeTableView(gpUtilities3.UnpackGPValue(revisionTableParameter), out revisionTable, out revisionTableQueryFilter); } catch { message.AddError(120045,resourceManager.GetString("GPTools_OSMGPUpload_missingRevisionTable")); return; } int revChangeSetIDFieldIndex = revisionTable.Fields.FindField("osmchangeset"); int revActionFieldIndex = revisionTable.Fields.FindField("osmaction"); int revElementTypeFieldIndex = revisionTable.Fields.FindField("osmelementtype"); int revVersionFieldIndex = revisionTable.Fields.FindField("osmversion"); int revFCNameFieldIndex = revisionTable.Fields.FindField("sourcefcname"); int revOldIDFieldIndex = revisionTable.Fields.FindField("osmoldid"); int revNewIDFieldIndex = revisionTable.Fields.FindField("osmnewid"); int revStatusFieldIndex = revisionTable.Fields.FindField("osmstatus"); int revStatusCodeFieldIndex = revisionTable.Fields.FindField("osmstatuscode"); int revErrorMessageFieldIndex = revisionTable.Fields.FindField("osmerrormessage"); int revLongitudeFieldIndex = revisionTable.Fields.FindField("osmlon"); int revLatitudeFieldIndex = revisionTable.Fields.FindField("osmlat"); // let's find all the rows that have a different status than OK - meaning success IQueryFilter queryFilter = new QueryFilterClass(); searchCursor = revisionTable.Search(queryFilter, false); IRow searchRowToUpdate = null; // lookup table to adjust all osm ID references if there are know entities Dictionary<long, long> nodeosmIDLookup = new Dictionary<long, long>(); Dictionary<long, long> wayosmIDLookup = new Dictionary<long, long>(); Dictionary<long, long> relationosmIDLookup = new Dictionary<long, long>(); // let's pre-populate the lookup IDs with already know entities // it is necessary if the revision table is used more than once and in different sessions queryFilter.WhereClause = "NOT " + revisionTable.SqlIdentifier("osmnewid") + " IS NULL"; using (ComReleaser comReleaser = new ComReleaser()) { ICursor searchIDCursor = revisionTable.Search(queryFilter, false); comReleaser.ManageLifetime(searchIDCursor); IRow searchRow = searchIDCursor.NextRow(); comReleaser.ManageLifetime(searchRow); while (searchRow != null) { if (revOldIDFieldIndex > -1 && revNewIDFieldIndex > -1) { string elementType = Convert.ToString(searchRow.get_Value(revElementTypeFieldIndex)); switch (elementType) { case "node": if (nodeosmIDLookup.ContainsKey(Convert.ToInt64(searchRow.get_Value(revOldIDFieldIndex))) == false) { nodeosmIDLookup.Add(Convert.ToInt64(searchRow.get_Value(revOldIDFieldIndex)), Convert.ToInt64(searchRow.get_Value(revNewIDFieldIndex))); } break; case "way": if (wayosmIDLookup.ContainsKey(Convert.ToInt64(searchRow.get_Value(revOldIDFieldIndex))) == false) { wayosmIDLookup.Add(Convert.ToInt64(searchRow.get_Value(revOldIDFieldIndex)), Convert.ToInt64(searchRow.get_Value(revNewIDFieldIndex))); } break; case "relation": if (relationosmIDLookup.ContainsKey(Convert.ToInt64(searchRow.get_Value(revOldIDFieldIndex))) == false) { relationosmIDLookup.Add(Convert.ToInt64(searchRow.get_Value(revOldIDFieldIndex)), Convert.ToInt64(searchRow.get_Value(revNewIDFieldIndex))); } break; default: break; } } searchRow = searchIDCursor.NextRow(); } } IFeatureClass pointFeatureClass = null; int pointOSMIDFieldIndex = -1; IFeatureClass lineFeatureClass = null; IFeatureClass polygonFeatureClass = null; ITable relationTable = null; int osmDelimiterPosition = ((IDataset)revisionTable).Name.IndexOf("_osm_"); string osmBaseName = ((IDataset)revisionTable).Name.Substring(0, osmDelimiterPosition); IFeatureWorkspace osmFeatureWorkspace = ((IDataset)revisionTable).Workspace as IFeatureWorkspace; if (osmFeatureWorkspace != null) { pointFeatureClass = osmFeatureWorkspace.OpenFeatureClass(osmBaseName + "_osm_pt"); pointOSMIDFieldIndex = pointFeatureClass.FindField("OSMID"); lineFeatureClass = osmFeatureWorkspace.OpenFeatureClass(osmBaseName + "_osm_ln"); polygonFeatureClass = osmFeatureWorkspace.OpenFeatureClass(osmBaseName + "_osm_ply"); relationTable = osmFeatureWorkspace.OpenTable(osmBaseName + "_osm_relation"); } // determine version of extension int internalExtensionVersion = pointFeatureClass.OSMExtensionVersion(); string sData = OsmRest.SerializeUtils.CreateXmlSerializable(createChangeSetOSM, serializer, Encoding.ASCII, "text/xml"); HttpWebRequest httpClient2 = HttpWebRequest.Create(baseURLGPString.Value + "/api/0.6/changeset/create") as HttpWebRequest; httpClient2.Method = "PUT"; httpClient2 = OSMGPDownload.AssignProxyandCredentials(httpClient2); SetBasicAuthHeader(httpClient2, userCredentialGPValue.EncodedUserNamePassWord); httpClient2.Timeout = secondsToTimeout * 1000; try { Stream requestStream = httpClient2.GetRequestStream(); StreamWriter mywriter = new StreamWriter(requestStream); mywriter.Write(sData); mywriter.Close(); WebResponse clientResponse = httpClient2.GetResponse(); Stream readStream = clientResponse.GetResponseStream(); StreamReader streamReader = new StreamReader(readStream); changeSetID = streamReader.ReadToEnd(); streamReader.Close(); message.AddMessage(String.Format(resourceManager.GetString("GPTools_OSMGPUpload_openChangeSet"), changeSetID)); } catch (Exception ex) { if (httpResponse != null) { if (httpResponse.StatusCode != System.Net.HttpStatusCode.OK) { foreach (var errorItem in httpResponse.Headers.GetValues("Error")) { message.AddError(120009, errorItem); } message.AddError(120009, httpResponse.StatusCode.ToString()); message.AddError(120009, ex.Message); } } else { message.AddError(120047, ex.Message); } return; } IGPParameter uploadFormatParameter = paramvalues.get_Element(in_uploadFormatNumber) as IGPParameter; IGPBoolean useOSMChangeFormatGPValue = gpUtilities3.UnpackGPValue(uploadFormatParameter) as IGPBoolean; // Al Hack if (useOSMChangeFormatGPValue == null) { useOSMChangeFormatGPValue = new GPBoolean(); useOSMChangeFormatGPValue.Value = false; } SQLFormatter sqlFormatter = new SQLFormatter(revisionTable); if (useOSMChangeFormatGPValue.Value == true) { #region osmchange upload format osmChange osmChangeDocument = new osmChange(); osmChangeDocument.generator = m_Generator; osmChangeDocument.version = "0.6"; // xml elements to describe the changeset create uploadCreates = null; modify uploadModify = null; delete uploadDelete = null; // helper classes to keep track of elements entered into a changeset List<object> listOfCreates = null; List<object> listOfModifies = null; List<object> listOfDeletes = null; List<object> changeSetItems = new List<object>(); #region upload create actions // loop through creates queryFilter.WhereClause = "(" + sqlFormatter.SqlIdentifier("osmstatuscode") + " <> 200 OR " + sqlFormatter.SqlIdentifier("osmstatus") + " IS NULL) AND " + sqlFormatter.SqlIdentifier("osmaction") + " = 'create'"; using (ComReleaser comReleaser = new ComReleaser()) { searchCursor = revisionTable.Search(queryFilter, false); comReleaser.ManageLifetime(searchCursor); searchRowToUpdate = searchCursor.NextRow(); comReleaser.ManageLifetime(searchRowToUpdate); // if we have at least one entry with a create action, then add the 'create' element to the changeset representation if (searchRowToUpdate != null) { uploadCreates = new create(); listOfCreates = new List<object>(); } while (searchRowToUpdate != null) { try { if (TrackCancel.Continue() == false) { closeChangeSet(message, userCredentialGPValue.EncodedUserNamePassWord, secondsToTimeout, changeSetID, baseURLGPString); return; } string action = String.Empty; if (revActionFieldIndex != -1) { action = searchRowToUpdate.get_Value(revActionFieldIndex) as string; } string elementType = String.Empty; if (revElementTypeFieldIndex != -1) { elementType = searchRowToUpdate.get_Value(revElementTypeFieldIndex) as string; } string sourceFCName = String.Empty; if (revFCNameFieldIndex != -1) { sourceFCName = searchRowToUpdate.get_Value(revFCNameFieldIndex) as string; } long osmOldID = -1; if (revOldIDFieldIndex != -1) { osmOldID = Convert.ToInt64(searchRowToUpdate.get_Value(revOldIDFieldIndex)); } // if the overall number of uploaded elements is too big for a single changeset we do need to split it up // into multiple sets if (featureUpdateCounter > 0 & (featureUpdateCounter % maxElementsinChangeSet) == 0) { // add any outstanding creations to the changeset items if (listOfCreates != null && uploadCreates != null) { uploadCreates.Items = listOfCreates.ToArray(); // in case there are any creates let's add them to the changeset document changeSetItems.Add(uploadCreates); } // add all the changeset items to the changeset document osmChangeDocument.Items = changeSetItems.ToArray(); // submit changeset try { httpClient = HttpWebRequest.Create(baseURLGPString.Value + "/api/0.6/changeset/" + changeSetID + "/upload") as HttpWebRequest; httpClient = OSMGPDownload.AssignProxyandCredentials(httpClient); httpClient.Method = "POST"; SetBasicAuthHeader(httpClient, userCredentialGPValue.EncodedUserNamePassWord); httpClient.Timeout = secondsToTimeout * 1000; string sContent = OsmRest.SerializeUtils.CreateXmlSerializable(osmChangeDocument, null, Encoding.UTF8, "text/xml"); message.AddMessage(String.Format(resourceManager.GetString("GPTools_OSMGPUpload_featureSubmit"), featureUpdateCounter)); OsmRest.HttpUtils.Post(httpClient, sContent); httpResponse = httpClient.GetResponse() as HttpWebResponse; diffResult diffResultResonse = OsmRest.HttpUtils.GetResponse(httpResponse); // parse changes locally and update local data sources if (diffResultResonse != null) { ParseResultDiff(diffResultResonse, revisionTable, pointFeatureClass, lineFeatureClass, polygonFeatureClass, relationTable, user_displayname, userID, changeSetID, nodeosmIDLookup, wayosmIDLookup, relationosmIDLookup, internalExtensionVersion); } } catch (Exception ex) { closeChangeSet(message, userCredentialGPValue.EncodedUserNamePassWord, secondsToTimeout, changeSetID, baseURLGPString); message.AddError(120009, ex.Message); if (ex is WebException) { WebException webException = ex as WebException; string serverErrorMessage = webException.Response.Headers["Error"]; if (!String.IsNullOrEmpty(serverErrorMessage)) { message.AddError(120009, serverErrorMessage); } } if (httpResponse != null) { httpResponse.Close(); } return; } finally { // reset the list and containers of modifications for the next batch listOfCreates.Clear(); changeSetItems.Clear(); if (httpResponse != null) { httpResponse.Close(); } } if (TrackCancel.Continue() == false) { closeChangeSet(message, userCredentialGPValue.EncodedUserNamePassWord, secondsToTimeout, changeSetID, baseURLGPString); return; } CreateNextChangeSet(message, createChangeSetOSM, userCredentialGPValue.EncodedUserNamePassWord, secondsToTimeout, ref changeSetID, baseURLGPString, ref featureUpdateCounter); } switch (elementType) { case "node": node createNode = CreateNodeRepresentation(pointFeatureClass, action, osmOldID, changeSetID, 1, null, internalExtensionVersion); listOfCreates.Add(createNode); break; case "way": way createWay = null; if (sourceFCName.Contains("_osm_ln")) { createWay = CreateWayRepresentation(lineFeatureClass, action, osmOldID, changeSetID, 1, nodeosmIDLookup, pointFeatureClass, pointOSMIDFieldIndex, internalExtensionVersion); } else if (sourceFCName.Contains("_osm_ply")) { createWay = CreateWayRepresentation(polygonFeatureClass, action, osmOldID, changeSetID, 1, nodeosmIDLookup, pointFeatureClass, pointOSMIDFieldIndex, internalExtensionVersion); } listOfCreates.Add(createWay); break; case "relation": relation createRelation = null; if (sourceFCName.Contains("_osm_ln")) { createRelation = CreateRelationRepresentation((ITable)lineFeatureClass, action, osmOldID, changeSetID, 1, nodeosmIDLookup, wayosmIDLookup, relationosmIDLookup, internalExtensionVersion); } else if (sourceFCName.Contains("_osm_ply")) { createRelation = CreateRelationRepresentation((ITable)polygonFeatureClass, action, osmOldID, changeSetID, 1, nodeosmIDLookup, wayosmIDLookup, relationosmIDLookup, internalExtensionVersion); } else if (sourceFCName.Contains("_osm_relation")) { createRelation = CreateRelationRepresentation(relationTable, action, osmOldID, changeSetID, 1, nodeosmIDLookup, wayosmIDLookup, relationosmIDLookup, internalExtensionVersion); } listOfCreates.Add(createRelation); break; default: break; } // increment the counter keeping track of the submitted changes featureUpdateCounter = featureUpdateCounter + 1; } catch { } searchRowToUpdate = searchCursor.NextRow(); } if (listOfCreates != null && uploadCreates != null) { // sort the list of created elements in the order of nodes, ways, relations listOfCreates.Sort(new OSMElementComparer()); uploadCreates.Items = listOfCreates.ToArray(); // in case there are any creates let's add them to the changeset document changeSetItems.Add(uploadCreates); } } #endregion #region upload modify actions // loop through modifies using (ComReleaser comReleaser = new ComReleaser()) { queryFilter.WhereClause = "(" + sqlFormatter.SqlIdentifier("osmstatuscode") + " <> 200 OR " + sqlFormatter.SqlIdentifier("osmstatus") + " IS NULL) AND " + sqlFormatter.SqlIdentifier("osmaction") + " = 'modify'"; searchCursor = revisionTable.Search(queryFilter, false); comReleaser.ManageLifetime(searchCursor); searchRowToUpdate = searchCursor.NextRow(); if (searchRowToUpdate != null) { uploadModify = new modify(); listOfModifies = new List<object>(); } while (searchRowToUpdate != null) { if (TrackCancel.Continue() == false) { closeChangeSet(message, userCredentialGPValue.EncodedUserNamePassWord, secondsToTimeout, changeSetID, baseURLGPString); return; } try { string action = String.Empty; if (revActionFieldIndex != -1) { action = searchRowToUpdate.get_Value(revActionFieldIndex) as string; } string elementType = String.Empty; if (revElementTypeFieldIndex != -1) { elementType = searchRowToUpdate.get_Value(revElementTypeFieldIndex) as string; } string sourceFCName = String.Empty; if (revFCNameFieldIndex != -1) { sourceFCName = searchRowToUpdate.get_Value(revFCNameFieldIndex) as string; } long osmOldID = -1; if (revOldIDFieldIndex != -1) { osmOldID = Convert.ToInt64(searchRowToUpdate.get_Value(revOldIDFieldIndex)); } // if the overall number of uploaded elements is too big for a single changeset we do need to split it up long modifyID = -1; if (revNewIDFieldIndex != -1) { object osmIDValue = searchRowToUpdate.get_Value(revNewIDFieldIndex); if (osmIDValue == DBNull.Value) { osmIDValue = osmOldID; } try { modifyID = Convert.ToInt64(osmIDValue); } catch { } // modifies should only happen to osm IDs > 0 // if that condition is not met let's skip this feature as something is not right if (modifyID < 0) { searchRowToUpdate = searchCursor.NextRow(); continue; } } int osmVersion = -1; if (revVersionFieldIndex != -1) { osmVersion = Convert.ToInt32(searchRowToUpdate.get_Value(revVersionFieldIndex)); } // into multiple sets if ((featureUpdateCounter % maxElementsinChangeSet) == 0) { // add any outstanding modifications to the changeset items if (listOfModifies != null && uploadModify != null) { uploadModify.Items = listOfModifies.ToArray(); // in case there are any creates let's add them to the changeset document changeSetItems.Add(uploadModify); } // add all the changeset items to the changeset document osmChangeDocument.Items = changeSetItems.ToArray(); // submit changeset try { httpClient = HttpWebRequest.Create(baseURLGPString.Value + "/api/0.6/changeset/" + changeSetID + "/upload") as HttpWebRequest; httpClient = OSMGPDownload.AssignProxyandCredentials(httpClient); httpClient.Method = "POST"; SetBasicAuthHeader(httpClient, userCredentialGPValue.EncodedUserNamePassWord); httpClient.Timeout = secondsToTimeout * 1000; string sContent = OsmRest.SerializeUtils.CreateXmlSerializable(osmChangeDocument, null, Encoding.UTF8, "text/xml"); OsmRest.HttpUtils.Post(httpClient, sContent); httpResponse = httpClient.GetResponse() as HttpWebResponse; diffResult diffResultResonse = OsmRest.HttpUtils.GetResponse(httpResponse); // parse changes locally and update local data sources if (diffResultResonse != null) { ParseResultDiff(diffResultResonse, revisionTable, pointFeatureClass, lineFeatureClass, polygonFeatureClass, relationTable, user_displayname, userID, changeSetID, nodeosmIDLookup, wayosmIDLookup, relationosmIDLookup, internalExtensionVersion); } } catch (Exception ex) { closeChangeSet(message, userCredentialGPValue.EncodedUserNamePassWord, secondsToTimeout, changeSetID, baseURLGPString); message.AddError(120009, ex.Message); if (ex is WebException) { WebException webException = ex as WebException; string serverErrorMessage = webException.Response.Headers["Error"]; if (!String.IsNullOrEmpty(serverErrorMessage)) { message.AddError(120009, serverErrorMessage); } if (httpResponse != null) { httpResponse.Close(); } } return; } finally { // reset the list and containers of modifications for the next batch listOfModifies.Clear(); changeSetItems.Clear(); if (httpResponse != null) { httpResponse.Close(); } } if (TrackCancel.Continue() == false) { closeChangeSet(message, userCredentialGPValue.EncodedUserNamePassWord, secondsToTimeout, changeSetID, baseURLGPString); return; } CreateNextChangeSet(message, createChangeSetOSM, userCredentialGPValue.EncodedUserNamePassWord, secondsToTimeout, ref changeSetID, baseURLGPString, ref featureUpdateCounter); } switch (elementType) { case "node": node updateNode = CreateNodeRepresentation(pointFeatureClass, action, modifyID, changeSetID, osmVersion, null, internalExtensionVersion); listOfModifies.Add(updateNode); break; case "way": way updateWay = null; if (sourceFCName.Contains("_osm_ln")) { updateWay = CreateWayRepresentation(lineFeatureClass, action, modifyID, changeSetID, osmVersion, nodeosmIDLookup, pointFeatureClass, pointOSMIDFieldIndex, internalExtensionVersion); } else if (sourceFCName.Contains("_osm_ply")) { updateWay = CreateWayRepresentation(polygonFeatureClass, action, modifyID, changeSetID, osmVersion, nodeosmIDLookup, pointFeatureClass, pointOSMIDFieldIndex, internalExtensionVersion); } listOfModifies.Add(updateWay); break; case "relation": relation updateRelation = null; if (sourceFCName.Contains("_osm_ln")) { updateRelation = CreateRelationRepresentation((ITable)lineFeatureClass, action, modifyID, changeSetID, osmVersion, nodeosmIDLookup, wayosmIDLookup, relationosmIDLookup, internalExtensionVersion); } else if (sourceFCName.Contains("_osm_ply")) { updateRelation = CreateRelationRepresentation((ITable)polygonFeatureClass, action, modifyID, changeSetID, osmVersion, nodeosmIDLookup, wayosmIDLookup, relationosmIDLookup, internalExtensionVersion); } else if (sourceFCName.Contains("_osm_relation")) { updateRelation = CreateRelationRepresentation(relationTable, action, modifyID, changeSetID, osmVersion, nodeosmIDLookup, wayosmIDLookup, relationosmIDLookup, internalExtensionVersion); } listOfModifies.Add(updateRelation); break; default: break; } // track the update/sync requests against the server featureUpdateCounter = featureUpdateCounter + 1; } catch { } searchRowToUpdate = searchCursor.NextRow(); } if (listOfModifies != null && uploadModify != null) { uploadModify.Items = listOfModifies.ToArray(); // in case there are any creates let's add them to the changeset document changeSetItems.Add(uploadModify); } } #endregion #region upload delete actions // loop through deletes in "reverse" - relation, then way, then node string[] elementTypes = new string[] { "relation", "way", "node" }; foreach (string osmElementType in elementTypes) { using (ComReleaser comReleaser = new ComReleaser()) { queryFilter.WhereClause = "(" + sqlFormatter.SqlIdentifier("osmstatuscode") + " <> 200 OR " + sqlFormatter.SqlIdentifier("osmstatus") + " IS NULL) AND " + sqlFormatter.SqlIdentifier("osmaction") + " = 'delete' AND " + sqlFormatter.SqlIdentifier("osmelementtype") + " = '" + osmElementType + "'"; searchCursor = revisionTable.Search(queryFilter, false); comReleaser.ManageLifetime(searchCursor); searchRowToUpdate = searchCursor.NextRow(); if (searchRowToUpdate != null) { if (TrackCancel.Continue() == false) { closeChangeSet(message, userCredentialGPValue.EncodedUserNamePassWord, secondsToTimeout, changeSetID, baseURLGPString); return; } if (uploadDelete == null) { uploadDelete = new delete(); listOfDeletes = new List<object>(); } } while (searchRowToUpdate != null) { try { string action = String.Empty; if (revActionFieldIndex != -1) { action = searchRowToUpdate.get_Value(revActionFieldIndex) as string; } string elementType = String.Empty; if (revElementTypeFieldIndex != -1) { elementType = searchRowToUpdate.get_Value(revElementTypeFieldIndex) as string; } string sourceFCName = String.Empty; if (revFCNameFieldIndex != -1) { sourceFCName = searchRowToUpdate.get_Value(revFCNameFieldIndex) as string; } long osmOldID = -1; if (revOldIDFieldIndex != -1) { osmOldID = Convert.ToInt64(searchRowToUpdate.get_Value(revOldIDFieldIndex)); } int osmVersion = -1; if (revVersionFieldIndex != -1) { osmVersion = Convert.ToInt32(searchRowToUpdate.get_Value(revVersionFieldIndex)); } // into multiple sets if ((featureUpdateCounter % maxElementsinChangeSet) == 0) { // add any outstanding creations to the changeset items if (listOfDeletes != null && uploadDelete != null) { uploadDelete.Items = listOfDeletes.ToArray(); // in case there are any creates let's add them to the changeset document changeSetItems.Add(uploadDelete); } // add all the changeset items to the changeset document osmChangeDocument.Items = changeSetItems.ToArray(); // submit changeset try { httpClient = HttpWebRequest.Create(baseURLGPString.Value + "/api/0.6/changeset/" + changeSetID + "/upload") as HttpWebRequest; httpClient = OSMGPDownload.AssignProxyandCredentials(httpClient); httpClient.Method = "POST"; SetBasicAuthHeader(httpClient, userCredentialGPValue.EncodedUserNamePassWord); httpClient.Timeout = secondsToTimeout * 1000; string sContent = OsmRest.SerializeUtils.CreateXmlSerializable(osmChangeDocument, null, Encoding.UTF8, "text/xml"); OsmRest.HttpUtils.Post(httpClient, sContent); httpResponse = httpClient.GetResponse() as HttpWebResponse; diffResult diffResultResonse = OsmRest.HttpUtils.GetResponse(httpResponse); // parse changes locally and update local data sources if (diffResultResonse != null) { ParseResultDiff(diffResultResonse, revisionTable, pointFeatureClass, lineFeatureClass, polygonFeatureClass, relationTable, user_displayname, userID, changeSetID, nodeosmIDLookup, wayosmIDLookup, relationosmIDLookup, internalExtensionVersion); } } catch (Exception ex) { closeChangeSet(message, userCredentialGPValue.EncodedUserNamePassWord, secondsToTimeout, changeSetID, baseURLGPString); message.AddError(120009, ex.Message); if (ex is WebException) { WebException webException = ex as WebException; string serverErrorMessage = webException.Response.Headers["Error"]; if (!String.IsNullOrEmpty(serverErrorMessage)) { message.AddError(120009, serverErrorMessage); } } if (httpResponse != null) { httpResponse.Close(); } return; } finally { // reset the list and containers of modifications for the next batch listOfDeletes.Clear(); changeSetItems.Clear(); if (httpResponse != null) { httpResponse.Close(); } } if (TrackCancel.Continue() == false) { closeChangeSet(message, userCredentialGPValue.EncodedUserNamePassWord, secondsToTimeout, changeSetID, baseURLGPString); return; } CreateNextChangeSet(message, createChangeSetOSM, userCredentialGPValue.EncodedUserNamePassWord, secondsToTimeout, ref changeSetID, baseURLGPString, ref featureUpdateCounter); } switch (elementType) { case "node": IPoint deletePoint = null; if (revLongitudeFieldIndex != -1 && revLatitudeFieldIndex != -1) { try { // let's reconstruct the delete point deletePoint = new PointClass(); deletePoint.X = Convert.ToDouble(searchRowToUpdate.get_Value(revLongitudeFieldIndex)); deletePoint.Y = Convert.ToDouble(searchRowToUpdate.get_Value(revLatitudeFieldIndex)); deletePoint.SpatialReference = m_wgs84; } catch (Exception ex) { message.AddWarning(ex.Message); } if (deletePoint == null) { // inform the about the issue - no successful creation of point and continue on to the next delete instruction // in the revision table message.AddWarning(resourceManager.GetString("GPTools_OSMGPUpload_invalidPoint")); searchRowToUpdate = searchCursor.NextRow(); continue; } } node deleteNode = CreateNodeRepresentation(pointFeatureClass, action, osmOldID, changeSetID, osmVersion, deletePoint, internalExtensionVersion); listOfDeletes.Add(deleteNode); break; case "way": way deleteWay = null; if (sourceFCName.Contains("_osm_ln")) { deleteWay = CreateWayRepresentation(lineFeatureClass, action, osmOldID, changeSetID, osmVersion, nodeosmIDLookup, pointFeatureClass, pointOSMIDFieldIndex, internalExtensionVersion); } else if (sourceFCName.Contains("_osm_ply")) { deleteWay = CreateWayRepresentation(polygonFeatureClass, action, osmOldID, changeSetID, osmVersion, nodeosmIDLookup, pointFeatureClass, pointOSMIDFieldIndex, internalExtensionVersion); } listOfDeletes.Add(deleteWay); break; case "relation": relation deleteRelation = null; if (sourceFCName.Contains("_osm_ln")) { deleteRelation = CreateRelationRepresentation((ITable)lineFeatureClass, action, osmOldID, changeSetID, osmVersion, nodeosmIDLookup, wayosmIDLookup, relationosmIDLookup, internalExtensionVersion); } else if (sourceFCName.Contains("_osm_ply")) { deleteRelation = CreateRelationRepresentation((ITable)polygonFeatureClass, action, osmOldID, changeSetID, osmVersion, nodeosmIDLookup, wayosmIDLookup, relationosmIDLookup, internalExtensionVersion); } else if (sourceFCName.Contains("_osm_relation")) { deleteRelation = CreateRelationRepresentation(relationTable, action, osmOldID, changeSetID, osmVersion, nodeosmIDLookup, wayosmIDLookup, relationosmIDLookup, internalExtensionVersion); } listOfDeletes.Add(deleteRelation); break; default: break; } // track the update/sync requests against the server featureUpdateCounter = featureUpdateCounter + 1; } catch { } searchRowToUpdate = searchCursor.NextRow(); } } } if (listOfDeletes != null && uploadDelete != null) { uploadDelete.Items = listOfDeletes.ToArray(); // in case there are any creates let's add them to the changeset document changeSetItems.Add(uploadDelete); } #endregion if (TrackCancel.Continue() == false) { closeChangeSet(message, userCredentialGPValue.EncodedUserNamePassWord, secondsToTimeout, changeSetID, baseURLGPString); return; } // add all the changeset items to the changeset document osmChangeDocument.Items = changeSetItems.ToArray(); // submit changeset try { httpClient = HttpWebRequest.Create(baseURLGPString.Value + "/api/0.6/changeset/" + changeSetID + "/upload") as HttpWebRequest; httpClient = OSMGPDownload.AssignProxyandCredentials(httpClient); httpClient.Method = "POST"; SetBasicAuthHeader(httpClient, userCredentialGPValue.EncodedUserNamePassWord); httpClient.Timeout = secondsToTimeout * 1000; message.AddMessage(String.Format(resourceManager.GetString("GPTools_OSMGPUpload_featureSubmit"), featureUpdateCounter)); string sContent = OsmRest.SerializeUtils.CreateXmlSerializable(osmChangeDocument, null, Encoding.UTF8, "text/xml"); OsmRest.HttpUtils.Post(httpClient, sContent); httpResponse = httpClient.GetResponse() as HttpWebResponse; //Exception with an error HTTP 400 diffResult diffResultResonse = OsmRest.HttpUtils.GetResponse(httpResponse); message.AddMessage(resourceManager.GetString("GPTools_OSMGPUpload_updatelocalData")); // parse changes locally and update local data sources if (diffResultResonse != null) { ParseResultDiff(diffResultResonse, revisionTable, pointFeatureClass, lineFeatureClass, polygonFeatureClass, relationTable, user_displayname, userID, changeSetID, nodeosmIDLookup, wayosmIDLookup, relationosmIDLookup, internalExtensionVersion); } } catch (Exception ex) { message.AddError(120009, ex.Message); try { if (ex is WebException) { WebException webException = ex as WebException; string serverErrorMessage = webException.Response.Headers["Error"]; if (!String.IsNullOrEmpty(serverErrorMessage)) { message.AddError(120009, serverErrorMessage); } } } catch (Exception innerexception) { message.AddError(120009, innerexception.Message); } } finally { if (httpResponse != null) { httpResponse.Close(); } } #endregion } else { #region single upload format #region submit the create nodes first queryFilter.WhereClause = "(" + sqlFormatter.SqlIdentifier("osmstatuscode") + " <> 200 OR " + sqlFormatter.SqlIdentifier("osmstatus") + " IS NULL) AND " + sqlFormatter.SqlIdentifier("osmaction") + " = 'create' AND " + sqlFormatter.SqlIdentifier("osmelementtype") + " = 'node'"; using (ComReleaser comReleaser = new ComReleaser()) { searchCursor = revisionTable.Search(queryFilter, false); comReleaser.ManageLifetime(searchCursor); while ((searchRowToUpdate = searchCursor.NextRow()) != null) { try { string action = String.Empty; if (revActionFieldIndex != -1) { action = searchRowToUpdate.get_Value(revActionFieldIndex) as string; } string elementType = String.Empty; if (revElementTypeFieldIndex != -1) { elementType = searchRowToUpdate.get_Value(revElementTypeFieldIndex) as string; } string sourceFCName = String.Empty; if (revFCNameFieldIndex != -1) { sourceFCName = searchRowToUpdate.get_Value(revFCNameFieldIndex) as string; } long osmOldID = -1; if (revOldIDFieldIndex != -1) { osmOldID = Convert.ToInt64(searchRowToUpdate.get_Value(revOldIDFieldIndex)); } // if the overall number of uploaded elements is too big for a single changeset we do need to split it up // into multiple sets if ((featureUpdateCounter % maxElementsinChangeSet) == 0) { CreateNextChangeSet(message, createChangeSetOSM, userCredentialGPValue.EncodedUserNamePassWord, secondsToTimeout, ref changeSetID, baseURLGPString, ref featureUpdateCounter); } osm createNode = CreateOSMNodeRepresentation(pointFeatureClass, action, osmOldID, changeSetID, -1, null, internalExtensionVersion); httpClient = null; httpClient = HttpWebRequest.Create(baseURLGPString.Value + "/api/0.6/" + elementType + "/create") as HttpWebRequest; httpClient = OSMGPDownload.AssignProxyandCredentials(httpClient); httpClient.Method = "PUT"; SetBasicAuthHeader(httpClient, userCredentialGPValue.EncodedUserNamePassWord); httpClient.Timeout = secondsToTimeout * 1000; httpResponse = null; string nodeContent = OsmRest.SerializeUtils.CreateXmlSerializable(createNode, serializer, Encoding.UTF8, "text/xml"); if (String.IsNullOrEmpty(nodeContent)) { continue; } OsmRest.HttpUtils.Put(httpClient, nodeContent); httpResponse = httpClient.GetResponse() as HttpWebResponse; createNode = null; // track the update/sync requests against the server featureUpdateCounter = featureUpdateCounter + 1; if (httpResponse != null) { string newIDString = OsmRest.HttpUtils.GetResponseContent(httpResponse); nodeosmIDLookup.Add(osmOldID, Convert.ToInt64(newIDString)); // update the revision table if (revNewIDFieldIndex != -1) { searchRowToUpdate.set_Value(revNewIDFieldIndex, Convert.ToString(newIDString)); } if (revVersionFieldIndex != -1) { searchRowToUpdate.set_Value(revVersionFieldIndex, 1); } if (revStatusFieldIndex != -1) { searchRowToUpdate.set_Value(revStatusFieldIndex, httpResponse.StatusCode.ToString()); } if (revStatusCodeFieldIndex != -1) { searchRowToUpdate.set_Value(revStatusCodeFieldIndex, (int)httpResponse.StatusCode); } if (revChangeSetIDFieldIndex != -1) { searchRowToUpdate.set_Value(revChangeSetIDFieldIndex, Convert.ToString(changeSetID)); } // update the source point feature class as well updateSource((ITable)pointFeatureClass, action, osmOldID, Convert.ToInt64(newIDString), user_displayname, userID, 1, Convert.ToInt32(changeSetID), nodeosmIDLookup, wayosmIDLookup, relationosmIDLookup,internalExtensionVersion); } } catch (Exception ex) { message.AddError(120009, ex.Message); if (ex is WebException) { updateErrorStatus(message, revStatusFieldIndex, revStatusCodeFieldIndex, revErrorMessageFieldIndex, ref searchRowToUpdate, ex); } } finally { try { searchRowToUpdate.Store(); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.Message); } if (httpResponse != null) { httpResponse.Close(); } } if (TrackCancel.Continue() == false) { closeChangeSet(message, userCredentialGPValue.EncodedUserNamePassWord, secondsToTimeout, changeSetID, baseURLGPString); return; } } } #endregion #region next the create ways queryFilter.WhereClause = "(" + sqlFormatter.SqlIdentifier("osmstatuscode") + " <> 200 OR " + sqlFormatter.SqlIdentifier("osmstatus") + " IS NULL) AND " + sqlFormatter.SqlIdentifier("osmaction") + " = 'create' AND " + sqlFormatter.SqlIdentifier("osmelementtype") + " = 'way'"; using (ComReleaser comReleaser = new ComReleaser()) { searchCursor = revisionTable.Search(queryFilter, false); comReleaser.ManageLifetime(searchCursor); while ((searchRowToUpdate = searchCursor.NextRow()) != null) { try { string action = String.Empty; if (revActionFieldIndex != -1) { action = searchRowToUpdate.get_Value(revActionFieldIndex) as string; } string elementType = String.Empty; if (revElementTypeFieldIndex != -1) { elementType = searchRowToUpdate.get_Value(revElementTypeFieldIndex) as string; } string sourceFCName = String.Empty; if (revFCNameFieldIndex != -1) { sourceFCName = searchRowToUpdate.get_Value(revFCNameFieldIndex) as string; } long osmOldID = -1; if (revOldIDFieldIndex != -1) { osmOldID = Convert.ToInt64(searchRowToUpdate.get_Value(revOldIDFieldIndex)); } bool isPolygon = false; if (sourceFCName.IndexOf("_osm_ply") > -1) { isPolygon = true; } // if the overall number of uploaded elements is too big for a single changeset we do need to split it up // into multiple sets if ((featureUpdateCounter % maxElementsinChangeSet) == 0) { CreateNextChangeSet(message, createChangeSetOSM, userCredentialGPValue.EncodedUserNamePassWord, secondsToTimeout, ref changeSetID, baseURLGPString, ref featureUpdateCounter); } osm createWay = new osm(); if (isPolygon == false) { createWay = CreateOSMWayRepresentation(lineFeatureClass, action, osmOldID, changeSetID, -1, nodeosmIDLookup, pointFeatureClass, pointOSMIDFieldIndex, internalExtensionVersion); } else { createWay = CreateOSMWayRepresentation(polygonFeatureClass, action, osmOldID, changeSetID, -1, nodeosmIDLookup, pointFeatureClass, pointOSMIDFieldIndex, internalExtensionVersion); } try { HttpWebRequest httpClient3 = HttpWebRequest.Create(baseURLGPString.Value + "/api/0.6/" + elementType + "/create") as HttpWebRequest; httpClient3 = OSMGPDownload.AssignProxyandCredentials(httpClient3); httpClient3.Method = "PUT"; SetBasicAuthHeader(httpClient3, userCredentialGPValue.EncodedUserNamePassWord); httpClient.Timeout = secondsToTimeout * 1000; string sContent = OsmRest.SerializeUtils.CreateXmlSerializable(createWay, serializer, Encoding.UTF8, "text/xml"); OsmRest.HttpUtils.Put(httpClient3, sContent); createWay = null; httpResponse = null; httpResponse = httpClient3.GetResponse() as HttpWebResponse; // track the update/sync requests against the server featureUpdateCounter = featureUpdateCounter + 1; } catch (Exception ex) { message.AddError(120009, ex.Message); if (ex is WebException) { updateErrorStatus(message, revStatusFieldIndex, revStatusCodeFieldIndex, revErrorMessageFieldIndex, ref searchRowToUpdate, ex); } } if (httpResponse != null) { string newIDString = OsmRest.HttpUtils.GetResponseContent(httpResponse); wayosmIDLookup.Add(osmOldID, Convert.ToInt64(newIDString)); // update the revision table if (revNewIDFieldIndex != -1) { searchRowToUpdate.set_Value(revNewIDFieldIndex, Convert.ToString(newIDString)); } if (revVersionFieldIndex != -1) { searchRowToUpdate.set_Value(revVersionFieldIndex, 1); } if (revStatusFieldIndex != -1) { searchRowToUpdate.set_Value(revStatusFieldIndex, httpResponse.StatusCode.ToString()); } if (revStatusCodeFieldIndex != -1) { searchRowToUpdate.set_Value(revStatusCodeFieldIndex, (int)httpResponse.StatusCode); } if (revChangeSetIDFieldIndex != -1) { searchRowToUpdate.set_Value(revChangeSetIDFieldIndex, Convert.ToString(changeSetID)); } // update the source line/polygon feature class as well if (isPolygon == false) { updateSource((ITable)lineFeatureClass, action, osmOldID, Convert.ToInt64(newIDString), user_displayname, userID, 1, Convert.ToInt32(changeSetID), nodeosmIDLookup, wayosmIDLookup, relationosmIDLookup, internalExtensionVersion); } else { updateSource((ITable)polygonFeatureClass, action, osmOldID, Convert.ToInt64(newIDString), user_displayname, userID, 1, Convert.ToInt32(changeSetID), nodeosmIDLookup, wayosmIDLookup, relationosmIDLookup, internalExtensionVersion); } } } catch (Exception ex) { message.AddError(120009, ex.Message); if (ex is WebException) { updateErrorStatus(message, revStatusFieldIndex, revStatusCodeFieldIndex, revErrorMessageFieldIndex, ref searchRowToUpdate, ex); } } finally { try { searchRowToUpdate.Store(); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.Message); } if (httpResponse != null) { httpResponse.Close(); } } if (TrackCancel.Continue() == false) { closeChangeSet(message, userCredentialGPValue.EncodedUserNamePassWord, secondsToTimeout, changeSetID, baseURLGPString); return; } } } #endregion #region and then create relations queryFilter.WhereClause = "(" + sqlFormatter.SqlIdentifier("osmstatuscode") + " <> 200 OR " + sqlFormatter.SqlIdentifier("osmstatus") + " IS NULL) AND " + sqlFormatter.SqlIdentifier("osmaction") + " = 'create' AND " + sqlFormatter.SqlIdentifier("osmelementtype") + " = 'relation'"; using (ComReleaser comReleaser = new ComReleaser()) { searchCursor = revisionTable.Search(queryFilter, false); comReleaser.ManageLifetime(searchCursor); while ((searchRowToUpdate = searchCursor.NextRow()) != null) { try { string action = String.Empty; if (revActionFieldIndex != -1) { action = searchRowToUpdate.get_Value(revActionFieldIndex) as string; } string elementType = String.Empty; if (revElementTypeFieldIndex != -1) { elementType = searchRowToUpdate.get_Value(revElementTypeFieldIndex) as string; } string sourceFCName = String.Empty; if (revFCNameFieldIndex != -1) { sourceFCName = searchRowToUpdate.get_Value(revFCNameFieldIndex) as string; } long osmOldID = -1; if (revOldIDFieldIndex != -1) { osmOldID = Convert.ToInt64(searchRowToUpdate.get_Value(revOldIDFieldIndex)); } bool isPolygon = false; if (sourceFCName.IndexOf("_osm_ply") > -1) { isPolygon = true; } // if the overall number of uploaded elements is too big for a single changeset we do need to split it up // into multiple sets if ((featureUpdateCounter % maxElementsinChangeSet) == 0) { CreateNextChangeSet(message, createChangeSetOSM, userCredentialGPValue.EncodedUserNamePassWord, secondsToTimeout, ref changeSetID, baseURLGPString, ref featureUpdateCounter); } osm createRelation = null; // the relation is acutally multi-part line if (sourceFCName.Contains("_osm_ln")) { createRelation = CreateOSMRelationRepresentation((ITable)lineFeatureClass, action, osmOldID, changeSetID, -1, nodeosmIDLookup, wayosmIDLookup, relationosmIDLookup, internalExtensionVersion); } else if (sourceFCName.Contains("_osm_ply")) { createRelation = CreateOSMRelationRepresentation((ITable)polygonFeatureClass, action, osmOldID, changeSetID, -1, nodeosmIDLookup, wayosmIDLookup, relationosmIDLookup, internalExtensionVersion); } else { createRelation = CreateOSMRelationRepresentation(relationTable, action, osmOldID, changeSetID, -1, nodeosmIDLookup, wayosmIDLookup, relationosmIDLookup, internalExtensionVersion); } try { HttpWebRequest httpClient4 = HttpWebRequest.Create(baseURLGPString.Value + "/api/0.6/" + elementType + "/create") as HttpWebRequest; httpClient4 = OSMGPDownload.AssignProxyandCredentials(httpClient4); SetBasicAuthHeader(httpClient4, userCredentialGPValue.EncodedUserNamePassWord); httpClient4.Timeout = secondsToTimeout * 1000; string sContent = OsmRest.SerializeUtils.CreateXmlSerializable(createRelation, serializer, Encoding.UTF8, "text/xml"); OsmRest.HttpUtils.Put(httpClient4, sContent); httpResponse = null; httpResponse = httpClient4.GetResponse() as HttpWebResponse; // track the update/sync requests against the server featureUpdateCounter = featureUpdateCounter + 1; } catch (Exception ex) { message.AddError(120009, ex.Message); if (ex is WebException) { updateErrorStatus(message, revStatusFieldIndex, revStatusCodeFieldIndex, revErrorMessageFieldIndex, ref searchRowToUpdate, ex); } } if (httpResponse != null) { string newIDString = OsmRest.HttpUtils.GetResponseContent(httpResponse); relationosmIDLookup.Add(osmOldID, Convert.ToInt64(newIDString)); // update the revision table if (revNewIDFieldIndex != -1) { searchRowToUpdate.set_Value(revNewIDFieldIndex, Convert.ToString(newIDString)); } if (revVersionFieldIndex != -1) { searchRowToUpdate.set_Value(revVersionFieldIndex, 1); } if (revStatusFieldIndex != -1) { searchRowToUpdate.set_Value(revStatusFieldIndex, httpResponse.StatusCode.ToString()); } if (revStatusCodeFieldIndex != -1) { searchRowToUpdate.set_Value(revStatusCodeFieldIndex, (int)httpResponse.StatusCode); } if (revChangeSetIDFieldIndex != -1) { searchRowToUpdate.set_Value(revChangeSetIDFieldIndex, Convert.ToInt32(changeSetID)); } if (sourceFCName.Contains("_osm_ln")) { updateSource((ITable)lineFeatureClass, action, osmOldID, Convert.ToInt64(newIDString), user_displayname, userID, 1, Convert.ToInt32(changeSetID), nodeosmIDLookup, wayosmIDLookup, relationosmIDLookup, internalExtensionVersion); } else if (sourceFCName.Contains("_osm_ply")) { updateSource((ITable)polygonFeatureClass, action, osmOldID, Convert.ToInt64(newIDString), user_displayname, userID, 1, Convert.ToInt32(changeSetID), nodeosmIDLookup, wayosmIDLookup, relationosmIDLookup, internalExtensionVersion); } else { // update the source table holding the relation information class as well updateSource(relationTable, action, osmOldID, Convert.ToInt64(newIDString), user_displayname, userID, 1, Convert.ToInt32(changeSetID), nodeosmIDLookup, wayosmIDLookup, relationosmIDLookup, internalExtensionVersion); } } } catch (Exception ex) { message.AddError(120009, ex.Message); if (ex is WebException) { updateErrorStatus(message, revStatusFieldIndex, revStatusCodeFieldIndex, revErrorMessageFieldIndex, ref searchRowToUpdate, ex); } } finally { try { searchRowToUpdate.Store(); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.Message); } } if (TrackCancel.Continue() == false) { closeChangeSet(message, userCredentialGPValue.EncodedUserNamePassWord, secondsToTimeout, changeSetID, baseURLGPString); return; } } } #endregion #region after that submit the modify node, way, relation using (ComReleaser comReleaser = new ComReleaser()) { queryFilter.WhereClause = "(" + sqlFormatter.SqlIdentifier("osmstatuscode") + " <> 200 OR " + sqlFormatter.SqlIdentifier("osmstatus") + " IS NULL) AND " + sqlFormatter.SqlIdentifier("osmaction") + " = 'modify'"; searchCursor = revisionTable.Search(queryFilter, false); comReleaser.ManageLifetime(searchCursor); while ((searchRowToUpdate = searchCursor.NextRow()) != null) { try { string action = String.Empty; if (revActionFieldIndex != -1) { action = searchRowToUpdate.get_Value(revActionFieldIndex) as string; } string elementType = String.Empty; if (revElementTypeFieldIndex != -1) { elementType = searchRowToUpdate.get_Value(revElementTypeFieldIndex) as string; } string sourceFCName = String.Empty; if (revFCNameFieldIndex != -1) { sourceFCName = searchRowToUpdate.get_Value(revFCNameFieldIndex) as string; } long osmOldID = -1; if (revOldIDFieldIndex != -1) { osmOldID = Convert.ToInt64(searchRowToUpdate.get_Value(revOldIDFieldIndex)); } // if the overall number of uploaded elements is too big for a single changeset we do need to split it up // into multiple sets if ((featureUpdateCounter % maxElementsinChangeSet) == 0) { CreateNextChangeSet(message, createChangeSetOSM, userCredentialGPValue.EncodedUserNamePassWord, secondsToTimeout, ref changeSetID, baseURLGPString, ref featureUpdateCounter); } switch (elementType) { case "node": #region submit nodes to OSM server switch (action) { case "modify": long modifyID = -1; if (revNewIDFieldIndex != -1) { object osmIDValue = searchRowToUpdate.get_Value(revNewIDFieldIndex); if (osmIDValue == DBNull.Value) { osmIDValue = osmOldID; } try { modifyID = Convert.ToInt64(osmIDValue); } catch { } // modifies should only happen to osm IDs > 0 // if that condition is not met let's skip this feature as something is not right if (modifyID < 0) { continue; } } int osmVersion = -1; if (revVersionFieldIndex != -1) { osmVersion = Convert.ToInt32(searchRowToUpdate.get_Value(revVersionFieldIndex)); } try { HttpWebRequest httpClient5 = HttpWebRequest.Create(baseURLGPString.Value + "/api/0.6/" + elementType + "/" + modifyID.ToString()) as HttpWebRequest; httpClient5 = OSMGPDownload.AssignProxyandCredentials(httpClient5); SetBasicAuthHeader(httpClient5, userCredentialGPValue.EncodedUserNamePassWord); osm updateNode = CreateOSMNodeRepresentation(pointFeatureClass, action, modifyID, changeSetID, osmVersion, null, internalExtensionVersion); string sContent = OsmRest.SerializeUtils.CreateXmlSerializable(updateNode, serializer, Encoding.UTF8, "text/xml"); // if the serialized node at this time is a null or an empty string let's continue to the next point if (String.IsNullOrEmpty(sContent)) { continue; } OsmRest.HttpUtils.Put(httpClient5, sContent); httpResponse = httpClient5.GetResponse() as HttpWebResponse; // track the update/sync requests against the server featureUpdateCounter = featureUpdateCounter + 1; if (httpResponse != null) { string newVersionString = OsmRest.HttpUtils.GetResponseContent(httpResponse); // update the revision table if (revVersionFieldIndex != -1) { searchRowToUpdate.set_Value(revVersionFieldIndex, Convert.ToString(newVersionString)); } if (revStatusFieldIndex != -1) { searchRowToUpdate.set_Value(revStatusFieldIndex, httpResponse.StatusCode.ToString()); } if (revStatusCodeFieldIndex != -1) { searchRowToUpdate.set_Value(revStatusCodeFieldIndex, (int)httpResponse.StatusCode); } if (revChangeSetIDFieldIndex != -1) { searchRowToUpdate.set_Value(revChangeSetIDFieldIndex, Convert.ToInt32(changeSetID)); } // for a modify the old id is still the new id if (revNewIDFieldIndex != -1 && revOldIDFieldIndex != -1) { searchRowToUpdate.set_Value(revNewIDFieldIndex, searchRowToUpdate.get_Value(revOldIDFieldIndex)); } // update the source point feature class as well updateSource((ITable)pointFeatureClass, action, modifyID, modifyID, user_displayname, userID, Convert.ToInt32(newVersionString), Convert.ToInt32(changeSetID), null, null, null, internalExtensionVersion); httpResponse.Close(); } } catch (Exception ex) { message.AddError(120009, ex.Message); if (ex is WebException) { updateErrorStatus(message, revStatusFieldIndex, revStatusCodeFieldIndex, revErrorMessageFieldIndex, ref searchRowToUpdate, ex); } } break; case "delete": // the delete operations are handled separately break; default: break; } break; #endregion case "way": #region submit ways to the OSM server // determine if we have a polygon or a polyline feature class bool isPolygon = false; if (sourceFCName.IndexOf("_osm_ply") > -1) { isPolygon = true; } switch (action) { case "modify": long modifyID = -1; if (revNewIDFieldIndex != -1) { object osmIDValue = searchRowToUpdate.get_Value(revNewIDFieldIndex); if (osmIDValue == DBNull.Value) { osmIDValue = osmOldID; } try { modifyID = Convert.ToInt64(osmIDValue); } catch { } // modifies should only happen to osm IDs > 0 // if that condition is not met let's skip this feature as something is not right if (modifyID < 0) { continue; } } int osmVersion = -1; if (revVersionFieldIndex != -1) { osmVersion = Convert.ToInt32(searchRowToUpdate.get_Value(revVersionFieldIndex)); } osm updateWay = new osm(); if (isPolygon == false) { updateWay = CreateOSMWayRepresentation(lineFeatureClass, action, modifyID, changeSetID, osmVersion, nodeosmIDLookup, pointFeatureClass, pointOSMIDFieldIndex, internalExtensionVersion); } else { updateWay = CreateOSMWayRepresentation(polygonFeatureClass, action, modifyID, changeSetID, osmVersion, nodeosmIDLookup, pointFeatureClass, pointOSMIDFieldIndex, internalExtensionVersion); } try { string sContent = OsmRest.SerializeUtils.CreateXmlSerializable(updateWay, serializer, Encoding.UTF8, "text/xml"); httpClient = HttpWebRequest.Create(baseURLGPString.Value + "/api/0.6/" + elementType + "/" + modifyID.ToString()) as HttpWebRequest; httpClient = OSMGPDownload.AssignProxyandCredentials(httpClient); SetBasicAuthHeader(httpClient, userCredentialGPValue.EncodedUserNamePassWord); OsmRest.HttpUtils.Put(httpClient, sContent); httpResponse = httpClient.GetResponse() as HttpWebResponse; // track the update/sync requests against the server featureUpdateCounter = featureUpdateCounter + 1; if (httpResponse != null) { string newVersionString = OsmRest.HttpUtils.GetResponseContent(httpResponse); // update the revision table if (revVersionFieldIndex != -1) { searchRowToUpdate.set_Value(revVersionFieldIndex, Convert.ToString(newVersionString)); } if (revStatusFieldIndex != -1) { searchRowToUpdate.set_Value(revStatusFieldIndex, httpResponse.StatusCode.ToString()); } if (revStatusCodeFieldIndex != -1) { searchRowToUpdate.set_Value(revStatusCodeFieldIndex, (int)httpResponse.StatusCode); } if (revChangeSetIDFieldIndex != -1) { searchRowToUpdate.set_Value(revChangeSetIDFieldIndex, Convert.ToInt32(changeSetID)); } // for a modify the old id is still the new id if (revNewIDFieldIndex != -1 && revOldIDFieldIndex != -1) { searchRowToUpdate.set_Value(revNewIDFieldIndex, searchRowToUpdate.get_Value(revOldIDFieldIndex)); } // update the source line/polygon feature class as well if (isPolygon == false) { updateSource((ITable)lineFeatureClass, action, modifyID, modifyID, user_displayname, userID, Convert.ToInt32(newVersionString), Convert.ToInt32(changeSetID), nodeosmIDLookup, wayosmIDLookup, relationosmIDLookup, internalExtensionVersion); } else { updateSource((ITable)polygonFeatureClass, action, modifyID, modifyID, user_displayname, userID, Convert.ToInt32(newVersionString), Convert.ToInt32(changeSetID), nodeosmIDLookup, wayosmIDLookup, relationosmIDLookup, internalExtensionVersion); } httpResponse.Close(); } } catch (Exception ex) { message.AddError(120009, ex.Message); if (ex is WebException) { updateErrorStatus(message, revStatusFieldIndex, revStatusCodeFieldIndex, revErrorMessageFieldIndex, ref searchRowToUpdate, ex); } } break; case "delete": // the delete operations are handled separately break; default: break; } break; #endregion case "relation": #region submit relations to the OSM server switch (action) { case "create": break; case "modify": long modifyID = -1; if (revNewIDFieldIndex != -1) { object osmIDValue = searchRowToUpdate.get_Value(revNewIDFieldIndex); if (osmIDValue == DBNull.Value) { osmIDValue = osmOldID; } try { modifyID = Convert.ToInt64(osmIDValue); } catch { } // modifies should only happen to osm IDs > 0 // if that condition is not met let's skip this feature as something is not right if (modifyID < 0) { continue; } } int osmVersion = -1; if (revVersionFieldIndex != -1) { osmVersion = Convert.ToInt32(searchRowToUpdate.get_Value(revVersionFieldIndex)); } osm updateRelation = CreateOSMRelationRepresentation(relationTable, action, modifyID, changeSetID, osmVersion, nodeosmIDLookup, wayosmIDLookup, relationosmIDLookup, internalExtensionVersion); try { string sContent = OsmRest.SerializeUtils.CreateXmlSerializable(updateRelation, serializer, Encoding.UTF8, "text/xml"); httpClient = HttpWebRequest.Create(baseURLGPString.Value + "/api/0.6/" + elementType + "/" + modifyID.ToString()) as HttpWebRequest; httpClient = OSMGPDownload.AssignProxyandCredentials(httpClient); SetBasicAuthHeader(httpClient, userCredentialGPValue.EncodedUserNamePassWord); OsmRest.HttpUtils.Put(httpClient, sContent); httpResponse = httpClient.GetResponse() as HttpWebResponse; // track the update/sync requests against the server featureUpdateCounter = featureUpdateCounter + 1; if (httpResponse != null) { string newVersionString = OsmRest.HttpUtils.GetResponseContent(httpResponse); // update the revision table if (revVersionFieldIndex != -1) { searchRowToUpdate.set_Value(revVersionFieldIndex, Convert.ToInt32(newVersionString)); } if (revStatusFieldIndex != -1) { searchRowToUpdate.set_Value(revStatusFieldIndex, httpResponse.StatusCode.ToString()); } if (revStatusCodeFieldIndex != -1) { searchRowToUpdate.set_Value(revStatusCodeFieldIndex, (int)httpResponse.StatusCode); } if (revChangeSetIDFieldIndex != -1) { searchRowToUpdate.set_Value(revChangeSetIDFieldIndex, Convert.ToInt32(changeSetID)); } // for a modify the old id is still the new id if (revNewIDFieldIndex != -1 && revOldIDFieldIndex != -1) { searchRowToUpdate.set_Value(revNewIDFieldIndex, searchRowToUpdate.get_Value(revOldIDFieldIndex)); } // update the source table holding the relation information class as well updateSource(relationTable, action, modifyID, modifyID, user_displayname, userID, Convert.ToInt32(newVersionString), Convert.ToInt32(changeSetID), nodeosmIDLookup, wayosmIDLookup, relationosmIDLookup, internalExtensionVersion); httpResponse.Close(); } } catch (Exception ex) { message.AddError(120009, ex.Message); if (ex is WebException) { updateErrorStatus(message, revStatusFieldIndex, revStatusCodeFieldIndex, revErrorMessageFieldIndex, ref searchRowToUpdate, ex); } } break; case "delete": // the delete operations are handled separately break; default: break; } break; #endregion default: break; } } catch (Exception ex) { message.AddAbort(ex.Message); if (ex is WebException) { updateErrorStatus(message, revStatusFieldIndex, revStatusCodeFieldIndex, revErrorMessageFieldIndex, ref searchRowToUpdate, ex); } } finally { try { searchRowToUpdate.Store(); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.Message); } if (httpResponse != null) { httpResponse.Close(); } } if (TrackCancel.Continue() == false) { closeChangeSet(message, userCredentialGPValue.EncodedUserNamePassWord, secondsToTimeout, changeSetID, baseURLGPString); return; } } } #endregion #region now let's handle the delete in the reverse order - relation first, then ways, and then nodes as the last entity #region delete relations // now let's handle the delete in the reverse order - relation first, then ways, and then nodes as the last entity queryFilter.WhereClause = "(" + sqlFormatter.SqlIdentifier("osmstatuscode") + " <> 200 OR " + sqlFormatter.SqlIdentifier("osmstatus") + " IS NULL) AND " + sqlFormatter.SqlIdentifier("osmaction") + " = 'delete' AND " + sqlFormatter.SqlIdentifier("osmelementtype") + " = 'relation'"; using (ComReleaser comReleaser = new ComReleaser()) { searchCursor = revisionTable.Search(queryFilter, false); comReleaser.ManageLifetime(searchCursor); while ((searchRowToUpdate = searchCursor.NextRow()) != null) { // if the overall number of uploaded elements is too big for a single changeset we do need to split it up // into multiple sets if ((featureUpdateCounter % maxElementsinChangeSet) == 0) { CreateNextChangeSet(message, createChangeSetOSM, userCredentialGPValue.EncodedUserNamePassWord, secondsToTimeout, ref changeSetID, baseURLGPString, ref featureUpdateCounter); } long osmID = -1; if (revOldIDFieldIndex != -1) { osmID = Convert.ToInt64(searchRowToUpdate.get_Value(revOldIDFieldIndex)); } int osmVersion = -1; if (revVersionFieldIndex != -1) { osmVersion = Convert.ToInt32(searchRowToUpdate.get_Value(revVersionFieldIndex)); } osm deleteRelation = CreateOSMRelationRepresentation(relationTable, "delete", osmID, changeSetID, osmVersion, nodeosmIDLookup, wayosmIDLookup, relationosmIDLookup, internalExtensionVersion); string sContent = OsmRest.SerializeUtils.CreateXmlSerializable(deleteRelation, serializer, Encoding.UTF8, "text/xml"); string errorMessage = String.Empty; try { httpResponse = OsmRest.HttpUtils.Delete(baseURLGPString.Value + "/api/0.6/relation/" + Convert.ToString(osmID), sContent, userCredentialGPValue.EncodedUserNamePassWord, secondsToTimeout) as HttpWebResponse; // track the update/sync requests against the server featureUpdateCounter = featureUpdateCounter + 1; if (revStatusFieldIndex != -1) { searchRowToUpdate.set_Value(revStatusFieldIndex, (int)httpResponse.StatusCode); } if (revStatusCodeFieldIndex != -1) { searchRowToUpdate.set_Value(revStatusCodeFieldIndex, (int)httpResponse.StatusCode); } if (httpResponse != null) { httpResponse.Close(); } } catch (Exception ex) { message.AddError(120009, ex.Message); if (ex is WebException) { updateErrorStatus(message, revStatusFieldIndex, revStatusCodeFieldIndex, revErrorMessageFieldIndex, ref searchRowToUpdate, ex); } if (httpResponse != null) { httpResponse.Close(); } } try { searchRowToUpdate.Store(); } catch { } if (TrackCancel.Continue() == false) { closeChangeSet(message, userCredentialGPValue.EncodedUserNamePassWord, secondsToTimeout, changeSetID, baseURLGPString); return; } } } #endregion #region handle delete ways queryFilter.WhereClause = "(" + sqlFormatter.SqlIdentifier("osmstatuscode") + " <> 200 OR " + sqlFormatter.SqlIdentifier("osmstatus") + " IS NULL) AND " + sqlFormatter.SqlIdentifier("osmaction") + " = 'delete' AND " + sqlFormatter.SqlIdentifier("osmelementtype") + " = 'way'"; using (ComReleaser comReleaser = new ComReleaser()) { searchCursor = revisionTable.Search(queryFilter, false); comReleaser.ManageLifetime(searchCursor); while ((searchRowToUpdate = searchCursor.NextRow()) != null) { // if the overall number of uploaded elements is too big for a single changeset we do need to split it up // into multiple sets if ((featureUpdateCounter % maxElementsinChangeSet) == 0) { CreateNextChangeSet(message, createChangeSetOSM, userCredentialGPValue.EncodedUserNamePassWord, secondsToTimeout, ref changeSetID, baseURLGPString, ref featureUpdateCounter); } long osmID = -1; if (revOldIDFieldIndex != -1) { osmID = Convert.ToInt64(searchRowToUpdate.get_Value(revOldIDFieldIndex)); } int osmVersion = -1; if (revVersionFieldIndex != -1) { osmVersion = Convert.ToInt32(searchRowToUpdate.get_Value(revVersionFieldIndex)); } osm deleteWay = CreateOSMWayRepresentation(lineFeatureClass, "delete", osmID, changeSetID, osmVersion, wayosmIDLookup, pointFeatureClass, pointOSMIDFieldIndex, internalExtensionVersion); string sContent = OsmRest.SerializeUtils.CreateXmlSerializable(deleteWay, serializer, Encoding.UTF8, "text/xml"); try { httpResponse = null; httpResponse = OsmRest.HttpUtils.Delete(baseURLGPString.Value + "/api/0.6/way/" + Convert.ToString(osmID), sContent, userCredentialGPValue.EncodedUserNamePassWord, secondsToTimeout) as HttpWebResponse; // track the update/sync requests against the server featureUpdateCounter = featureUpdateCounter + 1; string errorMessage = String.Empty; // just grab the response and set it on the database if (revStatusFieldIndex != -1) { searchRowToUpdate.set_Value(revStatusFieldIndex, (int)httpResponse.StatusCode); } if (revStatusCodeFieldIndex != -1) { searchRowToUpdate.set_Value(revStatusCodeFieldIndex, (int)httpResponse.StatusCode); } if (httpResponse != null) { httpResponse.Close(); } } catch (Exception ex) { message.AddError(1200009, ex.Message); if (ex is WebException) { updateErrorStatus(message, revStatusFieldIndex, revStatusCodeFieldIndex, revErrorMessageFieldIndex, ref searchRowToUpdate, ex); } if (httpResponse != null) { httpResponse.Close(); } } try { searchRowToUpdate.Store(); } catch { } if (TrackCancel.Continue() == false) { closeChangeSet(message, userCredentialGPValue.EncodedUserNamePassWord, secondsToTimeout, changeSetID, baseURLGPString); return; } } } #endregion #region handle delete points queryFilter.WhereClause = "(" + sqlFormatter.SqlIdentifier("osmstatuscode") + " <> 200 OR " + sqlFormatter.SqlIdentifier("osmstatus") + " IS NULL) AND " + sqlFormatter.SqlIdentifier("osmaction") + " = 'delete' AND " + sqlFormatter.SqlIdentifier("osmelementtype") + " = 'node'"; using (ComReleaser comReleaser = new ComReleaser()) { searchCursor = revisionTable.Search(queryFilter, false); comReleaser.ManageLifetime(searchCursor); while ((searchRowToUpdate = searchCursor.NextRow()) != null) { // if the overall number of uploaded elements is too big for a single changeset we do need to split it up // into multiple sets if ((featureUpdateCounter % maxElementsinChangeSet) == 0) { CreateNextChangeSet(message, createChangeSetOSM, userCredentialGPValue.EncodedUserNamePassWord, secondsToTimeout, ref changeSetID, baseURLGPString, ref featureUpdateCounter); } long osmID = -1; if (revOldIDFieldIndex != -1) { osmID = Convert.ToInt64(searchRowToUpdate.get_Value(revOldIDFieldIndex)); } int osmVersion = -1; if (revVersionFieldIndex != -1) { osmVersion = Convert.ToInt32(searchRowToUpdate.get_Value(revVersionFieldIndex)); } IPoint deletePoint = null; if (revLongitudeFieldIndex != -1 && revLatitudeFieldIndex != -1) { try { // let's reconstruct the delete point deletePoint = new PointClass(); deletePoint.X = Convert.ToDouble(searchRowToUpdate.get_Value(revLongitudeFieldIndex)); deletePoint.Y = Convert.ToDouble(searchRowToUpdate.get_Value(revLatitudeFieldIndex)); deletePoint.SpatialReference = m_wgs84; } catch (Exception ex) { message.AddWarning(ex.Message); } if (deletePoint == null) { // inform the about the issue - no successful creation of point and continue on to the next delete instruction // in the revision table message.AddWarning(resourceManager.GetString("GPTools_OSMGPUpload_invalidPoint")); continue; } } osm deleteNode = CreateOSMNodeRepresentation(pointFeatureClass, "delete", osmID, changeSetID, osmVersion, deletePoint, internalExtensionVersion); string sContent = OsmRest.SerializeUtils.CreateXmlSerializable(deleteNode, serializer, Encoding.UTF8, "text/xml"); if (String.IsNullOrEmpty(sContent)) { continue; } string errorMessage = String.Empty; try { httpResponse = OsmRest.HttpUtils.Delete(baseURLGPString.Value + "/api/0.6/node/" + Convert.ToString(osmID), sContent, userCredentialGPValue.EncodedUserNamePassWord, secondsToTimeout) as HttpWebResponse; if (revStatusFieldIndex != -1) { searchRowToUpdate.set_Value(revStatusFieldIndex, (int)httpResponse.StatusCode); } if (revStatusCodeFieldIndex != -1) { searchRowToUpdate.set_Value(revStatusCodeFieldIndex, (int)httpResponse.StatusCode); } if (httpResponse != null) { httpResponse.Close(); } } catch (Exception ex) { message.AddError(120009, ex.Message); if (ex is WebException) { updateErrorStatus(message, revStatusFieldIndex, revStatusCodeFieldIndex, revErrorMessageFieldIndex, ref searchRowToUpdate, ex); } if (httpResponse != null) { httpResponse.Close(); } } // track the update/sync requests against the server featureUpdateCounter = featureUpdateCounter + 1; try { searchRowToUpdate.Store(); } catch { } if (TrackCancel.Continue() == false) { closeChangeSet(message, userCredentialGPValue.EncodedUserNamePassWord, secondsToTimeout, changeSetID, baseURLGPString); return; } } } #endregion #endregion #endregion } } catch (Exception ex) { message.AddError(120058, ex.Message); message.AddError(120058, ex.StackTrace); } finally { closeChangeSet(message, userCredentialGPValue.EncodedUserNamePassWord, secondsToTimeout, changeSetID, baseURLGPString); if (revisionTable != null) { try { ISchemaLock tableSchemaLock = revisionTable as ISchemaLock; if (tableSchemaLock != null) { tableSchemaLock.ChangeSchemaLock(esriSchemaLock.esriSharedSchemaLock); } } catch (Exception eLock) { message.AddError(120059, resourceManager.GetString("GPTools_OSMGPUpload_LockErrorTitle") + eLock.Message); } } if (revisionTable != null) { Marshal.FinalReleaseComObject(revisionTable); } // if the searchCursor still has a reference somewhere do release it now - and as a result release any remaining table locks if (searchCursor != null) { Marshal.FinalReleaseComObject(searchCursor); } gpUtilities3.RemoveInternalData(); gpUtilities3.ReleaseInternals(); //Marshal.ReleaseComObject(gpUtilities3); } }
private static void ProfileCreateGraph(IApplication app, List<ProfileGraphDetails> ProfileGraph, IPolyline pPolyline, List<mainDetails> SewerColMains, List<manholeDetails> SewerColManholes, List<tapDetails> SewerColTap, int CurrentDetail) { // profile the sewer line and the surface elevation data // pPolyLine is a line composed from the edge results of the network trace IWorkspace pWS = null; ICursor pCursor = null; IMxDocument pMxDoc = null; IMap pMap = null; IZ pPolyLineZ = null; IZAware pZAwareLineZ = null; ISurface pSurface = null; IRasterLayer pRasterLayer = null; //get the elevation layer ILayer pRasLay = null; IPoint pPtOrigFrom = null; IPoint pPtOrigTo = null; IStandaloneTableCollection pStandAloneTabColl = null; IStandaloneTable pStandAloneTabMainLabel = null; ITable pTapTable = null; ITable pMainTable = null; ITable pManholeTable = null; ITable pSurfaceTable = null; ITable pMainLabelTable = null; ITableFields pTableFieldsMainLabel = null; IStandaloneTable pStandAloneTabMain = null; ITableFields pTableFieldsMain = null; IStandaloneTable pStandAloneTabManhole = null; ITableFields pTableFieldsManhole = null; IStandaloneTable pStandAloneTabSurface = null; ITableFields pTableFieldsSurface = null; IStandaloneTable pStandAloneTabTap = null; ITableFields pTableFieldsTap = null; IRowBuffer pRowBuff = null; ICursor pLabelCursor = null; ICursor pTapCursor = null; ISegment pSegment = null; ILine pLine = null; IPoint pFromPnt = null; IPoint pToPnt = null; IPoint pMidPnt = null; IDataGraphBase pDataGraphBase = null; IDataGraphT pDataGraphT = null; IPointCollection pPtCollection = null; IEnumVertex pEnumVertex = null; IPoint pPt = null; ISeriesProperties pAreaSeriesProps = null; IColor pColor = null; String strXDataFldName = null; String strYDataFldName = null; IDataSortSeriesProperties pSortFlds = null; IPointSeriesProperties pScatterSeriesProps2 = null; ISeriesProperties pScatterSeriesProps = null; IBarSeriesProperties pManHoleSeries = null; ILineSeriesProperties pLineSeriesProps2 = null; ISeriesProperties pLineSeriesProps = null; ITrackCancel pCancelTracker = null; IDataGraphWindow2 pDataGraphWin = null; IDataGraphCollection pDataGraphs = null; try { pMxDoc = (IMxDocument)app.Document; pMap = pMxDoc.FocusMap; // Open the Workspace pWS = Globals.CreateInMemoryWorkspace(); //get the elevation layer bool FCorLayerRas = true; pRasLay = Globals.FindLayer(pMap, ProfileGraph[CurrentDetail].Elevation_LayerName, ref FCorLayerRas); if (pRasLay != null) { pRasterLayer = pRasLay as IRasterLayer; // get the surface to interpolate from pSurface = Globals.GetSurface(pRasterLayer); // make the polyline z-aware pZAwareLineZ = (IZAware)pPolyline; pZAwareLineZ.ZAware = true; // work around for InterpolateFromSurface sometimes flipping polyline pPtOrigFrom = pPolyline.FromPoint; pPtOrigTo = pPolyline.ToPoint; pPolyline.Project((pRasterLayer as IGeoDataset).SpatialReference); // add z values to the polyline pPolyLineZ = (IZ)pPolyline; pPolyLineZ.InterpolateFromSurface(pSurface); pPolyline.ReverseOrientation(); } int i; pStandAloneTabColl = (IStandaloneTableCollection)pMap; for (i = pStandAloneTabColl.StandaloneTableCount - 1; i > 0; i--) { if (pStandAloneTabColl.StandaloneTable[i].Name == "Point Table") { pStandAloneTabColl.RemoveStandaloneTable(pStandAloneTabColl.StandaloneTable[i]); continue; } else if (pStandAloneTabColl.StandaloneTable[i].Name == "Surface Table") { pStandAloneTabColl.RemoveStandaloneTable(pStandAloneTabColl.StandaloneTable[i]); continue; } else if (pStandAloneTabColl.StandaloneTable[i].Name == "Line Table") { pStandAloneTabColl.RemoveStandaloneTable(pStandAloneTabColl.StandaloneTable[i]); continue; } else if (pStandAloneTabColl.StandaloneTable[i].Name == "Line Label Table") { pStandAloneTabColl.RemoveStandaloneTable(pStandAloneTabColl.StandaloneTable[i]); continue; } else if (pStandAloneTabColl.StandaloneTable[i].Name == "Points Along Table") { pStandAloneTabColl.RemoveStandaloneTable(pStandAloneTabColl.StandaloneTable[i]); continue; } } pMainTable = Globals.createTableInMemory("Line Table", createLineFields(), pWS); if (pMainTable == null) return; pManholeTable = Globals.createTableInMemory("Point Table", createPointFields(), pWS); if (pManholeTable == null) return; if (pRasterLayer != null) { pSurfaceTable = Globals.createTableInMemory("Surface Table", createSurfaceFields(), pWS); if (pSurfaceTable == null) return; } pMainLabelTable = Globals.createTableInMemory("Line Label Table", createLineLabelFields(), pWS); if (pMainLabelTable == null) return; pTapTable = Globals.createTableInMemory("Points Along Table", createLineLabelFields(), pWS); if (pTapTable == null) return; // add the table to the map so it can be edited // Create a new standalone table and add it to the collection of the focus map pStandAloneTabMainLabel = new StandaloneTableClass(); pStandAloneTabMainLabel.Table = pMainLabelTable; pStandAloneTabColl.AddStandaloneTable(pStandAloneTabMainLabel); pMainLabelTable = (ITable)pStandAloneTabMainLabel;// QI, used in data graph pTableFieldsMainLabel = (ITableFields)pStandAloneTabMainLabel; pStandAloneTabMain = new StandaloneTableClass(); pStandAloneTabMain.Table = pMainTable; pStandAloneTabColl.AddStandaloneTable(pStandAloneTabMain); pMainTable = (ITable)pStandAloneTabMain;// QI, used in data graph pTableFieldsMain = (ITableFields)pStandAloneTabMain; pStandAloneTabManhole = new StandaloneTableClass(); pStandAloneTabManhole.Table = pManholeTable; pStandAloneTabColl.AddStandaloneTable(pStandAloneTabManhole); pManholeTable = (ITable)pStandAloneTabManhole;// QI, used in data graph pTableFieldsManhole = (ITableFields)pStandAloneTabManhole; if (pSurfaceTable != null) { pStandAloneTabSurface = new StandaloneTableClass(); pStandAloneTabSurface.Table = pSurfaceTable; pStandAloneTabColl.AddStandaloneTable(pStandAloneTabSurface); pSurfaceTable = (ITable)pStandAloneTabSurface;// QI, used in data graph pTableFieldsSurface = (ITableFields)pStandAloneTabSurface; } if (pTapTable != null) { pStandAloneTabTap = new StandaloneTableClass(); pStandAloneTabTap.Table = pTapTable; pStandAloneTabColl.AddStandaloneTable(pStandAloneTabTap); pTapTable = (ITable)pStandAloneTabTap;// QI, used in data graph pTableFieldsTap = (ITableFields)pStandAloneTabTap; } // Refresh the TOC pMxDoc.UpdateContents(); // get an insert cursor for the table pCursor = pManholeTable.Insert(true); double minChartVal = 0.0; double maxChartVal = 0.0; int id = 0; foreach (manholeDetails manholeDetail in SewerColManholes) { //SewerElevCollManholesDetails.Add(new object[] { pPt.M, manRim, manInvElev, manInv, manID }); pRowBuff = pManholeTable.CreateRowBuffer(); pRowBuff.set_Value(pRowBuff.Fields.FindField("X"), manholeDetail.M);//0 pRowBuff.set_Value(pRowBuff.Fields.FindField("TOPELEV"), manholeDetail.Top);//1 pRowBuff.set_Value(pRowBuff.Fields.FindField("BOTELEV"), manholeDetail.Bottom);//2 //pRowBuff.set_Value(pRowBuff.Fields.FindField("INVERT"), manholeDetail.Invert);//3 pRowBuff.set_Value(pRowBuff.Fields.FindField("ID"), manholeDetail.ManholeID);//4 if (id == 0) { minChartVal = (double)manholeDetail.Bottom; maxChartVal = (double)manholeDetail.Top; id++; } else { if (minChartVal > (double)manholeDetail.Bottom) minChartVal = (double)manholeDetail.Bottom; if (maxChartVal < (double)manholeDetail.Top) maxChartVal = (double)manholeDetail.Top; } pCursor.InsertRow(pRowBuff); } // flush any writes pCursor.Flush(); Marshal.ReleaseComObject(pCursor); pCursor = pMainTable.Insert(true); pLabelCursor = pMainLabelTable.Insert(true); pTapCursor = pTapTable.Insert(true); foreach (mainDetails mainDetail in SewerColMains) { //SewerElevCollManholesDetails.Add(new object[] { pPt.M, manRim, manInvElev, manInv, manID }); //pRowBuff.set_Value(pRowBuff.Fields.FindField("FROMM"), mainDetail.UpM);//0 //pRowBuff.set_Value(pRowBuff.Fields.FindField("TOM"), mainDetail.DownM);//1 //pRowBuff.set_Value(pRowBuff.Fields.FindField("FROMELEV"), mainDetail.UpElev);//2 //pRowBuff.set_Value(pRowBuff.Fields.FindField("TOELEV"), mainDetail.DownElev);//3 pRowBuff = pMainTable.CreateRowBuffer(); pRowBuff.set_Value(pRowBuff.Fields.FindField("ELEVATION"), mainDetail.UpElev);//2 pRowBuff.set_Value(pRowBuff.Fields.FindField("MEASURE"), mainDetail.UpM);//3 pRowBuff.set_Value(pRowBuff.Fields.FindField("FACILITYID"), mainDetail.MainID);//4 pCursor.InsertRow(pRowBuff); pRowBuff = pMainTable.CreateRowBuffer(); pRowBuff.set_Value(pRowBuff.Fields.FindField("ELEVATION"), mainDetail.DownElev);//2 pRowBuff.set_Value(pRowBuff.Fields.FindField("MEASURE"), mainDetail.DownM);//3 pRowBuff.set_Value(pRowBuff.Fields.FindField("FACILITYID"), mainDetail.MainID);//4 pCursor.InsertRow(pRowBuff); pLine = new LineClass(); pFromPnt = new PointClass(); pToPnt = new PointClass(); pMidPnt = new PointClass(); pFromPnt.Y = mainDetail.UpElev; pFromPnt.X = mainDetail.UpM; pToPnt.Y = mainDetail.DownElev; pToPnt.X = mainDetail.DownM; pLine.PutCoords(pFromPnt, pToPnt); pSegment = pLine as ISegment; pSegment.QueryPoint(esriSegmentExtension.esriNoExtension, 0.5, true, pMidPnt); // pSegM = (ISegmentM)pSegment; // pSegM.SetMs( pRowBuff = pMainLabelTable.CreateRowBuffer(); pRowBuff.set_Value(pRowBuff.Fields.FindField("ELEVATION"), pMidPnt.Y);//2 pRowBuff.set_Value(pRowBuff.Fields.FindField("MEASURE"), pMidPnt.X);//3 pRowBuff.set_Value(pRowBuff.Fields.FindField("FACILITYID"), mainDetail.MainID);//4 pRowBuff.set_Value(pRowBuff.Fields.FindField("LABEL"), mainDetail.Label);//4 pLabelCursor.InsertRow(pRowBuff); double slope = (pToPnt.Y - pFromPnt.Y) / (pToPnt.X - pFromPnt.X); foreach (tapDetails tpDet in SewerColTap) { double distDown; if (tpDet.Added == true) continue; if (pFromPnt.X < pToPnt.X) { if (tpDet.M > pFromPnt.X && tpDet.M < pToPnt.X) { distDown = tpDet.M - pFromPnt.X; } else continue; } else { if (tpDet.M > pToPnt.X && tpDet.M < pFromPnt.X) { distDown = tpDet.M - pToPnt.X; } else continue; } { pSegment.QueryPoint(esriSegmentExtension.esriNoExtension, distDown, false, pMidPnt); //if (pMidPnt.X == tpDet.M) //{ pRowBuff = pTapTable.CreateRowBuffer(); pRowBuff.set_Value(pRowBuff.Fields.FindField("ELEVATION"), pMidPnt.Y);//2 pRowBuff.set_Value(pRowBuff.Fields.FindField("MEASURE"), tpDet.M);//3 pRowBuff.set_Value(pRowBuff.Fields.FindField("FACILITYID"), tpDet.tapID);//4 pRowBuff.set_Value(pRowBuff.Fields.FindField("LABEL"), tpDet.tapLabel);//4 //pRowBuff.set_Value(pRowBuff.Fields.FindField("LABEL"), mainDetail.Label);//4 pTapCursor.InsertRow(pRowBuff); tpDet.Added = true; //SewerColTap.Remove(tpDet); // } } } //if (minChartVal > (double)manholeDetail.InvertElev) // minChartVal = (double)manholeDetail.InvertElev; //if (maxChartVal < (double)manholeDetail.Rim) // maxChartVal = (double)manholeDetail.Rim; } // flush any writes pCursor.Flush(); Marshal.ReleaseComObject(pCursor); pLabelCursor.Flush(); Marshal.ReleaseComObject(pLabelCursor); pTapCursor.Flush(); Marshal.ReleaseComObject(pTapCursor); if (pSurfaceTable != null) { pPtCollection = (IPointCollection)pPolyLineZ; pEnumVertex = pPtCollection.EnumVertices; pEnumVertex.Reset(); int lPartIndex; int lVertexIndex; pEnumVertex.Next(out pPt, out lPartIndex, out lVertexIndex); pCursor = pSurfaceTable.Insert(true); while (pPt != null) { pRowBuff = pSurfaceTable.CreateRowBuffer(); pRowBuff.set_Value(pRowBuff.Fields.FindField("X"), pPt.M);//2 pRowBuff.set_Value(pRowBuff.Fields.FindField("Y"), pPt.Z);//3 pCursor.InsertRow(pRowBuff); pEnumVertex.Next(out pPt, out lPartIndex, out lVertexIndex); } } //============================================================================= // create the graph from the table // create graph pDataGraphBase = new DataGraphTClass(); pDataGraphT = (IDataGraphT)pDataGraphBase; // graph, axis and legend titles. Substitute them for different input layer pDataGraphT.GeneralProperties.Title = ProfileGraph[CurrentDetail].GraphTitle_Name; // "Sewer Main Profile"; pDataGraphT.LegendProperties.Title = ProfileGraph[CurrentDetail].Legend_Name; //"Profile Legend"; // IDataGraphTAxisProperties pHort = pDataGraphT.AxisProperties[0]; pDataGraphT.AxisProperties[0].Title = ProfileGraph[CurrentDetail].LeftAxis_Name; pDataGraphT.AxisProperties[0].AutomaticMaximum = true; pDataGraphT.AxisProperties[0].AutomaticMinimum = true; pDataGraphT.AxisProperties[0].Minimum = minChartVal - 5; pDataGraphT.AxisProperties[0].Maximum = maxChartVal + 5; pDataGraphT.AxisProperties[0].InitDefaults(); //pDataGraphT.AxisProperties[1].AutomaticMaximum = true; //pDataGraphT.AxisProperties[1].AutomaticMinimum = false; //pDataGraphT.AxisProperties[1].Minimum = minChartVal - 5; ////pDataGraphT.AxisProperties[1].Title = "Manholes"; //pDataGraphT.AxisProperties[1].Visible = true; pDataGraphT.AxisProperties[3].Visible = true; pDataGraphT.AxisProperties[3].Title = ProfileGraph[CurrentDetail].TopAxis_Name; pDataGraphT.AxisProperties[2].Title = ProfileGraph[CurrentDetail].BottomAxis_Name; // "Date"; pDataGraphT.AxisProperties[2].ValueFormat = "0"; pDataGraphT.AxisProperties[2].Minimum = 0; pDataGraphT.AxisProperties[2].AutomaticMinimum = false; pDataGraphT.AxisProperties[2].ValueFormat = "#,##0.###"; pDataGraphBase.Name = ProfileGraph[CurrentDetail].Graph_Name; ; // & strTableName layerName; //IDataGraphTGeneralProperties pGenProp = pDataGraphT.GeneralProperties; //pGenProp.Show3D = true; // put the legend below the graph //pDataGraphT.LegendProperties.Alignment = esriDataGraphTLegendBottom // use only for series-specific properties //IPointSeriesProperties pPtSeries; //IAreaSeriesProperties pAreaSeries; //ILineSeriesProperties pLineSeries; //------------------------------------------------------------------------------- // area series - ground elevation int idx = 0; if (pSurfaceTable != null) { // create the area graph for the ground elevation pAreaSeriesProps = pDataGraphT.AddSeries("area:vertical"); //("scatter_plot") '("line:vertical") pAreaSeriesProps.SourceData = pSurfaceTable;// pLayer pAreaSeriesProps.ColorType = esriGraphColorType.esriGraphColorCustomAll; pColor = Globals.GetColor(137, 112, 68); pAreaSeriesProps.CustomColor = pColor.RGB; // pSymbol.Color.RGB // get the fields to graph - ground elevation strXDataFldName = "X"; //pTable.Fields.Field(i).Name ' "Dist_to_Rds" strYDataFldName = "Y"; // pTable.Fields.Field(i).Name ' "Dist_to_Rds" // pSeriesProps.whereClause = whereClause pAreaSeriesProps.InLegend = true; //show legend ' false = don't show legend pAreaSeriesProps.Name = ProfileGraph[CurrentDetail].Elevation_LayerName;//A4LGSharedFunctions.Localizer.GetString("GeoNetToolsAlias_1"); //pSeriesProps.LabelField = "OBJECTID"; pAreaSeriesProps.ValueFormat = "0 "; pAreaSeriesProps.SetField(0, strXDataFldName); // timefldName pAreaSeriesProps.SetField(1, strYDataFldName); // sort on the X value pSortFlds = (IDataSortSeriesProperties)pAreaSeriesProps; pSortFlds.AddSortingField(strXDataFldName, true, ref idx); } //------------------------------------------------------------------------------- //------Manhole Locations // create the area graph for the ground elevation pAreaSeriesProps = pDataGraphT.AddSeries("bar:minmax"); //("scatter_plot") '("line:vertical") pManHoleSeries = (IBarSeriesProperties)pAreaSeriesProps; pManHoleSeries.BarStyle = esriBarStyle.esriCylinderBar; pManHoleSeries.BarSize = 5; pAreaSeriesProps.SourceData = pManholeTable;// pLayer pAreaSeriesProps.ColorType = esriGraphColorType.esriGraphColorCustomAll; pColor = Globals.GetColor(255, 255, 68); pAreaSeriesProps.CustomColor = pColor.RGB; // pSymbol.Color.RGB pAreaSeriesProps.InLegend = true; //show legend ' false = don't show legend pAreaSeriesProps.Name = ProfileGraph[CurrentDetail].Point_LayerName;//"Point Locations"; pAreaSeriesProps.HorizontalAxis = 3; pAreaSeriesProps.LabelField = "ID"; pAreaSeriesProps.SetField(0, "X"); pAreaSeriesProps.SetField(1, "BOTELEV"); pAreaSeriesProps.SetField(2, "TOPELEV"); // sort on the X value //pSortFlds = (IDataSortSeriesProperties)pAreaSeriesProps; //idx = 0; //pSortFlds.AddSortingField("X", true, ref idx); //---- // line series - sewer line pColor = Globals.GetColor(76, 230, 0);// green pLineSeriesProps = pDataGraphT.AddSeries("line:vertical"); //("area:vertical") '("scatter_plot") '("line:vertical") pLineSeriesProps.SourceData = pMainTable; // pLayer pLineSeriesProps.ColorType = esriGraphColorType.esriGraphColorCustomAll; pLineSeriesProps.PenProperties.Width = 3; pLineSeriesProps.CustomColor = pColor.RGB; // pSymbol.Color.RGB // don't have any symbols on the line, just solid pLineSeriesProps2 = (ILineSeriesProperties)pLineSeriesProps;// 'QI pLineSeriesProps2.SymbolProperties.Style = esriDataGraphTSymbolType.esriDataGraphTSymbolNothing; // get the fields to graph strXDataFldName = "MEASURE"; strYDataFldName = "ELEVATION"; pLineSeriesProps.InLegend = true; // show legend ' false = don't show legend pLineSeriesProps.Name = ProfileGraph[CurrentDetail].Line_LayerName;//"Line Profile";// pMainTable.Fields.get_Field(pMainTable.Fields.FindField("ELEVATION")).AliasName; //pSeriesProps.LabelField = "OBJECTID" pLineSeriesProps.ValueFormat = "0 "; pLineSeriesProps.SetField(0, strXDataFldName);// timefldName pLineSeriesProps.SetField(1, strYDataFldName); // sort on the X value pSortFlds = (IDataSortSeriesProperties)pLineSeriesProps; pSortFlds.AddSortingField(strXDataFldName, true, ref idx); //---------- end line series pScatterSeriesProps = pDataGraphT.AddSeries("scatter_plot"); //("area:vertical") '("scatter_plot") '("line:vertical") pScatterSeriesProps.SourceData = pMainLabelTable; // pLayer pScatterSeriesProps.ColorType = esriGraphColorType.esriGraphColorCustomAll; pScatterSeriesProps.PenProperties.Width = 3; pScatterSeriesProps.CustomColor = pColor.RGB; // pSymbol.Color.RGB // don't have any symbols on the line, just solid pScatterSeriesProps2 = (IPointSeriesProperties)pScatterSeriesProps;// 'QI pScatterSeriesProps2.SymbolProperties.Style = esriDataGraphTSymbolType.esriDataGraphTSymbolCircle; pScatterSeriesProps2.SymbolProperties.Visible = false; pScatterSeriesProps2.SymbolProperties.Color = pColor.RGB; pScatterSeriesProps2.SymbolProperties.BorderProperties.Color = pColor.RGB; pScatterSeriesProps2.SymbolProperties.BorderProperties.Style = esriDataGraphTPenType.esriDataGraphTPenClear; // get the fields to graph strXDataFldName = "MEASURE"; strYDataFldName = "ELEVATION"; pScatterSeriesProps.InLegend = false; // show legend ' false = don't show legend pScatterSeriesProps.Name = A4LGSharedFunctions.Localizer.GetString("GeoNetToolsAlias_14"); //pSeriesProps.LabelField = "OBJECTID" pScatterSeriesProps.ValueFormat = " "; pScatterSeriesProps.HorizontalAxis = 3; pScatterSeriesProps.LabelField = "LABEL"; pScatterSeriesProps.Marks = true; pScatterSeriesProps.SetField(0, strXDataFldName);// timefldName pScatterSeriesProps.SetField(1, strYDataFldName); //pScatterSeriesProps.SetField(2, "LABEL"); // sort on the X value // pSortFlds = (IDataSortSeriesProperties)pScatterSeriesProps; // pSortFlds.AddSortingField(strXDataFldName, true, ref idx); //ISeriesProperties pScatterSeriesProps; pScatterSeriesProps = pDataGraphT.AddSeries("scatter_plot"); //("area:vertical") '("scatter_plot") '("line:vertical") pScatterSeriesProps.SourceData = pTapTable; // pLayer // get the fields to graph strXDataFldName = "MEASURE"; strYDataFldName = "ELEVATION"; pScatterSeriesProps.ColorType = esriGraphColorType.esriGraphColorCustomAll; pScatterSeriesProps.PenProperties.Width = 3; pScatterSeriesProps.HorizontalAxis = 5; pScatterSeriesProps.LabelField = "LABEL"; if (ProfileGraph[CurrentDetail].PointAlong_ShowLabels.ToUpper() == "TRUE" && ProfileGraph[CurrentDetail].PointAlong_Labels.Length > 0) { pScatterSeriesProps.Marks = true; } pScatterSeriesProps.InLegend = true; // show legend ' false = don't show legend pScatterSeriesProps.Name = ProfileGraph[CurrentDetail].PointAlong_LayerName;//"Points Along"; //pSeriesProps.LabelField = "OBJECTID" pScatterSeriesProps.ValueFormat = " "; pScatterSeriesProps.SetField(0, strXDataFldName);// timefldName pScatterSeriesProps.SetField(1, strYDataFldName); pColor = Globals.GetColor(255, 0, 0);// green pScatterSeriesProps.CustomColor = pColor.RGB; // pSymbol.Color.RGB // don't have any symbols on the line, just solid //IPointSeriesProperties pScatterSeriesProps2; pScatterSeriesProps2 = (IPointSeriesProperties)pScatterSeriesProps;// 'QI pScatterSeriesProps2.SymbolProperties.Style = esriDataGraphTSymbolType.esriDataGraphTSymbolStar; pScatterSeriesProps2.SymbolProperties.Visible = true; pScatterSeriesProps2.SymbolProperties.Color = pColor.RGB; pScatterSeriesProps2.SymbolProperties.BorderProperties.Color = pColor.RGB; pScatterSeriesProps2.SymbolProperties.BorderProperties.Style = esriDataGraphTPenType.esriDataGraphTPenSolid; pDataGraphBase.UseSelectedSet = false; pCancelTracker = new CancelTrackerClass(); pDataGraphT.Update(pCancelTracker); // create data graph window pDataGraphWin = new DataGraphWindowClass(); pDataGraphWin.DataGraphBase = pDataGraphBase; pDataGraphWin.Application = app; // size and position the window pDataGraphWin.PutPosition(0, 0, 900, 250); // add the graph to the project pDataGraphs = (IDataGraphCollection)pMxDoc; //QI pDataGraphs.AddDataGraph(pDataGraphBase); //IDataGraphT ptmp = (IDataGraphT)pDataGraphs.DataGraph[1]; //string fld = ptmp.SeriesProperties[5].GetField(0); //fld = ptmp.SeriesProperties[5].GetField(1); //fld = ptmp.SeriesProperties[5].GetField(2); //fld = ptmp.SeriesProperties[5].LabelField; //fld = ptmp.SeriesProperties[5].Marks.ToString(); // fld = ptmp.SeriesProperties[5].HorizontalAxis; pDataGraphT.AxisProperties[0].AutomaticMaximum = true; pDataGraphT.AxisProperties[0].AutomaticMinimum = true; // pDataGraphT.AxisProperties[0].Minimum = minChartVal - 5; //pDataGraphT.AxisProperties[0].Maximum = maxChartVal + 5; pDataGraphT.AxisProperties[0].InitDefaults(); // show the graph pDataGraphWin.Show(true); //// get an insert cursor for the table //pCursor = null; //pRowBuff = null; //pCursor = pProfTable.Insert(true); //// populate the table //IPoint pPt; //int lPartIndex; //int lVertexIndex; //IEnumVertex pEnumVertex; //pPtCollection = (IPointCollection)pPolyline; //pEnumVertex = pPtCollection.EnumVertices; //pEnumVertex.Reset(); //// add the vertex xyz to the new table //i = 0; //pEnumVertex.Next(out pPt, out lPartIndex, out lVertexIndex); //while (pPt != null) //{ // pRowBuff = pProfTable.CreateRowBuffer(); // pRowBuff.set_Value(pRowBuff.Fields.FindField("X"), pPt.X); // pRowBuff.set_Value(pRowBuff.Fields.FindField("Y"), pPt.Y); // pRowBuff.set_Value(pRowBuff.Fields.FindField("Z"), pPt.Z); // pRowBuff.set_Value(pRowBuff.Fields.FindField("M"), pPt.M); // // keep -99999 as a flag, data will be calculated later, // // right now a graph can't ignore null values // if (SewerElevCollFroms[i] == null || SewerElevCollFroms[i].ToString() == "") // { // pRowBuff.set_Value(pRowBuff.Fields.FindField("UPELEV"), -99999); // if (MessageBox.Show("There is a null value in the Upstream Elevations, Continue?", "Missing Data", MessageBoxButtons.YesNo) == DialogResult.No) // { // return; // } // } // else // { // pRowBuff.set_Value(pRowBuff.Fields.FindField("UPELEV"), SewerElevCollFroms[i]); // } // if (SewerElevCollTos[i] == null || SewerElevCollTos[i].ToString() == "") // { // pRowBuff.set_Value(pRowBuff.Fields.FindField("DOWNELEV"), -99999); // if (MessageBox.Show("There is a null value in the Downstream Elevations, Continue?", "Missing Data", MessageBoxButtons.YesNo) == DialogResult.No) // { // return; // } // } // else // { // pRowBuff.set_Value(pRowBuff.Fields.FindField("DOWNELEV"), SewerElevCollTos[i]); // } // if (SewerElevCollRim[i] == null || SewerElevCollRim[i].ToString() == "") // { // pRowBuff.set_Value(pRowBuff.Fields.FindField("RIMELEV"), -99999); // if (MessageBox.Show("There is a null value in the Rim Elevation, Continue?", "Missing Data", MessageBoxButtons.YesNo) == DialogResult.No) // { // return; // } // } // else // { // pRowBuff.set_Value(pRowBuff.Fields.FindField("RIMELEV"), SewerElevCollRim[i]); // } // if (SewerElevCollInvertElev[i] == null || SewerElevCollInvertElev[i].ToString() == "") // { // pRowBuff.set_Value(pRowBuff.Fields.FindField("INVERTELEV"), -99999); // if (MessageBox.Show("There is a null value in the Invert Elevation, Continue?", "Missing Data", MessageBoxButtons.YesNo) == DialogResult.No) // { // return; // } // } // else // { // pRowBuff.set_Value(pRowBuff.Fields.FindField("INVERTELEV"), SewerElevCollInvertElev[i]); // } // // pRowBuff.set_Value(pRowBuff.Fields.FindField("UPELEV"), SewerElevCollFroms[i]); // //pRowBuff.set_Value(pRowBuff.Fields.FindField("DOWNELEV"), SewerElevCollTos[i]); // // pRowBuff.set_Value(pRowBuff.Fields.FindField("RIMELEV"), SewerElevCollRim[i]); // // pRowBuff.set_Value(pRowBuff.Fields.FindField("INVERTELEV"), SewerElevCollInvertElev[i]); // /** use this code if graph can ignore null data // ' ' skip records with -99999 as sewer elev // ' If SewerElevColl(i) <> -99999 Then // ' pRowBuff.Value(pRowBuff.Fields.FindField("SewerElev")) = SewerElevColl(i) // ' Else // ' pRowBuff.Value(pRowBuff.Fields.FindField("SewerElev")) = Null // ' End If*/ // pCursor.InsertRow(pRowBuff); // pEnumVertex.Next(out pPt, out lPartIndex, out lVertexIndex); // i++; //} //// flush any writes //pCursor.Flush(); //Marshal.ReleaseComObject(pCursor); ///* // ' Calculate a value for an intermediate point between 2 manholes // ' needed because graph requires a value for every record or it gives it a zero. // ' Sewer lines have values at each manhole but a sewerline is composed of many // ' lines - where the laterals break it. // ' ** this may change if they modify the software to ignore null values in a graph // */ //// make a cursor of just the records that have a valid sewer elev //// needed to get the deltaSewerElev of the sewer elev data ////********* //string currentField = "UPELEV"; //for (int k = 0; k < 4; k++) //{ // switch (k) // { // case 0: // currentField = "UPELEV"; // break; // case 1: // currentField = "DOWNELEV"; // break; // case 2: // currentField = "RIMELEV"; // break; // case 3: // currentField = "INVERTELEV"; // break; // } // double Mmin = 0.0; // double Mmax = 0.0; // double minSewerElev = 0.0; // double maxSewerElev = 0.0; // double deltaSewerElev = 0.0; // double deltaM = 0.0; // double newZ = 0.0; // double m = 0.0; // double sewerelev = 0.0; // int j; // IRow pRowSewerElev; // ICursor pCursorSewerElev; // IQueryFilter pQueryFilter; // pQueryFilter = new QueryFilterClass(); // pQueryFilter.WhereClause = currentField + " <> -99999"; // pCursorSewerElev = pProfTable.Search(pQueryFilter, false); // // recreate the cursor as an update cursor // pCursor = null; // pCursor = pProfTable.Update(null, false); // pRowBuff = pCursor.NextRow(); // j = 0; // deltaM = 0; // while (pRowBuff != null) // { // // for the intermediate records, SewerElev will have a value of -99999, // // update them with a calculated value // if ((double)(pRowBuff.get_Value(pRowBuff.Fields.FindField(currentField))) == -99999) // { // m = (double)pRowBuff.get_Value(pRowBuff.Fields.FindField("M")); // newZ = (((m - Mmin) / deltaM) * deltaSewerElev) + sewerelev; // pRowBuff.set_Value(pRowBuff.Fields.FindField(currentField), newZ); // pCursor.UpdateRow(pRowBuff as IRow); // } // else // { // //valid sewer elev record // // calculate the delta sewer elev // if (j == 0) // { // // get the min and max sewer elev values // // get the man and max M value, this is used in the ratio calculation, // // I can't use the whole line length as the M because the slope of the // // sewer pipe can change at each manhole so the calculation has to be // // from manhole to manhole, not the whole line // try // { // pRowSewerElev = pCursorSewerElev.NextRow(); // minSewerElev = (double)pRowSewerElev.get_Value(pRowSewerElev.Fields.FindField(currentField)); // //string tmp = pRowSewerElev.get_Value(pRowSewerElev.Fields.FindField("M")).ToString(); // //if (tmp == "") // // Mmin = 0.0; // //else // // Mmin = Convert.ToDouble(tmp); // Mmin = (double)pRowSewerElev.get_Value(pRowSewerElev.Fields.FindField("M")); // pRowSewerElev = pCursorSewerElev.NextRow(); // maxSewerElev = (double)pRowSewerElev.get_Value(pRowSewerElev.Fields.FindField(currentField)); // Mmax = (double)pRowSewerElev.get_Value(pRowSewerElev.Fields.FindField("M")); // } // catch (Exception Ex) // { // MessageBox.Show(Ex.Message); // } // } // else // { // pRowSewerElev = pCursorSewerElev.NextRow(); // if (pRowSewerElev == null) // { // break; // } // minSewerElev = maxSewerElev; // Mmin = Mmax; // maxSewerElev = (double)pRowSewerElev.get_Value(pRowSewerElev.Fields.FindField(currentField)); // Mmax = (double)pRowSewerElev.get_Value(pRowSewerElev.Fields.FindField("M")); // } // deltaSewerElev = maxSewerElev - minSewerElev; // deltaM = Mmax - Mmin; // // this value is the base value that the calc'd values need as a base // sewerelev = minSewerElev;//pRowBuff.Value(pRowBuff.Fields.FindField("SewerElev")) // j++; // } // pRowBuff = (IRowBuffer)pCursor.NextRow(); // } // pCursor.Flush(); // Marshal.ReleaseComObject(pCursor); // Marshal.ReleaseComObject(pCursorSewerElev); //} ////============================================================================= //// create the graph from the table //IDataGraphBase pDataGraphBase; //IDataGraphT pDataGraphT; //// create graph //pDataGraphBase = new DataGraphTClass(); //pDataGraphT = (IDataGraphT)pDataGraphBase; //// graph, axis and legend titles. Substitute them for different input layer //pDataGraphT.GeneralProperties.Title = "Sewer Main Profile"; //pDataGraphT.LegendProperties.Title = "Profile Legend"; //// IDataGraphTAxisProperties pHort = pDataGraphT.AxisProperties[0]; //pDataGraphT.AxisProperties[0].Title = A4LGSharedFunctions.Localizer.GetString("GeoNetToolsAlias_13"); //pDataGraphT.AxisProperties[0].AutomaticMaximum = true; //pDataGraphT.AxisProperties[0].AutomaticMinimum = true; ////pDataGraphT.AxisProperties[0].Minimum = minChartVal - 5; ////pDataGraphT.AxisProperties[0].Maximum= maxChartVal + 5; ////pDataGraphT.AxisProperties[1].AutomaticMaximum = true; ////pDataGraphT.AxisProperties[1].AutomaticMinimum = false; ////pDataGraphT.AxisProperties[1].Minimum = minChartVal - 5; //////pDataGraphT.AxisProperties[1].Title = "Manholes"; ////pDataGraphT.AxisProperties[1].Visible = true; //pDataGraphT.AxisProperties[3].Visible = true; //pDataGraphT.AxisProperties[3].Title = "Manholes"; //pDataGraphT.AxisProperties[2].Title = "Length (feet)"; // "Date"; //pDataGraphT.AxisProperties[2].ValueFormat = "0"; //pDataGraphT.AxisProperties[2].Minimum = 0; //pDataGraphT.AxisProperties[2].AutomaticMinimum = false; //pDataGraphT.AxisProperties[2].ValueFormat = "#,##0.###"; //pDataGraphBase.Name = "Sewer Main Profile Graph"; // & strTableName layerName; ////IDataGraphTGeneralProperties pGenProp = pDataGraphT.GeneralProperties; ////pGenProp.Show3D = true; //// put the legend below the graph ////pDataGraphT.LegendProperties.Alignment = esriDataGraphTLegendBottom //// use only for series-specific properties ////IPointSeriesProperties pPtSeries; ////IAreaSeriesProperties pAreaSeries; ////ILineSeriesProperties pLineSeries; ////------------------------------------------------------------------------------- //// area series - ground elevation //ISeriesProperties pAreaSeriesProps; //IColor pColor; //// create the area graph for the ground elevation //pAreaSeriesProps = pDataGraphT.AddSeries("area:vertical"); //("scatter_plot") '("line:vertical") //pAreaSeriesProps.SourceData = pProfTable;// pLayer //pAreaSeriesProps.ColorType = esriGraphColorType.esriGraphColorCustomAll; //pColor = Globals.GetColor(137, 112, 68); //pAreaSeriesProps.CustomColor = pColor.RGB; // pSymbol.Color.RGB //String strXDataFldName; //String strYDataFldName; //// get the fields to graph - ground elevation //strXDataFldName = "M"; //pTable.Fields.Field(i).Name ' "Dist_to_Rds" //strYDataFldName = "Z"; // pTable.Fields.Field(i).Name ' "Dist_to_Rds" ////timefldName = "TSDateTime" ' substitute data/time field name for different dataset ////gageIDFldName = "Name" ' substitute gage ID field name for different dataset //// pSeriesProps.whereClause = whereClause //pAreaSeriesProps.InLegend = true; //show legend ' false = don't show legend //pAreaSeriesProps.Name = A4LGSharedFunctions.Localizer.GetString("GeoNetToolsAlias_1"); ////pSeriesProps.LabelField = "OBJECTID"; //pAreaSeriesProps.ValueFormat = "0 "; //pAreaSeriesProps.SetField(0, strXDataFldName); // timefldName //pAreaSeriesProps.SetField(1, strYDataFldName); //// sort on the X value //IDataSortSeriesProperties pSortFlds; //pSortFlds = (IDataSortSeriesProperties)pAreaSeriesProps; //int idx = 0; //pSortFlds.AddSortingField(strXDataFldName, true, ref idx); ////------------------------------------------------------------------------------- ////------Manhole Locations //IBarSeriesProperties pManHoleSeries; //// create the area graph for the ground elevation //pAreaSeriesProps = pDataGraphT.AddSeries("bar:minmax"); //("scatter_plot") '("line:vertical") //pManHoleSeries = (IBarSeriesProperties)pAreaSeriesProps; //pManHoleSeries.BarStyle = esriBarStyle.esriCylinderBar; //pManHoleSeries.BarSize = 5; //pAreaSeriesProps.SourceData = pManTable;// pLayer //pAreaSeriesProps.ColorType = esriGraphColorType.esriGraphColorCustomAll; //pColor = Globals.GetColor(255, 255, 68); //pAreaSeriesProps.CustomColor = pColor.RGB; // pSymbol.Color.RGB //pAreaSeriesProps.InLegend = true; //show legend ' false = don't show legend //pAreaSeriesProps.Name = "Manhole Locations"; //pAreaSeriesProps.HorizontalAxis = 3; //pAreaSeriesProps.LabelField = "ID"; //pAreaSeriesProps.SetField(0, "X"); //pAreaSeriesProps.SetField(1, "INVERTELEV"); //pAreaSeriesProps.SetField(2, "RIMELEV"); //// sort on the X value ////pSortFlds = (IDataSortSeriesProperties)pAreaSeriesProps; ////idx = 0; ////pSortFlds.AddSortingField("X", true, ref idx); ////---- //// line series - sewer line //currentField = "UPELEV"; //int currentFieldWidth = 1; //for (int k = 3; k >= 0; k--) //{ // switch (k) // { // case 0: // currentField = "UPELEV"; // pColor = Globals.GetColor(76, 230, 0);// green // currentFieldWidth = 3; // break; // case 1: // currentField = "DOWNELEV"; // pColor = Globals.GetColor(76, 0, 255); // currentFieldWidth = 3; // break; // case 2: // currentField = "RIMELEV"; // pColor = Globals.GetColor(76, 230, 255); // currentFieldWidth = 3; // continue; // //break; // case 3: // currentField = "INVERTELEV"; // pColor = Globals.GetColor(255, 230, 0); // currentFieldWidth = 3; // break; // } // ISeriesProperties pLineSeriesProps; // pLineSeriesProps = pDataGraphT.AddSeries("line:vertical"); //("area:vertical") '("scatter_plot") '("line:vertical") // pLineSeriesProps.SourceData = pProfTable; // pLayer // pLineSeriesProps.ColorType = esriGraphColorType.esriGraphColorCustomAll; // pLineSeriesProps.PenProperties.Width = currentFieldWidth; // pLineSeriesProps.CustomColor = pColor.RGB; // pSymbol.Color.RGB // // don't have any symbols on the line, just solid // ILineSeriesProperties pLineSeriesProps2; // pLineSeriesProps2 = (ILineSeriesProperties)pLineSeriesProps;// 'QI // pLineSeriesProps2.SymbolProperties.Style = esriDataGraphTSymbolType.esriDataGraphTSymbolNothing; // // get the fields to graph // strXDataFldName = "M"; // strYDataFldName = currentField; // pLineSeriesProps.InLegend = true; // show legend ' false = don't show legend // pLineSeriesProps.Name = pProfTable.Fields.get_Field(pProfTable.Fields.FindField(currentField)).AliasName; // //pSeriesProps.LabelField = "OBJECTID" // pLineSeriesProps.ValueFormat = "0 "; // pLineSeriesProps.SetField(0, strXDataFldName);// timefldName // pLineSeriesProps.SetField(1, strYDataFldName); // // sort on the X value // pSortFlds = (IDataSortSeriesProperties)pLineSeriesProps; // pSortFlds.AddSortingField(strXDataFldName, true, ref idx); // //---------- end line series //} //pDataGraphBase.UseSelectedSet = false; //ITrackCancel pCancelTracker; //pCancelTracker = new CancelTrackerClass(); //pDataGraphT.Update(pCancelTracker); ////pDataGraphT.get_AxisProperties(0).AutomaticMaximum = true; ////pDataGraphT.get_AxisProperties(0).AutomaticMinimum= true; ////pDataGraphT.get_AxisProperties(1).AutomaticMaximum = true; ////pDataGraphT.get_AxisProperties(1).AutomaticMinimum = true; ////pDataGraphT.get_AxisProperties(2).AutomaticMaximum = true; ////pDataGraphT.get_AxisProperties(2).AutomaticMinimum = true; ////pDataGraphT.get_AxisProperties(3).AutomaticMaximum = true; ////pDataGraphT.get_AxisProperties(3).AutomaticMinimum = true; //// create data graph window //IDataGraphWindow2 pDataGraphWin; //pDataGraphWin = new DataGraphWindowClass(); //pDataGraphWin.DataGraphBase = pDataGraphBase; //pDataGraphWin.Application = app; //// size and position the window //pDataGraphWin.PutPosition(0, 0, 900, 250); //// add the graph to the project //IDataGraphCollection pDataGraphs; //pDataGraphs = (IDataGraphCollection)pMxDoc; //QI //pDataGraphs.AddDataGraph(pDataGraphBase); ////IDataGraphT ptmp = (IDataGraphT)pDataGraphs.DataGraph[1]; ////string fld = ptmp.SeriesProperties[5].GetField(0); ////fld = ptmp.SeriesProperties[5].GetField(1); ////fld = ptmp.SeriesProperties[5].GetField(2); ////fld = ptmp.SeriesProperties[5].LabelField; ////fld = ptmp.SeriesProperties[5].Marks.ToString(); //// fld = ptmp.SeriesProperties[5].HorizontalAxis; //// show the graph //pDataGraphWin.Show(true); } catch (Exception Ex) { MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("ErrorInThe") + "ProfileCreateGraph " + Ex.Message); } finally { pWS = null; pCursor = null; pMxDoc = null; pMap = null; pPolyLineZ = null; pZAwareLineZ = null; pSurface = null; pRasterLayer = null; pRasLay = null; pPtOrigFrom = null; pPtOrigTo = null; pStandAloneTabColl = null; pStandAloneTabMainLabel = null; pTapTable = null; pMainTable = null; pManholeTable = null; pSurfaceTable = null; pMainLabelTable = null; pTableFieldsMainLabel = null; pStandAloneTabMain = null; pTableFieldsMain = null; pStandAloneTabManhole = null; pTableFieldsManhole = null; pStandAloneTabSurface = null; pTableFieldsSurface = null; pStandAloneTabTap = null; pTableFieldsTap = null; pRowBuff = null; pLabelCursor = null; pTapCursor = null; pSegment = null; pLine = null; pFromPnt = null; pToPnt = null; pMidPnt = null; pDataGraphBase = null; pDataGraphT = null; pPtCollection = null; pEnumVertex = null; pPt = null; pAreaSeriesProps = null; pColor = null; pSortFlds = null; pScatterSeriesProps2 = null; pScatterSeriesProps = null; pManHoleSeries = null; pLineSeriesProps2 = null; pLineSeriesProps = null; pCancelTracker = null; pDataGraphWin = null; pDataGraphs = null; } }
public void Execute(ESRI.ArcGIS.esriSystem.IArray paramvalues, ESRI.ArcGIS.esriSystem.ITrackCancel TrackCancel, ESRI.ArcGIS.Geoprocessing.IGPEnvironmentManager envMgr, ESRI.ArcGIS.Geodatabase.IGPMessages message) { IFeatureClass osmPointFeatureClass = null; IFeatureClass osmLineFeatureClass = null; IFeatureClass osmPolygonFeatureClass = null; OSMToolHelper osmToolHelper = null; try { DateTime syncTime = DateTime.Now; IGPUtilities3 gpUtilities3 = new GPUtilitiesClass(); osmToolHelper = new OSMToolHelper(); if (TrackCancel == null) { TrackCancel = new CancelTrackerClass(); } IGPParameter osmFileParameter = paramvalues.get_Element(in_osmFileNumber) as IGPParameter; IGPValue osmFileLocationString = gpUtilities3.UnpackGPValue(osmFileParameter) as IGPValue; // ensure that the specified file does exist bool osmFileExists = false; try { osmFileExists = System.IO.File.Exists(osmFileLocationString.GetAsText()); } catch (Exception ex) { message.AddError(120029, String.Format(resourceManager.GetString("GPTools_OSMGPMultiLoader_problemaccessingfile"), ex.Message)); return; } if (osmFileExists == false) { message.AddError(120030, String.Format(resourceManager.GetString("GPTools_OSMGPFileReader_osmfiledoesnotexist"), osmFileLocationString.GetAsText())); return; } long nodeCapacity = 0; long wayCapacity = 0; long relationCapacity = 0; // this assume a clean, tidy XML file - if this is not the case, there will by sync issues later on osmToolHelper.countOSMStuffFast(osmFileLocationString.GetAsText(), ref nodeCapacity, ref wayCapacity, ref relationCapacity, ref TrackCancel); if (nodeCapacity == 0 && wayCapacity == 0 && relationCapacity == 0) { return; } message.AddMessage(String.Format(resourceManager.GetString("GPTools_OSMGPMultiLoader_countedElements"), nodeCapacity, wayCapacity, relationCapacity)); // determine the number of threads to be used IGPEnvironment parallelProcessingFactorEnvironment = OSMToolHelper.getEnvironment(envMgr, "parallelProcessingFactor"); IGPString parallelProcessingFactorString = parallelProcessingFactorEnvironment.Value as IGPString; // the default value is to use half the cores for additional threads - I am aware that we are comparing apples and oranges but I need a number int numberOfThreads = Convert.ToInt32(System.Environment.ProcessorCount / 2); if (!(parallelProcessingFactorEnvironment.Value.IsEmpty())) { if (!Int32.TryParse(parallelProcessingFactorString.Value, out numberOfThreads)) { // this case we have a percent string string resultString = Regex.Match(parallelProcessingFactorString.Value, @"\d+").Value; numberOfThreads = Convert.ToInt32(Int32.Parse(resultString) / 100 * System.Environment.ProcessorCount); } } // tread the special case of 0 if (numberOfThreads <= 0) numberOfThreads = 1; IGPEnvironment configKeyword = OSMToolHelper.getEnvironment(envMgr, "configKeyword"); IGPString gpString = configKeyword.Value as IGPString; string storageKeyword = String.Empty; if (gpString != null) { storageKeyword = gpString.Value; } // determine the temp folder to be use for the intermediate files IGPEnvironment scratchWorkspaceEnvironment = OSMToolHelper.getEnvironment(envMgr, "scratchWorkspace"); IDEWorkspace deWorkspace = scratchWorkspaceEnvironment.Value as IDEWorkspace; String scratchWorkspaceFolder = String.Empty; if (deWorkspace != null) { if (scratchWorkspaceEnvironment.Value.IsEmpty()) { scratchWorkspaceFolder = (new System.IO.FileInfo(osmFileLocationString.GetAsText())).DirectoryName; } else { if (deWorkspace.WorkspaceType == esriWorkspaceType.esriRemoteDatabaseWorkspace) { scratchWorkspaceFolder = System.IO.Path.GetTempPath(); } else if (deWorkspace.WorkspaceType == esriWorkspaceType.esriFileSystemWorkspace) { scratchWorkspaceFolder = ((IDataElement)deWorkspace).CatalogPath; } else { scratchWorkspaceFolder = (new System.IO.FileInfo(((IDataElement)deWorkspace).CatalogPath)).DirectoryName; } } } else { scratchWorkspaceFolder = (new System.IO.FileInfo(osmFileLocationString.GetAsText())).DirectoryName; } string metadataAbstract = resourceManager.GetString("GPTools_OSMGPFileReader_metadata_abstract"); string metadataPurpose = resourceManager.GetString("GPTools_OSMGPFileReader_metadata_purpose"); IGPParameter osmPointsFeatureClassParameter = paramvalues.get_Element(out_osmPointsNumber) as IGPParameter; IGPValue osmPointsFeatureClassGPValue = gpUtilities3.UnpackGPValue(osmPointsFeatureClassParameter) as IGPValue; IName workspaceName = gpUtilities3.CreateParentFromCatalogPath(osmPointsFeatureClassGPValue.GetAsText()); IWorkspace2 pointFeatureWorkspace = workspaceName.Open() as IWorkspace2; string[] pointFCNameElements = osmPointsFeatureClassGPValue.GetAsText().Split(System.IO.Path.DirectorySeparatorChar); IGPParameter tagPointCollectionParameter = paramvalues.get_Element(in_pointFieldNamesNumber) as IGPParameter; IGPMultiValue tagPointCollectionGPValue = gpUtilities3.UnpackGPValue(tagPointCollectionParameter) as IGPMultiValue; List<String> pointTagstoExtract = null; if (tagPointCollectionGPValue.Count > 0) { pointTagstoExtract = new List<string>(); for (int valueIndex = 0; valueIndex < tagPointCollectionGPValue.Count; valueIndex++) { string nameOfTag = tagPointCollectionGPValue.get_Value(valueIndex).GetAsText(); pointTagstoExtract.Add(nameOfTag); } } else { pointTagstoExtract = OSMToolHelper.OSMSmallFeatureClassFields(); } // points try { osmPointFeatureClass = osmToolHelper.CreateSmallPointFeatureClass(pointFeatureWorkspace, pointFCNameElements[pointFCNameElements.Length - 1], storageKeyword, metadataAbstract, metadataPurpose, pointTagstoExtract); } catch (Exception ex) { message.AddError(120035, String.Format(resourceManager.GetString("GPTools_OSMGPDownload_nullpointfeatureclass"), ex.Message)); return; } if (osmPointFeatureClass == null) { return; } int osmPointIDFieldIndex = osmPointFeatureClass.FindField("OSMID"); Dictionary<string, int> mainPointAttributeFieldIndices = new Dictionary<string, int>(); foreach (string fieldName in OSMToolHelper.OSMSmallFeatureClassFields()) { int currentFieldIndex = osmPointFeatureClass.FindField(fieldName); if (currentFieldIndex != -1) { mainPointAttributeFieldIndices.Add(fieldName, currentFieldIndex); } } int tagCollectionPointFieldIndex = osmPointFeatureClass.FindField("osmTags"); int osmSupportingElementPointFieldIndex = osmPointFeatureClass.FindField("osmSupportingElement"); IGPParameter osmLineFeatureClassParameter = paramvalues.get_Element(out_osmLinesNumber) as IGPParameter; IGPValue osmLineFeatureClassGPValue = gpUtilities3.UnpackGPValue(osmLineFeatureClassParameter) as IGPValue; IName lineWorkspaceName = gpUtilities3.CreateParentFromCatalogPath(osmLineFeatureClassGPValue.GetAsText()); IWorkspace2 lineFeatureWorkspace = lineWorkspaceName.Open() as IWorkspace2; string[] lineFCNameElements = osmLineFeatureClassGPValue.GetAsText().Split(System.IO.Path.DirectorySeparatorChar); IGPParameter tagLineCollectionParameter = paramvalues.get_Element(in_lineFieldNamesNumber) as IGPParameter; IGPMultiValue tagLineCollectionGPValue = gpUtilities3.UnpackGPValue(tagLineCollectionParameter) as IGPMultiValue; List<String> lineTagstoExtract = null; if (tagLineCollectionGPValue.Count > 0) { lineTagstoExtract = new List<string>(); for (int valueIndex = 0; valueIndex < tagLineCollectionGPValue.Count; valueIndex++) { string nameOfTag = tagLineCollectionGPValue.get_Value(valueIndex).GetAsText(); lineTagstoExtract.Add(nameOfTag); } } else { lineTagstoExtract = OSMToolHelper.OSMSmallFeatureClassFields(); } // lines try { osmLineFeatureClass = osmToolHelper.CreateSmallLineFeatureClass(lineFeatureWorkspace, lineFCNameElements[lineFCNameElements.Length -1], storageKeyword, metadataAbstract, metadataPurpose, lineTagstoExtract); } catch (Exception ex) { message.AddError(120036, String.Format(resourceManager.GetString("GPTools_OSMGPDownload_nulllinefeatureclass"), ex.Message)); return; } if (osmLineFeatureClass == null) { return; } int osmLineIDFieldIndex = osmLineFeatureClass.FindField("OSMID"); Dictionary<string, int> mainLineAttributeFieldIndices = new Dictionary<string, int>(); foreach (string fieldName in OSMToolHelper.OSMSmallFeatureClassFields()) { int currentFieldIndex = osmLineFeatureClass.FindField(fieldName); if (currentFieldIndex != -1) { mainLineAttributeFieldIndices.Add(fieldName, currentFieldIndex); } } int tagCollectionPolylineFieldIndex = osmLineFeatureClass.FindField("osmTags"); int osmSupportingElementPolylineFieldIndex = osmLineFeatureClass.FindField("osmSupportingElement"); IGPParameter osmPolygonFeatureClassParameter = paramvalues.get_Element(out_osmPolygonsNumber) as IGPParameter; IGPValue osmPolygonFeatureClassGPValue = gpUtilities3.UnpackGPValue(osmPolygonFeatureClassParameter) as IGPValue; IName polygonWorkspaceName = gpUtilities3.CreateParentFromCatalogPath(osmPolygonFeatureClassGPValue.GetAsText()); IWorkspace2 polygonFeatureWorkspace = polygonWorkspaceName.Open() as IWorkspace2; string[] polygonFCNameElements = osmPolygonFeatureClassGPValue.GetAsText().Split(System.IO.Path.DirectorySeparatorChar); IGPParameter tagPolygonCollectionParameter = paramvalues.get_Element(in_polygonFieldNamesNumber) as IGPParameter; IGPMultiValue tagPolygonCollectionGPValue = gpUtilities3.UnpackGPValue(tagPolygonCollectionParameter) as IGPMultiValue; List<String> polygonTagstoExtract = null; if (tagPolygonCollectionGPValue.Count > 0) { polygonTagstoExtract = new List<string>(); for (int valueIndex = 0; valueIndex < tagPolygonCollectionGPValue.Count; valueIndex++) { string nameOfTag = tagPolygonCollectionGPValue.get_Value(valueIndex).GetAsText(); polygonTagstoExtract.Add(nameOfTag); } } else { polygonTagstoExtract = OSMToolHelper.OSMSmallFeatureClassFields(); } // polygons try { osmPolygonFeatureClass = osmToolHelper.CreateSmallPolygonFeatureClass(polygonFeatureWorkspace, polygonFCNameElements[polygonFCNameElements.Length -1], storageKeyword, metadataAbstract, metadataPurpose, polygonTagstoExtract); } catch (Exception ex) { message.AddError(120037, String.Format(resourceManager.GetString("GPTools_OSMGPDownload_nullpolygonfeatureclass"), ex.Message)); return; } if (osmPolygonFeatureClass == null) { return; } int osmPolygonIDFieldIndex = osmPolygonFeatureClass.FindField("OSMID"); Dictionary<string, int> mainPolygonAttributeFieldIndices = new Dictionary<string, int>(); foreach (var fieldName in OSMToolHelper.OSMSmallFeatureClassFields()) { int currentFieldIndex = osmPolygonFeatureClass.FindField(fieldName); if (currentFieldIndex != -1) { mainPolygonAttributeFieldIndices.Add(fieldName, currentFieldIndex); } } int tagCollectionPolygonFieldIndex = osmPolygonFeatureClass.FindField("osmTags"); int osmSupportingElementPolygonFieldIndex = osmPolygonFeatureClass.FindField("osmSupportingElement"); ComReleaser.ReleaseCOMObject(osmPointFeatureClass); osmPointFeatureClass = null; ComReleaser.ReleaseCOMObject(osmLineFeatureClass); osmLineFeatureClass = null; ComReleaser.ReleaseCOMObject(osmPolygonFeatureClass); osmPolygonFeatureClass = null; List<string> nodeOSMFileNames = new List<string>(numberOfThreads); List<string> nodeGDBFileNames = new List<string>(numberOfThreads); List<string> wayOSMFileNames = new List<string>(numberOfThreads); List<string> wayGDBFileNames = new List<string>(numberOfThreads); List<string> relationOSMFileNames = new List<string>(numberOfThreads); List<string> relationGDBFileNames = new List<string>(numberOfThreads); if (TrackCancel.Continue() == false) { return; } // split the original OSM xml file into smaller pieces for the python processes osmToolHelper.splitOSMFile(osmFileLocationString.GetAsText(), scratchWorkspaceFolder, nodeCapacity, wayCapacity, relationCapacity, numberOfThreads, out nodeOSMFileNames, out nodeGDBFileNames, out wayOSMFileNames, out wayGDBFileNames, out relationOSMFileNames, out relationGDBFileNames); IGPParameter deleteSourceOSMFileParameter = paramvalues.get_Element(in_deleteOSMSourceFileNumber) as IGPParameter; IGPBoolean deleteSourceOSMFileGPValue = gpUtilities3.UnpackGPValue(deleteSourceOSMFileParameter) as IGPBoolean; if (deleteSourceOSMFileGPValue.Value) { try { System.IO.File.Delete(osmFileLocationString.GetAsText()); } catch (Exception ex) { message.AddWarning(ex.Message); } } if (TrackCancel.Continue() == false) { return; } if (nodeOSMFileNames.Count == 0) { nodeOSMFileNames.Add(osmFileLocationString.GetAsText()); nodeGDBFileNames.Add(osmPointsFeatureClassGPValue.GetAsText()); wayOSMFileNames.Add(osmFileLocationString.GetAsText()); wayGDBFileNames.Add(osmLineFeatureClassGPValue.GetAsText()); relationOSMFileNames.Add(osmFileLocationString.GetAsText()); relationGDBFileNames.Add(osmPolygonFeatureClassGPValue.GetAsText()); } else { // for the nodes let's load one of the parts directly into the target file geodatabase nodeGDBFileNames[0] = ((IWorkspace)pointFeatureWorkspace).PathName; } // define variables helping to invoke core tools for data management IGeoProcessorResult2 gpResults2 = null; IGeoProcessor2 geoProcessor = new GeoProcessorClass(); IGPParameter deleteSupportingNodesParameter = paramvalues.get_Element(in_deleteSupportNodesNumber) as IGPParameter; IGPBoolean deleteSupportingNodesGPValue = gpUtilities3.UnpackGPValue(deleteSupportingNodesParameter) as IGPBoolean; #region load points osmToolHelper.loadOSMNodes(nodeOSMFileNames, nodeGDBFileNames, pointFCNameElements[pointFCNameElements.Length - 1], osmPointsFeatureClassGPValue.GetAsText(), pointTagstoExtract, deleteSupportingNodesGPValue.Value, ref message, ref TrackCancel); #endregion if (TrackCancel.Continue() == false) { return; } #region load ways osmToolHelper.loadOSMWays(wayOSMFileNames, osmPointsFeatureClassGPValue.GetAsText(), wayGDBFileNames, lineFCNameElements[lineFCNameElements.Length - 1], polygonFCNameElements[polygonFCNameElements.Length - 1], lineTagstoExtract, polygonTagstoExtract, ref message, ref TrackCancel); #endregion #region for local geodatabases enforce spatial integrity bool storedOriginalLocal = geoProcessor.AddOutputsToMap; geoProcessor.AddOutputsToMap = false; try { osmLineFeatureClass = ((IFeatureWorkspace)lineFeatureWorkspace).OpenFeatureClass(lineFCNameElements[lineFCNameElements.Length - 1]); if (osmLineFeatureClass != null) { if (((IDataset)osmLineFeatureClass).Workspace.Type == esriWorkspaceType.esriLocalDatabaseWorkspace) { gpUtilities3 = new GPUtilitiesClass() as IGPUtilities3; IGPParameter outLinesParameter = paramvalues.get_Element(out_osmLinesNumber) as IGPParameter; IGPValue lineFeatureClass = gpUtilities3.UnpackGPValue(outLinesParameter); DataManagementTools.RepairGeometry repairlineGeometry = new DataManagementTools.RepairGeometry(osmLineFeatureClass); IVariantArray repairGeometryParameterArray = new VarArrayClass(); repairGeometryParameterArray.Add(lineFeatureClass.GetAsText()); repairGeometryParameterArray.Add("DELETE_NULL"); gpResults2 = geoProcessor.Execute(repairlineGeometry.ToolName, repairGeometryParameterArray, TrackCancel) as IGeoProcessorResult2; message.AddMessages(gpResults2.GetResultMessages()); ComReleaser.ReleaseCOMObject(gpUtilities3); } } } catch { } finally { ComReleaser.ReleaseCOMObject(osmLineFeatureClass); } try { osmPolygonFeatureClass = ((IFeatureWorkspace)polygonFeatureWorkspace).OpenFeatureClass(polygonFCNameElements[polygonFCNameElements.Length - 1]); if (osmPolygonFeatureClass != null) { if (((IDataset)osmPolygonFeatureClass).Workspace.Type == esriWorkspaceType.esriLocalDatabaseWorkspace) { gpUtilities3 = new GPUtilitiesClass() as IGPUtilities3; IGPParameter outPolygonParameter = paramvalues.get_Element(out_osmPolygonsNumber) as IGPParameter; IGPValue polygonFeatureClass = gpUtilities3.UnpackGPValue(outPolygonParameter); DataManagementTools.RepairGeometry repairpolygonGeometry = new DataManagementTools.RepairGeometry(osmPolygonFeatureClass); IVariantArray repairGeometryParameterArray = new VarArrayClass(); repairGeometryParameterArray.Add(polygonFeatureClass.GetAsText()); repairGeometryParameterArray.Add("DELETE_NULL"); gpResults2 = geoProcessor.Execute(repairpolygonGeometry.ToolName, repairGeometryParameterArray, TrackCancel) as IGeoProcessorResult2; message.AddMessages(gpResults2.GetResultMessages()); ComReleaser.ReleaseCOMObject(gpUtilities3); } } } catch { } finally { ComReleaser.ReleaseCOMObject(osmPolygonFeatureClass); } geoProcessor.AddOutputsToMap = storedOriginalLocal; #endregion if (TrackCancel.Continue() == false) { return; } #region load relations osmToolHelper.loadOSMRelations(relationOSMFileNames, osmLineFeatureClassGPValue.GetAsText(), osmPolygonFeatureClassGPValue.GetAsText(), relationGDBFileNames, lineTagstoExtract, polygonTagstoExtract, ref TrackCancel, ref message); #endregion // check for user interruption if (TrackCancel.Continue() == false) { return; } #region for local geodatabases enforce spatial integrity //storedOriginalLocal = geoProcessor.AddOutputsToMap; //geoProcessor.AddOutputsToMap = false; //try //{ // osmLineFeatureClass = ((IFeatureWorkspace)lineFeatureWorkspace).OpenFeatureClass(lineFCNameElements[lineFCNameElements.Length - 1]); // if (osmLineFeatureClass != null) // { // if (((IDataset)osmLineFeatureClass).Workspace.Type == esriWorkspaceType.esriLocalDatabaseWorkspace) // { // gpUtilities3 = new GPUtilitiesClass() as IGPUtilities3; // IGPParameter outLinesParameter = paramvalues.get_Element(out_osmLinesNumber) as IGPParameter; // IGPValue lineFeatureClass = gpUtilities3.UnpackGPValue(outLinesParameter); // DataManagementTools.RepairGeometry repairlineGeometry = new DataManagementTools.RepairGeometry(osmLineFeatureClass); // IVariantArray repairGeometryParameterArray = new VarArrayClass(); // repairGeometryParameterArray.Add(lineFeatureClass.GetAsText()); // repairGeometryParameterArray.Add("DELETE_NULL"); // gpResults2 = geoProcessor.Execute(repairlineGeometry.ToolName, repairGeometryParameterArray, TrackCancel) as IGeoProcessorResult2; // message.AddMessages(gpResults2.GetResultMessages()); // ComReleaser.ReleaseCOMObject(gpUtilities3); // } // } //} //catch { } //finally //{ // ComReleaser.ReleaseCOMObject(osmLineFeatureClass); //} //try //{ // osmPolygonFeatureClass = ((IFeatureWorkspace)polygonFeatureWorkspace).OpenFeatureClass(polygonFCNameElements[polygonFCNameElements.Length - 1]); // if (osmPolygonFeatureClass != null) // { // if (((IDataset)osmPolygonFeatureClass).Workspace.Type == esriWorkspaceType.esriLocalDatabaseWorkspace) // { // gpUtilities3 = new GPUtilitiesClass() as IGPUtilities3; // IGPParameter outPolygonParameter = paramvalues.get_Element(out_osmPolygonsNumber) as IGPParameter; // IGPValue polygonFeatureClass = gpUtilities3.UnpackGPValue(outPolygonParameter); // DataManagementTools.RepairGeometry repairpolygonGeometry = new DataManagementTools.RepairGeometry(osmPolygonFeatureClass); // IVariantArray repairGeometryParameterArray = new VarArrayClass(); // repairGeometryParameterArray.Add(polygonFeatureClass.GetAsText()); // repairGeometryParameterArray.Add("DELETE_NULL"); // gpResults2 = geoProcessor.Execute(repairpolygonGeometry.ToolName, repairGeometryParameterArray, TrackCancel) as IGeoProcessorResult2; // message.AddMessages(gpResults2.GetResultMessages()); // ComReleaser.ReleaseCOMObject(gpUtilities3); // } // } //} //catch { } //finally //{ // ComReleaser.ReleaseCOMObject(osmPolygonFeatureClass); //} //geoProcessor.AddOutputsToMap = storedOriginalLocal; #endregion if (TrackCancel.Continue() == false) { return; } if (deleteSupportingNodesGPValue.Value) { message.AddMessage(String.Format(resourceManager.GetString("GPTools_OSMGPMultiLoader_remove_supportNodes"))); storedOriginalLocal = geoProcessor.AddOutputsToMap; geoProcessor.AddOutputsToMap = false; // create a layer file to select the points that have attributes osmPointFeatureClass = ((IFeatureWorkspace)pointFeatureWorkspace).OpenFeatureClass(pointFCNameElements[pointFCNameElements.Length - 1]); IVariantArray makeFeatureLayerParameterArray = new VarArrayClass(); makeFeatureLayerParameterArray.Add(osmPointsFeatureClassGPValue.GetAsText()); string tempLayerFile = System.IO.Path.GetTempFileName(); makeFeatureLayerParameterArray.Add(tempLayerFile); makeFeatureLayerParameterArray.Add(String.Format("{0} = 'no'", osmPointFeatureClass.SqlIdentifier("osmSupportingElement"))); geoProcessor.Execute("MakeFeatureLayer_management", makeFeatureLayerParameterArray, TrackCancel); // copy the features into its own feature class IVariantArray copyFeatureParametersArray = new VarArrayClass(); copyFeatureParametersArray.Add(tempLayerFile); string tempFeatureClass = String.Join("\\", new string[] { ((IWorkspace)pointFeatureWorkspace).PathName, "t_" + pointFCNameElements[pointFCNameElements.Length - 1] }); copyFeatureParametersArray.Add(tempFeatureClass); geoProcessor.Execute("CopyFeatures_management", copyFeatureParametersArray, TrackCancel); // delete the temp file System.IO.File.Delete(tempLayerFile); // delete the original feature class IVariantArray deleteParameterArray = new VarArrayClass(); deleteParameterArray.Add(osmPointsFeatureClassGPValue.GetAsText()); geoProcessor.Execute("Delete_management", deleteParameterArray, TrackCancel); // rename the temp feature class back to the original IVariantArray renameParameterArray = new VarArrayClass(); renameParameterArray.Add(tempFeatureClass); renameParameterArray.Add(osmPointsFeatureClassGPValue.GetAsText()); geoProcessor.Execute("Rename_management", renameParameterArray, TrackCancel); geoProcessor.AddOutputsToMap = storedOriginalLocal; ComReleaser.ReleaseCOMObject(osmPointFeatureClass); ComReleaser.ReleaseCOMObject(geoProcessor); } gpUtilities3 = new GPUtilitiesClass() as IGPUtilities3; // repackage the feature class into their respective gp values IGPParameter pointFeatureClassParameter = paramvalues.get_Element(out_osmPointsNumber) as IGPParameter; IGPValue pointFeatureClassGPValue = gpUtilities3.UnpackGPValue(pointFeatureClassParameter); gpUtilities3.PackGPValue(pointFeatureClassGPValue, pointFeatureClassParameter); IGPParameter lineFeatureClassParameter = paramvalues.get_Element(out_osmLinesNumber) as IGPParameter; IGPValue line1FeatureClassGPValue = gpUtilities3.UnpackGPValue(lineFeatureClassParameter); gpUtilities3.PackGPValue(line1FeatureClassGPValue, lineFeatureClassParameter); IGPParameter polygonFeatureClassParameter = paramvalues.get_Element(out_osmPolygonsNumber) as IGPParameter; IGPValue polygon1FeatureClassGPValue = gpUtilities3.UnpackGPValue(polygonFeatureClassParameter); gpUtilities3.PackGPValue(polygon1FeatureClassGPValue, polygonFeatureClassParameter); ComReleaser.ReleaseCOMObject(osmFileLocationString); gpUtilities3.ReleaseInternals(); ComReleaser.ReleaseCOMObject(gpUtilities3); } catch (Exception ex) { message.AddError(120055, ex.Message); message.AddError(120055, ex.StackTrace); } finally { try { osmToolHelper = null; System.GC.Collect(); System.GC.WaitForPendingFinalizers(); } catch (Exception ex) { message.AddError(120056, ex.ToString()); } } }
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 void Execute(ESRI.ArcGIS.esriSystem.IArray paramvalues, ESRI.ArcGIS.esriSystem.ITrackCancel TrackCancel, ESRI.ArcGIS.Geoprocessing.IGPEnvironmentManager envMgr, ESRI.ArcGIS.Geodatabase.IGPMessages message) { try { IGPUtilities3 gpUtilities3 = new GPUtilitiesClass(); if (TrackCancel == null) { TrackCancel = new CancelTrackerClass(); } IGPParameter inputSourceLayerParameter = paramvalues.get_Element(in_sourcelayerNumber) as IGPParameter; IGPValue inputSourceLayerGPValue = gpUtilities3.UnpackGPValue(inputSourceLayerParameter) as IGPValue; IGPParameter inputTargetLayerParameter = paramvalues.get_Element(in_targetlayerNumber) as IGPParameter; IGPValue inputTargetLayerGPValue = gpUtilities3.UnpackGPValue(inputTargetLayerParameter) as IGPValue; ILayer sourceLayer = gpUtilities3.DecodeLayer(inputSourceLayerGPValue); ILayer targetLayer = gpUtilities3.DecodeLayer(inputTargetLayerGPValue); ILayerExtensions sourceLayerExtensions = sourceLayer as ILayerExtensions; if (sourceLayerExtensions == null) { message.AddWarning(resourceManager.GetString("GPTools_GPCopyLayerExtension_source_noext_support")); return; } ILayerExtensions targetLayerExtensions = targetLayer as ILayerExtensions; if (targetLayerExtensions == null) { message.AddWarning(resourceManager.GetString("GPTools_GPCopyLayerExtension_target_noext_support")); return; } // test if the feature classes already exists, // if they do and the environments settings are such that an overwrite is not allowed we need to abort at this point IGeoProcessorSettings gpSettings = (IGeoProcessorSettings)envMgr; if (gpSettings.OverwriteOutput == true) { } else { if (gpUtilities3.Exists(inputTargetLayerGPValue) == true) { message.AddError(120003, String.Format(resourceManager.GetString("GPTools_GPCopyLayerExtension_targetlayeralreadyexists"), inputTargetLayerGPValue.GetAsText())); return; } } for (int targetExtensionIndex = 0; targetExtensionIndex < targetLayerExtensions.ExtensionCount; targetExtensionIndex++) { targetLayerExtensions.RemoveExtension(targetExtensionIndex); } for (int sourceExtensionIndex = 0; sourceExtensionIndex < sourceLayerExtensions.ExtensionCount; sourceExtensionIndex++) { targetLayerExtensions.AddExtension(sourceLayerExtensions.get_Extension(sourceExtensionIndex)); } } catch (Exception ex) { message.AddError(120004, ex.Message); } }
public void Execute(ESRI.ArcGIS.esriSystem.IArray paramvalues, ESRI.ArcGIS.esriSystem.ITrackCancel TrackCancel, ESRI.ArcGIS.Geoprocessing.IGPEnvironmentManager envMgr, ESRI.ArcGIS.Geodatabase.IGPMessages message) { try { IGPUtilities3 gpUtilities3 = new GPUtilitiesClass(); if (TrackCancel == null) { TrackCancel = new CancelTrackerClass(); } // find feature class inside the given feature dataset IGPParameter osmFeatureDatasetParameter = paramvalues.get_Element(in_osmFeatureDatasetNumber) as IGPParameter; IDEFeatureDataset osmFeatureDataset = gpUtilities3.UnpackGPValue(osmFeatureDatasetParameter) as IDEFeatureDataset; string osmPointFeatureClassString = ((IDataElement)osmFeatureDataset).Name + "_osm_pt"; string osmLineFeatureClassString = ((IDataElement)osmFeatureDataset).Name + "_osm_ln"; string osmPolygonFeatureClassString = ((IDataElement)osmFeatureDataset).Name + "_osm_ply"; IFeatureClass osmPointFeatureClass = gpUtilities3.OpenFeatureClassFromString(((IDataElement)osmFeatureDataset).CatalogPath + "/" + osmPointFeatureClassString); IFeatureClass osmLineFeatureClass = gpUtilities3.OpenFeatureClassFromString(((IDataElement)osmFeatureDataset).CatalogPath + "/" + osmLineFeatureClassString); IFeatureClass osmPoylgonFeatureClass = gpUtilities3.OpenFeatureClassFromString(((IDataElement)osmFeatureDataset).CatalogPath + "/" + osmPolygonFeatureClassString); // open the specified layers holding the symbology and editing templates IGPParameter osmPointSymbolTemplateParameter = paramvalues.get_Element(in_osmPointLayerNumber) as IGPParameter; IGPValue osmGPPointLayerValue = gpUtilities3.UnpackGPValue(osmPointSymbolTemplateParameter); IGPParameter outputPointGPParameter = paramvalues.get_Element(out_osmPointLayerNumber) as IGPParameter; IGPValue outputPointLayerGPValue = gpUtilities3.UnpackGPValue(outputPointGPParameter); bool isLayerOnDisk = false; // create a clone of the source layer // we will then go ahead and adjust the data source (dataset) of the cloned layer IObjectCopy objectCopy = new ObjectCopyClass(); ICompositeLayer adjustedPointTemplateLayer = objectCopy.Copy(osmGPPointLayerValue) as ICompositeLayer; IGPGroupLayer osmPointGroupTemplateLayer = adjustedPointTemplateLayer as IGPGroupLayer; ICompositeLayer compositeLayer = gpUtilities3.Open((IGPValue)osmPointGroupTemplateLayer) as ICompositeLayer; //ICompositeLayer adjustedPointTemplateLayer = osmGPPointLayerValue as ICompositeLayer; //IGPGroupLayer osmPointGroupTemplateLayer = osmGPPointLayerValue as IGPGroupLayer; //IClone cloneSource = osmPointGroupTemplateLayer as IClone; //ICompositeLayer compositeLayer = m_gpUtilities3.Open((IGPValue)cloneSource.Clone()) as ICompositeLayer; if (compositeLayer == null) { ILayerFactoryHelper layerFactoryHelper = new LayerFactoryHelperClass(); IFileName layerFileName = new FileNameClass(); layerFileName.Path = osmGPPointLayerValue.GetAsText(); IEnumLayer enumLayer = layerFactoryHelper.CreateLayersFromName((IName)layerFileName); enumLayer.Reset(); compositeLayer = enumLayer.Next() as ICompositeLayer; isLayerOnDisk = true; } IFeatureLayerDefinition2 featureLayerDefinition2 = null; ISQLSyntax sqlSyntax = null; IGPLayer adjustedPointGPLayer = null; if (compositeLayer != null) { for (int layerIndex = 0; layerIndex < compositeLayer.Count; layerIndex++) { IFeatureLayer2 geoFeatureLayer = compositeLayer.get_Layer(layerIndex) as IFeatureLayer2; if (geoFeatureLayer != null) { if (geoFeatureLayer.ShapeType == osmPointFeatureClass.ShapeType) { try { ((IDataLayer2)geoFeatureLayer).Disconnect(); } catch { } ((IDataLayer2)geoFeatureLayer).DataSourceName = ((IDataset)osmPointFeatureClass).FullName; ((IDataLayer2)geoFeatureLayer).Connect(((IDataset)osmPointFeatureClass).FullName); featureLayerDefinition2 = geoFeatureLayer as IFeatureLayerDefinition2; if (featureLayerDefinition2 != null) { string queryDefinition = featureLayerDefinition2.DefinitionExpression; sqlSyntax = ((IDataset)osmPointFeatureClass).Workspace as ISQLSyntax; string delimiterIdentifier = sqlSyntax.GetSpecialCharacter(esriSQLSpecialCharacters.esriSQL_DelimitedIdentifierPrefix); if (String.IsNullOrEmpty(queryDefinition) == false) { string stringToReplace = queryDefinition.Substring(0, 1); queryDefinition = queryDefinition.Replace(stringToReplace, delimiterIdentifier); } featureLayerDefinition2.DefinitionExpression = queryDefinition; } } } } adjustedPointGPLayer = gpUtilities3.MakeGPLayerFromLayer((ILayer)compositeLayer); // save the newly adjusted layer information to disk if (isLayerOnDisk == true) { ILayerFile pointLayerFile = new LayerFileClass(); if (pointLayerFile.get_IsPresent(outputPointLayerGPValue.GetAsText())) { try { File.Delete(outputPointLayerGPValue.GetAsText()); } catch (Exception ex) { message.AddError(120041, ex.Message); return; } } pointLayerFile.New(outputPointLayerGPValue.GetAsText()); pointLayerFile.ReplaceContents((ILayer)compositeLayer); pointLayerFile.Save(); adjustedPointGPLayer = gpUtilities3.MakeGPLayerFromLayer((ILayer)pointLayerFile.Layer); } // IGPLayer adjustedPointGPLayer = gpUtilities3.MakeGPLayerFromLayer((ILayer)compositeLayer); gpUtilities3.AddInternalLayer2((ILayer)compositeLayer, adjustedPointGPLayer); gpUtilities3.PackGPValue((IGPValue)adjustedPointGPLayer, outputPointGPParameter); } isLayerOnDisk = false; IGPParameter osmLineSymbolTemplateParameter = paramvalues.get_Element(in_osmLineLayerNumber) as IGPParameter; IGPValue osmGPLineLayerValue = gpUtilities3.UnpackGPValue(osmLineSymbolTemplateParameter) as IGPValue; IGPParameter outputLineGPParameter = paramvalues.get_Element(out_osmLineLayerNumber) as IGPParameter; IGPValue outputLineLayerGPValue = gpUtilities3.UnpackGPValue(outputLineGPParameter); IGPValue adjustedLineTemplateLayer = objectCopy.Copy(osmGPLineLayerValue) as IGPValue; IGPGroupLayer osmLineGroupTemplateLayer = adjustedLineTemplateLayer as IGPGroupLayer; compositeLayer = gpUtilities3.Open((IGPValue)osmLineGroupTemplateLayer) as ICompositeLayer; if (compositeLayer == null) { ILayerFactoryHelper layerFactoryHelper = new LayerFactoryHelperClass(); IFileName layerFileName = new FileNameClass(); layerFileName.Path = osmGPLineLayerValue.GetAsText(); IEnumLayer enumLayer = layerFactoryHelper.CreateLayersFromName((IName)layerFileName); enumLayer.Reset(); compositeLayer = enumLayer.Next() as ICompositeLayer; isLayerOnDisk = true; } if (compositeLayer != null) { for (int layerIndex = 0; layerIndex < compositeLayer.Count; layerIndex++) { IFeatureLayer2 geoFeatureLayer = compositeLayer.get_Layer(layerIndex) as IFeatureLayer2; if (geoFeatureLayer.ShapeType == osmLineFeatureClass.ShapeType) { try { ((IDataLayer2)geoFeatureLayer).Disconnect(); } catch { } ((IDataLayer2)geoFeatureLayer).DataSourceName = ((IDataset)osmLineFeatureClass).FullName; ((IDataLayer2)geoFeatureLayer).Connect(((IDataset)osmLineFeatureClass).FullName); featureLayerDefinition2 = geoFeatureLayer as IFeatureLayerDefinition2; if (featureLayerDefinition2 != null) { string queryDefinition = featureLayerDefinition2.DefinitionExpression; sqlSyntax = ((IDataset)osmLineFeatureClass).Workspace as ISQLSyntax; string delimiterIdentifier = sqlSyntax.GetSpecialCharacter(esriSQLSpecialCharacters.esriSQL_DelimitedIdentifierPrefix); if (string.IsNullOrEmpty(queryDefinition) == false) { string stringToReplace = queryDefinition.Substring(0, 1); queryDefinition = queryDefinition.Replace(stringToReplace, delimiterIdentifier); } featureLayerDefinition2.DefinitionExpression = queryDefinition; } } } // save the newly adjusted layer information to disk if (isLayerOnDisk == true) { ILayerFile lineLayerFile = new LayerFileClass(); if (lineLayerFile.get_IsPresent(outputLineLayerGPValue.GetAsText())) { try { File.Delete(outputLineLayerGPValue.GetAsText()); } catch (Exception ex) { message.AddError(120042, ex.Message); return; } } lineLayerFile.New(outputLineLayerGPValue.GetAsText()); lineLayerFile.ReplaceContents((ILayer)compositeLayer); lineLayerFile.Save(); } IGPLayer adjustLineGPLayer = gpUtilities3.MakeGPLayerFromLayer((ILayer)compositeLayer); gpUtilities3.AddInternalLayer2((ILayer)compositeLayer, adjustLineGPLayer); gpUtilities3.PackGPValue((IGPValue)adjustLineGPLayer, outputLineGPParameter); } isLayerOnDisk = false; IGPParameter osmPolygonSymbolTemplateParameter = paramvalues.get_Element(in_osmPolygonLayerNumber) as IGPParameter; IGPValue osmGPPolygonLayerValue = gpUtilities3.UnpackGPValue(osmPolygonSymbolTemplateParameter); IGPParameter outputPolygonGPParameter = paramvalues.get_Element(out_osmPolygonLayerNumber) as IGPParameter; IGPValue outputPolygonLayerGPValue = gpUtilities3.UnpackGPValue(outputPolygonGPParameter); IGPValue adjustedPolygonTemplateLayer = objectCopy.Copy(osmGPPolygonLayerValue) as IGPValue; IGPGroupLayer osmPolygonGroupTemplateLayer = adjustedPolygonTemplateLayer as IGPGroupLayer; compositeLayer = gpUtilities3.Open((IGPValue)osmPolygonGroupTemplateLayer) as ICompositeLayer; if (compositeLayer == null) { ILayerFactoryHelper layerFactoryHelper = new LayerFactoryHelperClass(); IFileName layerFileName = new FileNameClass(); layerFileName.Path = osmGPPolygonLayerValue.GetAsText(); IEnumLayer enumLayer = layerFactoryHelper.CreateLayersFromName((IName)layerFileName); enumLayer.Reset(); compositeLayer = enumLayer.Next() as ICompositeLayer; isLayerOnDisk = true; } if (compositeLayer != null) { for (int layerIndex = 0; layerIndex < compositeLayer.Count; layerIndex++) { IFeatureLayer2 geoFeatureLayer = compositeLayer.get_Layer(layerIndex) as IFeatureLayer2; if (geoFeatureLayer.ShapeType == osmPoylgonFeatureClass.ShapeType) { try { ((IDataLayer2)geoFeatureLayer).Disconnect(); } catch { } ((IDataLayer2)geoFeatureLayer).DataSourceName = ((IDataset)osmPoylgonFeatureClass).FullName; ((IDataLayer2)geoFeatureLayer).Connect(((IDataset)osmPoylgonFeatureClass).FullName); featureLayerDefinition2 = geoFeatureLayer as IFeatureLayerDefinition2; if (featureLayerDefinition2 != null) { string queryDefinition = featureLayerDefinition2.DefinitionExpression; sqlSyntax = ((IDataset)osmPoylgonFeatureClass).Workspace as ISQLSyntax; string delimiterIdentifier = sqlSyntax.GetSpecialCharacter(esriSQLSpecialCharacters.esriSQL_DelimitedIdentifierPrefix); if (String.IsNullOrEmpty(queryDefinition) == false) { string stringToReplace = queryDefinition.Substring(0, 1); queryDefinition = queryDefinition.Replace(stringToReplace, delimiterIdentifier); } featureLayerDefinition2.DefinitionExpression = queryDefinition; } } } // save the newly adjusted layer information to disk if (isLayerOnDisk == true) { ILayerFile polygonLayerFile = new LayerFileClass(); if (polygonLayerFile.get_IsPresent(outputPolygonLayerGPValue.GetAsText())) { try { File.Delete(outputPolygonLayerGPValue.GetAsText()); } catch (Exception ex) { message.AddError(120043, ex.Message); return; } } polygonLayerFile.New(outputPolygonLayerGPValue.GetAsText()); polygonLayerFile.ReplaceContents((ILayer)compositeLayer); polygonLayerFile.Save(); } IGPLayer adjustedPolygonGPLayer = gpUtilities3.MakeGPLayerFromLayer((ILayer)compositeLayer); gpUtilities3.AddInternalLayer2((ILayer)compositeLayer, adjustedPolygonGPLayer); gpUtilities3.PackGPValue((IGPValue)adjustedPolygonGPLayer, outputPolygonGPParameter); } } catch (Exception ex) { message.AddError(-10, ex.Message); } }
/// <summary> /// Occurs when this command is clicked /// </summary> public override void OnClick() { try { if (m_application == null) { return; } IDocument document = m_application.Document; ISxDocument sxDocument = (ISxDocument)(document); if (sxDocument != null) { m_scene = sxDocument.Scene; } if (m_scene == null) { return; } activeView = m_scene as IActiveView; //有图层选图层 if (m_scene.LayerCount == 0) { return; } //选择基准面 if (Common.SelectLayer(m_scene.Layers, out SelectedLyrIndex, true, "选择自定义表面") == false) { return; } //QI IRasterLayer baseRasterLayer = m_scene.Layer[SelectedLyrIndex[0]] as IRasterLayer; //不管选多少个只选第一个 if (baseRasterLayer == null) { throw new ArgumentNullException("自定义表面RasterLayer转换失败,为空。"); } IRaster raster = baseRasterLayer.Raster; if (raster == null) { throw new ArgumentNullException("自定义表面Raster转换失败,为空。"); } IRasterSurface rasterSurface = new RasterSurfaceClass(); rasterSurface.PutRaster(raster, 0); ISurface surface = rasterSurface as ISurface; //选择图层 if (Common.SelectLayer(m_scene.Layers, out SelectedLyrIndex, false, "选择要进行偏移的图层") == false) { return; } //选择倍数 NumSelect MultiNS = new NumSelect("输入夸大倍数", true); if (MultiNS.ShowDialog() != DialogResult.OK) { return; } double Multiplier = MultiNS.Result; //选择偏移量 NumSelect NS = new NumSelect(); if (NS.ShowDialog() != DialogResult.OK) { return; } double Offset = NS.Result; bool DisableCache = NS.DisableCache; //Create a CancelTracker. ITrackCancel pTrackCancel = new CancelTrackerClass(); //Create the ProgressDialog. This automatically displays the dialog IProgressDialogFactory pProgDlgFactory = new ProgressDialogFactoryClass(); IProgressDialog2 pProDlg = pProgDlgFactory.Create(pTrackCancel, m_application.hWnd) as IProgressDialog2; pProDlg.CancelEnabled = true; pProDlg.Title = "正在进行自定义表面设置及偏移调整"; pProDlg.Description = "设置中,请稍候..."; pProDlg.Animation = esriProgressAnimationTypes.esriProgressSpiral; IStepProgressor pStepPro = pProDlg as IStepProgressor; pStepPro.MinRange = 0; pStepPro.MaxRange = SelectedLyrIndex.Count; pStepPro.StepValue = 1; pStepPro.Message = "初始化中..."; bool bCont = true; //对每一个选中的图层进行操作 for (int i = 0; i < SelectedLyrIndex.Count; i++) { //m_application.StatusBar.set_Message(0, i.ToString()); pStepPro.Message = "已完成(" + i.ToString() + "/" + SelectedLyrIndex.Count.ToString() + ")"; bCont = pTrackCancel.Continue(); if (!bCont) { break; } //选中一个栅格图层 IRasterLayer rasterLayer = m_scene.Layer[SelectedLyrIndex[i]] as IRasterLayer; if (rasterLayer == null) { pStepPro.Message = "选中的图层非栅格图层..."; continue; } I3DProperties p3DProperties = null; ILayerExtensions layerExtensions = rasterLayer as ILayerExtensions; //遍历LayerExtensions找到I3DProperties for (int j = 0; j < layerExtensions.ExtensionCount; j++) { if (layerExtensions.get_Extension(j) is I3DProperties) { p3DProperties = layerExtensions.get_Extension(j) as I3DProperties; } } //设置I3DProperties p3DProperties.ZFactor = Multiplier; //系数 p3DProperties.BaseOption = esriBaseOption.esriBaseSurface; //基准面浮动 p3DProperties.BaseSurface = surface; //基准面 p3DProperties.OffsetExpressionString = Offset.ToString(); //偏移常量 if (DisableCache) { p3DProperties.RenderMode = esriRenderMode.esriRenderImmediate; //直接从文件渲染 p3DProperties.RenderVisibility = esriRenderVisibility.esriRenderWhenStopped; //停止导航时渲染 } p3DProperties.Apply3DProperties(rasterLayer); } pProDlg.HideDialog(); //========================================== //刷新,不起作用 if (activeView == null) { throw new Exception("活动视图为空! "); } if (m_sceneHookHelper.ActiveViewer == null) { throw new Exception("无活动视图!"); } activeView.Refresh(); m_sceneHookHelper.ActiveViewer.Redraw(true); //========================================== } catch (Exception err) { MessageBox.Show(err.ToString()); } }
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 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; } }
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 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; } }
///<summary>Flash geometry on the display.</summary> ///<param name="geometry"> The input IGeometry to flash. Supported geometry types are GeometryBag, Polygon, Polyline, Point and Multipoint.</param> ///<param name="screenDisplay">An IScreenDisplay reference</param> ///<param name="delay">An integer that is the time in milliseconds to wait.</param> public static void FlashGeometry(IGeometry geometry, IScreenDisplay screenDisplay, int delay, int times) { if (geometry == null || screenDisplay == null) { return; } bool continueFlashing = true; using (ComReleaser comReleaser = new ComReleaser()) { ITrackCancel cancelTracker = new CancelTrackerClass(); comReleaser.ManageLifetime(cancelTracker); screenDisplay.CancelTracker = cancelTracker; short cacheID = screenDisplay.AddCache(); int cacheMemDC = screenDisplay.get_CacheMemDC(cacheID); IRgbColor fillColor = new RgbColorClass(); comReleaser.ManageLifetime(fillColor); fillColor.Green = 128; IRgbColor lineColor = new RgbColorClass(); comReleaser.ManageLifetime(lineColor); screenDisplay.StartDrawing(cacheMemDC, cacheID); DrawGeometry(geometry, fillColor, lineColor, (IDisplay)screenDisplay, cancelTracker); ESRI.ArcGIS.esriSystem.tagRECT RECT = new tagRECT(); screenDisplay.FinishDrawing(); for (int j = 0; j < times; j++) { if (continueFlashing == true) { screenDisplay.DrawCache(screenDisplay.hDC, cacheID, ref RECT, ref RECT); if (delay > 0) { System.Threading.Thread.Sleep(delay); screenDisplay.Invalidate(null, true, cacheID); screenDisplay.UpdateWindow(); System.Threading.Thread.Sleep(delay); } } } //--------------------------------------------------------------------- screenDisplay.RemoveCache(cacheID); cancelTracker.Reset(); } }
public void Execute(ESRI.ArcGIS.esriSystem.IArray paramvalues, ESRI.ArcGIS.esriSystem.ITrackCancel TrackCancel, ESRI.ArcGIS.Geoprocessing.IGPEnvironmentManager envMgr, ESRI.ArcGIS.Geodatabase.IGPMessages message) { try { IGPUtilities3 execute_Utilities = new GPUtilitiesClass(); if (TrackCancel == null) { TrackCancel = new CancelTrackerClass(); } IGPParameter inputFeatureDatasetParameter = paramvalues.get_Element(in_featureDatasetParameterNumber) as IGPParameter; IGPValue inputFeatureDatasetGPValue = execute_Utilities.UnpackGPValue(inputFeatureDatasetParameter); IGPValue outputOSMFileGPValue = execute_Utilities.UnpackGPValue(paramvalues.get_Element(out_osmFileLocationParameterNumber)); // get the name of the feature dataset int fdDemlimiterPosition = inputFeatureDatasetGPValue.GetAsText().LastIndexOf("\\"); string nameOfFeatureDataset = inputFeatureDatasetGPValue.GetAsText().Substring(fdDemlimiterPosition + 1); XmlWriterSettings settings = new XmlWriterSettings(); settings.Indent = true; System.Xml.XmlWriter xmlWriter = null; try { xmlWriter = XmlWriter.Create(outputOSMFileGPValue.GetAsText(), settings); } catch (Exception ex) { message.AddError(120021, ex.Message); return; } xmlWriter.WriteStartDocument(); xmlWriter.WriteStartElement("osm"); // start the osm root node xmlWriter.WriteAttributeString("version", "0.6"); // add the version attribute xmlWriter.WriteAttributeString("generator", "ArcGIS Editor for OpenStreetMap"); // add the generator attribute // write all the nodes // use a feature search cursor to loop through all the known points and write them out as osm node IFeatureClassContainer osmFeatureClasses = execute_Utilities.OpenDataset(inputFeatureDatasetGPValue) as IFeatureClassContainer; if (osmFeatureClasses == null) { message.AddError(120022, string.Format(resourceManager.GetString("GPTools_NullPointerParameterType"), inputFeatureDatasetParameter.Name)); return; } IFeatureClass osmPointFeatureClass = osmFeatureClasses.get_ClassByName(nameOfFeatureDataset + "_osm_pt"); if (osmPointFeatureClass == null) { message.AddError(120023, string.Format(resourceManager.GetString("GPTools_OSMGPExport2OSM_no_pointfeatureclass"), nameOfFeatureDataset + "_osm_pt")); return; } // check the extension of the point feature class to determine its version int internalOSMExtensionVersion = osmPointFeatureClass.OSMExtensionVersion(); IFeatureCursor searchCursor = null; System.Xml.Serialization.XmlSerializerNamespaces xmlnsEmpty = new System.Xml.Serialization.XmlSerializerNamespaces(); xmlnsEmpty.Add("", ""); message.AddMessage(resourceManager.GetString("GPTools_OSMGPExport2OSM_exporting_pts_msg")); int pointCounter = 0; string nodesExportedMessage = String.Empty; // collect the indices for the point feature class once int pointOSMIDFieldIndex = osmPointFeatureClass.Fields.FindField("OSMID"); int pointChangesetFieldIndex = osmPointFeatureClass.Fields.FindField("osmchangeset"); int pointVersionFieldIndex = osmPointFeatureClass.Fields.FindField("osmversion"); int pointUIDFieldIndex = osmPointFeatureClass.Fields.FindField("osmuid"); int pointUserFieldIndex = osmPointFeatureClass.Fields.FindField("osmuser"); int pointTimeStampFieldIndex = osmPointFeatureClass.Fields.FindField("osmtimestamp"); int pointVisibleFieldIndex = osmPointFeatureClass.Fields.FindField("osmvisible"); int pointTagsFieldIndex = osmPointFeatureClass.Fields.FindField("osmTags"); using (ComReleaser comReleaser = new ComReleaser()) { searchCursor = osmPointFeatureClass.Search(null, false); comReleaser.ManageLifetime(searchCursor); System.Xml.Serialization.XmlSerializer pointSerializer = new System.Xml.Serialization.XmlSerializer(typeof(node)); IFeature currentFeature = searchCursor.NextFeature(); IWorkspace pointWorkspace = ((IDataset)osmPointFeatureClass).Workspace; while (currentFeature != null) { if (TrackCancel.Continue() == true) { // convert the found point feature into a osm node representation to store into the OSM XML file node osmNode = ConvertPointFeatureToOSMNode(currentFeature, pointWorkspace, pointTagsFieldIndex, pointOSMIDFieldIndex, pointChangesetFieldIndex, pointVersionFieldIndex, pointUIDFieldIndex, pointUserFieldIndex, pointTimeStampFieldIndex, pointVisibleFieldIndex, internalOSMExtensionVersion); pointSerializer.Serialize(xmlWriter, osmNode, xmlnsEmpty); // increase the point counter to later status report pointCounter++; currentFeature = searchCursor.NextFeature(); } else { // properly close the document xmlWriter.WriteEndElement(); // closing the osm root element xmlWriter.WriteEndDocument(); // finishing the document xmlWriter.Close(); // closing the document // report the number of elements loader so far nodesExportedMessage = String.Format(resourceManager.GetString("GPTools_OSMGPExport2OSM_pts_exported_msg"), pointCounter); message.AddMessage(nodesExportedMessage); return; } } } nodesExportedMessage = String.Format(resourceManager.GetString("GPTools_OSMGPExport2OSM_pts_exported_msg"), pointCounter); message.AddMessage(nodesExportedMessage); // next loop through the line and polygon feature classes to export those features as ways // in case we encounter a multi-part geometry, store it in a relation collection that will be serialized when exporting the relations table IFeatureClass osmLineFeatureClass = osmFeatureClasses.get_ClassByName(nameOfFeatureDataset + "_osm_ln"); if (osmLineFeatureClass == null) { message.AddError(120023, string.Format(resourceManager.GetString("GPTools_OSMGPExport2OSM_no_linefeatureclass"), nameOfFeatureDataset + "_osm_ln")); return; } message.AddMessage(resourceManager.GetString("GPTools_OSMGPExport2OSM_exporting_ways_msg")); // as we are looping through the line and polygon feature classes let's collect the multi-part features separately // as they are considered relations in the OSM world List<relation> multiPartElements = new List<relation>(); System.Xml.Serialization.XmlSerializer waySerializer = new System.Xml.Serialization.XmlSerializer(typeof(way)); int lineCounter = 0; int relationCounter = 0; string waysExportedMessage = String.Empty; using (ComReleaser comReleaser = new ComReleaser()) { searchCursor = osmLineFeatureClass.Search(null, false); comReleaser.ManageLifetime(searchCursor); IFeature currentFeature = searchCursor.NextFeature(); // collect the indices for the point feature class once int lineOSMIDFieldIndex = osmLineFeatureClass.Fields.FindField("OSMID"); int lineChangesetFieldIndex = osmLineFeatureClass.Fields.FindField("osmchangeset"); int lineVersionFieldIndex = osmLineFeatureClass.Fields.FindField("osmversion"); int lineUIDFieldIndex = osmLineFeatureClass.Fields.FindField("osmuid"); int lineUserFieldIndex = osmLineFeatureClass.Fields.FindField("osmuser"); int lineTimeStampFieldIndex = osmLineFeatureClass.Fields.FindField("osmtimestamp"); int lineVisibleFieldIndex = osmLineFeatureClass.Fields.FindField("osmvisible"); int lineTagsFieldIndex = osmLineFeatureClass.Fields.FindField("osmTags"); int lineMembersFieldIndex = osmLineFeatureClass.Fields.FindField("osmMembers"); IWorkspace lineWorkspace = ((IDataset)osmLineFeatureClass).Workspace; while (currentFeature != null) { if (TrackCancel.Continue() == false) { // properly close the document xmlWriter.WriteEndElement(); // closing the osm root element xmlWriter.WriteEndDocument(); // finishing the document xmlWriter.Close(); // closing the document // report the number of elements loaded so far waysExportedMessage = String.Format(resourceManager.GetString("GPTools_OSMGPExport2OSM_ways_exported_msg"), lineCounter); message.AddMessage(waysExportedMessage); return; } //test if the feature geometry has multiple parts IGeometryCollection geometryCollection = currentFeature.Shape as IGeometryCollection; if (geometryCollection != null) { if (geometryCollection.GeometryCount == 1) { // convert the found polyline feature into a osm way representation to store into the OSM XML file way osmWay = ConvertFeatureToOSMWay(currentFeature, lineWorkspace, osmPointFeatureClass, pointOSMIDFieldIndex, lineTagsFieldIndex, lineOSMIDFieldIndex, lineChangesetFieldIndex, lineVersionFieldIndex, lineUIDFieldIndex, lineUserFieldIndex, lineTimeStampFieldIndex, lineVisibleFieldIndex, internalOSMExtensionVersion); waySerializer.Serialize(xmlWriter, osmWay, xmlnsEmpty); // increase the line counter for later status report lineCounter++; } else { relation osmRelation = ConvertRowToOSMRelation((IRow)currentFeature, lineWorkspace, lineTagsFieldIndex, lineOSMIDFieldIndex, lineChangesetFieldIndex, lineVersionFieldIndex, lineUIDFieldIndex, lineUserFieldIndex, lineTimeStampFieldIndex, lineVisibleFieldIndex, lineMembersFieldIndex, internalOSMExtensionVersion); multiPartElements.Add(osmRelation); // increase the line counter for later status report relationCounter++; } } currentFeature = searchCursor.NextFeature(); } } IFeatureClass osmPolygonFeatureClass = osmFeatureClasses.get_ClassByName(nameOfFeatureDataset + "_osm_ply"); IFeatureWorkspace commonWorkspace = ((IDataset)osmPolygonFeatureClass).Workspace as IFeatureWorkspace; if (osmPolygonFeatureClass == null) { message.AddError(120024, string.Format(resourceManager.GetString("GPTools_OSMGPExport2OSM_no_polygonfeatureclass"), nameOfFeatureDataset + "_osm_ply")); return; } using (ComReleaser comReleaser = new ComReleaser()) { searchCursor = osmPolygonFeatureClass.Search(null, false); comReleaser.ManageLifetime(searchCursor); IFeature currentFeature = searchCursor.NextFeature(); // collect the indices for the point feature class once int polygonOSMIDFieldIndex = osmPolygonFeatureClass.Fields.FindField("OSMID"); int polygonChangesetFieldIndex = osmPolygonFeatureClass.Fields.FindField("osmchangeset"); int polygonVersionFieldIndex = osmPolygonFeatureClass.Fields.FindField("osmversion"); int polygonUIDFieldIndex = osmPolygonFeatureClass.Fields.FindField("osmuid"); int polygonUserFieldIndex = osmPolygonFeatureClass.Fields.FindField("osmuser"); int polygonTimeStampFieldIndex = osmPolygonFeatureClass.Fields.FindField("osmtimestamp"); int polygonVisibleFieldIndex = osmPolygonFeatureClass.Fields.FindField("osmvisible"); int polygonTagsFieldIndex = osmPolygonFeatureClass.Fields.FindField("osmTags"); int polygonMembersFieldIndex = osmPolygonFeatureClass.Fields.FindField("osmMembers"); IWorkspace polygonWorkspace = ((IDataset)osmPolygonFeatureClass).Workspace; while (currentFeature != null) { if (TrackCancel.Continue() == false) { // properly close the document xmlWriter.WriteEndElement(); // closing the osm root element xmlWriter.WriteEndDocument(); // finishing the document xmlWriter.Close(); // closing the document // report the number of elements loaded so far waysExportedMessage = String.Format(resourceManager.GetString("GPTools_OSMGPExport2OSM_ways_exported_msg"), lineCounter); message.AddMessage(waysExportedMessage); message.AddAbort(resourceManager.GetString("GPTools_toolabort")); return; } //test if the feature geometry has multiple parts IGeometryCollection geometryCollection = currentFeature.Shape as IGeometryCollection; if (geometryCollection != null) { if (geometryCollection.GeometryCount == 1) { // convert the found polyline feature into a osm way representation to store into the OSM XML file way osmWay = ConvertFeatureToOSMWay(currentFeature, polygonWorkspace, osmPointFeatureClass, pointOSMIDFieldIndex, polygonTagsFieldIndex, polygonOSMIDFieldIndex, polygonChangesetFieldIndex, polygonVersionFieldIndex, polygonUIDFieldIndex, polygonUserFieldIndex, polygonTimeStampFieldIndex, polygonVisibleFieldIndex, internalOSMExtensionVersion); waySerializer.Serialize(xmlWriter, osmWay, xmlnsEmpty); // increase the line counter for later status report lineCounter++; } else { relation osmRelation = ConvertRowToOSMRelation((IRow)currentFeature, polygonWorkspace, polygonTagsFieldIndex, polygonOSMIDFieldIndex, polygonChangesetFieldIndex, polygonVersionFieldIndex, polygonUIDFieldIndex, polygonUserFieldIndex, polygonTimeStampFieldIndex, polygonVisibleFieldIndex, polygonMembersFieldIndex, internalOSMExtensionVersion); multiPartElements.Add(osmRelation); // increase the line counter for later status report relationCounter++; } } currentFeature = searchCursor.NextFeature(); } } waysExportedMessage = String.Format(resourceManager.GetString("GPTools_OSMGPExport2OSM_ways_exported_msg"), lineCounter); message.AddMessage(waysExportedMessage); // now let's go through the relation table message.AddMessage(resourceManager.GetString("GPTools_OSMGPExport2OSM_exporting_relations_msg")); ITable relationTable = commonWorkspace.OpenTable(nameOfFeatureDataset + "_osm_relation"); if (relationTable == null) { message.AddError(120025, String.Format(resourceManager.GetString("GPTools_OSMGPExport2OSM_no_relationTable"), nameOfFeatureDataset + "_osm_relation")); return; } System.Xml.Serialization.XmlSerializer relationSerializer = new System.Xml.Serialization.XmlSerializer(typeof(relation)); string relationsExportedMessage = String.Empty; using (ComReleaser comReleaser = new ComReleaser()) { ICursor rowCursor = relationTable.Search(null, false); comReleaser.ManageLifetime(rowCursor); IRow currentRow = rowCursor.NextRow(); // collect the indices for the relation table once int relationOSMIDFieldIndex = relationTable.Fields.FindField("OSMID"); int relationChangesetFieldIndex = relationTable.Fields.FindField("osmchangeset"); int relationVersionFieldIndex = relationTable.Fields.FindField("osmversion"); int relationUIDFieldIndex = relationTable.Fields.FindField("osmuid"); int relationUserFieldIndex = relationTable.Fields.FindField("osmuser"); int relationTimeStampFieldIndex = relationTable.Fields.FindField("osmtimestamp"); int relationVisibleFieldIndex = relationTable.Fields.FindField("osmvisible"); int relationTagsFieldIndex = relationTable.Fields.FindField("osmTags"); int relationMembersFieldIndex = relationTable.Fields.FindField("osmMembers"); IWorkspace polygonWorkspace = ((IDataset)osmPolygonFeatureClass).Workspace; while (currentRow != null) { if (TrackCancel.Continue() == false) { // properly close the document xmlWriter.WriteEndElement(); // closing the osm root element xmlWriter.WriteEndDocument(); // finishing the document xmlWriter.Close(); // closing the document // report the number of elements loaded so far relationsExportedMessage = String.Format(resourceManager.GetString("GPTools_OSMGPExport2OSM_relations_exported_msg"), relationCounter); message.AddMessage(relationsExportedMessage); message.AddAbort(resourceManager.GetString("GPTools_toolabort")); return; } relation osmRelation = ConvertRowToOSMRelation(currentRow, (IWorkspace)commonWorkspace, relationTagsFieldIndex, relationOSMIDFieldIndex, relationChangesetFieldIndex, relationVersionFieldIndex, relationUIDFieldIndex, relationUserFieldIndex, relationTimeStampFieldIndex, relationVisibleFieldIndex, relationMembersFieldIndex, internalOSMExtensionVersion); relationSerializer.Serialize(xmlWriter, osmRelation, xmlnsEmpty); // increase the line counter for later status report relationCounter++; currentRow = rowCursor.NextRow(); } } // lastly let's serialize the collected multipart-geometries back into relation elements foreach (relation currentRelation in multiPartElements) { if (TrackCancel.Continue() == false) { // properly close the document xmlWriter.WriteEndElement(); // closing the osm root element xmlWriter.WriteEndDocument(); // finishing the document xmlWriter.Close(); // closing the document // report the number of elements loaded so far relationsExportedMessage = String.Format(resourceManager.GetString("GPTools_OSMGPExport2OSM_relations_exported_msg"), relationCounter); message.AddMessage(relationsExportedMessage); return; } relationSerializer.Serialize(xmlWriter, currentRelation, xmlnsEmpty); relationCounter++; } relationsExportedMessage = String.Format(resourceManager.GetString("GPTools_OSMGPExport2OSM_relations_exported_msg"), relationCounter); message.AddMessage(relationsExportedMessage); xmlWriter.WriteEndElement(); // closing the osm root element xmlWriter.WriteEndDocument(); // finishing the document xmlWriter.Close(); // closing the document } catch (Exception ex) { message.AddError(120026, ex.Message); } }
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; } }
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 void Execute(ESRI.ArcGIS.esriSystem.IArray paramvalues, ESRI.ArcGIS.esriSystem.ITrackCancel TrackCancel, ESRI.ArcGIS.Geoprocessing.IGPEnvironmentManager envMgr, ESRI.ArcGIS.Geodatabase.IGPMessages message) { _message = message; IFeatureClass osmPointFeatureClass = null; IFeatureClass osmLineFeatureClass = null; IFeatureClass osmPolygonFeatureClass = null; try { DateTime syncTime = DateTime.Now; IGPUtilities3 gpUtilities3 = new GPUtilitiesClass(); if (TrackCancel == null) { TrackCancel = new CancelTrackerClass(); } IGPParameter baseURLParameter = paramvalues.get_Element(in_downloadURLNumber) as IGPParameter; IGPString baseURLString = gpUtilities3.UnpackGPValue(baseURLParameter) as IGPString; if (baseURLString == null) { message.AddError(120048, string.Format(resourceManager.GetString("GPTools_NullPointerParameterType"), baseURLParameter.Name)); } IGPParameter downloadExtentParameter = paramvalues.get_Element(in_downloadExtentNumber) as IGPParameter; IGPValue downloadExtentGPValue = gpUtilities3.UnpackGPValue(downloadExtentParameter); esriGPExtentEnum gpExtent; IEnvelope downloadEnvelope = gpUtilities3.GetExtent(downloadExtentGPValue, out gpExtent); IGPParameter includeAllReferences = paramvalues.get_Element(in_includeReferencesNumber) as IGPParameter; IGPBoolean includeAllReferencesGPValue = gpUtilities3.UnpackGPValue(includeAllReferences) as IGPBoolean; if (includeAllReferencesGPValue == null) { message.AddError(120048, string.Format(resourceManager.GetString("GPTools_NullPointerParameterType"), includeAllReferences.Name)); } IEnvelope newExtent = null; ISpatialReferenceFactory spatialReferenceFactory = new SpatialReferenceEnvironmentClass() as ISpatialReferenceFactory; ISpatialReference wgs84 = spatialReferenceFactory.CreateGeographicCoordinateSystem((int)esriSRGeoCSType.esriSRGeoCS_WGS1984) as ISpatialReference; // this determines the spatial reference as defined from the gp environment settings and the initial wgs84 SR ISpatialReference downloadSpatialReference = gpUtilities3.GetGPSpRefEnv(envMgr, wgs84, newExtent, 0, 0, 0, 0, null); downloadEnvelope.Project(wgs84); Marshal.ReleaseComObject(wgs84); Marshal.ReleaseComObject(spatialReferenceFactory); HttpWebRequest httpClient; System.Xml.Serialization.XmlSerializer serializer = null; serializer = new XmlSerializer(typeof(osm)); // get the capabilities from the server HttpWebResponse httpResponse = null; api apiCapabilities = null; CultureInfo enUSCultureInfo = new CultureInfo("en-US"); #if DEBUG Console.WriteLine("Debbuging"); message.AddMessage("Debugging..."); #endif message.AddMessage(resourceManager.GetString("GPTools_OSMGPDownload_startingDownloadRequest")); try { httpClient = HttpWebRequest.Create(baseURLString.Value + "/api/capabilities") as HttpWebRequest; httpClient = AssignProxyandCredentials(httpClient); httpResponse = httpClient.GetResponse() as HttpWebResponse; osm osmCapabilities = null; Stream stream = httpResponse.GetResponseStream(); XmlTextReader xmlReader = new XmlTextReader(stream); osmCapabilities = serializer.Deserialize(xmlReader) as osm; xmlReader.Close(); apiCapabilities = osmCapabilities.Items[0] as api; } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.Message); message.AddError(120009, ex.Message); if (ex is WebException) { WebException webException = ex as WebException; string serverErrorMessage = webException.Response.Headers["Error"]; if (!String.IsNullOrEmpty(serverErrorMessage)) { message.AddError(120009, serverErrorMessage); } } } finally { if (httpResponse != null) { httpResponse.Close(); } httpClient = null; } if (apiCapabilities != null) { // check for the extent double roiArea = ((IArea)downloadEnvelope).Area; double capabilitiyArea = Convert.ToDouble(apiCapabilities.area.maximum, new CultureInfo("en-US")); if (roiArea > capabilitiyArea) { message.AddAbort(resourceManager.GetString("GPTools_OSMGPDownload_exceedDownloadROI")); return; } } // check for user interruption if (TrackCancel.Continue() == false) { return; } // list containing either only one document for a single bbox request or multiple if relation references need to be resolved List<string> downloadedOSMDocuments = new List<string>(); string requestURL = baseURLString.Value + "/api/0.6/map?bbox=" + downloadEnvelope.XMin.ToString("f5", enUSCultureInfo) + "," + downloadEnvelope.YMin.ToString("f5", enUSCultureInfo) + "," + downloadEnvelope.XMax.ToString("f5", enUSCultureInfo) + "," + downloadEnvelope.YMax.ToString("f5", enUSCultureInfo); string osmMasterDocument = downloadOSMDocument(ref message, requestURL, apiCapabilities); // check if the initial request was successfull // it might have failed at this point because too many nodes were requested or because of something else if (String.IsNullOrEmpty(osmMasterDocument)) { message.AddAbort(resourceManager.GetString("GPTools_OSMGPDownload_noValidOSMResponse")); return; } // add the "master document" ) original bbox request to the list downloadedOSMDocuments.Add(osmMasterDocument); if (includeAllReferencesGPValue.Value) { List<string> nodeList = new List<string>(); List<string> wayList = new List<string>(); List<string> relationList = new List<string>(); // check for user interruption if (TrackCancel.Continue() == false) { return; } parseOSMDocument(osmMasterDocument, ref message, ref nodeList, ref wayList, ref relationList, ref downloadedOSMDocuments, baseURLString.Value, apiCapabilities); } string metadataAbstract = resourceManager.GetString("GPTools_OSMGPDownload_metadata_abstract"); string metadataPurpose = resourceManager.GetString("GPTools_OSMGPDownload_metadata_purpose"); IGPParameter targetDatasetParameter = paramvalues.get_Element(out_targetDatasetNumber) as IGPParameter; IDEDataset2 targetDEDataset2 = gpUtilities3.UnpackGPValue(targetDatasetParameter) as IDEDataset2; IGPValue targetDatasetGPValue = gpUtilities3.UnpackGPValue(targetDatasetParameter); string targetDatasetName = ((IGPValue)targetDEDataset2).GetAsText(); IDataElement targetDataElement = targetDEDataset2 as IDataElement; IDataset targetDataset = gpUtilities3.OpenDatasetFromLocation(targetDataElement.CatalogPath); IName parentName = null; try { parentName = gpUtilities3.CreateParentFromCatalogPath(targetDataElement.CatalogPath); } catch { message.AddError(120033, resourceManager.GetString("GPTools_OSMGPFileReader_unable_to_create_fd")); return; } // test if the feature classes already exists, // if they do and the environments settings are such that an overwrite is not allowed we need to abort at this point IGeoProcessorSettings gpSettings = (IGeoProcessorSettings)envMgr; if (gpSettings.OverwriteOutput == true) { } else { if (gpUtilities3.Exists((IGPValue)targetDEDataset2) == true) { message.AddError(120010, String.Format(resourceManager.GetString("GPTools_OSMGPDownload_basenamealreadyexists"), targetDataElement.Name)); return; } } string Container = ""; IDEUtilities deUtilities = new DEUtilitiesClass(); deUtilities.ParseContainer(targetDataElement.CatalogPath, ref Container); IFeatureWorkspace featureWorkspace = gpUtilities3.OpenFromString(Container) as IFeatureWorkspace; if (featureWorkspace == null) { message.AddError(120011, String.Format(resourceManager.GetString("GPTools_OSMGPDownload_nofeatureworkspace"), Container)); return; } // load the descriptions from which to derive the domain values OSMDomains availableDomains = null; System.Xml.XmlTextReader reader = null; try { if (File.Exists(m_editorConfigurationSettings["osmdomainsfilepath"])) { reader = new System.Xml.XmlTextReader(m_editorConfigurationSettings["osmdomainsfilepath"]); } } // If is in the server and hasn't been install all the configuration files catch { if (File.Exists(System.IO.Path.Combine(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetAssembly(typeof(OSMGPDownload)).Location), "osm_domains.xml"))) { reader = new System.Xml.XmlTextReader(System.IO.Path.Combine(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetAssembly(typeof(OSMGPDownload)).Location), "osm_domains.xml")); } } if (reader == null) { message.AddError(120012, resourceManager.GetString("GPTools_OSMGPDownload_NoDomainConfigFile")); return; } try { serializer = new XmlSerializer(typeof(OSMDomains)); availableDomains = serializer.Deserialize(reader) as OSMDomains; } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.Message); System.Diagnostics.Debug.WriteLine(ex.StackTrace); message.AddError(120013, ex.Message); return; } #region define and add domains to the workspace // we are using domains to guide the edit templates in the editor for ArcGIS desktop Dictionary<string, IDomain> codedValueDomains = new Dictionary<string, IDomain>(); foreach (var domain in availableDomains.domain) { ICodedValueDomain pointCodedValueDomain = new CodedValueDomainClass(); ((IDomain)pointCodedValueDomain).Name = domain.name + "_pt"; ((IDomain)pointCodedValueDomain).FieldType = esriFieldType.esriFieldTypeString; ICodedValueDomain lineCodedValueDomain = new CodedValueDomainClass(); ((IDomain)lineCodedValueDomain).Name = domain.name + "_ln"; ((IDomain)lineCodedValueDomain).FieldType = esriFieldType.esriFieldTypeString; ICodedValueDomain polygonCodedValueDomain = new CodedValueDomainClass(); ((IDomain)polygonCodedValueDomain).Name = domain.name + "_ply"; ((IDomain)polygonCodedValueDomain).FieldType = esriFieldType.esriFieldTypeString; for (int i = 0; i < domain.domainvalue.Length; i++) { for (int domainGeometryIndex = 0; domainGeometryIndex < domain.domainvalue[i].geometrytype.Length; domainGeometryIndex++) { switch (domain.domainvalue[i].geometrytype[domainGeometryIndex]) { case geometrytype.point: pointCodedValueDomain.AddCode(domain.domainvalue[i].value, domain.domainvalue[i].value); break; case geometrytype.line: lineCodedValueDomain.AddCode(domain.domainvalue[i].value, domain.domainvalue[i].value); break; case geometrytype.polygon: polygonCodedValueDomain.AddCode(domain.domainvalue[i].value, domain.domainvalue[i].value); break; default: break; } } } // add the domain tables to the domains collection codedValueDomains.Add(((IDomain)pointCodedValueDomain).Name, (IDomain)pointCodedValueDomain); codedValueDomains.Add(((IDomain)lineCodedValueDomain).Name, (IDomain)lineCodedValueDomain); codedValueDomains.Add(((IDomain)polygonCodedValueDomain).Name, (IDomain)polygonCodedValueDomain); } IWorkspaceDomains workspaceDomain = featureWorkspace as IWorkspaceDomains; foreach (var domain in codedValueDomains.Values) { IDomain testDomain = null; try { testDomain = workspaceDomain.get_DomainByName(domain.Name); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.Message); System.Diagnostics.Debug.WriteLine(ex.StackTrace); } if (testDomain == null) { workspaceDomain.AddDomain(domain); } } #endregion IGPEnvironment configKeyword = getEnvironment(envMgr, "configKeyword"); IGPString gpString = null; if (configKeyword != null) gpString = configKeyword.Value as IGPString; string storageKeyword = String.Empty; if (gpString != null) { storageKeyword = gpString.Value; } IFeatureDataset targetFeatureDataset = null; if (gpUtilities3.Exists((IGPValue)targetDEDataset2)) { targetFeatureDataset = gpUtilities3.OpenDataset((IGPValue)targetDEDataset2) as IFeatureDataset; } else { targetFeatureDataset = featureWorkspace.CreateFeatureDataset(targetDataElement.Name, downloadSpatialReference); } ESRI.ArcGIS.esriSystem.UID osmClassExtensionUID = new ESRI.ArcGIS.esriSystem.UIDClass(); //GUID for the OSM feature class extension osmClassExtensionUID.Value = "{65CA4847-8661-45eb-8E1E-B2985CA17C78}"; downloadSpatialReference = ((IGeoDataset)targetFeatureDataset).SpatialReference; OSMToolHelper osmToolHelper = new OSMToolHelper(); #region create point/line/polygon feature classes and tables // points try { osmPointFeatureClass = osmToolHelper.CreatePointFeatureClass((IWorkspace2)featureWorkspace, targetFeatureDataset, targetDataElement.Name + "_osm_pt", null, null, osmClassExtensionUID, storageKeyword, availableDomains, metadataAbstract, metadataPurpose); } catch (Exception ex) { message.AddError(120014, String.Format(resourceManager.GetString("GPTools_OSMGPDownload_nullpointfeatureclass"), ex.Message)); return; } if (osmPointFeatureClass == null) { return; } // change the property set of the osm class extension to skip any change detection during the initial data load osmPointFeatureClass.RemoveOSMClassExtension(); // lines try { osmLineFeatureClass = osmToolHelper.CreateLineFeatureClass((IWorkspace2)featureWorkspace, targetFeatureDataset, targetDataElement.Name + "_osm_ln", null, null, osmClassExtensionUID, storageKeyword, availableDomains, metadataAbstract, metadataPurpose); } catch (Exception ex) { message.AddError(120015, String.Format(resourceManager.GetString("GPTools_OSMGPDownload_nulllinefeatureclass"), ex.Message)); return; } if (osmLineFeatureClass == null) { return; } // change the property set of the osm class extension to skip any change detection during the initial data load osmLineFeatureClass.RemoveOSMClassExtension(); // polygons try { osmPolygonFeatureClass = osmToolHelper.CreatePolygonFeatureClass((IWorkspace2)featureWorkspace, targetFeatureDataset, targetDataElement.Name + "_osm_ply", null, null, osmClassExtensionUID, storageKeyword, availableDomains, metadataAbstract, metadataPurpose); } catch (Exception ex) { message.AddError(120016, String.Format(resourceManager.GetString("GPTools_OSMGPDownload_nullpolygonfeatureclass"), ex.Message)); return; } if (osmPolygonFeatureClass == null) { return; } // change the property set of the osm class extension to skip any change detection during the initial data load osmPolygonFeatureClass.RemoveOSMClassExtension(); // relation table ITable relationTable = null; try { relationTable = osmToolHelper.CreateRelationTable((IWorkspace2)featureWorkspace, targetDataElement.Name + "_osm_relation", null, storageKeyword, metadataAbstract, metadataPurpose); } catch (Exception ex) { message.AddError(120017, String.Format(resourceManager.GetString("GPTools_OSMGPDownload_nullrelationtable"), ex.Message)); return; } if (relationTable == null) { return; } // revision table ITable revisionTable = null; try { revisionTable = osmToolHelper.CreateRevisionTable((IWorkspace2)featureWorkspace, targetDataElement.Name + "_osm_revision", null, storageKeyword); } catch (Exception ex) { message.AddError(120018, String.Format(resourceManager.GetString("GPTools_OSMGPDownload_nullrelationtable"), ex.Message)); return; } if (revisionTable == null) { return; } // check for user interruption if (TrackCancel.Continue() == false) { return; } #endregion #region clean any existing data from loading targets ESRI.ArcGIS.Geoprocessing.IGeoProcessor2 gp = new ESRI.ArcGIS.Geoprocessing.GeoProcessorClass(); IGeoProcessorResult gpResult = new GeoProcessorResultClass(); try { IVariantArray truncateParameters = new VarArrayClass(); truncateParameters.Add(((IWorkspace)featureWorkspace).PathName + "\\" + targetDataElement.Name + "\\" + targetDataElement.Name + "_osm_pt"); gpResult = gp.Execute("TruncateTable_management", truncateParameters, TrackCancel); truncateParameters = new VarArrayClass(); truncateParameters.Add(((IWorkspace)featureWorkspace).PathName + "\\" + targetDataElement.Name + "\\" + targetDataElement.Name + "_osm_ln"); gpResult = gp.Execute("TruncateTable_management", truncateParameters, TrackCancel); truncateParameters = new VarArrayClass(); truncateParameters.Add(((IWorkspace)featureWorkspace).PathName + "\\" + targetDataElement.Name + "\\" + targetDataElement.Name + "_osm_ply"); gpResult = gp.Execute("TruncateTable_management", truncateParameters, TrackCancel); truncateParameters = new VarArrayClass(); truncateParameters.Add(((IWorkspace)featureWorkspace).PathName + "\\" + targetDataElement.Name + "_osm_relation"); gpResult = gp.Execute("TruncateTable_management", truncateParameters, TrackCancel); truncateParameters = new VarArrayClass(); truncateParameters.Add(((IWorkspace)featureWorkspace).PathName + "\\" + targetDataElement.Name + "_osm_revision"); gpResult = gp.Execute("TruncateTable_management", truncateParameters, TrackCancel); } catch (Exception ex) { message.AddWarning(ex.Message); } #endregion Dictionary<string, OSMToolHelper.simplePointRef> osmNodeDictionary = null; foreach (string osmDownloadDocument in downloadedOSMDocuments.Reverse<string>()) { long nodeCapacity = 0; long wayCapacity = 0; long relationCapacity = 0; message.AddMessage(resourceManager.GetString("GPTools_OSMGPFileReader_countingNodes")); osmToolHelper.countOSMStuff(osmDownloadDocument, ref nodeCapacity, ref wayCapacity, ref relationCapacity, ref TrackCancel); message.AddMessage(String.Format(resourceManager.GetString("GPTools_OSMGPFileReader_countedElements"), nodeCapacity, wayCapacity, relationCapacity)); if (osmNodeDictionary == null) osmNodeDictionary = new Dictionary<string, OSMToolHelper.simplePointRef>(Convert.ToInt32(nodeCapacity)); #region load points osmToolHelper.loadOSMNodes(osmDownloadDocument, ref TrackCancel, ref message, targetDatasetGPValue, osmPointFeatureClass, false, false, Convert.ToInt32(nodeCapacity), ref osmNodeDictionary, featureWorkspace, downloadSpatialReference, availableDomains, false); #endregion if (TrackCancel.Continue() == false) { return; } #region load ways if (wayCapacity > 0) { List<string> missingWays = null; missingWays = osmToolHelper.loadOSMWays(osmDownloadDocument, ref TrackCancel, ref message, targetDatasetGPValue, osmPointFeatureClass, osmLineFeatureClass, osmPolygonFeatureClass, false, false, Convert.ToInt32(wayCapacity), ref osmNodeDictionary, featureWorkspace, downloadSpatialReference, availableDomains, false); } #endregion if (TrackCancel.Continue() == false) { return; } # region for conserve memory condition, update refcount int refCounterFieldIndex = osmPointFeatureClass.Fields.FindField("wayRefCount"); if (refCounterFieldIndex > -1) { foreach (var refNode in osmNodeDictionary) { try { IFeature updateFeature = osmPointFeatureClass.GetFeature(refNode.Value.pointObjectID); int refCount = refNode.Value.RefCounter; if (refCount == 0) { refCount = 1; } updateFeature.set_Value(refCounterFieldIndex, refCount); updateFeature.Store(); } catch { } } } #endregion // check for user interruption if (TrackCancel.Continue() == false) { return; } ESRI.ArcGIS.Geoprocessor.Geoprocessor geoProcessor = new ESRI.ArcGIS.Geoprocessor.Geoprocessor(); #region for local geodatabases enforce spatial integrity bool storedOriginal = geoProcessor.AddOutputsToMap; geoProcessor.AddOutputsToMap = false; try { if (osmLineFeatureClass != null) { if (((IDataset)osmLineFeatureClass).Workspace.Type == esriWorkspaceType.esriLocalDatabaseWorkspace) { IVariantArray lineRepairParameters = new VarArrayClass(); lineRepairParameters.Add(((IWorkspace)featureWorkspace).PathName + "\\" + targetDataElement.Name + "\\" + targetDataElement.Name + "_osm_ln"); lineRepairParameters.Add("DELETE_NULL"); IGeoProcessorResult2 gpResults = gp.Execute("RepairGeometry_management", lineRepairParameters, TrackCancel) as IGeoProcessorResult2; message.AddMessages(gpResults.GetResultMessages()); } } if (osmPolygonFeatureClass != null) { if (((IDataset)osmPolygonFeatureClass).Workspace.Type == esriWorkspaceType.esriLocalDatabaseWorkspace) { IVariantArray polygonRepairParameters = new VarArrayClass(); polygonRepairParameters.Add(((IWorkspace)featureWorkspace).PathName + "\\" + targetDataElement.Name + "\\" + targetDataElement.Name + "_osm_ply"); polygonRepairParameters.Add("DELETE_NULL"); IGeoProcessorResult2 gpResults = gp.Execute("RepairGeometry_management", polygonRepairParameters, TrackCancel) as IGeoProcessorResult2; message.AddMessages(gpResults.GetResultMessages()); } } } catch { message.AddWarning(resourceManager.GetString("GPTools_OSMGPDownload_repairgeometryfailure")); } geoProcessor.AddOutputsToMap = storedOriginal; #endregion #region load relations if (relationCapacity > 0) { List<string> missingRelations = null; missingRelations = osmToolHelper.loadOSMRelations(osmDownloadDocument, ref TrackCancel, ref message, targetDatasetGPValue, osmPointFeatureClass, osmLineFeatureClass, osmPolygonFeatureClass, Convert.ToInt32(relationCapacity), relationTable, availableDomains, false, false); } #endregion } #region update the references counts and member lists for nodes message.AddMessage(resourceManager.GetString("GPTools_OSMGPFileReader_updatereferences")); IFeatureCursor pointUpdateCursor = null; using (SchemaLockManager ptLockManager = new SchemaLockManager(osmPointFeatureClass as ITable)) { using (ComReleaser comReleaser = new ComReleaser()) { int updateCount = 0; pointUpdateCursor = osmPointFeatureClass.Update(null, false); updateCount = ((ITable)osmPointFeatureClass).RowCount(null); IStepProgressor stepProgressor = TrackCancel as IStepProgressor; if (stepProgressor != null) { stepProgressor.MinRange = 0; stepProgressor.MaxRange = updateCount; stepProgressor.Position = 0; stepProgressor.Message = resourceManager.GetString("GPTools_OSMGPFileReader_updatepointrefcount"); stepProgressor.StepValue = 1; stepProgressor.Show(); } comReleaser.ManageLifetime(pointUpdateCursor); IFeature pointFeature = pointUpdateCursor.NextFeature(); int osmPointIDFieldIndex = osmPointFeatureClass.FindField("OSMID"); int osmWayRefCountFieldIndex = osmPointFeatureClass.FindField("wayRefCount"); int positionCounter = 0; while (pointFeature != null) { positionCounter++; string nodeID = Convert.ToString(pointFeature.get_Value(osmPointIDFieldIndex)); // let get the reference counter from the internal node dictionary if (osmNodeDictionary[nodeID].RefCounter == 0) { pointFeature.set_Value(osmWayRefCountFieldIndex, 1); } else { pointFeature.set_Value(osmWayRefCountFieldIndex, osmNodeDictionary[nodeID].RefCounter); } pointUpdateCursor.UpdateFeature(pointFeature); if (pointFeature != null) Marshal.ReleaseComObject(pointFeature); pointFeature = pointUpdateCursor.NextFeature(); if (stepProgressor != null) { stepProgressor.Position = positionCounter; } } if (stepProgressor != null) { stepProgressor.Hide(); } } } #endregion // clean all the downloaded OSM files foreach (string osmFile in downloadedOSMDocuments) { if (File.Exists(osmFile)) { try { File.Delete(osmFile); } catch { } } } SyncState.StoreLastSyncTime(targetDatasetName, syncTime); gpUtilities3 = new GPUtilitiesClass() as IGPUtilities3; // repackage the feature class into their respective gp values IGPParameter pointFeatureClassParameter = paramvalues.get_Element(out_osmPointsNumber) as IGPParameter; IGPValue pointFeatureClassPackGPValue = gpUtilities3.UnpackGPValue(pointFeatureClassParameter); gpUtilities3.PackGPValue(pointFeatureClassPackGPValue, pointFeatureClassParameter); IGPParameter lineFeatureClassParameter = paramvalues.get_Element(out_osmLinesNumber) as IGPParameter; IGPValue lineFeatureClassPackGPValue = gpUtilities3.UnpackGPValue(lineFeatureClassParameter); gpUtilities3.PackGPValue(lineFeatureClassPackGPValue, lineFeatureClassParameter); IGPParameter polygonFeatureClassParameter = paramvalues.get_Element(out_osmPolygonsNumber) as IGPParameter; IGPValue polygon1FeatureClassPackGPValue = gpUtilities3.UnpackGPValue(polygonFeatureClassParameter); gpUtilities3.PackGPValue(polygon1FeatureClassPackGPValue, polygonFeatureClassParameter); gpUtilities3.ReleaseInternals(); Marshal.ReleaseComObject(gpUtilities3); Marshal.ReleaseComObject(baseURLString); Marshal.ReleaseComObject(downloadExtentGPValue); Marshal.ReleaseComObject(downloadEnvelope); Marshal.ReleaseComObject(includeAllReferences); Marshal.ReleaseComObject(downloadSpatialReference); if (osmToolHelper != null) osmToolHelper = null; } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.Message); System.Diagnostics.Debug.WriteLine(ex.StackTrace); message.AddError(120019, ex.Message); } finally { try { if (osmPointFeatureClass != null) { osmPointFeatureClass.ApplyOSMClassExtension(); Marshal.ReleaseComObject(osmPointFeatureClass); } if (osmLineFeatureClass != null) { osmLineFeatureClass.ApplyOSMClassExtension(); Marshal.ReleaseComObject(osmLineFeatureClass); } if (osmPolygonFeatureClass != null) { osmPolygonFeatureClass.ApplyOSMClassExtension(); Marshal.ReleaseComObject(osmPolygonFeatureClass); } } catch (Exception ex) { message.AddError(120020, ex.ToString()); } } }
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; } }