public bool? CompressFileGeoDB(string FileGeodatabase) { System.Collections.Generic.IEnumerable<ESRI.ArcGIS.RuntimeInfo> runtimeInfo = null; ESRI.ArcGIS.esriSystem.IVariantArray geoprocessorVariantArray = null; ESRI.ArcGIS.Geoprocessing.GeoProcessor compressGeoprocessor = null; try { // Make sure the File Geodatabase exists before attempting to uncompress it. if (!System.IO.Directory.Exists(FileGeodatabase)) { // Let the user know that the File Geodatabase does not exist. if (ErrorMessage != null) { ErrorMessage("The File Geodatabase - " + FileGeodatabase.ToUpper() + " does not exist and thus was not compressed..."); } // Return FALSE to the calling routine to indicate that this process failed. return false; } // Let the user know what is happening. if (ProcessMessage != null) { ProcessMessage(" - Attempting to compress the File Geodatabase - " + FileGeodatabase.ToUpper() + "..."); } // Determine the Install Path for the ArcGIS Software. runtimeInfo = ESRI.ArcGIS.RuntimeManager.InstalledRuntimes; string arcToolboxPath = null; foreach (ESRI.ArcGIS.RuntimeInfo currentRuntimeItem in runtimeInfo) { // Retrieve the Install Path for the ArcGIS Desktop Runtime (ArcGIS Toolbox Items // are found in this path). if (currentRuntimeItem.Product == ESRI.ArcGIS.ProductCode.Desktop) { arcToolboxPath = currentRuntimeItem.Path; } } // If the ArcToolBox Directory Exists, add it to the Path. if (System.IO.Directory.Exists(System.IO.Path.Combine(arcToolboxPath, @"ArcToolbox"))) { arcToolboxPath = System.IO.Path.Combine(arcToolboxPath, @"ArcToolbox"); } // If the Toolboxes Directory Exists, add it to the Path. if (System.IO.Directory.Exists(System.IO.Path.Combine(arcToolboxPath, @"Toolboxes"))) { arcToolboxPath = System.IO.Path.Combine(arcToolboxPath, @"Toolboxes"); } // If the Toolbox File Exists, add it to the Toolbox path. if (System.IO.File.Exists(System.IO.Path.Combine(arcToolboxPath, "Data Management Tools.tbx"))) { // Add the File Name to the path. arcToolboxPath = System.IO.Path.Combine(arcToolboxPath, "Data Management Tools.tbx"); } // Build the Geoprocessor Variant Array that will pass the arguments to the Geoprocessing Tool. geoprocessorVariantArray = new ESRI.ArcGIS.esriSystem.VarArrayClass(); geoprocessorVariantArray.Add(FileGeodatabase); // Initialize the Geoprocessing Object that will be used to compress the Geodatabase. compressGeoprocessor = new ESRI.ArcGIS.Geoprocessing.GeoProcessor(); compressGeoprocessor.AddToolbox(arcToolboxPath); try { // Perform the export. compressGeoprocessor.Execute("CompressFileGeodatabaseData_management", geoprocessorVariantArray, null); // Write the messages from the Compress Tool to the log file. if (ProcessMessage != null) { int toolMessageCount = compressGeoprocessor.MessageCount; int currentToolMessageIndex = 0; ProcessMessage(""); ProcessMessage(" - Successfully Compressed the File Geodatabase..."); ProcessMessage(" - Compress File Geodatabase Operation Messages..."); while (currentToolMessageIndex < toolMessageCount) { // Write the current message to the log file. ProcessMessage(" + " + compressGeoprocessor.GetMessage(currentToolMessageIndex)); // Increment the Tool Message Index Counter. currentToolMessageIndex++; } } } catch (System.IO.IOException ioException) { // Determine the Line Number from which the exception was thrown. System.Diagnostics.StackTrace stackTrace = new System.Diagnostics.StackTrace(ioException, true); System.Diagnostics.StackFrame stackFrame = stackTrace.GetFrame(stackTrace.FrameCount - 1); int lineNumber = stackFrame.GetFileLineNumber(); // Let the User know that the Compress Operation Failed. if (ErrorMessage != null) { ErrorMessage("The Compress File Geodatabase Operation in the FeatureClassUtilities.CompressFileGeoDB() Method Failed with error message - " + ioException.Message + " (" + ioException.Source + " Line: " + lineNumber.ToString() + ")!"); if (ProcessMessage != null) { int toolMessageCount = compressGeoprocessor.MessageCount; int currentToolMessageIndex = 0; ProcessMessage("The information from the Geoprocessor is:"); while (currentToolMessageIndex < toolMessageCount) { // Write the current message to the log file. ProcessMessage(" + " + compressGeoprocessor.GetMessage(currentToolMessageIndex)); // Increment to Toold Message Index Counter. currentToolMessageIndex++; } } } // Return FALSE to the calling routine ito indicate that this process failed. return false; } catch (System.Runtime.InteropServices.COMException comException) { // Determine the Line Number from which the exception was thrown. System.Diagnostics.StackTrace stackTrace = new System.Diagnostics.StackTrace(comException, true); System.Diagnostics.StackFrame stackFrame = stackTrace.GetFrame(stackTrace.FrameCount - 1); int lineNumber = stackFrame.GetFileLineNumber(); // Let the User know that the Compress Operation Failed. if (ErrorMessage != null) { ErrorMessage("The Compress File Geodatabase Operation in the CompressFileGeoDB() Method Failed with error message - " + comException.Message + " (" + comException.ErrorCode + " Line: " + lineNumber.ToString() + ")!"); if (ProcessMessage != null) { int toolMessageCount = compressGeoprocessor.MessageCount; int currentToolMessageIndex = 0; ProcessMessage("The information from the Geoprocessor is:"); while (currentToolMessageIndex < toolMessageCount) { // Write the current message to the log file. ProcessMessage(" + " + compressGeoprocessor.GetMessage(currentToolMessageIndex)); // Increment to Toold Message Index Counter. currentToolMessageIndex++; } } } // Return FALSE to the calling routine ito indicate that this process failed. return false; } // If the process made it to here, it was successful so return TRUE to the calling // method. return true; } catch (System.Exception caught) { // Determine the Line Number from which the exception was thrown. System.Diagnostics.StackTrace stackTrace = new System.Diagnostics.StackTrace(caught, true); System.Diagnostics.StackFrame stackFrame = stackTrace.GetFrame(stackTrace.FrameCount - 1); int lineNumber = stackFrame.GetFileLineNumber(); // Let the User know that this process failed. if (ErrorMessage != null) { ErrorMessage("The MaintTools.FeatureClassUtilities.CompressFileGeoDB() Method failed with error message: " + caught.Message + " (Line: " + lineNumber.ToString() + ")!"); } // Return NULL to the calling routine to indicate that this process failed. return null; } finally { // If the Installed Runtimes List has been instantiated, close it. if (runtimeInfo != null) { runtimeInfo = null; } // If the Geoprocessor Parameters Array has been instantiated, close it. if (geoprocessorVariantArray != null) { geoprocessorVariantArray = null; } // If the Uncompress Geoprocessor Object has been instantiated, close it. if (compressGeoprocessor != null) { compressGeoprocessor = null; } } }
public static void AddZValuesToPoints(int SurveyID, int NewBatchID, int TempBatchID, IGeoDataset ThisRasterDS, string ThisDEMUnits, ref string ErrorMessage) { ESRI.ArcGIS.Geoprocessing.IGeoProcessorResult GeoResult = null; ESRI.ArcGIS.Geoprocessing.IGeoProcessor ThisGeoProcessor = null; ESRI.ArcGIS.esriSystem.IVariantArray GPParams; IFeatureClass TempFCHolderFC = null, PointFC = null; string CopyRandFilter = "", TempElePoints, TempFCHolder, InternalError = ""; NPSGlobal NPS; int GPLIndex = 0; NPS = NPSGlobal.Instance; TempFCHolder = "TempFCHolder"; TempElePoints = "TempElePoints"; ThisDEMUnits = ThisDEMUnits.ToLower(); if (string.IsNullOrEmpty(ErrorMessage)) PointFC = Util.GetFeatureClass(NPS.LYR_RANDOMPOINTS, ref ErrorMessage); if (string.IsNullOrEmpty(ErrorMessage) == false) { Util.SetProgressMessage("Deleting old temp files"); //delete the temporary table if it already exists Util.DeleteDataset(TempElePoints, esriDatasetType.esriDTFeatureClass, ref InternalError); Util.DeleteDataset(TempElePoints + "_Tbl", esriDatasetType.esriDTTable, ref InternalError); Util.DeleteDataset(TempFCHolder, esriDatasetType.esriDTFeatureClass, ref InternalError); Util.DeleteDataset(TempFCHolder + "_Tbl", esriDatasetType.esriDTTable, ref InternalError); } if (string.IsNullOrEmpty(ErrorMessage)) { try { Util.SetProgressMessage("Copying random points to temp FeatureClass"); ThisGeoProcessor = new ESRI.ArcGIS.Geoprocessing.GeoProcessor(); GPParams = new ESRI.ArcGIS.esriSystem.VarArrayClass(); GPParams.Add(NPS.Workspace.PathName); GPParams.Add(TempFCHolder); GPParams.Add("POINT"); GPParams.Add(System.IO.Path.Combine(NPS.Workspace.PathName, ((IDataset)PointFC).Name)); GeoResult = ThisGeoProcessor.Execute("CreateFeatureClass_management", GPParams, null); } catch (Exception ex) { ErrorMessage = string.Format("Geoprocessor error:\r\nTask:CreateFeatureClass_management\r\n" + "Params:{0},{1},{2},{3}\r\nException:{4}", NPS.Workspace.PathName, TempFCHolder, "POINT", System.IO.Path.Combine(NPS.Workspace.PathName, ((IDataset)PointFC).Name), ex.Message); } ThisGeoProcessor = null; Util.DeleteLayerFromMap(TempFCHolder); } if (string.IsNullOrEmpty(ErrorMessage)) { CopyRandFilter = " SurveyID=" + SurveyID; if (TempBatchID != -1) CopyRandFilter += " And BATCH_ID=" + TempBatchID; //get the temp feature class and copy only surveyid points to it TempFCHolderFC = Util.GetFeatureClass(TempFCHolder, ref ErrorMessage); if (string.IsNullOrEmpty(ErrorMessage)) Util.CopyFeatures(PointFC, CopyRandFilter, TempFCHolderFC, null, ref ErrorMessage); int TestCount = FeatureCount(TempFCHolderFC, ""); } if (string.IsNullOrEmpty(ErrorMessage)) { try { Util.SetProgressMessage("Extracting point elevation from DEM"); ThisGeoProcessor = new ESRI.ArcGIS.Geoprocessing.GeoProcessor(); GPParams = new ESRI.ArcGIS.esriSystem.VarArrayClass(); //GPParams.Add(TempFCHolderFC); //GPParams.Add(ThisRasterDS); //GPParams.Add(System.IO.Path.Combine(NPS.Workspace.PathName, TempElePoints)); //GeoResult = ThisGeoProcessor.Execute("ExtractValuesToPoints_sa", GPParams, null); GPParams.Add(ThisRasterDS); GPParams.Add(TempFCHolderFC); GPParams.Add("Spot"); // field name to add GPParams.Add(1); // Z-Factor GeoResult = ThisGeoProcessor.Execute("SurfaceSpot_3D", GPParams, null); } catch (Exception ex) { ErrorMessage = string.Format("Geoprocessor error:\r\nTask:SurfaceSpot_3D\r\n" + "Params:{0},{1},{2},{3}\r\nException:{4}", ((IDataset)ThisRasterDS).Name, ((IDataset)TempFCHolderFC).Name, "Spot", 1, ex.Message); } ThisGeoProcessor = null; //delete GPL[index] layers created from SurfaceSpot geoprocessor call while (GPLIndex < 10) { Util.DeleteLayerFromMap("GPL" + GPLIndex); GPLIndex++; } } if (string.IsNullOrEmpty(ErrorMessage)) { Util.SetProgressMessage("Importing updated random points"); //delete all points for that survey Util.DeleteFeatures(PointFC, CopyRandFilter, ref ErrorMessage); //replace the points of that survey with these points Util.CopyFeaturesForPoints(TempFCHolderFC, "", PointFC, NewBatchID, ThisDEMUnits, ref ErrorMessage); } Util.SetProgressMessage("Cleaning up temp files"); Util.DeleteDataset(TempElePoints, esriDatasetType.esriDTFeatureClass, ref InternalError); Util.DeleteDataset(TempElePoints + "_Tbl", esriDatasetType.esriDTTable, ref InternalError); Util.DeleteDataset(TempFCHolder, esriDatasetType.esriDTFeatureClass, ref InternalError); Util.DeleteDataset(TempFCHolder + "_Tbl", esriDatasetType.esriDTTable, ref InternalError); }
/// <summary> /// Updates any locators in the specified File Geodatabase that use the specified Feature Class as Primary Reference Table. Any Alternate Names Tables that exist for the /// specified Feature Class will be copied from the specified Enterprise Geodatabase (InputWorkspace) to the File Geodatabase. /// </summary> /// <param name="OutputFileGeodatabasePathName"> /// The Full Path to the Output File Geodatabase that contains the Locators that are to be rebuilt. /// </param> /// <param name="FeatureClassName"> /// The Name of the Feature Class that has been updated in the Output File Geodatabase. /// </param> /// <param name="InputWorkspace"> /// An ESRI ArcGIS Workspace Object that points to the Enterprise Geodatabase that is being used as the source for updating the Output File Geodatabase datasets. /// </param> /// <param name="InputWorkspaceDBSchemaOwnerName"> /// The Name of the Schema Owner in the source Enterprise Geodatabase. /// </param> /// <returns> /// TRUE if all locators in which the udpated feature class participates have been rebuilt successfully. /// FALSE if the locators were not successfully rebuilt. /// </returns> public bool UpdateFileGeodatabaseLocators(string OutputFileGeodatabasePathName, string FeatureClassName, ESRI.ArcGIS.Geodatabase.IWorkspace InputWorkspace, string InputWorkspaceDBSchemaOwnerName) { ESRI.ArcGIS.Geodatabase.IWorkspace geodatabaseWorkspace = null; ESRI.ArcGIS.Location.ILocatorManager locatorManager = null; ESRI.ArcGIS.Geodatabase.ILocatorWorkspace2 locatorWorkspace = null; ESRI.ArcGIS.Geodatabase.IEnumLocatorName locatorNamesEnum = null; System.Collections.Specialized.StringCollection copiedReferenceTables = null; ESRI.ArcGIS.Geodatabase.ILocatorName currentLocatorName = null; ESRI.ArcGIS.Geodatabase.ILocator currentLocator = null; ESRI.ArcGIS.Location.IReferenceDataTables locatorReferenceTables = null; ESRI.ArcGIS.Location.IEnumReferenceDataTable locatorReferenceTablesEnum = null; ESRI.ArcGIS.Location.IReferenceDataTable2 currentLocatorReferenceTable = null; ESRI.ArcGIS.Geodatabase.IFeatureWorkspace geodatabaseFeatureWorkspace = null; ESRI.ArcGIS.Geodatabase.ITable deleteTable = null; ESRI.ArcGIS.Geodatabase.IDataset deleteDataset = null; ESRI.ArcGIS.Geodatabase.IFeatureWorkspace inputFeatureWorkspace = null; ESRI.ArcGIS.Geodatabase.ITable inputAlternateNameTable = null; ESRI.ArcGIS.Geodatabase.IDataset inputTableDataset = null; ESRI.ArcGIS.Geodatabase.IWorkspaceFactory inputWorkspaceFactory = null; ESRI.ArcGIS.Geoprocessing.GeoProcessor geoProcessorObject = null; ESRI.ArcGIS.esriSystem.IVariantArray tableToTableParams = null; ESRI.ArcGIS.Geoprocessing.IGeoProcessorResult geoprocessorResult = null; ESRI.ArcGIS.Geoprocessing.GeoProcessor rebuildGeoprocessorObject = null; ESRI.ArcGIS.esriSystem.IVariantArray rebuildLocatorParams = null; ESRI.ArcGIS.Geoprocessing.IGeoProcessorResult rebuildGeoprocessorResult = null; try { // Let the user know what is happening. if (ProcessMessage != null) { ProcessMessage(" - Initializing the process to rebuild any locators and determining if the specified Feature Class is a reference dataset for any locators in the File Geodatabase..."); } // Open the Locator Workspace. geodatabaseWorkspace = EstablishFileGeodatabaseConnection(OutputFileGeodatabasePathName); // Make sure the Output File Geodatabase Workspace Connection was established successfully before moving on. if (geodatabaseWorkspace == null) { // Let the user know that the connection could not be established. if (ErrorMessage != null) { ErrorMessage("Failed to open the Output File Geodatabase Workspace - " + OutputFileGeodatabasePathName + ". Aborting the Locator Rebuild!"); } // Return FALSE to the calling method to indicate that this method failed. return false; } locatorManager = new ESRI.ArcGIS.Location.LocatorManagerClass(); locatorWorkspace = (ESRI.ArcGIS.Geodatabase.ILocatorWorkspace2)locatorManager.GetLocatorWorkspace(geodatabaseWorkspace); // Get the list of Address Locator Names from the File Geodatabase. locatorNamesEnum = locatorWorkspace.get_LocatorNames(ESRI.ArcGIS.Geodatabase.esriLocatorQuery.esriLocator, "Address"); // Create a List of Reference Tables that are copied by this process so that they will not be copied multiple times if it is used by multiple locators. copiedReferenceTables = new System.Collections.Specialized.StringCollection(); // Go through the list of associated locators and rebuild them. currentLocatorName = locatorNamesEnum.Next(); while (currentLocatorName != null) { // If there is a valid Locator Name, rebuild the locator. if (currentLocatorName.Name.Length > 1) { // Let the User know that the locator is being rebuilt. if (ProcessMessage != null) { ProcessMessage(" + Determining if the " + FeatureClassName + " Feature Class participates in the " + currentLocatorName.Name.ToString() + " Locator..."); } // Open the Current Locator. currentLocator = locatorWorkspace.GetLocator(currentLocatorName.Name); // If the Current Locator is a composite Locator, skip it. if (!(currentLocator is ESRI.ArcGIS.Location.ICompositeLocator)) { // Determine if the specified Feature Class is a reference Dataset for the locator. locatorReferenceTables = (ESRI.ArcGIS.Location.IReferenceDataTables)currentLocator; locatorReferenceTablesEnum = locatorReferenceTables.Tables; locatorReferenceTablesEnum.Reset(); // Retrieve the First Table from the Locator. currentLocatorReferenceTable = (ESRI.ArcGIS.Location.IReferenceDataTable2)locatorReferenceTablesEnum.Next(); // Default the Found the Locator Indicator to FALSE. bool foundIt = false; // If the Updated Feature Class is the Primary Table for this locator, the locator needs to be rebuilt so default the 'FoundIt' indicator to true. while (currentLocatorReferenceTable != null) { // Determine if the current table is the specified Feature Class Business Table. if (currentLocatorReferenceTable.DisplayName.ToUpper() == "PRIMARY TABLE") { ESRI.ArcGIS.Geodatabase.IDatasetName currentFeatureClassName = null; currentFeatureClassName = (ESRI.ArcGIS.Geodatabase.IDatasetName)currentLocatorReferenceTable.Name; if (currentFeatureClassName.Name.ToString().ToUpper() == FeatureClassName.ToUpper()) { // Set the found the locator indicator to TRUE. foundIt = true; } } // Retrieve the Next Table from the Locator. currentLocatorReferenceTable = (ESRI.ArcGIS.Location.IReferenceDataTable2)locatorReferenceTablesEnum.Next(); } // If the specified Feature Class does participate in the current Locator, rebuild the Locator. if (foundIt) { // Let the User know that the locator is being rebuilt. if (ProcessMessage != null) { ProcessMessage(" + Starting the rebuild of the " + currentLocatorName.Name.ToString() + " Locator..."); } // Reset the Locator Reference Tables enumerator. locatorReferenceTablesEnum.Reset(); // Retrieve the First Table from the Locator. currentLocatorReferenceTable = (ESRI.ArcGIS.Location.IReferenceDataTable2)locatorReferenceTablesEnum.Next(); // Go through the Locator Reference Tables and rebuild any Alternate Name Tables that are associated with the locator. while (currentLocatorReferenceTable != null) { if (currentLocatorReferenceTable.DisplayName.ToUpper() == "ALTERNATE NAME TABLE") { ESRI.ArcGIS.Geodatabase.IDatasetName currentTableName = null; currentTableName = (ESRI.ArcGIS.Geodatabase.IDatasetName)currentLocatorReferenceTable.Name; // Alternate Name Tables have the string "_ALT" inserted in the name before the "_PDX" so, remove the "_PDX" from the Feature Class Name so that it can be // found in the Alternate Table Name. string searchName = FeatureClassName; if (searchName.Substring(searchName.Length - 3).ToUpper() == "PDX") { searchName = searchName.Substring(0, searchName.Length - 4); } // If the current Alternate Name Table is associated with this locator, delete it and copy the most current version from the source Geodatabase. if (currentTableName.Name.ToString().ToUpper().IndexOf(searchName.ToUpper()) != -1) { // If the Table Name includes some prefix information (Database Name and Table Owner Name), drop it for attempting to find the table in the search Geodatabase. string tableSearchName = currentTableName.Name.ToString(); if (tableSearchName.ToUpper().IndexOf(searchName.ToUpper()) > 0) { // Drop the prefix from the Table Name. tableSearchName = tableSearchName.Substring(tableSearchName.IndexOf(searchName.ToUpper())); } // If the Table has not already been updated by this process, update it. if (!copiedReferenceTables.Contains(tableSearchName)) { // Let the user know which locator is being rebuilt. if (ProcessMessage != null) { ProcessMessage(" < Deleting the - " + tableSearchName + " Alternate Name Table for the " + currentLocatorName.Name + " locator..."); } geodatabaseFeatureWorkspace = (ESRI.ArcGIS.Geodatabase.IFeatureWorkspace)geodatabaseWorkspace; deleteTable = geodatabaseFeatureWorkspace.OpenTable(currentTableName.Name.ToString()); deleteDataset = (ESRI.ArcGIS.Geodatabase.IDataset)deleteTable; deleteDataset.Delete(); // Release the Delete Objects to remove locks on the reference table. if (deleteDataset != null) { System.Runtime.InteropServices.Marshal.ReleaseComObject(deleteDataset); } if (deleteTable != null) { System.Runtime.InteropServices.Marshal.ReleaseComObject(deleteTable); } // Attempt to open the Source Table in the Input Geodatabase. inputFeatureWorkspace = (ESRI.ArcGIS.Geodatabase.IFeatureWorkspace)InputWorkspace; inputAlternateNameTable = (ESRI.ArcGIS.Geodatabase.ITable)inputFeatureWorkspace.OpenTable(InputWorkspaceDBSchemaOwnerName + "." + tableSearchName); inputTableDataset = (ESRI.ArcGIS.Geodatabase.IDataset)inputAlternateNameTable; // If the Table was opened successfully, Attempt to Copy it to the File Geodatabase. string temporaryDirectory = null; if (inputAlternateNameTable != null) { // Determine in which directory the Temporary SDE Connection File should // be created. if (System.IO.Directory.Exists(@"D:\Temp")) { // Set the Temporary Directory to 'D:\TEMP\'. temporaryDirectory = @"D:\Temp\"; } else { // Check to see if there is a 'C:\TEMP' Directory. if (System.IO.Directory.Exists(@"C:\Temp")) { // Set the Temporary Directory to 'C:\Temp\' temporaryDirectory = @"C:\Temp\"; } else { // Set the Temporary Directory to 'C:\'. temporaryDirectory = @"C:\"; } } // Create a Connection File for the Input Enterprise Geodatabase Connection. inputWorkspaceFactory = InputWorkspace.WorkspaceFactory; inputWorkspaceFactory.Create(temporaryDirectory, "inputConnection.sde", InputWorkspace.ConnectionProperties, 0); string connectionFile = temporaryDirectory + "\\inputConnection.sde"; // Let the user know which locator is being rebuilt. if (ProcessMessage != null) { ProcessMessage(" < Copying the - " + tableSearchName + " Alternate Name Table for the " + currentLocatorName.Name + " locator from the Source Geodatabase..."); } // Establish a Table Copy Geoprocessing Object to Copy the Enterprise // Enterprise Geodatabase Alternate Name Table to the File Geodatabase. geoProcessorObject = new ESRI.ArcGIS.Geoprocessing.GeoProcessor(); tableToTableParams = new ESRI.ArcGIS.esriSystem.VarArray(); tableToTableParams.Add(connectionFile + @"\" + inputTableDataset.Name); tableToTableParams.Add(OutputFileGeodatabasePathName); tableToTableParams.Add(tableSearchName); // Copy the Enterprise Geodatabase Alternate Name table to the File // Geodatabase. geoprocessorResult = (ESRI.ArcGIS.Geoprocessing.IGeoProcessorResult)geoProcessorObject.Execute("TableToTable_conversion", tableToTableParams, null); // Delete the Connection File since it is no longer needed. if (System.IO.File.Exists(temporaryDirectory + "\\inputConnection.sde")) { // Delete the file. System.IO.File.Delete(temporaryDirectory + "\\inputConnection.sde"); } if (geoProcessorObject != null) { System.Runtime.InteropServices.Marshal.ReleaseComObject(geoProcessorObject); } if (tableToTableParams != null) { System.Runtime.InteropServices.Marshal.ReleaseComObject(tableToTableParams); } if (geoprocessorResult != null) { System.Runtime.InteropServices.Marshal.ReleaseComObject(geoprocessorResult); } // Add the current table to the list of Tables that have been copied. copiedReferenceTables.Add(tableSearchName); } } } } // Get the next Reference Table from the enumerator. currentLocatorReferenceTable = (ESRI.ArcGIS.Location.IReferenceDataTable2)locatorReferenceTablesEnum.Next(); } // Let the user know which locator is being rebuilt. if (ProcessMessage != null) { ProcessMessage(" < Rebuilding the - " + currentLocatorName.Name + " locator..."); } // Build the Parameter Set necessary to Rebuild the Locator. rebuildLocatorParams = new ESRI.ArcGIS.esriSystem.VarArray(); rebuildLocatorParams.Add(OutputFileGeodatabasePathName + "\\" + currentLocatorName.Name); System.Runtime.InteropServices.Marshal.ReleaseComObject(currentLocatorName); if (currentLocatorReferenceTable != null) { System.Runtime.InteropServices.Marshal.ReleaseComObject(currentLocatorReferenceTable); } if (currentLocator != null) { System.Runtime.InteropServices.Marshal.ReleaseComObject(currentLocator); } // Attempt to rebuild the Locator. rebuildGeoprocessorObject = new ESRI.ArcGIS.Geoprocessing.GeoProcessor(); rebuildGeoprocessorResult = (ESRI.ArcGIS.Geoprocessing.IGeoProcessorResult)rebuildGeoprocessorObject.Execute("RebuildAddressLocator_geocoding", rebuildLocatorParams, null); // Present the results of the process to the user. if (rebuildGeoprocessorResult.Status == ESRI.ArcGIS.esriSystem.esriJobStatus.esriJobSucceeded) { // Let the user know that the Locator was rebuilt successfully. if (ProcessMessage != null) { ProcessMessage(" + Successfully rebuilt the - " + currentLocatorName.Name + " locator..."); if (rebuildGeoprocessorObject.MessageCount > 0) { ProcessMessage(" + The messages from the process were -"); for (int i = 0; i <= rebuildGeoprocessorObject.MessageCount - 1; i++) { ProcessMessage(" - " + rebuildGeoprocessorObject.GetMessage(i)); } } } } else { // Let the user know that the Locator Failed to Rebuild. if (ProcessMessage != null) { ProcessMessage(""); ProcessMessage("FAILED to rebuild the - " + currentLocatorName.Name + " locator..."); if (rebuildGeoprocessorObject.MessageCount > 0) { ProcessMessage(" + The messages from the process were -"); for (int i = 0; i <= rebuildGeoprocessorObject.MessageCount - 1; i++) { ProcessMessage(" - " + rebuildGeoprocessorObject.GetMessage(i)); } } } // Return FALSE to the calling method to indicate that this process failed. return false; } } } else { // Retrieve the list of locators that exist in the Composite Locator. ESRI.ArcGIS.Location.ICompositeLocator currentCompositeLocator = (ESRI.ArcGIS.Location.ICompositeLocator)currentLocator; string[] locatorNames = currentCompositeLocator.LocatorNames as string[]; ESRI.ArcGIS.Geodatabase.ILocator[] locators = new ESRI.ArcGIS.Geodatabase.ILocator[locatorNames.Length]; int i = 0; foreach (string currentSubLocatorName in locatorNames) { locators[i] = currentCompositeLocator.get_Locator(currentSubLocatorName); i++; } // Determine if the Updated Feature Class participates in any of the locators in the Composite Locator. bool foundIt = false; foreach (ESRI.ArcGIS.Geodatabase.ILocator currentSubLocator in locators) { // If the Current Locator is a Composite Locator, ignore it. if (!(currentSubLocator is ESRI.ArcGIS.Location.ICompositeLocator)) { // Determine if the specified Feature Class is a reference Dataset for the locator. locatorReferenceTables = (ESRI.ArcGIS.Location.IReferenceDataTables)currentSubLocator; locatorReferenceTablesEnum = locatorReferenceTables.Tables; locatorReferenceTablesEnum.Reset(); // Retrieve the First Table from the Locator. currentLocatorReferenceTable = (ESRI.ArcGIS.Location.IReferenceDataTable2)locatorReferenceTablesEnum.Next(); // Go through the Primary Tables participating in the Locator and determine if the Updated Feature Class Table is one of them. while ((currentLocatorReferenceTable != null) && (!foundIt)) { // Determine if the current table is the specified Feature Class Business Table. if (currentLocatorReferenceTable.DisplayName.ToUpper() == "PRIMARY TABLE") { ESRI.ArcGIS.Geodatabase.IDatasetName currentFeatureClassName = null; currentFeatureClassName = (ESRI.ArcGIS.Geodatabase.IDatasetName)currentLocatorReferenceTable.Name; if (currentFeatureClassName.Name.ToString().ToUpper() == FeatureClassName.ToUpper()) { // Set the found the locator indicator to TRUE. foundIt = true; } } // Retrieve the Next Table from the Locator. currentLocatorReferenceTable = (ESRI.ArcGIS.Location.IReferenceDataTable2)locatorReferenceTablesEnum.Next(); } } } // If the Updated Feature Class is a member of the Composite Locator, rebuild it. if (foundIt) { // Let the user know which locator is being rebuilt. if (ProcessMessage != null) { ProcessMessage(" < Rebuilding the - " + currentLocatorName.Name + " locator..."); } // Build the Parameter Set necessary to Rebuild the Locator. rebuildLocatorParams = new ESRI.ArcGIS.esriSystem.VarArray(); rebuildLocatorParams.Add(OutputFileGeodatabasePathName + "\\" + currentLocatorName.Name); // Attempt to rebuild the Locator. rebuildGeoprocessorObject = new ESRI.ArcGIS.Geoprocessing.GeoProcessor(); rebuildGeoprocessorResult = (ESRI.ArcGIS.Geoprocessing.IGeoProcessorResult)rebuildGeoprocessorObject.Execute("RebuildAddressLocator_geocoding", rebuildLocatorParams, null); // Present the results of the process to the user. if (rebuildGeoprocessorResult.Status == ESRI.ArcGIS.esriSystem.esriJobStatus.esriJobSucceeded) { // Let the user know that the Locator was rebuilt successfully. if (ProcessMessage != null) { ProcessMessage(" + Successfully rebuilt the - " + currentLocatorName.Name + " locator..."); if (rebuildGeoprocessorObject.MessageCount > 0) { ProcessMessage(" + The messages from the process were -"); for (int y = 0; y <= rebuildGeoprocessorObject.MessageCount - 1; y++) { ProcessMessage(" - " + rebuildGeoprocessorObject.GetMessage(y)); } } } } else { // Let the user know that the Locator Failed to Rebuild. if (ProcessMessage != null) { ProcessMessage(""); ProcessMessage("FAILED to rebuild the - " + currentLocatorName.Name + " locator..."); if (rebuildGeoprocessorObject.MessageCount > 0) { ProcessMessage(" + The messages from the process were -"); for (int y = 0; y <= rebuildGeoprocessorObject.MessageCount - 1; y++) { ProcessMessage(" - " + rebuildGeoprocessorObject.GetMessage(y)); } } } // Return FALSE to the calling method to indicate that this process failed. return false; } } } } // Retrieve the next Locator Name Object from the Locator Names Enumerator. currentLocatorName = locatorNamesEnum.Next(); } // If the process made it to here, it was successful so return TRUE to the calling routine. return true; } catch (System.Runtime.InteropServices.COMException comCaught) { // Determine the Line Number from which the exception was thrown. System.Diagnostics.StackTrace stackTrace = new System.Diagnostics.StackTrace(comCaught, true); System.Diagnostics.StackFrame stackFrame = stackTrace.GetFrame(stackTrace.FrameCount - 1); int lineNumber = stackFrame.GetFileLineNumber(); // Let the User know that this process failed. if (ErrorMessage != null) { ErrorMessage("The FeatureClassUtilities.UpdateFileGeodatabaseLocators() Method failed with error message: " + comCaught.Message + "(" + comCaught.ErrorCode + " Line: " + lineNumber.ToString() + ")!"); } // Return FALSE to the calling routine to indicate that this process failed. return false; } catch (System.Exception caught) { // Determine the Line Number from which the exception was thrown. System.Diagnostics.StackTrace stackTrace = new System.Diagnostics.StackTrace(caught, true); System.Diagnostics.StackFrame stackFrame = stackTrace.GetFrame(stackTrace.FrameCount - 1); int lineNumber = stackFrame.GetFileLineNumber(); // Let the User know that this process failed. if (ErrorMessage != null) { ErrorMessage("The FeatureClassUtilities.UpdateFileGeodatabaseLocators() Method failed with error message: " + caught.Message + " (Line: " + lineNumber.ToString() + ")!"); } // Return FALSE to the calling routine to indicate that this process failed. return false; } finally { // If the Geoprocessor Result Object was instantiated, close it. if (geoprocessorResult != null) { System.Runtime.InteropServices.Marshal.ReleaseComObject(geoprocessorResult); } // If the Table to Table Variant Array was instantiated, close it. if (tableToTableParams != null) { System.Runtime.InteropServices.Marshal.ReleaseComObject(tableToTableParams); } // If the Geoprocessor Object was instantiated, close it. if (geoProcessorObject != null) { System.Runtime.InteropServices.Marshal.ReleaseComObject(geoProcessorObject); } // If the InputWorkspace Factory Object was instantiated, close it. if (inputWorkspaceFactory != null) { System.Runtime.InteropServices.Marshal.ReleaseComObject(inputWorkspaceFactory); } // If the Input Table Dataset Object was instantiated, close it. if (inputTableDataset != null) { System.Runtime.InteropServices.Marshal.ReleaseComObject(inputTableDataset); } // If the Input Alternate Name Table Object was instantiated, close it. if (inputAlternateNameTable != null) { System.Runtime.InteropServices.Marshal.ReleaseComObject(inputAlternateNameTable); } // If the Input Feature Workspace Object was instantiated, close it. if (inputFeatureWorkspace != null) { System.Runtime.InteropServices.Marshal.ReleaseComObject(inputFeatureWorkspace); } // If the Delete Dataset Object was instantiated, close it. if (deleteDataset != null) { System.Runtime.InteropServices.Marshal.ReleaseComObject(deleteDataset); } // If the Delete Table Object was instantiated, close it. if (deleteTable != null) { System.Runtime.InteropServices.Marshal.ReleaseComObject(deleteTable); } // If the Geodatabase Feature Workspace Object was instantiated, close it. if (geodatabaseFeatureWorkspace != null) { System.Runtime.InteropServices.Marshal.ReleaseComObject(geodatabaseFeatureWorkspace); } // If the Current Locator Reference Table Object was instantiated, close it. if (currentLocatorReferenceTable != null) { System.Runtime.InteropServices.Marshal.ReleaseComObject(currentLocatorReferenceTable); } // If the Locator Reference Tables Enumerator was instantiated, close it. if (locatorReferenceTablesEnum != null) { System.Runtime.InteropServices.Marshal.ReleaseComObject(locatorReferenceTablesEnum); } // If the Locator Reference Tables Object was instantiated, close it. if (locatorReferenceTables != null) { System.Runtime.InteropServices.Marshal.ReleaseComObject(locatorReferenceTables); } // If the Current Locator Object was instantiated, close it. if (currentLocator != null) { System.Runtime.InteropServices.Marshal.ReleaseComObject(currentLocator); } // If the Current Locator Name Object was instantiated, close it. if (currentLocatorName != null) { System.Runtime.InteropServices.Marshal.ReleaseComObject(currentLocatorName); } // If the Locatore Names Enumerator Object was instantiated, close it. if (locatorNamesEnum != null) { System.Runtime.InteropServices.Marshal.ReleaseComObject(locatorNamesEnum); } // If the Locator Workspace Object was instantiated, close it. if (locatorWorkspace != null) { System.Runtime.InteropServices.Marshal.ReleaseComObject(locatorWorkspace); } // If the Locator Manager Object was instantiated, close it. if (locatorManager != null) { System.Runtime.InteropServices.Marshal.ReleaseComObject(locatorManager); } // If the Geodatabase Workspace Object was instantiated, close it. if (geodatabaseWorkspace != null) { System.Runtime.InteropServices.Marshal.ReleaseComObject(geodatabaseWorkspace); } } }
/// <summary> /// create a new feature class with buffer polygons of the input feature class /// </summary> public static IFeatureClass GP_Union_analysis(IFeatureClass FirstFC, IFeatureClass SecondFC, string OutFCPathAndName, ref string ErrorMessage) { ESRI.ArcGIS.esriSystem.IVariantArray GPParams; ESRI.ArcGIS.Geoprocessing.IGeoProcessor ThisGeoProcessor = null; ESRI.ArcGIS.Geoprocessing.IGeoProcessorResult GeoResult = null; IFeatureClass ResultsFC = null; NPSGlobal NPS; string FCName, FCList; NPS = NPSGlobal.Instance; try { ThisGeoProcessor = new ESRI.ArcGIS.Geoprocessing.GeoProcessor(); GPParams = new ESRI.ArcGIS.esriSystem.VarArrayClass(); FCList = ((IDataset)FirstFC).FullName + ";" + ((IDataset)SecondFC).FullName; FCList = System.IO.Path.Combine(((IDataset)FirstFC).Workspace.PathName, ((IDataset)FirstFC).Name) + ";" + System.IO.Path.Combine(((IDataset)FirstFC).Workspace.PathName, ((IDataset)SecondFC).Name); GPParams.Add(FCList); GPParams.Add(OutFCPathAndName); GPParams.Add("ALL"); GeoResult = ThisGeoProcessor.Execute("Union_analysis", GPParams, null); FCName = OutFCPathAndName.Substring(OutFCPathAndName.LastIndexOf("\\") + 1); ResultsFC = Util.GetFeatureClass(FCName, ref ErrorMessage); Util.DeleteLayerFromMap(FCName); } catch (Exception ex) { ErrorMessage = string.Format("Geoprocessor error:\r\nTask:Union_analysis\r\n" + "Params:{0},{1},{2},{3}\r\nException:{4}", ((IDataset)FirstFC).Name, ((IDataset)SecondFC).Name, OutFCPathAndName, "ALL", ex.Message); ThisGeoProcessor = null; return null; } ThisGeoProcessor = null; return ResultsFC; }
public static string RunSystemChecks() { string DEMFilePath, ErrorMessage = "", MXDPath, ArcGISVersion, ScratchWSPath = "", CurrentWSPath = "", GPError = ""; StringBuilder CheckResults = new StringBuilder(); Microsoft.Win32.RegistryKey RegKey; ESRI.ArcGIS.Geoprocessing.IGeoProcessor ThisGeoProcessor = null; List<string> WorkspacePaths; IGeoDataset GeoDS; IDataset ThisDS; NPSGlobal NPS; bool IsOK; NPS = NPSGlobal.Instance; //ArcMap version and service packs //==================== try { CheckResults.Append("ArcGIS Version:"); CheckResults.Append("\r\n"); RegKey = Microsoft.Win32.Registry.LocalMachine.OpenSubKey( @"SOFTWARE\ESRI\ArcInfo\Desktop\8.0"); ArcGISVersion = RegKey.GetValue("RealVersion", "") as string; } catch { ArcGISVersion = "!!!Could not read Realersion info!!!"; } CheckResults.Append(ArcGISVersion); CheckResults.Append("\r\n\r\n"); try { CheckResults.Append("ArcGIS Build:"); CheckResults.Append("\r\n"); RegKey = Microsoft.Win32.Registry.LocalMachine.OpenSubKey( @"SOFTWARE\ESRI\ArcInfo\Desktop\8.0"); ArcGISVersion = RegKey.GetValue("BuildNumber", "") as string; } catch { ArcGISVersion = "!!!Could not read Build info!!!"; } CheckResults.Append(ArcGISVersion); CheckResults.Append("\r\n\r\n"); //dem file path check //==================== IsOK = true; DEMFilePath = NPS.MainTransectForm.txtDemFileLocation.Text; CheckResults.Append("DEM File Path:"); CheckResults.Append("\r\n"); CheckResults.Append(DEMFilePath); CheckResults.Append("\r\n"); if (DEMFilePath.Contains(" ")) { IsOK = false; CheckResults.Append("!!!Spaces are not allowed in the path to the DEM file!!!"); } if (string.IsNullOrEmpty(DEMFilePath)) { IsOK = false; CheckResults.Append("No DEM file set"); } if (IsOK) CheckResults.Append("OK"); CheckResults.Append("\r\n\r\n"); //DEM file projection check //==================== CheckResults.Append("DEM file projection:"); CheckResults.Append("\r\n"); GeoDS = Util.OpenRasterDataset(DEMFilePath, ref ErrorMessage) as IGeoDataset; if (string.IsNullOrEmpty(ErrorMessage) == false || GeoDS == null) CheckResults.Append("!!!Could not load DEM file to determine projection!!!"); else CheckResults.Append(GeoDS.SpatialReference.Name); ErrorMessage = ""; CheckResults.Append("\r\n\r\n"); //MXD projection check //==================== CheckResults.Append("MXD projection:"); CheckResults.Append("\r\n"); CheckResults.Append(NPS.Map.SpatialReference.Name); CheckResults.Append("\r\n\r\n"); //Main FCs path check //==================== CheckResults.Append("Main FeatureClasses paths:"); CheckResults.Append("\r\n"); CheckResults.Append(NPS.LYR_SURVEY_BOUNDARY + ": "); ThisDS = Util.GetFeatureClass(NPS.LYR_SURVEY_BOUNDARY, ref ErrorMessage) as IDataset; if (string.IsNullOrEmpty(ErrorMessage) == false || ThisDS == null) CheckResults.Append("!!!Could not find FeatureClass!!!"); else CheckResults.Append(System.IO.Path.Combine(ThisDS.Workspace.PathName, ThisDS.Name)); ErrorMessage = ""; CheckResults.Append("\r\n"); //========== CheckResults.Append(NPS.LYR_EXCLUDED_AREAS + ": "); ThisDS = Util.GetFeatureClass(NPS.LYR_EXCLUDED_AREAS, ref ErrorMessage) as IDataset; if (string.IsNullOrEmpty(ErrorMessage) == false || ThisDS == null) CheckResults.Append("!!!Could not find FeatureClass!!!"); else CheckResults.Append(System.IO.Path.Combine(ThisDS.Workspace.PathName, ThisDS.Name)); ErrorMessage = ""; CheckResults.Append("\r\n"); //========== CheckResults.Append(NPS.LYR_RANDOMPOINTS + ": "); ThisDS = Util.GetFeatureClass(NPS.LYR_RANDOMPOINTS, ref ErrorMessage) as IDataset; if (string.IsNullOrEmpty(ErrorMessage) == false || ThisDS == null) CheckResults.Append("!!!Could not find FeatureClass!!!"); else CheckResults.Append(System.IO.Path.Combine(ThisDS.Workspace.PathName, ThisDS.Name)); ErrorMessage = ""; CheckResults.Append("\r\n"); //========== CheckResults.Append(NPS.LYR_GENERATED_TRANSECTS + ": "); ThisDS = Util.GetFeatureClass(NPS.LYR_GENERATED_TRANSECTS, ref ErrorMessage) as IDataset; if (string.IsNullOrEmpty(ErrorMessage) == false || ThisDS == null) CheckResults.Append("!!!Could not find FeatureClass!!!"); else CheckResults.Append(System.IO.Path.Combine(ThisDS.Workspace.PathName, ThisDS.Name)); ErrorMessage = ""; CheckResults.Append("\r\n\r\n"); //Workspace Paths //=================== CheckResults.Append("Workspaces active in MXD:"); CheckResults.Append("\r\n"); WorkspacePaths = Util.GetUniqueWorkspacesInMXD(); if (WorkspacePaths.Count > 0) { for (int Index = 0; Index < WorkspacePaths.Count; Index++) { CheckResults.Append(WorkspacePaths[Index]); if (Index != WorkspacePaths.Count - 1) CheckResults.Append("\r\n"); } } CheckResults.Append("\r\n\r\n"); try { ThisGeoProcessor = new ESRI.ArcGIS.Geoprocessing.GeoProcessor(); } catch (Exception ex) { GPError = ex.Message; ThisGeoProcessor = null; } //Scratch workspace path check //==================== CheckResults.Append("Scratch Workspace Path:"); CheckResults.Append("\r\n"); if (ThisGeoProcessor != null) { ScratchWSPath = ThisGeoProcessor.GetEnvironmentValue("scratchWorkspace") as string; if (ScratchWSPath == null) { ScratchWSPath = "NULL"; CheckResults.Append(ScratchWSPath); } else { CheckResults.Append(ScratchWSPath); if (ScratchWSPath.Contains(" ")) CheckResults.Append("!!!Spaces are not allowed in the scratch workspace path!!!"); else CheckResults.Append("OK"); } } else { CheckResults.Append("Could not load geoprocessor. " + GPError); } CheckResults.Append("\r\n\r\n"); //Current workspace path check //==================== CheckResults.Append("Current Workspace Path:"); CheckResults.Append("\r\n"); if (ThisGeoProcessor != null) { CurrentWSPath = ThisGeoProcessor.GetEnvironmentValue("workspace") as string; if (CurrentWSPath == null) { CurrentWSPath = "NULL"; CheckResults.Append(CurrentWSPath); } else { CheckResults.Append(CurrentWSPath); if (CurrentWSPath.Contains(" ")) CheckResults.Append("!!!Spaces are not allowed in the current workspace path!!!"); else CheckResults.Append("OK"); } } else { CheckResults.Append("Could not load geoprocessor. " + GPError); } CheckResults.Append("\r\n\r\n"); ThisGeoProcessor = null; //Read/Write scratch workspace path check //==================== if (string.IsNullOrEmpty(ScratchWSPath) == false) { if (ScratchWSPath != "NULL") { CheckResults.Append("Scratch Workspace Path Security:"); CheckResults.Append("\r\n"); if (Util.CheckPathPrivelages(ScratchWSPath, ref ErrorMessage) == false) CheckResults.Append("!!!Failed. " + ErrorMessage + "!!!"); else CheckResults.Append("OK"); CheckResults.Append("\r\n\r\n"); } } //Read/Write current workspace path check //==================== if (string.IsNullOrEmpty(CurrentWSPath) == false) { if (CurrentWSPath != "NULL") { CheckResults.Append("Current Workspace Path Security:"); CheckResults.Append("\r\n"); if (Util.CheckPathPrivelages(CurrentWSPath, ref ErrorMessage) == false) CheckResults.Append("!!!Failed. " + ErrorMessage + "!!!"); else CheckResults.Append("OK"); CheckResults.Append("\r\n\r\n"); } } //path to dll //==================== CheckResults.Append("Path to DLL:"); CheckResults.Append("\r\n"); CheckResults.Append(NPS.DLLPath); CheckResults.Append("\r\n\r\n"); //path to database //==================== IsOK = true; CheckResults.Append("Path to Database:"); CheckResults.Append("\r\n"); CheckResults.Append(NPS.DatabasePath); CheckResults.Append("\r\n"); if (NPS.DatabasePath.Contains(" ")) { IsOK = false; CheckResults.Append("!!!Spaces are not allowed in the path to the NPS.gdb file!!!"); } if (IsOK) CheckResults.Append("OK"); CheckResults.Append("\r\n\r\n"); //path to mxd //==================== IsOK = true; CheckResults.Append("Path to MXD:"); CheckResults.Append("\r\n"); MXDPath = NPS.Application.Templates.get_Item(NPS.Application.Templates.Count - 1); CheckResults.Append(MXDPath); CheckResults.Append("\r\n"); if (MXDPath.Contains(" ")) { IsOK = false; CheckResults.Append("!!!Spaces are not allowed in the path to the MXD file!!!"); } if (IsOK) CheckResults.Append("OK"); return CheckResults.ToString(); }
/// <summary> /// clips one feature class by another and returns the resulting feature class. the resulting featureclass /// is a temp feature class and will need to be deleted after it's features have been processed /// </summary> public static IFeatureClass GP_Clip_analysis(string TempClipFCName, IFeatureClass InputFC, IFeatureClass ClipFC, ref string ErrorMessage) { ESRI.ArcGIS.esriSystem.IVariantArray GPParams; ESRI.ArcGIS.Geoprocessing.IGeoProcessor ThisGeoProcessor = null; ESRI.ArcGIS.Geoprocessing.IGeoProcessorResult GeoResult = null; IFeatureClass TempClipFC = null; NPSGlobal NPS; NPS = NPSGlobal.Instance; try { ThisGeoProcessor = new ESRI.ArcGIS.Geoprocessing.GeoProcessor(); GPParams = new ESRI.ArcGIS.esriSystem.VarArrayClass(); GPParams.Add(InputFC); GPParams.Add(ClipFC); GPParams.Add(System.IO.Path.Combine(NPS.DatabasePath, TempClipFCName)); GeoResult = ThisGeoProcessor.Execute("Clip_analysis", GPParams, null); Util.DeleteLayerFromMap(TempClipFCName); TempClipFC = Util.GetFeatureClass(TempClipFCName, ref ErrorMessage); } catch (Exception ex) { ErrorMessage = string.Format("Geoprocessor error:\r\nTask:Clip_analysis\r\n" + "Params:{0},{1},{2}\r\nException:{3}", ((IDataset)InputFC).Name, ((IDataset)ClipFC).Name, System.IO.Path.Combine(NPS.DatabasePath, TempClipFCName), ex.Message); ThisGeoProcessor = null; return null; } ThisGeoProcessor = null; return TempClipFC; }
/// <summary> /// export a featureclass as a shapefile /// </summary> public static void GP_FeatureclassToShapefile_conversion(IFeatureClass ThisFC, string ShapeFileFolderPath, string WhereClause, ref string ErrorMessage) { ESRI.ArcGIS.esriSystem.IVariantArray GPParams; ESRI.ArcGIS.Geoprocessing.IGeoProcessor ThisGeoProcessor = null; ESRI.ArcGIS.Geoprocessing.IGeoProcessorResult GeoResult = null; IFeatureLayer TempLayer = null; NPSGlobal NPS; NPS = NPSGlobal.Instance; try { ThisGeoProcessor = new ESRI.ArcGIS.Geoprocessing.GeoProcessor(); GPParams = new ESRI.ArcGIS.esriSystem.VarArrayClass(); TempLayer = new FeatureLayerClass(); TempLayer.FeatureClass = ThisFC; ((ITableDefinition)TempLayer).DefinitionExpression = WhereClause; TempLayer.Name = ((IDataset)ThisFC).Name; GPParams.Add(TempLayer); GPParams.Add(ShapeFileFolderPath); ThisGeoProcessor.OverwriteOutput = true; GeoResult = ThisGeoProcessor.Execute("FeatureclassToShapefile_conversion", GPParams, null); } catch (Exception ex) { ErrorMessage = string.Format("Geoprocessor error:\r\nTask:Clip_analysis\r\n" + "Params:{0},{1}\r\nException:{2}", ((IDataset)ThisFC).Name, ShapeFileFolderPath, ex.Message); } ThisGeoProcessor = null; }
/// <summary> /// create a new feature class with buffer polygons of the input feature class /// </summary> public static IFeatureClass GP_Buffer_analysis(IFeatureClass FCToBuffer, string OutFCPathAndName, double BufferDistance, string BufferSide, ref string ErrorMessage) { ESRI.ArcGIS.esriSystem.IVariantArray GPParams; ESRI.ArcGIS.Geoprocessing.IGeoProcessor ThisGeoProcessor = null; ESRI.ArcGIS.Geoprocessing.IGeoProcessorResult GeoResult = null; IFeatureClass ResultsFC = null; NPSGlobal NPS; string FCName; NPS = NPSGlobal.Instance; try { ThisGeoProcessor = new ESRI.ArcGIS.Geoprocessing.GeoProcessor(); GPParams = new ESRI.ArcGIS.esriSystem.VarArrayClass(); GPParams.Add(FCToBuffer); GPParams.Add(OutFCPathAndName); GPParams.Add(BufferDistance); GPParams.Add(BufferSide.ToUpper()); GPParams.Add("FLAT"); GPParams.Add("NONE"); GeoResult = ThisGeoProcessor.Execute("Buffer_analysis", GPParams, null); FCName = OutFCPathAndName.Substring(OutFCPathAndName.LastIndexOf("\\") + 1); ResultsFC = Util.GetFeatureClass(FCName, ref ErrorMessage); Util.DeleteLayerFromMap(FCName); } catch (Exception ex) { ErrorMessage = string.Format("Geoprocessor error:\r\nTask:Buffer_analysis\r\n" + "Params:{0},{1},{2},{3},{4}\r\nException:{5}", ((IDataset)FCToBuffer).Name, OutFCPathAndName, BufferDistance, BufferSide, "NONE", ex.Message); ThisGeoProcessor = null; return null; } ThisGeoProcessor = null; return ResultsFC; }
/// <summary> /// generate flatarea poylgons for the specified survey using the specified raster /// </summary> public static void GenerateFlatAreaPolygons(int SurveyID, double MinSlope, double MaxSlope, IGeoDataset ClippedRasterDS, ref string ErrorMessage) { ESRI.ArcGIS.Geoprocessing.IGeoProcessorResult GeoResult = null; ESRI.ArcGIS.Geoprocessing.IGeoProcessor ThisGeoProcessor = null; ESRI.ArcGIS.GeoAnalyst.IRasterDescriptor ThisRasterDescriptor; ESRI.ArcGIS.GeoAnalyst.IConversionOp ThisConversionOp; IGeoDataset FloatRasterDS = null, IntRasterDS = null; ESRI.ArcGIS.esriSystem.IVariantArray GPParams; ESRI.ArcGIS.GeoAnalyst.ISurfaceOp ThisSurfaceOp; ESRI.ArcGIS.SpatialAnalyst.IMathOp ThisMathOp; IFeatureClass TempFlatAreasPolyFC = null, TempAggregateFC = null, TempAggregateClipFC = null, BoundaryFC = null, FlatAreasFC = null; IQueryFilter ThisQueryFilter; IFeatureCursor FlatAreasCursor, TempAggregateClipCursor; IFeatureBuffer FlatAreasFBuffer; IFeature TempAggregateClipFeature; string TempFlatAreasPolyFCName, TempAggregateFCName, InternalErrors = "", TempClipFCName; object zFactor; NPSGlobal NPS; int SurveyIDIndex; TempClipFCName = "NPS_TEMP_ClippedFC"; TempAggregateFCName = "NPS_TEMP_FlatAreasAggrFC"; TempFlatAreasPolyFCName = "NPS_TEMP_FlatAreasFC"; NPS = NPSGlobal.Instance; zFactor = 1; BoundaryFC = Util.GetFeatureClass(NPS.LYR_SURVEY_BOUNDARY, ref ErrorMessage); if (string.IsNullOrEmpty(ErrorMessage) == false) return; FlatAreasFC = Util.GetFeatureClass(NPS.LYR_FLAT_AREAS, ref ErrorMessage); if (string.IsNullOrEmpty(ErrorMessage) == false) return; SurveyIDIndex = FlatAreasFC.FindField("SurveyID"); if (SurveyIDIndex == -1) { ErrorMessage = "Could not find a SurveyID field on the " + ((IDataset)FlatAreasFC).Name + " FeatureClass."; return; } Util.SetProgressMessage("Deleting old temp files"); Util.DeleteDataset(TempFlatAreasPolyFCName, esriDatasetType.esriDTFeatureClass, ref InternalErrors); Util.DeleteDataset(TempAggregateFCName, esriDatasetType.esriDTFeatureClass, ref InternalErrors); Util.DeleteDataset(TempClipFCName, esriDatasetType.esriDTFeatureClass, ref InternalErrors); Util.DeleteDataset(TempAggregateFCName + "_Tbl", esriDatasetType.esriDTTable, ref InternalErrors); Util.DeleteDataset(TempClipFCName + "_Tbl", esriDatasetType.esriDTTable, ref InternalErrors); ThisSurfaceOp = new ESRI.ArcGIS.GeoAnalyst.RasterSurfaceOpClass(); try { Util.SetProgressMessage("Computing slope values from DEM"); FloatRasterDS = ThisSurfaceOp.Slope(ClippedRasterDS, ESRI.ArcGIS.GeoAnalyst.esriGeoAnalysisSlopeEnum.esriGeoAnalysisSlopeDegrees, ref zFactor); } catch (Exception ex) { ErrorMessage = "Error occured while converting DEM evelation values to float slope values. " + ex.Message; return; } try { Util.SetProgressMessage("Converting DEM values to integers"); ThisMathOp = new ESRI.ArcGIS.SpatialAnalyst.RasterMathOpsClass(); IntRasterDS = ThisMathOp.Int(FloatRasterDS); } catch (Exception ex) { ErrorMessage = "Error occured while converting DEM float slope values to slope integer values. " + ex.Message; return; } try { Util.SetProgressMessage("Building flat area polygons from DEM"); ThisQueryFilter = new QueryFilterClass(); ThisQueryFilter.WhereClause = " Value >= " + MinSlope + " AND Value <= " + MaxSlope; ThisRasterDescriptor = new ESRI.ArcGIS.GeoAnalyst.RasterDescriptorClass(); ThisRasterDescriptor.Create(IntRasterDS as IRaster, ThisQueryFilter, "Value"); ThisConversionOp = new ESRI.ArcGIS.GeoAnalyst.RasterConversionOpClass(); TempFlatAreasPolyFC = ThisConversionOp.RasterDataToPolygonFeatureData(ThisRasterDescriptor as IGeoDataset, NPS.Workspace, TempFlatAreasPolyFCName, true) as IFeatureClass; } catch (Exception ex) { ErrorMessage = "Error occured while generating a FeatureClass of flat " + "areas from the default DEM file. " + ex.Message; return; } try { Util.SetProgressMessage("Aggregating flat area polygons"); ThisGeoProcessor = new ESRI.ArcGIS.Geoprocessing.GeoProcessor(); GPParams = new ESRI.ArcGIS.esriSystem.VarArrayClass(); GPParams.Add(System.IO.Path.Combine(NPS.DatabasePath, TempFlatAreasPolyFCName)); GPParams.Add(System.IO.Path.Combine(NPS.DatabasePath, TempAggregateFCName)); GPParams.Add("1 Meters"); GeoResult = ThisGeoProcessor.Execute("AggregatePolygons_management", GPParams, null); } catch (Exception ex) { ErrorMessage = string.Format("Geoprocessor error:\r\nTask:AggregatePolygons_management\r\n" + "Params:{0},{1},{2}\r\nException:{3}", System.IO.Path.Combine(NPS.DatabasePath, TempFlatAreasPolyFCName), System.IO.Path.Combine(NPS.DatabasePath, TempAggregateFCName), "1 Meters", ex.Message); ThisGeoProcessor = null; return; } ThisGeoProcessor = null; Util.DeleteLayerFromMap(TempAggregateFCName); TempAggregateFC = Util.GetFeatureClass(TempAggregateFCName, ref ErrorMessage); if (string.IsNullOrEmpty(ErrorMessage) == false) { ErrorMessage = "Could not find temporary FeatureClass " + TempAggregateFCName + ". " + ErrorMessage; return; } Util.SetProgressMessage("Validating flat area polygons"); TempAggregateClipFC = Util.GP_Clip_analysis(TempClipFCName, TempAggregateFC, BoundaryFC, ref ErrorMessage); if (string.IsNullOrEmpty(ErrorMessage) == false) return; FlatAreasFBuffer = FlatAreasFC.CreateFeatureBuffer(); FlatAreasCursor = FlatAreasFC.Insert(true); ThisQueryFilter = null; ThisQueryFilter = new QueryFilterClass(); ThisQueryFilter.WhereClause = "SHAPE_AREA > 25000"; TempAggregateClipCursor = TempAggregateClipFC.Search(ThisQueryFilter, false); Util.SetProgressMessage("Importing flat area polygons to Survey"); while ((TempAggregateClipFeature = TempAggregateClipCursor.NextFeature()) != null) { if (TempAggregateClipFeature.Shape == null) continue; FlatAreasFBuffer.Shape = TempAggregateClipFeature.ShapeCopy; FlatAreasFBuffer.set_Value(SurveyIDIndex, SurveyID); FlatAreasCursor.InsertFeature(FlatAreasFBuffer); } TempAggregateClipCursor = null; FlatAreasCursor = null; Util.SetProgressMessage("Cleaning up temp files"); Util.DeleteDataset(TempFlatAreasPolyFCName, esriDatasetType.esriDTFeatureClass, ref InternalErrors); Util.DeleteDataset(TempAggregateFCName, esriDatasetType.esriDTFeatureClass, ref InternalErrors); Util.DeleteDataset(TempClipFCName, esriDatasetType.esriDTFeatureClass, ref InternalErrors); Util.DeleteDataset(TempAggregateFCName + "_Tbl", esriDatasetType.esriDTTable, ref InternalErrors); Util.DeleteDataset(TempClipFCName + "_Tbl", esriDatasetType.esriDTTable, ref InternalErrors); Util.CreateFillerPolygon(FlatAreasFC, SurveyID, ref InternalErrors); }
/// <summary> /// generate exlcuded area polygons for the specified survey and elevation /// </summary> public static void GenerateExcludedAreasPolygons(int SurveyID, int MaximumElevInFeet, bool IsAboveElevation, IGeoDataset ClippedRasterDS, ref string ErrorMessage) { ESRI.ArcGIS.SpatialAnalyst.IMathOp ThisMathOp; IGeoDataset IntRasterDS = null; IQueryFilter ThisQueryFilter; ESRI.ArcGIS.GeoAnalyst.IRasterDescriptor ThisRasterDescriptor; ESRI.ArcGIS.Geoprocessing.IGeoProcessorResult GeoResult = null; ESRI.ArcGIS.Geoprocessing.IGeoProcessor ThisGeoProcessor = null; ESRI.ArcGIS.esriSystem.IVariantArray GPParams; IFeatureClass NewElvPolyFC, BoundaryFC, ElvPolyFC; ESRI.ArcGIS.GeoAnalyst.IConversionOp ThisConversionOp; string TempElvFCName, TempAggFCName, InternalErrors = "", TempClipFCName; IFeatureBuffer InsertBuffer; IFeatureCursor InsertCursor, TempCursor; IFeature TempFeature; int ShapeAreaIndex; double CurrentShapeArea, MaxShapeArea; int SurveyIDIndex; NPSGlobal NPS; NPS = NPSGlobal.Instance; TempElvFCName = "NPS_TEMP_TempElvPolyFCName"; TempAggFCName = "NPS_TEMP_TempElevationFC"; TempClipFCName = "NPS_TEMP_TempClipFCName"; ElvPolyFC = Util.GetFeatureClass(NPS.LYR_EXCLUDED_AREAS, ref ErrorMessage); if (string.IsNullOrEmpty(ErrorMessage) == false) return; BoundaryFC = Util.GetFeatureClass(NPS.LYR_SURVEY_BOUNDARY, ref ErrorMessage); if (string.IsNullOrEmpty(ErrorMessage) == false) return; SurveyIDIndex = ElvPolyFC.FindField("SurveyID"); if (SurveyIDIndex == -1) { ErrorMessage = "Could not find the SurveyID field on the Excluded Areas FeatureClass."; return; } Util.SetProgressMessage("Deleting old temp files"); Util.DeleteDataset(TempElvFCName, esriDatasetType.esriDTFeatureClass, ref InternalErrors); Util.DeleteDataset(TempClipFCName, esriDatasetType.esriDTFeatureClass, ref InternalErrors); Util.DeleteDataset(TempAggFCName, esriDatasetType.esriDTFeatureClass, ref InternalErrors); Util.DeleteDataset(TempClipFCName + "_Tbl", esriDatasetType.esriDTTable, ref InternalErrors); Util.DeleteDataset(TempAggFCName + "_Tbl", esriDatasetType.esriDTTable, ref InternalErrors); try { Util.SetProgressMessage("Converting DEM values to integers"); ThisMathOp = new ESRI.ArcGIS.SpatialAnalyst.RasterMathOpsClass(); IntRasterDS = ThisMathOp.Int(ClippedRasterDS); } catch (Exception ex) { ErrorMessage = "Error occured while converting DEM float slope values to slope integer values. " + ex.Message; return; } try { Util.SetProgressMessage("Building excluded area polygons from DEM"); //determine which values to exclude ThisQueryFilter = new QueryFilterClass(); if (IsAboveElevation) ThisQueryFilter.WhereClause = " Value >= " + MaximumElevInFeet; else ThisQueryFilter.WhereClause = " Value <= " + MaximumElevInFeet; ThisRasterDescriptor = new ESRI.ArcGIS.GeoAnalyst.RasterDescriptorClass(); ThisRasterDescriptor.Create(IntRasterDS as IRaster, ThisQueryFilter, "Value"); ThisConversionOp = new ESRI.ArcGIS.GeoAnalyst.RasterConversionOpClass(); NewElvPolyFC = ThisConversionOp.RasterDataToPolygonFeatureData(ThisRasterDescriptor as IGeoDataset, NPS.Workspace, TempElvFCName, true) as IFeatureClass; } catch (Exception ex) { ErrorMessage = "Error occured while generating a FeatureClass of flat " + "areas from the default DEM file. " + ex.Message; return; } try { Util.SetProgressMessage("Aggregating excluded area polygons"); ThisGeoProcessor = new ESRI.ArcGIS.Geoprocessing.GeoProcessor(); GPParams = new ESRI.ArcGIS.esriSystem.VarArrayClass(); GPParams.Add(System.IO.Path.Combine(NPS.DatabasePath, TempElvFCName)); GPParams.Add(System.IO.Path.Combine(NPS.DatabasePath, TempAggFCName)); GPParams.Add("1 Meters"); GeoResult = ThisGeoProcessor.Execute("AggregatePolygons_management", GPParams, null); } catch (Exception ex) { ErrorMessage = string.Format("Geoprocessor error:\r\nTask:AggregatePolygons_management\r\n" + "Params:{0},{1},{2}\r\nException:{3}", System.IO.Path.Combine(NPS.DatabasePath, TempElvFCName), System.IO.Path.Combine(NPS.DatabasePath, TempAggFCName), "1 Meters", ex.Message); ThisGeoProcessor = null; return; } ThisGeoProcessor = null; Util.DeleteLayerFromMap(TempAggFCName); NewElvPolyFC = Util.GetFeatureClass(TempAggFCName, ref ErrorMessage); if (string.IsNullOrEmpty(ErrorMessage) == false) { ErrorMessage = "Could not find temporary FeatureClass " + TempAggFCName + ". " + ErrorMessage; return; } Util.SetProgressMessage("Validating excluded area polygons"); NewElvPolyFC = Util.GP_Clip_analysis(TempClipFCName, NewElvPolyFC, BoundaryFC, ref ErrorMessage); if (string.IsNullOrEmpty(ErrorMessage) == false) return; InsertBuffer = ElvPolyFC.CreateFeatureBuffer(); InsertCursor = ElvPolyFC.Insert(true); ThisQueryFilter = null; ThisQueryFilter = new QueryFilterClass(); TempCursor = NewElvPolyFC.Search(ThisQueryFilter, false); ShapeAreaIndex = NewElvPolyFC.FindField(NewElvPolyFC.AreaField.Name); MaxShapeArea = (double)Util.SafeConvert(Util.GetFirstRecordValue(BoundaryFC, BoundaryFC.AreaField.Name, "SurveyID=" + SurveyID), typeof(double)); Util.SetProgressMessage("Importing excluded area polygons to Survey"); while ((TempFeature = TempCursor.NextFeature()) != null) { if (TempFeature.Shape == null) continue; CurrentShapeArea = (double)Util.SafeConvert(TempFeature.get_Value(ShapeAreaIndex), typeof(double)); if ((CurrentShapeArea / MaxShapeArea) >= 0.95) continue; InsertBuffer.Shape = TempFeature.ShapeCopy; InsertBuffer.set_Value(SurveyIDIndex, SurveyID); InsertCursor.InsertFeature(InsertBuffer); } TempCursor = null; InsertCursor = null; Util.SetProgressMessage("Cleaning up temp files"); Util.DeleteDataset(TempElvFCName, esriDatasetType.esriDTFeatureClass, ref InternalErrors); Util.DeleteDataset(TempClipFCName, esriDatasetType.esriDTFeatureClass, ref InternalErrors); Util.DeleteDataset(TempAggFCName, esriDatasetType.esriDTFeatureClass, ref InternalErrors); Util.DeleteDataset(TempClipFCName + "_Tbl", esriDatasetType.esriDTTable, ref InternalErrors); Util.DeleteDataset(TempAggFCName + "_Tbl", esriDatasetType.esriDTTable, ref InternalErrors); Util.CreateFillerPolygon(ElvPolyFC, SurveyID, ref InternalErrors); }
/// <summary> /// export default values table to a standonly dbase file at the specified file path /// </summary> public static void ExportDefaultValuesTable(string ExportTablePath, ref string ErrorMessage) { ESRI.ArcGIS.Geoprocessing.IGeoProcessorResult GeoResult = null; ESRI.ArcGIS.Geoprocessing.IGeoProcessor ThisGeoProcessor = null; ESRI.ArcGIS.esriSystem.IVariantArray GPParams; ITable DefaultValuesTable; IWorkspace ShapeFileWorkspace; try { DefaultValuesTable = Util.GetDefaultValuesTable(ref ErrorMessage); if (string.IsNullOrEmpty(ErrorMessage) == false) return; ShapeFileWorkspace = Util.OpenShapeFileWorkspace(ExportTablePath, ref ErrorMessage); if (string.IsNullOrEmpty(ErrorMessage) == false) return; ThisGeoProcessor = new ESRI.ArcGIS.Geoprocessing.GeoProcessor(); GPParams = new ESRI.ArcGIS.esriSystem.VarArrayClass(); GPParams.Add(DefaultValuesTable); GPParams.Add(ShapeFileWorkspace); GPParams.Add("defaultvalues.dbf"); GeoResult = ThisGeoProcessor.Execute("TableToTable_conversion", GPParams, null); } catch (Exception ex) { ErrorMessage = "Error occured while exporting defaultvalues table. " + ex.Message; } }
public static void ExecuteGP(string GPToolName, List<object> Params, ref string ErrorMessage) { ESRI.ArcGIS.esriSystem.IVariantArray GPParams; ESRI.ArcGIS.Geoprocessing.IGeoProcessor ThisGeoProcessor = null; ESRI.ArcGIS.Geoprocessing.IGeoProcessorResult GeoResult = null; NPSGlobal NPS; NPS = NPSGlobal.Instance; try { ThisGeoProcessor = new ESRI.ArcGIS.Geoprocessing.GeoProcessor(); GPParams = new ESRI.ArcGIS.esriSystem.VarArrayClass(); foreach (object ThisParam in Params) GPParams.Add(ThisParam); GeoResult = ThisGeoProcessor.Execute(GPToolName, GPParams, null); } catch { } ThisGeoProcessor = null; }