Local server geoprocessing

View on GitHubSample viewer app

Create contour lines from local raster data using a local geoprocessing package .gpk and the contour geoprocessing tool.

Image of local server geoprocessing

Use case

For executing offline geoprocessing tasks in your apps via an offline (local) server.

How to use the sample

Contour Line Controls (Top Left):

  • Interval - Specifies the spacing between contour lines.
  • Generate Contours - Adds contour lines to map using interval.
  • Clear Results - Removes contour lines from map.

How it works

  1. Create and run a local server with LocalServer.Instance.
  2. Start the server asynchronously with server.StartAsync().
  3. Start a LocalGeoprocessingService and run a GeoprocessingTask.
    1. Instantiate LocalGeoprocessingService(Url, ServiceType) to create a local geoprocessing service.
    2. Call LocalGeoprocessingService.StartAsync() to start the service asynchronously.
    3. Instantiate GeoprocessingTask(LocalGeoprocessingService.Url + "/Contour") to create a geoprocessing task that uses the contour lines tool.
  4. Create an instance of GeoprocessingParameters.
    1. Instantiate GeoprocessingParameters(ExecutionType) creates geoprocessing parameters.
    2. Create a parameter using gpParams.Inputs["ContourInterval"] = new GeoprocessingDoublevalue) using the desired contour value.
  5. Create and start a GeoprocessingJob using the previous parameters.
    1. Create a geoprocessing job with GeoprocessingTask.CreateJob(GeoprocessingParameters).
    2. Start the job with GeoprocessingJob.Start().
  6. Add contour lines as an ArcGISMapImageLayer to the map.
    1. Get url from local geoprocessing service using the service.Url property.
    2. Get server job id of geoprocessing job using the GeoprocessingJob.ServerJobId property.
    3. Replace GPServer from url with MapServer/jobs/jobId, to get generate contour lines data.
    4. Create a map image layer from that new url and add that layer to the map.

Relevant API

  • GeoprocessingDouble
  • GeoprocessingJob
  • GeoprocessingParameter
  • GeoprocessingParameters
  • GeoprocessingTask
  • LocalGeoprocessingService
  • LocalGeoprocessingService.ServiceType
  • LocalServer
  • LocalServerStatus

Offline data

This sample downloads the following items from ArcGIS Online automatically:

Additional information

Local Server can be downloaded for Windows and Linux platforms from the developers website. Local Server is not supported on macOS.

Tags

geoprocessing, local, offline, parameters, processing, service

Sample Code

LocalServerGeoprocessing.xaml.csLocalServerGeoprocessing.xaml.csLocalServerGeoprocessing.xaml
Use dark colors for code blocksCopy
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
// Copyright 2021 Esri.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.
// You may obtain a copy of the License at: http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific
// language governing permissions and limitations under the License.

using ArcGIS.Samples.Managers;
using Esri.ArcGISRuntime.LocalServices;
using Esri.ArcGISRuntime.Mapping;
using Esri.ArcGISRuntime.Tasks;
using Esri.ArcGISRuntime.Tasks.Geoprocessing;
using System;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;

namespace ArcGIS.WPF.Samples.LocalServerGeoprocessing
{
    [ArcGIS.Samples.Shared.Attributes.Sample(
        name: "Local server geoprocessing",
        category: "Local Server",
        description: "Create contour lines from local raster data using a local geoprocessing package `.gpk` and the contour geoprocessing tool.",
        instructions: "Contour Line Controls (Top Left):",
        tags: new[] { "geoprocessing", "local", "offline", "parameters", "processing", "service" })]
    [ArcGIS.Samples.Shared.Attributes.OfflineData("3f38e1ae7c5948cc95334ba3a142a4ec", "a680362d6a7447e8afe2b1eb85fcde30")]
    public partial class LocalServerGeoprocessing
    {
        // Hold a reference to the local geoprocessing service
        private LocalGeoprocessingService _gpService;

        // Hold a reference to the task
        private GeoprocessingTask _gpTask;

        // Hold a reference to the job
        private GeoprocessingJob _gpJob;

        public LocalServerGeoprocessing()
        {
            InitializeComponent();

            // set up the sample
            _ = Initialize();
        }

        private async Task Initialize()
        {
            // Create a map and add it to the view
            MyMapView.Map = new Map(BasemapStyle.ArcGISLightGray);

            // Load the tiled layer and get the path
            string rasterPath = GetRasterPath();

            // Create a tile cache using the path to the raster
            TileCache myTileCache = new TileCache(rasterPath);

            // Create the tiled layer from the tile cache
            ArcGISTiledLayer tiledLayer = new ArcGISTiledLayer(myTileCache);

            // Try to load the tiled layer
            try
            {
                // Wait for the layer to load
                await tiledLayer.LoadAsync();

                // Zoom to extent of the tiled layer
                await MyMapView.SetViewpointGeometryAsync(tiledLayer.FullExtent);
            }
            catch (Exception)
            {
                MessageBox.Show("Couldn't load the tile package, ending sample load.");
                return;
            }

            // Add the layer to the map
            MyMapView.Map.OperationalLayers.Add(tiledLayer);

            // Try to start 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. On most systems, this will be C:\EsriSamples\AppData.
                // This path should be kept short to avoid Windows path length limitations.
                string tempDataPathRoot = Directory.GetParent(Environment.GetFolderPath(Environment.SpecialFolder.Windows)).FullName;
                string tempDataPath = Path.Combine(tempDataPathRoot, "EsriSamples", "AppData");
                Directory.CreateDirectory(tempDataPath); // CreateDirectory won't overwrite if it already exists.
                LocalServer.Instance.AppDataPath = tempDataPath;

                // Start the local server instance
                await LocalServer.Instance.StartAsync();
            }
            catch (Exception ex)
            {
                var localServerTypeInfo = typeof(LocalMapService).GetTypeInfo();
                var localServerVersion = FileVersionInfo.GetVersionInfo(localServerTypeInfo.Assembly.Location);

                MessageBox.Show($"Please ensure that local server {localServerVersion.FileVersion} is installed prior to using the sample. The download link is in the description. Message: {ex.Message}", "Local Server failed to start");
                return;
            }

            // Get the path to the geoprocessing task
            string gpServiceUrl = GetGpPath();

            // Create the geoprocessing service
            _gpService = new LocalGeoprocessingService(gpServiceUrl, GeoprocessingServiceType.AsynchronousSubmitWithMapServiceResult);

            // Take action once the service loads
            _gpService.StatusChanged += GpServiceOnStatusChanged;

            // Try to start the service
            try
            {
                // Start the service
                await _gpService.StartAsync();
            }
            catch (Exception)
            {
                MessageBox.Show("geoprocessing service failed to start.");
            }
        }

        private async void GpServiceOnStatusChanged(object sender, StatusChangedEventArgs statusChangedEventArgs)
        {
            // Return if the server hasn't started
            if (statusChangedEventArgs.Status != LocalServerStatus.Started) return;

            try
            {
                // Create the geoprocessing task from the service
                _gpTask = await GeoprocessingTask.CreateAsync(new Uri(_gpService.Url + "/Contour"));

                // Update UI
                MyUpdateContourButton.IsEnabled = true;
                MyLoadingIndicator.Visibility = Visibility.Collapsed;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        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.StatusChanged += GpJobOnJobChanged;

            // Start the job
            _gpJob.Start();
        }

        private async void GpJobOnJobChanged(object o, JobStatus e)
        {
            // Show message if job failed
            if (_gpJob.Status == JobStatus.Failed)
            {
                MessageBox.Show("Job Failed");
                return;
            }

            // Return if not succeeded
            if (_gpJob.Status != JobStatus.Succeeded) { return; }

            // Get the URL to the map service
            string gpServiceResultUrl = _gpService.Url.ToString();

            // Get the URL segment for the specific job results
            string jobSegment = "MapServer/jobs/" + _gpJob.ServerJobId;

            // Update the URL to point to the specific job from the service
            gpServiceResultUrl = gpServiceResultUrl.Replace("GPServer", jobSegment);

            // Create a map image layer to show the results
            ArcGISMapImageLayer myMapImageLayer = new ArcGISMapImageLayer(new Uri(gpServiceResultUrl));

            try
            {
                // Load the layer
                await myMapImageLayer.LoadAsync();

                // This is needed because the event comes from outside of the UI thread
                Dispatcher.Invoke(() =>
                {
                    // Add the layer to the map
                    MyMapView.Map.OperationalLayers.Add(myMapImageLayer);

                    // Hide the progress bar
                    MyLoadingIndicator.Visibility = Visibility.Collapsed;

                    // Disable the generate button
                    MyUpdateContourButton.IsEnabled = false;

                    // Enable the reset button
                    MyResetButton.IsEnabled = true;
                });
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
        }

        private static string GetRasterPath()
        {
            return DataManager.GetDataFolder("3f38e1ae7c5948cc95334ba3a142a4ec", "RasterHillshade.tpkx");
        }

        private static string GetGpPath()
        {
            return DataManager.GetDataFolder("a680362d6a7447e8afe2b1eb85fcde30", "Contour.gpkx");
        }

        private void MyResetButton_OnClick(object sender, RoutedEventArgs e)
        {
            // Remove the contour
            MyMapView.Map.OperationalLayers.RemoveAt(1);

            // Enable the generate button
            MyUpdateContourButton.IsEnabled = true;

            // Disable the reset button
            MyResetButton.IsEnabled = false;
        }

        private void MyUpdateContourButton_OnClick(object sender, RoutedEventArgs e)
        {
            // Disable the generate button
            ((Button)sender).IsEnabled = false;

            // Generate the contours
            GenerateContours();
        }
    }
}

Your browser is no longer supported. Please upgrade your browser for the best experience. See our browser deprecation post for more details.