Beispiel #1
0
        private void GenerateContours()
        {
            // Show the progress bar
            MyLoadingIndicator.Visibility      = Visibility.Visible;
            MyLoadingIndicator.IsIndeterminate = false;

            // Create the geoprocessing parameters
            GeoprocessingParameters gpParams = new GeoprocessingParameters(GeoprocessingExecutionType.AsynchronousSubmit);

            // Add the interval parameter to the geoprocessing parameters
            gpParams.Inputs["ContourInterval"] = new GeoprocessingDouble(MyContourSlider.Value);

            // Create the job
            _gpJob = _gpTask.CreateJob(gpParams);

            // Update the UI when job progress changes
            _gpJob.ProgressChanged += (sender, args) =>
            {
                Dispatcher.Invoke(() => { MyLoadingIndicator.Value = _gpJob.Progress; });
            };

            // Be notified when the task completes (or other change happens)
            _gpJob.JobChanged += GpJobOnJobChanged;

            // Start the job
            _gpJob.Start();
        }
        private async void btnGeoProcess_Click(object sender, RoutedEventArgs e)
        {
            //Get the local proprocessing package
            _gpService = new LocalGeoprocessingService(@"C:\Temp\tile_package_service.gpkx", GeoprocessingServiceType.AsynchronousSubmit);
            // Start the local service.
            try
            {
                await _gpService.StartAsync();
            }
            catch (Exception exe)
            {
                MessageBox.Show(exe.Message);
            }

            // If the service is started, get the URL for the specific geoprocessing tool.
            string gpSvcUrl = _gpService.Url.AbsoluteUri + "/TP_Model";

            // Create the geoprocessing task with the URL.
            _gpTask = await GeoprocessingTask.CreateAsync(new Uri(gpSvcUrl));

            GeoprocessingParameters gpParams = new GeoprocessingParameters(GeoprocessingExecutionType.AsynchronousSubmit);

            //******************************************
            //***This is the bit I think is wrong how do I pass a map obkect as a gpstring parameter?****
            //*********************************************
            gpParams.Inputs["Input_Map"] = new GeoprocessingString(MyMapView.Name);
            _gpJob             = _gpTask.CreateJob(gpParams);
            _gpJob.JobChanged += GeoprocessingJob_JobChanged;
            _gpJob.Start();
        }
        private async void OnAnalyzeHotspotsClicked(object sender, RoutedEventArgs e)
        {
            // Show the busyOverlay indication
            ShowBusyOverlay();

            // Get the 'from' and 'to' dates from the date pickers for the geoprocessing analysis
            var myFromDate = FromDate.SelectedDate.Value;
            var myToDate   = ToDate.SelectedDate.Value;


            // The end date must be at least one day after the start date
            if (myToDate <= myFromDate.AddDays(1))
            {
                // Show error message
                MessageBox.Show(
                    "Please select valid time range. There has to be at least one day in between To and From dates.",
                    "Invalid date range");

                // Remove the busyOverlay
                ShowBusyOverlay(false);
                return;
            }

            // Create the parameters that are passed to the used geoprocessing task
            GeoprocessingParameters myHotspotParameters = new GeoprocessingParameters(GeoprocessingExecutionType.AsynchronousSubmit);

            // Construct the date query
            var myQueryString = string.Format("(\"DATE\" > date '{0} 00:00:00' AND \"DATE\" < date '{1} 00:00:00')",
                                              myFromDate.ToString("yyyy-MM-dd"),
                                              myToDate.ToString("yyyy-MM-dd"));

            // Add the query that contains the date range used in the analysis
            myHotspotParameters.Inputs.Add("Query", new GeoprocessingString(myQueryString));

            // Create job that handles the communication between the application and the geoprocessing task
            _hotspotJob             = _hotspotTask.CreateJob(myHotspotParameters);
            _hotspotJob.JobChanged += _hotspotJob_JobChanged;
            //Start the Geoprocessing job
            _hotspotJob.Start();

            try
            {
                // Execute the geoprocessing analysis and wait for the results
                GeoprocessingResult myAnalysisResult = await _hotspotJob.GetResultAsync();

                // Add results to a map using map server from a geoprocessing task
                // Load to get access to full extent
                await myAnalysisResult.MapImageLayer.LoadAsync();

                // Add the analysis layer to the map view
                MyMapView.Map.OperationalLayers.Add(myAnalysisResult.MapImageLayer);

                // Zoom to the results
                await MyMapView.SetViewpointAsync(new Viewpoint(myAnalysisResult.MapImageLayer.FullExtent));
            }
            catch (TaskCanceledException)
            {
                // This is thrown if the task is canceled. Ignore.
            }
            catch (Exception ex)
            {
                // Display error messages if the geoprocessing task fails
                if (_hotspotJob.Status == JobStatus.Failed && _hotspotJob.Error != null)
                {
                    MessageBox.Show("Executing geoprocessing failed. " + _hotspotJob.Error.Message, "Geoprocessing error");
                }
                else
                {
                    MessageBox.Show("An error occurred. " + ex.ToString(), "Sample error");
                }
            }
            finally
            {
                // Remove the busyOverlay
                ShowBusyOverlay(false);
            }
        }
Beispiel #4
0
        private async void Initialize()
        {
            // Set paths that are relative to execution path
            string currentDir = Directory.GetCurrentDirectory();
            int    idx        = currentDir.IndexOf("bin") - 1;

            appRootDir = currentDir.Substring(0, idx);
            appDataDir = appRootDir + @"\Data";
            appTempDir = appRootDir + @"\temp";

            // Set up files
            testImage  = appDataDir + @"\sampleFile.tiff";
            gpPackage  = appDataDir + @"\CreateMapTilePackage.gpkx";
            mapPackage = appDataDir + @"\emptyMapPackage.mpkx";

            Debug.WriteLine(">> App Root Directory = " + appRootDir);
            Debug.WriteLine(">> App Data Directory = " + appDataDir);
            Debug.WriteLine(">> App Temp Directory = " + appTempDir);

            ////////////// start Q Basket set up //////////////////
            // Create raster layer from a raster file (Geotiff)
            Debug.WriteLine("Loading raster layer from " + testImage);
            RasterLayer inRasterLayer = new RasterLayer(testImage);

            // Load Raster into Raster Layer
            try
            {
                await inRasterLayer.LoadAsync();

                if (inRasterLayer.LoadStatus != Esri.ArcGISRuntime.LoadStatus.Loaded)
                {
                    Debug.WriteLine("Error - Input Raster Layer not loaded ");
                }
            }
            catch (Exception ex)
            {
                string msg = "Unable to load the raster\n";
                msg += "Raster file = " + testImage;
                msg += "Load status = " + inRasterLayer.LoadStatus.ToString();
                msg += "\n\nMessage: " + ex.Message;
                MessageBox.Show(msg, "inRasterLayer.LoadAsync failed");
            }

            // Create a new EnvelopeBuilder from the full extent of the raster layer.
            // Add a small zoom to make sure entire map is viewable
            EnvelopeBuilder envelopeBuilder = new EnvelopeBuilder(inRasterLayer.FullExtent);

            envelopeBuilder.Expand(0.75);

            // Create a basemap from the raster layer
            Basemap baseMap = new Basemap(inRasterLayer);

            // Create a new map using the new basemap
            Map newMap = new Map(baseMap);

            // Set the viewpoint of the map to the proper extent.
            newMap.InitialViewpoint = new Viewpoint(envelopeBuilder.ToGeometry().Extent);

            // Create a map and add it to the view
            MyMapView.Map = newMap;

            // Load new map to display basemap
            try
            {
                // Add map to the map view.
                MyMapView.Map = newMap;

                // Wait for the map to load.
                await newMap.LoadAsync();
            }
            catch (Exception ex)
            {
                string msg = "Unable to load the Map\n";
                msg += "\n\nMessage: " + ex.Message;
                MessageBox.Show(msg, "newMap.LoadAsync failed");
            }

            // Wait for rendering to finish before taking the screenshot for the thumbnail
            await WaitForRenderCompleteAsync(MyMapView);

            ////////////// end Q Basket set up //////////////////

            // Start the Local Server
            try
            {
                // LocalServer must not be running when setting the data path.
                if (LocalServer.Instance.Status == LocalServerStatus.Started)
                {
                    await LocalServer.Instance.StopAsync();
                }

                // Set the local data path - must be done before starting.
                // Avoid Windows path length limitations (260).
                // CreateDirectory won't overwrite if it already exists.
                Directory.CreateDirectory(appTempDir);
                LocalServer.Instance.AppDataPath = appTempDir;

                // Start the local server instance
                await LocalServer.Instance.StartAsync();

                MessageBox.Show("Local Server started");
                Debug.WriteLine(">> Local Server started");

                // Get the URL for the localServer
                // localhost port is variable
                localServerURL = LocalServer.Instance.Url.AbsoluteUri;

                Debug.WriteLine("\n>> Local server url - " + localServerURL);
                Debug.WriteLine(">> Local server App Data Path - " +
                                LocalServer.Instance.AppDataPath);
            }
            catch (Exception ex)
            {
                string msg = "Please ensure the local server is installed \nand configured correctly";
                msg += String.Format("\nMessage: {0}", ex.Message);
                MessageBox.Show(msg, "Local Server failed to start");
                Debug.WriteLine(msg);
                App.Current.Shutdown();
            }

            // LOCAL MAP SERVICE INIT
            // Create and start the local map service
            try
            {
                _localMapService = new LocalMapService(mapPackage);
            }
            catch (Exception ex)
            {
                string msg = "Cannot create the local map service";
                msg += "Map Package = " + mapPackage;
                msg += String.Format("\nMessage: {0}", ex.Message);
                MessageBox.Show(msg, "Local Map Server failed to start");
                Debug.WriteLine(msg);
                App.Current.Shutdown();
            }

            // RASTER WORKSPACE CREATION
            // Create the Raster workspace; this workspace name was chosen arbitrarily
            // Does workspace need to be the same directory as rasters?
            // setting to temp directory
            rasterWorkspace = new RasterWorkspace("raster_wkspc", appTempDir);
            Debug.WriteLine(">> raster workspace folder = " + rasterWorkspace.FolderPath);
            Debug.WriteLine(">> raster workspace id = " + rasterWorkspace.Id);

            // Create the layer source that represents the Raster on disk
            RasterSublayerSource source = new RasterSublayerSource(rasterWorkspace.Id, testImage);

            // Create a sublayer instance from the table source
            _rasterSublayer = new ArcGISMapImageSublayer(0, source);

            // Add the dynamic workspace to the map service
            _localMapService.SetDynamicWorkspaces(new List <DynamicWorkspace>()
            {
                rasterWorkspace
            });

            // Register map service status chagne event handle
            _localMapService.StatusChanged += _localMapService_StatusChanged;

            // Start the map service
            try
            {
                await _localMapService.StartAsync();
            }
            catch (Exception ex)
            {
                string msg = "Cannot start the local map service";
                msg += "Map Package = " + mapPackage;
                msg += String.Format("\nMessage: {0}", ex.Message);
                MessageBox.Show(msg, "Local Map Server failed to start");
                Debug.WriteLine(msg);
                App.Current.Shutdown();
            }

            // Get the url to the local map service
            localMapServiceURL = _localMapService.Url.AbsoluteUri;
            MessageBox.Show("Local Map Service URL = " + localMapServiceURL);
            Debug.WriteLine("Local Map Service URL = " + localMapServiceURL);

            // LOCAL GEOPROCESSING SERVICE INIT
            // Create the geoprocessing service
            _localGPservice = new LocalGeoprocessingService(gpPackage, gpServiceType);

            // Ass GP service status chagned event handler
            _localGPservice.StatusChanged += GpServiceOnStatusChanged;

            // Try to start the service
            try
            {
                // Start the service
                await _localGPservice.StartAsync();

                if (_localGPservice.Status == LocalServerStatus.Failed)
                {
                    string msg = ("Geoprocessing service failed to start.\n");
                    MessageBox.Show(msg, "gpService.StartAsync failed");
                    App.Current.Shutdown();
                }
                else if (_localGPservice.Status == LocalServerStatus.Started)
                {
                    localGPserviceUrl = _localGPservice.Url.AbsoluteUri + "/CreateMapTilePackage";

                    string msg = ("Geoprocessing service started.\n");
                    msg += "\n>> GP Service URL: " + localGPserviceUrl;
                    msg += ">> GP Service Max Records: " + _localGPservice.MaxRecords;
                    msg += ">> GP Service Package Path: " + _localGPservice.PackagePath;
                    msg += ">> GP Service Type: " + _localGPservice.ServiceType;
                    MessageBox.Show(msg, "gpService.StartAsync started");

                    Debug.WriteLine("\n>> GP Service URL: " + localGPserviceUrl);
                    Debug.WriteLine(">> GP Service Max Records: " + _localGPservice.MaxRecords);
                    Debug.WriteLine(">> GP Service Package Path: " + _localGPservice.PackagePath);
                    Debug.WriteLine(">> GP Service Type: " + _localGPservice.ServiceType);
                }
            }
            catch (Exception ex)
            {
                string msg = ("Geoprocessing service failed to start.\n");
                msg += "\nGeoprocessing package - " + gpPackage + "\n";
                msg += String.Format("\nMessage: {0}", ex.Message);
                MessageBox.Show(msg, "gpService.StartAsync failed");
                return;
            }

            // GEOPROCESSING TASK INIT
            // Create the geoprocessing task from the service
            try
            {
                string url = _localGPservice.Url + "/CreateMapTilePackage";
                _gpTask = await GeoprocessingTask.CreateAsync(new Uri(url));
            }
            catch (Exception ex)
            {
                string msg = ("Geoprocessing task failed to start.\n");
                msg += "\nlocalGPserviceUrl- " + localGPserviceUrl + "\n";
                msg += String.Format("\nMessage: {0}", ex.Message);
                MessageBox.Show(msg, "GeoprocessingTask.CreateAsync failed");
                return;
            }
            MessageBox.Show("GeoprocessingTask.CreateAsync created");

            // GEOPROCESSING JOB
            // Create the geoprocessing parameters
            GeoprocessingParameters gpParams = new GeoprocessingParameters(gpExecutionType);

            // Add the interval parameter to the geoprocessing parameters
            //GeoprocessingString Input_Map = new GeoprocessingString("MyMapView.Map");
            GeoprocessingString Input_Map      = new GeoprocessingString("localMapServiceURL");
            GeoprocessingDouble Max_LOD        = new GeoprocessingDouble(10);
            GeoprocessingString Output_Package = new GeoprocessingString("C://Karen/Data/TilePackages/test.tpkx");

            gpParams.Inputs.Add("Input_Map", Input_Map);
            gpParams.Inputs.Add("Max_LOD", Max_LOD);
            gpParams.Inputs.Add("Output_Package", Output_Package);

            // Create the job
            try
            {
                _gpJob = _gpTask.CreateJob(gpParams);
            }
            catch (Exception ex)
            {
                string msg = ("Geoprocessing job cannot be created.\n");
                msg += String.Format("\nMessage: {0}", ex.Message);
                MessageBox.Show(msg, "_gpTask.CreateJob failed");
                return;
            }
            MessageBox.Show("GeoprocessingTask.CreateJob created");
            MyLoadingIndicator.Visibility = Visibility.Visible;

            // Update the UI when job progress changes
            _gpJob.ProgressChanged += (sender, args) =>
            {
                Dispatcher.Invoke(() => { MyLoadingIndicator.Value = _gpJob.Progress; });
            };

            // Be notified when the task completes (or other change happens)
            _gpJob.JobChanged += GpJobOnJobChanged;

            // Start the job
            try
            {
                _gpJob.Start();
            }
            catch (Exception ex)
            {
                string msg = ("Geoprocessing start job failed to start.\n");
                msg += String.Format("\nMessage: {0}", ex.Message);
                MessageBox.Show(msg, "_gpjob.Start failed");
                return;
            }
            MessageBox.Show("GeoprocessingTask job started");
        }