Beispiel #1
0
        private IGeoProcessorResult UnionOverlay2(Geoprocessor gp)
        {
            //Union_analysis (in_features, out_feature_class, join_attributes, cluster_tolerance, gaps)

            IGpValueTableObject vtobject = new GpValueTableObjectClass();

            vtobject.SetColumns(2);
            object row = "";

            row = strInputLayer + " " + inputLevel.ToString();
            vtobject.AddRow(ref row);
            row = strOverLayer + " " + overlayLevel.ToString();
            vtobject.AddRow(ref row);
            IVariantArray pVarArray = new VarArrayClass();

            pVarArray.Add(vtobject);
            string outputFullPath = System.IO.Path.Combine(strOutputPath, strInputLayer + "_" + strOverLayer + "_" + "Union");

            pVarArray.Add(outputFullPath);
            pVarArray.Add(strJoinAttributeType);
            pVarArray.Add(tolerance);

            IGeoProcessorResult results = gp.Execute("Union_analysis", pVarArray, null) as IGeoProcessorResult;

            System.Runtime.InteropServices.Marshal.ReleaseComObject(pVarArray);
            System.Runtime.InteropServices.Marshal.ReleaseComObject(vtobject);

            return(results);
        }
        private IGeoProcessorResult IntersectOverlay(Geoprocessor gp)
        {
            string pOutPutFullPath = System.IO.Path.Combine(m_OutPutPath, m_InputLayer + "_" + m_OverlayLayer + "_" + "Intersect");

            IGpValueTableObject pGpValueTableObject = new GpValueTableObjectClass();

            pGpValueTableObject.SetColumns(2);

            object pRow = null;

            pRow = m_InputLayer + " " + m_InputLayerPrecisionLevel;
            pGpValueTableObject.AddRow(ref pRow);
            pRow = m_OverlayLayer + " " + m_OverlayLayerPrecisionLevel;
            pGpValueTableObject.AddRow(ref pRow);

            IVariantArray pVariantArray = new VarArrayClass();

            pVariantArray.Add(pGpValueTableObject);
            pVariantArray.Add(pOutPutFullPath);
            pVariantArray.Add(m_OutputAttributeType);
            pVariantArray.Add(m_Tolerance);
            pVariantArray.Add(m_OutputFeatureType);

            IGeoProcessorResult pGPResult = (IGeoProcessorResult)gp.Execute("intersect_analysis", pVariantArray, null);

            return(pGPResult);
        }
Beispiel #3
0
        /// <summary>Selects a subset of features to a new feature class</summary>
        private void SelectFeaturesToNewFeatureClass(string source, string target, string query)
        {
            try
            {
                IVariantArray paramArray = new VarArrayClass();
                paramArray.Add(source);
                paramArray.Add(target);
                paramArray.Add(query);

                _taskManager.ExecuteTool("Select_analysis", paramArray);
            }
            catch (COMException comex)
            {
                // When working with file geodatabase, assume E_FAIL is a locking issue
                if (_osmDataset.Workspace.Type == esriWorkspaceType.esriLocalDatabaseWorkspace)
                {
                    if ((uint)comex.ErrorCode == 0x80004005)
                    {
                        throw new ApplicationException(string.Format(RESMGR.GetString("GPTools_OSMGPCreateNetworkDataset_lockedTarget"), target));
                    }
                }

                throw;
            }
        }
        private IGeoProcessorResult UnionOverlay(Geoprocessor gp)
        {
            //Union_analysis (in_features, out_feature_class, join_attributes, cluster_tolerance, gaps)

            string pOutPutFullPath = System.IO.Path.Combine(m_OutPutPath, m_InputLayer + "_" + m_OverlayLayer + "_" + "Union");

            IGpValueTableObject pGpValueTableObject = new GpValueTableObjectClass();

            pGpValueTableObject.SetColumns(2);

            object pRow = "";

            pRow = m_InputLayer + " " + m_InputLayerPrecisionLevel;
            pGpValueTableObject.AddRow(ref pRow);
            pRow = m_OverlayLayer + " " + m_OverlayLayerPrecisionLevel;
            pGpValueTableObject.AddRow(ref pRow);

            IVariantArray pVariantArray = new VarArrayClass();

            pVariantArray.Add(pGpValueTableObject);
            pVariantArray.Add(pOutPutFullPath);
            pVariantArray.Add(m_OutputAttributeType);
            pVariantArray.Add(m_Tolerance);



            IGeoProcessorResult pGPResult = gp.Execute("Union_analysis", pVariantArray, null) as IGeoProcessorResult;

            return(pGPResult);
        }
Beispiel #5
0
        private void buttonXExport_Click(object sender, EventArgs e)
        {
            try
            {
                IVariantArray parameters = new VarArrayClass();
                string        layers     = "";
                for (int i = 0; i < listBox2.Items.Count; i++)
                {
                    layers = layers + listBox2.Items[i].ToString() + ";";
                }
                layers = layers.TrimEnd(';');

                // parameters.Add(@"D:\mydb.gdb\myFeatuerClass1;D:\mydb.gdb\myFeatuerClass2");
                //parameters.Add("DWG_R2007");
                //parameters.Add(@"C:\temp\ExportCAD.DWG");
                parameters.Add(layers);
                parameters.Add(comboBox1.SelectedItem.ToString());
                parameters.Add(textBox1.Text);
                GeoProcessor gp       = new GeoProcessor();
                bool         response = RunTool("ExportCAD_conversion", parameters, null, false);
                MessageBox.Show("导出完成");
            }
            catch
            {
            }
        }
        private IGeoProcessorResult IntersectOverlay(Geoprocessor gp)
        {
            IGpValueTableObject vtobject = new GpValueTableObject()
                                           as IGpValueTableObject;

            vtobject.SetColumns(1);
            object row = null;

            row = GetFeatureLayer(strInputLayer);
            vtobject.AddRow(ref row);
            row = GetFeatureLayer(strOverLayer);
            vtobject.AddRow(ref row);
            IVariantArray pVarArray = new VarArrayClass();

            pVarArray.Add(vtobject);
            string outputFullPath = System.IO.Path.Combine
                                        (strOutputPath, strInputLayer + "_" + strOverLayer + "_" + "Intersect");

            pVarArray.Add(outputFullPath);
            pVarArray.Add(strJoinAttributeType);
            pVarArray.Add(tolerance);
            pVarArray.Add(strOutputFeatureType);
            IGeoProcessorResult results = gp.Execute(
                "intersect_analysis", pVarArray, null) as IGeoProcessorResult;

            return(results);
        }
        public static void BufferAnalysis(IFeatureClass feacls,string dist)
        {
            IGeoProcessor2 gp = new GeoProcessorClass();
            gp.OverwriteOutput = true;

            IGeoProcessorResult result = new GeoProcessorResultClass();

            //gp.SetEnvironmentValue("workspace", @"e:\data");

            IVariantArray vararr = new VarArrayClass();
            object sev = null;
            try
            {
                vararr.Add(feacls);
                vararr.Add(@"e:\data\wwwwwww.shp");
                vararr.Add(dist);

                result = gp.Execute("Buffer_analysis", vararr, null);

                while (result.Status == esriJobStatus.esriJobExecuting)
                    Thread.Sleep(1000);

                MessageBox.Show(gp.GetMessages(ref sev));
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.Message);
                MessageBox.Show(gp.GetMessages(ref sev));
            }
        }
Beispiel #8
0
        /// <summary>
        /// 调用一个模型
        /// </summary>
        public void GPtest2()
        {
            Geoprocessor gp = new Geoprocessor();

            gp.OverwriteOutput = true;
            gp.SetEnvironmentValue("scratchworkspace", @"F:\gpTest1\data");
            gp.AddToolbox(@"F:\gpTest\Toolbox.tbx");
            IVariantArray parameters = new VarArrayClass();

            parameters.Add(@"F:\gpTest\data\test .xlsx");
            parameters.Add("a");
            parameters.Add("b");
            ISpatialReferenceFactory spatialReferenceFactory = new SpatialReferenceEnvironmentClass();
            ISpatialReference        spatialReference        = spatialReferenceFactory.CreateProjectedCoordinateSystem(2379);

            parameters.Add(spatialReference);
            parameters.Add(@"F:\gpTest\data\project1.shp");
            try
            {
                gp.Execute("excel", parameters, null);
            }
            catch (Exception ex)
            {
                string a = ex.Message;
            }
        }
Beispiel #9
0
        private void simpleButton4_Click(object sender, EventArgs e)
        {
            if (this.comboBoxEditInputRaster2.Text.ToString() == "" || this.comboBoxEditOutputRaster.Text.ToString() == "")
            {
                MessageBox.Show("请输入参数!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            string strResultsDBPath = m_pGDBHelper.GetResultsDBPath();

            if (Utilities.GDBUtilites.CheckNameExist(strResultsDBPath, this.comboBoxEditOutputRaster.Text.ToString()) == false)
            {
                //执行R2V分析
                ILayer pInputLayer1 = null;

                for (int i = 0; i < m_pMapCtrl.LayerCount; i++)
                {
                    if (m_pMapCtrl.get_Layer(i).Name == this.comboBoxEditInputRaster2.Text.ToString())
                    {
                        pInputLayer1 = m_pMapCtrl.get_Layer(i);
                    }
                }

                if (pInputLayer1 != null)
                {
                    IRasterLayer pRasterLayer1 = pInputLayer1 as IRasterLayer;

                    IGeoProcessor2 pGP = new GeoProcessorClass();
                    pGP.AddToolbox(m_pGDBHelper.GetToolboxPath());

                    IVariantArray gpParameters = new VarArrayClass();
                    gpParameters.Add(pRasterLayer1.Raster);

                    gpParameters.Add(m_pGDBHelper.GetResultsDBPath() + "\\" + this.comboBoxEditOutputRaster.Text.ToString());

                    IGeoProcessorResult pGeoProcessorResult = pGP.Execute("Raster2Vector", gpParameters, null);
                    if (pGeoProcessorResult.Status == esriJobStatus.esriJobSucceeded)
                    {
                        if (this.checkBox1.Checked)
                        {
                            //IWorkspaceFactory2 pWKF = new FileGDBWorkspaceFactoryClass();
                            //IFeatureL pFW = (IFeatureWorkspace)pWKF.OpenFromFile(m_pGDBHelper.GetResultsDBPath() + "\\" + this.comboBoxEditOutputRaster.Text.ToString(), 0);
                            //IRasterWorkspaceEx pRasterWKEx = (IRasterWorkspaceEx)pWKF.OpenFromFile(m_pGDBHelper.GetResultsDBPath(), 0);
                            //IRasterDataset3 pRasterDataset = pRasterWKEx.OpenRasterDataset(this.comboBoxEditOutputRaster.Text.ToString()) as IRasterDataset3;

                            //Utilities.MapUtilites.AddRasterLayer(m_pMapCtrl.ActiveView, pRasterDataset, null);
                        }
                        MessageBox.Show("转换完成!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                }

                this.DialogResult = DialogResult.OK;
                this.Close();
            }
            else
            {
                MessageBox.Show("已存在同名数据!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
        }
Beispiel #10
0
        private void iToolStripMenuItem_Click(object sender, EventArgs e)
        {
            // Initialize the geoprocessor.
            IGeoProcessor2 gp = new GeoProcessorClass();

            gp.OverwriteOutput = true;
            // Add the BestPath toolbox.
            gp.AddToolbox(tbxPath);

            // Generate the array of parameters.
            IVariantArray parameters = new VarArrayClass();

            parameters.Add(FileGDBPath + "\\LotIds");
            parameters.Add("100 Feet");
            parameters.Add(FileGDBPath + "\\LotIds_BufferCustomArray1");


            object sev = null;

            try
            {
                // Execute the model tool by name.
                gp.Execute("Model2", parameters, null);

                Console.WriteLine(gp.GetMessages(ref sev));
            }
            catch (Exception ex)
            {
                // Print geoprocessing execution error messages.
                Console.WriteLine(gp.GetMessages(ref sev));
            }
        }
Beispiel #11
0
        private void iVariantArray方式ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            IGeoProcessor2 gp = new GeoProcessorClass();

            gp.OverwriteOutput = true;

            IGeoProcessorResult result = new GeoProcessorResultClass();

            // Create a variant array to hold the parameter values.
            IVariantArray parameters = new VarArrayClass();

            object sev = null;

            try
            {
                // Populate the variant array with parameter values.
                parameters.Add(FileGDBPath + "\\LotIds");
                parameters.Add(FileGDBPath + "\\LotIds_BufferArray");
                parameters.Add("100 Feet");

                // Execute the tool.
                result = gp.Execute("Buffer_analysis", parameters, null);

                // Print geoprocessring messages.
                Console.WriteLine(gp.GetMessages(ref sev));
            }

            catch (Exception ex)
            {
                // Print a generic exception message.
                Console.WriteLine(ex.Message);
                // Print geoprocessing execution error messages.
                Console.WriteLine(gp.GetMessages(ref sev));
            }
        }
Beispiel #12
0
        private void managed方式ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            // Initialize the geoprocessor.
            Geoprocessor GP = new Geoprocessor();

            GP.OverwriteOutput = true;
            // Add the BestPath toolbox.
            GP.AddToolbox(tbxPath);

            // Generate the array of parameters.
            IVariantArray parameters = new VarArrayClass();

            parameters.Add(FileGDBPath + "\\LotIds");
            parameters.Add("100 Feet");
            parameters.Add(FileGDBPath + "\\LotIds_BufferCustomArray2");

            object sev = null;

            try
            {
                // Execute the model tool by name.
                GP.Execute("Model2", parameters, null);

                Console.WriteLine(GP.GetMessages(ref sev));
            }
            catch (Exception ex)
            {
                // Print geoprocessing execution error messages.
                Console.WriteLine(GP.GetMessages(ref sev));
                //for (int i = 0; i < GP.MessageCount; i++)
                //    Console.WriteLine(GP.GetMessage(i));
            }
        }
Beispiel #13
0
        private static void ReproCase()
        {
            Geoprocessor gp = new Geoprocessor {
                OverwriteOutput = true
            };                                                                                                      // Instantiate the geoprocessor using the managed assembly.

            string tbx  = GetArcPadExePath().Replace("ArcPad.exe", @"DesktopTools10.0\Toolboxes\ArcPad Tools.tbx"); // Get path to ArcPadTools toolbox.
            string gdb  = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), @"data\Riverside.gdb");
            string axf  = gdb.Replace(".gdb", ".axf");
            string tool = "ArcPadCheckout_ArcPad";
            string feat = string.Join(";", GetFeatures(OpenGeodatabaseWorkspace(gdb), ref gp)); // Get the features in the included gdb.

            Console.WriteLine("Will attempt to run the {0} tool...\n", tool);

            try
            {
                gp.AddToolbox(tbx); // Add the toolbox

                IVariantArray parameters = new VarArrayClass();
                parameters.Add(feat);  // Features
                parameters.Add("");    // Schema Only
                parameters.Add("");    // Password
                parameters.Add("");    // Encrypt
                parameters.Add(axf);   // Axf

                if (File.Exists(axf))
                {
                    File.Delete(axf);                                                  // Delete the axf if it exists. Tool will not allow you to overwrite
                }
                var result = (IGeoProcessorResult2)gp.Execute(tool, parameters, null); // Execute the gp tool
                Messages(result);                                                      // Display the GP Messages for the successful tool.
            }
            catch (Exception e) { Messages(e, ref gp); } // Display the Exception/GP Messages for the failing tool
            finally { gp.RemoveToolbox(tbx); }
        }
        private IGeoProcessorResult UnionOverlay(Geoprocessor gp)
        {
            IGpValueTableObject vtobject = new GpValueTableObject()
                                           as IGpValueTableObject;

            vtobject.SetColumns(1);
            object row = "";

            row = GetFeatureLayer(strInputLayer);
            vtobject.AddRow(ref row);
            row = GetFeatureLayer(strOverLayer);
            vtobject.AddRow(ref row);
            IVariantArray pVarArray = new VarArrayClass();

            pVarArray.Add(vtobject);
            string outputFullPath = System.IO.Path.Combine
                                        (strOutputPath, strInputLayer + "_" + strOverLayer + "_" + "Union.shp");

            pVarArray.Add(outputFullPath);
            pVarArray.Add(strJoinAttributeType);
            pVarArray.Add(tolerance);
            IGeoProcessorResult results = gp.Execute
                                              ("Union_analysis", pVarArray, null) as IGeoProcessorResult;

            System.Runtime.InteropServices.Marshal.ReleaseComObject(pVarArray);
            System.Runtime.InteropServices.Marshal.ReleaseComObject(vtobject);
            return(results);
        }
        public bool ConvertLayerToKML(IFeatureClass fc, string kmzOutputPath, string tmpShapefilePath, ESRI.ArcGIS.Carto.IMap map)
        {
            try
            {
                string kmzName    = System.IO.Path.GetFileName(kmzOutputPath);
                string folderName = System.IO.Path.GetDirectoryName(kmzOutputPath);
                var    fcName     = System.IO.Path.GetFileNameWithoutExtension(kmzName);

                IFeatureLayer fLayer = new FeatureLayer();
                fLayer.FeatureClass = fc;
                var geoLayer = (fLayer as IGeoFeatureLayer);
                if (geoLayer.FeatureClass.ShapeType == esriGeometryType.esriGeometryPoint)
                {
                    ISimpleMarkerSymbol pSimpleMarkerSymbol = new SimpleMarkerSymbolClass();
                    pSimpleMarkerSymbol.Style = esriSimpleMarkerStyle.esriSMSCircle;
                    pSimpleMarkerSymbol.Size  = CoordinateConversionLibrary.Constants.SymbolSize;
                    pSimpleMarkerSymbol.Color = new RgbColorClass()
                    {
                        Red = 255
                    };
                    ISimpleRenderer pSimpleRenderer;
                    pSimpleRenderer        = new SimpleRenderer();
                    pSimpleRenderer.Symbol = (ISymbol)pSimpleMarkerSymbol;
                    geoLayer.Name          = fcName;
                    geoLayer.Renderer      = (IFeatureRenderer)pSimpleRenderer;
                }
                var featureLayer = geoLayer as FeatureLayer;

                map.AddLayer(geoLayer);

                // Initialize the geoprocessor.
                IGeoProcessor2 gp         = new GeoProcessorClass();
                IVariantArray  parameters = new VarArrayClass();
                parameters.Add(featureLayer.Name);
                parameters.Add(folderName + "\\" + kmzName);
                var result = gp.Execute(CoordinateConversionLibrary.Constants.LayerToKMLGPTool, parameters, null);

                // Remove the temporary layer from the TOC
                for (int i = 0; i < map.LayerCount; i++)
                {
                    ILayer layer = map.get_Layer(i);
                    if (layer.Name == fcName)
                    {
                        map.DeleteLayer(layer);
                        break;
                    }
                }

                return(true);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message);
            }

            return(false);
        }
        static void Main(string[] args)
        {
            // Load the product code and version to the version manager
            ESRI.ArcGIS.RuntimeManager.Bind(ESRI.ArcGIS.ProductCode.Desktop);

            //ESRI License Initializer generated code.
            m_AOLicenseInitializer.InitializeApplication(new esriLicenseProductCode[] { esriLicenseProductCode.esriLicenseProductCodeAdvanced },
                                                         new esriLicenseExtensionCode[] { });

            // Create geoprocessor. Overwrite true will replace existing output
            IGeoProcessor2 gp = new GeoProcessorClass();

            gp.OverwriteOutput = true;

            // Get the workspace from the user
            Console.WriteLine("Enter the path to folder where you copied the data folder.");
            Console.WriteLine("Example: C:\\AirportsAndGolf\\data");
            Console.Write(">");
            string wks = Console.ReadLine();

            // set the workspace to the value user entered
            gp.SetEnvironmentValue("workspace", wks + "\\" + "golf.gdb");

            // Add the custom toolbox to geoprocessor
            gp.AddToolbox(wks + "\\" + "Find Golf Courses.tbx");

            // Create a variant - data are in the workspace
            IVariantArray parameters = new VarArrayClass();

            parameters.Add("Airports");
            parameters.Add("8 Miles");
            parameters.Add("Golf");
            parameters.Add("GolfNearAirports");

            object sev = null;

            try
            {
                gp.Execute("GolfFinder", parameters, null);
                Console.WriteLine(gp.GetMessages(ref sev));
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                string errorMsgs = gp.GetMessages(ref sev);
                Console.WriteLine(errorMsgs);
            }
            finally
            {
                Console.WriteLine("Hit Enter to quit");
                Console.ReadLine(); // pause the console to see messages
            }

            //ESRI License Initializer generated code.
            //Do not make any call to ArcObjects after ShutDownApplication()
            m_AOLicenseInitializer.ShutdownApplication();
        }
Beispiel #17
0
        private void btn_CalibrateRoute_Click(object sender, EventArgs e)
        {
            // Create the geoprocessor.
            IGeoProcessor2 gp = new GeoProcessorClass();

            gp.OverwriteOutput = true;

            IGeoProcessorResult result = new GeoProcessorResultClass();

            // Create a variant array to hold the parameter values.
            IVariantArray parameters = new VarArrayClass();

            object sev = null;

            string wholeName = RouteBox.Text;

            string[] arrayName = wholeName.Split('\\');
            string   gdbName   = arrayName.GetGDBPath();
            string   outName   = gdbName + "\\test\\CalibrateRoute2";

            Console.WriteLine(outName);

            try
            {
                // Populate the variant array with parameter values.
                parameters.Add(@RouteBox.Text);
                parameters.Add("ProjectID");
                parameters.Add(PointBox.Text);
                parameters.Add("SvyLineID");
                parameters.Add("distance");
                parameters.Add(@outName);

                // Execute the tool.
                result = gp.Execute("CalibrateRoutes_lr ", parameters, null);

                // Wait until the execution completes.
                while (result.Status == esriJobStatus.esriJobExecuting)
                {
                    Thread.Sleep(1000);
                }
                // Wait for 1 second.

                // Print geoprocessring messages.
                Console.WriteLine(gp.GetMessages(ref sev));
            }

            catch (Exception ex)
            {
                // Print a generic exception message.
                Console.WriteLine(ex.Message);

                // Print geoprocessing execution error messages.
                Console.WriteLine(gp.GetMessages(ref sev));
            }
            MessageBox.Show("线性参考完成!");
        }
        /// <summary>
        /// Run RasterToPoly tool to convert input raster to poly's.  Then run Intersect if input geomList has features
        /// </summary>
        /// <param name="rasterLayer"></param>
        /// <param name="ipDataset"></param>
        /// <param name="workspace"></param>
        /// <param name="geomList"></param>
        /// <returns>Featureclass name</returns>
        private string IntersectOutput(IRasterLayer rasterLayer, IDataset ipDataset, IFeatureWorkspace workspace, List <IGeometry> geomList)
        {
            IGeoProcessor2 gp = new GeoProcessorClass();

            gp.AddOutputsToMap = false;

            // Run RasterToPolygon
            string inRaster = rasterLayer.FilePath;
            string outRasterToPolyFcName = ipDataset.BrowseName + "_rasterToPoly";
            string outRasterToPolyPath   = ipDataset.Workspace.PathName + "\\" + outRasterToPolyFcName;
            string field = "VALUE";

            IVariantArray rasterToPolyParams = new VarArrayClass();

            rasterToPolyParams.Add(inRaster);
            rasterToPolyParams.Add(outRasterToPolyPath);
            rasterToPolyParams.Add("NO_SIMPLIFY");
            rasterToPolyParams.Add(field);

            try
            {
                object oResult = gp.Execute("RasterToPolygon_conversion", rasterToPolyParams, null);
                IGeoProcessorResult ipResult = (IGeoProcessorResult)oResult;

                if (geomList.Count == 0)
                {
                    return(outRasterToPolyFcName);
                }

                if (ipResult.Status == esriJobStatus.esriJobSucceeded)
                {
                    string outFcName = ipDataset.BrowseName + "_intersectRaster";
                    string outPath   = ipDataset.Workspace.PathName + "\\" + outFcName;

                    // Add a mask to buffer the output to selected distance
                    string fcPath    = SetGPMask(workspace, geomList, gp, "intersectMask");
                    string pathParam = outRasterToPolyPath + ";" + fcPath;

                    IVariantArray parameters = new VarArrayClass();
                    parameters.Add(pathParam);
                    parameters.Add(outPath);

                    object oResult2 = gp.Execute("Intersect_analysis", parameters, null);
                    IGeoProcessorResult ipResult2 = (IGeoProcessorResult)oResult2;
                    return(outFcName);
                }
                else
                {
                    return(null);
                }
            }
            catch (Exception ex)
            {
                return(null);
            }
        }
Beispiel #19
0
        public bool ConvertLayerToKML(string kmzOutputPath, string tmpShapefilePath,
                                      ESRI.ArcGIS.Carto.IMap map, GraphicTypes graphicType)
        {
            try
            {
                string kmzName = System.IO.Path.GetFileName(kmzOutputPath);

                IGeoProcessor2 gp = new GeoProcessorClass();
                gp.OverwriteOutput = true;
                IGeoFeatureLayer geoLayer = null;

                IVariantArray parameters = new VarArrayClass();
                parameters.Add(tmpShapefilePath);
                parameters.Add(kmzName);
                gp.Execute("MakeFeatureLayer_management", parameters, null);

                string layerFileName = getLayerFileFromGraphicType(graphicType);
                if (!string.IsNullOrEmpty(layerFileName))
                {
                    IVariantArray parametersASM = new VarArrayClass();
                    parametersASM.Add(kmzName);
                    parametersASM.Add(layerFileName);
                    gp.Execute("ApplySymbologyFromLayer_management", parametersASM, null);
                }

                IVariantArray parameters1 = new VarArrayClass();
                // assign  parameters
                parameters1.Add(kmzName);
                parameters1.Add(kmzOutputPath);

                gp.Execute("LayerToKML_conversion", parameters1, null);

                // Remove the temporary layer from the TOC
                for (int i = 0; i < map.LayerCount; i++)
                {
                    ILayer layer = map.get_Layer(i);
                    if ((layer.Name == "featureLayer") || (layer.Name == kmzName))
                    {
                        map.DeleteLayer(layer);
                        break;
                    }
                }
                if (geoLayer != null)
                {
                    map.DeleteLayer(geoLayer);
                }

                return(true);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message);
                return(false);
            }
        }
        static void Main(string[] args)
        {
            // Load the product code and version to the version manager
            ESRI.ArcGIS.RuntimeManager.Bind(ESRI.ArcGIS.ProductCode.Desktop);

            //ESRI License Initializer generated code.
            m_AOLicenseInitializer.InitializeApplication(new esriLicenseProductCode[] { esriLicenseProductCode.esriLicenseProductCodeAdvanced },
            new esriLicenseExtensionCode[] { });

            // Create geoprocessor. Overwrite true will replace existing output
            IGeoProcessor2 gp = new GeoProcessorClass();
            gp.OverwriteOutput = true;

            // Get the workspace from the user
            Console.WriteLine("Enter the path to folder where you copied the data folder.");
            Console.WriteLine("Example: C:\\AirportsAndGolf\\data");
            Console.Write(">");
            string wks = Console.ReadLine();

            // set the workspace to the value user entered
            gp.SetEnvironmentValue("workspace", wks + "\\" + "golf.gdb");

            // Add the custom toolbox to geoprocessor
            gp.AddToolbox(wks + "\\" + "Find Golf Courses.tbx");

            // Create a variant - data are in the workspace
            IVariantArray parameters = new VarArrayClass();
            parameters.Add("Airports");
            parameters.Add("8 Miles");
            parameters.Add("Golf");
            parameters.Add("GolfNearAirports");

            object sev = null;

            try
            {
                gp.Execute("GolfFinder", parameters, null);
                Console.WriteLine(gp.GetMessages(ref sev));
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                string errorMsgs = gp.GetMessages(ref sev);
                Console.WriteLine(errorMsgs);
            }
            finally
            {
                Console.WriteLine("Hit Enter to quit");
                Console.ReadLine(); // pause the console to see messages
            }

            //ESRI License Initializer generated code.
            //Do not make any call to ArcObjects after ShutDownApplication()
            m_AOLicenseInitializer.ShutdownApplication();
        }
Beispiel #21
0
        //执行GP的数据修复功能
        //田晶添加20080916
        //修改,提高效率
        //靳军杰2011-11-30
        /// <summary>
        /// 修复面图层自相交错误
        /// </summary>
        /// <param name="sPath"></param>
        /// <returns></returns>
        public bool FeatureRepair(string sPath)
        {
            if (string.IsNullOrEmpty(sPath))
            {
                return(false);
            }

            IGeoProcessor pGP = new GeoProcessorClass();

            try
            {
                //GT_CARTO.XApplication.ProgressBar.ShowGifProgress(null);
                //GT_CARTO.XApplication.ProgressBar.ShowHint("正在预处理地类图斑数据...");
                //string sPath = pWks.PathName;
                pGP.OverwriteOutput = true;
                pGP.SetEnvironmentValue("workspace", (object)sPath);

                IGpEnumList pfds = pGP.ListFeatureClasses("", "Polygon", "Dataset");

                string sFeatClsName = pfds.Next();

                //IGeoProcessorResult pResult;

                while (!string.IsNullOrEmpty(sFeatClsName))
                {
                    if (!sFeatClsName.Contains("_Standard") &&
                        !sFeatClsName.Equals("TK", StringComparison.OrdinalIgnoreCase))
                    {
                        //要修复的FeatureClass路径
                        string        sInFeatureClassPath = string.Format("{0}\\dataset\\{1}", sPath, sFeatClsName);
                        IVariantArray pValues             = new VarArrayClass();
                        pValues.Add(sInFeatureClassPath);
                        pGP.Execute("RepairGeometry", pValues, null);
                        object obj = 2;
                        //GT_CONST.LogAPI.CheckLog.AppendErrLogs(pGP.GetMessages(ref obj));
                    }
                    sFeatClsName = pfds.Next();
                }
                return(true);
            }

            catch (Exception exp)
            {
                Hy.Common.Utility.Log.OperationalLogManager.AppendMessage(exp.ToString());

                //GT_CARTO.XApplication.ProgressBar.Hide();
                return(false);
            }
            finally
            {
                //GT_CARTO.XApplication.ProgressBar.Hide();
                Marshal.ReleaseComObject(pGP);
            }
        }
Beispiel #22
0
        private void OK_Click(object sender, EventArgs e)
        {
            // 2013-04-10 张航宇
            // 添加验证
            if (string.IsNullOrWhiteSpace(buttonEdit1.Text))
            {
                MessageBox.Show("请选择原DEM路径!");
                return;
            }
            if (string.IsNullOrWhiteSpace(buttonEdit2.Text))
            {
                MessageBox.Show("请选择山脊线生成路径!");
                return;
            }

            if (string.IsNullOrWhiteSpace(buttonEdit3.Text))
            {
                MessageBox.Show("请选择山谷线生成路径!");
                return;
            }

            //1-定义GeoProcessor对象
            this.gp = new Geoprocessor();
            object sev = null;

            //2-设置参数
            gp.OverwriteOutput = true;
            //3-设置工具箱所在的路径
            gp.AddToolbox(Application.StartupPath + @"\Convert\TerrainTool.tbx");
            //4-设置输入参数
            ESRI.ArcGIS.esriSystem.IVariantArray parameters = new VarArrayClass();
            parameters.Add(buttonEdit1.Text);
            parameters.Add(buttonEdit2.Text + "\\shanji");
            parameters.Add(buttonEdit3.Text + "\\shangu");
            parameters.Add(Convert.ToDouble(spinEdit1.Value));
            IGeoProcessorResult results = null;

            try
            {
                results = (IGeoProcessorResult)gp.Execute("Terrain", parameters, null);
                if (results == null)
                {
                    MessageBox.Show("生成失败!");
                }
                MessageBox.Show("生成成功!", "", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show("生成失败!");

                //throw;
            }
        }
Beispiel #23
0
        private void btnRename_Click(object sender, EventArgs e)
        {
            IGeoProcessor2 gp = new GeoProcessorClass();

            IVariantArray parameters = new VarArrayClass();

            // Populate the variant array with parameter values.
            parameters.Add(@"C:\gis\Projects\syria\data\temp\Export_Output.shp");
            parameters.Add(@"C:\gis\Projects\syria\data\temp\Export_Output2.shp");
            // Execute the tool
            gp.Execute("Rename_management", parameters, null);
        }
        public static void CopyFeatures(IFeatureClass feaCls)
        {
            IGeoProcessor2 geoProcessor2 = new GeoProcessorClass();
            geoProcessor2.OverwriteOutput = true;
            geoProcessor2.SetEnvironmentValue("workspace", @"e:\GP\California.gdb");

            IVariantArray parameters = new VarArrayClass();
            parameters.Add("Lakes");
            parameters.Add("origin_copy");

            geoProcessor2.Execute("CopyFeatures_management", parameters, null);
        }
Beispiel #25
0
        /// <summary>
        /// 拷贝要素类
        /// </summary>
        /// <param name="sourcePath">需要拷贝的要素类路径</param>
        /// <param name="targetPath">拷贝要素类的路径</param>
        static private IFeatureClass CopyFeatureClass(string sourcePath, string targetPath)
        {
            Console.WriteLine("拷贝要素类");
            IWorkspace        workspace;
            IFeatureWorkspace featureWorkspace;
            IWorkspaceFactory workspaceFactory = new ShapefileWorkspaceFactoryClass();
            string            path_dir         = System.IO.Path.GetDirectoryName(targetPath);

            workspace        = workspaceFactory.OpenFromFile(System.IO.Path.GetDirectoryName(targetPath), 0);
            featureWorkspace = workspace as IFeatureWorkspace;

            if (File.Exists(targetPath))                                                         //存在该路径,则在文件夹中找到文件并删除
            {
                string        fileName = System.IO.Path.GetFileNameWithoutExtension(targetPath); //文件名称
                DirectoryInfo root     = new DirectoryInfo(path_dir);
                foreach (FileInfo f in root.GetFiles())
                {
                    if (f.Name.Split('.')[0] == fileName)
                    {
                        string filepath = f.FullName;
                        File.Delete(filepath);
                    }
                }
            }

            //拷贝要素类
            IGeoProcessor2 gp = new GeoProcessorClass();

            gp.OverwriteOutput = true;
            IGeoProcessorResult result     = new GeoProcessorResultClass();
            IVariantArray       parameters = new VarArrayClass();
            object sev = null;

            try
            {
                parameters.Add(sourcePath);
                parameters.Add(targetPath);
                result = gp.Execute("Copy_management", parameters, null);
                Console.WriteLine(gp.GetMessages(ref sev));
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine(gp.GetMessages(ref sev));
            }

            string        name         = System.IO.Path.GetFileName(targetPath);
            IFeatureClass featureClass = featureWorkspace.OpenFeatureClass(name);

            return(featureClass);
        }
Beispiel #26
0
        public void ShapeInWhereTest3()
        {
            //new ArcEngineLicense();
            RuntimeManager.BindLicense(ProductCode.EngineOrDesktop);
            //ESRI.ArcGIS.RuntimeManager.Bind(ESRI.ArcGIS.ProductCode.EngineOrDesktop);
            var sdeWs = DataActions.GetSdeWorkspace(new Dictionary <string, object>()
            {
                { "INSTANCE", "sde:oracle11g:192.168.0.2/orcl" },
                { "USER", "dzgisdata" },
                { "PASSWORD", "dzgisdata" },
            });



            var outFcname = $@"C:/test/i{DateTime.Now.ToBinary()}.shp";
            var feaWs     = (IFeatureWorkspace)sdeWs;
            var xzqh      = feaWs.OpenFeatureClass("DZGISDATA.XZQH");
            //var ydhx = feaWs.OpenFeatureClass("DZGISDATA.YDHX_SP");

            IVariantArray arr = new VarArrayClass();

            //arr.Add(@"C:\test\dzgisdata02.sde\DZGISDATA.XZQH\DZGISDATA.XZQH");
            arr.Add(outFcname);

            //IGeoProcessor gp2 = new GeoProcessorClass();
            //IGeoProcessorResult result = gp2.Execute("Select", arr, null);
            var gp = new Geoprocessor();


            var result = gp.Execute(new Select()
            {
                in_features       = @"C:\test\continents.shp",
                out_feature_class = outFcname,
            }, null);

            ;

            //Select sel = new Select()
            //{
            //    in_features = xzqh,
            //    out_feature_class = outFcname

            //};
            //var result = new Geoprocessor().Execute(sel, null);

            //var gpResult = (IGeoProcessorResult)result;

            //var gpms = gpResult.GetResultMessages();
        }
Beispiel #27
0
//---------------------------------------------------------------------------------------------------------------------
        /// <summary>
        /// 用arcgis模型工具根据表格数据把表格转化为shp文件
        /// </summary>
        /// <param name="modelName">arcgis中模型的名称</param>
        /// <param name="excelpath">表格路径</param>
        /// <param name="xField">表格中作为X坐标的字段</param>
        /// <param name="yField">表格中作为Y坐标的字段</param>
        /// <param name="wkid">坐标系参数</param>
        /// <param name="shpPath">输出shp文件路径</param>
        /// <returns></returns>
        public bool ExcelToShp(string modelName, string excelpath, string xField, string yField, int wkid, string shpPath)
        {
            IVariantArray parameters = new VarArrayClass();

            parameters.Add(excelpath);
            parameters.Add(xField);
            parameters.Add(yField);
            ISpatialReferenceFactory spatialReferenceFactory = new SpatialReferenceEnvironmentClass();
            ISpatialReference        spatialReference        = spatialReferenceFactory.CreateProjectedCoordinateSystem(wkid);

            parameters.Add(spatialReference);
            parameters.Add(shpPath);
            RunModelTool(System.AppDomain.CurrentDomain.BaseDirectory + "gisModelTool\\Tool\\Toolbox.tbx", System.AppDomain.CurrentDomain.BaseDirectory + "gisModelTool\\Data", parameters, modelName);
            return(true);
        }
Beispiel #28
0
        //获取栅格最小值
        public double GetMinPixelValue(string fullfilepath)
        {
            double         min = 0;
            IGeoProcessor2 gp  = new GeoProcessorClass();

            gp.OverwriteOutput = true;
            IGeoProcessorResult result     = new GeoProcessorResultClass();
            IVariantArray       parameters = new VarArrayClass();

            parameters.Add(fullfilepath);
            parameters.Add("MINIMUM");
            result = gp.Execute("GetRasterProperties_management", parameters, null);
            min    = Convert.ToDouble(result.ReturnValue);
            return(min);
        }
Beispiel #29
0
        //获得转换的方法和转换的参数
        private void GetTnsInfo(ref string strMethod, ref IVariantArray pArray)
        {
            pArray = new VarArrayClass();
            if (this.cmboTnsMethod.SelectedIndex < 0)
            {
                return;
            }

            DataTable dt = this.dtTns.DataSource as DataTable;

            strMethod = this.cmboTnsMethod.Text;
            if (strMethod == "基于地心三参数转换法")
            {
                pArray.Add("PARAMETER['X_Axis_Translation'," + GetTnsValue("X偏移(米)", dt).ToString() + "]");
                pArray.Add("PARAMETER['Y_Axis_Translation'," + GetTnsValue("Y偏移(米)", dt).ToString() + "]");
                pArray.Add("PARAMETER['Z_Axis_Translation'," + GetTnsValue("Z偏移(米)", dt).ToString() + "]");
            }
            else if (strMethod == "位置矢量法")
            {
                pArray.Add("PARAMETER['X_Axis_Translation'," + GetTnsValue("X偏移(米)", dt).ToString() + "]");
                pArray.Add("PARAMETER['Y_Axis_Translation'," + GetTnsValue("Y偏移(米)", dt).ToString() + "]");
                pArray.Add("PARAMETER['Z_Axis_Translation'," + GetTnsValue("Z偏移(米)", dt).ToString() + "]");
                pArray.Add("PARAMETER['X_Axis_Rotation'," + GetTnsValue("X旋转(秒)", dt).ToString() + "]");
                pArray.Add("PARAMETER['Y_Axis_Rotation'," + GetTnsValue("Y旋转(秒)", dt).ToString() + "]");
                pArray.Add("PARAMETER['Z_Axis_Rotation'," + GetTnsValue("Z旋转(秒)", dt).ToString() + "]");
                pArray.Add("PARAMETER['Scale_Difference'," + GetTnsValue("比例因子(百万分率)", dt).ToString() + "]");
            }
            else if (strMethod == "")
            {
            }

            string strArr = "";

            for (int i = 0; i < pArray.Count; i++)
            {
                string strTemp = pArray.get_Element(i).ToString();
                if (strArr == "")
                {
                    strArr = strTemp;
                }
                else
                {
                    strArr = strArr + "," + strTemp;
                }
            }

            strMethod = "GEOGTRAN[METHOD['" + GetMethod(strMethod) + "']," + strArr;
        }
 /// <summary>
 /// 根据输入的中红外影像获取洪湖矢量边界
 /// </summary>
 /// <param name="inputPath"></param>
 /// <param name="savePath"></param>
 public void CalculateBoundary(string inputPath, string savePath)
 {
     try
     {
         //使用模型来处理
         _gp.AddToolbox(@"D:\RasterMaSysTemp\hhData\MyToolbox.tbx");
         IVariantArray parametersArray = new VarArrayClass();
         parametersArray.Add(inputPath);
         parametersArray.Add(savePath);
         _gp.Execute("GetHonghuBoundary", parametersArray, null);
     }
     catch (Exception e)
     {
         MessageBox.Show("获取边界出现错误:" + e.ToString());
     }
 }
 /// <summary>
 /// 克里金插值
 /// </summary>
 ///  /// <param name="field">插值字段</param>
 /// <param name="outputName">输出影像</param>
 public void CalKriging(string field, string outputName)
 {
     try
     {
         //使用模型来处理
         //先使用克里金插值,然后裁剪
         _gp.AddToolbox(@"D:\RasterMaSysTemp\hhData\MyToolbox.tbx");
         IVariantArray parametersArray = new VarArrayClass();
         parametersArray.Add(field);
         parametersArray.Add(outputName);
         _gp.Execute("GridInterpolation", parametersArray, null);
     }
     catch (Exception exception)
     {
         MessageBox.Show("插值出现错误:" + exception.ToString());
     }
 }
Beispiel #32
0
        static void LoadDirToRasterCatalog(string outRasterCatalog, string inputDir)
        {
            //Initialize GeoProcessor
            ESRI.ArcGIS.Geoprocessor.Geoprocessor geoProcessor = new ESRI.ArcGIS.Geoprocessor.Geoprocessor();

            //Set parameters
            IVariantArray parameters = new VarArrayClass();

            //Set input folder
            parameters.Add(inputDir);

            //Set target GDB raster catalog
            parameters.Add(outRasterCatalog);

            //Execute the tool to load rasters in the directory to raster catalog
            geoProcessor.Execute("WorkspaceToRasterCatalog", parameters, null);
            ReturnMessages(geoProcessor);
        }
Beispiel #33
0
        public Task <string> DoGeoprocessingThing(CancellationToken cts, BackgroundWorker worker)
        {
            System.Object obj = "";
            Geoprocessor  gp1 = new Geoprocessor();
            GeoProcessor  gp  = new GeoProcessor();

            gp1.OverwriteOutput = true;
            try
            {
                // ################################################
                // Working call to an existing ArcGIS Toolbox Tool:
                CreateFileGDB createFileGdb = new CreateFileGDB();
                createFileGdb.out_folder_path = "c:/temp";
                createFileGdb.out_name        = "tmp.gdb";
                gp1.Execute(createFileGdb, null);
                // ###############################################

                // ###########################################
                // This process will fail if you've already started ArcObjects by opening the form UI dialog
                gp.AddToolbox(@"C:\temp\ArcObjectsIssue\HelloTest.tbx"); //path to your toolbox here!!!!!!!!!!!!!!!
                IVariantArray parameters = new VarArrayClass();
                parameters = new VarArrayClass();
                parameters.Add("Hello Geoprocessing Tool with Python Script!");
                gp.Execute("helloPython", parameters, null);
                cts.ThrowIfCancellationRequested();
                // ###########################################
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
                Console.WriteLine(ReturnGpMessages(gp, obj)); //from a support library not shared here.

                throw new Exception("yeah things went south");
            }
            finally
            {
                gp  = null;
                gp1 = null;
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }

            return(null);
        }
        private void CreateNetworkTurnFeatureClass()
        {
            IVariantArray paramArray = new VarArrayClass();
            paramArray.Add(_dsPath);
            paramArray.Add(_turnClassName);
            paramArray.Add(2);

            TaskManager.ExecuteTool("CreateTurnFeatureClass_na", paramArray);

            paramArray.RemoveAll();
            paramArray.Add(_dsPath + "\\" + _turnClassName);
            paramArray.Add("RestrictionType");
            paramArray.Add("TEXT");
            paramArray.Add("");
            paramArray.Add("");
            paramArray.Add(30);
            paramArray.Add("");
            paramArray.Add("NULLABLE");

            TaskManager.ExecuteTool("AddField_management", paramArray);
        }
Beispiel #35
0
        static void Main(string[] args)
        {
            RuntimeManager.Bind(ProductCode.Desktop);
            GeoProcessor gp =new  GeoProcessor();
            IVariantArray parameters = new VarArrayClass();
               
            //input layer location
            parameters.Add(@"C:\junk\122.mdb\test");
            //output location
            parameters.Add(@"C:\\Users\\shri7493\\Documents\\ArcGIS\\Default.gdb\\TBL_HYDRANT_Statistics");
            //summary field followed by summary method - in this case "MAX" - maximium value
            parameters.Add("OBJECTID MAX");

            IGeoProcessorResult gpResult = gp.Execute("Statistics_analysis", parameters, null);
            for (int i = 0; i < gpResult.MessageCount; i++)
            {
            Console.Write (gpResult.GetMessage(i).ToString());
            }


            gp.ClearMessages();
        }
        public bool ConvertLayerToKML(string kmzOutputPath, string tmpShapefilePath, ESRI.ArcGIS.Carto.IMap map)
        {
            try
            {
                string kmzName = System.IO.Path.GetFileName(kmzOutputPath);
                string folderName = System.IO.Path.GetDirectoryName(kmzOutputPath);

                IGeoProcessor2 gp = new GeoProcessorClass();
                IVariantArray parameters = new VarArrayClass();
                parameters.Add(tmpShapefilePath);
                parameters.Add(kmzName);
                gp.Execute("MakeFeatureLayer_management", parameters, null);

                IVariantArray parameters1 = new VarArrayClass();
                // assign  parameters        
                parameters1.Add(kmzName);
                parameters1.Add(kmzOutputPath);

                gp.Execute("LayerToKML_conversion", parameters1, null);

                // Remove the temporary layer from the TOC
                for (int i = 0; i < map.LayerCount; i++ )
                {
                    ILayer layer = map.get_Layer(i);
                    if (layer.Name == "featureLayer")
                    {
                        map.DeleteLayer(layer);
                        break;
                    }
                }

                return true;
            }
            catch(Exception ex)
            {
                return false;
            }
        }
Beispiel #37
0
        public static string ConvertMXDToMSD(string mxdfile, string convertMXDtoMSDtoolboxPath)
        {
            if (!File.Exists(convertMXDtoMSDtoolboxPath))
            {
                MessageBox.Show(string.Format("GP Toolbox {0} to convert mxd to msd is not found", convertMXDtoMSDtoolboxPath), "Convert MXD to MSD", MessageBoxButton.OK, MessageBoxImage.Error);
                return null;
            }

            Geoprocessor gp = new Geoprocessor()
            {
                OverwriteOutput = true
            };
            gp.AddToolbox(convertMXDtoMSDtoolboxPath);
            IVariantArray gpparams = new VarArrayClass();
            gpparams.Add(mxdfile);

            IGeoProcessorResult gpresult = null;
            try
            {
                gpresult = gp.Execute(Properties.Settings.Default.toolname, gpparams, null) as IGeoProcessorResult;
            }
            catch (Exception)
            {
                object sev = 2;
                System.Windows.MessageBox.Show(gp.GetMessages(ref sev));
                return null;
            }

            string msdfile = ((IGPString)gpresult.GetOutput(0)).Value;
            //MessageBox.Show(msdfile);

            gp = null;
            gpresult = null;

            return msdfile;
        }
Beispiel #38
0
        //执行GP的数据修复功能
        //田晶添加20080916
        //修改,提高效率
        //靳军杰2011-11-30
        /// <summary>
        /// 修复面图层自相交错误
        /// </summary>
        /// <param name="sPath"></param>
        /// <returns></returns>
        public bool FeatureRepair(string sPath)
        {
            if (string.IsNullOrEmpty(sPath))
            {
                return false;
            }

            IGeoProcessor pGP = new GeoProcessorClass();
            try
            {
                //GT_CARTO.XApplication.ProgressBar.ShowGifProgress(null);
                //GT_CARTO.XApplication.ProgressBar.ShowHint("正在预处理地类图斑数据...");
                //string sPath = pWks.PathName;
                pGP.OverwriteOutput = true;
                pGP.SetEnvironmentValue("workspace", (object)sPath);

                IGpEnumList pfds = pGP.ListFeatureClasses("", "Polygon", "Dataset");

                string sFeatClsName = pfds.Next();

                //IGeoProcessorResult pResult;

                while (!string.IsNullOrEmpty(sFeatClsName))
                {
                    if (!sFeatClsName.Contains("_Standard") &&
                        !sFeatClsName.Equals("TK", StringComparison.OrdinalIgnoreCase))
                    {
                        //要修复的FeatureClass路径
                        string sInFeatureClassPath = string.Format("{0}\\dataset\\{1}", sPath, sFeatClsName);
                        IVariantArray pValues = new VarArrayClass();
                        pValues.Add(sInFeatureClassPath);
                        pGP.Execute("RepairGeometry", pValues, null);
                        object obj = 2;
                        //GT_CONST.LogAPI.CheckLog.AppendErrLogs(pGP.GetMessages(ref obj));
                    }
                    sFeatClsName = pfds.Next();
                }
                return true;
            }

            catch (Exception exp)
            {
                Hy.Common.Utility.Log.OperationalLogManager.AppendMessage(exp.ToString());

                //GT_CARTO.XApplication.ProgressBar.Hide();
                return false;
            }
            finally
            {
                //GT_CARTO.XApplication.ProgressBar.Hide();
                Marshal.ReleaseComObject(pGP);
            }
        }
        static void LoadDirToRasterCatalog(string outRasterCatalog, string inputDir)
        {
            //Initialize GeoProcessor
            ESRI.ArcGIS.Geoprocessor.Geoprocessor geoProcessor = new ESRI.ArcGIS.Geoprocessor.Geoprocessor();

            //Set parameters
            IVariantArray parameters = new VarArrayClass();

            //Set input folder
            parameters.Add(inputDir);

            //Set target GDB raster catalog
            parameters.Add(outRasterCatalog);

            //Execute the tool to load rasters in the directory to raster catalog
            geoProcessor.Execute("WorkspaceToRasterCatalog", parameters, null);
            ReturnMessages(geoProcessor);
        }
        /// <summary>Selects a subset of features to a new feature class</summary>
        private void SelectFeaturesToNewFeatureClass(string source, string target, string query)
        {
            try
            {
                IVariantArray paramArray = new VarArrayClass();
                paramArray.Add(source);
                paramArray.Add(target);
                paramArray.Add(query);

                _taskManager.ExecuteTool("Select_analysis", paramArray);
            }
            catch (COMException comex)
            {
                // When working with file geodatabase, assume E_FAIL is a locking issue
                if (_osmDataset.Workspace.Type == esriWorkspaceType.esriLocalDatabaseWorkspace)
                {
                    if ((uint)comex.ErrorCode == 0x80004005)
                    {
                        throw new ApplicationException(string.Format(RESMGR.GetString("GPTools_OSMGPCreateNetworkDataset_lockedTarget"), target));
                    }
                }

                throw;
            }
        }
        /// <summary>Use AttributeSelector to create attributes for fields specified in the config XML</summary>
        private void ConvertRequiredTagsToAttributes(bool isEdge)
        {
            string featureClassName = ((isEdge) ? _osmLineName : _osmPointName);
            string featureClassPath = ((isEdge) ? _osmLinePath : _osmPointPath);

            using (ComReleaser cr = new ComReleaser())
            {
                IFeatureClass fc = ((IFeatureWorkspace)_osmDataset.Workspace).OpenFeatureClass(featureClassName);
                cr.ManageLifetime(fc);

                string[] requiredFieldNames = ((isEdge) ? _xml.EdgeFieldNames() : _xml.JunctionFieldNames())
                    .Where(fld => fc.FindField("osm_" + fld) == -1)
                    .ToArray();

                if (requiredFieldNames.Length > 0)
                {
                    IVariantArray paramArray = new VarArrayClass();
                    paramArray.Add(featureClassPath);
                    paramArray.Add(string.Join(";", requiredFieldNames));

                    _taskManager.ExecuteTool("OSMGPAttributeSelector_osmtools", paramArray);
                }
            }
        }
        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());
                }
            }
        }
        /// <summary>
        /// Called when a step of this type is executed in the workflow.
        /// </summary>
        /// <param name="JobID">ID of the job being executed</param>
        /// <param name="StepID">ID of the step being executed</param>
        /// <param name="argv">Array of arguments passed into the step's execution</param>
        /// <param name="ipFeedback">Feedback object to return status messages and files</param>
        /// <returns>Return code of execution for workflow path traversal</returns>
        public int Execute(int jobID, int stepID, ref object[] argv, ref IJTXCustomStepFeedback ipFeedback)
        {
#if (!SERVER)
            StatusForm sfd = null;
#endif
            bool success = true;

            // Reset the message logging
            this.ClearCachedLogMessages();

            try
            {
                Log("ExecuteGPTool.Execute beginning..");

                // Define variables
                string strToolboxPath = "";
                string strTool = "";
                string strToolboxRoot = "";
                string strToolboxName = "";

                // Get the toolbox name (check for errors)
                if (!StepUtilities.GetArgument(ref argv, "toolboxpath", true, out strToolboxPath) || strToolboxPath.Equals(String.Empty))
                {
                    success = false;
                    Log("Error getting 'toolboxpath' argument");
#if (!SERVER)
                    MessageBox.Show("Missing toolbox argument.");
#endif
                }
                // Get the tool name (check for errors)
                else if (!StepUtilities.GetArgument(ref argv, "tool", true, out strTool) || strTool.Equals(String.Empty))
                {
                    success = false;
                    Log("Error getting 'tool' argument");
#if (!SERVER)
                    MessageBox.Show("Missing tool argument.");
#endif
                }
                else
                {
#if (!SERVER)
                    // Display status dialog
                    sfd = new StatusForm();
                    sfd.ToolName = strTool;
                    sfd.Show();
                    sfd.Refresh();
#endif

                    // Get directory of toolbox
                    strToolboxRoot = Path.GetDirectoryName(strToolboxPath);
                    // Get toolbox name without .tbx extension
                    strToolboxName = Path.GetFileNameWithoutExtension(strToolboxPath);

                    // Open toolbox and tool
                    IWorkspaceFactory pToolboxWorkspaceFactory = new ToolboxWorkspaceFactoryClass();
                    IToolboxWorkspace pToolboxWorkspace = pToolboxWorkspaceFactory.OpenFromFile(strToolboxRoot, 0) as IToolboxWorkspace;
                    IGPToolbox pGPToolbox = pToolboxWorkspace.OpenToolbox(strToolboxName);
                    IGPTool pGPTool = pGPToolbox.OpenTool(strTool);

                    Log("ExecuteGPTool.Execute successfully opened Tool " + strTool + " in Toolbox " + strToolboxPath + "..");

                    // Generate the arrays for parameters
                    IVariantArray parameters = new VarArrayClass();  // For Execute method
                    ESRI.ArcGIS.esriSystem.IArray pParameterArray = pGPTool.ParameterInfo;  // For Validate and InvokeModal methods

                    // Get parameter "pairs"; "GetDoubleArguments" supports the GP-style,
                    // two-colon argument strings, like "/param:tool_param_name:tool_param_value"
                    string[] argNames;
                    string[] argValues;
                    if (StepUtilities.GetDoubleArguments(ref argv, "param", true, out argNames, out argValues))
                    {
                        // Stash away the variables that were passed in
                        Dictionary<string, string> argTable = new Dictionary<string, string>();
                        for (int i = 0; i < argNames.Length; i++)
                        {
                            string uppercaseName = argNames[i].ToUpper();
                            argTable[uppercaseName] = argValues[i];
                        }

                        // The GP tool's parameter list may include parameters that weren't specified in the
                        // JTX step arguments.  So iterate through the tool's parameters, setting the values
                        // from the input where you can.  Where no value was passed in, just skip the
                        // parameter and go with the default.
                        for (int i = 0; i < pParameterArray.Count; i++)
                        {
                            IGPParameter pGPParam = (IGPParameter)pParameterArray.get_Element(i);
                            IGPParameterEdit pGPParamEdit = (IGPParameterEdit)pGPParam;
                            string uppercaseName = pGPParam.Name.ToUpper();

                            // Override the default value, if something was passed in
                            if (argTable.ContainsKey(uppercaseName))
                            {
                                IGPDataType pGPType = pGPParam.DataType;
                                string strValue = argTable[uppercaseName];
                                pGPParamEdit.Value = pGPType.CreateValue(strValue);

                                Log("ExecuteGPTool.Execute Tool Parameter = " + uppercaseName + ", Value = " + strValue + "..");
                            }

                            // Always stash away the current parameter value, since we need the complete list
                            // for "Execute" below.
                            parameters.Add(pGPParam.Value);
                        }
                    }

                    Log("ExecuteGPTool.Execute successfully setup parameter values..");


                    // Initialize the geoprocessor
                    IGeoProcessor pGP = new GeoProcessorClass();

                    // Create callback object for GP messages
                    JTXGPCallback pCallback = new JTXGPCallback();

                    // Set up the geoprocessor
                    pGP.AddToolbox(strToolboxPath);
                    pGP.RegisterGeoProcessorEvents(pCallback);

                    Log("ExecuteGPTool.Execute created and registered GeoProcessor..");

                    // Create the messages object and a bool to pass to InvokeModal method
                    IGPMessages pGPMessages = pGPTool.Validate(pParameterArray, true, null);
                    IGPMessages pInvokeMessages = new GPMessagesClass();
                    string strMessage = "";

                    // Check for error messages
                    if (pGPMessages.MaxSeverity == esriGPMessageSeverity.esriGPMessageSeverityError)
                    {
#if (!SERVER)
                        // Only want to invoke a modal dialog if we're running on a workstation
                        // Set a reference to IGPCommandHelper2 interface
                        IGPToolCommandHelper2 pToolHelper = new GPToolCommandHelperClass() as IGPToolCommandHelper2;
                        pToolHelper.SetTool(pGPTool);
                        bool pOK = true;

                        // Open tool GUI
                        pToolHelper.InvokeModal(0, pParameterArray, out pOK, out pInvokeMessages);
                        if (pOK == true)
                        {
                            bool bFailureMessages;
                            strMessage = ConvertGPMessagesToString(pInvokeMessages, out bFailureMessages);
                            success = !bFailureMessages;
                        }
                        else
                        {
                            success = false;
                        }
#else
                        Log("ExecuteGPTool.Execute Tool Validate failed..");

                        // If we're running on a server, then just indicate a failure.  (Someone will
                        // have to use the JTX application to fix the step arguments, if they can be
                        // fixed.)
                        success = false;
#endif
                    }
                    else  // If there are no error messages, execute the tool
                    {
                        Log("ExecuteGPTool.Execute successfully validated parameter values, About to Execute..");
                        IGPMessages ipMessages = new GPMessagesClass();
                        try
                        {
                            pGPTool.Execute(pParameterArray, null, new GPEnvironmentManagerClass(), ipMessages);
                            Log("ExecuteGPTool.Execute completed call to pGPTool.Execute()");
                        }
                        catch (System.Runtime.InteropServices.COMException ex)
                        {
                            success = false;
                            Log("ExecuteGPTool.Execute Tool Execute failed, Message = " + ex.Message + ", DataCode = " + ex.ErrorCode + ", Data = " + ex.StackTrace);
                        }

                        // Get Messages
                        bool bFailureMessages = false;
                        strMessage += this.ConvertGPMessagesToString(ipMessages, out bFailureMessages);

                        Log("ExecuteGPTool.Execute got messages from tool");
                        Log("*** GP MESSAGES ***" + System.Environment.NewLine + strMessage + System.Environment.NewLine);
                        Log("*** END GP MESSAGES ***");

                        // If tool failed during execution, indicate a failure
                        if (pGP.MaxSeverity == (int)esriGPMessageSeverity.esriGPMessageSeverityError)
                        {
                            success = false;
                            Log("ExecuteGPTool.Execute Found Error messages from the tool..");
                        }
                    }

                    // Call AttachMsg
                    try
                    {
                        IJTXJobManager ipJobManager = m_ipDatabase.JobManager;
                        IJTXJob ipJob = ipJobManager.GetJob(jobID);
                        AttachMsg(ipJob, strTool, this.GetCachedLogMessages());
                        this.ClearCachedLogMessages();
                    }
                    catch (Exception ex)
                    {
                        string strEx = ex.Message;
                        Log("Caught exception: " + ex.Message);
                    }
                    
                    pGP.UnRegisterGeoProcessorEvents(pCallback);
                }
            }
            catch (Exception ex2)
            {
                success = false;
                Log("Caught exception: " + ex2.Message);
#if (!SERVER)
                string msg = "";
                if (ex2.InnerException == null)
                {
                    msg = "Inner Exception is null";
                }
                else
                {
                    msg = "Inner Exception is not null";
                }

                MessageBox.Show("Stack Trace: " + ex2.StackTrace + Environment.NewLine + "Message: " + ex2.Message + Environment.NewLine + "Source: " + ex2.Source + Environment.NewLine + msg);
#endif
            }

            // Clean up
#if (!SERVER)
            if (sfd != null)
            {
                sfd.Close();
            }
#endif

            // Indicate success or failure
            if (success == true)
            {
                return 1;
            }
            else
            {
                return 0;
            }
        }
        protected override void OnClick()
        {
            if (!Utilities.DoesConfigFileExist)
            {
                //Send a warning that the extension needs to be setup
                MessageBox.Show(string.Format("No Configuration File Available.  Please save config.xml at {0}", Utilities.iFormFolder));
            }

            //Read all the Layers in the MXD and process the Sync Table for that workspace
            IEnumLayer layers = ArcMap.Document.FocusMap.get_Layers();
            ILayer layer = layers.Next();
            SelectionTargetComboBox s_combo = SelectionTargetComboBox.GetSelectionComboBox();
            iFormBuilderAPI.iFormBuilder api = new iFormBuilderAPI.iFormBuilder();
            api.ReadConfiguration(Utilities.iFormConfigFile);
            processedworkspaces = new List<IWorkspace>();

            while (layer != null)
            {
                //if (layer.GetType() == typeof(IFeatureLayer))
                //{
                    IFeatureLayer fLayer = layer as IFeatureLayer;
                    IDataset pDataSet = fLayer.FeatureClass as IDataset;
                    try
                    {
                        if (!processedworkspaces.Contains(pDataSet.Workspace))
                        {
                            GPMessageEventHandler gpEventHandler = new GPMessageEventHandler();
                            //get an instance of the geoprocessor
                            //instruct the geoprocessing engine to overwrite existing datasets
                            GP.OverwriteOutput = true;
                            GP.AddToolbox(Utilities.iFormFolder + "\\" + "iFormTools.tbx");

                            // Create a variant. Data is in the workspace.
                            IVariantArray parameters = new VarArrayClass();
                            parameters.Add(pDataSet.Workspace.PathName);
                            parameters.Add(Utilities.iFormConfigFile);
                            parameters.Add(1);

                            GP.ToolExecuted += new EventHandler<ESRI.ArcGIS.Geoprocessor.ToolExecutedEventArgs>(gpToolExecuted);
                            GP.ExecuteAsync("SynciFormDatabase", parameters);

                            //add this workspace to the processed workspaces
                            processedworkspaces.Add(pDataSet.Workspace);
                        }
                    }
                    catch
                    {
                        MessageBox.Show("Synchronization Failed");
                    }
                    layer = layers.Next();
                //}
            }
        }
        internal IVariantArray CreateAddIndexParameterArray(string featureClassName, string fieldsToIndex, string IndexName, string unique, string sortingOrder)
        {
            IVariantArray parameterArrary = new VarArrayClass();
            // add first the name of the feature class
            parameterArrary.Add(featureClassName);
            // second parameter is the list of field to be indexed
            parameterArrary.Add(fieldsToIndex);
            // the third parameter is the name of index
            parameterArrary.Add(IndexName);
            // the fourth parameter is the (optional) indicator of the index contains unique values
            if (!String.IsNullOrEmpty(unique))
            {
                parameterArrary.Add(unique);
            }
            // the fifth parameter is the (optional) sorting order of the index
            if (!String.IsNullOrEmpty(sortingOrder))
            {
                parameterArrary.Add(sortingOrder);
            }

            return parameterArrary;
        }
        private IVariantArray CreateAddGridIndexParameterArray(string featureClassName, double gridIndex1, double gridIndex2, double gridIndex3)
        {
            IVariantArray featureClassArray = new VarArrayClass();

            // the feature class information as the first parameter
            featureClassArray.Add(featureClassName);

            // add the grid indices as additional parameters
            featureClassArray.Add(gridIndex1);
            featureClassArray.Add(gridIndex2);
            featureClassArray.Add(gridIndex3);

            return featureClassArray;
        }
        private IVariantArray CreateDefaultGridParamterArrary(string featureClassName)
        {
            IVariantArray featureClassArray = new VarArrayClass();

            featureClassArray.Add(featureClassName);

            return featureClassArray;
        }
        /// <summary>
        /// Run RasterToPoly tool to convert input raster to poly's.  Then run Intersect if input geomList has features
        /// </summary>
        /// <param name="rasterLayer"></param>
        /// <param name="ipDataset"></param>
        /// <param name="workspace"></param>
        /// <param name="geomList"></param>
        /// <returns>Featureclass name</returns>
        private string IntersectOutput(IRasterLayer rasterLayer, IDataset ipDataset, IFeatureWorkspace workspace, List<IGeometry> geomList)
        {
            IGeoProcessor2 gp = new GeoProcessorClass();
            gp.AddOutputsToMap = false;

            // Run RasterToPolygon
            string inRaster = rasterLayer.FilePath;
            string outRasterToPolyFcName = ipDataset.BrowseName + "_rasterToPoly";
            string outRasterToPolyPath = ipDataset.Workspace.PathName + "\\" + outRasterToPolyFcName;
            string field = "VALUE";

            IVariantArray rasterToPolyParams = new VarArrayClass();
            rasterToPolyParams.Add(inRaster);
            rasterToPolyParams.Add(outRasterToPolyPath);
            rasterToPolyParams.Add("NO_SIMPLIFY");
            rasterToPolyParams.Add(field);

            try
            {
                object oResult = gp.Execute("RasterToPolygon_conversion", rasterToPolyParams, null);
                IGeoProcessorResult ipResult = (IGeoProcessorResult)oResult;

                if (geomList.Count == 0)
                    return outRasterToPolyFcName;

                if (ipResult.Status == esriJobStatus.esriJobSucceeded)
                {
                    string outFcName = ipDataset.BrowseName + "_intersectRaster";
                    string outPath = ipDataset.Workspace.PathName + "\\" + outFcName;

                    // Add a mask to buffer the output to selected distance
                    string fcPath = SetGPMask(workspace, geomList, gp, "intersectMask");
                    string pathParam = outRasterToPolyPath + ";" + fcPath;

                    IVariantArray parameters = new VarArrayClass();
                    parameters.Add(pathParam);
                    parameters.Add(outPath);

                    object oResult2 = gp.Execute("Intersect_analysis", parameters, null);
                    IGeoProcessorResult ipResult2 = (IGeoProcessorResult)oResult2;
                    return outFcName;
                }
                else
                {
                    return null;
                }
            }
            catch (Exception ex)
            {
                return null;
            }
        }
        public bool AppendTable(string InTable, string TargetTable, bool Messages = false)
        {
            ESRI.ArcGIS.Geoprocessor.Geoprocessor gp = new ESRI.ArcGIS.Geoprocessor.Geoprocessor();
            gp.OverwriteOutput = true;

            IGeoProcessorResult myresult = new GeoProcessorResultClass();

            // Create a variant array to hold the parameter values.
            IVariantArray parameters = new VarArrayClass();


            // Populate the variant array with parameter values.
            parameters.Add(InTable);
            parameters.Add(TargetTable);

            // Execute the tool. Note this only works with geodatabase tables.
            try
            {
                myresult = (IGeoProcessorResult)gp.Execute("Append_management", parameters, null);

                // Wait until the execution completes.
                while (myresult.Status == esriJobStatus.esriJobExecuting)
                    Thread.Sleep(1000);
                // Wait for 1 second.
                if (Messages)
                {
                    MessageBox.Show("Process complete");
                }
                gp = null;
                return true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                gp = null;
                return false;
            }
        }
        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 bool CopyTable(string InTable, string OutTable, bool Messages = false)
        {
            // This works absolutely fine for dbf and geodatabase but does not export to CSV.

            // Note the csv export already removes ghe geometry field; in this case it is not necessary to check again.

            ESRI.ArcGIS.Geoprocessor.Geoprocessor gp = new ESRI.ArcGIS.Geoprocessor.Geoprocessor();
            gp.OverwriteOutput = true;

            IGeoProcessorResult myresult = new GeoProcessorResultClass();

            // Create a variant array to hold the parameter values.
            IVariantArray parameters = new VarArrayClass();

            // Populate the variant array with parameter values.
            parameters.Add(InTable);
            parameters.Add(OutTable);

            // Execute the tool.
            try
            {
                myresult = (IGeoProcessorResult)gp.Execute("CopyRows_management", parameters, null);

                // Wait until the execution completes.
                while (myresult.Status == esriJobStatus.esriJobExecuting)
                    Thread.Sleep(1000);
                    // Wait for 1 second.

                
                if (Messages)
                {
                    MessageBox.Show("Process complete");
                }
                gp = null;
                return true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                gp = null;
                return false;
            }
        }
        public bool CopyFeatures(string InFeatureClass, string OutFeatureClass, bool Messages = false)
        {
            ESRI.ArcGIS.Geoprocessor.Geoprocessor gp = new ESRI.ArcGIS.Geoprocessor.Geoprocessor();
            gp.OverwriteOutput = true;
            IGeoProcessorResult myresult = new GeoProcessorResultClass();
            object sev = null;

            // Create a variant array to hold the parameter values.
            IVariantArray parameters = new VarArrayClass();

            // Populate the variant array with parameter values.
            parameters.Add(InFeatureClass);
            parameters.Add(OutFeatureClass);

            // Execute the tool.
            try
            {
                myresult = (IGeoProcessorResult)gp.Execute("CopyFeatures_management", parameters, null);
                // Wait until the execution completes.
                while (myresult.Status == esriJobStatus.esriJobExecuting)
                    Thread.Sleep(1000);
                    // Wait for 1 second.
                if (Messages)
                {
                    MessageBox.Show("Process complete");
                }
                gp = null;
                return true;
            }
            catch (Exception ex)
            {
                if (Messages)
                {
                    MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    MessageBox.Show(gp.GetMessages(ref sev));
                }
                gp = null;
                return false;
            }
        }
        /// <summary>
        /// Where all of the work is done.  Override from TabBaseViewModel
        /// </summary>
        internal override void CreateMapElement()
        {
            if (!CanCreateElement || ArcMap.Document == null || ArcMap.Document.FocusMap == null || string.IsNullOrWhiteSpace(SelectedSurfaceName))
                return;

            //base.CreateMapElement();

            var surface = GetSurfaceFromMapByName(ArcMap.Document.FocusMap, SelectedSurfaceName);

            if (surface == null)
                return;

            using (ComReleaser oComReleaser = new ComReleaser())
            {

                // Create feature workspace
                IFeatureWorkspace workspace = CreateFeatureWorkspace("tempWorkspace");

                StartEditOperation((IWorkspace)workspace);

                // Create feature class
                IFeatureClass pointFc = CreateObserversFeatureClass(workspace, "Output" + RunCount.ToString());

                double finalObserverOffset = GetOffsetInZUnits(ArcMap.Document.FocusMap, ObserverOffset.Value, surface.ZFactor, OffsetUnitType);
                double finalSurfaceOffset = GetOffsetInZUnits(ArcMap.Document.FocusMap, SurfaceOffset, surface.ZFactor, OffsetUnitType);

                double conversionFactor = GetConversionFactor(ArcMap.Document.FocusMap.SpatialReference);
                double convertedMinDistance = MinDistance * conversionFactor;
                double convertedMaxDistance = MaxDistance * conversionFactor;
                double finalMinDistance = GetLinearDistance(ArcMap.Document.FocusMap, convertedMinDistance, OffsetUnitType);
                double finalMaxDistance = GetLinearDistance(ArcMap.Document.FocusMap, convertedMaxDistance, OffsetUnitType);

                double finalLeftHorizontalFOV = GetAngularDistance(ArcMap.Document.FocusMap, LeftHorizontalFOV, AngularUnitType);
                double finalRightHorizontalFOV = GetAngularDistance(ArcMap.Document.FocusMap, RightHorizontalFOV, AngularUnitType);
                double finalBottomVerticalFOV = GetAngularDistance(ArcMap.Document.FocusMap, BottomVerticalFOV, AngularUnitType);
                double finalTopVerticalFOV = GetAngularDistance(ArcMap.Document.FocusMap, TopVerticalFOV, AngularUnitType);

                // Out radius geometries
                List<IGeometry> radius2GeomList = new List<IGeometry>();
                List<IGeometry> radius1_2GeomList = new List<IGeometry>();
                List<IGeometry> donutGeomList = new List<IGeometry>();

                foreach (var observerPoint in ObserverAddInPoints)
                {
                    // Create buffer geometries for final Min/Max distance
                    ITopologicalOperator topologicalOperator = observerPoint.Point as ITopologicalOperator;
                    IGeometry geom = topologicalOperator.Buffer(finalMaxDistance);
                    radius2GeomList.Add(geom);
                    radius1_2GeomList.Add(geom);
                    if (finalMinDistance > 0)
                    {
                        IGeometry geom2 = topologicalOperator.Buffer(finalMinDistance);

                        ITopologicalOperator eraseTopo = geom as ITopologicalOperator;
                        IGeometry erasedGeom = eraseTopo.Difference(geom2);
                        donutGeomList.Add(erasedGeom);
                    }
                    else
                    {
                        radius1_2GeomList.Add(geom);
                    }

                    double z1 = surface.GetElevation(observerPoint.Point) + finalObserverOffset;

                    //create a new point feature
                    IFeature ipFeature = pointFc.CreateFeature();

                    // Set the field values for the feature
                    SetFieldValues(finalObserverOffset, finalSurfaceOffset, finalMinDistance, finalMaxDistance, finalLeftHorizontalFOV,
                        finalRightHorizontalFOV, finalBottomVerticalFOV, finalTopVerticalFOV, ipFeature);

                    //Create shape
                    IPoint point = new PointClass() { Z = z1, X = observerPoint.Point.X, Y = observerPoint.Point.Y, ZAware = true };
                    ipFeature.Shape = point;
                    ipFeature.Store();
                }

                IFeatureClassDescriptor fd = new FeatureClassDescriptorClass();
                fd.Create(pointFc, null, "OBJECTID");

                StopEditOperation((IWorkspace)workspace);

                try
                {
                    ILayer layer = GetLayerFromMapByName(ArcMap.Document.FocusMap, SelectedSurfaceName);
                    string layerPath = GetLayerPath(layer);

                IFeatureLayer ipFeatureLayer = new FeatureLayerClass();
                ipFeatureLayer.FeatureClass = pointFc;

                IDataset ipDataset = (IDataset)pointFc;
                string outputFcName = ipDataset.BrowseName + "_output";
                string strPath = ipDataset.Workspace.PathName + "\\" + ipDataset.BrowseName;
                string outPath = ipDataset.Workspace.PathName + "\\" + outputFcName;

                IVariantArray parameters = new VarArrayClass();
                    parameters.Add(layerPath);
                parameters.Add(strPath);
                parameters.Add(outPath);

                    esriLicenseStatus status = GetSpatialAnalystLicense();

                    IGeoProcessor2 gp = new GeoProcessorClass();

                    gp.AddOutputsToMap = false;

                    // Add a mask to buffer the output to selected distance
                    SetGPMask(workspace, radius2GeomList, gp, "radiusMask");

                    object oResult = gp.Execute("Visibility_sa", parameters, null);
                    IGeoProcessorResult ipResult = (IGeoProcessorResult)oResult;

                    ComReleaser.ReleaseCOMObject(gp);
                    gp = null;
                    GC.Collect();

                    // Add buffer geometries to the map
                    foreach (IGeometry geom in radius1_2GeomList)
                    {
                        var color = new RgbColorClass() { Blue = 255 } as IColor;
                        AddGraphicToMap(geom, color, true);
                    }

                    IRasterLayer outputRasterLayer = new RasterLayerClass();
                    outputRasterLayer.CreateFromFilePath(outPath);

                    string fcName = IntersectOutput(outputRasterLayer, ipDataset, workspace, donutGeomList);

                    IFeatureClass finalFc = workspace.OpenFeatureClass(fcName);

                    IFeatureLayer outputFeatureLayer = new FeatureLayerClass();
                    outputFeatureLayer.FeatureClass = finalFc;

                    //Add it to a map if the layer is valid.
                    if (outputFeatureLayer != null)
                    {
                        // set the renderer
                        IFeatureRenderer featRend = UnqueValueRenderer(workspace, finalFc);
                        IGeoFeatureLayer geoLayer = outputFeatureLayer as IGeoFeatureLayer;
                        geoLayer.Renderer = featRend;
                        geoLayer.Name = "VisibilityLayer_" + RunCount.ToString();

                        // Set the layer transparency
                        IDisplayFilterManager filterManager = (IDisplayFilterManager)outputFeatureLayer;
                        ITransparencyDisplayFilter filter = new TransparencyDisplayFilter();
             			            filter.Transparency = 80;
             			            filterManager.DisplayFilter = filter;

                        ESRI.ArcGIS.Carto.IMap map = ArcMap.Document.FocusMap;
                        map.AddLayer((ILayer)outputFeatureLayer);
                    }

                    RunCount += 1;
                }
                catch (Exception ex)
                {
                    string exception = ex.ToString();
                    System.Windows.MessageBox.Show(VisibilityLibrary.Properties.Resources.MsgTryAgain, VisibilityLibrary.Properties.Resources.MsgCalcCancelled);
                }

                //Reset(true);
            }
        }
        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());
                }
            }
        }
Beispiel #55
0
        private void OK_Click(object sender, EventArgs e)
        {
            // 2013-04-10 张航宇
            // 添加验证
            if (string.IsNullOrWhiteSpace(buttonEdit1.Text))
            {
                MessageBox.Show("请选择原DEM路径!");
                return;
            }
            if (string.IsNullOrWhiteSpace(buttonEdit2.Text))
            {
                MessageBox.Show("请选择山脊线生成路径!");
                return;
            }

            if (string.IsNullOrWhiteSpace(buttonEdit3.Text))
            {
                MessageBox.Show("请选择山谷线生成路径!");
                return;
            }

            //1-定义GeoProcessor对象
            this.gp = new Geoprocessor();
            object sev = null;
            //2-设置参数
            gp.OverwriteOutput = true;
            //3-设置工具箱所在的路径
            gp.AddToolbox(Application.StartupPath + @"\Convert\TerrainTool.tbx");
            //4-设置输入参数
            ESRI.ArcGIS.esriSystem.IVariantArray parameters = new VarArrayClass();
            parameters.Add(buttonEdit1.Text);
            parameters.Add(buttonEdit2.Text+"\\shanji");
            parameters.Add(buttonEdit3.Text+"\\shangu");
            parameters.Add(Convert.ToDouble(spinEdit1.Value));
            IGeoProcessorResult results = null;
            try
            {
                results = (IGeoProcessorResult)gp.Execute("Terrain", parameters, null);
                if (results == null)
                {
                    MessageBox.Show("生成失败!");
                }
                MessageBox.Show("生成成功!", "", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show("生成失败!");

                //throw;
            }
        }