예제 #1
0
        public async void OnMeasurementChanged(object sender, IEventArgs <IFeatureCollection> args)
        {
            InUpdateMeasurementMode.WaitOne(MaxWaitTime);
            InUpdateMeasurementMode.Reset();
            FeatureCollection = args.Value;
            IStreetSmartAPI api = sender as IStreetSmartAPI;

            foreach (IFeature feature in FeatureCollection.Features)
            {
                if (feature.Properties is IMeasurementProperties properties)
                {
                    Measurement measurement;

                    if (Count == 0)
                    {
                        measurement = new Measurement(properties, feature.Geometry, DrawPoint, api)
                        {
                            ObjectId    = _lastObjectId,
                            VectorLayer = _lastVectorLayer
                        };

                        Add(properties.Id, measurement);
                        measurement.Open();

                        if (_lastSketch)
                        {
                            measurement.SetSketch();
                        }
                    }
                    else
                    {
                        measurement = this.ElementAt(0).Value;
                    }

                    measurement.ObservationLines = properties.ObservationLines;

                    if (measurement.Properties == null)
                    {
                        measurement.Properties = properties;
                    }

                    if (measurement.Geometry == null)
                    {
                        measurement.Geometry = feature.Geometry;
                    }

                    if (!measurement.UpdateMeasurement)
                    {
                        measurement.UpdateMeasurement = true;
                        IGeometry geometry = feature.Geometry;
                        StreetSmartGeometryType geometryType = geometry.Type;

                        switch (geometryType)
                        {
                        case StreetSmartGeometryType.Point:
                            await RemoveLineStringPoints(measurement);
                            await RemovePolygonPoints(measurement);

                            if (geometry is IPoint pointDst)
                            {
                                if (measurement.Count >= 1 && measurement[0].Point != null &&
                                    (pointDst.X == null || pointDst.Y == null) && measurement.MeasurementId != properties.Id)
                                {
                                    MapView  mapView        = MapView.Active;
                                    Geometry geometrySketch = await mapView.GetCurrentSketchAsync();

                                    await measurement.VectorLayer.AddFeatureAsync(geometrySketch);

                                    await mapView.ClearSketchAsync();

                                    measurement[0].Dispose();
                                }
                                else
                                {
                                    measurement.MeasurementId = properties.Id;
                                    await measurement.UpdatePointAsync(0, feature);

                                    measurement.Geometry = geometry;
                                }
                            }

                            await measurement.UpdateMap();

                            break;

                        case StreetSmartGeometryType.LineString:
                            await RemovePointPoints(measurement);
                            await RemovePolygonPoints(measurement);

                            if (geometry is ILineString lineDst)
                            {
                                if (measurement.Count >= 1 && measurement[0].Point != null &&
                                    lineDst.Count == 0 && measurement.MeasurementId != properties.Id)
                                {
                                    MapView  mapView        = MapView.Active;
                                    Geometry geometrySketch = await mapView.GetCurrentSketchAsync();

                                    await measurement.VectorLayer.AddFeatureAsync(geometrySketch);

                                    await mapView.ClearSketchAsync();

                                    if (geometrySketch != null)
                                    {
                                        await QueuedTask.Run(() =>
                                        {
                                            List <MapPoint> points = new List <MapPoint>();
                                            Polyline line          = PolylineBuilder.CreatePolyline(points, geometrySketch.SpatialReference);
                                            mapView.SetCurrentSketchAsync(line);
                                        });
                                    }
                                }
                                else if (measurement.Geometry is ILineString lineSrc)
                                {
                                    measurement.MeasurementId = properties.Id;

                                    for (int i = 0; i < Math.Max(lineDst.Count, lineSrc.Count); i++)
                                    {
                                        measurement.RemoveObservations(i, feature);

                                        if (lineSrc.Count > i && lineDst.Count > i)
                                        {
                                            await measurement.UpdatePointAsync(i, feature);
                                        }
                                        else if (lineSrc.Count <= i && lineDst.Count > i)
                                        {
                                            measurement.AddPoint(lineSrc.Count);
                                            await measurement.UpdatePointAsync(i, feature);
                                        }
                                        else if (lineSrc.Count > i && lineDst.Count <= i)
                                        {
                                            await measurement.RemovePoint(i);

                                            await measurement.UpdatePointAsync(Math.Min(i, lineDst.Count - 1), feature);
                                        }
                                    }

                                    measurement.Geometry = geometry;
                                    await measurement.UpdateMap();
                                }
                                else
                                {
                                    measurement.MeasurementId = properties.Id;

                                    for (int i = 0; i < lineDst.Count; i++)
                                    {
                                        measurement.AddPoint(i);
                                        await measurement.UpdatePointAsync(i, feature);
                                    }

                                    measurement.Geometry = geometry;
                                    await measurement.UpdateMap();
                                }
                            }

                            break;

                        case StreetSmartGeometryType.Polygon:
                            await RemovePointPoints(measurement);
                            await RemoveLineStringPoints(measurement);

                            if (geometry is IPolygon polyDst)
                            {
                                if (measurement.Count >= 1 && measurement[measurement.ElementAt(0).Key].Point != null &&
                                    polyDst[0].Count == 0 && measurement.MeasurementId != properties.Id)
                                {
                                    MapView  mapView        = MapView.Active;
                                    Geometry geometrySketch = await mapView.GetCurrentSketchAsync();

                                    await measurement.VectorLayer.AddFeatureAsync(geometrySketch);

                                    await mapView.ClearSketchAsync();

                                    if (geometrySketch != null)
                                    {
                                        await QueuedTask.Run(() =>
                                        {
                                            List <MapPoint> points = new List <MapPoint>();
                                            Polygon polygon        = PolygonBuilder.CreatePolygon(points, geometrySketch.SpatialReference);
                                            mapView.SetCurrentSketchAsync(polygon);
                                        });
                                    }
                                }
                                else if (measurement.Geometry is IPolygon polySrc)
                                {
                                    measurement.MeasurementId = properties.Id;
                                    int polySrcCount = polySrc[0].Count;
                                    int pylyDstCount = polyDst[0].Count;

                                    for (int i = 0; i < Math.Max(pylyDstCount, polySrcCount); i++)
                                    {
                                        measurement.RemoveObservations(i, feature);
                                        if (polySrcCount > i && pylyDstCount > i)
                                        {
                                            await measurement.UpdatePointAsync(i, feature);
                                        }
                                        else if (polySrcCount <= i && pylyDstCount > i)
                                        {
                                            measurement.AddPoint(polySrcCount++);
                                            await measurement.UpdatePointAsync(i, feature);
                                        }
                                        else if (polySrcCount > i && pylyDstCount <= i)
                                        {
                                            await measurement.RemovePoint(i);

                                            polySrcCount--;
                                            await measurement.UpdatePointAsync(Math.Min(i, pylyDstCount - 1), feature);
                                        }
                                    }

                                    measurement.Geometry = geometry;
                                    await measurement.UpdateMap();
                                }
                                else
                                {
                                    measurement.MeasurementId = properties.Id;
                                    int pylyDstCount = polyDst[0].Count;

                                    for (int i = 0; i < pylyDstCount; i++)
                                    {
                                        measurement.AddPoint(i);
                                        await measurement.UpdatePointAsync(i, feature);
                                    }

                                    measurement.Geometry = geometry;
                                    await measurement.UpdateMap();
                                }
                            }

                            break;
                        }

                        measurement.UpdateMeasurement = false;
                    }
                    else
                    {
                        measurement.DoChange = true;
                    }
                }
            }

            if (FeatureCollection.Type == FeatureType.Unknown)
            {
                if (Count == 1)
                {
                    Measurement measurement = this.ElementAt(0).Value;
                    measurement.Close();
                    await FrameworkApplication.SetCurrentToolAsync(string.Empty);
                }
            }

            InUpdateMeasurementMode.Set();
        }
 private void OnMapToolCommand(object obj)
 {
     FrameworkApplication.SetCurrentToolAsync("ProAppCoordConversionModule_CoordinateMapTool");
 }
예제 #3
0
 protected override void OnClick()
 {
     FrameworkApplication.SetCurrentToolAsync("esri_mapping_selectByRectangleTool");
 }
 protected override void OnClick()
 {
     FrameworkApplication.SetCurrentToolAsync("esri_mapping_exploreTool");
 }
 /// <summary>
 /// Handler for the activate tool command
 /// Sets the current tool
 /// </summary>
 /// <param name="obj"></param>
 internal virtual void OnActivateToolCommand(object obj)
 {
     FrameworkApplication.SetCurrentToolAsync("ProAppVisibilityModule_MapTool");
 }
예제 #6
0
        private async Task SetAsCurrentToolAsync()
        {
            await FrameworkApplication.SetCurrentToolAsync("ProAppCoordConversionModule_CoordinateMapTool");

            RaisePropertyChanged(() => IsToolActive);
        }
예제 #7
0
        public void Snippets()
        {
            #region Execute a command
            IPlugInWrapper wrapper = FrameworkApplication.GetPlugInWrapper("esri_editing_ShowAttributes");
            var            command = wrapper as ICommand; // tool and command(Button) supports this

            if ((command != null) && command.CanExecute(null))
            {
                command.Execute(null);
            }

            #endregion

            #region Set the current tool

            // use SetCurrentToolAsync
            FrameworkApplication.SetCurrentToolAsync("esri_mapping_selectByRectangleTool");

            // or use ICommand.Execute
            ICommand cmd = FrameworkApplication.GetPlugInWrapper("esri_mapping_selectByRectangleTool") as ICommand;
            if ((cmd != null) && cmd.CanExecute(null))
            {
                cmd.Execute(null);
            }
            #endregion

            #region Activate a tab
            FrameworkApplication.ActivateTab("esri_mapping_insertTab");
            #endregion

            bool activate = true;
            #region Activate/Deactivate a state - to modify a condition

            // Define the condition in the DAML file based on the state
            if (activate)
            {
                FrameworkApplication.State.Activate("someState");
            }
            else
            {
                FrameworkApplication.State.Deactivate("someState");
            }
            #endregion

            #region Determine if the application is busy

            // The application is considered busy if a task is currently running on the main worker thread or any
            // pane or dock pane reports that it is busy or intiializing.

            // Many Pro styles (such as Esri_SimpleButton) ensure that a button is disabled when FrameworkApplication.IsBusy is true
            // You would use this property to bind to the IsEnabled property of a control (such as a listbox) on a dockpane or pane in order
            // to disable it from user interaction while the application is busy.
            bool isbusy = FrameworkApplication.IsBusy;
            #endregion

            #region Get the Application main window
            System.Windows.Window window = FrameworkApplication.Current.MainWindow;

            // center it
            Rect rect = System.Windows.SystemParameters.WorkArea;
            FrameworkApplication.Current.MainWindow.Left = rect.Left + (rect.Width - FrameworkApplication.Current.MainWindow.ActualWidth) / 2;
            FrameworkApplication.Current.MainWindow.Top  = rect.Top + (rect.Height - FrameworkApplication.Current.MainWindow.ActualHeight) / 2;

            #endregion

            #region Close ArcGIS Pro
            FrameworkApplication.Close();
            #endregion

            #region Get ArcGIS Pro version
            //"GetEntryAssembly" should be ArcGISPro.exe
            string version = System.Reflection.Assembly.GetEntryAssembly().GetName().Version.ToString();
            #endregion
            #region Close a specific pane

            string _viewPaneID = "my pane"; //DAML ID of your pane
            //You could have multiple instances (InstanceIDs) of your pane.
            //So you can iterate through the Panes to get "your" panes only
            IList <uint> myPaneInstanceIDs = new List <uint>();
            foreach (Pane pane in FrameworkApplication.Panes)
            {
                if (pane.ContentID == _viewPaneID)
                {
                    myPaneInstanceIDs.Add(pane.InstanceID); //InstanceID of your pane, could be multiple, so build the collection
                }
            }
            foreach (var instanceID in myPaneInstanceIDs) //close each of "your" panes.
            {
                FrameworkApplication.Panes.ClosePane(instanceID);
            }
            #endregion

            #region Activate a pane
            var mapPanes = ProApp.Panes.OfType <IMapPane>();
            foreach (Pane pane in mapPanes)
            {
                if (pane.Caption == "MyMap")
                {
                    pane.Activate();
                    break;
                }
            }
            #endregion
        }
예제 #8
0
        public void LoadedItemInfo(object sender, RoutedEventArgs e)
        {
            object context = Utils.Utils.GetDataContext(sender);

            // If this page is declared in the window,
            // the intial data context will be NULL.
            //
            // A second pass, will set this context
            // and the control will work...
            if (null == context)
            {
                return;
            }

            var mdModule = FrameworkApplication.FindModule("esri_metadata_module") as IMetadataEditorHost;

            if (mdModule != null)
            {
                mdModule.SetIsLoadingPage(this, true);
            }

            // Cache this context for the unload event.
            // When unload is called, the context is already cleared
            this.cachedContext = context;
            this.cachedRTB     = sender as RichTextBox;

            // load it
            Utils.Utils.LoadRichTextbox(sender, context);

            // add me, so I can be called later
            if (mdModule != null)
            {
                mdModule.AddCommitPage(this);
            }

            var editorPage = this;

            // update XML on lost focus
            this.LostFocus += new RoutedEventHandler(delegate(object sender2, RoutedEventArgs rea)
            {
                Utils.Utils.UnLoadRichTextbox(editorPage.cachedRTB, editorPage.cachedContext, true);

                // create event and raise it
                MetadataRuleSet rules = editorPage.cachedRTB.GetValue(MetadataRules.RulesProperty) as MetadataRuleSet;
                if (null != rules)
                {
                    rules.RunRules(editorPage.cachedRTB, null);
                }

                SetBorderOnError();
            });

            // create event and raise it
            {
                Utils.Utils.UnLoadRichTextbox(editorPage.cachedRTB, editorPage.cachedContext, true);

                // create event and raise it
                MetadataRuleSet rules = editorPage.cachedRTB.GetValue(MetadataRules.RulesProperty) as MetadataRuleSet;
                if (null != rules)
                {
                    rules.RunRules(editorPage.cachedRTB, null);
                }
            }

            SetBorderOnError();

            if (mdModule != null)
            {
                mdModule.SetIsLoadingPage(this, false);
            }
        }
 /// <summary>
 /// Handler for the activate tool command
 /// Sets the current tool
 /// </summary>
 /// <param name="obj"></param>
 internal virtual void OnActivateToolCommand(object obj)
 {
     FrameworkApplication.SetCurrentToolAsync(VisibilityMapTool.ToolId);
 }
 public void DeactivateSelf()
 {
     FrameworkApplication.SetCurrentToolAsync(ExploreTool);
 }
 public ExampleCustomizationFilter()
 {
     //TODO - register the Customization Filter
     FrameworkApplication.RegisterCustomizationFilter(this);
 }
예제 #12
0
 private void ActivateDrawFeatureSketchTool(object parameter)
 {
     FrameworkApplication.SetCurrentToolAsync("ProSymbolEditor_DrawFeatureSketchTool");
     AddToMapToolEnabled = true;
 }
예제 #13
0
 public ExampleCustomizationFilter()
 {
     FrameworkApplication.RegisterCustomizationFilter(this);
 }
예제 #14
0
        /// <summary>
        /// load form
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        //public void LoadContacts(object sender, RoutedEventArgs e)
        //{
        //    ReloadContacts();
        //}

        public void LoadContacts(object sender, RoutedEventArgs e)
        {
            #region Load EME Configuration File
            // Load emeConfig.xml
            try { _emeConfig.Load(_filePathEme + "emeConfig.xml"); }
            catch (System.IO.FileNotFoundException)
            {
                _emeConfig.LoadXml(
                    "<?xml version=\"1.0\" standalone=\"yes\"?> \n" +
                    "<emeConfig> \n" +
                    "  <xs:schema id=\"emeConfig\" xmlns=\"\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\" xmlns:msdata=\"urn:schemas-microsoft-com:xml-msdata\"> \n" +
                    "    <xs:element name=\"emeControl\"> \n" +
                    "      <xs:complexType> \n" +
                    "        <xs:sequence> \n" +
                    "          <xs:element name=\"controlName\" type=\"xs:string\"/> \n" +
                    "          <xs:element name=\"param\" maxOccurs=\"10\" minOccurs=\"0\"> \n" +
                    "            <xs:complexType mixed=\"true\"> \n" +
                    "              <xs:attribute name=\"label\" type=\"xs:string\" use=\"required\" /> \n" +
                    "            </xs:complexType> \n" +
                    "          </xs:element> \n" +
                    "          <xs:element name=\"url\" maxOccurs=\"10\" minOccurs=\"0\"> \n" +
                    "            <xs:complexType mixed=\"true\"> \n" +
                    "              <xs:attribute name=\"label\" type=\"xs:string\" use=\"required\" /> \n" +
                    "            </xs:complexType> \n" +
                    "          </xs:element> \n" +
                    "          <xs:element name=\"date\" maxOccurs=\"10\" minOccurs=\"0\"> \n" +
                    "            <xs:complexType mixed=\"true\"> \n" +
                    "              <xs:attribute name=\"label\" type=\"xs:string\" use=\"required\" /> \n" +
                    "            </xs:complexType> \n" +
                    "          </xs:element> \n" +
                    "          <xs:element name=\"required\" maxOccurs=\"10\" minOccurs=\"0\"> \n" +
                    "            <xs:complexType mixed=\"true\"> \n" +
                    "              <xs:attribute name=\"label\" type=\"xs:string\" use=\"required\" /> \n" +
                    "            </xs:complexType> \n" +
                    "          </xs:element> \n" +
                    "        </xs:sequence> \n" +
                    "      </xs:complexType> \n" +
                    "    </xs:element> \n" +
                    "    <xs:element name=\"emeControl\"> \n" +
                    "      <xs:complexType> \n" +
                    "        <xs:choice minOccurs=\"0\" maxOccurs=\"unbounded\"> \n" +
                    "          <xs:element ref=\"emeControl\" /> \n" +
                    "        </xs:choice> \n" +
                    "      </xs:complexType> \n" +
                    "    </xs:element> \n" +
                    "  </xs:schema> \n" +
                    "  <emeControl> \n" +
                    "    <controlName>Contacts Manager</controlName> \n" +
                    "    <param label=\"Contacts Source\">EPA Contact</param> \n" +
                    "    <url label=\"Contacts URL\">https://edg.epa.gov/EME/contacts.xml</url> \n" +
                    "    <date label=\"Local Cache\">2010-06-27T12:00:00-07:00</date> \n" +
                    "  </emeControl> \n" +
                    "</emeConfig>");
            }
            #endregion

            var      directoryName = _emeConfig.SelectSingleNode("//emeControl[controlName[contains(. , 'Contacts Manager')]]/param").InnerText;
            var      directoryUrl  = _emeConfig.SelectSingleNode("//emeControl[controlName[contains(. , 'Contacts Manager')]]/url").InnerText;
            TimeSpan syncAge       = ((DateTime.Now) - (DateTime.Parse(_emeConfig.SelectSingleNode("//emeControl[controlName[contains(. , 'Contacts Manager')]]/date").InnerText)));
            var      syncDays      = syncAge.ToString("d'd 'h'h 'm'm 's's'");

            // Check to see if local file is older than 12 hours:
            //bool dbExpired = syncAge > (new TimeSpan(0, 12, 0, 0));
            // Check if contacts.bak exists
            // this is created during LoadList. If LoadList crashes, then contacts.xml will be corrupted
            // replace contacts.xml with contacts.bak
            if (File.Exists(_filePathEsri + "contacts.bak"))
            {
                File.Delete(_filePathEsri + "contacts.xml");
                File.Copy(_filePathEsri + "contacts.bak", _filePathEsri + "contacts.xml");
                File.Delete(_filePathEsri + "contacts.bak");
            }
            //HttpWebRequest request = (HttpWebRequest)WebRequest.Create(directoryUrl);
            ////request.Timeout = 15000;
            //request.Timeout = 25000;
            //request.Method = "HEAD"; //test URL without downloading the content

            //if (syncAge > (new TimeSpan(0, 12, 0, 0)))
            //{
            //    //MessageBoxResult fileCheck = MessageBox.Show("Local cache is " + syncDays + " old.\nLoading contacts from \"" + directoryName + "\"\n (" + directoryUrl + ")", "EME Contacts Manager", MessageBoxButton.OK, MessageBoxImage.Information);
            //    try
            //    {
            //        using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
            //        {
            //            if (response.StatusCode.ToString() == "OK")
            //            {
            //                // Return contacts.xml Date Modified
            //                try { _contactsWEB.Load(directoryUrl); }
            //                catch (System.IO.FileNotFoundException)
            //                {
            //                    _contactsWEB.LoadXml(
            //                    "<contacts> \n" +
            //                    "  <contact> \n" +
            //                    "    <editorSource></editorSource> \n" +
            //                    "    <editorDigest></editorDigest> \n" +
            //                    "    <rpIndName></rpIndName> \n" +
            //                    "    <rpOrgName></rpOrgName> \n" +
            //                    "    <rpPosName></rpPosName> \n" +
            //                    "    <editorSave></editorSave> \n" +
            //                    "    <rpCntInfo></rpCntInfo> \n" +
            //                    "  </contact> \n" +
            //                    "</contacts>");
            //                }
            //                _contactsWEB.Save(_filePathEme + "contacts.xml");

            //                // Add timestamp to config file
            //                _emeConfig.SelectSingleNode("//emeControl[controlName[contains(. , 'Contacts Manager')]]/date").InnerText = DateTime.Now.ToString("o");
            //                _emeConfig.Save(_filePathEme + "emeConfig.xml");
            //            }
            //            else
            //            {
            //                MessageBoxResult webResponse = MessageBox.Show("Error loading contacts from " + directoryUrl + "." + "\n" + "EME contacts will be loaded from local cache.", "EME 5.0 Web Request", MessageBoxButton.OK, MessageBoxImage.Information);
            //            }
            //        }
            //    }
            //    catch (Exception weberror)
            //    {
            //        {
            //            MessageBoxResult result = MessageBox.Show(weberror.Message + "\n" + "EME contacts will be loaded from local cache.", "EME 5.0 Web Request", MessageBoxButton.OK, MessageBoxImage.Warning);
            //        }
            //    }
            //}
            //else
            //{
            //    //MessageBoxResult fileCheck = MessageBox.Show("Local cache is " + syncDays + " old.\nContacts will be loaded from local cache.", "EME Contacts Manager", MessageBoxButton.OK, MessageBoxImage.Information);
            //}

            try { _contactsBAK.Load(_filePathEsri + "contacts.xml"); }
            catch (System.IO.FileNotFoundException)
            {
                _contactsBAK.LoadXml(
                    "<contacts> \n" +
                    "  <contact> \n" +
                    "    <editorSource></editorSource> \n" +
                    "    <editorDigest></editorDigest> \n" +
                    "    <rpIndName></rpIndName> \n" +
                    "    <rpOrgName></rpOrgName> \n" +
                    "    <rpPosName></rpPosName> \n" +
                    "    <editorSave></editorSave> \n" +
                    "    <rpCntInfo></rpCntInfo> \n" +
                    "  </contact> \n" +
                    "</contacts>");
            }
            // save backup of user contacts.xml
            _contactsBAK.Save(_filePathEsri + "contacts.bak");

            try { _contactsEsri.Load(_filePathEsri + "contacts.xml"); }
            catch (System.IO.FileNotFoundException)
            {
                _contactsEsri.LoadXml(
                    "<contacts> \n" +
                    "  <contact> \n" +
                    "    <editorSource></editorSource> \n" +
                    "    <editorDigest></editorDigest> \n" +
                    "    <rpIndName></rpIndName> \n" +
                    "    <rpOrgName></rpOrgName> \n" +
                    "    <rpPosName></rpPosName> \n" +
                    "    <editorSave></editorSave> \n" +
                    "    <rpCntInfo></rpCntInfo> \n" +
                    "  </contact> \n" +
                    "</contacts>");
            }

            try { _contactsEpa.Load(_filePathEme + "contacts.xml"); }
            catch (System.IO.FileNotFoundException)
            {
                _contactsEpa.LoadXml(
                    "<contacts> \n" +
                    "  <contact> \n" +
                    "    <editorSource></editorSource> \n" +
                    "    <editorDigest></editorDigest> \n" +
                    "    <rpIndName></rpIndName> \n" +
                    "    <rpOrgName></rpOrgName> \n" +
                    "    <rpPosName></rpPosName> \n" +
                    "    <editorSave></editorSave> \n" +
                    "    <rpCntInfo></rpCntInfo> \n" +
                    "  </contact> \n" +
                    "</contacts>");
            }

            // new document
            XmlDocument cloneMerge = new XmlDocument();

            #region This method took 8.66 seconds to load contacts
            //try { cloneMerge.Load(_filePathEsri + "contacts.cfg"); }
            //catch
            //{
            //    MessageBoxResult contactsTest = MessageBox.Show("Could not load contacts.cfg", "EME Contacts Manager", MessageBoxButton.OK, MessageBoxImage.Information);
            //}
            #endregion

            #region This takes 8.00 seconds to load
            XmlNode contactsNodeMerge = cloneMerge.CreateElement("contacts");
            cloneMerge.AppendChild(contactsNodeMerge);

            // Populate contacts list with local contacts.xml and Agency Directory
            var           listEsri = _contactsEsri.SelectNodes("//contact");
            var           listEpa  = _contactsEpa.SelectNodes("//contact");
            StringBuilder sb2      = new StringBuilder();
            foreach (XmlNode child in listEsri)
            {
                // remove editorSource
                XmlNode e1 = child.SelectSingleNode("editorSource");
                if (null != e1)
                {
                    e1.InnerText = "My Contacts";
                }

                e1 = child.SelectSingleNode("editorDigest");
                if (null != e1)
                {
                    string digest = Utils.Utils.GeneratePartyKey(child);
                    e1.InnerText = digest;
                }

                // save back localuser editorSource
                sb2.Append("<contact>");
                sb2.Append(child.InnerXml);
                sb2.Append("</contact>");
            }
            foreach (XmlNode child in listEpa)
            {
                // remove editorSource
                XmlNode e2 = child.SelectSingleNode("editorSource");
                if (null != e2)
                {
                    e2.InnerText = directoryName;
                }

                e2 = child.SelectSingleNode("editorDigest");
                if (null != e2)
                {
                    string digest = Utils.Utils.GeneratePartyKey(child);
                    e2.InnerText = digest;
                }

                e2 = child.SelectSingleNode("editorSave");
                if (null != e2)
                {
                    e2.InnerText = "False";
                }

                // save back epa editorSource
                sb2.Append("<contact>");
                sb2.Append(child.InnerXml);
                sb2.Append("</contact>");
            }

            // append to clone
            contactsNodeMerge.InnerXml = sb2.ToString();
            #endregion

            // save to file
            cloneMerge.Save(Utils.Utils.GetContactsFileLocation());
            //cloneMerge.Save(_filePathEsri + "contacts.cfg");


            // generate contact list
            contactsListBox.ItemsSource = Utils.Utils.GenerateContactsList(_contactsDoc, this.DataContext);

            // restore contacts.xml to original state
            _contactsBAK.Save(Utils.Utils.GetContactsFileLocation());

            // contacts.xml restored successfully. It is now safe to delete BAK file.
            if (File.Exists(_filePathEsri + "contacts.bak"))
            {
                File.Delete(_filePathEsri + "contacts.bak");
            }

            //_contactsDoc = new XmlDocument();
            //contactsListBox.ItemsSource = Utils.Utils.GenerateContactsList(_contactsDoc, this.DataContext);

            var mdModule = FrameworkApplication.FindModule("esri_metadata_module") as IMetadataEditorHost;
            if (mdModule != null)
            {
                mdModule.AddCommitPage(this);
            }
        }
예제 #15
0
        /// <summary>
        /// Apply the layout to the diagram layer
        /// </summary>
        /// <param name="diagramLayer">Diagram Layer</param>
        public void Apply(DiagramLayer diagramLayer)
        {
            if (diagramLayer == null)
            {
                return;
            }
            try
            {
                QueuedTask.Run(() =>
                {
                    NetworkDiagram Diagram = diagramLayer.GetNetworkDiagram();

                    var selection = MapView.Active.Map.GetSelection();
                    if (selection != null && selection.Count > 0)
                    {
                        List <long> JunctionObjectIDs  = new List <long>();
                        List <long> ContainerObjectIDs = new List <long>();
                        List <long> EdgeObjectIDs      = new List <long>();

                        foreach (var v in selection.ToDictionary())
                        {
                            if (v.Key is FeatureLayer layer)
                            {
                                if (layer.ShapeType == ArcGIS.Core.CIM.esriGeometryType.esriGeometryPoint)
                                {
                                    JunctionObjectIDs.AddRange(v.Value);
                                }
                                else if (layer.ShapeType == ArcGIS.Core.CIM.esriGeometryType.esriGeometryPolygon)
                                {
                                    ContainerObjectIDs.AddRange(v.Value);
                                }
                                else if (layer.ShapeType == ArcGIS.Core.CIM.esriGeometryType.esriGeometryPolyline)
                                {
                                    EdgeObjectIDs.AddRange(v.Value);
                                }
                            }
                        }

                        Diagram.ApplyLayout(layoutParameters, new DiagramElementObjectIDs
                        {
                            ContainerObjectIDs = ContainerObjectIDs,
                            JunctionObjectIDs  = JunctionObjectIDs,
                            EdgeObjectIDs      = EdgeObjectIDs
                        }, ArcGIS.Core.Data.ServiceSynchronizationType.Synchronous);
                    }
                    else
                    {
                        Diagram.ApplyLayout(layoutParameters, ArcGIS.Core.Data.ServiceSynchronizationType.Synchronous);
                    }

                    MapView.Active.Redraw(true);
                    MapView.Active.ZoomTo(Diagram.GetDiagramInfo().DiagramExtent.Expand(1.05, 1.05, true));

                    if (FrameworkApplication.CurrentTool.Contains("_networkdiagrams_"))
                    {
                        FrameworkApplication.SetCurrentToolAsync("esri_mapping_exploreTool");
                    }
                });
            }
            catch (Exception ex)
            {
                ShowException(ex);
            }
        }
        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!");
        }
예제 #17
0
 private void StartSAAnalysis()
 {
     _previousActiveTool = FrameworkApplication.CurrentTool;
     FrameworkApplication.SetCurrentToolAsync(MPDSATool.TOOL_ID);
 }
예제 #18
0
        private async Task <ArcGIS.Core.Geometry.GeometryEngine.ProximityResult> ComputeDistanceToGeometryAsync(MapPoint clickPoint, FeatureLayer targetLayer, int hitNumber, double searchDistance)
        {
            FeatureClass featureClass = await targetLayer.GetTableAsync() as FeatureClass;

            Geometry        searchBuffer = null;
            List <Geometry> geometryList = new List <Geometry>();

            double closestDistance = double.MaxValue;

            ArcGIS.Core.Geometry.GeometryEngine.ProximityResult clickResult = null;
            MapPoint closestPoint = null;
            bool     foundFeatureAndComputedDistance = false;


            await QueuingTaskFactory.StartNew(() =>
            {
                var classDefinition = featureClass.Definition as FeatureClassDefinition;

                searchBuffer = GeometryEngine.Project(GeometryEngine.Buffer(clickPoint, searchDistance), classDefinition.SpatialReference);

                SpatialQueryFilter spatialFilter = new SpatialQueryFilter()
                {
                    FilterGeometry      = searchBuffer,
                    SpatialRelationship = SpatialRelationship.EnvelopeIntersects
                };

                RowCursor featureCursor = featureClass.Search(spatialFilter, false);

                while (featureCursor.MoveNext())
                {
                    var feature = featureCursor.Current as Feature;

                    geometryList.Add(feature.Shape);
                }

                clickPoint = GeometryEngine.Project(clickPoint, classDefinition.SpatialReference) as MapPoint;

                foreach (var geometry in geometryList)
                {
                    var geoResult = GeometryEngine.NearestBoundaryPoint(geometry, clickPoint, searchDistance);
                    if (geoResult.Distance < closestDistance)
                    {
                        closestDistance = geoResult.Distance;
                        clickResult     = geoResult;
                        foundFeatureAndComputedDistance = true;
                    }
                }
            });

            if (foundFeatureAndComputedDistance)
            {
                DockPane dockPane = FrameworkApplication.FindDockPane("GeometrySamples_ClosestGeometryPane");
                if (dockPane == null)
                {
                    return(new ArcGIS.Core.Geometry.GeometryEngine.ProximityResult());
                }

                DistancePaneViewModel cgVM = dockPane as DistancePaneViewModel;
                cgVM.DistanceDisplayUnit = _linearDisplayUnit;
                cgVM.ClickResult         = clickResult;
            }

            return(clickResult);
        }
예제 #19
0
        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);
            }
        }
예제 #20
0
        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);
            }
        }
예제 #21
0
파일: Main.cs 프로젝트: agrc/TrailsAddin
        public async void AddNewRoute(string routeName)
        {
            var map = MapView.Active.Map;

            if (!BuildOnSelect && SegmentsLayer.SelectionCount == 0)
            {
                MessageBox.Show("At least one segment must be selected!");
                return;
            }

            await QueuedTask.Run(async() =>
            {
                using (var routesTable = RoutesStandaloneTable.GetTable())
                    using (var routeToHeadsTable = RouteToTrailheadsTable.GetTable())
                        using (var routeToSegmentsTable = RouteToTrailSegmentsTable.GetTable())
                            using (var routeBuf = routesTable.CreateRowBuffer())
                                using (var tempSegsFeatureClass = TempSegmentsLayer.GetFeatureClass())
                                {
                                    var namesFilter = new QueryFilter()
                                    {
                                        WhereClause = $"Upper({RouteName}) = '{routeName.ToUpper().Replace("'", "''")}'"
                                    };
                                    using (var namesCursor = RoutesStandaloneTable.Search(namesFilter))
                                    {
                                        if (namesCursor.MoveNext())
                                        {
                                            MessageBox.Show($"There is already a route named: {routeName}!");
                                            return;
                                        }
                                    }

                                    var operation  = new EditOperation();
                                    operation.Name = "Create new trails route: " + routeName;

                                    await EnsureIDsForSelectedAsync(operation);
                                    await operation.ExecuteAsync();

                                    if (!operation.IsSucceeded)
                                    {
                                        MessageBox.Show(operation.ErrorMessage);
                                        return;
                                    }

                                    var operation2 = operation.CreateChainedOperation();

                                    operation2.Callback(context =>
                                    {
                                        // create route row
                                        routeBuf[RouteName] = routeName;
                                        routeBuf[RouteID]   = $"{{{Guid.NewGuid()}}}";
                                        using (var routeRow = routesTable.CreateRow(routeBuf))
                                            using (var headsCursor = HeadsLayer.GetSelection().Search(null, false))
                                                using (var segmentCursor = SegmentsLayer.GetSelection().Search((QueryFilter)null, false))
                                                {
                                                    var segments = new List <string>();
                                                    var parts    = new Dictionary <int, List <Polyline> >();
                                                    if (BuildOnSelect)
                                                    {
                                                        // get segments from TempSegments layer
                                                        bool atLeastOne = false;
                                                        using (var tempSegsCursor = tempSegsFeatureClass.Search(null, false))
                                                        {
                                                            while (tempSegsCursor.MoveNext())
                                                            {
                                                                atLeastOne = true;
                                                                var row    = tempSegsCursor.Current;

                                                                var partNum = int.Parse(row[RoutePart].ToString());
                                                                var segID   = (string)row[USNG_SEG];
                                                                CreateRoutePart(segID, (string)routeRow[RouteID], partNum, context, routeToSegmentsTable);

                                                                segments.Add(segID);

                                                                var geometry = (Polyline)row["SHAPE"];
                                                                if (parts.ContainsKey(partNum))
                                                                {
                                                                    parts[partNum].Add(geometry);
                                                                }
                                                                else
                                                                {
                                                                    parts[partNum] = new List <Polyline>()
                                                                    {
                                                                        geometry
                                                                    };
                                                                }
                                                            }
                                                            Reset();
                                                            tempSegsFeatureClass.DeleteRows(new QueryFilter());
                                                            context.Invalidate(tempSegsFeatureClass);
                                                        }

                                                        if (!atLeastOne)
                                                        {
                                                            context.Abort("There must be at least one feature in TempSegments!");
                                                        }
                                                    }
                                                    else
                                                    {
                                                        //get segments from selected features
                                                        while (segmentCursor.MoveNext())
                                                        {
                                                            var segRow = segmentCursor.Current;

                                                            var segID         = (string)segRow[USNG_SEG];
                                                            const int partNum = 1;
                                                            CreateRoutePart(segID, routeRow[RouteID], partNum, context, routeToSegmentsTable);

                                                            segments.Add(segID);

                                                            var geometry = (Polyline)segRow["SHAPE"];
                                                            if (parts.ContainsKey(partNum))
                                                            {
                                                                parts[partNum].Add(geometry);
                                                            }
                                                            else
                                                            {
                                                                parts[partNum] = new List <Polyline>()
                                                                {
                                                                    geometry
                                                                };
                                                            }
                                                        }
                                                    }

                                                    if (segments.Count > 1 && !ValidateConnectivity(parts))
                                                    {
                                                        context.Abort("Not all segments are connected!");
                                                        return;
                                                    }

                                                    // trailhead
                                                    if (HeadsLayer.SelectionCount > 0)
                                                    {
                                                        while (headsCursor.MoveNext())
                                                        {
                                                            using (var headBuffer = routeToHeadsTable.CreateRowBuffer())
                                                            {
                                                                headBuffer[RouteID] = (string)routeRow[RouteID];
                                                                headBuffer[USNG_TH] = headsCursor.Current[USNG_TH];

                                                                using (var headRow = routeToHeadsTable.CreateRow(headBuffer))
                                                                {
                                                                    context.Invalidate(headRow);
                                                                }
                                                            }
                                                        }
                                                    }

                                                    context.Invalidate(routeRow);
                                                }
                                    }, routesTable, routeToSegmentsTable, routeToHeadsTable, tempSegsFeatureClass);

                                    await operation2.ExecuteAsync();
                                    if (operation2.IsSucceeded)
                                    {
                                        FrameworkApplication.AddNotification(new Notification
                                        {
                                            Title    = FrameworkApplication.Title,
                                            Message  = $"Route: \"{routeName}\" added successfully!",
                                            ImageUrl = "pack://application:,,,/ArcGIS.Desktop.Resources;component/Images/GenericCheckMark32.png"
                                        });

                                        SegmentsLayer.ClearSelection();
                                        HeadsLayer.ClearSelection();
                                    }
                                    else
                                    {
                                        MessageBox.Show(operation2.ErrorMessage);
                                    }
                                }
            });
        }
        protected override void OnClick()
        {
            FrameworkApplication.RemoveNotification(this);

            ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("hello world");
        }
 protected override void OnClick()
 {
     FrameworkApplication.OpenBackstage("ControlStyles_Backstage_BackstageStyling");
 }
예제 #24
0
 private void ConfigWindow_Closing(object sender, CancelEventArgs e)
 {
     FrameworkApplication.SetCurrentToolAsync(null);
 }
예제 #25
0
        public void DetermineStyle(object sender, RoutedEventArgs e)
        {
            // get current profile
            string currentProfile = null;

            var mdModule = FrameworkApplication.FindModule("esri_metadata_module") as IMetadataEditorHost;

            if (mdModule != null)
            {
                currentProfile = mdModule.GetCurrentProfile(sender as DependencyObject);
            }

            if (null == currentProfile)
            {
                return;
            }

            // only list
            //
            if (null != _onlyList && 0 < _onlyList.Length)
            {
                string[] parts = _onlyList.Split(',');
                bool     avail = false;
                foreach (string part in parts)
                {
                    if (currentProfile.Equals(part, StringComparison.InvariantCultureIgnoreCase))
                    {
                        avail = true;
                        break;
                    }
                }

                // if there were profiles listed in the 'only' list
                // and the current profile was NOT on that list
                // then don't show the control
                if (!avail)
                {
                    this.Visibility = Visibility.Collapsed;
                    return;
                }
            }

            // so far, this will be visible...

            // except list
            //
            if (null != _exceptList && 0 < _exceptList.Length)
            {
                string[] parts = _exceptList.Split(',');
                foreach (string part in parts)
                {
                    if (currentProfile.Equals(part, StringComparison.InvariantCultureIgnoreCase))
                    {
                        this.Visibility = Visibility.Collapsed;
                        return;
                    }
                }
            }

            // show it
            this.Visibility = Visibility.Visible;
        }
예제 #26
0
 public CapabilitiesView()
 {
     InitializeComponent();
     MenuBurgerButton.PopupMenu = FrameworkApplication.CreateContextMenu(MenuId);
     DataContextChanged        += OnDataContextChanged;
 }
예제 #27
0
 /// <summary>
 /// Unregister for command filtering
 /// </summary>
 public void UnRegister()
 {
     FrameworkApplication.UnregisterCustomizationFilter(this);
 }
        public async void CalculateVolume()
        {
            // Update the viewmodel with values
            await FrameworkApplication.SetCurrentToolAsync("esri_mapping_exploreTool");

            // Check for an active mapview
            if (MapView.Active == null)
            {
                ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("No MapView currently active. Exiting...", "Info");
                return;
            }

            // Prompt before proceeding with calculation work
            var response = ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("Save edits and calculate volume on selected features?", "Calculate Volume", System.Windows.MessageBoxButton.YesNo, System.Windows.MessageBoxImage.Question);

            if (response == MessageBoxResult.No)
            {
                return;
            }

            // Save edits for reading by GP Tool
            await Project.Current.SaveEditsAsync();

            try
            {
                await QueuedTask.Run((Func <Task>)(async() =>
                {
                    var featLayer = MapView.Active.Map.FindLayers("Clip_Polygon_Asphalt").FirstOrDefault() as FeatureLayer;

                    // Get the selected records, and check/exit if there are none:
                    var featSelectionOIDs = featLayer.GetSelection().GetObjectIDs();
                    if (featSelectionOIDs.Count == 0)
                    {
                        ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("No records selected for layer, " + featLayer.Name + ". Exiting...", "Info");
                        return;
                    }

                    // Ensure value for reference plane direction combobox
                    else if (SceneCalcVM.ReferencePlaneDirection == string.Empty)
                    {
                        ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("Choose the reference plane direction for volume calculation. Exiting...", "Value Needed");
                        return;
                    }

                    // Ensure there is a valid reference plane height/elevation value for all selected records
                    RowCursor cursorPolygons = featLayer.GetSelection().Search(null);
                    while (cursorPolygons.MoveNext())
                    {
                        using (Row currentRow = cursorPolygons.Current)
                        {
                            // Get values for dockpane
                            if (currentRow["PlaneHeight"] == null || Convert.ToDouble(currentRow["PlaneHeight"]) == 0)
                            {
                                string currentObjectID = Convert.ToString(currentRow["ObjectID"]);
                                ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("Empty or invalid Plane Height value for polygon ObjectID: " + currentObjectID + ". Exiting...", "Value Needed");
                                return;
                            }
                        }
                    }

                    // Get the name of the attribute to update, and the value to set:
                    double refPlaneElevation = SceneCalcVM.ReferencePlaneElevation;
                    string refPlaneDirection = SceneCalcVM.ReferencePlaneDirection;

                    // Start progress dialog
                    var progDialog = new ProgressDialog("Calculating Volume");
                    var progSource = new ProgressorSource(progDialog);
                    progDialog.Show();

                    // Prepare for run of GP tool -- Get the path to the LAS point layer
                    string surfaceLASDataset = "Asphalt3D_132_point_cloud.las";
                    var inspector            = new ArcGIS.Desktop.Editing.Attributes.Inspector(true);
                    inspector.Load(featLayer, featSelectionOIDs);
                    inspector["PlaneDirection"]    = refPlaneDirection;
                    inspector["DateOfCapture"]     = DateTime.Today;
                    inspector["ElevationMeshFile"] = "Asphalt3D_132_3d_mesh.slpk";
                    inspector["PointCloudFile"]    = surfaceLASDataset;

                    var editOp  = new EditOperation();
                    editOp.Name = "Edit " + featLayer.Name + ", " + Convert.ToString(featSelectionOIDs.Count) + " records.";
                    editOp.Modify(inspector);
                    await editOp.ExecuteAsync();
                    await Project.Current.SaveEditsAsync();

                    // Get the path to the layer's feature class
                    string infc = featLayer.Name;
                    // Place parameters into an array
                    var parameters = Geoprocessing.MakeValueArray(surfaceLASDataset, infc, "PlaneHeight", refPlaneDirection);
                    // Place environment settings in an array, in this case, OK to over-write
                    var environments = Geoprocessing.MakeEnvironmentArray(overwriteoutput: true);
                    // Execute the GP tool with parameters
                    var gpResult = await Geoprocessing.ExecuteToolAsync("PolygonVolume_3d", parameters, environments);
                    // Save edits again
                    await Project.Current.SaveEditsAsync();

                    // var selFeatures = featLayer.GetSelection().GetCount();
                    RowCursor cursorPolygons2 = featLayer.GetSelection().Search(null);

                    double totalVolumeValue  = 0;
                    double totalAreaValue    = 0;
                    double totalWeightInTons = 0;
                    double currentVolume;
                    double currentSArea;
                    double currentWeightInTons;
                    long currentOID;

                    while (cursorPolygons2.MoveNext())
                    {
                        using (Row currentRow = cursorPolygons2.Current)
                        {
                            // Get values for dockpane
                            currentOID = currentRow.GetObjectID();
                            // Convert volume in cubic meters from source data to cubic feet:
                            currentVolume = Convert.ToDouble(currentRow["Volume"]) * 35.3147;
                            // Convert surface area value from square meters from source data to square feet:
                            currentSArea = Convert.ToDouble(currentRow["SArea"]) * 10.7639;
                            // Calculate estimated weight in tons = (volume in square foot * 103.7 pounds per square foot) / 2000 pounds per ton
                            currentWeightInTons = (currentVolume * 103.7) / 2000;

                            // Update the new cubic feet and square feet values for the feature:
                            inspector.Load(featLayer, currentOID);
                            inspector["Volume"]          = currentVolume;
                            inspector["SArea"]           = currentSArea;
                            inspector["EstWeightInTons"] = currentWeightInTons;
                            await inspector.ApplyAsync();

                            // Combine values for display of total volume and surface area values in the dockpane:
                            totalVolumeValue  += currentVolume;
                            totalAreaValue    += currentSArea;
                            totalWeightInTons += currentWeightInTons;
                        }
                    }

                    // Apply the values and refresh selection update
                    await Project.Current.SaveEditsAsync();
                    FeatureSelectionChanged();
                    // Close progress dialog
                    progDialog.Hide();
                    progDialog.Dispose();
                }));
            }
            catch (Exception exc)
            {
                // Catch any exception found and display a message box.
                ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("Exception caught while trying to perform update: " + exc.Message);
                return;
            }
        }
예제 #29
0
        /// <summary>
        /// Get the ICommand interface for a given typed DAML representation like for example: DAML.Button.esri_core_showProjectDockPane
        /// or the string itself as for example "esri_core_contentsDockPane"
        /// </summary>
        /// <exception cref="ArgumentException">Thrown when the specified commandId parameter didn't yield a valid ICommand</exception>
        /// <param name="commandId">Id of the command: use the typed DAML representation if possible to prevent errors i.e. DAML.Button.esri_core_showProjectDockPane or the string itself "esri_core_contentsDockPane" </param>
        /// <returns>ICommand if an ICommand interface exists otherwise an exception is thrown</returns>
        internal static ICommand GetICommand(string commandId)
        {
            var iCommand = FrameworkApplication.GetPlugInWrapper(commandId) as ICommand;

            return(iCommand);
        }
예제 #30
0
 protected override void OnClick()
 {
     FrameworkApplication.ActivateTab("EMEProToolkit_Tab1");
 }