public static async Task <BA_ReturnCode> CreateGeodatabaseFoldersAsync(string strAoiPath, FolderType fType) { BA_ReturnCode success = BA_ReturnCode.UnknownError; await QueuedTask.Run(() => { var environments = Geoprocessing.MakeEnvironmentArray(workspace: strAoiPath); string[] arrGeodatabaseNames = GeodatabaseNames.AllNames; if (fType == FolderType.BASIN) { arrGeodatabaseNames = GeodatabaseNames.BasinNames; } { foreach (var item in arrGeodatabaseNames) { var parameters = Geoprocessing.MakeValueArray(strAoiPath, item); var gpResult = Geoprocessing.ExecuteToolAsync("CreateFileGDB_management", parameters, environments, CancelableProgressor.None, GPExecuteToolFlags.AddToHistory); if (gpResult.Result.IsFailed) { Module1.Current.ModuleLogManager.LogError(nameof(CreateGeodatabaseFoldersAsync), "Unable to create file geodatabase. Error code: " + gpResult.Result.ErrorCode); } else { success = BA_ReturnCode.Success; } } } }); return(success); }
protected async override void OnClick() { try { Module1.DeactivateState("BtnExcelTables_State"); var cmdShowHistory = FrameworkApplication.GetPlugInWrapper("esri_geoprocessing_showToolHistory") as ICommand; if (cmdShowHistory != null) { if (cmdShowHistory.CanExecute(null)) { cmdShowHistory.Execute(null); } } BA_ReturnCode success = await GeneralTools.GenerateTablesAsync(true); Module1.ActivateState("BtnExcelTables_State"); if (!success.Equals(BA_ReturnCode.Success)) { MessageBox.Show("An error occurred while generating the Excel tables!!", "BAGIS-PRO"); } } catch (Exception e) { MessageBox.Show("An exception occurred while trying to export the tables!! " + e.Message, "BAGIS PRO"); Module1.Current.ModuleLogManager.LogError(nameof(OnClick), "An error occurred while trying to export the tables!! " + e.Message); } }
public static async Task <string[]> QueryAoiEnvelopeAsync(Uri clipFileGdbUri, string clipName) { string[] arrRetValues = new string[2]; Geometry aoiGeo = null; int intCount = 0; await QueuedTask.Run(() => { using (Geodatabase geodatabase = new Geodatabase(new FileGeodatabaseConnectionPath(clipFileGdbUri))) using (Table table = geodatabase.OpenDataset <Table>(clipName)) { //check for multiple buffer polygons and buffer AOI if we need to QueryFilter queryFilter = new QueryFilter(); using (RowCursor cursor = table.Search(queryFilter, false)) { while (cursor.MoveNext()) { using (Feature feature = (Feature)cursor.Current) { aoiGeo = feature.GetShape(); } intCount++; } } } }); if (intCount > 1) { string tmpClipBuffer = "tmpClipBuffer"; BA_ReturnCode success = await GeoprocessingTools.BufferAsync(clipFileGdbUri.LocalPath + "\\" + clipName, clipFileGdbUri.LocalPath + "\\" + tmpClipBuffer, "0.5 Meters", "ALL"); if (success == BA_ReturnCode.Success) { await QueuedTask.Run(() => { using (Geodatabase geodatabase = new Geodatabase(new FileGeodatabaseConnectionPath(clipFileGdbUri))) using (Table table = geodatabase.OpenDataset <Table>(tmpClipBuffer)) { //check for multiple buffer polygons and buffer AOI if we need to QueryFilter queryFilter = new QueryFilter(); using (RowCursor cursor = table.Search(queryFilter, false)) { while (cursor.MoveNext()) { using (Feature feature = (Feature)cursor.Current) { aoiGeo = feature.GetShape(); // Replace unbuffered geometry with buffered clipName = tmpClipBuffer; } } } } }); } } arrRetValues[0] = aoiGeo.Extent.XMin + " " + aoiGeo.Extent.YMin + " " + aoiGeo.Extent.XMax + " " + aoiGeo.Extent.YMax; arrRetValues[1] = clipFileGdbUri.LocalPath + "\\" + clipName; return(arrRetValues); }
public static async Task <BA_ReturnCode> AddPointMarkersAsync(Uri aoiUri, string displayName, CIMColor markerColor, SimpleMarkerStyle markerStyle, double markerSize) { // parse the uri for the folder and file string strFileName = null; string strFolderPath = null; if (aoiUri.IsFile) { strFileName = System.IO.Path.GetFileName(aoiUri.LocalPath); strFolderPath = System.IO.Path.GetDirectoryName(aoiUri.LocalPath); } BA_ReturnCode success = BA_ReturnCode.UnknownError; await QueuedTask.Run(() => { FeatureClass fClass = null; // Opens a file geodatabase. This will open the geodatabase if the folder exists and contains a valid geodatabase. using (Geodatabase geodatabase = new Geodatabase(new FileGeodatabaseConnectionPath(new Uri(strFolderPath)))) { // Use the geodatabase. try { fClass = geodatabase.OpenDataset <FeatureClass>(strFileName); } catch (GeodatabaseTableException e) { Debug.WriteLine("DisplayPointMarkersAsync: Unable to open feature class " + strFileName); Debug.WriteLine("DisplayPointMarkersAsync: " + e.Message); success = BA_ReturnCode.ReadError; return; } } // Create symbology for feature layer var flyrCreatnParam = new FeatureLayerCreationParams(fClass) { Name = displayName, IsVisible = true, RendererDefinition = new SimpleRendererDefinition() { SymbolTemplate = SymbolFactory.Instance.ConstructPointSymbol(markerColor, markerSize, markerStyle) .MakeSymbolReference() } }; FeatureLayer fLayer = LayerFactory.Instance.CreateLayer <FeatureLayer>(flyrCreatnParam, MapView.Active.Map); }); success = BA_ReturnCode.Success; return(success); }
public static async Task <BA_ReturnCode> AddPolygonLayerAsync(Uri uri, CIMColor fillColor, bool isVisible, string displayName = "") { // parse the uri for the folder and file string strFileName = null; string strFolderPath = null; if (uri.IsFile) { strFileName = System.IO.Path.GetFileName(uri.LocalPath); strFolderPath = System.IO.Path.GetDirectoryName(uri.LocalPath); } BA_ReturnCode success = BA_ReturnCode.UnknownError; await QueuedTask.Run(() => { FeatureClass fClass = null; // Opens a file geodatabase. This will open the geodatabase if the folder exists and contains a valid geodatabase. using (Geodatabase geodatabase = new Geodatabase(new FileGeodatabaseConnectionPath(new Uri(strFolderPath)))) { // Use the geodatabase. fClass = geodatabase.OpenDataset <FeatureClass>(strFileName); } if (String.IsNullOrEmpty(displayName)) { displayName = fClass.GetDefinition().GetAliasName(); } // Create symbology for feature layer var flyrCreatnParam = new FeatureLayerCreationParams(fClass) { Name = displayName, IsVisible = true, RendererDefinition = new SimpleRendererDefinition() { //SymbolTemplate = SymbolFactory.Instance.ConstructPolygonSymbol(fillColor).MakeSymbolReference() SymbolTemplate = SymbolFactory.Instance.ConstructPolygonSymbol( fillColor, SimpleFillStyle.Solid, SymbolFactory.Instance.ConstructStroke(ColorFactory.Instance.BlackRGB, 0)) .MakeSymbolReference() } }; FeatureLayer fLayer = LayerFactory.Instance.CreateLayer <FeatureLayer>(flyrCreatnParam, MapView.Active.Map); fLayer.SetVisibility(isVisible); success = BA_ReturnCode.Success; }); return(success); }
public async Task <BA_ReturnCode> DownloadBatchSettingsAsync(string webserviceUrl, string strSaveToPath) { BA_ReturnCode success = BA_ReturnCode.UnknownError; webserviceUrl = webserviceUrl + @"/api/rest/desktop/settings/bagis-pro/"; EsriHttpResponseMessage response = new EsriHttpClient().Get(webserviceUrl); JObject jsonVal = JObject.Parse(await response.Content.ReadAsStringAsync()) as JObject; dynamic oSettings = (JObject)jsonVal["BatchSettings"]; using (System.IO.StreamWriter file = File.CreateText(strSaveToPath)) using (JsonTextWriter writer = new JsonTextWriter(file)) { oSettings.WriteTo(writer); } success = BA_ReturnCode.Success; return(success); }
public static async Task ToggleAsync(BagisMapType mapType) { //Get map definition BA_Objects.MapDefinition thisMap = MapTools.LoadMapDefinition(mapType); Layout oLayout = await MapTools.GetDefaultLayoutAsync(Constants.MAPS_DEFAULT_LAYOUT_NAME); if (oLayout != null) { foreach (var pane in FrameworkApplication.Panes) { if (!(pane is ILayoutPane layoutPane)) //if not a layout view, continue to the next pane { continue; } if (layoutPane.LayoutView.Layout == oLayout) //if there is a match, activate the view { (layoutPane as Pane).Activate(); } } } // toggle layers according to map definition Module1.Current.MapFinishedLoading = false; var allLayers = MapView.Active.Map.Layers.ToList(); await QueuedTask.Run(() => { foreach (var layer in allLayers) { if (thisMap.LayerList.Contains(layer.Name)) { layer.SetVisibility(true); } else { layer.SetVisibility(false); } } }); await MapTools.UpdateMapElementsAsync(Module1.Current.Aoi.NwccName.ToUpper(), thisMap); BA_ReturnCode success = await MapTools.UpdateLegendAsync(oLayout, thisMap.LegendLayerList); Module1.Current.MapFinishedLoading = true; Module1.Current.DisplayedMap = thisMap.PdfFileName; }
public static async Task <BA_ReturnCode> UpdateReclassFeatureAttributesAsync(Uri uriFeatureClass, string strFeatureClassName, IList <BA_Objects.Interval> lstIntervals) { BA_ReturnCode success = BA_ReturnCode.UnknownError; // Add fields to be updated to feature class, if missing string[] arrReclassFields = { Constants.FIELD_NAME, Constants.FIELD_LBOUND, Constants.FIELD_UBOUND }; string[] arrReclassFieldTypes = { "TEXT", "DOUBLE", "DOUBLE" }; string strFeatureClassPath = uriFeatureClass.LocalPath + "\\" + strFeatureClassName; for (int i = 0; i < arrReclassFields.Length; i++) { if (await AttributeExistsAsync(uriFeatureClass, strFeatureClassName, arrReclassFields[i]) == false) { success = await GeoprocessingTools.AddFieldAsync(strFeatureClassPath, arrReclassFields[i], arrReclassFieldTypes[i]); } } if (success != BA_ReturnCode.Success) { Module1.Current.ModuleLogManager.LogError(nameof(UpdateReclassFeatureAttributesAsync), "Unable to add fields to " + strFeatureClassPath); ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("Unable to add fields to " + strFeatureClassPath + "!!", "BAGIS-PRO"); return(success); } // Populate the fields bool modificationResult = false; string errorMsg = ""; await QueuedTask.Run(() => { using (Geodatabase geodatabase = new Geodatabase(new FileGeodatabaseConnectionPath(uriFeatureClass))) { if (!String.IsNullOrEmpty(strFeatureClassPath)) { QueryFilter queryFilter = new QueryFilter(); using (Table table = geodatabase.OpenDataset <Table>(strFeatureClassName)) { foreach (var oInterval in lstIntervals) { queryFilter.WhereClause = Constants.FIELD_GRID_CODE + " = " + oInterval.Value; EditOperation editOperation = new EditOperation(); editOperation.Callback(context => { using (RowCursor aCursor = table.Search(queryFilter, false)) { while (aCursor.MoveNext()) { using (Feature feature = (Feature)aCursor.Current) { // name int idxTarget = feature.FindField(arrReclassFields[0]); if (idxTarget > -1) { feature[idxTarget] = oInterval.Name; } // lower bound idxTarget = feature.FindField(arrReclassFields[1]); if (idxTarget > -1) { feature[idxTarget] = oInterval.LowerBound; } // upper bound idxTarget = feature.FindField(arrReclassFields[2]); if (idxTarget > -1) { feature[idxTarget] = oInterval.UpperBound; } feature.Store(); // Has to be called after the store too context.Invalidate(feature); } } } }, table); try { modificationResult = editOperation.Execute(); if (!modificationResult) { errorMsg = editOperation.ErrorMessage; } // increment feature counter } catch (GeodatabaseException exObj) { errorMsg = exObj.Message; } } } } } }); if (String.IsNullOrEmpty(errorMsg)) { await Project.Current.SaveEditsAsync(); } else { if (Project.Current.HasEdits) { await Project.Current.DiscardEditsAsync(); } Module1.Current.ModuleLogManager.LogError(nameof(UpdateReclassFeatureAttributesAsync), "Exception: " + errorMsg); return(BA_ReturnCode.UnknownError); } return(success); }
public async Task <BA_ReturnCode> UpdateAoiItemsAsync(string stationTriplet) { string nwccAoiName = ""; string huc = ""; string aoiSummaryTag = ""; BA_ReturnCode success = GeneralTools.LoadBatchToolSettings(); if (success != BA_ReturnCode.Success) { MessageBox.Show("Batch tool settings could not be loaded. The portal files cannot be updated!!"); return(success); } string[] arrResults = await GeneralTools.QueryMasterAoiProperties(stationTriplet); if (arrResults.Length == 4) { nwccAoiName = arrResults[0].Trim(); nwccAoiName = nwccAoiName.Replace(" ", "_"); huc = arrResults[3]; string[] pieces = stationTriplet.Split(':'); if (pieces.Length == 3) { aoiSummaryTag = arrResults[0].Trim() + " " + pieces[0] + " " + pieces[1]; } else { MessageBox.Show("Unable to parse station triplet. The portal files cannot be updated!!"); return(BA_ReturnCode.ReadError); } } else { MessageBox.Show("Unable to retrieve AOI properties from Master. The portal files cannot be updated!!"); return(BA_ReturnCode.ReadError); } // Ensure that the user is signed into the NRCS Portal BA_Objects.AGSPortalProperties portalProps = new BA_Objects.AGSPortalProperties(); var info = await ArcGISPortalManager.Current.GetActivePortal().GetPortalInfoAsync(); if (info.OrganizationName.Equals(BA_Objects.AGSPortalProperties.PORTAL_ORGANIZATION)) { portalProps.IsNrcsPortal = true; } await QueuedTask.Run(() => { portalProps.IsSignedIn = ArcGISPortalManager.Current.GetActivePortal().IsSignedOn(); portalProps.UserName = ArcGISPortalManager.Current.GetActivePortal().GetSignOnUsername(); if (portalProps.UserName.Equals(BA_Objects.AGSPortalProperties.NWCC_NRCS_USER)) { portalProps.IsNrcsUser = true; } }); if (!portalProps.IsNrcsPortal) { MessageBox.Show("Please sign into the USDA NRCS ArcGIS Online portal before trying to update items!!", "BAGIS-PRO"); return(BA_ReturnCode.NotSupportedOperation); } if (!portalProps.IsSignedIn) { var result = await ArcGISPortalManager.Current.GetActivePortal().SignInAsync(); if (result.success == false) { Module1.Current.ModuleLogManager.LogError(nameof(GetPortalFile), "Unable to signIn to the NRCS Portal. Can you connect to the portal in the ArcGIS Pro 'Portals' tab? Items cannot be updated ! " + "ArcGIS Pro will use a previous version of the file if it exists"); return(BA_ReturnCode.NotSupportedOperation); } } UriBuilder searchURL = new UriBuilder(ArcGISPortalManager.Current.GetActivePortal().PortalUri); EsriHttpClient httpClient = new EsriHttpClient(); searchURL.Path = "sharing/rest/search"; string pdfDocs = "(type:\"PDF\")"; string titleAoi = "(title:\"" + nwccAoiName + "\")"; searchURL.Query = string.Format("q=owner:{0} {1} {2} &f=json", portalProps.UserName, titleAoi, pdfDocs); var searchResponse = httpClient.Get(searchURL.Uri.ToString()); dynamic resultItems = JObject.Parse(await searchResponse.Content.ReadAsStringAsync()); long numberOfTotalItems = resultItems.total.Value; if (numberOfTotalItems == 0) { return(BA_ReturnCode.ReadError); } //string fileName = aoiName + "_overview.pdf"; List <string> allFileNames = new List <string> { nwccAoiName + "_" + Constants.FILE_EXPORT_OVERVIEW_PDF, nwccAoiName + "_" + Constants.FILE_EXPORT_MAP_ELEV_PDF, nwccAoiName + "_" + Constants.FILE_EXPORT_LAND_COVER_PDF, nwccAoiName + "_" + Constants.FILE_EXPORT_ASPECT_DISTRIBUTION_PDF, nwccAoiName + "_" + Constants.FILE_EXPORT_SLOPE_DISTRIBUTION_PDF, nwccAoiName + "_" + Constants.FILE_EXPORT_SITE_REPRESENTATION_PDF, nwccAoiName + "_" + Constants.FILE_EXPORT_PRECIPITATION_DISTRIBUTION_PDF, nwccAoiName + "_" + Constants.FILE_EXPORT_SEASONAL_PRECIP_DISTRIBUTION_PDF, nwccAoiName + "_" + Constants.FILE_EXPORT_SNODAS_SWE_PDF, nwccAoiName + "_" + Constants.FILE_EXPORT_POTENTIAL_SITE_ANALYSIS_PDF, nwccAoiName + "_" + Constants.FILE_EXPORT_WATERSHED_REPORT_PDF }; List <string> requiredTags = new List <string>() { "GIS", "BAGIS", "SNOTEL", "eBagis", huc, aoiSummaryTag }; List <dynamic> resultItemList = new List <dynamic>(); resultItemList.AddRange(resultItems.results); foreach (var item in resultItemList) { string itemFile = (string)item.name; if (allFileNames.Contains(itemFile)) { string itemId = (string)item.id; string strTitle = (string)item.title; List <string> tags = item.tags.ToObject <List <string> >(); UpdateItem(portalProps.UserName, itemId, strTitle, requiredTags, tags); } } return(BA_ReturnCode.Success); }
protected async override void OnClick() { string tempAoiPath = "C:\\Docs\\animas_AOI_prms"; try { Layout layout = await MapTools.GetDefaultLayoutAsync(Constants.MAPS_DEFAULT_LAYOUT_NAME); BA_ReturnCode success = await MapTools.DisplayMaps(tempAoiPath, layout, true); if (success == BA_ReturnCode.Success && layout != null) { bool bFoundIt = false; //A layout view may exist but it may not be active //Iterate through each pane in the application and check to see if the layout is already open and if so, activate it foreach (var pane in FrameworkApplication.Panes) { if (!(pane is ILayoutPane layoutPane)) //if not a layout view, continue to the next pane { continue; } if (layoutPane.LayoutView != null && layoutPane.LayoutView.Layout == layout) //if there is a match, activate the view { (layoutPane as Pane).Activate(); bFoundIt = true; } else { continue; } } if (!bFoundIt) { ILayoutPane iNewLayoutPane = await FrameworkApplication.Panes.CreateLayoutPaneAsync(layout); //GUI thread } } // Legend success = await MapTools.DisplayLegendAsync(Constants.MAPS_DEFAULT_MAP_FRAME_NAME, layout, "ArcGIS Colors", "1.5 Point", true); // update map elements for default map (elevation) if (FrameworkApplication.State.Contains("MapButtonPalette_BtnElevation_State")) { BA_Objects.MapDefinition defaultMap = MapTools.LoadMapDefinition(BagisMapType.ELEVATION); await MapTools.UpdateMapElementsAsync(Module1.Current.Aoi.NwccName.ToUpper(), defaultMap); success = await MapTools.UpdateLegendAsync(layout, defaultMap.LegendLayerList); } else { MessageBox.Show("The default Elevation Zones map could not be loaded. Use " + "the Display Maps buttons to display other maps!!", "BAGIS-PRO"); } Module1.Current.DisplayedMap = Constants.FILE_EXPORT_MAP_ELEV_PDF; Module1.ActivateState("BtnMapLoad_State"); MessageBox.Show("The maps are loaded. Use the Toggle Maps buttons to view the maps.", "BAGIS-PRO"); } catch (Exception e) { MessageBox.Show("An error occurred while trying to load the maps!! " + e.Message, "BAGIS PRO"); } }
private async void RunImplAsync(object param) { // Create initial log entry string strLogEntry = DateTime.Now.ToString("MM/dd/yy H:mm:ss ") + "Starting batch tool to publish in " + Path.GetDirectoryName(_strLogFile) + "\r\n"; File.WriteAllText(_strLogFile, strLogEntry); // overwrite file if it exists // Check for existing map package files and warn user if (ArchiveChecked) { string[] filePaths = Directory.GetFiles(AoiFolder + "\\" + Constants.FOLDER_MAP_PACKAGE, "*.pdf", SearchOption.TopDirectoryOnly); if (filePaths.Length > 0) { System.Windows.MessageBoxResult res = ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("BAGIS-PRO found at least one .pdf document in the " + "maps\\publish folder. These document(s) may be overwritten during the batch process. Uncheck " + "the 'Copy Reports' checkbox to stop copying documents to the maps\\publish folder. " + "The map packages will still be created in each AOI. Do you wish to continue and overwrite " + "the documents ?", "BAGIS-PRO", System.Windows.MessageBoxButton.YesNo); if (res != System.Windows.MessageBoxResult.Yes) { return; } } } // Save off the publisher name if it is different than previous string strPublisher = (string)Module1.Current.BatchToolSettings.Publisher; if (!Publisher.Trim().Equals(strPublisher)) { Module1.Current.BatchToolSettings.Publisher = Publisher; String json = JsonConvert.SerializeObject(Module1.Current.BatchToolSettings, Formatting.Indented); File.WriteAllText(SettingsFile, json); } // Make directory for required folders if they don't exist // Make sure that maps and maps_publish folders exist for (int idxRow = 0; idxRow < Names.Count; idxRow++) { if (Names[idxRow].AoiBatchIsSelected) { int errorCount = 0; // keep track of any non-fatal errors AoiFolder = Names[idxRow].FilePath; Names[idxRow].AoiBatchStateText = AoiBatchState.Started.ToString(); // update gui string[] arrFolders = { AoiFolder + "\\" + Constants.FOLDER_MAPS, AoiFolder + "\\" + Constants.FOLDER_MAP_PACKAGE, AoiFolder + "\\" + Constants.FOLDER_LOGS }; foreach (var directory in arrFolders) { if (!Directory.Exists(directory)) { Directory.CreateDirectory(directory); } } // Set logger to AOI directory string logFolderName = AoiFolder + "\\" + Constants.FOLDER_LOGS; Module1.Current.ModuleLogManager.UpdateLogFileLocation(logFolderName); // Set current AOI BA_Objects.Aoi oAoi = await GeneralTools.SetAoiAsync(AoiFolder); if (Module1.Current.CboCurrentAoi != null) { FrameworkApplication.Current.Dispatcher.Invoke(() => { // Do something on the GUI thread Module1.Current.CboCurrentAoi.SetAoiName(oAoi.Name); }); } // Create opening log entry for AOI strLogEntry = DateTime.Now.ToString("MM/dd/yy H:mm:ss ") + "Starting batch PDF export for " + oAoi.Name + "\r\n"; File.AppendAllText(_strLogFile, strLogEntry); // append // Bring GP History tool forward var cmdShowHistory = FrameworkApplication.GetPlugInWrapper("esri_geoprocessing_showToolHistory") as ICommand; if (cmdShowHistory != null) { if (cmdShowHistory.CanExecute(null)) { cmdShowHistory.Execute(null); } } oAoi = Module1.Current.Aoi; // Elevation zones BA_ReturnCode success = await AnalysisTools.CalculateElevationZonesAsync(Module1.Current.Aoi.FilePath); if (success != BA_ReturnCode.Success) { errorCount++; } // Slope zones string strLayer = GeodatabaseTools.GetGeodatabasePath(AoiFolder, GeodatabaseNames.Surfaces, true) + Constants.FILE_SLOPE; string strZonesRaster = GeodatabaseTools.GetGeodatabasePath(AoiFolder, GeodatabaseNames.Analysis, true) + Constants.FILE_SLOPE_ZONE; string strMaskPath = GeodatabaseTools.GetGeodatabasePath(AoiFolder, GeodatabaseNames.Aoi, true) + Constants.FILE_AOI_BUFFERED_VECTOR; IList <BA_Objects.Interval> lstInterval = AnalysisTools.GetSlopeClasses(); success = await AnalysisTools.CalculateZonesAsync(AoiFolder, strLayer, lstInterval, strZonesRaster, strMaskPath, "SLOPE"); if (success != BA_ReturnCode.Success) { errorCount++; } // Check for PRISM buffer units string[] arrPrismBufferInfo = await GeneralTools.QueryBufferDistanceAsync(AoiFolder, GeodatabaseTools.GetGeodatabasePath(AoiFolder, GeodatabaseNames.Aoi), Constants.FILE_AOI_PRISM_VECTOR, false); string pBufferDistance = arrPrismBufferInfo[0]; string pBufferUnits = arrPrismBufferInfo[1]; // Clip PRISM string strDefaultBufferDistance = (string)Module1.Current.BatchToolSettings.PrecipBufferDistance; string strDefaultBufferUnits = (string)Module1.Current.BatchToolSettings.PrecipBufferUnits; success = await AnalysisTools.ClipLayersAsync(AoiFolder, Constants.DATA_TYPE_PRECIPITATION, pBufferDistance, pBufferUnits, strDefaultBufferDistance, strDefaultBufferUnits); if (success == BA_ReturnCode.Success) { success = await AnalysisTools.UpdateSitesPropertiesAsync(Module1.Current.Aoi.FilePath, SiteProperties.Precipitation); } if (success != BA_ReturnCode.Success) { errorCount++; } // PRISM Zones strLayer = GeodatabaseTools.GetGeodatabasePath(Module1.Current.Aoi.FilePath, GeodatabaseNames.Prism, true) + Path.GetFileName((string)Module1.Current.BatchToolSettings.AoiPrecipFile); strZonesRaster = GeodatabaseTools.GetGeodatabasePath(Module1.Current.Aoi.FilePath, GeodatabaseNames.Analysis, true) + Constants.FILE_PRECIP_ZONE; success = await AnalysisTools.CalculatePrecipitationZonesAsync(strLayer, strZonesRaster); if (success != BA_ReturnCode.Success) { errorCount++; } // Winter Precipitation success = await AnalysisTools.GenerateWinterPrecipitationLayerAsync(oAoi); if (success != BA_ReturnCode.Success) { errorCount++; } // Clip SWE success = await AnalysisTools.ClipSweLayersAsync(pBufferDistance, pBufferUnits, strDefaultBufferDistance, strDefaultBufferUnits); if (success != BA_ReturnCode.Success) { errorCount++; } // Generate SWE Delta Layers success = await AnalysisTools.CalculateSWEDeltaAsync(AoiFolder); // Clip Snotel and Snow Course double dblDistance = -1; bool isDouble = Double.TryParse((string)Module1.Current.BatchToolSettings.SnotelBufferDistance, out dblDistance); if (!isDouble) { dblDistance = 0; } Module1.Current.ModuleLogManager.LogDebug(nameof(RunImplAsync), "Buffer distance from settings: " + dblDistance); string snoBufferDistance = dblDistance + " " + (string)Module1.Current.BatchToolSettings.SnotelBufferUnits; Module1.Current.ModuleLogManager.LogDebug(nameof(RunImplAsync), "Sites buffer distance string: " + snoBufferDistance); success = await AnalysisTools.ClipSnoLayersAsync(Module1.Current.Aoi.FilePath, true, snoBufferDistance, true, snoBufferDistance); if (success != BA_ReturnCode.Success) { errorCount++; } // Represented Area if (success == BA_ReturnCode.Success) { double siteBufferDistanceMiles = (double)Module1.Current.BatchToolSettings.SiteBufferDistMiles; double siteElevRangeFeet = (double)Module1.Current.BatchToolSettings.SiteElevRangeFeet; success = await AnalysisTools.GenerateSiteLayersAsync(siteBufferDistanceMiles, siteElevRangeFeet); if (success != BA_ReturnCode.Success) { errorCount++; } // Sites Zones Uri uri = new Uri(GeodatabaseTools.GetGeodatabasePath(Module1.Current.Aoi.FilePath, GeodatabaseNames.Layers)); bool hasSnotel = await GeodatabaseTools.FeatureClassExistsAsync(uri, Constants.FILE_SNOTEL); bool hasSnowCourse = await GeodatabaseTools.FeatureClassExistsAsync(uri, Constants.FILE_SNOW_COURSE); if (hasSnotel || hasSnowCourse) { success = await AnalysisTools.CalculateSitesZonesAsync(Module1.Current.Aoi.FilePath, hasSnotel, hasSnowCourse); if (success != BA_ReturnCode.Success) { errorCount++; } } else { Module1.Current.ModuleLogManager.LogError(nameof(CmdRun), "No sites found to create sites zone layers!!"); } } // Precipitation Contribution; Passing in -1 for threshold so we use STDEV success = await AnalysisTools.CalculatePrecipitationContributionAsync(Module1.Current.Aoi.FilePath, -1); if (success != BA_ReturnCode.Success) { errorCount++; } // Quarterly Precipitation Contribution success = await AnalysisTools.CalculateQuarterlyPrecipitationAsync(Module1.Current.Aoi); if (success != BA_ReturnCode.Success) { errorCount++; } // Aspect zones success = await AnalysisTools.CalculateAspectZonesAsync(); if (success != BA_ReturnCode.Success) { errorCount++; } string[] arrUnmanagedBufferInfo = await GeneralTools.QueryBufferDistanceAsync(AoiFolder, GeodatabaseTools.GetGeodatabasePath(AoiFolder, GeodatabaseNames.Aoi), Constants.FILE_AOI_BUFFERED_VECTOR, false); string unmanagedBufferDistance = arrPrismBufferInfo[0]; string unmanagedBufferUnits = arrPrismBufferInfo[1]; if (SiteAnalysisChecked) { // Clip Roads string strOutputFc = GeodatabaseTools.GetGeodatabasePath(AoiFolder, GeodatabaseNames.Layers, true) + Constants.FILE_ROADS; success = await AnalysisTools.ClipFeatureLayerAsync(AoiFolder, strOutputFc, Constants.DATA_TYPE_ROADS, unmanagedBufferDistance, unmanagedBufferUnits); if (success != BA_ReturnCode.Success) { errorCount++; } if (success == BA_ReturnCode.Success) { // Buffer clipped roads for analysis Uri uri = new Uri(GeodatabaseTools.GetGeodatabasePath(AoiFolder, GeodatabaseNames.Layers)); bool bExists = await GeodatabaseTools.FeatureClassExistsAsync(uri, Constants.FILE_ROADS); if (!bExists) { Module1.Current.ModuleLogManager.LogDebug(nameof(CmdRun), "Unable to buffer roads because fs_roads layer does not exist. Process stopped!!"); } else { string strDistance = Module1.Current.BatchToolSettings.RoadsAnalysisBufferDistance + " " + Module1.Current.BatchToolSettings.RoadsAnalysisBufferUnits; success = await AnalysisTools.GenerateProximityRoadsLayerAsync(uri, strDistance); if (success != BA_ReturnCode.Success) { errorCount++; } } } // Clip public lands strOutputFc = GeodatabaseTools.GetGeodatabasePath(AoiFolder, GeodatabaseNames.Layers, true) + Constants.FILE_PUBLIC_LAND; success = await AnalysisTools.ClipFeatureLayerAsync(AoiFolder, strOutputFc, Constants.DATA_TYPE_PUBLIC_LAND, unmanagedBufferDistance, unmanagedBufferUnits); if (success != BA_ReturnCode.Success) { errorCount++; } if (success == BA_ReturnCode.Success) { // Create public lands layer for potential site analysis success = await AnalysisTools.GetFederalNonWildernessLandsAsync(AoiFolder); if (success != BA_ReturnCode.Success) { errorCount++; } } // Clip Vegetation layer string strOutputRaster = GeodatabaseTools.GetGeodatabasePath(AoiFolder, GeodatabaseNames.Layers, true) + Constants.FILE_VEGETATION_EVT; success = await AnalysisTools.ClipRasterLayerAsync(AoiFolder, strOutputRaster, Constants.DATA_TYPE_VEGETATION, unmanagedBufferDistance, unmanagedBufferUnits); if (success != BA_ReturnCode.Success) { errorCount++; } if (success == BA_ReturnCode.Success) { // Create area below treeline layer for potential site analysis success = await AnalysisTools.ExtractBelowTreelineAsync(AoiFolder); if (success != BA_ReturnCode.Success) { errorCount++; } } // Generate Potential Sites layer success = await AnalysisTools.CalculatePotentialSitesAreaAsync(AoiFolder); if (success != BA_ReturnCode.Success) { errorCount++; } } // Clip Land cover success = await AnalysisTools.ClipLandCoverAsync(AoiFolder, unmanagedBufferDistance, unmanagedBufferUnits); // Generate Elevation Precipitation Correlation layer strLayer = GeodatabaseTools.GetGeodatabasePath(AoiFolder, GeodatabaseNames.Prism, true) + Path.GetFileName((string)Module1.Current.BatchToolSettings.AoiPrecipFile); Uri uriPrism = new Uri(GeodatabaseTools.GetGeodatabasePath(AoiFolder, GeodatabaseNames.Prism)); success = await AnalysisTools.CalculateElevPrecipCorrAsync(AoiFolder, uriPrism, Path.GetFileName((string)Module1.Current.BatchToolSettings.AoiPrecipFile)); if (success != BA_ReturnCode.Success) { errorCount++; } if (success == BA_ReturnCode.Success) { Module1.Current.ModuleLogManager.LogDebug(nameof(CmdRun), "Generated Elevation Precipitation Correlation layer"); } // Generate complete PDF document try { // Delete any old PDF files //string[] arrAllPdfFiles = new string[Constants.FILES_EXPORT_WATERSHED_PDF.Length + FILES_EXPORT_SITE_ANALYSIS_PDF.Length]; //Array.Copy(Constants.FILES_EXPORT_WATERSHED_PDF, arrAllPdfFiles, Constants.FILES_EXPORT_WATERSHED_PDF.Length); //Array.Copy(Constants.FILES_EXPORT_SITE_ANALYSIS_PDF, 0, arrAllPdfFiles, // Constants.FILES_EXPORT_WATERSHED_PDF.Length, Constants.FILES_EXPORT_SITE_ANALYSIS_PDF.Length); foreach (var item in Constants.FILES_EXPORT_WATERSHED_PDF) { string strPath = Module1.Current.Aoi.FilePath + "\\" + Constants.FOLDER_MAP_PACKAGE + "\\" + item; if (System.IO.File.Exists(strPath)) { try { System.IO.File.Delete(strPath); } catch (Exception) { System.Windows.MessageBoxResult res = MessageBox.Show("Unable to delete file before creating new pdf. Do you want to close the file and try again?", "BAGIS-PRO", System.Windows.MessageBoxButton.YesNo); if (res == System.Windows.MessageBoxResult.Yes) { return; } } } } Layout oLayout = await MapTools.GetDefaultLayoutAsync(Constants.MAPS_DEFAULT_LAYOUT_NAME); // Always load the maps in case we are running through multiple Aois success = await MapTools.DisplayMaps(Module1.Current.Aoi.FilePath, oLayout, false); if (success != BA_ReturnCode.Success) { MessageBox.Show("Unable to load maps. The map package cannot be exported!!", "BAGIS-PRO"); Names[idxRow].AoiBatchStateText = AoiBatchState.Failed.ToString(); return; } // Legend success = await MapTools.DisplayLegendAsync(Constants.MAPS_DEFAULT_MAP_FRAME_NAME, oLayout, "ArcGIS Colors", "1.5 Point", true); if (success != BA_ReturnCode.Success) { errorCount++; } if (oLayout != null) { bool bFoundIt = false; //A layout view may exist but it may not be active //Iterate through each pane in the application and check to see if the layout is already open and if so, activate it foreach (var pane in FrameworkApplication.Panes) { if (!(pane is ILayoutPane layoutPane)) //if not a layout view, continue to the next pane { continue; } if (layoutPane.LayoutView != null && layoutPane.LayoutView.Layout == oLayout) //if there is a match, activate the view { (layoutPane as Pane).Activate(); bFoundIt = true; } } if (!bFoundIt) { await FrameworkApplication.Current.Dispatcher.Invoke(async() => { // Do something on the GUI thread ILayoutPane iNewLayoutPane = await FrameworkApplication.Panes.CreateLayoutPaneAsync(oLayout); //GUI thread (iNewLayoutPane as Pane).Activate(); }); } } success = await MapTools.PublishMapsAsync(ReportType.Watershed); // export the watershed maps to pdf if (success != BA_ReturnCode.Success) { MessageBox.Show("An error occurred while generating the watershed characteristics maps!!", "BAGIS-PRO"); errorCount++; } //if (SiteAnalysisChecked) //{ // success = await MapTools.PublishMapsAsync(ReportType.SiteAnalysis); // export the site analysis maps to pdf // if (success != BA_ReturnCode.Success) // { // MessageBox.Show("An error occurred while generating the site analysis maps!!", "BAGIS-PRO"); // errorCount++; // } //} success = await GeneralTools.GenerateTablesAsync(false); // export the tables to pdf if (success != BA_ReturnCode.Success) { MessageBox.Show("An error occurred while generating the Excel tables!!", "BAGIS-PRO"); errorCount++; } else { // Generate the crtical precip map; It has to follow the tables Uri uriAnalysis = new Uri(GeodatabaseTools.GetGeodatabasePath(Module1.Current.Aoi.FilePath, GeodatabaseNames.Analysis)); if (await GeodatabaseTools.FeatureClassExistsAsync(uriAnalysis, Constants.FILE_CRITICAL_PRECIP_ZONE)) { success = await MapTools.DisplayCriticalPrecipitationZonesMap(uriAnalysis); string strButtonState = "MapButtonPalette_BtnCriticalPrecipZone_State"; if (success.Equals(BA_ReturnCode.Success)) { Module1.ActivateState(strButtonState); } int foundS1 = strButtonState.IndexOf("_State"); string strMapButton = strButtonState.Remove(foundS1); ICommand cmd = FrameworkApplication.GetPlugInWrapper(strMapButton) as ICommand; Module1.Current.ModuleLogManager.LogDebug(nameof(RunImplAsync), "About to toggle map button " + strMapButton); if ((cmd != null)) { do { await Task.Delay(TimeSpan.FromSeconds(0.4)); // build in delay until the command can execute }while (!cmd.CanExecute(null)); cmd.Execute(null); } do { await Task.Delay(TimeSpan.FromSeconds(0.4)); // build in delay so maps can load }while (Module1.Current.MapFinishedLoading == false); success = await GeneralTools.ExportMapToPdfAsync(150); // export map to pdf if (success == BA_ReturnCode.Success) { // append the map and chart together for posting IList <string> lstToConcat = new List <string>(); lstToConcat.Add(GeneralTools.GetFullPdfFileName(Constants.FILE_EXPORT_MAP_CRITICAL_PRECIPITATION_ZONES_PDF)); lstToConcat.Add(GeneralTools.GetFullPdfFileName(Constants.FILE_EXPORT_TABLE_PRECIP_REPRESENT_PDF)); success = GeneralTools.ConcatenatePagesInPdf(GeneralTools.GetFullPdfFileName(Constants.FILE_EXPORT_CRITICAL_PRECIPITATION_ZONES_PDF), lstToConcat); } else { Module1.Current.ModuleLogManager.LogError(nameof(RunImplAsync), "Unable to generate critical precipitation zones map!!"); } } } success = await GeneralTools.GenerateSitesTableAsync(Module1.Current.Aoi); success = await GeneralTools.GenerateMapsTitlePageAsync(ReportType.Watershed, strPublisher, Comments); if (success != BA_ReturnCode.Success) { MessageBox.Show("An error occurred while generating the Title page!!", "BAGIS-PRO"); errorCount++; } string outputPath = GeneralTools.GetFullPdfFileName(Constants.FILE_EXPORT_WATERSHED_REPORT_PDF); success = GeneralTools.PublishFullPdfDocument(outputPath, ReportType.Watershed); // Put it all together into a single pdf document if (success != BA_ReturnCode.Success) { errorCount++; } //if (SiteAnalysisChecked) //{ // success = await GeneralTools.GenerateMapsTitlePageAsync(ReportType.SiteAnalysis, strPublisher, Comments); // outputPath = GeneralTools.GetFullPdfFileName(Constants.FILE_EXPORT_SITE_ANALYSIS_REPORT_PDF); // success = GeneralTools.PublishFullPdfDocument(outputPath, ReportType.SiteAnalysis); // Put it all together into a single pdf document //} if (success != BA_ReturnCode.Success) { errorCount++; } else if (ArchiveChecked) { string reportName = Constants.FILE_EXPORT_WATERSHED_REPORT_PDF; // Copy final watershed analysis report to a central location if (File.Exists(outputPath)) { File.Copy(outputPath, GeneralTools.GetFullPdfFileName(reportName), true); } //if (SiteAnalysisChecked) //{ // reportName = Constants.FILE_EXPORT_SITE_ANALYSIS_REPORT_PDF; // File.Copy(outputPath, GeneralTools.GetFullPdfFileName(reportName), true); //} } // Create closing log entry for AOI if (errorCount == 0) { strLogEntry = DateTime.Now.ToString("MM/dd/yy H:mm:ss ") + "Completed batch PDF export for " + oAoi.Name + ". The output is located at " + oAoi.FilePath + "\\" + Constants.FOLDER_MAP_PACKAGE + "\r\n"; Names[idxRow].AoiBatchStateText = AoiBatchState.Completed.ToString(); } else { strLogEntry = DateTime.Now.ToString("MM/dd/yy H:mm:ss ") + "Completed batch PDF export WITH ERRORS for " + oAoi.Name + ". The output is located at " + oAoi.FilePath + "\\" + Constants.FOLDER_MAP_PACKAGE + "\r\n" + "Check for errors in the logs at " + oAoi.FilePath + "\\" + Constants.FOLDER_LOGS + "! \r\n"; Names[idxRow].AoiBatchStateText = AoiBatchState.Errors.ToString(); } File.AppendAllText(_strLogFile, strLogEntry); } catch (Exception e) { MessageBox.Show("An error occurred while running the Batch PDF Tool!! " + e.Message, "BAGIS PRO"); Module1.Current.ModuleLogManager.LogError(nameof(RunImplAsync), e.StackTrace); strLogEntry = DateTime.Now.ToString("MM/dd/yy H:mm:ss ") + "Batch PDF export failed for " + oAoi.Name + ". Check for errors in the logs at " + oAoi.FilePath + "\\" + Constants.FOLDER_LOGS + "!\r\n"; File.AppendAllText(_strLogFile, strLogEntry); Names[idxRow].AoiBatchStateText = AoiBatchState.Failed.ToString(); } } } MessageBox.Show("Done!"); // Concluding log entry strLogEntry = DateTime.Now.ToString("MM/dd/yy H:mm:ss ") + "Batch tool finished!! \r\n"; using (StreamWriter sw = File.AppendText(_strLogFile)) { sw.WriteLine(strLogEntry); } }
private async Task ClipLayersAsync(bool clipSwe, bool clipPrism, bool clipSnotel, bool clipSnowCos, bool clipRoads, bool clipPublicLands, bool clipVegetation, bool clipLandcover) { try { if (String.IsNullOrEmpty(Module1.Current.Aoi.Name)) { MessageBox.Show("No AOI selected for analysis !!", "BAGIS-PRO"); return; } if (clipSwe == false && clipPrism == false && clipSnotel == false && clipSnowCos == false && clipRoads == false && clipPublicLands == false && clipVegetation == false && clipLandcover == false) { MessageBox.Show("No layers selected to clip !!", "BAGIS-PRO"); return; } var cmdShowHistory = FrameworkApplication.GetPlugInWrapper("esri_geoprocessing_showToolHistory") as ICommand; if (cmdShowHistory != null) { if (cmdShowHistory.CanExecute(null)) { cmdShowHistory.Execute(null); } } var layersPane = (DockpaneLayersViewModel)FrameworkApplication.DockPaneManager.Find("bagis_pro_DockpaneLayers"); BA_ReturnCode success = BA_ReturnCode.Success; // Check for PRISM units string strPrismPath = GeodatabaseTools.GetGeodatabasePath(Module1.Current.Aoi.FilePath, GeodatabaseNames.Prism, true) + PrismFile.Annual.ToString(); string pBufferDistance = ""; string pBufferUnits = ""; string strBagisTag = await GeneralTools.GetBagisTagAsync(strPrismPath, Constants.META_TAG_XPATH); if (!string.IsNullOrEmpty(strBagisTag)) { pBufferDistance = GeneralTools.GetValueForKey(strBagisTag, Constants.META_TAG_BUFFER_DISTANCE, ';'); pBufferUnits = GeneralTools.GetValueForKey(strBagisTag, Constants.META_TAG_XUNIT_VALUE, ';'); } // Apply default buffer if left null if (string.IsNullOrEmpty(PrismBufferDistance)) { PrismBufferDistance = (string)Module1.Current.BatchToolSettings.PrecipBufferDistance; PrismBufferUnits = (string)Module1.Current.BatchToolSettings.PrecipBufferUnits; } if (clipPrism) { success = await AnalysisTools.ClipLayersAsync(Module1.Current.Aoi.FilePath, Constants.DATA_TYPE_PRECIPITATION, pBufferDistance, pBufferUnits, PrismBufferDistance, PrismBufferUnits); if (success == BA_ReturnCode.Success) { success = await AnalysisTools.UpdateSitesPropertiesAsync(Module1.Current.Aoi.FilePath, SiteProperties.Precipitation); } if (success == BA_ReturnCode.Success) { layersPane.ReclipPrism_Checked = false; layersPane.Prism_Checked = true; } } if (clipSwe) { success = await AnalysisTools.ClipSweLayersAsync(pBufferDistance, pBufferUnits, SWEBufferDistance, SWEBufferUnits); if (success == BA_ReturnCode.Success) { layersPane.ReclipSwe_Checked = false; layersPane.SWE_Checked = true; } } if (clipSnotel || clipSnowCos) { string snotelBufferDistance = ""; string snowCosBufferDistance = ""; double dblDistance = -1; bool isDouble = Double.TryParse(SnotelBufferDistance, out dblDistance); if (clipSnotel && isDouble && dblDistance > 0) { snotelBufferDistance = SnotelBufferDistance + " " + SnotelBufferUnits; } isDouble = Double.TryParse(SnowCosBufferDistance, out dblDistance); if (clipSnowCos && isDouble && dblDistance > 0) { snowCosBufferDistance = SnowCosBufferDistance + " " + SnowCosBufferUnits; } success = await AnalysisTools.ClipSnoLayersAsync(Module1.Current.Aoi.FilePath, clipSnotel, snotelBufferDistance, clipSnowCos, snowCosBufferDistance); if (success == BA_ReturnCode.Success) { if (clipSnotel) { layersPane.ReclipSNOTEL_Checked = false; layersPane.SNOTEL_Checked = true; } if (clipSnowCos) { layersPane.ReclipSnowCos_Checked = false; layersPane.SnowCos_Checked = true; } } } if (clipRoads) { string strOutputFc = GeodatabaseTools.GetGeodatabasePath(Module1.Current.Aoi.FilePath, GeodatabaseNames.Layers, true) + Constants.FILE_ROADS; success = await AnalysisTools.ClipFeatureLayerAsync(Module1.Current.Aoi.FilePath, strOutputFc, Constants.DATA_TYPE_ROADS, RoadsBufferDistance, RoadsBufferUnits); if (success == BA_ReturnCode.Success) { layersPane.ReclipRoads_Checked = false; layersPane.Roads_Checked = true; } else { MessageBox.Show("An error occurred while clipping the roads. Check the log file!!", "BAGIS-PRO"); } } if (clipPublicLands) { string strOutputFc = GeodatabaseTools.GetGeodatabasePath(Module1.Current.Aoi.FilePath, GeodatabaseNames.Layers, true) + Constants.FILE_PUBLIC_LAND; success = await AnalysisTools.ClipFeatureLayerAsync(Module1.Current.Aoi.FilePath, strOutputFc, Constants.DATA_TYPE_PUBLIC_LAND, PublicLandsBufferDistance, PublicLandsBufferUnits); if (success == BA_ReturnCode.Success) { layersPane.ReclipPublicLands_Checked = false; layersPane.PublicLands_Checked = true; } else { MessageBox.Show("An error occurred while clipping the public lands. Check the log file!!", "BAGIS-PRO"); } } if (clipVegetation) { string strOutputRaster = GeodatabaseTools.GetGeodatabasePath(Module1.Current.Aoi.FilePath, GeodatabaseNames.Layers, true) + Constants.FILE_VEGETATION_EVT; success = await AnalysisTools.ClipRasterLayerAsync(Module1.Current.Aoi.FilePath, strOutputRaster, Constants.DATA_TYPE_VEGETATION, VegetationBufferDistance, VegetationBufferUnits); if (success == BA_ReturnCode.Success) { layersPane.ReclipVegetation_Checked = false; layersPane.Vegetation_Checked = true; } else { MessageBox.Show("An error occurred while clipping the vegetation layer. Check the log file!!", "BAGIS-PRO"); } } if (clipLandcover) { success = await AnalysisTools.ClipLandCoverAsync(Module1.Current.Aoi.FilePath, LandCoverBufferDistance, LandCoverBufferUnits); if (success == BA_ReturnCode.Success) { layersPane.ReclipLandCover_Checked = false; layersPane.LandCover_Checked = true; } else { MessageBox.Show("An error occurred while clipping the land cover layer. Check the log file!!", "BAGIS-PRO"); } } if (success == BA_ReturnCode.Success) { MessageBox.Show("Analysis layers clipped!!", "BAGIS-PRO"); } else { MessageBox.Show("An error occurred while trying to clip the layers !!", "BAGIS-PRO"); } } catch (Exception ex) { Module1.Current.ModuleLogManager.LogError(nameof(ClipLayersAsync), "Exception: " + ex.Message); } }
private async void RunImplAsync(object param) { // Bring GP History tool forward var cmdShowHistory = FrameworkApplication.GetPlugInWrapper("esri_geoprocessing_showToolHistory") as ICommand; if (cmdShowHistory != null) { if (cmdShowHistory.CanExecute(null)) { cmdShowHistory.Execute(null); } } foreach (var oAoi in Names) { if (oAoi.AoiBatchIsSelected) { // Currently only support AOI conversion but BASIN may be added in future FolderType fType = await GeodatabaseTools.GetWeaselAoiFolderTypeAsync(oAoi.FilePath); IList <string> lstExistingGdb = null; if (fType == FolderType.AOI) { lstExistingGdb = CheckForBagisGdb(oAoi.FilePath); } else { lstExistingGdb = CheckForBasinGdb(oAoi.FilePath); } // Make directory for log if it doesn't exist if (!Directory.Exists(oAoi.FilePath + "\\" + Constants.FOLDER_LOGS)) { DirectoryInfo info = Directory.CreateDirectory(oAoi.FilePath + "\\" + Constants.FOLDER_LOGS); if (info == null) { MessageBox.Show("Unable to create logs directory in Aoi folder!!", "BAGIS-PRO"); } } // Set logger to AOI directory string logFolderName = oAoi.FilePath + "\\" + Constants.FOLDER_LOGS; Module1.Current.ModuleLogManager.UpdateLogFileLocation(logFolderName); // Delete old geodatabases if they exist foreach (var geodatabasePath in lstExistingGdb) { IGPResult gpResult = await QueuedTask.Run(() => { var parameters = Geoprocessing.MakeValueArray(geodatabasePath); return(Geoprocessing.ExecuteToolAsync("Delete_management", parameters, null, CancelableProgressor.None, GPExecuteToolFlags.AddToHistory)); }); if (gpResult.IsFailed) { Module1.Current.ModuleLogManager.LogError(nameof(RunImplAsync), "Unable to delete geodatabase. Error code: " + gpResult.ErrorCode); MessageBox.Show("Unable to delete geodatabase " + geodatabasePath + "!"); } } // Create new geodatabases BA_ReturnCode success = await GeodatabaseTools.CreateGeodatabaseFoldersAsync(oAoi.FilePath, fType); if (success == BA_ReturnCode.Success) { Module1.Current.ModuleLogManager.LogInfo(nameof(RunImplAsync), "Created geodatabases in " + oAoi.FilePath); } else { MessageBox.Show("Unable to create geodatabases in " + oAoi.FilePath + ". Check logs!"); } // Assemble a dictionary with rasters we want to copy IDictionary <string, string> rastersToCopy = GetDictOfReqRasters(oAoi.FilePath, fType); // Accomodate two possible names for raster aoi boundary layer (aoibagis or aoi) IList <string> lstTest = new List <string> { oAoi.FilePath + @"\aoibagis" }; string aoiGdb = GeodatabaseTools.GetGeodatabasePath(oAoi.FilePath, GeodatabaseNames.Aoi, true); IList <string> existingLayers = null; if (fType == FolderType.AOI) { existingLayers = await GeneralTools.RasterDatasetsExistAsync(lstTest); if (existingLayers.Count == 0) { lstTest.Clear(); string strLayer = oAoi.FilePath + @"\aoi"; lstTest.Add(strLayer); existingLayers = await GeneralTools.RasterDatasetsExistAsync(lstTest); if (existingLayers.Count > 0) { rastersToCopy[strLayer] = aoiGdb + Constants.FILE_AOI_RASTER; } } else { rastersToCopy[oAoi.FilePath + @"\aoibagis"] = aoiGdb + Constants.FILE_AOI_RASTER; } } // Check to see if optional layers are present IDictionary <string, string> optRasterDict = GetDictOptWeaselRasters(oAoi.FilePath, fType); existingLayers = await GeneralTools.RasterDatasetsExistAsync(optRasterDict.Keys); foreach (var layerPath in existingLayers) { string gdbPath = optRasterDict[layerPath]; rastersToCopy[layerPath] = gdbPath; } // Raster layers with non-deterministic names in analysis and layers folders string strWeaselFolder = oAoi.FilePath + @"\layers"; string strGdbPath = GeodatabaseTools.GetGeodatabasePath(oAoi.FilePath, GeodatabaseNames.Layers, true); IList <string> lstRasters = await GeneralTools.GetLayersInFolderAsync(strWeaselFolder, "Raster Dataset"); foreach (var item in lstRasters) { rastersToCopy[strWeaselFolder + "\\" + item] = strGdbPath + item; } strWeaselFolder = oAoi.FilePath + @"\analysis"; strGdbPath = GeodatabaseTools.GetGeodatabasePath(oAoi.FilePath, GeodatabaseNames.Analysis, true); lstRasters = await GeneralTools.GetLayersInFolderAsync(strWeaselFolder, "Raster Dataset"); foreach (var item in lstRasters) { rastersToCopy[strWeaselFolder + "\\" + item] = strGdbPath + item; } // Use Geoprocessor to copy the files int errorCount = 0; foreach (var key in rastersToCopy.Keys) { IGPResult gpResult = await QueuedTask.Run(() => { var environments = Geoprocessing.MakeEnvironmentArray(workspace: oAoi.FilePath, cellSize: "MINOF"); var parameters = Geoprocessing.MakeValueArray(key, rastersToCopy[key]); return(Geoprocessing.ExecuteToolAsync("CopyRaster_management", parameters, null, CancelableProgressor.None, GPExecuteToolFlags.AddToHistory)); }); if (gpResult.IsFailed) { Module1.Current.ModuleLogManager.LogError(nameof(RunImplAsync), "Failed to copy raster " + key + "!"); errorCount++; } } Module1.Current.ModuleLogManager.LogDebug(nameof(RunImplAsync), "Raster copy completed with " + errorCount + " errors."); // Assemble a dictionary with vectors we want to copy IDictionary <string, string> vectorsToCopy = GetDictOfReqWeaselVectors(oAoi.FilePath, fType); // Check for an optional vector lstTest.Clear(); lstTest.Add(oAoi.FilePath + @"\unsnappedpp.shp"); existingLayers = await GeneralTools.ShapefilesExistAsync(lstTest); if (existingLayers.Count > 0) { vectorsToCopy[oAoi.FilePath + @"\unsnappedpp.shp"] = aoiGdb + Constants.FILE_UNSNAPPED_POURPOINT; } // Vector layers with non-deterministic names in analysis and layers folders strWeaselFolder = oAoi.FilePath + @"\layers"; strGdbPath = GeodatabaseTools.GetGeodatabasePath(oAoi.FilePath, GeodatabaseNames.Layers, true); IList <string> lstVectors = await GeneralTools.GetLayersInFolderAsync(strWeaselFolder, "Shapefile"); foreach (var item in lstVectors) { string noExtension = Path.GetFileNameWithoutExtension(item); vectorsToCopy[strWeaselFolder + "\\" + item] = strGdbPath + noExtension; } strWeaselFolder = oAoi.FilePath + @"\analysis"; strGdbPath = GeodatabaseTools.GetGeodatabasePath(oAoi.FilePath, GeodatabaseNames.Analysis, true); lstVectors = await GeneralTools.GetLayersInFolderAsync(strWeaselFolder, "Shapefile"); foreach (var item in lstVectors) { string noExtension = Path.GetFileNameWithoutExtension(item); vectorsToCopy[strWeaselFolder + "\\" + item] = strGdbPath + noExtension; } // Use Geoprocessor to copy the files errorCount = 0; foreach (var entry in vectorsToCopy) { string strKey = entry.Key; } string strTempFile = Path.GetFileName("tmpVector"); string strDirectory = ""; foreach (var entry in vectorsToCopy) { IGPResult gpResult = await QueuedTask.Run(() => { var environments = Geoprocessing.MakeEnvironmentArray(workspace: oAoi.FilePath); strDirectory = Path.GetDirectoryName(entry.Value); var parameters = Geoprocessing.MakeValueArray(entry.Key, strDirectory, strTempFile); return(Geoprocessing.ExecuteToolAsync("FeatureClassToFeatureClass_conversion", parameters, null, CancelableProgressor.None, GPExecuteToolFlags.AddToHistory)); }); if (gpResult.IsFailed) { Module1.Current.ModuleLogManager.LogError(nameof(RunImplAsync), "Failed to convert vector " + entry.Key + "!"); errorCount++; } else { //There is a bug with using converted shapefiles in Pro; We need to rename the converted file //so that functions related to extent work gpResult = await QueuedTask.Run(() => { var environments = Geoprocessing.MakeEnvironmentArray(workspace: oAoi.FilePath); strDirectory = Path.GetDirectoryName(entry.Value); var parameters = Geoprocessing.MakeValueArray(strDirectory + "\\" + strTempFile, entry.Value); return(Geoprocessing.ExecuteToolAsync("Rename_management", parameters, null, CancelableProgressor.None, GPExecuteToolFlags.AddToHistory)); }); if (gpResult.IsFailed) { Module1.Current.ModuleLogManager.LogError(nameof(RunImplAsync), "Failed to copy feature class " + entry.Key + "!"); errorCount++; } } } Module1.Current.ModuleLogManager.LogDebug(nameof(RunImplAsync), "Vector copy completed with " + errorCount + " errors."); } } MessageBox.Show("Done!"); }
private async Task GenerateLayersAsync(bool calculateRepresented, bool calculatePrism, bool calculateAspect, bool calculateSlope, bool calculateElevation, bool bufferRoads, bool extractPublicLand, bool extractBelowTreeline, bool elevPrecipCorr, bool calculateSitesZones, bool calculateSweDelta, bool calculatePrecipContrib, bool winterPrecip) { try { if (String.IsNullOrEmpty(Module1.Current.Aoi.Name)) { MessageBox.Show("No AOI selected for analysis !!", "BAGIS-PRO"); return; } if (calculateRepresented == false && calculatePrism == false && calculateAspect == false && calculateSlope == false && calculateElevation == false && bufferRoads == false && extractPublicLand == false && extractBelowTreeline == false && elevPrecipCorr == false && calculateSitesZones == false && calculateSweDelta == false && calculatePrecipContrib == false && winterPrecip == false) { MessageBox.Show("No layers selected to generate !!", "BAGIS-PRO"); return; } var cmdShowHistory = FrameworkApplication.GetPlugInWrapper("esri_geoprocessing_showToolHistory") as ICommand; if (cmdShowHistory != null) { if (cmdShowHistory.CanExecute(null)) { cmdShowHistory.Execute(null); } } var layersPane = (DockAnalysisLayersViewModel)FrameworkApplication.DockPaneManager.Find("bagis_pro_DockAnalysisLayers"); BA_ReturnCode success = BA_ReturnCode.Success; if (calculateRepresented) { double siteBufferDistanceMiles = (double)Module1.Current.BatchToolSettings.SiteBufferDistMiles; double siteElevRangeFeet = (double)Module1.Current.BatchToolSettings.SiteElevRangeFeet; success = await AnalysisTools.GenerateSiteLayersAsync(siteBufferDistanceMiles, siteElevRangeFeet); if (success == BA_ReturnCode.Success) { layersPane.RepresentedArea_Checked = false; } } if (calculatePrism) { string strLayer = GeodatabaseTools.GetGeodatabasePath(Module1.Current.Aoi.FilePath, GeodatabaseNames.Prism, true) + Path.GetFileName((string)Module1.Current.BatchToolSettings.AoiPrecipFile); string strZonesRaster = GeodatabaseTools.GetGeodatabasePath(Module1.Current.Aoi.FilePath, GeodatabaseNames.Analysis, true) + Constants.FILE_PRECIP_ZONE; success = await AnalysisTools.CalculatePrecipitationZonesAsync(strLayer, strZonesRaster); if (success == BA_ReturnCode.Success) { layersPane.PrismZones_Checked = false; } } if (calculateAspect) { success = await AnalysisTools.CalculateAspectZonesAsync(); if (success == BA_ReturnCode.Success) { layersPane.AspectZones_Checked = false; } } if (calculateSlope) { string strLayer = GeodatabaseTools.GetGeodatabasePath(Module1.Current.Aoi.FilePath, GeodatabaseNames.Surfaces, true) + Constants.FILE_SLOPE; string strZonesRaster = GeodatabaseTools.GetGeodatabasePath(Module1.Current.Aoi.FilePath, GeodatabaseNames.Analysis, true) + Constants.FILE_SLOPE_ZONE; string strMaskPath = GeodatabaseTools.GetGeodatabasePath(Module1.Current.Aoi.FilePath, GeodatabaseNames.Aoi, true) + Constants.FILE_AOI_BUFFERED_VECTOR; IList <BA_Objects.Interval> lstInterval = AnalysisTools.GetSlopeClasses(); success = await AnalysisTools.CalculateZonesAsync(Module1.Current.Aoi.FilePath, strLayer, lstInterval, strZonesRaster, strMaskPath, "SLOPE"); if (success == BA_ReturnCode.Success) { layersPane.SlopeZones_Checked = false; } } if (calculateElevation) { success = await AnalysisTools.CalculateElevationZonesAsync(Module1.Current.Aoi.FilePath); if (success == BA_ReturnCode.Success) { layersPane.ElevationZones_Checked = false; } } if (calculateSitesZones) { Uri uri = new Uri(GeodatabaseTools.GetGeodatabasePath(Module1.Current.Aoi.FilePath, GeodatabaseNames.Layers)); bool hasSnotel = await GeodatabaseTools.FeatureClassExistsAsync(uri, Constants.FILE_SNOTEL); bool hasSnowCourse = await GeodatabaseTools.FeatureClassExistsAsync(uri, Constants.FILE_SNOW_COURSE); if (hasSnotel || hasSnowCourse) { success = await AnalysisTools.CalculateSitesZonesAsync(Module1.Current.Aoi.FilePath, hasSnotel, hasSnowCourse); } else { MessageBox.Show("No sites found to create sites zone layers!!", "BAGIS-PRO"); } if (success == BA_ReturnCode.Success) { layersPane.SitesZones_Checked = false; } } bool bSkipPotentialSites = false; if (bufferRoads) { Uri uri = new Uri(GeodatabaseTools.GetGeodatabasePath(Module1.Current.Aoi.FilePath, GeodatabaseNames.Layers)); bool bExists = await GeodatabaseTools.FeatureClassExistsAsync(uri, Constants.FILE_ROADS); if (!bExists) { MessageBox.Show("The roads layer is missing. Clip the roads layer before creating the roads analysis layer!!", "BAGIS-PRO"); Module1.Current.ModuleLogManager.LogDebug(nameof(GenerateLayersAsync), "Unable to buffer roads because fs_roads layer does not exist. Process stopped!!"); return; } // This could come from the UI eventually string strDistance = Module1.Current.BatchToolSettings.RoadsAnalysisBufferDistance + " " + Module1.Current.BatchToolSettings.RoadsAnalysisBufferUnits; success = await AnalysisTools.GenerateProximityRoadsLayerAsync(uri, strDistance); if (success == BA_ReturnCode.Success) { layersPane.Roads_Checked = false; } else { bSkipPotentialSites = true; // may skip combined potential sites because this layer couldn't be generated } } if (extractPublicLand) { success = await AnalysisTools.GetFederalNonWildernessLandsAsync(Module1.Current.Aoi.FilePath); if (success == BA_ReturnCode.Success) { layersPane.FederalLand_Checked = false; } else { bSkipPotentialSites = true; // may skip combined potential sites because this layer couldn't be generated } } if (extractBelowTreeline) { success = await AnalysisTools.ExtractBelowTreelineAsync(Module1.Current.Aoi.FilePath); if (success == BA_ReturnCode.Success) { layersPane.BelowTreeline_Checked = false; } else { bSkipPotentialSites = true; // may skip combined potential sites because this layer couldn't be generated } } if (!bSkipPotentialSites) { if (bufferRoads || extractPublicLand || extractBelowTreeline) { // if either of the underlying layers changed, we need to recalculate the // potential sites layer success = await AnalysisTools.CalculatePotentialSitesAreaAsync(Module1.Current.Aoi.FilePath); if (success != BA_ReturnCode.Success) { MessageBox.Show("An error occurred while generating the potential sites layer!!", "BAGIS-PRO"); } } } if (elevPrecipCorr == true) { string strLayer = GeodatabaseTools.GetGeodatabasePath(Module1.Current.Aoi.FilePath, GeodatabaseNames.Prism, true) + Path.GetFileName((string)Module1.Current.BatchToolSettings.AoiPrecipFile); Uri uriPrism = new Uri(GeodatabaseTools.GetGeodatabasePath(Module1.Current.Aoi.FilePath, GeodatabaseNames.Prism)); success = await AnalysisTools.CalculateElevPrecipCorrAsync(Module1.Current.Aoi.FilePath, uriPrism, Path.GetFileName((string)Module1.Current.BatchToolSettings.AoiPrecipFile)); if (success == BA_ReturnCode.Success) { layersPane.ElevPrecipCorr_Checked = false; } } if (calculateSweDelta == true) { success = await AnalysisTools.CalculateSWEDeltaAsync(Module1.Current.Aoi.FilePath); if (success == BA_ReturnCode.Success) { layersPane.SWE_Delta_Checked = false; } } if (calculatePrecipContrib == true) { success = await AnalysisTools.CalculatePrecipitationContributionAsync(Module1.Current.Aoi.FilePath, -1); success = await AnalysisTools.CalculateQuarterlyPrecipitationAsync(Module1.Current.Aoi); if (success == BA_ReturnCode.Success) { layersPane.Precip_Contrib_Checked = false; } } if (winterPrecip == true) { success = await AnalysisTools.GenerateWinterPrecipitationLayerAsync(Module1.Current.Aoi); if (success == BA_ReturnCode.Success) { layersPane.Winter_Precip_Checked = false; } } if (success == BA_ReturnCode.Success) { MessageBox.Show("Analysis layers generated !!", "BAGIS-PRO"); } } catch (Exception ex) { Module1.Current.ModuleLogManager.LogError(nameof(GenerateLayersAsync), "Exception: " + ex.Message); } }
public static async Task DisplayMaps(string strAoiPath) { BA_Objects.Aoi oAoi = Module1.Current.Aoi; if (String.IsNullOrEmpty(oAoi.Name)) { if (System.IO.Directory.Exists(strAoiPath)) { // Initialize AOI object oAoi = new BA_Objects.Aoi("animas_AOI_prms", strAoiPath); // Store current AOI in Module1 Module1.Current.Aoi = oAoi; } else { ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("!!Please set an AOI before testing the maps", "BAGIS Pro"); } } Map oMap = await MapTools.SetDefaultMapNameAsync(Constants.MAPS_DEFAULT_MAP_NAME); if (oMap != null) { if (oMap.Layers.Count() > 0) { string strMessage = "Adding the maps to the display will overwrite the current arrangement of data layers. " + "This action cannot be undone." + System.Environment.NewLine + "Do you wish to continue ?"; MessageBoxResult oRes = ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show(strMessage, "BAGIS", MessageBoxButton.YesNo); if (oRes != MessageBoxResult.Yes) { return; } } Layout layout = await MapTools.GetDefaultLayoutAsync(Constants.MAPS_DEFAULT_LAYOUT_NAME); if (layout != null) { bool bFoundIt = false; //A layout view may exist but it may not be active //Iterate through each pane in the application and check to see if the layout is already open and if so, activate it foreach (var pane in ProApp.Panes) { if (!(pane is ILayoutPane layoutPane)) //if not a layout view, continue to the next pane { continue; } if (layoutPane.LayoutView.Layout == layout) //if there is a match, activate the view { (layoutPane as Pane).Activate(); bFoundIt = true; } } if (!bFoundIt) { ILayoutPane iNewLayoutPane = await ProApp.Panes.CreateLayoutPaneAsync(layout); //GUI thread } await MapTools.SetDefaultMapFrameDimensionAsync(Constants.MAPS_DEFAULT_MAP_FRAME_NAME, layout, oMap, 1.0, 2.0, 7.5, 9.0); //remove existing layers from map frame await MapTools.RemoveLayersfromMapFrame(); //add aoi boundary to map and zoom to layer string strPath = GeodatabaseTools.GetGeodatabasePath(oAoi.FilePath, GeodatabaseNames.Aoi, true) + Constants.FILE_AOI_VECTOR; Uri aoiUri = new Uri(strPath); await MapTools.AddAoiBoundaryToMapAsync(aoiUri, Constants.MAPS_AOI_BOUNDARY); //add Snotel Represented Area Layer strPath = GeodatabaseTools.GetGeodatabasePath(oAoi.FilePath, GeodatabaseNames.Analysis, true) + Constants.FILE_SNOTEL_REPRESENTED; Uri uri = new Uri(strPath); CIMColor fillColor = CIMColor.CreateRGBColor(255, 0, 0, 50); //Red with 30% transparency BA_ReturnCode success = await MapTools.AddPolygonLayerAsync(uri, fillColor, false, Constants.MAPS_SNOTEL_REPRESENTED); if (success.Equals(BA_ReturnCode.Success)) { Module1.ToggleState("MapButtonPalette_BtnSnotel_State"); } // add aoi streams layer strPath = GeodatabaseTools.GetGeodatabasePath(oAoi.FilePath, GeodatabaseNames.Layers, true) + Constants.FILE_STREAMS; uri = new Uri(strPath); await MapTools.AddLineLayerAsync(uri, Constants.MAPS_STREAMS, ColorFactory.Instance.BlueRGB); // add Snotel Layer strPath = GeodatabaseTools.GetGeodatabasePath(oAoi.FilePath, GeodatabaseNames.Layers, true) + Constants.FILE_SNOTEL; uri = new Uri(strPath); success = await MapTools.AddPointMarkersAsync(uri, Constants.MAPS_SNOTEL, ColorFactory.Instance.BlueRGB, SimpleMarkerStyle.X, 16); if (success == BA_ReturnCode.Success) { Module1.Current.AoiHasSnotel = true; } // add Snow Course Layer strPath = GeodatabaseTools.GetGeodatabasePath(oAoi.FilePath, GeodatabaseNames.Layers, true) + Constants.FILE_SNOW_COURSE; uri = new Uri(strPath); success = await MapTools.AddPointMarkersAsync(uri, Constants.MAPS_SNOW_COURSE, CIMColor.CreateRGBColor(0, 255, 255), SimpleMarkerStyle.Star, 16); if (success == BA_ReturnCode.Success) { Module1.Current.AoiHasSnowCourse = true; } // add hillshade layer strPath = GeodatabaseTools.GetGeodatabasePath(oAoi.FilePath, GeodatabaseNames.Surfaces, true) + Constants.FILE_HILLSHADE; uri = new Uri(strPath); await MapTools.DisplayRasterAsync(uri, Constants.MAPS_HILLSHADE, 0); // add elev zones layer strPath = GeodatabaseTools.GetGeodatabasePath(oAoi.FilePath, GeodatabaseNames.Analysis, true) + Constants.FILE_ELEV_ZONE; uri = new Uri(strPath); await MapTools.DisplayRasterWithSymbolAsync(uri, Constants.MAPS_ELEV_ZONE, "ArcGIS Colors", "Elevation #2", "NAME", 30, true); Module1.ToggleState("MapButtonPalette_BtnElevation_State"); // add slope zones layer strPath = GeodatabaseTools.GetGeodatabasePath(oAoi.FilePath, GeodatabaseNames.Analysis, true) + Constants.FILE_SLOPE_ZONE; uri = new Uri(strPath); await MapTools.DisplayRasterWithSymbolAsync(uri, Constants.MAPS_SLOPE_ZONE, "ArcGIS Colors", "Slope", "NAME", 30, false); Module1.ToggleState("MapButtonPalette_BtnSlope_State"); // add aspect zones layer strPath = GeodatabaseTools.GetGeodatabasePath(oAoi.FilePath, GeodatabaseNames.Analysis, true) + Constants.FILE_ASPECT_ZONE; uri = new Uri(strPath); await MapTools.DisplayRasterWithSymbolAsync(uri, Constants.MAPS_ASPECT_ZONE, "ArcGIS Colors", "Aspect", "NAME", 30, false); Module1.ToggleState("MapButtonPalette_BtnAspect_State"); // create map elements await MapTools.AddMapElements(Constants.MAPS_DEFAULT_LAYOUT_NAME, "ArcGIS Colors", "1.5 Point"); await MapTools.DisplayNorthArrowAsync(layout, Constants.MAPS_DEFAULT_MAP_FRAME_NAME); await MapTools.DisplayScaleBarAsync(layout, Constants.MAPS_DEFAULT_MAP_FRAME_NAME); // update map elements for default map (elevation) BA_Objects.MapDefinition defaultMap = MapTools.LoadMapDefinition(BagisMapType.ELEVATION); await MapTools.UpdateMapElementsAsync(layout, Module1.Current.Aoi.Name.ToUpper(), defaultMap); await MapTools.UpdateLegendAsync(layout, defaultMap); //zoom to aoi boundary layer double bufferFactor = 1.1; bool bZoomed = await MapTools.ZoomToExtentAsync(aoiUri, bufferFactor); } } }
protected async override void OnClick() { ReportType rType = ReportType.Watershed; try { string outputDirectory = Module1.Current.Aoi.FilePath + "\\" + Constants.FOLDER_MAP_PACKAGE; if (!System.IO.Directory.Exists(outputDirectory)) { System.IO.Directory.CreateDirectory(outputDirectory); } // Delete any old PDF files //string[] arrFilesToDelete = Constants.FILES_EXPORT_WATERSHED_PDF.Concat(Constants.FILES_EXPORT_SITE_ANALYSIS_PDF).ToArray(); foreach (var item in Constants.FILES_EXPORT_WATERSHED_PDF) { string strPath = GeneralTools.GetFullPdfFileName(item); if (System.IO.File.Exists(strPath)) { try { System.IO.File.Delete(strPath); } catch (Exception) { System.Windows.MessageBoxResult res = MessageBox.Show("Unable to delete file before creating new pdf. Do you want to close the file and try again?", "BAGIS-PRO", System.Windows.MessageBoxButton.YesNo); if (res == System.Windows.MessageBoxResult.Yes) { return; } } } } Layout oLayout = await MapTools.GetDefaultLayoutAsync(Constants.MAPS_DEFAULT_LAYOUT_NAME); // Load the maps if they aren't in the viewer already BA_ReturnCode success = BA_ReturnCode.Success; string strTestState = Constants.STATES_WATERSHED_MAP_BUTTONS[0]; //if (rType.Equals(ReportType.SiteAnalysis)) //{ // strTestState = Constants.STATES_SITE_ANALYSIS_MAP_BUTTONS[0]; //} if (!FrameworkApplication.State.Contains(strTestState)) { success = await MapTools.DisplayMaps(Module1.Current.Aoi.FilePath, oLayout, true); success = await MapTools.DisplayLegendAsync(Constants.MAPS_DEFAULT_MAP_FRAME_NAME, oLayout, "ArcGIS Colors", "1.5 Point", true); } if (success != BA_ReturnCode.Success) { MessageBox.Show("Unable to load maps. The map package cannot be exported!!", "BAGIS-PRO"); return; } if (oLayout != null) { bool bFoundIt = false; //A layout view may exist but it may not be active //Iterate through each pane in the application and check to see if the layout is already open and if so, activate it foreach (var pane in FrameworkApplication.Panes) { if (!(pane is ILayoutPane layoutPane)) //if not a layout view, continue to the next pane { continue; } if (layoutPane.LayoutView != null && layoutPane.LayoutView.Layout == oLayout) //if there is a match, activate the view { (layoutPane as Pane).Activate(); bFoundIt = true; } } if (!bFoundIt) { ILayoutPane iNewLayoutPane = await FrameworkApplication.Panes.CreateLayoutPaneAsync(oLayout); //GUI thread (iNewLayoutPane as Pane).Activate(); } } success = await MapTools.PublishMapsAsync(rType); // export the maps to pdf if (success != BA_ReturnCode.Success) { MessageBox.Show("An error occurred while generating the maps!!", "BAGIS-PRO"); } // Only run critical precip for watershed report if (rType.Equals(ReportType.Watershed)) { success = await GeneralTools.GenerateTablesAsync(false); // export the tables to pdf if (success != BA_ReturnCode.Success) { MessageBox.Show("An error occurred while generating the Excel tables!!", "BAGIS-PRO"); } else { // Generate the crtical precip map; It has to follow the tables Uri uriAnalysis = new Uri(GeodatabaseTools.GetGeodatabasePath(Module1.Current.Aoi.FilePath, GeodatabaseNames.Analysis)); if (await GeodatabaseTools.FeatureClassExistsAsync(uriAnalysis, Constants.FILE_CRITICAL_PRECIP_ZONE)) { success = await MapTools.DisplayCriticalPrecipitationZonesMap(uriAnalysis); string strButtonState = "MapButtonPalette_BtnCriticalPrecipZone_State"; if (success.Equals(BA_ReturnCode.Success)) { Module1.ActivateState(strButtonState); } int foundS1 = strButtonState.IndexOf("_State"); string strMapButton = strButtonState.Remove(foundS1); ICommand cmd = FrameworkApplication.GetPlugInWrapper(strMapButton) as ICommand; Module1.Current.ModuleLogManager.LogDebug(nameof(OnClick), "About to toggle map button " + strMapButton); if ((cmd != null)) { do { await Task.Delay(TimeSpan.FromSeconds(0.4)); // build in delay until the command can execute }while (!cmd.CanExecute(null)); cmd.Execute(null); } do { await Task.Delay(TimeSpan.FromSeconds(0.4)); // build in delay so maps can load }while (Module1.Current.MapFinishedLoading == false); success = await GeneralTools.ExportMapToPdfAsync(150); // export map to pdf if (success == BA_ReturnCode.Success) { // append the map and chart together for posting IList <string> lstToConcat = new List <string>(); lstToConcat.Add(GeneralTools.GetFullPdfFileName(Constants.FILE_EXPORT_MAP_CRITICAL_PRECIPITATION_ZONES_PDF)); lstToConcat.Add(GeneralTools.GetFullPdfFileName(Constants.FILE_EXPORT_TABLE_PRECIP_REPRESENT_PDF)); success = GeneralTools.ConcatenatePagesInPdf(GeneralTools.GetFullPdfFileName(Constants.FILE_EXPORT_CRITICAL_PRECIPITATION_ZONES_PDF), lstToConcat); } else { MessageBox.Show("Unable to generate critical precipitation zones map!!", "BAGIS-PRO"); } } } } success = await GeneralTools.GenerateSitesTableAsync(Module1.Current.Aoi); string strPublisher = (string)Module1.Current.BatchToolSettings.Publisher; success = await GeneralTools.GenerateMapsTitlePageAsync(rType, strPublisher, ""); string outputPath = GeneralTools.GetFullPdfFileName(Constants.FILE_EXPORT_WATERSHED_REPORT_PDF); //if (rType.Equals(ReportType.SiteAnalysis)) //{ // outputPath = GeneralTools.GetFullPdfFileName(Constants.FILE_EXPORT_SITE_ANALYSIS_REPORT_PDF); //} GeneralTools.PublishFullPdfDocument(outputPath, rType); // Put it all together into a single pdf document MessageBox.Show("Map package exported to " + outputPath + "!!", "BAGIS-PRO"); } catch (Exception e) { MessageBox.Show("An error occurred while trying to export the maps!! " + e.Message, "BAGIS PRO"); } }