forked from Esri/arcgis-maps-sdk-dotnet-samples
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAuthorMap.xaml.cs
375 lines (316 loc) · 16.1 KB
/
AuthorMap.xaml.cs
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
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
// Copyright 2016 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 Esri.ArcGISRuntime.Geometry;
using Esri.ArcGISRuntime.Mapping;
using Esri.ArcGISRuntime.Portal;
using Esri.ArcGISRuntime.Security;
using Esri.ArcGISRuntime.UI;
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using Windows.UI.Popups;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
namespace ArcGISRuntime.UWP.Samples.AuthorMap
{
[ArcGISRuntime.Samples.Shared.Attributes.Sample(
"Author a map",
"Map",
"This sample demonstrates how to author and save a map as an ArcGIS portal item (web map). Saving a map to arcgis.com requires an ArcGIS Online login.",
"1. Pan and zoom to the extent you would like for your map.\n2. Choose a basemap from the list of available basemaps.\n3. Choose one or more operational layers to include.\n4. Provide a Client ID and Redirect URL for OAuth authentication with ArcGIS Online.\n5. Provide info for the new portal item, such as a Title, Description, and Tags.\n6. Click 'Save Map to Portal'.\n7. After successfully logging in to your ArcGIS Online account, the map will be saved to your default folder. \n8. You can make additional changes, update the map, and then re-save to store changes in the portal item.")]
public partial class AuthorMap
{
// Constants for OAuth-related values ...
// URL of the server to authenticate with
private string ServerUrl = "https://www.arcgis.com/sharing/rest";
// TODO: Add Client ID for an app registered with the server
private string _appClientId = "lgAdHkYZYlwwfAhC";
// TODO: Add URL for redirecting after a successful authorization
// Note - this must be a URL configured as a valid Redirect URI with your app
private string _oAuthRedirectUrl = "my-ags-app://auth";
// String array to store names of the available basemaps
private readonly string[] _basemapNames = {
"Light Gray",
"Topographic",
"Streets",
"Imagery",
"Ocean"
};
// Dictionary of operational layer names and URLs
private readonly Dictionary<string, string> _operationalLayerUrls = new Dictionary<string, string>
{
{"World Elevations", "https://sampleserver6.arcgisonline.com/arcgis/rest/services/Elevation/WorldElevations/MapServer"},
{"World Cities", "https://sampleserver6.arcgisonline.com/arcgis/rest/services/SampleWorldCities/MapServer/" },
{"US Census Data", "https://sampleserver6.arcgisonline.com/arcgis/rest/services/Census/MapServer"}
};
public AuthorMap()
{
InitializeComponent();
// Create the UI, setup the control references and execute initialization
Initialize();
}
private void Initialize()
{
// Create the map
MyMapView.Map = new Map();
// Update the UI with basemaps and layers
BasemapListBox.ItemsSource = _basemapNames;
BasemapListBox.SelectedIndex = 0;
OperationalLayerListBox.ItemsSource = _operationalLayerUrls;
// Show the OAuth settings in the page
ClientIdTextBox.Text = _appClientId;
RedirectUrlTextBox.Text = _oAuthRedirectUrl;
// Update the extent labels whenever the view point (extent) changes
MyMapView.ViewpointChanged += (s, evt) => UpdateViewExtentLabels();
}
#region UI event handlers
private void LayerSelectionChanged(object sender, SelectionChangedEventArgs e)
{
// Call a function to add operational layers to the map
AddOperationalLayers();
}
private async void SaveMapClicked(object sender, RoutedEventArgs e)
{
try
{
// Don't attempt to save if the OAuth settings weren't provided
if(String.IsNullOrEmpty(_appClientId) || String.IsNullOrEmpty(_oAuthRedirectUrl))
{
MessageDialog dialog = new MessageDialog("OAuth settings were not provided.", "Cannot Save");
await dialog.ShowAsync();
return;
}
// Show the progress bar so the user knows work is happening
SaveProgressBar.Visibility = Visibility.Visible;
// Get the current map
Map myMap = MyMapView.Map;
// Apply the current extent as the map's initial extent
myMap.InitialViewpoint = MyMapView.GetCurrentViewpoint(ViewpointType.BoundingGeometry);
// Export the current map view to use as the item's thumbnail
RuntimeImage thumbnailImg = await MyMapView.ExportImageAsync();
// See if the map has already been saved (has an associated portal item)
if (myMap.Item == null)
{
// Get information for the new portal item
string title = TitleTextBox.Text;
string description = DescriptionTextBox.Text;
string tagText = TagsTextBox.Text;
// Make sure all required info was entered
if (String.IsNullOrEmpty(title) || String.IsNullOrEmpty(description) || String.IsNullOrEmpty(tagText))
{
throw new Exception("Please enter a title, description, and some tags to describe the map.");
}
// Call a function to save the map as a new portal item
await SaveNewMapAsync(MyMapView.Map, title, description, tagText.Split(','), thumbnailImg);
// Report a successful save
MessageDialog messageDialog = new MessageDialog("Saved '" + title + "' to ArcGIS Online!", "Map Saved");
await messageDialog.ShowAsync();
}
else
{
// This is not the initial save, call SaveAsync to save changes to the existing portal item
await myMap.SaveAsync();
// Get the file stream from the new thumbnail image
Stream imageStream = await thumbnailImg.GetEncodedBufferAsync();
// Update the item thumbnail
((PortalItem)myMap.Item).SetThumbnail(imageStream);
await myMap.SaveAsync();
// Report update was successful
MessageDialog messageDialog = new MessageDialog("Saved changes to '" + myMap.Item.Title + "'", "Updates Saved");
await messageDialog.ShowAsync();
}
}
catch (Exception ex)
{
// Report error message
MessageDialog messageDialog = new MessageDialog("Error saving map to ArcGIS Online: " + ex.Message);
await messageDialog.ShowAsync();
}
finally
{
// Hide the progress bar
SaveProgressBar.Visibility = Visibility.Collapsed;
}
}
private void ClearMapClicked(object sender, RoutedEventArgs e)
{
// Create a new map (will not have an associated PortalItem)
MyMapView.Map = new Map(Basemap.CreateLightGrayCanvas());
// Reset the basemap selection in the UI
BasemapListBox.SelectedIndex = 0;
// Reset the layer selection in the UI;
OperationalLayerListBox.SelectedIndex = -1;
// Reset the extent labels
UpdateViewExtentLabels();
}
#endregion
private void ApplyBasemap(string basemapName)
{
// Get the current map
Map myMap = MyMapView.Map;
// Set the basemap for the map according to the user's choice in the list box
switch (basemapName)
{
case "Light Gray":
// Set the basemap to Light Gray Canvas
myMap.Basemap = Basemap.CreateLightGrayCanvas();
break;
case "Topographic":
// Set the basemap to Topographic
myMap.Basemap = Basemap.CreateTopographic();
break;
case "Streets":
// Set the basemap to Streets
myMap.Basemap = Basemap.CreateStreets();
break;
case "Imagery":
// Set the basemap to Imagery
myMap.Basemap = Basemap.CreateImagery();
break;
case "Ocean":
// Set the basemap to Oceans
myMap.Basemap = Basemap.CreateOceans();
break;
}
}
private void AddOperationalLayers()
{
// Clear the operational layers from the map
Map myMap = MyMapView.Map;
myMap.OperationalLayers.Clear();
// Loop through the selected items in the operational layers list box
foreach (KeyValuePair<string, string> item in OperationalLayerListBox.SelectedItems)
{
// Get the service uri for each selected item
KeyValuePair<string, string> layerInfo = item;
Uri layerUri = new Uri(layerInfo.Value);
// Create a new map image layer, set it 50% opaque, and add it to the map
ArcGISMapImageLayer layer = new ArcGISMapImageLayer(layerUri)
{
Opacity = 0.5
};
myMap.OperationalLayers.Add(layer);
}
}
private async Task SaveNewMapAsync(Map myMap, string title, string description, string[] tags, RuntimeImage img)
{
// Challenge the user for portal credentials (OAuth credential request for arcgis.com)
CredentialRequestInfo loginInfo = new CredentialRequestInfo
{
// Use the OAuth implicit grant flow
GenerateTokenOptions = new GenerateTokenOptions
{
TokenAuthenticationType = TokenAuthenticationType.OAuthImplicit
},
// Indicate the url (portal) to authenticate with (ArcGIS Online)
ServiceUri = new Uri("https://www.arcgis.com/sharing/rest")
};
try
{
// Get a reference to the (singleton) AuthenticationManager for the app
AuthenticationManager thisAuthenticationManager = AuthenticationManager.Current;
// Call GetCredentialAsync on the AuthenticationManager to invoke the challenge handler
await thisAuthenticationManager.GetCredentialAsync(loginInfo, false);
}
catch (OperationCanceledException)
{
// user canceled the login
throw new Exception("Portal log in was canceled.");
}
// Get the ArcGIS Online portal (will use credential from login above)
ArcGISPortal agsOnline = await ArcGISPortal.CreateAsync();
// Save the current state of the map as a portal item in the user's default folder
await myMap.SaveAsAsync(agsOnline, null, title, description, tags, img);
}
private void UpdateViewExtentLabels()
{
// Get the current view point for the map view
Viewpoint currentViewpoint = MyMapView.GetCurrentViewpoint(ViewpointType.BoundingGeometry);
if (currentViewpoint == null) { return; }
// Get the current map extent (envelope) from the view point
Envelope currentExtent = currentViewpoint.TargetGeometry as Envelope;
// Project the current extent to geographic coordinates (longitude / latitude)
Envelope currentGeoExtent = (Envelope)GeometryEngine.Project(currentExtent, SpatialReferences.Wgs84);
// Fill the app text boxes with min / max longitude (x) and latitude (y) to four decimal places
XMinTextBox.Text = currentGeoExtent.XMin.ToString("0.####");
YMinTextBox.Text = currentGeoExtent.YMin.ToString("0.####");
XMaxTextBox.Text = currentGeoExtent.XMax.ToString("0.####");
YMaxTextBox.Text = currentGeoExtent.YMax.ToString("0.####");
}
#region OAuth helpers
private void SaveOAuthSettingsClicked(object sender, RoutedEventArgs e)
{
// Settings were provided, update the configuration settings for OAuth authorization
_appClientId = ClientIdTextBox.Text.Trim();
_oAuthRedirectUrl = RedirectUrlTextBox.Text.Trim();
// Update authentication manager with the OAuth settings
UpdateAuthenticationManager();
// Update the UI
SaveMapGrid.Visibility = Visibility.Visible;
OAuthSettingsGrid.Visibility = Visibility.Collapsed;
}
private void UpdateAuthenticationManager()
{
// Register the server information with the AuthenticationManager
ServerInfo portalServerInfo = new ServerInfo
{
ServerUri = new Uri(ServerUrl),
OAuthClientInfo = new OAuthClientInfo
{
ClientId = _appClientId,
RedirectUri = new Uri(_oAuthRedirectUrl)
},
// Specify OAuthAuthorizationCode if you need a refresh token (and have specified a valid client secret)
// Otherwise, use OAuthImplicit
TokenAuthenticationType = TokenAuthenticationType.OAuthImplicit
};
// Get a reference to the (singleton) AuthenticationManager for the app
AuthenticationManager thisAuthenticationManager = AuthenticationManager.Current;
// Register the server information
thisAuthenticationManager.RegisterServer(portalServerInfo);
// Create a new ChallengeHandler that uses a method in this class to challenge for credentials
thisAuthenticationManager.ChallengeHandler = new ChallengeHandler(CreateCredentialAsync);
}
// ChallengeHandler function for AuthenticationManager that will be called whenever access to a secured
// resource is attempted
public async Task<Credential> CreateCredentialAsync(CredentialRequestInfo info)
{
OAuthTokenCredential credential = null;
try
{
// Create generate token options if necessary
if (info.GenerateTokenOptions == null)
{
info.GenerateTokenOptions = new GenerateTokenOptions();
}
// IOAuthAuthorizeHandler will challenge the user for credentials
credential = await AuthenticationManager.Current.GenerateCredentialAsync
(
info.ServiceUri,
info.GenerateTokenOptions
) as OAuthTokenCredential;
}
catch (Exception)
{
// Exception will be reported in calling function
throw;
}
return credential;
}
#endregion
private void BasemapListView_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
// Get the name of the desired basemap
string name = e.AddedItems[0].ToString();
// Apply the basemap to the current map
ApplyBasemap(name);
}
}
}