From ca4e795aa97a7dd31fe4ec2258103b845393be61 Mon Sep 17 00:00:00 2001 From: arcgisprosdk Date: Wed, 14 Feb 2018 08:56:38 -1000 Subject: [PATCH] ArcGIS Pro 2.1 SDK for .NET - fixed threading issues causing thread exception --- .../Common/SubmitQuery.cs | 479 +++++++++--------- .../ConfigWithStartWizard.xml | 24 +- .../Models/OnlineResultItem.cs | 252 ++++----- .../UI/StartPages/OnlineItemStartPage.xaml | 272 +++++++--- .../OnlineItemStartPageViewModel.cs | 128 +++-- 5 files changed, 658 insertions(+), 497 deletions(-) diff --git a/Framework/ConfigWithStartWizard/Common/SubmitQuery.cs b/Framework/ConfigWithStartWizard/Common/SubmitQuery.cs index c8b2a686..c6cb6b84 100644 --- a/Framework/ConfigWithStartWizard/Common/SubmitQuery.cs +++ b/Framework/ConfigWithStartWizard/Common/SubmitQuery.cs @@ -29,256 +29,231 @@ limitations under the License. using ArcGIS.Desktop.Core.Portal; using System.Linq; -namespace ConfigWithStartWizard.Common { - internal class SubmitQuery { - public static string DefaultUserAgent = - "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; GTB7.1; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; InfoPath.2; .NET CLR 1.1.4322; .NET4.0C; .NET4.0E; OfficeLiveConnector.1.3; OfficeLivePatch.0.0; MS-RTC LM 8)"; - - public static readonly string DefaultReferer = "Browse AGS"; - public static readonly int DefaultMaxResults = 100; - public static readonly int DefaultMaxResponseLength = 2048; - - - private StringBuilder _response; - private string _errorResponse = ""; - - /// - /// Gets the original response from the portal - /// - public string Response => _response != null ? _response.ToString() : ""; - - /// - /// Gets the error response if there was an exception - /// - public string ErrorResponse - { - get - { - return _errorResponse; - } - } - - /// - /// Gets and sets the (approx) maximum number of characters for the DEBUG response - /// - /// Has no effect on the length of the actual response from online - public int MaxResponseLength { get; set; } - - public Task DownloadFileAsync(OnlineQuery query) { - return new EsriHttpClient().GetAsFileAsync(query.DownloadUrl, query.DownloadFileName); - } - - public async Task ExecDownloadAsync(OnlineQuery query, string fileName) { - - EsriHttpClient httpClient = new EsriHttpClient(); - var response = httpClient.Get(query.DownloadUrl); - var stm = await response.Content.ReadAsStreamAsync(); - - using (MemoryStream ms = new MemoryStream()) { - stm.CopyTo(ms); - System.IO.File.WriteAllBytes(fileName, ms.ToArray()); - } - } - - - - /// - /// Execute the given query and return the result - /// - /// - /// - /// - /// - /// - //public string Exec(OnlineQuery query, ObservableCollection results, - // int maxResults = 0) { - - // if (maxResults == 0) - // maxResults = DefaultMaxResults; - // if (MaxResponseLength == 0) - // MaxResponseLength = DefaultMaxResponseLength; - - // _response = new StringBuilder(); - // _errorResponse = ""; - - // //slap in the initial request - // _response.AppendLine(query.FinalUrl); - // _response.AppendLine(""); - - // results.Clear(); - - // try { - // Tuple stats = new Tuple(-1, -1); - // do { - - // query.Start = stats.Item2; - - // System.Diagnostics.Debug.WriteLine(""); - // System.Diagnostics.Debug.WriteLine(query.FinalUrl); - // System.Diagnostics.Debug.WriteLine(""); - - // EsriHttpClient httpClient = new EsriHttpClient(); - - // var response = httpClient.Get(query.FinalUri.ToString()); - // var raw = response.Content.ReadAsStringAsync().Result;//block - // stats = ProcessResults(results, raw, query); - // } while (stats.Item2 < maxResults && stats.Item2 > 0); - - // } - // catch (WebException we) { - // //bad request - // _response.AppendLine(""); - // _response.AppendLine("WebException: " + we.Message); - // _response.AppendLine(query.FinalUrl); - // _response.AppendLine(""); - // _response.AppendLine(new Uri(query.FinalUrl).Scheme.ToUpper() + " " + - // ((int)we.Status).ToString()); - // try { - // _errorResponse = new StreamReader(we.Response.GetResponseStream()).ReadToEnd(); - // _response.AppendLine(_errorResponse); - // } - // catch { - // } - // } - // finally { - // //content = _response.ToString() - // // .Replace("{", "{\r\n") - // // .Replace("}", "\r\n}") - // // .Replace(",\"", ",\r\n\""); - // } - // return _response.ToString(); - //} - - public async void Exec2Async(OnlineQuery query, ObservableCollection results, string portalUrl, - int maxResults = 0) - { - - if (maxResults == 0) - maxResults = DefaultMaxResults; - if (MaxResponseLength == 0) - MaxResponseLength = DefaultMaxResponseLength; - - _response = new StringBuilder(); - _errorResponse = ""; - - //slap in the initial request - _response.AppendLine(query.FinalUrl); - _response.AppendLine(""); - - results.Clear(); - - try - { - Tuple stats = new Tuple(-1, -1); - var portal = ArcGISPortalManager.Current.GetPortal(new Uri(portalUrl)); - int startIndex = 0; - do - { - query.Start = startIndex; - - System.Diagnostics.Debug.WriteLine(""); - System.Diagnostics.Debug.WriteLine(query.FinalUrl); - System.Diagnostics.Debug.WriteLine(""); - - PortalQueryResultSet portalResults = await ArcGISPortalExtensions.SearchForContentAsync(portal, query.PortalQueryParams); - - foreach (var item in portalResults.Results.OfType()) - { - results.Add(item); - } - startIndex = results.Count + startIndex; - } while (startIndex < maxResults) ; - - } - catch (WebException we) - { - //bad request - _response.AppendLine(""); - _response.AppendLine("WebException: " + we.Message); - _response.AppendLine(query.FinalUrl); - _response.AppendLine(""); - _response.AppendLine(new Uri(query.FinalUrl).Scheme.ToUpper() + " " + - ((int)we.Status).ToString()); - try - { - _errorResponse = new StreamReader(we.Response.GetResponseStream()).ReadToEnd(); - _response.AppendLine(_errorResponse); - } - catch - { - } - } - finally - { - - } - //return _response.ToString(); - } - - private Tuple ProcessResults2(ObservableCollection results) - { - long num = -1; - int next = -1; - if ((results == null) || (results.Count == 0)) - return new Tuple(num, next); - - - var numberOfTotalItems = results.Count; - - if (numberOfTotalItems > 0) - { - - num = numberOfTotalItems; - next = numberOfTotalItems + 1; - } - return new Tuple(num, next); - } - - private Tuple ProcessResults( - ObservableCollection results, - string json, - OnlineQuery query) - { - long num = -1; - long next = -1; - if (string.IsNullOrEmpty(json)) - return new Tuple(num, next); - - //process the query results - dynamic queryResults = JObject.Parse(json); - if (queryResults.error != null) - //there was an error in the query - return new Tuple(num, next); - - long numberOfTotalItems = queryResults.total.Value; - int count = 0; - - if (numberOfTotalItems > 0) - { - //these are the results - List userItemResults = new List(); - // store the results in the list - userItemResults.AddRange(queryResults.results); - foreach (dynamic item in userItemResults) - { - count++; - OnlineResultItem ri = new OnlineResultItem(); - ri.Id = item.id; - ri.Title = item.title ?? String.Format("Item {0}", count); - ri.Name = item.name; - //ri.Snippet = item.snippet ?? "no snippet"; - ri.Url = item.url ?? ""; - string thumb = item.thumbnail ?? ""; - string s = item.snippet; - string t = item.type; - string a = item.access; - ri.Configure(query.URL, ri.Id, thumb, s, t, a); - results.Add(ri); - } - num = queryResults.num.Value; - next = queryResults.nextStart.Value; - } - return new Tuple(num, next); - } - } +namespace ConfigWithStartWizard.Common +{ + internal class SubmitQuery + { + public static string DefaultUserAgent = + "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; GTB7.1; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; InfoPath.2; .NET CLR 1.1.4322; .NET4.0C; .NET4.0E; OfficeLiveConnector.1.3; OfficeLivePatch.0.0; MS-RTC LM 8)"; + + public static readonly string DefaultReferer = "Browse AGS"; + public static readonly int DefaultMaxResults = 100; + public static readonly int DefaultMaxResponseLength = 2048; + + + private StringBuilder _response; + private string _errorResponse = ""; + + /// + /// Gets the original response from the portal + /// + public string Response => _response != null ? _response.ToString() : ""; + + /// + /// Gets the error response if there was an exception + /// + public string ErrorResponse + { + get + { + return _errorResponse; + } + } + + /// + /// Gets and sets the (approx) maximum number of characters for the DEBUG response + /// + /// Has no effect on the length of the actual response from online + public int MaxResponseLength { get; set; } + + public Task DownloadFileAsync(OnlineQuery query) + { + return new EsriHttpClient().GetAsFileAsync(query.DownloadUrl, query.DownloadFileName); + } + + public async Task ExecDownloadAsync(OnlineQuery query, string fileName) + { + + EsriHttpClient httpClient = new EsriHttpClient(); + var response = httpClient.Get(query.DownloadUrl); + var stm = await response.Content.ReadAsStreamAsync(); + + using (MemoryStream ms = new MemoryStream()) + { + stm.CopyTo(ms); + System.IO.File.WriteAllBytes(fileName, ms.ToArray()); + } + } + + + + /// + /// Execute the given query and return the result + /// + /// + /// + /// + /// + /// + //public string Exec(OnlineQuery query, ObservableCollection results, + // int maxResults = 0) { + + // if (maxResults == 0) + // maxResults = DefaultMaxResults; + // if (MaxResponseLength == 0) + // MaxResponseLength = DefaultMaxResponseLength; + + // _response = new StringBuilder(); + // _errorResponse = ""; + + // //slap in the initial request + // _response.AppendLine(query.FinalUrl); + // _response.AppendLine(""); + + // results.Clear(); + + // try { + // Tuple stats = new Tuple(-1, -1); + // do { + + // query.Start = stats.Item2; + + // System.Diagnostics.Debug.WriteLine(""); + // System.Diagnostics.Debug.WriteLine(query.FinalUrl); + // System.Diagnostics.Debug.WriteLine(""); + + // EsriHttpClient httpClient = new EsriHttpClient(); + + // var response = httpClient.Get(query.FinalUri.ToString()); + // var raw = response.Content.ReadAsStringAsync().Result;//block + // stats = ProcessResults(results, raw, query); + // } while (stats.Item2 < maxResults && stats.Item2 > 0); + + // } + // catch (WebException we) { + // //bad request + // _response.AppendLine(""); + // _response.AppendLine("WebException: " + we.Message); + // _response.AppendLine(query.FinalUrl); + // _response.AppendLine(""); + // _response.AppendLine(new Uri(query.FinalUrl).Scheme.ToUpper() + " " + + // ((int)we.Status).ToString()); + // try { + // _errorResponse = new StreamReader(we.Response.GetResponseStream()).ReadToEnd(); + // _response.AppendLine(_errorResponse); + // } + // catch { + // } + // } + // finally { + // //content = _response.ToString() + // // .Replace("{", "{\r\n") + // // .Replace("}", "\r\n}") + // // .Replace(",\"", ",\r\n\""); + // } + // return _response.ToString(); + //} + + public async void Exec2Async(OnlineQuery query, + ObservableCollection results, + string portalUrl, + int maxResults = 0) + { + if (maxResults == 0) + maxResults = DefaultMaxResults; + if (MaxResponseLength == 0) + MaxResponseLength = DefaultMaxResponseLength; + + _response = new StringBuilder(); + _errorResponse = ""; + + //slap in the initial request + _response.AppendLine(query.FinalUrl); + _response.AppendLine(""); + + results.Clear(); + + try + { + Tuple stats = new Tuple(-1, -1); + var portal = ArcGISPortalManager.Current.GetPortal(new Uri(portalUrl)); + int startIndex = 0; + var totalCount = 0; + do + { + query.Start = startIndex; + + System.Diagnostics.Debug.WriteLine(""); + System.Diagnostics.Debug.WriteLine(query.FinalUrl); + System.Diagnostics.Debug.WriteLine(""); + + PortalQueryResultSet portalResults = await ArcGISPortalExtensions.SearchForContentAsync(portal, query.PortalQueryParams); + if (portalResults.Results.Count <= 0) break; + foreach (var item in portalResults.Results.OfType()) + { + OnlinePortalItem ri = new OnlinePortalItem + { + Id = item.ID, + Title = item.Title ?? String.Format("Item {0}", startIndex + ++totalCount), + Name = item.Name, + Snippet = item.Description ?? "no snippet", + Url = item.Url ?? "", + ThumbnailUrl = item.ThumbnailPath, + PortalItemType = item.PortalItemType + }; + string thumb = item.ThumbnailUri?.ToString() ?? ""; + string s = item.Description; + string a = item.Access.ToString(); + ri.Configure(query.URL, ri.Id, thumb, s, item.PortalItemType, a); + results.Add(ri); + totalCount++; + } + startIndex += results.Count; + } while (totalCount < maxResults); + } + catch (WebException we) + { + //bad request + _response.AppendLine(""); + _response.AppendLine("WebException: " + we.Message); + _response.AppendLine(query.FinalUrl); + _response.AppendLine(""); + _response.AppendLine(new Uri(query.FinalUrl).Scheme.ToUpper() + " " + + ((int)we.Status).ToString()); + try + { + _errorResponse = new StreamReader(we.Response.GetResponseStream()).ReadToEnd(); + _response.AppendLine(_errorResponse); + } + catch + { + } + } + finally + { + + } + //return _response.ToString(); + } + + private Tuple ProcessResults2(ObservableCollection results) + { + long num = -1; + int next = -1; + if ((results == null) || (results.Count == 0)) + return new Tuple(num, next); + + + var numberOfTotalItems = results.Count; + + if (numberOfTotalItems > 0) + { + + num = numberOfTotalItems; + next = numberOfTotalItems + 1; + } + return new Tuple(num, next); + } + + } } \ No newline at end of file diff --git a/Framework/ConfigWithStartWizard/ConfigWithStartWizard.xml b/Framework/ConfigWithStartWizard/ConfigWithStartWizard.xml index 3e99535b..836c61a2 100644 --- a/Framework/ConfigWithStartWizard/ConfigWithStartWizard.xml +++ b/Framework/ConfigWithStartWizard/ConfigWithStartWizard.xml @@ -20,7 +20,7 @@ Has no effect on the length of the actual response from online - + Execute the given query and return the result @@ -131,47 +131,47 @@ Implemented UserControl with about box information. Return null if a custom about box is not needed. Default ArcGIS Pro About box will be displayed. - + An individual result from an online query - + Gets and sets the item id - + Gets and sets the item title - + Gets and sets the name - + Gets and sets the item snippet - + Gets and sets the item url - + Gets and sets the online item type - + Gets the Thumbnail url of the ResultItem - + Provide the item thumbnail URL for the given item id and thumbnail url @@ -180,7 +180,7 @@ the online item id - + Configure the online item result @@ -188,7 +188,7 @@ - + diff --git a/Framework/ConfigWithStartWizard/Models/OnlineResultItem.cs b/Framework/ConfigWithStartWizard/Models/OnlineResultItem.cs index 0351c8c3..f335e999 100644 --- a/Framework/ConfigWithStartWizard/Models/OnlineResultItem.cs +++ b/Framework/ConfigWithStartWizard/Models/OnlineResultItem.cs @@ -16,139 +16,139 @@ You may obtain a copy of the License at limitations under the License. */ -namespace ConfigWithStartWizard.Models { - public enum OnlineItemType { - ProjectPackage = 0, - Template, - WebMap, - MapPackage, - Layer, - RulePackage - }; - /// - /// An individual result from an online query - /// - class OnlineResultItem { - //private BitmapImage _thumbnail = null; - private string _thumbnailUrl = ""; - private string _snippet = ""; - private string _linkText = ""; - /// - /// Gets and sets the item id - /// - public string Id { get; set; } - /// - /// Gets and sets the item title - /// - public string Title { get; set; } +using ArcGIS.Desktop.Core.Portal; - /// - /// Gets and sets the name - /// - public string Name { get; set; } +namespace ConfigWithStartWizard.Models +{ + public enum OnlineItemType + { + ProjectPackage = 0, + Template, + WebMap, + MapPackage, + Layer, + RulePackage + }; + /// + /// An individual result from an online query + /// + class OnlinePortalItem + { + private string _snippet = ""; + private string _linkText = ""; + /// + /// Gets and sets the item id + /// + public string Id { get; set; } + /// + /// Gets and sets the item title + /// + public string Title { get; set; } - /// - /// Gets and sets the item snippet - /// - public string Snippet - { - get - { - return _snippet; - } - set - { - _snippet = value; - } - } - /// - /// Gets and sets the item url - /// - public string Url { get; set; } + /// + /// Gets and sets the name + /// + public string Name { get; set; } - public string LinkText => _linkText; - /// - /// Gets and sets the online item type - /// - public OnlineItemType OnlineItemType { get; set; } - // /// - // /// Gets and sets the underlying item for this result - // /// - // public ArcGIS.Desktop.Core.Item Item { get; set; } - /// - /// Gets the Thumbnail url of the ResultItem - /// - public string ThumbnailUrl - { - get - { - return _thumbnailUrl; - } - } + /// + /// Gets and sets the item snippet + /// + public string Snippet + { + get + { + return _snippet; + } + set + { + _snippet = value; + } + } + /// + /// Gets and sets the item url + /// + public string Url { get; set; } - /// - /// Provide the item thumbnail URL for the given item id and thumbnail url - /// - /// The portal web url - /// The thumbnail url from the online item - /// the online item id - /// - public string SetThumbnailURL(string portal, string id, string thumbnail) { + public string LinkText => _linkText; + /// + /// Gets and sets the online item type + /// + public PortalItemType PortalItemType { get; set; } + // /// + // /// Gets and sets the underlying item for this result + // /// + // public ArcGIS.Desktop.Core.Item Item { get; set; } + /// + /// Gets the Thumbnail url of the ResultItem + /// + public string ThumbnailUrl { get; set; } - _thumbnailUrl = !string.IsNullOrEmpty(thumbnail) - ? string.Format("{0}/sharing/content/items/{1}/info/{2}", portal, id, thumbnail) - : @"http://static.arcgis.com/images/desktopapp.png"; - return _thumbnailUrl; - } + /// + /// Provide the item thumbnail URL for the given item id and thumbnail url + /// + /// The portal web url + /// The thumbnail url from the online item + /// the online item id + /// + public string SetThumbnailURL(string portal, string id, string thumbnail) + { - /// - /// Configure the online item result - /// - /// - /// - /// - /// - /// - /// - public void Configure(string portal, string id, string thumbnail, - string snippet, string itemType, string access) { + ThumbnailUrl = !string.IsNullOrEmpty(thumbnail) + ? string.Format("{0}/sharing/content/items/{1}/info/{2}", portal, id, thumbnail) + : @"http://static.arcgis.com/images/desktopapp.png"; + return ThumbnailUrl; + } - //Note: private item thumbnails cannot be retrieved via URL reference - _thumbnailUrl = !string.IsNullOrEmpty(thumbnail) && access == "public" - ? string.Format("{0}/sharing/content/items/{1}/info/{2}", portal, id, thumbnail) - : @"http://static.arcgis.com/images/desktopapp.png"; + /// + /// Configure the online item result + /// + /// + /// + /// + /// + /// + /// + public void Configure(string portal, string id, string thumbnail, + string snippet, PortalItemType portalItemType, string access) + { + //Note: private item thumbnails cannot be retrieved via URL reference + if (string.IsNullOrEmpty(ThumbnailUrl)) + ThumbnailUrl = @"http://static.arcgis.com/images/desktopapp.png"; - if (itemType == "Project Package") { - this.OnlineItemType = OnlineItemType.ProjectPackage; - _snippet = snippet + "\r\nArcGIS Pro Project Package"; - _linkText = $"Open {itemType}"; - } - else if (itemType == "Project Template") { - this.OnlineItemType = OnlineItemType.Template; - _snippet = snippet ?? "Project Template"; - _linkText = $"Create Project"; - } - else if (itemType == "Web Map" || itemType == "Web Scene") { - this.OnlineItemType = OnlineItemType.WebMap; - _snippet = snippet ?? this.Name; - _linkText = $"Open {itemType}"; - } - else if (itemType == "Pro Map") { - this.OnlineItemType = OnlineItemType.MapPackage; - _snippet = snippet ?? this.Name; - _linkText = $"Open Map Package"; - } - else if (itemType == "Feature Service" || itemType == "Map Service" || itemType == "Layer Package") { - this.OnlineItemType = OnlineItemType.Layer; - _snippet = snippet ?? this.Name; - _linkText = $"Open {itemType}"; - } - else if (itemType == "Rule Package") { - this.OnlineItemType = OnlineItemType.RulePackage; - _snippet = snippet ?? this.Name; - _linkText = $"Open {itemType}"; - } - } - } + if (portalItemType == PortalItemType.ProjectPackage) + { + _snippet = snippet + "\r\nArcGIS Pro Project Package"; + _linkText = $"Open {portalItemType}"; + } + else if (portalItemType == PortalItemType.ProjectTemplate) + { + _snippet = snippet ?? "Project Template"; + _linkText = $"Create Project"; + } + else if (portalItemType == PortalItemType.WebMap + || portalItemType == PortalItemType.WebScene) + { + _snippet = snippet ?? this.Name; + _linkText = $"Open {portalItemType}"; + } + else if (portalItemType == PortalItemType.MapPackage) + { + _snippet = snippet ?? this.Name; + _linkText = $"Open Map Package"; + } + else if (portalItemType == PortalItemType.FeatureService + || portalItemType == PortalItemType.MapService + || portalItemType == PortalItemType.LayerPackage) + { + _snippet = snippet ?? this.Name; + _linkText = $"Open {portalItemType}"; + } + else if (portalItemType == PortalItemType.RulePackage) + { + _snippet = snippet ?? this.Name; + _linkText = $"Open {portalItemType}"; + } + } + } } diff --git a/Framework/ConfigWithStartWizard/UI/StartPages/OnlineItemStartPage.xaml b/Framework/ConfigWithStartWizard/UI/StartPages/OnlineItemStartPage.xaml index 7a4977e9..19a72fab 100644 --- a/Framework/ConfigWithStartWizard/UI/StartPages/OnlineItemStartPage.xaml +++ b/Framework/ConfigWithStartWizard/UI/StartPages/OnlineItemStartPage.xaml @@ -26,85 +26,211 @@ mc:Ignorable="d" d:DesignHeight="300" d:DesignWidth="300" d:DataContext="{Binding Path=startPages.OnlineItemStartPageViewModel}"> - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - - - - - - - + + + + + + + + + - - - + + - - + + - - - - - - - - - - + + + + + + + + + - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Framework/ConfigWithStartWizard/UI/StartPages/OnlineItemStartPageViewModel.cs b/Framework/ConfigWithStartWizard/UI/StartPages/OnlineItemStartPageViewModel.cs index e9f92038..f0146f3d 100644 --- a/Framework/ConfigWithStartWizard/UI/StartPages/OnlineItemStartPageViewModel.cs +++ b/Framework/ConfigWithStartWizard/UI/StartPages/OnlineItemStartPageViewModel.cs @@ -30,6 +30,7 @@ limitations under the License. using ConfigWithStartWizard.Common; using ConfigWithStartWizard.Models; using ArcGIS.Desktop.Core.Portal; +using System.Windows; namespace ConfigWithStartWizard.UI.StartPages { @@ -39,21 +40,72 @@ internal class OnlineItemStartPageViewModel : StartPageViewModelBase private string _contentType = ""; private static string _activePortalUri = ""; private static string _token = ""; - private ObservableCollection _results = new ObservableCollection(); + private ObservableCollection _results = new ObservableCollection(); private int _selectedItemIndex = -1; private static readonly object _lock = new object(); private bool _initialized = false; - private PortalItem _result = null; + private OnlinePortalItem _selectedResult = null; private SubscriptionToken _eventToken = null; - - + public OnlineItemStartPageViewModel(string contentType) { BindingOperations.CollectionRegistering += BindingOperations_CollectionRegistering; _contentType = contentType; - } + _visibleList = Visibility.Visible; + _visibleText = Visibility.Collapsed; + } + + public OnlineItemStartPageViewModel() + { + _visibleList = Visibility.Visible; + _visibleText = Visibility.Collapsed; + } + + private Visibility _visibleText; + public Visibility VisibleText + { + get { return _visibleText; } + set + { + _visibleText = value; + NotifyPropertyChanged("VisibleText"); + } + } + + private Visibility _visibleList; + public Visibility VisibleList + { + get { return _visibleList; } + set + { + _visibleList = value; + NotifyPropertyChanged("VisibleList"); + } + } + + private string _statusTitle; + public string StatusTitle + { + get { return _statusTitle; } + set + { + _statusTitle = value; + NotifyPropertyChanged("StatusTitle"); + } + } + + private string _status; + public string Status + { + get { return _status; } + set + { + _status = value; + NotifyPropertyChanged("Status"); + } + } - void BindingOperations_CollectionRegistering(object sender, CollectionRegisteringEventArgs e) + void BindingOperations_CollectionRegistering(object sender, CollectionRegisteringEventArgs e) { if (!Equals(e.Collection, Results)) return; BindingOperations.EnableCollectionSynchronization(_results, _lock); @@ -66,24 +118,29 @@ private void _results_CollectionChanged(object sender, NotifyCollectionChangedEv this.SelectedItemIndex = -1; } - protected internal async virtual void ExecuteItemAction(string url) + protected internal async virtual void ExecuteItemAction(string id) { - _result = _results.FirstOrDefault(ri => ri.ID == url); - if (_result == null) return; - - //Either we open a project and then create the item or - //we download the item and then create a project from it. - //MapPackage is a special case. We download it, create - //a project and then add the map package to it. - switch (_result.PortalItemType) + _selectedResult = _results.FirstOrDefault(ri => ri.Id == id); + if (_selectedResult == null) return; + + //Either we open a project and then create the item or + //we download the item and then create a project from it. + //MapPackage is a special case. We download it, create + //a project and then add the map package to it. + + VisibleList = Visibility.Collapsed; + VisibleText = Visibility.Visible; + StatusTitle = $@"{_selectedResult.LinkText}: {_selectedResult.Title}"; + + switch (_selectedResult.PortalItemType) { case PortalItemType.WebMap: { await Project.CreateAsync(new CreateProjectSettings() { - Name = System.IO.Path.GetFileNameWithoutExtension(_result.Name) + Name = System.IO.Path.GetFileNameWithoutExtension(_selectedResult.Name) }); - var currentItem = ItemFactory.Instance.Create(_result.ID, ItemFactory.ItemType.PortalItem); + var currentItem = ItemFactory.Instance.Create(_selectedResult.Id, ItemFactory.ItemType.PortalItem); if (MapFactory.Instance.CanCreateMapFrom(currentItem)) { await QueuedTask.Run(() => @@ -98,13 +155,13 @@ await QueuedTask.Run(() => { var ps = new CreateProjectSettings() { - Name = System.IO.Path.GetFileNameWithoutExtension(_result.Name), + Name = System.IO.Path.GetFileNameWithoutExtension(_selectedResult.Name), LocationPath = ConfigWithStartWizardModule.DefaultFolder(), TemplatePath = ConfigWithStartWizardModule.GetDefaultTemplates()[0] //Scene }; _eventToken = ArcGIS.Desktop.Mapping.Events.MapViewInitializedEvent.Subscribe((args) => { - Item currentItem = ItemFactory.Instance.Create(_result.ID, ItemFactory.ItemType.PortalItem); + Item currentItem = ItemFactory.Instance.Create(_selectedResult.Id, ItemFactory.ItemType.PortalItem); if (LayerFactory.Instance.CanCreateLayerFrom(currentItem)) { QueuedTask.Run(() => LayerFactory.Instance.CreateLayer(currentItem, args.MapView.Map)); @@ -118,27 +175,28 @@ await QueuedTask.Run(() => } catch (Exception ex) { - System.Diagnostics.Debug.WriteLine(ex.ToString()); + Status = $@"Error occurred: {ex.ToString()}"; + System.Diagnostics.Debug.WriteLine(ex.ToString()); } } break; default: var query = new OnlineQuery(_activePortalUri); - query.ConfigureData("", _result.ID, _result.Name); - - await new SubmitQuery().DownloadFileAsync(query); - - //Project package - if (_result.PortalItemType == PortalItemType.ProjectPackage) + query.ConfigureData("", _selectedResult.Id, _selectedResult.Name); + Status = "Downloading"; + await new SubmitQuery().DownloadFileAsync(query); + Status = "Opening"; + //Project package + if (_selectedResult.PortalItemType == PortalItemType.ProjectPackage) { await Project.OpenAsync(query.DownloadFileName); } //Project Template - else if (_result.PortalItemType == PortalItemType.MapTemplate) + else if (_selectedResult.PortalItemType == PortalItemType.MapTemplate) { var ps = new CreateProjectSettings() { - Name = System.IO.Path.GetFileNameWithoutExtension(_result.Name), + Name = System.IO.Path.GetFileNameWithoutExtension(_selectedResult.Name), LocationPath = ConfigWithStartWizardModule.DefaultFolder(), TemplatePath = query.DownloadFileName }; @@ -149,15 +207,16 @@ await QueuedTask.Run(() => catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.ToString()); - } + Status = $@"Error occurred: {ex.ToString()}"; + } } //Map Package - else if (_result.PortalItemType == PortalItemType.MapPackage) + else if (_selectedResult.PortalItemType == PortalItemType.MapPackage) { await Project.CreateAsync(new CreateProjectSettings() { - Name = System.IO.Path.GetFileNameWithoutExtension(_result.Name) + Name = System.IO.Path.GetFileNameWithoutExtension(_selectedResult.Name) }); try @@ -168,7 +227,8 @@ await Project.CreateAsync(new CreateProjectSettings() catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.ToString()); - } + Status = $@"Error occurred: {ex.ToString()}"; + } } break; } @@ -204,7 +264,7 @@ protected internal override Task InitializeAsync() /// /// Gets the list of results from the query /// - public ObservableCollection Results + public ObservableCollection Results { get { @@ -224,7 +284,7 @@ public int SelectedItemIndex if (_selectedItemIndex >= 0) { var item = _results[_selectedItemIndex]; - this.ExecuteItemAction(item.ID); + this.ExecuteItemAction(item.Id); } NotifyPropertyChanged(); }